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.
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/oom.h>
47 #include <linux/pagevec.h>
48 #include <linux/prefetch.h>
49 #include <linux/printk.h>
50 #include <linux/dax.h>
51 #include <linux/psi.h>
52 #include <linux/pagewalk.h>
53 #include <linux/shmem_fs.h>
54 #include <linux/ctype.h>
56 #include <asm/tlbflush.h>
57 #include <asm/div64.h>
59 #include <linux/swapops.h>
60 #include <linux/balloon_compaction.h>
61 #include <linux/sched/sysctl.h>
66 #define CREATE_TRACE_POINTS
67 #include <trace/events/vmscan.h>
70 /* How many pages shrink_list() should reclaim */
71 unsigned long nr_to_reclaim;
74 * Nodemask of nodes allowed by the caller. If NULL, all nodes
80 * The memory cgroup that hit its limit and as a result is the
81 * primary target of this reclaim invocation.
83 struct mem_cgroup *target_mem_cgroup;
86 * Scan pressure balancing between anon and file LRUs
88 unsigned long anon_cost;
89 unsigned long file_cost;
91 /* Can active pages be deactivated as part of reclaim? */
92 #define DEACTIVATE_ANON 1
93 #define DEACTIVATE_FILE 2
94 unsigned int may_deactivate:2;
95 unsigned int force_deactivate:1;
96 unsigned int skipped_deactivate:1;
98 /* Writepage batching in laptop mode; RECLAIM_WRITE */
99 unsigned int may_writepage:1;
101 /* Can mapped pages be reclaimed? */
102 unsigned int may_unmap:1;
104 /* Can pages be swapped as part of reclaim? */
105 unsigned int may_swap:1;
107 /* Proactive reclaim invoked by userspace through memory.reclaim */
108 unsigned int proactive:1;
111 * Cgroup memory below memory.low is protected as long as we
112 * don't threaten to OOM. If any cgroup is reclaimed at
113 * reduced force or passed over entirely due to its memory.low
114 * setting (memcg_low_skipped), and nothing is reclaimed as a
115 * result, then go back for one more cycle that reclaims the protected
116 * memory (memcg_low_reclaim) to avert OOM.
118 unsigned int memcg_low_reclaim:1;
119 unsigned int memcg_low_skipped:1;
121 unsigned int hibernation_mode:1;
123 /* One of the zones is ready for compaction */
124 unsigned int compaction_ready:1;
126 /* There is easily reclaimable cold cache in the current node */
127 unsigned int cache_trim_mode:1;
129 /* The file pages on the current node are dangerously low */
130 unsigned int file_is_tiny:1;
132 /* Always discard instead of demoting to lower tier memory */
133 unsigned int no_demotion:1;
135 #ifdef CONFIG_LRU_GEN
136 /* help kswapd make better choices among multiple memcgs */
137 unsigned int memcgs_need_aging:1;
138 unsigned long last_reclaimed;
141 /* Allocation order */
144 /* Scan (total_size >> priority) pages at once */
147 /* The highest zone to isolate pages for reclaim from */
150 /* This context's GFP mask */
153 /* Incremented by the number of inactive pages that were scanned */
154 unsigned long nr_scanned;
156 /* Number of pages freed so far during a call to shrink_zones() */
157 unsigned long nr_reclaimed;
161 unsigned int unqueued_dirty;
162 unsigned int congested;
163 unsigned int writeback;
164 unsigned int immediate;
165 unsigned int file_taken;
169 /* for recording the reclaimed slab by now */
170 struct reclaim_state reclaim_state;
173 #ifdef ARCH_HAS_PREFETCHW
174 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
176 if ((_folio)->lru.prev != _base) { \
177 struct folio *prev; \
179 prev = lru_to_folio(&(_folio->lru)); \
180 prefetchw(&prev->_field); \
184 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
188 * From 0 .. 200. Higher means more swappy.
190 int vm_swappiness = 60;
192 static void set_task_reclaim_state(struct task_struct *task,
193 struct reclaim_state *rs)
195 /* Check for an overwrite */
196 WARN_ON_ONCE(rs && task->reclaim_state);
198 /* Check for the nulling of an already-nulled member */
199 WARN_ON_ONCE(!rs && !task->reclaim_state);
201 task->reclaim_state = rs;
204 LIST_HEAD(shrinker_list);
205 DECLARE_RWSEM(shrinker_rwsem);
208 static int shrinker_nr_max;
210 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
211 static inline int shrinker_map_size(int nr_items)
213 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
216 static inline int shrinker_defer_size(int nr_items)
218 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
221 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
224 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
225 lockdep_is_held(&shrinker_rwsem));
228 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
229 int map_size, int defer_size,
230 int old_map_size, int old_defer_size)
232 struct shrinker_info *new, *old;
233 struct mem_cgroup_per_node *pn;
235 int size = map_size + defer_size;
238 pn = memcg->nodeinfo[nid];
239 old = shrinker_info_protected(memcg, nid);
240 /* Not yet online memcg */
244 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
248 new->nr_deferred = (atomic_long_t *)(new + 1);
249 new->map = (void *)new->nr_deferred + defer_size;
251 /* map: set all old bits, clear all new bits */
252 memset(new->map, (int)0xff, old_map_size);
253 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
254 /* nr_deferred: copy old values, clear all new values */
255 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
256 memset((void *)new->nr_deferred + old_defer_size, 0,
257 defer_size - old_defer_size);
259 rcu_assign_pointer(pn->shrinker_info, new);
260 kvfree_rcu(old, rcu);
266 void free_shrinker_info(struct mem_cgroup *memcg)
268 struct mem_cgroup_per_node *pn;
269 struct shrinker_info *info;
273 pn = memcg->nodeinfo[nid];
274 info = rcu_dereference_protected(pn->shrinker_info, true);
276 rcu_assign_pointer(pn->shrinker_info, NULL);
280 int alloc_shrinker_info(struct mem_cgroup *memcg)
282 struct shrinker_info *info;
283 int nid, size, ret = 0;
284 int map_size, defer_size = 0;
286 down_write(&shrinker_rwsem);
287 map_size = shrinker_map_size(shrinker_nr_max);
288 defer_size = shrinker_defer_size(shrinker_nr_max);
289 size = map_size + defer_size;
291 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
293 free_shrinker_info(memcg);
297 info->nr_deferred = (atomic_long_t *)(info + 1);
298 info->map = (void *)info->nr_deferred + defer_size;
299 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
301 up_write(&shrinker_rwsem);
306 static inline bool need_expand(int nr_max)
308 return round_up(nr_max, BITS_PER_LONG) >
309 round_up(shrinker_nr_max, BITS_PER_LONG);
312 static int expand_shrinker_info(int new_id)
315 int new_nr_max = new_id + 1;
316 int map_size, defer_size = 0;
317 int old_map_size, old_defer_size = 0;
318 struct mem_cgroup *memcg;
320 if (!need_expand(new_nr_max))
323 if (!root_mem_cgroup)
326 lockdep_assert_held(&shrinker_rwsem);
328 map_size = shrinker_map_size(new_nr_max);
329 defer_size = shrinker_defer_size(new_nr_max);
330 old_map_size = shrinker_map_size(shrinker_nr_max);
331 old_defer_size = shrinker_defer_size(shrinker_nr_max);
333 memcg = mem_cgroup_iter(NULL, NULL, NULL);
335 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
336 old_map_size, old_defer_size);
338 mem_cgroup_iter_break(NULL, memcg);
341 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
344 shrinker_nr_max = new_nr_max;
349 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
351 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
352 struct shrinker_info *info;
355 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
356 /* Pairs with smp mb in shrink_slab() */
357 smp_mb__before_atomic();
358 set_bit(shrinker_id, info->map);
363 static DEFINE_IDR(shrinker_idr);
365 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
367 int id, ret = -ENOMEM;
369 if (mem_cgroup_disabled())
372 down_write(&shrinker_rwsem);
373 /* This may call shrinker, so it must use down_read_trylock() */
374 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
378 if (id >= shrinker_nr_max) {
379 if (expand_shrinker_info(id)) {
380 idr_remove(&shrinker_idr, id);
387 up_write(&shrinker_rwsem);
391 static void unregister_memcg_shrinker(struct shrinker *shrinker)
393 int id = shrinker->id;
397 lockdep_assert_held(&shrinker_rwsem);
399 idr_remove(&shrinker_idr, id);
402 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
403 struct mem_cgroup *memcg)
405 struct shrinker_info *info;
407 info = shrinker_info_protected(memcg, nid);
408 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
411 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
412 struct mem_cgroup *memcg)
414 struct shrinker_info *info;
416 info = shrinker_info_protected(memcg, nid);
417 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
420 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
424 struct mem_cgroup *parent;
425 struct shrinker_info *child_info, *parent_info;
427 parent = parent_mem_cgroup(memcg);
429 parent = root_mem_cgroup;
431 /* Prevent from concurrent shrinker_info expand */
432 down_read(&shrinker_rwsem);
434 child_info = shrinker_info_protected(memcg, nid);
435 parent_info = shrinker_info_protected(parent, nid);
436 for (i = 0; i < shrinker_nr_max; i++) {
437 nr = atomic_long_read(&child_info->nr_deferred[i]);
438 atomic_long_add(nr, &parent_info->nr_deferred[i]);
441 up_read(&shrinker_rwsem);
444 static bool cgroup_reclaim(struct scan_control *sc)
446 return sc->target_mem_cgroup;
450 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
451 * @sc: scan_control in question
453 * The normal page dirty throttling mechanism in balance_dirty_pages() is
454 * completely broken with the legacy memcg and direct stalling in
455 * shrink_page_list() is used for throttling instead, which lacks all the
456 * niceties such as fairness, adaptive pausing, bandwidth proportional
457 * allocation and configurability.
459 * This function tests whether the vmscan currently in progress can assume
460 * that the normal dirty throttling mechanism is operational.
462 static bool writeback_throttling_sane(struct scan_control *sc)
464 if (!cgroup_reclaim(sc))
466 #ifdef CONFIG_CGROUP_WRITEBACK
467 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
473 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
478 static void unregister_memcg_shrinker(struct shrinker *shrinker)
482 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
483 struct mem_cgroup *memcg)
488 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
489 struct mem_cgroup *memcg)
494 static bool cgroup_reclaim(struct scan_control *sc)
499 static bool writeback_throttling_sane(struct scan_control *sc)
505 static long xchg_nr_deferred(struct shrinker *shrinker,
506 struct shrink_control *sc)
510 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
514 (shrinker->flags & SHRINKER_MEMCG_AWARE))
515 return xchg_nr_deferred_memcg(nid, shrinker,
518 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
522 static long add_nr_deferred(long nr, struct shrinker *shrinker,
523 struct shrink_control *sc)
527 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
531 (shrinker->flags & SHRINKER_MEMCG_AWARE))
532 return add_nr_deferred_memcg(nr, nid, shrinker,
535 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
538 static bool can_demote(int nid, struct scan_control *sc)
540 if (!numa_demotion_enabled)
542 if (sc && sc->no_demotion)
544 if (next_demotion_node(nid) == NUMA_NO_NODE)
550 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
552 struct scan_control *sc)
556 * For non-memcg reclaim, is there
557 * space in any swap device?
559 if (get_nr_swap_pages() > 0)
562 /* Is the memcg below its swap limit? */
563 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
568 * The page can not be swapped.
570 * Can it be reclaimed from this node via demotion?
572 return can_demote(nid, sc);
576 * This misses isolated pages which are not accounted for to save counters.
577 * As the data only determines if reclaim or compaction continues, it is
578 * not expected that isolated pages will be a dominating factor.
580 unsigned long zone_reclaimable_pages(struct zone *zone)
584 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
585 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
586 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
587 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
588 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
594 * lruvec_lru_size - Returns the number of pages on the given LRU list.
595 * @lruvec: lru vector
597 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
599 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
602 unsigned long size = 0;
605 for (zid = 0; zid <= zone_idx; zid++) {
606 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
608 if (!managed_zone(zone))
611 if (!mem_cgroup_disabled())
612 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
614 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
620 * Add a shrinker callback to be called from the vm.
622 static int __prealloc_shrinker(struct shrinker *shrinker)
627 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
628 err = prealloc_memcg_shrinker(shrinker);
632 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
635 size = sizeof(*shrinker->nr_deferred);
636 if (shrinker->flags & SHRINKER_NUMA_AWARE)
639 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
640 if (!shrinker->nr_deferred)
646 #ifdef CONFIG_SHRINKER_DEBUG
647 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
653 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
658 err = __prealloc_shrinker(shrinker);
660 kfree_const(shrinker->name);
661 shrinker->name = NULL;
667 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
669 return __prealloc_shrinker(shrinker);
673 void free_prealloced_shrinker(struct shrinker *shrinker)
675 #ifdef CONFIG_SHRINKER_DEBUG
676 kfree_const(shrinker->name);
677 shrinker->name = NULL;
679 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
680 down_write(&shrinker_rwsem);
681 unregister_memcg_shrinker(shrinker);
682 up_write(&shrinker_rwsem);
686 kfree(shrinker->nr_deferred);
687 shrinker->nr_deferred = NULL;
690 void register_shrinker_prepared(struct shrinker *shrinker)
692 down_write(&shrinker_rwsem);
693 list_add_tail(&shrinker->list, &shrinker_list);
694 shrinker->flags |= SHRINKER_REGISTERED;
695 shrinker_debugfs_add(shrinker);
696 up_write(&shrinker_rwsem);
699 static int __register_shrinker(struct shrinker *shrinker)
701 int err = __prealloc_shrinker(shrinker);
705 register_shrinker_prepared(shrinker);
709 #ifdef CONFIG_SHRINKER_DEBUG
710 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
716 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
721 err = __register_shrinker(shrinker);
723 kfree_const(shrinker->name);
724 shrinker->name = NULL;
729 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
731 return __register_shrinker(shrinker);
734 EXPORT_SYMBOL(register_shrinker);
739 void unregister_shrinker(struct shrinker *shrinker)
741 if (!(shrinker->flags & SHRINKER_REGISTERED))
744 down_write(&shrinker_rwsem);
745 list_del(&shrinker->list);
746 shrinker->flags &= ~SHRINKER_REGISTERED;
747 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
748 unregister_memcg_shrinker(shrinker);
749 shrinker_debugfs_remove(shrinker);
750 up_write(&shrinker_rwsem);
752 kfree(shrinker->nr_deferred);
753 shrinker->nr_deferred = NULL;
755 EXPORT_SYMBOL(unregister_shrinker);
758 * synchronize_shrinkers - Wait for all running shrinkers to complete.
760 * This is equivalent to calling unregister_shrink() and register_shrinker(),
761 * but atomically and with less overhead. This is useful to guarantee that all
762 * shrinker invocations have seen an update, before freeing memory, similar to
765 void synchronize_shrinkers(void)
767 down_write(&shrinker_rwsem);
768 up_write(&shrinker_rwsem);
770 EXPORT_SYMBOL(synchronize_shrinkers);
772 #define SHRINK_BATCH 128
774 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
775 struct shrinker *shrinker, int priority)
777 unsigned long freed = 0;
778 unsigned long long delta;
783 long batch_size = shrinker->batch ? shrinker->batch
785 long scanned = 0, next_deferred;
787 freeable = shrinker->count_objects(shrinker, shrinkctl);
788 if (freeable == 0 || freeable == SHRINK_EMPTY)
792 * copy the current shrinker scan count into a local variable
793 * and zero it so that other concurrent shrinker invocations
794 * don't also do this scanning work.
796 nr = xchg_nr_deferred(shrinker, shrinkctl);
798 if (shrinker->seeks) {
799 delta = freeable >> priority;
801 do_div(delta, shrinker->seeks);
804 * These objects don't require any IO to create. Trim
805 * them aggressively under memory pressure to keep
806 * them from causing refetches in the IO caches.
808 delta = freeable / 2;
811 total_scan = nr >> priority;
813 total_scan = min(total_scan, (2 * freeable));
815 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
816 freeable, delta, total_scan, priority);
819 * Normally, we should not scan less than batch_size objects in one
820 * pass to avoid too frequent shrinker calls, but if the slab has less
821 * than batch_size objects in total and we are really tight on memory,
822 * we will try to reclaim all available objects, otherwise we can end
823 * up failing allocations although there are plenty of reclaimable
824 * objects spread over several slabs with usage less than the
827 * We detect the "tight on memory" situations by looking at the total
828 * number of objects we want to scan (total_scan). If it is greater
829 * than the total number of objects on slab (freeable), we must be
830 * scanning at high prio and therefore should try to reclaim as much as
833 while (total_scan >= batch_size ||
834 total_scan >= freeable) {
836 unsigned long nr_to_scan = min(batch_size, total_scan);
838 shrinkctl->nr_to_scan = nr_to_scan;
839 shrinkctl->nr_scanned = nr_to_scan;
840 ret = shrinker->scan_objects(shrinker, shrinkctl);
841 if (ret == SHRINK_STOP)
845 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
846 total_scan -= shrinkctl->nr_scanned;
847 scanned += shrinkctl->nr_scanned;
853 * The deferred work is increased by any new work (delta) that wasn't
854 * done, decreased by old deferred work that was done now.
856 * And it is capped to two times of the freeable items.
858 next_deferred = max_t(long, (nr + delta - scanned), 0);
859 next_deferred = min(next_deferred, (2 * freeable));
862 * move the unused scan count back into the shrinker in a
863 * manner that handles concurrent updates.
865 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
867 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
872 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
873 struct mem_cgroup *memcg, int priority)
875 struct shrinker_info *info;
876 unsigned long ret, freed = 0;
879 if (!mem_cgroup_online(memcg))
882 if (!down_read_trylock(&shrinker_rwsem))
885 info = shrinker_info_protected(memcg, nid);
889 for_each_set_bit(i, info->map, shrinker_nr_max) {
890 struct shrink_control sc = {
891 .gfp_mask = gfp_mask,
895 struct shrinker *shrinker;
897 shrinker = idr_find(&shrinker_idr, i);
898 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
900 clear_bit(i, info->map);
904 /* Call non-slab shrinkers even though kmem is disabled */
905 if (!memcg_kmem_enabled() &&
906 !(shrinker->flags & SHRINKER_NONSLAB))
909 ret = do_shrink_slab(&sc, shrinker, priority);
910 if (ret == SHRINK_EMPTY) {
911 clear_bit(i, info->map);
913 * After the shrinker reported that it had no objects to
914 * free, but before we cleared the corresponding bit in
915 * the memcg shrinker map, a new object might have been
916 * added. To make sure, we have the bit set in this
917 * case, we invoke the shrinker one more time and reset
918 * the bit if it reports that it is not empty anymore.
919 * The memory barrier here pairs with the barrier in
920 * set_shrinker_bit():
922 * list_lru_add() shrink_slab_memcg()
923 * list_add_tail() clear_bit()
925 * set_bit() do_shrink_slab()
927 smp_mb__after_atomic();
928 ret = do_shrink_slab(&sc, shrinker, priority);
929 if (ret == SHRINK_EMPTY)
932 set_shrinker_bit(memcg, nid, i);
936 if (rwsem_is_contended(&shrinker_rwsem)) {
942 up_read(&shrinker_rwsem);
945 #else /* CONFIG_MEMCG */
946 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
947 struct mem_cgroup *memcg, int priority)
951 #endif /* CONFIG_MEMCG */
954 * shrink_slab - shrink slab caches
955 * @gfp_mask: allocation context
956 * @nid: node whose slab caches to target
957 * @memcg: memory cgroup whose slab caches to target
958 * @priority: the reclaim priority
960 * Call the shrink functions to age shrinkable caches.
962 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
963 * unaware shrinkers will receive a node id of 0 instead.
965 * @memcg specifies the memory cgroup to target. Unaware shrinkers
966 * are called only if it is the root cgroup.
968 * @priority is sc->priority, we take the number of objects and >> by priority
969 * in order to get the scan target.
971 * Returns the number of reclaimed slab objects.
973 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
974 struct mem_cgroup *memcg,
977 unsigned long ret, freed = 0;
978 struct shrinker *shrinker;
981 * The root memcg might be allocated even though memcg is disabled
982 * via "cgroup_disable=memory" boot parameter. This could make
983 * mem_cgroup_is_root() return false, then just run memcg slab
984 * shrink, but skip global shrink. This may result in premature
987 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
988 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
990 if (!down_read_trylock(&shrinker_rwsem))
993 list_for_each_entry(shrinker, &shrinker_list, list) {
994 struct shrink_control sc = {
995 .gfp_mask = gfp_mask,
1000 ret = do_shrink_slab(&sc, shrinker, priority);
1001 if (ret == SHRINK_EMPTY)
1005 * Bail out if someone want to register a new shrinker to
1006 * prevent the registration from being stalled for long periods
1007 * by parallel ongoing shrinking.
1009 if (rwsem_is_contended(&shrinker_rwsem)) {
1010 freed = freed ? : 1;
1015 up_read(&shrinker_rwsem);
1021 static void drop_slab_node(int nid)
1023 unsigned long freed;
1027 struct mem_cgroup *memcg = NULL;
1029 if (fatal_signal_pending(current))
1033 memcg = mem_cgroup_iter(NULL, NULL, NULL);
1035 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1036 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1037 } while ((freed >> shift++) > 1);
1040 void drop_slab(void)
1044 for_each_online_node(nid)
1045 drop_slab_node(nid);
1048 static inline int is_page_cache_freeable(struct folio *folio)
1051 * A freeable page cache page is referenced only by the caller
1052 * that isolated the page, the page cache and optional buffer
1053 * heads at page->private.
1055 return folio_ref_count(folio) - folio_test_private(folio) ==
1056 1 + folio_nr_pages(folio);
1060 * We detected a synchronous write error writing a folio out. Probably
1061 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1062 * fsync(), msync() or close().
1064 * The tricky part is that after writepage we cannot touch the mapping: nothing
1065 * prevents it from being freed up. But we have a ref on the folio and once
1066 * that folio is locked, the mapping is pinned.
1068 * We're allowed to run sleeping folio_lock() here because we know the caller has
1071 static void handle_write_error(struct address_space *mapping,
1072 struct folio *folio, int error)
1075 if (folio_mapping(folio) == mapping)
1076 mapping_set_error(mapping, error);
1077 folio_unlock(folio);
1080 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1082 int reclaimable = 0, write_pending = 0;
1086 * If kswapd is disabled, reschedule if necessary but do not
1087 * throttle as the system is likely near OOM.
1089 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1093 * If there are a lot of dirty/writeback pages then do not
1094 * throttle as throttling will occur when the pages cycle
1095 * towards the end of the LRU if still under writeback.
1097 for (i = 0; i < MAX_NR_ZONES; i++) {
1098 struct zone *zone = pgdat->node_zones + i;
1100 if (!managed_zone(zone))
1103 reclaimable += zone_reclaimable_pages(zone);
1104 write_pending += zone_page_state_snapshot(zone,
1105 NR_ZONE_WRITE_PENDING);
1107 if (2 * write_pending <= reclaimable)
1113 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1115 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1120 * Do not throttle IO workers, kthreads other than kswapd or
1121 * workqueues. They may be required for reclaim to make
1122 * forward progress (e.g. journalling workqueues or kthreads).
1124 if (!current_is_kswapd() &&
1125 current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1131 * These figures are pulled out of thin air.
1132 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1133 * parallel reclaimers which is a short-lived event so the timeout is
1134 * short. Failing to make progress or waiting on writeback are
1135 * potentially long-lived events so use a longer timeout. This is shaky
1136 * logic as a failure to make progress could be due to anything from
1137 * writeback to a slow device to excessive references pages at the tail
1138 * of the inactive LRU.
1141 case VMSCAN_THROTTLE_WRITEBACK:
1144 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1145 WRITE_ONCE(pgdat->nr_reclaim_start,
1146 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1150 case VMSCAN_THROTTLE_CONGESTED:
1152 case VMSCAN_THROTTLE_NOPROGRESS:
1153 if (skip_throttle_noprogress(pgdat)) {
1161 case VMSCAN_THROTTLE_ISOLATED:
1170 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1171 ret = schedule_timeout(timeout);
1172 finish_wait(wqh, &wait);
1174 if (reason == VMSCAN_THROTTLE_WRITEBACK)
1175 atomic_dec(&pgdat->nr_writeback_throttled);
1177 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1178 jiffies_to_usecs(timeout - ret),
1183 * Account for pages written if tasks are throttled waiting on dirty
1184 * pages to clean. If enough pages have been cleaned since throttling
1185 * started then wakeup the throttled tasks.
1187 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1190 unsigned long nr_written;
1192 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1195 * This is an inaccurate read as the per-cpu deltas may not
1196 * be synchronised. However, given that the system is
1197 * writeback throttled, it is not worth taking the penalty
1198 * of getting an accurate count. At worst, the throttle
1199 * timeout guarantees forward progress.
1201 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1202 READ_ONCE(pgdat->nr_reclaim_start);
1204 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1205 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1208 /* possible outcome of pageout() */
1210 /* failed to write page out, page is locked */
1212 /* move page to the active list, page is locked */
1214 /* page has been sent to the disk successfully, page is unlocked */
1216 /* page is clean and locked */
1221 * pageout is called by shrink_page_list() for each dirty page.
1222 * Calls ->writepage().
1224 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1225 struct swap_iocb **plug)
1228 * If the folio is dirty, only perform writeback if that write
1229 * will be non-blocking. To prevent this allocation from being
1230 * stalled by pagecache activity. But note that there may be
1231 * stalls if we need to run get_block(). We could test
1232 * PagePrivate for that.
1234 * If this process is currently in __generic_file_write_iter() against
1235 * this folio's queue, we can perform writeback even if that
1238 * If the folio is swapcache, write it back even if that would
1239 * block, for some throttling. This happens by accident, because
1240 * swap_backing_dev_info is bust: it doesn't reflect the
1241 * congestion state of the swapdevs. Easy to fix, if needed.
1243 if (!is_page_cache_freeable(folio))
1247 * Some data journaling orphaned folios can have
1248 * folio->mapping == NULL while being dirty with clean buffers.
1250 if (folio_test_private(folio)) {
1251 if (try_to_free_buffers(folio)) {
1252 folio_clear_dirty(folio);
1253 pr_info("%s: orphaned folio\n", __func__);
1259 if (mapping->a_ops->writepage == NULL)
1260 return PAGE_ACTIVATE;
1262 if (folio_clear_dirty_for_io(folio)) {
1264 struct writeback_control wbc = {
1265 .sync_mode = WB_SYNC_NONE,
1266 .nr_to_write = SWAP_CLUSTER_MAX,
1268 .range_end = LLONG_MAX,
1273 folio_set_reclaim(folio);
1274 res = mapping->a_ops->writepage(&folio->page, &wbc);
1276 handle_write_error(mapping, folio, res);
1277 if (res == AOP_WRITEPAGE_ACTIVATE) {
1278 folio_clear_reclaim(folio);
1279 return PAGE_ACTIVATE;
1282 if (!folio_test_writeback(folio)) {
1283 /* synchronous write or broken a_ops? */
1284 folio_clear_reclaim(folio);
1286 trace_mm_vmscan_write_folio(folio);
1287 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1288 return PAGE_SUCCESS;
1295 * Same as remove_mapping, but if the page is removed from the mapping, it
1296 * gets returned with a refcount of 0.
1298 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1299 bool reclaimed, struct mem_cgroup *target_memcg)
1302 void *shadow = NULL;
1304 BUG_ON(!folio_test_locked(folio));
1305 BUG_ON(mapping != folio_mapping(folio));
1307 if (!folio_test_swapcache(folio))
1308 spin_lock(&mapping->host->i_lock);
1309 xa_lock_irq(&mapping->i_pages);
1311 * The non racy check for a busy page.
1313 * Must be careful with the order of the tests. When someone has
1314 * a ref to the page, it may be possible that they dirty it then
1315 * drop the reference. So if PageDirty is tested before page_count
1316 * here, then the following race may occur:
1318 * get_user_pages(&page);
1319 * [user mapping goes away]
1321 * !PageDirty(page) [good]
1322 * SetPageDirty(page);
1324 * !page_count(page) [good, discard it]
1326 * [oops, our write_to data is lost]
1328 * Reversing the order of the tests ensures such a situation cannot
1329 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1330 * load is not satisfied before that of page->_refcount.
1332 * Note that if SetPageDirty is always performed via set_page_dirty,
1333 * and thus under the i_pages lock, then this ordering is not required.
1335 refcount = 1 + folio_nr_pages(folio);
1336 if (!folio_ref_freeze(folio, refcount))
1338 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1339 if (unlikely(folio_test_dirty(folio))) {
1340 folio_ref_unfreeze(folio, refcount);
1344 if (folio_test_swapcache(folio)) {
1345 swp_entry_t swap = folio_swap_entry(folio);
1347 /* get a shadow entry before mem_cgroup_swapout() clears folio_memcg() */
1348 if (reclaimed && !mapping_exiting(mapping))
1349 shadow = workingset_eviction(folio, target_memcg);
1350 mem_cgroup_swapout(folio, swap);
1351 __delete_from_swap_cache(folio, swap, shadow);
1352 xa_unlock_irq(&mapping->i_pages);
1353 put_swap_page(&folio->page, swap);
1355 void (*free_folio)(struct folio *);
1357 free_folio = mapping->a_ops->free_folio;
1359 * Remember a shadow entry for reclaimed file cache in
1360 * order to detect refaults, thus thrashing, later on.
1362 * But don't store shadows in an address space that is
1363 * already exiting. This is not just an optimization,
1364 * inode reclaim needs to empty out the radix tree or
1365 * the nodes are lost. Don't plant shadows behind its
1368 * We also don't store shadows for DAX mappings because the
1369 * only page cache pages found in these are zero pages
1370 * covering holes, and because we don't want to mix DAX
1371 * exceptional entries and shadow exceptional entries in the
1372 * same address_space.
1374 if (reclaimed && folio_is_file_lru(folio) &&
1375 !mapping_exiting(mapping) && !dax_mapping(mapping))
1376 shadow = workingset_eviction(folio, target_memcg);
1377 __filemap_remove_folio(folio, shadow);
1378 xa_unlock_irq(&mapping->i_pages);
1379 if (mapping_shrinkable(mapping))
1380 inode_add_lru(mapping->host);
1381 spin_unlock(&mapping->host->i_lock);
1390 xa_unlock_irq(&mapping->i_pages);
1391 if (!folio_test_swapcache(folio))
1392 spin_unlock(&mapping->host->i_lock);
1397 * remove_mapping() - Attempt to remove a folio from its mapping.
1398 * @mapping: The address space.
1399 * @folio: The folio to remove.
1401 * If the folio is dirty, under writeback or if someone else has a ref
1402 * on it, removal will fail.
1403 * Return: The number of pages removed from the mapping. 0 if the folio
1404 * could not be removed.
1405 * Context: The caller should have a single refcount on the folio and
1408 long remove_mapping(struct address_space *mapping, struct folio *folio)
1410 if (__remove_mapping(mapping, folio, false, NULL)) {
1412 * Unfreezing the refcount with 1 effectively
1413 * drops the pagecache ref for us without requiring another
1416 folio_ref_unfreeze(folio, 1);
1417 return folio_nr_pages(folio);
1423 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1424 * @folio: Folio to be returned to an LRU list.
1426 * Add previously isolated @folio to appropriate LRU list.
1427 * The folio may still be unevictable for other reasons.
1429 * Context: lru_lock must not be held, interrupts must be enabled.
1431 void folio_putback_lru(struct folio *folio)
1433 folio_add_lru(folio);
1434 folio_put(folio); /* drop ref from isolate */
1437 enum page_references {
1439 PAGEREF_RECLAIM_CLEAN,
1444 static enum page_references folio_check_references(struct folio *folio,
1445 struct scan_control *sc)
1447 int referenced_ptes, referenced_folio;
1448 unsigned long vm_flags;
1450 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1452 referenced_folio = folio_test_clear_referenced(folio);
1455 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1456 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1458 if (vm_flags & VM_LOCKED)
1459 return PAGEREF_ACTIVATE;
1461 /* rmap lock contention: rotate */
1462 if (referenced_ptes == -1)
1463 return PAGEREF_KEEP;
1465 if (referenced_ptes) {
1467 * All mapped folios start out with page table
1468 * references from the instantiating fault, so we need
1469 * to look twice if a mapped file/anon folio is used more
1472 * Mark it and spare it for another trip around the
1473 * inactive list. Another page table reference will
1474 * lead to its activation.
1476 * Note: the mark is set for activated folios as well
1477 * so that recently deactivated but used folios are
1478 * quickly recovered.
1480 folio_set_referenced(folio);
1482 if (referenced_folio || referenced_ptes > 1)
1483 return PAGEREF_ACTIVATE;
1486 * Activate file-backed executable folios after first usage.
1488 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1489 return PAGEREF_ACTIVATE;
1491 return PAGEREF_KEEP;
1494 /* Reclaim if clean, defer dirty folios to writeback */
1495 if (referenced_folio && folio_is_file_lru(folio))
1496 return PAGEREF_RECLAIM_CLEAN;
1498 return PAGEREF_RECLAIM;
1501 /* Check if a page is dirty or under writeback */
1502 static void folio_check_dirty_writeback(struct folio *folio,
1503 bool *dirty, bool *writeback)
1505 struct address_space *mapping;
1508 * Anonymous pages are not handled by flushers and must be written
1509 * from reclaim context. Do not stall reclaim based on them.
1510 * MADV_FREE anonymous pages are put into inactive file list too.
1511 * They could be mistakenly treated as file lru. So further anon
1514 if (!folio_is_file_lru(folio) ||
1515 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1521 /* By default assume that the folio flags are accurate */
1522 *dirty = folio_test_dirty(folio);
1523 *writeback = folio_test_writeback(folio);
1525 /* Verify dirty/writeback state if the filesystem supports it */
1526 if (!folio_test_private(folio))
1529 mapping = folio_mapping(folio);
1530 if (mapping && mapping->a_ops->is_dirty_writeback)
1531 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1534 static struct page *alloc_demote_page(struct page *page, unsigned long node)
1536 struct migration_target_control mtc = {
1538 * Allocate from 'node', or fail quickly and quietly.
1539 * When this happens, 'page' will likely just be discarded
1540 * instead of migrated.
1542 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1543 __GFP_THISNODE | __GFP_NOWARN |
1544 __GFP_NOMEMALLOC | GFP_NOWAIT,
1548 return alloc_migration_target(page, (unsigned long)&mtc);
1552 * Take pages on @demote_list and attempt to demote them to
1553 * another node. Pages which are not demoted are left on
1556 static unsigned int demote_page_list(struct list_head *demote_pages,
1557 struct pglist_data *pgdat)
1559 int target_nid = next_demotion_node(pgdat->node_id);
1560 unsigned int nr_succeeded;
1562 if (list_empty(demote_pages))
1565 if (target_nid == NUMA_NO_NODE)
1568 /* Demotion ignores all cpuset and mempolicy settings */
1569 migrate_pages(demote_pages, alloc_demote_page, NULL,
1570 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1573 if (current_is_kswapd())
1574 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1576 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1578 return nr_succeeded;
1581 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1583 if (gfp_mask & __GFP_FS)
1585 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1588 * We can "enter_fs" for swap-cache with only __GFP_IO
1589 * providing this isn't SWP_FS_OPS.
1590 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1591 * but that will never affect SWP_FS_OPS, so the data_race
1594 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1598 * shrink_page_list() returns the number of reclaimed pages
1600 static unsigned int shrink_page_list(struct list_head *page_list,
1601 struct pglist_data *pgdat,
1602 struct scan_control *sc,
1603 struct reclaim_stat *stat,
1604 bool ignore_references)
1606 LIST_HEAD(ret_pages);
1607 LIST_HEAD(free_pages);
1608 LIST_HEAD(demote_pages);
1609 unsigned int nr_reclaimed = 0;
1610 unsigned int pgactivate = 0;
1611 bool do_demote_pass;
1612 struct swap_iocb *plug = NULL;
1614 memset(stat, 0, sizeof(*stat));
1616 do_demote_pass = can_demote(pgdat->node_id, sc);
1619 while (!list_empty(page_list)) {
1620 struct address_space *mapping;
1621 struct folio *folio;
1622 enum page_references references = PAGEREF_RECLAIM;
1623 bool dirty, writeback;
1624 unsigned int nr_pages;
1628 folio = lru_to_folio(page_list);
1629 list_del(&folio->lru);
1631 if (!folio_trylock(folio))
1634 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1636 nr_pages = folio_nr_pages(folio);
1638 /* Account the number of base pages */
1639 sc->nr_scanned += nr_pages;
1641 if (unlikely(!folio_evictable(folio)))
1642 goto activate_locked;
1644 if (!sc->may_unmap && folio_mapped(folio))
1647 /* folio_update_gen() tried to promote this page? */
1648 if (lru_gen_enabled() && !ignore_references &&
1649 folio_mapped(folio) && folio_test_referenced(folio))
1653 * The number of dirty pages determines if a node is marked
1654 * reclaim_congested. kswapd will stall and start writing
1655 * folios if the tail of the LRU is all dirty unqueued folios.
1657 folio_check_dirty_writeback(folio, &dirty, &writeback);
1658 if (dirty || writeback)
1659 stat->nr_dirty += nr_pages;
1661 if (dirty && !writeback)
1662 stat->nr_unqueued_dirty += nr_pages;
1665 * Treat this folio as congested if folios are cycling
1666 * through the LRU so quickly that the folios marked
1667 * for immediate reclaim are making it to the end of
1668 * the LRU a second time.
1670 if (writeback && folio_test_reclaim(folio))
1671 stat->nr_congested += nr_pages;
1674 * If a folio at the tail of the LRU is under writeback, there
1675 * are three cases to consider.
1677 * 1) If reclaim is encountering an excessive number
1678 * of folios under writeback and this folio has both
1679 * the writeback and reclaim flags set, then it
1680 * indicates that folios are being queued for I/O but
1681 * are being recycled through the LRU before the I/O
1682 * can complete. Waiting on the folio itself risks an
1683 * indefinite stall if it is impossible to writeback
1684 * the folio due to I/O error or disconnected storage
1685 * so instead note that the LRU is being scanned too
1686 * quickly and the caller can stall after the folio
1687 * list has been processed.
1689 * 2) Global or new memcg reclaim encounters a folio that is
1690 * not marked for immediate reclaim, or the caller does not
1691 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1692 * not to fs). In this case mark the folio for immediate
1693 * reclaim and continue scanning.
1695 * Require may_enter_fs() because we would wait on fs, which
1696 * may not have submitted I/O yet. And the loop driver might
1697 * enter reclaim, and deadlock if it waits on a folio for
1698 * which it is needed to do the write (loop masks off
1699 * __GFP_IO|__GFP_FS for this reason); but more thought
1700 * would probably show more reasons.
1702 * 3) Legacy memcg encounters a folio that already has the
1703 * reclaim flag set. memcg does not have any dirty folio
1704 * throttling so we could easily OOM just because too many
1705 * folios are in writeback and there is nothing else to
1706 * reclaim. Wait for the writeback to complete.
1708 * In cases 1) and 2) we activate the folios to get them out of
1709 * the way while we continue scanning for clean folios on the
1710 * inactive list and refilling from the active list. The
1711 * observation here is that waiting for disk writes is more
1712 * expensive than potentially causing reloads down the line.
1713 * Since they're marked for immediate reclaim, they won't put
1714 * memory pressure on the cache working set any longer than it
1715 * takes to write them to disk.
1717 if (folio_test_writeback(folio)) {
1719 if (current_is_kswapd() &&
1720 folio_test_reclaim(folio) &&
1721 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1722 stat->nr_immediate += nr_pages;
1723 goto activate_locked;
1726 } else if (writeback_throttling_sane(sc) ||
1727 !folio_test_reclaim(folio) ||
1728 !may_enter_fs(folio, sc->gfp_mask)) {
1730 * This is slightly racy -
1731 * folio_end_writeback() might have
1732 * just cleared the reclaim flag, then
1733 * setting the reclaim flag here ends up
1734 * interpreted as the readahead flag - but
1735 * that does not matter enough to care.
1736 * What we do want is for this folio to
1737 * have the reclaim flag set next time
1738 * memcg reclaim reaches the tests above,
1739 * so it will then wait for writeback to
1740 * avoid OOM; and it's also appropriate
1741 * in global reclaim.
1743 folio_set_reclaim(folio);
1744 stat->nr_writeback += nr_pages;
1745 goto activate_locked;
1749 folio_unlock(folio);
1750 folio_wait_writeback(folio);
1751 /* then go back and try same folio again */
1752 list_add_tail(&folio->lru, page_list);
1757 if (!ignore_references)
1758 references = folio_check_references(folio, sc);
1760 switch (references) {
1761 case PAGEREF_ACTIVATE:
1762 goto activate_locked;
1764 stat->nr_ref_keep += nr_pages;
1766 case PAGEREF_RECLAIM:
1767 case PAGEREF_RECLAIM_CLEAN:
1768 ; /* try to reclaim the folio below */
1772 * Before reclaiming the folio, try to relocate
1773 * its contents to another node.
1775 if (do_demote_pass &&
1776 (thp_migration_supported() || !folio_test_large(folio))) {
1777 list_add(&folio->lru, &demote_pages);
1778 folio_unlock(folio);
1783 * Anonymous process memory has backing store?
1784 * Try to allocate it some swap space here.
1785 * Lazyfree folio could be freed directly
1787 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1788 if (!folio_test_swapcache(folio)) {
1789 if (!(sc->gfp_mask & __GFP_IO))
1791 if (folio_maybe_dma_pinned(folio))
1793 if (folio_test_large(folio)) {
1794 /* cannot split folio, skip it */
1795 if (!can_split_folio(folio, NULL))
1796 goto activate_locked;
1798 * Split folios without a PMD map right
1799 * away. Chances are some or all of the
1800 * tail pages can be freed without IO.
1802 if (!folio_entire_mapcount(folio) &&
1803 split_folio_to_list(folio,
1805 goto activate_locked;
1807 if (!add_to_swap(folio)) {
1808 if (!folio_test_large(folio))
1809 goto activate_locked_split;
1810 /* Fallback to swap normal pages */
1811 if (split_folio_to_list(folio,
1813 goto activate_locked;
1814 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1815 count_vm_event(THP_SWPOUT_FALLBACK);
1817 if (!add_to_swap(folio))
1818 goto activate_locked_split;
1821 } else if (folio_test_swapbacked(folio) &&
1822 folio_test_large(folio)) {
1823 /* Split shmem folio */
1824 if (split_folio_to_list(folio, page_list))
1829 * If the folio was split above, the tail pages will make
1830 * their own pass through this function and be accounted
1833 if ((nr_pages > 1) && !folio_test_large(folio)) {
1834 sc->nr_scanned -= (nr_pages - 1);
1839 * The folio is mapped into the page tables of one or more
1840 * processes. Try to unmap it here.
1842 if (folio_mapped(folio)) {
1843 enum ttu_flags flags = TTU_BATCH_FLUSH;
1844 bool was_swapbacked = folio_test_swapbacked(folio);
1846 if (folio_test_pmd_mappable(folio))
1847 flags |= TTU_SPLIT_HUGE_PMD;
1849 try_to_unmap(folio, flags);
1850 if (folio_mapped(folio)) {
1851 stat->nr_unmap_fail += nr_pages;
1852 if (!was_swapbacked &&
1853 folio_test_swapbacked(folio))
1854 stat->nr_lazyfree_fail += nr_pages;
1855 goto activate_locked;
1859 mapping = folio_mapping(folio);
1860 if (folio_test_dirty(folio)) {
1862 * Only kswapd can writeback filesystem folios
1863 * to avoid risk of stack overflow. But avoid
1864 * injecting inefficient single-folio I/O into
1865 * flusher writeback as much as possible: only
1866 * write folios when we've encountered many
1867 * dirty folios, and when we've already scanned
1868 * the rest of the LRU for clean folios and see
1869 * the same dirty folios again (with the reclaim
1872 if (folio_is_file_lru(folio) &&
1873 (!current_is_kswapd() ||
1874 !folio_test_reclaim(folio) ||
1875 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1877 * Immediately reclaim when written back.
1878 * Similar in principle to deactivate_page()
1879 * except we already have the folio isolated
1880 * and know it's dirty
1882 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1884 folio_set_reclaim(folio);
1886 goto activate_locked;
1889 if (references == PAGEREF_RECLAIM_CLEAN)
1891 if (!may_enter_fs(folio, sc->gfp_mask))
1893 if (!sc->may_writepage)
1897 * Folio is dirty. Flush the TLB if a writable entry
1898 * potentially exists to avoid CPU writes after I/O
1899 * starts and then write it out here.
1901 try_to_unmap_flush_dirty();
1902 switch (pageout(folio, mapping, &plug)) {
1906 goto activate_locked;
1908 stat->nr_pageout += nr_pages;
1910 if (folio_test_writeback(folio))
1912 if (folio_test_dirty(folio))
1916 * A synchronous write - probably a ramdisk. Go
1917 * ahead and try to reclaim the folio.
1919 if (!folio_trylock(folio))
1921 if (folio_test_dirty(folio) ||
1922 folio_test_writeback(folio))
1924 mapping = folio_mapping(folio);
1927 ; /* try to free the folio below */
1932 * If the folio has buffers, try to free the buffer
1933 * mappings associated with this folio. If we succeed
1934 * we try to free the folio as well.
1936 * We do this even if the folio is dirty.
1937 * filemap_release_folio() does not perform I/O, but it
1938 * is possible for a folio to have the dirty flag set,
1939 * but it is actually clean (all its buffers are clean).
1940 * This happens if the buffers were written out directly,
1941 * with submit_bh(). ext3 will do this, as well as
1942 * the blockdev mapping. filemap_release_folio() will
1943 * discover that cleanness and will drop the buffers
1944 * and mark the folio clean - it can be freed.
1946 * Rarely, folios can have buffers and no ->mapping.
1947 * These are the folios which were not successfully
1948 * invalidated in truncate_cleanup_folio(). We try to
1949 * drop those buffers here and if that worked, and the
1950 * folio is no longer mapped into process address space
1951 * (refcount == 1) it can be freed. Otherwise, leave
1952 * the folio on the LRU so it is swappable.
1954 if (folio_has_private(folio)) {
1955 if (!filemap_release_folio(folio, sc->gfp_mask))
1956 goto activate_locked;
1957 if (!mapping && folio_ref_count(folio) == 1) {
1958 folio_unlock(folio);
1959 if (folio_put_testzero(folio))
1963 * rare race with speculative reference.
1964 * the speculative reference will free
1965 * this folio shortly, so we may
1966 * increment nr_reclaimed here (and
1967 * leave it off the LRU).
1969 nr_reclaimed += nr_pages;
1975 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1976 /* follow __remove_mapping for reference */
1977 if (!folio_ref_freeze(folio, 1))
1980 * The folio has only one reference left, which is
1981 * from the isolation. After the caller puts the
1982 * folio back on the lru and drops the reference, the
1983 * folio will be freed anyway. It doesn't matter
1984 * which lru it goes on. So we don't bother checking
1985 * the dirty flag here.
1987 count_vm_events(PGLAZYFREED, nr_pages);
1988 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1989 } else if (!mapping || !__remove_mapping(mapping, folio, true,
1990 sc->target_mem_cgroup))
1993 folio_unlock(folio);
1996 * Folio may get swapped out as a whole, need to account
1999 nr_reclaimed += nr_pages;
2002 * Is there need to periodically free_page_list? It would
2003 * appear not as the counts should be low
2005 if (unlikely(folio_test_large(folio)))
2006 destroy_large_folio(folio);
2008 list_add(&folio->lru, &free_pages);
2011 activate_locked_split:
2013 * The tail pages that are failed to add into swap cache
2014 * reach here. Fixup nr_scanned and nr_pages.
2017 sc->nr_scanned -= (nr_pages - 1);
2021 /* Not a candidate for swapping, so reclaim swap space. */
2022 if (folio_test_swapcache(folio) &&
2023 (mem_cgroup_swap_full(&folio->page) ||
2024 folio_test_mlocked(folio)))
2025 try_to_free_swap(&folio->page);
2026 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2027 if (!folio_test_mlocked(folio)) {
2028 int type = folio_is_file_lru(folio);
2029 folio_set_active(folio);
2030 stat->nr_activate[type] += nr_pages;
2031 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2034 folio_unlock(folio);
2036 list_add(&folio->lru, &ret_pages);
2037 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2038 folio_test_unevictable(folio), folio);
2040 /* 'page_list' is always empty here */
2042 /* Migrate folios selected for demotion */
2043 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
2044 /* Folios that could not be demoted are still in @demote_pages */
2045 if (!list_empty(&demote_pages)) {
2046 /* Folios which weren't demoted go back on @page_list for retry: */
2047 list_splice_init(&demote_pages, page_list);
2048 do_demote_pass = false;
2052 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2054 mem_cgroup_uncharge_list(&free_pages);
2055 try_to_unmap_flush();
2056 free_unref_page_list(&free_pages);
2058 list_splice(&ret_pages, page_list);
2059 count_vm_events(PGACTIVATE, pgactivate);
2062 swap_write_unplug(plug);
2063 return nr_reclaimed;
2066 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2067 struct list_head *folio_list)
2069 struct scan_control sc = {
2070 .gfp_mask = GFP_KERNEL,
2073 struct reclaim_stat stat;
2074 unsigned int nr_reclaimed;
2075 struct folio *folio, *next;
2076 LIST_HEAD(clean_folios);
2077 unsigned int noreclaim_flag;
2079 list_for_each_entry_safe(folio, next, folio_list, lru) {
2080 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2081 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2082 !folio_test_unevictable(folio)) {
2083 folio_clear_active(folio);
2084 list_move(&folio->lru, &clean_folios);
2089 * We should be safe here since we are only dealing with file pages and
2090 * we are not kswapd and therefore cannot write dirty file pages. But
2091 * call memalloc_noreclaim_save() anyway, just in case these conditions
2092 * change in the future.
2094 noreclaim_flag = memalloc_noreclaim_save();
2095 nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc,
2097 memalloc_noreclaim_restore(noreclaim_flag);
2099 list_splice(&clean_folios, folio_list);
2100 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2101 -(long)nr_reclaimed);
2103 * Since lazyfree pages are isolated from file LRU from the beginning,
2104 * they will rotate back to anonymous LRU in the end if it failed to
2105 * discard so isolated count will be mismatched.
2106 * Compensate the isolated count for both LRU lists.
2108 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2109 stat.nr_lazyfree_fail);
2110 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2111 -(long)stat.nr_lazyfree_fail);
2112 return nr_reclaimed;
2116 * Update LRU sizes after isolating pages. The LRU size updates must
2117 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2119 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2120 enum lru_list lru, unsigned long *nr_zone_taken)
2124 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2125 if (!nr_zone_taken[zid])
2128 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2134 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2136 * lruvec->lru_lock is heavily contended. Some of the functions that
2137 * shrink the lists perform better by taking out a batch of pages
2138 * and working on them outside the LRU lock.
2140 * For pagecache intensive workloads, this function is the hottest
2141 * spot in the kernel (apart from copy_*_user functions).
2143 * Lru_lock must be held before calling this function.
2145 * @nr_to_scan: The number of eligible pages to look through on the list.
2146 * @lruvec: The LRU vector to pull pages from.
2147 * @dst: The temp list to put pages on to.
2148 * @nr_scanned: The number of pages that were scanned.
2149 * @sc: The scan_control struct for this reclaim session
2150 * @lru: LRU list id for isolating
2152 * returns how many pages were moved onto *@dst.
2154 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
2155 struct lruvec *lruvec, struct list_head *dst,
2156 unsigned long *nr_scanned, struct scan_control *sc,
2159 struct list_head *src = &lruvec->lists[lru];
2160 unsigned long nr_taken = 0;
2161 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2162 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2163 unsigned long skipped = 0;
2164 unsigned long scan, total_scan, nr_pages;
2165 LIST_HEAD(folios_skipped);
2169 while (scan < nr_to_scan && !list_empty(src)) {
2170 struct list_head *move_to = src;
2171 struct folio *folio;
2173 folio = lru_to_folio(src);
2174 prefetchw_prev_lru_folio(folio, src, flags);
2176 nr_pages = folio_nr_pages(folio);
2177 total_scan += nr_pages;
2179 if (folio_zonenum(folio) > sc->reclaim_idx) {
2180 nr_skipped[folio_zonenum(folio)] += nr_pages;
2181 move_to = &folios_skipped;
2186 * Do not count skipped folios because that makes the function
2187 * return with no isolated folios if the LRU mostly contains
2188 * ineligible folios. This causes the VM to not reclaim any
2189 * folios, triggering a premature OOM.
2190 * Account all pages in a folio.
2194 if (!folio_test_lru(folio))
2196 if (!sc->may_unmap && folio_mapped(folio))
2200 * Be careful not to clear the lru flag until after we're
2201 * sure the folio is not being freed elsewhere -- the
2202 * folio release code relies on it.
2204 if (unlikely(!folio_try_get(folio)))
2207 if (!folio_test_clear_lru(folio)) {
2208 /* Another thread is already isolating this folio */
2213 nr_taken += nr_pages;
2214 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2217 list_move(&folio->lru, move_to);
2221 * Splice any skipped folios to the start of the LRU list. Note that
2222 * this disrupts the LRU order when reclaiming for lower zones but
2223 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2224 * scanning would soon rescan the same folios to skip and waste lots
2227 if (!list_empty(&folios_skipped)) {
2230 list_splice(&folios_skipped, src);
2231 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2232 if (!nr_skipped[zid])
2235 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2236 skipped += nr_skipped[zid];
2239 *nr_scanned = total_scan;
2240 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2241 total_scan, skipped, nr_taken,
2242 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2243 update_lru_sizes(lruvec, lru, nr_zone_taken);
2248 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2249 * @folio: Folio to isolate from its LRU list.
2251 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2252 * corresponding to whatever LRU list the folio was on.
2254 * The folio will have its LRU flag cleared. If it was found on the
2255 * active list, it will have the Active flag set. If it was found on the
2256 * unevictable list, it will have the Unevictable flag set. These flags
2257 * may need to be cleared by the caller before letting the page go.
2261 * (1) Must be called with an elevated refcount on the page. This is a
2262 * fundamental difference from isolate_lru_pages() (which is called
2263 * without a stable reference).
2264 * (2) The lru_lock must not be held.
2265 * (3) Interrupts must be enabled.
2267 * Return: 0 if the folio was removed from an LRU list.
2268 * -EBUSY if the folio was not on an LRU list.
2270 int folio_isolate_lru(struct folio *folio)
2274 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2276 if (folio_test_clear_lru(folio)) {
2277 struct lruvec *lruvec;
2280 lruvec = folio_lruvec_lock_irq(folio);
2281 lruvec_del_folio(lruvec, folio);
2282 unlock_page_lruvec_irq(lruvec);
2290 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2291 * then get rescheduled. When there are massive number of tasks doing page
2292 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2293 * the LRU list will go small and be scanned faster than necessary, leading to
2294 * unnecessary swapping, thrashing and OOM.
2296 static int too_many_isolated(struct pglist_data *pgdat, int file,
2297 struct scan_control *sc)
2299 unsigned long inactive, isolated;
2302 if (current_is_kswapd())
2305 if (!writeback_throttling_sane(sc))
2309 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2310 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2312 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2313 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2317 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2318 * won't get blocked by normal direct-reclaimers, forming a circular
2321 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2324 too_many = isolated > inactive;
2326 /* Wake up tasks throttled due to too_many_isolated. */
2328 wake_throttle_isolated(pgdat);
2334 * move_pages_to_lru() moves folios from private @list to appropriate LRU list.
2335 * On return, @list is reused as a list of folios to be freed by the caller.
2337 * Returns the number of pages moved to the given lruvec.
2339 static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2340 struct list_head *list)
2342 int nr_pages, nr_moved = 0;
2343 LIST_HEAD(folios_to_free);
2345 while (!list_empty(list)) {
2346 struct folio *folio = lru_to_folio(list);
2348 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2349 list_del(&folio->lru);
2350 if (unlikely(!folio_evictable(folio))) {
2351 spin_unlock_irq(&lruvec->lru_lock);
2352 folio_putback_lru(folio);
2353 spin_lock_irq(&lruvec->lru_lock);
2358 * The folio_set_lru needs to be kept here for list integrity.
2360 * #0 move_pages_to_lru #1 release_pages
2361 * if (!folio_put_testzero())
2362 * if (folio_put_testzero())
2363 * !lru //skip lru_lock
2365 * list_add(&folio->lru,)
2366 * list_add(&folio->lru,)
2368 folio_set_lru(folio);
2370 if (unlikely(folio_put_testzero(folio))) {
2371 __folio_clear_lru_flags(folio);
2373 if (unlikely(folio_test_large(folio))) {
2374 spin_unlock_irq(&lruvec->lru_lock);
2375 destroy_large_folio(folio);
2376 spin_lock_irq(&lruvec->lru_lock);
2378 list_add(&folio->lru, &folios_to_free);
2384 * All pages were isolated from the same lruvec (and isolation
2385 * inhibits memcg migration).
2387 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2388 lruvec_add_folio(lruvec, folio);
2389 nr_pages = folio_nr_pages(folio);
2390 nr_moved += nr_pages;
2391 if (folio_test_active(folio))
2392 workingset_age_nonresident(lruvec, nr_pages);
2396 * To save our caller's stack, now use input list for pages to free.
2398 list_splice(&folios_to_free, list);
2404 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2405 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2406 * we should not throttle. Otherwise it is safe to do so.
2408 static int current_may_throttle(void)
2410 return !(current->flags & PF_LOCAL_THROTTLE);
2414 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2415 * of reclaimed pages
2417 static unsigned long
2418 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
2419 struct scan_control *sc, enum lru_list lru)
2421 LIST_HEAD(page_list);
2422 unsigned long nr_scanned;
2423 unsigned int nr_reclaimed = 0;
2424 unsigned long nr_taken;
2425 struct reclaim_stat stat;
2426 bool file = is_file_lru(lru);
2427 enum vm_event_item item;
2428 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2429 bool stalled = false;
2431 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2435 /* wait a bit for the reclaimer. */
2437 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2439 /* We are about to die and free our memory. Return now. */
2440 if (fatal_signal_pending(current))
2441 return SWAP_CLUSTER_MAX;
2446 spin_lock_irq(&lruvec->lru_lock);
2448 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2449 &nr_scanned, sc, lru);
2451 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2452 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2453 if (!cgroup_reclaim(sc))
2454 __count_vm_events(item, nr_scanned);
2455 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2456 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2458 spin_unlock_irq(&lruvec->lru_lock);
2463 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2465 spin_lock_irq(&lruvec->lru_lock);
2466 move_pages_to_lru(lruvec, &page_list);
2468 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2469 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2470 if (!cgroup_reclaim(sc))
2471 __count_vm_events(item, nr_reclaimed);
2472 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2473 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2474 spin_unlock_irq(&lruvec->lru_lock);
2476 lru_note_cost(lruvec, file, stat.nr_pageout);
2477 mem_cgroup_uncharge_list(&page_list);
2478 free_unref_page_list(&page_list);
2481 * If dirty pages are scanned that are not queued for IO, it
2482 * implies that flushers are not doing their job. This can
2483 * happen when memory pressure pushes dirty pages to the end of
2484 * the LRU before the dirty limits are breached and the dirty
2485 * data has expired. It can also happen when the proportion of
2486 * dirty pages grows not through writes but through memory
2487 * pressure reclaiming all the clean cache. And in some cases,
2488 * the flushers simply cannot keep up with the allocation
2489 * rate. Nudge the flusher threads in case they are asleep.
2491 if (stat.nr_unqueued_dirty == nr_taken)
2492 wakeup_flusher_threads(WB_REASON_VMSCAN);
2494 sc->nr.dirty += stat.nr_dirty;
2495 sc->nr.congested += stat.nr_congested;
2496 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2497 sc->nr.writeback += stat.nr_writeback;
2498 sc->nr.immediate += stat.nr_immediate;
2499 sc->nr.taken += nr_taken;
2501 sc->nr.file_taken += nr_taken;
2503 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2504 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2505 return nr_reclaimed;
2509 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2511 * We move them the other way if the folio is referenced by one or more
2514 * If the folios are mostly unmapped, the processing is fast and it is
2515 * appropriate to hold lru_lock across the whole operation. But if
2516 * the folios are mapped, the processing is slow (folio_referenced()), so
2517 * we should drop lru_lock around each folio. It's impossible to balance
2518 * this, so instead we remove the folios from the LRU while processing them.
2519 * It is safe to rely on the active flag against the non-LRU folios in here
2520 * because nobody will play with that bit on a non-LRU folio.
2522 * The downside is that we have to touch folio->_refcount against each folio.
2523 * But we had to alter folio->flags anyway.
2525 static void shrink_active_list(unsigned long nr_to_scan,
2526 struct lruvec *lruvec,
2527 struct scan_control *sc,
2530 unsigned long nr_taken;
2531 unsigned long nr_scanned;
2532 unsigned long vm_flags;
2533 LIST_HEAD(l_hold); /* The folios which were snipped off */
2534 LIST_HEAD(l_active);
2535 LIST_HEAD(l_inactive);
2536 unsigned nr_deactivate, nr_activate;
2537 unsigned nr_rotated = 0;
2538 int file = is_file_lru(lru);
2539 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2543 spin_lock_irq(&lruvec->lru_lock);
2545 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2546 &nr_scanned, sc, lru);
2548 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2550 if (!cgroup_reclaim(sc))
2551 __count_vm_events(PGREFILL, nr_scanned);
2552 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2554 spin_unlock_irq(&lruvec->lru_lock);
2556 while (!list_empty(&l_hold)) {
2557 struct folio *folio;
2560 folio = lru_to_folio(&l_hold);
2561 list_del(&folio->lru);
2563 if (unlikely(!folio_evictable(folio))) {
2564 folio_putback_lru(folio);
2568 if (unlikely(buffer_heads_over_limit)) {
2569 if (folio_test_private(folio) && folio_trylock(folio)) {
2570 if (folio_test_private(folio))
2571 filemap_release_folio(folio, 0);
2572 folio_unlock(folio);
2576 /* Referenced or rmap lock contention: rotate */
2577 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2580 * Identify referenced, file-backed active folios and
2581 * give them one more trip around the active list. So
2582 * that executable code get better chances to stay in
2583 * memory under moderate memory pressure. Anon folios
2584 * are not likely to be evicted by use-once streaming
2585 * IO, plus JVM can create lots of anon VM_EXEC folios,
2586 * so we ignore them here.
2588 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2589 nr_rotated += folio_nr_pages(folio);
2590 list_add(&folio->lru, &l_active);
2595 folio_clear_active(folio); /* we are de-activating */
2596 folio_set_workingset(folio);
2597 list_add(&folio->lru, &l_inactive);
2601 * Move folios back to the lru list.
2603 spin_lock_irq(&lruvec->lru_lock);
2605 nr_activate = move_pages_to_lru(lruvec, &l_active);
2606 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2607 /* Keep all free folios in l_active list */
2608 list_splice(&l_inactive, &l_active);
2610 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2611 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2613 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2614 spin_unlock_irq(&lruvec->lru_lock);
2616 mem_cgroup_uncharge_list(&l_active);
2617 free_unref_page_list(&l_active);
2618 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2619 nr_deactivate, nr_rotated, sc->priority, file);
2622 static unsigned int reclaim_page_list(struct list_head *page_list,
2623 struct pglist_data *pgdat)
2625 struct reclaim_stat dummy_stat;
2626 unsigned int nr_reclaimed;
2627 struct folio *folio;
2628 struct scan_control sc = {
2629 .gfp_mask = GFP_KERNEL,
2636 nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false);
2637 while (!list_empty(page_list)) {
2638 folio = lru_to_folio(page_list);
2639 list_del(&folio->lru);
2640 folio_putback_lru(folio);
2643 return nr_reclaimed;
2646 unsigned long reclaim_pages(struct list_head *folio_list)
2649 unsigned int nr_reclaimed = 0;
2650 LIST_HEAD(node_folio_list);
2651 unsigned int noreclaim_flag;
2653 if (list_empty(folio_list))
2654 return nr_reclaimed;
2656 noreclaim_flag = memalloc_noreclaim_save();
2658 nid = folio_nid(lru_to_folio(folio_list));
2660 struct folio *folio = lru_to_folio(folio_list);
2662 if (nid == folio_nid(folio)) {
2663 folio_clear_active(folio);
2664 list_move(&folio->lru, &node_folio_list);
2668 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2669 nid = folio_nid(lru_to_folio(folio_list));
2670 } while (!list_empty(folio_list));
2672 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2674 memalloc_noreclaim_restore(noreclaim_flag);
2676 return nr_reclaimed;
2679 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2680 struct lruvec *lruvec, struct scan_control *sc)
2682 if (is_active_lru(lru)) {
2683 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2684 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2686 sc->skipped_deactivate = 1;
2690 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2694 * The inactive anon list should be small enough that the VM never has
2695 * to do too much work.
2697 * The inactive file list should be small enough to leave most memory
2698 * to the established workingset on the scan-resistant active list,
2699 * but large enough to avoid thrashing the aggregate readahead window.
2701 * Both inactive lists should also be large enough that each inactive
2702 * page has a chance to be referenced again before it is reclaimed.
2704 * If that fails and refaulting is observed, the inactive list grows.
2706 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2707 * on this LRU, maintained by the pageout code. An inactive_ratio
2708 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2711 * memory ratio inactive
2712 * -------------------------------------
2721 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2723 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2724 unsigned long inactive, active;
2725 unsigned long inactive_ratio;
2728 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2729 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2731 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2733 inactive_ratio = int_sqrt(10 * gb);
2737 return inactive * inactive_ratio < active;
2747 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2750 struct lruvec *target_lruvec;
2752 if (lru_gen_enabled())
2755 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2758 * Flush the memory cgroup stats, so that we read accurate per-memcg
2759 * lruvec stats for heuristics.
2761 mem_cgroup_flush_stats();
2764 * Determine the scan balance between anon and file LRUs.
2766 spin_lock_irq(&target_lruvec->lru_lock);
2767 sc->anon_cost = target_lruvec->anon_cost;
2768 sc->file_cost = target_lruvec->file_cost;
2769 spin_unlock_irq(&target_lruvec->lru_lock);
2772 * Target desirable inactive:active list ratios for the anon
2773 * and file LRU lists.
2775 if (!sc->force_deactivate) {
2776 unsigned long refaults;
2779 * When refaults are being observed, it means a new
2780 * workingset is being established. Deactivate to get
2781 * rid of any stale active pages quickly.
2783 refaults = lruvec_page_state(target_lruvec,
2784 WORKINGSET_ACTIVATE_ANON);
2785 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2786 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2787 sc->may_deactivate |= DEACTIVATE_ANON;
2789 sc->may_deactivate &= ~DEACTIVATE_ANON;
2791 refaults = lruvec_page_state(target_lruvec,
2792 WORKINGSET_ACTIVATE_FILE);
2793 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2794 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2795 sc->may_deactivate |= DEACTIVATE_FILE;
2797 sc->may_deactivate &= ~DEACTIVATE_FILE;
2799 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2802 * If we have plenty of inactive file pages that aren't
2803 * thrashing, try to reclaim those first before touching
2806 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2807 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2808 sc->cache_trim_mode = 1;
2810 sc->cache_trim_mode = 0;
2813 * Prevent the reclaimer from falling into the cache trap: as
2814 * cache pages start out inactive, every cache fault will tip
2815 * the scan balance towards the file LRU. And as the file LRU
2816 * shrinks, so does the window for rotation from references.
2817 * This means we have a runaway feedback loop where a tiny
2818 * thrashing file LRU becomes infinitely more attractive than
2819 * anon pages. Try to detect this based on file LRU size.
2821 if (!cgroup_reclaim(sc)) {
2822 unsigned long total_high_wmark = 0;
2823 unsigned long free, anon;
2826 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2827 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2828 node_page_state(pgdat, NR_INACTIVE_FILE);
2830 for (z = 0; z < MAX_NR_ZONES; z++) {
2831 struct zone *zone = &pgdat->node_zones[z];
2833 if (!managed_zone(zone))
2836 total_high_wmark += high_wmark_pages(zone);
2840 * Consider anon: if that's low too, this isn't a
2841 * runaway file reclaim problem, but rather just
2842 * extreme pressure. Reclaim as per usual then.
2844 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2847 file + free <= total_high_wmark &&
2848 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2849 anon >> sc->priority;
2854 * Determine how aggressively the anon and file LRU lists should be
2857 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2858 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2860 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2863 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2864 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2865 unsigned long anon_cost, file_cost, total_cost;
2866 int swappiness = mem_cgroup_swappiness(memcg);
2867 u64 fraction[ANON_AND_FILE];
2868 u64 denominator = 0; /* gcc */
2869 enum scan_balance scan_balance;
2870 unsigned long ap, fp;
2873 /* If we have no swap space, do not bother scanning anon pages. */
2874 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2875 scan_balance = SCAN_FILE;
2880 * Global reclaim will swap to prevent OOM even with no
2881 * swappiness, but memcg users want to use this knob to
2882 * disable swapping for individual groups completely when
2883 * using the memory controller's swap limit feature would be
2886 if (cgroup_reclaim(sc) && !swappiness) {
2887 scan_balance = SCAN_FILE;
2892 * Do not apply any pressure balancing cleverness when the
2893 * system is close to OOM, scan both anon and file equally
2894 * (unless the swappiness setting disagrees with swapping).
2896 if (!sc->priority && swappiness) {
2897 scan_balance = SCAN_EQUAL;
2902 * If the system is almost out of file pages, force-scan anon.
2904 if (sc->file_is_tiny) {
2905 scan_balance = SCAN_ANON;
2910 * If there is enough inactive page cache, we do not reclaim
2911 * anything from the anonymous working right now.
2913 if (sc->cache_trim_mode) {
2914 scan_balance = SCAN_FILE;
2918 scan_balance = SCAN_FRACT;
2920 * Calculate the pressure balance between anon and file pages.
2922 * The amount of pressure we put on each LRU is inversely
2923 * proportional to the cost of reclaiming each list, as
2924 * determined by the share of pages that are refaulting, times
2925 * the relative IO cost of bringing back a swapped out
2926 * anonymous page vs reloading a filesystem page (swappiness).
2928 * Although we limit that influence to ensure no list gets
2929 * left behind completely: at least a third of the pressure is
2930 * applied, before swappiness.
2932 * With swappiness at 100, anon and file have equal IO cost.
2934 total_cost = sc->anon_cost + sc->file_cost;
2935 anon_cost = total_cost + sc->anon_cost;
2936 file_cost = total_cost + sc->file_cost;
2937 total_cost = anon_cost + file_cost;
2939 ap = swappiness * (total_cost + 1);
2940 ap /= anon_cost + 1;
2942 fp = (200 - swappiness) * (total_cost + 1);
2943 fp /= file_cost + 1;
2947 denominator = ap + fp;
2949 for_each_evictable_lru(lru) {
2950 int file = is_file_lru(lru);
2951 unsigned long lruvec_size;
2952 unsigned long low, min;
2955 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2956 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2961 * Scale a cgroup's reclaim pressure by proportioning
2962 * its current usage to its memory.low or memory.min
2965 * This is important, as otherwise scanning aggression
2966 * becomes extremely binary -- from nothing as we
2967 * approach the memory protection threshold, to totally
2968 * nominal as we exceed it. This results in requiring
2969 * setting extremely liberal protection thresholds. It
2970 * also means we simply get no protection at all if we
2971 * set it too low, which is not ideal.
2973 * If there is any protection in place, we reduce scan
2974 * pressure by how much of the total memory used is
2975 * within protection thresholds.
2977 * There is one special case: in the first reclaim pass,
2978 * we skip over all groups that are within their low
2979 * protection. If that fails to reclaim enough pages to
2980 * satisfy the reclaim goal, we come back and override
2981 * the best-effort low protection. However, we still
2982 * ideally want to honor how well-behaved groups are in
2983 * that case instead of simply punishing them all
2984 * equally. As such, we reclaim them based on how much
2985 * memory they are using, reducing the scan pressure
2986 * again by how much of the total memory used is under
2989 unsigned long cgroup_size = mem_cgroup_size(memcg);
2990 unsigned long protection;
2992 /* memory.low scaling, make sure we retry before OOM */
2993 if (!sc->memcg_low_reclaim && low > min) {
2995 sc->memcg_low_skipped = 1;
3000 /* Avoid TOCTOU with earlier protection check */
3001 cgroup_size = max(cgroup_size, protection);
3003 scan = lruvec_size - lruvec_size * protection /
3007 * Minimally target SWAP_CLUSTER_MAX pages to keep
3008 * reclaim moving forwards, avoiding decrementing
3009 * sc->priority further than desirable.
3011 scan = max(scan, SWAP_CLUSTER_MAX);
3016 scan >>= sc->priority;
3019 * If the cgroup's already been deleted, make sure to
3020 * scrape out the remaining cache.
3022 if (!scan && !mem_cgroup_online(memcg))
3023 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
3025 switch (scan_balance) {
3027 /* Scan lists relative to size */
3031 * Scan types proportional to swappiness and
3032 * their relative recent reclaim efficiency.
3033 * Make sure we don't miss the last page on
3034 * the offlined memory cgroups because of a
3037 scan = mem_cgroup_online(memcg) ?
3038 div64_u64(scan * fraction[file], denominator) :
3039 DIV64_U64_ROUND_UP(scan * fraction[file],
3044 /* Scan one type exclusively */
3045 if ((scan_balance == SCAN_FILE) != file)
3049 /* Look ma, no brain */
3058 * Anonymous LRU management is a waste if there is
3059 * ultimately no way to reclaim the memory.
3061 static bool can_age_anon_pages(struct pglist_data *pgdat,
3062 struct scan_control *sc)
3064 /* Aging the anon LRU is valuable if swap is present: */
3065 if (total_swap_pages > 0)
3068 /* Also valuable if anon pages can be demoted: */
3069 return can_demote(pgdat->node_id, sc);
3072 #ifdef CONFIG_LRU_GEN
3074 #ifdef CONFIG_LRU_GEN_ENABLED
3075 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3076 #define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
3078 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3079 #define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
3082 /******************************************************************************
3084 ******************************************************************************/
3086 #define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
3088 #define DEFINE_MAX_SEQ(lruvec) \
3089 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3091 #define DEFINE_MIN_SEQ(lruvec) \
3092 unsigned long min_seq[ANON_AND_FILE] = { \
3093 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3094 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3097 #define for_each_gen_type_zone(gen, type, zone) \
3098 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3099 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3100 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3102 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
3104 struct pglist_data *pgdat = NODE_DATA(nid);
3108 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3110 /* for hotadd_new_pgdat() */
3112 lruvec->pgdat = pgdat;
3117 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3119 return pgdat ? &pgdat->__lruvec : NULL;
3122 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3124 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3125 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3127 if (!can_demote(pgdat->node_id, sc) &&
3128 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3131 return mem_cgroup_swappiness(memcg);
3134 static int get_nr_gens(struct lruvec *lruvec, int type)
3136 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3139 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3141 /* see the comment on lru_gen_struct */
3142 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3143 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3144 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3147 /******************************************************************************
3149 ******************************************************************************/
3151 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3153 static struct lru_gen_mm_list mm_list = {
3154 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3155 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3160 return &memcg->mm_list;
3162 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3167 void lru_gen_add_mm(struct mm_struct *mm)
3170 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3171 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3173 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3175 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3176 mm->lru_gen.memcg = memcg;
3178 spin_lock(&mm_list->lock);
3180 for_each_node_state(nid, N_MEMORY) {
3181 struct lruvec *lruvec = get_lruvec(memcg, nid);
3186 /* the first addition since the last iteration */
3187 if (lruvec->mm_state.tail == &mm_list->fifo)
3188 lruvec->mm_state.tail = &mm->lru_gen.list;
3191 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3193 spin_unlock(&mm_list->lock);
3196 void lru_gen_del_mm(struct mm_struct *mm)
3199 struct lru_gen_mm_list *mm_list;
3200 struct mem_cgroup *memcg = NULL;
3202 if (list_empty(&mm->lru_gen.list))
3206 memcg = mm->lru_gen.memcg;
3208 mm_list = get_mm_list(memcg);
3210 spin_lock(&mm_list->lock);
3212 for_each_node(nid) {
3213 struct lruvec *lruvec = get_lruvec(memcg, nid);
3218 /* where the last iteration ended (exclusive) */
3219 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3220 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3222 /* where the current iteration continues (inclusive) */
3223 if (lruvec->mm_state.head != &mm->lru_gen.list)
3226 lruvec->mm_state.head = lruvec->mm_state.head->next;
3227 /* the deletion ends the current iteration */
3228 if (lruvec->mm_state.head == &mm_list->fifo)
3229 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3232 list_del_init(&mm->lru_gen.list);
3234 spin_unlock(&mm_list->lock);
3237 mem_cgroup_put(mm->lru_gen.memcg);
3238 mm->lru_gen.memcg = NULL;
3243 void lru_gen_migrate_mm(struct mm_struct *mm)
3245 struct mem_cgroup *memcg;
3246 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3248 VM_WARN_ON_ONCE(task->mm != mm);
3249 lockdep_assert_held(&task->alloc_lock);
3251 /* for mm_update_next_owner() */
3252 if (mem_cgroup_disabled())
3256 memcg = mem_cgroup_from_task(task);
3258 if (memcg == mm->lru_gen.memcg)
3261 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3262 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3270 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3271 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3272 * bits in a bitmap, k is the number of hash functions and n is the number of
3275 * Page table walkers use one of the two filters to reduce their search space.
3276 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3277 * aging uses the double-buffering technique to flip to the other filter each
3278 * time it produces a new generation. For non-leaf entries that have enough
3279 * leaf entries, the aging carries them over to the next generation in
3280 * walk_pmd_range(); the eviction also report them when walking the rmap
3281 * in lru_gen_look_around().
3283 * For future optimizations:
3284 * 1. It's not necessary to keep both filters all the time. The spare one can be
3285 * freed after the RCU grace period and reallocated if needed again.
3286 * 2. And when reallocating, it's worth scaling its size according to the number
3287 * of inserted entries in the other filter, to reduce the memory overhead on
3288 * small systems and false positives on large systems.
3289 * 3. Jenkins' hash function is an alternative to Knuth's.
3291 #define BLOOM_FILTER_SHIFT 15
3293 static inline int filter_gen_from_seq(unsigned long seq)
3295 return seq % NR_BLOOM_FILTERS;
3298 static void get_item_key(void *item, int *key)
3300 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3302 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3304 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3305 key[1] = hash >> BLOOM_FILTER_SHIFT;
3308 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3310 unsigned long *filter;
3311 int gen = filter_gen_from_seq(seq);
3313 filter = lruvec->mm_state.filters[gen];
3315 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3319 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3320 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3321 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3324 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3327 unsigned long *filter;
3328 int gen = filter_gen_from_seq(seq);
3330 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3334 get_item_key(item, key);
3336 if (!test_bit(key[0], filter))
3337 set_bit(key[0], filter);
3338 if (!test_bit(key[1], filter))
3339 set_bit(key[1], filter);
3342 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3345 unsigned long *filter;
3346 int gen = filter_gen_from_seq(seq);
3348 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3352 get_item_key(item, key);
3354 return test_bit(key[0], filter) && test_bit(key[1], filter);
3357 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3362 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3365 hist = lru_hist_from_seq(walk->max_seq);
3367 for (i = 0; i < NR_MM_STATS; i++) {
3368 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3369 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3370 walk->mm_stats[i] = 0;
3374 if (NR_HIST_GENS > 1 && last) {
3375 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3377 for (i = 0; i < NR_MM_STATS; i++)
3378 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3382 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3385 unsigned long size = 0;
3386 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3387 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3389 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3392 clear_bit(key, &mm->lru_gen.bitmap);
3394 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3395 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3396 get_mm_counter(mm, MM_ANONPAGES) +
3397 get_mm_counter(mm, MM_SHMEMPAGES);
3400 if (size < MIN_LRU_BATCH)
3403 return !mmget_not_zero(mm);
3406 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3407 struct mm_struct **iter)
3411 struct mm_struct *mm = NULL;
3412 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3413 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3414 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3417 * There are four interesting cases for this page table walker:
3418 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3419 * there is nothing left to do.
3420 * 2. It's the first of the current generation, and it needs to reset
3421 * the Bloom filter for the next generation.
3422 * 3. It reaches the end of mm_list, and it needs to increment
3423 * mm_state->seq; the iteration is done.
3424 * 4. It's the last of the current generation, and it needs to reset the
3425 * mm stats counters for the next generation.
3427 spin_lock(&mm_list->lock);
3429 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3430 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3431 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3433 if (walk->max_seq <= mm_state->seq) {
3439 if (!mm_state->nr_walkers) {
3440 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3442 mm_state->head = mm_list->fifo.next;
3446 while (!mm && mm_state->head != &mm_list->fifo) {
3447 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3449 mm_state->head = mm_state->head->next;
3451 /* force scan for those added after the last iteration */
3452 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3453 mm_state->tail = mm_state->head;
3454 walk->force_scan = true;
3457 if (should_skip_mm(mm, walk))
3461 if (mm_state->head == &mm_list->fifo)
3462 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3465 mm_state->nr_walkers--;
3467 mm_state->nr_walkers++;
3469 if (mm_state->nr_walkers)
3473 reset_mm_stats(lruvec, walk, last);
3475 spin_unlock(&mm_list->lock);
3478 reset_bloom_filter(lruvec, walk->max_seq + 1);
3488 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3490 bool success = false;
3491 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3492 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3493 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3495 spin_lock(&mm_list->lock);
3497 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3499 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3500 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3502 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3503 reset_mm_stats(lruvec, NULL, true);
3507 spin_unlock(&mm_list->lock);
3512 /******************************************************************************
3513 * refault feedback loop
3514 ******************************************************************************/
3517 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3519 * The P term is refaulted/(evicted+protected) from a tier in the generation
3520 * currently being evicted; the I term is the exponential moving average of the
3521 * P term over the generations previously evicted, using the smoothing factor
3522 * 1/2; the D term isn't supported.
3524 * The setpoint (SP) is always the first tier of one type; the process variable
3525 * (PV) is either any tier of the other type or any other tier of the same
3528 * The error is the difference between the SP and the PV; the correction is to
3529 * turn off protection when SP>PV or turn on protection when SP<PV.
3531 * For future optimizations:
3532 * 1. The D term may discount the other two terms over time so that long-lived
3533 * generations can resist stale information.
3536 unsigned long refaulted;
3537 unsigned long total;
3541 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3542 struct ctrl_pos *pos)
3544 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3545 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3547 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3548 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3549 pos->total = lrugen->avg_total[type][tier] +
3550 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3552 pos->total += lrugen->protected[hist][type][tier - 1];
3556 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3559 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3560 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3561 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3563 lockdep_assert_held(&lruvec->lru_lock);
3565 if (!carryover && !clear)
3568 hist = lru_hist_from_seq(seq);
3570 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3574 sum = lrugen->avg_refaulted[type][tier] +
3575 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3576 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3578 sum = lrugen->avg_total[type][tier] +
3579 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3581 sum += lrugen->protected[hist][type][tier - 1];
3582 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3586 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3587 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3589 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3594 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3597 * Return true if the PV has a limited number of refaults or a lower
3598 * refaulted/total than the SP.
3600 return pv->refaulted < MIN_LRU_BATCH ||
3601 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3602 (sp->refaulted + 1) * pv->total * pv->gain;
3605 /******************************************************************************
3607 ******************************************************************************/
3609 /* promote pages accessed through page tables */
3610 static int folio_update_gen(struct folio *folio, int gen)
3612 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3614 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3615 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3618 /* lru_gen_del_folio() has isolated this page? */
3619 if (!(old_flags & LRU_GEN_MASK)) {
3620 /* for shrink_page_list() */
3621 new_flags = old_flags | BIT(PG_referenced);
3625 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3626 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3627 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3629 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3632 /* protect pages accessed multiple times through file descriptors */
3633 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3635 int type = folio_is_file_lru(folio);
3636 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3637 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3638 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3640 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3643 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3644 /* folio_update_gen() has promoted this page? */
3645 if (new_gen >= 0 && new_gen != old_gen)
3648 new_gen = (old_gen + 1) % MAX_NR_GENS;
3650 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3651 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3652 /* for folio_end_writeback() */
3654 new_flags |= BIT(PG_reclaim);
3655 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3657 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3662 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3663 int old_gen, int new_gen)
3665 int type = folio_is_file_lru(folio);
3666 int zone = folio_zonenum(folio);
3667 int delta = folio_nr_pages(folio);
3669 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3670 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3674 walk->nr_pages[old_gen][type][zone] -= delta;
3675 walk->nr_pages[new_gen][type][zone] += delta;
3678 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3680 int gen, type, zone;
3681 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3685 for_each_gen_type_zone(gen, type, zone) {
3686 enum lru_list lru = type * LRU_INACTIVE_FILE;
3687 int delta = walk->nr_pages[gen][type][zone];
3692 walk->nr_pages[gen][type][zone] = 0;
3693 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3694 lrugen->nr_pages[gen][type][zone] + delta);
3696 if (lru_gen_is_active(lruvec, gen))
3698 __update_lru_size(lruvec, lru, zone, delta);
3702 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3704 struct address_space *mapping;
3705 struct vm_area_struct *vma = args->vma;
3706 struct lru_gen_mm_walk *walk = args->private;
3708 if (!vma_is_accessible(vma))
3711 if (is_vm_hugetlb_page(vma))
3714 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3717 if (vma == get_gate_vma(vma->vm_mm))
3720 if (vma_is_anonymous(vma))
3721 return !walk->can_swap;
3723 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3726 mapping = vma->vm_file->f_mapping;
3727 if (mapping_unevictable(mapping))
3730 if (shmem_mapping(mapping))
3731 return !walk->can_swap;
3733 /* to exclude special mappings like dax, etc. */
3734 return !mapping->a_ops->read_folio;
3738 * Some userspace memory allocators map many single-page VMAs. Instead of
3739 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3740 * table to reduce zigzags and improve cache performance.
3742 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3743 unsigned long *vm_start, unsigned long *vm_end)
3745 unsigned long start = round_up(*vm_end, size);
3746 unsigned long end = (start | ~mask) + 1;
3748 VM_WARN_ON_ONCE(mask & size);
3749 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3752 if (start >= args->vma->vm_end) {
3753 args->vma = args->vma->vm_next;
3757 if (end && end <= args->vma->vm_start)
3760 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3761 args->vma = args->vma->vm_next;
3765 *vm_start = max(start, args->vma->vm_start);
3766 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3774 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3776 unsigned long pfn = pte_pfn(pte);
3778 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3780 if (!pte_present(pte) || is_zero_pfn(pfn))
3783 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3786 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3792 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3793 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3795 unsigned long pfn = pmd_pfn(pmd);
3797 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3799 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3802 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3805 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3812 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3813 struct pglist_data *pgdat, bool can_swap)
3815 struct folio *folio;
3817 /* try to avoid unnecessary memory loads */
3818 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3821 folio = pfn_folio(pfn);
3822 if (folio_nid(folio) != pgdat->node_id)
3825 if (folio_memcg_rcu(folio) != memcg)
3828 /* file VMAs can contain anon pages from COW */
3829 if (!folio_is_file_lru(folio) && !can_swap)
3835 static bool suitable_to_scan(int total, int young)
3837 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3839 /* suitable if the average number of young PTEs per cacheline is >=1 */
3840 return young * n >= total;
3843 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3844 struct mm_walk *args)
3852 struct lru_gen_mm_walk *walk = args->private;
3853 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3854 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3855 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3857 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3859 ptl = pte_lockptr(args->mm, pmd);
3860 if (!spin_trylock(ptl))
3863 arch_enter_lazy_mmu_mode();
3865 pte = pte_offset_map(pmd, start & PMD_MASK);
3867 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3869 struct folio *folio;
3872 walk->mm_stats[MM_LEAF_TOTAL]++;
3874 pfn = get_pte_pfn(pte[i], args->vma, addr);
3878 if (!pte_young(pte[i])) {
3879 walk->mm_stats[MM_LEAF_OLD]++;
3883 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3887 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3888 VM_WARN_ON_ONCE(true);
3891 walk->mm_stats[MM_LEAF_YOUNG]++;
3893 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
3894 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3895 !folio_test_swapcache(folio)))
3896 folio_mark_dirty(folio);
3898 old_gen = folio_update_gen(folio, new_gen);
3899 if (old_gen >= 0 && old_gen != new_gen)
3900 update_batch_size(walk, folio, old_gen, new_gen);
3903 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3908 arch_leave_lazy_mmu_mode();
3911 return suitable_to_scan(total, young);
3914 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3915 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3916 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3921 struct lru_gen_mm_walk *walk = args->private;
3922 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3923 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3924 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3926 VM_WARN_ON_ONCE(pud_leaf(*pud));
3928 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3934 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3935 if (i && i <= MIN_LRU_BATCH) {
3936 __set_bit(i - 1, bitmap);
3940 pmd = pmd_offset(pud, *start);
3942 ptl = pmd_lockptr(args->mm, pmd);
3943 if (!spin_trylock(ptl))
3946 arch_enter_lazy_mmu_mode();
3950 struct folio *folio;
3951 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3953 pfn = get_pmd_pfn(pmd[i], vma, addr);
3957 if (!pmd_trans_huge(pmd[i])) {
3958 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3959 get_cap(LRU_GEN_NONLEAF_YOUNG))
3960 pmdp_test_and_clear_young(vma, addr, pmd + i);
3964 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3968 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3971 walk->mm_stats[MM_LEAF_YOUNG]++;
3973 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
3974 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3975 !folio_test_swapcache(folio)))
3976 folio_mark_dirty(folio);
3978 old_gen = folio_update_gen(folio, new_gen);
3979 if (old_gen >= 0 && old_gen != new_gen)
3980 update_batch_size(walk, folio, old_gen, new_gen);
3982 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3983 } while (i <= MIN_LRU_BATCH);
3985 arch_leave_lazy_mmu_mode();
3989 bitmap_zero(bitmap, MIN_LRU_BATCH);
3992 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3993 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3998 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3999 struct mm_walk *args)
4005 struct vm_area_struct *vma;
4006 unsigned long pos = -1;
4007 struct lru_gen_mm_walk *walk = args->private;
4008 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4010 VM_WARN_ON_ONCE(pud_leaf(*pud));
4013 * Finish an entire PMD in two passes: the first only reaches to PTE
4014 * tables to avoid taking the PMD lock; the second, if necessary, takes
4015 * the PMD lock to clear the accessed bit in PMD entries.
4017 pmd = pmd_offset(pud, start & PUD_MASK);
4019 /* walk_pte_range() may call get_next_vma() */
4021 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
4022 pmd_t val = pmd_read_atomic(pmd + i);
4024 /* for pmd_read_atomic() */
4027 next = pmd_addr_end(addr, end);
4029 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4030 walk->mm_stats[MM_LEAF_TOTAL]++;
4034 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4035 if (pmd_trans_huge(val)) {
4036 unsigned long pfn = pmd_pfn(val);
4037 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4039 walk->mm_stats[MM_LEAF_TOTAL]++;
4041 if (!pmd_young(val)) {
4042 walk->mm_stats[MM_LEAF_OLD]++;
4046 /* try to avoid unnecessary memory loads */
4047 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4050 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4054 walk->mm_stats[MM_NONLEAF_TOTAL]++;
4056 #ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
4057 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
4058 if (!pmd_young(val))
4061 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4064 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4067 walk->mm_stats[MM_NONLEAF_FOUND]++;
4069 if (!walk_pte_range(&val, addr, next, args))
4072 walk->mm_stats[MM_NONLEAF_ADDED]++;
4074 /* carry over to the next generation */
4075 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4078 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
4080 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4084 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4085 struct mm_walk *args)
4091 struct lru_gen_mm_walk *walk = args->private;
4093 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4095 pud = pud_offset(p4d, start & P4D_MASK);
4097 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4098 pud_t val = READ_ONCE(pud[i]);
4100 next = pud_addr_end(addr, end);
4102 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4105 walk_pmd_range(&val, addr, next, args);
4107 /* a racy check to curtail the waiting time */
4108 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
4111 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4112 end = (addr | ~PUD_MASK) + 1;
4117 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4120 end = round_up(end, P4D_SIZE);
4122 if (!end || !args->vma)
4125 walk->next_addr = max(end, args->vma->vm_start);
4130 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4132 static const struct mm_walk_ops mm_walk_ops = {
4133 .test_walk = should_skip_vma,
4134 .p4d_entry = walk_pud_range,
4138 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4140 walk->next_addr = FIRST_USER_ADDRESS;
4145 /* folio_update_gen() requires stable folio_memcg() */
4146 if (!mem_cgroup_trylock_pages(memcg))
4149 /* the caller might be holding the lock for write */
4150 if (mmap_read_trylock(mm)) {
4151 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4153 mmap_read_unlock(mm);
4156 mem_cgroup_unlock_pages();
4158 if (walk->batched) {
4159 spin_lock_irq(&lruvec->lru_lock);
4160 reset_batch_size(lruvec, walk);
4161 spin_unlock_irq(&lruvec->lru_lock);
4165 } while (err == -EAGAIN);
4168 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4170 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4172 if (pgdat && current_is_kswapd()) {
4173 VM_WARN_ON_ONCE(walk);
4175 walk = &pgdat->mm_walk;
4176 } else if (!pgdat && !walk) {
4177 VM_WARN_ON_ONCE(current_is_kswapd());
4179 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4182 current->reclaim_state->mm_walk = walk;
4187 static void clear_mm_walk(void)
4189 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4191 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4192 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4194 current->reclaim_state->mm_walk = NULL;
4196 if (!current_is_kswapd())
4200 static void inc_min_seq(struct lruvec *lruvec, int type)
4202 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4204 reset_ctrl_pos(lruvec, type, true);
4205 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4208 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4210 int gen, type, zone;
4211 bool success = false;
4212 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4213 DEFINE_MIN_SEQ(lruvec);
4215 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4217 /* find the oldest populated generation */
4218 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4219 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4220 gen = lru_gen_from_seq(min_seq[type]);
4222 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4223 if (!list_empty(&lrugen->lists[gen][type][zone]))
4233 /* see the comment on lru_gen_struct */
4235 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4236 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4239 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4240 if (min_seq[type] == lrugen->min_seq[type])
4243 reset_ctrl_pos(lruvec, type, true);
4244 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4251 static void inc_max_seq(struct lruvec *lruvec, bool can_swap)
4255 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4257 spin_lock_irq(&lruvec->lru_lock);
4259 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4261 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4262 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4265 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
4267 inc_min_seq(lruvec, type);
4271 * Update the active/inactive LRU sizes for compatibility. Both sides of
4272 * the current max_seq need to be covered, since max_seq+1 can overlap
4273 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4274 * overlap, cold/hot inversion happens.
4276 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4277 next = lru_gen_from_seq(lrugen->max_seq + 1);
4279 for (type = 0; type < ANON_AND_FILE; type++) {
4280 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4281 enum lru_list lru = type * LRU_INACTIVE_FILE;
4282 long delta = lrugen->nr_pages[prev][type][zone] -
4283 lrugen->nr_pages[next][type][zone];
4288 __update_lru_size(lruvec, lru, zone, delta);
4289 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4293 for (type = 0; type < ANON_AND_FILE; type++)
4294 reset_ctrl_pos(lruvec, type, false);
4296 /* make sure preceding modifications appear */
4297 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4299 spin_unlock_irq(&lruvec->lru_lock);
4302 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4303 struct scan_control *sc, bool can_swap)
4306 struct lru_gen_mm_walk *walk;
4307 struct mm_struct *mm = NULL;
4308 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4310 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4312 /* see the comment in iterate_mm_list() */
4313 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4319 * If the hardware doesn't automatically set the accessed bit, fallback
4320 * to lru_gen_look_around(), which only clears the accessed bit in a
4321 * handful of PTEs. Spreading the work out over a period of time usually
4322 * is less efficient, but it avoids bursty page faults.
4324 if (!(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
4325 success = iterate_mm_list_nowalk(lruvec, max_seq);
4329 walk = set_mm_walk(NULL);
4331 success = iterate_mm_list_nowalk(lruvec, max_seq);
4335 walk->lruvec = lruvec;
4336 walk->max_seq = max_seq;
4337 walk->can_swap = can_swap;
4338 walk->force_scan = false;
4341 success = iterate_mm_list(lruvec, walk, &mm);
4343 walk_mm(lruvec, mm, walk);
4349 if (sc->priority <= DEF_PRIORITY - 2)
4350 wait_event_killable(lruvec->mm_state.wait,
4351 max_seq < READ_ONCE(lrugen->max_seq));
4353 return max_seq < READ_ONCE(lrugen->max_seq);
4356 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4358 inc_max_seq(lruvec, can_swap);
4359 /* either this sees any waiters or they will see updated max_seq */
4360 if (wq_has_sleeper(&lruvec->mm_state.wait))
4361 wake_up_all(&lruvec->mm_state.wait);
4363 wakeup_flusher_threads(WB_REASON_VMSCAN);
4368 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4369 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4371 int gen, type, zone;
4372 unsigned long old = 0;
4373 unsigned long young = 0;
4374 unsigned long total = 0;
4375 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4376 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4378 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4381 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4382 unsigned long size = 0;
4384 gen = lru_gen_from_seq(seq);
4386 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4387 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4392 else if (seq + MIN_NR_GENS == max_seq)
4397 /* try to scrape all its memory if this memcg was deleted */
4398 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4401 * The aging tries to be lazy to reduce the overhead, while the eviction
4402 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4403 * ideal number of generations is MIN_NR_GENS+1.
4405 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4407 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4411 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4412 * of the total number of pages for each generation. A reasonable range
4413 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4414 * aging cares about the upper bound of hot pages, while the eviction
4415 * cares about the lower bound of cold pages.
4417 if (young * MIN_NR_GENS > total)
4419 if (old * (MIN_NR_GENS + 2) < total)
4425 static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4428 unsigned long nr_to_scan;
4429 int swappiness = get_swappiness(lruvec, sc);
4430 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4431 DEFINE_MAX_SEQ(lruvec);
4432 DEFINE_MIN_SEQ(lruvec);
4434 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4436 mem_cgroup_calculate_protection(NULL, memcg);
4438 if (mem_cgroup_below_min(memcg))
4441 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4443 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness);
4446 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4448 struct mem_cgroup *memcg;
4450 VM_WARN_ON_ONCE(!current_is_kswapd());
4452 sc->last_reclaimed = sc->nr_reclaimed;
4455 * To reduce the chance of going into the aging path, which can be
4456 * costly, optimistically skip it if the flag below was cleared in the
4457 * eviction path. This improves the overall performance when multiple
4458 * memcgs are available.
4460 if (!sc->memcgs_need_aging) {
4461 sc->memcgs_need_aging = true;
4467 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4469 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4471 age_lruvec(lruvec, sc);
4474 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4480 * This function exploits spatial locality when shrink_page_list() walks the
4481 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4482 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4483 * the PTE table to the Bloom filter. This forms a feedback loop between the
4484 * eviction and the aging.
4486 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4490 unsigned long start;
4493 struct lru_gen_mm_walk *walk;
4495 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4496 struct folio *folio = pfn_folio(pvmw->pfn);
4497 struct mem_cgroup *memcg = folio_memcg(folio);
4498 struct pglist_data *pgdat = folio_pgdat(folio);
4499 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4500 DEFINE_MAX_SEQ(lruvec);
4501 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4503 lockdep_assert_held(pvmw->ptl);
4504 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4506 if (spin_is_contended(pvmw->ptl))
4509 /* avoid taking the LRU lock under the PTL when possible */
4510 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4512 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4513 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4515 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4516 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4517 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4518 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4519 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4521 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4522 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4526 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4529 arch_enter_lazy_mmu_mode();
4531 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4534 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4538 if (!pte_young(pte[i]))
4541 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4545 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4546 VM_WARN_ON_ONCE(true);
4550 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4551 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4552 !folio_test_swapcache(folio)))
4553 folio_mark_dirty(folio);
4555 old_gen = folio_lru_gen(folio);
4557 folio_set_referenced(folio);
4558 else if (old_gen != new_gen)
4559 __set_bit(i, bitmap);
4562 arch_leave_lazy_mmu_mode();
4565 /* feedback from rmap walkers to page table walkers */
4566 if (suitable_to_scan(i, young))
4567 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4569 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4570 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4571 folio = pfn_folio(pte_pfn(pte[i]));
4572 folio_activate(folio);
4577 /* folio_update_gen() requires stable folio_memcg() */
4578 if (!mem_cgroup_trylock_pages(memcg))
4582 spin_lock_irq(&lruvec->lru_lock);
4583 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4586 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4587 folio = pfn_folio(pte_pfn(pte[i]));
4588 if (folio_memcg_rcu(folio) != memcg)
4591 old_gen = folio_update_gen(folio, new_gen);
4592 if (old_gen < 0 || old_gen == new_gen)
4596 update_batch_size(walk, folio, old_gen, new_gen);
4598 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
4602 spin_unlock_irq(&lruvec->lru_lock);
4604 mem_cgroup_unlock_pages();
4607 /******************************************************************************
4609 ******************************************************************************/
4611 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4614 int gen = folio_lru_gen(folio);
4615 int type = folio_is_file_lru(folio);
4616 int zone = folio_zonenum(folio);
4617 int delta = folio_nr_pages(folio);
4618 int refs = folio_lru_refs(folio);
4619 int tier = lru_tier_from_refs(refs);
4620 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4622 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4625 if (!folio_evictable(folio)) {
4626 success = lru_gen_del_folio(lruvec, folio, true);
4627 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4628 folio_set_unevictable(folio);
4629 lruvec_add_folio(lruvec, folio);
4630 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4634 /* dirty lazyfree */
4635 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4636 success = lru_gen_del_folio(lruvec, folio, true);
4637 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4638 folio_set_swapbacked(folio);
4639 lruvec_add_folio_tail(lruvec, folio);
4644 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4645 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4650 if (tier > tier_idx) {
4651 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4653 gen = folio_inc_gen(lruvec, folio, false);
4654 list_move_tail(&folio->lru, &lrugen->lists[gen][type][zone]);
4656 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4657 lrugen->protected[hist][type][tier - 1] + delta);
4658 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4662 /* waiting for writeback */
4663 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4664 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4665 gen = folio_inc_gen(lruvec, folio, true);
4666 list_move(&folio->lru, &lrugen->lists[gen][type][zone]);
4673 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4677 /* unmapping inhibited */
4678 if (!sc->may_unmap && folio_mapped(folio))
4681 /* swapping inhibited */
4682 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4683 (folio_test_dirty(folio) ||
4684 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4687 /* raced with release_pages() */
4688 if (!folio_try_get(folio))
4691 /* raced with another isolation */
4692 if (!folio_test_clear_lru(folio)) {
4697 /* see the comment on MAX_NR_TIERS */
4698 if (!folio_test_referenced(folio))
4699 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4701 /* for shrink_page_list() */
4702 folio_clear_reclaim(folio);
4703 folio_clear_referenced(folio);
4705 success = lru_gen_del_folio(lruvec, folio, true);
4706 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4711 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4712 int type, int tier, struct list_head *list)
4715 enum vm_event_item item;
4719 int remaining = MAX_LRU_BATCH;
4720 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4721 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4723 VM_WARN_ON_ONCE(!list_empty(list));
4725 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4728 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4730 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4733 struct list_head *head = &lrugen->lists[gen][type][zone];
4735 while (!list_empty(head)) {
4736 struct folio *folio = lru_to_folio(head);
4737 int delta = folio_nr_pages(folio);
4739 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4740 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4741 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4742 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4746 if (sort_folio(lruvec, folio, tier))
4748 else if (isolate_folio(lruvec, folio, sc)) {
4749 list_add(&folio->lru, list);
4752 list_move(&folio->lru, &moved);
4756 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4761 list_splice(&moved, head);
4762 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4765 if (!remaining || isolated >= MIN_LRU_BATCH)
4769 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4770 if (!cgroup_reclaim(sc)) {
4771 __count_vm_events(item, isolated);
4772 __count_vm_events(PGREFILL, sorted);
4774 __count_memcg_events(memcg, item, isolated);
4775 __count_memcg_events(memcg, PGREFILL, sorted);
4776 __count_vm_events(PGSCAN_ANON + type, isolated);
4779 * There might not be eligible pages due to reclaim_idx, may_unmap and
4780 * may_writepage. Check the remaining to prevent livelock if it's not
4783 return isolated || !remaining ? scanned : 0;
4786 static int get_tier_idx(struct lruvec *lruvec, int type)
4789 struct ctrl_pos sp, pv;
4792 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4793 * This value is chosen because any other tier would have at least twice
4794 * as many refaults as the first tier.
4796 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4797 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4798 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4799 if (!positive_ctrl_err(&sp, &pv))
4806 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4809 struct ctrl_pos sp, pv;
4810 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4813 * Compare the first tier of anon with that of file to determine which
4814 * type to scan. Also need to compare other tiers of the selected type
4815 * with the first tier of the other type to determine the last tier (of
4816 * the selected type) to evict.
4818 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4819 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4820 type = positive_ctrl_err(&sp, &pv);
4822 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4823 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4824 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4825 if (!positive_ctrl_err(&sp, &pv))
4829 *tier_idx = tier - 1;
4834 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4835 int *type_scanned, struct list_head *list)
4841 DEFINE_MIN_SEQ(lruvec);
4844 * Try to make the obvious choice first. When anon and file are both
4845 * available from the same generation, interpret swappiness 1 as file
4846 * first and 200 as anon first.
4849 type = LRU_GEN_FILE;
4850 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4851 type = LRU_GEN_ANON;
4852 else if (swappiness == 1)
4853 type = LRU_GEN_FILE;
4854 else if (swappiness == 200)
4855 type = LRU_GEN_ANON;
4857 type = get_type_to_scan(lruvec, swappiness, &tier);
4859 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4861 tier = get_tier_idx(lruvec, type);
4863 scanned = scan_folios(lruvec, sc, type, tier, list);
4871 *type_scanned = type;
4876 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4877 bool *need_swapping)
4883 struct folio *folio;
4884 enum vm_event_item item;
4885 struct reclaim_stat stat;
4886 struct lru_gen_mm_walk *walk;
4887 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4888 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4890 spin_lock_irq(&lruvec->lru_lock);
4892 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
4894 scanned += try_to_inc_min_seq(lruvec, swappiness);
4896 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4899 spin_unlock_irq(&lruvec->lru_lock);
4901 if (list_empty(&list))
4904 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4906 list_for_each_entry(folio, &list, lru) {
4907 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
4908 if (folio_test_workingset(folio))
4909 folio_set_referenced(folio);
4911 /* don't add rejected pages to the oldest generation */
4912 if (folio_test_reclaim(folio) &&
4913 (folio_test_dirty(folio) || folio_test_writeback(folio)))
4914 folio_clear_active(folio);
4916 folio_set_active(folio);
4919 spin_lock_irq(&lruvec->lru_lock);
4921 move_pages_to_lru(lruvec, &list);
4923 walk = current->reclaim_state->mm_walk;
4924 if (walk && walk->batched)
4925 reset_batch_size(lruvec, walk);
4927 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4928 if (!cgroup_reclaim(sc))
4929 __count_vm_events(item, reclaimed);
4930 __count_memcg_events(memcg, item, reclaimed);
4931 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4933 spin_unlock_irq(&lruvec->lru_lock);
4935 mem_cgroup_uncharge_list(&list);
4936 free_unref_page_list(&list);
4938 sc->nr_reclaimed += reclaimed;
4940 if (need_swapping && type == LRU_GEN_ANON)
4941 *need_swapping = true;
4947 * For future optimizations:
4948 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4951 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
4952 bool can_swap, bool *need_aging)
4954 unsigned long nr_to_scan;
4955 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4956 DEFINE_MAX_SEQ(lruvec);
4957 DEFINE_MIN_SEQ(lruvec);
4959 if (mem_cgroup_below_min(memcg) ||
4960 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4963 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4967 /* skip the aging path at the default priority */
4968 if (sc->priority == DEF_PRIORITY)
4971 /* leave the work to lru_gen_age_node() */
4972 if (current_is_kswapd())
4975 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap))
4978 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4981 static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4982 struct scan_control *sc, bool need_swapping)
4985 DEFINE_MAX_SEQ(lruvec);
4987 if (!current_is_kswapd()) {
4988 /* age each memcg once to ensure fairness */
4989 if (max_seq - seq > 1)
4992 /* over-swapping can increase allocation latency */
4993 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4996 /* give this thread a chance to exit and free its memory */
4997 if (fatal_signal_pending(current)) {
4998 sc->nr_reclaimed += MIN_LRU_BATCH;
5002 if (cgroup_reclaim(sc))
5004 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
5007 /* keep scanning at low priorities to ensure fairness */
5008 if (sc->priority > DEF_PRIORITY - 2)
5012 * A minimum amount of work was done under global memory pressure. For
5013 * kswapd, it may be overshooting. For direct reclaim, the target isn't
5014 * met, and yet the allocation may still succeed, since kswapd may have
5015 * caught up. In either case, it's better to stop now, and restart if
5018 for (i = 0; i <= sc->reclaim_idx; i++) {
5019 unsigned long wmark;
5020 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
5022 if (!managed_zone(zone))
5025 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
5026 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
5030 sc->nr_reclaimed += MIN_LRU_BATCH;
5035 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5037 struct blk_plug plug;
5038 bool need_aging = false;
5039 bool need_swapping = false;
5040 unsigned long scanned = 0;
5041 unsigned long reclaimed = sc->nr_reclaimed;
5042 DEFINE_MAX_SEQ(lruvec);
5046 blk_start_plug(&plug);
5048 set_mm_walk(lruvec_pgdat(lruvec));
5053 unsigned long nr_to_scan;
5056 swappiness = get_swappiness(lruvec, sc);
5057 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
5062 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
5066 delta = evict_folios(lruvec, sc, swappiness, &need_swapping);
5071 if (scanned >= nr_to_scan)
5074 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
5080 /* see the comment in lru_gen_age_node() */
5081 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
5082 sc->memcgs_need_aging = false;
5086 blk_finish_plug(&plug);
5089 /******************************************************************************
5091 ******************************************************************************/
5093 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5095 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5097 if (lrugen->enabled) {
5100 for_each_evictable_lru(lru) {
5101 if (!list_empty(&lruvec->lists[lru]))
5105 int gen, type, zone;
5107 for_each_gen_type_zone(gen, type, zone) {
5108 if (!list_empty(&lrugen->lists[gen][type][zone]))
5116 static bool fill_evictable(struct lruvec *lruvec)
5119 int remaining = MAX_LRU_BATCH;
5121 for_each_evictable_lru(lru) {
5122 int type = is_file_lru(lru);
5123 bool active = is_active_lru(lru);
5124 struct list_head *head = &lruvec->lists[lru];
5126 while (!list_empty(head)) {
5128 struct folio *folio = lru_to_folio(head);
5130 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5131 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5132 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5133 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5135 lruvec_del_folio(lruvec, folio);
5136 success = lru_gen_add_folio(lruvec, folio, false);
5137 VM_WARN_ON_ONCE(!success);
5147 static bool drain_evictable(struct lruvec *lruvec)
5149 int gen, type, zone;
5150 int remaining = MAX_LRU_BATCH;
5152 for_each_gen_type_zone(gen, type, zone) {
5153 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5155 while (!list_empty(head)) {
5157 struct folio *folio = lru_to_folio(head);
5159 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5160 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5161 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5162 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5164 success = lru_gen_del_folio(lruvec, folio, false);
5165 VM_WARN_ON_ONCE(!success);
5166 lruvec_add_folio(lruvec, folio);
5176 static void lru_gen_change_state(bool enabled)
5178 static DEFINE_MUTEX(state_mutex);
5180 struct mem_cgroup *memcg;
5185 mutex_lock(&state_mutex);
5187 if (enabled == lru_gen_enabled())
5191 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5193 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5195 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5199 for_each_node(nid) {
5200 struct lruvec *lruvec = get_lruvec(memcg, nid);
5205 spin_lock_irq(&lruvec->lru_lock);
5207 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5208 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5210 lruvec->lrugen.enabled = enabled;
5212 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5213 spin_unlock_irq(&lruvec->lru_lock);
5215 spin_lock_irq(&lruvec->lru_lock);
5218 spin_unlock_irq(&lruvec->lru_lock);
5222 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5224 mutex_unlock(&state_mutex);
5230 /******************************************************************************
5232 ******************************************************************************/
5234 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5236 unsigned int caps = 0;
5238 if (get_cap(LRU_GEN_CORE))
5239 caps |= BIT(LRU_GEN_CORE);
5241 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5242 caps |= BIT(LRU_GEN_MM_WALK);
5244 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5245 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5247 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5250 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5251 const char *buf, size_t len)
5256 if (tolower(*buf) == 'n')
5258 else if (tolower(*buf) == 'y')
5260 else if (kstrtouint(buf, 0, &caps))
5263 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5264 bool enabled = caps & BIT(i);
5266 if (i == LRU_GEN_CORE)
5267 lru_gen_change_state(enabled);
5269 static_branch_enable(&lru_gen_caps[i]);
5271 static_branch_disable(&lru_gen_caps[i]);
5277 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5278 enabled, 0644, show_enabled, store_enabled
5281 static struct attribute *lru_gen_attrs[] = {
5282 &lru_gen_enabled_attr.attr,
5286 static struct attribute_group lru_gen_attr_group = {
5288 .attrs = lru_gen_attrs,
5291 /******************************************************************************
5293 ******************************************************************************/
5295 void lru_gen_init_lruvec(struct lruvec *lruvec)
5297 int gen, type, zone;
5298 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5300 lrugen->max_seq = MIN_NR_GENS + 1;
5301 lrugen->enabled = lru_gen_enabled();
5303 for_each_gen_type_zone(gen, type, zone)
5304 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
5306 lruvec->mm_state.seq = MIN_NR_GENS;
5307 init_waitqueue_head(&lruvec->mm_state.wait);
5311 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5313 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5314 spin_lock_init(&memcg->mm_list.lock);
5317 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5322 for_each_node(nid) {
5323 struct lruvec *lruvec = get_lruvec(memcg, nid);
5325 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5326 sizeof(lruvec->lrugen.nr_pages)));
5328 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5329 bitmap_free(lruvec->mm_state.filters[i]);
5330 lruvec->mm_state.filters[i] = NULL;
5336 static int __init init_lru_gen(void)
5338 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5339 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5341 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5342 pr_err("lru_gen: failed to create sysfs group\n");
5346 late_initcall(init_lru_gen);
5348 #else /* !CONFIG_LRU_GEN */
5350 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5354 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5358 #endif /* CONFIG_LRU_GEN */
5360 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5362 unsigned long nr[NR_LRU_LISTS];
5363 unsigned long targets[NR_LRU_LISTS];
5364 unsigned long nr_to_scan;
5366 unsigned long nr_reclaimed = 0;
5367 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5368 struct blk_plug plug;
5371 if (lru_gen_enabled()) {
5372 lru_gen_shrink_lruvec(lruvec, sc);
5376 get_scan_count(lruvec, sc, nr);
5378 /* Record the original scan target for proportional adjustments later */
5379 memcpy(targets, nr, sizeof(nr));
5382 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5383 * event that can occur when there is little memory pressure e.g.
5384 * multiple streaming readers/writers. Hence, we do not abort scanning
5385 * when the requested number of pages are reclaimed when scanning at
5386 * DEF_PRIORITY on the assumption that the fact we are direct
5387 * reclaiming implies that kswapd is not keeping up and it is best to
5388 * do a batch of work at once. For memcg reclaim one check is made to
5389 * abort proportional reclaim if either the file or anon lru has already
5390 * dropped to zero at the first pass.
5392 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5393 sc->priority == DEF_PRIORITY);
5395 blk_start_plug(&plug);
5396 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5397 nr[LRU_INACTIVE_FILE]) {
5398 unsigned long nr_anon, nr_file, percentage;
5399 unsigned long nr_scanned;
5401 for_each_evictable_lru(lru) {
5403 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5404 nr[lru] -= nr_to_scan;
5406 nr_reclaimed += shrink_list(lru, nr_to_scan,
5413 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5417 * For kswapd and memcg, reclaim at least the number of pages
5418 * requested. Ensure that the anon and file LRUs are scanned
5419 * proportionally what was requested by get_scan_count(). We
5420 * stop reclaiming one LRU and reduce the amount scanning
5421 * proportional to the original scan target.
5423 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5424 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5427 * It's just vindictive to attack the larger once the smaller
5428 * has gone to zero. And given the way we stop scanning the
5429 * smaller below, this makes sure that we only make one nudge
5430 * towards proportionality once we've got nr_to_reclaim.
5432 if (!nr_file || !nr_anon)
5435 if (nr_file > nr_anon) {
5436 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5437 targets[LRU_ACTIVE_ANON] + 1;
5439 percentage = nr_anon * 100 / scan_target;
5441 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5442 targets[LRU_ACTIVE_FILE] + 1;
5444 percentage = nr_file * 100 / scan_target;
5447 /* Stop scanning the smaller of the LRU */
5449 nr[lru + LRU_ACTIVE] = 0;
5452 * Recalculate the other LRU scan count based on its original
5453 * scan target and the percentage scanning already complete
5455 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5456 nr_scanned = targets[lru] - nr[lru];
5457 nr[lru] = targets[lru] * (100 - percentage) / 100;
5458 nr[lru] -= min(nr[lru], nr_scanned);
5461 nr_scanned = targets[lru] - nr[lru];
5462 nr[lru] = targets[lru] * (100 - percentage) / 100;
5463 nr[lru] -= min(nr[lru], nr_scanned);
5465 scan_adjusted = true;
5467 blk_finish_plug(&plug);
5468 sc->nr_reclaimed += nr_reclaimed;
5471 * Even if we did not try to evict anon pages at all, we want to
5472 * rebalance the anon lru active/inactive ratio.
5474 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5475 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5476 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5477 sc, LRU_ACTIVE_ANON);
5480 /* Use reclaim/compaction for costly allocs or under memory pressure */
5481 static bool in_reclaim_compaction(struct scan_control *sc)
5483 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
5484 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
5485 sc->priority < DEF_PRIORITY - 2))
5492 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5493 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5494 * true if more pages should be reclaimed such that when the page allocator
5495 * calls try_to_compact_pages() that it will have enough free pages to succeed.
5496 * It will give up earlier than that if there is difficulty reclaiming pages.
5498 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
5499 unsigned long nr_reclaimed,
5500 struct scan_control *sc)
5502 unsigned long pages_for_compaction;
5503 unsigned long inactive_lru_pages;
5506 /* If not in reclaim/compaction mode, stop */
5507 if (!in_reclaim_compaction(sc))
5511 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5512 * number of pages that were scanned. This will return to the caller
5513 * with the risk reclaim/compaction and the resulting allocation attempt
5514 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5515 * allocations through requiring that the full LRU list has been scanned
5516 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5517 * scan, but that approximation was wrong, and there were corner cases
5518 * where always a non-zero amount of pages were scanned.
5523 /* If compaction would go ahead or the allocation would succeed, stop */
5524 for (z = 0; z <= sc->reclaim_idx; z++) {
5525 struct zone *zone = &pgdat->node_zones[z];
5526 if (!managed_zone(zone))
5529 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
5530 case COMPACT_SUCCESS:
5531 case COMPACT_CONTINUE:
5534 /* check next zone */
5540 * If we have not reclaimed enough pages for compaction and the
5541 * inactive lists are large enough, continue reclaiming
5543 pages_for_compaction = compact_gap(sc->order);
5544 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
5545 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
5546 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5548 return inactive_lru_pages > pages_for_compaction;
5551 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
5553 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
5554 struct mem_cgroup *memcg;
5556 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
5558 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
5559 unsigned long reclaimed;
5560 unsigned long scanned;
5563 * This loop can become CPU-bound when target memcgs
5564 * aren't eligible for reclaim - either because they
5565 * don't have any reclaimable pages, or because their
5566 * memory is explicitly protected. Avoid soft lockups.
5570 mem_cgroup_calculate_protection(target_memcg, memcg);
5572 if (mem_cgroup_below_min(memcg)) {
5575 * If there is no reclaimable memory, OOM.
5578 } else if (mem_cgroup_below_low(memcg)) {
5581 * Respect the protection only as long as
5582 * there is an unprotected supply
5583 * of reclaimable memory from other cgroups.
5585 if (!sc->memcg_low_reclaim) {
5586 sc->memcg_low_skipped = 1;
5589 memcg_memory_event(memcg, MEMCG_LOW);
5592 reclaimed = sc->nr_reclaimed;
5593 scanned = sc->nr_scanned;
5595 shrink_lruvec(lruvec, sc);
5597 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5600 /* Record the group's reclaim efficiency */
5602 vmpressure(sc->gfp_mask, memcg, false,
5603 sc->nr_scanned - scanned,
5604 sc->nr_reclaimed - reclaimed);
5606 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5609 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
5611 struct reclaim_state *reclaim_state = current->reclaim_state;
5612 unsigned long nr_reclaimed, nr_scanned;
5613 struct lruvec *target_lruvec;
5614 bool reclaimable = false;
5616 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5619 memset(&sc->nr, 0, sizeof(sc->nr));
5621 nr_reclaimed = sc->nr_reclaimed;
5622 nr_scanned = sc->nr_scanned;
5624 prepare_scan_count(pgdat, sc);
5626 shrink_node_memcgs(pgdat, sc);
5628 if (reclaim_state) {
5629 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5630 reclaim_state->reclaimed_slab = 0;
5633 /* Record the subtree's reclaim efficiency */
5635 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
5636 sc->nr_scanned - nr_scanned,
5637 sc->nr_reclaimed - nr_reclaimed);
5639 if (sc->nr_reclaimed - nr_reclaimed)
5642 if (current_is_kswapd()) {
5644 * If reclaim is isolating dirty pages under writeback,
5645 * it implies that the long-lived page allocation rate
5646 * is exceeding the page laundering rate. Either the
5647 * global limits are not being effective at throttling
5648 * processes due to the page distribution throughout
5649 * zones or there is heavy usage of a slow backing
5650 * device. The only option is to throttle from reclaim
5651 * context which is not ideal as there is no guarantee
5652 * the dirtying process is throttled in the same way
5653 * balance_dirty_pages() manages.
5655 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5656 * count the number of pages under pages flagged for
5657 * immediate reclaim and stall if any are encountered
5658 * in the nr_immediate check below.
5660 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5661 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
5663 /* Allow kswapd to start writing pages during reclaim.*/
5664 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5665 set_bit(PGDAT_DIRTY, &pgdat->flags);
5668 * If kswapd scans pages marked for immediate
5669 * reclaim and under writeback (nr_immediate), it
5670 * implies that pages are cycling through the LRU
5671 * faster than they are written so forcibly stall
5672 * until some pages complete writeback.
5674 if (sc->nr.immediate)
5675 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
5679 * Tag a node/memcg as congested if all the dirty pages were marked
5680 * for writeback and immediate reclaim (counted in nr.congested).
5682 * Legacy memcg will stall in page writeback so avoid forcibly
5683 * stalling in reclaim_throttle().
5685 if ((current_is_kswapd() ||
5686 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
5687 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
5688 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
5691 * Stall direct reclaim for IO completions if the lruvec is
5692 * node is congested. Allow kswapd to continue until it
5693 * starts encountering unqueued dirty pages or cycling through
5694 * the LRU too quickly.
5696 if (!current_is_kswapd() && current_may_throttle() &&
5697 !sc->hibernation_mode &&
5698 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
5699 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
5701 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5706 * Kswapd gives up on balancing particular nodes after too
5707 * many failures to reclaim anything from them and goes to
5708 * sleep. On reclaim progress, reset the failure counter. A
5709 * successful direct reclaim run will revive a dormant kswapd.
5712 pgdat->kswapd_failures = 0;
5716 * Returns true if compaction should go ahead for a costly-order request, or
5717 * the allocation would already succeed without compaction. Return false if we
5718 * should reclaim first.
5720 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
5722 unsigned long watermark;
5723 enum compact_result suitable;
5725 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5726 if (suitable == COMPACT_SUCCESS)
5727 /* Allocation should succeed already. Don't reclaim. */
5729 if (suitable == COMPACT_SKIPPED)
5730 /* Compaction cannot yet proceed. Do reclaim. */
5734 * Compaction is already possible, but it takes time to run and there
5735 * are potentially other callers using the pages just freed. So proceed
5736 * with reclaim to make a buffer of free pages available to give
5737 * compaction a reasonable chance of completing and allocating the page.
5738 * Note that we won't actually reclaim the whole buffer in one attempt
5739 * as the target watermark in should_continue_reclaim() is lower. But if
5740 * we are already above the high+gap watermark, don't reclaim at all.
5742 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5744 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
5747 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
5750 * If reclaim is making progress greater than 12% efficiency then
5751 * wake all the NOPROGRESS throttled tasks.
5753 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
5754 wait_queue_head_t *wqh;
5756 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
5757 if (waitqueue_active(wqh))
5764 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
5765 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
5766 * under writeback and marked for immediate reclaim at the tail of the
5769 if (current_is_kswapd() || cgroup_reclaim(sc))
5772 /* Throttle if making no progress at high prioities. */
5773 if (sc->priority == 1 && !sc->nr_reclaimed)
5774 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
5778 * This is the direct reclaim path, for page-allocating processes. We only
5779 * try to reclaim pages from zones which will satisfy the caller's allocation
5782 * If a zone is deemed to be full of pinned pages then just give it a light
5783 * scan then give up on it.
5785 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
5789 unsigned long nr_soft_reclaimed;
5790 unsigned long nr_soft_scanned;
5792 pg_data_t *last_pgdat = NULL;
5793 pg_data_t *first_pgdat = NULL;
5796 * If the number of buffer_heads in the machine exceeds the maximum
5797 * allowed level, force direct reclaim to scan the highmem zone as
5798 * highmem pages could be pinning lowmem pages storing buffer_heads
5800 orig_mask = sc->gfp_mask;
5801 if (buffer_heads_over_limit) {
5802 sc->gfp_mask |= __GFP_HIGHMEM;
5803 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
5806 for_each_zone_zonelist_nodemask(zone, z, zonelist,
5807 sc->reclaim_idx, sc->nodemask) {
5809 * Take care memory controller reclaiming has small influence
5812 if (!cgroup_reclaim(sc)) {
5813 if (!cpuset_zone_allowed(zone,
5814 GFP_KERNEL | __GFP_HARDWALL))
5818 * If we already have plenty of memory free for
5819 * compaction in this zone, don't free any more.
5820 * Even though compaction is invoked for any
5821 * non-zero order, only frequent costly order
5822 * reclamation is disruptive enough to become a
5823 * noticeable problem, like transparent huge
5826 if (IS_ENABLED(CONFIG_COMPACTION) &&
5827 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
5828 compaction_ready(zone, sc)) {
5829 sc->compaction_ready = true;
5834 * Shrink each node in the zonelist once. If the
5835 * zonelist is ordered by zone (not the default) then a
5836 * node may be shrunk multiple times but in that case
5837 * the user prefers lower zones being preserved.
5839 if (zone->zone_pgdat == last_pgdat)
5843 * This steals pages from memory cgroups over softlimit
5844 * and returns the number of reclaimed pages and
5845 * scanned pages. This works for global memory pressure
5846 * and balancing, not for a memcg's limit.
5848 nr_soft_scanned = 0;
5849 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
5850 sc->order, sc->gfp_mask,
5852 sc->nr_reclaimed += nr_soft_reclaimed;
5853 sc->nr_scanned += nr_soft_scanned;
5854 /* need some check for avoid more shrink_zone() */
5858 first_pgdat = zone->zone_pgdat;
5860 /* See comment about same check for global reclaim above */
5861 if (zone->zone_pgdat == last_pgdat)
5863 last_pgdat = zone->zone_pgdat;
5864 shrink_node(zone->zone_pgdat, sc);
5868 consider_reclaim_throttle(first_pgdat, sc);
5871 * Restore to original mask to avoid the impact on the caller if we
5872 * promoted it to __GFP_HIGHMEM.
5874 sc->gfp_mask = orig_mask;
5877 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
5879 struct lruvec *target_lruvec;
5880 unsigned long refaults;
5882 if (lru_gen_enabled())
5885 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
5886 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5887 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
5888 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5889 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
5893 * This is the main entry point to direct page reclaim.
5895 * If a full scan of the inactive list fails to free enough memory then we
5896 * are "out of memory" and something needs to be killed.
5898 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5899 * high - the zone may be full of dirty or under-writeback pages, which this
5900 * caller can't do much about. We kick the writeback threads and take explicit
5901 * naps in the hope that some of these pages can be written. But if the
5902 * allocating task holds filesystem locks which prevent writeout this might not
5903 * work, and the allocation attempt will fail.
5905 * returns: 0, if no pages reclaimed
5906 * else, the number of pages reclaimed
5908 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
5909 struct scan_control *sc)
5911 int initial_priority = sc->priority;
5912 pg_data_t *last_pgdat;
5916 delayacct_freepages_start();
5918 if (!cgroup_reclaim(sc))
5919 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
5923 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5926 shrink_zones(zonelist, sc);
5928 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
5931 if (sc->compaction_ready)
5935 * If we're getting trouble reclaiming, start doing
5936 * writepage even in laptop mode.
5938 if (sc->priority < DEF_PRIORITY - 2)
5939 sc->may_writepage = 1;
5940 } while (--sc->priority >= 0);
5943 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5945 if (zone->zone_pgdat == last_pgdat)
5947 last_pgdat = zone->zone_pgdat;
5949 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
5951 if (cgroup_reclaim(sc)) {
5952 struct lruvec *lruvec;
5954 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5956 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5960 delayacct_freepages_end();
5962 if (sc->nr_reclaimed)
5963 return sc->nr_reclaimed;
5965 /* Aborted reclaim to try compaction? don't OOM, then */
5966 if (sc->compaction_ready)
5970 * We make inactive:active ratio decisions based on the node's
5971 * composition of memory, but a restrictive reclaim_idx or a
5972 * memory.low cgroup setting can exempt large amounts of
5973 * memory from reclaim. Neither of which are very common, so
5974 * instead of doing costly eligibility calculations of the
5975 * entire cgroup subtree up front, we assume the estimates are
5976 * good, and retry with forcible deactivation if that fails.
5978 if (sc->skipped_deactivate) {
5979 sc->priority = initial_priority;
5980 sc->force_deactivate = 1;
5981 sc->skipped_deactivate = 0;
5985 /* Untapped cgroup reserves? Don't OOM, retry. */
5986 if (sc->memcg_low_skipped) {
5987 sc->priority = initial_priority;
5988 sc->force_deactivate = 0;
5989 sc->memcg_low_reclaim = 1;
5990 sc->memcg_low_skipped = 0;
5997 static bool allow_direct_reclaim(pg_data_t *pgdat)
6000 unsigned long pfmemalloc_reserve = 0;
6001 unsigned long free_pages = 0;
6005 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6008 for (i = 0; i <= ZONE_NORMAL; i++) {
6009 zone = &pgdat->node_zones[i];
6010 if (!managed_zone(zone))
6013 if (!zone_reclaimable_pages(zone))
6016 pfmemalloc_reserve += min_wmark_pages(zone);
6017 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6020 /* If there are no reserves (unexpected config) then do not throttle */
6021 if (!pfmemalloc_reserve)
6024 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6026 /* kswapd must be awake if processes are being throttled */
6027 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6028 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6029 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6031 wake_up_interruptible(&pgdat->kswapd_wait);
6038 * Throttle direct reclaimers if backing storage is backed by the network
6039 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6040 * depleted. kswapd will continue to make progress and wake the processes
6041 * when the low watermark is reached.
6043 * Returns true if a fatal signal was delivered during throttling. If this
6044 * happens, the page allocator should not consider triggering the OOM killer.
6046 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6047 nodemask_t *nodemask)
6051 pg_data_t *pgdat = NULL;
6054 * Kernel threads should not be throttled as they may be indirectly
6055 * responsible for cleaning pages necessary for reclaim to make forward
6056 * progress. kjournald for example may enter direct reclaim while
6057 * committing a transaction where throttling it could forcing other
6058 * processes to block on log_wait_commit().
6060 if (current->flags & PF_KTHREAD)
6064 * If a fatal signal is pending, this process should not throttle.
6065 * It should return quickly so it can exit and free its memory
6067 if (fatal_signal_pending(current))
6071 * Check if the pfmemalloc reserves are ok by finding the first node
6072 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6073 * GFP_KERNEL will be required for allocating network buffers when
6074 * swapping over the network so ZONE_HIGHMEM is unusable.
6076 * Throttling is based on the first usable node and throttled processes
6077 * wait on a queue until kswapd makes progress and wakes them. There
6078 * is an affinity then between processes waking up and where reclaim
6079 * progress has been made assuming the process wakes on the same node.
6080 * More importantly, processes running on remote nodes will not compete
6081 * for remote pfmemalloc reserves and processes on different nodes
6082 * should make reasonable progress.
6084 for_each_zone_zonelist_nodemask(zone, z, zonelist,
6085 gfp_zone(gfp_mask), nodemask) {
6086 if (zone_idx(zone) > ZONE_NORMAL)
6089 /* Throttle based on the first usable node */
6090 pgdat = zone->zone_pgdat;
6091 if (allow_direct_reclaim(pgdat))
6096 /* If no zone was usable by the allocation flags then do not throttle */
6100 /* Account for the throttling */
6101 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6104 * If the caller cannot enter the filesystem, it's possible that it
6105 * is due to the caller holding an FS lock or performing a journal
6106 * transaction in the case of a filesystem like ext[3|4]. In this case,
6107 * it is not safe to block on pfmemalloc_wait as kswapd could be
6108 * blocked waiting on the same lock. Instead, throttle for up to a
6109 * second before continuing.
6111 if (!(gfp_mask & __GFP_FS))
6112 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6113 allow_direct_reclaim(pgdat), HZ);
6115 /* Throttle until kswapd wakes the process */
6116 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6117 allow_direct_reclaim(pgdat));
6119 if (fatal_signal_pending(current))
6126 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6127 gfp_t gfp_mask, nodemask_t *nodemask)
6129 unsigned long nr_reclaimed;
6130 struct scan_control sc = {
6131 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6132 .gfp_mask = current_gfp_context(gfp_mask),
6133 .reclaim_idx = gfp_zone(gfp_mask),
6135 .nodemask = nodemask,
6136 .priority = DEF_PRIORITY,
6137 .may_writepage = !laptop_mode,
6143 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6144 * Confirm they are large enough for max values.
6146 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6147 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6148 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6151 * Do not enter reclaim if fatal signal was delivered while throttled.
6152 * 1 is returned so that the page allocator does not OOM kill at this
6155 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6158 set_task_reclaim_state(current, &sc.reclaim_state);
6159 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6161 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6163 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6164 set_task_reclaim_state(current, NULL);
6166 return nr_reclaimed;
6171 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6172 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6173 gfp_t gfp_mask, bool noswap,
6175 unsigned long *nr_scanned)
6177 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6178 struct scan_control sc = {
6179 .nr_to_reclaim = SWAP_CLUSTER_MAX,
6180 .target_mem_cgroup = memcg,
6181 .may_writepage = !laptop_mode,
6183 .reclaim_idx = MAX_NR_ZONES - 1,
6184 .may_swap = !noswap,
6187 WARN_ON_ONCE(!current->reclaim_state);
6189 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6190 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6192 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6196 * NOTE: Although we can get the priority field, using it
6197 * here is not a good idea, since it limits the pages we can scan.
6198 * if we don't reclaim here, the shrink_node from balance_pgdat
6199 * will pick up pages from other mem cgroup's as well. We hack
6200 * the priority and make it zero.
6202 shrink_lruvec(lruvec, &sc);
6204 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6206 *nr_scanned = sc.nr_scanned;
6208 return sc.nr_reclaimed;
6211 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6212 unsigned long nr_pages,
6214 unsigned int reclaim_options)
6216 unsigned long nr_reclaimed;
6217 unsigned int noreclaim_flag;
6218 struct scan_control sc = {
6219 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6220 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6221 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6222 .reclaim_idx = MAX_NR_ZONES - 1,
6223 .target_mem_cgroup = memcg,
6224 .priority = DEF_PRIORITY,
6225 .may_writepage = !laptop_mode,
6227 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6228 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6231 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6232 * equal pressure on all the nodes. This is based on the assumption that
6233 * the reclaim does not bail out early.
6235 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6237 set_task_reclaim_state(current, &sc.reclaim_state);
6238 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6239 noreclaim_flag = memalloc_noreclaim_save();
6241 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6243 memalloc_noreclaim_restore(noreclaim_flag);
6244 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6245 set_task_reclaim_state(current, NULL);
6247 return nr_reclaimed;
6251 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6253 struct mem_cgroup *memcg;
6254 struct lruvec *lruvec;
6256 if (lru_gen_enabled()) {
6257 lru_gen_age_node(pgdat, sc);
6261 if (!can_age_anon_pages(pgdat, sc))
6264 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6265 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6268 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6270 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6271 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6272 sc, LRU_ACTIVE_ANON);
6273 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6277 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6283 * Check for watermark boosts top-down as the higher zones
6284 * are more likely to be boosted. Both watermarks and boosts
6285 * should not be checked at the same time as reclaim would
6286 * start prematurely when there is no boosting and a lower
6289 for (i = highest_zoneidx; i >= 0; i--) {
6290 zone = pgdat->node_zones + i;
6291 if (!managed_zone(zone))
6294 if (zone->watermark_boost)
6302 * Returns true if there is an eligible zone balanced for the request order
6303 * and highest_zoneidx
6305 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6308 unsigned long mark = -1;
6312 * Check watermarks bottom-up as lower zones are more likely to
6315 for (i = 0; i <= highest_zoneidx; i++) {
6316 zone = pgdat->node_zones + i;
6318 if (!managed_zone(zone))
6321 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6322 mark = wmark_pages(zone, WMARK_PROMO);
6324 mark = high_wmark_pages(zone);
6325 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6330 * If a node has no managed zone within highest_zoneidx, it does not
6331 * need balancing by definition. This can happen if a zone-restricted
6332 * allocation tries to wake a remote kswapd.
6340 /* Clear pgdat state for congested, dirty or under writeback. */
6341 static void clear_pgdat_congested(pg_data_t *pgdat)
6343 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6345 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6346 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6347 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6351 * Prepare kswapd for sleeping. This verifies that there are no processes
6352 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6354 * Returns true if kswapd is ready to sleep
6356 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6357 int highest_zoneidx)
6360 * The throttled processes are normally woken up in balance_pgdat() as
6361 * soon as allow_direct_reclaim() is true. But there is a potential
6362 * race between when kswapd checks the watermarks and a process gets
6363 * throttled. There is also a potential race if processes get
6364 * throttled, kswapd wakes, a large process exits thereby balancing the
6365 * zones, which causes kswapd to exit balance_pgdat() before reaching
6366 * the wake up checks. If kswapd is going to sleep, no process should
6367 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6368 * the wake up is premature, processes will wake kswapd and get
6369 * throttled again. The difference from wake ups in balance_pgdat() is
6370 * that here we are under prepare_to_wait().
6372 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6373 wake_up_all(&pgdat->pfmemalloc_wait);
6375 /* Hopeless node, leave it to direct reclaim */
6376 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6379 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6380 clear_pgdat_congested(pgdat);
6388 * kswapd shrinks a node of pages that are at or below the highest usable
6389 * zone that is currently unbalanced.
6391 * Returns true if kswapd scanned at least the requested number of pages to
6392 * reclaim or if the lack of progress was due to pages under writeback.
6393 * This is used to determine if the scanning priority needs to be raised.
6395 static bool kswapd_shrink_node(pg_data_t *pgdat,
6396 struct scan_control *sc)
6401 /* Reclaim a number of pages proportional to the number of zones */
6402 sc->nr_to_reclaim = 0;
6403 for (z = 0; z <= sc->reclaim_idx; z++) {
6404 zone = pgdat->node_zones + z;
6405 if (!managed_zone(zone))
6408 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6412 * Historically care was taken to put equal pressure on all zones but
6413 * now pressure is applied based on node LRU order.
6415 shrink_node(pgdat, sc);
6418 * Fragmentation may mean that the system cannot be rebalanced for
6419 * high-order allocations. If twice the allocation size has been
6420 * reclaimed then recheck watermarks only at order-0 to prevent
6421 * excessive reclaim. Assume that a process requested a high-order
6422 * can direct reclaim/compact.
6424 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6427 return sc->nr_scanned >= sc->nr_to_reclaim;
6430 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6432 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6437 for (i = 0; i <= highest_zoneidx; i++) {
6438 zone = pgdat->node_zones + i;
6440 if (!managed_zone(zone))
6444 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6446 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6451 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6453 update_reclaim_active(pgdat, highest_zoneidx, true);
6457 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6459 update_reclaim_active(pgdat, highest_zoneidx, false);
6463 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6464 * that are eligible for use by the caller until at least one zone is
6467 * Returns the order kswapd finished reclaiming at.
6469 * kswapd scans the zones in the highmem->normal->dma direction. It skips
6470 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6471 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6472 * or lower is eligible for reclaim until at least one usable zone is
6475 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
6478 unsigned long nr_soft_reclaimed;
6479 unsigned long nr_soft_scanned;
6480 unsigned long pflags;
6481 unsigned long nr_boost_reclaim;
6482 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6485 struct scan_control sc = {
6486 .gfp_mask = GFP_KERNEL,
6491 set_task_reclaim_state(current, &sc.reclaim_state);
6492 psi_memstall_enter(&pflags);
6493 __fs_reclaim_acquire(_THIS_IP_);
6495 count_vm_event(PAGEOUTRUN);
6498 * Account for the reclaim boost. Note that the zone boost is left in
6499 * place so that parallel allocations that are near the watermark will
6500 * stall or direct reclaim until kswapd is finished.
6502 nr_boost_reclaim = 0;
6503 for (i = 0; i <= highest_zoneidx; i++) {
6504 zone = pgdat->node_zones + i;
6505 if (!managed_zone(zone))
6508 nr_boost_reclaim += zone->watermark_boost;
6509 zone_boosts[i] = zone->watermark_boost;
6511 boosted = nr_boost_reclaim;
6514 set_reclaim_active(pgdat, highest_zoneidx);
6515 sc.priority = DEF_PRIORITY;
6517 unsigned long nr_reclaimed = sc.nr_reclaimed;
6518 bool raise_priority = true;
6522 sc.reclaim_idx = highest_zoneidx;
6525 * If the number of buffer_heads exceeds the maximum allowed
6526 * then consider reclaiming from all zones. This has a dual
6527 * purpose -- on 64-bit systems it is expected that
6528 * buffer_heads are stripped during active rotation. On 32-bit
6529 * systems, highmem pages can pin lowmem memory and shrinking
6530 * buffers can relieve lowmem pressure. Reclaim may still not
6531 * go ahead if all eligible zones for the original allocation
6532 * request are balanced to avoid excessive reclaim from kswapd.
6534 if (buffer_heads_over_limit) {
6535 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6536 zone = pgdat->node_zones + i;
6537 if (!managed_zone(zone))
6546 * If the pgdat is imbalanced then ignore boosting and preserve
6547 * the watermarks for a later time and restart. Note that the
6548 * zone watermarks will be still reset at the end of balancing
6549 * on the grounds that the normal reclaim should be enough to
6550 * re-evaluate if boosting is required when kswapd next wakes.
6552 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
6553 if (!balanced && nr_boost_reclaim) {
6554 nr_boost_reclaim = 0;
6559 * If boosting is not active then only reclaim if there are no
6560 * eligible zones. Note that sc.reclaim_idx is not used as
6561 * buffer_heads_over_limit may have adjusted it.
6563 if (!nr_boost_reclaim && balanced)
6566 /* Limit the priority of boosting to avoid reclaim writeback */
6567 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6568 raise_priority = false;
6571 * Do not writeback or swap pages for boosted reclaim. The
6572 * intent is to relieve pressure not issue sub-optimal IO
6573 * from reclaim context. If no pages are reclaimed, the
6574 * reclaim will be aborted.
6576 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6577 sc.may_swap = !nr_boost_reclaim;
6580 * Do some background aging, to give pages a chance to be
6581 * referenced before reclaiming. All pages are rotated
6582 * regardless of classzone as this is about consistent aging.
6584 kswapd_age_node(pgdat, &sc);
6587 * If we're getting trouble reclaiming, start doing writepage
6588 * even in laptop mode.
6590 if (sc.priority < DEF_PRIORITY - 2)
6591 sc.may_writepage = 1;
6593 /* Call soft limit reclaim before calling shrink_node. */
6595 nr_soft_scanned = 0;
6596 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
6597 sc.gfp_mask, &nr_soft_scanned);
6598 sc.nr_reclaimed += nr_soft_reclaimed;
6601 * There should be no need to raise the scanning priority if
6602 * enough pages are already being scanned that that high
6603 * watermark would be met at 100% efficiency.
6605 if (kswapd_shrink_node(pgdat, &sc))
6606 raise_priority = false;
6609 * If the low watermark is met there is no need for processes
6610 * to be throttled on pfmemalloc_wait as they should not be
6611 * able to safely make forward progress. Wake them
6613 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
6614 allow_direct_reclaim(pgdat))
6615 wake_up_all(&pgdat->pfmemalloc_wait);
6617 /* Check if kswapd should be suspending */
6618 __fs_reclaim_release(_THIS_IP_);
6619 ret = try_to_freeze();
6620 __fs_reclaim_acquire(_THIS_IP_);
6621 if (ret || kthread_should_stop())
6625 * Raise priority if scanning rate is too low or there was no
6626 * progress in reclaiming pages
6628 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
6629 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6632 * If reclaim made no progress for a boost, stop reclaim as
6633 * IO cannot be queued and it could be an infinite loop in
6634 * extreme circumstances.
6636 if (nr_boost_reclaim && !nr_reclaimed)
6639 if (raise_priority || !nr_reclaimed)
6641 } while (sc.priority >= 1);
6643 if (!sc.nr_reclaimed)
6644 pgdat->kswapd_failures++;
6647 clear_reclaim_active(pgdat, highest_zoneidx);
6649 /* If reclaim was boosted, account for the reclaim done in this pass */
6651 unsigned long flags;
6653 for (i = 0; i <= highest_zoneidx; i++) {
6654 if (!zone_boosts[i])
6657 /* Increments are under the zone lock */
6658 zone = pgdat->node_zones + i;
6659 spin_lock_irqsave(&zone->lock, flags);
6660 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6661 spin_unlock_irqrestore(&zone->lock, flags);
6665 * As there is now likely space, wakeup kcompact to defragment
6668 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
6671 snapshot_refaults(NULL, pgdat);
6672 __fs_reclaim_release(_THIS_IP_);
6673 psi_memstall_leave(&pflags);
6674 set_task_reclaim_state(current, NULL);
6677 * Return the order kswapd stopped reclaiming at as
6678 * prepare_kswapd_sleep() takes it into account. If another caller
6679 * entered the allocator slow path while kswapd was awake, order will
6680 * remain at the higher level.
6686 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6687 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6688 * not a valid index then either kswapd runs for first time or kswapd couldn't
6689 * sleep after previous reclaim attempt (node is still unbalanced). In that
6690 * case return the zone index of the previous kswapd reclaim cycle.
6692 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6693 enum zone_type prev_highest_zoneidx)
6695 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
6697 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
6700 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
6701 unsigned int highest_zoneidx)
6706 if (freezing(current) || kthread_should_stop())
6709 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6712 * Try to sleep for a short interval. Note that kcompactd will only be
6713 * woken if it is possible to sleep for a short interval. This is
6714 * deliberate on the assumption that if reclaim cannot keep an
6715 * eligible zone balanced that it's also unlikely that compaction will
6718 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
6720 * Compaction records what page blocks it recently failed to
6721 * isolate pages from and skips them in the future scanning.
6722 * When kswapd is going to sleep, it is reasonable to assume
6723 * that pages and compaction may succeed so reset the cache.
6725 reset_isolation_suitable(pgdat);
6728 * We have freed the memory, now we should compact it to make
6729 * allocation of the requested order possible.
6731 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
6733 remaining = schedule_timeout(HZ/10);
6736 * If woken prematurely then reset kswapd_highest_zoneidx and
6737 * order. The values will either be from a wakeup request or
6738 * the previous request that slept prematurely.
6741 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6742 kswapd_highest_zoneidx(pgdat,
6745 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6746 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
6749 finish_wait(&pgdat->kswapd_wait, &wait);
6750 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6754 * After a short sleep, check if it was a premature sleep. If not, then
6755 * go fully to sleep until explicitly woken up.
6758 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
6759 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6762 * vmstat counters are not perfectly accurate and the estimated
6763 * value for counters such as NR_FREE_PAGES can deviate from the
6764 * true value by nr_online_cpus * threshold. To avoid the zone
6765 * watermarks being breached while under pressure, we reduce the
6766 * per-cpu vmstat threshold while kswapd is awake and restore
6767 * them before going back to sleep.
6769 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
6771 if (!kthread_should_stop())
6774 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6777 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6779 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6781 finish_wait(&pgdat->kswapd_wait, &wait);
6785 * The background pageout daemon, started as a kernel thread
6786 * from the init process.
6788 * This basically trickles out pages so that we have _some_
6789 * free memory available even if there is no other activity
6790 * that frees anything up. This is needed for things like routing
6791 * etc, where we otherwise might have all activity going on in
6792 * asynchronous contexts that cannot page things out.
6794 * If there are applications that are active memory-allocators
6795 * (most normal use), this basically shouldn't matter.
6797 static int kswapd(void *p)
6799 unsigned int alloc_order, reclaim_order;
6800 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
6801 pg_data_t *pgdat = (pg_data_t *)p;
6802 struct task_struct *tsk = current;
6803 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
6805 if (!cpumask_empty(cpumask))
6806 set_cpus_allowed_ptr(tsk, cpumask);
6809 * Tell the memory management that we're a "memory allocator",
6810 * and that if we need more memory we should get access to it
6811 * regardless (see "__alloc_pages()"). "kswapd" should
6812 * never get caught in the normal page freeing logic.
6814 * (Kswapd normally doesn't need memory anyway, but sometimes
6815 * you need a small amount of memory in order to be able to
6816 * page out something else, and this flag essentially protects
6817 * us from recursively trying to free more memory as we're
6818 * trying to free the first piece of memory in the first place).
6820 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
6823 WRITE_ONCE(pgdat->kswapd_order, 0);
6824 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
6825 atomic_set(&pgdat->nr_writeback_throttled, 0);
6829 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
6830 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6834 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
6837 /* Read the new order and highest_zoneidx */
6838 alloc_order = READ_ONCE(pgdat->kswapd_order);
6839 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6841 WRITE_ONCE(pgdat->kswapd_order, 0);
6842 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
6844 ret = try_to_freeze();
6845 if (kthread_should_stop())
6849 * We can speed up thawing tasks if we don't call balance_pgdat
6850 * after returning from the refrigerator
6856 * Reclaim begins at the requested order but if a high-order
6857 * reclaim fails then kswapd falls back to reclaiming for
6858 * order-0. If that happens, kswapd will consider sleeping
6859 * for the order it finished reclaiming at (reclaim_order)
6860 * but kcompactd is woken to compact for the original
6861 * request (alloc_order).
6863 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
6865 reclaim_order = balance_pgdat(pgdat, alloc_order,
6867 if (reclaim_order < alloc_order)
6868 goto kswapd_try_sleep;
6871 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
6877 * A zone is low on free memory or too fragmented for high-order memory. If
6878 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6879 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6880 * has failed or is not needed, still wake up kcompactd if only compaction is
6883 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
6884 enum zone_type highest_zoneidx)
6887 enum zone_type curr_idx;
6889 if (!managed_zone(zone))
6892 if (!cpuset_zone_allowed(zone, gfp_flags))
6895 pgdat = zone->zone_pgdat;
6896 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
6898 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6899 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
6901 if (READ_ONCE(pgdat->kswapd_order) < order)
6902 WRITE_ONCE(pgdat->kswapd_order, order);
6904 if (!waitqueue_active(&pgdat->kswapd_wait))
6907 /* Hopeless node, leave it to direct reclaim if possible */
6908 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
6909 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6910 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
6912 * There may be plenty of free memory available, but it's too
6913 * fragmented for high-order allocations. Wake up kcompactd
6914 * and rely on compaction_suitable() to determine if it's
6915 * needed. If it fails, it will defer subsequent attempts to
6916 * ratelimit its work.
6918 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
6919 wakeup_kcompactd(pgdat, order, highest_zoneidx);
6923 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
6925 wake_up_interruptible(&pgdat->kswapd_wait);
6928 #ifdef CONFIG_HIBERNATION
6930 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
6933 * Rather than trying to age LRUs the aim is to preserve the overall
6934 * LRU order by reclaiming preferentially
6935 * inactive > active > active referenced > active mapped
6937 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
6939 struct scan_control sc = {
6940 .nr_to_reclaim = nr_to_reclaim,
6941 .gfp_mask = GFP_HIGHUSER_MOVABLE,
6942 .reclaim_idx = MAX_NR_ZONES - 1,
6943 .priority = DEF_PRIORITY,
6947 .hibernation_mode = 1,
6949 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6950 unsigned long nr_reclaimed;
6951 unsigned int noreclaim_flag;
6953 fs_reclaim_acquire(sc.gfp_mask);
6954 noreclaim_flag = memalloc_noreclaim_save();
6955 set_task_reclaim_state(current, &sc.reclaim_state);
6957 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6959 set_task_reclaim_state(current, NULL);
6960 memalloc_noreclaim_restore(noreclaim_flag);
6961 fs_reclaim_release(sc.gfp_mask);
6963 return nr_reclaimed;
6965 #endif /* CONFIG_HIBERNATION */
6968 * This kswapd start function will be called by init and node-hot-add.
6970 void kswapd_run(int nid)
6972 pg_data_t *pgdat = NODE_DATA(nid);
6974 pgdat_kswapd_lock(pgdat);
6975 if (!pgdat->kswapd) {
6976 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6977 if (IS_ERR(pgdat->kswapd)) {
6978 /* failure at boot is fatal */
6979 BUG_ON(system_state < SYSTEM_RUNNING);
6980 pr_err("Failed to start kswapd on node %d\n", nid);
6981 pgdat->kswapd = NULL;
6984 pgdat_kswapd_unlock(pgdat);
6988 * Called by memory hotplug when all memory in a node is offlined. Caller must
6989 * be holding mem_hotplug_begin/done().
6991 void kswapd_stop(int nid)
6993 pg_data_t *pgdat = NODE_DATA(nid);
6994 struct task_struct *kswapd;
6996 pgdat_kswapd_lock(pgdat);
6997 kswapd = pgdat->kswapd;
6999 kthread_stop(kswapd);
7000 pgdat->kswapd = NULL;
7002 pgdat_kswapd_unlock(pgdat);
7005 static int __init kswapd_init(void)
7010 for_each_node_state(nid, N_MEMORY)
7015 module_init(kswapd_init)
7021 * If non-zero call node_reclaim when the number of free pages falls below
7024 int node_reclaim_mode __read_mostly;
7027 * Priority for NODE_RECLAIM. This determines the fraction of pages
7028 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7031 #define NODE_RECLAIM_PRIORITY 4
7034 * Percentage of pages in a zone that must be unmapped for node_reclaim to
7037 int sysctl_min_unmapped_ratio = 1;
7040 * If the number of slab pages in a zone grows beyond this percentage then
7041 * slab reclaim needs to occur.
7043 int sysctl_min_slab_ratio = 5;
7045 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7047 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7048 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7049 node_page_state(pgdat, NR_ACTIVE_FILE);
7052 * It's possible for there to be more file mapped pages than
7053 * accounted for by the pages on the file LRU lists because
7054 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7056 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7059 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7060 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7062 unsigned long nr_pagecache_reclaimable;
7063 unsigned long delta = 0;
7066 * If RECLAIM_UNMAP is set, then all file pages are considered
7067 * potentially reclaimable. Otherwise, we have to worry about
7068 * pages like swapcache and node_unmapped_file_pages() provides
7071 if (node_reclaim_mode & RECLAIM_UNMAP)
7072 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7074 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7076 /* If we can't clean pages, remove dirty pages from consideration */
7077 if (!(node_reclaim_mode & RECLAIM_WRITE))
7078 delta += node_page_state(pgdat, NR_FILE_DIRTY);
7080 /* Watch for any possible underflows due to delta */
7081 if (unlikely(delta > nr_pagecache_reclaimable))
7082 delta = nr_pagecache_reclaimable;
7084 return nr_pagecache_reclaimable - delta;
7088 * Try to free up some pages from this node through reclaim.
7090 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7092 /* Minimum pages needed in order to stay on node */
7093 const unsigned long nr_pages = 1 << order;
7094 struct task_struct *p = current;
7095 unsigned int noreclaim_flag;
7096 struct scan_control sc = {
7097 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7098 .gfp_mask = current_gfp_context(gfp_mask),
7100 .priority = NODE_RECLAIM_PRIORITY,
7101 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7102 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7104 .reclaim_idx = gfp_zone(gfp_mask),
7106 unsigned long pflags;
7108 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7112 psi_memstall_enter(&pflags);
7113 fs_reclaim_acquire(sc.gfp_mask);
7115 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7117 noreclaim_flag = memalloc_noreclaim_save();
7118 set_task_reclaim_state(p, &sc.reclaim_state);
7120 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7121 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7123 * Free memory by calling shrink node with increasing
7124 * priorities until we have enough memory freed.
7127 shrink_node(pgdat, &sc);
7128 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7131 set_task_reclaim_state(p, NULL);
7132 memalloc_noreclaim_restore(noreclaim_flag);
7133 fs_reclaim_release(sc.gfp_mask);
7134 psi_memstall_leave(&pflags);
7136 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7138 return sc.nr_reclaimed >= nr_pages;
7141 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7146 * Node reclaim reclaims unmapped file backed pages and
7147 * slab pages if we are over the defined limits.
7149 * A small portion of unmapped file backed pages is needed for
7150 * file I/O otherwise pages read by file I/O will be immediately
7151 * thrown out if the node is overallocated. So we do not reclaim
7152 * if less than a specified percentage of the node is used by
7153 * unmapped file backed pages.
7155 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7156 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7157 pgdat->min_slab_pages)
7158 return NODE_RECLAIM_FULL;
7161 * Do not scan if the allocation should not be delayed.
7163 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7164 return NODE_RECLAIM_NOSCAN;
7167 * Only run node reclaim on the local node or on nodes that do not
7168 * have associated processors. This will favor the local processor
7169 * over remote processors and spread off node memory allocations
7170 * as wide as possible.
7172 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7173 return NODE_RECLAIM_NOSCAN;
7175 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7176 return NODE_RECLAIM_NOSCAN;
7178 ret = __node_reclaim(pgdat, gfp_mask, order);
7179 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7182 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7188 void check_move_unevictable_pages(struct pagevec *pvec)
7190 struct folio_batch fbatch;
7193 folio_batch_init(&fbatch);
7194 for (i = 0; i < pvec->nr; i++) {
7195 struct page *page = pvec->pages[i];
7197 if (PageTransTail(page))
7199 folio_batch_add(&fbatch, page_folio(page));
7201 check_move_unevictable_folios(&fbatch);
7203 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
7206 * check_move_unevictable_folios - Move evictable folios to appropriate zone
7208 * @fbatch: Batch of lru folios to check.
7210 * Checks folios for evictability, if an evictable folio is in the unevictable
7211 * lru list, moves it to the appropriate evictable lru list. This function
7212 * should be only used for lru folios.
7214 void check_move_unevictable_folios(struct folio_batch *fbatch)
7216 struct lruvec *lruvec = NULL;
7221 for (i = 0; i < fbatch->nr; i++) {
7222 struct folio *folio = fbatch->folios[i];
7223 int nr_pages = folio_nr_pages(folio);
7225 pgscanned += nr_pages;
7227 /* block memcg migration while the folio moves between lrus */
7228 if (!folio_test_clear_lru(folio))
7231 lruvec = folio_lruvec_relock_irq(folio, lruvec);
7232 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7233 lruvec_del_folio(lruvec, folio);
7234 folio_clear_unevictable(folio);
7235 lruvec_add_folio(lruvec, folio);
7236 pgrescued += nr_pages;
7238 folio_set_lru(folio);
7242 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7243 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7244 unlock_page_lruvec_irq(lruvec);
7245 } else if (pgscanned) {
7246 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7249 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);