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,
4252 .walk_lock = PGWALK_RDLOCK,
4256 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4258 walk->next_addr = FIRST_USER_ADDRESS;
4261 DEFINE_MAX_SEQ(lruvec);
4265 /* another thread might have called inc_max_seq() */
4266 if (walk->max_seq != max_seq)
4269 /* folio_update_gen() requires stable folio_memcg() */
4270 if (!mem_cgroup_trylock_pages(memcg))
4273 /* the caller might be holding the lock for write */
4274 if (mmap_read_trylock(mm)) {
4275 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4277 mmap_read_unlock(mm);
4280 mem_cgroup_unlock_pages();
4282 if (walk->batched) {
4283 spin_lock_irq(&lruvec->lru_lock);
4284 reset_batch_size(lruvec, walk);
4285 spin_unlock_irq(&lruvec->lru_lock);
4289 } while (err == -EAGAIN);
4292 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
4294 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4296 if (pgdat && current_is_kswapd()) {
4297 VM_WARN_ON_ONCE(walk);
4299 walk = &pgdat->mm_walk;
4300 } else if (!walk && force_alloc) {
4301 VM_WARN_ON_ONCE(current_is_kswapd());
4303 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4306 current->reclaim_state->mm_walk = walk;
4311 static void clear_mm_walk(void)
4313 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4315 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4316 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4318 current->reclaim_state->mm_walk = NULL;
4320 if (!current_is_kswapd())
4324 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4327 int remaining = MAX_LRU_BATCH;
4328 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4329 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4331 if (type == LRU_GEN_ANON && !can_swap)
4334 /* prevent cold/hot inversion if force_scan is true */
4335 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4336 struct list_head *head = &lrugen->folios[old_gen][type][zone];
4338 while (!list_empty(head)) {
4339 struct folio *folio = lru_to_folio(head);
4341 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4342 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4343 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4344 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4346 new_gen = folio_inc_gen(lruvec, folio, false);
4347 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
4354 reset_ctrl_pos(lruvec, type, true);
4355 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4360 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4362 int gen, type, zone;
4363 bool success = false;
4364 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4365 DEFINE_MIN_SEQ(lruvec);
4367 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4369 /* find the oldest populated generation */
4370 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4371 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4372 gen = lru_gen_from_seq(min_seq[type]);
4374 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4375 if (!list_empty(&lrugen->folios[gen][type][zone]))
4385 /* see the comment on lru_gen_folio */
4387 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4388 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4391 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4392 if (min_seq[type] == lrugen->min_seq[type])
4395 reset_ctrl_pos(lruvec, type, true);
4396 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4403 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4407 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4409 spin_lock_irq(&lruvec->lru_lock);
4411 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4413 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4414 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4417 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4419 while (!inc_min_seq(lruvec, type, can_swap)) {
4420 spin_unlock_irq(&lruvec->lru_lock);
4422 spin_lock_irq(&lruvec->lru_lock);
4427 * Update the active/inactive LRU sizes for compatibility. Both sides of
4428 * the current max_seq need to be covered, since max_seq+1 can overlap
4429 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4430 * overlap, cold/hot inversion happens.
4432 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4433 next = lru_gen_from_seq(lrugen->max_seq + 1);
4435 for (type = 0; type < ANON_AND_FILE; type++) {
4436 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4437 enum lru_list lru = type * LRU_INACTIVE_FILE;
4438 long delta = lrugen->nr_pages[prev][type][zone] -
4439 lrugen->nr_pages[next][type][zone];
4444 __update_lru_size(lruvec, lru, zone, delta);
4445 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4449 for (type = 0; type < ANON_AND_FILE; type++)
4450 reset_ctrl_pos(lruvec, type, false);
4452 WRITE_ONCE(lrugen->timestamps[next], jiffies);
4453 /* make sure preceding modifications appear */
4454 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4456 spin_unlock_irq(&lruvec->lru_lock);
4459 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4460 struct scan_control *sc, bool can_swap, bool force_scan)
4463 struct lru_gen_mm_walk *walk;
4464 struct mm_struct *mm = NULL;
4465 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4467 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4469 /* see the comment in iterate_mm_list() */
4470 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4476 * If the hardware doesn't automatically set the accessed bit, fallback
4477 * to lru_gen_look_around(), which only clears the accessed bit in a
4478 * handful of PTEs. Spreading the work out over a period of time usually
4479 * is less efficient, but it avoids bursty page faults.
4481 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
4482 success = iterate_mm_list_nowalk(lruvec, max_seq);
4486 walk = set_mm_walk(NULL, true);
4488 success = iterate_mm_list_nowalk(lruvec, max_seq);
4492 walk->lruvec = lruvec;
4493 walk->max_seq = max_seq;
4494 walk->can_swap = can_swap;
4495 walk->force_scan = force_scan;
4498 success = iterate_mm_list(lruvec, walk, &mm);
4500 walk_mm(lruvec, mm, walk);
4504 inc_max_seq(lruvec, can_swap, force_scan);
4509 /******************************************************************************
4510 * working set protection
4511 ******************************************************************************/
4513 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
4515 int gen, type, zone;
4516 unsigned long total = 0;
4517 bool can_swap = get_swappiness(lruvec, sc);
4518 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4519 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4520 DEFINE_MAX_SEQ(lruvec);
4521 DEFINE_MIN_SEQ(lruvec);
4523 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4526 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4527 gen = lru_gen_from_seq(seq);
4529 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4530 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4534 /* whether the size is big enough to be helpful */
4535 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4538 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4539 unsigned long min_ttl)
4542 unsigned long birth;
4543 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4544 DEFINE_MIN_SEQ(lruvec);
4546 /* see the comment on lru_gen_folio */
4547 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4548 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4550 if (time_is_after_jiffies(birth + min_ttl))
4553 if (!lruvec_is_sizable(lruvec, sc))
4556 mem_cgroup_calculate_protection(NULL, memcg);
4558 return !mem_cgroup_below_min(NULL, memcg);
4561 /* to protect the working set of the last N jiffies */
4562 static unsigned long lru_gen_min_ttl __read_mostly;
4564 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4566 struct mem_cgroup *memcg;
4567 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4569 VM_WARN_ON_ONCE(!current_is_kswapd());
4571 /* check the order to exclude compaction-induced reclaim */
4572 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
4575 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4577 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4579 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4580 mem_cgroup_iter_break(NULL, memcg);
4585 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4588 * The main goal is to OOM kill if every generation from all memcgs is
4589 * younger than min_ttl. However, another possibility is all memcgs are
4590 * either too small or below min.
4592 if (mutex_trylock(&oom_lock)) {
4593 struct oom_control oc = {
4594 .gfp_mask = sc->gfp_mask,
4599 mutex_unlock(&oom_lock);
4603 /******************************************************************************
4604 * rmap/PT walk feedback
4605 ******************************************************************************/
4608 * This function exploits spatial locality when shrink_folio_list() walks the
4609 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4610 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4611 * the PTE table to the Bloom filter. This forms a feedback loop between the
4612 * eviction and the aging.
4614 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4617 unsigned long start;
4619 struct lru_gen_mm_walk *walk;
4621 pte_t *pte = pvmw->pte;
4622 unsigned long addr = pvmw->address;
4623 struct folio *folio = pfn_folio(pvmw->pfn);
4624 struct mem_cgroup *memcg = folio_memcg(folio);
4625 struct pglist_data *pgdat = folio_pgdat(folio);
4626 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4627 DEFINE_MAX_SEQ(lruvec);
4628 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4630 lockdep_assert_held(pvmw->ptl);
4631 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4633 if (spin_is_contended(pvmw->ptl))
4636 /* avoid taking the LRU lock under the PTL when possible */
4637 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4639 start = max(addr & PMD_MASK, pvmw->vma->vm_start);
4640 end = min(addr | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4642 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4643 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4644 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4645 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
4646 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4648 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4649 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
4653 /* folio_update_gen() requires stable folio_memcg() */
4654 if (!mem_cgroup_trylock_pages(memcg))
4657 arch_enter_lazy_mmu_mode();
4659 pte -= (addr - start) / PAGE_SIZE;
4661 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4664 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4668 if (!pte_young(pte[i]))
4671 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4675 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4676 VM_WARN_ON_ONCE(true);
4680 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4681 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4682 !folio_test_swapcache(folio)))
4683 folio_mark_dirty(folio);
4686 old_gen = folio_update_gen(folio, new_gen);
4687 if (old_gen >= 0 && old_gen != new_gen)
4688 update_batch_size(walk, folio, old_gen, new_gen);
4693 old_gen = folio_lru_gen(folio);
4695 folio_set_referenced(folio);
4696 else if (old_gen != new_gen)
4697 folio_activate(folio);
4700 arch_leave_lazy_mmu_mode();
4701 mem_cgroup_unlock_pages();
4703 /* feedback from rmap walkers to page table walkers */
4704 if (suitable_to_scan(i, young))
4705 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4708 /******************************************************************************
4710 ******************************************************************************/
4712 /* see the comment on MEMCG_NR_GENS */
4723 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4725 return READ_ONCE(lruvec->lrugen.seg);
4728 static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4732 unsigned long flags;
4733 int bin = get_random_u32_below(MEMCG_NR_BINS);
4734 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4736 spin_lock_irqsave(&pgdat->memcg_lru.lock, flags);
4738 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4741 new = old = lruvec->lrugen.gen;
4743 /* see the comment on MEMCG_NR_GENS */
4744 if (op == MEMCG_LRU_HEAD)
4745 seg = MEMCG_LRU_HEAD;
4746 else if (op == MEMCG_LRU_TAIL)
4747 seg = MEMCG_LRU_TAIL;
4748 else if (op == MEMCG_LRU_OLD)
4749 new = get_memcg_gen(pgdat->memcg_lru.seq);
4750 else if (op == MEMCG_LRU_YOUNG)
4751 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4753 VM_WARN_ON_ONCE(true);
4755 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4757 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4758 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4760 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4762 pgdat->memcg_lru.nr_memcgs[old]--;
4763 pgdat->memcg_lru.nr_memcgs[new]++;
4765 lruvec->lrugen.gen = new;
4766 WRITE_ONCE(lruvec->lrugen.seg, seg);
4768 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4769 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4771 spin_unlock_irqrestore(&pgdat->memcg_lru.lock, flags);
4774 void lru_gen_online_memcg(struct mem_cgroup *memcg)
4778 int bin = get_random_u32_below(MEMCG_NR_BINS);
4780 for_each_node(nid) {
4781 struct pglist_data *pgdat = NODE_DATA(nid);
4782 struct lruvec *lruvec = get_lruvec(memcg, nid);
4784 spin_lock_irq(&pgdat->memcg_lru.lock);
4786 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4788 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4790 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4791 pgdat->memcg_lru.nr_memcgs[gen]++;
4793 lruvec->lrugen.gen = gen;
4795 spin_unlock_irq(&pgdat->memcg_lru.lock);
4799 void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4803 for_each_node(nid) {
4804 struct lruvec *lruvec = get_lruvec(memcg, nid);
4806 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4810 void lru_gen_release_memcg(struct mem_cgroup *memcg)
4815 for_each_node(nid) {
4816 struct pglist_data *pgdat = NODE_DATA(nid);
4817 struct lruvec *lruvec = get_lruvec(memcg, nid);
4819 spin_lock_irq(&pgdat->memcg_lru.lock);
4821 if (hlist_nulls_unhashed(&lruvec->lrugen.list))
4824 gen = lruvec->lrugen.gen;
4826 hlist_nulls_del_init_rcu(&lruvec->lrugen.list);
4827 pgdat->memcg_lru.nr_memcgs[gen]--;
4829 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4830 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4832 spin_unlock_irq(&pgdat->memcg_lru.lock);
4836 void lru_gen_soft_reclaim(struct lruvec *lruvec)
4838 /* see the comment on MEMCG_NR_GENS */
4839 if (lru_gen_memcg_seg(lruvec) != MEMCG_LRU_HEAD)
4840 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4843 #else /* !CONFIG_MEMCG */
4845 static int lru_gen_memcg_seg(struct lruvec *lruvec)
4852 /******************************************************************************
4854 ******************************************************************************/
4856 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4859 int gen = folio_lru_gen(folio);
4860 int type = folio_is_file_lru(folio);
4861 int zone = folio_zonenum(folio);
4862 int delta = folio_nr_pages(folio);
4863 int refs = folio_lru_refs(folio);
4864 int tier = lru_tier_from_refs(refs);
4865 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4867 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4870 if (!folio_evictable(folio)) {
4871 success = lru_gen_del_folio(lruvec, folio, true);
4872 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4873 folio_set_unevictable(folio);
4874 lruvec_add_folio(lruvec, folio);
4875 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4879 /* dirty lazyfree */
4880 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4881 success = lru_gen_del_folio(lruvec, folio, true);
4882 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4883 folio_set_swapbacked(folio);
4884 lruvec_add_folio_tail(lruvec, folio);
4889 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4890 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4895 if (tier > tier_idx) {
4896 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4898 gen = folio_inc_gen(lruvec, folio, false);
4899 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4901 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4902 lrugen->protected[hist][type][tier - 1] + delta);
4903 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4907 /* waiting for writeback */
4908 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4909 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4910 gen = folio_inc_gen(lruvec, folio, true);
4911 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4918 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4922 /* swapping inhibited */
4923 if (!(sc->gfp_mask & __GFP_IO) &&
4924 (folio_test_dirty(folio) ||
4925 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4928 /* raced with release_pages() */
4929 if (!folio_try_get(folio))
4932 /* raced with another isolation */
4933 if (!folio_test_clear_lru(folio)) {
4938 /* see the comment on MAX_NR_TIERS */
4939 if (!folio_test_referenced(folio))
4940 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4942 /* for shrink_folio_list() */
4943 folio_clear_reclaim(folio);
4944 folio_clear_referenced(folio);
4946 success = lru_gen_del_folio(lruvec, folio, true);
4947 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4952 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4953 int type, int tier, struct list_head *list)
4956 enum vm_event_item item;
4960 int remaining = MAX_LRU_BATCH;
4961 struct lru_gen_folio *lrugen = &lruvec->lrugen;
4962 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4964 VM_WARN_ON_ONCE(!list_empty(list));
4966 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4969 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4971 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4974 struct list_head *head = &lrugen->folios[gen][type][zone];
4976 while (!list_empty(head)) {
4977 struct folio *folio = lru_to_folio(head);
4978 int delta = folio_nr_pages(folio);
4980 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4981 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4982 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4983 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4987 if (sort_folio(lruvec, folio, tier))
4989 else if (isolate_folio(lruvec, folio, sc)) {
4990 list_add(&folio->lru, list);
4993 list_move(&folio->lru, &moved);
4997 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
5002 list_splice(&moved, head);
5003 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
5006 if (!remaining || isolated >= MIN_LRU_BATCH)
5010 item = PGSCAN_KSWAPD + reclaimer_offset();
5011 if (!cgroup_reclaim(sc)) {
5012 __count_vm_events(item, isolated);
5013 __count_vm_events(PGREFILL, sorted);
5015 __count_memcg_events(memcg, item, isolated);
5016 __count_memcg_events(memcg, PGREFILL, sorted);
5017 __count_vm_events(PGSCAN_ANON + type, isolated);
5020 * There might not be eligible folios due to reclaim_idx. Check the
5021 * remaining to prevent livelock if it's not making progress.
5023 return isolated || !remaining ? scanned : 0;
5026 static int get_tier_idx(struct lruvec *lruvec, int type)
5029 struct ctrl_pos sp, pv;
5032 * To leave a margin for fluctuations, use a larger gain factor (1:2).
5033 * This value is chosen because any other tier would have at least twice
5034 * as many refaults as the first tier.
5036 read_ctrl_pos(lruvec, type, 0, 1, &sp);
5037 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5038 read_ctrl_pos(lruvec, type, tier, 2, &pv);
5039 if (!positive_ctrl_err(&sp, &pv))
5046 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
5049 struct ctrl_pos sp, pv;
5050 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
5053 * Compare the first tier of anon with that of file to determine which
5054 * type to scan. Also need to compare other tiers of the selected type
5055 * with the first tier of the other type to determine the last tier (of
5056 * the selected type) to evict.
5058 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
5059 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
5060 type = positive_ctrl_err(&sp, &pv);
5062 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
5063 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5064 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
5065 if (!positive_ctrl_err(&sp, &pv))
5069 *tier_idx = tier - 1;
5074 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
5075 int *type_scanned, struct list_head *list)
5081 DEFINE_MIN_SEQ(lruvec);
5084 * Try to make the obvious choice first. When anon and file are both
5085 * available from the same generation, interpret swappiness 1 as file
5086 * first and 200 as anon first.
5089 type = LRU_GEN_FILE;
5090 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
5091 type = LRU_GEN_ANON;
5092 else if (swappiness == 1)
5093 type = LRU_GEN_FILE;
5094 else if (swappiness == 200)
5095 type = LRU_GEN_ANON;
5097 type = get_type_to_scan(lruvec, swappiness, &tier);
5099 for (i = !swappiness; i < ANON_AND_FILE; i++) {
5101 tier = get_tier_idx(lruvec, type);
5103 scanned = scan_folios(lruvec, sc, type, tier, list);
5111 *type_scanned = type;
5116 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
5123 struct folio *folio;
5125 enum vm_event_item item;
5126 struct reclaim_stat stat;
5127 struct lru_gen_mm_walk *walk;
5128 bool skip_retry = false;
5129 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5130 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5132 spin_lock_irq(&lruvec->lru_lock);
5134 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5136 scanned += try_to_inc_min_seq(lruvec, swappiness);
5138 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5141 spin_unlock_irq(&lruvec->lru_lock);
5143 if (list_empty(&list))
5146 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5147 sc->nr_reclaimed += reclaimed;
5149 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5150 if (!folio_evictable(folio)) {
5151 list_del(&folio->lru);
5152 folio_putback_lru(folio);
5156 if (folio_test_reclaim(folio) &&
5157 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5158 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5159 if (folio_test_workingset(folio))
5160 folio_set_referenced(folio);
5164 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5165 folio_mapped(folio) || folio_test_locked(folio) ||
5166 folio_test_dirty(folio) || folio_test_writeback(folio)) {
5167 /* don't add rejected folios to the oldest generation */
5168 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5173 /* retry folios that may have missed folio_rotate_reclaimable() */
5174 list_move(&folio->lru, &clean);
5175 sc->nr_scanned -= folio_nr_pages(folio);
5178 spin_lock_irq(&lruvec->lru_lock);
5180 move_folios_to_lru(lruvec, &list);
5182 walk = current->reclaim_state->mm_walk;
5183 if (walk && walk->batched)
5184 reset_batch_size(lruvec, walk);
5186 item = PGSTEAL_KSWAPD + reclaimer_offset();
5187 if (!cgroup_reclaim(sc))
5188 __count_vm_events(item, reclaimed);
5189 __count_memcg_events(memcg, item, reclaimed);
5190 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5192 spin_unlock_irq(&lruvec->lru_lock);
5194 mem_cgroup_uncharge_list(&list);
5195 free_unref_page_list(&list);
5197 INIT_LIST_HEAD(&list);
5198 list_splice_init(&clean, &list);
5200 if (!list_empty(&list)) {
5208 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
5209 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
5211 int gen, type, zone;
5212 unsigned long old = 0;
5213 unsigned long young = 0;
5214 unsigned long total = 0;
5215 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5216 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5217 DEFINE_MIN_SEQ(lruvec);
5219 /* whether this lruvec is completely out of cold folios */
5220 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
5225 for (type = !can_swap; type < ANON_AND_FILE; type++) {
5228 for (seq = min_seq[type]; seq <= max_seq; seq++) {
5229 unsigned long size = 0;
5231 gen = lru_gen_from_seq(seq);
5233 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5234 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5239 else if (seq + MIN_NR_GENS == max_seq)
5244 /* try to scrape all its memory if this memcg was deleted */
5245 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
5248 * The aging tries to be lazy to reduce the overhead, while the eviction
5249 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
5250 * ideal number of generations is MIN_NR_GENS+1.
5252 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
5256 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
5257 * of the total number of pages for each generation. A reasonable range
5258 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
5259 * aging cares about the upper bound of hot pages, while the eviction
5260 * cares about the lower bound of cold pages.
5262 if (young * MIN_NR_GENS > total)
5264 if (old * (MIN_NR_GENS + 2) < total)
5271 * For future optimizations:
5272 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5275 static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
5277 unsigned long nr_to_scan;
5278 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5279 DEFINE_MAX_SEQ(lruvec);
5281 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
5284 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
5287 /* skip the aging path at the default priority */
5288 if (sc->priority == DEF_PRIORITY)
5291 /* skip this lruvec as it's low on cold folios */
5292 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
5295 static unsigned long get_nr_to_reclaim(struct scan_control *sc)
5297 /* don't abort memcg reclaim to ensure fairness */
5298 if (!global_reclaim(sc))
5301 return max(sc->nr_to_reclaim, compact_gap(sc->order));
5304 static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5307 unsigned long scanned = 0;
5308 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5309 int swappiness = get_swappiness(lruvec, sc);
5311 /* clean file folios are more likely to exist */
5312 if (swappiness && !(sc->gfp_mask & __GFP_IO))
5318 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
5319 if (nr_to_scan <= 0)
5322 delta = evict_folios(lruvec, sc, swappiness);
5327 if (scanned >= nr_to_scan)
5330 if (sc->nr_reclaimed >= nr_to_reclaim)
5336 /* whether try_to_inc_max_seq() was successful */
5337 return nr_to_scan < 0;
5340 static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
5343 unsigned long scanned = sc->nr_scanned;
5344 unsigned long reclaimed = sc->nr_reclaimed;
5345 int seg = lru_gen_memcg_seg(lruvec);
5346 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5347 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5349 /* see the comment on MEMCG_NR_GENS */
5350 if (!lruvec_is_sizable(lruvec, sc))
5351 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5353 mem_cgroup_calculate_protection(NULL, memcg);
5355 if (mem_cgroup_below_min(NULL, memcg))
5356 return MEMCG_LRU_YOUNG;
5358 if (mem_cgroup_below_low(NULL, memcg)) {
5359 /* see the comment on MEMCG_NR_GENS */
5360 if (seg != MEMCG_LRU_TAIL)
5361 return MEMCG_LRU_TAIL;
5363 memcg_memory_event(memcg, MEMCG_LOW);
5366 success = try_to_shrink_lruvec(lruvec, sc);
5368 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5371 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5372 sc->nr_reclaimed - reclaimed);
5374 flush_reclaim_state(sc);
5376 return success ? MEMCG_LRU_YOUNG : 0;
5381 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5387 struct lruvec *lruvec;
5388 struct lru_gen_folio *lrugen;
5389 struct mem_cgroup *memcg;
5390 const struct hlist_nulls_node *pos;
5391 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5393 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
5397 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5401 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5403 lru_gen_rotate_memcg(lruvec, op);
5407 mem_cgroup_put(memcg);
5409 lruvec = container_of(lrugen, struct lruvec, lrugen);
5410 memcg = lruvec_memcg(lruvec);
5412 if (!mem_cgroup_tryget(memcg)) {
5413 lru_gen_release_memcg(memcg);
5420 op = shrink_one(lruvec, sc);
5424 if (sc->nr_reclaimed >= nr_to_reclaim)
5431 lru_gen_rotate_memcg(lruvec, op);
5433 mem_cgroup_put(memcg);
5435 if (sc->nr_reclaimed >= nr_to_reclaim)
5438 /* restart if raced with lru_gen_rotate_memcg() */
5439 if (gen != get_nulls_value(pos))
5442 /* try the rest of the bins of the current generation */
5443 bin = get_memcg_bin(bin + 1);
5444 if (bin != first_bin)
5448 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5450 struct blk_plug plug;
5452 VM_WARN_ON_ONCE(global_reclaim(sc));
5453 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
5457 blk_start_plug(&plug);
5459 set_mm_walk(NULL, sc->proactive);
5461 if (try_to_shrink_lruvec(lruvec, sc))
5462 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5466 blk_finish_plug(&plug);
5469 #else /* !CONFIG_MEMCG */
5471 static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5476 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5483 static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5486 unsigned long reclaimable;
5487 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5489 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5492 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5493 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5494 * estimated reclaimed_to_scanned_ratio = inactive / total.
5496 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5497 if (get_swappiness(lruvec, sc))
5498 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5500 reclaimable /= MEMCG_NR_GENS;
5502 /* round down reclaimable and round up sc->nr_to_reclaim */
5503 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5505 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5508 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5510 struct blk_plug plug;
5511 unsigned long reclaimed = sc->nr_reclaimed;
5513 VM_WARN_ON_ONCE(!global_reclaim(sc));
5516 * Unmapped clean folios are already prioritized. Scanning for more of
5517 * them is likely futile and can cause high reclaim latency when there
5518 * is a large number of memcgs.
5520 if (!sc->may_writepage || !sc->may_unmap)
5525 blk_start_plug(&plug);
5527 set_mm_walk(pgdat, sc->proactive);
5529 set_initial_priority(pgdat, sc);
5531 if (current_is_kswapd())
5532 sc->nr_reclaimed = 0;
5534 if (mem_cgroup_disabled())
5535 shrink_one(&pgdat->__lruvec, sc);
5537 shrink_many(pgdat, sc);
5539 if (current_is_kswapd())
5540 sc->nr_reclaimed += reclaimed;
5544 blk_finish_plug(&plug);
5546 /* kswapd should never fail */
5547 pgdat->kswapd_failures = 0;
5550 /******************************************************************************
5552 ******************************************************************************/
5554 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5556 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5558 if (lrugen->enabled) {
5561 for_each_evictable_lru(lru) {
5562 if (!list_empty(&lruvec->lists[lru]))
5566 int gen, type, zone;
5568 for_each_gen_type_zone(gen, type, zone) {
5569 if (!list_empty(&lrugen->folios[gen][type][zone]))
5577 static bool fill_evictable(struct lruvec *lruvec)
5580 int remaining = MAX_LRU_BATCH;
5582 for_each_evictable_lru(lru) {
5583 int type = is_file_lru(lru);
5584 bool active = is_active_lru(lru);
5585 struct list_head *head = &lruvec->lists[lru];
5587 while (!list_empty(head)) {
5589 struct folio *folio = lru_to_folio(head);
5591 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5592 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5593 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5594 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5596 lruvec_del_folio(lruvec, folio);
5597 success = lru_gen_add_folio(lruvec, folio, false);
5598 VM_WARN_ON_ONCE(!success);
5608 static bool drain_evictable(struct lruvec *lruvec)
5610 int gen, type, zone;
5611 int remaining = MAX_LRU_BATCH;
5613 for_each_gen_type_zone(gen, type, zone) {
5614 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5616 while (!list_empty(head)) {
5618 struct folio *folio = lru_to_folio(head);
5620 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5621 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5622 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5623 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5625 success = lru_gen_del_folio(lruvec, folio, false);
5626 VM_WARN_ON_ONCE(!success);
5627 lruvec_add_folio(lruvec, folio);
5637 static void lru_gen_change_state(bool enabled)
5639 static DEFINE_MUTEX(state_mutex);
5641 struct mem_cgroup *memcg;
5646 mutex_lock(&state_mutex);
5648 if (enabled == lru_gen_enabled())
5652 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5654 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5656 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5660 for_each_node(nid) {
5661 struct lruvec *lruvec = get_lruvec(memcg, nid);
5663 spin_lock_irq(&lruvec->lru_lock);
5665 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5666 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5668 lruvec->lrugen.enabled = enabled;
5670 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5671 spin_unlock_irq(&lruvec->lru_lock);
5673 spin_lock_irq(&lruvec->lru_lock);
5676 spin_unlock_irq(&lruvec->lru_lock);
5680 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5682 mutex_unlock(&state_mutex);
5688 /******************************************************************************
5690 ******************************************************************************/
5692 static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5694 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5697 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5698 static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5699 const char *buf, size_t len)
5703 if (kstrtouint(buf, 0, &msecs))
5706 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5711 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
5713 static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5715 unsigned int caps = 0;
5717 if (get_cap(LRU_GEN_CORE))
5718 caps |= BIT(LRU_GEN_CORE);
5720 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5721 caps |= BIT(LRU_GEN_MM_WALK);
5723 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5724 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5726 return sysfs_emit(buf, "0x%04x\n", caps);
5729 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5730 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
5731 const char *buf, size_t len)
5736 if (tolower(*buf) == 'n')
5738 else if (tolower(*buf) == 'y')
5740 else if (kstrtouint(buf, 0, &caps))
5743 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5744 bool enabled = caps & BIT(i);
5746 if (i == LRU_GEN_CORE)
5747 lru_gen_change_state(enabled);
5749 static_branch_enable(&lru_gen_caps[i]);
5751 static_branch_disable(&lru_gen_caps[i]);
5757 static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
5759 static struct attribute *lru_gen_attrs[] = {
5760 &lru_gen_min_ttl_attr.attr,
5761 &lru_gen_enabled_attr.attr,
5765 static const struct attribute_group lru_gen_attr_group = {
5767 .attrs = lru_gen_attrs,
5770 /******************************************************************************
5772 ******************************************************************************/
5774 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5776 struct mem_cgroup *memcg;
5777 loff_t nr_to_skip = *pos;
5779 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5781 return ERR_PTR(-ENOMEM);
5783 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5787 for_each_node_state(nid, N_MEMORY) {
5789 return get_lruvec(memcg, nid);
5791 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5796 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5798 if (!IS_ERR_OR_NULL(v))
5799 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5805 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5807 int nid = lruvec_pgdat(v)->node_id;
5808 struct mem_cgroup *memcg = lruvec_memcg(v);
5812 nid = next_memory_node(nid);
5813 if (nid == MAX_NUMNODES) {
5814 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5818 nid = first_memory_node;
5821 return get_lruvec(memcg, nid);
5824 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5825 unsigned long max_seq, unsigned long *min_seq,
5830 int hist = lru_hist_from_seq(seq);
5831 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5833 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5834 seq_printf(m, " %10d", tier);
5835 for (type = 0; type < ANON_AND_FILE; type++) {
5836 const char *s = " ";
5837 unsigned long n[3] = {};
5839 if (seq == max_seq) {
5841 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5842 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5843 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5845 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5846 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5848 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5851 for (i = 0; i < 3; i++)
5852 seq_printf(m, " %10lu%c", n[i], s[i]);
5858 for (i = 0; i < NR_MM_STATS; i++) {
5859 const char *s = " ";
5860 unsigned long n = 0;
5862 if (seq == max_seq && NR_HIST_GENS == 1) {
5864 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5865 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5867 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5870 seq_printf(m, " %10lu%c", n, s[i]);
5875 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5876 static int lru_gen_seq_show(struct seq_file *m, void *v)
5879 bool full = !debugfs_real_fops(m->file)->write;
5880 struct lruvec *lruvec = v;
5881 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5882 int nid = lruvec_pgdat(lruvec)->node_id;
5883 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5884 DEFINE_MAX_SEQ(lruvec);
5885 DEFINE_MIN_SEQ(lruvec);
5887 if (nid == first_memory_node) {
5888 const char *path = memcg ? m->private : "";
5892 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5894 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5897 seq_printf(m, " node %5d\n", nid);
5900 seq = min_seq[LRU_GEN_ANON];
5901 else if (max_seq >= MAX_NR_GENS)
5902 seq = max_seq - MAX_NR_GENS + 1;
5906 for (; seq <= max_seq; seq++) {
5908 int gen = lru_gen_from_seq(seq);
5909 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5911 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5913 for (type = 0; type < ANON_AND_FILE; type++) {
5914 unsigned long size = 0;
5915 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5917 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5918 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5920 seq_printf(m, " %10lu%c", size, mark);
5926 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5932 static const struct seq_operations lru_gen_seq_ops = {
5933 .start = lru_gen_seq_start,
5934 .stop = lru_gen_seq_stop,
5935 .next = lru_gen_seq_next,
5936 .show = lru_gen_seq_show,
5939 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5940 bool can_swap, bool force_scan)
5942 DEFINE_MAX_SEQ(lruvec);
5943 DEFINE_MIN_SEQ(lruvec);
5951 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5954 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5959 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5960 int swappiness, unsigned long nr_to_reclaim)
5962 DEFINE_MAX_SEQ(lruvec);
5964 if (seq + MIN_NR_GENS > max_seq)
5967 sc->nr_reclaimed = 0;
5969 while (!signal_pending(current)) {
5970 DEFINE_MIN_SEQ(lruvec);
5972 if (seq < min_seq[!swappiness])
5975 if (sc->nr_reclaimed >= nr_to_reclaim)
5978 if (!evict_folios(lruvec, sc, swappiness))
5987 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5988 struct scan_control *sc, int swappiness, unsigned long opt)
5990 struct lruvec *lruvec;
5992 struct mem_cgroup *memcg = NULL;
5994 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5997 if (!mem_cgroup_disabled()) {
6000 memcg = mem_cgroup_from_id(memcg_id);
6001 if (!mem_cgroup_tryget(memcg))
6010 if (memcg_id != mem_cgroup_id(memcg))
6013 lruvec = get_lruvec(memcg, nid);
6016 swappiness = get_swappiness(lruvec, sc);
6017 else if (swappiness > 200)
6022 err = run_aging(lruvec, seq, sc, swappiness, opt);
6025 err = run_eviction(lruvec, seq, sc, swappiness, opt);
6029 mem_cgroup_put(memcg);
6034 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
6035 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
6036 size_t len, loff_t *pos)
6041 struct blk_plug plug;
6043 struct scan_control sc = {
6044 .may_writepage = true,
6047 .reclaim_idx = MAX_NR_ZONES - 1,
6048 .gfp_mask = GFP_KERNEL,
6051 buf = kvmalloc(len + 1, GFP_KERNEL);
6055 if (copy_from_user(buf, src, len)) {
6060 set_task_reclaim_state(current, &sc.reclaim_state);
6061 flags = memalloc_noreclaim_save();
6062 blk_start_plug(&plug);
6063 if (!set_mm_walk(NULL, true)) {
6071 while ((cur = strsep(&next, ",;\n"))) {
6075 unsigned int memcg_id;
6078 unsigned int swappiness = -1;
6079 unsigned long opt = -1;
6081 cur = skip_spaces(cur);
6085 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
6086 &seq, &end, &swappiness, &end, &opt, &end);
6087 if (n < 4 || cur[end]) {
6092 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
6098 blk_finish_plug(&plug);
6099 memalloc_noreclaim_restore(flags);
6100 set_task_reclaim_state(current, NULL);
6107 static int lru_gen_seq_open(struct inode *inode, struct file *file)
6109 return seq_open(file, &lru_gen_seq_ops);
6112 static const struct file_operations lru_gen_rw_fops = {
6113 .open = lru_gen_seq_open,
6115 .write = lru_gen_seq_write,
6116 .llseek = seq_lseek,
6117 .release = seq_release,
6120 static const struct file_operations lru_gen_ro_fops = {
6121 .open = lru_gen_seq_open,
6123 .llseek = seq_lseek,
6124 .release = seq_release,
6127 /******************************************************************************
6129 ******************************************************************************/
6131 void lru_gen_init_lruvec(struct lruvec *lruvec)
6134 int gen, type, zone;
6135 struct lru_gen_folio *lrugen = &lruvec->lrugen;
6137 lrugen->max_seq = MIN_NR_GENS + 1;
6138 lrugen->enabled = lru_gen_enabled();
6140 for (i = 0; i <= MIN_NR_GENS + 1; i++)
6141 lrugen->timestamps[i] = jiffies;
6143 for_each_gen_type_zone(gen, type, zone)
6144 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
6146 lruvec->mm_state.seq = MIN_NR_GENS;
6151 void lru_gen_init_pgdat(struct pglist_data *pgdat)
6155 spin_lock_init(&pgdat->memcg_lru.lock);
6157 for (i = 0; i < MEMCG_NR_GENS; i++) {
6158 for (j = 0; j < MEMCG_NR_BINS; j++)
6159 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
6163 void lru_gen_init_memcg(struct mem_cgroup *memcg)
6165 INIT_LIST_HEAD(&memcg->mm_list.fifo);
6166 spin_lock_init(&memcg->mm_list.lock);
6169 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
6174 VM_WARN_ON_ONCE(!list_empty(&memcg->mm_list.fifo));
6176 for_each_node(nid) {
6177 struct lruvec *lruvec = get_lruvec(memcg, nid);
6179 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
6180 sizeof(lruvec->lrugen.nr_pages)));
6182 lruvec->lrugen.list.next = LIST_POISON1;
6184 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
6185 bitmap_free(lruvec->mm_state.filters[i]);
6186 lruvec->mm_state.filters[i] = NULL;
6191 #endif /* CONFIG_MEMCG */
6193 static int __init init_lru_gen(void)
6195 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
6196 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
6198 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
6199 pr_err("lru_gen: failed to create sysfs group\n");
6201 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
6202 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
6206 late_initcall(init_lru_gen);
6208 #else /* !CONFIG_LRU_GEN */
6210 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6214 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6218 static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
6222 #endif /* CONFIG_LRU_GEN */
6224 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6226 unsigned long nr[NR_LRU_LISTS];
6227 unsigned long targets[NR_LRU_LISTS];
6228 unsigned long nr_to_scan;
6230 unsigned long nr_reclaimed = 0;
6231 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
6232 bool proportional_reclaim;
6233 struct blk_plug plug;
6235 if (lru_gen_enabled() && !global_reclaim(sc)) {
6236 lru_gen_shrink_lruvec(lruvec, sc);
6240 get_scan_count(lruvec, sc, nr);
6242 /* Record the original scan target for proportional adjustments later */
6243 memcpy(targets, nr, sizeof(nr));
6246 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6247 * event that can occur when there is little memory pressure e.g.
6248 * multiple streaming readers/writers. Hence, we do not abort scanning
6249 * when the requested number of pages are reclaimed when scanning at
6250 * DEF_PRIORITY on the assumption that the fact we are direct
6251 * reclaiming implies that kswapd is not keeping up and it is best to
6252 * do a batch of work at once. For memcg reclaim one check is made to
6253 * abort proportional reclaim if either the file or anon lru has already
6254 * dropped to zero at the first pass.
6256 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6257 sc->priority == DEF_PRIORITY);
6259 blk_start_plug(&plug);
6260 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6261 nr[LRU_INACTIVE_FILE]) {
6262 unsigned long nr_anon, nr_file, percentage;
6263 unsigned long nr_scanned;
6265 for_each_evictable_lru(lru) {
6267 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6268 nr[lru] -= nr_to_scan;
6270 nr_reclaimed += shrink_list(lru, nr_to_scan,
6277 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
6281 * For kswapd and memcg, reclaim at least the number of pages
6282 * requested. Ensure that the anon and file LRUs are scanned
6283 * proportionally what was requested by get_scan_count(). We
6284 * stop reclaiming one LRU and reduce the amount scanning
6285 * proportional to the original scan target.
6287 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6288 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6291 * It's just vindictive to attack the larger once the smaller
6292 * has gone to zero. And given the way we stop scanning the
6293 * smaller below, this makes sure that we only make one nudge
6294 * towards proportionality once we've got nr_to_reclaim.
6296 if (!nr_file || !nr_anon)
6299 if (nr_file > nr_anon) {
6300 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6301 targets[LRU_ACTIVE_ANON] + 1;
6303 percentage = nr_anon * 100 / scan_target;
6305 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6306 targets[LRU_ACTIVE_FILE] + 1;
6308 percentage = nr_file * 100 / scan_target;
6311 /* Stop scanning the smaller of the LRU */
6313 nr[lru + LRU_ACTIVE] = 0;
6316 * Recalculate the other LRU scan count based on its original
6317 * scan target and the percentage scanning already complete
6319 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6320 nr_scanned = targets[lru] - nr[lru];
6321 nr[lru] = targets[lru] * (100 - percentage) / 100;
6322 nr[lru] -= min(nr[lru], nr_scanned);
6325 nr_scanned = targets[lru] - nr[lru];
6326 nr[lru] = targets[lru] * (100 - percentage) / 100;
6327 nr[lru] -= min(nr[lru], nr_scanned);
6329 blk_finish_plug(&plug);
6330 sc->nr_reclaimed += nr_reclaimed;
6333 * Even if we did not try to evict anon pages at all, we want to
6334 * rebalance the anon lru active/inactive ratio.
6336 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6337 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6338 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6339 sc, LRU_ACTIVE_ANON);
6342 /* Use reclaim/compaction for costly allocs or under memory pressure */
6343 static bool in_reclaim_compaction(struct scan_control *sc)
6345 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
6346 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6347 sc->priority < DEF_PRIORITY - 2))
6354 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6355 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6356 * true if more pages should be reclaimed such that when the page allocator
6357 * calls try_to_compact_pages() that it will have enough free pages to succeed.
6358 * It will give up earlier than that if there is difficulty reclaiming pages.
6360 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6361 unsigned long nr_reclaimed,
6362 struct scan_control *sc)
6364 unsigned long pages_for_compaction;
6365 unsigned long inactive_lru_pages;
6368 /* If not in reclaim/compaction mode, stop */
6369 if (!in_reclaim_compaction(sc))
6373 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6374 * number of pages that were scanned. This will return to the caller
6375 * with the risk reclaim/compaction and the resulting allocation attempt
6376 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6377 * allocations through requiring that the full LRU list has been scanned
6378 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6379 * scan, but that approximation was wrong, and there were corner cases
6380 * where always a non-zero amount of pages were scanned.
6385 /* If compaction would go ahead or the allocation would succeed, stop */
6386 for (z = 0; z <= sc->reclaim_idx; z++) {
6387 struct zone *zone = &pgdat->node_zones[z];
6388 if (!managed_zone(zone))
6391 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6392 case COMPACT_SUCCESS:
6393 case COMPACT_CONTINUE:
6396 /* check next zone */
6402 * If we have not reclaimed enough pages for compaction and the
6403 * inactive lists are large enough, continue reclaiming
6405 pages_for_compaction = compact_gap(sc->order);
6406 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6407 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6408 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6410 return inactive_lru_pages > pages_for_compaction;
6413 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6415 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6416 struct mem_cgroup *memcg;
6418 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6420 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6421 unsigned long reclaimed;
6422 unsigned long scanned;
6425 * This loop can become CPU-bound when target memcgs
6426 * aren't eligible for reclaim - either because they
6427 * don't have any reclaimable pages, or because their
6428 * memory is explicitly protected. Avoid soft lockups.
6432 mem_cgroup_calculate_protection(target_memcg, memcg);
6434 if (mem_cgroup_below_min(target_memcg, memcg)) {
6437 * If there is no reclaimable memory, OOM.
6440 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
6443 * Respect the protection only as long as
6444 * there is an unprotected supply
6445 * of reclaimable memory from other cgroups.
6447 if (!sc->memcg_low_reclaim) {
6448 sc->memcg_low_skipped = 1;
6451 memcg_memory_event(memcg, MEMCG_LOW);
6454 reclaimed = sc->nr_reclaimed;
6455 scanned = sc->nr_scanned;
6457 shrink_lruvec(lruvec, sc);
6459 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6462 /* Record the group's reclaim efficiency */
6464 vmpressure(sc->gfp_mask, memcg, false,
6465 sc->nr_scanned - scanned,
6466 sc->nr_reclaimed - reclaimed);
6468 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6471 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6473 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
6474 struct lruvec *target_lruvec;
6475 bool reclaimable = false;
6477 if (lru_gen_enabled() && global_reclaim(sc)) {
6478 lru_gen_shrink_node(pgdat, sc);
6482 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6485 memset(&sc->nr, 0, sizeof(sc->nr));
6487 nr_reclaimed = sc->nr_reclaimed;
6488 nr_scanned = sc->nr_scanned;
6490 prepare_scan_count(pgdat, sc);
6492 shrink_node_memcgs(pgdat, sc);
6494 flush_reclaim_state(sc);
6496 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
6498 /* Record the subtree's reclaim efficiency */
6500 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6501 sc->nr_scanned - nr_scanned, nr_node_reclaimed);
6503 if (nr_node_reclaimed)
6506 if (current_is_kswapd()) {
6508 * If reclaim is isolating dirty pages under writeback,
6509 * it implies that the long-lived page allocation rate
6510 * is exceeding the page laundering rate. Either the
6511 * global limits are not being effective at throttling
6512 * processes due to the page distribution throughout
6513 * zones or there is heavy usage of a slow backing
6514 * device. The only option is to throttle from reclaim
6515 * context which is not ideal as there is no guarantee
6516 * the dirtying process is throttled in the same way
6517 * balance_dirty_pages() manages.
6519 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6520 * count the number of pages under pages flagged for
6521 * immediate reclaim and stall if any are encountered
6522 * in the nr_immediate check below.
6524 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6525 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6527 /* Allow kswapd to start writing pages during reclaim.*/
6528 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6529 set_bit(PGDAT_DIRTY, &pgdat->flags);
6532 * If kswapd scans pages marked for immediate
6533 * reclaim and under writeback (nr_immediate), it
6534 * implies that pages are cycling through the LRU
6535 * faster than they are written so forcibly stall
6536 * until some pages complete writeback.
6538 if (sc->nr.immediate)
6539 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6543 * Tag a node/memcg as congested if all the dirty pages were marked
6544 * for writeback and immediate reclaim (counted in nr.congested).
6546 * Legacy memcg will stall in page writeback so avoid forcibly
6547 * stalling in reclaim_throttle().
6549 if ((current_is_kswapd() ||
6550 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6551 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6552 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6555 * Stall direct reclaim for IO completions if the lruvec is
6556 * node is congested. Allow kswapd to continue until it
6557 * starts encountering unqueued dirty pages or cycling through
6558 * the LRU too quickly.
6560 if (!current_is_kswapd() && current_may_throttle() &&
6561 !sc->hibernation_mode &&
6562 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6563 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6565 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
6569 * Kswapd gives up on balancing particular nodes after too
6570 * many failures to reclaim anything from them and goes to
6571 * sleep. On reclaim progress, reset the failure counter. A
6572 * successful direct reclaim run will revive a dormant kswapd.
6575 pgdat->kswapd_failures = 0;
6579 * Returns true if compaction should go ahead for a costly-order request, or
6580 * the allocation would already succeed without compaction. Return false if we
6581 * should reclaim first.
6583 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6585 unsigned long watermark;
6586 enum compact_result suitable;
6588 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6589 if (suitable == COMPACT_SUCCESS)
6590 /* Allocation should succeed already. Don't reclaim. */
6592 if (suitable == COMPACT_SKIPPED)
6593 /* Compaction cannot yet proceed. Do reclaim. */
6597 * Compaction is already possible, but it takes time to run and there
6598 * are potentially other callers using the pages just freed. So proceed
6599 * with reclaim to make a buffer of free pages available to give
6600 * compaction a reasonable chance of completing and allocating the page.
6601 * Note that we won't actually reclaim the whole buffer in one attempt
6602 * as the target watermark in should_continue_reclaim() is lower. But if
6603 * we are already above the high+gap watermark, don't reclaim at all.
6605 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6607 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6610 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6613 * If reclaim is making progress greater than 12% efficiency then
6614 * wake all the NOPROGRESS throttled tasks.
6616 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6617 wait_queue_head_t *wqh;
6619 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6620 if (waitqueue_active(wqh))
6627 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6628 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6629 * under writeback and marked for immediate reclaim at the tail of the
6632 if (current_is_kswapd() || cgroup_reclaim(sc))
6635 /* Throttle if making no progress at high prioities. */
6636 if (sc->priority == 1 && !sc->nr_reclaimed)
6637 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6641 * This is the direct reclaim path, for page-allocating processes. We only
6642 * try to reclaim pages from zones which will satisfy the caller's allocation
6645 * If a zone is deemed to be full of pinned pages then just give it a light
6646 * scan then give up on it.
6648 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6652 unsigned long nr_soft_reclaimed;
6653 unsigned long nr_soft_scanned;
6655 pg_data_t *last_pgdat = NULL;
6656 pg_data_t *first_pgdat = NULL;
6659 * If the number of buffer_heads in the machine exceeds the maximum
6660 * allowed level, force direct reclaim to scan the highmem zone as
6661 * highmem pages could be pinning lowmem pages storing buffer_heads
6663 orig_mask = sc->gfp_mask;
6664 if (buffer_heads_over_limit) {
6665 sc->gfp_mask |= __GFP_HIGHMEM;
6666 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6669 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6670 sc->reclaim_idx, sc->nodemask) {
6672 * Take care memory controller reclaiming has small influence
6675 if (!cgroup_reclaim(sc)) {
6676 if (!cpuset_zone_allowed(zone,
6677 GFP_KERNEL | __GFP_HARDWALL))
6681 * If we already have plenty of memory free for
6682 * compaction in this zone, don't free any more.
6683 * Even though compaction is invoked for any
6684 * non-zero order, only frequent costly order
6685 * reclamation is disruptive enough to become a
6686 * noticeable problem, like transparent huge
6689 if (IS_ENABLED(CONFIG_COMPACTION) &&
6690 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6691 compaction_ready(zone, sc)) {
6692 sc->compaction_ready = true;
6697 * Shrink each node in the zonelist once. If the
6698 * zonelist is ordered by zone (not the default) then a
6699 * node may be shrunk multiple times but in that case
6700 * the user prefers lower zones being preserved.
6702 if (zone->zone_pgdat == last_pgdat)
6706 * This steals pages from memory cgroups over softlimit
6707 * and returns the number of reclaimed pages and
6708 * scanned pages. This works for global memory pressure
6709 * and balancing, not for a memcg's limit.
6711 nr_soft_scanned = 0;
6712 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6713 sc->order, sc->gfp_mask,
6715 sc->nr_reclaimed += nr_soft_reclaimed;
6716 sc->nr_scanned += nr_soft_scanned;
6717 /* need some check for avoid more shrink_zone() */
6721 first_pgdat = zone->zone_pgdat;
6723 /* See comment about same check for global reclaim above */
6724 if (zone->zone_pgdat == last_pgdat)
6726 last_pgdat = zone->zone_pgdat;
6727 shrink_node(zone->zone_pgdat, sc);
6731 consider_reclaim_throttle(first_pgdat, sc);
6734 * Restore to original mask to avoid the impact on the caller if we
6735 * promoted it to __GFP_HIGHMEM.
6737 sc->gfp_mask = orig_mask;
6740 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6742 struct lruvec *target_lruvec;
6743 unsigned long refaults;
6745 if (lru_gen_enabled())
6748 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6749 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6750 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6751 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6752 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6756 * This is the main entry point to direct page reclaim.
6758 * If a full scan of the inactive list fails to free enough memory then we
6759 * are "out of memory" and something needs to be killed.
6761 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6762 * high - the zone may be full of dirty or under-writeback pages, which this
6763 * caller can't do much about. We kick the writeback threads and take explicit
6764 * naps in the hope that some of these pages can be written. But if the
6765 * allocating task holds filesystem locks which prevent writeout this might not
6766 * work, and the allocation attempt will fail.
6768 * returns: 0, if no pages reclaimed
6769 * else, the number of pages reclaimed
6771 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6772 struct scan_control *sc)
6774 int initial_priority = sc->priority;
6775 pg_data_t *last_pgdat;
6779 delayacct_freepages_start();
6781 if (!cgroup_reclaim(sc))
6782 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6786 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6789 shrink_zones(zonelist, sc);
6791 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6794 if (sc->compaction_ready)
6798 * If we're getting trouble reclaiming, start doing
6799 * writepage even in laptop mode.
6801 if (sc->priority < DEF_PRIORITY - 2)
6802 sc->may_writepage = 1;
6803 } while (--sc->priority >= 0);
6806 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6808 if (zone->zone_pgdat == last_pgdat)
6810 last_pgdat = zone->zone_pgdat;
6812 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6814 if (cgroup_reclaim(sc)) {
6815 struct lruvec *lruvec;
6817 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6819 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6823 delayacct_freepages_end();
6825 if (sc->nr_reclaimed)
6826 return sc->nr_reclaimed;
6828 /* Aborted reclaim to try compaction? don't OOM, then */
6829 if (sc->compaction_ready)
6833 * We make inactive:active ratio decisions based on the node's
6834 * composition of memory, but a restrictive reclaim_idx or a
6835 * memory.low cgroup setting can exempt large amounts of
6836 * memory from reclaim. Neither of which are very common, so
6837 * instead of doing costly eligibility calculations of the
6838 * entire cgroup subtree up front, we assume the estimates are
6839 * good, and retry with forcible deactivation if that fails.
6841 if (sc->skipped_deactivate) {
6842 sc->priority = initial_priority;
6843 sc->force_deactivate = 1;
6844 sc->skipped_deactivate = 0;
6848 /* Untapped cgroup reserves? Don't OOM, retry. */
6849 if (sc->memcg_low_skipped) {
6850 sc->priority = initial_priority;
6851 sc->force_deactivate = 0;
6852 sc->memcg_low_reclaim = 1;
6853 sc->memcg_low_skipped = 0;
6860 static bool allow_direct_reclaim(pg_data_t *pgdat)
6863 unsigned long pfmemalloc_reserve = 0;
6864 unsigned long free_pages = 0;
6868 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6871 for (i = 0; i <= ZONE_NORMAL; i++) {
6872 zone = &pgdat->node_zones[i];
6873 if (!managed_zone(zone))
6876 if (!zone_reclaimable_pages(zone))
6879 pfmemalloc_reserve += min_wmark_pages(zone);
6880 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6883 /* If there are no reserves (unexpected config) then do not throttle */
6884 if (!pfmemalloc_reserve)
6887 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6889 /* kswapd must be awake if processes are being throttled */
6890 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6891 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6892 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6894 wake_up_interruptible(&pgdat->kswapd_wait);
6901 * Throttle direct reclaimers if backing storage is backed by the network
6902 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6903 * depleted. kswapd will continue to make progress and wake the processes
6904 * when the low watermark is reached.
6906 * Returns true if a fatal signal was delivered during throttling. If this
6907 * happens, the page allocator should not consider triggering the OOM killer.
6909 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6910 nodemask_t *nodemask)
6914 pg_data_t *pgdat = NULL;
6917 * Kernel threads should not be throttled as they may be indirectly
6918 * responsible for cleaning pages necessary for reclaim to make forward
6919 * progress. kjournald for example may enter direct reclaim while
6920 * committing a transaction where throttling it could forcing other
6921 * processes to block on log_wait_commit().
6923 if (current->flags & PF_KTHREAD)
6927 * If a fatal signal is pending, this process should not throttle.
6928 * It should return quickly so it can exit and free its memory
6930 if (fatal_signal_pending(current))
6934 * Check if the pfmemalloc reserves are ok by finding the first node
6935 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6936 * GFP_KERNEL will be required for allocating network buffers when
6937 * swapping over the network so ZONE_HIGHMEM is unusable.
6939 * Throttling is based on the first usable node and throttled processes
6940 * wait on a queue until kswapd makes progress and wakes them. There
6941 * is an affinity then between processes waking up and where reclaim
6942 * progress has been made assuming the process wakes on the same node.
6943 * More importantly, processes running on remote nodes will not compete
6944 * for remote pfmemalloc reserves and processes on different nodes
6945 * should make reasonable progress.
6947 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6948 gfp_zone(gfp_mask), nodemask) {
6949 if (zone_idx(zone) > ZONE_NORMAL)
6952 /* Throttle based on the first usable node */
6953 pgdat = zone->zone_pgdat;
6954 if (allow_direct_reclaim(pgdat))
6959 /* If no zone was usable by the allocation flags then do not throttle */
6963 /* Account for the throttling */
6964 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6967 * If the caller cannot enter the filesystem, it's possible that it
6968 * is due to the caller holding an FS lock or performing a journal
6969 * transaction in the case of a filesystem like ext[3|4]. In this case,
6970 * it is not safe to block on pfmemalloc_wait as kswapd could be
6971 * blocked waiting on the same lock. Instead, throttle for up to a
6972 * second before continuing.
6974 if (!(gfp_mask & __GFP_FS))
6975 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6976 allow_direct_reclaim(pgdat), HZ);
6978 /* Throttle until kswapd wakes the process */
6979 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6980 allow_direct_reclaim(pgdat));
6982 if (fatal_signal_pending(current))
6989 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6990 gfp_t gfp_mask, nodemask_t *nodemask)
6992 unsigned long nr_reclaimed;
6993 struct scan_control sc = {
6994 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6995 .gfp_mask = current_gfp_context(gfp_mask),
6996 .reclaim_idx = gfp_zone(gfp_mask),
6998 .nodemask = nodemask,
6999 .priority = DEF_PRIORITY,
7000 .may_writepage = !laptop_mode,
7006 * scan_control uses s8 fields for order, priority, and reclaim_idx.
7007 * Confirm they are large enough for max values.
7009 BUILD_BUG_ON(MAX_ORDER >= S8_MAX);
7010 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
7011 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
7014 * Do not enter reclaim if fatal signal was delivered while throttled.
7015 * 1 is returned so that the page allocator does not OOM kill at this
7018 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
7021 set_task_reclaim_state(current, &sc.reclaim_state);
7022 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
7024 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7026 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
7027 set_task_reclaim_state(current, NULL);
7029 return nr_reclaimed;
7034 /* Only used by soft limit reclaim. Do not reuse for anything else. */
7035 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
7036 gfp_t gfp_mask, bool noswap,
7038 unsigned long *nr_scanned)
7040 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
7041 struct scan_control sc = {
7042 .nr_to_reclaim = SWAP_CLUSTER_MAX,
7043 .target_mem_cgroup = memcg,
7044 .may_writepage = !laptop_mode,
7046 .reclaim_idx = MAX_NR_ZONES - 1,
7047 .may_swap = !noswap,
7050 WARN_ON_ONCE(!current->reclaim_state);
7052 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
7053 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
7055 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
7059 * NOTE: Although we can get the priority field, using it
7060 * here is not a good idea, since it limits the pages we can scan.
7061 * if we don't reclaim here, the shrink_node from balance_pgdat
7062 * will pick up pages from other mem cgroup's as well. We hack
7063 * the priority and make it zero.
7065 shrink_lruvec(lruvec, &sc);
7067 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
7069 *nr_scanned = sc.nr_scanned;
7071 return sc.nr_reclaimed;
7074 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
7075 unsigned long nr_pages,
7077 unsigned int reclaim_options)
7079 unsigned long nr_reclaimed;
7080 unsigned int noreclaim_flag;
7081 struct scan_control sc = {
7082 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7083 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
7084 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
7085 .reclaim_idx = MAX_NR_ZONES - 1,
7086 .target_mem_cgroup = memcg,
7087 .priority = DEF_PRIORITY,
7088 .may_writepage = !laptop_mode,
7090 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
7091 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
7094 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
7095 * equal pressure on all the nodes. This is based on the assumption that
7096 * the reclaim does not bail out early.
7098 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7100 set_task_reclaim_state(current, &sc.reclaim_state);
7101 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
7102 noreclaim_flag = memalloc_noreclaim_save();
7104 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7106 memalloc_noreclaim_restore(noreclaim_flag);
7107 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
7108 set_task_reclaim_state(current, NULL);
7110 return nr_reclaimed;
7114 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
7116 struct mem_cgroup *memcg;
7117 struct lruvec *lruvec;
7119 if (lru_gen_enabled()) {
7120 lru_gen_age_node(pgdat, sc);
7124 if (!can_age_anon_pages(pgdat, sc))
7127 lruvec = mem_cgroup_lruvec(NULL, pgdat);
7128 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
7131 memcg = mem_cgroup_iter(NULL, NULL, NULL);
7133 lruvec = mem_cgroup_lruvec(memcg, pgdat);
7134 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
7135 sc, LRU_ACTIVE_ANON);
7136 memcg = mem_cgroup_iter(NULL, memcg, NULL);
7140 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
7146 * Check for watermark boosts top-down as the higher zones
7147 * are more likely to be boosted. Both watermarks and boosts
7148 * should not be checked at the same time as reclaim would
7149 * start prematurely when there is no boosting and a lower
7152 for (i = highest_zoneidx; i >= 0; i--) {
7153 zone = pgdat->node_zones + i;
7154 if (!managed_zone(zone))
7157 if (zone->watermark_boost)
7165 * Returns true if there is an eligible zone balanced for the request order
7166 * and highest_zoneidx
7168 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
7171 unsigned long mark = -1;
7175 * Check watermarks bottom-up as lower zones are more likely to
7178 for (i = 0; i <= highest_zoneidx; i++) {
7179 zone = pgdat->node_zones + i;
7181 if (!managed_zone(zone))
7184 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
7185 mark = wmark_pages(zone, WMARK_PROMO);
7187 mark = high_wmark_pages(zone);
7188 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
7193 * If a node has no managed zone within highest_zoneidx, it does not
7194 * need balancing by definition. This can happen if a zone-restricted
7195 * allocation tries to wake a remote kswapd.
7203 /* Clear pgdat state for congested, dirty or under writeback. */
7204 static void clear_pgdat_congested(pg_data_t *pgdat)
7206 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
7208 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
7209 clear_bit(PGDAT_DIRTY, &pgdat->flags);
7210 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
7214 * Prepare kswapd for sleeping. This verifies that there are no processes
7215 * waiting in throttle_direct_reclaim() and that watermarks have been met.
7217 * Returns true if kswapd is ready to sleep
7219 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
7220 int highest_zoneidx)
7223 * The throttled processes are normally woken up in balance_pgdat() as
7224 * soon as allow_direct_reclaim() is true. But there is a potential
7225 * race between when kswapd checks the watermarks and a process gets
7226 * throttled. There is also a potential race if processes get
7227 * throttled, kswapd wakes, a large process exits thereby balancing the
7228 * zones, which causes kswapd to exit balance_pgdat() before reaching
7229 * the wake up checks. If kswapd is going to sleep, no process should
7230 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
7231 * the wake up is premature, processes will wake kswapd and get
7232 * throttled again. The difference from wake ups in balance_pgdat() is
7233 * that here we are under prepare_to_wait().
7235 if (waitqueue_active(&pgdat->pfmemalloc_wait))
7236 wake_up_all(&pgdat->pfmemalloc_wait);
7238 /* Hopeless node, leave it to direct reclaim */
7239 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
7242 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
7243 clear_pgdat_congested(pgdat);
7251 * kswapd shrinks a node of pages that are at or below the highest usable
7252 * zone that is currently unbalanced.
7254 * Returns true if kswapd scanned at least the requested number of pages to
7255 * reclaim or if the lack of progress was due to pages under writeback.
7256 * This is used to determine if the scanning priority needs to be raised.
7258 static bool kswapd_shrink_node(pg_data_t *pgdat,
7259 struct scan_control *sc)
7264 /* Reclaim a number of pages proportional to the number of zones */
7265 sc->nr_to_reclaim = 0;
7266 for (z = 0; z <= sc->reclaim_idx; z++) {
7267 zone = pgdat->node_zones + z;
7268 if (!managed_zone(zone))
7271 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
7275 * Historically care was taken to put equal pressure on all zones but
7276 * now pressure is applied based on node LRU order.
7278 shrink_node(pgdat, sc);
7281 * Fragmentation may mean that the system cannot be rebalanced for
7282 * high-order allocations. If twice the allocation size has been
7283 * reclaimed then recheck watermarks only at order-0 to prevent
7284 * excessive reclaim. Assume that a process requested a high-order
7285 * can direct reclaim/compact.
7287 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
7290 return sc->nr_scanned >= sc->nr_to_reclaim;
7293 /* Page allocator PCP high watermark is lowered if reclaim is active. */
7295 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7300 for (i = 0; i <= highest_zoneidx; i++) {
7301 zone = pgdat->node_zones + i;
7303 if (!managed_zone(zone))
7307 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7309 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7314 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7316 update_reclaim_active(pgdat, highest_zoneidx, true);
7320 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7322 update_reclaim_active(pgdat, highest_zoneidx, false);
7326 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7327 * that are eligible for use by the caller until at least one zone is
7330 * Returns the order kswapd finished reclaiming at.
7332 * kswapd scans the zones in the highmem->normal->dma direction. It skips
7333 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
7334 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
7335 * or lower is eligible for reclaim until at least one usable zone is
7338 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
7341 unsigned long nr_soft_reclaimed;
7342 unsigned long nr_soft_scanned;
7343 unsigned long pflags;
7344 unsigned long nr_boost_reclaim;
7345 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7348 struct scan_control sc = {
7349 .gfp_mask = GFP_KERNEL,
7354 set_task_reclaim_state(current, &sc.reclaim_state);
7355 psi_memstall_enter(&pflags);
7356 __fs_reclaim_acquire(_THIS_IP_);
7358 count_vm_event(PAGEOUTRUN);
7361 * Account for the reclaim boost. Note that the zone boost is left in
7362 * place so that parallel allocations that are near the watermark will
7363 * stall or direct reclaim until kswapd is finished.
7365 nr_boost_reclaim = 0;
7366 for (i = 0; i <= highest_zoneidx; i++) {
7367 zone = pgdat->node_zones + i;
7368 if (!managed_zone(zone))
7371 nr_boost_reclaim += zone->watermark_boost;
7372 zone_boosts[i] = zone->watermark_boost;
7374 boosted = nr_boost_reclaim;
7377 set_reclaim_active(pgdat, highest_zoneidx);
7378 sc.priority = DEF_PRIORITY;
7380 unsigned long nr_reclaimed = sc.nr_reclaimed;
7381 bool raise_priority = true;
7385 sc.reclaim_idx = highest_zoneidx;
7388 * If the number of buffer_heads exceeds the maximum allowed
7389 * then consider reclaiming from all zones. This has a dual
7390 * purpose -- on 64-bit systems it is expected that
7391 * buffer_heads are stripped during active rotation. On 32-bit
7392 * systems, highmem pages can pin lowmem memory and shrinking
7393 * buffers can relieve lowmem pressure. Reclaim may still not
7394 * go ahead if all eligible zones for the original allocation
7395 * request are balanced to avoid excessive reclaim from kswapd.
7397 if (buffer_heads_over_limit) {
7398 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7399 zone = pgdat->node_zones + i;
7400 if (!managed_zone(zone))
7409 * If the pgdat is imbalanced then ignore boosting and preserve
7410 * the watermarks for a later time and restart. Note that the
7411 * zone watermarks will be still reset at the end of balancing
7412 * on the grounds that the normal reclaim should be enough to
7413 * re-evaluate if boosting is required when kswapd next wakes.
7415 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7416 if (!balanced && nr_boost_reclaim) {
7417 nr_boost_reclaim = 0;
7422 * If boosting is not active then only reclaim if there are no
7423 * eligible zones. Note that sc.reclaim_idx is not used as
7424 * buffer_heads_over_limit may have adjusted it.
7426 if (!nr_boost_reclaim && balanced)
7429 /* Limit the priority of boosting to avoid reclaim writeback */
7430 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7431 raise_priority = false;
7434 * Do not writeback or swap pages for boosted reclaim. The
7435 * intent is to relieve pressure not issue sub-optimal IO
7436 * from reclaim context. If no pages are reclaimed, the
7437 * reclaim will be aborted.
7439 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7440 sc.may_swap = !nr_boost_reclaim;
7443 * Do some background aging, to give pages a chance to be
7444 * referenced before reclaiming. All pages are rotated
7445 * regardless of classzone as this is about consistent aging.
7447 kswapd_age_node(pgdat, &sc);
7450 * If we're getting trouble reclaiming, start doing writepage
7451 * even in laptop mode.
7453 if (sc.priority < DEF_PRIORITY - 2)
7454 sc.may_writepage = 1;
7456 /* Call soft limit reclaim before calling shrink_node. */
7458 nr_soft_scanned = 0;
7459 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7460 sc.gfp_mask, &nr_soft_scanned);
7461 sc.nr_reclaimed += nr_soft_reclaimed;
7464 * There should be no need to raise the scanning priority if
7465 * enough pages are already being scanned that that high
7466 * watermark would be met at 100% efficiency.
7468 if (kswapd_shrink_node(pgdat, &sc))
7469 raise_priority = false;
7472 * If the low watermark is met there is no need for processes
7473 * to be throttled on pfmemalloc_wait as they should not be
7474 * able to safely make forward progress. Wake them
7476 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7477 allow_direct_reclaim(pgdat))
7478 wake_up_all(&pgdat->pfmemalloc_wait);
7480 /* Check if kswapd should be suspending */
7481 __fs_reclaim_release(_THIS_IP_);
7482 ret = try_to_freeze();
7483 __fs_reclaim_acquire(_THIS_IP_);
7484 if (ret || kthread_should_stop())
7488 * Raise priority if scanning rate is too low or there was no
7489 * progress in reclaiming pages
7491 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7492 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7495 * If reclaim made no progress for a boost, stop reclaim as
7496 * IO cannot be queued and it could be an infinite loop in
7497 * extreme circumstances.
7499 if (nr_boost_reclaim && !nr_reclaimed)
7502 if (raise_priority || !nr_reclaimed)
7504 } while (sc.priority >= 1);
7506 if (!sc.nr_reclaimed)
7507 pgdat->kswapd_failures++;
7510 clear_reclaim_active(pgdat, highest_zoneidx);
7512 /* If reclaim was boosted, account for the reclaim done in this pass */
7514 unsigned long flags;
7516 for (i = 0; i <= highest_zoneidx; i++) {
7517 if (!zone_boosts[i])
7520 /* Increments are under the zone lock */
7521 zone = pgdat->node_zones + i;
7522 spin_lock_irqsave(&zone->lock, flags);
7523 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7524 spin_unlock_irqrestore(&zone->lock, flags);
7528 * As there is now likely space, wakeup kcompact to defragment
7531 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7534 snapshot_refaults(NULL, pgdat);
7535 __fs_reclaim_release(_THIS_IP_);
7536 psi_memstall_leave(&pflags);
7537 set_task_reclaim_state(current, NULL);
7540 * Return the order kswapd stopped reclaiming at as
7541 * prepare_kswapd_sleep() takes it into account. If another caller
7542 * entered the allocator slow path while kswapd was awake, order will
7543 * remain at the higher level.
7549 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7550 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7551 * not a valid index then either kswapd runs for first time or kswapd couldn't
7552 * sleep after previous reclaim attempt (node is still unbalanced). In that
7553 * case return the zone index of the previous kswapd reclaim cycle.
7555 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7556 enum zone_type prev_highest_zoneidx)
7558 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7560 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7563 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7564 unsigned int highest_zoneidx)
7569 if (freezing(current) || kthread_should_stop())
7572 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7575 * Try to sleep for a short interval. Note that kcompactd will only be
7576 * woken if it is possible to sleep for a short interval. This is
7577 * deliberate on the assumption that if reclaim cannot keep an
7578 * eligible zone balanced that it's also unlikely that compaction will
7581 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7583 * Compaction records what page blocks it recently failed to
7584 * isolate pages from and skips them in the future scanning.
7585 * When kswapd is going to sleep, it is reasonable to assume
7586 * that pages and compaction may succeed so reset the cache.
7588 reset_isolation_suitable(pgdat);
7591 * We have freed the memory, now we should compact it to make
7592 * allocation of the requested order possible.
7594 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7596 remaining = schedule_timeout(HZ/10);
7599 * If woken prematurely then reset kswapd_highest_zoneidx and
7600 * order. The values will either be from a wakeup request or
7601 * the previous request that slept prematurely.
7604 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7605 kswapd_highest_zoneidx(pgdat,
7608 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7609 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7612 finish_wait(&pgdat->kswapd_wait, &wait);
7613 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7617 * After a short sleep, check if it was a premature sleep. If not, then
7618 * go fully to sleep until explicitly woken up.
7621 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7622 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7625 * vmstat counters are not perfectly accurate and the estimated
7626 * value for counters such as NR_FREE_PAGES can deviate from the
7627 * true value by nr_online_cpus * threshold. To avoid the zone
7628 * watermarks being breached while under pressure, we reduce the
7629 * per-cpu vmstat threshold while kswapd is awake and restore
7630 * them before going back to sleep.
7632 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7634 if (!kthread_should_stop())
7637 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7640 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7642 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7644 finish_wait(&pgdat->kswapd_wait, &wait);
7648 * The background pageout daemon, started as a kernel thread
7649 * from the init process.
7651 * This basically trickles out pages so that we have _some_
7652 * free memory available even if there is no other activity
7653 * that frees anything up. This is needed for things like routing
7654 * etc, where we otherwise might have all activity going on in
7655 * asynchronous contexts that cannot page things out.
7657 * If there are applications that are active memory-allocators
7658 * (most normal use), this basically shouldn't matter.
7660 static int kswapd(void *p)
7662 unsigned int alloc_order, reclaim_order;
7663 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7664 pg_data_t *pgdat = (pg_data_t *)p;
7665 struct task_struct *tsk = current;
7666 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7668 if (!cpumask_empty(cpumask))
7669 set_cpus_allowed_ptr(tsk, cpumask);
7672 * Tell the memory management that we're a "memory allocator",
7673 * and that if we need more memory we should get access to it
7674 * regardless (see "__alloc_pages()"). "kswapd" should
7675 * never get caught in the normal page freeing logic.
7677 * (Kswapd normally doesn't need memory anyway, but sometimes
7678 * you need a small amount of memory in order to be able to
7679 * page out something else, and this flag essentially protects
7680 * us from recursively trying to free more memory as we're
7681 * trying to free the first piece of memory in the first place).
7683 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7686 WRITE_ONCE(pgdat->kswapd_order, 0);
7687 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7688 atomic_set(&pgdat->nr_writeback_throttled, 0);
7692 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7693 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7697 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7700 /* Read the new order and highest_zoneidx */
7701 alloc_order = READ_ONCE(pgdat->kswapd_order);
7702 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7704 WRITE_ONCE(pgdat->kswapd_order, 0);
7705 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7707 ret = try_to_freeze();
7708 if (kthread_should_stop())
7712 * We can speed up thawing tasks if we don't call balance_pgdat
7713 * after returning from the refrigerator
7719 * Reclaim begins at the requested order but if a high-order
7720 * reclaim fails then kswapd falls back to reclaiming for
7721 * order-0. If that happens, kswapd will consider sleeping
7722 * for the order it finished reclaiming at (reclaim_order)
7723 * but kcompactd is woken to compact for the original
7724 * request (alloc_order).
7726 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7728 reclaim_order = balance_pgdat(pgdat, alloc_order,
7730 if (reclaim_order < alloc_order)
7731 goto kswapd_try_sleep;
7734 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7740 * A zone is low on free memory or too fragmented for high-order memory. If
7741 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7742 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7743 * has failed or is not needed, still wake up kcompactd if only compaction is
7746 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7747 enum zone_type highest_zoneidx)
7750 enum zone_type curr_idx;
7752 if (!managed_zone(zone))
7755 if (!cpuset_zone_allowed(zone, gfp_flags))
7758 pgdat = zone->zone_pgdat;
7759 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7761 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7762 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7764 if (READ_ONCE(pgdat->kswapd_order) < order)
7765 WRITE_ONCE(pgdat->kswapd_order, order);
7767 if (!waitqueue_active(&pgdat->kswapd_wait))
7770 /* Hopeless node, leave it to direct reclaim if possible */
7771 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7772 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7773 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7775 * There may be plenty of free memory available, but it's too
7776 * fragmented for high-order allocations. Wake up kcompactd
7777 * and rely on compaction_suitable() to determine if it's
7778 * needed. If it fails, it will defer subsequent attempts to
7779 * ratelimit its work.
7781 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7782 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7786 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7788 wake_up_interruptible(&pgdat->kswapd_wait);
7791 #ifdef CONFIG_HIBERNATION
7793 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7796 * Rather than trying to age LRUs the aim is to preserve the overall
7797 * LRU order by reclaiming preferentially
7798 * inactive > active > active referenced > active mapped
7800 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7802 struct scan_control sc = {
7803 .nr_to_reclaim = nr_to_reclaim,
7804 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7805 .reclaim_idx = MAX_NR_ZONES - 1,
7806 .priority = DEF_PRIORITY,
7810 .hibernation_mode = 1,
7812 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7813 unsigned long nr_reclaimed;
7814 unsigned int noreclaim_flag;
7816 fs_reclaim_acquire(sc.gfp_mask);
7817 noreclaim_flag = memalloc_noreclaim_save();
7818 set_task_reclaim_state(current, &sc.reclaim_state);
7820 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7822 set_task_reclaim_state(current, NULL);
7823 memalloc_noreclaim_restore(noreclaim_flag);
7824 fs_reclaim_release(sc.gfp_mask);
7826 return nr_reclaimed;
7828 #endif /* CONFIG_HIBERNATION */
7831 * This kswapd start function will be called by init and node-hot-add.
7833 void kswapd_run(int nid)
7835 pg_data_t *pgdat = NODE_DATA(nid);
7837 pgdat_kswapd_lock(pgdat);
7838 if (!pgdat->kswapd) {
7839 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7840 if (IS_ERR(pgdat->kswapd)) {
7841 /* failure at boot is fatal */
7842 BUG_ON(system_state < SYSTEM_RUNNING);
7843 pr_err("Failed to start kswapd on node %d\n", nid);
7844 pgdat->kswapd = NULL;
7847 pgdat_kswapd_unlock(pgdat);
7851 * Called by memory hotplug when all memory in a node is offlined. Caller must
7852 * be holding mem_hotplug_begin/done().
7854 void kswapd_stop(int nid)
7856 pg_data_t *pgdat = NODE_DATA(nid);
7857 struct task_struct *kswapd;
7859 pgdat_kswapd_lock(pgdat);
7860 kswapd = pgdat->kswapd;
7862 kthread_stop(kswapd);
7863 pgdat->kswapd = NULL;
7865 pgdat_kswapd_unlock(pgdat);
7868 static int __init kswapd_init(void)
7873 for_each_node_state(nid, N_MEMORY)
7878 module_init(kswapd_init)
7884 * If non-zero call node_reclaim when the number of free pages falls below
7887 int node_reclaim_mode __read_mostly;
7890 * Priority for NODE_RECLAIM. This determines the fraction of pages
7891 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7894 #define NODE_RECLAIM_PRIORITY 4
7897 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7900 int sysctl_min_unmapped_ratio = 1;
7903 * If the number of slab pages in a zone grows beyond this percentage then
7904 * slab reclaim needs to occur.
7906 int sysctl_min_slab_ratio = 5;
7908 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7910 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7911 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7912 node_page_state(pgdat, NR_ACTIVE_FILE);
7915 * It's possible for there to be more file mapped pages than
7916 * accounted for by the pages on the file LRU lists because
7917 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7919 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7922 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7923 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7925 unsigned long nr_pagecache_reclaimable;
7926 unsigned long delta = 0;
7929 * If RECLAIM_UNMAP is set, then all file pages are considered
7930 * potentially reclaimable. Otherwise, we have to worry about
7931 * pages like swapcache and node_unmapped_file_pages() provides
7934 if (node_reclaim_mode & RECLAIM_UNMAP)
7935 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7937 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7939 /* If we can't clean pages, remove dirty pages from consideration */
7940 if (!(node_reclaim_mode & RECLAIM_WRITE))
7941 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7943 /* Watch for any possible underflows due to delta */
7944 if (unlikely(delta > nr_pagecache_reclaimable))
7945 delta = nr_pagecache_reclaimable;
7947 return nr_pagecache_reclaimable - delta;
7951 * Try to free up some pages from this node through reclaim.
7953 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7955 /* Minimum pages needed in order to stay on node */
7956 const unsigned long nr_pages = 1 << order;
7957 struct task_struct *p = current;
7958 unsigned int noreclaim_flag;
7959 struct scan_control sc = {
7960 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7961 .gfp_mask = current_gfp_context(gfp_mask),
7963 .priority = NODE_RECLAIM_PRIORITY,
7964 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7965 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7967 .reclaim_idx = gfp_zone(gfp_mask),
7969 unsigned long pflags;
7971 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7975 psi_memstall_enter(&pflags);
7976 fs_reclaim_acquire(sc.gfp_mask);
7978 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7980 noreclaim_flag = memalloc_noreclaim_save();
7981 set_task_reclaim_state(p, &sc.reclaim_state);
7983 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7984 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7986 * Free memory by calling shrink node with increasing
7987 * priorities until we have enough memory freed.
7990 shrink_node(pgdat, &sc);
7991 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7994 set_task_reclaim_state(p, NULL);
7995 memalloc_noreclaim_restore(noreclaim_flag);
7996 fs_reclaim_release(sc.gfp_mask);
7997 psi_memstall_leave(&pflags);
7999 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
8001 return sc.nr_reclaimed >= nr_pages;
8004 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
8009 * Node reclaim reclaims unmapped file backed pages and
8010 * slab pages if we are over the defined limits.
8012 * A small portion of unmapped file backed pages is needed for
8013 * file I/O otherwise pages read by file I/O will be immediately
8014 * thrown out if the node is overallocated. So we do not reclaim
8015 * if less than a specified percentage of the node is used by
8016 * unmapped file backed pages.
8018 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
8019 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
8020 pgdat->min_slab_pages)
8021 return NODE_RECLAIM_FULL;
8024 * Do not scan if the allocation should not be delayed.
8026 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
8027 return NODE_RECLAIM_NOSCAN;
8030 * Only run node reclaim on the local node or on nodes that do not
8031 * have associated processors. This will favor the local processor
8032 * over remote processors and spread off node memory allocations
8033 * as wide as possible.
8035 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
8036 return NODE_RECLAIM_NOSCAN;
8038 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
8039 return NODE_RECLAIM_NOSCAN;
8041 ret = __node_reclaim(pgdat, gfp_mask, order);
8042 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
8045 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
8051 void check_move_unevictable_pages(struct pagevec *pvec)
8053 struct folio_batch fbatch;
8056 folio_batch_init(&fbatch);
8057 for (i = 0; i < pvec->nr; i++) {
8058 struct page *page = pvec->pages[i];
8060 if (PageTransTail(page))
8062 folio_batch_add(&fbatch, page_folio(page));
8064 check_move_unevictable_folios(&fbatch);
8066 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
8069 * check_move_unevictable_folios - Move evictable folios to appropriate zone
8071 * @fbatch: Batch of lru folios to check.
8073 * Checks folios for evictability, if an evictable folio is in the unevictable
8074 * lru list, moves it to the appropriate evictable lru list. This function
8075 * should be only used for lru folios.
8077 void check_move_unevictable_folios(struct folio_batch *fbatch)
8079 struct lruvec *lruvec = NULL;
8084 for (i = 0; i < fbatch->nr; i++) {
8085 struct folio *folio = fbatch->folios[i];
8086 int nr_pages = folio_nr_pages(folio);
8088 pgscanned += nr_pages;
8090 /* block memcg migration while the folio moves between lrus */
8091 if (!folio_test_clear_lru(folio))
8094 lruvec = folio_lruvec_relock_irq(folio, lruvec);
8095 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
8096 lruvec_del_folio(lruvec, folio);
8097 folio_clear_unevictable(folio);
8098 lruvec_add_folio(lruvec, folio);
8099 pgrescued += nr_pages;
8101 folio_set_lru(folio);
8105 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
8106 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8107 unlock_page_lruvec_irq(lruvec);
8108 } else if (pgscanned) {
8109 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
8112 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);