1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/sched/mm.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/highmem.h>
24 #include <linux/vmpressure.h>
25 #include <linux/vmstat.h>
26 #include <linux/file.h>
27 #include <linux/writeback.h>
28 #include <linux/blkdev.h>
29 #include <linux/buffer_head.h> /* for buffer_heads_over_limit */
30 #include <linux/mm_inline.h>
31 #include <linux/backing-dev.h>
32 #include <linux/rmap.h>
33 #include <linux/topology.h>
34 #include <linux/cpu.h>
35 #include <linux/cpuset.h>
36 #include <linux/compaction.h>
37 #include <linux/notifier.h>
38 #include <linux/rwsem.h>
39 #include <linux/delay.h>
40 #include <linux/kthread.h>
41 #include <linux/freezer.h>
42 #include <linux/memcontrol.h>
43 #include <linux/migrate.h>
44 #include <linux/delayacct.h>
45 #include <linux/sysctl.h>
46 #include <linux/memory-tiers.h>
47 #include <linux/oom.h>
48 #include <linux/pagevec.h>
49 #include <linux/prefetch.h>
50 #include <linux/printk.h>
51 #include <linux/dax.h>
52 #include <linux/psi.h>
53 #include <linux/pagewalk.h>
54 #include <linux/shmem_fs.h>
55 #include <linux/ctype.h>
56 #include <linux/debugfs.h>
57 #include <linux/khugepaged.h>
58 #include <linux/rculist_nulls.h>
59 #include <linux/random.h>
61 #include <asm/tlbflush.h>
62 #include <asm/div64.h>
64 #include <linux/swapops.h>
65 #include <linux/balloon_compaction.h>
66 #include <linux/sched/sysctl.h>
71 #define CREATE_TRACE_POINTS
72 #include <trace/events/vmscan.h>
75 /* How many pages shrink_list() should reclaim */
76 unsigned long nr_to_reclaim;
79 * Nodemask of nodes allowed by the caller. If NULL, all nodes
85 * The memory cgroup that hit its limit and as a result is the
86 * primary target of this reclaim invocation.
88 struct mem_cgroup *target_mem_cgroup;
91 * Scan pressure balancing between anon and file LRUs
93 unsigned long anon_cost;
94 unsigned long file_cost;
96 /* Can active folios be deactivated as part of reclaim? */
97 #define DEACTIVATE_ANON 1
98 #define DEACTIVATE_FILE 2
99 unsigned int may_deactivate:2;
100 unsigned int force_deactivate:1;
101 unsigned int skipped_deactivate:1;
103 /* Writepage batching in laptop mode; RECLAIM_WRITE */
104 unsigned int may_writepage:1;
106 /* Can mapped folios be reclaimed? */
107 unsigned int may_unmap:1;
109 /* Can folios be swapped as part of reclaim? */
110 unsigned int may_swap:1;
112 /* Proactive reclaim invoked by userspace through memory.reclaim */
113 unsigned int proactive:1;
116 * Cgroup memory below memory.low is protected as long as we
117 * don't threaten to OOM. If any cgroup is reclaimed at
118 * reduced force or passed over entirely due to its memory.low
119 * setting (memcg_low_skipped), and nothing is reclaimed as a
120 * result, then go back for one more cycle that reclaims the protected
121 * memory (memcg_low_reclaim) to avert OOM.
123 unsigned int memcg_low_reclaim:1;
124 unsigned int memcg_low_skipped:1;
126 unsigned int hibernation_mode:1;
128 /* One of the zones is ready for compaction */
129 unsigned int compaction_ready:1;
131 /* There is easily reclaimable cold cache in the current node */
132 unsigned int cache_trim_mode:1;
134 /* The file folios on the current node are dangerously low */
135 unsigned int file_is_tiny:1;
137 /* Always discard instead of demoting to lower tier memory */
138 unsigned int no_demotion:1;
140 /* Allocation order */
143 /* Scan (total_size >> priority) pages at once */
146 /* The highest zone to isolate folios for reclaim from */
149 /* This context's GFP mask */
152 /* Incremented by the number of inactive pages that were scanned */
153 unsigned long nr_scanned;
155 /* Number of pages freed so far during a call to shrink_zones() */
156 unsigned long nr_reclaimed;
160 unsigned int unqueued_dirty;
161 unsigned int congested;
162 unsigned int writeback;
163 unsigned int immediate;
164 unsigned int file_taken;
168 /* for recording the reclaimed slab by now */
169 struct reclaim_state reclaim_state;
172 #ifdef ARCH_HAS_PREFETCHW
173 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
175 if ((_folio)->lru.prev != _base) { \
176 struct folio *prev; \
178 prev = lru_to_folio(&(_folio->lru)); \
179 prefetchw(&prev->_field); \
183 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
187 * From 0 .. 200. Higher means more swappy.
189 int vm_swappiness = 60;
191 LIST_HEAD(shrinker_list);
192 DECLARE_RWSEM(shrinker_rwsem);
195 static int shrinker_nr_max;
197 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
198 static inline int shrinker_map_size(int nr_items)
200 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
203 static inline int shrinker_defer_size(int nr_items)
205 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
208 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
211 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
212 lockdep_is_held(&shrinker_rwsem));
215 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
216 int map_size, int defer_size,
217 int old_map_size, int old_defer_size,
220 struct shrinker_info *new, *old;
221 struct mem_cgroup_per_node *pn;
223 int size = map_size + defer_size;
226 pn = memcg->nodeinfo[nid];
227 old = shrinker_info_protected(memcg, nid);
228 /* Not yet online memcg */
232 /* Already expanded this shrinker_info */
233 if (new_nr_max <= old->map_nr_max)
236 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
240 new->nr_deferred = (atomic_long_t *)(new + 1);
241 new->map = (void *)new->nr_deferred + defer_size;
242 new->map_nr_max = new_nr_max;
244 /* map: set all old bits, clear all new bits */
245 memset(new->map, (int)0xff, old_map_size);
246 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
247 /* nr_deferred: copy old values, clear all new values */
248 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
249 memset((void *)new->nr_deferred + old_defer_size, 0,
250 defer_size - old_defer_size);
252 rcu_assign_pointer(pn->shrinker_info, new);
253 kvfree_rcu(old, rcu);
259 void free_shrinker_info(struct mem_cgroup *memcg)
261 struct mem_cgroup_per_node *pn;
262 struct shrinker_info *info;
266 pn = memcg->nodeinfo[nid];
267 info = rcu_dereference_protected(pn->shrinker_info, true);
269 rcu_assign_pointer(pn->shrinker_info, NULL);
273 int alloc_shrinker_info(struct mem_cgroup *memcg)
275 struct shrinker_info *info;
276 int nid, size, ret = 0;
277 int map_size, defer_size = 0;
279 down_write(&shrinker_rwsem);
280 map_size = shrinker_map_size(shrinker_nr_max);
281 defer_size = shrinker_defer_size(shrinker_nr_max);
282 size = map_size + defer_size;
284 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
286 free_shrinker_info(memcg);
290 info->nr_deferred = (atomic_long_t *)(info + 1);
291 info->map = (void *)info->nr_deferred + defer_size;
292 info->map_nr_max = shrinker_nr_max;
293 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
295 up_write(&shrinker_rwsem);
300 static int expand_shrinker_info(int new_id)
303 int new_nr_max = round_up(new_id + 1, BITS_PER_LONG);
304 int map_size, defer_size = 0;
305 int old_map_size, old_defer_size = 0;
306 struct mem_cgroup *memcg;
308 if (!root_mem_cgroup)
311 lockdep_assert_held(&shrinker_rwsem);
313 map_size = shrinker_map_size(new_nr_max);
314 defer_size = shrinker_defer_size(new_nr_max);
315 old_map_size = shrinker_map_size(shrinker_nr_max);
316 old_defer_size = shrinker_defer_size(shrinker_nr_max);
318 memcg = mem_cgroup_iter(NULL, NULL, NULL);
320 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
321 old_map_size, old_defer_size,
324 mem_cgroup_iter_break(NULL, memcg);
327 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
330 shrinker_nr_max = new_nr_max;
335 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
337 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
338 struct shrinker_info *info;
341 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
342 if (!WARN_ON_ONCE(shrinker_id >= info->map_nr_max)) {
343 /* Pairs with smp mb in shrink_slab() */
344 smp_mb__before_atomic();
345 set_bit(shrinker_id, info->map);
351 static DEFINE_IDR(shrinker_idr);
353 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
355 int id, ret = -ENOMEM;
357 if (mem_cgroup_disabled())
360 down_write(&shrinker_rwsem);
361 /* This may call shrinker, so it must use down_read_trylock() */
362 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
366 if (id >= shrinker_nr_max) {
367 if (expand_shrinker_info(id)) {
368 idr_remove(&shrinker_idr, id);
375 up_write(&shrinker_rwsem);
379 static void unregister_memcg_shrinker(struct shrinker *shrinker)
381 int id = shrinker->id;
385 lockdep_assert_held(&shrinker_rwsem);
387 idr_remove(&shrinker_idr, id);
390 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
391 struct mem_cgroup *memcg)
393 struct shrinker_info *info;
395 info = shrinker_info_protected(memcg, nid);
396 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
399 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
400 struct mem_cgroup *memcg)
402 struct shrinker_info *info;
404 info = shrinker_info_protected(memcg, nid);
405 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
408 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
412 struct mem_cgroup *parent;
413 struct shrinker_info *child_info, *parent_info;
415 parent = parent_mem_cgroup(memcg);
417 parent = root_mem_cgroup;
419 /* Prevent from concurrent shrinker_info expand */
420 down_read(&shrinker_rwsem);
422 child_info = shrinker_info_protected(memcg, nid);
423 parent_info = shrinker_info_protected(parent, nid);
424 for (i = 0; i < child_info->map_nr_max; i++) {
425 nr = atomic_long_read(&child_info->nr_deferred[i]);
426 atomic_long_add(nr, &parent_info->nr_deferred[i]);
429 up_read(&shrinker_rwsem);
432 static bool cgroup_reclaim(struct scan_control *sc)
434 return sc->target_mem_cgroup;
437 static bool global_reclaim(struct scan_control *sc)
439 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
443 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
444 * @sc: scan_control in question
446 * The normal page dirty throttling mechanism in balance_dirty_pages() is
447 * completely broken with the legacy memcg and direct stalling in
448 * shrink_folio_list() is used for throttling instead, which lacks all the
449 * niceties such as fairness, adaptive pausing, bandwidth proportional
450 * allocation and configurability.
452 * This function tests whether the vmscan currently in progress can assume
453 * that the normal dirty throttling mechanism is operational.
455 static bool writeback_throttling_sane(struct scan_control *sc)
457 if (!cgroup_reclaim(sc))
459 #ifdef CONFIG_CGROUP_WRITEBACK
460 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
466 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
471 static void unregister_memcg_shrinker(struct shrinker *shrinker)
475 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
476 struct mem_cgroup *memcg)
481 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
482 struct mem_cgroup *memcg)
487 static bool cgroup_reclaim(struct scan_control *sc)
492 static bool global_reclaim(struct scan_control *sc)
497 static bool writeback_throttling_sane(struct scan_control *sc)
503 static void set_task_reclaim_state(struct task_struct *task,
504 struct reclaim_state *rs)
506 /* Check for an overwrite */
507 WARN_ON_ONCE(rs && task->reclaim_state);
509 /* Check for the nulling of an already-nulled member */
510 WARN_ON_ONCE(!rs && !task->reclaim_state);
512 task->reclaim_state = rs;
516 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
517 * scan_control->nr_reclaimed.
519 static void flush_reclaim_state(struct scan_control *sc)
522 * Currently, reclaim_state->reclaimed includes three types of pages
523 * freed outside of vmscan:
525 * (2) Clean file pages from pruned inodes (on highmem systems).
526 * (3) XFS freed buffer pages.
528 * For all of these cases, we cannot universally link the pages to a
529 * single memcg. For example, a memcg-aware shrinker can free one object
530 * charged to the target memcg, causing an entire page to be freed.
531 * If we count the entire page as reclaimed from the memcg, we end up
532 * overestimating the reclaimed amount (potentially under-reclaiming).
534 * Only count such pages for global reclaim to prevent under-reclaiming
535 * from the target memcg; preventing unnecessary retries during memcg
536 * charging and false positives from proactive reclaim.
538 * For uncommon cases where the freed pages were actually mostly
539 * charged to the target memcg, we end up underestimating the reclaimed
540 * amount. This should be fine. The freed pages will be uncharged
541 * anyway, even if they are not counted here properly, and we will be
542 * able to make forward progress in charging (which is usually in a
545 * We can go one step further, and report the uncharged objcg pages in
546 * memcg reclaim, to make reporting more accurate and reduce
547 * underestimation, but it's probably not worth the complexity for now.
549 if (current->reclaim_state && global_reclaim(sc)) {
550 sc->nr_reclaimed += current->reclaim_state->reclaimed;
551 current->reclaim_state->reclaimed = 0;
555 static long xchg_nr_deferred(struct shrinker *shrinker,
556 struct shrink_control *sc)
560 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
564 (shrinker->flags & SHRINKER_MEMCG_AWARE))
565 return xchg_nr_deferred_memcg(nid, shrinker,
568 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
572 static long add_nr_deferred(long nr, struct shrinker *shrinker,
573 struct shrink_control *sc)
577 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
581 (shrinker->flags & SHRINKER_MEMCG_AWARE))
582 return add_nr_deferred_memcg(nr, nid, shrinker,
585 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
588 static bool can_demote(int nid, struct scan_control *sc)
590 if (!numa_demotion_enabled)
592 if (sc && sc->no_demotion)
594 if (next_demotion_node(nid) == NUMA_NO_NODE)
600 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
602 struct scan_control *sc)
606 * For non-memcg reclaim, is there
607 * space in any swap device?
609 if (get_nr_swap_pages() > 0)
612 /* Is the memcg below its swap limit? */
613 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
618 * The page can not be swapped.
620 * Can it be reclaimed from this node via demotion?
622 return can_demote(nid, sc);
626 * This misses isolated folios which are not accounted for to save counters.
627 * As the data only determines if reclaim or compaction continues, it is
628 * not expected that isolated folios will be a dominating factor.
630 unsigned long zone_reclaimable_pages(struct zone *zone)
634 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
635 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
636 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
637 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
638 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
644 * lruvec_lru_size - Returns the number of pages on the given LRU list.
645 * @lruvec: lru vector
647 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
649 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
652 unsigned long size = 0;
655 for (zid = 0; zid <= zone_idx; zid++) {
656 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
658 if (!managed_zone(zone))
661 if (!mem_cgroup_disabled())
662 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
664 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
670 * Add a shrinker callback to be called from the vm.
672 static int __prealloc_shrinker(struct shrinker *shrinker)
677 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
678 err = prealloc_memcg_shrinker(shrinker);
682 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
685 size = sizeof(*shrinker->nr_deferred);
686 if (shrinker->flags & SHRINKER_NUMA_AWARE)
689 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
690 if (!shrinker->nr_deferred)
696 #ifdef CONFIG_SHRINKER_DEBUG
697 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
703 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
708 err = __prealloc_shrinker(shrinker);
710 kfree_const(shrinker->name);
711 shrinker->name = NULL;
717 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
719 return __prealloc_shrinker(shrinker);
723 void free_prealloced_shrinker(struct shrinker *shrinker)
725 #ifdef CONFIG_SHRINKER_DEBUG
726 kfree_const(shrinker->name);
727 shrinker->name = NULL;
729 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
730 down_write(&shrinker_rwsem);
731 unregister_memcg_shrinker(shrinker);
732 up_write(&shrinker_rwsem);
736 kfree(shrinker->nr_deferred);
737 shrinker->nr_deferred = NULL;
740 void register_shrinker_prepared(struct shrinker *shrinker)
742 down_write(&shrinker_rwsem);
743 list_add_tail(&shrinker->list, &shrinker_list);
744 shrinker->flags |= SHRINKER_REGISTERED;
745 shrinker_debugfs_add(shrinker);
746 up_write(&shrinker_rwsem);
749 static int __register_shrinker(struct shrinker *shrinker)
751 int err = __prealloc_shrinker(shrinker);
755 register_shrinker_prepared(shrinker);
759 #ifdef CONFIG_SHRINKER_DEBUG
760 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
766 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
771 err = __register_shrinker(shrinker);
773 kfree_const(shrinker->name);
774 shrinker->name = NULL;
779 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
781 return __register_shrinker(shrinker);
784 EXPORT_SYMBOL(register_shrinker);
789 void unregister_shrinker(struct shrinker *shrinker)
791 struct dentry *debugfs_entry;
794 if (!(shrinker->flags & SHRINKER_REGISTERED))
797 down_write(&shrinker_rwsem);
798 list_del(&shrinker->list);
799 shrinker->flags &= ~SHRINKER_REGISTERED;
800 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
801 unregister_memcg_shrinker(shrinker);
802 debugfs_entry = shrinker_debugfs_detach(shrinker, &debugfs_id);
803 up_write(&shrinker_rwsem);
805 shrinker_debugfs_remove(debugfs_entry, debugfs_id);
807 kfree(shrinker->nr_deferred);
808 shrinker->nr_deferred = NULL;
810 EXPORT_SYMBOL(unregister_shrinker);
813 * synchronize_shrinkers - Wait for all running shrinkers to complete.
815 * This is equivalent to calling unregister_shrink() and register_shrinker(),
816 * but atomically and with less overhead. This is useful to guarantee that all
817 * shrinker invocations have seen an update, before freeing memory, similar to
820 void synchronize_shrinkers(void)
822 down_write(&shrinker_rwsem);
823 up_write(&shrinker_rwsem);
825 EXPORT_SYMBOL(synchronize_shrinkers);
827 #define SHRINK_BATCH 128
829 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
830 struct shrinker *shrinker, int priority)
832 unsigned long freed = 0;
833 unsigned long long delta;
838 long batch_size = shrinker->batch ? shrinker->batch
840 long scanned = 0, next_deferred;
842 freeable = shrinker->count_objects(shrinker, shrinkctl);
843 if (freeable == 0 || freeable == SHRINK_EMPTY)
847 * copy the current shrinker scan count into a local variable
848 * and zero it so that other concurrent shrinker invocations
849 * don't also do this scanning work.
851 nr = xchg_nr_deferred(shrinker, shrinkctl);
853 if (shrinker->seeks) {
854 delta = freeable >> priority;
856 do_div(delta, shrinker->seeks);
859 * These objects don't require any IO to create. Trim
860 * them aggressively under memory pressure to keep
861 * them from causing refetches in the IO caches.
863 delta = freeable / 2;
866 total_scan = nr >> priority;
868 total_scan = min(total_scan, (2 * freeable));
870 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
871 freeable, delta, total_scan, priority);
874 * Normally, we should not scan less than batch_size objects in one
875 * pass to avoid too frequent shrinker calls, but if the slab has less
876 * than batch_size objects in total and we are really tight on memory,
877 * we will try to reclaim all available objects, otherwise we can end
878 * up failing allocations although there are plenty of reclaimable
879 * objects spread over several slabs with usage less than the
882 * We detect the "tight on memory" situations by looking at the total
883 * number of objects we want to scan (total_scan). If it is greater
884 * than the total number of objects on slab (freeable), we must be
885 * scanning at high prio and therefore should try to reclaim as much as
888 while (total_scan >= batch_size ||
889 total_scan >= freeable) {
891 unsigned long nr_to_scan = min(batch_size, total_scan);
893 shrinkctl->nr_to_scan = nr_to_scan;
894 shrinkctl->nr_scanned = nr_to_scan;
895 ret = shrinker->scan_objects(shrinker, shrinkctl);
896 if (ret == SHRINK_STOP)
900 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
901 total_scan -= shrinkctl->nr_scanned;
902 scanned += shrinkctl->nr_scanned;
908 * The deferred work is increased by any new work (delta) that wasn't
909 * done, decreased by old deferred work that was done now.
911 * And it is capped to two times of the freeable items.
913 next_deferred = max_t(long, (nr + delta - scanned), 0);
914 next_deferred = min(next_deferred, (2 * freeable));
917 * move the unused scan count back into the shrinker in a
918 * manner that handles concurrent updates.
920 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
922 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
927 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
928 struct mem_cgroup *memcg, int priority)
930 struct shrinker_info *info;
931 unsigned long ret, freed = 0;
934 if (!mem_cgroup_online(memcg))
937 if (!down_read_trylock(&shrinker_rwsem))
940 info = shrinker_info_protected(memcg, nid);
944 for_each_set_bit(i, info->map, info->map_nr_max) {
945 struct shrink_control sc = {
946 .gfp_mask = gfp_mask,
950 struct shrinker *shrinker;
952 shrinker = idr_find(&shrinker_idr, i);
953 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
955 clear_bit(i, info->map);
959 /* Call non-slab shrinkers even though kmem is disabled */
960 if (!memcg_kmem_online() &&
961 !(shrinker->flags & SHRINKER_NONSLAB))
964 ret = do_shrink_slab(&sc, shrinker, priority);
965 if (ret == SHRINK_EMPTY) {
966 clear_bit(i, info->map);
968 * After the shrinker reported that it had no objects to
969 * free, but before we cleared the corresponding bit in
970 * the memcg shrinker map, a new object might have been
971 * added. To make sure, we have the bit set in this
972 * case, we invoke the shrinker one more time and reset
973 * the bit if it reports that it is not empty anymore.
974 * The memory barrier here pairs with the barrier in
975 * set_shrinker_bit():
977 * list_lru_add() shrink_slab_memcg()
978 * list_add_tail() clear_bit()
980 * set_bit() do_shrink_slab()
982 smp_mb__after_atomic();
983 ret = do_shrink_slab(&sc, shrinker, priority);
984 if (ret == SHRINK_EMPTY)
987 set_shrinker_bit(memcg, nid, i);
991 if (rwsem_is_contended(&shrinker_rwsem)) {
997 up_read(&shrinker_rwsem);
1000 #else /* CONFIG_MEMCG */
1001 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
1002 struct mem_cgroup *memcg, int priority)
1006 #endif /* CONFIG_MEMCG */
1009 * shrink_slab - shrink slab caches
1010 * @gfp_mask: allocation context
1011 * @nid: node whose slab caches to target
1012 * @memcg: memory cgroup whose slab caches to target
1013 * @priority: the reclaim priority
1015 * Call the shrink functions to age shrinkable caches.
1017 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
1018 * unaware shrinkers will receive a node id of 0 instead.
1020 * @memcg specifies the memory cgroup to target. Unaware shrinkers
1021 * are called only if it is the root cgroup.
1023 * @priority is sc->priority, we take the number of objects and >> by priority
1024 * in order to get the scan target.
1026 * Returns the number of reclaimed slab objects.
1028 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
1029 struct mem_cgroup *memcg,
1032 unsigned long ret, freed = 0;
1033 struct shrinker *shrinker;
1036 * The root memcg might be allocated even though memcg is disabled
1037 * via "cgroup_disable=memory" boot parameter. This could make
1038 * mem_cgroup_is_root() return false, then just run memcg slab
1039 * shrink, but skip global shrink. This may result in premature
1042 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
1043 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
1045 if (!down_read_trylock(&shrinker_rwsem))
1048 list_for_each_entry(shrinker, &shrinker_list, list) {
1049 struct shrink_control sc = {
1050 .gfp_mask = gfp_mask,
1055 ret = do_shrink_slab(&sc, shrinker, priority);
1056 if (ret == SHRINK_EMPTY)
1060 * Bail out if someone want to register a new shrinker to
1061 * prevent the registration from being stalled for long periods
1062 * by parallel ongoing shrinking.
1064 if (rwsem_is_contended(&shrinker_rwsem)) {
1065 freed = freed ? : 1;
1070 up_read(&shrinker_rwsem);
1076 static unsigned long drop_slab_node(int nid)
1078 unsigned long freed = 0;
1079 struct mem_cgroup *memcg = NULL;
1081 memcg = mem_cgroup_iter(NULL, NULL, NULL);
1083 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1084 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1089 void drop_slab(void)
1093 unsigned long freed;
1097 for_each_online_node(nid) {
1098 if (fatal_signal_pending(current))
1101 freed += drop_slab_node(nid);
1103 } while ((freed >> shift++) > 1);
1106 static int reclaimer_offset(void)
1108 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1109 PGDEMOTE_DIRECT - PGDEMOTE_KSWAPD);
1110 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1111 PGSCAN_DIRECT - PGSCAN_KSWAPD);
1112 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1113 PGDEMOTE_KHUGEPAGED - PGDEMOTE_KSWAPD);
1114 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1115 PGSCAN_KHUGEPAGED - PGSCAN_KSWAPD);
1117 if (current_is_kswapd())
1119 if (current_is_khugepaged())
1120 return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
1121 return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
1124 static inline int is_page_cache_freeable(struct folio *folio)
1127 * A freeable page cache folio is referenced only by the caller
1128 * that isolated the folio, the page cache and optional filesystem
1129 * private data at folio->private.
1131 return folio_ref_count(folio) - folio_test_private(folio) ==
1132 1 + folio_nr_pages(folio);
1136 * We detected a synchronous write error writing a folio out. Probably
1137 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1138 * fsync(), msync() or close().
1140 * The tricky part is that after writepage we cannot touch the mapping: nothing
1141 * prevents it from being freed up. But we have a ref on the folio and once
1142 * that folio is locked, the mapping is pinned.
1144 * We're allowed to run sleeping folio_lock() here because we know the caller has
1147 static void handle_write_error(struct address_space *mapping,
1148 struct folio *folio, int error)
1151 if (folio_mapping(folio) == mapping)
1152 mapping_set_error(mapping, error);
1153 folio_unlock(folio);
1156 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1158 int reclaimable = 0, write_pending = 0;
1162 * If kswapd is disabled, reschedule if necessary but do not
1163 * throttle as the system is likely near OOM.
1165 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1169 * If there are a lot of dirty/writeback folios then do not
1170 * throttle as throttling will occur when the folios cycle
1171 * towards the end of the LRU if still under writeback.
1173 for (i = 0; i < MAX_NR_ZONES; i++) {
1174 struct zone *zone = pgdat->node_zones + i;
1176 if (!managed_zone(zone))
1179 reclaimable += zone_reclaimable_pages(zone);
1180 write_pending += zone_page_state_snapshot(zone,
1181 NR_ZONE_WRITE_PENDING);
1183 if (2 * write_pending <= reclaimable)
1189 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1191 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1196 * Do not throttle user workers, kthreads other than kswapd or
1197 * workqueues. They may be required for reclaim to make
1198 * forward progress (e.g. journalling workqueues or kthreads).
1200 if (!current_is_kswapd() &&
1201 current->flags & (PF_USER_WORKER|PF_KTHREAD)) {
1207 * These figures are pulled out of thin air.
1208 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1209 * parallel reclaimers which is a short-lived event so the timeout is
1210 * short. Failing to make progress or waiting on writeback are
1211 * potentially long-lived events so use a longer timeout. This is shaky
1212 * logic as a failure to make progress could be due to anything from
1213 * writeback to a slow device to excessive referenced folios at the tail
1214 * of the inactive LRU.
1217 case VMSCAN_THROTTLE_WRITEBACK:
1220 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1221 WRITE_ONCE(pgdat->nr_reclaim_start,
1222 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1226 case VMSCAN_THROTTLE_CONGESTED:
1228 case VMSCAN_THROTTLE_NOPROGRESS:
1229 if (skip_throttle_noprogress(pgdat)) {
1237 case VMSCAN_THROTTLE_ISOLATED:
1246 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1247 ret = schedule_timeout(timeout);
1248 finish_wait(wqh, &wait);
1250 if (reason == VMSCAN_THROTTLE_WRITEBACK)
1251 atomic_dec(&pgdat->nr_writeback_throttled);
1253 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1254 jiffies_to_usecs(timeout - ret),
1259 * Account for folios written if tasks are throttled waiting on dirty
1260 * folios to clean. If enough folios have been cleaned since throttling
1261 * started then wakeup the throttled tasks.
1263 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1266 unsigned long nr_written;
1268 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1271 * This is an inaccurate read as the per-cpu deltas may not
1272 * be synchronised. However, given that the system is
1273 * writeback throttled, it is not worth taking the penalty
1274 * of getting an accurate count. At worst, the throttle
1275 * timeout guarantees forward progress.
1277 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1278 READ_ONCE(pgdat->nr_reclaim_start);
1280 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1281 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1284 /* possible outcome of pageout() */
1286 /* failed to write folio out, folio is locked */
1288 /* move folio to the active list, folio is locked */
1290 /* folio has been sent to the disk successfully, folio is unlocked */
1292 /* folio is clean and locked */
1297 * pageout is called by shrink_folio_list() for each dirty folio.
1298 * Calls ->writepage().
1300 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1301 struct swap_iocb **plug)
1304 * If the folio is dirty, only perform writeback if that write
1305 * will be non-blocking. To prevent this allocation from being
1306 * stalled by pagecache activity. But note that there may be
1307 * stalls if we need to run get_block(). We could test
1308 * PagePrivate for that.
1310 * If this process is currently in __generic_file_write_iter() against
1311 * this folio's queue, we can perform writeback even if that
1314 * If the folio is swapcache, write it back even if that would
1315 * block, for some throttling. This happens by accident, because
1316 * swap_backing_dev_info is bust: it doesn't reflect the
1317 * congestion state of the swapdevs. Easy to fix, if needed.
1319 if (!is_page_cache_freeable(folio))
1323 * Some data journaling orphaned folios can have
1324 * folio->mapping == NULL while being dirty with clean buffers.
1326 if (folio_test_private(folio)) {
1327 if (try_to_free_buffers(folio)) {
1328 folio_clear_dirty(folio);
1329 pr_info("%s: orphaned folio\n", __func__);
1335 if (mapping->a_ops->writepage == NULL)
1336 return PAGE_ACTIVATE;
1338 if (folio_clear_dirty_for_io(folio)) {
1340 struct writeback_control wbc = {
1341 .sync_mode = WB_SYNC_NONE,
1342 .nr_to_write = SWAP_CLUSTER_MAX,
1344 .range_end = LLONG_MAX,
1349 folio_set_reclaim(folio);
1350 res = mapping->a_ops->writepage(&folio->page, &wbc);
1352 handle_write_error(mapping, folio, res);
1353 if (res == AOP_WRITEPAGE_ACTIVATE) {
1354 folio_clear_reclaim(folio);
1355 return PAGE_ACTIVATE;
1358 if (!folio_test_writeback(folio)) {
1359 /* synchronous write or broken a_ops? */
1360 folio_clear_reclaim(folio);
1362 trace_mm_vmscan_write_folio(folio);
1363 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1364 return PAGE_SUCCESS;
1371 * Same as remove_mapping, but if the folio is removed from the mapping, it
1372 * gets returned with a refcount of 0.
1374 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1375 bool reclaimed, struct mem_cgroup *target_memcg)
1378 void *shadow = NULL;
1380 BUG_ON(!folio_test_locked(folio));
1381 BUG_ON(mapping != folio_mapping(folio));
1383 if (!folio_test_swapcache(folio))
1384 spin_lock(&mapping->host->i_lock);
1385 xa_lock_irq(&mapping->i_pages);
1387 * The non racy check for a busy folio.
1389 * Must be careful with the order of the tests. When someone has
1390 * a ref to the folio, it may be possible that they dirty it then
1391 * drop the reference. So if the dirty flag is tested before the
1392 * refcount here, then the following race may occur:
1394 * get_user_pages(&page);
1395 * [user mapping goes away]
1397 * !folio_test_dirty(folio) [good]
1398 * folio_set_dirty(folio);
1400 * !refcount(folio) [good, discard it]
1402 * [oops, our write_to data is lost]
1404 * Reversing the order of the tests ensures such a situation cannot
1405 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
1406 * load is not satisfied before that of folio->_refcount.
1408 * Note that if the dirty flag is always set via folio_mark_dirty,
1409 * and thus under the i_pages lock, then this ordering is not required.
1411 refcount = 1 + folio_nr_pages(folio);
1412 if (!folio_ref_freeze(folio, refcount))
1414 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
1415 if (unlikely(folio_test_dirty(folio))) {
1416 folio_ref_unfreeze(folio, refcount);
1420 if (folio_test_swapcache(folio)) {
1421 swp_entry_t swap = folio_swap_entry(folio);
1423 if (reclaimed && !mapping_exiting(mapping))
1424 shadow = workingset_eviction(folio, target_memcg);
1425 __delete_from_swap_cache(folio, swap, shadow);
1426 mem_cgroup_swapout(folio, swap);
1427 xa_unlock_irq(&mapping->i_pages);
1428 put_swap_folio(folio, swap);
1430 void (*free_folio)(struct folio *);
1432 free_folio = mapping->a_ops->free_folio;
1434 * Remember a shadow entry for reclaimed file cache in
1435 * order to detect refaults, thus thrashing, later on.
1437 * But don't store shadows in an address space that is
1438 * already exiting. This is not just an optimization,
1439 * inode reclaim needs to empty out the radix tree or
1440 * the nodes are lost. Don't plant shadows behind its
1443 * We also don't store shadows for DAX mappings because the
1444 * only page cache folios found in these are zero pages
1445 * covering holes, and because we don't want to mix DAX
1446 * exceptional entries and shadow exceptional entries in the
1447 * same address_space.
1449 if (reclaimed && folio_is_file_lru(folio) &&
1450 !mapping_exiting(mapping) && !dax_mapping(mapping))
1451 shadow = workingset_eviction(folio, target_memcg);
1452 __filemap_remove_folio(folio, shadow);
1453 xa_unlock_irq(&mapping->i_pages);
1454 if (mapping_shrinkable(mapping))
1455 inode_add_lru(mapping->host);
1456 spin_unlock(&mapping->host->i_lock);
1465 xa_unlock_irq(&mapping->i_pages);
1466 if (!folio_test_swapcache(folio))
1467 spin_unlock(&mapping->host->i_lock);
1472 * remove_mapping() - Attempt to remove a folio from its mapping.
1473 * @mapping: The address space.
1474 * @folio: The folio to remove.
1476 * If the folio is dirty, under writeback or if someone else has a ref
1477 * on it, removal will fail.
1478 * Return: The number of pages removed from the mapping. 0 if the folio
1479 * could not be removed.
1480 * Context: The caller should have a single refcount on the folio and
1483 long remove_mapping(struct address_space *mapping, struct folio *folio)
1485 if (__remove_mapping(mapping, folio, false, NULL)) {
1487 * Unfreezing the refcount with 1 effectively
1488 * drops the pagecache ref for us without requiring another
1491 folio_ref_unfreeze(folio, 1);
1492 return folio_nr_pages(folio);
1498 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1499 * @folio: Folio to be returned to an LRU list.
1501 * Add previously isolated @folio to appropriate LRU list.
1502 * The folio may still be unevictable for other reasons.
1504 * Context: lru_lock must not be held, interrupts must be enabled.
1506 void folio_putback_lru(struct folio *folio)
1508 folio_add_lru(folio);
1509 folio_put(folio); /* drop ref from isolate */
1512 enum folio_references {
1514 FOLIOREF_RECLAIM_CLEAN,
1519 static enum folio_references folio_check_references(struct folio *folio,
1520 struct scan_control *sc)
1522 int referenced_ptes, referenced_folio;
1523 unsigned long vm_flags;
1525 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1527 referenced_folio = folio_test_clear_referenced(folio);
1530 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1531 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1533 if (vm_flags & VM_LOCKED)
1534 return FOLIOREF_ACTIVATE;
1536 /* rmap lock contention: rotate */
1537 if (referenced_ptes == -1)
1538 return FOLIOREF_KEEP;
1540 if (referenced_ptes) {
1542 * All mapped folios start out with page table
1543 * references from the instantiating fault, so we need
1544 * to look twice if a mapped file/anon folio is used more
1547 * Mark it and spare it for another trip around the
1548 * inactive list. Another page table reference will
1549 * lead to its activation.
1551 * Note: the mark is set for activated folios as well
1552 * so that recently deactivated but used folios are
1553 * quickly recovered.
1555 folio_set_referenced(folio);
1557 if (referenced_folio || referenced_ptes > 1)
1558 return FOLIOREF_ACTIVATE;
1561 * Activate file-backed executable folios after first usage.
1563 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1564 return FOLIOREF_ACTIVATE;
1566 return FOLIOREF_KEEP;
1569 /* Reclaim if clean, defer dirty folios to writeback */
1570 if (referenced_folio && folio_is_file_lru(folio))
1571 return FOLIOREF_RECLAIM_CLEAN;
1573 return FOLIOREF_RECLAIM;
1576 /* Check if a folio is dirty or under writeback */
1577 static void folio_check_dirty_writeback(struct folio *folio,
1578 bool *dirty, bool *writeback)
1580 struct address_space *mapping;
1583 * Anonymous folios are not handled by flushers and must be written
1584 * from reclaim context. Do not stall reclaim based on them.
1585 * MADV_FREE anonymous folios are put into inactive file list too.
1586 * They could be mistakenly treated as file lru. So further anon
1589 if (!folio_is_file_lru(folio) ||
1590 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1596 /* By default assume that the folio flags are accurate */
1597 *dirty = folio_test_dirty(folio);
1598 *writeback = folio_test_writeback(folio);
1600 /* Verify dirty/writeback state if the filesystem supports it */
1601 if (!folio_test_private(folio))
1604 mapping = folio_mapping(folio);
1605 if (mapping && mapping->a_ops->is_dirty_writeback)
1606 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1609 static struct page *alloc_demote_page(struct page *page, unsigned long private)
1611 struct page *target_page;
1612 nodemask_t *allowed_mask;
1613 struct migration_target_control *mtc;
1615 mtc = (struct migration_target_control *)private;
1617 allowed_mask = mtc->nmask;
1619 * make sure we allocate from the target node first also trying to
1620 * demote or reclaim pages from the target node via kswapd if we are
1621 * low on free memory on target node. If we don't do this and if
1622 * we have free memory on the slower(lower) memtier, we would start
1623 * allocating pages from slower(lower) memory tiers without even forcing
1624 * a demotion of cold pages from the target memtier. This can result
1625 * in the kernel placing hot pages in slower(lower) memory tiers.
1628 mtc->gfp_mask |= __GFP_THISNODE;
1629 target_page = alloc_migration_target(page, (unsigned long)mtc);
1633 mtc->gfp_mask &= ~__GFP_THISNODE;
1634 mtc->nmask = allowed_mask;
1636 return alloc_migration_target(page, (unsigned long)mtc);
1640 * Take folios on @demote_folios and attempt to demote them to another node.
1641 * Folios which are not demoted are left on @demote_folios.
1643 static unsigned int demote_folio_list(struct list_head *demote_folios,
1644 struct pglist_data *pgdat)
1646 int target_nid = next_demotion_node(pgdat->node_id);
1647 unsigned int nr_succeeded;
1648 nodemask_t allowed_mask;
1650 struct migration_target_control mtc = {
1652 * Allocate from 'node', or fail quickly and quietly.
1653 * When this happens, 'page' will likely just be discarded
1654 * instead of migrated.
1656 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1657 __GFP_NOMEMALLOC | GFP_NOWAIT,
1659 .nmask = &allowed_mask
1662 if (list_empty(demote_folios))
1665 if (target_nid == NUMA_NO_NODE)
1668 node_get_allowed_targets(pgdat, &allowed_mask);
1670 /* Demotion ignores all cpuset and mempolicy settings */
1671 migrate_pages(demote_folios, alloc_demote_page, NULL,
1672 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1675 __count_vm_events(PGDEMOTE_KSWAPD + reclaimer_offset(), nr_succeeded);
1677 return nr_succeeded;
1680 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1682 if (gfp_mask & __GFP_FS)
1684 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1687 * We can "enter_fs" for swap-cache with only __GFP_IO
1688 * providing this isn't SWP_FS_OPS.
1689 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1690 * but that will never affect SWP_FS_OPS, so the data_race
1693 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1697 * shrink_folio_list() returns the number of reclaimed pages
1699 static unsigned int shrink_folio_list(struct list_head *folio_list,
1700 struct pglist_data *pgdat, struct scan_control *sc,
1701 struct reclaim_stat *stat, bool ignore_references)
1703 LIST_HEAD(ret_folios);
1704 LIST_HEAD(free_folios);
1705 LIST_HEAD(demote_folios);
1706 unsigned int nr_reclaimed = 0;
1707 unsigned int pgactivate = 0;
1708 bool do_demote_pass;
1709 struct swap_iocb *plug = NULL;
1711 memset(stat, 0, sizeof(*stat));
1713 do_demote_pass = can_demote(pgdat->node_id, sc);
1716 while (!list_empty(folio_list)) {
1717 struct address_space *mapping;
1718 struct folio *folio;
1719 enum folio_references references = FOLIOREF_RECLAIM;
1720 bool dirty, writeback;
1721 unsigned int nr_pages;
1725 folio = lru_to_folio(folio_list);
1726 list_del(&folio->lru);
1728 if (!folio_trylock(folio))
1731 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1733 nr_pages = folio_nr_pages(folio);
1735 /* Account the number of base pages */
1736 sc->nr_scanned += nr_pages;
1738 if (unlikely(!folio_evictable(folio)))
1739 goto activate_locked;
1741 if (!sc->may_unmap && folio_mapped(folio))
1744 /* folio_update_gen() tried to promote this page? */
1745 if (lru_gen_enabled() && !ignore_references &&
1746 folio_mapped(folio) && folio_test_referenced(folio))
1750 * The number of dirty pages determines if a node is marked
1751 * reclaim_congested. kswapd will stall and start writing
1752 * folios if the tail of the LRU is all dirty unqueued folios.
1754 folio_check_dirty_writeback(folio, &dirty, &writeback);
1755 if (dirty || writeback)
1756 stat->nr_dirty += nr_pages;
1758 if (dirty && !writeback)
1759 stat->nr_unqueued_dirty += nr_pages;
1762 * Treat this folio as congested if folios are cycling
1763 * through the LRU so quickly that the folios marked
1764 * for immediate reclaim are making it to the end of
1765 * the LRU a second time.
1767 if (writeback && folio_test_reclaim(folio))
1768 stat->nr_congested += nr_pages;
1771 * If a folio at the tail of the LRU is under writeback, there
1772 * are three cases to consider.
1774 * 1) If reclaim is encountering an excessive number
1775 * of folios under writeback and this folio has both
1776 * the writeback and reclaim flags set, then it
1777 * indicates that folios are being queued for I/O but
1778 * are being recycled through the LRU before the I/O
1779 * can complete. Waiting on the folio itself risks an
1780 * indefinite stall if it is impossible to writeback
1781 * the folio due to I/O error or disconnected storage
1782 * so instead note that the LRU is being scanned too
1783 * quickly and the caller can stall after the folio
1784 * list has been processed.
1786 * 2) Global or new memcg reclaim encounters a folio that is
1787 * not marked for immediate reclaim, or the caller does not
1788 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1789 * not to fs). In this case mark the folio for immediate
1790 * reclaim and continue scanning.
1792 * Require may_enter_fs() because we would wait on fs, which
1793 * may not have submitted I/O yet. And the loop driver might
1794 * enter reclaim, and deadlock if it waits on a folio for
1795 * which it is needed to do the write (loop masks off
1796 * __GFP_IO|__GFP_FS for this reason); but more thought
1797 * would probably show more reasons.
1799 * 3) Legacy memcg encounters a folio that already has the
1800 * reclaim flag set. memcg does not have any dirty folio
1801 * throttling so we could easily OOM just because too many
1802 * folios are in writeback and there is nothing else to
1803 * reclaim. Wait for the writeback to complete.
1805 * In cases 1) and 2) we activate the folios to get them out of
1806 * the way while we continue scanning for clean folios on the
1807 * inactive list and refilling from the active list. The
1808 * observation here is that waiting for disk writes is more
1809 * expensive than potentially causing reloads down the line.
1810 * Since they're marked for immediate reclaim, they won't put
1811 * memory pressure on the cache working set any longer than it
1812 * takes to write them to disk.
1814 if (folio_test_writeback(folio)) {
1816 if (current_is_kswapd() &&
1817 folio_test_reclaim(folio) &&
1818 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1819 stat->nr_immediate += nr_pages;
1820 goto activate_locked;
1823 } else if (writeback_throttling_sane(sc) ||
1824 !folio_test_reclaim(folio) ||
1825 !may_enter_fs(folio, sc->gfp_mask)) {
1827 * This is slightly racy -
1828 * folio_end_writeback() might have
1829 * just cleared the reclaim flag, then
1830 * setting the reclaim flag here ends up
1831 * interpreted as the readahead flag - but
1832 * that does not matter enough to care.
1833 * What we do want is for this folio to
1834 * have the reclaim flag set next time
1835 * memcg reclaim reaches the tests above,
1836 * so it will then wait for writeback to
1837 * avoid OOM; and it's also appropriate
1838 * in global reclaim.
1840 folio_set_reclaim(folio);
1841 stat->nr_writeback += nr_pages;
1842 goto activate_locked;
1846 folio_unlock(folio);
1847 folio_wait_writeback(folio);
1848 /* then go back and try same folio again */
1849 list_add_tail(&folio->lru, folio_list);
1854 if (!ignore_references)
1855 references = folio_check_references(folio, sc);
1857 switch (references) {
1858 case FOLIOREF_ACTIVATE:
1859 goto activate_locked;
1861 stat->nr_ref_keep += nr_pages;
1863 case FOLIOREF_RECLAIM:
1864 case FOLIOREF_RECLAIM_CLEAN:
1865 ; /* try to reclaim the folio below */
1869 * Before reclaiming the folio, try to relocate
1870 * its contents to another node.
1872 if (do_demote_pass &&
1873 (thp_migration_supported() || !folio_test_large(folio))) {
1874 list_add(&folio->lru, &demote_folios);
1875 folio_unlock(folio);
1880 * Anonymous process memory has backing store?
1881 * Try to allocate it some swap space here.
1882 * Lazyfree folio could be freed directly
1884 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1885 if (!folio_test_swapcache(folio)) {
1886 if (!(sc->gfp_mask & __GFP_IO))
1888 if (folio_maybe_dma_pinned(folio))
1890 if (folio_test_large(folio)) {
1891 /* cannot split folio, skip it */
1892 if (!can_split_folio(folio, NULL))
1893 goto activate_locked;
1895 * Split folios without a PMD map right
1896 * away. Chances are some or all of the
1897 * tail pages can be freed without IO.
1899 if (!folio_entire_mapcount(folio) &&
1900 split_folio_to_list(folio,
1902 goto activate_locked;
1904 if (!add_to_swap(folio)) {
1905 if (!folio_test_large(folio))
1906 goto activate_locked_split;
1907 /* Fallback to swap normal pages */
1908 if (split_folio_to_list(folio,
1910 goto activate_locked;
1911 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1912 count_vm_event(THP_SWPOUT_FALLBACK);
1914 if (!add_to_swap(folio))
1915 goto activate_locked_split;
1918 } else if (folio_test_swapbacked(folio) &&
1919 folio_test_large(folio)) {
1920 /* Split shmem folio */
1921 if (split_folio_to_list(folio, folio_list))
1926 * If the folio was split above, the tail pages will make
1927 * their own pass through this function and be accounted
1930 if ((nr_pages > 1) && !folio_test_large(folio)) {
1931 sc->nr_scanned -= (nr_pages - 1);
1936 * The folio is mapped into the page tables of one or more
1937 * processes. Try to unmap it here.
1939 if (folio_mapped(folio)) {
1940 enum ttu_flags flags = TTU_BATCH_FLUSH;
1941 bool was_swapbacked = folio_test_swapbacked(folio);
1943 if (folio_test_pmd_mappable(folio))
1944 flags |= TTU_SPLIT_HUGE_PMD;
1946 try_to_unmap(folio, flags);
1947 if (folio_mapped(folio)) {
1948 stat->nr_unmap_fail += nr_pages;
1949 if (!was_swapbacked &&
1950 folio_test_swapbacked(folio))
1951 stat->nr_lazyfree_fail += nr_pages;
1952 goto activate_locked;
1957 * Folio is unmapped now so it cannot be newly pinned anymore.
1958 * No point in trying to reclaim folio if it is pinned.
1959 * Furthermore we don't want to reclaim underlying fs metadata
1960 * if the folio is pinned and thus potentially modified by the
1961 * pinning process as that may upset the filesystem.
1963 if (folio_maybe_dma_pinned(folio))
1964 goto activate_locked;
1966 mapping = folio_mapping(folio);
1967 if (folio_test_dirty(folio)) {
1969 * Only kswapd can writeback filesystem folios
1970 * to avoid risk of stack overflow. But avoid
1971 * injecting inefficient single-folio I/O into
1972 * flusher writeback as much as possible: only
1973 * write folios when we've encountered many
1974 * dirty folios, and when we've already scanned
1975 * the rest of the LRU for clean folios and see
1976 * the same dirty folios again (with the reclaim
1979 if (folio_is_file_lru(folio) &&
1980 (!current_is_kswapd() ||
1981 !folio_test_reclaim(folio) ||
1982 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1984 * Immediately reclaim when written back.
1985 * Similar in principle to folio_deactivate()
1986 * except we already have the folio isolated
1987 * and know it's dirty
1989 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1991 folio_set_reclaim(folio);
1993 goto activate_locked;
1996 if (references == FOLIOREF_RECLAIM_CLEAN)
1998 if (!may_enter_fs(folio, sc->gfp_mask))
2000 if (!sc->may_writepage)
2004 * Folio is dirty. Flush the TLB if a writable entry
2005 * potentially exists to avoid CPU writes after I/O
2006 * starts and then write it out here.
2008 try_to_unmap_flush_dirty();
2009 switch (pageout(folio, mapping, &plug)) {
2013 goto activate_locked;
2015 stat->nr_pageout += nr_pages;
2017 if (folio_test_writeback(folio))
2019 if (folio_test_dirty(folio))
2023 * A synchronous write - probably a ramdisk. Go
2024 * ahead and try to reclaim the folio.
2026 if (!folio_trylock(folio))
2028 if (folio_test_dirty(folio) ||
2029 folio_test_writeback(folio))
2031 mapping = folio_mapping(folio);
2034 ; /* try to free the folio below */
2039 * If the folio has buffers, try to free the buffer
2040 * mappings associated with this folio. If we succeed
2041 * we try to free the folio as well.
2043 * We do this even if the folio is dirty.
2044 * filemap_release_folio() does not perform I/O, but it
2045 * is possible for a folio to have the dirty flag set,
2046 * but it is actually clean (all its buffers are clean).
2047 * This happens if the buffers were written out directly,
2048 * with submit_bh(). ext3 will do this, as well as
2049 * the blockdev mapping. filemap_release_folio() will
2050 * discover that cleanness and will drop the buffers
2051 * and mark the folio clean - it can be freed.
2053 * Rarely, folios can have buffers and no ->mapping.
2054 * These are the folios which were not successfully
2055 * invalidated in truncate_cleanup_folio(). We try to
2056 * drop those buffers here and if that worked, and the
2057 * folio is no longer mapped into process address space
2058 * (refcount == 1) it can be freed. Otherwise, leave
2059 * the folio on the LRU so it is swappable.
2061 if (folio_has_private(folio)) {
2062 if (!filemap_release_folio(folio, sc->gfp_mask))
2063 goto activate_locked;
2064 if (!mapping && folio_ref_count(folio) == 1) {
2065 folio_unlock(folio);
2066 if (folio_put_testzero(folio))
2070 * rare race with speculative reference.
2071 * the speculative reference will free
2072 * this folio shortly, so we may
2073 * increment nr_reclaimed here (and
2074 * leave it off the LRU).
2076 nr_reclaimed += nr_pages;
2082 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
2083 /* follow __remove_mapping for reference */
2084 if (!folio_ref_freeze(folio, 1))
2087 * The folio has only one reference left, which is
2088 * from the isolation. After the caller puts the
2089 * folio back on the lru and drops the reference, the
2090 * folio will be freed anyway. It doesn't matter
2091 * which lru it goes on. So we don't bother checking
2092 * the dirty flag here.
2094 count_vm_events(PGLAZYFREED, nr_pages);
2095 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
2096 } else if (!mapping || !__remove_mapping(mapping, folio, true,
2097 sc->target_mem_cgroup))
2100 folio_unlock(folio);
2103 * Folio may get swapped out as a whole, need to account
2106 nr_reclaimed += nr_pages;
2109 * Is there need to periodically free_folio_list? It would
2110 * appear not as the counts should be low
2112 if (unlikely(folio_test_large(folio)))
2113 destroy_large_folio(folio);
2115 list_add(&folio->lru, &free_folios);
2118 activate_locked_split:
2120 * The tail pages that are failed to add into swap cache
2121 * reach here. Fixup nr_scanned and nr_pages.
2124 sc->nr_scanned -= (nr_pages - 1);
2128 /* Not a candidate for swapping, so reclaim swap space. */
2129 if (folio_test_swapcache(folio) &&
2130 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
2131 folio_free_swap(folio);
2132 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2133 if (!folio_test_mlocked(folio)) {
2134 int type = folio_is_file_lru(folio);
2135 folio_set_active(folio);
2136 stat->nr_activate[type] += nr_pages;
2137 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2140 folio_unlock(folio);
2142 list_add(&folio->lru, &ret_folios);
2143 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2144 folio_test_unevictable(folio), folio);
2146 /* 'folio_list' is always empty here */
2148 /* Migrate folios selected for demotion */
2149 nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
2150 /* Folios that could not be demoted are still in @demote_folios */
2151 if (!list_empty(&demote_folios)) {
2152 /* Folios which weren't demoted go back on @folio_list */
2153 list_splice_init(&demote_folios, folio_list);
2156 * goto retry to reclaim the undemoted folios in folio_list if
2159 * Reclaiming directly from top tier nodes is not often desired
2160 * due to it breaking the LRU ordering: in general memory
2161 * should be reclaimed from lower tier nodes and demoted from
2164 * However, disabling reclaim from top tier nodes entirely
2165 * would cause ooms in edge scenarios where lower tier memory
2166 * is unreclaimable for whatever reason, eg memory being
2167 * mlocked or too hot to reclaim. We can disable reclaim
2168 * from top tier nodes in proactive reclaim though as that is
2169 * not real memory pressure.
2171 if (!sc->proactive) {
2172 do_demote_pass = false;
2177 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2179 mem_cgroup_uncharge_list(&free_folios);
2180 try_to_unmap_flush();
2181 free_unref_page_list(&free_folios);
2183 list_splice(&ret_folios, folio_list);
2184 count_vm_events(PGACTIVATE, pgactivate);
2187 swap_write_unplug(plug);
2188 return nr_reclaimed;
2191 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2192 struct list_head *folio_list)
2194 struct scan_control sc = {
2195 .gfp_mask = GFP_KERNEL,
2198 struct reclaim_stat stat;
2199 unsigned int nr_reclaimed;
2200 struct folio *folio, *next;
2201 LIST_HEAD(clean_folios);
2202 unsigned int noreclaim_flag;
2204 list_for_each_entry_safe(folio, next, folio_list, lru) {
2205 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2206 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2207 !folio_test_unevictable(folio)) {
2208 folio_clear_active(folio);
2209 list_move(&folio->lru, &clean_folios);
2214 * We should be safe here since we are only dealing with file pages and
2215 * we are not kswapd and therefore cannot write dirty file pages. But
2216 * call memalloc_noreclaim_save() anyway, just in case these conditions
2217 * change in the future.
2219 noreclaim_flag = memalloc_noreclaim_save();
2220 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
2222 memalloc_noreclaim_restore(noreclaim_flag);
2224 list_splice(&clean_folios, folio_list);
2225 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2226 -(long)nr_reclaimed);
2228 * Since lazyfree pages are isolated from file LRU from the beginning,
2229 * they will rotate back to anonymous LRU in the end if it failed to
2230 * discard so isolated count will be mismatched.
2231 * Compensate the isolated count for both LRU lists.
2233 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2234 stat.nr_lazyfree_fail);
2235 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2236 -(long)stat.nr_lazyfree_fail);
2237 return nr_reclaimed;
2241 * Update LRU sizes after isolating pages. The LRU size updates must
2242 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2244 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2245 enum lru_list lru, unsigned long *nr_zone_taken)
2249 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2250 if (!nr_zone_taken[zid])
2253 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2259 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2261 * lruvec->lru_lock is heavily contended. Some of the functions that
2262 * shrink the lists perform better by taking out a batch of pages
2263 * and working on them outside the LRU lock.
2265 * For pagecache intensive workloads, this function is the hottest
2266 * spot in the kernel (apart from copy_*_user functions).
2268 * Lru_lock must be held before calling this function.
2270 * @nr_to_scan: The number of eligible pages to look through on the list.
2271 * @lruvec: The LRU vector to pull pages from.
2272 * @dst: The temp list to put pages on to.
2273 * @nr_scanned: The number of pages that were scanned.
2274 * @sc: The scan_control struct for this reclaim session
2275 * @lru: LRU list id for isolating
2277 * returns how many pages were moved onto *@dst.
2279 static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
2280 struct lruvec *lruvec, struct list_head *dst,
2281 unsigned long *nr_scanned, struct scan_control *sc,
2284 struct list_head *src = &lruvec->lists[lru];
2285 unsigned long nr_taken = 0;
2286 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2287 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2288 unsigned long skipped = 0;
2289 unsigned long scan, total_scan, nr_pages;
2290 LIST_HEAD(folios_skipped);
2294 while (scan < nr_to_scan && !list_empty(src)) {
2295 struct list_head *move_to = src;
2296 struct folio *folio;
2298 folio = lru_to_folio(src);
2299 prefetchw_prev_lru_folio(folio, src, flags);
2301 nr_pages = folio_nr_pages(folio);
2302 total_scan += nr_pages;
2304 if (folio_zonenum(folio) > sc->reclaim_idx) {
2305 nr_skipped[folio_zonenum(folio)] += nr_pages;
2306 move_to = &folios_skipped;
2311 * Do not count skipped folios because that makes the function
2312 * return with no isolated folios if the LRU mostly contains
2313 * ineligible folios. This causes the VM to not reclaim any
2314 * folios, triggering a premature OOM.
2315 * Account all pages in a folio.
2319 if (!folio_test_lru(folio))
2321 if (!sc->may_unmap && folio_mapped(folio))
2325 * Be careful not to clear the lru flag until after we're
2326 * sure the folio is not being freed elsewhere -- the
2327 * folio release code relies on it.
2329 if (unlikely(!folio_try_get(folio)))
2332 if (!folio_test_clear_lru(folio)) {
2333 /* Another thread is already isolating this folio */
2338 nr_taken += nr_pages;
2339 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2342 list_move(&folio->lru, move_to);
2346 * Splice any skipped folios to the start of the LRU list. Note that
2347 * this disrupts the LRU order when reclaiming for lower zones but
2348 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2349 * scanning would soon rescan the same folios to skip and waste lots
2352 if (!list_empty(&folios_skipped)) {
2355 list_splice(&folios_skipped, src);
2356 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2357 if (!nr_skipped[zid])
2360 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2361 skipped += nr_skipped[zid];
2364 *nr_scanned = total_scan;
2365 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2366 total_scan, skipped, nr_taken,
2367 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2368 update_lru_sizes(lruvec, lru, nr_zone_taken);
2373 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2374 * @folio: Folio to isolate from its LRU list.
2376 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2377 * corresponding to whatever LRU list the folio was on.
2379 * The folio will have its LRU flag cleared. If it was found on the
2380 * active list, it will have the Active flag set. If it was found on the
2381 * unevictable list, it will have the Unevictable flag set. These flags
2382 * may need to be cleared by the caller before letting the page go.
2386 * (1) Must be called with an elevated refcount on the folio. This is a
2387 * fundamental difference from isolate_lru_folios() (which is called
2388 * without a stable reference).
2389 * (2) The lru_lock must not be held.
2390 * (3) Interrupts must be enabled.
2392 * Return: true if the folio was removed from an LRU list.
2393 * false if the folio was not on an LRU list.
2395 bool folio_isolate_lru(struct folio *folio)
2399 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2401 if (folio_test_clear_lru(folio)) {
2402 struct lruvec *lruvec;
2405 lruvec = folio_lruvec_lock_irq(folio);
2406 lruvec_del_folio(lruvec, folio);
2407 unlock_page_lruvec_irq(lruvec);
2415 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2416 * then get rescheduled. When there are massive number of tasks doing page
2417 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2418 * the LRU list will go small and be scanned faster than necessary, leading to
2419 * unnecessary swapping, thrashing and OOM.
2421 static int too_many_isolated(struct pglist_data *pgdat, int file,
2422 struct scan_control *sc)
2424 unsigned long inactive, isolated;
2427 if (current_is_kswapd())
2430 if (!writeback_throttling_sane(sc))
2434 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2435 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2437 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2438 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2442 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2443 * won't get blocked by normal direct-reclaimers, forming a circular
2446 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2449 too_many = isolated > inactive;
2451 /* Wake up tasks throttled due to too_many_isolated. */
2453 wake_throttle_isolated(pgdat);
2459 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
2460 * On return, @list is reused as a list of folios to be freed by the caller.
2462 * Returns the number of pages moved to the given lruvec.
2464 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
2465 struct list_head *list)
2467 int nr_pages, nr_moved = 0;
2468 LIST_HEAD(folios_to_free);
2470 while (!list_empty(list)) {
2471 struct folio *folio = lru_to_folio(list);
2473 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2474 list_del(&folio->lru);
2475 if (unlikely(!folio_evictable(folio))) {
2476 spin_unlock_irq(&lruvec->lru_lock);
2477 folio_putback_lru(folio);
2478 spin_lock_irq(&lruvec->lru_lock);
2483 * The folio_set_lru needs to be kept here for list integrity.
2485 * #0 move_folios_to_lru #1 release_pages
2486 * if (!folio_put_testzero())
2487 * if (folio_put_testzero())
2488 * !lru //skip lru_lock
2490 * list_add(&folio->lru,)
2491 * list_add(&folio->lru,)
2493 folio_set_lru(folio);
2495 if (unlikely(folio_put_testzero(folio))) {
2496 __folio_clear_lru_flags(folio);
2498 if (unlikely(folio_test_large(folio))) {
2499 spin_unlock_irq(&lruvec->lru_lock);
2500 destroy_large_folio(folio);
2501 spin_lock_irq(&lruvec->lru_lock);
2503 list_add(&folio->lru, &folios_to_free);
2509 * All pages were isolated from the same lruvec (and isolation
2510 * inhibits memcg migration).
2512 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2513 lruvec_add_folio(lruvec, folio);
2514 nr_pages = folio_nr_pages(folio);
2515 nr_moved += nr_pages;
2516 if (folio_test_active(folio))
2517 workingset_age_nonresident(lruvec, nr_pages);
2521 * To save our caller's stack, now use input list for pages to free.
2523 list_splice(&folios_to_free, list);
2529 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2530 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2531 * we should not throttle. Otherwise it is safe to do so.
2533 static int current_may_throttle(void)
2535 return !(current->flags & PF_LOCAL_THROTTLE);
2539 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2540 * of reclaimed pages
2542 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
2543 struct lruvec *lruvec, struct scan_control *sc,
2546 LIST_HEAD(folio_list);
2547 unsigned long nr_scanned;
2548 unsigned int nr_reclaimed = 0;
2549 unsigned long nr_taken;
2550 struct reclaim_stat stat;
2551 bool file = is_file_lru(lru);
2552 enum vm_event_item item;
2553 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2554 bool stalled = false;
2556 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2560 /* wait a bit for the reclaimer. */
2562 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2564 /* We are about to die and free our memory. Return now. */
2565 if (fatal_signal_pending(current))
2566 return SWAP_CLUSTER_MAX;
2571 spin_lock_irq(&lruvec->lru_lock);
2573 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
2574 &nr_scanned, sc, lru);
2576 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2577 item = PGSCAN_KSWAPD + reclaimer_offset();
2578 if (!cgroup_reclaim(sc))
2579 __count_vm_events(item, nr_scanned);
2580 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2581 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2583 spin_unlock_irq(&lruvec->lru_lock);
2588 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
2590 spin_lock_irq(&lruvec->lru_lock);
2591 move_folios_to_lru(lruvec, &folio_list);
2593 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2594 item = PGSTEAL_KSWAPD + reclaimer_offset();
2595 if (!cgroup_reclaim(sc))
2596 __count_vm_events(item, nr_reclaimed);
2597 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2598 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2599 spin_unlock_irq(&lruvec->lru_lock);
2601 lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
2602 mem_cgroup_uncharge_list(&folio_list);
2603 free_unref_page_list(&folio_list);
2606 * If dirty folios are scanned that are not queued for IO, it
2607 * implies that flushers are not doing their job. This can
2608 * happen when memory pressure pushes dirty folios to the end of
2609 * the LRU before the dirty limits are breached and the dirty
2610 * data has expired. It can also happen when the proportion of
2611 * dirty folios grows not through writes but through memory
2612 * pressure reclaiming all the clean cache. And in some cases,
2613 * the flushers simply cannot keep up with the allocation
2614 * rate. Nudge the flusher threads in case they are asleep.
2616 if (stat.nr_unqueued_dirty == nr_taken) {
2617 wakeup_flusher_threads(WB_REASON_VMSCAN);
2619 * For cgroupv1 dirty throttling is achieved by waking up
2620 * the kernel flusher here and later waiting on folios
2621 * which are in writeback to finish (see shrink_folio_list()).
2623 * Flusher may not be able to issue writeback quickly
2624 * enough for cgroupv1 writeback throttling to work
2625 * on a large system.
2627 if (!writeback_throttling_sane(sc))
2628 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2631 sc->nr.dirty += stat.nr_dirty;
2632 sc->nr.congested += stat.nr_congested;
2633 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2634 sc->nr.writeback += stat.nr_writeback;
2635 sc->nr.immediate += stat.nr_immediate;
2636 sc->nr.taken += nr_taken;
2638 sc->nr.file_taken += nr_taken;
2640 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2641 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2642 return nr_reclaimed;
2646 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2648 * We move them the other way if the folio is referenced by one or more
2651 * If the folios are mostly unmapped, the processing is fast and it is
2652 * appropriate to hold lru_lock across the whole operation. But if
2653 * the folios are mapped, the processing is slow (folio_referenced()), so
2654 * we should drop lru_lock around each folio. It's impossible to balance
2655 * this, so instead we remove the folios from the LRU while processing them.
2656 * It is safe to rely on the active flag against the non-LRU folios in here
2657 * because nobody will play with that bit on a non-LRU folio.
2659 * The downside is that we have to touch folio->_refcount against each folio.
2660 * But we had to alter folio->flags anyway.
2662 static void shrink_active_list(unsigned long nr_to_scan,
2663 struct lruvec *lruvec,
2664 struct scan_control *sc,
2667 unsigned long nr_taken;
2668 unsigned long nr_scanned;
2669 unsigned long vm_flags;
2670 LIST_HEAD(l_hold); /* The folios which were snipped off */
2671 LIST_HEAD(l_active);
2672 LIST_HEAD(l_inactive);
2673 unsigned nr_deactivate, nr_activate;
2674 unsigned nr_rotated = 0;
2675 int file = is_file_lru(lru);
2676 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2680 spin_lock_irq(&lruvec->lru_lock);
2682 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2683 &nr_scanned, sc, lru);
2685 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2687 if (!cgroup_reclaim(sc))
2688 __count_vm_events(PGREFILL, nr_scanned);
2689 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2691 spin_unlock_irq(&lruvec->lru_lock);
2693 while (!list_empty(&l_hold)) {
2694 struct folio *folio;
2697 folio = lru_to_folio(&l_hold);
2698 list_del(&folio->lru);
2700 if (unlikely(!folio_evictable(folio))) {
2701 folio_putback_lru(folio);
2705 if (unlikely(buffer_heads_over_limit)) {
2706 if (folio_test_private(folio) && folio_trylock(folio)) {
2707 if (folio_test_private(folio))
2708 filemap_release_folio(folio, 0);
2709 folio_unlock(folio);
2713 /* Referenced or rmap lock contention: rotate */
2714 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2717 * Identify referenced, file-backed active folios and
2718 * give them one more trip around the active list. So
2719 * that executable code get better chances to stay in
2720 * memory under moderate memory pressure. Anon folios
2721 * are not likely to be evicted by use-once streaming
2722 * IO, plus JVM can create lots of anon VM_EXEC folios,
2723 * so we ignore them here.
2725 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2726 nr_rotated += folio_nr_pages(folio);
2727 list_add(&folio->lru, &l_active);
2732 folio_clear_active(folio); /* we are de-activating */
2733 folio_set_workingset(folio);
2734 list_add(&folio->lru, &l_inactive);
2738 * Move folios back to the lru list.
2740 spin_lock_irq(&lruvec->lru_lock);
2742 nr_activate = move_folios_to_lru(lruvec, &l_active);
2743 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2744 /* Keep all free folios in l_active list */
2745 list_splice(&l_inactive, &l_active);
2747 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2748 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2750 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2751 spin_unlock_irq(&lruvec->lru_lock);
2754 lru_note_cost(lruvec, file, 0, nr_rotated);
2755 mem_cgroup_uncharge_list(&l_active);
2756 free_unref_page_list(&l_active);
2757 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2758 nr_deactivate, nr_rotated, sc->priority, file);
2761 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2762 struct pglist_data *pgdat)
2764 struct reclaim_stat dummy_stat;
2765 unsigned int nr_reclaimed;
2766 struct folio *folio;
2767 struct scan_control sc = {
2768 .gfp_mask = GFP_KERNEL,
2775 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2776 while (!list_empty(folio_list)) {
2777 folio = lru_to_folio(folio_list);
2778 list_del(&folio->lru);
2779 folio_putback_lru(folio);
2782 return nr_reclaimed;
2785 unsigned long reclaim_pages(struct list_head *folio_list)
2788 unsigned int nr_reclaimed = 0;
2789 LIST_HEAD(node_folio_list);
2790 unsigned int noreclaim_flag;
2792 if (list_empty(folio_list))
2793 return nr_reclaimed;
2795 noreclaim_flag = memalloc_noreclaim_save();
2797 nid = folio_nid(lru_to_folio(folio_list));
2799 struct folio *folio = lru_to_folio(folio_list);
2801 if (nid == folio_nid(folio)) {
2802 folio_clear_active(folio);
2803 list_move(&folio->lru, &node_folio_list);
2807 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2808 nid = folio_nid(lru_to_folio(folio_list));
2809 } while (!list_empty(folio_list));
2811 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2813 memalloc_noreclaim_restore(noreclaim_flag);
2815 return nr_reclaimed;
2818 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2819 struct lruvec *lruvec, struct scan_control *sc)
2821 if (is_active_lru(lru)) {
2822 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2823 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2825 sc->skipped_deactivate = 1;
2829 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2833 * The inactive anon list should be small enough that the VM never has
2834 * to do too much work.
2836 * The inactive file list should be small enough to leave most memory
2837 * to the established workingset on the scan-resistant active list,
2838 * but large enough to avoid thrashing the aggregate readahead window.
2840 * Both inactive lists should also be large enough that each inactive
2841 * folio has a chance to be referenced again before it is reclaimed.
2843 * If that fails and refaulting is observed, the inactive list grows.
2845 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2846 * on this LRU, maintained by the pageout code. An inactive_ratio
2847 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2850 * memory ratio inactive
2851 * -------------------------------------
2860 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2862 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2863 unsigned long inactive, active;
2864 unsigned long inactive_ratio;
2867 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2868 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2870 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2872 inactive_ratio = int_sqrt(10 * gb);
2876 return inactive * inactive_ratio < active;
2886 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2889 struct lruvec *target_lruvec;
2891 if (lru_gen_enabled())
2894 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2897 * Flush the memory cgroup stats, so that we read accurate per-memcg
2898 * lruvec stats for heuristics.
2900 mem_cgroup_flush_stats();
2903 * Determine the scan balance between anon and file LRUs.
2905 spin_lock_irq(&target_lruvec->lru_lock);
2906 sc->anon_cost = target_lruvec->anon_cost;
2907 sc->file_cost = target_lruvec->file_cost;
2908 spin_unlock_irq(&target_lruvec->lru_lock);
2911 * Target desirable inactive:active list ratios for the anon
2912 * and file LRU lists.
2914 if (!sc->force_deactivate) {
2915 unsigned long refaults;
2918 * When refaults are being observed, it means a new
2919 * workingset is being established. Deactivate to get
2920 * rid of any stale active pages quickly.
2922 refaults = lruvec_page_state(target_lruvec,
2923 WORKINGSET_ACTIVATE_ANON);
2924 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2925 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2926 sc->may_deactivate |= DEACTIVATE_ANON;
2928 sc->may_deactivate &= ~DEACTIVATE_ANON;
2930 refaults = lruvec_page_state(target_lruvec,
2931 WORKINGSET_ACTIVATE_FILE);
2932 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2933 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2934 sc->may_deactivate |= DEACTIVATE_FILE;
2936 sc->may_deactivate &= ~DEACTIVATE_FILE;
2938 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2941 * If we have plenty of inactive file pages that aren't
2942 * thrashing, try to reclaim those first before touching
2945 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2946 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2947 sc->cache_trim_mode = 1;
2949 sc->cache_trim_mode = 0;
2952 * Prevent the reclaimer from falling into the cache trap: as
2953 * cache pages start out inactive, every cache fault will tip
2954 * the scan balance towards the file LRU. And as the file LRU
2955 * shrinks, so does the window for rotation from references.
2956 * This means we have a runaway feedback loop where a tiny
2957 * thrashing file LRU becomes infinitely more attractive than
2958 * anon pages. Try to detect this based on file LRU size.
2960 if (!cgroup_reclaim(sc)) {
2961 unsigned long total_high_wmark = 0;
2962 unsigned long free, anon;
2965 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2966 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2967 node_page_state(pgdat, NR_INACTIVE_FILE);
2969 for (z = 0; z < MAX_NR_ZONES; z++) {
2970 struct zone *zone = &pgdat->node_zones[z];
2972 if (!managed_zone(zone))
2975 total_high_wmark += high_wmark_pages(zone);
2979 * Consider anon: if that's low too, this isn't a
2980 * runaway file reclaim problem, but rather just
2981 * extreme pressure. Reclaim as per usual then.
2983 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2986 file + free <= total_high_wmark &&
2987 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2988 anon >> sc->priority;
2993 * Determine how aggressively the anon and file LRU lists should be
2996 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2997 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2999 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
3002 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3003 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3004 unsigned long anon_cost, file_cost, total_cost;
3005 int swappiness = mem_cgroup_swappiness(memcg);
3006 u64 fraction[ANON_AND_FILE];
3007 u64 denominator = 0; /* gcc */
3008 enum scan_balance scan_balance;
3009 unsigned long ap, fp;
3012 /* If we have no swap space, do not bother scanning anon folios. */
3013 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
3014 scan_balance = SCAN_FILE;
3019 * Global reclaim will swap to prevent OOM even with no
3020 * swappiness, but memcg users want to use this knob to
3021 * disable swapping for individual groups completely when
3022 * using the memory controller's swap limit feature would be
3025 if (cgroup_reclaim(sc) && !swappiness) {
3026 scan_balance = SCAN_FILE;
3031 * Do not apply any pressure balancing cleverness when the
3032 * system is close to OOM, scan both anon and file equally
3033 * (unless the swappiness setting disagrees with swapping).
3035 if (!sc->priority && swappiness) {
3036 scan_balance = SCAN_EQUAL;
3041 * If the system is almost out of file pages, force-scan anon.
3043 if (sc->file_is_tiny) {
3044 scan_balance = SCAN_ANON;
3049 * If there is enough inactive page cache, we do not reclaim
3050 * anything from the anonymous working right now.
3052 if (sc->cache_trim_mode) {
3053 scan_balance = SCAN_FILE;
3057 scan_balance = SCAN_FRACT;
3059 * Calculate the pressure balance between anon and file pages.
3061 * The amount of pressure we put on each LRU is inversely
3062 * proportional to the cost of reclaiming each list, as
3063 * determined by the share of pages that are refaulting, times
3064 * the relative IO cost of bringing back a swapped out
3065 * anonymous page vs reloading a filesystem page (swappiness).
3067 * Although we limit that influence to ensure no list gets
3068 * left behind completely: at least a third of the pressure is
3069 * applied, before swappiness.
3071 * With swappiness at 100, anon and file have equal IO cost.
3073 total_cost = sc->anon_cost + sc->file_cost;
3074 anon_cost = total_cost + sc->anon_cost;
3075 file_cost = total_cost + sc->file_cost;
3076 total_cost = anon_cost + file_cost;
3078 ap = swappiness * (total_cost + 1);
3079 ap /= anon_cost + 1;
3081 fp = (200 - swappiness) * (total_cost + 1);
3082 fp /= file_cost + 1;
3086 denominator = ap + fp;
3088 for_each_evictable_lru(lru) {
3089 int file = is_file_lru(lru);
3090 unsigned long lruvec_size;
3091 unsigned long low, min;
3094 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
3095 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
3100 * Scale a cgroup's reclaim pressure by proportioning
3101 * its current usage to its memory.low or memory.min
3104 * This is important, as otherwise scanning aggression
3105 * becomes extremely binary -- from nothing as we
3106 * approach the memory protection threshold, to totally
3107 * nominal as we exceed it. This results in requiring
3108 * setting extremely liberal protection thresholds. It
3109 * also means we simply get no protection at all if we
3110 * set it too low, which is not ideal.
3112 * If there is any protection in place, we reduce scan
3113 * pressure by how much of the total memory used is
3114 * within protection thresholds.
3116 * There is one special case: in the first reclaim pass,
3117 * we skip over all groups that are within their low
3118 * protection. If that fails to reclaim enough pages to
3119 * satisfy the reclaim goal, we come back and override
3120 * the best-effort low protection. However, we still
3121 * ideally want to honor how well-behaved groups are in
3122 * that case instead of simply punishing them all
3123 * equally. As such, we reclaim them based on how much
3124 * memory they are using, reducing the scan pressure
3125 * again by how much of the total memory used is under
3128 unsigned long cgroup_size = mem_cgroup_size(memcg);
3129 unsigned long protection;
3131 /* memory.low scaling, make sure we retry before OOM */
3132 if (!sc->memcg_low_reclaim && low > min) {
3134 sc->memcg_low_skipped = 1;
3139 /* Avoid TOCTOU with earlier protection check */
3140 cgroup_size = max(cgroup_size, protection);
3142 scan = lruvec_size - lruvec_size * protection /
3146 * Minimally target SWAP_CLUSTER_MAX pages to keep
3147 * reclaim moving forwards, avoiding decrementing
3148 * sc->priority further than desirable.
3150 scan = max(scan, SWAP_CLUSTER_MAX);
3155 scan >>= sc->priority;
3158 * If the cgroup's already been deleted, make sure to
3159 * scrape out the remaining cache.
3161 if (!scan && !mem_cgroup_online(memcg))
3162 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
3164 switch (scan_balance) {
3166 /* Scan lists relative to size */
3170 * Scan types proportional to swappiness and
3171 * their relative recent reclaim efficiency.
3172 * Make sure we don't miss the last page on
3173 * the offlined memory cgroups because of a
3176 scan = mem_cgroup_online(memcg) ?
3177 div64_u64(scan * fraction[file], denominator) :
3178 DIV64_U64_ROUND_UP(scan * fraction[file],
3183 /* Scan one type exclusively */
3184 if ((scan_balance == SCAN_FILE) != file)
3188 /* Look ma, no brain */
3197 * Anonymous LRU management is a waste if there is
3198 * ultimately no way to reclaim the memory.
3200 static bool can_age_anon_pages(struct pglist_data *pgdat,
3201 struct scan_control *sc)
3203 /* Aging the anon LRU is valuable if swap is present: */
3204 if (total_swap_pages > 0)
3207 /* Also valuable if anon pages can be demoted: */
3208 return can_demote(pgdat->node_id, sc);
3211 #ifdef CONFIG_LRU_GEN
3213 #ifdef CONFIG_LRU_GEN_ENABLED
3214 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3215 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
3217 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3218 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
3221 /******************************************************************************
3223 ******************************************************************************/
3225 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
3227 #define DEFINE_MAX_SEQ(lruvec) \
3228 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3230 #define DEFINE_MIN_SEQ(lruvec) \
3231 unsigned long min_seq[ANON_AND_FILE] = { \
3232 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3233 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3236 #define for_each_gen_type_zone(gen, type, zone) \
3237 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3238 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3239 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3241 #define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
3242 #define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
3244 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
3246 struct pglist_data *pgdat = NODE_DATA(nid);
3250 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3252 /* see the comment in mem_cgroup_lruvec() */
3254 lruvec->pgdat = pgdat;
3259 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3261 return &pgdat->__lruvec;
3264 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3266 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3267 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3272 if (!can_demote(pgdat->node_id, sc) &&
3273 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3276 return mem_cgroup_swappiness(memcg);
3279 static int get_nr_gens(struct lruvec *lruvec, int type)
3281 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3284 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3286 /* see the comment on lru_gen_folio */
3287 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3288 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3289 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3292 /******************************************************************************
3294 ******************************************************************************/
3297 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3298 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3299 * bits in a bitmap, k is the number of hash functions and n is the number of
3302 * Page table walkers use one of the two filters to reduce their search space.
3303 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3304 * aging uses the double-buffering technique to flip to the other filter each
3305 * time it produces a new generation. For non-leaf entries that have enough
3306 * leaf entries, the aging carries them over to the next generation in
3307 * walk_pmd_range(); the eviction also report them when walking the rmap
3308 * in lru_gen_look_around().
3310 * For future optimizations:
3311 * 1. It's not necessary to keep both filters all the time. The spare one can be
3312 * freed after the RCU grace period and reallocated if needed again.
3313 * 2. And when reallocating, it's worth scaling its size according to the number
3314 * of inserted entries in the other filter, to reduce the memory overhead on
3315 * small systems and false positives on large systems.
3316 * 3. Jenkins' hash function is an alternative to Knuth's.
3318 #define BLOOM_FILTER_SHIFT 15
3320 static inline int filter_gen_from_seq(unsigned long seq)
3322 return seq % NR_BLOOM_FILTERS;
3325 static void get_item_key(void *item, int *key)
3327 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3329 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3331 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3332 key[1] = hash >> BLOOM_FILTER_SHIFT;
3335 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3338 unsigned long *filter;
3339 int gen = filter_gen_from_seq(seq);
3341 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3345 get_item_key(item, key);
3347 return test_bit(key[0], filter) && test_bit(key[1], filter);
3350 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3353 unsigned long *filter;
3354 int gen = filter_gen_from_seq(seq);
3356 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3360 get_item_key(item, key);
3362 if (!test_bit(key[0], filter))
3363 set_bit(key[0], filter);
3364 if (!test_bit(key[1], filter))
3365 set_bit(key[1], filter);
3368 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3370 unsigned long *filter;
3371 int gen = filter_gen_from_seq(seq);
3373 filter = lruvec->mm_state.filters[gen];
3375 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3379 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3380 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3381 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3384 /******************************************************************************
3386 ******************************************************************************/
3388 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3390 static struct lru_gen_mm_list mm_list = {
3391 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3392 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3397 return &memcg->mm_list;
3399 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3404 void lru_gen_add_mm(struct mm_struct *mm)
3407 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3408 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3410 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3412 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3413 mm->lru_gen.memcg = memcg;
3415 spin_lock(&mm_list->lock);
3417 for_each_node_state(nid, N_MEMORY) {
3418 struct lruvec *lruvec = get_lruvec(memcg, nid);
3420 /* the first addition since the last iteration */
3421 if (lruvec->mm_state.tail == &mm_list->fifo)
3422 lruvec->mm_state.tail = &mm->lru_gen.list;
3425 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3427 spin_unlock(&mm_list->lock);
3430 void lru_gen_del_mm(struct mm_struct *mm)
3433 struct lru_gen_mm_list *mm_list;
3434 struct mem_cgroup *memcg = NULL;
3436 if (list_empty(&mm->lru_gen.list))
3440 memcg = mm->lru_gen.memcg;
3442 mm_list = get_mm_list(memcg);
3444 spin_lock(&mm_list->lock);
3446 for_each_node(nid) {
3447 struct lruvec *lruvec = get_lruvec(memcg, nid);
3449 /* where the current iteration continues after */
3450 if (lruvec->mm_state.head == &mm->lru_gen.list)
3451 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3453 /* where the last iteration ended before */
3454 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3455 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3458 list_del_init(&mm->lru_gen.list);
3460 spin_unlock(&mm_list->lock);
3463 mem_cgroup_put(mm->lru_gen.memcg);
3464 mm->lru_gen.memcg = NULL;
3469 void lru_gen_migrate_mm(struct mm_struct *mm)
3471 struct mem_cgroup *memcg;
3472 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3474 VM_WARN_ON_ONCE(task->mm != mm);
3475 lockdep_assert_held(&task->alloc_lock);
3477 /* for mm_update_next_owner() */
3478 if (mem_cgroup_disabled())
3481 /* migration can happen before addition */
3482 if (!mm->lru_gen.memcg)
3486 memcg = mem_cgroup_from_task(task);
3488 if (memcg == mm->lru_gen.memcg)
3491 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3498 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3503 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3506 hist = lru_hist_from_seq(walk->max_seq);
3508 for (i = 0; i < NR_MM_STATS; i++) {
3509 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3510 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3511 walk->mm_stats[i] = 0;
3515 if (NR_HIST_GENS > 1 && last) {
3516 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3518 for (i = 0; i < NR_MM_STATS; i++)
3519 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3523 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3526 unsigned long size = 0;
3527 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3528 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3530 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3533 clear_bit(key, &mm->lru_gen.bitmap);
3535 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3536 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3537 get_mm_counter(mm, MM_ANONPAGES) +
3538 get_mm_counter(mm, MM_SHMEMPAGES);
3541 if (size < MIN_LRU_BATCH)
3544 return !mmget_not_zero(mm);
3547 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3548 struct mm_struct **iter)
3552 struct mm_struct *mm = NULL;
3553 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3554 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3555 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3558 * mm_state->seq is incremented after each iteration of mm_list. There
3559 * are three interesting cases for this page table walker:
3560 * 1. It tries to start a new iteration with a stale max_seq: there is
3561 * nothing left to do.
3562 * 2. It started the next iteration: it needs to reset the Bloom filter
3563 * so that a fresh set of PTE tables can be recorded.
3564 * 3. It ended the current iteration: it needs to reset the mm stats
3565 * counters and tell its caller to increment max_seq.
3567 spin_lock(&mm_list->lock);
3569 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3571 if (walk->max_seq <= mm_state->seq)
3574 if (!mm_state->head)
3575 mm_state->head = &mm_list->fifo;
3577 if (mm_state->head == &mm_list->fifo)
3581 mm_state->head = mm_state->head->next;
3582 if (mm_state->head == &mm_list->fifo) {
3583 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3588 /* force scan for those added after the last iteration */
3589 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3590 mm_state->tail = mm_state->head->next;
3591 walk->force_scan = true;
3594 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3595 if (should_skip_mm(mm, walk))
3600 reset_mm_stats(lruvec, walk, last);
3602 spin_unlock(&mm_list->lock);
3605 reset_bloom_filter(lruvec, walk->max_seq + 1);
3615 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3617 bool success = false;
3618 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3619 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3620 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3622 spin_lock(&mm_list->lock);
3624 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3626 if (max_seq > mm_state->seq) {
3627 mm_state->head = NULL;
3628 mm_state->tail = NULL;
3629 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3630 reset_mm_stats(lruvec, NULL, true);
3634 spin_unlock(&mm_list->lock);
3639 /******************************************************************************
3641 ******************************************************************************/
3644 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3646 * The P term is refaulted/(evicted+protected) from a tier in the generation
3647 * currently being evicted; the I term is the exponential moving average of the
3648 * P term over the generations previously evicted, using the smoothing factor
3649 * 1/2; the D term isn't supported.
3651 * The setpoint (SP) is always the first tier of one type; the process variable
3652 * (PV) is either any tier of the other type or any other tier of the same
3655 * The error is the difference between the SP and the PV; the correction is to
3656 * turn off protection when SP>PV or turn on protection when SP<PV.
3658 * For future optimizations:
3659 * 1. The D term may discount the other two terms over time so that long-lived
3660 * generations can resist stale information.
3663 unsigned long refaulted;
3664 unsigned long total;
3668 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3669 struct ctrl_pos *pos)
3671 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3672 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3674 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3675 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3676 pos->total = lrugen->avg_total[type][tier] +
3677 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3679 pos->total += lrugen->protected[hist][type][tier - 1];
3683 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3686 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3687 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3688 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3690 lockdep_assert_held(&lruvec->lru_lock);
3692 if (!carryover && !clear)
3695 hist = lru_hist_from_seq(seq);
3697 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3701 sum = lrugen->avg_refaulted[type][tier] +
3702 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3703 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3705 sum = lrugen->avg_total[type][tier] +
3706 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3708 sum += lrugen->protected[hist][type][tier - 1];
3709 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3713 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3714 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3716 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3721 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3724 * Return true if the PV has a limited number of refaults or a lower
3725 * refaulted/total than the SP.
3727 return pv->refaulted < MIN_LRU_BATCH ||
3728 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3729 (sp->refaulted + 1) * pv->total * pv->gain;
3732 /******************************************************************************
3734 ******************************************************************************/
3736 /* promote pages accessed through page tables */
3737 static int folio_update_gen(struct folio *folio, int gen)
3739 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3741 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3742 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3745 /* lru_gen_del_folio() has isolated this page? */
3746 if (!(old_flags & LRU_GEN_MASK)) {
3747 /* for shrink_folio_list() */
3748 new_flags = old_flags | BIT(PG_referenced);
3752 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3753 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3754 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3756 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3759 /* protect pages accessed multiple times through file descriptors */
3760 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3762 int type = folio_is_file_lru(folio);
3763 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3764 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3765 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3767 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3770 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3771 /* folio_update_gen() has promoted this page? */
3772 if (new_gen >= 0 && new_gen != old_gen)
3775 new_gen = (old_gen + 1) % MAX_NR_GENS;
3777 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3778 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3779 /* for folio_end_writeback() */
3781 new_flags |= BIT(PG_reclaim);
3782 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3784 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3789 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3790 int old_gen, int new_gen)
3792 int type = folio_is_file_lru(folio);
3793 int zone = folio_zonenum(folio);
3794 int delta = folio_nr_pages(folio);
3796 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3797 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3801 walk->nr_pages[old_gen][type][zone] -= delta;
3802 walk->nr_pages[new_gen][type][zone] += delta;
3805 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3807 int gen, type, zone;
3808 struct lru_gen_folio *lrugen = &lruvec->lrugen;
3812 for_each_gen_type_zone(gen, type, zone) {
3813 enum lru_list lru = type * LRU_INACTIVE_FILE;
3814 int delta = walk->nr_pages[gen][type][zone];
3819 walk->nr_pages[gen][type][zone] = 0;
3820 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3821 lrugen->nr_pages[gen][type][zone] + delta);
3823 if (lru_gen_is_active(lruvec, gen))
3825 __update_lru_size(lruvec, lru, zone, delta);
3829 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3831 struct address_space *mapping;
3832 struct vm_area_struct *vma = args->vma;
3833 struct lru_gen_mm_walk *walk = args->private;
3835 if (!vma_is_accessible(vma))
3838 if (is_vm_hugetlb_page(vma))
3841 if (!vma_has_recency(vma))
3844 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
3847 if (vma == get_gate_vma(vma->vm_mm))
3850 if (vma_is_anonymous(vma))
3851 return !walk->can_swap;
3853 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3856 mapping = vma->vm_file->f_mapping;
3857 if (mapping_unevictable(mapping))
3860 if (shmem_mapping(mapping))
3861 return !walk->can_swap;
3863 /* to exclude special mappings like dax, etc. */
3864 return !mapping->a_ops->read_folio;
3868 * Some userspace memory allocators map many single-page VMAs. Instead of
3869 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3870 * table to reduce zigzags and improve cache performance.
3872 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3873 unsigned long *vm_start, unsigned long *vm_end)
3875 unsigned long start = round_up(*vm_end, size);
3876 unsigned long end = (start | ~mask) + 1;
3877 VMA_ITERATOR(vmi, args->mm, start);
3879 VM_WARN_ON_ONCE(mask & size);
3880 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3882 for_each_vma(vmi, args->vma) {
3883 if (end && end <= args->vma->vm_start)
3886 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3889 *vm_start = max(start, args->vma->vm_start);
3890 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3898 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3900 unsigned long pfn = pte_pfn(pte);
3902 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3904 if (!pte_present(pte) || is_zero_pfn(pfn))
3907 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3910 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3916 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3917 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3919 unsigned long pfn = pmd_pfn(pmd);
3921 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3923 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3926 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3929 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3936 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3937 struct pglist_data *pgdat, bool can_swap)
3939 struct folio *folio;
3941 /* try to avoid unnecessary memory loads */
3942 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3945 folio = pfn_folio(pfn);
3946 if (folio_nid(folio) != pgdat->node_id)
3949 if (folio_memcg_rcu(folio) != memcg)
3952 /* file VMAs can contain anon pages from COW */
3953 if (!folio_is_file_lru(folio) && !can_swap)
3959 static bool suitable_to_scan(int total, int young)
3961 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3963 /* suitable if the average number of young PTEs per cacheline is >=1 */
3964 return young * n >= total;
3967 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3968 struct mm_walk *args)
3976 struct lru_gen_mm_walk *walk = args->private;
3977 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3978 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3979 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3981 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3983 ptl = pte_lockptr(args->mm, pmd);
3984 if (!spin_trylock(ptl))
3987 arch_enter_lazy_mmu_mode();
3989 pte = pte_offset_map(pmd, start & PMD_MASK);
3991 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3993 struct folio *folio;
3996 walk->mm_stats[MM_LEAF_TOTAL]++;
3998 pfn = get_pte_pfn(pte[i], args->vma, addr);
4002 if (!pte_young(pte[i])) {
4003 walk->mm_stats[MM_LEAF_OLD]++;
4007 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4011 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
4012 VM_WARN_ON_ONCE(true);
4015 walk->mm_stats[MM_LEAF_YOUNG]++;
4017 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4018 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4019 !folio_test_swapcache(folio)))
4020 folio_mark_dirty(folio);
4022 old_gen = folio_update_gen(folio, new_gen);
4023 if (old_gen >= 0 && old_gen != new_gen)
4024 update_batch_size(walk, folio, old_gen, new_gen);
4027 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
4032 arch_leave_lazy_mmu_mode();
4035 return suitable_to_scan(total, young);
4038 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
4039 static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
4040 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
4045 struct lru_gen_mm_walk *walk = args->private;
4046 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
4047 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4048 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
4050 VM_WARN_ON_ONCE(pud_leaf(*pud));
4052 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
4055 bitmap_zero(bitmap, MIN_LRU_BATCH);
4059 i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
4060 if (i && i <= MIN_LRU_BATCH) {
4061 __set_bit(i - 1, bitmap);
4065 pmd = pmd_offset(pud, *first);
4067 ptl = pmd_lockptr(args->mm, pmd);
4068 if (!spin_trylock(ptl))
4071 arch_enter_lazy_mmu_mode();
4075 struct folio *folio;
4077 /* don't round down the first address */
4078 addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
4080 pfn = get_pmd_pfn(pmd[i], vma, addr);
4084 if (!pmd_trans_huge(pmd[i])) {
4085 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
4086 pmdp_test_and_clear_young(vma, addr, pmd + i);
4090 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4094 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
4097 walk->mm_stats[MM_LEAF_YOUNG]++;
4099 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
4100 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4101 !folio_test_swapcache(folio)))
4102 folio_mark_dirty(folio);
4104 old_gen = folio_update_gen(folio, new_gen);
4105 if (old_gen >= 0 && old_gen != new_gen)
4106 update_batch_size(walk, folio, old_gen, new_gen);
4108 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
4109 } while (i <= MIN_LRU_BATCH);
4111 arch_leave_lazy_mmu_mode();
4117 static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
4118 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
4123 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
4124 struct mm_walk *args)
4130 struct vm_area_struct *vma;
4131 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)];
4132 unsigned long first = -1;
4133 struct lru_gen_mm_walk *walk = args->private;
4135 VM_WARN_ON_ONCE(pud_leaf(*pud));
4138 * Finish an entire PMD in two passes: the first only reaches to PTE
4139 * tables to avoid taking the PMD lock; the second, if necessary, takes
4140 * the PMD lock to clear the accessed bit in PMD entries.
4142 pmd = pmd_offset(pud, start & PUD_MASK);
4144 /* walk_pte_range() may call get_next_vma() */
4146 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
4147 pmd_t val = pmdp_get_lockless(pmd + i);
4149 next = pmd_addr_end(addr, end);
4151 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4152 walk->mm_stats[MM_LEAF_TOTAL]++;
4156 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4157 if (pmd_trans_huge(val)) {
4158 unsigned long pfn = pmd_pfn(val);
4159 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4161 walk->mm_stats[MM_LEAF_TOTAL]++;
4163 if (!pmd_young(val)) {
4164 walk->mm_stats[MM_LEAF_OLD]++;
4168 /* try to avoid unnecessary memory loads */
4169 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4172 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
4176 walk->mm_stats[MM_NONLEAF_TOTAL]++;
4178 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG)) {
4179 if (!pmd_young(val))
4182 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
4185 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4188 walk->mm_stats[MM_NONLEAF_FOUND]++;
4190 if (!walk_pte_range(&val, addr, next, args))
4193 walk->mm_stats[MM_NONLEAF_ADDED]++;
4195 /* carry over to the next generation */
4196 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4199 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
4201 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4205 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4206 struct mm_walk *args)
4212 struct lru_gen_mm_walk *walk = args->private;
4214 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4216 pud = pud_offset(p4d, start & P4D_MASK);
4218 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4219 pud_t val = READ_ONCE(pud[i]);
4221 next = pud_addr_end(addr, end);
4223 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4226 walk_pmd_range(&val, addr, next, args);
4228 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4229 end = (addr | ~PUD_MASK) + 1;
4234 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4237 end = round_up(end, P4D_SIZE);
4239 if (!end || !args->vma)
4242 walk->next_addr = max(end, args->vma->vm_start);
4247 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4249 static const struct mm_walk_ops mm_walk_ops = {
4250 .test_walk = should_skip_vma,
4251 .p4d_entry = walk_pud_range,
4255 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4257 walk->next_addr = FIRST_USER_ADDRESS;
4260 DEFINE_MAX_SEQ(lruvec);
4264 /* another thread might have called inc_max_seq() */
4265 if (walk->max_seq != max_seq)
4268 /* folio_update_gen() requires stable folio_memcg() */
4269 if (!mem_cgroup_trylock_pages(memcg))
4272 /* the caller might be holding the lock for write */
4273 if (mmap_read_trylock(mm)) {
4274 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4276 mmap_read_unlock(mm);
4279 mem_cgroup_unlock_pages();
4281 if (walk->batched) {
4282 spin_lock_irq(&lruvec->lru_lock);
4283 reset_batch_size(lruvec, walk);
4284 spin_unlock_irq(&lruvec->lru_lock);
4288 } while (err == -EAGAIN);
4291 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
4293 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4295 if (pgdat && current_is_kswapd()) {
4296 VM_WARN_ON_ONCE(walk);
4298 walk = &pgdat->mm_walk;
4299 } else if (!walk && force_alloc) {
4300 VM_WARN_ON_ONCE(current_is_kswapd());
4302 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4305 current->reclaim_state->mm_walk = walk;
4310 static void clear_mm_walk(void)
4312 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4314 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4315 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4317 current->reclaim_state->mm_walk = NULL;
4319 if (!current_is_kswapd())
4323 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4326 int remaining = MAX_LRU_BATCH;
4327 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4328 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4330 if (type == LRU_GEN_ANON && !can_swap)
4333 /* prevent cold/hot inversion if force_scan is true */
4334 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4335 struct list_head *head = &lrugen->folios[old_gen][type][zone];
4337 while (!list_empty(head)) {
4338 struct folio *folio = lru_to_folio(head);
4340 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4341 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4342 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4343 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4345 new_gen = folio_inc_gen(lruvec, folio, false);
4346 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
4353 reset_ctrl_pos(lruvec, type, true);
4354 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4359 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4361 int gen, type, zone;
4362 bool success = false;
4363 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4364 DEFINE_MIN_SEQ(lruvec);
4366 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4368 /* find the oldest populated generation */
4369 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4370 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4371 gen = lru_gen_from_seq(min_seq[type]);
4373 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4374 if (!list_empty(&lrugen->folios[gen][type][zone]))
4384 /* see the comment on lru_gen_folio */
4386 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4387 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4390 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4391 if (min_seq[type] == lrugen->min_seq[type])
4394 reset_ctrl_pos(lruvec, type, true);
4395 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4402 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4406 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4408 spin_lock_irq(&lruvec->lru_lock);
4410 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4412 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4413 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4416 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4418 while (!inc_min_seq(lruvec, type, can_swap)) {
4419 spin_unlock_irq(&lruvec->lru_lock);
4421 spin_lock_irq(&lruvec->lru_lock);
4426 * Update the active/inactive LRU sizes for compatibility. Both sides of
4427 * the current max_seq need to be covered, since max_seq+1 can overlap
4428 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4429 * overlap, cold/hot inversion happens.
4431 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4432 next = lru_gen_from_seq(lrugen->max_seq + 1);
4434 for (type = 0; type < ANON_AND_FILE; type++) {
4435 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4436 enum lru_list lru = type * LRU_INACTIVE_FILE;
4437 long delta = lrugen->nr_pages[prev][type][zone] -
4438 lrugen->nr_pages[next][type][zone];
4443 __update_lru_size(lruvec, lru, zone, delta);
4444 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4448 for (type = 0; type < ANON_AND_FILE; type++)
4449 reset_ctrl_pos(lruvec, type, false);
4451 WRITE_ONCE(lrugen->timestamps[next], jiffies);
4452 /* make sure preceding modifications appear */
4453 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4455 spin_unlock_irq(&lruvec->lru_lock);
4458 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4459 struct scan_control *sc, bool can_swap, bool force_scan)
4462 struct lru_gen_mm_walk *walk;
4463 struct mm_struct *mm = NULL;
4464 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4466 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4468 /* see the comment in iterate_mm_list() */
4469 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4475 * If the hardware doesn't automatically set the accessed bit, fallback
4476 * to lru_gen_look_around(), which only clears the accessed bit in a
4477 * handful of PTEs. Spreading the work out over a period of time usually
4478 * is less efficient, but it avoids bursty page faults.
4480 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
4481 success = iterate_mm_list_nowalk(lruvec, max_seq);
4485 walk = set_mm_walk(NULL, true);
4487 success = iterate_mm_list_nowalk(lruvec, max_seq);
4491 walk->lruvec = lruvec;
4492 walk->max_seq = max_seq;
4493 walk->can_swap = can_swap;
4494 walk->force_scan = force_scan;
4497 success = iterate_mm_list(lruvec, walk, &mm);
4499 walk_mm(lruvec, mm, walk);
4503 inc_max_seq(lruvec, can_swap, force_scan);
4508 /******************************************************************************
4509 * working set protection
4510 ******************************************************************************/
4512 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
4514 int gen, type, zone;
4515 unsigned long total = 0;
4516 bool can_swap = get_swappiness(lruvec, sc);
4517 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4518 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4519 DEFINE_MAX_SEQ(lruvec);
4520 DEFINE_MIN_SEQ(lruvec);
4522 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4525 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4526 gen = lru_gen_from_seq(seq);
4528 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4529 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4533 /* whether the size is big enough to be helpful */
4534 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4537 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4538 unsigned long min_ttl)
4541 unsigned long birth;
4542 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4543 DEFINE_MIN_SEQ(lruvec);
4545 /* see the comment on lru_gen_folio */
4546 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4547 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4549 if (time_is_after_jiffies(birth + min_ttl))
4552 if (!lruvec_is_sizable(lruvec, sc))
4555 mem_cgroup_calculate_protection(NULL, memcg);
4557 return !mem_cgroup_below_min(NULL, memcg);
4560 /* to protect the working set of the last N jiffies */
4561 static unsigned long lru_gen_min_ttl __read_mostly;
4563 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4565 struct mem_cgroup *memcg;
4566 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4568 VM_WARN_ON_ONCE(!current_is_kswapd());
4570 /* check the order to exclude compaction-induced reclaim */
4571 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
4574 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4576 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4578 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4579 mem_cgroup_iter_break(NULL, memcg);
4584 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4587 * The main goal is to OOM kill if every generation from all memcgs is
4588 * younger than min_ttl. However, another possibility is all memcgs are
4589 * either too small or below min.
4591 if (mutex_trylock(&oom_lock)) {
4592 struct oom_control oc = {
4593 .gfp_mask = sc->gfp_mask,
4598 mutex_unlock(&oom_lock);
4602 /******************************************************************************
4603 * rmap/PT walk feedback
4604 ******************************************************************************/
4607 * This function exploits spatial locality when shrink_folio_list() walks the
4608 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4609 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4610 * the PTE table to the Bloom filter. This forms a feedback loop between the
4611 * eviction and the aging.
4613 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4616 unsigned long start;
4618 struct lru_gen_mm_walk *walk;
4620 pte_t *pte = pvmw->pte;
4621 unsigned long addr = pvmw->address;
4622 struct folio *folio = pfn_folio(pvmw->pfn);
4623 struct mem_cgroup *memcg = folio_memcg(folio);
4624 struct pglist_data *pgdat = folio_pgdat(folio);
4625 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4626 DEFINE_MAX_SEQ(lruvec);
4627 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4629 lockdep_assert_held(pvmw->ptl);
4630 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4632 if (spin_is_contended(pvmw->ptl))
4635 /* avoid taking the LRU lock under the PTL when possible */
4636 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4638 start = max(addr & PMD_MASK, pvmw->vma->vm_start);
4639 end = min(addr | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4641 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4642 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4643 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4644 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
4645 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4647 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4648 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
4652 /* folio_update_gen() requires stable folio_memcg() */
4653 if (!mem_cgroup_trylock_pages(memcg))
4656 arch_enter_lazy_mmu_mode();
4658 pte -= (addr - start) / PAGE_SIZE;
4660 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4663 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4667 if (!pte_young(pte[i]))
4670 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4674 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4675 VM_WARN_ON_ONCE(true);
4679 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4680 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4681 !folio_test_swapcache(folio)))
4682 folio_mark_dirty(folio);
4685 old_gen = folio_update_gen(folio, new_gen);
4686 if (old_gen >= 0 && old_gen != new_gen)
4687 update_batch_size(walk, folio, old_gen, new_gen);
4692 old_gen = folio_lru_gen(folio);
4694 folio_set_referenced(folio);
4695 else if (old_gen != new_gen)
4696 folio_activate(folio);
4699 arch_leave_lazy_mmu_mode();
4700 mem_cgroup_unlock_pages();
4702 /* feedback from rmap walkers to page table walkers */
4703 if (suitable_to_scan(i, young))
4704 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4707 /******************************************************************************
4709 ******************************************************************************/
4711 /* see the comment on MEMCG_NR_GENS */
4722 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4724 return READ_ONCE(lruvec->lrugen.seg);
4727 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4731 int bin = get_random_u32_below(MEMCG_NR_BINS);
4732 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4734 spin_lock(&pgdat->memcg_lru.lock);
4736 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4739 new = old = lruvec->lrugen.gen;
4741 /* see the comment on MEMCG_NR_GENS */
4742 if (op == MEMCG_LRU_HEAD)
4743 seg = MEMCG_LRU_HEAD;
4744 else if (op == MEMCG_LRU_TAIL)
4745 seg = MEMCG_LRU_TAIL;
4746 else if (op == MEMCG_LRU_OLD)
4747 new = get_memcg_gen(pgdat->memcg_lru.seq);
4748 else if (op == MEMCG_LRU_YOUNG)
4749 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4751 VM_WARN_ON_ONCE(true);
4753 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4755 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4756 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4758 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4760 pgdat->memcg_lru.nr_memcgs[old]--;
4761 pgdat->memcg_lru.nr_memcgs[new]++;
4763 lruvec->lrugen.gen = new;
4764 WRITE_ONCE(lruvec->lrugen.seg, seg);
4766 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4767 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4769 spin_unlock(&pgdat->memcg_lru.lock);
4772 void lru_gen_online_memcg(struct mem_cgroup *memcg)
4776 int bin = get_random_u32_below(MEMCG_NR_BINS);
4778 for_each_node(nid) {
4779 struct pglist_data *pgdat = NODE_DATA(nid);
4780 struct lruvec *lruvec = get_lruvec(memcg, nid);
4782 spin_lock(&pgdat->memcg_lru.lock);
4784 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4786 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4788 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4789 pgdat->memcg_lru.nr_memcgs[gen]++;
4791 lruvec->lrugen.gen = gen;
4793 spin_unlock(&pgdat->memcg_lru.lock);
4797 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4801 for_each_node(nid) {
4802 struct lruvec *lruvec = get_lruvec(memcg, nid);
4804 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4808 void lru_gen_release_memcg(struct mem_cgroup *memcg)
4813 for_each_node(nid) {
4814 struct pglist_data *pgdat = NODE_DATA(nid);
4815 struct lruvec *lruvec = get_lruvec(memcg, nid);
4817 spin_lock(&pgdat->memcg_lru.lock);
4819 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4821 gen = lruvec->lrugen.gen;
4823 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4824 pgdat->memcg_lru.nr_memcgs[gen]--;
4826 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4827 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4829 spin_unlock(&pgdat->memcg_lru.lock);
4833 void lru_gen_soft_reclaim(struct lruvec *lruvec)
4835 /* see the comment on MEMCG_NR_GENS */
4836 if (lru_gen_memcg_seg(lruvec) != MEMCG_LRU_HEAD)
4837 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4840 #else /* !CONFIG_MEMCG */
4842 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4849 /******************************************************************************
4851 ******************************************************************************/
4853 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4856 int gen = folio_lru_gen(folio);
4857 int type = folio_is_file_lru(folio);
4858 int zone = folio_zonenum(folio);
4859 int delta = folio_nr_pages(folio);
4860 int refs = folio_lru_refs(folio);
4861 int tier = lru_tier_from_refs(refs);
4862 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4864 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4867 if (!folio_evictable(folio)) {
4868 success = lru_gen_del_folio(lruvec, folio, true);
4869 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4870 folio_set_unevictable(folio);
4871 lruvec_add_folio(lruvec, folio);
4872 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4876 /* dirty lazyfree */
4877 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4878 success = lru_gen_del_folio(lruvec, folio, true);
4879 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4880 folio_set_swapbacked(folio);
4881 lruvec_add_folio_tail(lruvec, folio);
4886 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4887 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4892 if (tier > tier_idx) {
4893 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4895 gen = folio_inc_gen(lruvec, folio, false);
4896 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4898 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4899 lrugen->protected[hist][type][tier - 1] + delta);
4900 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4904 /* waiting for writeback */
4905 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4906 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4907 gen = folio_inc_gen(lruvec, folio, true);
4908 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4915 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4919 /* swapping inhibited */
4920 if (!(sc->gfp_mask & __GFP_IO) &&
4921 (folio_test_dirty(folio) ||
4922 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4925 /* raced with release_pages() */
4926 if (!folio_try_get(folio))
4929 /* raced with another isolation */
4930 if (!folio_test_clear_lru(folio)) {
4935 /* see the comment on MAX_NR_TIERS */
4936 if (!folio_test_referenced(folio))
4937 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4939 /* for shrink_folio_list() */
4940 folio_clear_reclaim(folio);
4941 folio_clear_referenced(folio);
4943 success = lru_gen_del_folio(lruvec, folio, true);
4944 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4949 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4950 int type, int tier, struct list_head *list)
4953 enum vm_event_item item;
4957 int remaining = MAX_LRU_BATCH;
4958 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4959 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4961 VM_WARN_ON_ONCE(!list_empty(list));
4963 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4966 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4968 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4971 struct list_head *head = &lrugen->folios[gen][type][zone];
4973 while (!list_empty(head)) {
4974 struct folio *folio = lru_to_folio(head);
4975 int delta = folio_nr_pages(folio);
4977 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4978 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4979 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4980 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4984 if (sort_folio(lruvec, folio, tier))
4986 else if (isolate_folio(lruvec, folio, sc)) {
4987 list_add(&folio->lru, list);
4990 list_move(&folio->lru, &moved);
4994 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4999 list_splice(&moved, head);
5000 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
5003 if (!remaining || isolated >= MIN_LRU_BATCH)
5007 item = PGSCAN_KSWAPD + reclaimer_offset();
5008 if (!cgroup_reclaim(sc)) {
5009 __count_vm_events(item, isolated);
5010 __count_vm_events(PGREFILL, sorted);
5012 __count_memcg_events(memcg, item, isolated);
5013 __count_memcg_events(memcg, PGREFILL, sorted);
5014 __count_vm_events(PGSCAN_ANON + type, isolated);
5017 * There might not be eligible folios due to reclaim_idx. Check the
5018 * remaining to prevent livelock if it's not making progress.
5020 return isolated || !remaining ? scanned : 0;
5023 static int get_tier_idx(struct lruvec *lruvec, int type)
5026 struct ctrl_pos sp, pv;
5029 * To leave a margin for fluctuations, use a larger gain factor (1:2).
5030 * This value is chosen because any other tier would have at least twice
5031 * as many refaults as the first tier.
5033 read_ctrl_pos(lruvec, type, 0, 1, &sp);
5034 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5035 read_ctrl_pos(lruvec, type, tier, 2, &pv);
5036 if (!positive_ctrl_err(&sp, &pv))
5043 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
5046 struct ctrl_pos sp, pv;
5047 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
5050 * Compare the first tier of anon with that of file to determine which
5051 * type to scan. Also need to compare other tiers of the selected type
5052 * with the first tier of the other type to determine the last tier (of
5053 * the selected type) to evict.
5055 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
5056 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
5057 type = positive_ctrl_err(&sp, &pv);
5059 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
5060 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5061 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
5062 if (!positive_ctrl_err(&sp, &pv))
5066 *tier_idx = tier - 1;
5071 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
5072 int *type_scanned, struct list_head *list)
5078 DEFINE_MIN_SEQ(lruvec);
5081 * Try to make the obvious choice first. When anon and file are both
5082 * available from the same generation, interpret swappiness 1 as file
5083 * first and 200 as anon first.
5086 type = LRU_GEN_FILE;
5087 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
5088 type = LRU_GEN_ANON;
5089 else if (swappiness == 1)
5090 type = LRU_GEN_FILE;
5091 else if (swappiness == 200)
5092 type = LRU_GEN_ANON;
5094 type = get_type_to_scan(lruvec, swappiness, &tier);
5096 for (i = !swappiness; i < ANON_AND_FILE; i++) {
5098 tier = get_tier_idx(lruvec, type);
5100 scanned = scan_folios(lruvec, sc, type, tier, list);
5108 *type_scanned = type;
5113 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
5120 struct folio *folio;
5122 enum vm_event_item item;
5123 struct reclaim_stat stat;
5124 struct lru_gen_mm_walk *walk;
5125 bool skip_retry = false;
5126 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5127 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5129 spin_lock_irq(&lruvec->lru_lock);
5131 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5133 scanned += try_to_inc_min_seq(lruvec, swappiness);
5135 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5138 spin_unlock_irq(&lruvec->lru_lock);
5140 if (list_empty(&list))
5143 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5144 sc->nr_reclaimed += reclaimed;
5146 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5147 if (!folio_evictable(folio)) {
5148 list_del(&folio->lru);
5149 folio_putback_lru(folio);
5153 if (folio_test_reclaim(folio) &&
5154 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5155 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5156 if (folio_test_workingset(folio))
5157 folio_set_referenced(folio);
5161 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5162 folio_mapped(folio) || folio_test_locked(folio) ||
5163 folio_test_dirty(folio) || folio_test_writeback(folio)) {
5164 /* don't add rejected folios to the oldest generation */
5165 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5170 /* retry folios that may have missed folio_rotate_reclaimable() */
5171 list_move(&folio->lru, &clean);
5172 sc->nr_scanned -= folio_nr_pages(folio);
5175 spin_lock_irq(&lruvec->lru_lock);
5177 move_folios_to_lru(lruvec, &list);
5179 walk = current->reclaim_state->mm_walk;
5180 if (walk && walk->batched)
5181 reset_batch_size(lruvec, walk);
5183 item = PGSTEAL_KSWAPD + reclaimer_offset();
5184 if (!cgroup_reclaim(sc))
5185 __count_vm_events(item, reclaimed);
5186 __count_memcg_events(memcg, item, reclaimed);
5187 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5189 spin_unlock_irq(&lruvec->lru_lock);
5191 mem_cgroup_uncharge_list(&list);
5192 free_unref_page_list(&list);
5194 INIT_LIST_HEAD(&list);
5195 list_splice_init(&clean, &list);
5197 if (!list_empty(&list)) {
5205 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
5206 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
5208 int gen, type, zone;
5209 unsigned long old = 0;
5210 unsigned long young = 0;
5211 unsigned long total = 0;
5212 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5213 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5214 DEFINE_MIN_SEQ(lruvec);
5216 /* whether this lruvec is completely out of cold folios */
5217 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
5222 for (type = !can_swap; type < ANON_AND_FILE; type++) {
5225 for (seq = min_seq[type]; seq <= max_seq; seq++) {
5226 unsigned long size = 0;
5228 gen = lru_gen_from_seq(seq);
5230 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5231 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5236 else if (seq + MIN_NR_GENS == max_seq)
5241 /* try to scrape all its memory if this memcg was deleted */
5242 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
5245 * The aging tries to be lazy to reduce the overhead, while the eviction
5246 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
5247 * ideal number of generations is MIN_NR_GENS+1.
5249 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
5253 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
5254 * of the total number of pages for each generation. A reasonable range
5255 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
5256 * aging cares about the upper bound of hot pages, while the eviction
5257 * cares about the lower bound of cold pages.
5259 if (young * MIN_NR_GENS > total)
5261 if (old * (MIN_NR_GENS + 2) < total)
5268 * For future optimizations:
5269 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5272 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
5274 unsigned long nr_to_scan;
5275 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5276 DEFINE_MAX_SEQ(lruvec);
5278 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
5281 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
5284 /* skip the aging path at the default priority */
5285 if (sc->priority == DEF_PRIORITY)
5288 /* skip this lruvec as it's low on cold folios */
5289 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
5292 static unsigned long get_nr_to_reclaim(struct scan_control *sc)
5294 /* don't abort memcg reclaim to ensure fairness */
5295 if (!global_reclaim(sc))
5298 return max(sc->nr_to_reclaim, compact_gap(sc->order));
5301 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5304 unsigned long scanned = 0;
5305 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5306 int swappiness = get_swappiness(lruvec, sc);
5308 /* clean file folios are more likely to exist */
5309 if (swappiness && !(sc->gfp_mask & __GFP_IO))
5315 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
5316 if (nr_to_scan <= 0)
5319 delta = evict_folios(lruvec, sc, swappiness);
5324 if (scanned >= nr_to_scan)
5327 if (sc->nr_reclaimed >= nr_to_reclaim)
5333 /* whether try_to_inc_max_seq() was successful */
5334 return nr_to_scan < 0;
5337 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
5340 unsigned long scanned = sc->nr_scanned;
5341 unsigned long reclaimed = sc->nr_reclaimed;
5342 int seg = lru_gen_memcg_seg(lruvec);
5343 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5344 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5346 /* see the comment on MEMCG_NR_GENS */
5347 if (!lruvec_is_sizable(lruvec, sc))
5348 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5350 mem_cgroup_calculate_protection(NULL, memcg);
5352 if (mem_cgroup_below_min(NULL, memcg))
5353 return MEMCG_LRU_YOUNG;
5355 if (mem_cgroup_below_low(NULL, memcg)) {
5356 /* see the comment on MEMCG_NR_GENS */
5357 if (seg != MEMCG_LRU_TAIL)
5358 return MEMCG_LRU_TAIL;
5360 memcg_memory_event(memcg, MEMCG_LOW);
5363 success = try_to_shrink_lruvec(lruvec, sc);
5365 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5368 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5369 sc->nr_reclaimed - reclaimed);
5371 flush_reclaim_state(sc);
5373 return success ? MEMCG_LRU_YOUNG : 0;
5378 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5384 struct lruvec *lruvec;
5385 struct lru_gen_folio *lrugen;
5386 struct mem_cgroup *memcg;
5387 const struct hlist_nulls_node *pos;
5388 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5390 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
5394 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5398 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5400 lru_gen_rotate_memcg(lruvec, op);
5402 mem_cgroup_put(memcg);
5404 lruvec = container_of(lrugen, struct lruvec, lrugen);
5405 memcg = lruvec_memcg(lruvec);
5407 if (!mem_cgroup_tryget(memcg)) {
5415 op = shrink_one(lruvec, sc);
5419 if (sc->nr_reclaimed >= nr_to_reclaim)
5426 lru_gen_rotate_memcg(lruvec, op);
5428 mem_cgroup_put(memcg);
5430 if (sc->nr_reclaimed >= nr_to_reclaim)
5433 /* restart if raced with lru_gen_rotate_memcg() */
5434 if (gen != get_nulls_value(pos))
5437 /* try the rest of the bins of the current generation */
5438 bin = get_memcg_bin(bin + 1);
5439 if (bin != first_bin)
5443 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5445 struct blk_plug plug;
5447 VM_WARN_ON_ONCE(global_reclaim(sc));
5448 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
5452 blk_start_plug(&plug);
5454 set_mm_walk(NULL, sc->proactive);
5456 if (try_to_shrink_lruvec(lruvec, sc))
5457 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5461 blk_finish_plug(&plug);
5464 #else /* !CONFIG_MEMCG */
5466 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5471 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5478 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5481 unsigned long reclaimable;
5482 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5484 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5487 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5488 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5489 * estimated reclaimed_to_scanned_ratio = inactive / total.
5491 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5492 if (get_swappiness(lruvec, sc))
5493 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5495 reclaimable /= MEMCG_NR_GENS;
5497 /* round down reclaimable and round up sc->nr_to_reclaim */
5498 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5500 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5503 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5505 struct blk_plug plug;
5506 unsigned long reclaimed = sc->nr_reclaimed;
5508 VM_WARN_ON_ONCE(!global_reclaim(sc));
5511 * Unmapped clean folios are already prioritized. Scanning for more of
5512 * them is likely futile and can cause high reclaim latency when there
5513 * is a large number of memcgs.
5515 if (!sc->may_writepage || !sc->may_unmap)
5520 blk_start_plug(&plug);
5522 set_mm_walk(pgdat, sc->proactive);
5524 set_initial_priority(pgdat, sc);
5526 if (current_is_kswapd())
5527 sc->nr_reclaimed = 0;
5529 if (mem_cgroup_disabled())
5530 shrink_one(&pgdat->__lruvec, sc);
5532 shrink_many(pgdat, sc);
5534 if (current_is_kswapd())
5535 sc->nr_reclaimed += reclaimed;
5539 blk_finish_plug(&plug);
5541 /* kswapd should never fail */
5542 pgdat->kswapd_failures = 0;
5545 /******************************************************************************
5547 ******************************************************************************/
5549 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5551 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5553 if (lrugen->enabled) {
5556 for_each_evictable_lru(lru) {
5557 if (!list_empty(&lruvec->lists[lru]))
5561 int gen, type, zone;
5563 for_each_gen_type_zone(gen, type, zone) {
5564 if (!list_empty(&lrugen->folios[gen][type][zone]))
5572 static bool fill_evictable(struct lruvec *lruvec)
5575 int remaining = MAX_LRU_BATCH;
5577 for_each_evictable_lru(lru) {
5578 int type = is_file_lru(lru);
5579 bool active = is_active_lru(lru);
5580 struct list_head *head = &lruvec->lists[lru];
5582 while (!list_empty(head)) {
5584 struct folio *folio = lru_to_folio(head);
5586 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5587 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5588 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5589 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5591 lruvec_del_folio(lruvec, folio);
5592 success = lru_gen_add_folio(lruvec, folio, false);
5593 VM_WARN_ON_ONCE(!success);
5603 static bool drain_evictable(struct lruvec *lruvec)
5605 int gen, type, zone;
5606 int remaining = MAX_LRU_BATCH;
5608 for_each_gen_type_zone(gen, type, zone) {
5609 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5611 while (!list_empty(head)) {
5613 struct folio *folio = lru_to_folio(head);
5615 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5616 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5617 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5618 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5620 success = lru_gen_del_folio(lruvec, folio, false);
5621 VM_WARN_ON_ONCE(!success);
5622 lruvec_add_folio(lruvec, folio);
5632 static void lru_gen_change_state(bool enabled)
5634 static DEFINE_MUTEX(state_mutex);
5636 struct mem_cgroup *memcg;
5641 mutex_lock(&state_mutex);
5643 if (enabled == lru_gen_enabled())
5647 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5649 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5651 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5655 for_each_node(nid) {
5656 struct lruvec *lruvec = get_lruvec(memcg, nid);
5658 spin_lock_irq(&lruvec->lru_lock);
5660 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5661 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5663 lruvec->lrugen.enabled = enabled;
5665 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5666 spin_unlock_irq(&lruvec->lru_lock);
5668 spin_lock_irq(&lruvec->lru_lock);
5671 spin_unlock_irq(&lruvec->lru_lock);
5675 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5677 mutex_unlock(&state_mutex);
5683 /******************************************************************************
5685 ******************************************************************************/
5687 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5689 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5692 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5693 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5694 const char *buf, size_t len)
5698 if (kstrtouint(buf, 0, &msecs))
5701 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5706 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
5708 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5710 unsigned int caps = 0;
5712 if (get_cap(LRU_GEN_CORE))
5713 caps |= BIT(LRU_GEN_CORE);
5715 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5716 caps |= BIT(LRU_GEN_MM_WALK);
5718 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5719 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5721 return sysfs_emit(buf, "0x%04x\n", caps);
5724 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5725 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
5726 const char *buf, size_t len)
5731 if (tolower(*buf) == 'n')
5733 else if (tolower(*buf) == 'y')
5735 else if (kstrtouint(buf, 0, &caps))
5738 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5739 bool enabled = caps & BIT(i);
5741 if (i == LRU_GEN_CORE)
5742 lru_gen_change_state(enabled);
5744 static_branch_enable(&lru_gen_caps[i]);
5746 static_branch_disable(&lru_gen_caps[i]);
5752 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
5754 static struct attribute *lru_gen_attrs[] = {
5755 &lru_gen_min_ttl_attr.attr,
5756 &lru_gen_enabled_attr.attr,
5760 static const struct attribute_group lru_gen_attr_group = {
5762 .attrs = lru_gen_attrs,
5765 /******************************************************************************
5767 ******************************************************************************/
5769 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5771 struct mem_cgroup *memcg;
5772 loff_t nr_to_skip = *pos;
5774 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5776 return ERR_PTR(-ENOMEM);
5778 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5782 for_each_node_state(nid, N_MEMORY) {
5784 return get_lruvec(memcg, nid);
5786 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5791 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5793 if (!IS_ERR_OR_NULL(v))
5794 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5800 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5802 int nid = lruvec_pgdat(v)->node_id;
5803 struct mem_cgroup *memcg = lruvec_memcg(v);
5807 nid = next_memory_node(nid);
5808 if (nid == MAX_NUMNODES) {
5809 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5813 nid = first_memory_node;
5816 return get_lruvec(memcg, nid);
5819 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5820 unsigned long max_seq, unsigned long *min_seq,
5825 int hist = lru_hist_from_seq(seq);
5826 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5828 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5829 seq_printf(m, " %10d", tier);
5830 for (type = 0; type < ANON_AND_FILE; type++) {
5831 const char *s = " ";
5832 unsigned long n[3] = {};
5834 if (seq == max_seq) {
5836 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5837 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5838 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5840 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5841 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5843 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5846 for (i = 0; i < 3; i++)
5847 seq_printf(m, " %10lu%c", n[i], s[i]);
5853 for (i = 0; i < NR_MM_STATS; i++) {
5854 const char *s = " ";
5855 unsigned long n = 0;
5857 if (seq == max_seq && NR_HIST_GENS == 1) {
5859 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5860 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5862 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5865 seq_printf(m, " %10lu%c", n, s[i]);
5870 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5871 static int lru_gen_seq_show(struct seq_file *m, void *v)
5874 bool full = !debugfs_real_fops(m->file)->write;
5875 struct lruvec *lruvec = v;
5876 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5877 int nid = lruvec_pgdat(lruvec)->node_id;
5878 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5879 DEFINE_MAX_SEQ(lruvec);
5880 DEFINE_MIN_SEQ(lruvec);
5882 if (nid == first_memory_node) {
5883 const char *path = memcg ? m->private : "";
5887 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5889 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5892 seq_printf(m, " node %5d\n", nid);
5895 seq = min_seq[LRU_GEN_ANON];
5896 else if (max_seq >= MAX_NR_GENS)
5897 seq = max_seq - MAX_NR_GENS + 1;
5901 for (; seq <= max_seq; seq++) {
5903 int gen = lru_gen_from_seq(seq);
5904 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5906 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5908 for (type = 0; type < ANON_AND_FILE; type++) {
5909 unsigned long size = 0;
5910 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5912 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5913 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5915 seq_printf(m, " %10lu%c", size, mark);
5921 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5927 static const struct seq_operations lru_gen_seq_ops = {
5928 .start = lru_gen_seq_start,
5929 .stop = lru_gen_seq_stop,
5930 .next = lru_gen_seq_next,
5931 .show = lru_gen_seq_show,
5934 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5935 bool can_swap, bool force_scan)
5937 DEFINE_MAX_SEQ(lruvec);
5938 DEFINE_MIN_SEQ(lruvec);
5946 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5949 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5954 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5955 int swappiness, unsigned long nr_to_reclaim)
5957 DEFINE_MAX_SEQ(lruvec);
5959 if (seq + MIN_NR_GENS > max_seq)
5962 sc->nr_reclaimed = 0;
5964 while (!signal_pending(current)) {
5965 DEFINE_MIN_SEQ(lruvec);
5967 if (seq < min_seq[!swappiness])
5970 if (sc->nr_reclaimed >= nr_to_reclaim)
5973 if (!evict_folios(lruvec, sc, swappiness))
5982 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5983 struct scan_control *sc, int swappiness, unsigned long opt)
5985 struct lruvec *lruvec;
5987 struct mem_cgroup *memcg = NULL;
5989 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5992 if (!mem_cgroup_disabled()) {
5995 memcg = mem_cgroup_from_id(memcg_id);
5996 if (!mem_cgroup_tryget(memcg))
6005 if (memcg_id != mem_cgroup_id(memcg))
6008 lruvec = get_lruvec(memcg, nid);
6011 swappiness = get_swappiness(lruvec, sc);
6012 else if (swappiness > 200)
6017 err = run_aging(lruvec, seq, sc, swappiness, opt);
6020 err = run_eviction(lruvec, seq, sc, swappiness, opt);
6024 mem_cgroup_put(memcg);
6029 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
6030 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
6031 size_t len, loff_t *pos)
6036 struct blk_plug plug;
6038 struct scan_control sc = {
6039 .may_writepage = true,
6042 .reclaim_idx = MAX_NR_ZONES - 1,
6043 .gfp_mask = GFP_KERNEL,
6046 buf = kvmalloc(len + 1, GFP_KERNEL);
6050 if (copy_from_user(buf, src, len)) {
6055 set_task_reclaim_state(current, &sc.reclaim_state);
6056 flags = memalloc_noreclaim_save();
6057 blk_start_plug(&plug);
6058 if (!set_mm_walk(NULL, true)) {
6066 while ((cur = strsep(&next, ",;\n"))) {
6070 unsigned int memcg_id;
6073 unsigned int swappiness = -1;
6074 unsigned long opt = -1;
6076 cur = skip_spaces(cur);
6080 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
6081 &seq, &end, &swappiness, &end, &opt, &end);
6082 if (n < 4 || cur[end]) {
6087 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
6093 blk_finish_plug(&plug);
6094 memalloc_noreclaim_restore(flags);
6095 set_task_reclaim_state(current, NULL);
6102 static int lru_gen_seq_open(struct inode *inode, struct file *file)
6104 return seq_open(file, &lru_gen_seq_ops);
6107 static const struct file_operations lru_gen_rw_fops = {
6108 .open = lru_gen_seq_open,
6110 .write = lru_gen_seq_write,
6111 .llseek = seq_lseek,
6112 .release = seq_release,
6115 static const struct file_operations lru_gen_ro_fops = {
6116 .open = lru_gen_seq_open,
6118 .llseek = seq_lseek,
6119 .release = seq_release,
6122 /******************************************************************************
6124 ******************************************************************************/
6126 void lru_gen_init_lruvec(struct lruvec *lruvec)
6129 int gen, type, zone;
6130 struct lru_gen_folio *lrugen = &lruvec->lrugen;
6132 lrugen->max_seq = MIN_NR_GENS + 1;
6133 lrugen->enabled = lru_gen_enabled();
6135 for (i = 0; i <= MIN_NR_GENS + 1; i++)
6136 lrugen->timestamps[i] = jiffies;
6138 for_each_gen_type_zone(gen, type, zone)
6139 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
6141 lruvec->mm_state.seq = MIN_NR_GENS;
6146 void lru_gen_init_pgdat(struct pglist_data *pgdat)
6150 spin_lock_init(&pgdat->memcg_lru.lock);
6152 for (i = 0; i < MEMCG_NR_GENS; i++) {
6153 for (j = 0; j < MEMCG_NR_BINS; j++)
6154 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
6158 void lru_gen_init_memcg(struct mem_cgroup *memcg)
6160 INIT_LIST_HEAD(&memcg->mm_list.fifo);
6161 spin_lock_init(&memcg->mm_list.lock);
6164 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
6169 VM_WARN_ON_ONCE(!list_empty(&memcg->mm_list.fifo));
6171 for_each_node(nid) {
6172 struct lruvec *lruvec = get_lruvec(memcg, nid);
6174 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
6175 sizeof(lruvec->lrugen.nr_pages)));
6177 lruvec->lrugen.list.next = LIST_POISON1;
6179 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
6180 bitmap_free(lruvec->mm_state.filters[i]);
6181 lruvec->mm_state.filters[i] = NULL;
6186 #endif /* CONFIG_MEMCG */
6188 static int __init init_lru_gen(void)
6190 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
6191 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
6193 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
6194 pr_err("lru_gen: failed to create sysfs group\n");
6196 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
6197 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
6201 late_initcall(init_lru_gen);
6203 #else /* !CONFIG_LRU_GEN */
6205 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6209 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6213 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
6217 #endif /* CONFIG_LRU_GEN */
6219 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6221 unsigned long nr[NR_LRU_LISTS];
6222 unsigned long targets[NR_LRU_LISTS];
6223 unsigned long nr_to_scan;
6225 unsigned long nr_reclaimed = 0;
6226 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
6227 bool proportional_reclaim;
6228 struct blk_plug plug;
6230 if (lru_gen_enabled() && !global_reclaim(sc)) {
6231 lru_gen_shrink_lruvec(lruvec, sc);
6235 get_scan_count(lruvec, sc, nr);
6237 /* Record the original scan target for proportional adjustments later */
6238 memcpy(targets, nr, sizeof(nr));
6241 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6242 * event that can occur when there is little memory pressure e.g.
6243 * multiple streaming readers/writers. Hence, we do not abort scanning
6244 * when the requested number of pages are reclaimed when scanning at
6245 * DEF_PRIORITY on the assumption that the fact we are direct
6246 * reclaiming implies that kswapd is not keeping up and it is best to
6247 * do a batch of work at once. For memcg reclaim one check is made to
6248 * abort proportional reclaim if either the file or anon lru has already
6249 * dropped to zero at the first pass.
6251 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6252 sc->priority == DEF_PRIORITY);
6254 blk_start_plug(&plug);
6255 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6256 nr[LRU_INACTIVE_FILE]) {
6257 unsigned long nr_anon, nr_file, percentage;
6258 unsigned long nr_scanned;
6260 for_each_evictable_lru(lru) {
6262 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6263 nr[lru] -= nr_to_scan;
6265 nr_reclaimed += shrink_list(lru, nr_to_scan,
6272 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
6276 * For kswapd and memcg, reclaim at least the number of pages
6277 * requested. Ensure that the anon and file LRUs are scanned
6278 * proportionally what was requested by get_scan_count(). We
6279 * stop reclaiming one LRU and reduce the amount scanning
6280 * proportional to the original scan target.
6282 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6283 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6286 * It's just vindictive to attack the larger once the smaller
6287 * has gone to zero. And given the way we stop scanning the
6288 * smaller below, this makes sure that we only make one nudge
6289 * towards proportionality once we've got nr_to_reclaim.
6291 if (!nr_file || !nr_anon)
6294 if (nr_file > nr_anon) {
6295 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6296 targets[LRU_ACTIVE_ANON] + 1;
6298 percentage = nr_anon * 100 / scan_target;
6300 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6301 targets[LRU_ACTIVE_FILE] + 1;
6303 percentage = nr_file * 100 / scan_target;
6306 /* Stop scanning the smaller of the LRU */
6308 nr[lru + LRU_ACTIVE] = 0;
6311 * Recalculate the other LRU scan count based on its original
6312 * scan target and the percentage scanning already complete
6314 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6315 nr_scanned = targets[lru] - nr[lru];
6316 nr[lru] = targets[lru] * (100 - percentage) / 100;
6317 nr[lru] -= min(nr[lru], nr_scanned);
6320 nr_scanned = targets[lru] - nr[lru];
6321 nr[lru] = targets[lru] * (100 - percentage) / 100;
6322 nr[lru] -= min(nr[lru], nr_scanned);
6324 blk_finish_plug(&plug);
6325 sc->nr_reclaimed += nr_reclaimed;
6328 * Even if we did not try to evict anon pages at all, we want to
6329 * rebalance the anon lru active/inactive ratio.
6331 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6332 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6333 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6334 sc, LRU_ACTIVE_ANON);
6337 /* Use reclaim/compaction for costly allocs or under memory pressure */
6338 static bool in_reclaim_compaction(struct scan_control *sc)
6340 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
6341 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6342 sc->priority < DEF_PRIORITY - 2))
6349 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6350 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6351 * true if more pages should be reclaimed such that when the page allocator
6352 * calls try_to_compact_pages() that it will have enough free pages to succeed.
6353 * It will give up earlier than that if there is difficulty reclaiming pages.
6355 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6356 unsigned long nr_reclaimed,
6357 struct scan_control *sc)
6359 unsigned long pages_for_compaction;
6360 unsigned long inactive_lru_pages;
6363 /* If not in reclaim/compaction mode, stop */
6364 if (!in_reclaim_compaction(sc))
6368 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6369 * number of pages that were scanned. This will return to the caller
6370 * with the risk reclaim/compaction and the resulting allocation attempt
6371 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6372 * allocations through requiring that the full LRU list has been scanned
6373 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6374 * scan, but that approximation was wrong, and there were corner cases
6375 * where always a non-zero amount of pages were scanned.
6380 /* If compaction would go ahead or the allocation would succeed, stop */
6381 for (z = 0; z <= sc->reclaim_idx; z++) {
6382 struct zone *zone = &pgdat->node_zones[z];
6383 if (!managed_zone(zone))
6386 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6387 case COMPACT_SUCCESS:
6388 case COMPACT_CONTINUE:
6391 /* check next zone */
6397 * If we have not reclaimed enough pages for compaction and the
6398 * inactive lists are large enough, continue reclaiming
6400 pages_for_compaction = compact_gap(sc->order);
6401 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6402 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6403 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6405 return inactive_lru_pages > pages_for_compaction;
6408 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6410 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6411 struct mem_cgroup *memcg;
6413 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6415 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6416 unsigned long reclaimed;
6417 unsigned long scanned;
6420 * This loop can become CPU-bound when target memcgs
6421 * aren't eligible for reclaim - either because they
6422 * don't have any reclaimable pages, or because their
6423 * memory is explicitly protected. Avoid soft lockups.
6427 mem_cgroup_calculate_protection(target_memcg, memcg);
6429 if (mem_cgroup_below_min(target_memcg, memcg)) {
6432 * If there is no reclaimable memory, OOM.
6435 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
6438 * Respect the protection only as long as
6439 * there is an unprotected supply
6440 * of reclaimable memory from other cgroups.
6442 if (!sc->memcg_low_reclaim) {
6443 sc->memcg_low_skipped = 1;
6446 memcg_memory_event(memcg, MEMCG_LOW);
6449 reclaimed = sc->nr_reclaimed;
6450 scanned = sc->nr_scanned;
6452 shrink_lruvec(lruvec, sc);
6454 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6457 /* Record the group's reclaim efficiency */
6459 vmpressure(sc->gfp_mask, memcg, false,
6460 sc->nr_scanned - scanned,
6461 sc->nr_reclaimed - reclaimed);
6463 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6466 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6468 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
6469 struct lruvec *target_lruvec;
6470 bool reclaimable = false;
6472 if (lru_gen_enabled() && global_reclaim(sc)) {
6473 lru_gen_shrink_node(pgdat, sc);
6477 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6480 memset(&sc->nr, 0, sizeof(sc->nr));
6482 nr_reclaimed = sc->nr_reclaimed;
6483 nr_scanned = sc->nr_scanned;
6485 prepare_scan_count(pgdat, sc);
6487 shrink_node_memcgs(pgdat, sc);
6489 flush_reclaim_state(sc);
6491 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
6493 /* Record the subtree's reclaim efficiency */
6495 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6496 sc->nr_scanned - nr_scanned, nr_node_reclaimed);
6498 if (nr_node_reclaimed)
6501 if (current_is_kswapd()) {
6503 * If reclaim is isolating dirty pages under writeback,
6504 * it implies that the long-lived page allocation rate
6505 * is exceeding the page laundering rate. Either the
6506 * global limits are not being effective at throttling
6507 * processes due to the page distribution throughout
6508 * zones or there is heavy usage of a slow backing
6509 * device. The only option is to throttle from reclaim
6510 * context which is not ideal as there is no guarantee
6511 * the dirtying process is throttled in the same way
6512 * balance_dirty_pages() manages.
6514 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6515 * count the number of pages under pages flagged for
6516 * immediate reclaim and stall if any are encountered
6517 * in the nr_immediate check below.
6519 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6520 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6522 /* Allow kswapd to start writing pages during reclaim.*/
6523 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6524 set_bit(PGDAT_DIRTY, &pgdat->flags);
6527 * If kswapd scans pages marked for immediate
6528 * reclaim and under writeback (nr_immediate), it
6529 * implies that pages are cycling through the LRU
6530 * faster than they are written so forcibly stall
6531 * until some pages complete writeback.
6533 if (sc->nr.immediate)
6534 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6538 * Tag a node/memcg as congested if all the dirty pages were marked
6539 * for writeback and immediate reclaim (counted in nr.congested).
6541 * Legacy memcg will stall in page writeback so avoid forcibly
6542 * stalling in reclaim_throttle().
6544 if ((current_is_kswapd() ||
6545 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6546 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6547 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6550 * Stall direct reclaim for IO completions if the lruvec is
6551 * node is congested. Allow kswapd to continue until it
6552 * starts encountering unqueued dirty pages or cycling through
6553 * the LRU too quickly.
6555 if (!current_is_kswapd() && current_may_throttle() &&
6556 !sc->hibernation_mode &&
6557 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6558 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6560 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
6564 * Kswapd gives up on balancing particular nodes after too
6565 * many failures to reclaim anything from them and goes to
6566 * sleep. On reclaim progress, reset the failure counter. A
6567 * successful direct reclaim run will revive a dormant kswapd.
6570 pgdat->kswapd_failures = 0;
6574 * Returns true if compaction should go ahead for a costly-order request, or
6575 * the allocation would already succeed without compaction. Return false if we
6576 * should reclaim first.
6578 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6580 unsigned long watermark;
6581 enum compact_result suitable;
6583 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6584 if (suitable == COMPACT_SUCCESS)
6585 /* Allocation should succeed already. Don't reclaim. */
6587 if (suitable == COMPACT_SKIPPED)
6588 /* Compaction cannot yet proceed. Do reclaim. */
6592 * Compaction is already possible, but it takes time to run and there
6593 * are potentially other callers using the pages just freed. So proceed
6594 * with reclaim to make a buffer of free pages available to give
6595 * compaction a reasonable chance of completing and allocating the page.
6596 * Note that we won't actually reclaim the whole buffer in one attempt
6597 * as the target watermark in should_continue_reclaim() is lower. But if
6598 * we are already above the high+gap watermark, don't reclaim at all.
6600 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6602 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6605 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6608 * If reclaim is making progress greater than 12% efficiency then
6609 * wake all the NOPROGRESS throttled tasks.
6611 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6612 wait_queue_head_t *wqh;
6614 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6615 if (waitqueue_active(wqh))
6622 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6623 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6624 * under writeback and marked for immediate reclaim at the tail of the
6627 if (current_is_kswapd() || cgroup_reclaim(sc))
6630 /* Throttle if making no progress at high prioities. */
6631 if (sc->priority == 1 && !sc->nr_reclaimed)
6632 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6636 * This is the direct reclaim path, for page-allocating processes. We only
6637 * try to reclaim pages from zones which will satisfy the caller's allocation
6640 * If a zone is deemed to be full of pinned pages then just give it a light
6641 * scan then give up on it.
6643 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6647 unsigned long nr_soft_reclaimed;
6648 unsigned long nr_soft_scanned;
6650 pg_data_t *last_pgdat = NULL;
6651 pg_data_t *first_pgdat = NULL;
6654 * If the number of buffer_heads in the machine exceeds the maximum
6655 * allowed level, force direct reclaim to scan the highmem zone as
6656 * highmem pages could be pinning lowmem pages storing buffer_heads
6658 orig_mask = sc->gfp_mask;
6659 if (buffer_heads_over_limit) {
6660 sc->gfp_mask |= __GFP_HIGHMEM;
6661 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6664 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6665 sc->reclaim_idx, sc->nodemask) {
6667 * Take care memory controller reclaiming has small influence
6670 if (!cgroup_reclaim(sc)) {
6671 if (!cpuset_zone_allowed(zone,
6672 GFP_KERNEL | __GFP_HARDWALL))
6676 * If we already have plenty of memory free for
6677 * compaction in this zone, don't free any more.
6678 * Even though compaction is invoked for any
6679 * non-zero order, only frequent costly order
6680 * reclamation is disruptive enough to become a
6681 * noticeable problem, like transparent huge
6684 if (IS_ENABLED(CONFIG_COMPACTION) &&
6685 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6686 compaction_ready(zone, sc)) {
6687 sc->compaction_ready = true;
6692 * Shrink each node in the zonelist once. If the
6693 * zonelist is ordered by zone (not the default) then a
6694 * node may be shrunk multiple times but in that case
6695 * the user prefers lower zones being preserved.
6697 if (zone->zone_pgdat == last_pgdat)
6701 * This steals pages from memory cgroups over softlimit
6702 * and returns the number of reclaimed pages and
6703 * scanned pages. This works for global memory pressure
6704 * and balancing, not for a memcg's limit.
6706 nr_soft_scanned = 0;
6707 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6708 sc->order, sc->gfp_mask,
6710 sc->nr_reclaimed += nr_soft_reclaimed;
6711 sc->nr_scanned += nr_soft_scanned;
6712 /* need some check for avoid more shrink_zone() */
6716 first_pgdat = zone->zone_pgdat;
6718 /* See comment about same check for global reclaim above */
6719 if (zone->zone_pgdat == last_pgdat)
6721 last_pgdat = zone->zone_pgdat;
6722 shrink_node(zone->zone_pgdat, sc);
6726 consider_reclaim_throttle(first_pgdat, sc);
6729 * Restore to original mask to avoid the impact on the caller if we
6730 * promoted it to __GFP_HIGHMEM.
6732 sc->gfp_mask = orig_mask;
6735 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6737 struct lruvec *target_lruvec;
6738 unsigned long refaults;
6740 if (lru_gen_enabled())
6743 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6744 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6745 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6746 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6747 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6751 * This is the main entry point to direct page reclaim.
6753 * If a full scan of the inactive list fails to free enough memory then we
6754 * are "out of memory" and something needs to be killed.
6756 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6757 * high - the zone may be full of dirty or under-writeback pages, which this
6758 * caller can't do much about. We kick the writeback threads and take explicit
6759 * naps in the hope that some of these pages can be written. But if the
6760 * allocating task holds filesystem locks which prevent writeout this might not
6761 * work, and the allocation attempt will fail.
6763 * returns: 0, if no pages reclaimed
6764 * else, the number of pages reclaimed
6766 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6767 struct scan_control *sc)
6769 int initial_priority = sc->priority;
6770 pg_data_t *last_pgdat;
6774 delayacct_freepages_start();
6776 if (!cgroup_reclaim(sc))
6777 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6781 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6784 shrink_zones(zonelist, sc);
6786 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6789 if (sc->compaction_ready)
6793 * If we're getting trouble reclaiming, start doing
6794 * writepage even in laptop mode.
6796 if (sc->priority < DEF_PRIORITY - 2)
6797 sc->may_writepage = 1;
6798 } while (--sc->priority >= 0);
6801 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6803 if (zone->zone_pgdat == last_pgdat)
6805 last_pgdat = zone->zone_pgdat;
6807 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6809 if (cgroup_reclaim(sc)) {
6810 struct lruvec *lruvec;
6812 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6814 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6818 delayacct_freepages_end();
6820 if (sc->nr_reclaimed)
6821 return sc->nr_reclaimed;
6823 /* Aborted reclaim to try compaction? don't OOM, then */
6824 if (sc->compaction_ready)
6828 * We make inactive:active ratio decisions based on the node's
6829 * composition of memory, but a restrictive reclaim_idx or a
6830 * memory.low cgroup setting can exempt large amounts of
6831 * memory from reclaim. Neither of which are very common, so
6832 * instead of doing costly eligibility calculations of the
6833 * entire cgroup subtree up front, we assume the estimates are
6834 * good, and retry with forcible deactivation if that fails.
6836 if (sc->skipped_deactivate) {
6837 sc->priority = initial_priority;
6838 sc->force_deactivate = 1;
6839 sc->skipped_deactivate = 0;
6843 /* Untapped cgroup reserves? Don't OOM, retry. */
6844 if (sc->memcg_low_skipped) {
6845 sc->priority = initial_priority;
6846 sc->force_deactivate = 0;
6847 sc->memcg_low_reclaim = 1;
6848 sc->memcg_low_skipped = 0;
6855 static bool allow_direct_reclaim(pg_data_t *pgdat)
6858 unsigned long pfmemalloc_reserve = 0;
6859 unsigned long free_pages = 0;
6863 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6866 for (i = 0; i <= ZONE_NORMAL; i++) {
6867 zone = &pgdat->node_zones[i];
6868 if (!managed_zone(zone))
6871 if (!zone_reclaimable_pages(zone))
6874 pfmemalloc_reserve += min_wmark_pages(zone);
6875 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6878 /* If there are no reserves (unexpected config) then do not throttle */
6879 if (!pfmemalloc_reserve)
6882 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6884 /* kswapd must be awake if processes are being throttled */
6885 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6886 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6887 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6889 wake_up_interruptible(&pgdat->kswapd_wait);
6896 * Throttle direct reclaimers if backing storage is backed by the network
6897 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6898 * depleted. kswapd will continue to make progress and wake the processes
6899 * when the low watermark is reached.
6901 * Returns true if a fatal signal was delivered during throttling. If this
6902 * happens, the page allocator should not consider triggering the OOM killer.
6904 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6905 nodemask_t *nodemask)
6909 pg_data_t *pgdat = NULL;
6912 * Kernel threads should not be throttled as they may be indirectly
6913 * responsible for cleaning pages necessary for reclaim to make forward
6914 * progress. kjournald for example may enter direct reclaim while
6915 * committing a transaction where throttling it could forcing other
6916 * processes to block on log_wait_commit().
6918 if (current->flags & PF_KTHREAD)
6922 * If a fatal signal is pending, this process should not throttle.
6923 * It should return quickly so it can exit and free its memory
6925 if (fatal_signal_pending(current))
6929 * Check if the pfmemalloc reserves are ok by finding the first node
6930 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6931 * GFP_KERNEL will be required for allocating network buffers when
6932 * swapping over the network so ZONE_HIGHMEM is unusable.
6934 * Throttling is based on the first usable node and throttled processes
6935 * wait on a queue until kswapd makes progress and wakes them. There
6936 * is an affinity then between processes waking up and where reclaim
6937 * progress has been made assuming the process wakes on the same node.
6938 * More importantly, processes running on remote nodes will not compete
6939 * for remote pfmemalloc reserves and processes on different nodes
6940 * should make reasonable progress.
6942 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6943 gfp_zone(gfp_mask), nodemask) {
6944 if (zone_idx(zone) > ZONE_NORMAL)
6947 /* Throttle based on the first usable node */
6948 pgdat = zone->zone_pgdat;
6949 if (allow_direct_reclaim(pgdat))
6954 /* If no zone was usable by the allocation flags then do not throttle */
6958 /* Account for the throttling */
6959 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6962 * If the caller cannot enter the filesystem, it's possible that it
6963 * is due to the caller holding an FS lock or performing a journal
6964 * transaction in the case of a filesystem like ext[3|4]. In this case,
6965 * it is not safe to block on pfmemalloc_wait as kswapd could be
6966 * blocked waiting on the same lock. Instead, throttle for up to a
6967 * second before continuing.
6969 if (!(gfp_mask & __GFP_FS))
6970 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6971 allow_direct_reclaim(pgdat), HZ);
6973 /* Throttle until kswapd wakes the process */
6974 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6975 allow_direct_reclaim(pgdat));
6977 if (fatal_signal_pending(current))
6984 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6985 gfp_t gfp_mask, nodemask_t *nodemask)
6987 unsigned long nr_reclaimed;
6988 struct scan_control sc = {
6989 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6990 .gfp_mask = current_gfp_context(gfp_mask),
6991 .reclaim_idx = gfp_zone(gfp_mask),
6993 .nodemask = nodemask,
6994 .priority = DEF_PRIORITY,
6995 .may_writepage = !laptop_mode,
7001 * scan_control uses s8 fields for order, priority, and reclaim_idx.
7002 * Confirm they are large enough for max values.
7004 BUILD_BUG_ON(MAX_ORDER >= S8_MAX);
7005 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
7006 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
7009 * Do not enter reclaim if fatal signal was delivered while throttled.
7010 * 1 is returned so that the page allocator does not OOM kill at this
7013 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
7016 set_task_reclaim_state(current, &sc.reclaim_state);
7017 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
7019 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7021 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
7022 set_task_reclaim_state(current, NULL);
7024 return nr_reclaimed;
7029 /* Only used by soft limit reclaim. Do not reuse for anything else. */
7030 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
7031 gfp_t gfp_mask, bool noswap,
7033 unsigned long *nr_scanned)
7035 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
7036 struct scan_control sc = {
7037 .nr_to_reclaim = SWAP_CLUSTER_MAX,
7038 .target_mem_cgroup = memcg,
7039 .may_writepage = !laptop_mode,
7041 .reclaim_idx = MAX_NR_ZONES - 1,
7042 .may_swap = !noswap,
7045 WARN_ON_ONCE(!current->reclaim_state);
7047 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
7048 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
7050 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
7054 * NOTE: Although we can get the priority field, using it
7055 * here is not a good idea, since it limits the pages we can scan.
7056 * if we don't reclaim here, the shrink_node from balance_pgdat
7057 * will pick up pages from other mem cgroup's as well. We hack
7058 * the priority and make it zero.
7060 shrink_lruvec(lruvec, &sc);
7062 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
7064 *nr_scanned = sc.nr_scanned;
7066 return sc.nr_reclaimed;
7069 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
7070 unsigned long nr_pages,
7072 unsigned int reclaim_options)
7074 unsigned long nr_reclaimed;
7075 unsigned int noreclaim_flag;
7076 struct scan_control sc = {
7077 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7078 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
7079 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
7080 .reclaim_idx = MAX_NR_ZONES - 1,
7081 .target_mem_cgroup = memcg,
7082 .priority = DEF_PRIORITY,
7083 .may_writepage = !laptop_mode,
7085 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
7086 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
7089 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
7090 * equal pressure on all the nodes. This is based on the assumption that
7091 * the reclaim does not bail out early.
7093 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7095 set_task_reclaim_state(current, &sc.reclaim_state);
7096 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
7097 noreclaim_flag = memalloc_noreclaim_save();
7099 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7101 memalloc_noreclaim_restore(noreclaim_flag);
7102 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
7103 set_task_reclaim_state(current, NULL);
7105 return nr_reclaimed;
7109 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
7111 struct mem_cgroup *memcg;
7112 struct lruvec *lruvec;
7114 if (lru_gen_enabled()) {
7115 lru_gen_age_node(pgdat, sc);
7119 if (!can_age_anon_pages(pgdat, sc))
7122 lruvec = mem_cgroup_lruvec(NULL, pgdat);
7123 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
7126 memcg = mem_cgroup_iter(NULL, NULL, NULL);
7128 lruvec = mem_cgroup_lruvec(memcg, pgdat);
7129 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
7130 sc, LRU_ACTIVE_ANON);
7131 memcg = mem_cgroup_iter(NULL, memcg, NULL);
7135 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
7141 * Check for watermark boosts top-down as the higher zones
7142 * are more likely to be boosted. Both watermarks and boosts
7143 * should not be checked at the same time as reclaim would
7144 * start prematurely when there is no boosting and a lower
7147 for (i = highest_zoneidx; i >= 0; i--) {
7148 zone = pgdat->node_zones + i;
7149 if (!managed_zone(zone))
7152 if (zone->watermark_boost)
7160 * Returns true if there is an eligible zone balanced for the request order
7161 * and highest_zoneidx
7163 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
7166 unsigned long mark = -1;
7170 * Check watermarks bottom-up as lower zones are more likely to
7173 for (i = 0; i <= highest_zoneidx; i++) {
7174 zone = pgdat->node_zones + i;
7176 if (!managed_zone(zone))
7179 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
7180 mark = wmark_pages(zone, WMARK_PROMO);
7182 mark = high_wmark_pages(zone);
7183 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
7188 * If a node has no managed zone within highest_zoneidx, it does not
7189 * need balancing by definition. This can happen if a zone-restricted
7190 * allocation tries to wake a remote kswapd.
7198 /* Clear pgdat state for congested, dirty or under writeback. */
7199 static void clear_pgdat_congested(pg_data_t *pgdat)
7201 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
7203 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
7204 clear_bit(PGDAT_DIRTY, &pgdat->flags);
7205 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
7209 * Prepare kswapd for sleeping. This verifies that there are no processes
7210 * waiting in throttle_direct_reclaim() and that watermarks have been met.
7212 * Returns true if kswapd is ready to sleep
7214 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
7215 int highest_zoneidx)
7218 * The throttled processes are normally woken up in balance_pgdat() as
7219 * soon as allow_direct_reclaim() is true. But there is a potential
7220 * race between when kswapd checks the watermarks and a process gets
7221 * throttled. There is also a potential race if processes get
7222 * throttled, kswapd wakes, a large process exits thereby balancing the
7223 * zones, which causes kswapd to exit balance_pgdat() before reaching
7224 * the wake up checks. If kswapd is going to sleep, no process should
7225 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
7226 * the wake up is premature, processes will wake kswapd and get
7227 * throttled again. The difference from wake ups in balance_pgdat() is
7228 * that here we are under prepare_to_wait().
7230 if (waitqueue_active(&pgdat->pfmemalloc_wait))
7231 wake_up_all(&pgdat->pfmemalloc_wait);
7233 /* Hopeless node, leave it to direct reclaim */
7234 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
7237 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
7238 clear_pgdat_congested(pgdat);
7246 * kswapd shrinks a node of pages that are at or below the highest usable
7247 * zone that is currently unbalanced.
7249 * Returns true if kswapd scanned at least the requested number of pages to
7250 * reclaim or if the lack of progress was due to pages under writeback.
7251 * This is used to determine if the scanning priority needs to be raised.
7253 static bool kswapd_shrink_node(pg_data_t *pgdat,
7254 struct scan_control *sc)
7259 /* Reclaim a number of pages proportional to the number of zones */
7260 sc->nr_to_reclaim = 0;
7261 for (z = 0; z <= sc->reclaim_idx; z++) {
7262 zone = pgdat->node_zones + z;
7263 if (!managed_zone(zone))
7266 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
7270 * Historically care was taken to put equal pressure on all zones but
7271 * now pressure is applied based on node LRU order.
7273 shrink_node(pgdat, sc);
7276 * Fragmentation may mean that the system cannot be rebalanced for
7277 * high-order allocations. If twice the allocation size has been
7278 * reclaimed then recheck watermarks only at order-0 to prevent
7279 * excessive reclaim. Assume that a process requested a high-order
7280 * can direct reclaim/compact.
7282 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
7285 return sc->nr_scanned >= sc->nr_to_reclaim;
7288 /* Page allocator PCP high watermark is lowered if reclaim is active. */
7290 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7295 for (i = 0; i <= highest_zoneidx; i++) {
7296 zone = pgdat->node_zones + i;
7298 if (!managed_zone(zone))
7302 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7304 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7309 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7311 update_reclaim_active(pgdat, highest_zoneidx, true);
7315 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7317 update_reclaim_active(pgdat, highest_zoneidx, false);
7321 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7322 * that are eligible for use by the caller until at least one zone is
7325 * Returns the order kswapd finished reclaiming at.
7327 * kswapd scans the zones in the highmem->normal->dma direction. It skips
7328 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
7329 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
7330 * or lower is eligible for reclaim until at least one usable zone is
7333 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
7336 unsigned long nr_soft_reclaimed;
7337 unsigned long nr_soft_scanned;
7338 unsigned long pflags;
7339 unsigned long nr_boost_reclaim;
7340 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7343 struct scan_control sc = {
7344 .gfp_mask = GFP_KERNEL,
7349 set_task_reclaim_state(current, &sc.reclaim_state);
7350 psi_memstall_enter(&pflags);
7351 __fs_reclaim_acquire(_THIS_IP_);
7353 count_vm_event(PAGEOUTRUN);
7356 * Account for the reclaim boost. Note that the zone boost is left in
7357 * place so that parallel allocations that are near the watermark will
7358 * stall or direct reclaim until kswapd is finished.
7360 nr_boost_reclaim = 0;
7361 for (i = 0; i <= highest_zoneidx; i++) {
7362 zone = pgdat->node_zones + i;
7363 if (!managed_zone(zone))
7366 nr_boost_reclaim += zone->watermark_boost;
7367 zone_boosts[i] = zone->watermark_boost;
7369 boosted = nr_boost_reclaim;
7372 set_reclaim_active(pgdat, highest_zoneidx);
7373 sc.priority = DEF_PRIORITY;
7375 unsigned long nr_reclaimed = sc.nr_reclaimed;
7376 bool raise_priority = true;
7380 sc.reclaim_idx = highest_zoneidx;
7383 * If the number of buffer_heads exceeds the maximum allowed
7384 * then consider reclaiming from all zones. This has a dual
7385 * purpose -- on 64-bit systems it is expected that
7386 * buffer_heads are stripped during active rotation. On 32-bit
7387 * systems, highmem pages can pin lowmem memory and shrinking
7388 * buffers can relieve lowmem pressure. Reclaim may still not
7389 * go ahead if all eligible zones for the original allocation
7390 * request are balanced to avoid excessive reclaim from kswapd.
7392 if (buffer_heads_over_limit) {
7393 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7394 zone = pgdat->node_zones + i;
7395 if (!managed_zone(zone))
7404 * If the pgdat is imbalanced then ignore boosting and preserve
7405 * the watermarks for a later time and restart. Note that the
7406 * zone watermarks will be still reset at the end of balancing
7407 * on the grounds that the normal reclaim should be enough to
7408 * re-evaluate if boosting is required when kswapd next wakes.
7410 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7411 if (!balanced && nr_boost_reclaim) {
7412 nr_boost_reclaim = 0;
7417 * If boosting is not active then only reclaim if there are no
7418 * eligible zones. Note that sc.reclaim_idx is not used as
7419 * buffer_heads_over_limit may have adjusted it.
7421 if (!nr_boost_reclaim && balanced)
7424 /* Limit the priority of boosting to avoid reclaim writeback */
7425 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7426 raise_priority = false;
7429 * Do not writeback or swap pages for boosted reclaim. The
7430 * intent is to relieve pressure not issue sub-optimal IO
7431 * from reclaim context. If no pages are reclaimed, the
7432 * reclaim will be aborted.
7434 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7435 sc.may_swap = !nr_boost_reclaim;
7438 * Do some background aging, to give pages a chance to be
7439 * referenced before reclaiming. All pages are rotated
7440 * regardless of classzone as this is about consistent aging.
7442 kswapd_age_node(pgdat, &sc);
7445 * If we're getting trouble reclaiming, start doing writepage
7446 * even in laptop mode.
7448 if (sc.priority < DEF_PRIORITY - 2)
7449 sc.may_writepage = 1;
7451 /* Call soft limit reclaim before calling shrink_node. */
7453 nr_soft_scanned = 0;
7454 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7455 sc.gfp_mask, &nr_soft_scanned);
7456 sc.nr_reclaimed += nr_soft_reclaimed;
7459 * There should be no need to raise the scanning priority if
7460 * enough pages are already being scanned that that high
7461 * watermark would be met at 100% efficiency.
7463 if (kswapd_shrink_node(pgdat, &sc))
7464 raise_priority = false;
7467 * If the low watermark is met there is no need for processes
7468 * to be throttled on pfmemalloc_wait as they should not be
7469 * able to safely make forward progress. Wake them
7471 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7472 allow_direct_reclaim(pgdat))
7473 wake_up_all(&pgdat->pfmemalloc_wait);
7475 /* Check if kswapd should be suspending */
7476 __fs_reclaim_release(_THIS_IP_);
7477 ret = try_to_freeze();
7478 __fs_reclaim_acquire(_THIS_IP_);
7479 if (ret || kthread_should_stop())
7483 * Raise priority if scanning rate is too low or there was no
7484 * progress in reclaiming pages
7486 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7487 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7490 * If reclaim made no progress for a boost, stop reclaim as
7491 * IO cannot be queued and it could be an infinite loop in
7492 * extreme circumstances.
7494 if (nr_boost_reclaim && !nr_reclaimed)
7497 if (raise_priority || !nr_reclaimed)
7499 } while (sc.priority >= 1);
7501 if (!sc.nr_reclaimed)
7502 pgdat->kswapd_failures++;
7505 clear_reclaim_active(pgdat, highest_zoneidx);
7507 /* If reclaim was boosted, account for the reclaim done in this pass */
7509 unsigned long flags;
7511 for (i = 0; i <= highest_zoneidx; i++) {
7512 if (!zone_boosts[i])
7515 /* Increments are under the zone lock */
7516 zone = pgdat->node_zones + i;
7517 spin_lock_irqsave(&zone->lock, flags);
7518 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7519 spin_unlock_irqrestore(&zone->lock, flags);
7523 * As there is now likely space, wakeup kcompact to defragment
7526 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7529 snapshot_refaults(NULL, pgdat);
7530 __fs_reclaim_release(_THIS_IP_);
7531 psi_memstall_leave(&pflags);
7532 set_task_reclaim_state(current, NULL);
7535 * Return the order kswapd stopped reclaiming at as
7536 * prepare_kswapd_sleep() takes it into account. If another caller
7537 * entered the allocator slow path while kswapd was awake, order will
7538 * remain at the higher level.
7544 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7545 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7546 * not a valid index then either kswapd runs for first time or kswapd couldn't
7547 * sleep after previous reclaim attempt (node is still unbalanced). In that
7548 * case return the zone index of the previous kswapd reclaim cycle.
7550 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7551 enum zone_type prev_highest_zoneidx)
7553 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7555 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7558 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7559 unsigned int highest_zoneidx)
7564 if (freezing(current) || kthread_should_stop())
7567 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7570 * Try to sleep for a short interval. Note that kcompactd will only be
7571 * woken if it is possible to sleep for a short interval. This is
7572 * deliberate on the assumption that if reclaim cannot keep an
7573 * eligible zone balanced that it's also unlikely that compaction will
7576 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7578 * Compaction records what page blocks it recently failed to
7579 * isolate pages from and skips them in the future scanning.
7580 * When kswapd is going to sleep, it is reasonable to assume
7581 * that pages and compaction may succeed so reset the cache.
7583 reset_isolation_suitable(pgdat);
7586 * We have freed the memory, now we should compact it to make
7587 * allocation of the requested order possible.
7589 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7591 remaining = schedule_timeout(HZ/10);
7594 * If woken prematurely then reset kswapd_highest_zoneidx and
7595 * order. The values will either be from a wakeup request or
7596 * the previous request that slept prematurely.
7599 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7600 kswapd_highest_zoneidx(pgdat,
7603 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7604 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7607 finish_wait(&pgdat->kswapd_wait, &wait);
7608 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7612 * After a short sleep, check if it was a premature sleep. If not, then
7613 * go fully to sleep until explicitly woken up.
7616 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7617 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7620 * vmstat counters are not perfectly accurate and the estimated
7621 * value for counters such as NR_FREE_PAGES can deviate from the
7622 * true value by nr_online_cpus * threshold. To avoid the zone
7623 * watermarks being breached while under pressure, we reduce the
7624 * per-cpu vmstat threshold while kswapd is awake and restore
7625 * them before going back to sleep.
7627 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7629 if (!kthread_should_stop())
7632 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7635 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7637 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7639 finish_wait(&pgdat->kswapd_wait, &wait);
7643 * The background pageout daemon, started as a kernel thread
7644 * from the init process.
7646 * This basically trickles out pages so that we have _some_
7647 * free memory available even if there is no other activity
7648 * that frees anything up. This is needed for things like routing
7649 * etc, where we otherwise might have all activity going on in
7650 * asynchronous contexts that cannot page things out.
7652 * If there are applications that are active memory-allocators
7653 * (most normal use), this basically shouldn't matter.
7655 static int kswapd(void *p)
7657 unsigned int alloc_order, reclaim_order;
7658 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7659 pg_data_t *pgdat = (pg_data_t *)p;
7660 struct task_struct *tsk = current;
7661 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7663 if (!cpumask_empty(cpumask))
7664 set_cpus_allowed_ptr(tsk, cpumask);
7667 * Tell the memory management that we're a "memory allocator",
7668 * and that if we need more memory we should get access to it
7669 * regardless (see "__alloc_pages()"). "kswapd" should
7670 * never get caught in the normal page freeing logic.
7672 * (Kswapd normally doesn't need memory anyway, but sometimes
7673 * you need a small amount of memory in order to be able to
7674 * page out something else, and this flag essentially protects
7675 * us from recursively trying to free more memory as we're
7676 * trying to free the first piece of memory in the first place).
7678 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7681 WRITE_ONCE(pgdat->kswapd_order, 0);
7682 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7683 atomic_set(&pgdat->nr_writeback_throttled, 0);
7687 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7688 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7692 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7695 /* Read the new order and highest_zoneidx */
7696 alloc_order = READ_ONCE(pgdat->kswapd_order);
7697 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7699 WRITE_ONCE(pgdat->kswapd_order, 0);
7700 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7702 ret = try_to_freeze();
7703 if (kthread_should_stop())
7707 * We can speed up thawing tasks if we don't call balance_pgdat
7708 * after returning from the refrigerator
7714 * Reclaim begins at the requested order but if a high-order
7715 * reclaim fails then kswapd falls back to reclaiming for
7716 * order-0. If that happens, kswapd will consider sleeping
7717 * for the order it finished reclaiming at (reclaim_order)
7718 * but kcompactd is woken to compact for the original
7719 * request (alloc_order).
7721 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7723 reclaim_order = balance_pgdat(pgdat, alloc_order,
7725 if (reclaim_order < alloc_order)
7726 goto kswapd_try_sleep;
7729 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7735 * A zone is low on free memory or too fragmented for high-order memory. If
7736 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7737 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7738 * has failed or is not needed, still wake up kcompactd if only compaction is
7741 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7742 enum zone_type highest_zoneidx)
7745 enum zone_type curr_idx;
7747 if (!managed_zone(zone))
7750 if (!cpuset_zone_allowed(zone, gfp_flags))
7753 pgdat = zone->zone_pgdat;
7754 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7756 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7757 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7759 if (READ_ONCE(pgdat->kswapd_order) < order)
7760 WRITE_ONCE(pgdat->kswapd_order, order);
7762 if (!waitqueue_active(&pgdat->kswapd_wait))
7765 /* Hopeless node, leave it to direct reclaim if possible */
7766 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7767 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7768 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7770 * There may be plenty of free memory available, but it's too
7771 * fragmented for high-order allocations. Wake up kcompactd
7772 * and rely on compaction_suitable() to determine if it's
7773 * needed. If it fails, it will defer subsequent attempts to
7774 * ratelimit its work.
7776 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7777 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7781 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7783 wake_up_interruptible(&pgdat->kswapd_wait);
7786 #ifdef CONFIG_HIBERNATION
7788 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7791 * Rather than trying to age LRUs the aim is to preserve the overall
7792 * LRU order by reclaiming preferentially
7793 * inactive > active > active referenced > active mapped
7795 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7797 struct scan_control sc = {
7798 .nr_to_reclaim = nr_to_reclaim,
7799 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7800 .reclaim_idx = MAX_NR_ZONES - 1,
7801 .priority = DEF_PRIORITY,
7805 .hibernation_mode = 1,
7807 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7808 unsigned long nr_reclaimed;
7809 unsigned int noreclaim_flag;
7811 fs_reclaim_acquire(sc.gfp_mask);
7812 noreclaim_flag = memalloc_noreclaim_save();
7813 set_task_reclaim_state(current, &sc.reclaim_state);
7815 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7817 set_task_reclaim_state(current, NULL);
7818 memalloc_noreclaim_restore(noreclaim_flag);
7819 fs_reclaim_release(sc.gfp_mask);
7821 return nr_reclaimed;
7823 #endif /* CONFIG_HIBERNATION */
7826 * This kswapd start function will be called by init and node-hot-add.
7828 void kswapd_run(int nid)
7830 pg_data_t *pgdat = NODE_DATA(nid);
7832 pgdat_kswapd_lock(pgdat);
7833 if (!pgdat->kswapd) {
7834 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7835 if (IS_ERR(pgdat->kswapd)) {
7836 /* failure at boot is fatal */
7837 BUG_ON(system_state < SYSTEM_RUNNING);
7838 pr_err("Failed to start kswapd on node %d\n", nid);
7839 pgdat->kswapd = NULL;
7842 pgdat_kswapd_unlock(pgdat);
7846 * Called by memory hotplug when all memory in a node is offlined. Caller must
7847 * be holding mem_hotplug_begin/done().
7849 void kswapd_stop(int nid)
7851 pg_data_t *pgdat = NODE_DATA(nid);
7852 struct task_struct *kswapd;
7854 pgdat_kswapd_lock(pgdat);
7855 kswapd = pgdat->kswapd;
7857 kthread_stop(kswapd);
7858 pgdat->kswapd = NULL;
7860 pgdat_kswapd_unlock(pgdat);
7863 static int __init kswapd_init(void)
7868 for_each_node_state(nid, N_MEMORY)
7873 module_init(kswapd_init)
7879 * If non-zero call node_reclaim when the number of free pages falls below
7882 int node_reclaim_mode __read_mostly;
7885 * Priority for NODE_RECLAIM. This determines the fraction of pages
7886 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7889 #define NODE_RECLAIM_PRIORITY 4
7892 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7895 int sysctl_min_unmapped_ratio = 1;
7898 * If the number of slab pages in a zone grows beyond this percentage then
7899 * slab reclaim needs to occur.
7901 int sysctl_min_slab_ratio = 5;
7903 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7905 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7906 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7907 node_page_state(pgdat, NR_ACTIVE_FILE);
7910 * It's possible for there to be more file mapped pages than
7911 * accounted for by the pages on the file LRU lists because
7912 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7914 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7917 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7918 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7920 unsigned long nr_pagecache_reclaimable;
7921 unsigned long delta = 0;
7924 * If RECLAIM_UNMAP is set, then all file pages are considered
7925 * potentially reclaimable. Otherwise, we have to worry about
7926 * pages like swapcache and node_unmapped_file_pages() provides
7929 if (node_reclaim_mode & RECLAIM_UNMAP)
7930 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7932 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7934 /* If we can't clean pages, remove dirty pages from consideration */
7935 if (!(node_reclaim_mode & RECLAIM_WRITE))
7936 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7938 /* Watch for any possible underflows due to delta */
7939 if (unlikely(delta > nr_pagecache_reclaimable))
7940 delta = nr_pagecache_reclaimable;
7942 return nr_pagecache_reclaimable - delta;
7946 * Try to free up some pages from this node through reclaim.
7948 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7950 /* Minimum pages needed in order to stay on node */
7951 const unsigned long nr_pages = 1 << order;
7952 struct task_struct *p = current;
7953 unsigned int noreclaim_flag;
7954 struct scan_control sc = {
7955 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7956 .gfp_mask = current_gfp_context(gfp_mask),
7958 .priority = NODE_RECLAIM_PRIORITY,
7959 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7960 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7962 .reclaim_idx = gfp_zone(gfp_mask),
7964 unsigned long pflags;
7966 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7970 psi_memstall_enter(&pflags);
7971 fs_reclaim_acquire(sc.gfp_mask);
7973 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7975 noreclaim_flag = memalloc_noreclaim_save();
7976 set_task_reclaim_state(p, &sc.reclaim_state);
7978 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7979 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7981 * Free memory by calling shrink node with increasing
7982 * priorities until we have enough memory freed.
7985 shrink_node(pgdat, &sc);
7986 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7989 set_task_reclaim_state(p, NULL);
7990 memalloc_noreclaim_restore(noreclaim_flag);
7991 fs_reclaim_release(sc.gfp_mask);
7992 psi_memstall_leave(&pflags);
7994 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7996 return sc.nr_reclaimed >= nr_pages;
7999 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
8004 * Node reclaim reclaims unmapped file backed pages and
8005 * slab pages if we are over the defined limits.
8007 * A small portion of unmapped file backed pages is needed for
8008 * file I/O otherwise pages read by file I/O will be immediately
8009 * thrown out if the node is overallocated. So we do not reclaim
8010 * if less than a specified percentage of the node is used by
8011 * unmapped file backed pages.
8013 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
8014 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
8015 pgdat->min_slab_pages)
8016 return NODE_RECLAIM_FULL;
8019 * Do not scan if the allocation should not be delayed.
8021 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
8022 return NODE_RECLAIM_NOSCAN;
8025 * Only run node reclaim on the local node or on nodes that do not
8026 * have associated processors. This will favor the local processor
8027 * over remote processors and spread off node memory allocations
8028 * as wide as possible.
8030 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
8031 return NODE_RECLAIM_NOSCAN;
8033 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
8034 return NODE_RECLAIM_NOSCAN;
8036 ret = __node_reclaim(pgdat, gfp_mask, order);
8037 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
8040 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
8046 void check_move_unevictable_pages(struct pagevec *pvec)
8048 struct folio_batch fbatch;
8051 folio_batch_init(&fbatch);
8052 for (i = 0; i < pvec->nr; i++) {
8053 struct page *page = pvec->pages[i];
8055 if (PageTransTail(page))
8057 folio_batch_add(&fbatch, page_folio(page));
8059 check_move_unevictable_folios(&fbatch);
8061 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
8064 * check_move_unevictable_folios - Move evictable folios to appropriate zone
8066 * @fbatch: Batch of lru folios to check.
8068 * Checks folios for evictability, if an evictable folio is in the unevictable
8069 * lru list, moves it to the appropriate evictable lru list. This function
8070 * should be only used for lru folios.
8072 void check_move_unevictable_folios(struct folio_batch *fbatch)
8074 struct lruvec *lruvec = NULL;
8079 for (i = 0; i < fbatch->nr; i++) {
8080 struct folio *folio = fbatch->folios[i];
8081 int nr_pages = folio_nr_pages(folio);
8083 pgscanned += nr_pages;
8085 /* block memcg migration while the folio moves between lrus */
8086 if (!folio_test_clear_lru(folio))
8089 lruvec = folio_lruvec_relock_irq(folio, lruvec);
8090 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
8091 lruvec_del_folio(lruvec, folio);
8092 folio_clear_unevictable(folio);
8093 lruvec_add_folio(lruvec, folio);
8094 pgrescued += nr_pages;
8096 folio_set_lru(folio);
8100 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
8101 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8102 unlock_page_lruvec_irq(lruvec);
8103 } else if (pgscanned) {
8104 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8107 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);