1 // SPDX-License-Identifier: GPL-2.0
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
7 * Swap reorganised 29.12.95, Stephen Tweedie.
8 * kswapd added: 7.1.96 sct
9 * Removed kswapd_ctl limits, and swap out as many pages as needed
10 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
11 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
12 * Multiqueue VM started 5.8.00, Rik van Riel.
15 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 #include <linux/sched/mm.h>
19 #include <linux/module.h>
20 #include <linux/gfp.h>
21 #include <linux/kernel_stat.h>
22 #include <linux/swap.h>
23 #include <linux/pagemap.h>
24 #include <linux/init.h>
25 #include <linux/highmem.h>
26 #include <linux/vmpressure.h>
27 #include <linux/vmstat.h>
28 #include <linux/file.h>
29 #include <linux/writeback.h>
30 #include <linux/blkdev.h>
31 #include <linux/buffer_head.h> /* for try_to_release_page(),
32 buffer_heads_over_limit */
33 #include <linux/mm_inline.h>
34 #include <linux/backing-dev.h>
35 #include <linux/rmap.h>
36 #include <linux/topology.h>
37 #include <linux/cpu.h>
38 #include <linux/cpuset.h>
39 #include <linux/compaction.h>
40 #include <linux/notifier.h>
41 #include <linux/rwsem.h>
42 #include <linux/delay.h>
43 #include <linux/kthread.h>
44 #include <linux/freezer.h>
45 #include <linux/memcontrol.h>
46 #include <linux/delayacct.h>
47 #include <linux/sysctl.h>
48 #include <linux/oom.h>
49 #include <linux/pagevec.h>
50 #include <linux/prefetch.h>
51 #include <linux/printk.h>
52 #include <linux/dax.h>
53 #include <linux/psi.h>
54 #include <linux/pagewalk.h>
55 #include <linux/shmem_fs.h>
56 #include <linux/ctype.h>
57 #include <linux/debugfs.h>
59 #include <asm/tlbflush.h>
60 #include <asm/div64.h>
62 #include <linux/swapops.h>
63 #include <linux/balloon_compaction.h>
67 #define CREATE_TRACE_POINTS
68 #include <trace/events/vmscan.h>
71 /* How many pages shrink_list() should reclaim */
72 unsigned long nr_to_reclaim;
75 * Nodemask of nodes allowed by the caller. If NULL, all nodes
81 * The memory cgroup that hit its limit and as a result is the
82 * primary target of this reclaim invocation.
84 struct mem_cgroup *target_mem_cgroup;
86 /* Can active pages be deactivated as part of reclaim? */
87 #define DEACTIVATE_ANON 1
88 #define DEACTIVATE_FILE 2
89 unsigned int may_deactivate:2;
90 unsigned int force_deactivate:1;
91 unsigned int skipped_deactivate:1;
93 /* Writepage batching in laptop mode; RECLAIM_WRITE */
94 unsigned int may_writepage:1;
96 /* Can mapped pages be reclaimed? */
97 unsigned int may_unmap:1;
99 /* Can pages be swapped as part of reclaim? */
100 unsigned int may_swap:1;
103 * Cgroups are not reclaimed below their configured memory.low,
104 * unless we threaten to OOM. If any cgroups are skipped due to
105 * memory.low and nothing was reclaimed, go back for memory.low.
107 unsigned int memcg_low_reclaim:1;
108 unsigned int memcg_low_skipped:1;
110 unsigned int hibernation_mode:1;
112 /* One of the zones is ready for compaction */
113 unsigned int compaction_ready:1;
115 /* There is easily reclaimable cold cache in the current node */
116 unsigned int cache_trim_mode:1;
118 /* The file pages on the current node are dangerously low */
119 unsigned int file_is_tiny:1;
121 #ifdef CONFIG_LRU_GEN
122 /* help kswapd make better choices among multiple memcgs */
123 unsigned int memcgs_need_aging:1;
124 unsigned long last_reclaimed;
127 /* Allocation order */
130 /* Scan (total_size >> priority) pages at once */
133 /* The highest zone to isolate pages for reclaim from */
136 /* This context's GFP mask */
139 /* Incremented by the number of inactive pages that were scanned */
140 unsigned long nr_scanned;
142 /* Number of pages freed so far during a call to shrink_zones() */
143 unsigned long nr_reclaimed;
147 unsigned int unqueued_dirty;
148 unsigned int congested;
149 unsigned int writeback;
150 unsigned int immediate;
151 unsigned int file_taken;
155 /* for recording the reclaimed slab by now */
156 struct reclaim_state reclaim_state;
159 #ifdef ARCH_HAS_PREFETCH
160 #define prefetch_prev_lru_page(_page, _base, _field) \
162 if ((_page)->lru.prev != _base) { \
165 prev = lru_to_page(&(_page->lru)); \
166 prefetch(&prev->_field); \
170 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
173 #ifdef ARCH_HAS_PREFETCHW
174 #define prefetchw_prev_lru_page(_page, _base, _field) \
176 if ((_page)->lru.prev != _base) { \
179 prev = lru_to_page(&(_page->lru)); \
180 prefetchw(&prev->_field); \
184 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
188 * From 0 .. 100. Higher means more swappy.
190 int vm_swappiness = 60;
192 * The total number of pages which are beyond the high watermark within all
195 unsigned long vm_total_pages;
197 static void set_task_reclaim_state(struct task_struct *task,
198 struct reclaim_state *rs)
200 /* Check for an overwrite */
201 WARN_ON_ONCE(rs && task->reclaim_state);
203 /* Check for the nulling of an already-nulled member */
204 WARN_ON_ONCE(!rs && !task->reclaim_state);
206 task->reclaim_state = rs;
209 static LIST_HEAD(shrinker_list);
210 static DECLARE_RWSEM(shrinker_rwsem);
214 * We allow subsystems to populate their shrinker-related
215 * LRU lists before register_shrinker_prepared() is called
216 * for the shrinker, since we don't want to impose
217 * restrictions on their internal registration order.
218 * In this case shrink_slab_memcg() may find corresponding
219 * bit is set in the shrinkers map.
221 * This value is used by the function to detect registering
222 * shrinkers and to skip do_shrink_slab() calls for them.
224 #define SHRINKER_REGISTERING ((struct shrinker *)~0UL)
226 static DEFINE_IDR(shrinker_idr);
227 static int shrinker_nr_max;
229 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
231 int id, ret = -ENOMEM;
233 down_write(&shrinker_rwsem);
234 /* This may call shrinker, so it must use down_read_trylock() */
235 id = idr_alloc(&shrinker_idr, SHRINKER_REGISTERING, 0, 0, GFP_KERNEL);
239 if (id >= shrinker_nr_max) {
240 if (memcg_expand_shrinker_maps(id)) {
241 idr_remove(&shrinker_idr, id);
245 shrinker_nr_max = id + 1;
250 up_write(&shrinker_rwsem);
254 static void unregister_memcg_shrinker(struct shrinker *shrinker)
256 int id = shrinker->id;
260 down_write(&shrinker_rwsem);
261 idr_remove(&shrinker_idr, id);
262 up_write(&shrinker_rwsem);
265 static bool cgroup_reclaim(struct scan_control *sc)
267 return sc->target_mem_cgroup;
271 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
272 * @sc: scan_control in question
274 * The normal page dirty throttling mechanism in balance_dirty_pages() is
275 * completely broken with the legacy memcg and direct stalling in
276 * shrink_page_list() is used for throttling instead, which lacks all the
277 * niceties such as fairness, adaptive pausing, bandwidth proportional
278 * allocation and configurability.
280 * This function tests whether the vmscan currently in progress can assume
281 * that the normal dirty throttling mechanism is operational.
283 static bool writeback_throttling_sane(struct scan_control *sc)
285 if (!cgroup_reclaim(sc))
287 #ifdef CONFIG_CGROUP_WRITEBACK
288 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
294 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
299 static void unregister_memcg_shrinker(struct shrinker *shrinker)
303 static bool cgroup_reclaim(struct scan_control *sc)
308 static bool writeback_throttling_sane(struct scan_control *sc)
315 * This misses isolated pages which are not accounted for to save counters.
316 * As the data only determines if reclaim or compaction continues, it is
317 * not expected that isolated pages will be a dominating factor.
319 unsigned long zone_reclaimable_pages(struct zone *zone)
323 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
324 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
325 if (get_nr_swap_pages() > 0)
326 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
327 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
333 * lruvec_lru_size - Returns the number of pages on the given LRU list.
334 * @lruvec: lru vector
336 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
338 unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru, int zone_idx)
340 unsigned long size = 0;
343 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
344 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
346 if (!managed_zone(zone))
349 if (!mem_cgroup_disabled())
350 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
352 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
358 * Add a shrinker callback to be called from the vm.
360 int prealloc_shrinker(struct shrinker *shrinker)
362 unsigned int size = sizeof(*shrinker->nr_deferred);
364 if (shrinker->flags & SHRINKER_NUMA_AWARE)
367 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
368 if (!shrinker->nr_deferred)
371 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
372 if (prealloc_memcg_shrinker(shrinker))
379 kfree(shrinker->nr_deferred);
380 shrinker->nr_deferred = NULL;
384 void free_prealloced_shrinker(struct shrinker *shrinker)
386 if (!shrinker->nr_deferred)
389 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
390 unregister_memcg_shrinker(shrinker);
392 kfree(shrinker->nr_deferred);
393 shrinker->nr_deferred = NULL;
396 void register_shrinker_prepared(struct shrinker *shrinker)
398 down_write(&shrinker_rwsem);
399 list_add_tail(&shrinker->list, &shrinker_list);
401 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
402 idr_replace(&shrinker_idr, shrinker, shrinker->id);
404 up_write(&shrinker_rwsem);
407 int register_shrinker(struct shrinker *shrinker)
409 int err = prealloc_shrinker(shrinker);
413 register_shrinker_prepared(shrinker);
416 EXPORT_SYMBOL(register_shrinker);
421 void unregister_shrinker(struct shrinker *shrinker)
423 if (!shrinker->nr_deferred)
425 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
426 unregister_memcg_shrinker(shrinker);
427 down_write(&shrinker_rwsem);
428 list_del(&shrinker->list);
429 up_write(&shrinker_rwsem);
430 kfree(shrinker->nr_deferred);
431 shrinker->nr_deferred = NULL;
433 EXPORT_SYMBOL(unregister_shrinker);
435 #define SHRINK_BATCH 128
437 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
438 struct shrinker *shrinker, int priority)
440 unsigned long freed = 0;
441 unsigned long long delta;
446 int nid = shrinkctl->nid;
447 long batch_size = shrinker->batch ? shrinker->batch
449 long scanned = 0, next_deferred;
451 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
454 freeable = shrinker->count_objects(shrinker, shrinkctl);
455 if (freeable == 0 || freeable == SHRINK_EMPTY)
459 * copy the current shrinker scan count into a local variable
460 * and zero it so that other concurrent shrinker invocations
461 * don't also do this scanning work.
463 nr = atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
466 if (shrinker->seeks) {
467 delta = freeable >> priority;
469 do_div(delta, shrinker->seeks);
472 * These objects don't require any IO to create. Trim
473 * them aggressively under memory pressure to keep
474 * them from causing refetches in the IO caches.
476 delta = freeable / 2;
480 if (total_scan < 0) {
481 pr_err("shrink_slab: %pS negative objects to delete nr=%ld\n",
482 shrinker->scan_objects, total_scan);
483 total_scan = freeable;
486 next_deferred = total_scan;
489 * We need to avoid excessive windup on filesystem shrinkers
490 * due to large numbers of GFP_NOFS allocations causing the
491 * shrinkers to return -1 all the time. This results in a large
492 * nr being built up so when a shrink that can do some work
493 * comes along it empties the entire cache due to nr >>>
494 * freeable. This is bad for sustaining a working set in
497 * Hence only allow the shrinker to scan the entire cache when
498 * a large delta change is calculated directly.
500 if (delta < freeable / 4)
501 total_scan = min(total_scan, freeable / 2);
504 * Avoid risking looping forever due to too large nr value:
505 * never try to free more than twice the estimate number of
508 if (total_scan > freeable * 2)
509 total_scan = freeable * 2;
511 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
512 freeable, delta, total_scan, priority);
515 * Normally, we should not scan less than batch_size objects in one
516 * pass to avoid too frequent shrinker calls, but if the slab has less
517 * than batch_size objects in total and we are really tight on memory,
518 * we will try to reclaim all available objects, otherwise we can end
519 * up failing allocations although there are plenty of reclaimable
520 * objects spread over several slabs with usage less than the
523 * We detect the "tight on memory" situations by looking at the total
524 * number of objects we want to scan (total_scan). If it is greater
525 * than the total number of objects on slab (freeable), we must be
526 * scanning at high prio and therefore should try to reclaim as much as
529 while (total_scan >= batch_size ||
530 total_scan >= freeable) {
532 unsigned long nr_to_scan = min(batch_size, total_scan);
534 shrinkctl->nr_to_scan = nr_to_scan;
535 shrinkctl->nr_scanned = nr_to_scan;
536 ret = shrinker->scan_objects(shrinker, shrinkctl);
537 if (ret == SHRINK_STOP)
541 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
542 total_scan -= shrinkctl->nr_scanned;
543 scanned += shrinkctl->nr_scanned;
548 if (next_deferred >= scanned)
549 next_deferred -= scanned;
553 * move the unused scan count back into the shrinker in a
554 * manner that handles concurrent updates. If we exhausted the
555 * scan, there is no need to do an update.
557 if (next_deferred > 0)
558 new_nr = atomic_long_add_return(next_deferred,
559 &shrinker->nr_deferred[nid]);
561 new_nr = atomic_long_read(&shrinker->nr_deferred[nid]);
563 trace_mm_shrink_slab_end(shrinker, nid, freed, nr, new_nr, total_scan);
568 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
569 struct mem_cgroup *memcg, int priority)
571 struct memcg_shrinker_map *map;
572 unsigned long ret, freed = 0;
575 if (!mem_cgroup_online(memcg))
578 if (!down_read_trylock(&shrinker_rwsem))
581 map = rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_map,
586 for_each_set_bit(i, map->map, shrinker_nr_max) {
587 struct shrink_control sc = {
588 .gfp_mask = gfp_mask,
592 struct shrinker *shrinker;
594 shrinker = idr_find(&shrinker_idr, i);
595 if (unlikely(!shrinker || shrinker == SHRINKER_REGISTERING)) {
597 clear_bit(i, map->map);
601 /* Call non-slab shrinkers even though kmem is disabled */
602 if (!memcg_kmem_enabled() &&
603 !(shrinker->flags & SHRINKER_NONSLAB))
606 ret = do_shrink_slab(&sc, shrinker, priority);
607 if (ret == SHRINK_EMPTY) {
608 clear_bit(i, map->map);
610 * After the shrinker reported that it had no objects to
611 * free, but before we cleared the corresponding bit in
612 * the memcg shrinker map, a new object might have been
613 * added. To make sure, we have the bit set in this
614 * case, we invoke the shrinker one more time and reset
615 * the bit if it reports that it is not empty anymore.
616 * The memory barrier here pairs with the barrier in
617 * memcg_set_shrinker_bit():
619 * list_lru_add() shrink_slab_memcg()
620 * list_add_tail() clear_bit()
622 * set_bit() do_shrink_slab()
624 smp_mb__after_atomic();
625 ret = do_shrink_slab(&sc, shrinker, priority);
626 if (ret == SHRINK_EMPTY)
629 memcg_set_shrinker_bit(memcg, nid, i);
633 if (rwsem_is_contended(&shrinker_rwsem)) {
639 up_read(&shrinker_rwsem);
642 #else /* CONFIG_MEMCG */
643 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
644 struct mem_cgroup *memcg, int priority)
648 #endif /* CONFIG_MEMCG */
651 * shrink_slab - shrink slab caches
652 * @gfp_mask: allocation context
653 * @nid: node whose slab caches to target
654 * @memcg: memory cgroup whose slab caches to target
655 * @priority: the reclaim priority
657 * Call the shrink functions to age shrinkable caches.
659 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
660 * unaware shrinkers will receive a node id of 0 instead.
662 * @memcg specifies the memory cgroup to target. Unaware shrinkers
663 * are called only if it is the root cgroup.
665 * @priority is sc->priority, we take the number of objects and >> by priority
666 * in order to get the scan target.
668 * Returns the number of reclaimed slab objects.
670 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
671 struct mem_cgroup *memcg,
674 unsigned long ret, freed = 0;
675 struct shrinker *shrinker;
678 * The root memcg might be allocated even though memcg is disabled
679 * via "cgroup_disable=memory" boot parameter. This could make
680 * mem_cgroup_is_root() return false, then just run memcg slab
681 * shrink, but skip global shrink. This may result in premature
684 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
685 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
687 if (!down_read_trylock(&shrinker_rwsem))
690 list_for_each_entry(shrinker, &shrinker_list, list) {
691 struct shrink_control sc = {
692 .gfp_mask = gfp_mask,
697 ret = do_shrink_slab(&sc, shrinker, priority);
698 if (ret == SHRINK_EMPTY)
702 * Bail out if someone want to register a new shrinker to
703 * prevent the regsitration from being stalled for long periods
704 * by parallel ongoing shrinking.
706 if (rwsem_is_contended(&shrinker_rwsem)) {
712 up_read(&shrinker_rwsem);
718 void drop_slab_node(int nid)
723 struct mem_cgroup *memcg = NULL;
726 memcg = mem_cgroup_iter(NULL, NULL, NULL);
728 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
729 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
730 } while (freed > 10);
737 for_each_online_node(nid)
741 static inline int is_page_cache_freeable(struct page *page)
744 * A freeable page cache page is referenced only by the caller
745 * that isolated the page, the page cache and optional buffer
746 * heads at page->private.
748 int page_cache_pins = PageTransHuge(page) && PageSwapCache(page) ?
750 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
753 static int may_write_to_inode(struct inode *inode, struct scan_control *sc)
755 if (current->flags & PF_SWAPWRITE)
757 if (!inode_write_congested(inode))
759 if (inode_to_bdi(inode) == current->backing_dev_info)
765 * We detected a synchronous write error writing a page out. Probably
766 * -ENOSPC. We need to propagate that into the address_space for a subsequent
767 * fsync(), msync() or close().
769 * The tricky part is that after writepage we cannot touch the mapping: nothing
770 * prevents it from being freed up. But we have a ref on the page and once
771 * that page is locked, the mapping is pinned.
773 * We're allowed to run sleeping lock_page() here because we know the caller has
776 static void handle_write_error(struct address_space *mapping,
777 struct page *page, int error)
780 if (page_mapping(page) == mapping)
781 mapping_set_error(mapping, error);
785 /* possible outcome of pageout() */
787 /* failed to write page out, page is locked */
789 /* move page to the active list, page is locked */
791 /* page has been sent to the disk successfully, page is unlocked */
793 /* page is clean and locked */
798 * pageout is called by shrink_page_list() for each dirty page.
799 * Calls ->writepage().
801 static pageout_t pageout(struct page *page, struct address_space *mapping,
802 struct scan_control *sc)
805 * If the page is dirty, only perform writeback if that write
806 * will be non-blocking. To prevent this allocation from being
807 * stalled by pagecache activity. But note that there may be
808 * stalls if we need to run get_block(). We could test
809 * PagePrivate for that.
811 * If this process is currently in __generic_file_write_iter() against
812 * this page's queue, we can perform writeback even if that
815 * If the page is swapcache, write it back even if that would
816 * block, for some throttling. This happens by accident, because
817 * swap_backing_dev_info is bust: it doesn't reflect the
818 * congestion state of the swapdevs. Easy to fix, if needed.
820 if (!is_page_cache_freeable(page))
824 * Some data journaling orphaned pages can have
825 * page->mapping == NULL while being dirty with clean buffers.
827 if (page_has_private(page)) {
828 if (try_to_free_buffers(page)) {
829 ClearPageDirty(page);
830 pr_info("%s: orphaned page\n", __func__);
836 if (mapping->a_ops->writepage == NULL)
837 return PAGE_ACTIVATE;
838 if (!may_write_to_inode(mapping->host, sc))
841 if (clear_page_dirty_for_io(page)) {
843 struct writeback_control wbc = {
844 .sync_mode = WB_SYNC_NONE,
845 .nr_to_write = SWAP_CLUSTER_MAX,
847 .range_end = LLONG_MAX,
851 SetPageReclaim(page);
852 res = mapping->a_ops->writepage(page, &wbc);
854 handle_write_error(mapping, page, res);
855 if (res == AOP_WRITEPAGE_ACTIVATE) {
856 ClearPageReclaim(page);
857 return PAGE_ACTIVATE;
860 if (!PageWriteback(page)) {
861 /* synchronous write or broken a_ops? */
862 ClearPageReclaim(page);
864 trace_mm_vmscan_writepage(page);
865 inc_node_page_state(page, NR_VMSCAN_WRITE);
873 * Same as remove_mapping, but if the page is removed from the mapping, it
874 * gets returned with a refcount of 0.
876 static int __remove_mapping(struct address_space *mapping, struct page *page,
877 bool reclaimed, struct mem_cgroup *target_memcg)
882 BUG_ON(!PageLocked(page));
883 BUG_ON(mapping != page_mapping(page));
885 xa_lock_irqsave(&mapping->i_pages, flags);
887 * The non racy check for a busy page.
889 * Must be careful with the order of the tests. When someone has
890 * a ref to the page, it may be possible that they dirty it then
891 * drop the reference. So if PageDirty is tested before page_count
892 * here, then the following race may occur:
894 * get_user_pages(&page);
895 * [user mapping goes away]
897 * !PageDirty(page) [good]
898 * SetPageDirty(page);
900 * !page_count(page) [good, discard it]
902 * [oops, our write_to data is lost]
904 * Reversing the order of the tests ensures such a situation cannot
905 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
906 * load is not satisfied before that of page->_refcount.
908 * Note that if SetPageDirty is always performed via set_page_dirty,
909 * and thus under the i_pages lock, then this ordering is not required.
911 refcount = 1 + compound_nr(page);
912 if (!page_ref_freeze(page, refcount))
914 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
915 if (unlikely(PageDirty(page))) {
916 page_ref_unfreeze(page, refcount);
920 if (PageSwapCache(page)) {
921 swp_entry_t swap = { .val = page_private(page) };
922 mem_cgroup_swapout(page, swap);
923 __delete_from_swap_cache(page, swap);
924 xa_unlock_irqrestore(&mapping->i_pages, flags);
925 put_swap_page(page, swap);
927 void (*freepage)(struct page *);
930 freepage = mapping->a_ops->freepage;
932 * Remember a shadow entry for reclaimed file cache in
933 * order to detect refaults, thus thrashing, later on.
935 * But don't store shadows in an address space that is
936 * already exiting. This is not just an optizimation,
937 * inode reclaim needs to empty out the radix tree or
938 * the nodes are lost. Don't plant shadows behind its
941 * We also don't store shadows for DAX mappings because the
942 * only page cache pages found in these are zero pages
943 * covering holes, and because we don't want to mix DAX
944 * exceptional entries and shadow exceptional entries in the
945 * same address_space.
947 if (reclaimed && page_is_file_cache(page) &&
948 !mapping_exiting(mapping) && !dax_mapping(mapping))
949 shadow = workingset_eviction(page, target_memcg);
950 __delete_from_page_cache(page, shadow);
951 xa_unlock_irqrestore(&mapping->i_pages, flags);
953 if (freepage != NULL)
960 xa_unlock_irqrestore(&mapping->i_pages, flags);
965 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
966 * someone else has a ref on the page, abort and return 0. If it was
967 * successfully detached, return 1. Assumes the caller has a single ref on
970 int remove_mapping(struct address_space *mapping, struct page *page)
972 if (__remove_mapping(mapping, page, false, NULL)) {
974 * Unfreezing the refcount with 1 rather than 2 effectively
975 * drops the pagecache ref for us without requiring another
978 page_ref_unfreeze(page, 1);
985 * putback_lru_page - put previously isolated page onto appropriate LRU list
986 * @page: page to be put back to appropriate lru list
988 * Add previously isolated @page to appropriate LRU list.
989 * Page may still be unevictable for other reasons.
991 * lru_lock must not be held, interrupts must be enabled.
993 void putback_lru_page(struct page *page)
996 put_page(page); /* drop ref from isolate */
999 enum page_references {
1001 PAGEREF_RECLAIM_CLEAN,
1006 static enum page_references page_check_references(struct page *page,
1007 struct scan_control *sc)
1009 int referenced_ptes, referenced_page;
1010 unsigned long vm_flags;
1012 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1014 referenced_page = TestClearPageReferenced(page);
1017 * Mlock lost the isolation race with us. Let try_to_unmap()
1018 * move the page to the unevictable list.
1020 if (vm_flags & VM_LOCKED)
1021 return PAGEREF_RECLAIM;
1023 if (referenced_ptes) {
1024 if (PageSwapBacked(page))
1025 return PAGEREF_ACTIVATE;
1027 * All mapped pages start out with page table
1028 * references from the instantiating fault, so we need
1029 * to look twice if a mapped file page is used more
1032 * Mark it and spare it for another trip around the
1033 * inactive list. Another page table reference will
1034 * lead to its activation.
1036 * Note: the mark is set for activated pages as well
1037 * so that recently deactivated but used pages are
1038 * quickly recovered.
1040 SetPageReferenced(page);
1042 if (referenced_page || referenced_ptes > 1)
1043 return PAGEREF_ACTIVATE;
1046 * Activate file-backed executable pages after first usage.
1048 if (vm_flags & VM_EXEC)
1049 return PAGEREF_ACTIVATE;
1051 return PAGEREF_KEEP;
1054 /* Reclaim if clean, defer dirty pages to writeback */
1055 if (referenced_page && !PageSwapBacked(page))
1056 return PAGEREF_RECLAIM_CLEAN;
1058 return PAGEREF_RECLAIM;
1061 /* Check if a page is dirty or under writeback */
1062 static void page_check_dirty_writeback(struct page *page,
1063 bool *dirty, bool *writeback)
1065 struct address_space *mapping;
1068 * Anonymous pages are not handled by flushers and must be written
1069 * from reclaim context. Do not stall reclaim based on them
1071 if (!page_is_file_cache(page) ||
1072 (PageAnon(page) && !PageSwapBacked(page))) {
1078 /* By default assume that the page flags are accurate */
1079 *dirty = PageDirty(page);
1080 *writeback = PageWriteback(page);
1082 /* Verify dirty/writeback state if the filesystem supports it */
1083 if (!page_has_private(page))
1086 mapping = page_mapping(page);
1087 if (mapping && mapping->a_ops->is_dirty_writeback)
1088 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
1092 * shrink_page_list() returns the number of reclaimed pages
1094 static unsigned long shrink_page_list(struct list_head *page_list,
1095 struct pglist_data *pgdat,
1096 struct scan_control *sc,
1097 struct reclaim_stat *stat,
1098 bool ignore_references)
1100 LIST_HEAD(ret_pages);
1101 LIST_HEAD(free_pages);
1102 unsigned nr_reclaimed = 0;
1103 unsigned pgactivate = 0;
1105 memset(stat, 0, sizeof(*stat));
1108 while (!list_empty(page_list)) {
1109 struct address_space *mapping;
1112 enum page_references references = PAGEREF_RECLAIM;
1113 bool dirty, writeback;
1114 unsigned int nr_pages;
1118 page = lru_to_page(page_list);
1119 list_del(&page->lru);
1121 if (!trylock_page(page))
1124 VM_BUG_ON_PAGE(PageActive(page), page);
1126 nr_pages = compound_nr(page);
1128 /* Account the number of base pages even though THP */
1129 sc->nr_scanned += nr_pages;
1131 if (unlikely(!page_evictable(page)))
1132 goto activate_locked;
1134 if (!sc->may_unmap && page_mapped(page))
1137 /* page_update_gen() tried to promote this page? */
1138 if (lru_gen_enabled() && !ignore_references &&
1139 page_mapped(page) && PageReferenced(page))
1142 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1143 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1146 * The number of dirty pages determines if a node is marked
1147 * reclaim_congested which affects wait_iff_congested. kswapd
1148 * will stall and start writing pages if the tail of the LRU
1149 * is all dirty unqueued pages.
1151 page_check_dirty_writeback(page, &dirty, &writeback);
1152 if (dirty || writeback)
1155 if (dirty && !writeback)
1156 stat->nr_unqueued_dirty++;
1159 * Treat this page as congested if the underlying BDI is or if
1160 * pages are cycling through the LRU so quickly that the
1161 * pages marked for immediate reclaim are making it to the
1162 * end of the LRU a second time.
1164 mapping = page_mapping(page);
1165 if (((dirty || writeback) && mapping &&
1166 inode_write_congested(mapping->host)) ||
1167 (writeback && PageReclaim(page)))
1168 stat->nr_congested++;
1171 * If a page at the tail of the LRU is under writeback, there
1172 * are three cases to consider.
1174 * 1) If reclaim is encountering an excessive number of pages
1175 * under writeback and this page is both under writeback and
1176 * PageReclaim then it indicates that pages are being queued
1177 * for IO but are being recycled through the LRU before the
1178 * IO can complete. Waiting on the page itself risks an
1179 * indefinite stall if it is impossible to writeback the
1180 * page due to IO error or disconnected storage so instead
1181 * note that the LRU is being scanned too quickly and the
1182 * caller can stall after page list has been processed.
1184 * 2) Global or new memcg reclaim encounters a page that is
1185 * not marked for immediate reclaim, or the caller does not
1186 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1187 * not to fs). In this case mark the page for immediate
1188 * reclaim and continue scanning.
1190 * Require may_enter_fs because we would wait on fs, which
1191 * may not have submitted IO yet. And the loop driver might
1192 * enter reclaim, and deadlock if it waits on a page for
1193 * which it is needed to do the write (loop masks off
1194 * __GFP_IO|__GFP_FS for this reason); but more thought
1195 * would probably show more reasons.
1197 * 3) Legacy memcg encounters a page that is already marked
1198 * PageReclaim. memcg does not have any dirty pages
1199 * throttling so we could easily OOM just because too many
1200 * pages are in writeback and there is nothing else to
1201 * reclaim. Wait for the writeback to complete.
1203 * In cases 1) and 2) we activate the pages to get them out of
1204 * the way while we continue scanning for clean pages on the
1205 * inactive list and refilling from the active list. The
1206 * observation here is that waiting for disk writes is more
1207 * expensive than potentially causing reloads down the line.
1208 * Since they're marked for immediate reclaim, they won't put
1209 * memory pressure on the cache working set any longer than it
1210 * takes to write them to disk.
1212 if (PageWriteback(page)) {
1214 if (current_is_kswapd() &&
1215 PageReclaim(page) &&
1216 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1217 stat->nr_immediate++;
1218 goto activate_locked;
1221 } else if (writeback_throttling_sane(sc) ||
1222 !PageReclaim(page) || !may_enter_fs) {
1224 * This is slightly racy - end_page_writeback()
1225 * might have just cleared PageReclaim, then
1226 * setting PageReclaim here end up interpreted
1227 * as PageReadahead - but that does not matter
1228 * enough to care. What we do want is for this
1229 * page to have PageReclaim set next time memcg
1230 * reclaim reaches the tests above, so it will
1231 * then wait_on_page_writeback() to avoid OOM;
1232 * and it's also appropriate in global reclaim.
1234 SetPageReclaim(page);
1235 stat->nr_writeback++;
1236 goto activate_locked;
1241 wait_on_page_writeback(page);
1242 /* then go back and try same page again */
1243 list_add_tail(&page->lru, page_list);
1248 if (!ignore_references)
1249 references = page_check_references(page, sc);
1251 switch (references) {
1252 case PAGEREF_ACTIVATE:
1253 goto activate_locked;
1255 stat->nr_ref_keep += nr_pages;
1257 case PAGEREF_RECLAIM:
1258 case PAGEREF_RECLAIM_CLEAN:
1259 ; /* try to reclaim the page below */
1263 * Anonymous process memory has backing store?
1264 * Try to allocate it some swap space here.
1265 * Lazyfree page could be freed directly
1267 if (PageAnon(page) && PageSwapBacked(page)) {
1268 if (!PageSwapCache(page)) {
1269 if (!(sc->gfp_mask & __GFP_IO))
1271 if (PageTransHuge(page)) {
1272 /* cannot split THP, skip it */
1273 if (!can_split_huge_page(page, NULL))
1274 goto activate_locked;
1276 * Split pages without a PMD map right
1277 * away. Chances are some or all of the
1278 * tail pages can be freed without IO.
1280 if (!compound_mapcount(page) &&
1281 split_huge_page_to_list(page,
1283 goto activate_locked;
1285 if (!add_to_swap(page)) {
1286 if (!PageTransHuge(page))
1287 goto activate_locked_split;
1288 /* Fallback to swap normal pages */
1289 if (split_huge_page_to_list(page,
1291 goto activate_locked;
1292 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1293 count_vm_event(THP_SWPOUT_FALLBACK);
1295 if (!add_to_swap(page))
1296 goto activate_locked_split;
1301 /* Adding to swap updated mapping */
1302 mapping = page_mapping(page);
1304 } else if (unlikely(PageTransHuge(page))) {
1305 /* Split file THP */
1306 if (split_huge_page_to_list(page, page_list))
1311 * THP may get split above, need minus tail pages and update
1312 * nr_pages to avoid accounting tail pages twice.
1314 * The tail pages that are added into swap cache successfully
1317 if ((nr_pages > 1) && !PageTransHuge(page)) {
1318 sc->nr_scanned -= (nr_pages - 1);
1323 * The page is mapped into the page tables of one or more
1324 * processes. Try to unmap it here.
1326 if (page_mapped(page)) {
1327 enum ttu_flags flags = TTU_BATCH_FLUSH;
1329 if (unlikely(PageTransHuge(page)))
1330 flags |= TTU_SPLIT_HUGE_PMD;
1331 if (!try_to_unmap(page, flags)) {
1332 stat->nr_unmap_fail += nr_pages;
1333 goto activate_locked;
1337 if (PageDirty(page)) {
1339 * Only kswapd can writeback filesystem pages
1340 * to avoid risk of stack overflow. But avoid
1341 * injecting inefficient single-page IO into
1342 * flusher writeback as much as possible: only
1343 * write pages when we've encountered many
1344 * dirty pages, and when we've already scanned
1345 * the rest of the LRU for clean pages and see
1346 * the same dirty pages again (PageReclaim).
1348 if (page_is_file_cache(page) &&
1349 (!current_is_kswapd() || !PageReclaim(page) ||
1350 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1352 * Immediately reclaim when written back.
1353 * Similar in principal to deactivate_page()
1354 * except we already have the page isolated
1355 * and know it's dirty
1357 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
1358 SetPageReclaim(page);
1360 goto activate_locked;
1363 if (references == PAGEREF_RECLAIM_CLEAN)
1367 if (!sc->may_writepage)
1371 * Page is dirty. Flush the TLB if a writable entry
1372 * potentially exists to avoid CPU writes after IO
1373 * starts and then write it out here.
1375 try_to_unmap_flush_dirty();
1376 switch (pageout(page, mapping, sc)) {
1380 goto activate_locked;
1382 if (PageWriteback(page))
1384 if (PageDirty(page))
1388 * A synchronous write - probably a ramdisk. Go
1389 * ahead and try to reclaim the page.
1391 if (!trylock_page(page))
1393 if (PageDirty(page) || PageWriteback(page))
1395 mapping = page_mapping(page);
1397 ; /* try to free the page below */
1402 * If the page has buffers, try to free the buffer mappings
1403 * associated with this page. If we succeed we try to free
1406 * We do this even if the page is PageDirty().
1407 * try_to_release_page() does not perform I/O, but it is
1408 * possible for a page to have PageDirty set, but it is actually
1409 * clean (all its buffers are clean). This happens if the
1410 * buffers were written out directly, with submit_bh(). ext3
1411 * will do this, as well as the blockdev mapping.
1412 * try_to_release_page() will discover that cleanness and will
1413 * drop the buffers and mark the page clean - it can be freed.
1415 * Rarely, pages can have buffers and no ->mapping. These are
1416 * the pages which were not successfully invalidated in
1417 * truncate_complete_page(). We try to drop those buffers here
1418 * and if that worked, and the page is no longer mapped into
1419 * process address space (page_count == 1) it can be freed.
1420 * Otherwise, leave the page on the LRU so it is swappable.
1422 if (page_has_private(page)) {
1423 if (!try_to_release_page(page, sc->gfp_mask))
1424 goto activate_locked;
1425 if (!mapping && page_count(page) == 1) {
1427 if (put_page_testzero(page))
1431 * rare race with speculative reference.
1432 * the speculative reference will free
1433 * this page shortly, so we may
1434 * increment nr_reclaimed here (and
1435 * leave it off the LRU).
1443 if (PageAnon(page) && !PageSwapBacked(page)) {
1444 /* follow __remove_mapping for reference */
1445 if (!page_ref_freeze(page, 1))
1447 if (PageDirty(page)) {
1448 page_ref_unfreeze(page, 1);
1452 count_vm_event(PGLAZYFREED);
1453 count_memcg_page_event(page, PGLAZYFREED);
1454 } else if (!mapping || !__remove_mapping(mapping, page, true,
1455 sc->target_mem_cgroup))
1461 * THP may get swapped out in a whole, need account
1464 nr_reclaimed += nr_pages;
1467 * Is there need to periodically free_page_list? It would
1468 * appear not as the counts should be low
1470 if (unlikely(PageTransHuge(page)))
1471 (*get_compound_page_dtor(page))(page);
1473 list_add(&page->lru, &free_pages);
1476 activate_locked_split:
1478 * The tail pages that are failed to add into swap cache
1479 * reach here. Fixup nr_scanned and nr_pages.
1482 sc->nr_scanned -= (nr_pages - 1);
1486 /* Not a candidate for swapping, so reclaim swap space. */
1487 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1489 try_to_free_swap(page);
1490 VM_BUG_ON_PAGE(PageActive(page), page);
1491 if (!PageMlocked(page)) {
1492 int type = page_is_file_cache(page);
1493 SetPageActive(page);
1494 stat->nr_activate[type] += nr_pages;
1495 count_memcg_page_event(page, PGACTIVATE);
1500 list_add(&page->lru, &ret_pages);
1501 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
1504 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1506 mem_cgroup_uncharge_list(&free_pages);
1507 try_to_unmap_flush();
1508 free_unref_page_list(&free_pages);
1510 list_splice(&ret_pages, page_list);
1511 count_vm_events(PGACTIVATE, pgactivate);
1513 return nr_reclaimed;
1516 unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1517 struct list_head *page_list)
1519 struct scan_control sc = {
1520 .gfp_mask = GFP_KERNEL,
1521 .priority = DEF_PRIORITY,
1524 struct reclaim_stat dummy_stat;
1526 struct page *page, *next;
1527 LIST_HEAD(clean_pages);
1529 list_for_each_entry_safe(page, next, page_list, lru) {
1530 if (page_is_file_cache(page) && !PageDirty(page) &&
1531 !__PageMovable(page) && !PageUnevictable(page)) {
1532 ClearPageActive(page);
1533 list_move(&page->lru, &clean_pages);
1537 ret = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
1539 list_splice(&clean_pages, page_list);
1540 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE, -ret);
1545 * Attempt to remove the specified page from its LRU. Only take this page
1546 * if it is of the appropriate PageActive status. Pages which are being
1547 * freed elsewhere are also ignored.
1549 * page: page to consider
1550 * mode: one of the LRU isolation modes defined above
1552 * returns 0 on success, -ve errno on failure.
1554 int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1558 /* Only take pages on the LRU. */
1562 /* Compaction should not handle unevictable pages but CMA can do so */
1563 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1567 * To minimise LRU disruption, the caller can indicate that it only
1568 * wants to isolate pages it will be able to operate on without
1569 * blocking - clean pages for the most part.
1571 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1572 * that it is possible to migrate without blocking
1574 if (mode & ISOLATE_ASYNC_MIGRATE) {
1575 /* All the caller can do on PageWriteback is block */
1576 if (PageWriteback(page))
1579 if (PageDirty(page)) {
1580 struct address_space *mapping;
1584 * Only pages without mappings or that have a
1585 * ->migratepage callback are possible to migrate
1586 * without blocking. However, we can be racing with
1587 * truncation so it's necessary to lock the page
1588 * to stabilise the mapping as truncation holds
1589 * the page lock until after the page is removed
1590 * from the page cache.
1592 if (!trylock_page(page))
1595 mapping = page_mapping(page);
1596 migrate_dirty = !mapping || mapping->a_ops->migratepage;
1603 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1606 if (likely(get_page_unless_zero(page))) {
1608 * Be careful not to clear PageLRU until after we're
1609 * sure the page is not being freed elsewhere -- the
1610 * page release code relies on it.
1612 if (TestClearPageLRU(page))
1623 * Update LRU sizes after isolating pages. The LRU size updates must
1624 * be complete before mem_cgroup_update_lru_size due to a santity check.
1626 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
1627 enum lru_list lru, unsigned long *nr_zone_taken)
1631 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1632 if (!nr_zone_taken[zid])
1635 __update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1637 mem_cgroup_update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
1644 * pgdat->lru_lock is heavily contended. Some of the functions that
1645 * shrink the lists perform better by taking out a batch of pages
1646 * and working on them outside the LRU lock.
1648 * For pagecache intensive workloads, this function is the hottest
1649 * spot in the kernel (apart from copy_*_user functions).
1651 * Appropriate locks must be held before calling this function.
1653 * @nr_to_scan: The number of eligible pages to look through on the list.
1654 * @lruvec: The LRU vector to pull pages from.
1655 * @dst: The temp list to put pages on to.
1656 * @nr_scanned: The number of pages that were scanned.
1657 * @sc: The scan_control struct for this reclaim session
1658 * @mode: One of the LRU isolation modes
1659 * @lru: LRU list id for isolating
1661 * returns how many pages were moved onto *@dst.
1663 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1664 struct lruvec *lruvec, struct list_head *dst,
1665 unsigned long *nr_scanned, struct scan_control *sc,
1668 struct list_head *src = &lruvec->lists[lru];
1669 unsigned long nr_taken = 0;
1670 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
1671 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
1672 unsigned long skipped = 0;
1673 unsigned long scan, total_scan, nr_pages;
1674 LIST_HEAD(pages_skipped);
1675 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
1679 while (scan < nr_to_scan && !list_empty(src)) {
1682 page = lru_to_page(src);
1683 prefetchw_prev_lru_page(page, src, flags);
1685 nr_pages = compound_nr(page);
1686 total_scan += nr_pages;
1688 if (page_zonenum(page) > sc->reclaim_idx) {
1689 list_move(&page->lru, &pages_skipped);
1690 nr_skipped[page_zonenum(page)] += nr_pages;
1695 * Do not count skipped pages because that makes the function
1696 * return with no isolated pages if the LRU mostly contains
1697 * ineligible pages. This causes the VM to not reclaim any
1698 * pages, triggering a premature OOM.
1700 * Account all tail pages of THP. This would not cause
1701 * premature OOM since __isolate_lru_page() returns -EBUSY
1702 * only when the page is being freed somewhere else.
1705 switch (__isolate_lru_page(page, mode)) {
1707 nr_taken += nr_pages;
1708 nr_zone_taken[page_zonenum(page)] += nr_pages;
1709 list_move(&page->lru, dst);
1713 /* else it is being freed elsewhere */
1714 list_move(&page->lru, src);
1723 * Splice any skipped pages to the start of the LRU list. Note that
1724 * this disrupts the LRU order when reclaiming for lower zones but
1725 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1726 * scanning would soon rescan the same pages to skip and put the
1727 * system at risk of premature OOM.
1729 if (!list_empty(&pages_skipped)) {
1732 list_splice(&pages_skipped, src);
1733 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1734 if (!nr_skipped[zid])
1737 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1738 skipped += nr_skipped[zid];
1741 *nr_scanned = total_scan;
1742 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
1743 total_scan, skipped, nr_taken, mode, lru);
1744 update_lru_sizes(lruvec, lru, nr_zone_taken);
1749 * isolate_lru_page - tries to isolate a page from its LRU list
1750 * @page: page to isolate from its LRU list
1752 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1753 * vmstat statistic corresponding to whatever LRU list the page was on.
1755 * Returns 0 if the page was removed from an LRU list.
1756 * Returns -EBUSY if the page was not on an LRU list.
1758 * The returned page will have PageLRU() cleared. If it was found on
1759 * the active list, it will have PageActive set. If it was found on
1760 * the unevictable list, it will have the PageUnevictable bit set. That flag
1761 * may need to be cleared by the caller before letting the page go.
1763 * The vmstat statistic corresponding to the list on which the page was
1764 * found will be decremented.
1768 * (1) Must be called with an elevated refcount on the page. This is a
1769 * fundamentnal difference from isolate_lru_pages (which is called
1770 * without a stable reference).
1771 * (2) the lru_lock must not be held.
1772 * (3) interrupts must be enabled.
1774 int isolate_lru_page(struct page *page)
1778 VM_BUG_ON_PAGE(!page_count(page), page);
1779 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
1781 if (TestClearPageLRU(page)) {
1782 pg_data_t *pgdat = page_pgdat(page);
1783 struct lruvec *lruvec;
1786 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1787 spin_lock_irq(&pgdat->lru_lock);
1788 del_page_from_lru_list(page, lruvec, page_lru(page));
1789 spin_unlock_irq(&pgdat->lru_lock);
1797 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1798 * then get resheduled. When there are massive number of tasks doing page
1799 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1800 * the LRU list will go small and be scanned faster than necessary, leading to
1801 * unnecessary swapping, thrashing and OOM.
1803 static int too_many_isolated(struct pglist_data *pgdat, int file,
1804 struct scan_control *sc)
1806 unsigned long inactive, isolated;
1808 if (current_is_kswapd())
1811 if (!writeback_throttling_sane(sc))
1815 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
1816 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
1818 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
1819 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
1823 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1824 * won't get blocked by normal direct-reclaimers, forming a circular
1827 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
1830 return isolated > inactive;
1834 * This moves pages from @list to corresponding LRU list.
1836 * We move them the other way if the page is referenced by one or more
1837 * processes, from rmap.
1839 * If the pages are mostly unmapped, the processing is fast and it is
1840 * appropriate to hold zone_lru_lock across the whole operation. But if
1841 * the pages are mapped, the processing is slow (page_referenced()) so we
1842 * should drop zone_lru_lock around each page. It's impossible to balance
1843 * this, so instead we remove the pages from the LRU while processing them.
1844 * It is safe to rely on PG_active against the non-LRU pages in here because
1845 * nobody will play with that bit on a non-LRU page.
1847 * The downside is that we have to touch page->_refcount against each page.
1848 * But we had to alter page->flags anyway.
1850 * Returns the number of pages moved to the given lruvec.
1853 static unsigned noinline_for_stack move_pages_to_lru(struct lruvec *lruvec,
1854 struct list_head *list)
1856 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1857 int nr_pages, nr_moved = 0;
1858 LIST_HEAD(pages_to_free);
1862 while (!list_empty(list)) {
1863 page = lru_to_page(list);
1864 VM_BUG_ON_PAGE(PageLRU(page), page);
1865 if (unlikely(!page_evictable(page))) {
1866 list_del(&page->lru);
1867 spin_unlock_irq(&pgdat->lru_lock);
1868 putback_lru_page(page);
1869 spin_lock_irq(&pgdat->lru_lock);
1872 lruvec = mem_cgroup_page_lruvec(page, pgdat);
1875 lru = page_lru(page);
1877 nr_pages = hpage_nr_pages(page);
1878 update_lru_size(lruvec, lru, page_zonenum(page), nr_pages);
1879 list_move(&page->lru, &lruvec->lists[lru]);
1881 if (put_page_testzero(page)) {
1882 __ClearPageLRU(page);
1883 __ClearPageActive(page);
1884 del_page_from_lru_list(page, lruvec, lru);
1886 if (unlikely(PageCompound(page))) {
1887 spin_unlock_irq(&pgdat->lru_lock);
1888 (*get_compound_page_dtor(page))(page);
1889 spin_lock_irq(&pgdat->lru_lock);
1891 list_add(&page->lru, &pages_to_free);
1893 nr_moved += nr_pages;
1898 * To save our caller's stack, now use input list for pages to free.
1900 list_splice(&pages_to_free, list);
1906 * If a kernel thread (such as nfsd for loop-back mounts) services
1907 * a backing device by writing to the page cache it sets PF_LESS_THROTTLE.
1908 * In that case we should only throttle if the backing device it is
1909 * writing to is congested. In other cases it is safe to throttle.
1911 static int current_may_throttle(void)
1913 return !(current->flags & PF_LESS_THROTTLE) ||
1914 current->backing_dev_info == NULL ||
1915 bdi_write_congested(current->backing_dev_info);
1919 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1920 * of reclaimed pages
1922 static noinline_for_stack unsigned long
1923 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1924 struct scan_control *sc, enum lru_list lru)
1926 LIST_HEAD(page_list);
1927 unsigned long nr_scanned;
1928 unsigned long nr_reclaimed = 0;
1929 unsigned long nr_taken;
1930 struct reclaim_stat stat;
1931 int file = is_file_lru(lru);
1932 enum vm_event_item item;
1933 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1934 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1935 bool stalled = false;
1937 while (unlikely(too_many_isolated(pgdat, file, sc))) {
1941 /* wait a bit for the reclaimer. */
1945 /* We are about to die and free our memory. Return now. */
1946 if (fatal_signal_pending(current))
1947 return SWAP_CLUSTER_MAX;
1952 spin_lock_irq(&pgdat->lru_lock);
1954 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1955 &nr_scanned, sc, lru);
1957 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1958 reclaim_stat->recent_scanned[file] += nr_taken;
1960 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
1961 if (!cgroup_reclaim(sc))
1962 __count_vm_events(item, nr_scanned);
1963 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
1964 spin_unlock_irq(&pgdat->lru_lock);
1969 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
1971 spin_lock_irq(&pgdat->lru_lock);
1973 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
1974 if (!cgroup_reclaim(sc))
1975 __count_vm_events(item, nr_reclaimed);
1976 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
1977 reclaim_stat->recent_rotated[0] += stat.nr_activate[0];
1978 reclaim_stat->recent_rotated[1] += stat.nr_activate[1];
1980 move_pages_to_lru(lruvec, &page_list);
1982 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
1984 spin_unlock_irq(&pgdat->lru_lock);
1986 mem_cgroup_uncharge_list(&page_list);
1987 free_unref_page_list(&page_list);
1990 * If dirty pages are scanned that are not queued for IO, it
1991 * implies that flushers are not doing their job. This can
1992 * happen when memory pressure pushes dirty pages to the end of
1993 * the LRU before the dirty limits are breached and the dirty
1994 * data has expired. It can also happen when the proportion of
1995 * dirty pages grows not through writes but through memory
1996 * pressure reclaiming all the clean cache. And in some cases,
1997 * the flushers simply cannot keep up with the allocation
1998 * rate. Nudge the flusher threads in case they are asleep.
2000 if (stat.nr_unqueued_dirty == nr_taken)
2001 wakeup_flusher_threads(WB_REASON_VMSCAN);
2003 sc->nr.dirty += stat.nr_dirty;
2004 sc->nr.congested += stat.nr_congested;
2005 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2006 sc->nr.writeback += stat.nr_writeback;
2007 sc->nr.immediate += stat.nr_immediate;
2008 sc->nr.taken += nr_taken;
2010 sc->nr.file_taken += nr_taken;
2012 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2013 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2014 return nr_reclaimed;
2017 static void shrink_active_list(unsigned long nr_to_scan,
2018 struct lruvec *lruvec,
2019 struct scan_control *sc,
2022 unsigned long nr_taken;
2023 unsigned long nr_scanned;
2024 unsigned long vm_flags;
2025 LIST_HEAD(l_hold); /* The pages which were snipped off */
2026 LIST_HEAD(l_active);
2027 LIST_HEAD(l_inactive);
2029 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2030 unsigned nr_deactivate, nr_activate;
2031 unsigned nr_rotated = 0;
2032 int file = is_file_lru(lru);
2033 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2037 spin_lock_irq(&pgdat->lru_lock);
2039 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2040 &nr_scanned, sc, lru);
2042 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2043 reclaim_stat->recent_scanned[file] += nr_taken;
2045 __count_vm_events(PGREFILL, nr_scanned);
2046 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2048 spin_unlock_irq(&pgdat->lru_lock);
2050 while (!list_empty(&l_hold)) {
2052 page = lru_to_page(&l_hold);
2053 list_del(&page->lru);
2055 if (unlikely(!page_evictable(page))) {
2056 putback_lru_page(page);
2060 if (unlikely(buffer_heads_over_limit)) {
2061 if (page_has_private(page) && trylock_page(page)) {
2062 if (page_has_private(page))
2063 try_to_release_page(page, 0);
2068 if (page_referenced(page, 0, sc->target_mem_cgroup,
2070 nr_rotated += hpage_nr_pages(page);
2072 * Identify referenced, file-backed active pages and
2073 * give them one more trip around the active list. So
2074 * that executable code get better chances to stay in
2075 * memory under moderate memory pressure. Anon pages
2076 * are not likely to be evicted by use-once streaming
2077 * IO, plus JVM can create lots of anon VM_EXEC pages,
2078 * so we ignore them here.
2080 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
2081 list_add(&page->lru, &l_active);
2086 ClearPageActive(page); /* we are de-activating */
2087 SetPageWorkingset(page);
2088 list_add(&page->lru, &l_inactive);
2092 * Move pages back to the lru list.
2094 spin_lock_irq(&pgdat->lru_lock);
2096 * Count referenced pages from currently used mappings as rotated,
2097 * even though only some of them are actually re-activated. This
2098 * helps balance scan pressure between file and anonymous pages in
2101 reclaim_stat->recent_rotated[file] += nr_rotated;
2103 nr_activate = move_pages_to_lru(lruvec, &l_active);
2104 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2105 /* Keep all free pages in l_active list */
2106 list_splice(&l_inactive, &l_active);
2108 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2109 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2111 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2112 spin_unlock_irq(&pgdat->lru_lock);
2114 mem_cgroup_uncharge_list(&l_active);
2115 free_unref_page_list(&l_active);
2116 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2117 nr_deactivate, nr_rotated, sc->priority, file);
2120 unsigned long reclaim_pages(struct list_head *page_list)
2123 unsigned long nr_reclaimed = 0;
2124 LIST_HEAD(node_page_list);
2125 struct reclaim_stat dummy_stat;
2127 struct scan_control sc = {
2128 .gfp_mask = GFP_KERNEL,
2129 .priority = DEF_PRIORITY,
2135 while (!list_empty(page_list)) {
2136 page = lru_to_page(page_list);
2138 nid = page_to_nid(page);
2139 INIT_LIST_HEAD(&node_page_list);
2142 if (nid == page_to_nid(page)) {
2143 ClearPageActive(page);
2144 list_move(&page->lru, &node_page_list);
2148 nr_reclaimed += shrink_page_list(&node_page_list,
2150 &sc, &dummy_stat, false);
2151 while (!list_empty(&node_page_list)) {
2152 page = lru_to_page(&node_page_list);
2153 list_del(&page->lru);
2154 putback_lru_page(page);
2160 if (!list_empty(&node_page_list)) {
2161 nr_reclaimed += shrink_page_list(&node_page_list,
2163 &sc, &dummy_stat, false);
2164 while (!list_empty(&node_page_list)) {
2165 page = lru_to_page(&node_page_list);
2166 list_del(&page->lru);
2167 putback_lru_page(page);
2171 return nr_reclaimed;
2174 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2175 struct lruvec *lruvec, struct scan_control *sc)
2177 if (is_active_lru(lru)) {
2178 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2179 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2181 sc->skipped_deactivate = 1;
2185 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2189 * The inactive anon list should be small enough that the VM never has
2190 * to do too much work.
2192 * The inactive file list should be small enough to leave most memory
2193 * to the established workingset on the scan-resistant active list,
2194 * but large enough to avoid thrashing the aggregate readahead window.
2196 * Both inactive lists should also be large enough that each inactive
2197 * page has a chance to be referenced again before it is reclaimed.
2199 * If that fails and refaulting is observed, the inactive list grows.
2201 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2202 * on this LRU, maintained by the pageout code. An inactive_ratio
2203 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2206 * memory ratio inactive
2207 * -------------------------------------
2216 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2218 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2219 unsigned long inactive, active;
2220 unsigned long inactive_ratio;
2223 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2224 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2226 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2228 inactive_ratio = int_sqrt(10 * gb);
2232 return inactive * inactive_ratio < active;
2242 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2245 struct lruvec *target_lruvec;
2247 if (lru_gen_enabled())
2250 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2253 * Target desirable inactive:active list ratios for the anon
2254 * and file LRU lists.
2256 if (!sc->force_deactivate) {
2257 unsigned long refaults;
2259 if (inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2260 sc->may_deactivate |= DEACTIVATE_ANON;
2262 sc->may_deactivate &= ~DEACTIVATE_ANON;
2265 * When refaults are being observed, it means a new
2266 * workingset is being established. Deactivate to get
2267 * rid of any stale active pages quickly.
2269 refaults = lruvec_page_state(target_lruvec,
2270 WORKINGSET_ACTIVATE);
2271 if (refaults != target_lruvec->refaults ||
2272 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2273 sc->may_deactivate |= DEACTIVATE_FILE;
2275 sc->may_deactivate &= ~DEACTIVATE_FILE;
2277 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2280 * If we have plenty of inactive file pages that aren't
2281 * thrashing, try to reclaim those first before touching
2284 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2285 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2286 sc->cache_trim_mode = 1;
2288 sc->cache_trim_mode = 0;
2291 * Prevent the reclaimer from falling into the cache trap: as
2292 * cache pages start out inactive, every cache fault will tip
2293 * the scan balance towards the file LRU. And as the file LRU
2294 * shrinks, so does the window for rotation from references.
2295 * This means we have a runaway feedback loop where a tiny
2296 * thrashing file LRU becomes infinitely more attractive than
2297 * anon pages. Try to detect this based on file LRU size.
2299 if (!cgroup_reclaim(sc)) {
2300 unsigned long total_high_wmark = 0;
2301 unsigned long free, anon;
2304 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2305 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2306 node_page_state(pgdat, NR_INACTIVE_FILE);
2308 for (z = 0; z < MAX_NR_ZONES; z++) {
2309 struct zone *zone = &pgdat->node_zones[z];
2311 if (!managed_zone(zone))
2314 total_high_wmark += high_wmark_pages(zone);
2318 * Consider anon: if that's low too, this isn't a
2319 * runaway file reclaim problem, but rather just
2320 * extreme pressure. Reclaim as per usual then.
2322 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2325 file + free <= total_high_wmark &&
2326 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2327 anon >> sc->priority;
2332 * Determine how aggressively the anon and file LRU lists should be
2333 * scanned. The relative value of each set of LRU lists is determined
2334 * by looking at the fraction of the pages scanned we did rotate back
2335 * onto the active list instead of evict.
2337 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2338 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2340 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2343 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2344 int swappiness = mem_cgroup_swappiness(memcg);
2345 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2346 u64 fraction[ANON_AND_FILE];
2347 u64 denominator = 0; /* gcc */
2348 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2349 unsigned long anon_prio, file_prio;
2350 enum scan_balance scan_balance;
2351 unsigned long anon, file;
2352 unsigned long ap, fp;
2355 /* If we have no swap space, do not bother scanning anon pages. */
2356 if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2357 scan_balance = SCAN_FILE;
2362 * Global reclaim will swap to prevent OOM even with no
2363 * swappiness, but memcg users want to use this knob to
2364 * disable swapping for individual groups completely when
2365 * using the memory controller's swap limit feature would be
2368 if (cgroup_reclaim(sc) && !swappiness) {
2369 scan_balance = SCAN_FILE;
2374 * Do not apply any pressure balancing cleverness when the
2375 * system is close to OOM, scan both anon and file equally
2376 * (unless the swappiness setting disagrees with swapping).
2378 if (!sc->priority && swappiness) {
2379 scan_balance = SCAN_EQUAL;
2384 * If the system is almost out of file pages, force-scan anon.
2386 if (sc->file_is_tiny) {
2387 scan_balance = SCAN_ANON;
2392 * If there is enough inactive page cache, we do not reclaim
2393 * anything from the anonymous working right now.
2395 if (sc->cache_trim_mode) {
2396 scan_balance = SCAN_FILE;
2400 scan_balance = SCAN_FRACT;
2403 * With swappiness at 100, anonymous and file have the same priority.
2404 * This scanning priority is essentially the inverse of IO cost.
2406 anon_prio = swappiness;
2407 file_prio = 200 - anon_prio;
2410 * OK, so we have swap space and a fair amount of page cache
2411 * pages. We use the recently rotated / recently scanned
2412 * ratios to determine how valuable each cache is.
2414 * Because workloads change over time (and to avoid overflow)
2415 * we keep these statistics as a floating average, which ends
2416 * up weighing recent references more than old ones.
2418 * anon in [0], file in [1]
2421 anon = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2422 lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2423 file = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2424 lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
2426 spin_lock_irq(&pgdat->lru_lock);
2427 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
2428 reclaim_stat->recent_scanned[0] /= 2;
2429 reclaim_stat->recent_rotated[0] /= 2;
2432 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
2433 reclaim_stat->recent_scanned[1] /= 2;
2434 reclaim_stat->recent_rotated[1] /= 2;
2438 * The amount of pressure on anon vs file pages is inversely
2439 * proportional to the fraction of recently scanned pages on
2440 * each list that were recently referenced and in active use.
2442 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
2443 ap /= reclaim_stat->recent_rotated[0] + 1;
2445 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
2446 fp /= reclaim_stat->recent_rotated[1] + 1;
2447 spin_unlock_irq(&pgdat->lru_lock);
2451 denominator = ap + fp + 1;
2453 for_each_evictable_lru(lru) {
2454 int file = is_file_lru(lru);
2455 unsigned long lruvec_size;
2457 unsigned long protection;
2459 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2460 protection = mem_cgroup_protection(memcg,
2461 sc->memcg_low_reclaim);
2465 * Scale a cgroup's reclaim pressure by proportioning
2466 * its current usage to its memory.low or memory.min
2469 * This is important, as otherwise scanning aggression
2470 * becomes extremely binary -- from nothing as we
2471 * approach the memory protection threshold, to totally
2472 * nominal as we exceed it. This results in requiring
2473 * setting extremely liberal protection thresholds. It
2474 * also means we simply get no protection at all if we
2475 * set it too low, which is not ideal.
2477 * If there is any protection in place, we reduce scan
2478 * pressure by how much of the total memory used is
2479 * within protection thresholds.
2481 * There is one special case: in the first reclaim pass,
2482 * we skip over all groups that are within their low
2483 * protection. If that fails to reclaim enough pages to
2484 * satisfy the reclaim goal, we come back and override
2485 * the best-effort low protection. However, we still
2486 * ideally want to honor how well-behaved groups are in
2487 * that case instead of simply punishing them all
2488 * equally. As such, we reclaim them based on how much
2489 * memory they are using, reducing the scan pressure
2490 * again by how much of the total memory used is under
2493 unsigned long cgroup_size = mem_cgroup_size(memcg);
2495 /* Avoid TOCTOU with earlier protection check */
2496 cgroup_size = max(cgroup_size, protection);
2498 scan = lruvec_size - lruvec_size * protection /
2502 * Minimally target SWAP_CLUSTER_MAX pages to keep
2503 * reclaim moving forwards, avoiding decremeting
2504 * sc->priority further than desirable.
2506 scan = max(scan, SWAP_CLUSTER_MAX);
2511 scan >>= sc->priority;
2514 * If the cgroup's already been deleted, make sure to
2515 * scrape out the remaining cache.
2517 if (!scan && !mem_cgroup_online(memcg))
2518 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2520 switch (scan_balance) {
2522 /* Scan lists relative to size */
2526 * Scan types proportional to swappiness and
2527 * their relative recent reclaim efficiency.
2528 * Make sure we don't miss the last page on
2529 * the offlined memory cgroups because of a
2532 scan = mem_cgroup_online(memcg) ?
2533 div64_u64(scan * fraction[file], denominator) :
2534 DIV64_U64_ROUND_UP(scan * fraction[file],
2539 /* Scan one type exclusively */
2540 if ((scan_balance == SCAN_FILE) != file)
2544 /* Look ma, no brain */
2552 #ifdef CONFIG_LRU_GEN
2554 #ifdef CONFIG_LRU_GEN_ENABLED
2555 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2556 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2558 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2559 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2562 /******************************************************************************
2564 ******************************************************************************/
2566 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2568 #define DEFINE_MAX_SEQ(lruvec) \
2569 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2571 #define DEFINE_MIN_SEQ(lruvec) \
2572 unsigned long min_seq[ANON_AND_FILE] = { \
2573 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2574 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2577 #define for_each_gen_type_zone(gen, type, zone) \
2578 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2579 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2580 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2582 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2584 struct pglist_data *pgdat = NODE_DATA(nid);
2588 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2590 /* for hotadd_new_pgdat() */
2592 lruvec->pgdat = pgdat;
2597 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2599 return pgdat ? &pgdat->__lruvec : NULL;
2602 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2604 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2605 /* struct pglist_data *pgdat = lruvec_pgdat(lruvec); */
2607 /* FIXME: see a2a36488a61c + 26aa2d199d6f */
2608 if (/* !can_demote(pgdat->node_id, sc) && */
2609 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
2612 return mem_cgroup_swappiness(memcg);
2615 static int get_nr_gens(struct lruvec *lruvec, int type)
2617 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2620 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2622 /* see the comment on lru_gen_struct */
2623 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2624 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2625 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2628 /******************************************************************************
2630 ******************************************************************************/
2632 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2634 static struct lru_gen_mm_list mm_list = {
2635 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2636 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2641 return &memcg->mm_list;
2643 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2648 void lru_gen_add_mm(struct mm_struct *mm)
2651 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2652 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2654 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2656 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2657 mm->lru_gen.memcg = memcg;
2659 spin_lock(&mm_list->lock);
2661 for_each_node_state(nid, N_MEMORY) {
2662 struct lruvec *lruvec = get_lruvec(memcg, nid);
2667 /* the first addition since the last iteration */
2668 if (lruvec->mm_state.tail == &mm_list->fifo)
2669 lruvec->mm_state.tail = &mm->lru_gen.list;
2672 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2674 spin_unlock(&mm_list->lock);
2677 void lru_gen_del_mm(struct mm_struct *mm)
2680 struct lru_gen_mm_list *mm_list;
2681 struct mem_cgroup *memcg = NULL;
2683 if (list_empty(&mm->lru_gen.list))
2687 memcg = mm->lru_gen.memcg;
2689 mm_list = get_mm_list(memcg);
2691 spin_lock(&mm_list->lock);
2693 for_each_node(nid) {
2694 struct lruvec *lruvec = get_lruvec(memcg, nid);
2699 /* where the current iteration continues after */
2700 if (lruvec->mm_state.head == &mm->lru_gen.list)
2701 lruvec->mm_state.head = lruvec->mm_state.head->prev;
2703 /* where the last iteration ended before */
2704 if (lruvec->mm_state.tail == &mm->lru_gen.list)
2705 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
2708 list_del_init(&mm->lru_gen.list);
2710 spin_unlock(&mm_list->lock);
2713 mem_cgroup_put(mm->lru_gen.memcg);
2714 mm->lru_gen.memcg = NULL;
2719 void lru_gen_migrate_mm(struct mm_struct *mm)
2721 struct mem_cgroup *memcg;
2722 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
2724 VM_WARN_ON_ONCE(task->mm != mm);
2725 lockdep_assert_held(&task->alloc_lock);
2727 /* for mm_update_next_owner() */
2728 if (mem_cgroup_disabled())
2732 memcg = mem_cgroup_from_task(task);
2734 if (memcg == mm->lru_gen.memcg)
2737 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
2738 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
2746 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
2747 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
2748 * bits in a bitmap, k is the number of hash functions and n is the number of
2751 * Page table walkers use one of the two filters to reduce their search space.
2752 * To get rid of non-leaf entries that no longer have enough leaf entries, the
2753 * aging uses the double-buffering technique to flip to the other filter each
2754 * time it produces a new generation. For non-leaf entries that have enough
2755 * leaf entries, the aging carries them over to the next generation in
2756 * walk_pmd_range(); the eviction also report them when walking the rmap
2757 * in lru_gen_look_around().
2759 * For future optimizations:
2760 * 1. It's not necessary to keep both filters all the time. The spare one can be
2761 * freed after the RCU grace period and reallocated if needed again.
2762 * 2. And when reallocating, it's worth scaling its size according to the number
2763 * of inserted entries in the other filter, to reduce the memory overhead on
2764 * small systems and false positives on large systems.
2765 * 3. Jenkins' hash function is an alternative to Knuth's.
2767 #define BLOOM_FILTER_SHIFT 15
2769 static inline int filter_gen_from_seq(unsigned long seq)
2771 return seq % NR_BLOOM_FILTERS;
2774 static void get_item_key(void *item, int *key)
2776 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
2778 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
2780 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
2781 key[1] = hash >> BLOOM_FILTER_SHIFT;
2784 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
2786 unsigned long *filter;
2787 int gen = filter_gen_from_seq(seq);
2789 filter = lruvec->mm_state.filters[gen];
2791 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
2795 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
2796 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
2797 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
2800 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
2803 unsigned long *filter;
2804 int gen = filter_gen_from_seq(seq);
2806 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
2810 get_item_key(item, key);
2812 if (!test_bit(key[0], filter))
2813 set_bit(key[0], filter);
2814 if (!test_bit(key[1], filter))
2815 set_bit(key[1], filter);
2818 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
2821 unsigned long *filter;
2822 int gen = filter_gen_from_seq(seq);
2824 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
2828 get_item_key(item, key);
2830 return test_bit(key[0], filter) && test_bit(key[1], filter);
2833 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
2838 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
2841 hist = lru_hist_from_seq(walk->max_seq);
2843 for (i = 0; i < NR_MM_STATS; i++) {
2844 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
2845 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
2846 walk->mm_stats[i] = 0;
2850 if (NR_HIST_GENS > 1 && last) {
2851 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
2853 for (i = 0; i < NR_MM_STATS; i++)
2854 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
2858 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
2861 unsigned long size = 0;
2862 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
2863 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
2865 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
2868 clear_bit(key, &mm->lru_gen.bitmap);
2870 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
2871 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
2872 get_mm_counter(mm, MM_ANONPAGES) +
2873 get_mm_counter(mm, MM_SHMEMPAGES);
2876 if (size < MIN_LRU_BATCH)
2879 return !mmget_not_zero(mm);
2882 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
2883 struct mm_struct **iter)
2887 struct mm_struct *mm = NULL;
2888 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2889 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2890 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
2893 * mm_state->seq is incremented after each iteration of mm_list. There
2894 * are three interesting cases for this page table walker:
2895 * 1. It tries to start a new iteration with a stale max_seq: there is
2896 * nothing left to do.
2897 * 2. It started the next iteration: it needs to reset the Bloom filter
2898 * so that a fresh set of PTE tables can be recorded.
2899 * 3. It ended the current iteration: it needs to reset the mm stats
2900 * counters and tell its caller to increment max_seq.
2902 spin_lock(&mm_list->lock);
2904 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
2906 if (walk->max_seq <= mm_state->seq)
2909 if (!mm_state->head)
2910 mm_state->head = &mm_list->fifo;
2912 if (mm_state->head == &mm_list->fifo)
2916 mm_state->head = mm_state->head->next;
2917 if (mm_state->head == &mm_list->fifo) {
2918 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2923 /* force scan for those added after the last iteration */
2924 if (!mm_state->tail || mm_state->tail == mm_state->head) {
2925 mm_state->tail = mm_state->head->next;
2926 walk->force_scan = true;
2929 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
2930 if (should_skip_mm(mm, walk))
2935 reset_mm_stats(lruvec, walk, last);
2937 spin_unlock(&mm_list->lock);
2940 reset_bloom_filter(lruvec, walk->max_seq + 1);
2950 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
2952 bool success = false;
2953 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2954 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2955 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
2957 spin_lock(&mm_list->lock);
2959 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
2961 if (max_seq > mm_state->seq) {
2962 mm_state->head = NULL;
2963 mm_state->tail = NULL;
2964 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
2965 reset_mm_stats(lruvec, NULL, true);
2969 spin_unlock(&mm_list->lock);
2974 /******************************************************************************
2975 * refault feedback loop
2976 ******************************************************************************/
2979 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2981 * The P term is refaulted/(evicted+protected) from a tier in the generation
2982 * currently being evicted; the I term is the exponential moving average of the
2983 * P term over the generations previously evicted, using the smoothing factor
2984 * 1/2; the D term isn't supported.
2986 * The setpoint (SP) is always the first tier of one type; the process variable
2987 * (PV) is either any tier of the other type or any other tier of the same
2990 * The error is the difference between the SP and the PV; the correction is to
2991 * turn off protection when SP>PV or turn on protection when SP<PV.
2993 * For future optimizations:
2994 * 1. The D term may discount the other two terms over time so that long-lived
2995 * generations can resist stale information.
2998 unsigned long refaulted;
2999 unsigned long total;
3003 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3004 struct ctrl_pos *pos)
3006 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3007 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3009 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3010 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3011 pos->total = lrugen->avg_total[type][tier] +
3012 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3014 pos->total += lrugen->protected[hist][type][tier - 1];
3018 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3021 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3022 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3023 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3025 lockdep_assert_held(&lruvec_pgdat(lruvec)->lru_lock);
3027 if (!carryover && !clear)
3030 hist = lru_hist_from_seq(seq);
3032 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3036 sum = lrugen->avg_refaulted[type][tier] +
3037 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3038 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3040 sum = lrugen->avg_total[type][tier] +
3041 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3043 sum += lrugen->protected[hist][type][tier - 1];
3044 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3048 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3049 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3051 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3056 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3059 * Return true if the PV has a limited number of refaults or a lower
3060 * refaulted/total than the SP.
3062 return pv->refaulted < MIN_LRU_BATCH ||
3063 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3064 (sp->refaulted + 1) * pv->total * pv->gain;
3067 /******************************************************************************
3069 ******************************************************************************/
3071 /* promote pages accessed through page tables */
3072 static int page_update_gen(struct page *page, int gen)
3074 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3076 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3077 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3080 /* lru_gen_del_page() has isolated this page? */
3081 if (!(old_flags & LRU_GEN_MASK)) {
3082 /* for shrink_page_list() */
3083 new_flags = old_flags | BIT(PG_referenced);
3087 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3088 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3089 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3091 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3094 /* protect pages accessed multiple times through file descriptors */
3095 static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3097 int type = page_is_file_cache(page);
3098 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3099 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3100 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3102 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3105 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3106 /* page_update_gen() has promoted this page? */
3107 if (new_gen >= 0 && new_gen != old_gen)
3110 new_gen = (old_gen + 1) % MAX_NR_GENS;
3112 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3113 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3114 /* for end_page_writeback() */
3116 new_flags |= BIT(PG_reclaim);
3117 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3119 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3124 static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3125 int old_gen, int new_gen)
3127 int type = page_is_file_cache(page);
3128 int zone = page_zonenum(page);
3129 int delta = hpage_nr_pages(page);
3131 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3132 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3136 walk->nr_pages[old_gen][type][zone] -= delta;
3137 walk->nr_pages[new_gen][type][zone] += delta;
3140 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3142 int gen, type, zone;
3143 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3147 for_each_gen_type_zone(gen, type, zone) {
3148 enum lru_list lru = type * LRU_INACTIVE_FILE;
3149 int delta = walk->nr_pages[gen][type][zone];
3154 walk->nr_pages[gen][type][zone] = 0;
3155 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3156 lrugen->nr_pages[gen][type][zone] + delta);
3158 if (lru_gen_is_active(lruvec, gen))
3160 __update_lru_size(lruvec, lru, zone, delta);
3164 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3166 struct address_space *mapping;
3167 struct vm_area_struct *vma = args->vma;
3168 struct lru_gen_mm_walk *walk = args->private;
3170 if (!vma_is_accessible(vma))
3173 if (is_vm_hugetlb_page(vma))
3176 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3179 if (vma == get_gate_vma(vma->vm_mm))
3182 if (vma_is_anonymous(vma))
3183 return !walk->can_swap;
3185 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3188 mapping = vma->vm_file->f_mapping;
3189 if (mapping_unevictable(mapping))
3192 if (shmem_mapping(mapping))
3193 return !walk->can_swap;
3195 /* to exclude special mappings like dax, etc. */
3196 return !mapping->a_ops->readpage;
3200 * Some userspace memory allocators map many single-page VMAs. Instead of
3201 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3202 * table to reduce zigzags and improve cache performance.
3204 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3205 unsigned long *vm_start, unsigned long *vm_end)
3207 unsigned long start = round_up(*vm_end, size);
3208 unsigned long end = (start | ~mask) + 1;
3210 VM_WARN_ON_ONCE(mask & size);
3211 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3214 if (start >= args->vma->vm_end) {
3215 args->vma = args->vma->vm_next;
3219 if (end && end <= args->vma->vm_start)
3222 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3223 args->vma = args->vma->vm_next;
3227 *vm_start = max(start, args->vma->vm_start);
3228 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3236 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3238 unsigned long pfn = pte_pfn(pte);
3240 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3242 if (!pte_present(pte) || is_zero_pfn(pfn))
3245 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3248 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3254 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3255 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3257 unsigned long pfn = pmd_pfn(pmd);
3259 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3261 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3264 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3267 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3274 static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
3275 struct pglist_data *pgdat, bool can_swap)
3279 /* try to avoid unnecessary memory loads */
3280 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3283 page = compound_head(pfn_to_page(pfn));
3284 if (page_to_nid(page) != pgdat->node_id)
3287 if (page_memcg_rcu(page) != memcg)
3290 /* file VMAs can contain anon pages from COW */
3291 if (!page_is_file_cache(page) && !can_swap)
3297 static bool suitable_to_scan(int total, int young)
3299 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3301 /* suitable if the average number of young PTEs per cacheline is >=1 */
3302 return young * n >= total;
3305 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3306 struct mm_walk *args)
3314 struct lru_gen_mm_walk *walk = args->private;
3315 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3316 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3317 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3319 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3321 ptl = pte_lockptr(args->mm, pmd);
3322 if (!spin_trylock(ptl))
3325 arch_enter_lazy_mmu_mode();
3327 pte = pte_offset_map(pmd, start & PMD_MASK);
3329 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3334 walk->mm_stats[MM_LEAF_TOTAL]++;
3336 pfn = get_pte_pfn(pte[i], args->vma, addr);
3340 if (!pte_young(pte[i])) {
3341 walk->mm_stats[MM_LEAF_OLD]++;
3345 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3349 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3350 VM_WARN_ON_ONCE(true);
3353 walk->mm_stats[MM_LEAF_YOUNG]++;
3355 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3356 !(PageAnon(page) && PageSwapBacked(page) &&
3357 !PageSwapCache(page)))
3358 set_page_dirty(page);
3360 old_gen = page_update_gen(page, new_gen);
3361 if (old_gen >= 0 && old_gen != new_gen)
3362 update_batch_size(walk, page, old_gen, new_gen);
3365 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3370 arch_leave_lazy_mmu_mode();
3373 return suitable_to_scan(total, young);
3376 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3377 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3378 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3383 struct lru_gen_mm_walk *walk = args->private;
3384 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3385 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3386 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3388 VM_WARN_ON_ONCE(pud_leaf(*pud));
3390 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3396 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3397 if (i && i <= MIN_LRU_BATCH) {
3398 __set_bit(i - 1, bitmap);
3402 pmd = pmd_offset(pud, *start);
3404 ptl = pmd_lockptr(args->mm, pmd);
3405 if (!spin_trylock(ptl))
3408 arch_enter_lazy_mmu_mode();
3413 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3415 pfn = get_pmd_pfn(pmd[i], vma, addr);
3419 if (!pmd_trans_huge(pmd[i])) {
3420 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3421 get_cap(LRU_GEN_NONLEAF_YOUNG))
3422 pmdp_test_and_clear_young(vma, addr, pmd + i);
3426 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3430 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3433 walk->mm_stats[MM_LEAF_YOUNG]++;
3435 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3436 !(PageAnon(page) && PageSwapBacked(page) &&
3437 !PageSwapCache(page)))
3438 set_page_dirty(page);
3440 old_gen = page_update_gen(page, new_gen);
3441 if (old_gen >= 0 && old_gen != new_gen)
3442 update_batch_size(walk, page, old_gen, new_gen);
3444 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3445 } while (i <= MIN_LRU_BATCH);
3447 arch_leave_lazy_mmu_mode();
3451 bitmap_zero(bitmap, MIN_LRU_BATCH);
3454 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3455 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3460 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3461 struct mm_walk *args)
3467 struct vm_area_struct *vma;
3468 unsigned long pos = -1;
3469 struct lru_gen_mm_walk *walk = args->private;
3470 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3472 VM_WARN_ON_ONCE(pud_leaf(*pud));
3475 * Finish an entire PMD in two passes: the first only reaches to PTE
3476 * tables to avoid taking the PMD lock; the second, if necessary, takes
3477 * the PMD lock to clear the accessed bit in PMD entries.
3479 pmd = pmd_offset(pud, start & PUD_MASK);
3481 /* walk_pte_range() may call get_next_vma() */
3483 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3484 pmd_t val = pmd_read_atomic(pmd + i);
3486 /* for pmd_read_atomic() */
3489 next = pmd_addr_end(addr, end);
3491 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3492 walk->mm_stats[MM_LEAF_TOTAL]++;
3496 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3497 if (pmd_trans_huge(val)) {
3498 unsigned long pfn = pmd_pfn(val);
3499 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3501 walk->mm_stats[MM_LEAF_TOTAL]++;
3503 if (!pmd_young(val)) {
3504 walk->mm_stats[MM_LEAF_OLD]++;
3508 /* try to avoid unnecessary memory loads */
3509 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3512 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3516 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3518 #ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
3519 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3520 if (!pmd_young(val))
3523 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3526 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3529 walk->mm_stats[MM_NONLEAF_FOUND]++;
3531 if (!walk_pte_range(&val, addr, next, args))
3534 walk->mm_stats[MM_NONLEAF_ADDED]++;
3536 /* carry over to the next generation */
3537 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3540 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3542 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3546 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3547 struct mm_walk *args)
3553 struct lru_gen_mm_walk *walk = args->private;
3555 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3557 pud = pud_offset(p4d, start & P4D_MASK);
3559 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3560 pud_t val = READ_ONCE(pud[i]);
3562 next = pud_addr_end(addr, end);
3564 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3567 walk_pmd_range(&val, addr, next, args);
3569 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3570 end = (addr | ~PUD_MASK) + 1;
3575 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3578 end = round_up(end, P4D_SIZE);
3580 if (!end || !args->vma)
3583 walk->next_addr = max(end, args->vma->vm_start);
3588 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3590 static const struct mm_walk_ops mm_walk_ops = {
3591 .test_walk = should_skip_vma,
3592 .p4d_entry = walk_pud_range,
3596 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3598 walk->next_addr = FIRST_USER_ADDRESS;
3601 DEFINE_MAX_SEQ(lruvec);
3605 /* another thread might have called inc_max_seq() */
3606 if (walk->max_seq != max_seq)
3609 /* page_update_gen() requires stable page_memcg() */
3610 if (!mem_cgroup_trylock_pages(memcg))
3613 /* the caller might be holding the lock for write */
3614 if (down_read_trylock(&mm->mmap_sem)) {
3615 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3617 up_write(&mm->mmap_sem);
3620 mem_cgroup_unlock_pages();
3622 if (walk->batched) {
3623 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3624 reset_batch_size(lruvec, walk);
3625 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3629 } while (err == -EAGAIN);
3632 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3634 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3636 if (pgdat && current_is_kswapd()) {
3637 VM_WARN_ON_ONCE(walk);
3639 walk = &pgdat->mm_walk;
3640 } else if (!pgdat && !walk) {
3641 VM_WARN_ON_ONCE(current_is_kswapd());
3643 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3646 current->reclaim_state->mm_walk = walk;
3651 static void clear_mm_walk(void)
3653 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3655 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3656 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3658 current->reclaim_state->mm_walk = NULL;
3660 if (!current_is_kswapd())
3664 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
3667 int remaining = MAX_LRU_BATCH;
3668 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3669 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3671 if (type == LRU_GEN_ANON && !can_swap)
3674 /* prevent cold/hot inversion if force_scan is true */
3675 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3676 struct list_head *head = &lrugen->lists[old_gen][type][zone];
3678 while (!list_empty(head)) {
3679 struct page *page = lru_to_page(head);
3681 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
3682 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
3683 VM_WARN_ON_ONCE_PAGE(page_is_file_cache(page) != type, page);
3684 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
3686 new_gen = page_inc_gen(lruvec, page, false);
3687 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
3694 reset_ctrl_pos(lruvec, type, true);
3695 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3700 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3702 int gen, type, zone;
3703 bool success = false;
3704 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3705 DEFINE_MIN_SEQ(lruvec);
3707 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3709 /* find the oldest populated generation */
3710 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3711 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3712 gen = lru_gen_from_seq(min_seq[type]);
3714 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3715 if (!list_empty(&lrugen->lists[gen][type][zone]))
3725 /* see the comment on lru_gen_struct */
3727 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3728 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3731 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3732 if (min_seq[type] == lrugen->min_seq[type])
3735 reset_ctrl_pos(lruvec, type, true);
3736 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3743 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
3747 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3749 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3751 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3753 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3754 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3757 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
3759 while (!inc_min_seq(lruvec, type, can_swap)) {
3760 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3762 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3767 * Update the active/inactive LRU sizes for compatibility. Both sides of
3768 * the current max_seq need to be covered, since max_seq+1 can overlap
3769 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3770 * overlap, cold/hot inversion happens.
3772 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3773 next = lru_gen_from_seq(lrugen->max_seq + 1);
3775 for (type = 0; type < ANON_AND_FILE; type++) {
3776 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3777 enum lru_list lru = type * LRU_INACTIVE_FILE;
3778 long delta = lrugen->nr_pages[prev][type][zone] -
3779 lrugen->nr_pages[next][type][zone];
3784 __update_lru_size(lruvec, lru, zone, delta);
3785 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3789 for (type = 0; type < ANON_AND_FILE; type++)
3790 reset_ctrl_pos(lruvec, type, false);
3792 WRITE_ONCE(lrugen->timestamps[next], jiffies);
3793 /* make sure preceding modifications appear */
3794 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3796 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
3799 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
3800 struct scan_control *sc, bool can_swap, bool force_scan)
3803 struct lru_gen_mm_walk *walk;
3804 struct mm_struct *mm = NULL;
3805 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3807 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
3809 /* see the comment in iterate_mm_list() */
3810 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
3816 * If the hardware doesn't automatically set the accessed bit, fallback
3817 * to lru_gen_look_around(), which only clears the accessed bit in a
3818 * handful of PTEs. Spreading the work out over a period of time usually
3819 * is less efficient, but it avoids bursty page faults.
3821 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
3822 success = iterate_mm_list_nowalk(lruvec, max_seq);
3826 walk = set_mm_walk(NULL);
3828 success = iterate_mm_list_nowalk(lruvec, max_seq);
3832 walk->lruvec = lruvec;
3833 walk->max_seq = max_seq;
3834 walk->can_swap = can_swap;
3835 walk->force_scan = force_scan;
3838 success = iterate_mm_list(lruvec, walk, &mm);
3840 walk_mm(lruvec, mm, walk);
3844 inc_max_seq(lruvec, can_swap, force_scan);
3849 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
3850 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
3852 int gen, type, zone;
3853 unsigned long old = 0;
3854 unsigned long young = 0;
3855 unsigned long total = 0;
3856 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3857 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3859 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3862 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3863 unsigned long size = 0;
3865 gen = lru_gen_from_seq(seq);
3867 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3868 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3873 else if (seq + MIN_NR_GENS == max_seq)
3878 /* try to scrape all its memory if this memcg was deleted */
3879 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3882 * The aging tries to be lazy to reduce the overhead, while the eviction
3883 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
3884 * ideal number of generations is MIN_NR_GENS+1.
3886 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
3888 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
3892 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
3893 * of the total number of pages for each generation. A reasonable range
3894 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
3895 * aging cares about the upper bound of hot pages, while the eviction
3896 * cares about the lower bound of cold pages.
3898 if (young * MIN_NR_GENS > total)
3900 if (old * (MIN_NR_GENS + 2) < total)
3906 static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
3909 unsigned long nr_to_scan;
3910 int swappiness = get_swappiness(lruvec, sc);
3911 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3912 DEFINE_MAX_SEQ(lruvec);
3913 DEFINE_MIN_SEQ(lruvec);
3915 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
3917 mem_cgroup_calculate_protection(NULL, memcg);
3919 if (mem_cgroup_below_min(memcg))
3922 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
3925 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
3926 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
3928 if (time_is_after_jiffies(birth + min_ttl))
3931 /* the size is likely too small to be helpful */
3932 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
3937 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
3942 /* to protect the working set of the last N jiffies */
3943 static unsigned long lru_gen_min_ttl __read_mostly;
3945 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3947 struct mem_cgroup *memcg;
3948 bool success = false;
3949 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
3951 VM_WARN_ON_ONCE(!current_is_kswapd());
3953 sc->last_reclaimed = sc->nr_reclaimed;
3956 * To reduce the chance of going into the aging path, which can be
3957 * costly, optimistically skip it if the flag below was cleared in the
3958 * eviction path. This improves the overall performance when multiple
3959 * memcgs are available.
3961 if (!sc->memcgs_need_aging) {
3962 sc->memcgs_need_aging = true;
3968 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3970 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3972 if (age_lruvec(lruvec, sc, min_ttl))
3976 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3980 /* check the order to exclude compaction-induced reclaim */
3981 if (success || !min_ttl || sc->order)
3985 * The main goal is to OOM kill if every generation from all memcgs is
3986 * younger than min_ttl. However, another possibility is all memcgs are
3987 * either below min or empty.
3989 if (mutex_trylock(&oom_lock)) {
3990 struct oom_control oc = {
3991 .gfp_mask = sc->gfp_mask,
3996 mutex_unlock(&oom_lock);
4001 * This function exploits spatial locality when shrink_page_list() walks the
4002 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4003 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4004 * the PTE table to the Bloom filter. This forms a feedback loop between the
4005 * eviction and the aging.
4007 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4011 unsigned long start;
4014 struct lru_gen_mm_walk *walk;
4016 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4017 struct page *page = pvmw->page;
4018 struct mem_cgroup *memcg = page_memcg(page);
4019 struct pglist_data *pgdat = page_pgdat(page);
4020 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4021 DEFINE_MAX_SEQ(lruvec);
4022 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4024 lockdep_assert_held(pvmw->ptl);
4025 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4027 if (spin_is_contended(pvmw->ptl))
4030 /* avoid taking the LRU lock under the PTL when possible */
4031 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4033 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4034 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4036 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4037 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4038 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4039 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4040 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4042 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4043 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4047 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4050 arch_enter_lazy_mmu_mode();
4052 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4055 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4059 if (!pte_young(pte[i]))
4062 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
4066 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4067 VM_WARN_ON_ONCE(true);
4071 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4072 !(PageAnon(page) && PageSwapBacked(page) &&
4073 !PageSwapCache(page)))
4074 set_page_dirty(page);
4076 old_gen = page_lru_gen(page);
4078 SetPageReferenced(page);
4079 else if (old_gen != new_gen)
4080 __set_bit(i, bitmap);
4083 arch_leave_lazy_mmu_mode();
4086 /* feedback from rmap walkers to page table walkers */
4087 if (suitable_to_scan(i, young))
4088 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4090 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4091 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4092 page = pte_page(pte[i]);
4093 activate_page(page);
4098 /* page_update_gen() requires stable page_memcg() */
4099 if (!mem_cgroup_trylock_pages(memcg))
4103 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4104 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4107 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4108 page = compound_head(pte_page(pte[i]));
4109 if (page_memcg_rcu(page) != memcg)
4112 old_gen = page_update_gen(page, new_gen);
4113 if (old_gen < 0 || old_gen == new_gen)
4117 update_batch_size(walk, page, old_gen, new_gen);
4119 lru_gen_update_size(lruvec, page, old_gen, new_gen);
4123 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4125 mem_cgroup_unlock_pages();
4128 /******************************************************************************
4130 ******************************************************************************/
4132 static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4135 int gen = page_lru_gen(page);
4136 int type = page_is_file_cache(page);
4137 int zone = page_zonenum(page);
4138 int delta = hpage_nr_pages(page);
4139 int refs = page_lru_refs(page);
4140 int tier = lru_tier_from_refs(refs);
4141 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4143 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4146 if (!page_evictable(page)) {
4147 success = lru_gen_del_page(lruvec, page, true);
4148 VM_WARN_ON_ONCE_PAGE(!success, page);
4149 SetPageUnevictable(page);
4150 add_page_to_lru_list(page, lruvec, LRU_UNEVICTABLE);
4151 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4155 /* dirty lazyfree */
4156 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4157 enum lru_list lru = page_lru_base_type(page);
4159 success = lru_gen_del_page(lruvec, page, true);
4160 VM_WARN_ON_ONCE_PAGE(!success, page);
4161 SetPageSwapBacked(page);
4162 add_page_to_lru_list_tail(page, lruvec, lru);
4167 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4168 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4173 if (tier > tier_idx) {
4174 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4176 gen = page_inc_gen(lruvec, page, false);
4177 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4179 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4180 lrugen->protected[hist][type][tier - 1] + delta);
4181 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE, delta);
4185 /* waiting for writeback */
4186 if (PageLocked(page) || PageWriteback(page) ||
4187 (type == LRU_GEN_FILE && PageDirty(page))) {
4188 gen = page_inc_gen(lruvec, page, true);
4189 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4196 static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4200 /* unmapping inhibited */
4201 if (!sc->may_unmap && page_mapped(page))
4204 /* swapping inhibited */
4205 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4207 (PageAnon(page) && !PageSwapCache(page))))
4210 /* raced with release_pages() */
4211 if (!get_page_unless_zero(page))
4214 /* raced with another isolation */
4215 if (!TestClearPageLRU(page)) {
4220 /* see the comment on MAX_NR_TIERS */
4221 if (!PageReferenced(page))
4222 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4224 /* for shrink_page_list() */
4225 ClearPageReclaim(page);
4226 ClearPageReferenced(page);
4228 success = lru_gen_del_page(lruvec, page, true);
4229 VM_WARN_ON_ONCE_PAGE(!success, page);
4234 static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4235 int type, int tier, struct list_head *list)
4238 enum vm_event_item item;
4242 int remaining = MAX_LRU_BATCH;
4243 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4244 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4246 VM_WARN_ON_ONCE(!list_empty(list));
4248 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4251 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4253 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4256 struct list_head *head = &lrugen->lists[gen][type][zone];
4258 while (!list_empty(head)) {
4259 struct page *page = lru_to_page(head);
4260 int delta = hpage_nr_pages(page);
4262 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4263 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4264 VM_WARN_ON_ONCE_PAGE(page_is_file_cache(page) != type, page);
4265 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4269 if (sort_page(lruvec, page, tier))
4271 else if (isolate_page(lruvec, page, sc)) {
4272 list_add(&page->lru, list);
4275 list_move(&page->lru, &moved);
4279 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4284 list_splice(&moved, head);
4285 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4288 if (!remaining || isolated >= MIN_LRU_BATCH)
4292 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4293 if (!cgroup_reclaim(sc)) {
4294 __count_vm_events(item, isolated);
4295 __count_vm_events(PGREFILL, sorted);
4297 __count_memcg_events(memcg, item, isolated);
4298 __count_memcg_events(memcg, PGREFILL, sorted);
4301 * There might not be eligible pages due to reclaim_idx, may_unmap and
4302 * may_writepage. Check the remaining to prevent livelock if it's not
4305 return isolated || !remaining ? scanned : 0;
4308 static int get_tier_idx(struct lruvec *lruvec, int type)
4311 struct ctrl_pos sp, pv;
4314 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4315 * This value is chosen because any other tier would have at least twice
4316 * as many refaults as the first tier.
4318 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4319 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4320 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4321 if (!positive_ctrl_err(&sp, &pv))
4328 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4331 struct ctrl_pos sp, pv;
4332 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4335 * Compare the first tier of anon with that of file to determine which
4336 * type to scan. Also need to compare other tiers of the selected type
4337 * with the first tier of the other type to determine the last tier (of
4338 * the selected type) to evict.
4340 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4341 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4342 type = positive_ctrl_err(&sp, &pv);
4344 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4345 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4346 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4347 if (!positive_ctrl_err(&sp, &pv))
4351 *tier_idx = tier - 1;
4356 static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4357 int *type_scanned, struct list_head *list)
4363 DEFINE_MIN_SEQ(lruvec);
4366 * Try to make the obvious choice first. When anon and file are both
4367 * available from the same generation, interpret swappiness 1 as file
4368 * first and 200 as anon first.
4371 type = LRU_GEN_FILE;
4372 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4373 type = LRU_GEN_ANON;
4374 else if (swappiness == 1)
4375 type = LRU_GEN_FILE;
4376 else if (swappiness == 200)
4377 type = LRU_GEN_ANON;
4379 type = get_type_to_scan(lruvec, swappiness, &tier);
4381 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4383 tier = get_tier_idx(lruvec, type);
4385 scanned = scan_pages(lruvec, sc, type, tier, list);
4393 *type_scanned = type;
4398 static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4399 bool *need_swapping)
4406 enum vm_event_item item;
4407 struct reclaim_stat stat;
4408 struct lru_gen_mm_walk *walk;
4409 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4410 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4412 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4414 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4416 scanned += try_to_inc_min_seq(lruvec, swappiness);
4418 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4421 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4423 if (list_empty(&list))
4426 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4428 list_for_each_entry(page, &list, lru) {
4429 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4430 if (PageWorkingset(page))
4431 SetPageReferenced(page);
4433 /* don't add rejected pages to the oldest generation */
4434 if (PageReclaim(page) &&
4435 (PageDirty(page) || PageWriteback(page)))
4436 ClearPageActive(page);
4438 SetPageActive(page);
4441 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4443 move_pages_to_lru(lruvec, &list);
4445 walk = current->reclaim_state->mm_walk;
4446 if (walk && walk->batched)
4447 reset_batch_size(lruvec, walk);
4449 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4450 if (!cgroup_reclaim(sc))
4451 __count_vm_events(item, reclaimed);
4452 __count_memcg_events(memcg, item, reclaimed);
4454 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4456 mem_cgroup_uncharge_list(&list);
4457 free_unref_page_list(&list);
4459 sc->nr_reclaimed += reclaimed;
4461 if (need_swapping && type == LRU_GEN_ANON)
4462 *need_swapping = true;
4468 * For future optimizations:
4469 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4472 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
4473 bool can_swap, bool *need_aging)
4475 unsigned long nr_to_scan;
4476 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4477 DEFINE_MAX_SEQ(lruvec);
4478 DEFINE_MIN_SEQ(lruvec);
4480 if (mem_cgroup_below_min(memcg) ||
4481 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4484 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4488 /* skip the aging path at the default priority */
4489 if (sc->priority == DEF_PRIORITY)
4492 /* leave the work to lru_gen_age_node() */
4493 if (current_is_kswapd())
4496 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4499 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4502 static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4503 struct scan_control *sc, bool need_swapping)
4506 DEFINE_MAX_SEQ(lruvec);
4508 if (!current_is_kswapd()) {
4509 /* age each memcg at most once to ensure fairness */
4510 if (max_seq - seq > 1)
4513 /* over-swapping can increase allocation latency */
4514 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4517 /* give this thread a chance to exit and free its memory */
4518 if (fatal_signal_pending(current)) {
4519 sc->nr_reclaimed += MIN_LRU_BATCH;
4523 if (cgroup_reclaim(sc))
4525 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4528 /* keep scanning at low priorities to ensure fairness */
4529 if (sc->priority > DEF_PRIORITY - 2)
4533 * A minimum amount of work was done under global memory pressure. For
4534 * kswapd, it may be overshooting. For direct reclaim, the allocation
4535 * may succeed if all suitable zones are somewhat safe. In either case,
4536 * it's better to stop now, and restart later if necessary.
4538 for (i = 0; i <= sc->reclaim_idx; i++) {
4539 unsigned long wmark;
4540 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4542 if (!managed_zone(zone))
4545 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4546 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4550 sc->nr_reclaimed += MIN_LRU_BATCH;
4555 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4557 struct blk_plug plug;
4558 bool need_aging = false;
4559 bool need_swapping = false;
4560 unsigned long scanned = 0;
4561 unsigned long reclaimed = sc->nr_reclaimed;
4562 DEFINE_MAX_SEQ(lruvec);
4566 blk_start_plug(&plug);
4568 set_mm_walk(lruvec_pgdat(lruvec));
4573 unsigned long nr_to_scan;
4576 swappiness = get_swappiness(lruvec, sc);
4577 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4582 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
4586 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
4591 if (scanned >= nr_to_scan)
4594 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4600 /* see the comment in lru_gen_age_node() */
4601 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4602 sc->memcgs_need_aging = false;
4606 blk_finish_plug(&plug);
4609 /******************************************************************************
4611 ******************************************************************************/
4613 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4615 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4617 if (lrugen->enabled) {
4620 for_each_evictable_lru(lru) {
4621 if (!list_empty(&lruvec->lists[lru]))
4625 int gen, type, zone;
4627 for_each_gen_type_zone(gen, type, zone) {
4628 if (!list_empty(&lrugen->lists[gen][type][zone]))
4636 static bool fill_evictable(struct lruvec *lruvec)
4639 int remaining = MAX_LRU_BATCH;
4641 for_each_evictable_lru(lru) {
4642 int type = is_file_lru(lru);
4643 bool active = is_active_lru(lru);
4644 struct list_head *head = &lruvec->lists[lru];
4646 while (!list_empty(head)) {
4648 struct page *page = lru_to_page(head);
4649 enum lru_list lru = page_lru_base_type(page);
4651 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4652 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
4653 VM_WARN_ON_ONCE_PAGE(page_is_file_cache(page) != type, page);
4654 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
4656 del_page_from_lru_list(page, lruvec, lru);
4657 success = lru_gen_add_page(lruvec, page, false);
4658 VM_WARN_ON_ONCE(!success);
4668 static bool drain_evictable(struct lruvec *lruvec)
4670 int gen, type, zone;
4671 int remaining = MAX_LRU_BATCH;
4673 for_each_gen_type_zone(gen, type, zone) {
4674 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
4676 while (!list_empty(head)) {
4678 struct page *page = lru_to_page(head);
4679 enum lru_list lru = page_lru_base_type(page);
4681 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4682 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4683 VM_WARN_ON_ONCE_PAGE(page_is_file_cache(page) != type, page);
4684 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4686 success = lru_gen_del_page(lruvec, page, false);
4687 VM_WARN_ON_ONCE(!success);
4688 add_page_to_lru_list(page, lruvec, lru);
4698 static void lru_gen_change_state(bool enabled)
4700 static DEFINE_MUTEX(state_mutex);
4702 struct mem_cgroup *memcg;
4707 mutex_lock(&state_mutex);
4709 if (enabled == lru_gen_enabled())
4713 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4715 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4717 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4721 for_each_node(nid) {
4722 struct lruvec *lruvec = get_lruvec(memcg, nid);
4727 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4729 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4730 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
4732 lruvec->lrugen.enabled = enabled;
4734 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
4735 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4737 spin_lock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4740 spin_unlock_irq(&lruvec_pgdat(lruvec)->lru_lock);
4744 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4746 mutex_unlock(&state_mutex);
4752 /******************************************************************************
4754 ******************************************************************************/
4756 static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
4758 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
4761 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
4762 static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
4763 const char *buf, size_t len)
4767 if (kstrtouint(buf, 0, &msecs))
4770 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
4775 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
4776 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
4779 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
4781 unsigned int caps = 0;
4783 if (get_cap(LRU_GEN_CORE))
4784 caps |= BIT(LRU_GEN_CORE);
4786 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
4787 caps |= BIT(LRU_GEN_MM_WALK);
4789 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
4790 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
4792 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
4795 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
4796 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
4797 const char *buf, size_t len)
4802 if (tolower(*buf) == 'n')
4804 else if (tolower(*buf) == 'y')
4806 else if (kstrtouint(buf, 0, &caps))
4809 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
4810 bool enabled = caps & BIT(i);
4812 if (i == LRU_GEN_CORE)
4813 lru_gen_change_state(enabled);
4815 static_branch_enable(&lru_gen_caps[i]);
4817 static_branch_disable(&lru_gen_caps[i]);
4823 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
4824 enabled, 0644, show_enabled, store_enabled
4827 static struct attribute *lru_gen_attrs[] = {
4828 &lru_gen_min_ttl_attr.attr,
4829 &lru_gen_enabled_attr.attr,
4833 static struct attribute_group lru_gen_attr_group = {
4835 .attrs = lru_gen_attrs,
4838 /******************************************************************************
4840 ******************************************************************************/
4842 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
4844 struct mem_cgroup *memcg;
4845 loff_t nr_to_skip = *pos;
4847 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
4849 return ERR_PTR(-ENOMEM);
4851 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4855 for_each_node_state(nid, N_MEMORY) {
4857 return get_lruvec(memcg, nid);
4859 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4864 static void lru_gen_seq_stop(struct seq_file *m, void *v)
4866 if (!IS_ERR_OR_NULL(v))
4867 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
4873 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
4875 int nid = lruvec_pgdat(v)->node_id;
4876 struct mem_cgroup *memcg = lruvec_memcg(v);
4880 nid = next_memory_node(nid);
4881 if (nid == MAX_NUMNODES) {
4882 memcg = mem_cgroup_iter(NULL, memcg, NULL);
4886 nid = first_memory_node;
4889 return get_lruvec(memcg, nid);
4892 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
4893 unsigned long max_seq, unsigned long *min_seq,
4898 int hist = lru_hist_from_seq(seq);
4899 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4901 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
4902 seq_printf(m, " %10d", tier);
4903 for (type = 0; type < ANON_AND_FILE; type++) {
4904 const char *s = " ";
4905 unsigned long n[3] = {};
4907 if (seq == max_seq) {
4909 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
4910 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
4911 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
4913 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
4914 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
4916 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
4919 for (i = 0; i < 3; i++)
4920 seq_printf(m, " %10lu%c", n[i], s[i]);
4926 for (i = 0; i < NR_MM_STATS; i++) {
4927 const char *s = " ";
4928 unsigned long n = 0;
4930 if (seq == max_seq && NR_HIST_GENS == 1) {
4932 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
4933 } else if (seq != max_seq && NR_HIST_GENS > 1) {
4935 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
4938 seq_printf(m, " %10lu%c", n, s[i]);
4943 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
4944 static int lru_gen_seq_show(struct seq_file *m, void *v)
4947 bool full = !debugfs_real_fops(m->file)->write;
4948 struct lruvec *lruvec = v;
4949 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4950 int nid = lruvec_pgdat(lruvec)->node_id;
4951 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4952 DEFINE_MAX_SEQ(lruvec);
4953 DEFINE_MIN_SEQ(lruvec);
4955 if (nid == first_memory_node) {
4956 const char *path = memcg ? m->private : "";
4960 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
4962 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
4965 seq_printf(m, " node %5d\n", nid);
4968 seq = min_seq[LRU_GEN_ANON];
4969 else if (max_seq >= MAX_NR_GENS)
4970 seq = max_seq - MAX_NR_GENS + 1;
4974 for (; seq <= max_seq; seq++) {
4976 int gen = lru_gen_from_seq(seq);
4977 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4979 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
4981 for (type = 0; type < ANON_AND_FILE; type++) {
4982 unsigned long size = 0;
4983 char mark = full && seq < min_seq[type] ? 'x' : ' ';
4985 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4986 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4988 seq_printf(m, " %10lu%c", size, mark);
4994 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5000 static const struct seq_operations lru_gen_seq_ops = {
5001 .start = lru_gen_seq_start,
5002 .stop = lru_gen_seq_stop,
5003 .next = lru_gen_seq_next,
5004 .show = lru_gen_seq_show,
5007 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5008 bool can_swap, bool force_scan)
5010 DEFINE_MAX_SEQ(lruvec);
5011 DEFINE_MIN_SEQ(lruvec);
5019 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5022 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5027 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5028 int swappiness, unsigned long nr_to_reclaim)
5030 DEFINE_MAX_SEQ(lruvec);
5032 if (seq + MIN_NR_GENS > max_seq)
5035 sc->nr_reclaimed = 0;
5037 while (!signal_pending(current)) {
5038 DEFINE_MIN_SEQ(lruvec);
5040 if (seq < min_seq[!swappiness])
5043 if (sc->nr_reclaimed >= nr_to_reclaim)
5046 if (!evict_pages(lruvec, sc, swappiness, NULL))
5055 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5056 struct scan_control *sc, int swappiness, unsigned long opt)
5058 struct lruvec *lruvec;
5060 struct mem_cgroup *memcg = NULL;
5062 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5065 if (!mem_cgroup_disabled()) {
5067 memcg = mem_cgroup_from_id(memcg_id);
5069 if (memcg && !css_tryget(&memcg->css))
5078 if (memcg_id != mem_cgroup_id(memcg))
5081 lruvec = get_lruvec(memcg, nid);
5084 swappiness = get_swappiness(lruvec, sc);
5085 else if (swappiness > 200)
5090 err = run_aging(lruvec, seq, sc, swappiness, opt);
5093 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5097 mem_cgroup_put(memcg);
5102 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5103 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5104 size_t len, loff_t *pos)
5109 struct blk_plug plug;
5111 struct scan_control sc = {
5112 .may_writepage = true,
5115 .reclaim_idx = MAX_NR_ZONES - 1,
5116 .gfp_mask = GFP_KERNEL,
5119 buf = kvmalloc(len + 1, GFP_KERNEL);
5123 if (copy_from_user(buf, src, len)) {
5128 set_task_reclaim_state(current, &sc.reclaim_state);
5129 flags = memalloc_noreclaim_save();
5130 blk_start_plug(&plug);
5131 if (!set_mm_walk(NULL)) {
5139 while ((cur = strsep(&next, ",;\n"))) {
5143 unsigned int memcg_id;
5146 unsigned int swappiness = -1;
5147 unsigned long opt = -1;
5149 cur = skip_spaces(cur);
5153 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5154 &seq, &end, &swappiness, &end, &opt, &end);
5155 if (n < 4 || cur[end]) {
5160 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5166 blk_finish_plug(&plug);
5167 memalloc_noreclaim_restore(flags);
5168 set_task_reclaim_state(current, NULL);
5175 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5177 return seq_open(file, &lru_gen_seq_ops);
5180 static const struct file_operations lru_gen_rw_fops = {
5181 .open = lru_gen_seq_open,
5183 .write = lru_gen_seq_write,
5184 .llseek = seq_lseek,
5185 .release = seq_release,
5188 static const struct file_operations lru_gen_ro_fops = {
5189 .open = lru_gen_seq_open,
5191 .llseek = seq_lseek,
5192 .release = seq_release,
5195 /******************************************************************************
5197 ******************************************************************************/
5199 void lru_gen_init_lruvec(struct lruvec *lruvec)
5202 int gen, type, zone;
5203 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5205 lrugen->max_seq = MIN_NR_GENS + 1;
5206 lrugen->enabled = lru_gen_enabled();
5208 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5209 lrugen->timestamps[i] = jiffies;
5211 for_each_gen_type_zone(gen, type, zone)
5212 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
5214 lruvec->mm_state.seq = MIN_NR_GENS;
5218 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5220 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5221 spin_lock_init(&memcg->mm_list.lock);
5224 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5229 for_each_node(nid) {
5230 struct lruvec *lruvec = get_lruvec(memcg, nid);
5232 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5233 sizeof(lruvec->lrugen.nr_pages)));
5235 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5236 bitmap_free(lruvec->mm_state.filters[i]);
5237 lruvec->mm_state.filters[i] = NULL;
5243 static int __init init_lru_gen(void)
5245 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5246 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5248 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5249 pr_err("lru_gen: failed to create sysfs group\n");
5251 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5252 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5256 late_initcall(init_lru_gen);
5258 #else /* !CONFIG_LRU_GEN */
5260 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5264 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5268 #endif /* CONFIG_LRU_GEN */
5270 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5272 unsigned long nr[NR_LRU_LISTS];
5273 unsigned long targets[NR_LRU_LISTS];
5274 unsigned long nr_to_scan;
5276 unsigned long nr_reclaimed = 0;
5277 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5278 struct blk_plug plug;
5281 if (lru_gen_enabled()) {
5282 lru_gen_shrink_lruvec(lruvec, sc);
5286 get_scan_count(lruvec, sc, nr);
5288 /* Record the original scan target for proportional adjustments later */
5289 memcpy(targets, nr, sizeof(nr));
5292 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5293 * event that can occur when there is little memory pressure e.g.
5294 * multiple streaming readers/writers. Hence, we do not abort scanning
5295 * when the requested number of pages are reclaimed when scanning at
5296 * DEF_PRIORITY on the assumption that the fact we are direct
5297 * reclaiming implies that kswapd is not keeping up and it is best to
5298 * do a batch of work at once. For memcg reclaim one check is made to
5299 * abort proportional reclaim if either the file or anon lru has already
5300 * dropped to zero at the first pass.
5302 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5303 sc->priority == DEF_PRIORITY);
5305 blk_start_plug(&plug);
5306 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5307 nr[LRU_INACTIVE_FILE]) {
5308 unsigned long nr_anon, nr_file, percentage;
5309 unsigned long nr_scanned;
5311 for_each_evictable_lru(lru) {
5313 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5314 nr[lru] -= nr_to_scan;
5316 nr_reclaimed += shrink_list(lru, nr_to_scan,
5323 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5327 * For kswapd and memcg, reclaim at least the number of pages
5328 * requested. Ensure that the anon and file LRUs are scanned
5329 * proportionally what was requested by get_scan_count(). We
5330 * stop reclaiming one LRU and reduce the amount scanning
5331 * proportional to the original scan target.
5333 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5334 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5337 * It's just vindictive to attack the larger once the smaller
5338 * has gone to zero. And given the way we stop scanning the
5339 * smaller below, this makes sure that we only make one nudge
5340 * towards proportionality once we've got nr_to_reclaim.
5342 if (!nr_file || !nr_anon)
5345 if (nr_file > nr_anon) {
5346 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5347 targets[LRU_ACTIVE_ANON] + 1;
5349 percentage = nr_anon * 100 / scan_target;
5351 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5352 targets[LRU_ACTIVE_FILE] + 1;
5354 percentage = nr_file * 100 / scan_target;
5357 /* Stop scanning the smaller of the LRU */
5359 nr[lru + LRU_ACTIVE] = 0;
5362 * Recalculate the other LRU scan count based on its original
5363 * scan target and the percentage scanning already complete
5365 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5366 nr_scanned = targets[lru] - nr[lru];
5367 nr[lru] = targets[lru] * (100 - percentage) / 100;
5368 nr[lru] -= min(nr[lru], nr_scanned);
5371 nr_scanned = targets[lru] - nr[lru];
5372 nr[lru] = targets[lru] * (100 - percentage) / 100;
5373 nr[lru] -= min(nr[lru], nr_scanned);
5375 scan_adjusted = true;
5377 blk_finish_plug(&plug);
5378 sc->nr_reclaimed += nr_reclaimed;
5381 * Even if we did not try to evict anon pages at all, we want to
5382 * rebalance the anon lru active/inactive ratio.
5384 if (total_swap_pages && inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5385 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5386 sc, LRU_ACTIVE_ANON);
5389 /* Use reclaim/compaction for costly allocs or under memory pressure */
5390 static bool in_reclaim_compaction(struct scan_control *sc)
5392 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
5393 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
5394 sc->priority < DEF_PRIORITY - 2))
5401 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5402 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5403 * true if more pages should be reclaimed such that when the page allocator
5404 * calls try_to_compact_zone() that it will have enough free pages to succeed.
5405 * It will give up earlier than that if there is difficulty reclaiming pages.
5407 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
5408 unsigned long nr_reclaimed,
5409 struct scan_control *sc)
5411 unsigned long pages_for_compaction;
5412 unsigned long inactive_lru_pages;
5415 /* If not in reclaim/compaction mode, stop */
5416 if (!in_reclaim_compaction(sc))
5420 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5421 * number of pages that were scanned. This will return to the caller
5422 * with the risk reclaim/compaction and the resulting allocation attempt
5423 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5424 * allocations through requiring that the full LRU list has been scanned
5425 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5426 * scan, but that approximation was wrong, and there were corner cases
5427 * where always a non-zero amount of pages were scanned.
5432 /* If compaction would go ahead or the allocation would succeed, stop */
5433 for (z = 0; z <= sc->reclaim_idx; z++) {
5434 struct zone *zone = &pgdat->node_zones[z];
5435 if (!managed_zone(zone))
5438 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
5439 case COMPACT_SUCCESS:
5440 case COMPACT_CONTINUE:
5443 /* check next zone */
5449 * If we have not reclaimed enough pages for compaction and the
5450 * inactive lists are large enough, continue reclaiming
5452 pages_for_compaction = compact_gap(sc->order);
5453 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
5454 if (get_nr_swap_pages() > 0)
5455 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5457 return inactive_lru_pages > pages_for_compaction;
5460 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
5462 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
5463 struct mem_cgroup *memcg;
5465 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
5467 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
5468 unsigned long reclaimed;
5469 unsigned long scanned;
5471 mem_cgroup_calculate_protection(target_memcg, memcg);
5473 if (mem_cgroup_below_min(memcg)) {
5476 * If there is no reclaimable memory, OOM.
5479 } else if (mem_cgroup_below_low(memcg)) {
5482 * Respect the protection only as long as
5483 * there is an unprotected supply
5484 * of reclaimable memory from other cgroups.
5486 if (!sc->memcg_low_reclaim) {
5487 sc->memcg_low_skipped = 1;
5490 memcg_memory_event(memcg, MEMCG_LOW);
5493 reclaimed = sc->nr_reclaimed;
5494 scanned = sc->nr_scanned;
5496 shrink_lruvec(lruvec, sc);
5498 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5501 /* Record the group's reclaim efficiency */
5502 vmpressure(sc->gfp_mask, memcg, false,
5503 sc->nr_scanned - scanned,
5504 sc->nr_reclaimed - reclaimed);
5506 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5509 static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
5511 struct reclaim_state *reclaim_state = current->reclaim_state;
5512 unsigned long nr_reclaimed, nr_scanned;
5513 struct lruvec *target_lruvec;
5514 bool reclaimable = false;
5516 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5519 memset(&sc->nr, 0, sizeof(sc->nr));
5521 nr_reclaimed = sc->nr_reclaimed;
5522 nr_scanned = sc->nr_scanned;
5524 prepare_scan_count(pgdat, sc);
5526 shrink_node_memcgs(pgdat, sc);
5528 if (reclaim_state) {
5529 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5530 reclaim_state->reclaimed_slab = 0;
5533 /* Record the subtree's reclaim efficiency */
5534 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
5535 sc->nr_scanned - nr_scanned,
5536 sc->nr_reclaimed - nr_reclaimed);
5538 if (sc->nr_reclaimed - nr_reclaimed)
5541 if (current_is_kswapd()) {
5543 * If reclaim is isolating dirty pages under writeback,
5544 * it implies that the long-lived page allocation rate
5545 * is exceeding the page laundering rate. Either the
5546 * global limits are not being effective at throttling
5547 * processes due to the page distribution throughout
5548 * zones or there is heavy usage of a slow backing
5549 * device. The only option is to throttle from reclaim
5550 * context which is not ideal as there is no guarantee
5551 * the dirtying process is throttled in the same way
5552 * balance_dirty_pages() manages.
5554 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5555 * count the number of pages under pages flagged for
5556 * immediate reclaim and stall if any are encountered
5557 * in the nr_immediate check below.
5559 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5560 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
5562 /* Allow kswapd to start writing pages during reclaim.*/
5563 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5564 set_bit(PGDAT_DIRTY, &pgdat->flags);
5567 * If kswapd scans pages marked marked for immediate
5568 * reclaim and under writeback (nr_immediate), it
5569 * implies that pages are cycling through the LRU
5570 * faster than they are written so also forcibly stall.
5572 if (sc->nr.immediate)
5573 congestion_wait(BLK_RW_ASYNC, HZ/10);
5577 * Tag a node/memcg as congested if all the dirty pages
5578 * scanned were backed by a congested BDI and
5579 * wait_iff_congested will stall.
5581 * Legacy memcg will stall in page writeback so avoid forcibly
5582 * stalling in wait_iff_congested().
5584 if ((current_is_kswapd() ||
5585 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
5586 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
5587 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
5590 * Stall direct reclaim for IO completions if underlying BDIs
5591 * and node is congested. Allow kswapd to continue until it
5592 * starts encountering unqueued dirty pages or cycling through
5593 * the LRU too quickly.
5595 if (!current_is_kswapd() && current_may_throttle() &&
5596 !sc->hibernation_mode &&
5597 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
5598 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5600 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5605 * Kswapd gives up on balancing particular nodes after too
5606 * many failures to reclaim anything from them and goes to
5607 * sleep. On reclaim progress, reset the failure counter. A
5608 * successful direct reclaim run will revive a dormant kswapd.
5611 pgdat->kswapd_failures = 0;
5617 * Returns true if compaction should go ahead for a costly-order request, or
5618 * the allocation would already succeed without compaction. Return false if we
5619 * should reclaim first.
5621 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
5623 unsigned long watermark;
5624 enum compact_result suitable;
5626 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5627 if (suitable == COMPACT_SUCCESS)
5628 /* Allocation should succeed already. Don't reclaim. */
5630 if (suitable == COMPACT_SKIPPED)
5631 /* Compaction cannot yet proceed. Do reclaim. */
5635 * Compaction is already possible, but it takes time to run and there
5636 * are potentially other callers using the pages just freed. So proceed
5637 * with reclaim to make a buffer of free pages available to give
5638 * compaction a reasonable chance of completing and allocating the page.
5639 * Note that we won't actually reclaim the whole buffer in one attempt
5640 * as the target watermark in should_continue_reclaim() is lower. But if
5641 * we are already above the high+gap watermark, don't reclaim at all.
5643 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5645 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
5649 * This is the direct reclaim path, for page-allocating processes. We only
5650 * try to reclaim pages from zones which will satisfy the caller's allocation
5653 * If a zone is deemed to be full of pinned pages then just give it a light
5654 * scan then give up on it.
5656 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
5660 unsigned long nr_soft_reclaimed;
5661 unsigned long nr_soft_scanned;
5663 pg_data_t *last_pgdat = NULL;
5666 * If the number of buffer_heads in the machine exceeds the maximum
5667 * allowed level, force direct reclaim to scan the highmem zone as
5668 * highmem pages could be pinning lowmem pages storing buffer_heads
5670 orig_mask = sc->gfp_mask;
5671 if (buffer_heads_over_limit) {
5672 sc->gfp_mask |= __GFP_HIGHMEM;
5673 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
5676 for_each_zone_zonelist_nodemask(zone, z, zonelist,
5677 sc->reclaim_idx, sc->nodemask) {
5679 * Take care memory controller reclaiming has small influence
5682 if (!cgroup_reclaim(sc)) {
5683 if (!cpuset_zone_allowed(zone,
5684 GFP_KERNEL | __GFP_HARDWALL))
5688 * If we already have plenty of memory free for
5689 * compaction in this zone, don't free any more.
5690 * Even though compaction is invoked for any
5691 * non-zero order, only frequent costly order
5692 * reclamation is disruptive enough to become a
5693 * noticeable problem, like transparent huge
5696 if (IS_ENABLED(CONFIG_COMPACTION) &&
5697 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
5698 compaction_ready(zone, sc)) {
5699 sc->compaction_ready = true;
5704 * Shrink each node in the zonelist once. If the
5705 * zonelist is ordered by zone (not the default) then a
5706 * node may be shrunk multiple times but in that case
5707 * the user prefers lower zones being preserved.
5709 if (zone->zone_pgdat == last_pgdat)
5713 * This steals pages from memory cgroups over softlimit
5714 * and returns the number of reclaimed pages and
5715 * scanned pages. This works for global memory pressure
5716 * and balancing, not for a memcg's limit.
5718 nr_soft_scanned = 0;
5719 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
5720 sc->order, sc->gfp_mask,
5722 sc->nr_reclaimed += nr_soft_reclaimed;
5723 sc->nr_scanned += nr_soft_scanned;
5724 /* need some check for avoid more shrink_zone() */
5727 /* See comment about same check for global reclaim above */
5728 if (zone->zone_pgdat == last_pgdat)
5730 last_pgdat = zone->zone_pgdat;
5731 shrink_node(zone->zone_pgdat, sc);
5735 * Restore to original mask to avoid the impact on the caller if we
5736 * promoted it to __GFP_HIGHMEM.
5738 sc->gfp_mask = orig_mask;
5741 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
5743 struct lruvec *target_lruvec;
5744 unsigned long refaults;
5746 if (lru_gen_enabled())
5749 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
5750 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE);
5751 target_lruvec->refaults = refaults;
5755 * This is the main entry point to direct page reclaim.
5757 * If a full scan of the inactive list fails to free enough memory then we
5758 * are "out of memory" and something needs to be killed.
5760 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5761 * high - the zone may be full of dirty or under-writeback pages, which this
5762 * caller can't do much about. We kick the writeback threads and take explicit
5763 * naps in the hope that some of these pages can be written. But if the
5764 * allocating task holds filesystem locks which prevent writeout this might not
5765 * work, and the allocation attempt will fail.
5767 * returns: 0, if no pages reclaimed
5768 * else, the number of pages reclaimed
5770 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
5771 struct scan_control *sc)
5773 int initial_priority = sc->priority;
5774 pg_data_t *last_pgdat;
5778 delayacct_freepages_start();
5780 if (!cgroup_reclaim(sc))
5781 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
5784 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5787 shrink_zones(zonelist, sc);
5789 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
5792 if (sc->compaction_ready)
5796 * If we're getting trouble reclaiming, start doing
5797 * writepage even in laptop mode.
5799 if (sc->priority < DEF_PRIORITY - 2)
5800 sc->may_writepage = 1;
5801 } while (--sc->priority >= 0);
5804 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5806 if (zone->zone_pgdat == last_pgdat)
5808 last_pgdat = zone->zone_pgdat;
5810 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
5812 if (cgroup_reclaim(sc)) {
5813 struct lruvec *lruvec;
5815 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5817 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5821 delayacct_freepages_end();
5823 if (sc->nr_reclaimed)
5824 return sc->nr_reclaimed;
5826 /* Aborted reclaim to try compaction? don't OOM, then */
5827 if (sc->compaction_ready)
5831 * We make inactive:active ratio decisions based on the node's
5832 * composition of memory, but a restrictive reclaim_idx or a
5833 * memory.low cgroup setting can exempt large amounts of
5834 * memory from reclaim. Neither of which are very common, so
5835 * instead of doing costly eligibility calculations of the
5836 * entire cgroup subtree up front, we assume the estimates are
5837 * good, and retry with forcible deactivation if that fails.
5839 if (sc->skipped_deactivate) {
5840 sc->priority = initial_priority;
5841 sc->force_deactivate = 1;
5842 sc->skipped_deactivate = 0;
5846 /* Untapped cgroup reserves? Don't OOM, retry. */
5847 if (sc->memcg_low_skipped) {
5848 sc->priority = initial_priority;
5849 sc->force_deactivate = 0;
5850 sc->skipped_deactivate = 0;
5851 sc->memcg_low_reclaim = 1;
5852 sc->memcg_low_skipped = 0;
5859 static bool allow_direct_reclaim(pg_data_t *pgdat)
5862 unsigned long pfmemalloc_reserve = 0;
5863 unsigned long free_pages = 0;
5867 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5870 for (i = 0; i <= ZONE_NORMAL; i++) {
5871 zone = &pgdat->node_zones[i];
5872 if (!managed_zone(zone))
5875 if (!zone_reclaimable_pages(zone))
5878 pfmemalloc_reserve += min_wmark_pages(zone);
5879 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5882 /* If there are no reserves (unexpected config) then do not throttle */
5883 if (!pfmemalloc_reserve)
5886 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5888 /* kswapd must be awake if processes are being throttled */
5889 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
5890 pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
5891 (enum zone_type)ZONE_NORMAL);
5892 wake_up_interruptible(&pgdat->kswapd_wait);
5899 * Throttle direct reclaimers if backing storage is backed by the network
5900 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5901 * depleted. kswapd will continue to make progress and wake the processes
5902 * when the low watermark is reached.
5904 * Returns true if a fatal signal was delivered during throttling. If this
5905 * happens, the page allocator should not consider triggering the OOM killer.
5907 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
5908 nodemask_t *nodemask)
5912 pg_data_t *pgdat = NULL;
5915 * Kernel threads should not be throttled as they may be indirectly
5916 * responsible for cleaning pages necessary for reclaim to make forward
5917 * progress. kjournald for example may enter direct reclaim while
5918 * committing a transaction where throttling it could forcing other
5919 * processes to block on log_wait_commit().
5921 if (current->flags & PF_KTHREAD)
5925 * If a fatal signal is pending, this process should not throttle.
5926 * It should return quickly so it can exit and free its memory
5928 if (fatal_signal_pending(current))
5932 * Check if the pfmemalloc reserves are ok by finding the first node
5933 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5934 * GFP_KERNEL will be required for allocating network buffers when
5935 * swapping over the network so ZONE_HIGHMEM is unusable.
5937 * Throttling is based on the first usable node and throttled processes
5938 * wait on a queue until kswapd makes progress and wakes them. There
5939 * is an affinity then between processes waking up and where reclaim
5940 * progress has been made assuming the process wakes on the same node.
5941 * More importantly, processes running on remote nodes will not compete
5942 * for remote pfmemalloc reserves and processes on different nodes
5943 * should make reasonable progress.
5945 for_each_zone_zonelist_nodemask(zone, z, zonelist,
5946 gfp_zone(gfp_mask), nodemask) {
5947 if (zone_idx(zone) > ZONE_NORMAL)
5950 /* Throttle based on the first usable node */
5951 pgdat = zone->zone_pgdat;
5952 if (allow_direct_reclaim(pgdat))
5957 /* If no zone was usable by the allocation flags then do not throttle */
5961 /* Account for the throttling */
5962 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5965 * If the caller cannot enter the filesystem, it's possible that it
5966 * is due to the caller holding an FS lock or performing a journal
5967 * transaction in the case of a filesystem like ext[3|4]. In this case,
5968 * it is not safe to block on pfmemalloc_wait as kswapd could be
5969 * blocked waiting on the same lock. Instead, throttle for up to a
5970 * second before continuing.
5972 if (!(gfp_mask & __GFP_FS)) {
5973 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
5974 allow_direct_reclaim(pgdat), HZ);
5979 /* Throttle until kswapd wakes the process */
5980 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5981 allow_direct_reclaim(pgdat));
5984 if (fatal_signal_pending(current))
5991 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
5992 gfp_t gfp_mask, nodemask_t *nodemask)
5994 unsigned long nr_reclaimed;
5995 struct scan_control sc = {
5996 .nr_to_reclaim = SWAP_CLUSTER_MAX,
5997 .gfp_mask = current_gfp_context(gfp_mask),
5998 .reclaim_idx = gfp_zone(gfp_mask),
6000 .nodemask = nodemask,
6001 .priority = DEF_PRIORITY,
6002 .may_writepage = !laptop_mode,
6008 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6009 * Confirm they are large enough for max values.
6011 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6012 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6013 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6016 * Do not enter reclaim if fatal signal was delivered while throttled.
6017 * 1 is returned so that the page allocator does not OOM kill at this
6020 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6023 set_task_reclaim_state(current, &sc.reclaim_state);
6024 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6026 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6028 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6029 set_task_reclaim_state(current, NULL);
6031 return nr_reclaimed;
6036 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6037 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6038 gfp_t gfp_mask, bool noswap,
6040 unsigned long *nr_scanned)
6042 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6043 struct scan_control sc = {
6044 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6045 .target_mem_cgroup = memcg,
6046 .may_writepage = !laptop_mode,
6048 .reclaim_idx = MAX_NR_ZONES - 1,
6049 .may_swap = !noswap,
6052 WARN_ON_ONCE(!current->reclaim_state);
6054 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6055 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6057 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6061 * NOTE: Although we can get the priority field, using it
6062 * here is not a good idea, since it limits the pages we can scan.
6063 * if we don't reclaim here, the shrink_node from balance_pgdat
6064 * will pick up pages from other mem cgroup's as well. We hack
6065 * the priority and make it zero.
6067 shrink_lruvec(lruvec, &sc);
6069 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6071 *nr_scanned = sc.nr_scanned;
6073 return sc.nr_reclaimed;
6076 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6077 unsigned long nr_pages,
6081 struct zonelist *zonelist;
6082 unsigned long nr_reclaimed;
6083 unsigned long pflags;
6085 unsigned int noreclaim_flag;
6086 struct scan_control sc = {
6087 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6088 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6089 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6090 .reclaim_idx = MAX_NR_ZONES - 1,
6091 .target_mem_cgroup = memcg,
6092 .priority = DEF_PRIORITY,
6093 .may_writepage = !laptop_mode,
6095 .may_swap = may_swap,
6098 set_task_reclaim_state(current, &sc.reclaim_state);
6100 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
6101 * take care of from where we get pages. So the node where we start the
6102 * scan does not need to be the current node.
6104 nid = mem_cgroup_select_victim_node(memcg);
6106 zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
6108 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6110 psi_memstall_enter(&pflags);
6111 noreclaim_flag = memalloc_noreclaim_save();
6113 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6115 memalloc_noreclaim_restore(noreclaim_flag);
6116 psi_memstall_leave(&pflags);
6118 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6119 set_task_reclaim_state(current, NULL);
6121 return nr_reclaimed;
6125 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6127 struct mem_cgroup *memcg;
6128 struct lruvec *lruvec;
6130 if (lru_gen_enabled()) {
6131 lru_gen_age_node(pgdat, sc);
6136 if (!total_swap_pages)
6139 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6140 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6143 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6145 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6146 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6147 sc, LRU_ACTIVE_ANON);
6148 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6152 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
6158 * Check for watermark boosts top-down as the higher zones
6159 * are more likely to be boosted. Both watermarks and boosts
6160 * should not be checked at the time time as reclaim would
6161 * start prematurely when there is no boosting and a lower
6164 for (i = classzone_idx; i >= 0; i--) {
6165 zone = pgdat->node_zones + i;
6166 if (!managed_zone(zone))
6169 if (zone->watermark_boost)
6177 * Returns true if there is an eligible zone balanced for the request order
6180 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
6183 unsigned long mark = -1;
6187 * Check watermarks bottom-up as lower zones are more likely to
6190 for (i = 0; i <= classzone_idx; i++) {
6191 zone = pgdat->node_zones + i;
6193 if (!managed_zone(zone))
6196 mark = high_wmark_pages(zone);
6197 if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
6202 * If a node has no populated zone within classzone_idx, it does not
6203 * need balancing by definition. This can happen if a zone-restricted
6204 * allocation tries to wake a remote kswapd.
6212 /* Clear pgdat state for congested, dirty or under writeback. */
6213 static void clear_pgdat_congested(pg_data_t *pgdat)
6215 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6217 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6218 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6219 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6223 * Prepare kswapd for sleeping. This verifies that there are no processes
6224 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6226 * Returns true if kswapd is ready to sleep
6228 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
6231 * The throttled processes are normally woken up in balance_pgdat() as
6232 * soon as allow_direct_reclaim() is true. But there is a potential
6233 * race between when kswapd checks the watermarks and a process gets
6234 * throttled. There is also a potential race if processes get
6235 * throttled, kswapd wakes, a large process exits thereby balancing the
6236 * zones, which causes kswapd to exit balance_pgdat() before reaching
6237 * the wake up checks. If kswapd is going to sleep, no process should
6238 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6239 * the wake up is premature, processes will wake kswapd and get
6240 * throttled again. The difference from wake ups in balance_pgdat() is
6241 * that here we are under prepare_to_wait().
6243 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6244 wake_up_all(&pgdat->pfmemalloc_wait);
6246 /* Hopeless node, leave it to direct reclaim */
6247 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6250 if (pgdat_balanced(pgdat, order, classzone_idx)) {
6251 clear_pgdat_congested(pgdat);
6259 * kswapd shrinks a node of pages that are at or below the highest usable
6260 * zone that is currently unbalanced.
6262 * Returns true if kswapd scanned at least the requested number of pages to
6263 * reclaim or if the lack of progress was due to pages under writeback.
6264 * This is used to determine if the scanning priority needs to be raised.
6266 static bool kswapd_shrink_node(pg_data_t *pgdat,
6267 struct scan_control *sc)
6272 /* Reclaim a number of pages proportional to the number of zones */
6273 sc->nr_to_reclaim = 0;
6274 for (z = 0; z <= sc->reclaim_idx; z++) {
6275 zone = pgdat->node_zones + z;
6276 if (!managed_zone(zone))
6279 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6283 * Historically care was taken to put equal pressure on all zones but
6284 * now pressure is applied based on node LRU order.
6286 shrink_node(pgdat, sc);
6289 * Fragmentation may mean that the system cannot be rebalanced for
6290 * high-order allocations. If twice the allocation size has been
6291 * reclaimed then recheck watermarks only at order-0 to prevent
6292 * excessive reclaim. Assume that a process requested a high-order
6293 * can direct reclaim/compact.
6295 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6298 return sc->nr_scanned >= sc->nr_to_reclaim;
6302 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6303 * that are eligible for use by the caller until at least one zone is
6306 * Returns the order kswapd finished reclaiming at.
6308 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6309 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6310 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6311 * or lower is eligible for reclaim until at least one usable zone is
6314 static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
6317 unsigned long nr_soft_reclaimed;
6318 unsigned long nr_soft_scanned;
6319 unsigned long pflags;
6320 unsigned long nr_boost_reclaim;
6321 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6324 struct scan_control sc = {
6325 .gfp_mask = GFP_KERNEL,
6330 set_task_reclaim_state(current, &sc.reclaim_state);
6331 psi_memstall_enter(&pflags);
6332 __fs_reclaim_acquire();
6334 count_vm_event(PAGEOUTRUN);
6337 * Account for the reclaim boost. Note that the zone boost is left in
6338 * place so that parallel allocations that are near the watermark will
6339 * stall or direct reclaim until kswapd is finished.
6341 nr_boost_reclaim = 0;
6342 for (i = 0; i <= classzone_idx; i++) {
6343 zone = pgdat->node_zones + i;
6344 if (!managed_zone(zone))
6347 nr_boost_reclaim += zone->watermark_boost;
6348 zone_boosts[i] = zone->watermark_boost;
6350 boosted = nr_boost_reclaim;
6353 sc.priority = DEF_PRIORITY;
6355 unsigned long nr_reclaimed = sc.nr_reclaimed;
6356 bool raise_priority = true;
6360 sc.reclaim_idx = classzone_idx;
6363 * If the number of buffer_heads exceeds the maximum allowed
6364 * then consider reclaiming from all zones. This has a dual
6365 * purpose -- on 64-bit systems it is expected that
6366 * buffer_heads are stripped during active rotation. On 32-bit
6367 * systems, highmem pages can pin lowmem memory and shrinking
6368 * buffers can relieve lowmem pressure. Reclaim may still not
6369 * go ahead if all eligible zones for the original allocation
6370 * request are balanced to avoid excessive reclaim from kswapd.
6372 if (buffer_heads_over_limit) {
6373 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6374 zone = pgdat->node_zones + i;
6375 if (!managed_zone(zone))
6384 * If the pgdat is imbalanced then ignore boosting and preserve
6385 * the watermarks for a later time and restart. Note that the
6386 * zone watermarks will be still reset at the end of balancing
6387 * on the grounds that the normal reclaim should be enough to
6388 * re-evaluate if boosting is required when kswapd next wakes.
6390 balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
6391 if (!balanced && nr_boost_reclaim) {
6392 nr_boost_reclaim = 0;
6397 * If boosting is not active then only reclaim if there are no
6398 * eligible zones. Note that sc.reclaim_idx is not used as
6399 * buffer_heads_over_limit may have adjusted it.
6401 if (!nr_boost_reclaim && balanced)
6404 /* Limit the priority of boosting to avoid reclaim writeback */
6405 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6406 raise_priority = false;
6409 * Do not writeback or swap pages for boosted reclaim. The
6410 * intent is to relieve pressure not issue sub-optimal IO
6411 * from reclaim context. If no pages are reclaimed, the
6412 * reclaim will be aborted.
6414 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6415 sc.may_swap = !nr_boost_reclaim;
6418 * Do some background aging, to give pages a chance to be
6419 * referenced before reclaiming. All pages are rotated
6420 * regardless of classzone as this is about consistent aging.
6422 kswapd_age_node(pgdat, &sc);
6425 * If we're getting trouble reclaiming, start doing writepage
6426 * even in laptop mode.
6428 if (sc.priority < DEF_PRIORITY - 2)
6429 sc.may_writepage = 1;
6431 /* Call soft limit reclaim before calling shrink_node. */
6433 nr_soft_scanned = 0;
6434 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
6435 sc.gfp_mask, &nr_soft_scanned);
6436 sc.nr_reclaimed += nr_soft_reclaimed;
6439 * There should be no need to raise the scanning priority if
6440 * enough pages are already being scanned that that high
6441 * watermark would be met at 100% efficiency.
6443 if (kswapd_shrink_node(pgdat, &sc))
6444 raise_priority = false;
6447 * If the low watermark is met there is no need for processes
6448 * to be throttled on pfmemalloc_wait as they should not be
6449 * able to safely make forward progress. Wake them
6451 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
6452 allow_direct_reclaim(pgdat))
6453 wake_up_all(&pgdat->pfmemalloc_wait);
6455 /* Check if kswapd should be suspending */
6456 __fs_reclaim_release();
6457 ret = try_to_freeze();
6458 __fs_reclaim_acquire();
6459 if (ret || kthread_should_stop())
6463 * Raise priority if scanning rate is too low or there was no
6464 * progress in reclaiming pages
6466 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
6467 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6470 * If reclaim made no progress for a boost, stop reclaim as
6471 * IO cannot be queued and it could be an infinite loop in
6472 * extreme circumstances.
6474 if (nr_boost_reclaim && !nr_reclaimed)
6477 if (raise_priority || !nr_reclaimed)
6479 } while (sc.priority >= 1);
6481 if (!sc.nr_reclaimed)
6482 pgdat->kswapd_failures++;
6485 /* If reclaim was boosted, account for the reclaim done in this pass */
6487 unsigned long flags;
6489 for (i = 0; i <= classzone_idx; i++) {
6490 if (!zone_boosts[i])
6493 /* Increments are under the zone lock */
6494 zone = pgdat->node_zones + i;
6495 spin_lock_irqsave(&zone->lock, flags);
6496 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6497 spin_unlock_irqrestore(&zone->lock, flags);
6501 * As there is now likely space, wakeup kcompact to defragment
6504 wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
6507 snapshot_refaults(NULL, pgdat);
6508 __fs_reclaim_release();
6509 psi_memstall_leave(&pflags);
6510 set_task_reclaim_state(current, NULL);
6513 * Return the order kswapd stopped reclaiming at as
6514 * prepare_kswapd_sleep() takes it into account. If another caller
6515 * entered the allocator slow path while kswapd was awake, order will
6516 * remain at the higher level.
6522 * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
6523 * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
6524 * a valid index then either kswapd runs for first time or kswapd couldn't sleep
6525 * after previous reclaim attempt (node is still unbalanced). In that case
6526 * return the zone index of the previous kswapd reclaim cycle.
6528 static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
6529 enum zone_type prev_classzone_idx)
6531 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
6532 return prev_classzone_idx;
6533 return pgdat->kswapd_classzone_idx;
6536 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
6537 unsigned int classzone_idx)
6542 if (freezing(current) || kthread_should_stop())
6545 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6548 * Try to sleep for a short interval. Note that kcompactd will only be
6549 * woken if it is possible to sleep for a short interval. This is
6550 * deliberate on the assumption that if reclaim cannot keep an
6551 * eligible zone balanced that it's also unlikely that compaction will
6554 if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
6556 * Compaction records what page blocks it recently failed to
6557 * isolate pages from and skips them in the future scanning.
6558 * When kswapd is going to sleep, it is reasonable to assume
6559 * that pages and compaction may succeed so reset the cache.
6561 reset_isolation_suitable(pgdat);
6564 * We have freed the memory, now we should compact it to make
6565 * allocation of the requested order possible.
6567 wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
6569 remaining = schedule_timeout(HZ/10);
6572 * If woken prematurely then reset kswapd_classzone_idx and
6573 * order. The values will either be from a wakeup request or
6574 * the previous request that slept prematurely.
6577 pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
6578 pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
6581 finish_wait(&pgdat->kswapd_wait, &wait);
6582 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6586 * After a short sleep, check if it was a premature sleep. If not, then
6587 * go fully to sleep until explicitly woken up.
6590 prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
6591 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6594 * vmstat counters are not perfectly accurate and the estimated
6595 * value for counters such as NR_FREE_PAGES can deviate from the
6596 * true value by nr_online_cpus * threshold. To avoid the zone
6597 * watermarks being breached while under pressure, we reduce the
6598 * per-cpu vmstat threshold while kswapd is awake and restore
6599 * them before going back to sleep.
6601 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
6603 if (!kthread_should_stop())
6606 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6609 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6611 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6613 finish_wait(&pgdat->kswapd_wait, &wait);
6617 * The background pageout daemon, started as a kernel thread
6618 * from the init process.
6620 * This basically trickles out pages so that we have _some_
6621 * free memory available even if there is no other activity
6622 * that frees anything up. This is needed for things like routing
6623 * etc, where we otherwise might have all activity going on in
6624 * asynchronous contexts that cannot page things out.
6626 * If there are applications that are active memory-allocators
6627 * (most normal use), this basically shouldn't matter.
6629 static int kswapd(void *p)
6631 unsigned int alloc_order, reclaim_order;
6632 unsigned int classzone_idx = MAX_NR_ZONES - 1;
6633 pg_data_t *pgdat = (pg_data_t*)p;
6634 struct task_struct *tsk = current;
6635 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
6637 if (!cpumask_empty(cpumask))
6638 set_cpus_allowed_ptr(tsk, cpumask);
6641 * Tell the memory management that we're a "memory allocator",
6642 * and that if we need more memory we should get access to it
6643 * regardless (see "__alloc_pages()"). "kswapd" should
6644 * never get caught in the normal page freeing logic.
6646 * (Kswapd normally doesn't need memory anyway, but sometimes
6647 * you need a small amount of memory in order to be able to
6648 * page out something else, and this flag essentially protects
6649 * us from recursively trying to free more memory as we're
6650 * trying to free the first piece of memory in the first place).
6652 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
6655 pgdat->kswapd_order = 0;
6656 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
6660 alloc_order = reclaim_order = pgdat->kswapd_order;
6661 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
6664 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
6667 /* Read the new order and classzone_idx */
6668 alloc_order = reclaim_order = pgdat->kswapd_order;
6669 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
6670 pgdat->kswapd_order = 0;
6671 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
6673 ret = try_to_freeze();
6674 if (kthread_should_stop())
6678 * We can speed up thawing tasks if we don't call balance_pgdat
6679 * after returning from the refrigerator
6685 * Reclaim begins at the requested order but if a high-order
6686 * reclaim fails then kswapd falls back to reclaiming for
6687 * order-0. If that happens, kswapd will consider sleeping
6688 * for the order it finished reclaiming at (reclaim_order)
6689 * but kcompactd is woken to compact for the original
6690 * request (alloc_order).
6692 trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
6694 reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
6695 if (reclaim_order < alloc_order)
6696 goto kswapd_try_sleep;
6699 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
6705 * A zone is low on free memory or too fragmented for high-order memory. If
6706 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6707 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6708 * has failed or is not needed, still wake up kcompactd if only compaction is
6711 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
6712 enum zone_type classzone_idx)
6716 if (!managed_zone(zone))
6719 if (!cpuset_zone_allowed(zone, gfp_flags))
6721 pgdat = zone->zone_pgdat;
6723 if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
6724 pgdat->kswapd_classzone_idx = classzone_idx;
6726 pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
6728 pgdat->kswapd_order = max(pgdat->kswapd_order, order);
6729 if (!waitqueue_active(&pgdat->kswapd_wait))
6732 /* Hopeless node, leave it to direct reclaim if possible */
6733 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
6734 (pgdat_balanced(pgdat, order, classzone_idx) &&
6735 !pgdat_watermark_boosted(pgdat, classzone_idx))) {
6737 * There may be plenty of free memory available, but it's too
6738 * fragmented for high-order allocations. Wake up kcompactd
6739 * and rely on compaction_suitable() to determine if it's
6740 * needed. If it fails, it will defer subsequent attempts to
6741 * ratelimit its work.
6743 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
6744 wakeup_kcompactd(pgdat, order, classzone_idx);
6748 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
6750 wake_up_interruptible(&pgdat->kswapd_wait);
6753 #ifdef CONFIG_HIBERNATION
6755 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
6758 * Rather than trying to age LRUs the aim is to preserve the overall
6759 * LRU order by reclaiming preferentially
6760 * inactive > active > active referenced > active mapped
6762 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
6764 struct scan_control sc = {
6765 .nr_to_reclaim = nr_to_reclaim,
6766 .gfp_mask = GFP_HIGHUSER_MOVABLE,
6767 .reclaim_idx = MAX_NR_ZONES - 1,
6768 .priority = DEF_PRIORITY,
6772 .hibernation_mode = 1,
6774 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6775 unsigned long nr_reclaimed;
6776 unsigned int noreclaim_flag;
6778 fs_reclaim_acquire(sc.gfp_mask);
6779 noreclaim_flag = memalloc_noreclaim_save();
6780 set_task_reclaim_state(current, &sc.reclaim_state);
6782 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6784 set_task_reclaim_state(current, NULL);
6785 memalloc_noreclaim_restore(noreclaim_flag);
6786 fs_reclaim_release(sc.gfp_mask);
6788 return nr_reclaimed;
6790 #endif /* CONFIG_HIBERNATION */
6792 /* It's optimal to keep kswapds on the same CPUs as their memory, but
6793 not required for correctness. So if the last cpu in a node goes
6794 away, we get changed to run anywhere: as the first one comes back,
6795 restore their cpu bindings. */
6796 static int kswapd_cpu_online(unsigned int cpu)
6800 for_each_node_state(nid, N_MEMORY) {
6801 pg_data_t *pgdat = NODE_DATA(nid);
6802 const struct cpumask *mask;
6804 mask = cpumask_of_node(pgdat->node_id);
6806 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
6807 /* One of our CPUs online: restore mask */
6808 set_cpus_allowed_ptr(pgdat->kswapd, mask);
6814 * This kswapd start function will be called by init and node-hot-add.
6815 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6817 int kswapd_run(int nid)
6819 pg_data_t *pgdat = NODE_DATA(nid);
6825 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6826 if (IS_ERR(pgdat->kswapd)) {
6827 /* failure at boot is fatal */
6828 BUG_ON(system_state < SYSTEM_RUNNING);
6829 pr_err("Failed to start kswapd on node %d\n", nid);
6830 ret = PTR_ERR(pgdat->kswapd);
6831 pgdat->kswapd = NULL;
6837 * Called by memory hotplug when all memory in a node is offlined. Caller must
6838 * hold mem_hotplug_begin/end().
6840 void kswapd_stop(int nid)
6842 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
6845 kthread_stop(kswapd);
6846 NODE_DATA(nid)->kswapd = NULL;
6850 static int __init kswapd_init(void)
6855 for_each_node_state(nid, N_MEMORY)
6857 ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
6858 "mm/vmscan:online", kswapd_cpu_online,
6864 module_init(kswapd_init)
6870 * If non-zero call node_reclaim when the number of free pages falls below
6873 int node_reclaim_mode __read_mostly;
6875 #define RECLAIM_OFF 0
6876 #define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
6877 #define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
6878 #define RECLAIM_UNMAP (1<<2) /* Unmap pages during reclaim */
6881 * Priority for NODE_RECLAIM. This determines the fraction of pages
6882 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6885 #define NODE_RECLAIM_PRIORITY 4
6888 * Percentage of pages in a zone that must be unmapped for node_reclaim to
6891 int sysctl_min_unmapped_ratio = 1;
6894 * If the number of slab pages in a zone grows beyond this percentage then
6895 * slab reclaim needs to occur.
6897 int sysctl_min_slab_ratio = 5;
6899 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
6901 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6902 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6903 node_page_state(pgdat, NR_ACTIVE_FILE);
6906 * It's possible for there to be more file mapped pages than
6907 * accounted for by the pages on the file LRU lists because
6908 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6910 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6913 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
6914 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
6916 unsigned long nr_pagecache_reclaimable;
6917 unsigned long delta = 0;
6920 * If RECLAIM_UNMAP is set, then all file pages are considered
6921 * potentially reclaimable. Otherwise, we have to worry about
6922 * pages like swapcache and node_unmapped_file_pages() provides
6925 if (node_reclaim_mode & RECLAIM_UNMAP)
6926 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
6928 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
6930 /* If we can't clean pages, remove dirty pages from consideration */
6931 if (!(node_reclaim_mode & RECLAIM_WRITE))
6932 delta += node_page_state(pgdat, NR_FILE_DIRTY);
6934 /* Watch for any possible underflows due to delta */
6935 if (unlikely(delta > nr_pagecache_reclaimable))
6936 delta = nr_pagecache_reclaimable;
6938 return nr_pagecache_reclaimable - delta;
6942 * Try to free up some pages from this node through reclaim.
6944 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
6946 /* Minimum pages needed in order to stay on node */
6947 const unsigned long nr_pages = 1 << order;
6948 struct task_struct *p = current;
6949 unsigned int noreclaim_flag;
6950 struct scan_control sc = {
6951 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6952 .gfp_mask = current_gfp_context(gfp_mask),
6954 .priority = NODE_RECLAIM_PRIORITY,
6955 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6956 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
6958 .reclaim_idx = gfp_zone(gfp_mask),
6961 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6965 fs_reclaim_acquire(sc.gfp_mask);
6967 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
6968 * and we also need to be able to write out pages for RECLAIM_WRITE
6969 * and RECLAIM_UNMAP.
6971 noreclaim_flag = memalloc_noreclaim_save();
6972 p->flags |= PF_SWAPWRITE;
6973 set_task_reclaim_state(p, &sc.reclaim_state);
6975 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
6977 * Free memory by calling shrink node with increasing
6978 * priorities until we have enough memory freed.
6981 shrink_node(pgdat, &sc);
6982 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
6985 set_task_reclaim_state(p, NULL);
6986 current->flags &= ~PF_SWAPWRITE;
6987 memalloc_noreclaim_restore(noreclaim_flag);
6988 fs_reclaim_release(sc.gfp_mask);
6990 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6992 return sc.nr_reclaimed >= nr_pages;
6995 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7000 * Node reclaim reclaims unmapped file backed pages and
7001 * slab pages if we are over the defined limits.
7003 * A small portion of unmapped file backed pages is needed for
7004 * file I/O otherwise pages read by file I/O will be immediately
7005 * thrown out if the node is overallocated. So we do not reclaim
7006 * if less than a specified percentage of the node is used by
7007 * unmapped file backed pages.
7009 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7010 node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
7011 return NODE_RECLAIM_FULL;
7014 * Do not scan if the allocation should not be delayed.
7016 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7017 return NODE_RECLAIM_NOSCAN;
7020 * Only run node reclaim on the local node or on nodes that do not
7021 * have associated processors. This will favor the local processor
7022 * over remote processors and spread off node memory allocations
7023 * as wide as possible.
7025 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7026 return NODE_RECLAIM_NOSCAN;
7028 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7029 return NODE_RECLAIM_NOSCAN;
7031 ret = __node_reclaim(pgdat, gfp_mask, order);
7032 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7035 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7042 * page_evictable - test whether a page is evictable
7043 * @page: the page to test
7045 * Test whether page is evictable--i.e., should be placed on active/inactive
7046 * lists vs unevictable list.
7048 * Reasons page might not be evictable:
7049 * (1) page's mapping marked unevictable
7050 * (2) page is part of an mlocked VMA
7053 int page_evictable(struct page *page)
7057 /* Prevent address_space of inode and swap cache from being freed */
7059 ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
7065 * check_move_unevictable_pages - check pages for evictability and move to
7066 * appropriate zone lru list
7067 * @pvec: pagevec with lru pages to check
7069 * Checks pages for evictability, if an evictable page is in the unevictable
7070 * lru list, moves it to the appropriate evictable lru list. This function
7071 * should be only used for lru pages.
7073 void check_move_unevictable_pages(struct pagevec *pvec)
7075 struct lruvec *lruvec;
7076 struct pglist_data *pgdat = NULL;
7081 for (i = 0; i < pvec->nr; i++) {
7082 struct page *page = pvec->pages[i];
7083 struct pglist_data *pagepgdat = page_pgdat(page);
7087 if (!TestClearPageLRU(page))
7090 if (pagepgdat != pgdat) {
7092 spin_unlock_irq(&pgdat->lru_lock);
7094 spin_lock_irq(&pgdat->lru_lock);
7096 lruvec = mem_cgroup_page_lruvec(page, pgdat);
7098 if (page_evictable(page) && PageUnevictable(page)) {
7099 enum lru_list lru = page_lru_base_type(page);
7101 VM_BUG_ON_PAGE(PageActive(page), page);
7102 ClearPageUnevictable(page);
7103 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
7104 add_page_to_lru_list(page, lruvec, lru);
7111 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7112 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7113 spin_unlock_irq(&pgdat->lru_lock);
7114 } else if (pgscanned) {
7115 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7118 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);