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 struct dentry *debugfs_entry;
745 if (!(shrinker->flags & SHRINKER_REGISTERED))
748 down_write(&shrinker_rwsem);
749 list_del(&shrinker->list);
750 shrinker->flags &= ~SHRINKER_REGISTERED;
751 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
752 unregister_memcg_shrinker(shrinker);
753 debugfs_entry = shrinker_debugfs_remove(shrinker);
754 up_write(&shrinker_rwsem);
756 debugfs_remove_recursive(debugfs_entry);
758 kfree(shrinker->nr_deferred);
759 shrinker->nr_deferred = NULL;
761 EXPORT_SYMBOL(unregister_shrinker);
764 * synchronize_shrinkers - Wait for all running shrinkers to complete.
766 * This is equivalent to calling unregister_shrink() and register_shrinker(),
767 * but atomically and with less overhead. This is useful to guarantee that all
768 * shrinker invocations have seen an update, before freeing memory, similar to
771 void synchronize_shrinkers(void)
773 down_write(&shrinker_rwsem);
774 up_write(&shrinker_rwsem);
776 EXPORT_SYMBOL(synchronize_shrinkers);
778 #define SHRINK_BATCH 128
780 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
781 struct shrinker *shrinker, int priority)
783 unsigned long freed = 0;
784 unsigned long long delta;
789 long batch_size = shrinker->batch ? shrinker->batch
791 long scanned = 0, next_deferred;
793 freeable = shrinker->count_objects(shrinker, shrinkctl);
794 if (freeable == 0 || freeable == SHRINK_EMPTY)
798 * copy the current shrinker scan count into a local variable
799 * and zero it so that other concurrent shrinker invocations
800 * don't also do this scanning work.
802 nr = xchg_nr_deferred(shrinker, shrinkctl);
804 if (shrinker->seeks) {
805 delta = freeable >> priority;
807 do_div(delta, shrinker->seeks);
810 * These objects don't require any IO to create. Trim
811 * them aggressively under memory pressure to keep
812 * them from causing refetches in the IO caches.
814 delta = freeable / 2;
817 total_scan = nr >> priority;
819 total_scan = min(total_scan, (2 * freeable));
821 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
822 freeable, delta, total_scan, priority);
825 * Normally, we should not scan less than batch_size objects in one
826 * pass to avoid too frequent shrinker calls, but if the slab has less
827 * than batch_size objects in total and we are really tight on memory,
828 * we will try to reclaim all available objects, otherwise we can end
829 * up failing allocations although there are plenty of reclaimable
830 * objects spread over several slabs with usage less than the
833 * We detect the "tight on memory" situations by looking at the total
834 * number of objects we want to scan (total_scan). If it is greater
835 * than the total number of objects on slab (freeable), we must be
836 * scanning at high prio and therefore should try to reclaim as much as
839 while (total_scan >= batch_size ||
840 total_scan >= freeable) {
842 unsigned long nr_to_scan = min(batch_size, total_scan);
844 shrinkctl->nr_to_scan = nr_to_scan;
845 shrinkctl->nr_scanned = nr_to_scan;
846 ret = shrinker->scan_objects(shrinker, shrinkctl);
847 if (ret == SHRINK_STOP)
851 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
852 total_scan -= shrinkctl->nr_scanned;
853 scanned += shrinkctl->nr_scanned;
859 * The deferred work is increased by any new work (delta) that wasn't
860 * done, decreased by old deferred work that was done now.
862 * And it is capped to two times of the freeable items.
864 next_deferred = max_t(long, (nr + delta - scanned), 0);
865 next_deferred = min(next_deferred, (2 * freeable));
868 * move the unused scan count back into the shrinker in a
869 * manner that handles concurrent updates.
871 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
873 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
878 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
879 struct mem_cgroup *memcg, int priority)
881 struct shrinker_info *info;
882 unsigned long ret, freed = 0;
885 if (!mem_cgroup_online(memcg))
888 if (!down_read_trylock(&shrinker_rwsem))
891 info = shrinker_info_protected(memcg, nid);
895 for_each_set_bit(i, info->map, shrinker_nr_max) {
896 struct shrink_control sc = {
897 .gfp_mask = gfp_mask,
901 struct shrinker *shrinker;
903 shrinker = idr_find(&shrinker_idr, i);
904 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
906 clear_bit(i, info->map);
910 /* Call non-slab shrinkers even though kmem is disabled */
911 if (!memcg_kmem_enabled() &&
912 !(shrinker->flags & SHRINKER_NONSLAB))
915 ret = do_shrink_slab(&sc, shrinker, priority);
916 if (ret == SHRINK_EMPTY) {
917 clear_bit(i, info->map);
919 * After the shrinker reported that it had no objects to
920 * free, but before we cleared the corresponding bit in
921 * the memcg shrinker map, a new object might have been
922 * added. To make sure, we have the bit set in this
923 * case, we invoke the shrinker one more time and reset
924 * the bit if it reports that it is not empty anymore.
925 * The memory barrier here pairs with the barrier in
926 * set_shrinker_bit():
928 * list_lru_add() shrink_slab_memcg()
929 * list_add_tail() clear_bit()
931 * set_bit() do_shrink_slab()
933 smp_mb__after_atomic();
934 ret = do_shrink_slab(&sc, shrinker, priority);
935 if (ret == SHRINK_EMPTY)
938 set_shrinker_bit(memcg, nid, i);
942 if (rwsem_is_contended(&shrinker_rwsem)) {
948 up_read(&shrinker_rwsem);
951 #else /* CONFIG_MEMCG */
952 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
953 struct mem_cgroup *memcg, int priority)
957 #endif /* CONFIG_MEMCG */
960 * shrink_slab - shrink slab caches
961 * @gfp_mask: allocation context
962 * @nid: node whose slab caches to target
963 * @memcg: memory cgroup whose slab caches to target
964 * @priority: the reclaim priority
966 * Call the shrink functions to age shrinkable caches.
968 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
969 * unaware shrinkers will receive a node id of 0 instead.
971 * @memcg specifies the memory cgroup to target. Unaware shrinkers
972 * are called only if it is the root cgroup.
974 * @priority is sc->priority, we take the number of objects and >> by priority
975 * in order to get the scan target.
977 * Returns the number of reclaimed slab objects.
979 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
980 struct mem_cgroup *memcg,
983 unsigned long ret, freed = 0;
984 struct shrinker *shrinker;
987 * The root memcg might be allocated even though memcg is disabled
988 * via "cgroup_disable=memory" boot parameter. This could make
989 * mem_cgroup_is_root() return false, then just run memcg slab
990 * shrink, but skip global shrink. This may result in premature
993 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
994 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
996 if (!down_read_trylock(&shrinker_rwsem))
999 list_for_each_entry(shrinker, &shrinker_list, list) {
1000 struct shrink_control sc = {
1001 .gfp_mask = gfp_mask,
1006 ret = do_shrink_slab(&sc, shrinker, priority);
1007 if (ret == SHRINK_EMPTY)
1011 * Bail out if someone want to register a new shrinker to
1012 * prevent the registration from being stalled for long periods
1013 * by parallel ongoing shrinking.
1015 if (rwsem_is_contended(&shrinker_rwsem)) {
1016 freed = freed ? : 1;
1021 up_read(&shrinker_rwsem);
1027 static void drop_slab_node(int nid)
1029 unsigned long freed;
1033 struct mem_cgroup *memcg = NULL;
1035 if (fatal_signal_pending(current))
1039 memcg = mem_cgroup_iter(NULL, NULL, NULL);
1041 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1042 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1043 } while ((freed >> shift++) > 1);
1046 void drop_slab(void)
1050 for_each_online_node(nid)
1051 drop_slab_node(nid);
1054 static inline int is_page_cache_freeable(struct folio *folio)
1057 * A freeable page cache folio is referenced only by the caller
1058 * that isolated the folio, the page cache and optional filesystem
1059 * private data at folio->private.
1061 return folio_ref_count(folio) - folio_test_private(folio) ==
1062 1 + folio_nr_pages(folio);
1066 * We detected a synchronous write error writing a folio out. Probably
1067 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1068 * fsync(), msync() or close().
1070 * The tricky part is that after writepage we cannot touch the mapping: nothing
1071 * prevents it from being freed up. But we have a ref on the folio and once
1072 * that folio is locked, the mapping is pinned.
1074 * We're allowed to run sleeping folio_lock() here because we know the caller has
1077 static void handle_write_error(struct address_space *mapping,
1078 struct folio *folio, int error)
1081 if (folio_mapping(folio) == mapping)
1082 mapping_set_error(mapping, error);
1083 folio_unlock(folio);
1086 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1088 int reclaimable = 0, write_pending = 0;
1092 * If kswapd is disabled, reschedule if necessary but do not
1093 * throttle as the system is likely near OOM.
1095 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1099 * If there are a lot of dirty/writeback folios then do not
1100 * throttle as throttling will occur when the folios cycle
1101 * towards the end of the LRU if still under writeback.
1103 for (i = 0; i < MAX_NR_ZONES; i++) {
1104 struct zone *zone = pgdat->node_zones + i;
1106 if (!managed_zone(zone))
1109 reclaimable += zone_reclaimable_pages(zone);
1110 write_pending += zone_page_state_snapshot(zone,
1111 NR_ZONE_WRITE_PENDING);
1113 if (2 * write_pending <= reclaimable)
1119 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1121 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1126 * Do not throttle IO workers, kthreads other than kswapd or
1127 * workqueues. They may be required for reclaim to make
1128 * forward progress (e.g. journalling workqueues or kthreads).
1130 if (!current_is_kswapd() &&
1131 current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1137 * These figures are pulled out of thin air.
1138 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1139 * parallel reclaimers which is a short-lived event so the timeout is
1140 * short. Failing to make progress or waiting on writeback are
1141 * potentially long-lived events so use a longer timeout. This is shaky
1142 * logic as a failure to make progress could be due to anything from
1143 * writeback to a slow device to excessive referenced folios at the tail
1144 * of the inactive LRU.
1147 case VMSCAN_THROTTLE_WRITEBACK:
1150 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1151 WRITE_ONCE(pgdat->nr_reclaim_start,
1152 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1156 case VMSCAN_THROTTLE_CONGESTED:
1158 case VMSCAN_THROTTLE_NOPROGRESS:
1159 if (skip_throttle_noprogress(pgdat)) {
1167 case VMSCAN_THROTTLE_ISOLATED:
1176 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1177 ret = schedule_timeout(timeout);
1178 finish_wait(wqh, &wait);
1180 if (reason == VMSCAN_THROTTLE_WRITEBACK)
1181 atomic_dec(&pgdat->nr_writeback_throttled);
1183 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1184 jiffies_to_usecs(timeout - ret),
1189 * Account for folios written if tasks are throttled waiting on dirty
1190 * folios to clean. If enough folios have been cleaned since throttling
1191 * started then wakeup the throttled tasks.
1193 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1196 unsigned long nr_written;
1198 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1201 * This is an inaccurate read as the per-cpu deltas may not
1202 * be synchronised. However, given that the system is
1203 * writeback throttled, it is not worth taking the penalty
1204 * of getting an accurate count. At worst, the throttle
1205 * timeout guarantees forward progress.
1207 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1208 READ_ONCE(pgdat->nr_reclaim_start);
1210 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1211 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1214 /* possible outcome of pageout() */
1216 /* failed to write folio out, folio is locked */
1218 /* move folio to the active list, folio is locked */
1220 /* folio has been sent to the disk successfully, folio is unlocked */
1222 /* folio is clean and locked */
1227 * pageout is called by shrink_folio_list() for each dirty folio.
1228 * Calls ->writepage().
1230 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1231 struct swap_iocb **plug)
1234 * If the folio is dirty, only perform writeback if that write
1235 * will be non-blocking. To prevent this allocation from being
1236 * stalled by pagecache activity. But note that there may be
1237 * stalls if we need to run get_block(). We could test
1238 * PagePrivate for that.
1240 * If this process is currently in __generic_file_write_iter() against
1241 * this folio's queue, we can perform writeback even if that
1244 * If the folio is swapcache, write it back even if that would
1245 * block, for some throttling. This happens by accident, because
1246 * swap_backing_dev_info is bust: it doesn't reflect the
1247 * congestion state of the swapdevs. Easy to fix, if needed.
1249 if (!is_page_cache_freeable(folio))
1253 * Some data journaling orphaned folios can have
1254 * folio->mapping == NULL while being dirty with clean buffers.
1256 if (folio_test_private(folio)) {
1257 if (try_to_free_buffers(folio)) {
1258 folio_clear_dirty(folio);
1259 pr_info("%s: orphaned folio\n", __func__);
1265 if (mapping->a_ops->writepage == NULL)
1266 return PAGE_ACTIVATE;
1268 if (folio_clear_dirty_for_io(folio)) {
1270 struct writeback_control wbc = {
1271 .sync_mode = WB_SYNC_NONE,
1272 .nr_to_write = SWAP_CLUSTER_MAX,
1274 .range_end = LLONG_MAX,
1279 folio_set_reclaim(folio);
1280 res = mapping->a_ops->writepage(&folio->page, &wbc);
1282 handle_write_error(mapping, folio, res);
1283 if (res == AOP_WRITEPAGE_ACTIVATE) {
1284 folio_clear_reclaim(folio);
1285 return PAGE_ACTIVATE;
1288 if (!folio_test_writeback(folio)) {
1289 /* synchronous write or broken a_ops? */
1290 folio_clear_reclaim(folio);
1292 trace_mm_vmscan_write_folio(folio);
1293 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1294 return PAGE_SUCCESS;
1301 * Same as remove_mapping, but if the folio is removed from the mapping, it
1302 * gets returned with a refcount of 0.
1304 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1305 bool reclaimed, struct mem_cgroup *target_memcg)
1308 void *shadow = NULL;
1310 BUG_ON(!folio_test_locked(folio));
1311 BUG_ON(mapping != folio_mapping(folio));
1313 if (!folio_test_swapcache(folio))
1314 spin_lock(&mapping->host->i_lock);
1315 xa_lock_irq(&mapping->i_pages);
1317 * The non racy check for a busy folio.
1319 * Must be careful with the order of the tests. When someone has
1320 * a ref to the folio, it may be possible that they dirty it then
1321 * drop the reference. So if the dirty flag is tested before the
1322 * refcount here, then the following race may occur:
1324 * get_user_pages(&page);
1325 * [user mapping goes away]
1327 * !folio_test_dirty(folio) [good]
1328 * folio_set_dirty(folio);
1330 * !refcount(folio) [good, discard it]
1332 * [oops, our write_to data is lost]
1334 * Reversing the order of the tests ensures such a situation cannot
1335 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
1336 * load is not satisfied before that of folio->_refcount.
1338 * Note that if the dirty flag is always set via folio_mark_dirty,
1339 * and thus under the i_pages lock, then this ordering is not required.
1341 refcount = 1 + folio_nr_pages(folio);
1342 if (!folio_ref_freeze(folio, refcount))
1344 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
1345 if (unlikely(folio_test_dirty(folio))) {
1346 folio_ref_unfreeze(folio, refcount);
1350 if (folio_test_swapcache(folio)) {
1351 swp_entry_t swap = folio_swap_entry(folio);
1353 /* get a shadow entry before mem_cgroup_swapout() clears folio_memcg() */
1354 if (reclaimed && !mapping_exiting(mapping))
1355 shadow = workingset_eviction(folio, target_memcg);
1356 mem_cgroup_swapout(folio, swap);
1357 __delete_from_swap_cache(folio, swap, shadow);
1358 xa_unlock_irq(&mapping->i_pages);
1359 put_swap_folio(folio, swap);
1361 void (*free_folio)(struct folio *);
1363 free_folio = mapping->a_ops->free_folio;
1365 * Remember a shadow entry for reclaimed file cache in
1366 * order to detect refaults, thus thrashing, later on.
1368 * But don't store shadows in an address space that is
1369 * already exiting. This is not just an optimization,
1370 * inode reclaim needs to empty out the radix tree or
1371 * the nodes are lost. Don't plant shadows behind its
1374 * We also don't store shadows for DAX mappings because the
1375 * only page cache folios found in these are zero pages
1376 * covering holes, and because we don't want to mix DAX
1377 * exceptional entries and shadow exceptional entries in the
1378 * same address_space.
1380 if (reclaimed && folio_is_file_lru(folio) &&
1381 !mapping_exiting(mapping) && !dax_mapping(mapping))
1382 shadow = workingset_eviction(folio, target_memcg);
1383 __filemap_remove_folio(folio, shadow);
1384 xa_unlock_irq(&mapping->i_pages);
1385 if (mapping_shrinkable(mapping))
1386 inode_add_lru(mapping->host);
1387 spin_unlock(&mapping->host->i_lock);
1396 xa_unlock_irq(&mapping->i_pages);
1397 if (!folio_test_swapcache(folio))
1398 spin_unlock(&mapping->host->i_lock);
1403 * remove_mapping() - Attempt to remove a folio from its mapping.
1404 * @mapping: The address space.
1405 * @folio: The folio to remove.
1407 * If the folio is dirty, under writeback or if someone else has a ref
1408 * on it, removal will fail.
1409 * Return: The number of pages removed from the mapping. 0 if the folio
1410 * could not be removed.
1411 * Context: The caller should have a single refcount on the folio and
1414 long remove_mapping(struct address_space *mapping, struct folio *folio)
1416 if (__remove_mapping(mapping, folio, false, NULL)) {
1418 * Unfreezing the refcount with 1 effectively
1419 * drops the pagecache ref for us without requiring another
1422 folio_ref_unfreeze(folio, 1);
1423 return folio_nr_pages(folio);
1429 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1430 * @folio: Folio to be returned to an LRU list.
1432 * Add previously isolated @folio to appropriate LRU list.
1433 * The folio may still be unevictable for other reasons.
1435 * Context: lru_lock must not be held, interrupts must be enabled.
1437 void folio_putback_lru(struct folio *folio)
1439 folio_add_lru(folio);
1440 folio_put(folio); /* drop ref from isolate */
1443 enum folio_references {
1445 FOLIOREF_RECLAIM_CLEAN,
1450 static enum folio_references folio_check_references(struct folio *folio,
1451 struct scan_control *sc)
1453 int referenced_ptes, referenced_folio;
1454 unsigned long vm_flags;
1456 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1458 referenced_folio = folio_test_clear_referenced(folio);
1461 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1462 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1464 if (vm_flags & VM_LOCKED)
1465 return FOLIOREF_ACTIVATE;
1467 /* rmap lock contention: rotate */
1468 if (referenced_ptes == -1)
1469 return FOLIOREF_KEEP;
1471 if (referenced_ptes) {
1473 * All mapped folios start out with page table
1474 * references from the instantiating fault, so we need
1475 * to look twice if a mapped file/anon folio is used more
1478 * Mark it and spare it for another trip around the
1479 * inactive list. Another page table reference will
1480 * lead to its activation.
1482 * Note: the mark is set for activated folios as well
1483 * so that recently deactivated but used folios are
1484 * quickly recovered.
1486 folio_set_referenced(folio);
1488 if (referenced_folio || referenced_ptes > 1)
1489 return FOLIOREF_ACTIVATE;
1492 * Activate file-backed executable folios after first usage.
1494 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1495 return FOLIOREF_ACTIVATE;
1497 return FOLIOREF_KEEP;
1500 /* Reclaim if clean, defer dirty folios to writeback */
1501 if (referenced_folio && folio_is_file_lru(folio))
1502 return FOLIOREF_RECLAIM_CLEAN;
1504 return FOLIOREF_RECLAIM;
1507 /* Check if a folio is dirty or under writeback */
1508 static void folio_check_dirty_writeback(struct folio *folio,
1509 bool *dirty, bool *writeback)
1511 struct address_space *mapping;
1514 * Anonymous folios are not handled by flushers and must be written
1515 * from reclaim context. Do not stall reclaim based on them.
1516 * MADV_FREE anonymous folios are put into inactive file list too.
1517 * They could be mistakenly treated as file lru. So further anon
1520 if (!folio_is_file_lru(folio) ||
1521 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1527 /* By default assume that the folio flags are accurate */
1528 *dirty = folio_test_dirty(folio);
1529 *writeback = folio_test_writeback(folio);
1531 /* Verify dirty/writeback state if the filesystem supports it */
1532 if (!folio_test_private(folio))
1535 mapping = folio_mapping(folio);
1536 if (mapping && mapping->a_ops->is_dirty_writeback)
1537 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1540 static struct page *alloc_demote_page(struct page *page, unsigned long private)
1542 struct page *target_page;
1543 nodemask_t *allowed_mask;
1544 struct migration_target_control *mtc;
1546 mtc = (struct migration_target_control *)private;
1548 allowed_mask = mtc->nmask;
1550 * make sure we allocate from the target node first also trying to
1551 * demote or reclaim pages from the target node via kswapd if we are
1552 * low on free memory on target node. If we don't do this and if
1553 * we have free memory on the slower(lower) memtier, we would start
1554 * allocating pages from slower(lower) memory tiers without even forcing
1555 * a demotion of cold pages from the target memtier. This can result
1556 * in the kernel placing hot pages in slower(lower) memory tiers.
1559 mtc->gfp_mask |= __GFP_THISNODE;
1560 target_page = alloc_migration_target(page, (unsigned long)mtc);
1564 mtc->gfp_mask &= ~__GFP_THISNODE;
1565 mtc->nmask = allowed_mask;
1567 return alloc_migration_target(page, (unsigned long)mtc);
1571 * Take folios on @demote_folios and attempt to demote them to another node.
1572 * Folios which are not demoted are left on @demote_folios.
1574 static unsigned int demote_folio_list(struct list_head *demote_folios,
1575 struct pglist_data *pgdat)
1577 int target_nid = next_demotion_node(pgdat->node_id);
1578 unsigned int nr_succeeded;
1579 nodemask_t allowed_mask;
1581 struct migration_target_control mtc = {
1583 * Allocate from 'node', or fail quickly and quietly.
1584 * When this happens, 'page' will likely just be discarded
1585 * instead of migrated.
1587 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1588 __GFP_NOMEMALLOC | GFP_NOWAIT,
1590 .nmask = &allowed_mask
1593 if (list_empty(demote_folios))
1596 if (target_nid == NUMA_NO_NODE)
1599 node_get_allowed_targets(pgdat, &allowed_mask);
1601 /* Demotion ignores all cpuset and mempolicy settings */
1602 migrate_pages(demote_folios, alloc_demote_page, NULL,
1603 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1606 if (current_is_kswapd())
1607 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1609 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1611 return nr_succeeded;
1614 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1616 if (gfp_mask & __GFP_FS)
1618 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1621 * We can "enter_fs" for swap-cache with only __GFP_IO
1622 * providing this isn't SWP_FS_OPS.
1623 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1624 * but that will never affect SWP_FS_OPS, so the data_race
1627 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1631 * shrink_folio_list() returns the number of reclaimed pages
1633 static unsigned int shrink_folio_list(struct list_head *folio_list,
1634 struct pglist_data *pgdat, struct scan_control *sc,
1635 struct reclaim_stat *stat, bool ignore_references)
1637 LIST_HEAD(ret_folios);
1638 LIST_HEAD(free_folios);
1639 LIST_HEAD(demote_folios);
1640 unsigned int nr_reclaimed = 0;
1641 unsigned int pgactivate = 0;
1642 bool do_demote_pass;
1643 struct swap_iocb *plug = NULL;
1645 memset(stat, 0, sizeof(*stat));
1647 do_demote_pass = can_demote(pgdat->node_id, sc);
1650 while (!list_empty(folio_list)) {
1651 struct address_space *mapping;
1652 struct folio *folio;
1653 enum folio_references references = FOLIOREF_RECLAIM;
1654 bool dirty, writeback;
1655 unsigned int nr_pages;
1659 folio = lru_to_folio(folio_list);
1660 list_del(&folio->lru);
1662 if (!folio_trylock(folio))
1665 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1667 nr_pages = folio_nr_pages(folio);
1669 /* Account the number of base pages */
1670 sc->nr_scanned += nr_pages;
1672 if (unlikely(!folio_evictable(folio)))
1673 goto activate_locked;
1675 if (!sc->may_unmap && folio_mapped(folio))
1678 /* folio_update_gen() tried to promote this page? */
1679 if (lru_gen_enabled() && !ignore_references &&
1680 folio_mapped(folio) && folio_test_referenced(folio))
1684 * The number of dirty pages determines if a node is marked
1685 * reclaim_congested. kswapd will stall and start writing
1686 * folios if the tail of the LRU is all dirty unqueued folios.
1688 folio_check_dirty_writeback(folio, &dirty, &writeback);
1689 if (dirty || writeback)
1690 stat->nr_dirty += nr_pages;
1692 if (dirty && !writeback)
1693 stat->nr_unqueued_dirty += nr_pages;
1696 * Treat this folio as congested if folios are cycling
1697 * through the LRU so quickly that the folios marked
1698 * for immediate reclaim are making it to the end of
1699 * the LRU a second time.
1701 if (writeback && folio_test_reclaim(folio))
1702 stat->nr_congested += nr_pages;
1705 * If a folio at the tail of the LRU is under writeback, there
1706 * are three cases to consider.
1708 * 1) If reclaim is encountering an excessive number
1709 * of folios under writeback and this folio has both
1710 * the writeback and reclaim flags set, then it
1711 * indicates that folios are being queued for I/O but
1712 * are being recycled through the LRU before the I/O
1713 * can complete. Waiting on the folio itself risks an
1714 * indefinite stall if it is impossible to writeback
1715 * the folio due to I/O error or disconnected storage
1716 * so instead note that the LRU is being scanned too
1717 * quickly and the caller can stall after the folio
1718 * list has been processed.
1720 * 2) Global or new memcg reclaim encounters a folio that is
1721 * not marked for immediate reclaim, or the caller does not
1722 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1723 * not to fs). In this case mark the folio for immediate
1724 * reclaim and continue scanning.
1726 * Require may_enter_fs() because we would wait on fs, which
1727 * may not have submitted I/O yet. And the loop driver might
1728 * enter reclaim, and deadlock if it waits on a folio for
1729 * which it is needed to do the write (loop masks off
1730 * __GFP_IO|__GFP_FS for this reason); but more thought
1731 * would probably show more reasons.
1733 * 3) Legacy memcg encounters a folio that already has the
1734 * reclaim flag set. memcg does not have any dirty folio
1735 * throttling so we could easily OOM just because too many
1736 * folios are in writeback and there is nothing else to
1737 * reclaim. Wait for the writeback to complete.
1739 * In cases 1) and 2) we activate the folios to get them out of
1740 * the way while we continue scanning for clean folios on the
1741 * inactive list and refilling from the active list. The
1742 * observation here is that waiting for disk writes is more
1743 * expensive than potentially causing reloads down the line.
1744 * Since they're marked for immediate reclaim, they won't put
1745 * memory pressure on the cache working set any longer than it
1746 * takes to write them to disk.
1748 if (folio_test_writeback(folio)) {
1750 if (current_is_kswapd() &&
1751 folio_test_reclaim(folio) &&
1752 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1753 stat->nr_immediate += nr_pages;
1754 goto activate_locked;
1757 } else if (writeback_throttling_sane(sc) ||
1758 !folio_test_reclaim(folio) ||
1759 !may_enter_fs(folio, sc->gfp_mask)) {
1761 * This is slightly racy -
1762 * folio_end_writeback() might have
1763 * just cleared the reclaim flag, then
1764 * setting the reclaim flag here ends up
1765 * interpreted as the readahead flag - but
1766 * that does not matter enough to care.
1767 * What we do want is for this folio to
1768 * have the reclaim flag set next time
1769 * memcg reclaim reaches the tests above,
1770 * so it will then wait for writeback to
1771 * avoid OOM; and it's also appropriate
1772 * in global reclaim.
1774 folio_set_reclaim(folio);
1775 stat->nr_writeback += nr_pages;
1776 goto activate_locked;
1780 folio_unlock(folio);
1781 folio_wait_writeback(folio);
1782 /* then go back and try same folio again */
1783 list_add_tail(&folio->lru, folio_list);
1788 if (!ignore_references)
1789 references = folio_check_references(folio, sc);
1791 switch (references) {
1792 case FOLIOREF_ACTIVATE:
1793 goto activate_locked;
1795 stat->nr_ref_keep += nr_pages;
1797 case FOLIOREF_RECLAIM:
1798 case FOLIOREF_RECLAIM_CLEAN:
1799 ; /* try to reclaim the folio below */
1803 * Before reclaiming the folio, try to relocate
1804 * its contents to another node.
1806 if (do_demote_pass &&
1807 (thp_migration_supported() || !folio_test_large(folio))) {
1808 list_add(&folio->lru, &demote_folios);
1809 folio_unlock(folio);
1814 * Anonymous process memory has backing store?
1815 * Try to allocate it some swap space here.
1816 * Lazyfree folio could be freed directly
1818 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1819 if (!folio_test_swapcache(folio)) {
1820 if (!(sc->gfp_mask & __GFP_IO))
1822 if (folio_maybe_dma_pinned(folio))
1824 if (folio_test_large(folio)) {
1825 /* cannot split folio, skip it */
1826 if (!can_split_folio(folio, NULL))
1827 goto activate_locked;
1829 * Split folios without a PMD map right
1830 * away. Chances are some or all of the
1831 * tail pages can be freed without IO.
1833 if (!folio_entire_mapcount(folio) &&
1834 split_folio_to_list(folio,
1836 goto activate_locked;
1838 if (!add_to_swap(folio)) {
1839 if (!folio_test_large(folio))
1840 goto activate_locked_split;
1841 /* Fallback to swap normal pages */
1842 if (split_folio_to_list(folio,
1844 goto activate_locked;
1845 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1846 count_vm_event(THP_SWPOUT_FALLBACK);
1848 if (!add_to_swap(folio))
1849 goto activate_locked_split;
1852 } else if (folio_test_swapbacked(folio) &&
1853 folio_test_large(folio)) {
1854 /* Split shmem folio */
1855 if (split_folio_to_list(folio, folio_list))
1860 * If the folio was split above, the tail pages will make
1861 * their own pass through this function and be accounted
1864 if ((nr_pages > 1) && !folio_test_large(folio)) {
1865 sc->nr_scanned -= (nr_pages - 1);
1870 * The folio is mapped into the page tables of one or more
1871 * processes. Try to unmap it here.
1873 if (folio_mapped(folio)) {
1874 enum ttu_flags flags = TTU_BATCH_FLUSH;
1875 bool was_swapbacked = folio_test_swapbacked(folio);
1877 if (folio_test_pmd_mappable(folio))
1878 flags |= TTU_SPLIT_HUGE_PMD;
1880 try_to_unmap(folio, flags);
1881 if (folio_mapped(folio)) {
1882 stat->nr_unmap_fail += nr_pages;
1883 if (!was_swapbacked &&
1884 folio_test_swapbacked(folio))
1885 stat->nr_lazyfree_fail += nr_pages;
1886 goto activate_locked;
1891 * Folio is unmapped now so it cannot be newly pinned anymore.
1892 * No point in trying to reclaim folio if it is pinned.
1893 * Furthermore we don't want to reclaim underlying fs metadata
1894 * if the folio is pinned and thus potentially modified by the
1895 * pinning process as that may upset the filesystem.
1897 if (folio_maybe_dma_pinned(folio))
1898 goto activate_locked;
1900 mapping = folio_mapping(folio);
1901 if (folio_test_dirty(folio)) {
1903 * Only kswapd can writeback filesystem folios
1904 * to avoid risk of stack overflow. But avoid
1905 * injecting inefficient single-folio I/O into
1906 * flusher writeback as much as possible: only
1907 * write folios when we've encountered many
1908 * dirty folios, and when we've already scanned
1909 * the rest of the LRU for clean folios and see
1910 * the same dirty folios again (with the reclaim
1913 if (folio_is_file_lru(folio) &&
1914 (!current_is_kswapd() ||
1915 !folio_test_reclaim(folio) ||
1916 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1918 * Immediately reclaim when written back.
1919 * Similar in principle to deactivate_page()
1920 * except we already have the folio isolated
1921 * and know it's dirty
1923 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1925 folio_set_reclaim(folio);
1927 goto activate_locked;
1930 if (references == FOLIOREF_RECLAIM_CLEAN)
1932 if (!may_enter_fs(folio, sc->gfp_mask))
1934 if (!sc->may_writepage)
1938 * Folio is dirty. Flush the TLB if a writable entry
1939 * potentially exists to avoid CPU writes after I/O
1940 * starts and then write it out here.
1942 try_to_unmap_flush_dirty();
1943 switch (pageout(folio, mapping, &plug)) {
1947 goto activate_locked;
1949 stat->nr_pageout += nr_pages;
1951 if (folio_test_writeback(folio))
1953 if (folio_test_dirty(folio))
1957 * A synchronous write - probably a ramdisk. Go
1958 * ahead and try to reclaim the folio.
1960 if (!folio_trylock(folio))
1962 if (folio_test_dirty(folio) ||
1963 folio_test_writeback(folio))
1965 mapping = folio_mapping(folio);
1968 ; /* try to free the folio below */
1973 * If the folio has buffers, try to free the buffer
1974 * mappings associated with this folio. If we succeed
1975 * we try to free the folio as well.
1977 * We do this even if the folio is dirty.
1978 * filemap_release_folio() does not perform I/O, but it
1979 * is possible for a folio to have the dirty flag set,
1980 * but it is actually clean (all its buffers are clean).
1981 * This happens if the buffers were written out directly,
1982 * with submit_bh(). ext3 will do this, as well as
1983 * the blockdev mapping. filemap_release_folio() will
1984 * discover that cleanness and will drop the buffers
1985 * and mark the folio clean - it can be freed.
1987 * Rarely, folios can have buffers and no ->mapping.
1988 * These are the folios which were not successfully
1989 * invalidated in truncate_cleanup_folio(). We try to
1990 * drop those buffers here and if that worked, and the
1991 * folio is no longer mapped into process address space
1992 * (refcount == 1) it can be freed. Otherwise, leave
1993 * the folio on the LRU so it is swappable.
1995 if (folio_has_private(folio)) {
1996 if (!filemap_release_folio(folio, sc->gfp_mask))
1997 goto activate_locked;
1998 if (!mapping && folio_ref_count(folio) == 1) {
1999 folio_unlock(folio);
2000 if (folio_put_testzero(folio))
2004 * rare race with speculative reference.
2005 * the speculative reference will free
2006 * this folio shortly, so we may
2007 * increment nr_reclaimed here (and
2008 * leave it off the LRU).
2010 nr_reclaimed += nr_pages;
2016 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
2017 /* follow __remove_mapping for reference */
2018 if (!folio_ref_freeze(folio, 1))
2021 * The folio has only one reference left, which is
2022 * from the isolation. After the caller puts the
2023 * folio back on the lru and drops the reference, the
2024 * folio will be freed anyway. It doesn't matter
2025 * which lru it goes on. So we don't bother checking
2026 * the dirty flag here.
2028 count_vm_events(PGLAZYFREED, nr_pages);
2029 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
2030 } else if (!mapping || !__remove_mapping(mapping, folio, true,
2031 sc->target_mem_cgroup))
2034 folio_unlock(folio);
2037 * Folio may get swapped out as a whole, need to account
2040 nr_reclaimed += nr_pages;
2043 * Is there need to periodically free_folio_list? It would
2044 * appear not as the counts should be low
2046 if (unlikely(folio_test_large(folio)))
2047 destroy_large_folio(folio);
2049 list_add(&folio->lru, &free_folios);
2052 activate_locked_split:
2054 * The tail pages that are failed to add into swap cache
2055 * reach here. Fixup nr_scanned and nr_pages.
2058 sc->nr_scanned -= (nr_pages - 1);
2062 /* Not a candidate for swapping, so reclaim swap space. */
2063 if (folio_test_swapcache(folio) &&
2064 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
2065 folio_free_swap(folio);
2066 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2067 if (!folio_test_mlocked(folio)) {
2068 int type = folio_is_file_lru(folio);
2069 folio_set_active(folio);
2070 stat->nr_activate[type] += nr_pages;
2071 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2074 folio_unlock(folio);
2076 list_add(&folio->lru, &ret_folios);
2077 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2078 folio_test_unevictable(folio), folio);
2080 /* 'folio_list' is always empty here */
2082 /* Migrate folios selected for demotion */
2083 nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
2084 /* Folios that could not be demoted are still in @demote_folios */
2085 if (!list_empty(&demote_folios)) {
2086 /* Folios which weren't demoted go back on @folio_list for retry: */
2087 list_splice_init(&demote_folios, folio_list);
2088 do_demote_pass = false;
2092 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2094 mem_cgroup_uncharge_list(&free_folios);
2095 try_to_unmap_flush();
2096 free_unref_page_list(&free_folios);
2098 list_splice(&ret_folios, folio_list);
2099 count_vm_events(PGACTIVATE, pgactivate);
2102 swap_write_unplug(plug);
2103 return nr_reclaimed;
2106 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2107 struct list_head *folio_list)
2109 struct scan_control sc = {
2110 .gfp_mask = GFP_KERNEL,
2113 struct reclaim_stat stat;
2114 unsigned int nr_reclaimed;
2115 struct folio *folio, *next;
2116 LIST_HEAD(clean_folios);
2117 unsigned int noreclaim_flag;
2119 list_for_each_entry_safe(folio, next, folio_list, lru) {
2120 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2121 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2122 !folio_test_unevictable(folio)) {
2123 folio_clear_active(folio);
2124 list_move(&folio->lru, &clean_folios);
2129 * We should be safe here since we are only dealing with file pages and
2130 * we are not kswapd and therefore cannot write dirty file pages. But
2131 * call memalloc_noreclaim_save() anyway, just in case these conditions
2132 * change in the future.
2134 noreclaim_flag = memalloc_noreclaim_save();
2135 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
2137 memalloc_noreclaim_restore(noreclaim_flag);
2139 list_splice(&clean_folios, folio_list);
2140 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2141 -(long)nr_reclaimed);
2143 * Since lazyfree pages are isolated from file LRU from the beginning,
2144 * they will rotate back to anonymous LRU in the end if it failed to
2145 * discard so isolated count will be mismatched.
2146 * Compensate the isolated count for both LRU lists.
2148 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2149 stat.nr_lazyfree_fail);
2150 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2151 -(long)stat.nr_lazyfree_fail);
2152 return nr_reclaimed;
2156 * Update LRU sizes after isolating pages. The LRU size updates must
2157 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2159 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2160 enum lru_list lru, unsigned long *nr_zone_taken)
2164 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2165 if (!nr_zone_taken[zid])
2168 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2174 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2176 * lruvec->lru_lock is heavily contended. Some of the functions that
2177 * shrink the lists perform better by taking out a batch of pages
2178 * and working on them outside the LRU lock.
2180 * For pagecache intensive workloads, this function is the hottest
2181 * spot in the kernel (apart from copy_*_user functions).
2183 * Lru_lock must be held before calling this function.
2185 * @nr_to_scan: The number of eligible pages to look through on the list.
2186 * @lruvec: The LRU vector to pull pages from.
2187 * @dst: The temp list to put pages on to.
2188 * @nr_scanned: The number of pages that were scanned.
2189 * @sc: The scan_control struct for this reclaim session
2190 * @lru: LRU list id for isolating
2192 * returns how many pages were moved onto *@dst.
2194 static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
2195 struct lruvec *lruvec, struct list_head *dst,
2196 unsigned long *nr_scanned, struct scan_control *sc,
2199 struct list_head *src = &lruvec->lists[lru];
2200 unsigned long nr_taken = 0;
2201 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2202 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2203 unsigned long skipped = 0;
2204 unsigned long scan, total_scan, nr_pages;
2205 LIST_HEAD(folios_skipped);
2209 while (scan < nr_to_scan && !list_empty(src)) {
2210 struct list_head *move_to = src;
2211 struct folio *folio;
2213 folio = lru_to_folio(src);
2214 prefetchw_prev_lru_folio(folio, src, flags);
2216 nr_pages = folio_nr_pages(folio);
2217 total_scan += nr_pages;
2219 if (folio_zonenum(folio) > sc->reclaim_idx) {
2220 nr_skipped[folio_zonenum(folio)] += nr_pages;
2221 move_to = &folios_skipped;
2226 * Do not count skipped folios because that makes the function
2227 * return with no isolated folios if the LRU mostly contains
2228 * ineligible folios. This causes the VM to not reclaim any
2229 * folios, triggering a premature OOM.
2230 * Account all pages in a folio.
2234 if (!folio_test_lru(folio))
2236 if (!sc->may_unmap && folio_mapped(folio))
2240 * Be careful not to clear the lru flag until after we're
2241 * sure the folio is not being freed elsewhere -- the
2242 * folio release code relies on it.
2244 if (unlikely(!folio_try_get(folio)))
2247 if (!folio_test_clear_lru(folio)) {
2248 /* Another thread is already isolating this folio */
2253 nr_taken += nr_pages;
2254 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2257 list_move(&folio->lru, move_to);
2261 * Splice any skipped folios to the start of the LRU list. Note that
2262 * this disrupts the LRU order when reclaiming for lower zones but
2263 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2264 * scanning would soon rescan the same folios to skip and waste lots
2267 if (!list_empty(&folios_skipped)) {
2270 list_splice(&folios_skipped, src);
2271 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2272 if (!nr_skipped[zid])
2275 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2276 skipped += nr_skipped[zid];
2279 *nr_scanned = total_scan;
2280 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2281 total_scan, skipped, nr_taken,
2282 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2283 update_lru_sizes(lruvec, lru, nr_zone_taken);
2288 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2289 * @folio: Folio to isolate from its LRU list.
2291 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2292 * corresponding to whatever LRU list the folio was on.
2294 * The folio will have its LRU flag cleared. If it was found on the
2295 * active list, it will have the Active flag set. If it was found on the
2296 * unevictable list, it will have the Unevictable flag set. These flags
2297 * may need to be cleared by the caller before letting the page go.
2301 * (1) Must be called with an elevated refcount on the folio. This is a
2302 * fundamental difference from isolate_lru_folios() (which is called
2303 * without a stable reference).
2304 * (2) The lru_lock must not be held.
2305 * (3) Interrupts must be enabled.
2307 * Return: 0 if the folio was removed from an LRU list.
2308 * -EBUSY if the folio was not on an LRU list.
2310 int folio_isolate_lru(struct folio *folio)
2314 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2316 if (folio_test_clear_lru(folio)) {
2317 struct lruvec *lruvec;
2320 lruvec = folio_lruvec_lock_irq(folio);
2321 lruvec_del_folio(lruvec, folio);
2322 unlock_page_lruvec_irq(lruvec);
2330 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2331 * then get rescheduled. When there are massive number of tasks doing page
2332 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2333 * the LRU list will go small and be scanned faster than necessary, leading to
2334 * unnecessary swapping, thrashing and OOM.
2336 static int too_many_isolated(struct pglist_data *pgdat, int file,
2337 struct scan_control *sc)
2339 unsigned long inactive, isolated;
2342 if (current_is_kswapd())
2345 if (!writeback_throttling_sane(sc))
2349 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2350 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2352 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2353 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2357 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2358 * won't get blocked by normal direct-reclaimers, forming a circular
2361 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2364 too_many = isolated > inactive;
2366 /* Wake up tasks throttled due to too_many_isolated. */
2368 wake_throttle_isolated(pgdat);
2374 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
2375 * On return, @list is reused as a list of folios to be freed by the caller.
2377 * Returns the number of pages moved to the given lruvec.
2379 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
2380 struct list_head *list)
2382 int nr_pages, nr_moved = 0;
2383 LIST_HEAD(folios_to_free);
2385 while (!list_empty(list)) {
2386 struct folio *folio = lru_to_folio(list);
2388 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2389 list_del(&folio->lru);
2390 if (unlikely(!folio_evictable(folio))) {
2391 spin_unlock_irq(&lruvec->lru_lock);
2392 folio_putback_lru(folio);
2393 spin_lock_irq(&lruvec->lru_lock);
2398 * The folio_set_lru needs to be kept here for list integrity.
2400 * #0 move_folios_to_lru #1 release_pages
2401 * if (!folio_put_testzero())
2402 * if (folio_put_testzero())
2403 * !lru //skip lru_lock
2405 * list_add(&folio->lru,)
2406 * list_add(&folio->lru,)
2408 folio_set_lru(folio);
2410 if (unlikely(folio_put_testzero(folio))) {
2411 __folio_clear_lru_flags(folio);
2413 if (unlikely(folio_test_large(folio))) {
2414 spin_unlock_irq(&lruvec->lru_lock);
2415 destroy_large_folio(folio);
2416 spin_lock_irq(&lruvec->lru_lock);
2418 list_add(&folio->lru, &folios_to_free);
2424 * All pages were isolated from the same lruvec (and isolation
2425 * inhibits memcg migration).
2427 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2428 lruvec_add_folio(lruvec, folio);
2429 nr_pages = folio_nr_pages(folio);
2430 nr_moved += nr_pages;
2431 if (folio_test_active(folio))
2432 workingset_age_nonresident(lruvec, nr_pages);
2436 * To save our caller's stack, now use input list for pages to free.
2438 list_splice(&folios_to_free, list);
2444 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2445 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2446 * we should not throttle. Otherwise it is safe to do so.
2448 static int current_may_throttle(void)
2450 return !(current->flags & PF_LOCAL_THROTTLE);
2454 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2455 * of reclaimed pages
2457 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
2458 struct lruvec *lruvec, struct scan_control *sc,
2461 LIST_HEAD(folio_list);
2462 unsigned long nr_scanned;
2463 unsigned int nr_reclaimed = 0;
2464 unsigned long nr_taken;
2465 struct reclaim_stat stat;
2466 bool file = is_file_lru(lru);
2467 enum vm_event_item item;
2468 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2469 bool stalled = false;
2471 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2475 /* wait a bit for the reclaimer. */
2477 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2479 /* We are about to die and free our memory. Return now. */
2480 if (fatal_signal_pending(current))
2481 return SWAP_CLUSTER_MAX;
2486 spin_lock_irq(&lruvec->lru_lock);
2488 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
2489 &nr_scanned, sc, lru);
2491 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2492 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2493 if (!cgroup_reclaim(sc))
2494 __count_vm_events(item, nr_scanned);
2495 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2496 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2498 spin_unlock_irq(&lruvec->lru_lock);
2503 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
2505 spin_lock_irq(&lruvec->lru_lock);
2506 move_folios_to_lru(lruvec, &folio_list);
2508 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2509 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2510 if (!cgroup_reclaim(sc))
2511 __count_vm_events(item, nr_reclaimed);
2512 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2513 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2514 spin_unlock_irq(&lruvec->lru_lock);
2516 lru_note_cost(lruvec, file, stat.nr_pageout);
2517 mem_cgroup_uncharge_list(&folio_list);
2518 free_unref_page_list(&folio_list);
2521 * If dirty folios are scanned that are not queued for IO, it
2522 * implies that flushers are not doing their job. This can
2523 * happen when memory pressure pushes dirty folios to the end of
2524 * the LRU before the dirty limits are breached and the dirty
2525 * data has expired. It can also happen when the proportion of
2526 * dirty folios grows not through writes but through memory
2527 * pressure reclaiming all the clean cache. And in some cases,
2528 * the flushers simply cannot keep up with the allocation
2529 * rate. Nudge the flusher threads in case they are asleep.
2531 if (stat.nr_unqueued_dirty == nr_taken) {
2532 wakeup_flusher_threads(WB_REASON_VMSCAN);
2534 * For cgroupv1 dirty throttling is achieved by waking up
2535 * the kernel flusher here and later waiting on folios
2536 * which are in writeback to finish (see shrink_folio_list()).
2538 * Flusher may not be able to issue writeback quickly
2539 * enough for cgroupv1 writeback throttling to work
2540 * on a large system.
2542 if (!writeback_throttling_sane(sc))
2543 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2546 sc->nr.dirty += stat.nr_dirty;
2547 sc->nr.congested += stat.nr_congested;
2548 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2549 sc->nr.writeback += stat.nr_writeback;
2550 sc->nr.immediate += stat.nr_immediate;
2551 sc->nr.taken += nr_taken;
2553 sc->nr.file_taken += nr_taken;
2555 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2556 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2557 return nr_reclaimed;
2561 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2563 * We move them the other way if the folio is referenced by one or more
2566 * If the folios are mostly unmapped, the processing is fast and it is
2567 * appropriate to hold lru_lock across the whole operation. But if
2568 * the folios are mapped, the processing is slow (folio_referenced()), so
2569 * we should drop lru_lock around each folio. It's impossible to balance
2570 * this, so instead we remove the folios from the LRU while processing them.
2571 * It is safe to rely on the active flag against the non-LRU folios in here
2572 * because nobody will play with that bit on a non-LRU folio.
2574 * The downside is that we have to touch folio->_refcount against each folio.
2575 * But we had to alter folio->flags anyway.
2577 static void shrink_active_list(unsigned long nr_to_scan,
2578 struct lruvec *lruvec,
2579 struct scan_control *sc,
2582 unsigned long nr_taken;
2583 unsigned long nr_scanned;
2584 unsigned long vm_flags;
2585 LIST_HEAD(l_hold); /* The folios which were snipped off */
2586 LIST_HEAD(l_active);
2587 LIST_HEAD(l_inactive);
2588 unsigned nr_deactivate, nr_activate;
2589 unsigned nr_rotated = 0;
2590 int file = is_file_lru(lru);
2591 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2595 spin_lock_irq(&lruvec->lru_lock);
2597 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2598 &nr_scanned, sc, lru);
2600 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2602 if (!cgroup_reclaim(sc))
2603 __count_vm_events(PGREFILL, nr_scanned);
2604 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2606 spin_unlock_irq(&lruvec->lru_lock);
2608 while (!list_empty(&l_hold)) {
2609 struct folio *folio;
2612 folio = lru_to_folio(&l_hold);
2613 list_del(&folio->lru);
2615 if (unlikely(!folio_evictable(folio))) {
2616 folio_putback_lru(folio);
2620 if (unlikely(buffer_heads_over_limit)) {
2621 if (folio_test_private(folio) && folio_trylock(folio)) {
2622 if (folio_test_private(folio))
2623 filemap_release_folio(folio, 0);
2624 folio_unlock(folio);
2628 /* Referenced or rmap lock contention: rotate */
2629 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2632 * Identify referenced, file-backed active folios and
2633 * give them one more trip around the active list. So
2634 * that executable code get better chances to stay in
2635 * memory under moderate memory pressure. Anon folios
2636 * are not likely to be evicted by use-once streaming
2637 * IO, plus JVM can create lots of anon VM_EXEC folios,
2638 * so we ignore them here.
2640 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2641 nr_rotated += folio_nr_pages(folio);
2642 list_add(&folio->lru, &l_active);
2647 folio_clear_active(folio); /* we are de-activating */
2648 folio_set_workingset(folio);
2649 list_add(&folio->lru, &l_inactive);
2653 * Move folios back to the lru list.
2655 spin_lock_irq(&lruvec->lru_lock);
2657 nr_activate = move_folios_to_lru(lruvec, &l_active);
2658 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2659 /* Keep all free folios in l_active list */
2660 list_splice(&l_inactive, &l_active);
2662 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2663 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2665 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2666 spin_unlock_irq(&lruvec->lru_lock);
2668 mem_cgroup_uncharge_list(&l_active);
2669 free_unref_page_list(&l_active);
2670 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2671 nr_deactivate, nr_rotated, sc->priority, file);
2674 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2675 struct pglist_data *pgdat)
2677 struct reclaim_stat dummy_stat;
2678 unsigned int nr_reclaimed;
2679 struct folio *folio;
2680 struct scan_control sc = {
2681 .gfp_mask = GFP_KERNEL,
2688 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2689 while (!list_empty(folio_list)) {
2690 folio = lru_to_folio(folio_list);
2691 list_del(&folio->lru);
2692 folio_putback_lru(folio);
2695 return nr_reclaimed;
2698 unsigned long reclaim_pages(struct list_head *folio_list)
2701 unsigned int nr_reclaimed = 0;
2702 LIST_HEAD(node_folio_list);
2703 unsigned int noreclaim_flag;
2705 if (list_empty(folio_list))
2706 return nr_reclaimed;
2708 noreclaim_flag = memalloc_noreclaim_save();
2710 nid = folio_nid(lru_to_folio(folio_list));
2712 struct folio *folio = lru_to_folio(folio_list);
2714 if (nid == folio_nid(folio)) {
2715 folio_clear_active(folio);
2716 list_move(&folio->lru, &node_folio_list);
2720 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2721 nid = folio_nid(lru_to_folio(folio_list));
2722 } while (!list_empty(folio_list));
2724 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2726 memalloc_noreclaim_restore(noreclaim_flag);
2728 return nr_reclaimed;
2731 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2732 struct lruvec *lruvec, struct scan_control *sc)
2734 if (is_active_lru(lru)) {
2735 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2736 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2738 sc->skipped_deactivate = 1;
2742 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2746 * The inactive anon list should be small enough that the VM never has
2747 * to do too much work.
2749 * The inactive file list should be small enough to leave most memory
2750 * to the established workingset on the scan-resistant active list,
2751 * but large enough to avoid thrashing the aggregate readahead window.
2753 * Both inactive lists should also be large enough that each inactive
2754 * folio has a chance to be referenced again before it is reclaimed.
2756 * If that fails and refaulting is observed, the inactive list grows.
2758 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2759 * on this LRU, maintained by the pageout code. An inactive_ratio
2760 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2763 * memory ratio inactive
2764 * -------------------------------------
2773 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2775 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2776 unsigned long inactive, active;
2777 unsigned long inactive_ratio;
2780 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2781 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2783 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2785 inactive_ratio = int_sqrt(10 * gb);
2789 return inactive * inactive_ratio < active;
2799 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2802 struct lruvec *target_lruvec;
2804 if (lru_gen_enabled())
2807 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2810 * Flush the memory cgroup stats, so that we read accurate per-memcg
2811 * lruvec stats for heuristics.
2813 mem_cgroup_flush_stats();
2816 * Determine the scan balance between anon and file LRUs.
2818 spin_lock_irq(&target_lruvec->lru_lock);
2819 sc->anon_cost = target_lruvec->anon_cost;
2820 sc->file_cost = target_lruvec->file_cost;
2821 spin_unlock_irq(&target_lruvec->lru_lock);
2824 * Target desirable inactive:active list ratios for the anon
2825 * and file LRU lists.
2827 if (!sc->force_deactivate) {
2828 unsigned long refaults;
2831 * When refaults are being observed, it means a new
2832 * workingset is being established. Deactivate to get
2833 * rid of any stale active pages quickly.
2835 refaults = lruvec_page_state(target_lruvec,
2836 WORKINGSET_ACTIVATE_ANON);
2837 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2838 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2839 sc->may_deactivate |= DEACTIVATE_ANON;
2841 sc->may_deactivate &= ~DEACTIVATE_ANON;
2843 refaults = lruvec_page_state(target_lruvec,
2844 WORKINGSET_ACTIVATE_FILE);
2845 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2846 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2847 sc->may_deactivate |= DEACTIVATE_FILE;
2849 sc->may_deactivate &= ~DEACTIVATE_FILE;
2851 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2854 * If we have plenty of inactive file pages that aren't
2855 * thrashing, try to reclaim those first before touching
2858 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2859 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2860 sc->cache_trim_mode = 1;
2862 sc->cache_trim_mode = 0;
2865 * Prevent the reclaimer from falling into the cache trap: as
2866 * cache pages start out inactive, every cache fault will tip
2867 * the scan balance towards the file LRU. And as the file LRU
2868 * shrinks, so does the window for rotation from references.
2869 * This means we have a runaway feedback loop where a tiny
2870 * thrashing file LRU becomes infinitely more attractive than
2871 * anon pages. Try to detect this based on file LRU size.
2873 if (!cgroup_reclaim(sc)) {
2874 unsigned long total_high_wmark = 0;
2875 unsigned long free, anon;
2878 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2879 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2880 node_page_state(pgdat, NR_INACTIVE_FILE);
2882 for (z = 0; z < MAX_NR_ZONES; z++) {
2883 struct zone *zone = &pgdat->node_zones[z];
2885 if (!managed_zone(zone))
2888 total_high_wmark += high_wmark_pages(zone);
2892 * Consider anon: if that's low too, this isn't a
2893 * runaway file reclaim problem, but rather just
2894 * extreme pressure. Reclaim as per usual then.
2896 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2899 file + free <= total_high_wmark &&
2900 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2901 anon >> sc->priority;
2906 * Determine how aggressively the anon and file LRU lists should be
2909 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2910 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2912 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2915 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2916 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2917 unsigned long anon_cost, file_cost, total_cost;
2918 int swappiness = mem_cgroup_swappiness(memcg);
2919 u64 fraction[ANON_AND_FILE];
2920 u64 denominator = 0; /* gcc */
2921 enum scan_balance scan_balance;
2922 unsigned long ap, fp;
2925 /* If we have no swap space, do not bother scanning anon folios. */
2926 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2927 scan_balance = SCAN_FILE;
2932 * Global reclaim will swap to prevent OOM even with no
2933 * swappiness, but memcg users want to use this knob to
2934 * disable swapping for individual groups completely when
2935 * using the memory controller's swap limit feature would be
2938 if (cgroup_reclaim(sc) && !swappiness) {
2939 scan_balance = SCAN_FILE;
2944 * Do not apply any pressure balancing cleverness when the
2945 * system is close to OOM, scan both anon and file equally
2946 * (unless the swappiness setting disagrees with swapping).
2948 if (!sc->priority && swappiness) {
2949 scan_balance = SCAN_EQUAL;
2954 * If the system is almost out of file pages, force-scan anon.
2956 if (sc->file_is_tiny) {
2957 scan_balance = SCAN_ANON;
2962 * If there is enough inactive page cache, we do not reclaim
2963 * anything from the anonymous working right now.
2965 if (sc->cache_trim_mode) {
2966 scan_balance = SCAN_FILE;
2970 scan_balance = SCAN_FRACT;
2972 * Calculate the pressure balance between anon and file pages.
2974 * The amount of pressure we put on each LRU is inversely
2975 * proportional to the cost of reclaiming each list, as
2976 * determined by the share of pages that are refaulting, times
2977 * the relative IO cost of bringing back a swapped out
2978 * anonymous page vs reloading a filesystem page (swappiness).
2980 * Although we limit that influence to ensure no list gets
2981 * left behind completely: at least a third of the pressure is
2982 * applied, before swappiness.
2984 * With swappiness at 100, anon and file have equal IO cost.
2986 total_cost = sc->anon_cost + sc->file_cost;
2987 anon_cost = total_cost + sc->anon_cost;
2988 file_cost = total_cost + sc->file_cost;
2989 total_cost = anon_cost + file_cost;
2991 ap = swappiness * (total_cost + 1);
2992 ap /= anon_cost + 1;
2994 fp = (200 - swappiness) * (total_cost + 1);
2995 fp /= file_cost + 1;
2999 denominator = ap + fp;
3001 for_each_evictable_lru(lru) {
3002 int file = is_file_lru(lru);
3003 unsigned long lruvec_size;
3004 unsigned long low, min;
3007 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
3008 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
3013 * Scale a cgroup's reclaim pressure by proportioning
3014 * its current usage to its memory.low or memory.min
3017 * This is important, as otherwise scanning aggression
3018 * becomes extremely binary -- from nothing as we
3019 * approach the memory protection threshold, to totally
3020 * nominal as we exceed it. This results in requiring
3021 * setting extremely liberal protection thresholds. It
3022 * also means we simply get no protection at all if we
3023 * set it too low, which is not ideal.
3025 * If there is any protection in place, we reduce scan
3026 * pressure by how much of the total memory used is
3027 * within protection thresholds.
3029 * There is one special case: in the first reclaim pass,
3030 * we skip over all groups that are within their low
3031 * protection. If that fails to reclaim enough pages to
3032 * satisfy the reclaim goal, we come back and override
3033 * the best-effort low protection. However, we still
3034 * ideally want to honor how well-behaved groups are in
3035 * that case instead of simply punishing them all
3036 * equally. As such, we reclaim them based on how much
3037 * memory they are using, reducing the scan pressure
3038 * again by how much of the total memory used is under
3041 unsigned long cgroup_size = mem_cgroup_size(memcg);
3042 unsigned long protection;
3044 /* memory.low scaling, make sure we retry before OOM */
3045 if (!sc->memcg_low_reclaim && low > min) {
3047 sc->memcg_low_skipped = 1;
3052 /* Avoid TOCTOU with earlier protection check */
3053 cgroup_size = max(cgroup_size, protection);
3055 scan = lruvec_size - lruvec_size * protection /
3059 * Minimally target SWAP_CLUSTER_MAX pages to keep
3060 * reclaim moving forwards, avoiding decrementing
3061 * sc->priority further than desirable.
3063 scan = max(scan, SWAP_CLUSTER_MAX);
3068 scan >>= sc->priority;
3071 * If the cgroup's already been deleted, make sure to
3072 * scrape out the remaining cache.
3074 if (!scan && !mem_cgroup_online(memcg))
3075 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
3077 switch (scan_balance) {
3079 /* Scan lists relative to size */
3083 * Scan types proportional to swappiness and
3084 * their relative recent reclaim efficiency.
3085 * Make sure we don't miss the last page on
3086 * the offlined memory cgroups because of a
3089 scan = mem_cgroup_online(memcg) ?
3090 div64_u64(scan * fraction[file], denominator) :
3091 DIV64_U64_ROUND_UP(scan * fraction[file],
3096 /* Scan one type exclusively */
3097 if ((scan_balance == SCAN_FILE) != file)
3101 /* Look ma, no brain */
3110 * Anonymous LRU management is a waste if there is
3111 * ultimately no way to reclaim the memory.
3113 static bool can_age_anon_pages(struct pglist_data *pgdat,
3114 struct scan_control *sc)
3116 /* Aging the anon LRU is valuable if swap is present: */
3117 if (total_swap_pages > 0)
3120 /* Also valuable if anon pages can be demoted: */
3121 return can_demote(pgdat->node_id, sc);
3124 #ifdef CONFIG_LRU_GEN
3126 #ifdef CONFIG_LRU_GEN_ENABLED
3127 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3128 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
3130 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3131 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
3134 /******************************************************************************
3136 ******************************************************************************/
3138 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
3140 #define DEFINE_MAX_SEQ(lruvec) \
3141 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3143 #define DEFINE_MIN_SEQ(lruvec) \
3144 unsigned long min_seq[ANON_AND_FILE] = { \
3145 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3146 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3149 #define for_each_gen_type_zone(gen, type, zone) \
3150 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3151 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3152 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3154 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
3156 struct pglist_data *pgdat = NODE_DATA(nid);
3160 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3162 /* for hotadd_new_pgdat() */
3164 lruvec->pgdat = pgdat;
3169 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3171 return pgdat ? &pgdat->__lruvec : NULL;
3174 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3176 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3177 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3179 if (!can_demote(pgdat->node_id, sc) &&
3180 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3183 return mem_cgroup_swappiness(memcg);
3186 static int get_nr_gens(struct lruvec *lruvec, int type)
3188 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3191 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3193 /* see the comment on lru_gen_struct */
3194 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3195 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3196 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3199 /******************************************************************************
3201 ******************************************************************************/
3203 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3205 static struct lru_gen_mm_list mm_list = {
3206 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3207 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3212 return &memcg->mm_list;
3214 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3219 void lru_gen_add_mm(struct mm_struct *mm)
3222 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3223 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3225 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3227 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3228 mm->lru_gen.memcg = memcg;
3230 spin_lock(&mm_list->lock);
3232 for_each_node_state(nid, N_MEMORY) {
3233 struct lruvec *lruvec = get_lruvec(memcg, nid);
3238 /* the first addition since the last iteration */
3239 if (lruvec->mm_state.tail == &mm_list->fifo)
3240 lruvec->mm_state.tail = &mm->lru_gen.list;
3243 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3245 spin_unlock(&mm_list->lock);
3248 void lru_gen_del_mm(struct mm_struct *mm)
3251 struct lru_gen_mm_list *mm_list;
3252 struct mem_cgroup *memcg = NULL;
3254 if (list_empty(&mm->lru_gen.list))
3258 memcg = mm->lru_gen.memcg;
3260 mm_list = get_mm_list(memcg);
3262 spin_lock(&mm_list->lock);
3264 for_each_node(nid) {
3265 struct lruvec *lruvec = get_lruvec(memcg, nid);
3270 /* where the last iteration ended (exclusive) */
3271 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3272 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3274 /* where the current iteration continues (inclusive) */
3275 if (lruvec->mm_state.head != &mm->lru_gen.list)
3278 lruvec->mm_state.head = lruvec->mm_state.head->next;
3279 /* the deletion ends the current iteration */
3280 if (lruvec->mm_state.head == &mm_list->fifo)
3281 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3284 list_del_init(&mm->lru_gen.list);
3286 spin_unlock(&mm_list->lock);
3289 mem_cgroup_put(mm->lru_gen.memcg);
3290 mm->lru_gen.memcg = NULL;
3295 void lru_gen_migrate_mm(struct mm_struct *mm)
3297 struct mem_cgroup *memcg;
3298 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3300 VM_WARN_ON_ONCE(task->mm != mm);
3301 lockdep_assert_held(&task->alloc_lock);
3303 /* for mm_update_next_owner() */
3304 if (mem_cgroup_disabled())
3307 /* migration can happen before addition */
3308 if (!mm->lru_gen.memcg)
3312 memcg = mem_cgroup_from_task(task);
3314 if (memcg == mm->lru_gen.memcg)
3317 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3325 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3326 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3327 * bits in a bitmap, k is the number of hash functions and n is the number of
3330 * Page table walkers use one of the two filters to reduce their search space.
3331 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3332 * aging uses the double-buffering technique to flip to the other filter each
3333 * time it produces a new generation. For non-leaf entries that have enough
3334 * leaf entries, the aging carries them over to the next generation in
3335 * walk_pmd_range(); the eviction also report them when walking the rmap
3336 * in lru_gen_look_around().
3338 * For future optimizations:
3339 * 1. It's not necessary to keep both filters all the time. The spare one can be
3340 * freed after the RCU grace period and reallocated if needed again.
3341 * 2. And when reallocating, it's worth scaling its size according to the number
3342 * of inserted entries in the other filter, to reduce the memory overhead on
3343 * small systems and false positives on large systems.
3344 * 3. Jenkins' hash function is an alternative to Knuth's.
3346 #define BLOOM_FILTER_SHIFT 15
3348 static inline int filter_gen_from_seq(unsigned long seq)
3350 return seq % NR_BLOOM_FILTERS;
3353 static void get_item_key(void *item, int *key)
3355 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3357 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3359 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3360 key[1] = hash >> BLOOM_FILTER_SHIFT;
3363 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3365 unsigned long *filter;
3366 int gen = filter_gen_from_seq(seq);
3368 filter = lruvec->mm_state.filters[gen];
3370 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3374 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3375 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3376 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3379 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3382 unsigned long *filter;
3383 int gen = filter_gen_from_seq(seq);
3385 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3389 get_item_key(item, key);
3391 if (!test_bit(key[0], filter))
3392 set_bit(key[0], filter);
3393 if (!test_bit(key[1], filter))
3394 set_bit(key[1], filter);
3397 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3400 unsigned long *filter;
3401 int gen = filter_gen_from_seq(seq);
3403 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3407 get_item_key(item, key);
3409 return test_bit(key[0], filter) && test_bit(key[1], filter);
3412 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3417 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3420 hist = lru_hist_from_seq(walk->max_seq);
3422 for (i = 0; i < NR_MM_STATS; i++) {
3423 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3424 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3425 walk->mm_stats[i] = 0;
3429 if (NR_HIST_GENS > 1 && last) {
3430 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3432 for (i = 0; i < NR_MM_STATS; i++)
3433 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3437 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3440 unsigned long size = 0;
3441 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3442 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3444 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3447 clear_bit(key, &mm->lru_gen.bitmap);
3449 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3450 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3451 get_mm_counter(mm, MM_ANONPAGES) +
3452 get_mm_counter(mm, MM_SHMEMPAGES);
3455 if (size < MIN_LRU_BATCH)
3458 return !mmget_not_zero(mm);
3461 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3462 struct mm_struct **iter)
3466 struct mm_struct *mm = NULL;
3467 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3468 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3469 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3472 * There are four interesting cases for this page table walker:
3473 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3474 * there is nothing left to do.
3475 * 2. It's the first of the current generation, and it needs to reset
3476 * the Bloom filter for the next generation.
3477 * 3. It reaches the end of mm_list, and it needs to increment
3478 * mm_state->seq; the iteration is done.
3479 * 4. It's the last of the current generation, and it needs to reset the
3480 * mm stats counters for the next generation.
3482 spin_lock(&mm_list->lock);
3484 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3485 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3486 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3488 if (walk->max_seq <= mm_state->seq) {
3494 if (!mm_state->nr_walkers) {
3495 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3497 mm_state->head = mm_list->fifo.next;
3501 while (!mm && mm_state->head != &mm_list->fifo) {
3502 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3504 mm_state->head = mm_state->head->next;
3506 /* force scan for those added after the last iteration */
3507 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3508 mm_state->tail = mm_state->head;
3509 walk->force_scan = true;
3512 if (should_skip_mm(mm, walk))
3516 if (mm_state->head == &mm_list->fifo)
3517 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3520 mm_state->nr_walkers--;
3522 mm_state->nr_walkers++;
3524 if (mm_state->nr_walkers)
3528 reset_mm_stats(lruvec, walk, last);
3530 spin_unlock(&mm_list->lock);
3533 reset_bloom_filter(lruvec, walk->max_seq + 1);
3543 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3545 bool success = false;
3546 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3547 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3548 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3550 spin_lock(&mm_list->lock);
3552 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3554 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3555 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3557 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3558 reset_mm_stats(lruvec, NULL, true);
3562 spin_unlock(&mm_list->lock);
3567 /******************************************************************************
3568 * refault feedback loop
3569 ******************************************************************************/
3572 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3574 * The P term is refaulted/(evicted+protected) from a tier in the generation
3575 * currently being evicted; the I term is the exponential moving average of the
3576 * P term over the generations previously evicted, using the smoothing factor
3577 * 1/2; the D term isn't supported.
3579 * The setpoint (SP) is always the first tier of one type; the process variable
3580 * (PV) is either any tier of the other type or any other tier of the same
3583 * The error is the difference between the SP and the PV; the correction is to
3584 * turn off protection when SP>PV or turn on protection when SP<PV.
3586 * For future optimizations:
3587 * 1. The D term may discount the other two terms over time so that long-lived
3588 * generations can resist stale information.
3591 unsigned long refaulted;
3592 unsigned long total;
3596 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3597 struct ctrl_pos *pos)
3599 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3600 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3602 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3603 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3604 pos->total = lrugen->avg_total[type][tier] +
3605 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3607 pos->total += lrugen->protected[hist][type][tier - 1];
3611 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3614 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3615 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3616 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3618 lockdep_assert_held(&lruvec->lru_lock);
3620 if (!carryover && !clear)
3623 hist = lru_hist_from_seq(seq);
3625 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3629 sum = lrugen->avg_refaulted[type][tier] +
3630 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3631 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3633 sum = lrugen->avg_total[type][tier] +
3634 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3636 sum += lrugen->protected[hist][type][tier - 1];
3637 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3641 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3642 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3644 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3649 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3652 * Return true if the PV has a limited number of refaults or a lower
3653 * refaulted/total than the SP.
3655 return pv->refaulted < MIN_LRU_BATCH ||
3656 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3657 (sp->refaulted + 1) * pv->total * pv->gain;
3660 /******************************************************************************
3662 ******************************************************************************/
3664 /* promote pages accessed through page tables */
3665 static int folio_update_gen(struct folio *folio, int gen)
3667 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3669 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3670 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3673 /* lru_gen_del_folio() has isolated this page? */
3674 if (!(old_flags & LRU_GEN_MASK)) {
3675 /* for shrink_folio_list() */
3676 new_flags = old_flags | BIT(PG_referenced);
3680 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3681 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3682 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3684 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3687 /* protect pages accessed multiple times through file descriptors */
3688 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3690 int type = folio_is_file_lru(folio);
3691 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3692 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3693 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3695 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3698 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3699 /* folio_update_gen() has promoted this page? */
3700 if (new_gen >= 0 && new_gen != old_gen)
3703 new_gen = (old_gen + 1) % MAX_NR_GENS;
3705 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3706 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3707 /* for folio_end_writeback() */
3709 new_flags |= BIT(PG_reclaim);
3710 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3712 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3717 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3718 int old_gen, int new_gen)
3720 int type = folio_is_file_lru(folio);
3721 int zone = folio_zonenum(folio);
3722 int delta = folio_nr_pages(folio);
3724 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3725 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3729 walk->nr_pages[old_gen][type][zone] -= delta;
3730 walk->nr_pages[new_gen][type][zone] += delta;
3733 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3735 int gen, type, zone;
3736 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3740 for_each_gen_type_zone(gen, type, zone) {
3741 enum lru_list lru = type * LRU_INACTIVE_FILE;
3742 int delta = walk->nr_pages[gen][type][zone];
3747 walk->nr_pages[gen][type][zone] = 0;
3748 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3749 lrugen->nr_pages[gen][type][zone] + delta);
3751 if (lru_gen_is_active(lruvec, gen))
3753 __update_lru_size(lruvec, lru, zone, delta);
3757 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3759 struct address_space *mapping;
3760 struct vm_area_struct *vma = args->vma;
3761 struct lru_gen_mm_walk *walk = args->private;
3763 if (!vma_is_accessible(vma))
3766 if (is_vm_hugetlb_page(vma))
3769 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3772 if (vma == get_gate_vma(vma->vm_mm))
3775 if (vma_is_anonymous(vma))
3776 return !walk->can_swap;
3778 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3781 mapping = vma->vm_file->f_mapping;
3782 if (mapping_unevictable(mapping))
3785 if (shmem_mapping(mapping))
3786 return !walk->can_swap;
3788 /* to exclude special mappings like dax, etc. */
3789 return !mapping->a_ops->read_folio;
3793 * Some userspace memory allocators map many single-page VMAs. Instead of
3794 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3795 * table to reduce zigzags and improve cache performance.
3797 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3798 unsigned long *vm_start, unsigned long *vm_end)
3800 unsigned long start = round_up(*vm_end, size);
3801 unsigned long end = (start | ~mask) + 1;
3802 VMA_ITERATOR(vmi, args->mm, start);
3804 VM_WARN_ON_ONCE(mask & size);
3805 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3807 for_each_vma(vmi, args->vma) {
3808 if (end && end <= args->vma->vm_start)
3811 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3814 *vm_start = max(start, args->vma->vm_start);
3815 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3823 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3825 unsigned long pfn = pte_pfn(pte);
3827 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3829 if (!pte_present(pte) || is_zero_pfn(pfn))
3832 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3835 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3841 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3842 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3844 unsigned long pfn = pmd_pfn(pmd);
3846 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3848 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3851 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3854 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3861 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3862 struct pglist_data *pgdat, bool can_swap)
3864 struct folio *folio;
3866 /* try to avoid unnecessary memory loads */
3867 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3870 folio = pfn_folio(pfn);
3871 if (folio_nid(folio) != pgdat->node_id)
3874 if (folio_memcg_rcu(folio) != memcg)
3877 /* file VMAs can contain anon pages from COW */
3878 if (!folio_is_file_lru(folio) && !can_swap)
3884 static bool suitable_to_scan(int total, int young)
3886 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3888 /* suitable if the average number of young PTEs per cacheline is >=1 */
3889 return young * n >= total;
3892 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3893 struct mm_walk *args)
3901 struct lru_gen_mm_walk *walk = args->private;
3902 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3903 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3904 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3906 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3908 ptl = pte_lockptr(args->mm, pmd);
3909 if (!spin_trylock(ptl))
3912 arch_enter_lazy_mmu_mode();
3914 pte = pte_offset_map(pmd, start & PMD_MASK);
3916 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3918 struct folio *folio;
3921 walk->mm_stats[MM_LEAF_TOTAL]++;
3923 pfn = get_pte_pfn(pte[i], args->vma, addr);
3927 if (!pte_young(pte[i])) {
3928 walk->mm_stats[MM_LEAF_OLD]++;
3932 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3936 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3937 VM_WARN_ON_ONCE(true);
3940 walk->mm_stats[MM_LEAF_YOUNG]++;
3942 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
3943 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3944 !folio_test_swapcache(folio)))
3945 folio_mark_dirty(folio);
3947 old_gen = folio_update_gen(folio, new_gen);
3948 if (old_gen >= 0 && old_gen != new_gen)
3949 update_batch_size(walk, folio, old_gen, new_gen);
3952 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3957 arch_leave_lazy_mmu_mode();
3960 return suitable_to_scan(total, young);
3963 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3964 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3965 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3970 struct lru_gen_mm_walk *walk = args->private;
3971 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3972 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3973 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3975 VM_WARN_ON_ONCE(pud_leaf(*pud));
3977 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3983 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3984 if (i && i <= MIN_LRU_BATCH) {
3985 __set_bit(i - 1, bitmap);
3989 pmd = pmd_offset(pud, *start);
3991 ptl = pmd_lockptr(args->mm, pmd);
3992 if (!spin_trylock(ptl))
3995 arch_enter_lazy_mmu_mode();
3999 struct folio *folio;
4000 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
4002 pfn = get_pmd_pfn(pmd[i], vma, addr);
4006 if (!pmd_trans_huge(pmd[i])) {
4007 if (arch_has_hw_nonleaf_pmd_young() &&
4008 get_cap(LRU_GEN_NONLEAF_YOUNG))
4009 pmdp_test_and_clear_young(vma, addr, pmd + i);
4013 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4017 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
4020 walk->mm_stats[MM_LEAF_YOUNG]++;
4022 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
4023 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4024 !folio_test_swapcache(folio)))
4025 folio_mark_dirty(folio);
4027 old_gen = folio_update_gen(folio, new_gen);
4028 if (old_gen >= 0 && old_gen != new_gen)
4029 update_batch_size(walk, folio, old_gen, new_gen);
4031 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
4032 } while (i <= MIN_LRU_BATCH);
4034 arch_leave_lazy_mmu_mode();
4038 bitmap_zero(bitmap, MIN_LRU_BATCH);
4041 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
4042 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
4047 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
4048 struct mm_walk *args)
4054 struct vm_area_struct *vma;
4055 unsigned long pos = -1;
4056 struct lru_gen_mm_walk *walk = args->private;
4057 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4059 VM_WARN_ON_ONCE(pud_leaf(*pud));
4062 * Finish an entire PMD in two passes: the first only reaches to PTE
4063 * tables to avoid taking the PMD lock; the second, if necessary, takes
4064 * the PMD lock to clear the accessed bit in PMD entries.
4066 pmd = pmd_offset(pud, start & PUD_MASK);
4068 /* walk_pte_range() may call get_next_vma() */
4070 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
4071 pmd_t val = pmd_read_atomic(pmd + i);
4073 /* for pmd_read_atomic() */
4076 next = pmd_addr_end(addr, end);
4078 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4079 walk->mm_stats[MM_LEAF_TOTAL]++;
4083 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4084 if (pmd_trans_huge(val)) {
4085 unsigned long pfn = pmd_pfn(val);
4086 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4088 walk->mm_stats[MM_LEAF_TOTAL]++;
4090 if (!pmd_young(val)) {
4091 walk->mm_stats[MM_LEAF_OLD]++;
4095 /* try to avoid unnecessary memory loads */
4096 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4099 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4103 walk->mm_stats[MM_NONLEAF_TOTAL]++;
4105 if (arch_has_hw_nonleaf_pmd_young() &&
4106 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
4107 if (!pmd_young(val))
4110 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4113 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4116 walk->mm_stats[MM_NONLEAF_FOUND]++;
4118 if (!walk_pte_range(&val, addr, next, args))
4121 walk->mm_stats[MM_NONLEAF_ADDED]++;
4123 /* carry over to the next generation */
4124 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4127 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
4129 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4133 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4134 struct mm_walk *args)
4140 struct lru_gen_mm_walk *walk = args->private;
4142 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4144 pud = pud_offset(p4d, start & P4D_MASK);
4146 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4147 pud_t val = READ_ONCE(pud[i]);
4149 next = pud_addr_end(addr, end);
4151 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4154 walk_pmd_range(&val, addr, next, args);
4156 /* a racy check to curtail the waiting time */
4157 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
4160 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4161 end = (addr | ~PUD_MASK) + 1;
4166 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4169 end = round_up(end, P4D_SIZE);
4171 if (!end || !args->vma)
4174 walk->next_addr = max(end, args->vma->vm_start);
4179 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4181 static const struct mm_walk_ops mm_walk_ops = {
4182 .test_walk = should_skip_vma,
4183 .p4d_entry = walk_pud_range,
4187 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4189 walk->next_addr = FIRST_USER_ADDRESS;
4194 /* folio_update_gen() requires stable folio_memcg() */
4195 if (!mem_cgroup_trylock_pages(memcg))
4198 /* the caller might be holding the lock for write */
4199 if (mmap_read_trylock(mm)) {
4200 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4202 mmap_read_unlock(mm);
4205 mem_cgroup_unlock_pages();
4207 if (walk->batched) {
4208 spin_lock_irq(&lruvec->lru_lock);
4209 reset_batch_size(lruvec, walk);
4210 spin_unlock_irq(&lruvec->lru_lock);
4214 } while (err == -EAGAIN);
4217 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4219 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4221 if (pgdat && current_is_kswapd()) {
4222 VM_WARN_ON_ONCE(walk);
4224 walk = &pgdat->mm_walk;
4225 } else if (!pgdat && !walk) {
4226 VM_WARN_ON_ONCE(current_is_kswapd());
4228 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4231 current->reclaim_state->mm_walk = walk;
4236 static void clear_mm_walk(void)
4238 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4240 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4241 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4243 current->reclaim_state->mm_walk = NULL;
4245 if (!current_is_kswapd())
4249 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4252 int remaining = MAX_LRU_BATCH;
4253 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4254 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4256 if (type == LRU_GEN_ANON && !can_swap)
4259 /* prevent cold/hot inversion if force_scan is true */
4260 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4261 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4263 while (!list_empty(head)) {
4264 struct folio *folio = lru_to_folio(head);
4266 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4267 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4268 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4269 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4271 new_gen = folio_inc_gen(lruvec, folio, false);
4272 list_move_tail(&folio->lru, &lrugen->lists[new_gen][type][zone]);
4279 reset_ctrl_pos(lruvec, type, true);
4280 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4285 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4287 int gen, type, zone;
4288 bool success = false;
4289 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4290 DEFINE_MIN_SEQ(lruvec);
4292 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4294 /* find the oldest populated generation */
4295 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4296 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4297 gen = lru_gen_from_seq(min_seq[type]);
4299 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4300 if (!list_empty(&lrugen->lists[gen][type][zone]))
4310 /* see the comment on lru_gen_struct */
4312 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4313 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4316 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4317 if (min_seq[type] == lrugen->min_seq[type])
4320 reset_ctrl_pos(lruvec, type, true);
4321 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4328 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4332 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4334 spin_lock_irq(&lruvec->lru_lock);
4336 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4338 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4339 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4342 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4344 while (!inc_min_seq(lruvec, type, can_swap)) {
4345 spin_unlock_irq(&lruvec->lru_lock);
4347 spin_lock_irq(&lruvec->lru_lock);
4352 * Update the active/inactive LRU sizes for compatibility. Both sides of
4353 * the current max_seq need to be covered, since max_seq+1 can overlap
4354 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4355 * overlap, cold/hot inversion happens.
4357 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4358 next = lru_gen_from_seq(lrugen->max_seq + 1);
4360 for (type = 0; type < ANON_AND_FILE; type++) {
4361 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4362 enum lru_list lru = type * LRU_INACTIVE_FILE;
4363 long delta = lrugen->nr_pages[prev][type][zone] -
4364 lrugen->nr_pages[next][type][zone];
4369 __update_lru_size(lruvec, lru, zone, delta);
4370 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4374 for (type = 0; type < ANON_AND_FILE; type++)
4375 reset_ctrl_pos(lruvec, type, false);
4377 WRITE_ONCE(lrugen->timestamps[next], jiffies);
4378 /* make sure preceding modifications appear */
4379 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4381 spin_unlock_irq(&lruvec->lru_lock);
4384 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4385 struct scan_control *sc, bool can_swap, bool force_scan)
4388 struct lru_gen_mm_walk *walk;
4389 struct mm_struct *mm = NULL;
4390 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4392 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4394 /* see the comment in iterate_mm_list() */
4395 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4401 * If the hardware doesn't automatically set the accessed bit, fallback
4402 * to lru_gen_look_around(), which only clears the accessed bit in a
4403 * handful of PTEs. Spreading the work out over a period of time usually
4404 * is less efficient, but it avoids bursty page faults.
4406 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
4407 success = iterate_mm_list_nowalk(lruvec, max_seq);
4411 walk = set_mm_walk(NULL);
4413 success = iterate_mm_list_nowalk(lruvec, max_seq);
4417 walk->lruvec = lruvec;
4418 walk->max_seq = max_seq;
4419 walk->can_swap = can_swap;
4420 walk->force_scan = force_scan;
4423 success = iterate_mm_list(lruvec, walk, &mm);
4425 walk_mm(lruvec, mm, walk);
4431 if (sc->priority <= DEF_PRIORITY - 2)
4432 wait_event_killable(lruvec->mm_state.wait,
4433 max_seq < READ_ONCE(lrugen->max_seq));
4435 return max_seq < READ_ONCE(lrugen->max_seq);
4438 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4440 inc_max_seq(lruvec, can_swap, force_scan);
4441 /* either this sees any waiters or they will see updated max_seq */
4442 if (wq_has_sleeper(&lruvec->mm_state.wait))
4443 wake_up_all(&lruvec->mm_state.wait);
4448 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4449 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4451 int gen, type, zone;
4452 unsigned long old = 0;
4453 unsigned long young = 0;
4454 unsigned long total = 0;
4455 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4456 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4458 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4461 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4462 unsigned long size = 0;
4464 gen = lru_gen_from_seq(seq);
4466 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4467 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4472 else if (seq + MIN_NR_GENS == max_seq)
4477 /* try to scrape all its memory if this memcg was deleted */
4478 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4481 * The aging tries to be lazy to reduce the overhead, while the eviction
4482 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4483 * ideal number of generations is MIN_NR_GENS+1.
4485 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4487 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4491 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4492 * of the total number of pages for each generation. A reasonable range
4493 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4494 * aging cares about the upper bound of hot pages, while the eviction
4495 * cares about the lower bound of cold pages.
4497 if (young * MIN_NR_GENS > total)
4499 if (old * (MIN_NR_GENS + 2) < total)
4505 static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
4508 unsigned long nr_to_scan;
4509 int swappiness = get_swappiness(lruvec, sc);
4510 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4511 DEFINE_MAX_SEQ(lruvec);
4512 DEFINE_MIN_SEQ(lruvec);
4514 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4516 mem_cgroup_calculate_protection(NULL, memcg);
4518 if (mem_cgroup_below_min(memcg))
4521 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4524 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4525 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4527 if (time_is_after_jiffies(birth + min_ttl))
4530 /* the size is likely too small to be helpful */
4531 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4536 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
4541 /* to protect the working set of the last N jiffies */
4542 static unsigned long lru_gen_min_ttl __read_mostly;
4544 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4546 struct mem_cgroup *memcg;
4547 bool success = false;
4548 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4550 VM_WARN_ON_ONCE(!current_is_kswapd());
4552 sc->last_reclaimed = sc->nr_reclaimed;
4555 * To reduce the chance of going into the aging path, which can be
4556 * costly, optimistically skip it if the flag below was cleared in the
4557 * eviction path. This improves the overall performance when multiple
4558 * memcgs are available.
4560 if (!sc->memcgs_need_aging) {
4561 sc->memcgs_need_aging = true;
4567 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4569 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4571 if (age_lruvec(lruvec, sc, min_ttl))
4575 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4579 /* check the order to exclude compaction-induced reclaim */
4580 if (success || !min_ttl || sc->order)
4584 * The main goal is to OOM kill if every generation from all memcgs is
4585 * younger than min_ttl. However, another possibility is all memcgs are
4586 * either below min or empty.
4588 if (mutex_trylock(&oom_lock)) {
4589 struct oom_control oc = {
4590 .gfp_mask = sc->gfp_mask,
4595 mutex_unlock(&oom_lock);
4600 * This function exploits spatial locality when shrink_folio_list() walks the
4601 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4602 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4603 * the PTE table to the Bloom filter. This forms a feedback loop between the
4604 * eviction and the aging.
4606 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4610 unsigned long start;
4613 struct lru_gen_mm_walk *walk;
4615 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4616 struct folio *folio = pfn_folio(pvmw->pfn);
4617 struct mem_cgroup *memcg = folio_memcg(folio);
4618 struct pglist_data *pgdat = folio_pgdat(folio);
4619 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4620 DEFINE_MAX_SEQ(lruvec);
4621 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4623 lockdep_assert_held(pvmw->ptl);
4624 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4626 if (spin_is_contended(pvmw->ptl))
4629 /* avoid taking the LRU lock under the PTL when possible */
4630 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4632 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4633 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4635 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4636 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4637 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4638 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4639 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4641 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4642 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4646 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4649 arch_enter_lazy_mmu_mode();
4651 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4654 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4658 if (!pte_young(pte[i]))
4661 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4665 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4666 VM_WARN_ON_ONCE(true);
4670 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4671 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4672 !folio_test_swapcache(folio)))
4673 folio_mark_dirty(folio);
4675 old_gen = folio_lru_gen(folio);
4677 folio_set_referenced(folio);
4678 else if (old_gen != new_gen)
4679 __set_bit(i, bitmap);
4682 arch_leave_lazy_mmu_mode();
4685 /* feedback from rmap walkers to page table walkers */
4686 if (suitable_to_scan(i, young))
4687 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4689 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4690 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4691 folio = pfn_folio(pte_pfn(pte[i]));
4692 folio_activate(folio);
4697 /* folio_update_gen() requires stable folio_memcg() */
4698 if (!mem_cgroup_trylock_pages(memcg))
4702 spin_lock_irq(&lruvec->lru_lock);
4703 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4706 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4707 folio = pfn_folio(pte_pfn(pte[i]));
4708 if (folio_memcg_rcu(folio) != memcg)
4711 old_gen = folio_update_gen(folio, new_gen);
4712 if (old_gen < 0 || old_gen == new_gen)
4716 update_batch_size(walk, folio, old_gen, new_gen);
4718 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
4722 spin_unlock_irq(&lruvec->lru_lock);
4724 mem_cgroup_unlock_pages();
4727 /******************************************************************************
4729 ******************************************************************************/
4731 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4734 int gen = folio_lru_gen(folio);
4735 int type = folio_is_file_lru(folio);
4736 int zone = folio_zonenum(folio);
4737 int delta = folio_nr_pages(folio);
4738 int refs = folio_lru_refs(folio);
4739 int tier = lru_tier_from_refs(refs);
4740 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4742 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4745 if (!folio_evictable(folio)) {
4746 success = lru_gen_del_folio(lruvec, folio, true);
4747 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4748 folio_set_unevictable(folio);
4749 lruvec_add_folio(lruvec, folio);
4750 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4754 /* dirty lazyfree */
4755 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4756 success = lru_gen_del_folio(lruvec, folio, true);
4757 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4758 folio_set_swapbacked(folio);
4759 lruvec_add_folio_tail(lruvec, folio);
4764 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4765 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4770 if (tier > tier_idx) {
4771 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4773 gen = folio_inc_gen(lruvec, folio, false);
4774 list_move_tail(&folio->lru, &lrugen->lists[gen][type][zone]);
4776 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4777 lrugen->protected[hist][type][tier - 1] + delta);
4778 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4782 /* waiting for writeback */
4783 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4784 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4785 gen = folio_inc_gen(lruvec, folio, true);
4786 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4793 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4797 /* unmapping inhibited */
4798 if (!sc->may_unmap && folio_mapped(folio))
4801 /* swapping inhibited */
4802 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4803 (folio_test_dirty(folio) ||
4804 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4807 /* raced with release_pages() */
4808 if (!folio_try_get(folio))
4811 /* raced with another isolation */
4812 if (!folio_test_clear_lru(folio)) {
4817 /* see the comment on MAX_NR_TIERS */
4818 if (!folio_test_referenced(folio))
4819 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4821 /* for shrink_folio_list() */
4822 folio_clear_reclaim(folio);
4823 folio_clear_referenced(folio);
4825 success = lru_gen_del_folio(lruvec, folio, true);
4826 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4831 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4832 int type, int tier, struct list_head *list)
4835 enum vm_event_item item;
4839 int remaining = MAX_LRU_BATCH;
4840 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4841 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4843 VM_WARN_ON_ONCE(!list_empty(list));
4845 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4848 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4850 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4853 struct list_head *head = &lrugen->lists[gen][type][zone];
4855 while (!list_empty(head)) {
4856 struct folio *folio = lru_to_folio(head);
4857 int delta = folio_nr_pages(folio);
4859 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4860 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4861 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4862 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4866 if (sort_folio(lruvec, folio, tier))
4868 else if (isolate_folio(lruvec, folio, sc)) {
4869 list_add(&folio->lru, list);
4872 list_move(&folio->lru, &moved);
4876 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4881 list_splice(&moved, head);
4882 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4885 if (!remaining || isolated >= MIN_LRU_BATCH)
4889 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4890 if (!cgroup_reclaim(sc)) {
4891 __count_vm_events(item, isolated);
4892 __count_vm_events(PGREFILL, sorted);
4894 __count_memcg_events(memcg, item, isolated);
4895 __count_memcg_events(memcg, PGREFILL, sorted);
4896 __count_vm_events(PGSCAN_ANON + type, isolated);
4899 * There might not be eligible pages due to reclaim_idx, may_unmap and
4900 * may_writepage. Check the remaining to prevent livelock if it's not
4903 return isolated || !remaining ? scanned : 0;
4906 static int get_tier_idx(struct lruvec *lruvec, int type)
4909 struct ctrl_pos sp, pv;
4912 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4913 * This value is chosen because any other tier would have at least twice
4914 * as many refaults as the first tier.
4916 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4917 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4918 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4919 if (!positive_ctrl_err(&sp, &pv))
4926 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4929 struct ctrl_pos sp, pv;
4930 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4933 * Compare the first tier of anon with that of file to determine which
4934 * type to scan. Also need to compare other tiers of the selected type
4935 * with the first tier of the other type to determine the last tier (of
4936 * the selected type) to evict.
4938 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4939 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4940 type = positive_ctrl_err(&sp, &pv);
4942 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4943 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4944 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4945 if (!positive_ctrl_err(&sp, &pv))
4949 *tier_idx = tier - 1;
4954 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4955 int *type_scanned, struct list_head *list)
4961 DEFINE_MIN_SEQ(lruvec);
4964 * Try to make the obvious choice first. When anon and file are both
4965 * available from the same generation, interpret swappiness 1 as file
4966 * first and 200 as anon first.
4969 type = LRU_GEN_FILE;
4970 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4971 type = LRU_GEN_ANON;
4972 else if (swappiness == 1)
4973 type = LRU_GEN_FILE;
4974 else if (swappiness == 200)
4975 type = LRU_GEN_ANON;
4977 type = get_type_to_scan(lruvec, swappiness, &tier);
4979 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4981 tier = get_tier_idx(lruvec, type);
4983 scanned = scan_folios(lruvec, sc, type, tier, list);
4991 *type_scanned = type;
4996 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4997 bool *need_swapping)
5004 struct folio *folio;
5006 enum vm_event_item item;
5007 struct reclaim_stat stat;
5008 struct lru_gen_mm_walk *walk;
5009 bool skip_retry = false;
5010 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5011 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5013 spin_lock_irq(&lruvec->lru_lock);
5015 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5017 scanned += try_to_inc_min_seq(lruvec, swappiness);
5019 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5022 spin_unlock_irq(&lruvec->lru_lock);
5024 if (list_empty(&list))
5027 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5028 sc->nr_reclaimed += reclaimed;
5030 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5031 if (!folio_evictable(folio)) {
5032 list_del(&folio->lru);
5033 folio_putback_lru(folio);
5037 if (folio_test_reclaim(folio) &&
5038 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5039 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5040 if (folio_test_workingset(folio))
5041 folio_set_referenced(folio);
5045 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5046 folio_mapped(folio) || folio_test_locked(folio) ||
5047 folio_test_dirty(folio) || folio_test_writeback(folio)) {
5048 /* don't add rejected folios to the oldest generation */
5049 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5054 /* retry folios that may have missed folio_rotate_reclaimable() */
5055 list_move(&folio->lru, &clean);
5056 sc->nr_scanned -= folio_nr_pages(folio);
5059 spin_lock_irq(&lruvec->lru_lock);
5061 move_folios_to_lru(lruvec, &list);
5063 walk = current->reclaim_state->mm_walk;
5064 if (walk && walk->batched)
5065 reset_batch_size(lruvec, walk);
5067 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
5068 if (!cgroup_reclaim(sc))
5069 __count_vm_events(item, reclaimed);
5070 __count_memcg_events(memcg, item, reclaimed);
5071 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5073 spin_unlock_irq(&lruvec->lru_lock);
5075 mem_cgroup_uncharge_list(&list);
5076 free_unref_page_list(&list);
5078 INIT_LIST_HEAD(&list);
5079 list_splice_init(&clean, &list);
5081 if (!list_empty(&list)) {
5086 if (need_swapping && type == LRU_GEN_ANON)
5087 *need_swapping = true;
5093 * For future optimizations:
5094 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5097 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
5098 bool can_swap, bool *need_aging)
5100 unsigned long nr_to_scan;
5101 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5102 DEFINE_MAX_SEQ(lruvec);
5103 DEFINE_MIN_SEQ(lruvec);
5105 if (mem_cgroup_below_min(memcg) ||
5106 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
5109 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
5113 /* skip the aging path at the default priority */
5114 if (sc->priority == DEF_PRIORITY)
5117 /* leave the work to lru_gen_age_node() */
5118 if (current_is_kswapd())
5121 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
5124 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
5127 static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
5128 struct scan_control *sc, bool need_swapping)
5131 DEFINE_MAX_SEQ(lruvec);
5133 if (!current_is_kswapd()) {
5134 /* age each memcg at most once to ensure fairness */
5135 if (max_seq - seq > 1)
5138 /* over-swapping can increase allocation latency */
5139 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
5142 /* give this thread a chance to exit and free its memory */
5143 if (fatal_signal_pending(current)) {
5144 sc->nr_reclaimed += MIN_LRU_BATCH;
5148 if (cgroup_reclaim(sc))
5150 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
5153 /* keep scanning at low priorities to ensure fairness */
5154 if (sc->priority > DEF_PRIORITY - 2)
5158 * A minimum amount of work was done under global memory pressure. For
5159 * kswapd, it may be overshooting. For direct reclaim, the allocation
5160 * may succeed if all suitable zones are somewhat safe. In either case,
5161 * it's better to stop now, and restart later if necessary.
5163 for (i = 0; i <= sc->reclaim_idx; i++) {
5164 unsigned long wmark;
5165 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
5167 if (!managed_zone(zone))
5170 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
5171 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
5175 sc->nr_reclaimed += MIN_LRU_BATCH;
5180 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5182 struct blk_plug plug;
5183 bool need_aging = false;
5184 bool need_swapping = false;
5185 unsigned long scanned = 0;
5186 unsigned long reclaimed = sc->nr_reclaimed;
5187 DEFINE_MAX_SEQ(lruvec);
5191 blk_start_plug(&plug);
5193 set_mm_walk(lruvec_pgdat(lruvec));
5198 unsigned long nr_to_scan;
5201 swappiness = get_swappiness(lruvec, sc);
5202 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
5207 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
5211 delta = evict_folios(lruvec, sc, swappiness, &need_swapping);
5216 if (scanned >= nr_to_scan)
5219 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
5225 /* see the comment in lru_gen_age_node() */
5226 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
5227 sc->memcgs_need_aging = false;
5231 blk_finish_plug(&plug);
5234 /******************************************************************************
5236 ******************************************************************************/
5238 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5240 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5242 if (lrugen->enabled) {
5245 for_each_evictable_lru(lru) {
5246 if (!list_empty(&lruvec->lists[lru]))
5250 int gen, type, zone;
5252 for_each_gen_type_zone(gen, type, zone) {
5253 if (!list_empty(&lrugen->lists[gen][type][zone]))
5261 static bool fill_evictable(struct lruvec *lruvec)
5264 int remaining = MAX_LRU_BATCH;
5266 for_each_evictable_lru(lru) {
5267 int type = is_file_lru(lru);
5268 bool active = is_active_lru(lru);
5269 struct list_head *head = &lruvec->lists[lru];
5271 while (!list_empty(head)) {
5273 struct folio *folio = lru_to_folio(head);
5275 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5276 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5277 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5278 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5280 lruvec_del_folio(lruvec, folio);
5281 success = lru_gen_add_folio(lruvec, folio, false);
5282 VM_WARN_ON_ONCE(!success);
5292 static bool drain_evictable(struct lruvec *lruvec)
5294 int gen, type, zone;
5295 int remaining = MAX_LRU_BATCH;
5297 for_each_gen_type_zone(gen, type, zone) {
5298 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5300 while (!list_empty(head)) {
5302 struct folio *folio = lru_to_folio(head);
5304 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5305 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5306 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5307 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5309 success = lru_gen_del_folio(lruvec, folio, false);
5310 VM_WARN_ON_ONCE(!success);
5311 lruvec_add_folio(lruvec, folio);
5321 static void lru_gen_change_state(bool enabled)
5323 static DEFINE_MUTEX(state_mutex);
5325 struct mem_cgroup *memcg;
5330 mutex_lock(&state_mutex);
5332 if (enabled == lru_gen_enabled())
5336 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5338 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5340 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5344 for_each_node(nid) {
5345 struct lruvec *lruvec = get_lruvec(memcg, nid);
5350 spin_lock_irq(&lruvec->lru_lock);
5352 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5353 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5355 lruvec->lrugen.enabled = enabled;
5357 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5358 spin_unlock_irq(&lruvec->lru_lock);
5360 spin_lock_irq(&lruvec->lru_lock);
5363 spin_unlock_irq(&lruvec->lru_lock);
5367 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5369 mutex_unlock(&state_mutex);
5375 /******************************************************************************
5377 ******************************************************************************/
5379 static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5381 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5384 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5385 static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5386 const char *buf, size_t len)
5390 if (kstrtouint(buf, 0, &msecs))
5393 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5398 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5399 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5402 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5404 unsigned int caps = 0;
5406 if (get_cap(LRU_GEN_CORE))
5407 caps |= BIT(LRU_GEN_CORE);
5409 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5410 caps |= BIT(LRU_GEN_MM_WALK);
5412 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5413 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5415 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5418 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5419 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5420 const char *buf, size_t len)
5425 if (tolower(*buf) == 'n')
5427 else if (tolower(*buf) == 'y')
5429 else if (kstrtouint(buf, 0, &caps))
5432 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5433 bool enabled = caps & BIT(i);
5435 if (i == LRU_GEN_CORE)
5436 lru_gen_change_state(enabled);
5438 static_branch_enable(&lru_gen_caps[i]);
5440 static_branch_disable(&lru_gen_caps[i]);
5446 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5447 enabled, 0644, show_enabled, store_enabled
5450 static struct attribute *lru_gen_attrs[] = {
5451 &lru_gen_min_ttl_attr.attr,
5452 &lru_gen_enabled_attr.attr,
5456 static struct attribute_group lru_gen_attr_group = {
5458 .attrs = lru_gen_attrs,
5461 /******************************************************************************
5463 ******************************************************************************/
5465 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5467 struct mem_cgroup *memcg;
5468 loff_t nr_to_skip = *pos;
5470 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5472 return ERR_PTR(-ENOMEM);
5474 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5478 for_each_node_state(nid, N_MEMORY) {
5480 return get_lruvec(memcg, nid);
5482 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5487 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5489 if (!IS_ERR_OR_NULL(v))
5490 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5496 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5498 int nid = lruvec_pgdat(v)->node_id;
5499 struct mem_cgroup *memcg = lruvec_memcg(v);
5503 nid = next_memory_node(nid);
5504 if (nid == MAX_NUMNODES) {
5505 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5509 nid = first_memory_node;
5512 return get_lruvec(memcg, nid);
5515 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5516 unsigned long max_seq, unsigned long *min_seq,
5521 int hist = lru_hist_from_seq(seq);
5522 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5524 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5525 seq_printf(m, " %10d", tier);
5526 for (type = 0; type < ANON_AND_FILE; type++) {
5527 const char *s = " ";
5528 unsigned long n[3] = {};
5530 if (seq == max_seq) {
5532 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5533 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5534 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5536 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5537 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5539 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5542 for (i = 0; i < 3; i++)
5543 seq_printf(m, " %10lu%c", n[i], s[i]);
5549 for (i = 0; i < NR_MM_STATS; i++) {
5550 const char *s = " ";
5551 unsigned long n = 0;
5553 if (seq == max_seq && NR_HIST_GENS == 1) {
5555 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5556 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5558 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5561 seq_printf(m, " %10lu%c", n, s[i]);
5566 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5567 static int lru_gen_seq_show(struct seq_file *m, void *v)
5570 bool full = !debugfs_real_fops(m->file)->write;
5571 struct lruvec *lruvec = v;
5572 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5573 int nid = lruvec_pgdat(lruvec)->node_id;
5574 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5575 DEFINE_MAX_SEQ(lruvec);
5576 DEFINE_MIN_SEQ(lruvec);
5578 if (nid == first_memory_node) {
5579 const char *path = memcg ? m->private : "";
5583 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5585 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5588 seq_printf(m, " node %5d\n", nid);
5591 seq = min_seq[LRU_GEN_ANON];
5592 else if (max_seq >= MAX_NR_GENS)
5593 seq = max_seq - MAX_NR_GENS + 1;
5597 for (; seq <= max_seq; seq++) {
5599 int gen = lru_gen_from_seq(seq);
5600 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5602 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5604 for (type = 0; type < ANON_AND_FILE; type++) {
5605 unsigned long size = 0;
5606 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5608 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5609 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5611 seq_printf(m, " %10lu%c", size, mark);
5617 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5623 static const struct seq_operations lru_gen_seq_ops = {
5624 .start = lru_gen_seq_start,
5625 .stop = lru_gen_seq_stop,
5626 .next = lru_gen_seq_next,
5627 .show = lru_gen_seq_show,
5630 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5631 bool can_swap, bool force_scan)
5633 DEFINE_MAX_SEQ(lruvec);
5634 DEFINE_MIN_SEQ(lruvec);
5642 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5645 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5650 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5651 int swappiness, unsigned long nr_to_reclaim)
5653 DEFINE_MAX_SEQ(lruvec);
5655 if (seq + MIN_NR_GENS > max_seq)
5658 sc->nr_reclaimed = 0;
5660 while (!signal_pending(current)) {
5661 DEFINE_MIN_SEQ(lruvec);
5663 if (seq < min_seq[!swappiness])
5666 if (sc->nr_reclaimed >= nr_to_reclaim)
5669 if (!evict_folios(lruvec, sc, swappiness, NULL))
5678 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5679 struct scan_control *sc, int swappiness, unsigned long opt)
5681 struct lruvec *lruvec;
5683 struct mem_cgroup *memcg = NULL;
5685 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5688 if (!mem_cgroup_disabled()) {
5690 memcg = mem_cgroup_from_id(memcg_id);
5692 if (memcg && !css_tryget(&memcg->css))
5701 if (memcg_id != mem_cgroup_id(memcg))
5704 lruvec = get_lruvec(memcg, nid);
5707 swappiness = get_swappiness(lruvec, sc);
5708 else if (swappiness > 200)
5713 err = run_aging(lruvec, seq, sc, swappiness, opt);
5716 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5720 mem_cgroup_put(memcg);
5725 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5726 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5727 size_t len, loff_t *pos)
5732 struct blk_plug plug;
5734 struct scan_control sc = {
5735 .may_writepage = true,
5738 .reclaim_idx = MAX_NR_ZONES - 1,
5739 .gfp_mask = GFP_KERNEL,
5742 buf = kvmalloc(len + 1, GFP_KERNEL);
5746 if (copy_from_user(buf, src, len)) {
5751 set_task_reclaim_state(current, &sc.reclaim_state);
5752 flags = memalloc_noreclaim_save();
5753 blk_start_plug(&plug);
5754 if (!set_mm_walk(NULL)) {
5762 while ((cur = strsep(&next, ",;\n"))) {
5766 unsigned int memcg_id;
5769 unsigned int swappiness = -1;
5770 unsigned long opt = -1;
5772 cur = skip_spaces(cur);
5776 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5777 &seq, &end, &swappiness, &end, &opt, &end);
5778 if (n < 4 || cur[end]) {
5783 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5789 blk_finish_plug(&plug);
5790 memalloc_noreclaim_restore(flags);
5791 set_task_reclaim_state(current, NULL);
5798 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5800 return seq_open(file, &lru_gen_seq_ops);
5803 static const struct file_operations lru_gen_rw_fops = {
5804 .open = lru_gen_seq_open,
5806 .write = lru_gen_seq_write,
5807 .llseek = seq_lseek,
5808 .release = seq_release,
5811 static const struct file_operations lru_gen_ro_fops = {
5812 .open = lru_gen_seq_open,
5814 .llseek = seq_lseek,
5815 .release = seq_release,
5818 /******************************************************************************
5820 ******************************************************************************/
5822 void lru_gen_init_lruvec(struct lruvec *lruvec)
5825 int gen, type, zone;
5826 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5828 lrugen->max_seq = MIN_NR_GENS + 1;
5829 lrugen->enabled = lru_gen_enabled();
5831 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5832 lrugen->timestamps[i] = jiffies;
5834 for_each_gen_type_zone(gen, type, zone)
5835 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
5837 lruvec->mm_state.seq = MIN_NR_GENS;
5838 init_waitqueue_head(&lruvec->mm_state.wait);
5842 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5844 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5845 spin_lock_init(&memcg->mm_list.lock);
5848 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5853 for_each_node(nid) {
5854 struct lruvec *lruvec = get_lruvec(memcg, nid);
5856 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5857 sizeof(lruvec->lrugen.nr_pages)));
5859 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5860 bitmap_free(lruvec->mm_state.filters[i]);
5861 lruvec->mm_state.filters[i] = NULL;
5867 static int __init init_lru_gen(void)
5869 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5870 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5872 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5873 pr_err("lru_gen: failed to create sysfs group\n");
5875 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5876 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5880 late_initcall(init_lru_gen);
5882 #else /* !CONFIG_LRU_GEN */
5884 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5888 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5892 #endif /* CONFIG_LRU_GEN */
5894 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5896 unsigned long nr[NR_LRU_LISTS];
5897 unsigned long targets[NR_LRU_LISTS];
5898 unsigned long nr_to_scan;
5900 unsigned long nr_reclaimed = 0;
5901 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5902 bool proportional_reclaim;
5903 struct blk_plug plug;
5905 if (lru_gen_enabled()) {
5906 lru_gen_shrink_lruvec(lruvec, sc);
5910 get_scan_count(lruvec, sc, nr);
5912 /* Record the original scan target for proportional adjustments later */
5913 memcpy(targets, nr, sizeof(nr));
5916 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5917 * event that can occur when there is little memory pressure e.g.
5918 * multiple streaming readers/writers. Hence, we do not abort scanning
5919 * when the requested number of pages are reclaimed when scanning at
5920 * DEF_PRIORITY on the assumption that the fact we are direct
5921 * reclaiming implies that kswapd is not keeping up and it is best to
5922 * do a batch of work at once. For memcg reclaim one check is made to
5923 * abort proportional reclaim if either the file or anon lru has already
5924 * dropped to zero at the first pass.
5926 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5927 sc->priority == DEF_PRIORITY);
5929 blk_start_plug(&plug);
5930 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5931 nr[LRU_INACTIVE_FILE]) {
5932 unsigned long nr_anon, nr_file, percentage;
5933 unsigned long nr_scanned;
5935 for_each_evictable_lru(lru) {
5937 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5938 nr[lru] -= nr_to_scan;
5940 nr_reclaimed += shrink_list(lru, nr_to_scan,
5947 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5951 * For kswapd and memcg, reclaim at least the number of pages
5952 * requested. Ensure that the anon and file LRUs are scanned
5953 * proportionally what was requested by get_scan_count(). We
5954 * stop reclaiming one LRU and reduce the amount scanning
5955 * proportional to the original scan target.
5957 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5958 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5961 * It's just vindictive to attack the larger once the smaller
5962 * has gone to zero. And given the way we stop scanning the
5963 * smaller below, this makes sure that we only make one nudge
5964 * towards proportionality once we've got nr_to_reclaim.
5966 if (!nr_file || !nr_anon)
5969 if (nr_file > nr_anon) {
5970 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5971 targets[LRU_ACTIVE_ANON] + 1;
5973 percentage = nr_anon * 100 / scan_target;
5975 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5976 targets[LRU_ACTIVE_FILE] + 1;
5978 percentage = nr_file * 100 / scan_target;
5981 /* Stop scanning the smaller of the LRU */
5983 nr[lru + LRU_ACTIVE] = 0;
5986 * Recalculate the other LRU scan count based on its original
5987 * scan target and the percentage scanning already complete
5989 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5990 nr_scanned = targets[lru] - nr[lru];
5991 nr[lru] = targets[lru] * (100 - percentage) / 100;
5992 nr[lru] -= min(nr[lru], nr_scanned);
5995 nr_scanned = targets[lru] - nr[lru];
5996 nr[lru] = targets[lru] * (100 - percentage) / 100;
5997 nr[lru] -= min(nr[lru], nr_scanned);
5999 blk_finish_plug(&plug);
6000 sc->nr_reclaimed += nr_reclaimed;
6003 * Even if we did not try to evict anon pages at all, we want to
6004 * rebalance the anon lru active/inactive ratio.
6006 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6007 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6008 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6009 sc, LRU_ACTIVE_ANON);
6012 /* Use reclaim/compaction for costly allocs or under memory pressure */
6013 static bool in_reclaim_compaction(struct scan_control *sc)
6015 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
6016 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
6017 sc->priority < DEF_PRIORITY - 2))
6024 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6025 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6026 * true if more pages should be reclaimed such that when the page allocator
6027 * calls try_to_compact_pages() that it will have enough free pages to succeed.
6028 * It will give up earlier than that if there is difficulty reclaiming pages.
6030 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
6031 unsigned long nr_reclaimed,
6032 struct scan_control *sc)
6034 unsigned long pages_for_compaction;
6035 unsigned long inactive_lru_pages;
6038 /* If not in reclaim/compaction mode, stop */
6039 if (!in_reclaim_compaction(sc))
6043 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6044 * number of pages that were scanned. This will return to the caller
6045 * with the risk reclaim/compaction and the resulting allocation attempt
6046 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6047 * allocations through requiring that the full LRU list has been scanned
6048 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6049 * scan, but that approximation was wrong, and there were corner cases
6050 * where always a non-zero amount of pages were scanned.
6055 /* If compaction would go ahead or the allocation would succeed, stop */
6056 for (z = 0; z <= sc->reclaim_idx; z++) {
6057 struct zone *zone = &pgdat->node_zones[z];
6058 if (!managed_zone(zone))
6061 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6062 case COMPACT_SUCCESS:
6063 case COMPACT_CONTINUE:
6066 /* check next zone */
6072 * If we have not reclaimed enough pages for compaction and the
6073 * inactive lists are large enough, continue reclaiming
6075 pages_for_compaction = compact_gap(sc->order);
6076 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6077 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6078 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6080 return inactive_lru_pages > pages_for_compaction;
6083 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6085 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6086 struct mem_cgroup *memcg;
6088 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6090 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6091 unsigned long reclaimed;
6092 unsigned long scanned;
6095 * This loop can become CPU-bound when target memcgs
6096 * aren't eligible for reclaim - either because they
6097 * don't have any reclaimable pages, or because their
6098 * memory is explicitly protected. Avoid soft lockups.
6102 mem_cgroup_calculate_protection(target_memcg, memcg);
6104 if (mem_cgroup_below_min(memcg)) {
6107 * If there is no reclaimable memory, OOM.
6110 } else if (mem_cgroup_below_low(memcg)) {
6113 * Respect the protection only as long as
6114 * there is an unprotected supply
6115 * of reclaimable memory from other cgroups.
6117 if (!sc->memcg_low_reclaim) {
6118 sc->memcg_low_skipped = 1;
6121 memcg_memory_event(memcg, MEMCG_LOW);
6124 reclaimed = sc->nr_reclaimed;
6125 scanned = sc->nr_scanned;
6127 shrink_lruvec(lruvec, sc);
6129 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6132 /* Record the group's reclaim efficiency */
6134 vmpressure(sc->gfp_mask, memcg, false,
6135 sc->nr_scanned - scanned,
6136 sc->nr_reclaimed - reclaimed);
6138 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6141 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6143 struct reclaim_state *reclaim_state = current->reclaim_state;
6144 unsigned long nr_reclaimed, nr_scanned;
6145 struct lruvec *target_lruvec;
6146 bool reclaimable = false;
6148 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6151 memset(&sc->nr, 0, sizeof(sc->nr));
6153 nr_reclaimed = sc->nr_reclaimed;
6154 nr_scanned = sc->nr_scanned;
6156 prepare_scan_count(pgdat, sc);
6158 shrink_node_memcgs(pgdat, sc);
6160 if (reclaim_state) {
6161 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6162 reclaim_state->reclaimed_slab = 0;
6165 /* Record the subtree's reclaim efficiency */
6167 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6168 sc->nr_scanned - nr_scanned,
6169 sc->nr_reclaimed - nr_reclaimed);
6171 if (sc->nr_reclaimed - nr_reclaimed)
6174 if (current_is_kswapd()) {
6176 * If reclaim is isolating dirty pages under writeback,
6177 * it implies that the long-lived page allocation rate
6178 * is exceeding the page laundering rate. Either the
6179 * global limits are not being effective at throttling
6180 * processes due to the page distribution throughout
6181 * zones or there is heavy usage of a slow backing
6182 * device. The only option is to throttle from reclaim
6183 * context which is not ideal as there is no guarantee
6184 * the dirtying process is throttled in the same way
6185 * balance_dirty_pages() manages.
6187 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6188 * count the number of pages under pages flagged for
6189 * immediate reclaim and stall if any are encountered
6190 * in the nr_immediate check below.
6192 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6193 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6195 /* Allow kswapd to start writing pages during reclaim.*/
6196 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6197 set_bit(PGDAT_DIRTY, &pgdat->flags);
6200 * If kswapd scans pages marked for immediate
6201 * reclaim and under writeback (nr_immediate), it
6202 * implies that pages are cycling through the LRU
6203 * faster than they are written so forcibly stall
6204 * until some pages complete writeback.
6206 if (sc->nr.immediate)
6207 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6211 * Tag a node/memcg as congested if all the dirty pages were marked
6212 * for writeback and immediate reclaim (counted in nr.congested).
6214 * Legacy memcg will stall in page writeback so avoid forcibly
6215 * stalling in reclaim_throttle().
6217 if ((current_is_kswapd() ||
6218 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6219 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6220 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6223 * Stall direct reclaim for IO completions if the lruvec is
6224 * node is congested. Allow kswapd to continue until it
6225 * starts encountering unqueued dirty pages or cycling through
6226 * the LRU too quickly.
6228 if (!current_is_kswapd() && current_may_throttle() &&
6229 !sc->hibernation_mode &&
6230 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6231 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6233 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6238 * Kswapd gives up on balancing particular nodes after too
6239 * many failures to reclaim anything from them and goes to
6240 * sleep. On reclaim progress, reset the failure counter. A
6241 * successful direct reclaim run will revive a dormant kswapd.
6244 pgdat->kswapd_failures = 0;
6248 * Returns true if compaction should go ahead for a costly-order request, or
6249 * the allocation would already succeed without compaction. Return false if we
6250 * should reclaim first.
6252 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6254 unsigned long watermark;
6255 enum compact_result suitable;
6257 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6258 if (suitable == COMPACT_SUCCESS)
6259 /* Allocation should succeed already. Don't reclaim. */
6261 if (suitable == COMPACT_SKIPPED)
6262 /* Compaction cannot yet proceed. Do reclaim. */
6266 * Compaction is already possible, but it takes time to run and there
6267 * are potentially other callers using the pages just freed. So proceed
6268 * with reclaim to make a buffer of free pages available to give
6269 * compaction a reasonable chance of completing and allocating the page.
6270 * Note that we won't actually reclaim the whole buffer in one attempt
6271 * as the target watermark in should_continue_reclaim() is lower. But if
6272 * we are already above the high+gap watermark, don't reclaim at all.
6274 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6276 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6279 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6282 * If reclaim is making progress greater than 12% efficiency then
6283 * wake all the NOPROGRESS throttled tasks.
6285 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6286 wait_queue_head_t *wqh;
6288 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6289 if (waitqueue_active(wqh))
6296 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6297 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6298 * under writeback and marked for immediate reclaim at the tail of the
6301 if (current_is_kswapd() || cgroup_reclaim(sc))
6304 /* Throttle if making no progress at high prioities. */
6305 if (sc->priority == 1 && !sc->nr_reclaimed)
6306 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6310 * This is the direct reclaim path, for page-allocating processes. We only
6311 * try to reclaim pages from zones which will satisfy the caller's allocation
6314 * If a zone is deemed to be full of pinned pages then just give it a light
6315 * scan then give up on it.
6317 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6321 unsigned long nr_soft_reclaimed;
6322 unsigned long nr_soft_scanned;
6324 pg_data_t *last_pgdat = NULL;
6325 pg_data_t *first_pgdat = NULL;
6328 * If the number of buffer_heads in the machine exceeds the maximum
6329 * allowed level, force direct reclaim to scan the highmem zone as
6330 * highmem pages could be pinning lowmem pages storing buffer_heads
6332 orig_mask = sc->gfp_mask;
6333 if (buffer_heads_over_limit) {
6334 sc->gfp_mask |= __GFP_HIGHMEM;
6335 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6338 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6339 sc->reclaim_idx, sc->nodemask) {
6341 * Take care memory controller reclaiming has small influence
6344 if (!cgroup_reclaim(sc)) {
6345 if (!cpuset_zone_allowed(zone,
6346 GFP_KERNEL | __GFP_HARDWALL))
6350 * If we already have plenty of memory free for
6351 * compaction in this zone, don't free any more.
6352 * Even though compaction is invoked for any
6353 * non-zero order, only frequent costly order
6354 * reclamation is disruptive enough to become a
6355 * noticeable problem, like transparent huge
6358 if (IS_ENABLED(CONFIG_COMPACTION) &&
6359 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6360 compaction_ready(zone, sc)) {
6361 sc->compaction_ready = true;
6366 * Shrink each node in the zonelist once. If the
6367 * zonelist is ordered by zone (not the default) then a
6368 * node may be shrunk multiple times but in that case
6369 * the user prefers lower zones being preserved.
6371 if (zone->zone_pgdat == last_pgdat)
6375 * This steals pages from memory cgroups over softlimit
6376 * and returns the number of reclaimed pages and
6377 * scanned pages. This works for global memory pressure
6378 * and balancing, not for a memcg's limit.
6380 nr_soft_scanned = 0;
6381 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6382 sc->order, sc->gfp_mask,
6384 sc->nr_reclaimed += nr_soft_reclaimed;
6385 sc->nr_scanned += nr_soft_scanned;
6386 /* need some check for avoid more shrink_zone() */
6390 first_pgdat = zone->zone_pgdat;
6392 /* See comment about same check for global reclaim above */
6393 if (zone->zone_pgdat == last_pgdat)
6395 last_pgdat = zone->zone_pgdat;
6396 shrink_node(zone->zone_pgdat, sc);
6400 consider_reclaim_throttle(first_pgdat, sc);
6403 * Restore to original mask to avoid the impact on the caller if we
6404 * promoted it to __GFP_HIGHMEM.
6406 sc->gfp_mask = orig_mask;
6409 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6411 struct lruvec *target_lruvec;
6412 unsigned long refaults;
6414 if (lru_gen_enabled())
6417 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6418 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6419 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6420 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6421 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6425 * This is the main entry point to direct page reclaim.
6427 * If a full scan of the inactive list fails to free enough memory then we
6428 * are "out of memory" and something needs to be killed.
6430 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6431 * high - the zone may be full of dirty or under-writeback pages, which this
6432 * caller can't do much about. We kick the writeback threads and take explicit
6433 * naps in the hope that some of these pages can be written. But if the
6434 * allocating task holds filesystem locks which prevent writeout this might not
6435 * work, and the allocation attempt will fail.
6437 * returns: 0, if no pages reclaimed
6438 * else, the number of pages reclaimed
6440 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6441 struct scan_control *sc)
6443 int initial_priority = sc->priority;
6444 pg_data_t *last_pgdat;
6448 delayacct_freepages_start();
6450 if (!cgroup_reclaim(sc))
6451 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6455 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6458 shrink_zones(zonelist, sc);
6460 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6463 if (sc->compaction_ready)
6467 * If we're getting trouble reclaiming, start doing
6468 * writepage even in laptop mode.
6470 if (sc->priority < DEF_PRIORITY - 2)
6471 sc->may_writepage = 1;
6472 } while (--sc->priority >= 0);
6475 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6477 if (zone->zone_pgdat == last_pgdat)
6479 last_pgdat = zone->zone_pgdat;
6481 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6483 if (cgroup_reclaim(sc)) {
6484 struct lruvec *lruvec;
6486 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6488 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6492 delayacct_freepages_end();
6494 if (sc->nr_reclaimed)
6495 return sc->nr_reclaimed;
6497 /* Aborted reclaim to try compaction? don't OOM, then */
6498 if (sc->compaction_ready)
6502 * We make inactive:active ratio decisions based on the node's
6503 * composition of memory, but a restrictive reclaim_idx or a
6504 * memory.low cgroup setting can exempt large amounts of
6505 * memory from reclaim. Neither of which are very common, so
6506 * instead of doing costly eligibility calculations of the
6507 * entire cgroup subtree up front, we assume the estimates are
6508 * good, and retry with forcible deactivation if that fails.
6510 if (sc->skipped_deactivate) {
6511 sc->priority = initial_priority;
6512 sc->force_deactivate = 1;
6513 sc->skipped_deactivate = 0;
6517 /* Untapped cgroup reserves? Don't OOM, retry. */
6518 if (sc->memcg_low_skipped) {
6519 sc->priority = initial_priority;
6520 sc->force_deactivate = 0;
6521 sc->memcg_low_reclaim = 1;
6522 sc->memcg_low_skipped = 0;
6529 static bool allow_direct_reclaim(pg_data_t *pgdat)
6532 unsigned long pfmemalloc_reserve = 0;
6533 unsigned long free_pages = 0;
6537 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6540 for (i = 0; i <= ZONE_NORMAL; i++) {
6541 zone = &pgdat->node_zones[i];
6542 if (!managed_zone(zone))
6545 if (!zone_reclaimable_pages(zone))
6548 pfmemalloc_reserve += min_wmark_pages(zone);
6549 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6552 /* If there are no reserves (unexpected config) then do not throttle */
6553 if (!pfmemalloc_reserve)
6556 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6558 /* kswapd must be awake if processes are being throttled */
6559 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6560 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6561 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6563 wake_up_interruptible(&pgdat->kswapd_wait);
6570 * Throttle direct reclaimers if backing storage is backed by the network
6571 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6572 * depleted. kswapd will continue to make progress and wake the processes
6573 * when the low watermark is reached.
6575 * Returns true if a fatal signal was delivered during throttling. If this
6576 * happens, the page allocator should not consider triggering the OOM killer.
6578 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6579 nodemask_t *nodemask)
6583 pg_data_t *pgdat = NULL;
6586 * Kernel threads should not be throttled as they may be indirectly
6587 * responsible for cleaning pages necessary for reclaim to make forward
6588 * progress. kjournald for example may enter direct reclaim while
6589 * committing a transaction where throttling it could forcing other
6590 * processes to block on log_wait_commit().
6592 if (current->flags & PF_KTHREAD)
6596 * If a fatal signal is pending, this process should not throttle.
6597 * It should return quickly so it can exit and free its memory
6599 if (fatal_signal_pending(current))
6603 * Check if the pfmemalloc reserves are ok by finding the first node
6604 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6605 * GFP_KERNEL will be required for allocating network buffers when
6606 * swapping over the network so ZONE_HIGHMEM is unusable.
6608 * Throttling is based on the first usable node and throttled processes
6609 * wait on a queue until kswapd makes progress and wakes them. There
6610 * is an affinity then between processes waking up and where reclaim
6611 * progress has been made assuming the process wakes on the same node.
6612 * More importantly, processes running on remote nodes will not compete
6613 * for remote pfmemalloc reserves and processes on different nodes
6614 * should make reasonable progress.
6616 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6617 gfp_zone(gfp_mask), nodemask) {
6618 if (zone_idx(zone) > ZONE_NORMAL)
6621 /* Throttle based on the first usable node */
6622 pgdat = zone->zone_pgdat;
6623 if (allow_direct_reclaim(pgdat))
6628 /* If no zone was usable by the allocation flags then do not throttle */
6632 /* Account for the throttling */
6633 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6636 * If the caller cannot enter the filesystem, it's possible that it
6637 * is due to the caller holding an FS lock or performing a journal
6638 * transaction in the case of a filesystem like ext[3|4]. In this case,
6639 * it is not safe to block on pfmemalloc_wait as kswapd could be
6640 * blocked waiting on the same lock. Instead, throttle for up to a
6641 * second before continuing.
6643 if (!(gfp_mask & __GFP_FS))
6644 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6645 allow_direct_reclaim(pgdat), HZ);
6647 /* Throttle until kswapd wakes the process */
6648 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6649 allow_direct_reclaim(pgdat));
6651 if (fatal_signal_pending(current))
6658 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6659 gfp_t gfp_mask, nodemask_t *nodemask)
6661 unsigned long nr_reclaimed;
6662 struct scan_control sc = {
6663 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6664 .gfp_mask = current_gfp_context(gfp_mask),
6665 .reclaim_idx = gfp_zone(gfp_mask),
6667 .nodemask = nodemask,
6668 .priority = DEF_PRIORITY,
6669 .may_writepage = !laptop_mode,
6675 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6676 * Confirm they are large enough for max values.
6678 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6679 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6680 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6683 * Do not enter reclaim if fatal signal was delivered while throttled.
6684 * 1 is returned so that the page allocator does not OOM kill at this
6687 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6690 set_task_reclaim_state(current, &sc.reclaim_state);
6691 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6693 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6695 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6696 set_task_reclaim_state(current, NULL);
6698 return nr_reclaimed;
6703 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6704 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6705 gfp_t gfp_mask, bool noswap,
6707 unsigned long *nr_scanned)
6709 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6710 struct scan_control sc = {
6711 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6712 .target_mem_cgroup = memcg,
6713 .may_writepage = !laptop_mode,
6715 .reclaim_idx = MAX_NR_ZONES - 1,
6716 .may_swap = !noswap,
6719 WARN_ON_ONCE(!current->reclaim_state);
6721 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6722 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6724 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6728 * NOTE: Although we can get the priority field, using it
6729 * here is not a good idea, since it limits the pages we can scan.
6730 * if we don't reclaim here, the shrink_node from balance_pgdat
6731 * will pick up pages from other mem cgroup's as well. We hack
6732 * the priority and make it zero.
6734 shrink_lruvec(lruvec, &sc);
6736 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6738 *nr_scanned = sc.nr_scanned;
6740 return sc.nr_reclaimed;
6743 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6744 unsigned long nr_pages,
6746 unsigned int reclaim_options)
6748 unsigned long nr_reclaimed;
6749 unsigned int noreclaim_flag;
6750 struct scan_control sc = {
6751 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6752 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6753 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6754 .reclaim_idx = MAX_NR_ZONES - 1,
6755 .target_mem_cgroup = memcg,
6756 .priority = DEF_PRIORITY,
6757 .may_writepage = !laptop_mode,
6759 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6760 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6763 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6764 * equal pressure on all the nodes. This is based on the assumption that
6765 * the reclaim does not bail out early.
6767 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6769 set_task_reclaim_state(current, &sc.reclaim_state);
6770 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6771 noreclaim_flag = memalloc_noreclaim_save();
6773 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6775 memalloc_noreclaim_restore(noreclaim_flag);
6776 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6777 set_task_reclaim_state(current, NULL);
6779 return nr_reclaimed;
6783 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6785 struct mem_cgroup *memcg;
6786 struct lruvec *lruvec;
6788 if (lru_gen_enabled()) {
6789 lru_gen_age_node(pgdat, sc);
6793 if (!can_age_anon_pages(pgdat, sc))
6796 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6797 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6800 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6802 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6803 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6804 sc, LRU_ACTIVE_ANON);
6805 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6809 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6815 * Check for watermark boosts top-down as the higher zones
6816 * are more likely to be boosted. Both watermarks and boosts
6817 * should not be checked at the same time as reclaim would
6818 * start prematurely when there is no boosting and a lower
6821 for (i = highest_zoneidx; i >= 0; i--) {
6822 zone = pgdat->node_zones + i;
6823 if (!managed_zone(zone))
6826 if (zone->watermark_boost)
6834 * Returns true if there is an eligible zone balanced for the request order
6835 * and highest_zoneidx
6837 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6840 unsigned long mark = -1;
6844 * Check watermarks bottom-up as lower zones are more likely to
6847 for (i = 0; i <= highest_zoneidx; i++) {
6848 zone = pgdat->node_zones + i;
6850 if (!managed_zone(zone))
6853 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6854 mark = wmark_pages(zone, WMARK_PROMO);
6856 mark = high_wmark_pages(zone);
6857 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6862 * If a node has no managed zone within highest_zoneidx, it does not
6863 * need balancing by definition. This can happen if a zone-restricted
6864 * allocation tries to wake a remote kswapd.
6872 /* Clear pgdat state for congested, dirty or under writeback. */
6873 static void clear_pgdat_congested(pg_data_t *pgdat)
6875 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6877 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6878 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6879 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6883 * Prepare kswapd for sleeping. This verifies that there are no processes
6884 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6886 * Returns true if kswapd is ready to sleep
6888 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6889 int highest_zoneidx)
6892 * The throttled processes are normally woken up in balance_pgdat() as
6893 * soon as allow_direct_reclaim() is true. But there is a potential
6894 * race between when kswapd checks the watermarks and a process gets
6895 * throttled. There is also a potential race if processes get
6896 * throttled, kswapd wakes, a large process exits thereby balancing the
6897 * zones, which causes kswapd to exit balance_pgdat() before reaching
6898 * the wake up checks. If kswapd is going to sleep, no process should
6899 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6900 * the wake up is premature, processes will wake kswapd and get
6901 * throttled again. The difference from wake ups in balance_pgdat() is
6902 * that here we are under prepare_to_wait().
6904 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6905 wake_up_all(&pgdat->pfmemalloc_wait);
6907 /* Hopeless node, leave it to direct reclaim */
6908 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6911 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6912 clear_pgdat_congested(pgdat);
6920 * kswapd shrinks a node of pages that are at or below the highest usable
6921 * zone that is currently unbalanced.
6923 * Returns true if kswapd scanned at least the requested number of pages to
6924 * reclaim or if the lack of progress was due to pages under writeback.
6925 * This is used to determine if the scanning priority needs to be raised.
6927 static bool kswapd_shrink_node(pg_data_t *pgdat,
6928 struct scan_control *sc)
6933 /* Reclaim a number of pages proportional to the number of zones */
6934 sc->nr_to_reclaim = 0;
6935 for (z = 0; z <= sc->reclaim_idx; z++) {
6936 zone = pgdat->node_zones + z;
6937 if (!managed_zone(zone))
6940 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6944 * Historically care was taken to put equal pressure on all zones but
6945 * now pressure is applied based on node LRU order.
6947 shrink_node(pgdat, sc);
6950 * Fragmentation may mean that the system cannot be rebalanced for
6951 * high-order allocations. If twice the allocation size has been
6952 * reclaimed then recheck watermarks only at order-0 to prevent
6953 * excessive reclaim. Assume that a process requested a high-order
6954 * can direct reclaim/compact.
6956 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6959 return sc->nr_scanned >= sc->nr_to_reclaim;
6962 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6964 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6969 for (i = 0; i <= highest_zoneidx; i++) {
6970 zone = pgdat->node_zones + i;
6972 if (!managed_zone(zone))
6976 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6978 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6983 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6985 update_reclaim_active(pgdat, highest_zoneidx, true);
6989 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6991 update_reclaim_active(pgdat, highest_zoneidx, false);
6995 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6996 * that are eligible for use by the caller until at least one zone is
6999 * Returns the order kswapd finished reclaiming at.
7001 * kswapd scans the zones in the highmem->normal->dma direction. It skips
7002 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
7003 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
7004 * or lower is eligible for reclaim until at least one usable zone is
7007 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
7010 unsigned long nr_soft_reclaimed;
7011 unsigned long nr_soft_scanned;
7012 unsigned long pflags;
7013 unsigned long nr_boost_reclaim;
7014 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7017 struct scan_control sc = {
7018 .gfp_mask = GFP_KERNEL,
7023 set_task_reclaim_state(current, &sc.reclaim_state);
7024 psi_memstall_enter(&pflags);
7025 __fs_reclaim_acquire(_THIS_IP_);
7027 count_vm_event(PAGEOUTRUN);
7030 * Account for the reclaim boost. Note that the zone boost is left in
7031 * place so that parallel allocations that are near the watermark will
7032 * stall or direct reclaim until kswapd is finished.
7034 nr_boost_reclaim = 0;
7035 for (i = 0; i <= highest_zoneidx; i++) {
7036 zone = pgdat->node_zones + i;
7037 if (!managed_zone(zone))
7040 nr_boost_reclaim += zone->watermark_boost;
7041 zone_boosts[i] = zone->watermark_boost;
7043 boosted = nr_boost_reclaim;
7046 set_reclaim_active(pgdat, highest_zoneidx);
7047 sc.priority = DEF_PRIORITY;
7049 unsigned long nr_reclaimed = sc.nr_reclaimed;
7050 bool raise_priority = true;
7054 sc.reclaim_idx = highest_zoneidx;
7057 * If the number of buffer_heads exceeds the maximum allowed
7058 * then consider reclaiming from all zones. This has a dual
7059 * purpose -- on 64-bit systems it is expected that
7060 * buffer_heads are stripped during active rotation. On 32-bit
7061 * systems, highmem pages can pin lowmem memory and shrinking
7062 * buffers can relieve lowmem pressure. Reclaim may still not
7063 * go ahead if all eligible zones for the original allocation
7064 * request are balanced to avoid excessive reclaim from kswapd.
7066 if (buffer_heads_over_limit) {
7067 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7068 zone = pgdat->node_zones + i;
7069 if (!managed_zone(zone))
7078 * If the pgdat is imbalanced then ignore boosting and preserve
7079 * the watermarks for a later time and restart. Note that the
7080 * zone watermarks will be still reset at the end of balancing
7081 * on the grounds that the normal reclaim should be enough to
7082 * re-evaluate if boosting is required when kswapd next wakes.
7084 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7085 if (!balanced && nr_boost_reclaim) {
7086 nr_boost_reclaim = 0;
7091 * If boosting is not active then only reclaim if there are no
7092 * eligible zones. Note that sc.reclaim_idx is not used as
7093 * buffer_heads_over_limit may have adjusted it.
7095 if (!nr_boost_reclaim && balanced)
7098 /* Limit the priority of boosting to avoid reclaim writeback */
7099 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7100 raise_priority = false;
7103 * Do not writeback or swap pages for boosted reclaim. The
7104 * intent is to relieve pressure not issue sub-optimal IO
7105 * from reclaim context. If no pages are reclaimed, the
7106 * reclaim will be aborted.
7108 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7109 sc.may_swap = !nr_boost_reclaim;
7112 * Do some background aging, to give pages a chance to be
7113 * referenced before reclaiming. All pages are rotated
7114 * regardless of classzone as this is about consistent aging.
7116 kswapd_age_node(pgdat, &sc);
7119 * If we're getting trouble reclaiming, start doing writepage
7120 * even in laptop mode.
7122 if (sc.priority < DEF_PRIORITY - 2)
7123 sc.may_writepage = 1;
7125 /* Call soft limit reclaim before calling shrink_node. */
7127 nr_soft_scanned = 0;
7128 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7129 sc.gfp_mask, &nr_soft_scanned);
7130 sc.nr_reclaimed += nr_soft_reclaimed;
7133 * There should be no need to raise the scanning priority if
7134 * enough pages are already being scanned that that high
7135 * watermark would be met at 100% efficiency.
7137 if (kswapd_shrink_node(pgdat, &sc))
7138 raise_priority = false;
7141 * If the low watermark is met there is no need for processes
7142 * to be throttled on pfmemalloc_wait as they should not be
7143 * able to safely make forward progress. Wake them
7145 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7146 allow_direct_reclaim(pgdat))
7147 wake_up_all(&pgdat->pfmemalloc_wait);
7149 /* Check if kswapd should be suspending */
7150 __fs_reclaim_release(_THIS_IP_);
7151 ret = try_to_freeze();
7152 __fs_reclaim_acquire(_THIS_IP_);
7153 if (ret || kthread_should_stop())
7157 * Raise priority if scanning rate is too low or there was no
7158 * progress in reclaiming pages
7160 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7161 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7164 * If reclaim made no progress for a boost, stop reclaim as
7165 * IO cannot be queued and it could be an infinite loop in
7166 * extreme circumstances.
7168 if (nr_boost_reclaim && !nr_reclaimed)
7171 if (raise_priority || !nr_reclaimed)
7173 } while (sc.priority >= 1);
7175 if (!sc.nr_reclaimed)
7176 pgdat->kswapd_failures++;
7179 clear_reclaim_active(pgdat, highest_zoneidx);
7181 /* If reclaim was boosted, account for the reclaim done in this pass */
7183 unsigned long flags;
7185 for (i = 0; i <= highest_zoneidx; i++) {
7186 if (!zone_boosts[i])
7189 /* Increments are under the zone lock */
7190 zone = pgdat->node_zones + i;
7191 spin_lock_irqsave(&zone->lock, flags);
7192 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7193 spin_unlock_irqrestore(&zone->lock, flags);
7197 * As there is now likely space, wakeup kcompact to defragment
7200 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7203 snapshot_refaults(NULL, pgdat);
7204 __fs_reclaim_release(_THIS_IP_);
7205 psi_memstall_leave(&pflags);
7206 set_task_reclaim_state(current, NULL);
7209 * Return the order kswapd stopped reclaiming at as
7210 * prepare_kswapd_sleep() takes it into account. If another caller
7211 * entered the allocator slow path while kswapd was awake, order will
7212 * remain at the higher level.
7218 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7219 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7220 * not a valid index then either kswapd runs for first time or kswapd couldn't
7221 * sleep after previous reclaim attempt (node is still unbalanced). In that
7222 * case return the zone index of the previous kswapd reclaim cycle.
7224 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7225 enum zone_type prev_highest_zoneidx)
7227 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7229 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7232 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7233 unsigned int highest_zoneidx)
7238 if (freezing(current) || kthread_should_stop())
7241 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7244 * Try to sleep for a short interval. Note that kcompactd will only be
7245 * woken if it is possible to sleep for a short interval. This is
7246 * deliberate on the assumption that if reclaim cannot keep an
7247 * eligible zone balanced that it's also unlikely that compaction will
7250 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7252 * Compaction records what page blocks it recently failed to
7253 * isolate pages from and skips them in the future scanning.
7254 * When kswapd is going to sleep, it is reasonable to assume
7255 * that pages and compaction may succeed so reset the cache.
7257 reset_isolation_suitable(pgdat);
7260 * We have freed the memory, now we should compact it to make
7261 * allocation of the requested order possible.
7263 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7265 remaining = schedule_timeout(HZ/10);
7268 * If woken prematurely then reset kswapd_highest_zoneidx and
7269 * order. The values will either be from a wakeup request or
7270 * the previous request that slept prematurely.
7273 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7274 kswapd_highest_zoneidx(pgdat,
7277 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7278 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7281 finish_wait(&pgdat->kswapd_wait, &wait);
7282 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7286 * After a short sleep, check if it was a premature sleep. If not, then
7287 * go fully to sleep until explicitly woken up.
7290 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7291 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7294 * vmstat counters are not perfectly accurate and the estimated
7295 * value for counters such as NR_FREE_PAGES can deviate from the
7296 * true value by nr_online_cpus * threshold. To avoid the zone
7297 * watermarks being breached while under pressure, we reduce the
7298 * per-cpu vmstat threshold while kswapd is awake and restore
7299 * them before going back to sleep.
7301 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7303 if (!kthread_should_stop())
7306 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7309 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7311 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7313 finish_wait(&pgdat->kswapd_wait, &wait);
7317 * The background pageout daemon, started as a kernel thread
7318 * from the init process.
7320 * This basically trickles out pages so that we have _some_
7321 * free memory available even if there is no other activity
7322 * that frees anything up. This is needed for things like routing
7323 * etc, where we otherwise might have all activity going on in
7324 * asynchronous contexts that cannot page things out.
7326 * If there are applications that are active memory-allocators
7327 * (most normal use), this basically shouldn't matter.
7329 static int kswapd(void *p)
7331 unsigned int alloc_order, reclaim_order;
7332 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7333 pg_data_t *pgdat = (pg_data_t *)p;
7334 struct task_struct *tsk = current;
7335 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7337 if (!cpumask_empty(cpumask))
7338 set_cpus_allowed_ptr(tsk, cpumask);
7341 * Tell the memory management that we're a "memory allocator",
7342 * and that if we need more memory we should get access to it
7343 * regardless (see "__alloc_pages()"). "kswapd" should
7344 * never get caught in the normal page freeing logic.
7346 * (Kswapd normally doesn't need memory anyway, but sometimes
7347 * you need a small amount of memory in order to be able to
7348 * page out something else, and this flag essentially protects
7349 * us from recursively trying to free more memory as we're
7350 * trying to free the first piece of memory in the first place).
7352 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7355 WRITE_ONCE(pgdat->kswapd_order, 0);
7356 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7357 atomic_set(&pgdat->nr_writeback_throttled, 0);
7361 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7362 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7366 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7369 /* Read the new order and highest_zoneidx */
7370 alloc_order = READ_ONCE(pgdat->kswapd_order);
7371 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7373 WRITE_ONCE(pgdat->kswapd_order, 0);
7374 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7376 ret = try_to_freeze();
7377 if (kthread_should_stop())
7381 * We can speed up thawing tasks if we don't call balance_pgdat
7382 * after returning from the refrigerator
7388 * Reclaim begins at the requested order but if a high-order
7389 * reclaim fails then kswapd falls back to reclaiming for
7390 * order-0. If that happens, kswapd will consider sleeping
7391 * for the order it finished reclaiming at (reclaim_order)
7392 * but kcompactd is woken to compact for the original
7393 * request (alloc_order).
7395 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7397 reclaim_order = balance_pgdat(pgdat, alloc_order,
7399 if (reclaim_order < alloc_order)
7400 goto kswapd_try_sleep;
7403 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7409 * A zone is low on free memory or too fragmented for high-order memory. If
7410 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7411 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7412 * has failed or is not needed, still wake up kcompactd if only compaction is
7415 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7416 enum zone_type highest_zoneidx)
7419 enum zone_type curr_idx;
7421 if (!managed_zone(zone))
7424 if (!cpuset_zone_allowed(zone, gfp_flags))
7427 pgdat = zone->zone_pgdat;
7428 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7430 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7431 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7433 if (READ_ONCE(pgdat->kswapd_order) < order)
7434 WRITE_ONCE(pgdat->kswapd_order, order);
7436 if (!waitqueue_active(&pgdat->kswapd_wait))
7439 /* Hopeless node, leave it to direct reclaim if possible */
7440 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7441 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7442 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7444 * There may be plenty of free memory available, but it's too
7445 * fragmented for high-order allocations. Wake up kcompactd
7446 * and rely on compaction_suitable() to determine if it's
7447 * needed. If it fails, it will defer subsequent attempts to
7448 * ratelimit its work.
7450 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7451 wakeup_kcompactd(pgdat, order, highest_zoneidx);
7455 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7457 wake_up_interruptible(&pgdat->kswapd_wait);
7460 #ifdef CONFIG_HIBERNATION
7462 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7465 * Rather than trying to age LRUs the aim is to preserve the overall
7466 * LRU order by reclaiming preferentially
7467 * inactive > active > active referenced > active mapped
7469 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7471 struct scan_control sc = {
7472 .nr_to_reclaim = nr_to_reclaim,
7473 .gfp_mask = GFP_HIGHUSER_MOVABLE,
7474 .reclaim_idx = MAX_NR_ZONES - 1,
7475 .priority = DEF_PRIORITY,
7479 .hibernation_mode = 1,
7481 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7482 unsigned long nr_reclaimed;
7483 unsigned int noreclaim_flag;
7485 fs_reclaim_acquire(sc.gfp_mask);
7486 noreclaim_flag = memalloc_noreclaim_save();
7487 set_task_reclaim_state(current, &sc.reclaim_state);
7489 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7491 set_task_reclaim_state(current, NULL);
7492 memalloc_noreclaim_restore(noreclaim_flag);
7493 fs_reclaim_release(sc.gfp_mask);
7495 return nr_reclaimed;
7497 #endif /* CONFIG_HIBERNATION */
7500 * This kswapd start function will be called by init and node-hot-add.
7502 void kswapd_run(int nid)
7504 pg_data_t *pgdat = NODE_DATA(nid);
7506 pgdat_kswapd_lock(pgdat);
7507 if (!pgdat->kswapd) {
7508 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7509 if (IS_ERR(pgdat->kswapd)) {
7510 /* failure at boot is fatal */
7511 BUG_ON(system_state < SYSTEM_RUNNING);
7512 pr_err("Failed to start kswapd on node %d\n", nid);
7513 pgdat->kswapd = NULL;
7516 pgdat_kswapd_unlock(pgdat);
7520 * Called by memory hotplug when all memory in a node is offlined. Caller must
7521 * be holding mem_hotplug_begin/done().
7523 void kswapd_stop(int nid)
7525 pg_data_t *pgdat = NODE_DATA(nid);
7526 struct task_struct *kswapd;
7528 pgdat_kswapd_lock(pgdat);
7529 kswapd = pgdat->kswapd;
7531 kthread_stop(kswapd);
7532 pgdat->kswapd = NULL;
7534 pgdat_kswapd_unlock(pgdat);
7537 static int __init kswapd_init(void)
7542 for_each_node_state(nid, N_MEMORY)
7547 module_init(kswapd_init)
7553 * If non-zero call node_reclaim when the number of free pages falls below
7556 int node_reclaim_mode __read_mostly;
7559 * Priority for NODE_RECLAIM. This determines the fraction of pages
7560 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7563 #define NODE_RECLAIM_PRIORITY 4
7566 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7569 int sysctl_min_unmapped_ratio = 1;
7572 * If the number of slab pages in a zone grows beyond this percentage then
7573 * slab reclaim needs to occur.
7575 int sysctl_min_slab_ratio = 5;
7577 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7579 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7580 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7581 node_page_state(pgdat, NR_ACTIVE_FILE);
7584 * It's possible for there to be more file mapped pages than
7585 * accounted for by the pages on the file LRU lists because
7586 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7588 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7591 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7592 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7594 unsigned long nr_pagecache_reclaimable;
7595 unsigned long delta = 0;
7598 * If RECLAIM_UNMAP is set, then all file pages are considered
7599 * potentially reclaimable. Otherwise, we have to worry about
7600 * pages like swapcache and node_unmapped_file_pages() provides
7603 if (node_reclaim_mode & RECLAIM_UNMAP)
7604 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7606 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7608 /* If we can't clean pages, remove dirty pages from consideration */
7609 if (!(node_reclaim_mode & RECLAIM_WRITE))
7610 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7612 /* Watch for any possible underflows due to delta */
7613 if (unlikely(delta > nr_pagecache_reclaimable))
7614 delta = nr_pagecache_reclaimable;
7616 return nr_pagecache_reclaimable - delta;
7620 * Try to free up some pages from this node through reclaim.
7622 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7624 /* Minimum pages needed in order to stay on node */
7625 const unsigned long nr_pages = 1 << order;
7626 struct task_struct *p = current;
7627 unsigned int noreclaim_flag;
7628 struct scan_control sc = {
7629 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7630 .gfp_mask = current_gfp_context(gfp_mask),
7632 .priority = NODE_RECLAIM_PRIORITY,
7633 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7634 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7636 .reclaim_idx = gfp_zone(gfp_mask),
7638 unsigned long pflags;
7640 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7644 psi_memstall_enter(&pflags);
7645 fs_reclaim_acquire(sc.gfp_mask);
7647 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7649 noreclaim_flag = memalloc_noreclaim_save();
7650 set_task_reclaim_state(p, &sc.reclaim_state);
7652 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7653 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7655 * Free memory by calling shrink node with increasing
7656 * priorities until we have enough memory freed.
7659 shrink_node(pgdat, &sc);
7660 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7663 set_task_reclaim_state(p, NULL);
7664 memalloc_noreclaim_restore(noreclaim_flag);
7665 fs_reclaim_release(sc.gfp_mask);
7666 psi_memstall_leave(&pflags);
7668 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7670 return sc.nr_reclaimed >= nr_pages;
7673 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7678 * Node reclaim reclaims unmapped file backed pages and
7679 * slab pages if we are over the defined limits.
7681 * A small portion of unmapped file backed pages is needed for
7682 * file I/O otherwise pages read by file I/O will be immediately
7683 * thrown out if the node is overallocated. So we do not reclaim
7684 * if less than a specified percentage of the node is used by
7685 * unmapped file backed pages.
7687 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7688 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7689 pgdat->min_slab_pages)
7690 return NODE_RECLAIM_FULL;
7693 * Do not scan if the allocation should not be delayed.
7695 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7696 return NODE_RECLAIM_NOSCAN;
7699 * Only run node reclaim on the local node or on nodes that do not
7700 * have associated processors. This will favor the local processor
7701 * over remote processors and spread off node memory allocations
7702 * as wide as possible.
7704 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7705 return NODE_RECLAIM_NOSCAN;
7707 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7708 return NODE_RECLAIM_NOSCAN;
7710 ret = __node_reclaim(pgdat, gfp_mask, order);
7711 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7714 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7720 void check_move_unevictable_pages(struct pagevec *pvec)
7722 struct folio_batch fbatch;
7725 folio_batch_init(&fbatch);
7726 for (i = 0; i < pvec->nr; i++) {
7727 struct page *page = pvec->pages[i];
7729 if (PageTransTail(page))
7731 folio_batch_add(&fbatch, page_folio(page));
7733 check_move_unevictable_folios(&fbatch);
7735 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
7738 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7740 * @fbatch: Batch of lru folios to check.
7742 * Checks folios for evictability, if an evictable folio is in the unevictable
7743 * lru list, moves it to the appropriate evictable lru list. This function
7744 * should be only used for lru folios.
7746 void check_move_unevictable_folios(struct folio_batch *fbatch)
7748 struct lruvec *lruvec = NULL;
7753 for (i = 0; i < fbatch->nr; i++) {
7754 struct folio *folio = fbatch->folios[i];
7755 int nr_pages = folio_nr_pages(folio);
7757 pgscanned += nr_pages;
7759 /* block memcg migration while the folio moves between lrus */
7760 if (!folio_test_clear_lru(folio))
7763 lruvec = folio_lruvec_relock_irq(folio, lruvec);
7764 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7765 lruvec_del_folio(lruvec, folio);
7766 folio_clear_unevictable(folio);
7767 lruvec_add_folio(lruvec, folio);
7768 pgrescued += nr_pages;
7770 folio_set_lru(folio);
7774 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7775 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7776 unlock_page_lruvec_irq(lruvec);
7777 } else if (pgscanned) {
7778 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7781 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);