1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
16 #include <linux/sched/mm.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/highmem.h>
24 #include <linux/vmpressure.h>
25 #include <linux/vmstat.h>
26 #include <linux/file.h>
27 #include <linux/writeback.h>
28 #include <linux/blkdev.h>
29 #include <linux/buffer_head.h> /* for buffer_heads_over_limit */
30 #include <linux/mm_inline.h>
31 #include <linux/backing-dev.h>
32 #include <linux/rmap.h>
33 #include <linux/topology.h>
34 #include <linux/cpu.h>
35 #include <linux/cpuset.h>
36 #include <linux/compaction.h>
37 #include <linux/notifier.h>
38 #include <linux/rwsem.h>
39 #include <linux/delay.h>
40 #include <linux/kthread.h>
41 #include <linux/freezer.h>
42 #include <linux/memcontrol.h>
43 #include <linux/migrate.h>
44 #include <linux/delayacct.h>
45 #include <linux/sysctl.h>
46 #include <linux/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>
53 #include <asm/tlbflush.h>
54 #include <asm/div64.h>
56 #include <linux/swapops.h>
57 #include <linux/balloon_compaction.h>
58 #include <linux/sched/sysctl.h>
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/vmscan.h>
67 /* How many pages shrink_list() should reclaim */
68 unsigned long nr_to_reclaim;
71 * Nodemask of nodes allowed by the caller. If NULL, all nodes
77 * The memory cgroup that hit its limit and as a result is the
78 * primary target of this reclaim invocation.
80 struct mem_cgroup *target_mem_cgroup;
83 * Scan pressure balancing between anon and file LRUs
85 unsigned long anon_cost;
86 unsigned long file_cost;
88 /* Can active pages be deactivated as part of reclaim? */
89 #define DEACTIVATE_ANON 1
90 #define DEACTIVATE_FILE 2
91 unsigned int may_deactivate:2;
92 unsigned int force_deactivate:1;
93 unsigned int skipped_deactivate:1;
95 /* Writepage batching in laptop mode; RECLAIM_WRITE */
96 unsigned int may_writepage:1;
98 /* Can mapped pages be reclaimed? */
99 unsigned int may_unmap:1;
101 /* Can pages be swapped as part of reclaim? */
102 unsigned int may_swap:1;
105 * Cgroup memory below memory.low is protected as long as we
106 * don't threaten to OOM. If any cgroup is reclaimed at
107 * reduced force or passed over entirely due to its memory.low
108 * setting (memcg_low_skipped), and nothing is reclaimed as a
109 * result, then go back for one more cycle that reclaims the protected
110 * memory (memcg_low_reclaim) to avert OOM.
112 unsigned int memcg_low_reclaim:1;
113 unsigned int memcg_low_skipped:1;
115 unsigned int hibernation_mode:1;
117 /* One of the zones is ready for compaction */
118 unsigned int compaction_ready:1;
120 /* There is easily reclaimable cold cache in the current node */
121 unsigned int cache_trim_mode:1;
123 /* The file pages on the current node are dangerously low */
124 unsigned int file_is_tiny:1;
126 /* Always discard instead of demoting to lower tier memory */
127 unsigned int no_demotion:1;
129 /* Allocation order */
132 /* Scan (total_size >> priority) pages at once */
135 /* The highest zone to isolate pages for reclaim from */
138 /* This context's GFP mask */
141 /* Incremented by the number of inactive pages that were scanned */
142 unsigned long nr_scanned;
144 /* Number of pages freed so far during a call to shrink_zones() */
145 unsigned long nr_reclaimed;
149 unsigned int unqueued_dirty;
150 unsigned int congested;
151 unsigned int writeback;
152 unsigned int immediate;
153 unsigned int file_taken;
157 /* for recording the reclaimed slab by now */
158 struct reclaim_state reclaim_state;
161 #ifdef ARCH_HAS_PREFETCHW
162 #define prefetchw_prev_lru_folio(_folio, _base, _field) \
164 if ((_folio)->lru.prev != _base) { \
165 struct folio *prev; \
167 prev = lru_to_folio(&(_folio->lru)); \
168 prefetchw(&prev->_field); \
172 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
176 * From 0 .. 200. Higher means more swappy.
178 int vm_swappiness = 60;
180 static void set_task_reclaim_state(struct task_struct *task,
181 struct reclaim_state *rs)
183 /* Check for an overwrite */
184 WARN_ON_ONCE(rs && task->reclaim_state);
186 /* Check for the nulling of an already-nulled member */
187 WARN_ON_ONCE(!rs && !task->reclaim_state);
189 task->reclaim_state = rs;
192 LIST_HEAD(shrinker_list);
193 DECLARE_RWSEM(shrinker_rwsem);
196 static int shrinker_nr_max;
198 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
199 static inline int shrinker_map_size(int nr_items)
201 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
204 static inline int shrinker_defer_size(int nr_items)
206 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
209 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
212 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
213 lockdep_is_held(&shrinker_rwsem));
216 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
217 int map_size, int defer_size,
218 int old_map_size, int old_defer_size)
220 struct shrinker_info *new, *old;
221 struct mem_cgroup_per_node *pn;
223 int size = map_size + defer_size;
226 pn = memcg->nodeinfo[nid];
227 old = shrinker_info_protected(memcg, nid);
228 /* Not yet online memcg */
232 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
236 new->nr_deferred = (atomic_long_t *)(new + 1);
237 new->map = (void *)new->nr_deferred + defer_size;
239 /* map: set all old bits, clear all new bits */
240 memset(new->map, (int)0xff, old_map_size);
241 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
242 /* nr_deferred: copy old values, clear all new values */
243 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
244 memset((void *)new->nr_deferred + old_defer_size, 0,
245 defer_size - old_defer_size);
247 rcu_assign_pointer(pn->shrinker_info, new);
248 kvfree_rcu(old, rcu);
254 void free_shrinker_info(struct mem_cgroup *memcg)
256 struct mem_cgroup_per_node *pn;
257 struct shrinker_info *info;
261 pn = memcg->nodeinfo[nid];
262 info = rcu_dereference_protected(pn->shrinker_info, true);
264 rcu_assign_pointer(pn->shrinker_info, NULL);
268 int alloc_shrinker_info(struct mem_cgroup *memcg)
270 struct shrinker_info *info;
271 int nid, size, ret = 0;
272 int map_size, defer_size = 0;
274 down_write(&shrinker_rwsem);
275 map_size = shrinker_map_size(shrinker_nr_max);
276 defer_size = shrinker_defer_size(shrinker_nr_max);
277 size = map_size + defer_size;
279 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
281 free_shrinker_info(memcg);
285 info->nr_deferred = (atomic_long_t *)(info + 1);
286 info->map = (void *)info->nr_deferred + defer_size;
287 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
289 up_write(&shrinker_rwsem);
294 static inline bool need_expand(int nr_max)
296 return round_up(nr_max, BITS_PER_LONG) >
297 round_up(shrinker_nr_max, BITS_PER_LONG);
300 static int expand_shrinker_info(int new_id)
303 int new_nr_max = new_id + 1;
304 int map_size, defer_size = 0;
305 int old_map_size, old_defer_size = 0;
306 struct mem_cgroup *memcg;
308 if (!need_expand(new_nr_max))
311 if (!root_mem_cgroup)
314 lockdep_assert_held(&shrinker_rwsem);
316 map_size = shrinker_map_size(new_nr_max);
317 defer_size = shrinker_defer_size(new_nr_max);
318 old_map_size = shrinker_map_size(shrinker_nr_max);
319 old_defer_size = shrinker_defer_size(shrinker_nr_max);
321 memcg = mem_cgroup_iter(NULL, NULL, NULL);
323 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
324 old_map_size, old_defer_size);
326 mem_cgroup_iter_break(NULL, memcg);
329 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
332 shrinker_nr_max = new_nr_max;
337 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
339 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
340 struct shrinker_info *info;
343 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
344 /* Pairs with smp mb in shrink_slab() */
345 smp_mb__before_atomic();
346 set_bit(shrinker_id, info->map);
351 static DEFINE_IDR(shrinker_idr);
353 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
355 int id, ret = -ENOMEM;
357 if (mem_cgroup_disabled())
360 down_write(&shrinker_rwsem);
361 /* This may call shrinker, so it must use down_read_trylock() */
362 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
366 if (id >= shrinker_nr_max) {
367 if (expand_shrinker_info(id)) {
368 idr_remove(&shrinker_idr, id);
375 up_write(&shrinker_rwsem);
379 static void unregister_memcg_shrinker(struct shrinker *shrinker)
381 int id = shrinker->id;
385 lockdep_assert_held(&shrinker_rwsem);
387 idr_remove(&shrinker_idr, id);
390 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
391 struct mem_cgroup *memcg)
393 struct shrinker_info *info;
395 info = shrinker_info_protected(memcg, nid);
396 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
399 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
400 struct mem_cgroup *memcg)
402 struct shrinker_info *info;
404 info = shrinker_info_protected(memcg, nid);
405 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
408 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
412 struct mem_cgroup *parent;
413 struct shrinker_info *child_info, *parent_info;
415 parent = parent_mem_cgroup(memcg);
417 parent = root_mem_cgroup;
419 /* Prevent from concurrent shrinker_info expand */
420 down_read(&shrinker_rwsem);
422 child_info = shrinker_info_protected(memcg, nid);
423 parent_info = shrinker_info_protected(parent, nid);
424 for (i = 0; i < shrinker_nr_max; i++) {
425 nr = atomic_long_read(&child_info->nr_deferred[i]);
426 atomic_long_add(nr, &parent_info->nr_deferred[i]);
429 up_read(&shrinker_rwsem);
432 static bool cgroup_reclaim(struct scan_control *sc)
434 return sc->target_mem_cgroup;
438 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
439 * @sc: scan_control in question
441 * The normal page dirty throttling mechanism in balance_dirty_pages() is
442 * completely broken with the legacy memcg and direct stalling in
443 * shrink_page_list() is used for throttling instead, which lacks all the
444 * niceties such as fairness, adaptive pausing, bandwidth proportional
445 * allocation and configurability.
447 * This function tests whether the vmscan currently in progress can assume
448 * that the normal dirty throttling mechanism is operational.
450 static bool writeback_throttling_sane(struct scan_control *sc)
452 if (!cgroup_reclaim(sc))
454 #ifdef CONFIG_CGROUP_WRITEBACK
455 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
461 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
466 static void unregister_memcg_shrinker(struct shrinker *shrinker)
470 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
471 struct mem_cgroup *memcg)
476 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
477 struct mem_cgroup *memcg)
482 static bool cgroup_reclaim(struct scan_control *sc)
487 static bool writeback_throttling_sane(struct scan_control *sc)
493 static long xchg_nr_deferred(struct shrinker *shrinker,
494 struct shrink_control *sc)
498 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
502 (shrinker->flags & SHRINKER_MEMCG_AWARE))
503 return xchg_nr_deferred_memcg(nid, shrinker,
506 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
510 static long add_nr_deferred(long nr, struct shrinker *shrinker,
511 struct shrink_control *sc)
515 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
519 (shrinker->flags & SHRINKER_MEMCG_AWARE))
520 return add_nr_deferred_memcg(nr, nid, shrinker,
523 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
526 static bool can_demote(int nid, struct scan_control *sc)
528 if (!numa_demotion_enabled)
530 if (sc && sc->no_demotion)
532 if (next_demotion_node(nid) == NUMA_NO_NODE)
538 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
540 struct scan_control *sc)
544 * For non-memcg reclaim, is there
545 * space in any swap device?
547 if (get_nr_swap_pages() > 0)
550 /* Is the memcg below its swap limit? */
551 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
556 * The page can not be swapped.
558 * Can it be reclaimed from this node via demotion?
560 return can_demote(nid, sc);
564 * This misses isolated pages which are not accounted for to save counters.
565 * As the data only determines if reclaim or compaction continues, it is
566 * not expected that isolated pages will be a dominating factor.
568 unsigned long zone_reclaimable_pages(struct zone *zone)
572 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
573 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
574 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
575 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
576 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
582 * lruvec_lru_size - Returns the number of pages on the given LRU list.
583 * @lruvec: lru vector
585 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
587 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
590 unsigned long size = 0;
593 for (zid = 0; zid <= zone_idx; zid++) {
594 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
596 if (!managed_zone(zone))
599 if (!mem_cgroup_disabled())
600 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
602 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
608 * Add a shrinker callback to be called from the vm.
610 static int __prealloc_shrinker(struct shrinker *shrinker)
615 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
616 err = prealloc_memcg_shrinker(shrinker);
620 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
623 size = sizeof(*shrinker->nr_deferred);
624 if (shrinker->flags & SHRINKER_NUMA_AWARE)
627 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
628 if (!shrinker->nr_deferred)
634 #ifdef CONFIG_SHRINKER_DEBUG
635 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
641 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
646 err = __prealloc_shrinker(shrinker);
648 kfree_const(shrinker->name);
653 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
655 return __prealloc_shrinker(shrinker);
659 void free_prealloced_shrinker(struct shrinker *shrinker)
661 #ifdef CONFIG_SHRINKER_DEBUG
662 kfree_const(shrinker->name);
664 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
665 down_write(&shrinker_rwsem);
666 unregister_memcg_shrinker(shrinker);
667 up_write(&shrinker_rwsem);
671 kfree(shrinker->nr_deferred);
672 shrinker->nr_deferred = NULL;
675 void register_shrinker_prepared(struct shrinker *shrinker)
677 down_write(&shrinker_rwsem);
678 list_add_tail(&shrinker->list, &shrinker_list);
679 shrinker->flags |= SHRINKER_REGISTERED;
680 shrinker_debugfs_add(shrinker);
681 up_write(&shrinker_rwsem);
684 static int __register_shrinker(struct shrinker *shrinker)
686 int err = __prealloc_shrinker(shrinker);
690 register_shrinker_prepared(shrinker);
694 #ifdef CONFIG_SHRINKER_DEBUG
695 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
701 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
706 err = __register_shrinker(shrinker);
708 kfree_const(shrinker->name);
712 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
714 return __register_shrinker(shrinker);
717 EXPORT_SYMBOL(register_shrinker);
722 void unregister_shrinker(struct shrinker *shrinker)
724 if (!(shrinker->flags & SHRINKER_REGISTERED))
727 down_write(&shrinker_rwsem);
728 list_del(&shrinker->list);
729 shrinker->flags &= ~SHRINKER_REGISTERED;
730 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
731 unregister_memcg_shrinker(shrinker);
732 shrinker_debugfs_remove(shrinker);
733 up_write(&shrinker_rwsem);
735 kfree(shrinker->nr_deferred);
736 shrinker->nr_deferred = NULL;
738 EXPORT_SYMBOL(unregister_shrinker);
741 * synchronize_shrinkers - Wait for all running shrinkers to complete.
743 * This is equivalent to calling unregister_shrink() and register_shrinker(),
744 * but atomically and with less overhead. This is useful to guarantee that all
745 * shrinker invocations have seen an update, before freeing memory, similar to
748 void synchronize_shrinkers(void)
750 down_write(&shrinker_rwsem);
751 up_write(&shrinker_rwsem);
753 EXPORT_SYMBOL(synchronize_shrinkers);
755 #define SHRINK_BATCH 128
757 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
758 struct shrinker *shrinker, int priority)
760 unsigned long freed = 0;
761 unsigned long long delta;
766 long batch_size = shrinker->batch ? shrinker->batch
768 long scanned = 0, next_deferred;
770 freeable = shrinker->count_objects(shrinker, shrinkctl);
771 if (freeable == 0 || freeable == SHRINK_EMPTY)
775 * copy the current shrinker scan count into a local variable
776 * and zero it so that other concurrent shrinker invocations
777 * don't also do this scanning work.
779 nr = xchg_nr_deferred(shrinker, shrinkctl);
781 if (shrinker->seeks) {
782 delta = freeable >> priority;
784 do_div(delta, shrinker->seeks);
787 * These objects don't require any IO to create. Trim
788 * them aggressively under memory pressure to keep
789 * them from causing refetches in the IO caches.
791 delta = freeable / 2;
794 total_scan = nr >> priority;
796 total_scan = min(total_scan, (2 * freeable));
798 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
799 freeable, delta, total_scan, priority);
802 * Normally, we should not scan less than batch_size objects in one
803 * pass to avoid too frequent shrinker calls, but if the slab has less
804 * than batch_size objects in total and we are really tight on memory,
805 * we will try to reclaim all available objects, otherwise we can end
806 * up failing allocations although there are plenty of reclaimable
807 * objects spread over several slabs with usage less than the
810 * We detect the "tight on memory" situations by looking at the total
811 * number of objects we want to scan (total_scan). If it is greater
812 * than the total number of objects on slab (freeable), we must be
813 * scanning at high prio and therefore should try to reclaim as much as
816 while (total_scan >= batch_size ||
817 total_scan >= freeable) {
819 unsigned long nr_to_scan = min(batch_size, total_scan);
821 shrinkctl->nr_to_scan = nr_to_scan;
822 shrinkctl->nr_scanned = nr_to_scan;
823 ret = shrinker->scan_objects(shrinker, shrinkctl);
824 if (ret == SHRINK_STOP)
828 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
829 total_scan -= shrinkctl->nr_scanned;
830 scanned += shrinkctl->nr_scanned;
836 * The deferred work is increased by any new work (delta) that wasn't
837 * done, decreased by old deferred work that was done now.
839 * And it is capped to two times of the freeable items.
841 next_deferred = max_t(long, (nr + delta - scanned), 0);
842 next_deferred = min(next_deferred, (2 * freeable));
845 * move the unused scan count back into the shrinker in a
846 * manner that handles concurrent updates.
848 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
850 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
855 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
856 struct mem_cgroup *memcg, int priority)
858 struct shrinker_info *info;
859 unsigned long ret, freed = 0;
862 if (!mem_cgroup_online(memcg))
865 if (!down_read_trylock(&shrinker_rwsem))
868 info = shrinker_info_protected(memcg, nid);
872 for_each_set_bit(i, info->map, shrinker_nr_max) {
873 struct shrink_control sc = {
874 .gfp_mask = gfp_mask,
878 struct shrinker *shrinker;
880 shrinker = idr_find(&shrinker_idr, i);
881 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
883 clear_bit(i, info->map);
887 /* Call non-slab shrinkers even though kmem is disabled */
888 if (!memcg_kmem_enabled() &&
889 !(shrinker->flags & SHRINKER_NONSLAB))
892 ret = do_shrink_slab(&sc, shrinker, priority);
893 if (ret == SHRINK_EMPTY) {
894 clear_bit(i, info->map);
896 * After the shrinker reported that it had no objects to
897 * free, but before we cleared the corresponding bit in
898 * the memcg shrinker map, a new object might have been
899 * added. To make sure, we have the bit set in this
900 * case, we invoke the shrinker one more time and reset
901 * the bit if it reports that it is not empty anymore.
902 * The memory barrier here pairs with the barrier in
903 * set_shrinker_bit():
905 * list_lru_add() shrink_slab_memcg()
906 * list_add_tail() clear_bit()
908 * set_bit() do_shrink_slab()
910 smp_mb__after_atomic();
911 ret = do_shrink_slab(&sc, shrinker, priority);
912 if (ret == SHRINK_EMPTY)
915 set_shrinker_bit(memcg, nid, i);
919 if (rwsem_is_contended(&shrinker_rwsem)) {
925 up_read(&shrinker_rwsem);
928 #else /* CONFIG_MEMCG */
929 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
930 struct mem_cgroup *memcg, int priority)
934 #endif /* CONFIG_MEMCG */
937 * shrink_slab - shrink slab caches
938 * @gfp_mask: allocation context
939 * @nid: node whose slab caches to target
940 * @memcg: memory cgroup whose slab caches to target
941 * @priority: the reclaim priority
943 * Call the shrink functions to age shrinkable caches.
945 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
946 * unaware shrinkers will receive a node id of 0 instead.
948 * @memcg specifies the memory cgroup to target. Unaware shrinkers
949 * are called only if it is the root cgroup.
951 * @priority is sc->priority, we take the number of objects and >> by priority
952 * in order to get the scan target.
954 * Returns the number of reclaimed slab objects.
956 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
957 struct mem_cgroup *memcg,
960 unsigned long ret, freed = 0;
961 struct shrinker *shrinker;
964 * The root memcg might be allocated even though memcg is disabled
965 * via "cgroup_disable=memory" boot parameter. This could make
966 * mem_cgroup_is_root() return false, then just run memcg slab
967 * shrink, but skip global shrink. This may result in premature
970 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
971 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
973 if (!down_read_trylock(&shrinker_rwsem))
976 list_for_each_entry(shrinker, &shrinker_list, list) {
977 struct shrink_control sc = {
978 .gfp_mask = gfp_mask,
983 ret = do_shrink_slab(&sc, shrinker, priority);
984 if (ret == SHRINK_EMPTY)
988 * Bail out if someone want to register a new shrinker to
989 * prevent the registration from being stalled for long periods
990 * by parallel ongoing shrinking.
992 if (rwsem_is_contended(&shrinker_rwsem)) {
998 up_read(&shrinker_rwsem);
1004 static void drop_slab_node(int nid)
1006 unsigned long freed;
1010 struct mem_cgroup *memcg = NULL;
1012 if (fatal_signal_pending(current))
1016 memcg = mem_cgroup_iter(NULL, NULL, NULL);
1018 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1019 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1020 } while ((freed >> shift++) > 1);
1023 void drop_slab(void)
1027 for_each_online_node(nid)
1028 drop_slab_node(nid);
1031 static inline int is_page_cache_freeable(struct folio *folio)
1034 * A freeable page cache page is referenced only by the caller
1035 * that isolated the page, the page cache and optional buffer
1036 * heads at page->private.
1038 return folio_ref_count(folio) - folio_test_private(folio) ==
1039 1 + folio_nr_pages(folio);
1043 * We detected a synchronous write error writing a folio out. Probably
1044 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1045 * fsync(), msync() or close().
1047 * The tricky part is that after writepage we cannot touch the mapping: nothing
1048 * prevents it from being freed up. But we have a ref on the folio and once
1049 * that folio is locked, the mapping is pinned.
1051 * We're allowed to run sleeping folio_lock() here because we know the caller has
1054 static void handle_write_error(struct address_space *mapping,
1055 struct folio *folio, int error)
1058 if (folio_mapping(folio) == mapping)
1059 mapping_set_error(mapping, error);
1060 folio_unlock(folio);
1063 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1065 int reclaimable = 0, write_pending = 0;
1069 * If kswapd is disabled, reschedule if necessary but do not
1070 * throttle as the system is likely near OOM.
1072 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1076 * If there are a lot of dirty/writeback pages then do not
1077 * throttle as throttling will occur when the pages cycle
1078 * towards the end of the LRU if still under writeback.
1080 for (i = 0; i < MAX_NR_ZONES; i++) {
1081 struct zone *zone = pgdat->node_zones + i;
1083 if (!managed_zone(zone))
1086 reclaimable += zone_reclaimable_pages(zone);
1087 write_pending += zone_page_state_snapshot(zone,
1088 NR_ZONE_WRITE_PENDING);
1090 if (2 * write_pending <= reclaimable)
1096 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1098 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1103 * Do not throttle IO workers, kthreads other than kswapd or
1104 * workqueues. They may be required for reclaim to make
1105 * forward progress (e.g. journalling workqueues or kthreads).
1107 if (!current_is_kswapd() &&
1108 current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1114 * These figures are pulled out of thin air.
1115 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1116 * parallel reclaimers which is a short-lived event so the timeout is
1117 * short. Failing to make progress or waiting on writeback are
1118 * potentially long-lived events so use a longer timeout. This is shaky
1119 * logic as a failure to make progress could be due to anything from
1120 * writeback to a slow device to excessive references pages at the tail
1121 * of the inactive LRU.
1124 case VMSCAN_THROTTLE_WRITEBACK:
1127 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1128 WRITE_ONCE(pgdat->nr_reclaim_start,
1129 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1133 case VMSCAN_THROTTLE_CONGESTED:
1135 case VMSCAN_THROTTLE_NOPROGRESS:
1136 if (skip_throttle_noprogress(pgdat)) {
1144 case VMSCAN_THROTTLE_ISOLATED:
1153 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1154 ret = schedule_timeout(timeout);
1155 finish_wait(wqh, &wait);
1157 if (reason == VMSCAN_THROTTLE_WRITEBACK)
1158 atomic_dec(&pgdat->nr_writeback_throttled);
1160 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1161 jiffies_to_usecs(timeout - ret),
1166 * Account for pages written if tasks are throttled waiting on dirty
1167 * pages to clean. If enough pages have been cleaned since throttling
1168 * started then wakeup the throttled tasks.
1170 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1173 unsigned long nr_written;
1175 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1178 * This is an inaccurate read as the per-cpu deltas may not
1179 * be synchronised. However, given that the system is
1180 * writeback throttled, it is not worth taking the penalty
1181 * of getting an accurate count. At worst, the throttle
1182 * timeout guarantees forward progress.
1184 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1185 READ_ONCE(pgdat->nr_reclaim_start);
1187 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1188 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1191 /* possible outcome of pageout() */
1193 /* failed to write page out, page is locked */
1195 /* move page to the active list, page is locked */
1197 /* page has been sent to the disk successfully, page is unlocked */
1199 /* page is clean and locked */
1204 * pageout is called by shrink_page_list() for each dirty page.
1205 * Calls ->writepage().
1207 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1208 struct swap_iocb **plug)
1211 * If the folio is dirty, only perform writeback if that write
1212 * will be non-blocking. To prevent this allocation from being
1213 * stalled by pagecache activity. But note that there may be
1214 * stalls if we need to run get_block(). We could test
1215 * PagePrivate for that.
1217 * If this process is currently in __generic_file_write_iter() against
1218 * this folio's queue, we can perform writeback even if that
1221 * If the folio is swapcache, write it back even if that would
1222 * block, for some throttling. This happens by accident, because
1223 * swap_backing_dev_info is bust: it doesn't reflect the
1224 * congestion state of the swapdevs. Easy to fix, if needed.
1226 if (!is_page_cache_freeable(folio))
1230 * Some data journaling orphaned folios can have
1231 * folio->mapping == NULL while being dirty with clean buffers.
1233 if (folio_test_private(folio)) {
1234 if (try_to_free_buffers(folio)) {
1235 folio_clear_dirty(folio);
1236 pr_info("%s: orphaned folio\n", __func__);
1242 if (mapping->a_ops->writepage == NULL)
1243 return PAGE_ACTIVATE;
1245 if (folio_clear_dirty_for_io(folio)) {
1247 struct writeback_control wbc = {
1248 .sync_mode = WB_SYNC_NONE,
1249 .nr_to_write = SWAP_CLUSTER_MAX,
1251 .range_end = LLONG_MAX,
1256 folio_set_reclaim(folio);
1257 res = mapping->a_ops->writepage(&folio->page, &wbc);
1259 handle_write_error(mapping, folio, res);
1260 if (res == AOP_WRITEPAGE_ACTIVATE) {
1261 folio_clear_reclaim(folio);
1262 return PAGE_ACTIVATE;
1265 if (!folio_test_writeback(folio)) {
1266 /* synchronous write or broken a_ops? */
1267 folio_clear_reclaim(folio);
1269 trace_mm_vmscan_write_folio(folio);
1270 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1271 return PAGE_SUCCESS;
1278 * Same as remove_mapping, but if the page is removed from the mapping, it
1279 * gets returned with a refcount of 0.
1281 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1282 bool reclaimed, struct mem_cgroup *target_memcg)
1285 void *shadow = NULL;
1287 BUG_ON(!folio_test_locked(folio));
1288 BUG_ON(mapping != folio_mapping(folio));
1290 if (!folio_test_swapcache(folio))
1291 spin_lock(&mapping->host->i_lock);
1292 xa_lock_irq(&mapping->i_pages);
1294 * The non racy check for a busy page.
1296 * Must be careful with the order of the tests. When someone has
1297 * a ref to the page, it may be possible that they dirty it then
1298 * drop the reference. So if PageDirty is tested before page_count
1299 * here, then the following race may occur:
1301 * get_user_pages(&page);
1302 * [user mapping goes away]
1304 * !PageDirty(page) [good]
1305 * SetPageDirty(page);
1307 * !page_count(page) [good, discard it]
1309 * [oops, our write_to data is lost]
1311 * Reversing the order of the tests ensures such a situation cannot
1312 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1313 * load is not satisfied before that of page->_refcount.
1315 * Note that if SetPageDirty is always performed via set_page_dirty,
1316 * and thus under the i_pages lock, then this ordering is not required.
1318 refcount = 1 + folio_nr_pages(folio);
1319 if (!folio_ref_freeze(folio, refcount))
1321 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1322 if (unlikely(folio_test_dirty(folio))) {
1323 folio_ref_unfreeze(folio, refcount);
1327 if (folio_test_swapcache(folio)) {
1328 swp_entry_t swap = folio_swap_entry(folio);
1329 mem_cgroup_swapout(folio, swap);
1330 if (reclaimed && !mapping_exiting(mapping))
1331 shadow = workingset_eviction(folio, target_memcg);
1332 __delete_from_swap_cache(folio, swap, shadow);
1333 xa_unlock_irq(&mapping->i_pages);
1334 put_swap_page(&folio->page, swap);
1336 void (*free_folio)(struct folio *);
1338 free_folio = mapping->a_ops->free_folio;
1340 * Remember a shadow entry for reclaimed file cache in
1341 * order to detect refaults, thus thrashing, later on.
1343 * But don't store shadows in an address space that is
1344 * already exiting. This is not just an optimization,
1345 * inode reclaim needs to empty out the radix tree or
1346 * the nodes are lost. Don't plant shadows behind its
1349 * We also don't store shadows for DAX mappings because the
1350 * only page cache pages found in these are zero pages
1351 * covering holes, and because we don't want to mix DAX
1352 * exceptional entries and shadow exceptional entries in the
1353 * same address_space.
1355 if (reclaimed && folio_is_file_lru(folio) &&
1356 !mapping_exiting(mapping) && !dax_mapping(mapping))
1357 shadow = workingset_eviction(folio, target_memcg);
1358 __filemap_remove_folio(folio, shadow);
1359 xa_unlock_irq(&mapping->i_pages);
1360 if (mapping_shrinkable(mapping))
1361 inode_add_lru(mapping->host);
1362 spin_unlock(&mapping->host->i_lock);
1371 xa_unlock_irq(&mapping->i_pages);
1372 if (!folio_test_swapcache(folio))
1373 spin_unlock(&mapping->host->i_lock);
1378 * remove_mapping() - Attempt to remove a folio from its mapping.
1379 * @mapping: The address space.
1380 * @folio: The folio to remove.
1382 * If the folio is dirty, under writeback or if someone else has a ref
1383 * on it, removal will fail.
1384 * Return: The number of pages removed from the mapping. 0 if the folio
1385 * could not be removed.
1386 * Context: The caller should have a single refcount on the folio and
1389 long remove_mapping(struct address_space *mapping, struct folio *folio)
1391 if (__remove_mapping(mapping, folio, false, NULL)) {
1393 * Unfreezing the refcount with 1 effectively
1394 * drops the pagecache ref for us without requiring another
1397 folio_ref_unfreeze(folio, 1);
1398 return folio_nr_pages(folio);
1404 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1405 * @folio: Folio to be returned to an LRU list.
1407 * Add previously isolated @folio to appropriate LRU list.
1408 * The folio may still be unevictable for other reasons.
1410 * Context: lru_lock must not be held, interrupts must be enabled.
1412 void folio_putback_lru(struct folio *folio)
1414 folio_add_lru(folio);
1415 folio_put(folio); /* drop ref from isolate */
1418 enum page_references {
1420 PAGEREF_RECLAIM_CLEAN,
1425 static enum page_references folio_check_references(struct folio *folio,
1426 struct scan_control *sc)
1428 int referenced_ptes, referenced_folio;
1429 unsigned long vm_flags;
1431 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1433 referenced_folio = folio_test_clear_referenced(folio);
1436 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1437 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1439 if (vm_flags & VM_LOCKED)
1440 return PAGEREF_ACTIVATE;
1442 /* rmap lock contention: rotate */
1443 if (referenced_ptes == -1)
1444 return PAGEREF_KEEP;
1446 if (referenced_ptes) {
1448 * All mapped folios start out with page table
1449 * references from the instantiating fault, so we need
1450 * to look twice if a mapped file/anon folio is used more
1453 * Mark it and spare it for another trip around the
1454 * inactive list. Another page table reference will
1455 * lead to its activation.
1457 * Note: the mark is set for activated folios as well
1458 * so that recently deactivated but used folios are
1459 * quickly recovered.
1461 folio_set_referenced(folio);
1463 if (referenced_folio || referenced_ptes > 1)
1464 return PAGEREF_ACTIVATE;
1467 * Activate file-backed executable folios after first usage.
1469 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1470 return PAGEREF_ACTIVATE;
1472 return PAGEREF_KEEP;
1475 /* Reclaim if clean, defer dirty folios to writeback */
1476 if (referenced_folio && folio_is_file_lru(folio))
1477 return PAGEREF_RECLAIM_CLEAN;
1479 return PAGEREF_RECLAIM;
1482 /* Check if a page is dirty or under writeback */
1483 static void folio_check_dirty_writeback(struct folio *folio,
1484 bool *dirty, bool *writeback)
1486 struct address_space *mapping;
1489 * Anonymous pages are not handled by flushers and must be written
1490 * from reclaim context. Do not stall reclaim based on them.
1491 * MADV_FREE anonymous pages are put into inactive file list too.
1492 * They could be mistakenly treated as file lru. So further anon
1495 if (!folio_is_file_lru(folio) ||
1496 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1502 /* By default assume that the folio flags are accurate */
1503 *dirty = folio_test_dirty(folio);
1504 *writeback = folio_test_writeback(folio);
1506 /* Verify dirty/writeback state if the filesystem supports it */
1507 if (!folio_test_private(folio))
1510 mapping = folio_mapping(folio);
1511 if (mapping && mapping->a_ops->is_dirty_writeback)
1512 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1515 static struct page *alloc_demote_page(struct page *page, unsigned long node)
1517 struct migration_target_control mtc = {
1519 * Allocate from 'node', or fail quickly and quietly.
1520 * When this happens, 'page' will likely just be discarded
1521 * instead of migrated.
1523 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1524 __GFP_THISNODE | __GFP_NOWARN |
1525 __GFP_NOMEMALLOC | GFP_NOWAIT,
1529 return alloc_migration_target(page, (unsigned long)&mtc);
1533 * Take pages on @demote_list and attempt to demote them to
1534 * another node. Pages which are not demoted are left on
1537 static unsigned int demote_page_list(struct list_head *demote_pages,
1538 struct pglist_data *pgdat)
1540 int target_nid = next_demotion_node(pgdat->node_id);
1541 unsigned int nr_succeeded;
1543 if (list_empty(demote_pages))
1546 if (target_nid == NUMA_NO_NODE)
1549 /* Demotion ignores all cpuset and mempolicy settings */
1550 migrate_pages(demote_pages, alloc_demote_page, NULL,
1551 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1554 if (current_is_kswapd())
1555 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1557 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1559 return nr_succeeded;
1562 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1564 if (gfp_mask & __GFP_FS)
1566 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1569 * We can "enter_fs" for swap-cache with only __GFP_IO
1570 * providing this isn't SWP_FS_OPS.
1571 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1572 * but that will never affect SWP_FS_OPS, so the data_race
1575 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1579 * shrink_page_list() returns the number of reclaimed pages
1581 static unsigned int shrink_page_list(struct list_head *page_list,
1582 struct pglist_data *pgdat,
1583 struct scan_control *sc,
1584 struct reclaim_stat *stat,
1585 bool ignore_references)
1587 LIST_HEAD(ret_pages);
1588 LIST_HEAD(free_pages);
1589 LIST_HEAD(demote_pages);
1590 unsigned int nr_reclaimed = 0;
1591 unsigned int pgactivate = 0;
1592 bool do_demote_pass;
1593 struct swap_iocb *plug = NULL;
1595 memset(stat, 0, sizeof(*stat));
1597 do_demote_pass = can_demote(pgdat->node_id, sc);
1600 while (!list_empty(page_list)) {
1601 struct address_space *mapping;
1602 struct folio *folio;
1603 enum page_references references = PAGEREF_RECLAIM;
1604 bool dirty, writeback;
1605 unsigned int nr_pages;
1609 folio = lru_to_folio(page_list);
1610 list_del(&folio->lru);
1612 if (!folio_trylock(folio))
1615 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1617 nr_pages = folio_nr_pages(folio);
1619 /* Account the number of base pages */
1620 sc->nr_scanned += nr_pages;
1622 if (unlikely(!folio_evictable(folio)))
1623 goto activate_locked;
1625 if (!sc->may_unmap && folio_mapped(folio))
1629 * The number of dirty pages determines if a node is marked
1630 * reclaim_congested. kswapd will stall and start writing
1631 * folios if the tail of the LRU is all dirty unqueued folios.
1633 folio_check_dirty_writeback(folio, &dirty, &writeback);
1634 if (dirty || writeback)
1635 stat->nr_dirty += nr_pages;
1637 if (dirty && !writeback)
1638 stat->nr_unqueued_dirty += nr_pages;
1641 * Treat this folio as congested if folios are cycling
1642 * through the LRU so quickly that the folios marked
1643 * for immediate reclaim are making it to the end of
1644 * the LRU a second time.
1646 if (writeback && folio_test_reclaim(folio))
1647 stat->nr_congested += nr_pages;
1650 * If a folio at the tail of the LRU is under writeback, there
1651 * are three cases to consider.
1653 * 1) If reclaim is encountering an excessive number
1654 * of folios under writeback and this folio has both
1655 * the writeback and reclaim flags set, then it
1656 * indicates that folios are being queued for I/O but
1657 * are being recycled through the LRU before the I/O
1658 * can complete. Waiting on the folio itself risks an
1659 * indefinite stall if it is impossible to writeback
1660 * the folio due to I/O error or disconnected storage
1661 * so instead note that the LRU is being scanned too
1662 * quickly and the caller can stall after the folio
1663 * list has been processed.
1665 * 2) Global or new memcg reclaim encounters a folio that is
1666 * not marked for immediate reclaim, or the caller does not
1667 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1668 * not to fs). In this case mark the folio for immediate
1669 * reclaim and continue scanning.
1671 * Require may_enter_fs() because we would wait on fs, which
1672 * may not have submitted I/O yet. And the loop driver might
1673 * enter reclaim, and deadlock if it waits on a folio for
1674 * which it is needed to do the write (loop masks off
1675 * __GFP_IO|__GFP_FS for this reason); but more thought
1676 * would probably show more reasons.
1678 * 3) Legacy memcg encounters a folio that already has the
1679 * reclaim flag set. memcg does not have any dirty folio
1680 * throttling so we could easily OOM just because too many
1681 * folios are in writeback and there is nothing else to
1682 * reclaim. Wait for the writeback to complete.
1684 * In cases 1) and 2) we activate the folios to get them out of
1685 * the way while we continue scanning for clean folios on the
1686 * inactive list and refilling from the active list. The
1687 * observation here is that waiting for disk writes is more
1688 * expensive than potentially causing reloads down the line.
1689 * Since they're marked for immediate reclaim, they won't put
1690 * memory pressure on the cache working set any longer than it
1691 * takes to write them to disk.
1693 if (folio_test_writeback(folio)) {
1695 if (current_is_kswapd() &&
1696 folio_test_reclaim(folio) &&
1697 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1698 stat->nr_immediate += nr_pages;
1699 goto activate_locked;
1702 } else if (writeback_throttling_sane(sc) ||
1703 !folio_test_reclaim(folio) ||
1704 !may_enter_fs(folio, sc->gfp_mask)) {
1706 * This is slightly racy -
1707 * folio_end_writeback() might have
1708 * just cleared the reclaim flag, then
1709 * setting the reclaim flag here ends up
1710 * interpreted as the readahead flag - but
1711 * that does not matter enough to care.
1712 * What we do want is for this folio to
1713 * have the reclaim flag set next time
1714 * memcg reclaim reaches the tests above,
1715 * so it will then wait for writeback to
1716 * avoid OOM; and it's also appropriate
1717 * in global reclaim.
1719 folio_set_reclaim(folio);
1720 stat->nr_writeback += nr_pages;
1721 goto activate_locked;
1725 folio_unlock(folio);
1726 folio_wait_writeback(folio);
1727 /* then go back and try same folio again */
1728 list_add_tail(&folio->lru, page_list);
1733 if (!ignore_references)
1734 references = folio_check_references(folio, sc);
1736 switch (references) {
1737 case PAGEREF_ACTIVATE:
1738 goto activate_locked;
1740 stat->nr_ref_keep += nr_pages;
1742 case PAGEREF_RECLAIM:
1743 case PAGEREF_RECLAIM_CLEAN:
1744 ; /* try to reclaim the folio below */
1748 * Before reclaiming the folio, try to relocate
1749 * its contents to another node.
1751 if (do_demote_pass &&
1752 (thp_migration_supported() || !folio_test_large(folio))) {
1753 list_add(&folio->lru, &demote_pages);
1754 folio_unlock(folio);
1759 * Anonymous process memory has backing store?
1760 * Try to allocate it some swap space here.
1761 * Lazyfree folio could be freed directly
1763 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1764 if (!folio_test_swapcache(folio)) {
1765 if (!(sc->gfp_mask & __GFP_IO))
1767 if (folio_maybe_dma_pinned(folio))
1769 if (folio_test_large(folio)) {
1770 /* cannot split folio, skip it */
1771 if (!can_split_folio(folio, NULL))
1772 goto activate_locked;
1774 * Split folios without a PMD map right
1775 * away. Chances are some or all of the
1776 * tail pages can be freed without IO.
1778 if (!folio_entire_mapcount(folio) &&
1779 split_folio_to_list(folio,
1781 goto activate_locked;
1783 if (!add_to_swap(folio)) {
1784 if (!folio_test_large(folio))
1785 goto activate_locked_split;
1786 /* Fallback to swap normal pages */
1787 if (split_folio_to_list(folio,
1789 goto activate_locked;
1790 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1791 count_vm_event(THP_SWPOUT_FALLBACK);
1793 if (!add_to_swap(folio))
1794 goto activate_locked_split;
1797 } else if (folio_test_swapbacked(folio) &&
1798 folio_test_large(folio)) {
1799 /* Split shmem folio */
1800 if (split_folio_to_list(folio, page_list))
1805 * If the folio was split above, the tail pages will make
1806 * their own pass through this function and be accounted
1809 if ((nr_pages > 1) && !folio_test_large(folio)) {
1810 sc->nr_scanned -= (nr_pages - 1);
1815 * The folio is mapped into the page tables of one or more
1816 * processes. Try to unmap it here.
1818 if (folio_mapped(folio)) {
1819 enum ttu_flags flags = TTU_BATCH_FLUSH;
1820 bool was_swapbacked = folio_test_swapbacked(folio);
1822 if (folio_test_pmd_mappable(folio))
1823 flags |= TTU_SPLIT_HUGE_PMD;
1825 try_to_unmap(folio, flags);
1826 if (folio_mapped(folio)) {
1827 stat->nr_unmap_fail += nr_pages;
1828 if (!was_swapbacked &&
1829 folio_test_swapbacked(folio))
1830 stat->nr_lazyfree_fail += nr_pages;
1831 goto activate_locked;
1835 mapping = folio_mapping(folio);
1836 if (folio_test_dirty(folio)) {
1838 * Only kswapd can writeback filesystem folios
1839 * to avoid risk of stack overflow. But avoid
1840 * injecting inefficient single-folio I/O into
1841 * flusher writeback as much as possible: only
1842 * write folios when we've encountered many
1843 * dirty folios, and when we've already scanned
1844 * the rest of the LRU for clean folios and see
1845 * the same dirty folios again (with the reclaim
1848 if (folio_is_file_lru(folio) &&
1849 (!current_is_kswapd() ||
1850 !folio_test_reclaim(folio) ||
1851 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1853 * Immediately reclaim when written back.
1854 * Similar in principle to deactivate_page()
1855 * except we already have the folio isolated
1856 * and know it's dirty
1858 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1860 folio_set_reclaim(folio);
1862 goto activate_locked;
1865 if (references == PAGEREF_RECLAIM_CLEAN)
1867 if (!may_enter_fs(folio, sc->gfp_mask))
1869 if (!sc->may_writepage)
1873 * Folio is dirty. Flush the TLB if a writable entry
1874 * potentially exists to avoid CPU writes after I/O
1875 * starts and then write it out here.
1877 try_to_unmap_flush_dirty();
1878 switch (pageout(folio, mapping, &plug)) {
1882 goto activate_locked;
1884 stat->nr_pageout += nr_pages;
1886 if (folio_test_writeback(folio))
1888 if (folio_test_dirty(folio))
1892 * A synchronous write - probably a ramdisk. Go
1893 * ahead and try to reclaim the folio.
1895 if (!folio_trylock(folio))
1897 if (folio_test_dirty(folio) ||
1898 folio_test_writeback(folio))
1900 mapping = folio_mapping(folio);
1903 ; /* try to free the folio below */
1908 * If the folio has buffers, try to free the buffer
1909 * mappings associated with this folio. If we succeed
1910 * we try to free the folio as well.
1912 * We do this even if the folio is dirty.
1913 * filemap_release_folio() does not perform I/O, but it
1914 * is possible for a folio to have the dirty flag set,
1915 * but it is actually clean (all its buffers are clean).
1916 * This happens if the buffers were written out directly,
1917 * with submit_bh(). ext3 will do this, as well as
1918 * the blockdev mapping. filemap_release_folio() will
1919 * discover that cleanness and will drop the buffers
1920 * and mark the folio clean - it can be freed.
1922 * Rarely, folios can have buffers and no ->mapping.
1923 * These are the folios which were not successfully
1924 * invalidated in truncate_cleanup_folio(). We try to
1925 * drop those buffers here and if that worked, and the
1926 * folio is no longer mapped into process address space
1927 * (refcount == 1) it can be freed. Otherwise, leave
1928 * the folio on the LRU so it is swappable.
1930 if (folio_has_private(folio)) {
1931 if (!filemap_release_folio(folio, sc->gfp_mask))
1932 goto activate_locked;
1933 if (!mapping && folio_ref_count(folio) == 1) {
1934 folio_unlock(folio);
1935 if (folio_put_testzero(folio))
1939 * rare race with speculative reference.
1940 * the speculative reference will free
1941 * this folio shortly, so we may
1942 * increment nr_reclaimed here (and
1943 * leave it off the LRU).
1945 nr_reclaimed += nr_pages;
1951 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1952 /* follow __remove_mapping for reference */
1953 if (!folio_ref_freeze(folio, 1))
1956 * The folio has only one reference left, which is
1957 * from the isolation. After the caller puts the
1958 * folio back on the lru and drops the reference, the
1959 * folio will be freed anyway. It doesn't matter
1960 * which lru it goes on. So we don't bother checking
1961 * the dirty flag here.
1963 count_vm_events(PGLAZYFREED, nr_pages);
1964 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
1965 } else if (!mapping || !__remove_mapping(mapping, folio, true,
1966 sc->target_mem_cgroup))
1969 folio_unlock(folio);
1972 * Folio may get swapped out as a whole, need to account
1975 nr_reclaimed += nr_pages;
1978 * Is there need to periodically free_page_list? It would
1979 * appear not as the counts should be low
1981 if (unlikely(folio_test_large(folio)))
1982 destroy_large_folio(folio);
1984 list_add(&folio->lru, &free_pages);
1987 activate_locked_split:
1989 * The tail pages that are failed to add into swap cache
1990 * reach here. Fixup nr_scanned and nr_pages.
1993 sc->nr_scanned -= (nr_pages - 1);
1997 /* Not a candidate for swapping, so reclaim swap space. */
1998 if (folio_test_swapcache(folio) &&
1999 (mem_cgroup_swap_full(&folio->page) ||
2000 folio_test_mlocked(folio)))
2001 try_to_free_swap(&folio->page);
2002 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2003 if (!folio_test_mlocked(folio)) {
2004 int type = folio_is_file_lru(folio);
2005 folio_set_active(folio);
2006 stat->nr_activate[type] += nr_pages;
2007 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2010 folio_unlock(folio);
2012 list_add(&folio->lru, &ret_pages);
2013 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2014 folio_test_unevictable(folio), folio);
2016 /* 'page_list' is always empty here */
2018 /* Migrate folios selected for demotion */
2019 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
2020 /* Folios that could not be demoted are still in @demote_pages */
2021 if (!list_empty(&demote_pages)) {
2022 /* Folios which weren't demoted go back on @page_list for retry: */
2023 list_splice_init(&demote_pages, page_list);
2024 do_demote_pass = false;
2028 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2030 mem_cgroup_uncharge_list(&free_pages);
2031 try_to_unmap_flush();
2032 free_unref_page_list(&free_pages);
2034 list_splice(&ret_pages, page_list);
2035 count_vm_events(PGACTIVATE, pgactivate);
2038 swap_write_unplug(plug);
2039 return nr_reclaimed;
2042 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2043 struct list_head *folio_list)
2045 struct scan_control sc = {
2046 .gfp_mask = GFP_KERNEL,
2049 struct reclaim_stat stat;
2050 unsigned int nr_reclaimed;
2051 struct folio *folio, *next;
2052 LIST_HEAD(clean_folios);
2053 unsigned int noreclaim_flag;
2055 list_for_each_entry_safe(folio, next, folio_list, lru) {
2056 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2057 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2058 !folio_test_unevictable(folio)) {
2059 folio_clear_active(folio);
2060 list_move(&folio->lru, &clean_folios);
2065 * We should be safe here since we are only dealing with file pages and
2066 * we are not kswapd and therefore cannot write dirty file pages. But
2067 * call memalloc_noreclaim_save() anyway, just in case these conditions
2068 * change in the future.
2070 noreclaim_flag = memalloc_noreclaim_save();
2071 nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc,
2073 memalloc_noreclaim_restore(noreclaim_flag);
2075 list_splice(&clean_folios, folio_list);
2076 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2077 -(long)nr_reclaimed);
2079 * Since lazyfree pages are isolated from file LRU from the beginning,
2080 * they will rotate back to anonymous LRU in the end if it failed to
2081 * discard so isolated count will be mismatched.
2082 * Compensate the isolated count for both LRU lists.
2084 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2085 stat.nr_lazyfree_fail);
2086 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2087 -(long)stat.nr_lazyfree_fail);
2088 return nr_reclaimed;
2092 * Update LRU sizes after isolating pages. The LRU size updates must
2093 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2095 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2096 enum lru_list lru, unsigned long *nr_zone_taken)
2100 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2101 if (!nr_zone_taken[zid])
2104 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2110 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2112 * lruvec->lru_lock is heavily contended. Some of the functions that
2113 * shrink the lists perform better by taking out a batch of pages
2114 * and working on them outside the LRU lock.
2116 * For pagecache intensive workloads, this function is the hottest
2117 * spot in the kernel (apart from copy_*_user functions).
2119 * Lru_lock must be held before calling this function.
2121 * @nr_to_scan: The number of eligible pages to look through on the list.
2122 * @lruvec: The LRU vector to pull pages from.
2123 * @dst: The temp list to put pages on to.
2124 * @nr_scanned: The number of pages that were scanned.
2125 * @sc: The scan_control struct for this reclaim session
2126 * @lru: LRU list id for isolating
2128 * returns how many pages were moved onto *@dst.
2130 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
2131 struct lruvec *lruvec, struct list_head *dst,
2132 unsigned long *nr_scanned, struct scan_control *sc,
2135 struct list_head *src = &lruvec->lists[lru];
2136 unsigned long nr_taken = 0;
2137 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2138 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2139 unsigned long skipped = 0;
2140 unsigned long scan, total_scan, nr_pages;
2141 LIST_HEAD(folios_skipped);
2145 while (scan < nr_to_scan && !list_empty(src)) {
2146 struct list_head *move_to = src;
2147 struct folio *folio;
2149 folio = lru_to_folio(src);
2150 prefetchw_prev_lru_folio(folio, src, flags);
2152 nr_pages = folio_nr_pages(folio);
2153 total_scan += nr_pages;
2155 if (folio_zonenum(folio) > sc->reclaim_idx) {
2156 nr_skipped[folio_zonenum(folio)] += nr_pages;
2157 move_to = &folios_skipped;
2162 * Do not count skipped folios because that makes the function
2163 * return with no isolated folios if the LRU mostly contains
2164 * ineligible folios. This causes the VM to not reclaim any
2165 * folios, triggering a premature OOM.
2166 * Account all pages in a folio.
2170 if (!folio_test_lru(folio))
2172 if (!sc->may_unmap && folio_mapped(folio))
2176 * Be careful not to clear the lru flag until after we're
2177 * sure the folio is not being freed elsewhere -- the
2178 * folio release code relies on it.
2180 if (unlikely(!folio_try_get(folio)))
2183 if (!folio_test_clear_lru(folio)) {
2184 /* Another thread is already isolating this folio */
2189 nr_taken += nr_pages;
2190 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2193 list_move(&folio->lru, move_to);
2197 * Splice any skipped folios to the start of the LRU list. Note that
2198 * this disrupts the LRU order when reclaiming for lower zones but
2199 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2200 * scanning would soon rescan the same folios to skip and waste lots
2203 if (!list_empty(&folios_skipped)) {
2206 list_splice(&folios_skipped, src);
2207 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2208 if (!nr_skipped[zid])
2211 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2212 skipped += nr_skipped[zid];
2215 *nr_scanned = total_scan;
2216 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2217 total_scan, skipped, nr_taken,
2218 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2219 update_lru_sizes(lruvec, lru, nr_zone_taken);
2224 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2225 * @folio: Folio to isolate from its LRU list.
2227 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2228 * corresponding to whatever LRU list the folio was on.
2230 * The folio will have its LRU flag cleared. If it was found on the
2231 * active list, it will have the Active flag set. If it was found on the
2232 * unevictable list, it will have the Unevictable flag set. These flags
2233 * may need to be cleared by the caller before letting the page go.
2237 * (1) Must be called with an elevated refcount on the page. This is a
2238 * fundamental difference from isolate_lru_pages() (which is called
2239 * without a stable reference).
2240 * (2) The lru_lock must not be held.
2241 * (3) Interrupts must be enabled.
2243 * Return: 0 if the folio was removed from an LRU list.
2244 * -EBUSY if the folio was not on an LRU list.
2246 int folio_isolate_lru(struct folio *folio)
2250 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2252 if (folio_test_clear_lru(folio)) {
2253 struct lruvec *lruvec;
2256 lruvec = folio_lruvec_lock_irq(folio);
2257 lruvec_del_folio(lruvec, folio);
2258 unlock_page_lruvec_irq(lruvec);
2266 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2267 * then get rescheduled. When there are massive number of tasks doing page
2268 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2269 * the LRU list will go small and be scanned faster than necessary, leading to
2270 * unnecessary swapping, thrashing and OOM.
2272 static int too_many_isolated(struct pglist_data *pgdat, int file,
2273 struct scan_control *sc)
2275 unsigned long inactive, isolated;
2278 if (current_is_kswapd())
2281 if (!writeback_throttling_sane(sc))
2285 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2286 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2288 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2289 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2293 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2294 * won't get blocked by normal direct-reclaimers, forming a circular
2297 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2300 too_many = isolated > inactive;
2302 /* Wake up tasks throttled due to too_many_isolated. */
2304 wake_throttle_isolated(pgdat);
2310 * move_pages_to_lru() moves folios from private @list to appropriate LRU list.
2311 * On return, @list is reused as a list of folios to be freed by the caller.
2313 * Returns the number of pages moved to the given lruvec.
2315 static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2316 struct list_head *list)
2318 int nr_pages, nr_moved = 0;
2319 LIST_HEAD(folios_to_free);
2321 while (!list_empty(list)) {
2322 struct folio *folio = lru_to_folio(list);
2324 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2325 list_del(&folio->lru);
2326 if (unlikely(!folio_evictable(folio))) {
2327 spin_unlock_irq(&lruvec->lru_lock);
2328 folio_putback_lru(folio);
2329 spin_lock_irq(&lruvec->lru_lock);
2334 * The folio_set_lru needs to be kept here for list integrity.
2336 * #0 move_pages_to_lru #1 release_pages
2337 * if (!folio_put_testzero())
2338 * if (folio_put_testzero())
2339 * !lru //skip lru_lock
2341 * list_add(&folio->lru,)
2342 * list_add(&folio->lru,)
2344 folio_set_lru(folio);
2346 if (unlikely(folio_put_testzero(folio))) {
2347 __folio_clear_lru_flags(folio);
2349 if (unlikely(folio_test_large(folio))) {
2350 spin_unlock_irq(&lruvec->lru_lock);
2351 destroy_large_folio(folio);
2352 spin_lock_irq(&lruvec->lru_lock);
2354 list_add(&folio->lru, &folios_to_free);
2360 * All pages were isolated from the same lruvec (and isolation
2361 * inhibits memcg migration).
2363 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2364 lruvec_add_folio(lruvec, folio);
2365 nr_pages = folio_nr_pages(folio);
2366 nr_moved += nr_pages;
2367 if (folio_test_active(folio))
2368 workingset_age_nonresident(lruvec, nr_pages);
2372 * To save our caller's stack, now use input list for pages to free.
2374 list_splice(&folios_to_free, list);
2380 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2381 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2382 * we should not throttle. Otherwise it is safe to do so.
2384 static int current_may_throttle(void)
2386 return !(current->flags & PF_LOCAL_THROTTLE);
2390 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2391 * of reclaimed pages
2393 static unsigned long
2394 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
2395 struct scan_control *sc, enum lru_list lru)
2397 LIST_HEAD(page_list);
2398 unsigned long nr_scanned;
2399 unsigned int nr_reclaimed = 0;
2400 unsigned long nr_taken;
2401 struct reclaim_stat stat;
2402 bool file = is_file_lru(lru);
2403 enum vm_event_item item;
2404 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2405 bool stalled = false;
2407 while (unlikely(too_many_isolated(pgdat, file, sc))) {
2411 /* wait a bit for the reclaimer. */
2413 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2415 /* We are about to die and free our memory. Return now. */
2416 if (fatal_signal_pending(current))
2417 return SWAP_CLUSTER_MAX;
2422 spin_lock_irq(&lruvec->lru_lock);
2424 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
2425 &nr_scanned, sc, lru);
2427 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2428 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
2429 if (!cgroup_reclaim(sc))
2430 __count_vm_events(item, nr_scanned);
2431 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2432 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2434 spin_unlock_irq(&lruvec->lru_lock);
2439 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
2441 spin_lock_irq(&lruvec->lru_lock);
2442 move_pages_to_lru(lruvec, &page_list);
2444 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2445 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
2446 if (!cgroup_reclaim(sc))
2447 __count_vm_events(item, nr_reclaimed);
2448 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2449 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2450 spin_unlock_irq(&lruvec->lru_lock);
2452 lru_note_cost(lruvec, file, stat.nr_pageout);
2453 mem_cgroup_uncharge_list(&page_list);
2454 free_unref_page_list(&page_list);
2457 * If dirty pages are scanned that are not queued for IO, it
2458 * implies that flushers are not doing their job. This can
2459 * happen when memory pressure pushes dirty pages to the end of
2460 * the LRU before the dirty limits are breached and the dirty
2461 * data has expired. It can also happen when the proportion of
2462 * dirty pages grows not through writes but through memory
2463 * pressure reclaiming all the clean cache. And in some cases,
2464 * the flushers simply cannot keep up with the allocation
2465 * rate. Nudge the flusher threads in case they are asleep.
2467 if (stat.nr_unqueued_dirty == nr_taken)
2468 wakeup_flusher_threads(WB_REASON_VMSCAN);
2470 sc->nr.dirty += stat.nr_dirty;
2471 sc->nr.congested += stat.nr_congested;
2472 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2473 sc->nr.writeback += stat.nr_writeback;
2474 sc->nr.immediate += stat.nr_immediate;
2475 sc->nr.taken += nr_taken;
2477 sc->nr.file_taken += nr_taken;
2479 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2480 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2481 return nr_reclaimed;
2485 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2487 * We move them the other way if the folio is referenced by one or more
2490 * If the folios are mostly unmapped, the processing is fast and it is
2491 * appropriate to hold lru_lock across the whole operation. But if
2492 * the folios are mapped, the processing is slow (folio_referenced()), so
2493 * we should drop lru_lock around each folio. It's impossible to balance
2494 * this, so instead we remove the folios from the LRU while processing them.
2495 * It is safe to rely on the active flag against the non-LRU folios in here
2496 * because nobody will play with that bit on a non-LRU folio.
2498 * The downside is that we have to touch folio->_refcount against each folio.
2499 * But we had to alter folio->flags anyway.
2501 static void shrink_active_list(unsigned long nr_to_scan,
2502 struct lruvec *lruvec,
2503 struct scan_control *sc,
2506 unsigned long nr_taken;
2507 unsigned long nr_scanned;
2508 unsigned long vm_flags;
2509 LIST_HEAD(l_hold); /* The folios which were snipped off */
2510 LIST_HEAD(l_active);
2511 LIST_HEAD(l_inactive);
2512 unsigned nr_deactivate, nr_activate;
2513 unsigned nr_rotated = 0;
2514 int file = is_file_lru(lru);
2515 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2519 spin_lock_irq(&lruvec->lru_lock);
2521 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
2522 &nr_scanned, sc, lru);
2524 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2526 if (!cgroup_reclaim(sc))
2527 __count_vm_events(PGREFILL, nr_scanned);
2528 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2530 spin_unlock_irq(&lruvec->lru_lock);
2532 while (!list_empty(&l_hold)) {
2533 struct folio *folio;
2536 folio = lru_to_folio(&l_hold);
2537 list_del(&folio->lru);
2539 if (unlikely(!folio_evictable(folio))) {
2540 folio_putback_lru(folio);
2544 if (unlikely(buffer_heads_over_limit)) {
2545 if (folio_get_private(folio) && folio_trylock(folio)) {
2546 if (folio_get_private(folio))
2547 filemap_release_folio(folio, 0);
2548 folio_unlock(folio);
2552 /* Referenced or rmap lock contention: rotate */
2553 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2556 * Identify referenced, file-backed active folios and
2557 * give them one more trip around the active list. So
2558 * that executable code get better chances to stay in
2559 * memory under moderate memory pressure. Anon folios
2560 * are not likely to be evicted by use-once streaming
2561 * IO, plus JVM can create lots of anon VM_EXEC folios,
2562 * so we ignore them here.
2564 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2565 nr_rotated += folio_nr_pages(folio);
2566 list_add(&folio->lru, &l_active);
2571 folio_clear_active(folio); /* we are de-activating */
2572 folio_set_workingset(folio);
2573 list_add(&folio->lru, &l_inactive);
2577 * Move folios back to the lru list.
2579 spin_lock_irq(&lruvec->lru_lock);
2581 nr_activate = move_pages_to_lru(lruvec, &l_active);
2582 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
2583 /* Keep all free folios in l_active list */
2584 list_splice(&l_inactive, &l_active);
2586 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2587 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2589 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2590 spin_unlock_irq(&lruvec->lru_lock);
2592 mem_cgroup_uncharge_list(&l_active);
2593 free_unref_page_list(&l_active);
2594 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2595 nr_deactivate, nr_rotated, sc->priority, file);
2598 static unsigned int reclaim_page_list(struct list_head *page_list,
2599 struct pglist_data *pgdat)
2601 struct reclaim_stat dummy_stat;
2602 unsigned int nr_reclaimed;
2603 struct folio *folio;
2604 struct scan_control sc = {
2605 .gfp_mask = GFP_KERNEL,
2612 nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false);
2613 while (!list_empty(page_list)) {
2614 folio = lru_to_folio(page_list);
2615 list_del(&folio->lru);
2616 folio_putback_lru(folio);
2619 return nr_reclaimed;
2622 unsigned long reclaim_pages(struct list_head *folio_list)
2625 unsigned int nr_reclaimed = 0;
2626 LIST_HEAD(node_folio_list);
2627 unsigned int noreclaim_flag;
2629 if (list_empty(folio_list))
2630 return nr_reclaimed;
2632 noreclaim_flag = memalloc_noreclaim_save();
2634 nid = folio_nid(lru_to_folio(folio_list));
2636 struct folio *folio = lru_to_folio(folio_list);
2638 if (nid == folio_nid(folio)) {
2639 folio_clear_active(folio);
2640 list_move(&folio->lru, &node_folio_list);
2644 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2645 nid = folio_nid(lru_to_folio(folio_list));
2646 } while (!list_empty(folio_list));
2648 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2650 memalloc_noreclaim_restore(noreclaim_flag);
2652 return nr_reclaimed;
2655 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2656 struct lruvec *lruvec, struct scan_control *sc)
2658 if (is_active_lru(lru)) {
2659 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2660 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2662 sc->skipped_deactivate = 1;
2666 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2670 * The inactive anon list should be small enough that the VM never has
2671 * to do too much work.
2673 * The inactive file list should be small enough to leave most memory
2674 * to the established workingset on the scan-resistant active list,
2675 * but large enough to avoid thrashing the aggregate readahead window.
2677 * Both inactive lists should also be large enough that each inactive
2678 * page has a chance to be referenced again before it is reclaimed.
2680 * If that fails and refaulting is observed, the inactive list grows.
2682 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2683 * on this LRU, maintained by the pageout code. An inactive_ratio
2684 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2687 * memory ratio inactive
2688 * -------------------------------------
2697 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2699 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2700 unsigned long inactive, active;
2701 unsigned long inactive_ratio;
2704 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2705 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2707 gb = (inactive + active) >> (30 - PAGE_SHIFT);
2709 inactive_ratio = int_sqrt(10 * gb);
2713 return inactive * inactive_ratio < active;
2724 * Determine how aggressively the anon and file LRU lists should be
2727 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2728 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2730 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2733 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2734 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2735 unsigned long anon_cost, file_cost, total_cost;
2736 int swappiness = mem_cgroup_swappiness(memcg);
2737 u64 fraction[ANON_AND_FILE];
2738 u64 denominator = 0; /* gcc */
2739 enum scan_balance scan_balance;
2740 unsigned long ap, fp;
2743 /* If we have no swap space, do not bother scanning anon pages. */
2744 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2745 scan_balance = SCAN_FILE;
2750 * Global reclaim will swap to prevent OOM even with no
2751 * swappiness, but memcg users want to use this knob to
2752 * disable swapping for individual groups completely when
2753 * using the memory controller's swap limit feature would be
2756 if (cgroup_reclaim(sc) && !swappiness) {
2757 scan_balance = SCAN_FILE;
2762 * Do not apply any pressure balancing cleverness when the
2763 * system is close to OOM, scan both anon and file equally
2764 * (unless the swappiness setting disagrees with swapping).
2766 if (!sc->priority && swappiness) {
2767 scan_balance = SCAN_EQUAL;
2772 * If the system is almost out of file pages, force-scan anon.
2774 if (sc->file_is_tiny) {
2775 scan_balance = SCAN_ANON;
2780 * If there is enough inactive page cache, we do not reclaim
2781 * anything from the anonymous working right now.
2783 if (sc->cache_trim_mode) {
2784 scan_balance = SCAN_FILE;
2788 scan_balance = SCAN_FRACT;
2790 * Calculate the pressure balance between anon and file pages.
2792 * The amount of pressure we put on each LRU is inversely
2793 * proportional to the cost of reclaiming each list, as
2794 * determined by the share of pages that are refaulting, times
2795 * the relative IO cost of bringing back a swapped out
2796 * anonymous page vs reloading a filesystem page (swappiness).
2798 * Although we limit that influence to ensure no list gets
2799 * left behind completely: at least a third of the pressure is
2800 * applied, before swappiness.
2802 * With swappiness at 100, anon and file have equal IO cost.
2804 total_cost = sc->anon_cost + sc->file_cost;
2805 anon_cost = total_cost + sc->anon_cost;
2806 file_cost = total_cost + sc->file_cost;
2807 total_cost = anon_cost + file_cost;
2809 ap = swappiness * (total_cost + 1);
2810 ap /= anon_cost + 1;
2812 fp = (200 - swappiness) * (total_cost + 1);
2813 fp /= file_cost + 1;
2817 denominator = ap + fp;
2819 for_each_evictable_lru(lru) {
2820 int file = is_file_lru(lru);
2821 unsigned long lruvec_size;
2822 unsigned long low, min;
2825 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2826 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2831 * Scale a cgroup's reclaim pressure by proportioning
2832 * its current usage to its memory.low or memory.min
2835 * This is important, as otherwise scanning aggression
2836 * becomes extremely binary -- from nothing as we
2837 * approach the memory protection threshold, to totally
2838 * nominal as we exceed it. This results in requiring
2839 * setting extremely liberal protection thresholds. It
2840 * also means we simply get no protection at all if we
2841 * set it too low, which is not ideal.
2843 * If there is any protection in place, we reduce scan
2844 * pressure by how much of the total memory used is
2845 * within protection thresholds.
2847 * There is one special case: in the first reclaim pass,
2848 * we skip over all groups that are within their low
2849 * protection. If that fails to reclaim enough pages to
2850 * satisfy the reclaim goal, we come back and override
2851 * the best-effort low protection. However, we still
2852 * ideally want to honor how well-behaved groups are in
2853 * that case instead of simply punishing them all
2854 * equally. As such, we reclaim them based on how much
2855 * memory they are using, reducing the scan pressure
2856 * again by how much of the total memory used is under
2859 unsigned long cgroup_size = mem_cgroup_size(memcg);
2860 unsigned long protection;
2862 /* memory.low scaling, make sure we retry before OOM */
2863 if (!sc->memcg_low_reclaim && low > min) {
2865 sc->memcg_low_skipped = 1;
2870 /* Avoid TOCTOU with earlier protection check */
2871 cgroup_size = max(cgroup_size, protection);
2873 scan = lruvec_size - lruvec_size * protection /
2877 * Minimally target SWAP_CLUSTER_MAX pages to keep
2878 * reclaim moving forwards, avoiding decrementing
2879 * sc->priority further than desirable.
2881 scan = max(scan, SWAP_CLUSTER_MAX);
2886 scan >>= sc->priority;
2889 * If the cgroup's already been deleted, make sure to
2890 * scrape out the remaining cache.
2892 if (!scan && !mem_cgroup_online(memcg))
2893 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2895 switch (scan_balance) {
2897 /* Scan lists relative to size */
2901 * Scan types proportional to swappiness and
2902 * their relative recent reclaim efficiency.
2903 * Make sure we don't miss the last page on
2904 * the offlined memory cgroups because of a
2907 scan = mem_cgroup_online(memcg) ?
2908 div64_u64(scan * fraction[file], denominator) :
2909 DIV64_U64_ROUND_UP(scan * fraction[file],
2914 /* Scan one type exclusively */
2915 if ((scan_balance == SCAN_FILE) != file)
2919 /* Look ma, no brain */
2928 * Anonymous LRU management is a waste if there is
2929 * ultimately no way to reclaim the memory.
2931 static bool can_age_anon_pages(struct pglist_data *pgdat,
2932 struct scan_control *sc)
2934 /* Aging the anon LRU is valuable if swap is present: */
2935 if (total_swap_pages > 0)
2938 /* Also valuable if anon pages can be demoted: */
2939 return can_demote(pgdat->node_id, sc);
2942 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2944 unsigned long nr[NR_LRU_LISTS];
2945 unsigned long targets[NR_LRU_LISTS];
2946 unsigned long nr_to_scan;
2948 unsigned long nr_reclaimed = 0;
2949 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2950 struct blk_plug plug;
2953 get_scan_count(lruvec, sc, nr);
2955 /* Record the original scan target for proportional adjustments later */
2956 memcpy(targets, nr, sizeof(nr));
2959 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2960 * event that can occur when there is little memory pressure e.g.
2961 * multiple streaming readers/writers. Hence, we do not abort scanning
2962 * when the requested number of pages are reclaimed when scanning at
2963 * DEF_PRIORITY on the assumption that the fact we are direct
2964 * reclaiming implies that kswapd is not keeping up and it is best to
2965 * do a batch of work at once. For memcg reclaim one check is made to
2966 * abort proportional reclaim if either the file or anon lru has already
2967 * dropped to zero at the first pass.
2969 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
2970 sc->priority == DEF_PRIORITY);
2972 blk_start_plug(&plug);
2973 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2974 nr[LRU_INACTIVE_FILE]) {
2975 unsigned long nr_anon, nr_file, percentage;
2976 unsigned long nr_scanned;
2978 for_each_evictable_lru(lru) {
2980 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2981 nr[lru] -= nr_to_scan;
2983 nr_reclaimed += shrink_list(lru, nr_to_scan,
2990 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2994 * For kswapd and memcg, reclaim at least the number of pages
2995 * requested. Ensure that the anon and file LRUs are scanned
2996 * proportionally what was requested by get_scan_count(). We
2997 * stop reclaiming one LRU and reduce the amount scanning
2998 * proportional to the original scan target.
3000 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3001 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3004 * It's just vindictive to attack the larger once the smaller
3005 * has gone to zero. And given the way we stop scanning the
3006 * smaller below, this makes sure that we only make one nudge
3007 * towards proportionality once we've got nr_to_reclaim.
3009 if (!nr_file || !nr_anon)
3012 if (nr_file > nr_anon) {
3013 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3014 targets[LRU_ACTIVE_ANON] + 1;
3016 percentage = nr_anon * 100 / scan_target;
3018 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3019 targets[LRU_ACTIVE_FILE] + 1;
3021 percentage = nr_file * 100 / scan_target;
3024 /* Stop scanning the smaller of the LRU */
3026 nr[lru + LRU_ACTIVE] = 0;
3029 * Recalculate the other LRU scan count based on its original
3030 * scan target and the percentage scanning already complete
3032 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3033 nr_scanned = targets[lru] - nr[lru];
3034 nr[lru] = targets[lru] * (100 - percentage) / 100;
3035 nr[lru] -= min(nr[lru], nr_scanned);
3038 nr_scanned = targets[lru] - nr[lru];
3039 nr[lru] = targets[lru] * (100 - percentage) / 100;
3040 nr[lru] -= min(nr[lru], nr_scanned);
3042 scan_adjusted = true;
3044 blk_finish_plug(&plug);
3045 sc->nr_reclaimed += nr_reclaimed;
3048 * Even if we did not try to evict anon pages at all, we want to
3049 * rebalance the anon lru active/inactive ratio.
3051 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
3052 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3053 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3054 sc, LRU_ACTIVE_ANON);
3057 /* Use reclaim/compaction for costly allocs or under memory pressure */
3058 static bool in_reclaim_compaction(struct scan_control *sc)
3060 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
3061 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
3062 sc->priority < DEF_PRIORITY - 2))
3069 * Reclaim/compaction is used for high-order allocation requests. It reclaims
3070 * order-0 pages before compacting the zone. should_continue_reclaim() returns
3071 * true if more pages should be reclaimed such that when the page allocator
3072 * calls try_to_compact_pages() that it will have enough free pages to succeed.
3073 * It will give up earlier than that if there is difficulty reclaiming pages.
3075 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
3076 unsigned long nr_reclaimed,
3077 struct scan_control *sc)
3079 unsigned long pages_for_compaction;
3080 unsigned long inactive_lru_pages;
3083 /* If not in reclaim/compaction mode, stop */
3084 if (!in_reclaim_compaction(sc))
3088 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
3089 * number of pages that were scanned. This will return to the caller
3090 * with the risk reclaim/compaction and the resulting allocation attempt
3091 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
3092 * allocations through requiring that the full LRU list has been scanned
3093 * first, by assuming that zero delta of sc->nr_scanned means full LRU
3094 * scan, but that approximation was wrong, and there were corner cases
3095 * where always a non-zero amount of pages were scanned.
3100 /* If compaction would go ahead or the allocation would succeed, stop */
3101 for (z = 0; z <= sc->reclaim_idx; z++) {
3102 struct zone *zone = &pgdat->node_zones[z];
3103 if (!managed_zone(zone))
3106 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
3107 case COMPACT_SUCCESS:
3108 case COMPACT_CONTINUE:
3111 /* check next zone */
3117 * If we have not reclaimed enough pages for compaction and the
3118 * inactive lists are large enough, continue reclaiming
3120 pages_for_compaction = compact_gap(sc->order);
3121 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
3122 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
3123 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
3125 return inactive_lru_pages > pages_for_compaction;
3128 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
3130 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
3131 struct mem_cgroup *memcg;
3133 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
3135 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3136 unsigned long reclaimed;
3137 unsigned long scanned;
3140 * This loop can become CPU-bound when target memcgs
3141 * aren't eligible for reclaim - either because they
3142 * don't have any reclaimable pages, or because their
3143 * memory is explicitly protected. Avoid soft lockups.
3147 mem_cgroup_calculate_protection(target_memcg, memcg);
3149 if (mem_cgroup_below_min(memcg)) {
3152 * If there is no reclaimable memory, OOM.
3155 } else if (mem_cgroup_below_low(memcg)) {
3158 * Respect the protection only as long as
3159 * there is an unprotected supply
3160 * of reclaimable memory from other cgroups.
3162 if (!sc->memcg_low_reclaim) {
3163 sc->memcg_low_skipped = 1;
3166 memcg_memory_event(memcg, MEMCG_LOW);
3169 reclaimed = sc->nr_reclaimed;
3170 scanned = sc->nr_scanned;
3172 shrink_lruvec(lruvec, sc);
3174 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
3177 /* Record the group's reclaim efficiency */
3178 vmpressure(sc->gfp_mask, memcg, false,
3179 sc->nr_scanned - scanned,
3180 sc->nr_reclaimed - reclaimed);
3182 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
3185 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
3187 struct reclaim_state *reclaim_state = current->reclaim_state;
3188 unsigned long nr_reclaimed, nr_scanned;
3189 struct lruvec *target_lruvec;
3190 bool reclaimable = false;
3193 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
3197 * Flush the memory cgroup stats, so that we read accurate per-memcg
3198 * lruvec stats for heuristics.
3200 mem_cgroup_flush_stats();
3202 memset(&sc->nr, 0, sizeof(sc->nr));
3204 nr_reclaimed = sc->nr_reclaimed;
3205 nr_scanned = sc->nr_scanned;
3208 * Determine the scan balance between anon and file LRUs.
3210 spin_lock_irq(&target_lruvec->lru_lock);
3211 sc->anon_cost = target_lruvec->anon_cost;
3212 sc->file_cost = target_lruvec->file_cost;
3213 spin_unlock_irq(&target_lruvec->lru_lock);
3216 * Target desirable inactive:active list ratios for the anon
3217 * and file LRU lists.
3219 if (!sc->force_deactivate) {
3220 unsigned long refaults;
3222 refaults = lruvec_page_state(target_lruvec,
3223 WORKINGSET_ACTIVATE_ANON);
3224 if (refaults != target_lruvec->refaults[0] ||
3225 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
3226 sc->may_deactivate |= DEACTIVATE_ANON;
3228 sc->may_deactivate &= ~DEACTIVATE_ANON;
3231 * When refaults are being observed, it means a new
3232 * workingset is being established. Deactivate to get
3233 * rid of any stale active pages quickly.
3235 refaults = lruvec_page_state(target_lruvec,
3236 WORKINGSET_ACTIVATE_FILE);
3237 if (refaults != target_lruvec->refaults[1] ||
3238 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
3239 sc->may_deactivate |= DEACTIVATE_FILE;
3241 sc->may_deactivate &= ~DEACTIVATE_FILE;
3243 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
3246 * If we have plenty of inactive file pages that aren't
3247 * thrashing, try to reclaim those first before touching
3250 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
3251 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
3252 sc->cache_trim_mode = 1;
3254 sc->cache_trim_mode = 0;
3257 * Prevent the reclaimer from falling into the cache trap: as
3258 * cache pages start out inactive, every cache fault will tip
3259 * the scan balance towards the file LRU. And as the file LRU
3260 * shrinks, so does the window for rotation from references.
3261 * This means we have a runaway feedback loop where a tiny
3262 * thrashing file LRU becomes infinitely more attractive than
3263 * anon pages. Try to detect this based on file LRU size.
3265 if (!cgroup_reclaim(sc)) {
3266 unsigned long total_high_wmark = 0;
3267 unsigned long free, anon;
3270 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
3271 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
3272 node_page_state(pgdat, NR_INACTIVE_FILE);
3274 for (z = 0; z < MAX_NR_ZONES; z++) {
3275 struct zone *zone = &pgdat->node_zones[z];
3276 if (!managed_zone(zone))
3279 total_high_wmark += high_wmark_pages(zone);
3283 * Consider anon: if that's low too, this isn't a
3284 * runaway file reclaim problem, but rather just
3285 * extreme pressure. Reclaim as per usual then.
3287 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
3290 file + free <= total_high_wmark &&
3291 !(sc->may_deactivate & DEACTIVATE_ANON) &&
3292 anon >> sc->priority;
3295 shrink_node_memcgs(pgdat, sc);
3297 if (reclaim_state) {
3298 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
3299 reclaim_state->reclaimed_slab = 0;
3302 /* Record the subtree's reclaim efficiency */
3303 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
3304 sc->nr_scanned - nr_scanned,
3305 sc->nr_reclaimed - nr_reclaimed);
3307 if (sc->nr_reclaimed - nr_reclaimed)
3310 if (current_is_kswapd()) {
3312 * If reclaim is isolating dirty pages under writeback,
3313 * it implies that the long-lived page allocation rate
3314 * is exceeding the page laundering rate. Either the
3315 * global limits are not being effective at throttling
3316 * processes due to the page distribution throughout
3317 * zones or there is heavy usage of a slow backing
3318 * device. The only option is to throttle from reclaim
3319 * context which is not ideal as there is no guarantee
3320 * the dirtying process is throttled in the same way
3321 * balance_dirty_pages() manages.
3323 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3324 * count the number of pages under pages flagged for
3325 * immediate reclaim and stall if any are encountered
3326 * in the nr_immediate check below.
3328 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3329 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
3331 /* Allow kswapd to start writing pages during reclaim.*/
3332 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3333 set_bit(PGDAT_DIRTY, &pgdat->flags);
3336 * If kswapd scans pages marked for immediate
3337 * reclaim and under writeback (nr_immediate), it
3338 * implies that pages are cycling through the LRU
3339 * faster than they are written so forcibly stall
3340 * until some pages complete writeback.
3342 if (sc->nr.immediate)
3343 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
3347 * Tag a node/memcg as congested if all the dirty pages were marked
3348 * for writeback and immediate reclaim (counted in nr.congested).
3350 * Legacy memcg will stall in page writeback so avoid forcibly
3351 * stalling in reclaim_throttle().
3353 if ((current_is_kswapd() ||
3354 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
3355 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
3356 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
3359 * Stall direct reclaim for IO completions if the lruvec is
3360 * node is congested. Allow kswapd to continue until it
3361 * starts encountering unqueued dirty pages or cycling through
3362 * the LRU too quickly.
3364 if (!current_is_kswapd() && current_may_throttle() &&
3365 !sc->hibernation_mode &&
3366 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
3367 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
3369 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3374 * Kswapd gives up on balancing particular nodes after too
3375 * many failures to reclaim anything from them and goes to
3376 * sleep. On reclaim progress, reset the failure counter. A
3377 * successful direct reclaim run will revive a dormant kswapd.
3380 pgdat->kswapd_failures = 0;
3384 * Returns true if compaction should go ahead for a costly-order request, or
3385 * the allocation would already succeed without compaction. Return false if we
3386 * should reclaim first.
3388 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
3390 unsigned long watermark;
3391 enum compact_result suitable;
3393 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3394 if (suitable == COMPACT_SUCCESS)
3395 /* Allocation should succeed already. Don't reclaim. */
3397 if (suitable == COMPACT_SKIPPED)
3398 /* Compaction cannot yet proceed. Do reclaim. */
3402 * Compaction is already possible, but it takes time to run and there
3403 * are potentially other callers using the pages just freed. So proceed
3404 * with reclaim to make a buffer of free pages available to give
3405 * compaction a reasonable chance of completing and allocating the page.
3406 * Note that we won't actually reclaim the whole buffer in one attempt
3407 * as the target watermark in should_continue_reclaim() is lower. But if
3408 * we are already above the high+gap watermark, don't reclaim at all.
3410 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
3412 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
3415 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
3418 * If reclaim is making progress greater than 12% efficiency then
3419 * wake all the NOPROGRESS throttled tasks.
3421 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
3422 wait_queue_head_t *wqh;
3424 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
3425 if (waitqueue_active(wqh))
3432 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
3433 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
3434 * under writeback and marked for immediate reclaim at the tail of the
3437 if (current_is_kswapd() || cgroup_reclaim(sc))
3440 /* Throttle if making no progress at high prioities. */
3441 if (sc->priority == 1 && !sc->nr_reclaimed)
3442 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
3446 * This is the direct reclaim path, for page-allocating processes. We only
3447 * try to reclaim pages from zones which will satisfy the caller's allocation
3450 * If a zone is deemed to be full of pinned pages then just give it a light
3451 * scan then give up on it.
3453 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
3457 unsigned long nr_soft_reclaimed;
3458 unsigned long nr_soft_scanned;
3460 pg_data_t *last_pgdat = NULL;
3461 pg_data_t *first_pgdat = NULL;
3464 * If the number of buffer_heads in the machine exceeds the maximum
3465 * allowed level, force direct reclaim to scan the highmem zone as
3466 * highmem pages could be pinning lowmem pages storing buffer_heads
3468 orig_mask = sc->gfp_mask;
3469 if (buffer_heads_over_limit) {
3470 sc->gfp_mask |= __GFP_HIGHMEM;
3471 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
3474 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3475 sc->reclaim_idx, sc->nodemask) {
3477 * Take care memory controller reclaiming has small influence
3480 if (!cgroup_reclaim(sc)) {
3481 if (!cpuset_zone_allowed(zone,
3482 GFP_KERNEL | __GFP_HARDWALL))
3486 * If we already have plenty of memory free for
3487 * compaction in this zone, don't free any more.
3488 * Even though compaction is invoked for any
3489 * non-zero order, only frequent costly order
3490 * reclamation is disruptive enough to become a
3491 * noticeable problem, like transparent huge
3494 if (IS_ENABLED(CONFIG_COMPACTION) &&
3495 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
3496 compaction_ready(zone, sc)) {
3497 sc->compaction_ready = true;
3502 * Shrink each node in the zonelist once. If the
3503 * zonelist is ordered by zone (not the default) then a
3504 * node may be shrunk multiple times but in that case
3505 * the user prefers lower zones being preserved.
3507 if (zone->zone_pgdat == last_pgdat)
3511 * This steals pages from memory cgroups over softlimit
3512 * and returns the number of reclaimed pages and
3513 * scanned pages. This works for global memory pressure
3514 * and balancing, not for a memcg's limit.
3516 nr_soft_scanned = 0;
3517 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
3518 sc->order, sc->gfp_mask,
3520 sc->nr_reclaimed += nr_soft_reclaimed;
3521 sc->nr_scanned += nr_soft_scanned;
3522 /* need some check for avoid more shrink_zone() */
3526 first_pgdat = zone->zone_pgdat;
3528 /* See comment about same check for global reclaim above */
3529 if (zone->zone_pgdat == last_pgdat)
3531 last_pgdat = zone->zone_pgdat;
3532 shrink_node(zone->zone_pgdat, sc);
3536 consider_reclaim_throttle(first_pgdat, sc);
3539 * Restore to original mask to avoid the impact on the caller if we
3540 * promoted it to __GFP_HIGHMEM.
3542 sc->gfp_mask = orig_mask;
3545 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
3547 struct lruvec *target_lruvec;
3548 unsigned long refaults;
3550 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
3551 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
3552 target_lruvec->refaults[0] = refaults;
3553 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
3554 target_lruvec->refaults[1] = refaults;
3558 * This is the main entry point to direct page reclaim.
3560 * If a full scan of the inactive list fails to free enough memory then we
3561 * are "out of memory" and something needs to be killed.
3563 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3564 * high - the zone may be full of dirty or under-writeback pages, which this
3565 * caller can't do much about. We kick the writeback threads and take explicit
3566 * naps in the hope that some of these pages can be written. But if the
3567 * allocating task holds filesystem locks which prevent writeout this might not
3568 * work, and the allocation attempt will fail.
3570 * returns: 0, if no pages reclaimed
3571 * else, the number of pages reclaimed
3573 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3574 struct scan_control *sc)
3576 int initial_priority = sc->priority;
3577 pg_data_t *last_pgdat;
3581 delayacct_freepages_start();
3583 if (!cgroup_reclaim(sc))
3584 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3587 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3590 shrink_zones(zonelist, sc);
3592 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3595 if (sc->compaction_ready)
3599 * If we're getting trouble reclaiming, start doing
3600 * writepage even in laptop mode.
3602 if (sc->priority < DEF_PRIORITY - 2)
3603 sc->may_writepage = 1;
3604 } while (--sc->priority >= 0);
3607 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3609 if (zone->zone_pgdat == last_pgdat)
3611 last_pgdat = zone->zone_pgdat;
3613 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3615 if (cgroup_reclaim(sc)) {
3616 struct lruvec *lruvec;
3618 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3620 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3624 delayacct_freepages_end();
3626 if (sc->nr_reclaimed)
3627 return sc->nr_reclaimed;
3629 /* Aborted reclaim to try compaction? don't OOM, then */
3630 if (sc->compaction_ready)
3634 * We make inactive:active ratio decisions based on the node's
3635 * composition of memory, but a restrictive reclaim_idx or a
3636 * memory.low cgroup setting can exempt large amounts of
3637 * memory from reclaim. Neither of which are very common, so
3638 * instead of doing costly eligibility calculations of the
3639 * entire cgroup subtree up front, we assume the estimates are
3640 * good, and retry with forcible deactivation if that fails.
3642 if (sc->skipped_deactivate) {
3643 sc->priority = initial_priority;
3644 sc->force_deactivate = 1;
3645 sc->skipped_deactivate = 0;
3649 /* Untapped cgroup reserves? Don't OOM, retry. */
3650 if (sc->memcg_low_skipped) {
3651 sc->priority = initial_priority;
3652 sc->force_deactivate = 0;
3653 sc->memcg_low_reclaim = 1;
3654 sc->memcg_low_skipped = 0;
3661 static bool allow_direct_reclaim(pg_data_t *pgdat)
3664 unsigned long pfmemalloc_reserve = 0;
3665 unsigned long free_pages = 0;
3669 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3672 for (i = 0; i <= ZONE_NORMAL; i++) {
3673 zone = &pgdat->node_zones[i];
3674 if (!managed_zone(zone))
3677 if (!zone_reclaimable_pages(zone))
3680 pfmemalloc_reserve += min_wmark_pages(zone);
3681 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3684 /* If there are no reserves (unexpected config) then do not throttle */
3685 if (!pfmemalloc_reserve)
3688 wmark_ok = free_pages > pfmemalloc_reserve / 2;
3690 /* kswapd must be awake if processes are being throttled */
3691 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3692 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
3693 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
3695 wake_up_interruptible(&pgdat->kswapd_wait);
3702 * Throttle direct reclaimers if backing storage is backed by the network
3703 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3704 * depleted. kswapd will continue to make progress and wake the processes
3705 * when the low watermark is reached.
3707 * Returns true if a fatal signal was delivered during throttling. If this
3708 * happens, the page allocator should not consider triggering the OOM killer.
3710 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
3711 nodemask_t *nodemask)
3715 pg_data_t *pgdat = NULL;
3718 * Kernel threads should not be throttled as they may be indirectly
3719 * responsible for cleaning pages necessary for reclaim to make forward
3720 * progress. kjournald for example may enter direct reclaim while
3721 * committing a transaction where throttling it could forcing other
3722 * processes to block on log_wait_commit().
3724 if (current->flags & PF_KTHREAD)
3728 * If a fatal signal is pending, this process should not throttle.
3729 * It should return quickly so it can exit and free its memory
3731 if (fatal_signal_pending(current))
3735 * Check if the pfmemalloc reserves are ok by finding the first node
3736 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3737 * GFP_KERNEL will be required for allocating network buffers when
3738 * swapping over the network so ZONE_HIGHMEM is unusable.
3740 * Throttling is based on the first usable node and throttled processes
3741 * wait on a queue until kswapd makes progress and wakes them. There
3742 * is an affinity then between processes waking up and where reclaim
3743 * progress has been made assuming the process wakes on the same node.
3744 * More importantly, processes running on remote nodes will not compete
3745 * for remote pfmemalloc reserves and processes on different nodes
3746 * should make reasonable progress.
3748 for_each_zone_zonelist_nodemask(zone, z, zonelist,
3749 gfp_zone(gfp_mask), nodemask) {
3750 if (zone_idx(zone) > ZONE_NORMAL)
3753 /* Throttle based on the first usable node */
3754 pgdat = zone->zone_pgdat;
3755 if (allow_direct_reclaim(pgdat))
3760 /* If no zone was usable by the allocation flags then do not throttle */
3764 /* Account for the throttling */
3765 count_vm_event(PGSCAN_DIRECT_THROTTLE);
3768 * If the caller cannot enter the filesystem, it's possible that it
3769 * is due to the caller holding an FS lock or performing a journal
3770 * transaction in the case of a filesystem like ext[3|4]. In this case,
3771 * it is not safe to block on pfmemalloc_wait as kswapd could be
3772 * blocked waiting on the same lock. Instead, throttle for up to a
3773 * second before continuing.
3775 if (!(gfp_mask & __GFP_FS))
3776 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3777 allow_direct_reclaim(pgdat), HZ);
3779 /* Throttle until kswapd wakes the process */
3780 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3781 allow_direct_reclaim(pgdat));
3783 if (fatal_signal_pending(current))
3790 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3791 gfp_t gfp_mask, nodemask_t *nodemask)
3793 unsigned long nr_reclaimed;
3794 struct scan_control sc = {
3795 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3796 .gfp_mask = current_gfp_context(gfp_mask),
3797 .reclaim_idx = gfp_zone(gfp_mask),
3799 .nodemask = nodemask,
3800 .priority = DEF_PRIORITY,
3801 .may_writepage = !laptop_mode,
3807 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3808 * Confirm they are large enough for max values.
3810 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3811 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3812 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3815 * Do not enter reclaim if fatal signal was delivered while throttled.
3816 * 1 is returned so that the page allocator does not OOM kill at this
3819 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
3822 set_task_reclaim_state(current, &sc.reclaim_state);
3823 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
3825 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3827 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
3828 set_task_reclaim_state(current, NULL);
3830 return nr_reclaimed;
3835 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3836 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
3837 gfp_t gfp_mask, bool noswap,
3839 unsigned long *nr_scanned)
3841 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3842 struct scan_control sc = {
3843 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3844 .target_mem_cgroup = memcg,
3845 .may_writepage = !laptop_mode,
3847 .reclaim_idx = MAX_NR_ZONES - 1,
3848 .may_swap = !noswap,
3851 WARN_ON_ONCE(!current->reclaim_state);
3853 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3854 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3856 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3860 * NOTE: Although we can get the priority field, using it
3861 * here is not a good idea, since it limits the pages we can scan.
3862 * if we don't reclaim here, the shrink_node from balance_pgdat
3863 * will pick up pages from other mem cgroup's as well. We hack
3864 * the priority and make it zero.
3866 shrink_lruvec(lruvec, &sc);
3868 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3870 *nr_scanned = sc.nr_scanned;
3872 return sc.nr_reclaimed;
3875 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3876 unsigned long nr_pages,
3880 unsigned long nr_reclaimed;
3881 unsigned int noreclaim_flag;
3882 struct scan_control sc = {
3883 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3884 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3885 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3886 .reclaim_idx = MAX_NR_ZONES - 1,
3887 .target_mem_cgroup = memcg,
3888 .priority = DEF_PRIORITY,
3889 .may_writepage = !laptop_mode,
3891 .may_swap = may_swap,
3894 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3895 * equal pressure on all the nodes. This is based on the assumption that
3896 * the reclaim does not bail out early.
3898 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3900 set_task_reclaim_state(current, &sc.reclaim_state);
3901 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3902 noreclaim_flag = memalloc_noreclaim_save();
3904 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3906 memalloc_noreclaim_restore(noreclaim_flag);
3907 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3908 set_task_reclaim_state(current, NULL);
3910 return nr_reclaimed;
3914 static void age_active_anon(struct pglist_data *pgdat,
3915 struct scan_control *sc)
3917 struct mem_cgroup *memcg;
3918 struct lruvec *lruvec;
3920 if (!can_age_anon_pages(pgdat, sc))
3923 lruvec = mem_cgroup_lruvec(NULL, pgdat);
3924 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3927 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3929 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3930 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3931 sc, LRU_ACTIVE_ANON);
3932 memcg = mem_cgroup_iter(NULL, memcg, NULL);
3936 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
3942 * Check for watermark boosts top-down as the higher zones
3943 * are more likely to be boosted. Both watermarks and boosts
3944 * should not be checked at the same time as reclaim would
3945 * start prematurely when there is no boosting and a lower
3948 for (i = highest_zoneidx; i >= 0; i--) {
3949 zone = pgdat->node_zones + i;
3950 if (!managed_zone(zone))
3953 if (zone->watermark_boost)
3961 * Returns true if there is an eligible zone balanced for the request order
3962 * and highest_zoneidx
3964 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
3967 unsigned long mark = -1;
3971 * Check watermarks bottom-up as lower zones are more likely to
3974 for (i = 0; i <= highest_zoneidx; i++) {
3975 zone = pgdat->node_zones + i;
3977 if (!managed_zone(zone))
3980 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
3981 mark = wmark_pages(zone, WMARK_PROMO);
3983 mark = high_wmark_pages(zone);
3984 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
3989 * If a node has no managed zone within highest_zoneidx, it does not
3990 * need balancing by definition. This can happen if a zone-restricted
3991 * allocation tries to wake a remote kswapd.
3999 /* Clear pgdat state for congested, dirty or under writeback. */
4000 static void clear_pgdat_congested(pg_data_t *pgdat)
4002 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4004 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4005 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4006 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4010 * Prepare kswapd for sleeping. This verifies that there are no processes
4011 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4013 * Returns true if kswapd is ready to sleep
4015 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
4016 int highest_zoneidx)
4019 * The throttled processes are normally woken up in balance_pgdat() as
4020 * soon as allow_direct_reclaim() is true. But there is a potential
4021 * race between when kswapd checks the watermarks and a process gets
4022 * throttled. There is also a potential race if processes get
4023 * throttled, kswapd wakes, a large process exits thereby balancing the
4024 * zones, which causes kswapd to exit balance_pgdat() before reaching
4025 * the wake up checks. If kswapd is going to sleep, no process should
4026 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4027 * the wake up is premature, processes will wake kswapd and get
4028 * throttled again. The difference from wake ups in balance_pgdat() is
4029 * that here we are under prepare_to_wait().
4031 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4032 wake_up_all(&pgdat->pfmemalloc_wait);
4034 /* Hopeless node, leave it to direct reclaim */
4035 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4038 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
4039 clear_pgdat_congested(pgdat);
4047 * kswapd shrinks a node of pages that are at or below the highest usable
4048 * zone that is currently unbalanced.
4050 * Returns true if kswapd scanned at least the requested number of pages to
4051 * reclaim or if the lack of progress was due to pages under writeback.
4052 * This is used to determine if the scanning priority needs to be raised.
4054 static bool kswapd_shrink_node(pg_data_t *pgdat,
4055 struct scan_control *sc)
4060 /* Reclaim a number of pages proportional to the number of zones */
4061 sc->nr_to_reclaim = 0;
4062 for (z = 0; z <= sc->reclaim_idx; z++) {
4063 zone = pgdat->node_zones + z;
4064 if (!managed_zone(zone))
4067 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
4071 * Historically care was taken to put equal pressure on all zones but
4072 * now pressure is applied based on node LRU order.
4074 shrink_node(pgdat, sc);
4077 * Fragmentation may mean that the system cannot be rebalanced for
4078 * high-order allocations. If twice the allocation size has been
4079 * reclaimed then recheck watermarks only at order-0 to prevent
4080 * excessive reclaim. Assume that a process requested a high-order
4081 * can direct reclaim/compact.
4083 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
4086 return sc->nr_scanned >= sc->nr_to_reclaim;
4089 /* Page allocator PCP high watermark is lowered if reclaim is active. */
4091 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4096 for (i = 0; i <= highest_zoneidx; i++) {
4097 zone = pgdat->node_zones + i;
4099 if (!managed_zone(zone))
4103 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4105 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4110 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4112 update_reclaim_active(pgdat, highest_zoneidx, true);
4116 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4118 update_reclaim_active(pgdat, highest_zoneidx, false);
4122 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4123 * that are eligible for use by the caller until at least one zone is
4126 * Returns the order kswapd finished reclaiming at.
4128 * kswapd scans the zones in the highmem->normal->dma direction. It skips
4129 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
4130 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
4131 * or lower is eligible for reclaim until at least one usable zone is
4134 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
4137 unsigned long nr_soft_reclaimed;
4138 unsigned long nr_soft_scanned;
4139 unsigned long pflags;
4140 unsigned long nr_boost_reclaim;
4141 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
4144 struct scan_control sc = {
4145 .gfp_mask = GFP_KERNEL,
4150 set_task_reclaim_state(current, &sc.reclaim_state);
4151 psi_memstall_enter(&pflags);
4152 __fs_reclaim_acquire(_THIS_IP_);
4154 count_vm_event(PAGEOUTRUN);
4157 * Account for the reclaim boost. Note that the zone boost is left in
4158 * place so that parallel allocations that are near the watermark will
4159 * stall or direct reclaim until kswapd is finished.
4161 nr_boost_reclaim = 0;
4162 for (i = 0; i <= highest_zoneidx; i++) {
4163 zone = pgdat->node_zones + i;
4164 if (!managed_zone(zone))
4167 nr_boost_reclaim += zone->watermark_boost;
4168 zone_boosts[i] = zone->watermark_boost;
4170 boosted = nr_boost_reclaim;
4173 set_reclaim_active(pgdat, highest_zoneidx);
4174 sc.priority = DEF_PRIORITY;
4176 unsigned long nr_reclaimed = sc.nr_reclaimed;
4177 bool raise_priority = true;
4181 sc.reclaim_idx = highest_zoneidx;
4184 * If the number of buffer_heads exceeds the maximum allowed
4185 * then consider reclaiming from all zones. This has a dual
4186 * purpose -- on 64-bit systems it is expected that
4187 * buffer_heads are stripped during active rotation. On 32-bit
4188 * systems, highmem pages can pin lowmem memory and shrinking
4189 * buffers can relieve lowmem pressure. Reclaim may still not
4190 * go ahead if all eligible zones for the original allocation
4191 * request are balanced to avoid excessive reclaim from kswapd.
4193 if (buffer_heads_over_limit) {
4194 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
4195 zone = pgdat->node_zones + i;
4196 if (!managed_zone(zone))
4205 * If the pgdat is imbalanced then ignore boosting and preserve
4206 * the watermarks for a later time and restart. Note that the
4207 * zone watermarks will be still reset at the end of balancing
4208 * on the grounds that the normal reclaim should be enough to
4209 * re-evaluate if boosting is required when kswapd next wakes.
4211 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
4212 if (!balanced && nr_boost_reclaim) {
4213 nr_boost_reclaim = 0;
4218 * If boosting is not active then only reclaim if there are no
4219 * eligible zones. Note that sc.reclaim_idx is not used as
4220 * buffer_heads_over_limit may have adjusted it.
4222 if (!nr_boost_reclaim && balanced)
4225 /* Limit the priority of boosting to avoid reclaim writeback */
4226 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
4227 raise_priority = false;
4230 * Do not writeback or swap pages for boosted reclaim. The
4231 * intent is to relieve pressure not issue sub-optimal IO
4232 * from reclaim context. If no pages are reclaimed, the
4233 * reclaim will be aborted.
4235 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
4236 sc.may_swap = !nr_boost_reclaim;
4239 * Do some background aging of the anon list, to give
4240 * pages a chance to be referenced before reclaiming. All
4241 * pages are rotated regardless of classzone as this is
4242 * about consistent aging.
4244 age_active_anon(pgdat, &sc);
4247 * If we're getting trouble reclaiming, start doing writepage
4248 * even in laptop mode.
4250 if (sc.priority < DEF_PRIORITY - 2)
4251 sc.may_writepage = 1;
4253 /* Call soft limit reclaim before calling shrink_node. */
4255 nr_soft_scanned = 0;
4256 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
4257 sc.gfp_mask, &nr_soft_scanned);
4258 sc.nr_reclaimed += nr_soft_reclaimed;
4261 * There should be no need to raise the scanning priority if
4262 * enough pages are already being scanned that that high
4263 * watermark would be met at 100% efficiency.
4265 if (kswapd_shrink_node(pgdat, &sc))
4266 raise_priority = false;
4269 * If the low watermark is met there is no need for processes
4270 * to be throttled on pfmemalloc_wait as they should not be
4271 * able to safely make forward progress. Wake them
4273 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
4274 allow_direct_reclaim(pgdat))
4275 wake_up_all(&pgdat->pfmemalloc_wait);
4277 /* Check if kswapd should be suspending */
4278 __fs_reclaim_release(_THIS_IP_);
4279 ret = try_to_freeze();
4280 __fs_reclaim_acquire(_THIS_IP_);
4281 if (ret || kthread_should_stop())
4285 * Raise priority if scanning rate is too low or there was no
4286 * progress in reclaiming pages
4288 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
4289 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
4292 * If reclaim made no progress for a boost, stop reclaim as
4293 * IO cannot be queued and it could be an infinite loop in
4294 * extreme circumstances.
4296 if (nr_boost_reclaim && !nr_reclaimed)
4299 if (raise_priority || !nr_reclaimed)
4301 } while (sc.priority >= 1);
4303 if (!sc.nr_reclaimed)
4304 pgdat->kswapd_failures++;
4307 clear_reclaim_active(pgdat, highest_zoneidx);
4309 /* If reclaim was boosted, account for the reclaim done in this pass */
4311 unsigned long flags;
4313 for (i = 0; i <= highest_zoneidx; i++) {
4314 if (!zone_boosts[i])
4317 /* Increments are under the zone lock */
4318 zone = pgdat->node_zones + i;
4319 spin_lock_irqsave(&zone->lock, flags);
4320 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
4321 spin_unlock_irqrestore(&zone->lock, flags);
4325 * As there is now likely space, wakeup kcompact to defragment
4328 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
4331 snapshot_refaults(NULL, pgdat);
4332 __fs_reclaim_release(_THIS_IP_);
4333 psi_memstall_leave(&pflags);
4334 set_task_reclaim_state(current, NULL);
4337 * Return the order kswapd stopped reclaiming at as
4338 * prepare_kswapd_sleep() takes it into account. If another caller
4339 * entered the allocator slow path while kswapd was awake, order will
4340 * remain at the higher level.
4346 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
4347 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
4348 * not a valid index then either kswapd runs for first time or kswapd couldn't
4349 * sleep after previous reclaim attempt (node is still unbalanced). In that
4350 * case return the zone index of the previous kswapd reclaim cycle.
4352 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
4353 enum zone_type prev_highest_zoneidx)
4355 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
4357 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
4360 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
4361 unsigned int highest_zoneidx)
4366 if (freezing(current) || kthread_should_stop())
4369 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4372 * Try to sleep for a short interval. Note that kcompactd will only be
4373 * woken if it is possible to sleep for a short interval. This is
4374 * deliberate on the assumption that if reclaim cannot keep an
4375 * eligible zone balanced that it's also unlikely that compaction will
4378 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4380 * Compaction records what page blocks it recently failed to
4381 * isolate pages from and skips them in the future scanning.
4382 * When kswapd is going to sleep, it is reasonable to assume
4383 * that pages and compaction may succeed so reset the cache.
4385 reset_isolation_suitable(pgdat);
4388 * We have freed the memory, now we should compact it to make
4389 * allocation of the requested order possible.
4391 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
4393 remaining = schedule_timeout(HZ/10);
4396 * If woken prematurely then reset kswapd_highest_zoneidx and
4397 * order. The values will either be from a wakeup request or
4398 * the previous request that slept prematurely.
4401 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
4402 kswapd_highest_zoneidx(pgdat,
4405 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
4406 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
4409 finish_wait(&pgdat->kswapd_wait, &wait);
4410 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4414 * After a short sleep, check if it was a premature sleep. If not, then
4415 * go fully to sleep until explicitly woken up.
4418 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
4419 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4422 * vmstat counters are not perfectly accurate and the estimated
4423 * value for counters such as NR_FREE_PAGES can deviate from the
4424 * true value by nr_online_cpus * threshold. To avoid the zone
4425 * watermarks being breached while under pressure, we reduce the
4426 * per-cpu vmstat threshold while kswapd is awake and restore
4427 * them before going back to sleep.
4429 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
4431 if (!kthread_should_stop())
4434 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4437 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4439 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4441 finish_wait(&pgdat->kswapd_wait, &wait);
4445 * The background pageout daemon, started as a kernel thread
4446 * from the init process.
4448 * This basically trickles out pages so that we have _some_
4449 * free memory available even if there is no other activity
4450 * that frees anything up. This is needed for things like routing
4451 * etc, where we otherwise might have all activity going on in
4452 * asynchronous contexts that cannot page things out.
4454 * If there are applications that are active memory-allocators
4455 * (most normal use), this basically shouldn't matter.
4457 static int kswapd(void *p)
4459 unsigned int alloc_order, reclaim_order;
4460 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
4461 pg_data_t *pgdat = (pg_data_t *)p;
4462 struct task_struct *tsk = current;
4463 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
4465 if (!cpumask_empty(cpumask))
4466 set_cpus_allowed_ptr(tsk, cpumask);
4469 * Tell the memory management that we're a "memory allocator",
4470 * and that if we need more memory we should get access to it
4471 * regardless (see "__alloc_pages()"). "kswapd" should
4472 * never get caught in the normal page freeing logic.
4474 * (Kswapd normally doesn't need memory anyway, but sometimes
4475 * you need a small amount of memory in order to be able to
4476 * page out something else, and this flag essentially protects
4477 * us from recursively trying to free more memory as we're
4478 * trying to free the first piece of memory in the first place).
4480 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
4483 WRITE_ONCE(pgdat->kswapd_order, 0);
4484 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4485 atomic_set(&pgdat->nr_writeback_throttled, 0);
4489 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
4490 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4494 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
4497 /* Read the new order and highest_zoneidx */
4498 alloc_order = READ_ONCE(pgdat->kswapd_order);
4499 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4501 WRITE_ONCE(pgdat->kswapd_order, 0);
4502 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
4504 ret = try_to_freeze();
4505 if (kthread_should_stop())
4509 * We can speed up thawing tasks if we don't call balance_pgdat
4510 * after returning from the refrigerator
4516 * Reclaim begins at the requested order but if a high-order
4517 * reclaim fails then kswapd falls back to reclaiming for
4518 * order-0. If that happens, kswapd will consider sleeping
4519 * for the order it finished reclaiming at (reclaim_order)
4520 * but kcompactd is woken to compact for the original
4521 * request (alloc_order).
4523 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
4525 reclaim_order = balance_pgdat(pgdat, alloc_order,
4527 if (reclaim_order < alloc_order)
4528 goto kswapd_try_sleep;
4531 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
4537 * A zone is low on free memory or too fragmented for high-order memory. If
4538 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4539 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4540 * has failed or is not needed, still wake up kcompactd if only compaction is
4543 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
4544 enum zone_type highest_zoneidx)
4547 enum zone_type curr_idx;
4549 if (!managed_zone(zone))
4552 if (!cpuset_zone_allowed(zone, gfp_flags))
4555 pgdat = zone->zone_pgdat;
4556 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
4558 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
4559 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
4561 if (READ_ONCE(pgdat->kswapd_order) < order)
4562 WRITE_ONCE(pgdat->kswapd_order, order);
4564 if (!waitqueue_active(&pgdat->kswapd_wait))
4567 /* Hopeless node, leave it to direct reclaim if possible */
4568 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
4569 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
4570 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
4572 * There may be plenty of free memory available, but it's too
4573 * fragmented for high-order allocations. Wake up kcompactd
4574 * and rely on compaction_suitable() to determine if it's
4575 * needed. If it fails, it will defer subsequent attempts to
4576 * ratelimit its work.
4578 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
4579 wakeup_kcompactd(pgdat, order, highest_zoneidx);
4583 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
4585 wake_up_interruptible(&pgdat->kswapd_wait);
4588 #ifdef CONFIG_HIBERNATION
4590 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4593 * Rather than trying to age LRUs the aim is to preserve the overall
4594 * LRU order by reclaiming preferentially
4595 * inactive > active > active referenced > active mapped
4597 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
4599 struct scan_control sc = {
4600 .nr_to_reclaim = nr_to_reclaim,
4601 .gfp_mask = GFP_HIGHUSER_MOVABLE,
4602 .reclaim_idx = MAX_NR_ZONES - 1,
4603 .priority = DEF_PRIORITY,
4607 .hibernation_mode = 1,
4609 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4610 unsigned long nr_reclaimed;
4611 unsigned int noreclaim_flag;
4613 fs_reclaim_acquire(sc.gfp_mask);
4614 noreclaim_flag = memalloc_noreclaim_save();
4615 set_task_reclaim_state(current, &sc.reclaim_state);
4617 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4619 set_task_reclaim_state(current, NULL);
4620 memalloc_noreclaim_restore(noreclaim_flag);
4621 fs_reclaim_release(sc.gfp_mask);
4623 return nr_reclaimed;
4625 #endif /* CONFIG_HIBERNATION */
4628 * This kswapd start function will be called by init and node-hot-add.
4630 void kswapd_run(int nid)
4632 pg_data_t *pgdat = NODE_DATA(nid);
4637 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4638 if (IS_ERR(pgdat->kswapd)) {
4639 /* failure at boot is fatal */
4640 BUG_ON(system_state < SYSTEM_RUNNING);
4641 pr_err("Failed to start kswapd on node %d\n", nid);
4642 pgdat->kswapd = NULL;
4647 * Called by memory hotplug when all memory in a node is offlined. Caller must
4648 * be holding mem_hotplug_begin/done().
4650 void kswapd_stop(int nid)
4652 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4655 kthread_stop(kswapd);
4656 NODE_DATA(nid)->kswapd = NULL;
4660 static int __init kswapd_init(void)
4665 for_each_node_state(nid, N_MEMORY)
4670 module_init(kswapd_init)
4676 * If non-zero call node_reclaim when the number of free pages falls below
4679 int node_reclaim_mode __read_mostly;
4682 * Priority for NODE_RECLAIM. This determines the fraction of pages
4683 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4686 #define NODE_RECLAIM_PRIORITY 4
4689 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4692 int sysctl_min_unmapped_ratio = 1;
4695 * If the number of slab pages in a zone grows beyond this percentage then
4696 * slab reclaim needs to occur.
4698 int sysctl_min_slab_ratio = 5;
4700 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
4702 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4703 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4704 node_page_state(pgdat, NR_ACTIVE_FILE);
4707 * It's possible for there to be more file mapped pages than
4708 * accounted for by the pages on the file LRU lists because
4709 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4711 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4714 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4715 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
4717 unsigned long nr_pagecache_reclaimable;
4718 unsigned long delta = 0;
4721 * If RECLAIM_UNMAP is set, then all file pages are considered
4722 * potentially reclaimable. Otherwise, we have to worry about
4723 * pages like swapcache and node_unmapped_file_pages() provides
4726 if (node_reclaim_mode & RECLAIM_UNMAP)
4727 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
4729 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
4731 /* If we can't clean pages, remove dirty pages from consideration */
4732 if (!(node_reclaim_mode & RECLAIM_WRITE))
4733 delta += node_page_state(pgdat, NR_FILE_DIRTY);
4735 /* Watch for any possible underflows due to delta */
4736 if (unlikely(delta > nr_pagecache_reclaimable))
4737 delta = nr_pagecache_reclaimable;
4739 return nr_pagecache_reclaimable - delta;
4743 * Try to free up some pages from this node through reclaim.
4745 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4747 /* Minimum pages needed in order to stay on node */
4748 const unsigned long nr_pages = 1 << order;
4749 struct task_struct *p = current;
4750 unsigned int noreclaim_flag;
4751 struct scan_control sc = {
4752 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4753 .gfp_mask = current_gfp_context(gfp_mask),
4755 .priority = NODE_RECLAIM_PRIORITY,
4756 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4757 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4759 .reclaim_idx = gfp_zone(gfp_mask),
4761 unsigned long pflags;
4763 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4767 psi_memstall_enter(&pflags);
4768 fs_reclaim_acquire(sc.gfp_mask);
4770 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4772 noreclaim_flag = memalloc_noreclaim_save();
4773 set_task_reclaim_state(p, &sc.reclaim_state);
4775 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
4776 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
4778 * Free memory by calling shrink node with increasing
4779 * priorities until we have enough memory freed.
4782 shrink_node(pgdat, &sc);
4783 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
4786 set_task_reclaim_state(p, NULL);
4787 memalloc_noreclaim_restore(noreclaim_flag);
4788 fs_reclaim_release(sc.gfp_mask);
4789 psi_memstall_leave(&pflags);
4791 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4793 return sc.nr_reclaimed >= nr_pages;
4796 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4801 * Node reclaim reclaims unmapped file backed pages and
4802 * slab pages if we are over the defined limits.
4804 * A small portion of unmapped file backed pages is needed for
4805 * file I/O otherwise pages read by file I/O will be immediately
4806 * thrown out if the node is overallocated. So we do not reclaim
4807 * if less than a specified percentage of the node is used by
4808 * unmapped file backed pages.
4810 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4811 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4812 pgdat->min_slab_pages)
4813 return NODE_RECLAIM_FULL;
4816 * Do not scan if the allocation should not be delayed.
4818 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4819 return NODE_RECLAIM_NOSCAN;
4822 * Only run node reclaim on the local node or on nodes that do not
4823 * have associated processors. This will favor the local processor
4824 * over remote processors and spread off node memory allocations
4825 * as wide as possible.
4827 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4828 return NODE_RECLAIM_NOSCAN;
4830 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4831 return NODE_RECLAIM_NOSCAN;
4833 ret = __node_reclaim(pgdat, gfp_mask, order);
4834 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4837 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4844 * check_move_unevictable_pages - check pages for evictability and move to
4845 * appropriate zone lru list
4846 * @pvec: pagevec with lru pages to check
4848 * Checks pages for evictability, if an evictable page is in the unevictable
4849 * lru list, moves it to the appropriate evictable lru list. This function
4850 * should be only used for lru pages.
4852 void check_move_unevictable_pages(struct pagevec *pvec)
4854 struct lruvec *lruvec = NULL;
4859 for (i = 0; i < pvec->nr; i++) {
4860 struct page *page = pvec->pages[i];
4861 struct folio *folio = page_folio(page);
4864 if (PageTransTail(page))
4867 nr_pages = thp_nr_pages(page);
4868 pgscanned += nr_pages;
4870 /* block memcg migration during page moving between lru */
4871 if (!TestClearPageLRU(page))
4874 lruvec = folio_lruvec_relock_irq(folio, lruvec);
4875 if (page_evictable(page) && PageUnevictable(page)) {
4876 del_page_from_lru_list(page, lruvec);
4877 ClearPageUnevictable(page);
4878 add_page_to_lru_list(page, lruvec);
4879 pgrescued += nr_pages;
4885 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4886 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4887 unlock_page_lruvec_irq(lruvec);
4888 } else if (pgscanned) {
4889 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4892 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);