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>
58 #include <asm/tlbflush.h>
59 #include <asm/div64.h>
61 #include <linux/swapops.h>
62 #include <linux/balloon_compaction.h>
63 #include <linux/sched/sysctl.h>
68 #define CREATE_TRACE_POINTS
69 #include <trace/events/vmscan.h>
72 /* How many pages shrink_list() should reclaim */
73 unsigned long nr_to_reclaim;
76 * Nodemask of nodes allowed by the caller. If NULL, all nodes
82 * The memory cgroup that hit its limit and as a result is the
83 * primary target of this reclaim invocation.
85 struct mem_cgroup *target_mem_cgroup;
88 * Scan pressure balancing between anon and file LRUs
90 unsigned long anon_cost;
91 unsigned long file_cost;
93 /* Can active folios be deactivated as part of reclaim? */
94 #define DEACTIVATE_ANON 1
95 #define DEACTIVATE_FILE 2
96 unsigned int may_deactivate:2;
97 unsigned int force_deactivate:1;
98 unsigned int skipped_deactivate:1;
100 /* Writepage batching in laptop mode; RECLAIM_WRITE */
101 unsigned int may_writepage:1;
103 /* Can mapped folios be reclaimed? */
104 unsigned int may_unmap:1;
106 /* Can folios be swapped as part of reclaim? */
107 unsigned int may_swap:1;
109 /* Proactive reclaim invoked by userspace through memory.reclaim */
110 unsigned int proactive:1;
113 * Cgroup memory below memory.low is protected as long as we
114 * don't threaten to OOM. If any cgroup is reclaimed at
115 * reduced force or passed over entirely due to its memory.low
116 * setting (memcg_low_skipped), and nothing is reclaimed as a
117 * result, then go back for one more cycle that reclaims the protected
118 * memory (memcg_low_reclaim) to avert OOM.
120 unsigned int memcg_low_reclaim:1;
121 unsigned int memcg_low_skipped:1;
123 unsigned int hibernation_mode:1;
125 /* One of the zones is ready for compaction */
126 unsigned int compaction_ready:1;
128 /* There is easily reclaimable cold cache in the current node */
129 unsigned int cache_trim_mode:1;
131 /* The file folios on the current node are dangerously low */
132 unsigned int file_is_tiny:1;
134 /* Always discard instead of demoting to lower tier memory */
135 unsigned int no_demotion:1;
137 #ifdef CONFIG_LRU_GEN
138 /* help kswapd make better choices among multiple memcgs */
139 unsigned int memcgs_need_aging:1;
140 unsigned long last_reclaimed;
143 /* Allocation order */
146 /* Scan (total_size >> priority) pages at once */
149 /* The highest zone to isolate folios for reclaim from */
152 /* This context's GFP mask */
155 /* Incremented by the number of inactive pages that were scanned */
156 unsigned long nr_scanned;
158 /* Number of pages freed so far during a call to shrink_zones() */
159 unsigned long nr_reclaimed;
163 unsigned int unqueued_dirty;
164 unsigned int congested;
165 unsigned int writeback;
166 unsigned int immediate;
167 unsigned int file_taken;
171 /* for recording the reclaimed slab by now */
172 struct reclaim_state reclaim_state;
175 #ifdef ARCH_HAS_PREFETCHW
176 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
178 if ((_folio)->lru.prev != _base) { \
179 struct folio *prev; \
181 prev = lru_to_folio(&(_folio->lru)); \
182 prefetchw(&prev->_field); \
186 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
190 * From 0 .. 200. Higher means more swappy.
192 int vm_swappiness = 60;
194 static void set_task_reclaim_state(struct task_struct *task,
195 struct reclaim_state *rs)
197 /* Check for an overwrite */
198 WARN_ON_ONCE(rs && task->reclaim_state);
200 /* Check for the nulling of an already-nulled member */
201 WARN_ON_ONCE(!rs && !task->reclaim_state);
203 task->reclaim_state = rs;
206 LIST_HEAD(shrinker_list);
207 DECLARE_RWSEM(shrinker_rwsem);
210 static int shrinker_nr_max;
212 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
213 static inline int shrinker_map_size(int nr_items)
215 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
218 static inline int shrinker_defer_size(int nr_items)
220 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
223 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
226 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
227 lockdep_is_held(&shrinker_rwsem));
230 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
231 int map_size, int defer_size,
232 int old_map_size, int old_defer_size)
234 struct shrinker_info *new, *old;
235 struct mem_cgroup_per_node *pn;
237 int size = map_size + defer_size;
240 pn = memcg->nodeinfo[nid];
241 old = shrinker_info_protected(memcg, nid);
242 /* Not yet online memcg */
246 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
250 new->nr_deferred = (atomic_long_t *)(new + 1);
251 new->map = (void *)new->nr_deferred + defer_size;
253 /* map: set all old bits, clear all new bits */
254 memset(new->map, (int)0xff, old_map_size);
255 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
256 /* nr_deferred: copy old values, clear all new values */
257 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
258 memset((void *)new->nr_deferred + old_defer_size, 0,
259 defer_size - old_defer_size);
261 rcu_assign_pointer(pn->shrinker_info, new);
262 kvfree_rcu(old, rcu);
268 void free_shrinker_info(struct mem_cgroup *memcg)
270 struct mem_cgroup_per_node *pn;
271 struct shrinker_info *info;
275 pn = memcg->nodeinfo[nid];
276 info = rcu_dereference_protected(pn->shrinker_info, true);
278 rcu_assign_pointer(pn->shrinker_info, NULL);
282 int alloc_shrinker_info(struct mem_cgroup *memcg)
284 struct shrinker_info *info;
285 int nid, size, ret = 0;
286 int map_size, defer_size = 0;
288 down_write(&shrinker_rwsem);
289 map_size = shrinker_map_size(shrinker_nr_max);
290 defer_size = shrinker_defer_size(shrinker_nr_max);
291 size = map_size + defer_size;
293 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
295 free_shrinker_info(memcg);
299 info->nr_deferred = (atomic_long_t *)(info + 1);
300 info->map = (void *)info->nr_deferred + defer_size;
301 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
303 up_write(&shrinker_rwsem);
308 static inline bool need_expand(int nr_max)
310 return round_up(nr_max, BITS_PER_LONG) >
311 round_up(shrinker_nr_max, BITS_PER_LONG);
314 static int expand_shrinker_info(int new_id)
317 int new_nr_max = new_id + 1;
318 int map_size, defer_size = 0;
319 int old_map_size, old_defer_size = 0;
320 struct mem_cgroup *memcg;
322 if (!need_expand(new_nr_max))
325 if (!root_mem_cgroup)
328 lockdep_assert_held(&shrinker_rwsem);
330 map_size = shrinker_map_size(new_nr_max);
331 defer_size = shrinker_defer_size(new_nr_max);
332 old_map_size = shrinker_map_size(shrinker_nr_max);
333 old_defer_size = shrinker_defer_size(shrinker_nr_max);
335 memcg = mem_cgroup_iter(NULL, NULL, NULL);
337 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
338 old_map_size, old_defer_size);
340 mem_cgroup_iter_break(NULL, memcg);
343 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
346 shrinker_nr_max = new_nr_max;
351 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
353 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
354 struct shrinker_info *info;
357 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
358 /* Pairs with smp mb in shrink_slab() */
359 smp_mb__before_atomic();
360 set_bit(shrinker_id, info->map);
365 static DEFINE_IDR(shrinker_idr);
367 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
369 int id, ret = -ENOMEM;
371 if (mem_cgroup_disabled())
374 down_write(&shrinker_rwsem);
375 /* This may call shrinker, so it must use down_read_trylock() */
376 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
380 if (id >= shrinker_nr_max) {
381 if (expand_shrinker_info(id)) {
382 idr_remove(&shrinker_idr, id);
389 up_write(&shrinker_rwsem);
393 static void unregister_memcg_shrinker(struct shrinker *shrinker)
395 int id = shrinker->id;
399 lockdep_assert_held(&shrinker_rwsem);
401 idr_remove(&shrinker_idr, id);
404 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
405 struct mem_cgroup *memcg)
407 struct shrinker_info *info;
409 info = shrinker_info_protected(memcg, nid);
410 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
413 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
414 struct mem_cgroup *memcg)
416 struct shrinker_info *info;
418 info = shrinker_info_protected(memcg, nid);
419 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
422 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
426 struct mem_cgroup *parent;
427 struct shrinker_info *child_info, *parent_info;
429 parent = parent_mem_cgroup(memcg);
431 parent = root_mem_cgroup;
433 /* Prevent from concurrent shrinker_info expand */
434 down_read(&shrinker_rwsem);
436 child_info = shrinker_info_protected(memcg, nid);
437 parent_info = shrinker_info_protected(parent, nid);
438 for (i = 0; i < shrinker_nr_max; i++) {
439 nr = atomic_long_read(&child_info->nr_deferred[i]);
440 atomic_long_add(nr, &parent_info->nr_deferred[i]);
443 up_read(&shrinker_rwsem);
446 static bool cgroup_reclaim(struct scan_control *sc)
448 return sc->target_mem_cgroup;
452 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
453 * @sc: scan_control in question
455 * The normal page dirty throttling mechanism in balance_dirty_pages() is
456 * completely broken with the legacy memcg and direct stalling in
457 * shrink_folio_list() is used for throttling instead, which lacks all the
458 * niceties such as fairness, adaptive pausing, bandwidth proportional
459 * allocation and configurability.
461 * This function tests whether the vmscan currently in progress can assume
462 * that the normal dirty throttling mechanism is operational.
464 static bool writeback_throttling_sane(struct scan_control *sc)
466 if (!cgroup_reclaim(sc))
468 #ifdef CONFIG_CGROUP_WRITEBACK
469 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
475 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
480 static void unregister_memcg_shrinker(struct shrinker *shrinker)
484 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
485 struct mem_cgroup *memcg)
490 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
491 struct mem_cgroup *memcg)
496 static bool cgroup_reclaim(struct scan_control *sc)
501 static bool writeback_throttling_sane(struct scan_control *sc)
507 static long xchg_nr_deferred(struct shrinker *shrinker,
508 struct shrink_control *sc)
512 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
516 (shrinker->flags & SHRINKER_MEMCG_AWARE))
517 return xchg_nr_deferred_memcg(nid, shrinker,
520 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
524 static long add_nr_deferred(long nr, struct shrinker *shrinker,
525 struct shrink_control *sc)
529 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
533 (shrinker->flags & SHRINKER_MEMCG_AWARE))
534 return add_nr_deferred_memcg(nr, nid, shrinker,
537 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
540 static bool can_demote(int nid, struct scan_control *sc)
542 if (!numa_demotion_enabled)
544 if (sc && sc->no_demotion)
546 if (next_demotion_node(nid) == NUMA_NO_NODE)
552 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
554 struct scan_control *sc)
558 * For non-memcg reclaim, is there
559 * space in any swap device?
561 if (get_nr_swap_pages() > 0)
564 /* Is the memcg below its swap limit? */
565 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
570 * The page can not be swapped.
572 * Can it be reclaimed from this node via demotion?
574 return can_demote(nid, sc);
578 * This misses isolated folios which are not accounted for to save counters.
579 * As the data only determines if reclaim or compaction continues, it is
580 * not expected that isolated folios will be a dominating factor.
582 unsigned long zone_reclaimable_pages(struct zone *zone)
586 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
587 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
588 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
589 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
590 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
596 * lruvec_lru_size - Returns the number of pages on the given LRU list.
597 * @lruvec: lru vector
599 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
601 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
604 unsigned long size = 0;
607 for (zid = 0; zid <= zone_idx; zid++) {
608 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
610 if (!managed_zone(zone))
613 if (!mem_cgroup_disabled())
614 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
616 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
622 * Add a shrinker callback to be called from the vm.
624 static int __prealloc_shrinker(struct shrinker *shrinker)
629 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
630 err = prealloc_memcg_shrinker(shrinker);
634 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
637 size = sizeof(*shrinker->nr_deferred);
638 if (shrinker->flags & SHRINKER_NUMA_AWARE)
641 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
642 if (!shrinker->nr_deferred)
648 #ifdef CONFIG_SHRINKER_DEBUG
649 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
655 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
660 err = __prealloc_shrinker(shrinker);
662 kfree_const(shrinker->name);
663 shrinker->name = NULL;
669 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
671 return __prealloc_shrinker(shrinker);
675 void free_prealloced_shrinker(struct shrinker *shrinker)
677 #ifdef CONFIG_SHRINKER_DEBUG
678 kfree_const(shrinker->name);
679 shrinker->name = NULL;
681 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
682 down_write(&shrinker_rwsem);
683 unregister_memcg_shrinker(shrinker);
684 up_write(&shrinker_rwsem);
688 kfree(shrinker->nr_deferred);
689 shrinker->nr_deferred = NULL;
692 void register_shrinker_prepared(struct shrinker *shrinker)
694 down_write(&shrinker_rwsem);
695 list_add_tail(&shrinker->list, &shrinker_list);
696 shrinker->flags |= SHRINKER_REGISTERED;
697 shrinker_debugfs_add(shrinker);
698 up_write(&shrinker_rwsem);
701 static int __register_shrinker(struct shrinker *shrinker)
703 int err = __prealloc_shrinker(shrinker);
707 register_shrinker_prepared(shrinker);
711 #ifdef CONFIG_SHRINKER_DEBUG
712 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
718 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
723 err = __register_shrinker(shrinker);
725 kfree_const(shrinker->name);
726 shrinker->name = NULL;
731 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
733 return __register_shrinker(shrinker);
736 EXPORT_SYMBOL(register_shrinker);
741 void unregister_shrinker(struct shrinker *shrinker)
743 if (!(shrinker->flags & SHRINKER_REGISTERED))
746 down_write(&shrinker_rwsem);
747 list_del(&shrinker->list);
748 shrinker->flags &= ~SHRINKER_REGISTERED;
749 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
750 unregister_memcg_shrinker(shrinker);
751 shrinker_debugfs_remove(shrinker);
752 up_write(&shrinker_rwsem);
754 kfree(shrinker->nr_deferred);
755 shrinker->nr_deferred = NULL;
757 EXPORT_SYMBOL(unregister_shrinker);
760 * synchronize_shrinkers - Wait for all running shrinkers to complete.
762 * This is equivalent to calling unregister_shrink() and register_shrinker(),
763 * but atomically and with less overhead. This is useful to guarantee that all
764 * shrinker invocations have seen an update, before freeing memory, similar to
767 void synchronize_shrinkers(void)
769 down_write(&shrinker_rwsem);
770 up_write(&shrinker_rwsem);
772 EXPORT_SYMBOL(synchronize_shrinkers);
774 #define SHRINK_BATCH 128
776 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
777 struct shrinker *shrinker, int priority)
779 unsigned long freed = 0;
780 unsigned long long delta;
785 long batch_size = shrinker->batch ? shrinker->batch
787 long scanned = 0, next_deferred;
789 freeable = shrinker->count_objects(shrinker, shrinkctl);
790 if (freeable == 0 || freeable == SHRINK_EMPTY)
794 * copy the current shrinker scan count into a local variable
795 * and zero it so that other concurrent shrinker invocations
796 * don't also do this scanning work.
798 nr = xchg_nr_deferred(shrinker, shrinkctl);
800 if (shrinker->seeks) {
801 delta = freeable >> priority;
803 do_div(delta, shrinker->seeks);
806 * These objects don't require any IO to create. Trim
807 * them aggressively under memory pressure to keep
808 * them from causing refetches in the IO caches.
810 delta = freeable / 2;
813 total_scan = nr >> priority;
815 total_scan = min(total_scan, (2 * freeable));
817 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
818 freeable, delta, total_scan, priority);
821 * Normally, we should not scan less than batch_size objects in one
822 * pass to avoid too frequent shrinker calls, but if the slab has less
823 * than batch_size objects in total and we are really tight on memory,
824 * we will try to reclaim all available objects, otherwise we can end
825 * up failing allocations although there are plenty of reclaimable
826 * objects spread over several slabs with usage less than the
829 * We detect the "tight on memory" situations by looking at the total
830 * number of objects we want to scan (total_scan). If it is greater
831 * than the total number of objects on slab (freeable), we must be
832 * scanning at high prio and therefore should try to reclaim as much as
835 while (total_scan >= batch_size ||
836 total_scan >= freeable) {
838 unsigned long nr_to_scan = min(batch_size, total_scan);
840 shrinkctl->nr_to_scan = nr_to_scan;
841 shrinkctl->nr_scanned = nr_to_scan;
842 ret = shrinker->scan_objects(shrinker, shrinkctl);
843 if (ret == SHRINK_STOP)
847 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
848 total_scan -= shrinkctl->nr_scanned;
849 scanned += shrinkctl->nr_scanned;
855 * The deferred work is increased by any new work (delta) that wasn't
856 * done, decreased by old deferred work that was done now.
858 * And it is capped to two times of the freeable items.
860 next_deferred = max_t(long, (nr + delta - scanned), 0);
861 next_deferred = min(next_deferred, (2 * freeable));
864 * move the unused scan count back into the shrinker in a
865 * manner that handles concurrent updates.
867 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
869 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
874 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
875 struct mem_cgroup *memcg, int priority)
877 struct shrinker_info *info;
878 unsigned long ret, freed = 0;
881 if (!mem_cgroup_online(memcg))
884 if (!down_read_trylock(&shrinker_rwsem))
887 info = shrinker_info_protected(memcg, nid);
891 for_each_set_bit(i, info->map, shrinker_nr_max) {
892 struct shrink_control sc = {
893 .gfp_mask = gfp_mask,
897 struct shrinker *shrinker;
899 shrinker = idr_find(&shrinker_idr, i);
900 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
902 clear_bit(i, info->map);
906 /* Call non-slab shrinkers even though kmem is disabled */
907 if (!memcg_kmem_enabled() &&
908 !(shrinker->flags & SHRINKER_NONSLAB))
911 ret = do_shrink_slab(&sc, shrinker, priority);
912 if (ret == SHRINK_EMPTY) {
913 clear_bit(i, info->map);
915 * After the shrinker reported that it had no objects to
916 * free, but before we cleared the corresponding bit in
917 * the memcg shrinker map, a new object might have been
918 * added. To make sure, we have the bit set in this
919 * case, we invoke the shrinker one more time and reset
920 * the bit if it reports that it is not empty anymore.
921 * The memory barrier here pairs with the barrier in
922 * set_shrinker_bit():
924 * list_lru_add() shrink_slab_memcg()
925 * list_add_tail() clear_bit()
927 * set_bit() do_shrink_slab()
929 smp_mb__after_atomic();
930 ret = do_shrink_slab(&sc, shrinker, priority);
931 if (ret == SHRINK_EMPTY)
934 set_shrinker_bit(memcg, nid, i);
938 if (rwsem_is_contended(&shrinker_rwsem)) {
944 up_read(&shrinker_rwsem);
947 #else /* CONFIG_MEMCG */
948 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
949 struct mem_cgroup *memcg, int priority)
953 #endif /* CONFIG_MEMCG */
956 * shrink_slab - shrink slab caches
957 * @gfp_mask: allocation context
958 * @nid: node whose slab caches to target
959 * @memcg: memory cgroup whose slab caches to target
960 * @priority: the reclaim priority
962 * Call the shrink functions to age shrinkable caches.
964 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
965 * unaware shrinkers will receive a node id of 0 instead.
967 * @memcg specifies the memory cgroup to target. Unaware shrinkers
968 * are called only if it is the root cgroup.
970 * @priority is sc->priority, we take the number of objects and >> by priority
971 * in order to get the scan target.
973 * Returns the number of reclaimed slab objects.
975 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
976 struct mem_cgroup *memcg,
979 unsigned long ret, freed = 0;
980 struct shrinker *shrinker;
983 * The root memcg might be allocated even though memcg is disabled
984 * via "cgroup_disable=memory" boot parameter. This could make
985 * mem_cgroup_is_root() return false, then just run memcg slab
986 * shrink, but skip global shrink. This may result in premature
989 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
990 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
992 if (!down_read_trylock(&shrinker_rwsem))
995 list_for_each_entry(shrinker, &shrinker_list, list) {
996 struct shrink_control sc = {
997 .gfp_mask = gfp_mask,
1002 ret = do_shrink_slab(&sc, shrinker, priority);
1003 if (ret == SHRINK_EMPTY)
1007 * Bail out if someone want to register a new shrinker to
1008 * prevent the registration from being stalled for long periods
1009 * by parallel ongoing shrinking.
1011 if (rwsem_is_contended(&shrinker_rwsem)) {
1012 freed = freed ? : 1;
1017 up_read(&shrinker_rwsem);
1023 static void drop_slab_node(int nid)
1025 unsigned long freed;
1029 struct mem_cgroup *memcg = NULL;
1031 if (fatal_signal_pending(current))
1035 memcg = mem_cgroup_iter(NULL, NULL, NULL);
1037 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1038 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1039 } while ((freed >> shift++) > 1);
1042 void drop_slab(void)
1046 for_each_online_node(nid)
1047 drop_slab_node(nid);
1050 static inline int is_page_cache_freeable(struct folio *folio)
1053 * A freeable page cache folio is referenced only by the caller
1054 * that isolated the folio, the page cache and optional filesystem
1055 * private data at folio->private.
1057 return folio_ref_count(folio) - folio_test_private(folio) ==
1058 1 + folio_nr_pages(folio);
1062 * We detected a synchronous write error writing a folio out. Probably
1063 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1064 * fsync(), msync() or close().
1066 * The tricky part is that after writepage we cannot touch the mapping: nothing
1067 * prevents it from being freed up. But we have a ref on the folio and once
1068 * that folio is locked, the mapping is pinned.
1070 * We're allowed to run sleeping folio_lock() here because we know the caller has
1073 static void handle_write_error(struct address_space *mapping,
1074 struct folio *folio, int error)
1077 if (folio_mapping(folio) == mapping)
1078 mapping_set_error(mapping, error);
1079 folio_unlock(folio);
1082 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1084 int reclaimable = 0, write_pending = 0;
1088 * If kswapd is disabled, reschedule if necessary but do not
1089 * throttle as the system is likely near OOM.
1091 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1095 * If there are a lot of dirty/writeback folios then do not
1096 * throttle as throttling will occur when the folios cycle
1097 * towards the end of the LRU if still under writeback.
1099 for (i = 0; i < MAX_NR_ZONES; i++) {
1100 struct zone *zone = pgdat->node_zones + i;
1102 if (!managed_zone(zone))
1105 reclaimable += zone_reclaimable_pages(zone);
1106 write_pending += zone_page_state_snapshot(zone,
1107 NR_ZONE_WRITE_PENDING);
1109 if (2 * write_pending <= reclaimable)
1115 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1117 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1122 * Do not throttle IO workers, kthreads other than kswapd or
1123 * workqueues. They may be required for reclaim to make
1124 * forward progress (e.g. journalling workqueues or kthreads).
1126 if (!current_is_kswapd() &&
1127 current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1133 * These figures are pulled out of thin air.
1134 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1135 * parallel reclaimers which is a short-lived event so the timeout is
1136 * short. Failing to make progress or waiting on writeback are
1137 * potentially long-lived events so use a longer timeout. This is shaky
1138 * logic as a failure to make progress could be due to anything from
1139 * writeback to a slow device to excessive referenced folios at the tail
1140 * of the inactive LRU.
1143 case VMSCAN_THROTTLE_WRITEBACK:
1146 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1147 WRITE_ONCE(pgdat->nr_reclaim_start,
1148 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1152 case VMSCAN_THROTTLE_CONGESTED:
1154 case VMSCAN_THROTTLE_NOPROGRESS:
1155 if (skip_throttle_noprogress(pgdat)) {
1163 case VMSCAN_THROTTLE_ISOLATED:
1172 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1173 ret = schedule_timeout(timeout);
1174 finish_wait(wqh, &wait);
1176 if (reason == VMSCAN_THROTTLE_WRITEBACK)
1177 atomic_dec(&pgdat->nr_writeback_throttled);
1179 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1180 jiffies_to_usecs(timeout - ret),
1185 * Account for folios written if tasks are throttled waiting on dirty
1186 * folios to clean. If enough folios have been cleaned since throttling
1187 * started then wakeup the throttled tasks.
1189 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1192 unsigned long nr_written;
1194 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1197 * This is an inaccurate read as the per-cpu deltas may not
1198 * be synchronised. However, given that the system is
1199 * writeback throttled, it is not worth taking the penalty
1200 * of getting an accurate count. At worst, the throttle
1201 * timeout guarantees forward progress.
1203 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1204 READ_ONCE(pgdat->nr_reclaim_start);
1206 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1207 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1210 /* possible outcome of pageout() */
1212 /* failed to write folio out, folio is locked */
1214 /* move folio to the active list, folio is locked */
1216 /* folio has been sent to the disk successfully, folio is unlocked */
1218 /* folio is clean and locked */
1223 * pageout is called by shrink_folio_list() for each dirty folio.
1224 * Calls ->writepage().
1226 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1227 struct swap_iocb **plug)
1230 * If the folio is dirty, only perform writeback if that write
1231 * will be non-blocking. To prevent this allocation from being
1232 * stalled by pagecache activity. But note that there may be
1233 * stalls if we need to run get_block(). We could test
1234 * PagePrivate for that.
1236 * If this process is currently in __generic_file_write_iter() against
1237 * this folio's queue, we can perform writeback even if that
1240 * If the folio is swapcache, write it back even if that would
1241 * block, for some throttling. This happens by accident, because
1242 * swap_backing_dev_info is bust: it doesn't reflect the
1243 * congestion state of the swapdevs. Easy to fix, if needed.
1245 if (!is_page_cache_freeable(folio))
1249 * Some data journaling orphaned folios can have
1250 * folio->mapping == NULL while being dirty with clean buffers.
1252 if (folio_test_private(folio)) {
1253 if (try_to_free_buffers(folio)) {
1254 folio_clear_dirty(folio);
1255 pr_info("%s: orphaned folio\n", __func__);
1261 if (mapping->a_ops->writepage == NULL)
1262 return PAGE_ACTIVATE;
1264 if (folio_clear_dirty_for_io(folio)) {
1266 struct writeback_control wbc = {
1267 .sync_mode = WB_SYNC_NONE,
1268 .nr_to_write = SWAP_CLUSTER_MAX,
1270 .range_end = LLONG_MAX,
1275 folio_set_reclaim(folio);
1276 res = mapping->a_ops->writepage(&folio->page, &wbc);
1278 handle_write_error(mapping, folio, res);
1279 if (res == AOP_WRITEPAGE_ACTIVATE) {
1280 folio_clear_reclaim(folio);
1281 return PAGE_ACTIVATE;
1284 if (!folio_test_writeback(folio)) {
1285 /* synchronous write or broken a_ops? */
1286 folio_clear_reclaim(folio);
1288 trace_mm_vmscan_write_folio(folio);
1289 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1290 return PAGE_SUCCESS;
1297 * Same as remove_mapping, but if the folio is removed from the mapping, it
1298 * gets returned with a refcount of 0.
1300 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1301 bool reclaimed, struct mem_cgroup *target_memcg)
1304 void *shadow = NULL;
1306 BUG_ON(!folio_test_locked(folio));
1307 BUG_ON(mapping != folio_mapping(folio));
1309 if (!folio_test_swapcache(folio))
1310 spin_lock(&mapping->host->i_lock);
1311 xa_lock_irq(&mapping->i_pages);
1313 * The non racy check for a busy folio.
1315 * Must be careful with the order of the tests. When someone has
1316 * a ref to the folio, it may be possible that they dirty it then
1317 * drop the reference. So if the dirty flag is tested before the
1318 * refcount here, then the following race may occur:
1320 * get_user_pages(&page);
1321 * [user mapping goes away]
1323 * !folio_test_dirty(folio) [good]
1324 * folio_set_dirty(folio);
1326 * !refcount(folio) [good, discard it]
1328 * [oops, our write_to data is lost]
1330 * Reversing the order of the tests ensures such a situation cannot
1331 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
1332 * load is not satisfied before that of folio->_refcount.
1334 * Note that if the dirty flag is always set via folio_mark_dirty,
1335 * and thus under the i_pages lock, then this ordering is not required.
1337 refcount = 1 + folio_nr_pages(folio);
1338 if (!folio_ref_freeze(folio, refcount))
1340 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
1341 if (unlikely(folio_test_dirty(folio))) {
1342 folio_ref_unfreeze(folio, refcount);
1346 if (folio_test_swapcache(folio)) {
1347 swp_entry_t swap = folio_swap_entry(folio);
1349 /* get a shadow entry before mem_cgroup_swapout() clears folio_memcg() */
1350 if (reclaimed && !mapping_exiting(mapping))
1351 shadow = workingset_eviction(folio, target_memcg);
1352 mem_cgroup_swapout(folio, swap);
1353 __delete_from_swap_cache(folio, swap, shadow);
1354 xa_unlock_irq(&mapping->i_pages);
1355 put_swap_folio(folio, swap);
1357 void (*free_folio)(struct folio *);
1359 free_folio = mapping->a_ops->free_folio;
1361 * Remember a shadow entry for reclaimed file cache in
1362 * order to detect refaults, thus thrashing, later on.
1364 * But don't store shadows in an address space that is
1365 * already exiting. This is not just an optimization,
1366 * inode reclaim needs to empty out the radix tree or
1367 * the nodes are lost. Don't plant shadows behind its
1370 * We also don't store shadows for DAX mappings because the
1371 * only page cache folios found in these are zero pages
1372 * covering holes, and because we don't want to mix DAX
1373 * exceptional entries and shadow exceptional entries in the
1374 * same address_space.
1376 if (reclaimed && folio_is_file_lru(folio) &&
1377 !mapping_exiting(mapping) && !dax_mapping(mapping))
1378 shadow = workingset_eviction(folio, target_memcg);
1379 __filemap_remove_folio(folio, shadow);
1380 xa_unlock_irq(&mapping->i_pages);
1381 if (mapping_shrinkable(mapping))
1382 inode_add_lru(mapping->host);
1383 spin_unlock(&mapping->host->i_lock);
1392 xa_unlock_irq(&mapping->i_pages);
1393 if (!folio_test_swapcache(folio))
1394 spin_unlock(&mapping->host->i_lock);
1399 * remove_mapping() - Attempt to remove a folio from its mapping.
1400 * @mapping: The address space.
1401 * @folio: The folio to remove.
1403 * If the folio is dirty, under writeback or if someone else has a ref
1404 * on it, removal will fail.
1405 * Return: The number of pages removed from the mapping. 0 if the folio
1406 * could not be removed.
1407 * Context: The caller should have a single refcount on the folio and
1410 long remove_mapping(struct address_space *mapping, struct folio *folio)
1412 if (__remove_mapping(mapping, folio, false, NULL)) {
1414 * Unfreezing the refcount with 1 effectively
1415 * drops the pagecache ref for us without requiring another
1418 folio_ref_unfreeze(folio, 1);
1419 return folio_nr_pages(folio);
1425 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1426 * @folio: Folio to be returned to an LRU list.
1428 * Add previously isolated @folio to appropriate LRU list.
1429 * The folio may still be unevictable for other reasons.
1431 * Context: lru_lock must not be held, interrupts must be enabled.
1433 void folio_putback_lru(struct folio *folio)
1435 folio_add_lru(folio);
1436 folio_put(folio); /* drop ref from isolate */
1439 enum folio_references {
1441 FOLIOREF_RECLAIM_CLEAN,
1446 static enum folio_references folio_check_references(struct folio *folio,
1447 struct scan_control *sc)
1449 int referenced_ptes, referenced_folio;
1450 unsigned long vm_flags;
1452 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1454 referenced_folio = folio_test_clear_referenced(folio);
1457 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1458 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1460 if (vm_flags & VM_LOCKED)
1461 return FOLIOREF_ACTIVATE;
1463 /* rmap lock contention: rotate */
1464 if (referenced_ptes == -1)
1465 return FOLIOREF_KEEP;
1467 if (referenced_ptes) {
1469 * All mapped folios start out with page table
1470 * references from the instantiating fault, so we need
1471 * to look twice if a mapped file/anon folio is used more
1474 * Mark it and spare it for another trip around the
1475 * inactive list. Another page table reference will
1476 * lead to its activation.
1478 * Note: the mark is set for activated folios as well
1479 * so that recently deactivated but used folios are
1480 * quickly recovered.
1482 folio_set_referenced(folio);
1484 if (referenced_folio || referenced_ptes > 1)
1485 return FOLIOREF_ACTIVATE;
1488 * Activate file-backed executable folios after first usage.
1490 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1491 return FOLIOREF_ACTIVATE;
1493 return FOLIOREF_KEEP;
1496 /* Reclaim if clean, defer dirty folios to writeback */
1497 if (referenced_folio && folio_is_file_lru(folio))
1498 return FOLIOREF_RECLAIM_CLEAN;
1500 return FOLIOREF_RECLAIM;
1503 /* Check if a folio is dirty or under writeback */
1504 static void folio_check_dirty_writeback(struct folio *folio,
1505 bool *dirty, bool *writeback)
1507 struct address_space *mapping;
1510 * Anonymous folios are not handled by flushers and must be written
1511 * from reclaim context. Do not stall reclaim based on them.
1512 * MADV_FREE anonymous folios are put into inactive file list too.
1513 * They could be mistakenly treated as file lru. So further anon
1516 if (!folio_is_file_lru(folio) ||
1517 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1523 /* By default assume that the folio flags are accurate */
1524 *dirty = folio_test_dirty(folio);
1525 *writeback = folio_test_writeback(folio);
1527 /* Verify dirty/writeback state if the filesystem supports it */
1528 if (!folio_test_private(folio))
1531 mapping = folio_mapping(folio);
1532 if (mapping && mapping->a_ops->is_dirty_writeback)
1533 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1536 static struct page *alloc_demote_page(struct page *page, unsigned long private)
1538 struct page *target_page;
1539 nodemask_t *allowed_mask;
1540 struct migration_target_control *mtc;
1542 mtc = (struct migration_target_control *)private;
1544 allowed_mask = mtc->nmask;
1546 * make sure we allocate from the target node first also trying to
1547 * demote or reclaim pages from the target node via kswapd if we are
1548 * low on free memory on target node. If we don't do this and if
1549 * we have free memory on the slower(lower) memtier, we would start
1550 * allocating pages from slower(lower) memory tiers without even forcing
1551 * a demotion of cold pages from the target memtier. This can result
1552 * in the kernel placing hot pages in slower(lower) memory tiers.
1555 mtc->gfp_mask |= __GFP_THISNODE;
1556 target_page = alloc_migration_target(page, (unsigned long)mtc);
1560 mtc->gfp_mask &= ~__GFP_THISNODE;
1561 mtc->nmask = allowed_mask;
1563 return alloc_migration_target(page, (unsigned long)mtc);
1567 * Take folios on @demote_folios and attempt to demote them to another node.
1568 * Folios which are not demoted are left on @demote_folios.
1570 static unsigned int demote_folio_list(struct list_head *demote_folios,
1571 struct pglist_data *pgdat)
1573 int target_nid = next_demotion_node(pgdat->node_id);
1574 unsigned int nr_succeeded;
1575 nodemask_t allowed_mask;
1577 struct migration_target_control mtc = {
1579 * Allocate from 'node', or fail quickly and quietly.
1580 * When this happens, 'page' will likely just be discarded
1581 * instead of migrated.
1583 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1584 __GFP_NOMEMALLOC | GFP_NOWAIT,
1586 .nmask = &allowed_mask
1589 if (list_empty(demote_folios))
1592 if (target_nid == NUMA_NO_NODE)
1595 node_get_allowed_targets(pgdat, &allowed_mask);
1597 /* Demotion ignores all cpuset and mempolicy settings */
1598 migrate_pages(demote_folios, alloc_demote_page, NULL,
1599 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1602 if (current_is_kswapd())
1603 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1605 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1607 return nr_succeeded;
1610 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1612 if (gfp_mask & __GFP_FS)
1614 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1617 * We can "enter_fs" for swap-cache with only __GFP_IO
1618 * providing this isn't SWP_FS_OPS.
1619 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1620 * but that will never affect SWP_FS_OPS, so the data_race
1623 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1627 * shrink_folio_list() returns the number of reclaimed pages
1629 static unsigned int shrink_folio_list(struct list_head *folio_list,
1630 struct pglist_data *pgdat, struct scan_control *sc,
1631 struct reclaim_stat *stat, bool ignore_references)
1633 LIST_HEAD(ret_folios);
1634 LIST_HEAD(free_folios);
1635 LIST_HEAD(demote_folios);
1636 unsigned int nr_reclaimed = 0;
1637 unsigned int pgactivate = 0;
1638 bool do_demote_pass;
1639 struct swap_iocb *plug = NULL;
1641 memset(stat, 0, sizeof(*stat));
1643 do_demote_pass = can_demote(pgdat->node_id, sc);
1646 while (!list_empty(folio_list)) {
1647 struct address_space *mapping;
1648 struct folio *folio;
1649 enum folio_references references = FOLIOREF_RECLAIM;
1650 bool dirty, writeback;
1651 unsigned int nr_pages;
1655 folio = lru_to_folio(folio_list);
1656 list_del(&folio->lru);
1658 if (!folio_trylock(folio))
1661 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1663 nr_pages = folio_nr_pages(folio);
1665 /* Account the number of base pages */
1666 sc->nr_scanned += nr_pages;
1668 if (unlikely(!folio_evictable(folio)))
1669 goto activate_locked;
1671 if (!sc->may_unmap && folio_mapped(folio))
1674 /* folio_update_gen() tried to promote this page? */
1675 if (lru_gen_enabled() && !ignore_references &&
1676 folio_mapped(folio) && folio_test_referenced(folio))
1680 * The number of dirty pages determines if a node is marked
1681 * reclaim_congested. kswapd will stall and start writing
1682 * folios if the tail of the LRU is all dirty unqueued folios.
1684 folio_check_dirty_writeback(folio, &dirty, &writeback);
1685 if (dirty || writeback)
1686 stat->nr_dirty += nr_pages;
1688 if (dirty && !writeback)
1689 stat->nr_unqueued_dirty += nr_pages;
1692 * Treat this folio as congested if folios are cycling
1693 * through the LRU so quickly that the folios marked
1694 * for immediate reclaim are making it to the end of
1695 * the LRU a second time.
1697 if (writeback && folio_test_reclaim(folio))
1698 stat->nr_congested += nr_pages;
1701 * If a folio at the tail of the LRU is under writeback, there
1702 * are three cases to consider.
1704 * 1) If reclaim is encountering an excessive number
1705 * of folios under writeback and this folio has both
1706 * the writeback and reclaim flags set, then it
1707 * indicates that folios are being queued for I/O but
1708 * are being recycled through the LRU before the I/O
1709 * can complete. Waiting on the folio itself risks an
1710 * indefinite stall if it is impossible to writeback
1711 * the folio due to I/O error or disconnected storage
1712 * so instead note that the LRU is being scanned too
1713 * quickly and the caller can stall after the folio
1714 * list has been processed.
1716 * 2) Global or new memcg reclaim encounters a folio that is
1717 * not marked for immediate reclaim, or the caller does not
1718 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1719 * not to fs). In this case mark the folio for immediate
1720 * reclaim and continue scanning.
1722 * Require may_enter_fs() because we would wait on fs, which
1723 * may not have submitted I/O yet. And the loop driver might
1724 * enter reclaim, and deadlock if it waits on a folio for
1725 * which it is needed to do the write (loop masks off
1726 * __GFP_IO|__GFP_FS for this reason); but more thought
1727 * would probably show more reasons.
1729 * 3) Legacy memcg encounters a folio that already has the
1730 * reclaim flag set. memcg does not have any dirty folio
1731 * throttling so we could easily OOM just because too many
1732 * folios are in writeback and there is nothing else to
1733 * reclaim. Wait for the writeback to complete.
1735 * In cases 1) and 2) we activate the folios to get them out of
1736 * the way while we continue scanning for clean folios on the
1737 * inactive list and refilling from the active list. The
1738 * observation here is that waiting for disk writes is more
1739 * expensive than potentially causing reloads down the line.
1740 * Since they're marked for immediate reclaim, they won't put
1741 * memory pressure on the cache working set any longer than it
1742 * takes to write them to disk.
1744 if (folio_test_writeback(folio)) {
1746 if (current_is_kswapd() &&
1747 folio_test_reclaim(folio) &&
1748 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1749 stat->nr_immediate += nr_pages;
1750 goto activate_locked;
1753 } else if (writeback_throttling_sane(sc) ||
1754 !folio_test_reclaim(folio) ||
1755 !may_enter_fs(folio, sc->gfp_mask)) {
1757 * This is slightly racy -
1758 * folio_end_writeback() might have
1759 * just cleared the reclaim flag, then
1760 * setting the reclaim flag here ends up
1761 * interpreted as the readahead flag - but
1762 * that does not matter enough to care.
1763 * What we do want is for this folio to
1764 * have the reclaim flag set next time
1765 * memcg reclaim reaches the tests above,
1766 * so it will then wait for writeback to
1767 * avoid OOM; and it's also appropriate
1768 * in global reclaim.
1770 folio_set_reclaim(folio);
1771 stat->nr_writeback += nr_pages;
1772 goto activate_locked;
1776 folio_unlock(folio);
1777 folio_wait_writeback(folio);
1778 /* then go back and try same folio again */
1779 list_add_tail(&folio->lru, folio_list);
1784 if (!ignore_references)
1785 references = folio_check_references(folio, sc);
1787 switch (references) {
1788 case FOLIOREF_ACTIVATE:
1789 goto activate_locked;
1791 stat->nr_ref_keep += nr_pages;
1793 case FOLIOREF_RECLAIM:
1794 case FOLIOREF_RECLAIM_CLEAN:
1795 ; /* try to reclaim the folio below */
1799 * Before reclaiming the folio, try to relocate
1800 * its contents to another node.
1802 if (do_demote_pass &&
1803 (thp_migration_supported() || !folio_test_large(folio))) {
1804 list_add(&folio->lru, &demote_folios);
1805 folio_unlock(folio);
1810 * Anonymous process memory has backing store?
1811 * Try to allocate it some swap space here.
1812 * Lazyfree folio could be freed directly
1814 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1815 if (!folio_test_swapcache(folio)) {
1816 if (!(sc->gfp_mask & __GFP_IO))
1818 if (folio_maybe_dma_pinned(folio))
1820 if (folio_test_large(folio)) {
1821 /* cannot split folio, skip it */
1822 if (!can_split_folio(folio, NULL))
1823 goto activate_locked;
1825 * Split folios without a PMD map right
1826 * away. Chances are some or all of the
1827 * tail pages can be freed without IO.
1829 if (!folio_entire_mapcount(folio) &&
1830 split_folio_to_list(folio,
1832 goto activate_locked;
1834 if (!add_to_swap(folio)) {
1835 if (!folio_test_large(folio))
1836 goto activate_locked_split;
1837 /* Fallback to swap normal pages */
1838 if (split_folio_to_list(folio,
1840 goto activate_locked;
1841 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1842 count_vm_event(THP_SWPOUT_FALLBACK);
1844 if (!add_to_swap(folio))
1845 goto activate_locked_split;
1848 } else if (folio_test_swapbacked(folio) &&
1849 folio_test_large(folio)) {
1850 /* Split shmem folio */
1851 if (split_folio_to_list(folio, folio_list))
1856 * If the folio was split above, the tail pages will make
1857 * their own pass through this function and be accounted
1860 if ((nr_pages > 1) && !folio_test_large(folio)) {
1861 sc->nr_scanned -= (nr_pages - 1);
1866 * The folio is mapped into the page tables of one or more
1867 * processes. Try to unmap it here.
1869 if (folio_mapped(folio)) {
1870 enum ttu_flags flags = TTU_BATCH_FLUSH;
1871 bool was_swapbacked = folio_test_swapbacked(folio);
1873 if (folio_test_pmd_mappable(folio))
1874 flags |= TTU_SPLIT_HUGE_PMD;
1876 try_to_unmap(folio, flags);
1877 if (folio_mapped(folio)) {
1878 stat->nr_unmap_fail += nr_pages;
1879 if (!was_swapbacked &&
1880 folio_test_swapbacked(folio))
1881 stat->nr_lazyfree_fail += nr_pages;
1882 goto activate_locked;
1886 mapping = folio_mapping(folio);
1887 if (folio_test_dirty(folio)) {
1889 * Only kswapd can writeback filesystem folios
1890 * to avoid risk of stack overflow. But avoid
1891 * injecting inefficient single-folio I/O into
1892 * flusher writeback as much as possible: only
1893 * write folios when we've encountered many
1894 * dirty folios, and when we've already scanned
1895 * the rest of the LRU for clean folios and see
1896 * the same dirty folios again (with the reclaim
1899 if (folio_is_file_lru(folio) &&
1900 (!current_is_kswapd() ||
1901 !folio_test_reclaim(folio) ||
1902 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1904 * Immediately reclaim when written back.
1905 * Similar in principle to deactivate_page()
1906 * except we already have the folio isolated
1907 * and know it's dirty
1909 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1911 folio_set_reclaim(folio);
1913 goto activate_locked;
1916 if (references == FOLIOREF_RECLAIM_CLEAN)
1918 if (!may_enter_fs(folio, sc->gfp_mask))
1920 if (!sc->may_writepage)
1924 * Folio is dirty. Flush the TLB if a writable entry
1925 * potentially exists to avoid CPU writes after I/O
1926 * starts and then write it out here.
1928 try_to_unmap_flush_dirty();
1929 switch (pageout(folio, mapping, &plug)) {
1933 goto activate_locked;
1935 stat->nr_pageout += nr_pages;
1937 if (folio_test_writeback(folio))
1939 if (folio_test_dirty(folio))
1943 * A synchronous write - probably a ramdisk. Go
1944 * ahead and try to reclaim the folio.
1946 if (!folio_trylock(folio))
1948 if (folio_test_dirty(folio) ||
1949 folio_test_writeback(folio))
1951 mapping = folio_mapping(folio);
1954 ; /* try to free the folio below */
1959 * If the folio has buffers, try to free the buffer
1960 * mappings associated with this folio. If we succeed
1961 * we try to free the folio as well.
1963 * We do this even if the folio is dirty.
1964 * filemap_release_folio() does not perform I/O, but it
1965 * is possible for a folio to have the dirty flag set,
1966 * but it is actually clean (all its buffers are clean).
1967 * This happens if the buffers were written out directly,
1968 * with submit_bh(). ext3 will do this, as well as
1969 * the blockdev mapping. filemap_release_folio() will
1970 * discover that cleanness and will drop the buffers
1971 * and mark the folio clean - it can be freed.
1973 * Rarely, folios can have buffers and no ->mapping.
1974 * These are the folios which were not successfully
1975 * invalidated in truncate_cleanup_folio(). We try to
1976 * drop those buffers here and if that worked, and the
1977 * folio is no longer mapped into process address space
1978 * (refcount == 1) it can be freed. Otherwise, leave
1979 * the folio on the LRU so it is swappable.
1981 if (folio_has_private(folio)) {
1982 if (!filemap_release_folio(folio, sc->gfp_mask))
1983 goto activate_locked;
1984 if (!mapping && folio_ref_count(folio) == 1) {
1985 folio_unlock(folio);
1986 if (folio_put_testzero(folio))
1990 * rare race with speculative reference.
1991 * the speculative reference will free
1992 * this folio shortly, so we may
1993 * increment nr_reclaimed here (and
1994 * leave it off the LRU).
1996 nr_reclaimed += nr_pages;
2002 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
2003 /* follow __remove_mapping for reference */
2004 if (!folio_ref_freeze(folio, 1))
2007 * The folio has only one reference left, which is
2008 * from the isolation. After the caller puts the
2009 * folio back on the lru and drops the reference, the
2010 * folio will be freed anyway. It doesn't matter
2011 * which lru it goes on. So we don't bother checking
2012 * the dirty flag here.
2014 count_vm_events(PGLAZYFREED, nr_pages);
2015 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
2016 } else if (!mapping || !__remove_mapping(mapping, folio, true,
2017 sc->target_mem_cgroup))
2020 folio_unlock(folio);
2023 * Folio may get swapped out as a whole, need to account
2026 nr_reclaimed += nr_pages;
2029 * Is there need to periodically free_folio_list? It would
2030 * appear not as the counts should be low
2032 if (unlikely(folio_test_large(folio)))
2033 destroy_large_folio(folio);
2035 list_add(&folio->lru, &free_folios);
2038 activate_locked_split:
2040 * The tail pages that are failed to add into swap cache
2041 * reach here. Fixup nr_scanned and nr_pages.
2044 sc->nr_scanned -= (nr_pages - 1);
2048 /* Not a candidate for swapping, so reclaim swap space. */
2049 if (folio_test_swapcache(folio) &&
2050 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
2051 folio_free_swap(folio);
2052 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2053 if (!folio_test_mlocked(folio)) {
2054 int type = folio_is_file_lru(folio);
2055 folio_set_active(folio);
2056 stat->nr_activate[type] += nr_pages;
2057 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2060 folio_unlock(folio);
2062 list_add(&folio->lru, &ret_folios);
2063 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2064 folio_test_unevictable(folio), folio);
2066 /* 'folio_list' is always empty here */
2068 /* Migrate folios selected for demotion */
2069 nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
2070 /* Folios that could not be demoted are still in @demote_folios */
2071 if (!list_empty(&demote_folios)) {
2072 /* Folios which weren't demoted go back on @folio_list for retry: */
2073 list_splice_init(&demote_folios, folio_list);
2074 do_demote_pass = false;
2078 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2080 mem_cgroup_uncharge_list(&free_folios);
2081 try_to_unmap_flush();
2082 free_unref_page_list(&free_folios);
2084 list_splice(&ret_folios, folio_list);
2085 count_vm_events(PGACTIVATE, pgactivate);
2088 swap_write_unplug(plug);
2089 return nr_reclaimed;
2092 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2093 struct list_head *folio_list)
2095 struct scan_control sc = {
2096 .gfp_mask = GFP_KERNEL,
2099 struct reclaim_stat stat;
2100 unsigned int nr_reclaimed;
2101 struct folio *folio, *next;
2102 LIST_HEAD(clean_folios);
2103 unsigned int noreclaim_flag;
2105 list_for_each_entry_safe(folio, next, folio_list, lru) {
2106 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2107 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2108 !folio_test_unevictable(folio)) {
2109 folio_clear_active(folio);
2110 list_move(&folio->lru, &clean_folios);
2115 * We should be safe here since we are only dealing with file pages and
2116 * we are not kswapd and therefore cannot write dirty file pages. But
2117 * call memalloc_noreclaim_save() anyway, just in case these conditions
2118 * change in the future.
2120 noreclaim_flag = memalloc_noreclaim_save();
2121 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
2123 memalloc_noreclaim_restore(noreclaim_flag);
2125 list_splice(&clean_folios, folio_list);
2126 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2127 -(long)nr_reclaimed);
2129 * Since lazyfree pages are isolated from file LRU from the beginning,
2130 * they will rotate back to anonymous LRU in the end if it failed to
2131 * discard so isolated count will be mismatched.
2132 * Compensate the isolated count for both LRU lists.
2134 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2135 stat.nr_lazyfree_fail);
2136 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2137 -(long)stat.nr_lazyfree_fail);
2138 return nr_reclaimed;
2142 * Update LRU sizes after isolating pages. The LRU size updates must
2143 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2145 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2146 enum lru_list lru, unsigned long *nr_zone_taken)
2150 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2151 if (!nr_zone_taken[zid])
2154 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2160 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2162 * lruvec->lru_lock is heavily contended. Some of the functions that
2163 * shrink the lists perform better by taking out a batch of pages
2164 * and working on them outside the LRU lock.
2166 * For pagecache intensive workloads, this function is the hottest
2167 * spot in the kernel (apart from copy_*_user functions).
2169 * Lru_lock must be held before calling this function.
2171 * @nr_to_scan: The number of eligible pages to look through on the list.
2172 * @lruvec: The LRU vector to pull pages from.
2173 * @dst: The temp list to put pages on to.
2174 * @nr_scanned: The number of pages that were scanned.
2175 * @sc: The scan_control struct for this reclaim session
2176 * @lru: LRU list id for isolating
2178 * returns how many pages were moved onto *@dst.
2180 static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
2181 struct lruvec *lruvec, struct list_head *dst,
2182 unsigned long *nr_scanned, struct scan_control *sc,
2185 struct list_head *src = &lruvec->lists[lru];
2186 unsigned long nr_taken = 0;
2187 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2188 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2189 unsigned long skipped = 0;
2190 unsigned long scan, total_scan, nr_pages;
2191 LIST_HEAD(folios_skipped);
2195 while (scan < nr_to_scan && !list_empty(src)) {
2196 struct list_head *move_to = src;
2197 struct folio *folio;
2199 folio = lru_to_folio(src);
2200 prefetchw_prev_lru_folio(folio, src, flags);
2202 nr_pages = folio_nr_pages(folio);
2203 total_scan += nr_pages;
2205 if (folio_zonenum(folio) > sc->reclaim_idx) {
2206 nr_skipped[folio_zonenum(folio)] += nr_pages;
2207 move_to = &folios_skipped;
2212 * Do not count skipped folios because that makes the function
2213 * return with no isolated folios if the LRU mostly contains
2214 * ineligible folios. This causes the VM to not reclaim any
2215 * folios, triggering a premature OOM.
2216 * Account all pages in a folio.
2220 if (!folio_test_lru(folio))
2222 if (!sc->may_unmap && folio_mapped(folio))
2226 * Be careful not to clear the lru flag until after we're
2227 * sure the folio is not being freed elsewhere -- the
2228 * folio release code relies on it.
2230 if (unlikely(!folio_try_get(folio)))
2233 if (!folio_test_clear_lru(folio)) {
2234 /* Another thread is already isolating this folio */
2239 nr_taken += nr_pages;
2240 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2243 list_move(&folio->lru, move_to);
2247 * Splice any skipped folios to the start of the LRU list. Note that
2248 * this disrupts the LRU order when reclaiming for lower zones but
2249 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2250 * scanning would soon rescan the same folios to skip and waste lots
2253 if (!list_empty(&folios_skipped)) {
2256 list_splice(&folios_skipped, src);
2257 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2258 if (!nr_skipped[zid])
2261 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2262 skipped += nr_skipped[zid];
2265 *nr_scanned = total_scan;
2266 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2267 total_scan, skipped, nr_taken,
2268 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2269 update_lru_sizes(lruvec, lru, nr_zone_taken);
2274 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2275 * @folio: Folio to isolate from its LRU list.
2277 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2278 * corresponding to whatever LRU list the folio was on.
2280 * The folio will have its LRU flag cleared. If it was found on the
2281 * active list, it will have the Active flag set. If it was found on the
2282 * unevictable list, it will have the Unevictable flag set. These flags
2283 * may need to be cleared by the caller before letting the page go.
2287 * (1) Must be called with an elevated refcount on the folio. This is a
2288 * fundamental difference from isolate_lru_folios() (which is called
2289 * without a stable reference).
2290 * (2) The lru_lock must not be held.
2291 * (3) Interrupts must be enabled.
2293 * Return: 0 if the folio was removed from an LRU list.
2294 * -EBUSY if the folio was not on an LRU list.
2296 int folio_isolate_lru(struct folio *folio)
2300 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2302 if (folio_test_clear_lru(folio)) {
2303 struct lruvec *lruvec;
2306 lruvec = folio_lruvec_lock_irq(folio);
2307 lruvec_del_folio(lruvec, folio);
2308 unlock_page_lruvec_irq(lruvec);
2316 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2317 * then get rescheduled. When there are massive number of tasks doing page
2318 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2319 * the LRU list will go small and be scanned faster than necessary, leading to
2320 * unnecessary swapping, thrashing and OOM.
2322 static int too_many_isolated(struct pglist_data *pgdat, int file,
2323 struct scan_control *sc)
2325 unsigned long inactive, isolated;
2328 if (current_is_kswapd())
2331 if (!writeback_throttling_sane(sc))
2335 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2336 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2338 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2339 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2343 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2344 * won't get blocked by normal direct-reclaimers, forming a circular
2347 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2350 too_many = isolated > inactive;
2352 /* Wake up tasks throttled due to too_many_isolated. */
2354 wake_throttle_isolated(pgdat);
2360 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
2361 * On return, @list is reused as a list of folios to be freed by the caller.
2363 * Returns the number of pages moved to the given lruvec.
2365 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
2366 struct list_head *list)
2368 int nr_pages, nr_moved = 0;
2369 LIST_HEAD(folios_to_free);
2371 while (!list_empty(list)) {
2372 struct folio *folio = lru_to_folio(list);
2374 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2375 list_del(&folio->lru);
2376 if (unlikely(!folio_evictable(folio))) {
2377 spin_unlock_irq(&lruvec->lru_lock);
2378 folio_putback_lru(folio);
2379 spin_lock_irq(&lruvec->lru_lock);
2384 * The folio_set_lru needs to be kept here for list integrity.
2386 * #0 move_folios_to_lru #1 release_pages
2387 * if (!folio_put_testzero())
2388 * if (folio_put_testzero())
2389 * !lru //skip lru_lock
2391 * list_add(&folio->lru,)
2392 * list_add(&folio->lru,)
2394 folio_set_lru(folio);
2396 if (unlikely(folio_put_testzero(folio))) {
2397 __folio_clear_lru_flags(folio);
2399 if (unlikely(folio_test_large(folio))) {
2400 spin_unlock_irq(&lruvec->lru_lock);
2401 destroy_large_folio(folio);
2402 spin_lock_irq(&lruvec->lru_lock);
2404 list_add(&folio->lru, &folios_to_free);
2410 * All pages were isolated from the same lruvec (and isolation
2411 * inhibits memcg migration).
2413 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2414 lruvec_add_folio(lruvec, folio);
2415 nr_pages = folio_nr_pages(folio);
2416 nr_moved += nr_pages;
2417 if (folio_test_active(folio))
2418 workingset_age_nonresident(lruvec, nr_pages);
2422 * To save our caller's stack, now use input list for pages to free.
2424 list_splice(&folios_to_free, list);
2430 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2431 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2432 * we should not throttle. Otherwise it is safe to do so.
2434 static int current_may_throttle(void)
2436 return !(current->flags & PF_LOCAL_THROTTLE);
2440 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2441 * of reclaimed pages
2443 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
2444 struct lruvec *lruvec, struct scan_control *sc,
2447 LIST_HEAD(folio_list);
2448 unsigned long nr_scanned;
2449 unsigned int nr_reclaimed = 0;
2450 unsigned long nr_taken;
2451 struct reclaim_stat stat;
2452 bool file = is_file_lru(lru);
2453 enum vm_event_item item;
2454 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2455 bool stalled = false;
2457 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2461 /* wait a bit for the reclaimer. */
2463 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2465 /* We are about to die and free our memory. Return now. */
2466 if (fatal_signal_pending(current))
2467 return SWAP_CLUSTER_MAX;
2472 spin_lock_irq(&lruvec->lru_lock);
2474 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
2475 &nr_scanned, sc, lru);
2477 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2478 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2479 if (!cgroup_reclaim(sc))
2480 __count_vm_events(item, nr_scanned);
2481 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2482 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2484 spin_unlock_irq(&lruvec->lru_lock);
2489 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
2491 spin_lock_irq(&lruvec->lru_lock);
2492 move_folios_to_lru(lruvec, &folio_list);
2494 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2495 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2496 if (!cgroup_reclaim(sc))
2497 __count_vm_events(item, nr_reclaimed);
2498 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2499 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2500 spin_unlock_irq(&lruvec->lru_lock);
2502 lru_note_cost(lruvec, file, stat.nr_pageout);
2503 mem_cgroup_uncharge_list(&folio_list);
2504 free_unref_page_list(&folio_list);
2507 * If dirty folios are scanned that are not queued for IO, it
2508 * implies that flushers are not doing their job. This can
2509 * happen when memory pressure pushes dirty folios to the end of
2510 * the LRU before the dirty limits are breached and the dirty
2511 * data has expired. It can also happen when the proportion of
2512 * dirty folios grows not through writes but through memory
2513 * pressure reclaiming all the clean cache. And in some cases,
2514 * the flushers simply cannot keep up with the allocation
2515 * rate. Nudge the flusher threads in case they are asleep.
2517 if (stat.nr_unqueued_dirty == nr_taken) {
2518 wakeup_flusher_threads(WB_REASON_VMSCAN);
2520 * For cgroupv1 dirty throttling is achieved by waking up
2521 * the kernel flusher here and later waiting on folios
2522 * which are in writeback to finish (see shrink_folio_list()).
2524 * Flusher may not be able to issue writeback quickly
2525 * enough for cgroupv1 writeback throttling to work
2526 * on a large system.
2528 if (!writeback_throttling_sane(sc))
2529 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2532 sc->nr.dirty += stat.nr_dirty;
2533 sc->nr.congested += stat.nr_congested;
2534 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2535 sc->nr.writeback += stat.nr_writeback;
2536 sc->nr.immediate += stat.nr_immediate;
2537 sc->nr.taken += nr_taken;
2539 sc->nr.file_taken += nr_taken;
2541 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2542 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2543 return nr_reclaimed;
2547 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2549 * We move them the other way if the folio is referenced by one or more
2552 * If the folios are mostly unmapped, the processing is fast and it is
2553 * appropriate to hold lru_lock across the whole operation. But if
2554 * the folios are mapped, the processing is slow (folio_referenced()), so
2555 * we should drop lru_lock around each folio. It's impossible to balance
2556 * this, so instead we remove the folios from the LRU while processing them.
2557 * It is safe to rely on the active flag against the non-LRU folios in here
2558 * because nobody will play with that bit on a non-LRU folio.
2560 * The downside is that we have to touch folio->_refcount against each folio.
2561 * But we had to alter folio->flags anyway.
2563 static void shrink_active_list(unsigned long nr_to_scan,
2564 struct lruvec *lruvec,
2565 struct scan_control *sc,
2568 unsigned long nr_taken;
2569 unsigned long nr_scanned;
2570 unsigned long vm_flags;
2571 LIST_HEAD(l_hold); /* The folios which were snipped off */
2572 LIST_HEAD(l_active);
2573 LIST_HEAD(l_inactive);
2574 unsigned nr_deactivate, nr_activate;
2575 unsigned nr_rotated = 0;
2576 int file = is_file_lru(lru);
2577 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2581 spin_lock_irq(&lruvec->lru_lock);
2583 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2584 &nr_scanned, sc, lru);
2586 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2588 if (!cgroup_reclaim(sc))
2589 __count_vm_events(PGREFILL, nr_scanned);
2590 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2592 spin_unlock_irq(&lruvec->lru_lock);
2594 while (!list_empty(&l_hold)) {
2595 struct folio *folio;
2598 folio = lru_to_folio(&l_hold);
2599 list_del(&folio->lru);
2601 if (unlikely(!folio_evictable(folio))) {
2602 folio_putback_lru(folio);
2606 if (unlikely(buffer_heads_over_limit)) {
2607 if (folio_test_private(folio) && folio_trylock(folio)) {
2608 if (folio_test_private(folio))
2609 filemap_release_folio(folio, 0);
2610 folio_unlock(folio);
2614 /* Referenced or rmap lock contention: rotate */
2615 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2618 * Identify referenced, file-backed active folios and
2619 * give them one more trip around the active list. So
2620 * that executable code get better chances to stay in
2621 * memory under moderate memory pressure. Anon folios
2622 * are not likely to be evicted by use-once streaming
2623 * IO, plus JVM can create lots of anon VM_EXEC folios,
2624 * so we ignore them here.
2626 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2627 nr_rotated += folio_nr_pages(folio);
2628 list_add(&folio->lru, &l_active);
2633 folio_clear_active(folio); /* we are de-activating */
2634 folio_set_workingset(folio);
2635 list_add(&folio->lru, &l_inactive);
2639 * Move folios back to the lru list.
2641 spin_lock_irq(&lruvec->lru_lock);
2643 nr_activate = move_folios_to_lru(lruvec, &l_active);
2644 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2645 /* Keep all free folios in l_active list */
2646 list_splice(&l_inactive, &l_active);
2648 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2649 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2651 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2652 spin_unlock_irq(&lruvec->lru_lock);
2654 mem_cgroup_uncharge_list(&l_active);
2655 free_unref_page_list(&l_active);
2656 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2657 nr_deactivate, nr_rotated, sc->priority, file);
2660 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2661 struct pglist_data *pgdat)
2663 struct reclaim_stat dummy_stat;
2664 unsigned int nr_reclaimed;
2665 struct folio *folio;
2666 struct scan_control sc = {
2667 .gfp_mask = GFP_KERNEL,
2674 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2675 while (!list_empty(folio_list)) {
2676 folio = lru_to_folio(folio_list);
2677 list_del(&folio->lru);
2678 folio_putback_lru(folio);
2681 return nr_reclaimed;
2684 unsigned long reclaim_pages(struct list_head *folio_list)
2687 unsigned int nr_reclaimed = 0;
2688 LIST_HEAD(node_folio_list);
2689 unsigned int noreclaim_flag;
2691 if (list_empty(folio_list))
2692 return nr_reclaimed;
2694 noreclaim_flag = memalloc_noreclaim_save();
2696 nid = folio_nid(lru_to_folio(folio_list));
2698 struct folio *folio = lru_to_folio(folio_list);
2700 if (nid == folio_nid(folio)) {
2701 folio_clear_active(folio);
2702 list_move(&folio->lru, &node_folio_list);
2706 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2707 nid = folio_nid(lru_to_folio(folio_list));
2708 } while (!list_empty(folio_list));
2710 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2712 memalloc_noreclaim_restore(noreclaim_flag);
2714 return nr_reclaimed;
2717 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2718 struct lruvec *lruvec, struct scan_control *sc)
2720 if (is_active_lru(lru)) {
2721 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2722 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2724 sc->skipped_deactivate = 1;
2728 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2732 * The inactive anon list should be small enough that the VM never has
2733 * to do too much work.
2735 * The inactive file list should be small enough to leave most memory
2736 * to the established workingset on the scan-resistant active list,
2737 * but large enough to avoid thrashing the aggregate readahead window.
2739 * Both inactive lists should also be large enough that each inactive
2740 * folio has a chance to be referenced again before it is reclaimed.
2742 * If that fails and refaulting is observed, the inactive list grows.
2744 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2745 * on this LRU, maintained by the pageout code. An inactive_ratio
2746 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2749 * memory ratio inactive
2750 * -------------------------------------
2759 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2761 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2762 unsigned long inactive, active;
2763 unsigned long inactive_ratio;
2766 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2767 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2769 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2771 inactive_ratio = int_sqrt(10 * gb);
2775 return inactive * inactive_ratio < active;
2785 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2788 struct lruvec *target_lruvec;
2790 if (lru_gen_enabled())
2793 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2796 * Flush the memory cgroup stats, so that we read accurate per-memcg
2797 * lruvec stats for heuristics.
2799 mem_cgroup_flush_stats();
2802 * Determine the scan balance between anon and file LRUs.
2804 spin_lock_irq(&target_lruvec->lru_lock);
2805 sc->anon_cost = target_lruvec->anon_cost;
2806 sc->file_cost = target_lruvec->file_cost;
2807 spin_unlock_irq(&target_lruvec->lru_lock);
2810 * Target desirable inactive:active list ratios for the anon
2811 * and file LRU lists.
2813 if (!sc->force_deactivate) {
2814 unsigned long refaults;
2817 * When refaults are being observed, it means a new
2818 * workingset is being established. Deactivate to get
2819 * rid of any stale active pages quickly.
2821 refaults = lruvec_page_state(target_lruvec,
2822 WORKINGSET_ACTIVATE_ANON);
2823 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2824 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2825 sc->may_deactivate |= DEACTIVATE_ANON;
2827 sc->may_deactivate &= ~DEACTIVATE_ANON;
2829 refaults = lruvec_page_state(target_lruvec,
2830 WORKINGSET_ACTIVATE_FILE);
2831 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2832 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2833 sc->may_deactivate |= DEACTIVATE_FILE;
2835 sc->may_deactivate &= ~DEACTIVATE_FILE;
2837 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2840 * If we have plenty of inactive file pages that aren't
2841 * thrashing, try to reclaim those first before touching
2844 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2845 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2846 sc->cache_trim_mode = 1;
2848 sc->cache_trim_mode = 0;
2851 * Prevent the reclaimer from falling into the cache trap: as
2852 * cache pages start out inactive, every cache fault will tip
2853 * the scan balance towards the file LRU. And as the file LRU
2854 * shrinks, so does the window for rotation from references.
2855 * This means we have a runaway feedback loop where a tiny
2856 * thrashing file LRU becomes infinitely more attractive than
2857 * anon pages. Try to detect this based on file LRU size.
2859 if (!cgroup_reclaim(sc)) {
2860 unsigned long total_high_wmark = 0;
2861 unsigned long free, anon;
2864 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2865 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2866 node_page_state(pgdat, NR_INACTIVE_FILE);
2868 for (z = 0; z < MAX_NR_ZONES; z++) {
2869 struct zone *zone = &pgdat->node_zones[z];
2871 if (!managed_zone(zone))
2874 total_high_wmark += high_wmark_pages(zone);
2878 * Consider anon: if that's low too, this isn't a
2879 * runaway file reclaim problem, but rather just
2880 * extreme pressure. Reclaim as per usual then.
2882 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2885 file + free <= total_high_wmark &&
2886 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2887 anon >> sc->priority;
2892 * Determine how aggressively the anon and file LRU lists should be
2895 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2896 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2898 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2901 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2902 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2903 unsigned long anon_cost, file_cost, total_cost;
2904 int swappiness = mem_cgroup_swappiness(memcg);
2905 u64 fraction[ANON_AND_FILE];
2906 u64 denominator = 0; /* gcc */
2907 enum scan_balance scan_balance;
2908 unsigned long ap, fp;
2911 /* If we have no swap space, do not bother scanning anon folios. */
2912 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2913 scan_balance = SCAN_FILE;
2918 * Global reclaim will swap to prevent OOM even with no
2919 * swappiness, but memcg users want to use this knob to
2920 * disable swapping for individual groups completely when
2921 * using the memory controller's swap limit feature would be
2924 if (cgroup_reclaim(sc) && !swappiness) {
2925 scan_balance = SCAN_FILE;
2930 * Do not apply any pressure balancing cleverness when the
2931 * system is close to OOM, scan both anon and file equally
2932 * (unless the swappiness setting disagrees with swapping).
2934 if (!sc->priority && swappiness) {
2935 scan_balance = SCAN_EQUAL;
2940 * If the system is almost out of file pages, force-scan anon.
2942 if (sc->file_is_tiny) {
2943 scan_balance = SCAN_ANON;
2948 * If there is enough inactive page cache, we do not reclaim
2949 * anything from the anonymous working right now.
2951 if (sc->cache_trim_mode) {
2952 scan_balance = SCAN_FILE;
2956 scan_balance = SCAN_FRACT;
2958 * Calculate the pressure balance between anon and file pages.
2960 * The amount of pressure we put on each LRU is inversely
2961 * proportional to the cost of reclaiming each list, as
2962 * determined by the share of pages that are refaulting, times
2963 * the relative IO cost of bringing back a swapped out
2964 * anonymous page vs reloading a filesystem page (swappiness).
2966 * Although we limit that influence to ensure no list gets
2967 * left behind completely: at least a third of the pressure is
2968 * applied, before swappiness.
2970 * With swappiness at 100, anon and file have equal IO cost.
2972 total_cost = sc->anon_cost + sc->file_cost;
2973 anon_cost = total_cost + sc->anon_cost;
2974 file_cost = total_cost + sc->file_cost;
2975 total_cost = anon_cost + file_cost;
2977 ap = swappiness * (total_cost + 1);
2978 ap /= anon_cost + 1;
2980 fp = (200 - swappiness) * (total_cost + 1);
2981 fp /= file_cost + 1;
2985 denominator = ap + fp;
2987 for_each_evictable_lru(lru) {
2988 int file = is_file_lru(lru);
2989 unsigned long lruvec_size;
2990 unsigned long low, min;
2993 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2994 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2999 * Scale a cgroup's reclaim pressure by proportioning
3000 * its current usage to its memory.low or memory.min
3003 * This is important, as otherwise scanning aggression
3004 * becomes extremely binary -- from nothing as we
3005 * approach the memory protection threshold, to totally
3006 * nominal as we exceed it. This results in requiring
3007 * setting extremely liberal protection thresholds. It
3008 * also means we simply get no protection at all if we
3009 * set it too low, which is not ideal.
3011 * If there is any protection in place, we reduce scan
3012 * pressure by how much of the total memory used is
3013 * within protection thresholds.
3015 * There is one special case: in the first reclaim pass,
3016 * we skip over all groups that are within their low
3017 * protection. If that fails to reclaim enough pages to
3018 * satisfy the reclaim goal, we come back and override
3019 * the best-effort low protection. However, we still
3020 * ideally want to honor how well-behaved groups are in
3021 * that case instead of simply punishing them all
3022 * equally. As such, we reclaim them based on how much
3023 * memory they are using, reducing the scan pressure
3024 * again by how much of the total memory used is under
3027 unsigned long cgroup_size = mem_cgroup_size(memcg);
3028 unsigned long protection;
3030 /* memory.low scaling, make sure we retry before OOM */
3031 if (!sc->memcg_low_reclaim && low > min) {
3033 sc->memcg_low_skipped = 1;
3038 /* Avoid TOCTOU with earlier protection check */
3039 cgroup_size = max(cgroup_size, protection);
3041 scan = lruvec_size - lruvec_size * protection /
3045 * Minimally target SWAP_CLUSTER_MAX pages to keep
3046 * reclaim moving forwards, avoiding decrementing
3047 * sc->priority further than desirable.
3049 scan = max(scan, SWAP_CLUSTER_MAX);
3054 scan >>= sc->priority;
3057 * If the cgroup's already been deleted, make sure to
3058 * scrape out the remaining cache.
3060 if (!scan && !mem_cgroup_online(memcg))
3061 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
3063 switch (scan_balance) {
3065 /* Scan lists relative to size */
3069 * Scan types proportional to swappiness and
3070 * their relative recent reclaim efficiency.
3071 * Make sure we don't miss the last page on
3072 * the offlined memory cgroups because of a
3075 scan = mem_cgroup_online(memcg) ?
3076 div64_u64(scan * fraction[file], denominator) :
3077 DIV64_U64_ROUND_UP(scan * fraction[file],
3082 /* Scan one type exclusively */
3083 if ((scan_balance == SCAN_FILE) != file)
3087 /* Look ma, no brain */
3096 * Anonymous LRU management is a waste if there is
3097 * ultimately no way to reclaim the memory.
3099 static bool can_age_anon_pages(struct pglist_data *pgdat,
3100 struct scan_control *sc)
3102 /* Aging the anon LRU is valuable if swap is present: */
3103 if (total_swap_pages > 0)
3106 /* Also valuable if anon pages can be demoted: */
3107 return can_demote(pgdat->node_id, sc);
3110 #ifdef CONFIG_LRU_GEN
3112 #ifdef CONFIG_LRU_GEN_ENABLED
3113 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3114 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
3116 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3117 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
3120 /******************************************************************************
3122 ******************************************************************************/
3124 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
3126 #define DEFINE_MAX_SEQ(lruvec) \
3127 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3129 #define DEFINE_MIN_SEQ(lruvec) \
3130 unsigned long min_seq[ANON_AND_FILE] = { \
3131 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3132 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3135 #define for_each_gen_type_zone(gen, type, zone) \
3136 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3137 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3138 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3140 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
3142 struct pglist_data *pgdat = NODE_DATA(nid);
3146 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3148 /* for hotadd_new_pgdat() */
3150 lruvec->pgdat = pgdat;
3155 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3157 return pgdat ? &pgdat->__lruvec : NULL;
3160 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3162 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3163 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3165 if (!can_demote(pgdat->node_id, sc) &&
3166 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3169 return mem_cgroup_swappiness(memcg);
3172 static int get_nr_gens(struct lruvec *lruvec, int type)
3174 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3177 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3179 /* see the comment on lru_gen_struct */
3180 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3181 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3182 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3185 /******************************************************************************
3187 ******************************************************************************/
3189 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3191 static struct lru_gen_mm_list mm_list = {
3192 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3193 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3198 return &memcg->mm_list;
3200 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3205 void lru_gen_add_mm(struct mm_struct *mm)
3208 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3209 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3211 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3213 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3214 mm->lru_gen.memcg = memcg;
3216 spin_lock(&mm_list->lock);
3218 for_each_node_state(nid, N_MEMORY) {
3219 struct lruvec *lruvec = get_lruvec(memcg, nid);
3224 /* the first addition since the last iteration */
3225 if (lruvec->mm_state.tail == &mm_list->fifo)
3226 lruvec->mm_state.tail = &mm->lru_gen.list;
3229 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3231 spin_unlock(&mm_list->lock);
3234 void lru_gen_del_mm(struct mm_struct *mm)
3237 struct lru_gen_mm_list *mm_list;
3238 struct mem_cgroup *memcg = NULL;
3240 if (list_empty(&mm->lru_gen.list))
3244 memcg = mm->lru_gen.memcg;
3246 mm_list = get_mm_list(memcg);
3248 spin_lock(&mm_list->lock);
3250 for_each_node(nid) {
3251 struct lruvec *lruvec = get_lruvec(memcg, nid);
3256 /* where the last iteration ended (exclusive) */
3257 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3258 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3260 /* where the current iteration continues (inclusive) */
3261 if (lruvec->mm_state.head != &mm->lru_gen.list)
3264 lruvec->mm_state.head = lruvec->mm_state.head->next;
3265 /* the deletion ends the current iteration */
3266 if (lruvec->mm_state.head == &mm_list->fifo)
3267 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3270 list_del_init(&mm->lru_gen.list);
3272 spin_unlock(&mm_list->lock);
3275 mem_cgroup_put(mm->lru_gen.memcg);
3276 mm->lru_gen.memcg = NULL;
3281 void lru_gen_migrate_mm(struct mm_struct *mm)
3283 struct mem_cgroup *memcg;
3284 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3286 VM_WARN_ON_ONCE(task->mm != mm);
3287 lockdep_assert_held(&task->alloc_lock);
3289 /* for mm_update_next_owner() */
3290 if (mem_cgroup_disabled())
3294 memcg = mem_cgroup_from_task(task);
3296 if (memcg == mm->lru_gen.memcg)
3299 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3300 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3308 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3309 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3310 * bits in a bitmap, k is the number of hash functions and n is the number of
3313 * Page table walkers use one of the two filters to reduce their search space.
3314 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3315 * aging uses the double-buffering technique to flip to the other filter each
3316 * time it produces a new generation. For non-leaf entries that have enough
3317 * leaf entries, the aging carries them over to the next generation in
3318 * walk_pmd_range(); the eviction also report them when walking the rmap
3319 * in lru_gen_look_around().
3321 * For future optimizations:
3322 * 1. It's not necessary to keep both filters all the time. The spare one can be
3323 * freed after the RCU grace period and reallocated if needed again.
3324 * 2. And when reallocating, it's worth scaling its size according to the number
3325 * of inserted entries in the other filter, to reduce the memory overhead on
3326 * small systems and false positives on large systems.
3327 * 3. Jenkins' hash function is an alternative to Knuth's.
3329 #define BLOOM_FILTER_SHIFT 15
3331 static inline int filter_gen_from_seq(unsigned long seq)
3333 return seq % NR_BLOOM_FILTERS;
3336 static void get_item_key(void *item, int *key)
3338 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3340 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3342 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3343 key[1] = hash >> BLOOM_FILTER_SHIFT;
3346 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3348 unsigned long *filter;
3349 int gen = filter_gen_from_seq(seq);
3351 filter = lruvec->mm_state.filters[gen];
3353 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3357 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3358 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3359 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3362 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3365 unsigned long *filter;
3366 int gen = filter_gen_from_seq(seq);
3368 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3372 get_item_key(item, key);
3374 if (!test_bit(key[0], filter))
3375 set_bit(key[0], filter);
3376 if (!test_bit(key[1], filter))
3377 set_bit(key[1], filter);
3380 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3383 unsigned long *filter;
3384 int gen = filter_gen_from_seq(seq);
3386 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3390 get_item_key(item, key);
3392 return test_bit(key[0], filter) && test_bit(key[1], filter);
3395 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3400 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3403 hist = lru_hist_from_seq(walk->max_seq);
3405 for (i = 0; i < NR_MM_STATS; i++) {
3406 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3407 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3408 walk->mm_stats[i] = 0;
3412 if (NR_HIST_GENS > 1 && last) {
3413 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3415 for (i = 0; i < NR_MM_STATS; i++)
3416 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3420 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3423 unsigned long size = 0;
3424 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3425 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3427 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3430 clear_bit(key, &mm->lru_gen.bitmap);
3432 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3433 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3434 get_mm_counter(mm, MM_ANONPAGES) +
3435 get_mm_counter(mm, MM_SHMEMPAGES);
3438 if (size < MIN_LRU_BATCH)
3441 return !mmget_not_zero(mm);
3444 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3445 struct mm_struct **iter)
3449 struct mm_struct *mm = NULL;
3450 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3451 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3452 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3455 * There are four interesting cases for this page table walker:
3456 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3457 * there is nothing left to do.
3458 * 2. It's the first of the current generation, and it needs to reset
3459 * the Bloom filter for the next generation.
3460 * 3. It reaches the end of mm_list, and it needs to increment
3461 * mm_state->seq; the iteration is done.
3462 * 4. It's the last of the current generation, and it needs to reset the
3463 * mm stats counters for the next generation.
3465 spin_lock(&mm_list->lock);
3467 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3468 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3469 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3471 if (walk->max_seq <= mm_state->seq) {
3477 if (!mm_state->nr_walkers) {
3478 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3480 mm_state->head = mm_list->fifo.next;
3484 while (!mm && mm_state->head != &mm_list->fifo) {
3485 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3487 mm_state->head = mm_state->head->next;
3489 /* force scan for those added after the last iteration */
3490 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3491 mm_state->tail = mm_state->head;
3492 walk->force_scan = true;
3495 if (should_skip_mm(mm, walk))
3499 if (mm_state->head == &mm_list->fifo)
3500 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3503 mm_state->nr_walkers--;
3505 mm_state->nr_walkers++;
3507 if (mm_state->nr_walkers)
3511 reset_mm_stats(lruvec, walk, last);
3513 spin_unlock(&mm_list->lock);
3516 reset_bloom_filter(lruvec, walk->max_seq + 1);
3526 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3528 bool success = false;
3529 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3530 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3531 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3533 spin_lock(&mm_list->lock);
3535 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3537 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3538 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3540 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3541 reset_mm_stats(lruvec, NULL, true);
3545 spin_unlock(&mm_list->lock);
3550 /******************************************************************************
3551 * refault feedback loop
3552 ******************************************************************************/
3555 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3557 * The P term is refaulted/(evicted+protected) from a tier in the generation
3558 * currently being evicted; the I term is the exponential moving average of the
3559 * P term over the generations previously evicted, using the smoothing factor
3560 * 1/2; the D term isn't supported.
3562 * The setpoint (SP) is always the first tier of one type; the process variable
3563 * (PV) is either any tier of the other type or any other tier of the same
3566 * The error is the difference between the SP and the PV; the correction is to
3567 * turn off protection when SP>PV or turn on protection when SP<PV.
3569 * For future optimizations:
3570 * 1. The D term may discount the other two terms over time so that long-lived
3571 * generations can resist stale information.
3574 unsigned long refaulted;
3575 unsigned long total;
3579 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3580 struct ctrl_pos *pos)
3582 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3583 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3585 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3586 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3587 pos->total = lrugen->avg_total[type][tier] +
3588 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3590 pos->total += lrugen->protected[hist][type][tier - 1];
3594 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3597 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3598 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3599 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3601 lockdep_assert_held(&lruvec->lru_lock);
3603 if (!carryover && !clear)
3606 hist = lru_hist_from_seq(seq);
3608 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3612 sum = lrugen->avg_refaulted[type][tier] +
3613 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3614 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3616 sum = lrugen->avg_total[type][tier] +
3617 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3619 sum += lrugen->protected[hist][type][tier - 1];
3620 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3624 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3625 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3627 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3632 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3635 * Return true if the PV has a limited number of refaults or a lower
3636 * refaulted/total than the SP.
3638 return pv->refaulted < MIN_LRU_BATCH ||
3639 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3640 (sp->refaulted + 1) * pv->total * pv->gain;
3643 /******************************************************************************
3645 ******************************************************************************/
3647 /* promote pages accessed through page tables */
3648 static int folio_update_gen(struct folio *folio, int gen)
3650 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3652 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3653 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3656 /* lru_gen_del_folio() has isolated this page? */
3657 if (!(old_flags & LRU_GEN_MASK)) {
3658 /* for shrink_folio_list() */
3659 new_flags = old_flags | BIT(PG_referenced);
3663 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3664 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3665 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3667 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3670 /* protect pages accessed multiple times through file descriptors */
3671 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3673 int type = folio_is_file_lru(folio);
3674 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3675 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3676 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3678 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3681 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3682 /* folio_update_gen() has promoted this page? */
3683 if (new_gen >= 0 && new_gen != old_gen)
3686 new_gen = (old_gen + 1) % MAX_NR_GENS;
3688 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3689 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3690 /* for folio_end_writeback() */
3692 new_flags |= BIT(PG_reclaim);
3693 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3695 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3700 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3701 int old_gen, int new_gen)
3703 int type = folio_is_file_lru(folio);
3704 int zone = folio_zonenum(folio);
3705 int delta = folio_nr_pages(folio);
3707 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3708 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3712 walk->nr_pages[old_gen][type][zone] -= delta;
3713 walk->nr_pages[new_gen][type][zone] += delta;
3716 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3718 int gen, type, zone;
3719 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3723 for_each_gen_type_zone(gen, type, zone) {
3724 enum lru_list lru = type * LRU_INACTIVE_FILE;
3725 int delta = walk->nr_pages[gen][type][zone];
3730 walk->nr_pages[gen][type][zone] = 0;
3731 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3732 lrugen->nr_pages[gen][type][zone] + delta);
3734 if (lru_gen_is_active(lruvec, gen))
3736 __update_lru_size(lruvec, lru, zone, delta);
3740 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3742 struct address_space *mapping;
3743 struct vm_area_struct *vma = args->vma;
3744 struct lru_gen_mm_walk *walk = args->private;
3746 if (!vma_is_accessible(vma))
3749 if (is_vm_hugetlb_page(vma))
3752 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3755 if (vma == get_gate_vma(vma->vm_mm))
3758 if (vma_is_anonymous(vma))
3759 return !walk->can_swap;
3761 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3764 mapping = vma->vm_file->f_mapping;
3765 if (mapping_unevictable(mapping))
3768 if (shmem_mapping(mapping))
3769 return !walk->can_swap;
3771 /* to exclude special mappings like dax, etc. */
3772 return !mapping->a_ops->read_folio;
3776 * Some userspace memory allocators map many single-page VMAs. Instead of
3777 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3778 * table to reduce zigzags and improve cache performance.
3780 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3781 unsigned long *vm_start, unsigned long *vm_end)
3783 unsigned long start = round_up(*vm_end, size);
3784 unsigned long end = (start | ~mask) + 1;
3785 VMA_ITERATOR(vmi, args->mm, start);
3787 VM_WARN_ON_ONCE(mask & size);
3788 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3790 for_each_vma(vmi, args->vma) {
3791 if (end && end <= args->vma->vm_start)
3794 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3797 *vm_start = max(start, args->vma->vm_start);
3798 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3806 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3808 unsigned long pfn = pte_pfn(pte);
3810 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3812 if (!pte_present(pte) || is_zero_pfn(pfn))
3815 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3818 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3824 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3825 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3827 unsigned long pfn = pmd_pfn(pmd);
3829 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3831 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3834 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3837 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3844 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3845 struct pglist_data *pgdat, bool can_swap)
3847 struct folio *folio;
3849 /* try to avoid unnecessary memory loads */
3850 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3853 folio = pfn_folio(pfn);
3854 if (folio_nid(folio) != pgdat->node_id)
3857 if (folio_memcg_rcu(folio) != memcg)
3860 /* file VMAs can contain anon pages from COW */
3861 if (!folio_is_file_lru(folio) && !can_swap)
3867 static bool suitable_to_scan(int total, int young)
3869 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3871 /* suitable if the average number of young PTEs per cacheline is >=1 */
3872 return young * n >= total;
3875 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3876 struct mm_walk *args)
3884 struct lru_gen_mm_walk *walk = args->private;
3885 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3886 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3887 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3889 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3891 ptl = pte_lockptr(args->mm, pmd);
3892 if (!spin_trylock(ptl))
3895 arch_enter_lazy_mmu_mode();
3897 pte = pte_offset_map(pmd, start & PMD_MASK);
3899 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3901 struct folio *folio;
3904 walk->mm_stats[MM_LEAF_TOTAL]++;
3906 pfn = get_pte_pfn(pte[i], args->vma, addr);
3910 if (!pte_young(pte[i])) {
3911 walk->mm_stats[MM_LEAF_OLD]++;
3915 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3919 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3920 VM_WARN_ON_ONCE(true);
3923 walk->mm_stats[MM_LEAF_YOUNG]++;
3925 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
3926 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3927 !folio_test_swapcache(folio)))
3928 folio_mark_dirty(folio);
3930 old_gen = folio_update_gen(folio, new_gen);
3931 if (old_gen >= 0 && old_gen != new_gen)
3932 update_batch_size(walk, folio, old_gen, new_gen);
3935 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3940 arch_leave_lazy_mmu_mode();
3943 return suitable_to_scan(total, young);
3946 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3947 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3948 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3953 struct lru_gen_mm_walk *walk = args->private;
3954 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3955 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3956 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3958 VM_WARN_ON_ONCE(pud_leaf(*pud));
3960 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3966 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3967 if (i && i <= MIN_LRU_BATCH) {
3968 __set_bit(i - 1, bitmap);
3972 pmd = pmd_offset(pud, *start);
3974 ptl = pmd_lockptr(args->mm, pmd);
3975 if (!spin_trylock(ptl))
3978 arch_enter_lazy_mmu_mode();
3982 struct folio *folio;
3983 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3985 pfn = get_pmd_pfn(pmd[i], vma, addr);
3989 if (!pmd_trans_huge(pmd[i])) {
3990 if (arch_has_hw_nonleaf_pmd_young() &&
3991 get_cap(LRU_GEN_NONLEAF_YOUNG))
3992 pmdp_test_and_clear_young(vma, addr, pmd + i);
3996 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4000 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
4003 walk->mm_stats[MM_LEAF_YOUNG]++;
4005 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
4006 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4007 !folio_test_swapcache(folio)))
4008 folio_mark_dirty(folio);
4010 old_gen = folio_update_gen(folio, new_gen);
4011 if (old_gen >= 0 && old_gen != new_gen)
4012 update_batch_size(walk, folio, old_gen, new_gen);
4014 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
4015 } while (i <= MIN_LRU_BATCH);
4017 arch_leave_lazy_mmu_mode();
4021 bitmap_zero(bitmap, MIN_LRU_BATCH);
4024 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
4025 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
4030 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
4031 struct mm_walk *args)
4037 struct vm_area_struct *vma;
4038 unsigned long pos = -1;
4039 struct lru_gen_mm_walk *walk = args->private;
4040 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4042 VM_WARN_ON_ONCE(pud_leaf(*pud));
4045 * Finish an entire PMD in two passes: the first only reaches to PTE
4046 * tables to avoid taking the PMD lock; the second, if necessary, takes
4047 * the PMD lock to clear the accessed bit in PMD entries.
4049 pmd = pmd_offset(pud, start & PUD_MASK);
4051 /* walk_pte_range() may call get_next_vma() */
4053 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
4054 pmd_t val = pmd_read_atomic(pmd + i);
4056 /* for pmd_read_atomic() */
4059 next = pmd_addr_end(addr, end);
4061 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4062 walk->mm_stats[MM_LEAF_TOTAL]++;
4066 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4067 if (pmd_trans_huge(val)) {
4068 unsigned long pfn = pmd_pfn(val);
4069 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4071 walk->mm_stats[MM_LEAF_TOTAL]++;
4073 if (!pmd_young(val)) {
4074 walk->mm_stats[MM_LEAF_OLD]++;
4078 /* try to avoid unnecessary memory loads */
4079 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4082 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4086 walk->mm_stats[MM_NONLEAF_TOTAL]++;
4088 if (arch_has_hw_nonleaf_pmd_young() &&
4089 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
4090 if (!pmd_young(val))
4093 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4096 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4099 walk->mm_stats[MM_NONLEAF_FOUND]++;
4101 if (!walk_pte_range(&val, addr, next, args))
4104 walk->mm_stats[MM_NONLEAF_ADDED]++;
4106 /* carry over to the next generation */
4107 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4110 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
4112 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4116 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4117 struct mm_walk *args)
4123 struct lru_gen_mm_walk *walk = args->private;
4125 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4127 pud = pud_offset(p4d, start & P4D_MASK);
4129 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4130 pud_t val = READ_ONCE(pud[i]);
4132 next = pud_addr_end(addr, end);
4134 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4137 walk_pmd_range(&val, addr, next, args);
4139 /* a racy check to curtail the waiting time */
4140 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
4143 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4144 end = (addr | ~PUD_MASK) + 1;
4149 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4152 end = round_up(end, P4D_SIZE);
4154 if (!end || !args->vma)
4157 walk->next_addr = max(end, args->vma->vm_start);
4162 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4164 static const struct mm_walk_ops mm_walk_ops = {
4165 .test_walk = should_skip_vma,
4166 .p4d_entry = walk_pud_range,
4170 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4172 walk->next_addr = FIRST_USER_ADDRESS;
4177 /* folio_update_gen() requires stable folio_memcg() */
4178 if (!mem_cgroup_trylock_pages(memcg))
4181 /* the caller might be holding the lock for write */
4182 if (mmap_read_trylock(mm)) {
4183 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4185 mmap_read_unlock(mm);
4188 mem_cgroup_unlock_pages();
4190 if (walk->batched) {
4191 spin_lock_irq(&lruvec->lru_lock);
4192 reset_batch_size(lruvec, walk);
4193 spin_unlock_irq(&lruvec->lru_lock);
4197 } while (err == -EAGAIN);
4200 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4202 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4204 if (pgdat && current_is_kswapd()) {
4205 VM_WARN_ON_ONCE(walk);
4207 walk = &pgdat->mm_walk;
4208 } else if (!pgdat && !walk) {
4209 VM_WARN_ON_ONCE(current_is_kswapd());
4211 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4214 current->reclaim_state->mm_walk = walk;
4219 static void clear_mm_walk(void)
4221 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4223 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4224 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4226 current->reclaim_state->mm_walk = NULL;
4228 if (!current_is_kswapd())
4232 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4235 int remaining = MAX_LRU_BATCH;
4236 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4237 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4239 if (type == LRU_GEN_ANON && !can_swap)
4242 /* prevent cold/hot inversion if force_scan is true */
4243 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4244 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4246 while (!list_empty(head)) {
4247 struct folio *folio = lru_to_folio(head);
4249 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4250 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4251 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4252 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4254 new_gen = folio_inc_gen(lruvec, folio, false);
4255 list_move_tail(&folio->lru, &lrugen->lists[new_gen][type][zone]);
4262 reset_ctrl_pos(lruvec, type, true);
4263 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4268 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4270 int gen, type, zone;
4271 bool success = false;
4272 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4273 DEFINE_MIN_SEQ(lruvec);
4275 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4277 /* find the oldest populated generation */
4278 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4279 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4280 gen = lru_gen_from_seq(min_seq[type]);
4282 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4283 if (!list_empty(&lrugen->lists[gen][type][zone]))
4293 /* see the comment on lru_gen_struct */
4295 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4296 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4299 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4300 if (min_seq[type] == lrugen->min_seq[type])
4303 reset_ctrl_pos(lruvec, type, true);
4304 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4311 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4315 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4317 spin_lock_irq(&lruvec->lru_lock);
4319 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4321 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4322 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4325 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4327 while (!inc_min_seq(lruvec, type, can_swap)) {
4328 spin_unlock_irq(&lruvec->lru_lock);
4330 spin_lock_irq(&lruvec->lru_lock);
4335 * Update the active/inactive LRU sizes for compatibility. Both sides of
4336 * the current max_seq need to be covered, since max_seq+1 can overlap
4337 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4338 * overlap, cold/hot inversion happens.
4340 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4341 next = lru_gen_from_seq(lrugen->max_seq + 1);
4343 for (type = 0; type < ANON_AND_FILE; type++) {
4344 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4345 enum lru_list lru = type * LRU_INACTIVE_FILE;
4346 long delta = lrugen->nr_pages[prev][type][zone] -
4347 lrugen->nr_pages[next][type][zone];
4352 __update_lru_size(lruvec, lru, zone, delta);
4353 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4357 for (type = 0; type < ANON_AND_FILE; type++)
4358 reset_ctrl_pos(lruvec, type, false);
4360 WRITE_ONCE(lrugen->timestamps[next], jiffies);
4361 /* make sure preceding modifications appear */
4362 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4364 spin_unlock_irq(&lruvec->lru_lock);
4367 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4368 struct scan_control *sc, bool can_swap, bool force_scan)
4371 struct lru_gen_mm_walk *walk;
4372 struct mm_struct *mm = NULL;
4373 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4375 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4377 /* see the comment in iterate_mm_list() */
4378 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4384 * If the hardware doesn't automatically set the accessed bit, fallback
4385 * to lru_gen_look_around(), which only clears the accessed bit in a
4386 * handful of PTEs. Spreading the work out over a period of time usually
4387 * is less efficient, but it avoids bursty page faults.
4389 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
4390 success = iterate_mm_list_nowalk(lruvec, max_seq);
4394 walk = set_mm_walk(NULL);
4396 success = iterate_mm_list_nowalk(lruvec, max_seq);
4400 walk->lruvec = lruvec;
4401 walk->max_seq = max_seq;
4402 walk->can_swap = can_swap;
4403 walk->force_scan = force_scan;
4406 success = iterate_mm_list(lruvec, walk, &mm);
4408 walk_mm(lruvec, mm, walk);
4414 if (sc->priority <= DEF_PRIORITY - 2)
4415 wait_event_killable(lruvec->mm_state.wait,
4416 max_seq < READ_ONCE(lrugen->max_seq));
4418 return max_seq < READ_ONCE(lrugen->max_seq);
4421 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4423 inc_max_seq(lruvec, can_swap, force_scan);
4424 /* either this sees any waiters or they will see updated max_seq */
4425 if (wq_has_sleeper(&lruvec->mm_state.wait))
4426 wake_up_all(&lruvec->mm_state.wait);
4431 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4432 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4434 int gen, type, zone;
4435 unsigned long old = 0;
4436 unsigned long young = 0;
4437 unsigned long total = 0;
4438 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4439 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4441 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4444 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4445 unsigned long size = 0;
4447 gen = lru_gen_from_seq(seq);
4449 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4450 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4455 else if (seq + MIN_NR_GENS == max_seq)
4460 /* try to scrape all its memory if this memcg was deleted */
4461 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4464 * The aging tries to be lazy to reduce the overhead, while the eviction
4465 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4466 * ideal number of generations is MIN_NR_GENS+1.
4468 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4470 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4474 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4475 * of the total number of pages for each generation. A reasonable range
4476 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4477 * aging cares about the upper bound of hot pages, while the eviction
4478 * cares about the lower bound of cold pages.
4480 if (young * MIN_NR_GENS > total)
4482 if (old * (MIN_NR_GENS + 2) < total)
4488 static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
4491 unsigned long nr_to_scan;
4492 int swappiness = get_swappiness(lruvec, sc);
4493 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4494 DEFINE_MAX_SEQ(lruvec);
4495 DEFINE_MIN_SEQ(lruvec);
4497 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4499 mem_cgroup_calculate_protection(NULL, memcg);
4501 if (mem_cgroup_below_min(memcg))
4504 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4507 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4508 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4510 if (time_is_after_jiffies(birth + min_ttl))
4513 /* the size is likely too small to be helpful */
4514 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4519 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
4524 /* to protect the working set of the last N jiffies */
4525 static unsigned long lru_gen_min_ttl __read_mostly;
4527 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4529 struct mem_cgroup *memcg;
4530 bool success = false;
4531 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4533 VM_WARN_ON_ONCE(!current_is_kswapd());
4535 sc->last_reclaimed = sc->nr_reclaimed;
4538 * To reduce the chance of going into the aging path, which can be
4539 * costly, optimistically skip it if the flag below was cleared in the
4540 * eviction path. This improves the overall performance when multiple
4541 * memcgs are available.
4543 if (!sc->memcgs_need_aging) {
4544 sc->memcgs_need_aging = true;
4550 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4552 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4554 if (age_lruvec(lruvec, sc, min_ttl))
4558 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4562 /* check the order to exclude compaction-induced reclaim */
4563 if (success || !min_ttl || sc->order)
4567 * The main goal is to OOM kill if every generation from all memcgs is
4568 * younger than min_ttl. However, another possibility is all memcgs are
4569 * either below min or empty.
4571 if (mutex_trylock(&oom_lock)) {
4572 struct oom_control oc = {
4573 .gfp_mask = sc->gfp_mask,
4578 mutex_unlock(&oom_lock);
4583 * This function exploits spatial locality when shrink_folio_list() walks the
4584 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4585 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4586 * the PTE table to the Bloom filter. This forms a feedback loop between the
4587 * eviction and the aging.
4589 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4593 unsigned long start;
4596 struct lru_gen_mm_walk *walk;
4598 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4599 struct folio *folio = pfn_folio(pvmw->pfn);
4600 struct mem_cgroup *memcg = folio_memcg(folio);
4601 struct pglist_data *pgdat = folio_pgdat(folio);
4602 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4603 DEFINE_MAX_SEQ(lruvec);
4604 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4606 lockdep_assert_held(pvmw->ptl);
4607 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4609 if (spin_is_contended(pvmw->ptl))
4612 /* avoid taking the LRU lock under the PTL when possible */
4613 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4615 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4616 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4618 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4619 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4620 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4621 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4622 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4624 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4625 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4629 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4632 arch_enter_lazy_mmu_mode();
4634 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4637 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4641 if (!pte_young(pte[i]))
4644 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4648 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4649 VM_WARN_ON_ONCE(true);
4653 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4654 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4655 !folio_test_swapcache(folio)))
4656 folio_mark_dirty(folio);
4658 old_gen = folio_lru_gen(folio);
4660 folio_set_referenced(folio);
4661 else if (old_gen != new_gen)
4662 __set_bit(i, bitmap);
4665 arch_leave_lazy_mmu_mode();
4668 /* feedback from rmap walkers to page table walkers */
4669 if (suitable_to_scan(i, young))
4670 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4672 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4673 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4674 folio = pfn_folio(pte_pfn(pte[i]));
4675 folio_activate(folio);
4680 /* folio_update_gen() requires stable folio_memcg() */
4681 if (!mem_cgroup_trylock_pages(memcg))
4685 spin_lock_irq(&lruvec->lru_lock);
4686 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4689 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4690 folio = pfn_folio(pte_pfn(pte[i]));
4691 if (folio_memcg_rcu(folio) != memcg)
4694 old_gen = folio_update_gen(folio, new_gen);
4695 if (old_gen < 0 || old_gen == new_gen)
4699 update_batch_size(walk, folio, old_gen, new_gen);
4701 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
4705 spin_unlock_irq(&lruvec->lru_lock);
4707 mem_cgroup_unlock_pages();
4710 /******************************************************************************
4712 ******************************************************************************/
4714 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4717 int gen = folio_lru_gen(folio);
4718 int type = folio_is_file_lru(folio);
4719 int zone = folio_zonenum(folio);
4720 int delta = folio_nr_pages(folio);
4721 int refs = folio_lru_refs(folio);
4722 int tier = lru_tier_from_refs(refs);
4723 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4725 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4728 if (!folio_evictable(folio)) {
4729 success = lru_gen_del_folio(lruvec, folio, true);
4730 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4731 folio_set_unevictable(folio);
4732 lruvec_add_folio(lruvec, folio);
4733 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4737 /* dirty lazyfree */
4738 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4739 success = lru_gen_del_folio(lruvec, folio, true);
4740 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4741 folio_set_swapbacked(folio);
4742 lruvec_add_folio_tail(lruvec, folio);
4747 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4748 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4753 if (tier > tier_idx) {
4754 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4756 gen = folio_inc_gen(lruvec, folio, false);
4757 list_move_tail(&folio->lru, &lrugen->lists[gen][type][zone]);
4759 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4760 lrugen->protected[hist][type][tier - 1] + delta);
4761 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4765 /* waiting for writeback */
4766 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4767 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4768 gen = folio_inc_gen(lruvec, folio, true);
4769 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4776 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4780 /* unmapping inhibited */
4781 if (!sc->may_unmap && folio_mapped(folio))
4784 /* swapping inhibited */
4785 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4786 (folio_test_dirty(folio) ||
4787 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4790 /* raced with release_pages() */
4791 if (!folio_try_get(folio))
4794 /* raced with another isolation */
4795 if (!folio_test_clear_lru(folio)) {
4800 /* see the comment on MAX_NR_TIERS */
4801 if (!folio_test_referenced(folio))
4802 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4804 /* for shrink_folio_list() */
4805 folio_clear_reclaim(folio);
4806 folio_clear_referenced(folio);
4808 success = lru_gen_del_folio(lruvec, folio, true);
4809 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4814 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4815 int type, int tier, struct list_head *list)
4818 enum vm_event_item item;
4822 int remaining = MAX_LRU_BATCH;
4823 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4824 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4826 VM_WARN_ON_ONCE(!list_empty(list));
4828 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4831 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4833 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4836 struct list_head *head = &lrugen->lists[gen][type][zone];
4838 while (!list_empty(head)) {
4839 struct folio *folio = lru_to_folio(head);
4840 int delta = folio_nr_pages(folio);
4842 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4843 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4844 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4845 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4849 if (sort_folio(lruvec, folio, tier))
4851 else if (isolate_folio(lruvec, folio, sc)) {
4852 list_add(&folio->lru, list);
4855 list_move(&folio->lru, &moved);
4859 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4864 list_splice(&moved, head);
4865 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4868 if (!remaining || isolated >= MIN_LRU_BATCH)
4872 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4873 if (!cgroup_reclaim(sc)) {
4874 __count_vm_events(item, isolated);
4875 __count_vm_events(PGREFILL, sorted);
4877 __count_memcg_events(memcg, item, isolated);
4878 __count_memcg_events(memcg, PGREFILL, sorted);
4879 __count_vm_events(PGSCAN_ANON + type, isolated);
4882 * There might not be eligible pages due to reclaim_idx, may_unmap and
4883 * may_writepage. Check the remaining to prevent livelock if it's not
4886 return isolated || !remaining ? scanned : 0;
4889 static int get_tier_idx(struct lruvec *lruvec, int type)
4892 struct ctrl_pos sp, pv;
4895 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4896 * This value is chosen because any other tier would have at least twice
4897 * as many refaults as the first tier.
4899 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4900 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4901 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4902 if (!positive_ctrl_err(&sp, &pv))
4909 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4912 struct ctrl_pos sp, pv;
4913 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4916 * Compare the first tier of anon with that of file to determine which
4917 * type to scan. Also need to compare other tiers of the selected type
4918 * with the first tier of the other type to determine the last tier (of
4919 * the selected type) to evict.
4921 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4922 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4923 type = positive_ctrl_err(&sp, &pv);
4925 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4926 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4927 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4928 if (!positive_ctrl_err(&sp, &pv))
4932 *tier_idx = tier - 1;
4937 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4938 int *type_scanned, struct list_head *list)
4944 DEFINE_MIN_SEQ(lruvec);
4947 * Try to make the obvious choice first. When anon and file are both
4948 * available from the same generation, interpret swappiness 1 as file
4949 * first and 200 as anon first.
4952 type = LRU_GEN_FILE;
4953 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4954 type = LRU_GEN_ANON;
4955 else if (swappiness == 1)
4956 type = LRU_GEN_FILE;
4957 else if (swappiness == 200)
4958 type = LRU_GEN_ANON;
4960 type = get_type_to_scan(lruvec, swappiness, &tier);
4962 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4964 tier = get_tier_idx(lruvec, type);
4966 scanned = scan_folios(lruvec, sc, type, tier, list);
4974 *type_scanned = type;
4979 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4980 bool *need_swapping)
4987 struct folio *folio;
4989 enum vm_event_item item;
4990 struct reclaim_stat stat;
4991 struct lru_gen_mm_walk *walk;
4992 bool skip_retry = false;
4993 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4994 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4996 spin_lock_irq(&lruvec->lru_lock);
4998 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5000 scanned += try_to_inc_min_seq(lruvec, swappiness);
5002 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5005 spin_unlock_irq(&lruvec->lru_lock);
5007 if (list_empty(&list))
5010 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5011 sc->nr_reclaimed += reclaimed;
5013 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5014 if (!folio_evictable(folio)) {
5015 list_del(&folio->lru);
5016 folio_putback_lru(folio);
5020 if (folio_test_reclaim(folio) &&
5021 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5022 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5023 if (folio_test_workingset(folio))
5024 folio_set_referenced(folio);
5028 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5029 folio_mapped(folio) || folio_test_locked(folio) ||
5030 folio_test_dirty(folio) || folio_test_writeback(folio)) {
5031 /* don't add rejected folios to the oldest generation */
5032 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5037 /* retry folios that may have missed folio_rotate_reclaimable() */
5038 list_move(&folio->lru, &clean);
5039 sc->nr_scanned -= folio_nr_pages(folio);
5042 spin_lock_irq(&lruvec->lru_lock);
5044 move_folios_to_lru(lruvec, &list);
5046 walk = current->reclaim_state->mm_walk;
5047 if (walk && walk->batched)
5048 reset_batch_size(lruvec, walk);
5050 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
5051 if (!cgroup_reclaim(sc))
5052 __count_vm_events(item, reclaimed);
5053 __count_memcg_events(memcg, item, reclaimed);
5054 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5056 spin_unlock_irq(&lruvec->lru_lock);
5058 mem_cgroup_uncharge_list(&list);
5059 free_unref_page_list(&list);
5061 INIT_LIST_HEAD(&list);
5062 list_splice_init(&clean, &list);
5064 if (!list_empty(&list)) {
5069 if (need_swapping && type == LRU_GEN_ANON)
5070 *need_swapping = true;
5076 * For future optimizations:
5077 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5080 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
5081 bool can_swap, bool *need_aging)
5083 unsigned long nr_to_scan;
5084 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5085 DEFINE_MAX_SEQ(lruvec);
5086 DEFINE_MIN_SEQ(lruvec);
5088 if (mem_cgroup_below_min(memcg) ||
5089 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
5092 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
5096 /* skip the aging path at the default priority */
5097 if (sc->priority == DEF_PRIORITY)
5100 /* leave the work to lru_gen_age_node() */
5101 if (current_is_kswapd())
5104 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
5107 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
5110 static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
5111 struct scan_control *sc, bool need_swapping)
5114 DEFINE_MAX_SEQ(lruvec);
5116 if (!current_is_kswapd()) {
5117 /* age each memcg at most once to ensure fairness */
5118 if (max_seq - seq > 1)
5121 /* over-swapping can increase allocation latency */
5122 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
5125 /* give this thread a chance to exit and free its memory */
5126 if (fatal_signal_pending(current)) {
5127 sc->nr_reclaimed += MIN_LRU_BATCH;
5131 if (cgroup_reclaim(sc))
5133 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
5136 /* keep scanning at low priorities to ensure fairness */
5137 if (sc->priority > DEF_PRIORITY - 2)
5141 * A minimum amount of work was done under global memory pressure. For
5142 * kswapd, it may be overshooting. For direct reclaim, the allocation
5143 * may succeed if all suitable zones are somewhat safe. In either case,
5144 * it's better to stop now, and restart later if necessary.
5146 for (i = 0; i <= sc->reclaim_idx; i++) {
5147 unsigned long wmark;
5148 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
5150 if (!managed_zone(zone))
5153 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
5154 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
5158 sc->nr_reclaimed += MIN_LRU_BATCH;
5163 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5165 struct blk_plug plug;
5166 bool need_aging = false;
5167 bool need_swapping = false;
5168 unsigned long scanned = 0;
5169 unsigned long reclaimed = sc->nr_reclaimed;
5170 DEFINE_MAX_SEQ(lruvec);
5174 blk_start_plug(&plug);
5176 set_mm_walk(lruvec_pgdat(lruvec));
5181 unsigned long nr_to_scan;
5184 swappiness = get_swappiness(lruvec, sc);
5185 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
5190 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
5194 delta = evict_folios(lruvec, sc, swappiness, &need_swapping);
5199 if (scanned >= nr_to_scan)
5202 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
5208 /* see the comment in lru_gen_age_node() */
5209 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
5210 sc->memcgs_need_aging = false;
5214 blk_finish_plug(&plug);
5217 /******************************************************************************
5219 ******************************************************************************/
5221 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5223 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5225 if (lrugen->enabled) {
5228 for_each_evictable_lru(lru) {
5229 if (!list_empty(&lruvec->lists[lru]))
5233 int gen, type, zone;
5235 for_each_gen_type_zone(gen, type, zone) {
5236 if (!list_empty(&lrugen->lists[gen][type][zone]))
5244 static bool fill_evictable(struct lruvec *lruvec)
5247 int remaining = MAX_LRU_BATCH;
5249 for_each_evictable_lru(lru) {
5250 int type = is_file_lru(lru);
5251 bool active = is_active_lru(lru);
5252 struct list_head *head = &lruvec->lists[lru];
5254 while (!list_empty(head)) {
5256 struct folio *folio = lru_to_folio(head);
5258 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5259 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5260 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5261 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5263 lruvec_del_folio(lruvec, folio);
5264 success = lru_gen_add_folio(lruvec, folio, false);
5265 VM_WARN_ON_ONCE(!success);
5275 static bool drain_evictable(struct lruvec *lruvec)
5277 int gen, type, zone;
5278 int remaining = MAX_LRU_BATCH;
5280 for_each_gen_type_zone(gen, type, zone) {
5281 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5283 while (!list_empty(head)) {
5285 struct folio *folio = lru_to_folio(head);
5287 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5288 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5289 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5290 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5292 success = lru_gen_del_folio(lruvec, folio, false);
5293 VM_WARN_ON_ONCE(!success);
5294 lruvec_add_folio(lruvec, folio);
5304 static void lru_gen_change_state(bool enabled)
5306 static DEFINE_MUTEX(state_mutex);
5308 struct mem_cgroup *memcg;
5313 mutex_lock(&state_mutex);
5315 if (enabled == lru_gen_enabled())
5319 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5321 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5323 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5327 for_each_node(nid) {
5328 struct lruvec *lruvec = get_lruvec(memcg, nid);
5333 spin_lock_irq(&lruvec->lru_lock);
5335 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5336 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5338 lruvec->lrugen.enabled = enabled;
5340 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5341 spin_unlock_irq(&lruvec->lru_lock);
5343 spin_lock_irq(&lruvec->lru_lock);
5346 spin_unlock_irq(&lruvec->lru_lock);
5350 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5352 mutex_unlock(&state_mutex);
5358 /******************************************************************************
5360 ******************************************************************************/
5362 static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5364 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5367 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5368 static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5369 const char *buf, size_t len)
5373 if (kstrtouint(buf, 0, &msecs))
5376 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5381 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5382 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5385 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5387 unsigned int caps = 0;
5389 if (get_cap(LRU_GEN_CORE))
5390 caps |= BIT(LRU_GEN_CORE);
5392 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5393 caps |= BIT(LRU_GEN_MM_WALK);
5395 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5396 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5398 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5401 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5402 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5403 const char *buf, size_t len)
5408 if (tolower(*buf) == 'n')
5410 else if (tolower(*buf) == 'y')
5412 else if (kstrtouint(buf, 0, &caps))
5415 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5416 bool enabled = caps & BIT(i);
5418 if (i == LRU_GEN_CORE)
5419 lru_gen_change_state(enabled);
5421 static_branch_enable(&lru_gen_caps[i]);
5423 static_branch_disable(&lru_gen_caps[i]);
5429 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5430 enabled, 0644, show_enabled, store_enabled
5433 static struct attribute *lru_gen_attrs[] = {
5434 &lru_gen_min_ttl_attr.attr,
5435 &lru_gen_enabled_attr.attr,
5439 static struct attribute_group lru_gen_attr_group = {
5441 .attrs = lru_gen_attrs,
5444 /******************************************************************************
5446 ******************************************************************************/
5448 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5450 struct mem_cgroup *memcg;
5451 loff_t nr_to_skip = *pos;
5453 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5455 return ERR_PTR(-ENOMEM);
5457 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5461 for_each_node_state(nid, N_MEMORY) {
5463 return get_lruvec(memcg, nid);
5465 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5470 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5472 if (!IS_ERR_OR_NULL(v))
5473 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5479 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5481 int nid = lruvec_pgdat(v)->node_id;
5482 struct mem_cgroup *memcg = lruvec_memcg(v);
5486 nid = next_memory_node(nid);
5487 if (nid == MAX_NUMNODES) {
5488 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5492 nid = first_memory_node;
5495 return get_lruvec(memcg, nid);
5498 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5499 unsigned long max_seq, unsigned long *min_seq,
5504 int hist = lru_hist_from_seq(seq);
5505 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5507 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5508 seq_printf(m, " %10d", tier);
5509 for (type = 0; type < ANON_AND_FILE; type++) {
5510 const char *s = " ";
5511 unsigned long n[3] = {};
5513 if (seq == max_seq) {
5515 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5516 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5517 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5519 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5520 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5522 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5525 for (i = 0; i < 3; i++)
5526 seq_printf(m, " %10lu%c", n[i], s[i]);
5532 for (i = 0; i < NR_MM_STATS; i++) {
5533 const char *s = " ";
5534 unsigned long n = 0;
5536 if (seq == max_seq && NR_HIST_GENS == 1) {
5538 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5539 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5541 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5544 seq_printf(m, " %10lu%c", n, s[i]);
5549 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5550 static int lru_gen_seq_show(struct seq_file *m, void *v)
5553 bool full = !debugfs_real_fops(m->file)->write;
5554 struct lruvec *lruvec = v;
5555 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5556 int nid = lruvec_pgdat(lruvec)->node_id;
5557 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5558 DEFINE_MAX_SEQ(lruvec);
5559 DEFINE_MIN_SEQ(lruvec);
5561 if (nid == first_memory_node) {
5562 const char *path = memcg ? m->private : "";
5566 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5568 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5571 seq_printf(m, " node %5d\n", nid);
5574 seq = min_seq[LRU_GEN_ANON];
5575 else if (max_seq >= MAX_NR_GENS)
5576 seq = max_seq - MAX_NR_GENS + 1;
5580 for (; seq <= max_seq; seq++) {
5582 int gen = lru_gen_from_seq(seq);
5583 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5585 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5587 for (type = 0; type < ANON_AND_FILE; type++) {
5588 unsigned long size = 0;
5589 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5591 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5592 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5594 seq_printf(m, " %10lu%c", size, mark);
5600 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5606 static const struct seq_operations lru_gen_seq_ops = {
5607 .start = lru_gen_seq_start,
5608 .stop = lru_gen_seq_stop,
5609 .next = lru_gen_seq_next,
5610 .show = lru_gen_seq_show,
5613 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5614 bool can_swap, bool force_scan)
5616 DEFINE_MAX_SEQ(lruvec);
5617 DEFINE_MIN_SEQ(lruvec);
5625 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5628 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5633 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5634 int swappiness, unsigned long nr_to_reclaim)
5636 DEFINE_MAX_SEQ(lruvec);
5638 if (seq + MIN_NR_GENS > max_seq)
5641 sc->nr_reclaimed = 0;
5643 while (!signal_pending(current)) {
5644 DEFINE_MIN_SEQ(lruvec);
5646 if (seq < min_seq[!swappiness])
5649 if (sc->nr_reclaimed >= nr_to_reclaim)
5652 if (!evict_folios(lruvec, sc, swappiness, NULL))
5661 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5662 struct scan_control *sc, int swappiness, unsigned long opt)
5664 struct lruvec *lruvec;
5666 struct mem_cgroup *memcg = NULL;
5668 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5671 if (!mem_cgroup_disabled()) {
5673 memcg = mem_cgroup_from_id(memcg_id);
5675 if (memcg && !css_tryget(&memcg->css))
5684 if (memcg_id != mem_cgroup_id(memcg))
5687 lruvec = get_lruvec(memcg, nid);
5690 swappiness = get_swappiness(lruvec, sc);
5691 else if (swappiness > 200)
5696 err = run_aging(lruvec, seq, sc, swappiness, opt);
5699 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5703 mem_cgroup_put(memcg);
5708 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5709 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5710 size_t len, loff_t *pos)
5715 struct blk_plug plug;
5717 struct scan_control sc = {
5718 .may_writepage = true,
5721 .reclaim_idx = MAX_NR_ZONES - 1,
5722 .gfp_mask = GFP_KERNEL,
5725 buf = kvmalloc(len + 1, GFP_KERNEL);
5729 if (copy_from_user(buf, src, len)) {
5734 set_task_reclaim_state(current, &sc.reclaim_state);
5735 flags = memalloc_noreclaim_save();
5736 blk_start_plug(&plug);
5737 if (!set_mm_walk(NULL)) {
5745 while ((cur = strsep(&next, ",;\n"))) {
5749 unsigned int memcg_id;
5752 unsigned int swappiness = -1;
5753 unsigned long opt = -1;
5755 cur = skip_spaces(cur);
5759 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5760 &seq, &end, &swappiness, &end, &opt, &end);
5761 if (n < 4 || cur[end]) {
5766 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5772 blk_finish_plug(&plug);
5773 memalloc_noreclaim_restore(flags);
5774 set_task_reclaim_state(current, NULL);
5781 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5783 return seq_open(file, &lru_gen_seq_ops);
5786 static const struct file_operations lru_gen_rw_fops = {
5787 .open = lru_gen_seq_open,
5789 .write = lru_gen_seq_write,
5790 .llseek = seq_lseek,
5791 .release = seq_release,
5794 static const struct file_operations lru_gen_ro_fops = {
5795 .open = lru_gen_seq_open,
5797 .llseek = seq_lseek,
5798 .release = seq_release,
5801 /******************************************************************************
5803 ******************************************************************************/
5805 void lru_gen_init_lruvec(struct lruvec *lruvec)
5808 int gen, type, zone;
5809 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5811 lrugen->max_seq = MIN_NR_GENS + 1;
5812 lrugen->enabled = lru_gen_enabled();
5814 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5815 lrugen->timestamps[i] = jiffies;
5817 for_each_gen_type_zone(gen, type, zone)
5818 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
5820 lruvec->mm_state.seq = MIN_NR_GENS;
5821 init_waitqueue_head(&lruvec->mm_state.wait);
5825 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5827 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5828 spin_lock_init(&memcg->mm_list.lock);
5831 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5836 for_each_node(nid) {
5837 struct lruvec *lruvec = get_lruvec(memcg, nid);
5839 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5840 sizeof(lruvec->lrugen.nr_pages)));
5842 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5843 bitmap_free(lruvec->mm_state.filters[i]);
5844 lruvec->mm_state.filters[i] = NULL;
5850 static int __init init_lru_gen(void)
5852 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5853 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5855 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5856 pr_err("lru_gen: failed to create sysfs group\n");
5858 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5859 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5863 late_initcall(init_lru_gen);
5865 #else /* !CONFIG_LRU_GEN */
5867 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5871 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5875 #endif /* CONFIG_LRU_GEN */
5877 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5879 unsigned long nr[NR_LRU_LISTS];
5880 unsigned long targets[NR_LRU_LISTS];
5881 unsigned long nr_to_scan;
5883 unsigned long nr_reclaimed = 0;
5884 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5885 bool proportional_reclaim;
5886 struct blk_plug plug;
5888 if (lru_gen_enabled()) {
5889 lru_gen_shrink_lruvec(lruvec, sc);
5893 get_scan_count(lruvec, sc, nr);
5895 /* Record the original scan target for proportional adjustments later */
5896 memcpy(targets, nr, sizeof(nr));
5899 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5900 * event that can occur when there is little memory pressure e.g.
5901 * multiple streaming readers/writers. Hence, we do not abort scanning
5902 * when the requested number of pages are reclaimed when scanning at
5903 * DEF_PRIORITY on the assumption that the fact we are direct
5904 * reclaiming implies that kswapd is not keeping up and it is best to
5905 * do a batch of work at once. For memcg reclaim one check is made to
5906 * abort proportional reclaim if either the file or anon lru has already
5907 * dropped to zero at the first pass.
5909 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5910 sc->priority == DEF_PRIORITY);
5912 blk_start_plug(&plug);
5913 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5914 nr[LRU_INACTIVE_FILE]) {
5915 unsigned long nr_anon, nr_file, percentage;
5916 unsigned long nr_scanned;
5918 for_each_evictable_lru(lru) {
5920 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5921 nr[lru] -= nr_to_scan;
5923 nr_reclaimed += shrink_list(lru, nr_to_scan,
5930 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5934 * For kswapd and memcg, reclaim at least the number of pages
5935 * requested. Ensure that the anon and file LRUs are scanned
5936 * proportionally what was requested by get_scan_count(). We
5937 * stop reclaiming one LRU and reduce the amount scanning
5938 * proportional to the original scan target.
5940 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5941 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5944 * It's just vindictive to attack the larger once the smaller
5945 * has gone to zero. And given the way we stop scanning the
5946 * smaller below, this makes sure that we only make one nudge
5947 * towards proportionality once we've got nr_to_reclaim.
5949 if (!nr_file || !nr_anon)
5952 if (nr_file > nr_anon) {
5953 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5954 targets[LRU_ACTIVE_ANON] + 1;
5956 percentage = nr_anon * 100 / scan_target;
5958 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5959 targets[LRU_ACTIVE_FILE] + 1;
5961 percentage = nr_file * 100 / scan_target;
5964 /* Stop scanning the smaller of the LRU */
5966 nr[lru + LRU_ACTIVE] = 0;
5969 * Recalculate the other LRU scan count based on its original
5970 * scan target and the percentage scanning already complete
5972 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5973 nr_scanned = targets[lru] - nr[lru];
5974 nr[lru] = targets[lru] * (100 - percentage) / 100;
5975 nr[lru] -= min(nr[lru], nr_scanned);
5978 nr_scanned = targets[lru] - nr[lru];
5979 nr[lru] = targets[lru] * (100 - percentage) / 100;
5980 nr[lru] -= min(nr[lru], nr_scanned);
5982 blk_finish_plug(&plug);
5983 sc->nr_reclaimed += nr_reclaimed;
5986 * Even if we did not try to evict anon pages at all, we want to
5987 * rebalance the anon lru active/inactive ratio.
5989 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5990 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5991 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5992 sc, LRU_ACTIVE_ANON);
5995 /* Use reclaim/compaction for costly allocs or under memory pressure */
5996 static bool in_reclaim_compaction(struct scan_control *sc)
5998 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
5999 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6000 sc->priority < DEF_PRIORITY - 2))
6007 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6008 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6009 * true if more pages should be reclaimed such that when the page allocator
6010 * calls try_to_compact_pages() that it will have enough free pages to succeed.
6011 * It will give up earlier than that if there is difficulty reclaiming pages.
6013 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6014 unsigned long nr_reclaimed,
6015 struct scan_control *sc)
6017 unsigned long pages_for_compaction;
6018 unsigned long inactive_lru_pages;
6021 /* If not in reclaim/compaction mode, stop */
6022 if (!in_reclaim_compaction(sc))
6026 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6027 * number of pages that were scanned. This will return to the caller
6028 * with the risk reclaim/compaction and the resulting allocation attempt
6029 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6030 * allocations through requiring that the full LRU list has been scanned
6031 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6032 * scan, but that approximation was wrong, and there were corner cases
6033 * where always a non-zero amount of pages were scanned.
6038 /* If compaction would go ahead or the allocation would succeed, stop */
6039 for (z = 0; z <= sc->reclaim_idx; z++) {
6040 struct zone *zone = &pgdat->node_zones[z];
6041 if (!managed_zone(zone))
6044 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6045 case COMPACT_SUCCESS:
6046 case COMPACT_CONTINUE:
6049 /* check next zone */
6055 * If we have not reclaimed enough pages for compaction and the
6056 * inactive lists are large enough, continue reclaiming
6058 pages_for_compaction = compact_gap(sc->order);
6059 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6060 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6061 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6063 return inactive_lru_pages > pages_for_compaction;
6066 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6068 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6069 struct mem_cgroup *memcg;
6071 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6073 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6074 unsigned long reclaimed;
6075 unsigned long scanned;
6078 * This loop can become CPU-bound when target memcgs
6079 * aren't eligible for reclaim - either because they
6080 * don't have any reclaimable pages, or because their
6081 * memory is explicitly protected. Avoid soft lockups.
6085 mem_cgroup_calculate_protection(target_memcg, memcg);
6087 if (mem_cgroup_below_min(memcg)) {
6090 * If there is no reclaimable memory, OOM.
6093 } else if (mem_cgroup_below_low(memcg)) {
6096 * Respect the protection only as long as
6097 * there is an unprotected supply
6098 * of reclaimable memory from other cgroups.
6100 if (!sc->memcg_low_reclaim) {
6101 sc->memcg_low_skipped = 1;
6104 memcg_memory_event(memcg, MEMCG_LOW);
6107 reclaimed = sc->nr_reclaimed;
6108 scanned = sc->nr_scanned;
6110 shrink_lruvec(lruvec, sc);
6112 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6115 /* Record the group's reclaim efficiency */
6117 vmpressure(sc->gfp_mask, memcg, false,
6118 sc->nr_scanned - scanned,
6119 sc->nr_reclaimed - reclaimed);
6121 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6124 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6126 struct reclaim_state *reclaim_state = current->reclaim_state;
6127 unsigned long nr_reclaimed, nr_scanned;
6128 struct lruvec *target_lruvec;
6129 bool reclaimable = false;
6131 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6134 memset(&sc->nr, 0, sizeof(sc->nr));
6136 nr_reclaimed = sc->nr_reclaimed;
6137 nr_scanned = sc->nr_scanned;
6139 prepare_scan_count(pgdat, sc);
6141 shrink_node_memcgs(pgdat, sc);
6143 if (reclaim_state) {
6144 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6145 reclaim_state->reclaimed_slab = 0;
6148 /* Record the subtree's reclaim efficiency */
6150 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6151 sc->nr_scanned - nr_scanned,
6152 sc->nr_reclaimed - nr_reclaimed);
6154 if (sc->nr_reclaimed - nr_reclaimed)
6157 if (current_is_kswapd()) {
6159 * If reclaim is isolating dirty pages under writeback,
6160 * it implies that the long-lived page allocation rate
6161 * is exceeding the page laundering rate. Either the
6162 * global limits are not being effective at throttling
6163 * processes due to the page distribution throughout
6164 * zones or there is heavy usage of a slow backing
6165 * device. The only option is to throttle from reclaim
6166 * context which is not ideal as there is no guarantee
6167 * the dirtying process is throttled in the same way
6168 * balance_dirty_pages() manages.
6170 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6171 * count the number of pages under pages flagged for
6172 * immediate reclaim and stall if any are encountered
6173 * in the nr_immediate check below.
6175 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6176 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6178 /* Allow kswapd to start writing pages during reclaim.*/
6179 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6180 set_bit(PGDAT_DIRTY, &pgdat->flags);
6183 * If kswapd scans pages marked for immediate
6184 * reclaim and under writeback (nr_immediate), it
6185 * implies that pages are cycling through the LRU
6186 * faster than they are written so forcibly stall
6187 * until some pages complete writeback.
6189 if (sc->nr.immediate)
6190 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6194 * Tag a node/memcg as congested if all the dirty pages were marked
6195 * for writeback and immediate reclaim (counted in nr.congested).
6197 * Legacy memcg will stall in page writeback so avoid forcibly
6198 * stalling in reclaim_throttle().
6200 if ((current_is_kswapd() ||
6201 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6202 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6203 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6206 * Stall direct reclaim for IO completions if the lruvec is
6207 * node is congested. Allow kswapd to continue until it
6208 * starts encountering unqueued dirty pages or cycling through
6209 * the LRU too quickly.
6211 if (!current_is_kswapd() && current_may_throttle() &&
6212 !sc->hibernation_mode &&
6213 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6214 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6216 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6221 * Kswapd gives up on balancing particular nodes after too
6222 * many failures to reclaim anything from them and goes to
6223 * sleep. On reclaim progress, reset the failure counter. A
6224 * successful direct reclaim run will revive a dormant kswapd.
6227 pgdat->kswapd_failures = 0;
6231 * Returns true if compaction should go ahead for a costly-order request, or
6232 * the allocation would already succeed without compaction. Return false if we
6233 * should reclaim first.
6235 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6237 unsigned long watermark;
6238 enum compact_result suitable;
6240 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6241 if (suitable == COMPACT_SUCCESS)
6242 /* Allocation should succeed already. Don't reclaim. */
6244 if (suitable == COMPACT_SKIPPED)
6245 /* Compaction cannot yet proceed. Do reclaim. */
6249 * Compaction is already possible, but it takes time to run and there
6250 * are potentially other callers using the pages just freed. So proceed
6251 * with reclaim to make a buffer of free pages available to give
6252 * compaction a reasonable chance of completing and allocating the page.
6253 * Note that we won't actually reclaim the whole buffer in one attempt
6254 * as the target watermark in should_continue_reclaim() is lower. But if
6255 * we are already above the high+gap watermark, don't reclaim at all.
6257 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6259 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6262 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6265 * If reclaim is making progress greater than 12% efficiency then
6266 * wake all the NOPROGRESS throttled tasks.
6268 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6269 wait_queue_head_t *wqh;
6271 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6272 if (waitqueue_active(wqh))
6279 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6280 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6281 * under writeback and marked for immediate reclaim at the tail of the
6284 if (current_is_kswapd() || cgroup_reclaim(sc))
6287 /* Throttle if making no progress at high prioities. */
6288 if (sc->priority == 1 && !sc->nr_reclaimed)
6289 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6293 * This is the direct reclaim path, for page-allocating processes. We only
6294 * try to reclaim pages from zones which will satisfy the caller's allocation
6297 * If a zone is deemed to be full of pinned pages then just give it a light
6298 * scan then give up on it.
6300 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6304 unsigned long nr_soft_reclaimed;
6305 unsigned long nr_soft_scanned;
6307 pg_data_t *last_pgdat = NULL;
6308 pg_data_t *first_pgdat = NULL;
6311 * If the number of buffer_heads in the machine exceeds the maximum
6312 * allowed level, force direct reclaim to scan the highmem zone as
6313 * highmem pages could be pinning lowmem pages storing buffer_heads
6315 orig_mask = sc->gfp_mask;
6316 if (buffer_heads_over_limit) {
6317 sc->gfp_mask |= __GFP_HIGHMEM;
6318 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6321 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6322 sc->reclaim_idx, sc->nodemask) {
6324 * Take care memory controller reclaiming has small influence
6327 if (!cgroup_reclaim(sc)) {
6328 if (!cpuset_zone_allowed(zone,
6329 GFP_KERNEL | __GFP_HARDWALL))
6333 * If we already have plenty of memory free for
6334 * compaction in this zone, don't free any more.
6335 * Even though compaction is invoked for any
6336 * non-zero order, only frequent costly order
6337 * reclamation is disruptive enough to become a
6338 * noticeable problem, like transparent huge
6341 if (IS_ENABLED(CONFIG_COMPACTION) &&
6342 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6343 compaction_ready(zone, sc)) {
6344 sc->compaction_ready = true;
6349 * Shrink each node in the zonelist once. If the
6350 * zonelist is ordered by zone (not the default) then a
6351 * node may be shrunk multiple times but in that case
6352 * the user prefers lower zones being preserved.
6354 if (zone->zone_pgdat == last_pgdat)
6358 * This steals pages from memory cgroups over softlimit
6359 * and returns the number of reclaimed pages and
6360 * scanned pages. This works for global memory pressure
6361 * and balancing, not for a memcg's limit.
6363 nr_soft_scanned = 0;
6364 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6365 sc->order, sc->gfp_mask,
6367 sc->nr_reclaimed += nr_soft_reclaimed;
6368 sc->nr_scanned += nr_soft_scanned;
6369 /* need some check for avoid more shrink_zone() */
6373 first_pgdat = zone->zone_pgdat;
6375 /* See comment about same check for global reclaim above */
6376 if (zone->zone_pgdat == last_pgdat)
6378 last_pgdat = zone->zone_pgdat;
6379 shrink_node(zone->zone_pgdat, sc);
6383 consider_reclaim_throttle(first_pgdat, sc);
6386 * Restore to original mask to avoid the impact on the caller if we
6387 * promoted it to __GFP_HIGHMEM.
6389 sc->gfp_mask = orig_mask;
6392 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6394 struct lruvec *target_lruvec;
6395 unsigned long refaults;
6397 if (lru_gen_enabled())
6400 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6401 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6402 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6403 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6404 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6408 * This is the main entry point to direct page reclaim.
6410 * If a full scan of the inactive list fails to free enough memory then we
6411 * are "out of memory" and something needs to be killed.
6413 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6414 * high - the zone may be full of dirty or under-writeback pages, which this
6415 * caller can't do much about. We kick the writeback threads and take explicit
6416 * naps in the hope that some of these pages can be written. But if the
6417 * allocating task holds filesystem locks which prevent writeout this might not
6418 * work, and the allocation attempt will fail.
6420 * returns: 0, if no pages reclaimed
6421 * else, the number of pages reclaimed
6423 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6424 struct scan_control *sc)
6426 int initial_priority = sc->priority;
6427 pg_data_t *last_pgdat;
6431 delayacct_freepages_start();
6433 if (!cgroup_reclaim(sc))
6434 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6438 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6441 shrink_zones(zonelist, sc);
6443 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6446 if (sc->compaction_ready)
6450 * If we're getting trouble reclaiming, start doing
6451 * writepage even in laptop mode.
6453 if (sc->priority < DEF_PRIORITY - 2)
6454 sc->may_writepage = 1;
6455 } while (--sc->priority >= 0);
6458 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6460 if (zone->zone_pgdat == last_pgdat)
6462 last_pgdat = zone->zone_pgdat;
6464 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6466 if (cgroup_reclaim(sc)) {
6467 struct lruvec *lruvec;
6469 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6471 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6475 delayacct_freepages_end();
6477 if (sc->nr_reclaimed)
6478 return sc->nr_reclaimed;
6480 /* Aborted reclaim to try compaction? don't OOM, then */
6481 if (sc->compaction_ready)
6485 * We make inactive:active ratio decisions based on the node's
6486 * composition of memory, but a restrictive reclaim_idx or a
6487 * memory.low cgroup setting can exempt large amounts of
6488 * memory from reclaim. Neither of which are very common, so
6489 * instead of doing costly eligibility calculations of the
6490 * entire cgroup subtree up front, we assume the estimates are
6491 * good, and retry with forcible deactivation if that fails.
6493 if (sc->skipped_deactivate) {
6494 sc->priority = initial_priority;
6495 sc->force_deactivate = 1;
6496 sc->skipped_deactivate = 0;
6500 /* Untapped cgroup reserves? Don't OOM, retry. */
6501 if (sc->memcg_low_skipped) {
6502 sc->priority = initial_priority;
6503 sc->force_deactivate = 0;
6504 sc->memcg_low_reclaim = 1;
6505 sc->memcg_low_skipped = 0;
6512 static bool allow_direct_reclaim(pg_data_t *pgdat)
6515 unsigned long pfmemalloc_reserve = 0;
6516 unsigned long free_pages = 0;
6520 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6523 for (i = 0; i <= ZONE_NORMAL; i++) {
6524 zone = &pgdat->node_zones[i];
6525 if (!managed_zone(zone))
6528 if (!zone_reclaimable_pages(zone))
6531 pfmemalloc_reserve += min_wmark_pages(zone);
6532 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6535 /* If there are no reserves (unexpected config) then do not throttle */
6536 if (!pfmemalloc_reserve)
6539 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6541 /* kswapd must be awake if processes are being throttled */
6542 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6543 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6544 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6546 wake_up_interruptible(&pgdat->kswapd_wait);
6553 * Throttle direct reclaimers if backing storage is backed by the network
6554 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6555 * depleted. kswapd will continue to make progress and wake the processes
6556 * when the low watermark is reached.
6558 * Returns true if a fatal signal was delivered during throttling. If this
6559 * happens, the page allocator should not consider triggering the OOM killer.
6561 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6562 nodemask_t *nodemask)
6566 pg_data_t *pgdat = NULL;
6569 * Kernel threads should not be throttled as they may be indirectly
6570 * responsible for cleaning pages necessary for reclaim to make forward
6571 * progress. kjournald for example may enter direct reclaim while
6572 * committing a transaction where throttling it could forcing other
6573 * processes to block on log_wait_commit().
6575 if (current->flags & PF_KTHREAD)
6579 * If a fatal signal is pending, this process should not throttle.
6580 * It should return quickly so it can exit and free its memory
6582 if (fatal_signal_pending(current))
6586 * Check if the pfmemalloc reserves are ok by finding the first node
6587 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6588 * GFP_KERNEL will be required for allocating network buffers when
6589 * swapping over the network so ZONE_HIGHMEM is unusable.
6591 * Throttling is based on the first usable node and throttled processes
6592 * wait on a queue until kswapd makes progress and wakes them. There
6593 * is an affinity then between processes waking up and where reclaim
6594 * progress has been made assuming the process wakes on the same node.
6595 * More importantly, processes running on remote nodes will not compete
6596 * for remote pfmemalloc reserves and processes on different nodes
6597 * should make reasonable progress.
6599 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6600 gfp_zone(gfp_mask), nodemask) {
6601 if (zone_idx(zone) > ZONE_NORMAL)
6604 /* Throttle based on the first usable node */
6605 pgdat = zone->zone_pgdat;
6606 if (allow_direct_reclaim(pgdat))
6611 /* If no zone was usable by the allocation flags then do not throttle */
6615 /* Account for the throttling */
6616 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6619 * If the caller cannot enter the filesystem, it's possible that it
6620 * is due to the caller holding an FS lock or performing a journal
6621 * transaction in the case of a filesystem like ext[3|4]. In this case,
6622 * it is not safe to block on pfmemalloc_wait as kswapd could be
6623 * blocked waiting on the same lock. Instead, throttle for up to a
6624 * second before continuing.
6626 if (!(gfp_mask & __GFP_FS))
6627 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6628 allow_direct_reclaim(pgdat), HZ);
6630 /* Throttle until kswapd wakes the process */
6631 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6632 allow_direct_reclaim(pgdat));
6634 if (fatal_signal_pending(current))
6641 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6642 gfp_t gfp_mask, nodemask_t *nodemask)
6644 unsigned long nr_reclaimed;
6645 struct scan_control sc = {
6646 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6647 .gfp_mask = current_gfp_context(gfp_mask),
6648 .reclaim_idx = gfp_zone(gfp_mask),
6650 .nodemask = nodemask,
6651 .priority = DEF_PRIORITY,
6652 .may_writepage = !laptop_mode,
6658 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6659 * Confirm they are large enough for max values.
6661 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6662 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6663 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6666 * Do not enter reclaim if fatal signal was delivered while throttled.
6667 * 1 is returned so that the page allocator does not OOM kill at this
6670 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6673 set_task_reclaim_state(current, &sc.reclaim_state);
6674 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6676 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6678 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6679 set_task_reclaim_state(current, NULL);
6681 return nr_reclaimed;
6686 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6687 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6688 gfp_t gfp_mask, bool noswap,
6690 unsigned long *nr_scanned)
6692 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6693 struct scan_control sc = {
6694 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6695 .target_mem_cgroup = memcg,
6696 .may_writepage = !laptop_mode,
6698 .reclaim_idx = MAX_NR_ZONES - 1,
6699 .may_swap = !noswap,
6702 WARN_ON_ONCE(!current->reclaim_state);
6704 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6705 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6707 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6711 * NOTE: Although we can get the priority field, using it
6712 * here is not a good idea, since it limits the pages we can scan.
6713 * if we don't reclaim here, the shrink_node from balance_pgdat
6714 * will pick up pages from other mem cgroup's as well. We hack
6715 * the priority and make it zero.
6717 shrink_lruvec(lruvec, &sc);
6719 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6721 *nr_scanned = sc.nr_scanned;
6723 return sc.nr_reclaimed;
6726 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6727 unsigned long nr_pages,
6729 unsigned int reclaim_options)
6731 unsigned long nr_reclaimed;
6732 unsigned int noreclaim_flag;
6733 struct scan_control sc = {
6734 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6735 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6736 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6737 .reclaim_idx = MAX_NR_ZONES - 1,
6738 .target_mem_cgroup = memcg,
6739 .priority = DEF_PRIORITY,
6740 .may_writepage = !laptop_mode,
6742 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6743 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6746 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6747 * equal pressure on all the nodes. This is based on the assumption that
6748 * the reclaim does not bail out early.
6750 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6752 set_task_reclaim_state(current, &sc.reclaim_state);
6753 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6754 noreclaim_flag = memalloc_noreclaim_save();
6756 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6758 memalloc_noreclaim_restore(noreclaim_flag);
6759 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6760 set_task_reclaim_state(current, NULL);
6762 return nr_reclaimed;
6766 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6768 struct mem_cgroup *memcg;
6769 struct lruvec *lruvec;
6771 if (lru_gen_enabled()) {
6772 lru_gen_age_node(pgdat, sc);
6776 if (!can_age_anon_pages(pgdat, sc))
6779 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6780 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6783 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6785 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6786 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6787 sc, LRU_ACTIVE_ANON);
6788 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6792 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6798 * Check for watermark boosts top-down as the higher zones
6799 * are more likely to be boosted. Both watermarks and boosts
6800 * should not be checked at the same time as reclaim would
6801 * start prematurely when there is no boosting and a lower
6804 for (i = highest_zoneidx; i >= 0; i--) {
6805 zone = pgdat->node_zones + i;
6806 if (!managed_zone(zone))
6809 if (zone->watermark_boost)
6817 * Returns true if there is an eligible zone balanced for the request order
6818 * and highest_zoneidx
6820 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6823 unsigned long mark = -1;
6827 * Check watermarks bottom-up as lower zones are more likely to
6830 for (i = 0; i <= highest_zoneidx; i++) {
6831 zone = pgdat->node_zones + i;
6833 if (!managed_zone(zone))
6836 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6837 mark = wmark_pages(zone, WMARK_PROMO);
6839 mark = high_wmark_pages(zone);
6840 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6845 * If a node has no managed zone within highest_zoneidx, it does not
6846 * need balancing by definition. This can happen if a zone-restricted
6847 * allocation tries to wake a remote kswapd.
6855 /* Clear pgdat state for congested, dirty or under writeback. */
6856 static void clear_pgdat_congested(pg_data_t *pgdat)
6858 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6860 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6861 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6862 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6866 * Prepare kswapd for sleeping. This verifies that there are no processes
6867 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6869 * Returns true if kswapd is ready to sleep
6871 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6872 int highest_zoneidx)
6875 * The throttled processes are normally woken up in balance_pgdat() as
6876 * soon as allow_direct_reclaim() is true. But there is a potential
6877 * race between when kswapd checks the watermarks and a process gets
6878 * throttled. There is also a potential race if processes get
6879 * throttled, kswapd wakes, a large process exits thereby balancing the
6880 * zones, which causes kswapd to exit balance_pgdat() before reaching
6881 * the wake up checks. If kswapd is going to sleep, no process should
6882 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6883 * the wake up is premature, processes will wake kswapd and get
6884 * throttled again. The difference from wake ups in balance_pgdat() is
6885 * that here we are under prepare_to_wait().
6887 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6888 wake_up_all(&pgdat->pfmemalloc_wait);
6890 /* Hopeless node, leave it to direct reclaim */
6891 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6894 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6895 clear_pgdat_congested(pgdat);
6903 * kswapd shrinks a node of pages that are at or below the highest usable
6904 * zone that is currently unbalanced.
6906 * Returns true if kswapd scanned at least the requested number of pages to
6907 * reclaim or if the lack of progress was due to pages under writeback.
6908 * This is used to determine if the scanning priority needs to be raised.
6910 static bool kswapd_shrink_node(pg_data_t *pgdat,
6911 struct scan_control *sc)
6916 /* Reclaim a number of pages proportional to the number of zones */
6917 sc->nr_to_reclaim = 0;
6918 for (z = 0; z <= sc->reclaim_idx; z++) {
6919 zone = pgdat->node_zones + z;
6920 if (!managed_zone(zone))
6923 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6927 * Historically care was taken to put equal pressure on all zones but
6928 * now pressure is applied based on node LRU order.
6930 shrink_node(pgdat, sc);
6933 * Fragmentation may mean that the system cannot be rebalanced for
6934 * high-order allocations. If twice the allocation size has been
6935 * reclaimed then recheck watermarks only at order-0 to prevent
6936 * excessive reclaim. Assume that a process requested a high-order
6937 * can direct reclaim/compact.
6939 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6942 return sc->nr_scanned >= sc->nr_to_reclaim;
6945 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6947 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6952 for (i = 0; i <= highest_zoneidx; i++) {
6953 zone = pgdat->node_zones + i;
6955 if (!managed_zone(zone))
6959 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6961 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6966 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6968 update_reclaim_active(pgdat, highest_zoneidx, true);
6972 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6974 update_reclaim_active(pgdat, highest_zoneidx, false);
6978 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6979 * that are eligible for use by the caller until at least one zone is
6982 * Returns the order kswapd finished reclaiming at.
6984 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6985 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6986 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6987 * or lower is eligible for reclaim until at least one usable zone is
6990 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
6993 unsigned long nr_soft_reclaimed;
6994 unsigned long nr_soft_scanned;
6995 unsigned long pflags;
6996 unsigned long nr_boost_reclaim;
6997 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7000 struct scan_control sc = {
7001 .gfp_mask = GFP_KERNEL,
7006 set_task_reclaim_state(current, &sc.reclaim_state);
7007 psi_memstall_enter(&pflags);
7008 __fs_reclaim_acquire(_THIS_IP_);
7010 count_vm_event(PAGEOUTRUN);
7013 * Account for the reclaim boost. Note that the zone boost is left in
7014 * place so that parallel allocations that are near the watermark will
7015 * stall or direct reclaim until kswapd is finished.
7017 nr_boost_reclaim = 0;
7018 for (i = 0; i <= highest_zoneidx; i++) {
7019 zone = pgdat->node_zones + i;
7020 if (!managed_zone(zone))
7023 nr_boost_reclaim += zone->watermark_boost;
7024 zone_boosts[i] = zone->watermark_boost;
7026 boosted = nr_boost_reclaim;
7029 set_reclaim_active(pgdat, highest_zoneidx);
7030 sc.priority = DEF_PRIORITY;
7032 unsigned long nr_reclaimed = sc.nr_reclaimed;
7033 bool raise_priority = true;
7037 sc.reclaim_idx = highest_zoneidx;
7040 * If the number of buffer_heads exceeds the maximum allowed
7041 * then consider reclaiming from all zones. This has a dual
7042 * purpose -- on 64-bit systems it is expected that
7043 * buffer_heads are stripped during active rotation. On 32-bit
7044 * systems, highmem pages can pin lowmem memory and shrinking
7045 * buffers can relieve lowmem pressure. Reclaim may still not
7046 * go ahead if all eligible zones for the original allocation
7047 * request are balanced to avoid excessive reclaim from kswapd.
7049 if (buffer_heads_over_limit) {
7050 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7051 zone = pgdat->node_zones + i;
7052 if (!managed_zone(zone))
7061 * If the pgdat is imbalanced then ignore boosting and preserve
7062 * the watermarks for a later time and restart. Note that the
7063 * zone watermarks will be still reset at the end of balancing
7064 * on the grounds that the normal reclaim should be enough to
7065 * re-evaluate if boosting is required when kswapd next wakes.
7067 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7068 if (!balanced && nr_boost_reclaim) {
7069 nr_boost_reclaim = 0;
7074 * If boosting is not active then only reclaim if there are no
7075 * eligible zones. Note that sc.reclaim_idx is not used as
7076 * buffer_heads_over_limit may have adjusted it.
7078 if (!nr_boost_reclaim && balanced)
7081 /* Limit the priority of boosting to avoid reclaim writeback */
7082 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7083 raise_priority = false;
7086 * Do not writeback or swap pages for boosted reclaim. The
7087 * intent is to relieve pressure not issue sub-optimal IO
7088 * from reclaim context. If no pages are reclaimed, the
7089 * reclaim will be aborted.
7091 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7092 sc.may_swap = !nr_boost_reclaim;
7095 * Do some background aging, to give pages a chance to be
7096 * referenced before reclaiming. All pages are rotated
7097 * regardless of classzone as this is about consistent aging.
7099 kswapd_age_node(pgdat, &sc);
7102 * If we're getting trouble reclaiming, start doing writepage
7103 * even in laptop mode.
7105 if (sc.priority < DEF_PRIORITY - 2)
7106 sc.may_writepage = 1;
7108 /* Call soft limit reclaim before calling shrink_node. */
7110 nr_soft_scanned = 0;
7111 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7112 sc.gfp_mask, &nr_soft_scanned);
7113 sc.nr_reclaimed += nr_soft_reclaimed;
7116 * There should be no need to raise the scanning priority if
7117 * enough pages are already being scanned that that high
7118 * watermark would be met at 100% efficiency.
7120 if (kswapd_shrink_node(pgdat, &sc))
7121 raise_priority = false;
7124 * If the low watermark is met there is no need for processes
7125 * to be throttled on pfmemalloc_wait as they should not be
7126 * able to safely make forward progress. Wake them
7128 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7129 allow_direct_reclaim(pgdat))
7130 wake_up_all(&pgdat->pfmemalloc_wait);
7132 /* Check if kswapd should be suspending */
7133 __fs_reclaim_release(_THIS_IP_);
7134 ret = try_to_freeze();
7135 __fs_reclaim_acquire(_THIS_IP_);
7136 if (ret || kthread_should_stop())
7140 * Raise priority if scanning rate is too low or there was no
7141 * progress in reclaiming pages
7143 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7144 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7147 * If reclaim made no progress for a boost, stop reclaim as
7148 * IO cannot be queued and it could be an infinite loop in
7149 * extreme circumstances.
7151 if (nr_boost_reclaim && !nr_reclaimed)
7154 if (raise_priority || !nr_reclaimed)
7156 } while (sc.priority >= 1);
7158 if (!sc.nr_reclaimed)
7159 pgdat->kswapd_failures++;
7162 clear_reclaim_active(pgdat, highest_zoneidx);
7164 /* If reclaim was boosted, account for the reclaim done in this pass */
7166 unsigned long flags;
7168 for (i = 0; i <= highest_zoneidx; i++) {
7169 if (!zone_boosts[i])
7172 /* Increments are under the zone lock */
7173 zone = pgdat->node_zones + i;
7174 spin_lock_irqsave(&zone->lock, flags);
7175 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7176 spin_unlock_irqrestore(&zone->lock, flags);
7180 * As there is now likely space, wakeup kcompact to defragment
7183 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7186 snapshot_refaults(NULL, pgdat);
7187 __fs_reclaim_release(_THIS_IP_);
7188 psi_memstall_leave(&pflags);
7189 set_task_reclaim_state(current, NULL);
7192 * Return the order kswapd stopped reclaiming at as
7193 * prepare_kswapd_sleep() takes it into account. If another caller
7194 * entered the allocator slow path while kswapd was awake, order will
7195 * remain at the higher level.
7201 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7202 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7203 * not a valid index then either kswapd runs for first time or kswapd couldn't
7204 * sleep after previous reclaim attempt (node is still unbalanced). In that
7205 * case return the zone index of the previous kswapd reclaim cycle.
7207 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7208 enum zone_type prev_highest_zoneidx)
7210 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7212 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7215 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7216 unsigned int highest_zoneidx)
7221 if (freezing(current) || kthread_should_stop())
7224 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7227 * Try to sleep for a short interval. Note that kcompactd will only be
7228 * woken if it is possible to sleep for a short interval. This is
7229 * deliberate on the assumption that if reclaim cannot keep an
7230 * eligible zone balanced that it's also unlikely that compaction will
7233 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7235 * Compaction records what page blocks it recently failed to
7236 * isolate pages from and skips them in the future scanning.
7237 * When kswapd is going to sleep, it is reasonable to assume
7238 * that pages and compaction may succeed so reset the cache.
7240 reset_isolation_suitable(pgdat);
7243 * We have freed the memory, now we should compact it to make
7244 * allocation of the requested order possible.
7246 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7248 remaining = schedule_timeout(HZ/10);
7251 * If woken prematurely then reset kswapd_highest_zoneidx and
7252 * order. The values will either be from a wakeup request or
7253 * the previous request that slept prematurely.
7256 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7257 kswapd_highest_zoneidx(pgdat,
7260 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7261 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7264 finish_wait(&pgdat->kswapd_wait, &wait);
7265 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7269 * After a short sleep, check if it was a premature sleep. If not, then
7270 * go fully to sleep until explicitly woken up.
7273 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7274 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7277 * vmstat counters are not perfectly accurate and the estimated
7278 * value for counters such as NR_FREE_PAGES can deviate from the
7279 * true value by nr_online_cpus * threshold. To avoid the zone
7280 * watermarks being breached while under pressure, we reduce the
7281 * per-cpu vmstat threshold while kswapd is awake and restore
7282 * them before going back to sleep.
7284 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7286 if (!kthread_should_stop())
7289 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7292 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7294 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7296 finish_wait(&pgdat->kswapd_wait, &wait);
7300 * The background pageout daemon, started as a kernel thread
7301 * from the init process.
7303 * This basically trickles out pages so that we have _some_
7304 * free memory available even if there is no other activity
7305 * that frees anything up. This is needed for things like routing
7306 * etc, where we otherwise might have all activity going on in
7307 * asynchronous contexts that cannot page things out.
7309 * If there are applications that are active memory-allocators
7310 * (most normal use), this basically shouldn't matter.
7312 static int kswapd(void *p)
7314 unsigned int alloc_order, reclaim_order;
7315 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7316 pg_data_t *pgdat = (pg_data_t *)p;
7317 struct task_struct *tsk = current;
7318 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7320 if (!cpumask_empty(cpumask))
7321 set_cpus_allowed_ptr(tsk, cpumask);
7324 * Tell the memory management that we're a "memory allocator",
7325 * and that if we need more memory we should get access to it
7326 * regardless (see "__alloc_pages()"). "kswapd" should
7327 * never get caught in the normal page freeing logic.
7329 * (Kswapd normally doesn't need memory anyway, but sometimes
7330 * you need a small amount of memory in order to be able to
7331 * page out something else, and this flag essentially protects
7332 * us from recursively trying to free more memory as we're
7333 * trying to free the first piece of memory in the first place).
7335 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7338 WRITE_ONCE(pgdat->kswapd_order, 0);
7339 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7340 atomic_set(&pgdat->nr_writeback_throttled, 0);
7344 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7345 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7349 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7352 /* Read the new order and highest_zoneidx */
7353 alloc_order = READ_ONCE(pgdat->kswapd_order);
7354 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7356 WRITE_ONCE(pgdat->kswapd_order, 0);
7357 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7359 ret = try_to_freeze();
7360 if (kthread_should_stop())
7364 * We can speed up thawing tasks if we don't call balance_pgdat
7365 * after returning from the refrigerator
7371 * Reclaim begins at the requested order but if a high-order
7372 * reclaim fails then kswapd falls back to reclaiming for
7373 * order-0. If that happens, kswapd will consider sleeping
7374 * for the order it finished reclaiming at (reclaim_order)
7375 * but kcompactd is woken to compact for the original
7376 * request (alloc_order).
7378 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7380 reclaim_order = balance_pgdat(pgdat, alloc_order,
7382 if (reclaim_order < alloc_order)
7383 goto kswapd_try_sleep;
7386 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7392 * A zone is low on free memory or too fragmented for high-order memory. If
7393 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7394 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7395 * has failed or is not needed, still wake up kcompactd if only compaction is
7398 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7399 enum zone_type highest_zoneidx)
7402 enum zone_type curr_idx;
7404 if (!managed_zone(zone))
7407 if (!cpuset_zone_allowed(zone, gfp_flags))
7410 pgdat = zone->zone_pgdat;
7411 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7413 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7414 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7416 if (READ_ONCE(pgdat->kswapd_order) < order)
7417 WRITE_ONCE(pgdat->kswapd_order, order);
7419 if (!waitqueue_active(&pgdat->kswapd_wait))
7422 /* Hopeless node, leave it to direct reclaim if possible */
7423 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7424 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7425 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7427 * There may be plenty of free memory available, but it's too
7428 * fragmented for high-order allocations. Wake up kcompactd
7429 * and rely on compaction_suitable() to determine if it's
7430 * needed. If it fails, it will defer subsequent attempts to
7431 * ratelimit its work.
7433 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7434 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7438 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7440 wake_up_interruptible(&pgdat->kswapd_wait);
7443 #ifdef CONFIG_HIBERNATION
7445 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7448 * Rather than trying to age LRUs the aim is to preserve the overall
7449 * LRU order by reclaiming preferentially
7450 * inactive > active > active referenced > active mapped
7452 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7454 struct scan_control sc = {
7455 .nr_to_reclaim = nr_to_reclaim,
7456 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7457 .reclaim_idx = MAX_NR_ZONES - 1,
7458 .priority = DEF_PRIORITY,
7462 .hibernation_mode = 1,
7464 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7465 unsigned long nr_reclaimed;
7466 unsigned int noreclaim_flag;
7468 fs_reclaim_acquire(sc.gfp_mask);
7469 noreclaim_flag = memalloc_noreclaim_save();
7470 set_task_reclaim_state(current, &sc.reclaim_state);
7472 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7474 set_task_reclaim_state(current, NULL);
7475 memalloc_noreclaim_restore(noreclaim_flag);
7476 fs_reclaim_release(sc.gfp_mask);
7478 return nr_reclaimed;
7480 #endif /* CONFIG_HIBERNATION */
7483 * This kswapd start function will be called by init and node-hot-add.
7485 void kswapd_run(int nid)
7487 pg_data_t *pgdat = NODE_DATA(nid);
7489 pgdat_kswapd_lock(pgdat);
7490 if (!pgdat->kswapd) {
7491 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7492 if (IS_ERR(pgdat->kswapd)) {
7493 /* failure at boot is fatal */
7494 BUG_ON(system_state < SYSTEM_RUNNING);
7495 pr_err("Failed to start kswapd on node %d\n", nid);
7496 pgdat->kswapd = NULL;
7499 pgdat_kswapd_unlock(pgdat);
7503 * Called by memory hotplug when all memory in a node is offlined. Caller must
7504 * be holding mem_hotplug_begin/done().
7506 void kswapd_stop(int nid)
7508 pg_data_t *pgdat = NODE_DATA(nid);
7509 struct task_struct *kswapd;
7511 pgdat_kswapd_lock(pgdat);
7512 kswapd = pgdat->kswapd;
7514 kthread_stop(kswapd);
7515 pgdat->kswapd = NULL;
7517 pgdat_kswapd_unlock(pgdat);
7520 static int __init kswapd_init(void)
7525 for_each_node_state(nid, N_MEMORY)
7530 module_init(kswapd_init)
7536 * If non-zero call node_reclaim when the number of free pages falls below
7539 int node_reclaim_mode __read_mostly;
7542 * Priority for NODE_RECLAIM. This determines the fraction of pages
7543 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7546 #define NODE_RECLAIM_PRIORITY 4
7549 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7552 int sysctl_min_unmapped_ratio = 1;
7555 * If the number of slab pages in a zone grows beyond this percentage then
7556 * slab reclaim needs to occur.
7558 int sysctl_min_slab_ratio = 5;
7560 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7562 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7563 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7564 node_page_state(pgdat, NR_ACTIVE_FILE);
7567 * It's possible for there to be more file mapped pages than
7568 * accounted for by the pages on the file LRU lists because
7569 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7571 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7574 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7575 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7577 unsigned long nr_pagecache_reclaimable;
7578 unsigned long delta = 0;
7581 * If RECLAIM_UNMAP is set, then all file pages are considered
7582 * potentially reclaimable. Otherwise, we have to worry about
7583 * pages like swapcache and node_unmapped_file_pages() provides
7586 if (node_reclaim_mode & RECLAIM_UNMAP)
7587 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7589 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7591 /* If we can't clean pages, remove dirty pages from consideration */
7592 if (!(node_reclaim_mode & RECLAIM_WRITE))
7593 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7595 /* Watch for any possible underflows due to delta */
7596 if (unlikely(delta > nr_pagecache_reclaimable))
7597 delta = nr_pagecache_reclaimable;
7599 return nr_pagecache_reclaimable - delta;
7603 * Try to free up some pages from this node through reclaim.
7605 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7607 /* Minimum pages needed in order to stay on node */
7608 const unsigned long nr_pages = 1 << order;
7609 struct task_struct *p = current;
7610 unsigned int noreclaim_flag;
7611 struct scan_control sc = {
7612 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7613 .gfp_mask = current_gfp_context(gfp_mask),
7615 .priority = NODE_RECLAIM_PRIORITY,
7616 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7617 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7619 .reclaim_idx = gfp_zone(gfp_mask),
7621 unsigned long pflags;
7623 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7627 psi_memstall_enter(&pflags);
7628 fs_reclaim_acquire(sc.gfp_mask);
7630 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7632 noreclaim_flag = memalloc_noreclaim_save();
7633 set_task_reclaim_state(p, &sc.reclaim_state);
7635 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7636 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7638 * Free memory by calling shrink node with increasing
7639 * priorities until we have enough memory freed.
7642 shrink_node(pgdat, &sc);
7643 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7646 set_task_reclaim_state(p, NULL);
7647 memalloc_noreclaim_restore(noreclaim_flag);
7648 fs_reclaim_release(sc.gfp_mask);
7649 psi_memstall_leave(&pflags);
7651 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7653 return sc.nr_reclaimed >= nr_pages;
7656 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7661 * Node reclaim reclaims unmapped file backed pages and
7662 * slab pages if we are over the defined limits.
7664 * A small portion of unmapped file backed pages is needed for
7665 * file I/O otherwise pages read by file I/O will be immediately
7666 * thrown out if the node is overallocated. So we do not reclaim
7667 * if less than a specified percentage of the node is used by
7668 * unmapped file backed pages.
7670 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7671 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7672 pgdat->min_slab_pages)
7673 return NODE_RECLAIM_FULL;
7676 * Do not scan if the allocation should not be delayed.
7678 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7679 return NODE_RECLAIM_NOSCAN;
7682 * Only run node reclaim on the local node or on nodes that do not
7683 * have associated processors. This will favor the local processor
7684 * over remote processors and spread off node memory allocations
7685 * as wide as possible.
7687 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7688 return NODE_RECLAIM_NOSCAN;
7690 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7691 return NODE_RECLAIM_NOSCAN;
7693 ret = __node_reclaim(pgdat, gfp_mask, order);
7694 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7697 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7703 void check_move_unevictable_pages(struct pagevec *pvec)
7705 struct folio_batch fbatch;
7708 folio_batch_init(&fbatch);
7709 for (i = 0; i < pvec->nr; i++) {
7710 struct page *page = pvec->pages[i];
7712 if (PageTransTail(page))
7714 folio_batch_add(&fbatch, page_folio(page));
7716 check_move_unevictable_folios(&fbatch);
7718 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
7721 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7723 * @fbatch: Batch of lru folios to check.
7725 * Checks folios for evictability, if an evictable folio is in the unevictable
7726 * lru list, moves it to the appropriate evictable lru list. This function
7727 * should be only used for lru folios.
7729 void check_move_unevictable_folios(struct folio_batch *fbatch)
7731 struct lruvec *lruvec = NULL;
7736 for (i = 0; i < fbatch->nr; i++) {
7737 struct folio *folio = fbatch->folios[i];
7738 int nr_pages = folio_nr_pages(folio);
7740 pgscanned += nr_pages;
7742 /* block memcg migration while the folio moves between lrus */
7743 if (!folio_test_clear_lru(folio))
7746 lruvec = folio_lruvec_relock_irq(folio, lruvec);
7747 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7748 lruvec_del_folio(lruvec, folio);
7749 folio_clear_unevictable(folio);
7750 lruvec_add_folio(lruvec, folio);
7751 pgrescued += nr_pages;
7753 folio_set_lru(folio);
7757 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7758 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7759 unlock_page_lruvec_irq(lruvec);
7760 } else if (pgscanned) {
7761 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7764 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);