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 try_to_release_page(),
30 buffer_heads_over_limit */
31 #include <linux/mm_inline.h>
32 #include <linux/backing-dev.h>
33 #include <linux/rmap.h>
34 #include <linux/topology.h>
35 #include <linux/cpu.h>
36 #include <linux/cpuset.h>
37 #include <linux/compaction.h>
38 #include <linux/notifier.h>
39 #include <linux/rwsem.h>
40 #include <linux/delay.h>
41 #include <linux/kthread.h>
42 #include <linux/freezer.h>
43 #include <linux/memcontrol.h>
44 #include <linux/migrate.h>
45 #include <linux/delayacct.h>
46 #include <linux/sysctl.h>
47 #include <linux/oom.h>
48 #include <linux/pagevec.h>
49 #include <linux/prefetch.h>
50 #include <linux/printk.h>
51 #include <linux/dax.h>
52 #include <linux/psi.h>
54 #include <asm/tlbflush.h>
55 #include <asm/div64.h>
57 #include <linux/swapops.h>
58 #include <linux/balloon_compaction.h>
59 #include <linux/sched/sysctl.h>
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/vmscan.h>
68 /* How many pages shrink_list() should reclaim */
69 unsigned long nr_to_reclaim
;
72 * Nodemask of nodes allowed by the caller. If NULL, all nodes
78 * The memory cgroup that hit its limit and as a result is the
79 * primary target of this reclaim invocation.
81 struct mem_cgroup
*target_mem_cgroup
;
84 * Scan pressure balancing between anon and file LRUs
86 unsigned long anon_cost
;
87 unsigned long file_cost
;
89 /* Can active pages be deactivated as part of reclaim? */
90 #define DEACTIVATE_ANON 1
91 #define DEACTIVATE_FILE 2
92 unsigned int may_deactivate
:2;
93 unsigned int force_deactivate
:1;
94 unsigned int skipped_deactivate
:1;
96 /* Writepage batching in laptop mode; RECLAIM_WRITE */
97 unsigned int may_writepage
:1;
99 /* Can mapped pages be reclaimed? */
100 unsigned int may_unmap
:1;
102 /* Can pages be swapped as part of reclaim? */
103 unsigned int may_swap
:1;
106 * Cgroup memory below memory.low is protected as long as we
107 * don't threaten to OOM. If any cgroup is reclaimed at
108 * reduced force or passed over entirely due to its memory.low
109 * setting (memcg_low_skipped), and nothing is reclaimed as a
110 * result, then go back for one more cycle that reclaims the protected
111 * memory (memcg_low_reclaim) to avert OOM.
113 unsigned int memcg_low_reclaim
:1;
114 unsigned int memcg_low_skipped
:1;
116 unsigned int hibernation_mode
:1;
118 /* One of the zones is ready for compaction */
119 unsigned int compaction_ready
:1;
121 /* There is easily reclaimable cold cache in the current node */
122 unsigned int cache_trim_mode
:1;
124 /* The file pages on the current node are dangerously low */
125 unsigned int file_is_tiny
:1;
127 /* Always discard instead of demoting to lower tier memory */
128 unsigned int no_demotion
:1;
130 /* Allocation order */
133 /* Scan (total_size >> priority) pages at once */
136 /* The highest zone to isolate pages for reclaim from */
139 /* This context's GFP mask */
142 /* Incremented by the number of inactive pages that were scanned */
143 unsigned long nr_scanned
;
145 /* Number of pages freed so far during a call to shrink_zones() */
146 unsigned long nr_reclaimed
;
150 unsigned int unqueued_dirty
;
151 unsigned int congested
;
152 unsigned int writeback
;
153 unsigned int immediate
;
154 unsigned int file_taken
;
158 /* for recording the reclaimed slab by now */
159 struct reclaim_state reclaim_state
;
162 #ifdef ARCH_HAS_PREFETCHW
163 #define prefetchw_prev_lru_page(_page, _base, _field) \
165 if ((_page)->lru.prev != _base) { \
168 prev = lru_to_page(&(_page->lru)); \
169 prefetchw(&prev->_field); \
173 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
177 * From 0 .. 200. Higher means more swappy.
179 int vm_swappiness
= 60;
181 static void set_task_reclaim_state(struct task_struct
*task
,
182 struct reclaim_state
*rs
)
184 /* Check for an overwrite */
185 WARN_ON_ONCE(rs
&& task
->reclaim_state
);
187 /* Check for the nulling of an already-nulled member */
188 WARN_ON_ONCE(!rs
&& !task
->reclaim_state
);
190 task
->reclaim_state
= rs
;
193 static LIST_HEAD(shrinker_list
);
194 static DECLARE_RWSEM(shrinker_rwsem
);
197 static int shrinker_nr_max
;
199 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
200 static inline int shrinker_map_size(int nr_items
)
202 return (DIV_ROUND_UP(nr_items
, BITS_PER_LONG
) * sizeof(unsigned long));
205 static inline int shrinker_defer_size(int nr_items
)
207 return (round_up(nr_items
, BITS_PER_LONG
) * sizeof(atomic_long_t
));
210 static struct shrinker_info
*shrinker_info_protected(struct mem_cgroup
*memcg
,
213 return rcu_dereference_protected(memcg
->nodeinfo
[nid
]->shrinker_info
,
214 lockdep_is_held(&shrinker_rwsem
));
217 static int expand_one_shrinker_info(struct mem_cgroup
*memcg
,
218 int map_size
, int defer_size
,
219 int old_map_size
, int old_defer_size
)
221 struct shrinker_info
*new, *old
;
222 struct mem_cgroup_per_node
*pn
;
224 int size
= map_size
+ defer_size
;
227 pn
= memcg
->nodeinfo
[nid
];
228 old
= shrinker_info_protected(memcg
, nid
);
229 /* Not yet online memcg */
233 new = kvmalloc_node(sizeof(*new) + size
, GFP_KERNEL
, nid
);
237 new->nr_deferred
= (atomic_long_t
*)(new + 1);
238 new->map
= (void *)new->nr_deferred
+ defer_size
;
240 /* map: set all old bits, clear all new bits */
241 memset(new->map
, (int)0xff, old_map_size
);
242 memset((void *)new->map
+ old_map_size
, 0, map_size
- old_map_size
);
243 /* nr_deferred: copy old values, clear all new values */
244 memcpy(new->nr_deferred
, old
->nr_deferred
, old_defer_size
);
245 memset((void *)new->nr_deferred
+ old_defer_size
, 0,
246 defer_size
- old_defer_size
);
248 rcu_assign_pointer(pn
->shrinker_info
, new);
249 kvfree_rcu(old
, rcu
);
255 void free_shrinker_info(struct mem_cgroup
*memcg
)
257 struct mem_cgroup_per_node
*pn
;
258 struct shrinker_info
*info
;
262 pn
= memcg
->nodeinfo
[nid
];
263 info
= rcu_dereference_protected(pn
->shrinker_info
, true);
265 rcu_assign_pointer(pn
->shrinker_info
, NULL
);
269 int alloc_shrinker_info(struct mem_cgroup
*memcg
)
271 struct shrinker_info
*info
;
272 int nid
, size
, ret
= 0;
273 int map_size
, defer_size
= 0;
275 down_write(&shrinker_rwsem
);
276 map_size
= shrinker_map_size(shrinker_nr_max
);
277 defer_size
= shrinker_defer_size(shrinker_nr_max
);
278 size
= map_size
+ defer_size
;
280 info
= kvzalloc_node(sizeof(*info
) + size
, GFP_KERNEL
, nid
);
282 free_shrinker_info(memcg
);
286 info
->nr_deferred
= (atomic_long_t
*)(info
+ 1);
287 info
->map
= (void *)info
->nr_deferred
+ defer_size
;
288 rcu_assign_pointer(memcg
->nodeinfo
[nid
]->shrinker_info
, info
);
290 up_write(&shrinker_rwsem
);
295 static inline bool need_expand(int nr_max
)
297 return round_up(nr_max
, BITS_PER_LONG
) >
298 round_up(shrinker_nr_max
, BITS_PER_LONG
);
301 static int expand_shrinker_info(int new_id
)
304 int new_nr_max
= new_id
+ 1;
305 int map_size
, defer_size
= 0;
306 int old_map_size
, old_defer_size
= 0;
307 struct mem_cgroup
*memcg
;
309 if (!need_expand(new_nr_max
))
312 if (!root_mem_cgroup
)
315 lockdep_assert_held(&shrinker_rwsem
);
317 map_size
= shrinker_map_size(new_nr_max
);
318 defer_size
= shrinker_defer_size(new_nr_max
);
319 old_map_size
= shrinker_map_size(shrinker_nr_max
);
320 old_defer_size
= shrinker_defer_size(shrinker_nr_max
);
322 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
324 ret
= expand_one_shrinker_info(memcg
, map_size
, defer_size
,
325 old_map_size
, old_defer_size
);
327 mem_cgroup_iter_break(NULL
, memcg
);
330 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
333 shrinker_nr_max
= new_nr_max
;
338 void set_shrinker_bit(struct mem_cgroup
*memcg
, int nid
, int shrinker_id
)
340 if (shrinker_id
>= 0 && memcg
&& !mem_cgroup_is_root(memcg
)) {
341 struct shrinker_info
*info
;
344 info
= rcu_dereference(memcg
->nodeinfo
[nid
]->shrinker_info
);
345 /* Pairs with smp mb in shrink_slab() */
346 smp_mb__before_atomic();
347 set_bit(shrinker_id
, info
->map
);
352 static DEFINE_IDR(shrinker_idr
);
354 static int prealloc_memcg_shrinker(struct shrinker
*shrinker
)
356 int id
, ret
= -ENOMEM
;
358 if (mem_cgroup_disabled())
361 down_write(&shrinker_rwsem
);
362 /* This may call shrinker, so it must use down_read_trylock() */
363 id
= idr_alloc(&shrinker_idr
, shrinker
, 0, 0, GFP_KERNEL
);
367 if (id
>= shrinker_nr_max
) {
368 if (expand_shrinker_info(id
)) {
369 idr_remove(&shrinker_idr
, id
);
376 up_write(&shrinker_rwsem
);
380 static void unregister_memcg_shrinker(struct shrinker
*shrinker
)
382 int id
= shrinker
->id
;
386 lockdep_assert_held(&shrinker_rwsem
);
388 idr_remove(&shrinker_idr
, id
);
391 static long xchg_nr_deferred_memcg(int nid
, struct shrinker
*shrinker
,
392 struct mem_cgroup
*memcg
)
394 struct shrinker_info
*info
;
396 info
= shrinker_info_protected(memcg
, nid
);
397 return atomic_long_xchg(&info
->nr_deferred
[shrinker
->id
], 0);
400 static long add_nr_deferred_memcg(long nr
, int nid
, struct shrinker
*shrinker
,
401 struct mem_cgroup
*memcg
)
403 struct shrinker_info
*info
;
405 info
= shrinker_info_protected(memcg
, nid
);
406 return atomic_long_add_return(nr
, &info
->nr_deferred
[shrinker
->id
]);
409 void reparent_shrinker_deferred(struct mem_cgroup
*memcg
)
413 struct mem_cgroup
*parent
;
414 struct shrinker_info
*child_info
, *parent_info
;
416 parent
= parent_mem_cgroup(memcg
);
418 parent
= root_mem_cgroup
;
420 /* Prevent from concurrent shrinker_info expand */
421 down_read(&shrinker_rwsem
);
423 child_info
= shrinker_info_protected(memcg
, nid
);
424 parent_info
= shrinker_info_protected(parent
, nid
);
425 for (i
= 0; i
< shrinker_nr_max
; i
++) {
426 nr
= atomic_long_read(&child_info
->nr_deferred
[i
]);
427 atomic_long_add(nr
, &parent_info
->nr_deferred
[i
]);
430 up_read(&shrinker_rwsem
);
433 static bool cgroup_reclaim(struct scan_control
*sc
)
435 return sc
->target_mem_cgroup
;
439 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
440 * @sc: scan_control in question
442 * The normal page dirty throttling mechanism in balance_dirty_pages() is
443 * completely broken with the legacy memcg and direct stalling in
444 * shrink_page_list() is used for throttling instead, which lacks all the
445 * niceties such as fairness, adaptive pausing, bandwidth proportional
446 * allocation and configurability.
448 * This function tests whether the vmscan currently in progress can assume
449 * that the normal dirty throttling mechanism is operational.
451 static bool writeback_throttling_sane(struct scan_control
*sc
)
453 if (!cgroup_reclaim(sc
))
455 #ifdef CONFIG_CGROUP_WRITEBACK
456 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
462 static int prealloc_memcg_shrinker(struct shrinker
*shrinker
)
467 static void unregister_memcg_shrinker(struct shrinker
*shrinker
)
471 static long xchg_nr_deferred_memcg(int nid
, struct shrinker
*shrinker
,
472 struct mem_cgroup
*memcg
)
477 static long add_nr_deferred_memcg(long nr
, int nid
, struct shrinker
*shrinker
,
478 struct mem_cgroup
*memcg
)
483 static bool cgroup_reclaim(struct scan_control
*sc
)
488 static bool writeback_throttling_sane(struct scan_control
*sc
)
494 static long xchg_nr_deferred(struct shrinker
*shrinker
,
495 struct shrink_control
*sc
)
499 if (!(shrinker
->flags
& SHRINKER_NUMA_AWARE
))
503 (shrinker
->flags
& SHRINKER_MEMCG_AWARE
))
504 return xchg_nr_deferred_memcg(nid
, shrinker
,
507 return atomic_long_xchg(&shrinker
->nr_deferred
[nid
], 0);
511 static long add_nr_deferred(long nr
, struct shrinker
*shrinker
,
512 struct shrink_control
*sc
)
516 if (!(shrinker
->flags
& SHRINKER_NUMA_AWARE
))
520 (shrinker
->flags
& SHRINKER_MEMCG_AWARE
))
521 return add_nr_deferred_memcg(nr
, nid
, shrinker
,
524 return atomic_long_add_return(nr
, &shrinker
->nr_deferred
[nid
]);
527 static bool can_demote(int nid
, struct scan_control
*sc
)
529 if (!numa_demotion_enabled
)
534 /* It is pointless to do demotion in memcg reclaim */
535 if (cgroup_reclaim(sc
))
538 if (next_demotion_node(nid
) == NUMA_NO_NODE
)
544 static inline bool can_reclaim_anon_pages(struct mem_cgroup
*memcg
,
546 struct scan_control
*sc
)
550 * For non-memcg reclaim, is there
551 * space in any swap device?
553 if (get_nr_swap_pages() > 0)
556 /* Is the memcg below its swap limit? */
557 if (mem_cgroup_get_nr_swap_pages(memcg
) > 0)
562 * The page can not be swapped.
564 * Can it be reclaimed from this node via demotion?
566 return can_demote(nid
, sc
);
570 * This misses isolated pages which are not accounted for to save counters.
571 * As the data only determines if reclaim or compaction continues, it is
572 * not expected that isolated pages will be a dominating factor.
574 unsigned long zone_reclaimable_pages(struct zone
*zone
)
578 nr
= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_FILE
) +
579 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_FILE
);
580 if (can_reclaim_anon_pages(NULL
, zone_to_nid(zone
), NULL
))
581 nr
+= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_ANON
) +
582 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_ANON
);
588 * lruvec_lru_size - Returns the number of pages on the given LRU list.
589 * @lruvec: lru vector
591 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
593 static unsigned long lruvec_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
596 unsigned long size
= 0;
599 for (zid
= 0; zid
<= zone_idx
; zid
++) {
600 struct zone
*zone
= &lruvec_pgdat(lruvec
)->node_zones
[zid
];
602 if (!managed_zone(zone
))
605 if (!mem_cgroup_disabled())
606 size
+= mem_cgroup_get_zone_lru_size(lruvec
, lru
, zid
);
608 size
+= zone_page_state(zone
, NR_ZONE_LRU_BASE
+ lru
);
614 * Add a shrinker callback to be called from the vm.
616 int prealloc_shrinker(struct shrinker
*shrinker
)
621 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
) {
622 err
= prealloc_memcg_shrinker(shrinker
);
626 shrinker
->flags
&= ~SHRINKER_MEMCG_AWARE
;
629 size
= sizeof(*shrinker
->nr_deferred
);
630 if (shrinker
->flags
& SHRINKER_NUMA_AWARE
)
633 shrinker
->nr_deferred
= kzalloc(size
, GFP_KERNEL
);
634 if (!shrinker
->nr_deferred
)
640 void free_prealloced_shrinker(struct shrinker
*shrinker
)
642 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
) {
643 down_write(&shrinker_rwsem
);
644 unregister_memcg_shrinker(shrinker
);
645 up_write(&shrinker_rwsem
);
649 kfree(shrinker
->nr_deferred
);
650 shrinker
->nr_deferred
= NULL
;
653 void register_shrinker_prepared(struct shrinker
*shrinker
)
655 down_write(&shrinker_rwsem
);
656 list_add_tail(&shrinker
->list
, &shrinker_list
);
657 shrinker
->flags
|= SHRINKER_REGISTERED
;
658 up_write(&shrinker_rwsem
);
661 int register_shrinker(struct shrinker
*shrinker
)
663 int err
= prealloc_shrinker(shrinker
);
667 register_shrinker_prepared(shrinker
);
670 EXPORT_SYMBOL(register_shrinker
);
675 void unregister_shrinker(struct shrinker
*shrinker
)
677 if (!(shrinker
->flags
& SHRINKER_REGISTERED
))
680 down_write(&shrinker_rwsem
);
681 list_del(&shrinker
->list
);
682 shrinker
->flags
&= ~SHRINKER_REGISTERED
;
683 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
)
684 unregister_memcg_shrinker(shrinker
);
685 up_write(&shrinker_rwsem
);
687 kfree(shrinker
->nr_deferred
);
688 shrinker
->nr_deferred
= NULL
;
690 EXPORT_SYMBOL(unregister_shrinker
);
693 * synchronize_shrinkers - Wait for all running shrinkers to complete.
695 * This is equivalent to calling unregister_shrink() and register_shrinker(),
696 * but atomically and with less overhead. This is useful to guarantee that all
697 * shrinker invocations have seen an update, before freeing memory, similar to
700 void synchronize_shrinkers(void)
702 down_write(&shrinker_rwsem
);
703 up_write(&shrinker_rwsem
);
705 EXPORT_SYMBOL(synchronize_shrinkers
);
707 #define SHRINK_BATCH 128
709 static unsigned long do_shrink_slab(struct shrink_control
*shrinkctl
,
710 struct shrinker
*shrinker
, int priority
)
712 unsigned long freed
= 0;
713 unsigned long long delta
;
718 long batch_size
= shrinker
->batch
? shrinker
->batch
720 long scanned
= 0, next_deferred
;
722 freeable
= shrinker
->count_objects(shrinker
, shrinkctl
);
723 if (freeable
== 0 || freeable
== SHRINK_EMPTY
)
727 * copy the current shrinker scan count into a local variable
728 * and zero it so that other concurrent shrinker invocations
729 * don't also do this scanning work.
731 nr
= xchg_nr_deferred(shrinker
, shrinkctl
);
733 if (shrinker
->seeks
) {
734 delta
= freeable
>> priority
;
736 do_div(delta
, shrinker
->seeks
);
739 * These objects don't require any IO to create. Trim
740 * them aggressively under memory pressure to keep
741 * them from causing refetches in the IO caches.
743 delta
= freeable
/ 2;
746 total_scan
= nr
>> priority
;
748 total_scan
= min(total_scan
, (2 * freeable
));
750 trace_mm_shrink_slab_start(shrinker
, shrinkctl
, nr
,
751 freeable
, delta
, total_scan
, priority
);
754 * Normally, we should not scan less than batch_size objects in one
755 * pass to avoid too frequent shrinker calls, but if the slab has less
756 * than batch_size objects in total and we are really tight on memory,
757 * we will try to reclaim all available objects, otherwise we can end
758 * up failing allocations although there are plenty of reclaimable
759 * objects spread over several slabs with usage less than the
762 * We detect the "tight on memory" situations by looking at the total
763 * number of objects we want to scan (total_scan). If it is greater
764 * than the total number of objects on slab (freeable), we must be
765 * scanning at high prio and therefore should try to reclaim as much as
768 while (total_scan
>= batch_size
||
769 total_scan
>= freeable
) {
771 unsigned long nr_to_scan
= min(batch_size
, total_scan
);
773 shrinkctl
->nr_to_scan
= nr_to_scan
;
774 shrinkctl
->nr_scanned
= nr_to_scan
;
775 ret
= shrinker
->scan_objects(shrinker
, shrinkctl
);
776 if (ret
== SHRINK_STOP
)
780 count_vm_events(SLABS_SCANNED
, shrinkctl
->nr_scanned
);
781 total_scan
-= shrinkctl
->nr_scanned
;
782 scanned
+= shrinkctl
->nr_scanned
;
788 * The deferred work is increased by any new work (delta) that wasn't
789 * done, decreased by old deferred work that was done now.
791 * And it is capped to two times of the freeable items.
793 next_deferred
= max_t(long, (nr
+ delta
- scanned
), 0);
794 next_deferred
= min(next_deferred
, (2 * freeable
));
797 * move the unused scan count back into the shrinker in a
798 * manner that handles concurrent updates.
800 new_nr
= add_nr_deferred(next_deferred
, shrinker
, shrinkctl
);
802 trace_mm_shrink_slab_end(shrinker
, shrinkctl
->nid
, freed
, nr
, new_nr
, total_scan
);
807 static unsigned long shrink_slab_memcg(gfp_t gfp_mask
, int nid
,
808 struct mem_cgroup
*memcg
, int priority
)
810 struct shrinker_info
*info
;
811 unsigned long ret
, freed
= 0;
814 if (!mem_cgroup_online(memcg
))
817 if (!down_read_trylock(&shrinker_rwsem
))
820 info
= shrinker_info_protected(memcg
, nid
);
824 for_each_set_bit(i
, info
->map
, shrinker_nr_max
) {
825 struct shrink_control sc
= {
826 .gfp_mask
= gfp_mask
,
830 struct shrinker
*shrinker
;
832 shrinker
= idr_find(&shrinker_idr
, i
);
833 if (unlikely(!shrinker
|| !(shrinker
->flags
& SHRINKER_REGISTERED
))) {
835 clear_bit(i
, info
->map
);
839 /* Call non-slab shrinkers even though kmem is disabled */
840 if (!memcg_kmem_enabled() &&
841 !(shrinker
->flags
& SHRINKER_NONSLAB
))
844 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
845 if (ret
== SHRINK_EMPTY
) {
846 clear_bit(i
, info
->map
);
848 * After the shrinker reported that it had no objects to
849 * free, but before we cleared the corresponding bit in
850 * the memcg shrinker map, a new object might have been
851 * added. To make sure, we have the bit set in this
852 * case, we invoke the shrinker one more time and reset
853 * the bit if it reports that it is not empty anymore.
854 * The memory barrier here pairs with the barrier in
855 * set_shrinker_bit():
857 * list_lru_add() shrink_slab_memcg()
858 * list_add_tail() clear_bit()
860 * set_bit() do_shrink_slab()
862 smp_mb__after_atomic();
863 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
864 if (ret
== SHRINK_EMPTY
)
867 set_shrinker_bit(memcg
, nid
, i
);
871 if (rwsem_is_contended(&shrinker_rwsem
)) {
877 up_read(&shrinker_rwsem
);
880 #else /* CONFIG_MEMCG */
881 static unsigned long shrink_slab_memcg(gfp_t gfp_mask
, int nid
,
882 struct mem_cgroup
*memcg
, int priority
)
886 #endif /* CONFIG_MEMCG */
889 * shrink_slab - shrink slab caches
890 * @gfp_mask: allocation context
891 * @nid: node whose slab caches to target
892 * @memcg: memory cgroup whose slab caches to target
893 * @priority: the reclaim priority
895 * Call the shrink functions to age shrinkable caches.
897 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
898 * unaware shrinkers will receive a node id of 0 instead.
900 * @memcg specifies the memory cgroup to target. Unaware shrinkers
901 * are called only if it is the root cgroup.
903 * @priority is sc->priority, we take the number of objects and >> by priority
904 * in order to get the scan target.
906 * Returns the number of reclaimed slab objects.
908 static unsigned long shrink_slab(gfp_t gfp_mask
, int nid
,
909 struct mem_cgroup
*memcg
,
912 unsigned long ret
, freed
= 0;
913 struct shrinker
*shrinker
;
916 * The root memcg might be allocated even though memcg is disabled
917 * via "cgroup_disable=memory" boot parameter. This could make
918 * mem_cgroup_is_root() return false, then just run memcg slab
919 * shrink, but skip global shrink. This may result in premature
922 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg
))
923 return shrink_slab_memcg(gfp_mask
, nid
, memcg
, priority
);
925 if (!down_read_trylock(&shrinker_rwsem
))
928 list_for_each_entry(shrinker
, &shrinker_list
, list
) {
929 struct shrink_control sc
= {
930 .gfp_mask
= gfp_mask
,
935 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
936 if (ret
== SHRINK_EMPTY
)
940 * Bail out if someone want to register a new shrinker to
941 * prevent the registration from being stalled for long periods
942 * by parallel ongoing shrinking.
944 if (rwsem_is_contended(&shrinker_rwsem
)) {
950 up_read(&shrinker_rwsem
);
956 static void drop_slab_node(int nid
)
962 struct mem_cgroup
*memcg
= NULL
;
964 if (fatal_signal_pending(current
))
968 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
970 freed
+= shrink_slab(GFP_KERNEL
, nid
, memcg
, 0);
971 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
972 } while ((freed
>> shift
++) > 1);
979 for_each_online_node(nid
)
983 static inline int is_page_cache_freeable(struct folio
*folio
)
986 * A freeable page cache page is referenced only by the caller
987 * that isolated the page, the page cache and optional buffer
988 * heads at page->private.
990 return folio_ref_count(folio
) - folio_test_private(folio
) ==
991 1 + folio_nr_pages(folio
);
995 * We detected a synchronous write error writing a folio out. Probably
996 * -ENOSPC. We need to propagate that into the address_space for a subsequent
997 * fsync(), msync() or close().
999 * The tricky part is that after writepage we cannot touch the mapping: nothing
1000 * prevents it from being freed up. But we have a ref on the folio and once
1001 * that folio is locked, the mapping is pinned.
1003 * We're allowed to run sleeping folio_lock() here because we know the caller has
1006 static void handle_write_error(struct address_space
*mapping
,
1007 struct folio
*folio
, int error
)
1010 if (folio_mapping(folio
) == mapping
)
1011 mapping_set_error(mapping
, error
);
1012 folio_unlock(folio
);
1015 static bool skip_throttle_noprogress(pg_data_t
*pgdat
)
1017 int reclaimable
= 0, write_pending
= 0;
1021 * If kswapd is disabled, reschedule if necessary but do not
1022 * throttle as the system is likely near OOM.
1024 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
1028 * If there are a lot of dirty/writeback pages then do not
1029 * throttle as throttling will occur when the pages cycle
1030 * towards the end of the LRU if still under writeback.
1032 for (i
= 0; i
< MAX_NR_ZONES
; i
++) {
1033 struct zone
*zone
= pgdat
->node_zones
+ i
;
1035 if (!managed_zone(zone
))
1038 reclaimable
+= zone_reclaimable_pages(zone
);
1039 write_pending
+= zone_page_state_snapshot(zone
,
1040 NR_ZONE_WRITE_PENDING
);
1042 if (2 * write_pending
<= reclaimable
)
1048 void reclaim_throttle(pg_data_t
*pgdat
, enum vmscan_throttle_state reason
)
1050 wait_queue_head_t
*wqh
= &pgdat
->reclaim_wait
[reason
];
1055 * Do not throttle IO workers, kthreads other than kswapd or
1056 * workqueues. They may be required for reclaim to make
1057 * forward progress (e.g. journalling workqueues or kthreads).
1059 if (!current_is_kswapd() &&
1060 current
->flags
& (PF_IO_WORKER
|PF_KTHREAD
)) {
1066 * These figures are pulled out of thin air.
1067 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1068 * parallel reclaimers which is a short-lived event so the timeout is
1069 * short. Failing to make progress or waiting on writeback are
1070 * potentially long-lived events so use a longer timeout. This is shaky
1071 * logic as a failure to make progress could be due to anything from
1072 * writeback to a slow device to excessive references pages at the tail
1073 * of the inactive LRU.
1076 case VMSCAN_THROTTLE_WRITEBACK
:
1079 if (atomic_inc_return(&pgdat
->nr_writeback_throttled
) == 1) {
1080 WRITE_ONCE(pgdat
->nr_reclaim_start
,
1081 node_page_state(pgdat
, NR_THROTTLED_WRITTEN
));
1085 case VMSCAN_THROTTLE_CONGESTED
:
1087 case VMSCAN_THROTTLE_NOPROGRESS
:
1088 if (skip_throttle_noprogress(pgdat
)) {
1096 case VMSCAN_THROTTLE_ISOLATED
:
1105 prepare_to_wait(wqh
, &wait
, TASK_UNINTERRUPTIBLE
);
1106 ret
= schedule_timeout(timeout
);
1107 finish_wait(wqh
, &wait
);
1109 if (reason
== VMSCAN_THROTTLE_WRITEBACK
)
1110 atomic_dec(&pgdat
->nr_writeback_throttled
);
1112 trace_mm_vmscan_throttled(pgdat
->node_id
, jiffies_to_usecs(timeout
),
1113 jiffies_to_usecs(timeout
- ret
),
1118 * Account for pages written if tasks are throttled waiting on dirty
1119 * pages to clean. If enough pages have been cleaned since throttling
1120 * started then wakeup the throttled tasks.
1122 void __acct_reclaim_writeback(pg_data_t
*pgdat
, struct folio
*folio
,
1125 unsigned long nr_written
;
1127 node_stat_add_folio(folio
, NR_THROTTLED_WRITTEN
);
1130 * This is an inaccurate read as the per-cpu deltas may not
1131 * be synchronised. However, given that the system is
1132 * writeback throttled, it is not worth taking the penalty
1133 * of getting an accurate count. At worst, the throttle
1134 * timeout guarantees forward progress.
1136 nr_written
= node_page_state(pgdat
, NR_THROTTLED_WRITTEN
) -
1137 READ_ONCE(pgdat
->nr_reclaim_start
);
1139 if (nr_written
> SWAP_CLUSTER_MAX
* nr_throttled
)
1140 wake_up(&pgdat
->reclaim_wait
[VMSCAN_THROTTLE_WRITEBACK
]);
1143 /* possible outcome of pageout() */
1145 /* failed to write page out, page is locked */
1147 /* move page to the active list, page is locked */
1149 /* page has been sent to the disk successfully, page is unlocked */
1151 /* page is clean and locked */
1156 * pageout is called by shrink_page_list() for each dirty page.
1157 * Calls ->writepage().
1159 static pageout_t
pageout(struct folio
*folio
, struct address_space
*mapping
)
1162 * If the folio is dirty, only perform writeback if that write
1163 * will be non-blocking. To prevent this allocation from being
1164 * stalled by pagecache activity. But note that there may be
1165 * stalls if we need to run get_block(). We could test
1166 * PagePrivate for that.
1168 * If this process is currently in __generic_file_write_iter() against
1169 * this folio's queue, we can perform writeback even if that
1172 * If the folio is swapcache, write it back even if that would
1173 * block, for some throttling. This happens by accident, because
1174 * swap_backing_dev_info is bust: it doesn't reflect the
1175 * congestion state of the swapdevs. Easy to fix, if needed.
1177 if (!is_page_cache_freeable(folio
))
1181 * Some data journaling orphaned folios can have
1182 * folio->mapping == NULL while being dirty with clean buffers.
1184 if (folio_test_private(folio
)) {
1185 if (try_to_free_buffers(&folio
->page
)) {
1186 folio_clear_dirty(folio
);
1187 pr_info("%s: orphaned folio\n", __func__
);
1193 if (mapping
->a_ops
->writepage
== NULL
)
1194 return PAGE_ACTIVATE
;
1196 if (folio_clear_dirty_for_io(folio
)) {
1198 struct writeback_control wbc
= {
1199 .sync_mode
= WB_SYNC_NONE
,
1200 .nr_to_write
= SWAP_CLUSTER_MAX
,
1202 .range_end
= LLONG_MAX
,
1206 folio_set_reclaim(folio
);
1207 res
= mapping
->a_ops
->writepage(&folio
->page
, &wbc
);
1209 handle_write_error(mapping
, folio
, res
);
1210 if (res
== AOP_WRITEPAGE_ACTIVATE
) {
1211 folio_clear_reclaim(folio
);
1212 return PAGE_ACTIVATE
;
1215 if (!folio_test_writeback(folio
)) {
1216 /* synchronous write or broken a_ops? */
1217 folio_clear_reclaim(folio
);
1219 trace_mm_vmscan_write_folio(folio
);
1220 node_stat_add_folio(folio
, NR_VMSCAN_WRITE
);
1221 return PAGE_SUCCESS
;
1228 * Same as remove_mapping, but if the page is removed from the mapping, it
1229 * gets returned with a refcount of 0.
1231 static int __remove_mapping(struct address_space
*mapping
, struct folio
*folio
,
1232 bool reclaimed
, struct mem_cgroup
*target_memcg
)
1235 void *shadow
= NULL
;
1237 BUG_ON(!folio_test_locked(folio
));
1238 BUG_ON(mapping
!= folio_mapping(folio
));
1240 if (!folio_test_swapcache(folio
))
1241 spin_lock(&mapping
->host
->i_lock
);
1242 xa_lock_irq(&mapping
->i_pages
);
1244 * The non racy check for a busy page.
1246 * Must be careful with the order of the tests. When someone has
1247 * a ref to the page, it may be possible that they dirty it then
1248 * drop the reference. So if PageDirty is tested before page_count
1249 * here, then the following race may occur:
1251 * get_user_pages(&page);
1252 * [user mapping goes away]
1254 * !PageDirty(page) [good]
1255 * SetPageDirty(page);
1257 * !page_count(page) [good, discard it]
1259 * [oops, our write_to data is lost]
1261 * Reversing the order of the tests ensures such a situation cannot
1262 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1263 * load is not satisfied before that of page->_refcount.
1265 * Note that if SetPageDirty is always performed via set_page_dirty,
1266 * and thus under the i_pages lock, then this ordering is not required.
1268 refcount
= 1 + folio_nr_pages(folio
);
1269 if (!folio_ref_freeze(folio
, refcount
))
1271 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1272 if (unlikely(folio_test_dirty(folio
))) {
1273 folio_ref_unfreeze(folio
, refcount
);
1277 if (folio_test_swapcache(folio
)) {
1278 swp_entry_t swap
= folio_swap_entry(folio
);
1279 mem_cgroup_swapout(folio
, swap
);
1280 if (reclaimed
&& !mapping_exiting(mapping
))
1281 shadow
= workingset_eviction(folio
, target_memcg
);
1282 __delete_from_swap_cache(&folio
->page
, swap
, shadow
);
1283 xa_unlock_irq(&mapping
->i_pages
);
1284 put_swap_page(&folio
->page
, swap
);
1286 void (*freepage
)(struct page
*);
1288 freepage
= mapping
->a_ops
->freepage
;
1290 * Remember a shadow entry for reclaimed file cache in
1291 * order to detect refaults, thus thrashing, later on.
1293 * But don't store shadows in an address space that is
1294 * already exiting. This is not just an optimization,
1295 * inode reclaim needs to empty out the radix tree or
1296 * the nodes are lost. Don't plant shadows behind its
1299 * We also don't store shadows for DAX mappings because the
1300 * only page cache pages found in these are zero pages
1301 * covering holes, and because we don't want to mix DAX
1302 * exceptional entries and shadow exceptional entries in the
1303 * same address_space.
1305 if (reclaimed
&& folio_is_file_lru(folio
) &&
1306 !mapping_exiting(mapping
) && !dax_mapping(mapping
))
1307 shadow
= workingset_eviction(folio
, target_memcg
);
1308 __filemap_remove_folio(folio
, shadow
);
1309 xa_unlock_irq(&mapping
->i_pages
);
1310 if (mapping_shrinkable(mapping
))
1311 inode_add_lru(mapping
->host
);
1312 spin_unlock(&mapping
->host
->i_lock
);
1314 if (freepage
!= NULL
)
1315 freepage(&folio
->page
);
1321 xa_unlock_irq(&mapping
->i_pages
);
1322 if (!folio_test_swapcache(folio
))
1323 spin_unlock(&mapping
->host
->i_lock
);
1328 * remove_mapping() - Attempt to remove a folio from its mapping.
1329 * @mapping: The address space.
1330 * @folio: The folio to remove.
1332 * If the folio is dirty, under writeback or if someone else has a ref
1333 * on it, removal will fail.
1334 * Return: The number of pages removed from the mapping. 0 if the folio
1335 * could not be removed.
1336 * Context: The caller should have a single refcount on the folio and
1339 long remove_mapping(struct address_space
*mapping
, struct folio
*folio
)
1341 if (__remove_mapping(mapping
, folio
, false, NULL
)) {
1343 * Unfreezing the refcount with 1 effectively
1344 * drops the pagecache ref for us without requiring another
1347 folio_ref_unfreeze(folio
, 1);
1348 return folio_nr_pages(folio
);
1354 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1355 * @folio: Folio to be returned to an LRU list.
1357 * Add previously isolated @folio to appropriate LRU list.
1358 * The folio may still be unevictable for other reasons.
1360 * Context: lru_lock must not be held, interrupts must be enabled.
1362 void folio_putback_lru(struct folio
*folio
)
1364 folio_add_lru(folio
);
1365 folio_put(folio
); /* drop ref from isolate */
1368 enum page_references
{
1370 PAGEREF_RECLAIM_CLEAN
,
1375 static enum page_references
folio_check_references(struct folio
*folio
,
1376 struct scan_control
*sc
)
1378 int referenced_ptes
, referenced_folio
;
1379 unsigned long vm_flags
;
1381 referenced_ptes
= folio_referenced(folio
, 1, sc
->target_mem_cgroup
,
1383 referenced_folio
= folio_test_clear_referenced(folio
);
1386 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1387 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1389 if (vm_flags
& VM_LOCKED
)
1390 return PAGEREF_ACTIVATE
;
1392 if (referenced_ptes
) {
1394 * All mapped folios start out with page table
1395 * references from the instantiating fault, so we need
1396 * to look twice if a mapped file/anon folio is used more
1399 * Mark it and spare it for another trip around the
1400 * inactive list. Another page table reference will
1401 * lead to its activation.
1403 * Note: the mark is set for activated folios as well
1404 * so that recently deactivated but used folios are
1405 * quickly recovered.
1407 folio_set_referenced(folio
);
1409 if (referenced_folio
|| referenced_ptes
> 1)
1410 return PAGEREF_ACTIVATE
;
1413 * Activate file-backed executable folios after first usage.
1415 if ((vm_flags
& VM_EXEC
) && !folio_test_swapbacked(folio
))
1416 return PAGEREF_ACTIVATE
;
1418 return PAGEREF_KEEP
;
1421 /* Reclaim if clean, defer dirty folios to writeback */
1422 if (referenced_folio
&& !folio_test_swapbacked(folio
))
1423 return PAGEREF_RECLAIM_CLEAN
;
1425 return PAGEREF_RECLAIM
;
1428 /* Check if a page is dirty or under writeback */
1429 static void folio_check_dirty_writeback(struct folio
*folio
,
1430 bool *dirty
, bool *writeback
)
1432 struct address_space
*mapping
;
1435 * Anonymous pages are not handled by flushers and must be written
1436 * from reclaim context. Do not stall reclaim based on them
1438 if (!folio_is_file_lru(folio
) ||
1439 (folio_test_anon(folio
) && !folio_test_swapbacked(folio
))) {
1445 /* By default assume that the folio flags are accurate */
1446 *dirty
= folio_test_dirty(folio
);
1447 *writeback
= folio_test_writeback(folio
);
1449 /* Verify dirty/writeback state if the filesystem supports it */
1450 if (!folio_test_private(folio
))
1453 mapping
= folio_mapping(folio
);
1454 if (mapping
&& mapping
->a_ops
->is_dirty_writeback
)
1455 mapping
->a_ops
->is_dirty_writeback(&folio
->page
, dirty
, writeback
);
1458 static struct page
*alloc_demote_page(struct page
*page
, unsigned long node
)
1460 struct migration_target_control mtc
= {
1462 * Allocate from 'node', or fail quickly and quietly.
1463 * When this happens, 'page' will likely just be discarded
1464 * instead of migrated.
1466 .gfp_mask
= (GFP_HIGHUSER_MOVABLE
& ~__GFP_RECLAIM
) |
1467 __GFP_THISNODE
| __GFP_NOWARN
|
1468 __GFP_NOMEMALLOC
| GFP_NOWAIT
,
1472 return alloc_migration_target(page
, (unsigned long)&mtc
);
1476 * Take pages on @demote_list and attempt to demote them to
1477 * another node. Pages which are not demoted are left on
1480 static unsigned int demote_page_list(struct list_head
*demote_pages
,
1481 struct pglist_data
*pgdat
)
1483 int target_nid
= next_demotion_node(pgdat
->node_id
);
1484 unsigned int nr_succeeded
;
1486 if (list_empty(demote_pages
))
1489 if (target_nid
== NUMA_NO_NODE
)
1492 /* Demotion ignores all cpuset and mempolicy settings */
1493 migrate_pages(demote_pages
, alloc_demote_page
, NULL
,
1494 target_nid
, MIGRATE_ASYNC
, MR_DEMOTION
,
1497 if (current_is_kswapd())
1498 __count_vm_events(PGDEMOTE_KSWAPD
, nr_succeeded
);
1500 __count_vm_events(PGDEMOTE_DIRECT
, nr_succeeded
);
1502 return nr_succeeded
;
1505 static bool may_enter_fs(struct page
*page
, gfp_t gfp_mask
)
1507 if (gfp_mask
& __GFP_FS
)
1509 if (!PageSwapCache(page
) || !(gfp_mask
& __GFP_IO
))
1512 * We can "enter_fs" for swap-cache with only __GFP_IO
1513 * providing this isn't SWP_FS_OPS.
1514 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1515 * but that will never affect SWP_FS_OPS, so the data_race
1518 return !data_race(page_swap_flags(page
) & SWP_FS_OPS
);
1522 * shrink_page_list() returns the number of reclaimed pages
1524 static unsigned int shrink_page_list(struct list_head
*page_list
,
1525 struct pglist_data
*pgdat
,
1526 struct scan_control
*sc
,
1527 struct reclaim_stat
*stat
,
1528 bool ignore_references
)
1530 LIST_HEAD(ret_pages
);
1531 LIST_HEAD(free_pages
);
1532 LIST_HEAD(demote_pages
);
1533 unsigned int nr_reclaimed
= 0;
1534 unsigned int pgactivate
= 0;
1535 bool do_demote_pass
;
1537 memset(stat
, 0, sizeof(*stat
));
1539 do_demote_pass
= can_demote(pgdat
->node_id
, sc
);
1542 while (!list_empty(page_list
)) {
1543 struct address_space
*mapping
;
1545 struct folio
*folio
;
1546 enum page_references references
= PAGEREF_RECLAIM
;
1547 bool dirty
, writeback
;
1548 unsigned int nr_pages
;
1552 folio
= lru_to_folio(page_list
);
1553 list_del(&folio
->lru
);
1554 page
= &folio
->page
;
1556 if (!trylock_page(page
))
1559 VM_BUG_ON_PAGE(PageActive(page
), page
);
1561 nr_pages
= compound_nr(page
);
1563 /* Account the number of base pages even though THP */
1564 sc
->nr_scanned
+= nr_pages
;
1566 if (unlikely(!page_evictable(page
)))
1567 goto activate_locked
;
1569 if (!sc
->may_unmap
&& page_mapped(page
))
1573 * The number of dirty pages determines if a node is marked
1574 * reclaim_congested. kswapd will stall and start writing
1575 * pages if the tail of the LRU is all dirty unqueued pages.
1577 folio_check_dirty_writeback(folio
, &dirty
, &writeback
);
1578 if (dirty
|| writeback
)
1579 stat
->nr_dirty
+= nr_pages
;
1581 if (dirty
&& !writeback
)
1582 stat
->nr_unqueued_dirty
+= nr_pages
;
1585 * Treat this page as congested if the underlying BDI is or if
1586 * pages are cycling through the LRU so quickly that the
1587 * pages marked for immediate reclaim are making it to the
1588 * end of the LRU a second time.
1590 mapping
= page_mapping(page
);
1591 if (writeback
&& PageReclaim(page
))
1592 stat
->nr_congested
+= nr_pages
;
1595 * If a page at the tail of the LRU is under writeback, there
1596 * are three cases to consider.
1598 * 1) If reclaim is encountering an excessive number of pages
1599 * under writeback and this page is both under writeback and
1600 * PageReclaim then it indicates that pages are being queued
1601 * for IO but are being recycled through the LRU before the
1602 * IO can complete. Waiting on the page itself risks an
1603 * indefinite stall if it is impossible to writeback the
1604 * page due to IO error or disconnected storage so instead
1605 * note that the LRU is being scanned too quickly and the
1606 * caller can stall after page list has been processed.
1608 * 2) Global or new memcg reclaim encounters a page that is
1609 * not marked for immediate reclaim, or the caller does not
1610 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1611 * not to fs). In this case mark the page for immediate
1612 * reclaim and continue scanning.
1614 * Require may_enter_fs() because we would wait on fs, which
1615 * may not have submitted IO yet. And the loop driver might
1616 * enter reclaim, and deadlock if it waits on a page for
1617 * which it is needed to do the write (loop masks off
1618 * __GFP_IO|__GFP_FS for this reason); but more thought
1619 * would probably show more reasons.
1621 * 3) Legacy memcg encounters a page that is already marked
1622 * PageReclaim. memcg does not have any dirty pages
1623 * throttling so we could easily OOM just because too many
1624 * pages are in writeback and there is nothing else to
1625 * reclaim. Wait for the writeback to complete.
1627 * In cases 1) and 2) we activate the pages to get them out of
1628 * the way while we continue scanning for clean pages on the
1629 * inactive list and refilling from the active list. The
1630 * observation here is that waiting for disk writes is more
1631 * expensive than potentially causing reloads down the line.
1632 * Since they're marked for immediate reclaim, they won't put
1633 * memory pressure on the cache working set any longer than it
1634 * takes to write them to disk.
1636 if (PageWriteback(page
)) {
1638 if (current_is_kswapd() &&
1639 PageReclaim(page
) &&
1640 test_bit(PGDAT_WRITEBACK
, &pgdat
->flags
)) {
1641 stat
->nr_immediate
+= nr_pages
;
1642 goto activate_locked
;
1645 } else if (writeback_throttling_sane(sc
) ||
1646 !PageReclaim(page
) || !may_enter_fs(page
, sc
->gfp_mask
)) {
1648 * This is slightly racy - end_page_writeback()
1649 * might have just cleared PageReclaim, then
1650 * setting PageReclaim here end up interpreted
1651 * as PageReadahead - but that does not matter
1652 * enough to care. What we do want is for this
1653 * page to have PageReclaim set next time memcg
1654 * reclaim reaches the tests above, so it will
1655 * then wait_on_page_writeback() to avoid OOM;
1656 * and it's also appropriate in global reclaim.
1658 SetPageReclaim(page
);
1659 stat
->nr_writeback
+= nr_pages
;
1660 goto activate_locked
;
1665 wait_on_page_writeback(page
);
1666 /* then go back and try same page again */
1667 list_add_tail(&page
->lru
, page_list
);
1672 if (!ignore_references
)
1673 references
= folio_check_references(folio
, sc
);
1675 switch (references
) {
1676 case PAGEREF_ACTIVATE
:
1677 goto activate_locked
;
1679 stat
->nr_ref_keep
+= nr_pages
;
1681 case PAGEREF_RECLAIM
:
1682 case PAGEREF_RECLAIM_CLEAN
:
1683 ; /* try to reclaim the page below */
1687 * Before reclaiming the page, try to relocate
1688 * its contents to another node.
1690 if (do_demote_pass
&&
1691 (thp_migration_supported() || !PageTransHuge(page
))) {
1692 list_add(&page
->lru
, &demote_pages
);
1698 * Anonymous process memory has backing store?
1699 * Try to allocate it some swap space here.
1700 * Lazyfree page could be freed directly
1702 if (PageAnon(page
) && PageSwapBacked(page
)) {
1703 if (!PageSwapCache(page
)) {
1704 if (!(sc
->gfp_mask
& __GFP_IO
))
1706 if (folio_maybe_dma_pinned(folio
))
1708 if (PageTransHuge(page
)) {
1709 /* cannot split THP, skip it */
1710 if (!can_split_folio(folio
, NULL
))
1711 goto activate_locked
;
1713 * Split pages without a PMD map right
1714 * away. Chances are some or all of the
1715 * tail pages can be freed without IO.
1717 if (!folio_entire_mapcount(folio
) &&
1718 split_folio_to_list(folio
,
1720 goto activate_locked
;
1722 if (!add_to_swap(page
)) {
1723 if (!PageTransHuge(page
))
1724 goto activate_locked_split
;
1725 /* Fallback to swap normal pages */
1726 if (split_folio_to_list(folio
,
1728 goto activate_locked
;
1729 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1730 count_vm_event(THP_SWPOUT_FALLBACK
);
1732 if (!add_to_swap(page
))
1733 goto activate_locked_split
;
1736 /* Adding to swap updated mapping */
1737 mapping
= page_mapping(page
);
1739 } else if (PageSwapBacked(page
) && PageTransHuge(page
)) {
1740 /* Split shmem THP */
1741 if (split_folio_to_list(folio
, page_list
))
1746 * THP may get split above, need minus tail pages and update
1747 * nr_pages to avoid accounting tail pages twice.
1749 * The tail pages that are added into swap cache successfully
1752 if ((nr_pages
> 1) && !PageTransHuge(page
)) {
1753 sc
->nr_scanned
-= (nr_pages
- 1);
1758 * The page is mapped into the page tables of one or more
1759 * processes. Try to unmap it here.
1761 if (page_mapped(page
)) {
1762 enum ttu_flags flags
= TTU_BATCH_FLUSH
;
1763 bool was_swapbacked
= PageSwapBacked(page
);
1765 if (PageTransHuge(page
) &&
1766 thp_order(page
) >= HPAGE_PMD_ORDER
)
1767 flags
|= TTU_SPLIT_HUGE_PMD
;
1769 try_to_unmap(folio
, flags
);
1770 if (page_mapped(page
)) {
1771 stat
->nr_unmap_fail
+= nr_pages
;
1772 if (!was_swapbacked
&& PageSwapBacked(page
))
1773 stat
->nr_lazyfree_fail
+= nr_pages
;
1774 goto activate_locked
;
1778 if (PageDirty(page
)) {
1780 * Only kswapd can writeback filesystem pages
1781 * to avoid risk of stack overflow. But avoid
1782 * injecting inefficient single-page IO into
1783 * flusher writeback as much as possible: only
1784 * write pages when we've encountered many
1785 * dirty pages, and when we've already scanned
1786 * the rest of the LRU for clean pages and see
1787 * the same dirty pages again (PageReclaim).
1789 if (page_is_file_lru(page
) &&
1790 (!current_is_kswapd() || !PageReclaim(page
) ||
1791 !test_bit(PGDAT_DIRTY
, &pgdat
->flags
))) {
1793 * Immediately reclaim when written back.
1794 * Similar in principal to deactivate_page()
1795 * except we already have the page isolated
1796 * and know it's dirty
1798 inc_node_page_state(page
, NR_VMSCAN_IMMEDIATE
);
1799 SetPageReclaim(page
);
1801 goto activate_locked
;
1804 if (references
== PAGEREF_RECLAIM_CLEAN
)
1806 if (!may_enter_fs(page
, sc
->gfp_mask
))
1808 if (!sc
->may_writepage
)
1812 * Page is dirty. Flush the TLB if a writable entry
1813 * potentially exists to avoid CPU writes after IO
1814 * starts and then write it out here.
1816 try_to_unmap_flush_dirty();
1817 switch (pageout(folio
, mapping
)) {
1821 goto activate_locked
;
1823 stat
->nr_pageout
+= nr_pages
;
1825 if (PageWriteback(page
))
1827 if (PageDirty(page
))
1831 * A synchronous write - probably a ramdisk. Go
1832 * ahead and try to reclaim the page.
1834 if (!trylock_page(page
))
1836 if (PageDirty(page
) || PageWriteback(page
))
1838 mapping
= page_mapping(page
);
1841 ; /* try to free the page below */
1846 * If the page has buffers, try to free the buffer mappings
1847 * associated with this page. If we succeed we try to free
1850 * We do this even if the page is PageDirty().
1851 * try_to_release_page() does not perform I/O, but it is
1852 * possible for a page to have PageDirty set, but it is actually
1853 * clean (all its buffers are clean). This happens if the
1854 * buffers were written out directly, with submit_bh(). ext3
1855 * will do this, as well as the blockdev mapping.
1856 * try_to_release_page() will discover that cleanness and will
1857 * drop the buffers and mark the page clean - it can be freed.
1859 * Rarely, pages can have buffers and no ->mapping. These are
1860 * the pages which were not successfully invalidated in
1861 * truncate_cleanup_page(). We try to drop those buffers here
1862 * and if that worked, and the page is no longer mapped into
1863 * process address space (page_count == 1) it can be freed.
1864 * Otherwise, leave the page on the LRU so it is swappable.
1866 if (page_has_private(page
)) {
1867 if (!try_to_release_page(page
, sc
->gfp_mask
))
1868 goto activate_locked
;
1869 if (!mapping
&& page_count(page
) == 1) {
1871 if (put_page_testzero(page
))
1875 * rare race with speculative reference.
1876 * the speculative reference will free
1877 * this page shortly, so we may
1878 * increment nr_reclaimed here (and
1879 * leave it off the LRU).
1887 if (PageAnon(page
) && !PageSwapBacked(page
)) {
1888 /* follow __remove_mapping for reference */
1889 if (!page_ref_freeze(page
, 1))
1892 * The page has only one reference left, which is
1893 * from the isolation. After the caller puts the
1894 * page back on lru and drops the reference, the
1895 * page will be freed anyway. It doesn't matter
1896 * which lru it goes. So we don't bother checking
1899 count_vm_event(PGLAZYFREED
);
1900 count_memcg_page_event(page
, PGLAZYFREED
);
1901 } else if (!mapping
|| !__remove_mapping(mapping
, folio
, true,
1902 sc
->target_mem_cgroup
))
1908 * THP may get swapped out in a whole, need account
1911 nr_reclaimed
+= nr_pages
;
1914 * Is there need to periodically free_page_list? It would
1915 * appear not as the counts should be low
1917 if (unlikely(PageTransHuge(page
)))
1918 destroy_compound_page(page
);
1920 list_add(&page
->lru
, &free_pages
);
1923 activate_locked_split
:
1925 * The tail pages that are failed to add into swap cache
1926 * reach here. Fixup nr_scanned and nr_pages.
1929 sc
->nr_scanned
-= (nr_pages
- 1);
1933 /* Not a candidate for swapping, so reclaim swap space. */
1934 if (PageSwapCache(page
) && (mem_cgroup_swap_full(page
) ||
1936 try_to_free_swap(page
);
1937 VM_BUG_ON_PAGE(PageActive(page
), page
);
1938 if (!PageMlocked(page
)) {
1939 int type
= page_is_file_lru(page
);
1940 SetPageActive(page
);
1941 stat
->nr_activate
[type
] += nr_pages
;
1942 count_memcg_page_event(page
, PGACTIVATE
);
1947 list_add(&page
->lru
, &ret_pages
);
1948 VM_BUG_ON_PAGE(PageLRU(page
) || PageUnevictable(page
), page
);
1950 /* 'page_list' is always empty here */
1952 /* Migrate pages selected for demotion */
1953 nr_reclaimed
+= demote_page_list(&demote_pages
, pgdat
);
1954 /* Pages that could not be demoted are still in @demote_pages */
1955 if (!list_empty(&demote_pages
)) {
1956 /* Pages which failed to demoted go back on @page_list for retry: */
1957 list_splice_init(&demote_pages
, page_list
);
1958 do_demote_pass
= false;
1962 pgactivate
= stat
->nr_activate
[0] + stat
->nr_activate
[1];
1964 mem_cgroup_uncharge_list(&free_pages
);
1965 try_to_unmap_flush();
1966 free_unref_page_list(&free_pages
);
1968 list_splice(&ret_pages
, page_list
);
1969 count_vm_events(PGACTIVATE
, pgactivate
);
1971 return nr_reclaimed
;
1974 unsigned int reclaim_clean_pages_from_list(struct zone
*zone
,
1975 struct list_head
*page_list
)
1977 struct scan_control sc
= {
1978 .gfp_mask
= GFP_KERNEL
,
1981 struct reclaim_stat stat
;
1982 unsigned int nr_reclaimed
;
1983 struct page
*page
, *next
;
1984 LIST_HEAD(clean_pages
);
1985 unsigned int noreclaim_flag
;
1987 list_for_each_entry_safe(page
, next
, page_list
, lru
) {
1988 if (!PageHuge(page
) && page_is_file_lru(page
) &&
1989 !PageDirty(page
) && !__PageMovable(page
) &&
1990 !PageUnevictable(page
)) {
1991 ClearPageActive(page
);
1992 list_move(&page
->lru
, &clean_pages
);
1997 * We should be safe here since we are only dealing with file pages and
1998 * we are not kswapd and therefore cannot write dirty file pages. But
1999 * call memalloc_noreclaim_save() anyway, just in case these conditions
2000 * change in the future.
2002 noreclaim_flag
= memalloc_noreclaim_save();
2003 nr_reclaimed
= shrink_page_list(&clean_pages
, zone
->zone_pgdat
, &sc
,
2005 memalloc_noreclaim_restore(noreclaim_flag
);
2007 list_splice(&clean_pages
, page_list
);
2008 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
2009 -(long)nr_reclaimed
);
2011 * Since lazyfree pages are isolated from file LRU from the beginning,
2012 * they will rotate back to anonymous LRU in the end if it failed to
2013 * discard so isolated count will be mismatched.
2014 * Compensate the isolated count for both LRU lists.
2016 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_ANON
,
2017 stat
.nr_lazyfree_fail
);
2018 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
2019 -(long)stat
.nr_lazyfree_fail
);
2020 return nr_reclaimed
;
2024 * Update LRU sizes after isolating pages. The LRU size updates must
2025 * be complete before mem_cgroup_update_lru_size due to a sanity check.
2027 static __always_inline
void update_lru_sizes(struct lruvec
*lruvec
,
2028 enum lru_list lru
, unsigned long *nr_zone_taken
)
2032 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
2033 if (!nr_zone_taken
[zid
])
2036 update_lru_size(lruvec
, lru
, zid
, -nr_zone_taken
[zid
]);
2042 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2044 * lruvec->lru_lock is heavily contended. Some of the functions that
2045 * shrink the lists perform better by taking out a batch of pages
2046 * and working on them outside the LRU lock.
2048 * For pagecache intensive workloads, this function is the hottest
2049 * spot in the kernel (apart from copy_*_user functions).
2051 * Lru_lock must be held before calling this function.
2053 * @nr_to_scan: The number of eligible pages to look through on the list.
2054 * @lruvec: The LRU vector to pull pages from.
2055 * @dst: The temp list to put pages on to.
2056 * @nr_scanned: The number of pages that were scanned.
2057 * @sc: The scan_control struct for this reclaim session
2058 * @lru: LRU list id for isolating
2060 * returns how many pages were moved onto *@dst.
2062 static unsigned long isolate_lru_pages(unsigned long nr_to_scan
,
2063 struct lruvec
*lruvec
, struct list_head
*dst
,
2064 unsigned long *nr_scanned
, struct scan_control
*sc
,
2067 struct list_head
*src
= &lruvec
->lists
[lru
];
2068 unsigned long nr_taken
= 0;
2069 unsigned long nr_zone_taken
[MAX_NR_ZONES
] = { 0 };
2070 unsigned long nr_skipped
[MAX_NR_ZONES
] = { 0, };
2071 unsigned long skipped
= 0;
2072 unsigned long scan
, total_scan
, nr_pages
;
2073 LIST_HEAD(pages_skipped
);
2077 while (scan
< nr_to_scan
&& !list_empty(src
)) {
2078 struct list_head
*move_to
= src
;
2081 page
= lru_to_page(src
);
2082 prefetchw_prev_lru_page(page
, src
, flags
);
2084 nr_pages
= compound_nr(page
);
2085 total_scan
+= nr_pages
;
2087 if (page_zonenum(page
) > sc
->reclaim_idx
) {
2088 nr_skipped
[page_zonenum(page
)] += nr_pages
;
2089 move_to
= &pages_skipped
;
2094 * Do not count skipped pages because that makes the function
2095 * return with no isolated pages if the LRU mostly contains
2096 * ineligible pages. This causes the VM to not reclaim any
2097 * pages, triggering a premature OOM.
2098 * Account all tail pages of THP.
2104 if (!sc
->may_unmap
&& page_mapped(page
))
2108 * Be careful not to clear PageLRU until after we're
2109 * sure the page is not being freed elsewhere -- the
2110 * page release code relies on it.
2112 if (unlikely(!get_page_unless_zero(page
)))
2115 if (!TestClearPageLRU(page
)) {
2116 /* Another thread is already isolating this page */
2121 nr_taken
+= nr_pages
;
2122 nr_zone_taken
[page_zonenum(page
)] += nr_pages
;
2125 list_move(&page
->lru
, move_to
);
2129 * Splice any skipped pages to the start of the LRU list. Note that
2130 * this disrupts the LRU order when reclaiming for lower zones but
2131 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2132 * scanning would soon rescan the same pages to skip and waste lots
2135 if (!list_empty(&pages_skipped
)) {
2138 list_splice(&pages_skipped
, src
);
2139 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
2140 if (!nr_skipped
[zid
])
2143 __count_zid_vm_events(PGSCAN_SKIP
, zid
, nr_skipped
[zid
]);
2144 skipped
+= nr_skipped
[zid
];
2147 *nr_scanned
= total_scan
;
2148 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, nr_to_scan
,
2149 total_scan
, skipped
, nr_taken
,
2150 sc
->may_unmap
? 0 : ISOLATE_UNMAPPED
, lru
);
2151 update_lru_sizes(lruvec
, lru
, nr_zone_taken
);
2156 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2157 * @folio: Folio to isolate from its LRU list.
2159 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2160 * corresponding to whatever LRU list the folio was on.
2162 * The folio will have its LRU flag cleared. If it was found on the
2163 * active list, it will have the Active flag set. If it was found on the
2164 * unevictable list, it will have the Unevictable flag set. These flags
2165 * may need to be cleared by the caller before letting the page go.
2169 * (1) Must be called with an elevated refcount on the page. This is a
2170 * fundamental difference from isolate_lru_pages() (which is called
2171 * without a stable reference).
2172 * (2) The lru_lock must not be held.
2173 * (3) Interrupts must be enabled.
2175 * Return: 0 if the folio was removed from an LRU list.
2176 * -EBUSY if the folio was not on an LRU list.
2178 int folio_isolate_lru(struct folio
*folio
)
2182 VM_BUG_ON_FOLIO(!folio_ref_count(folio
), folio
);
2184 if (folio_test_clear_lru(folio
)) {
2185 struct lruvec
*lruvec
;
2188 lruvec
= folio_lruvec_lock_irq(folio
);
2189 lruvec_del_folio(lruvec
, folio
);
2190 unlock_page_lruvec_irq(lruvec
);
2198 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2199 * then get rescheduled. When there are massive number of tasks doing page
2200 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2201 * the LRU list will go small and be scanned faster than necessary, leading to
2202 * unnecessary swapping, thrashing and OOM.
2204 static int too_many_isolated(struct pglist_data
*pgdat
, int file
,
2205 struct scan_control
*sc
)
2207 unsigned long inactive
, isolated
;
2210 if (current_is_kswapd())
2213 if (!writeback_throttling_sane(sc
))
2217 inactive
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
2218 isolated
= node_page_state(pgdat
, NR_ISOLATED_FILE
);
2220 inactive
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2221 isolated
= node_page_state(pgdat
, NR_ISOLATED_ANON
);
2225 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2226 * won't get blocked by normal direct-reclaimers, forming a circular
2229 if ((sc
->gfp_mask
& (__GFP_IO
| __GFP_FS
)) == (__GFP_IO
| __GFP_FS
))
2232 too_many
= isolated
> inactive
;
2234 /* Wake up tasks throttled due to too_many_isolated. */
2236 wake_throttle_isolated(pgdat
);
2242 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2243 * On return, @list is reused as a list of pages to be freed by the caller.
2245 * Returns the number of pages moved to the given lruvec.
2247 static unsigned int move_pages_to_lru(struct lruvec
*lruvec
,
2248 struct list_head
*list
)
2250 int nr_pages
, nr_moved
= 0;
2251 LIST_HEAD(pages_to_free
);
2254 while (!list_empty(list
)) {
2255 page
= lru_to_page(list
);
2256 VM_BUG_ON_PAGE(PageLRU(page
), page
);
2257 list_del(&page
->lru
);
2258 if (unlikely(!page_evictable(page
))) {
2259 spin_unlock_irq(&lruvec
->lru_lock
);
2260 putback_lru_page(page
);
2261 spin_lock_irq(&lruvec
->lru_lock
);
2266 * The SetPageLRU needs to be kept here for list integrity.
2268 * #0 move_pages_to_lru #1 release_pages
2269 * if !put_page_testzero
2270 * if (put_page_testzero())
2271 * !PageLRU //skip lru_lock
2273 * list_add(&page->lru,)
2274 * list_add(&page->lru,)
2278 if (unlikely(put_page_testzero(page
))) {
2279 __clear_page_lru_flags(page
);
2281 if (unlikely(PageCompound(page
))) {
2282 spin_unlock_irq(&lruvec
->lru_lock
);
2283 destroy_compound_page(page
);
2284 spin_lock_irq(&lruvec
->lru_lock
);
2286 list_add(&page
->lru
, &pages_to_free
);
2292 * All pages were isolated from the same lruvec (and isolation
2293 * inhibits memcg migration).
2295 VM_BUG_ON_PAGE(!folio_matches_lruvec(page_folio(page
), lruvec
), page
);
2296 add_page_to_lru_list(page
, lruvec
);
2297 nr_pages
= thp_nr_pages(page
);
2298 nr_moved
+= nr_pages
;
2299 if (PageActive(page
))
2300 workingset_age_nonresident(lruvec
, nr_pages
);
2304 * To save our caller's stack, now use input list for pages to free.
2306 list_splice(&pages_to_free
, list
);
2312 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2313 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2314 * we should not throttle. Otherwise it is safe to do so.
2316 static int current_may_throttle(void)
2318 return !(current
->flags
& PF_LOCAL_THROTTLE
);
2322 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2323 * of reclaimed pages
2325 static unsigned long
2326 shrink_inactive_list(unsigned long nr_to_scan
, struct lruvec
*lruvec
,
2327 struct scan_control
*sc
, enum lru_list lru
)
2329 LIST_HEAD(page_list
);
2330 unsigned long nr_scanned
;
2331 unsigned int nr_reclaimed
= 0;
2332 unsigned long nr_taken
;
2333 struct reclaim_stat stat
;
2334 bool file
= is_file_lru(lru
);
2335 enum vm_event_item item
;
2336 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2337 bool stalled
= false;
2339 while (unlikely(too_many_isolated(pgdat
, file
, sc
))) {
2343 /* wait a bit for the reclaimer. */
2345 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_ISOLATED
);
2347 /* We are about to die and free our memory. Return now. */
2348 if (fatal_signal_pending(current
))
2349 return SWAP_CLUSTER_MAX
;
2354 spin_lock_irq(&lruvec
->lru_lock
);
2356 nr_taken
= isolate_lru_pages(nr_to_scan
, lruvec
, &page_list
,
2357 &nr_scanned
, sc
, lru
);
2359 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2360 item
= current_is_kswapd() ? PGSCAN_KSWAPD
: PGSCAN_DIRECT
;
2361 if (!cgroup_reclaim(sc
))
2362 __count_vm_events(item
, nr_scanned
);
2363 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_scanned
);
2364 __count_vm_events(PGSCAN_ANON
+ file
, nr_scanned
);
2366 spin_unlock_irq(&lruvec
->lru_lock
);
2371 nr_reclaimed
= shrink_page_list(&page_list
, pgdat
, sc
, &stat
, false);
2373 spin_lock_irq(&lruvec
->lru_lock
);
2374 move_pages_to_lru(lruvec
, &page_list
);
2376 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2377 item
= current_is_kswapd() ? PGSTEAL_KSWAPD
: PGSTEAL_DIRECT
;
2378 if (!cgroup_reclaim(sc
))
2379 __count_vm_events(item
, nr_reclaimed
);
2380 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_reclaimed
);
2381 __count_vm_events(PGSTEAL_ANON
+ file
, nr_reclaimed
);
2382 spin_unlock_irq(&lruvec
->lru_lock
);
2384 lru_note_cost(lruvec
, file
, stat
.nr_pageout
);
2385 mem_cgroup_uncharge_list(&page_list
);
2386 free_unref_page_list(&page_list
);
2389 * If dirty pages are scanned that are not queued for IO, it
2390 * implies that flushers are not doing their job. This can
2391 * happen when memory pressure pushes dirty pages to the end of
2392 * the LRU before the dirty limits are breached and the dirty
2393 * data has expired. It can also happen when the proportion of
2394 * dirty pages grows not through writes but through memory
2395 * pressure reclaiming all the clean cache. And in some cases,
2396 * the flushers simply cannot keep up with the allocation
2397 * rate. Nudge the flusher threads in case they are asleep.
2399 if (stat
.nr_unqueued_dirty
== nr_taken
)
2400 wakeup_flusher_threads(WB_REASON_VMSCAN
);
2402 sc
->nr
.dirty
+= stat
.nr_dirty
;
2403 sc
->nr
.congested
+= stat
.nr_congested
;
2404 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
2405 sc
->nr
.writeback
+= stat
.nr_writeback
;
2406 sc
->nr
.immediate
+= stat
.nr_immediate
;
2407 sc
->nr
.taken
+= nr_taken
;
2409 sc
->nr
.file_taken
+= nr_taken
;
2411 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
2412 nr_scanned
, nr_reclaimed
, &stat
, sc
->priority
, file
);
2413 return nr_reclaimed
;
2417 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2419 * We move them the other way if the page is referenced by one or more
2422 * If the pages are mostly unmapped, the processing is fast and it is
2423 * appropriate to hold lru_lock across the whole operation. But if
2424 * the pages are mapped, the processing is slow (folio_referenced()), so
2425 * we should drop lru_lock around each page. It's impossible to balance
2426 * this, so instead we remove the pages from the LRU while processing them.
2427 * It is safe to rely on PG_active against the non-LRU pages in here because
2428 * nobody will play with that bit on a non-LRU page.
2430 * The downside is that we have to touch page->_refcount against each page.
2431 * But we had to alter page->flags anyway.
2433 static void shrink_active_list(unsigned long nr_to_scan
,
2434 struct lruvec
*lruvec
,
2435 struct scan_control
*sc
,
2438 unsigned long nr_taken
;
2439 unsigned long nr_scanned
;
2440 unsigned long vm_flags
;
2441 LIST_HEAD(l_hold
); /* The pages which were snipped off */
2442 LIST_HEAD(l_active
);
2443 LIST_HEAD(l_inactive
);
2444 unsigned nr_deactivate
, nr_activate
;
2445 unsigned nr_rotated
= 0;
2446 int file
= is_file_lru(lru
);
2447 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2451 spin_lock_irq(&lruvec
->lru_lock
);
2453 nr_taken
= isolate_lru_pages(nr_to_scan
, lruvec
, &l_hold
,
2454 &nr_scanned
, sc
, lru
);
2456 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2458 if (!cgroup_reclaim(sc
))
2459 __count_vm_events(PGREFILL
, nr_scanned
);
2460 __count_memcg_events(lruvec_memcg(lruvec
), PGREFILL
, nr_scanned
);
2462 spin_unlock_irq(&lruvec
->lru_lock
);
2464 while (!list_empty(&l_hold
)) {
2465 struct folio
*folio
;
2469 folio
= lru_to_folio(&l_hold
);
2470 list_del(&folio
->lru
);
2471 page
= &folio
->page
;
2473 if (unlikely(!page_evictable(page
))) {
2474 putback_lru_page(page
);
2478 if (unlikely(buffer_heads_over_limit
)) {
2479 if (page_has_private(page
) && trylock_page(page
)) {
2480 if (page_has_private(page
))
2481 try_to_release_page(page
, 0);
2486 if (folio_referenced(folio
, 0, sc
->target_mem_cgroup
,
2489 * Identify referenced, file-backed active pages and
2490 * give them one more trip around the active list. So
2491 * that executable code get better chances to stay in
2492 * memory under moderate memory pressure. Anon pages
2493 * are not likely to be evicted by use-once streaming
2494 * IO, plus JVM can create lots of anon VM_EXEC pages,
2495 * so we ignore them here.
2497 if ((vm_flags
& VM_EXEC
) && page_is_file_lru(page
)) {
2498 nr_rotated
+= thp_nr_pages(page
);
2499 list_add(&page
->lru
, &l_active
);
2504 ClearPageActive(page
); /* we are de-activating */
2505 SetPageWorkingset(page
);
2506 list_add(&page
->lru
, &l_inactive
);
2510 * Move pages back to the lru list.
2512 spin_lock_irq(&lruvec
->lru_lock
);
2514 nr_activate
= move_pages_to_lru(lruvec
, &l_active
);
2515 nr_deactivate
= move_pages_to_lru(lruvec
, &l_inactive
);
2516 /* Keep all free pages in l_active list */
2517 list_splice(&l_inactive
, &l_active
);
2519 __count_vm_events(PGDEACTIVATE
, nr_deactivate
);
2520 __count_memcg_events(lruvec_memcg(lruvec
), PGDEACTIVATE
, nr_deactivate
);
2522 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2523 spin_unlock_irq(&lruvec
->lru_lock
);
2525 mem_cgroup_uncharge_list(&l_active
);
2526 free_unref_page_list(&l_active
);
2527 trace_mm_vmscan_lru_shrink_active(pgdat
->node_id
, nr_taken
, nr_activate
,
2528 nr_deactivate
, nr_rotated
, sc
->priority
, file
);
2531 unsigned long reclaim_pages(struct list_head
*page_list
)
2533 int nid
= NUMA_NO_NODE
;
2534 unsigned int nr_reclaimed
= 0;
2535 LIST_HEAD(node_page_list
);
2536 struct reclaim_stat dummy_stat
;
2538 unsigned int noreclaim_flag
;
2539 struct scan_control sc
= {
2540 .gfp_mask
= GFP_KERNEL
,
2547 noreclaim_flag
= memalloc_noreclaim_save();
2549 while (!list_empty(page_list
)) {
2550 page
= lru_to_page(page_list
);
2551 if (nid
== NUMA_NO_NODE
) {
2552 nid
= page_to_nid(page
);
2553 INIT_LIST_HEAD(&node_page_list
);
2556 if (nid
== page_to_nid(page
)) {
2557 ClearPageActive(page
);
2558 list_move(&page
->lru
, &node_page_list
);
2562 nr_reclaimed
+= shrink_page_list(&node_page_list
,
2564 &sc
, &dummy_stat
, false);
2565 while (!list_empty(&node_page_list
)) {
2566 page
= lru_to_page(&node_page_list
);
2567 list_del(&page
->lru
);
2568 putback_lru_page(page
);
2574 if (!list_empty(&node_page_list
)) {
2575 nr_reclaimed
+= shrink_page_list(&node_page_list
,
2577 &sc
, &dummy_stat
, false);
2578 while (!list_empty(&node_page_list
)) {
2579 page
= lru_to_page(&node_page_list
);
2580 list_del(&page
->lru
);
2581 putback_lru_page(page
);
2585 memalloc_noreclaim_restore(noreclaim_flag
);
2587 return nr_reclaimed
;
2590 static unsigned long shrink_list(enum lru_list lru
, unsigned long nr_to_scan
,
2591 struct lruvec
*lruvec
, struct scan_control
*sc
)
2593 if (is_active_lru(lru
)) {
2594 if (sc
->may_deactivate
& (1 << is_file_lru(lru
)))
2595 shrink_active_list(nr_to_scan
, lruvec
, sc
, lru
);
2597 sc
->skipped_deactivate
= 1;
2601 return shrink_inactive_list(nr_to_scan
, lruvec
, sc
, lru
);
2605 * The inactive anon list should be small enough that the VM never has
2606 * to do too much work.
2608 * The inactive file list should be small enough to leave most memory
2609 * to the established workingset on the scan-resistant active list,
2610 * but large enough to avoid thrashing the aggregate readahead window.
2612 * Both inactive lists should also be large enough that each inactive
2613 * page has a chance to be referenced again before it is reclaimed.
2615 * If that fails and refaulting is observed, the inactive list grows.
2617 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2618 * on this LRU, maintained by the pageout code. An inactive_ratio
2619 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2622 * memory ratio inactive
2623 * -------------------------------------
2632 static bool inactive_is_low(struct lruvec
*lruvec
, enum lru_list inactive_lru
)
2634 enum lru_list active_lru
= inactive_lru
+ LRU_ACTIVE
;
2635 unsigned long inactive
, active
;
2636 unsigned long inactive_ratio
;
2639 inactive
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ inactive_lru
);
2640 active
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ active_lru
);
2642 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
2644 inactive_ratio
= int_sqrt(10 * gb
);
2648 return inactive
* inactive_ratio
< active
;
2659 * Determine how aggressively the anon and file LRU lists should be
2662 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2663 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2665 static void get_scan_count(struct lruvec
*lruvec
, struct scan_control
*sc
,
2668 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2669 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2670 unsigned long anon_cost
, file_cost
, total_cost
;
2671 int swappiness
= mem_cgroup_swappiness(memcg
);
2672 u64 fraction
[ANON_AND_FILE
];
2673 u64 denominator
= 0; /* gcc */
2674 enum scan_balance scan_balance
;
2675 unsigned long ap
, fp
;
2678 /* If we have no swap space, do not bother scanning anon pages. */
2679 if (!sc
->may_swap
|| !can_reclaim_anon_pages(memcg
, pgdat
->node_id
, sc
)) {
2680 scan_balance
= SCAN_FILE
;
2685 * Global reclaim will swap to prevent OOM even with no
2686 * swappiness, but memcg users want to use this knob to
2687 * disable swapping for individual groups completely when
2688 * using the memory controller's swap limit feature would be
2691 if (cgroup_reclaim(sc
) && !swappiness
) {
2692 scan_balance
= SCAN_FILE
;
2697 * Do not apply any pressure balancing cleverness when the
2698 * system is close to OOM, scan both anon and file equally
2699 * (unless the swappiness setting disagrees with swapping).
2701 if (!sc
->priority
&& swappiness
) {
2702 scan_balance
= SCAN_EQUAL
;
2707 * If the system is almost out of file pages, force-scan anon.
2709 if (sc
->file_is_tiny
) {
2710 scan_balance
= SCAN_ANON
;
2715 * If there is enough inactive page cache, we do not reclaim
2716 * anything from the anonymous working right now.
2718 if (sc
->cache_trim_mode
) {
2719 scan_balance
= SCAN_FILE
;
2723 scan_balance
= SCAN_FRACT
;
2725 * Calculate the pressure balance between anon and file pages.
2727 * The amount of pressure we put on each LRU is inversely
2728 * proportional to the cost of reclaiming each list, as
2729 * determined by the share of pages that are refaulting, times
2730 * the relative IO cost of bringing back a swapped out
2731 * anonymous page vs reloading a filesystem page (swappiness).
2733 * Although we limit that influence to ensure no list gets
2734 * left behind completely: at least a third of the pressure is
2735 * applied, before swappiness.
2737 * With swappiness at 100, anon and file have equal IO cost.
2739 total_cost
= sc
->anon_cost
+ sc
->file_cost
;
2740 anon_cost
= total_cost
+ sc
->anon_cost
;
2741 file_cost
= total_cost
+ sc
->file_cost
;
2742 total_cost
= anon_cost
+ file_cost
;
2744 ap
= swappiness
* (total_cost
+ 1);
2745 ap
/= anon_cost
+ 1;
2747 fp
= (200 - swappiness
) * (total_cost
+ 1);
2748 fp
/= file_cost
+ 1;
2752 denominator
= ap
+ fp
;
2754 for_each_evictable_lru(lru
) {
2755 int file
= is_file_lru(lru
);
2756 unsigned long lruvec_size
;
2757 unsigned long low
, min
;
2760 lruvec_size
= lruvec_lru_size(lruvec
, lru
, sc
->reclaim_idx
);
2761 mem_cgroup_protection(sc
->target_mem_cgroup
, memcg
,
2766 * Scale a cgroup's reclaim pressure by proportioning
2767 * its current usage to its memory.low or memory.min
2770 * This is important, as otherwise scanning aggression
2771 * becomes extremely binary -- from nothing as we
2772 * approach the memory protection threshold, to totally
2773 * nominal as we exceed it. This results in requiring
2774 * setting extremely liberal protection thresholds. It
2775 * also means we simply get no protection at all if we
2776 * set it too low, which is not ideal.
2778 * If there is any protection in place, we reduce scan
2779 * pressure by how much of the total memory used is
2780 * within protection thresholds.
2782 * There is one special case: in the first reclaim pass,
2783 * we skip over all groups that are within their low
2784 * protection. If that fails to reclaim enough pages to
2785 * satisfy the reclaim goal, we come back and override
2786 * the best-effort low protection. However, we still
2787 * ideally want to honor how well-behaved groups are in
2788 * that case instead of simply punishing them all
2789 * equally. As such, we reclaim them based on how much
2790 * memory they are using, reducing the scan pressure
2791 * again by how much of the total memory used is under
2794 unsigned long cgroup_size
= mem_cgroup_size(memcg
);
2795 unsigned long protection
;
2797 /* memory.low scaling, make sure we retry before OOM */
2798 if (!sc
->memcg_low_reclaim
&& low
> min
) {
2800 sc
->memcg_low_skipped
= 1;
2805 /* Avoid TOCTOU with earlier protection check */
2806 cgroup_size
= max(cgroup_size
, protection
);
2808 scan
= lruvec_size
- lruvec_size
* protection
/
2812 * Minimally target SWAP_CLUSTER_MAX pages to keep
2813 * reclaim moving forwards, avoiding decrementing
2814 * sc->priority further than desirable.
2816 scan
= max(scan
, SWAP_CLUSTER_MAX
);
2821 scan
>>= sc
->priority
;
2824 * If the cgroup's already been deleted, make sure to
2825 * scrape out the remaining cache.
2827 if (!scan
&& !mem_cgroup_online(memcg
))
2828 scan
= min(lruvec_size
, SWAP_CLUSTER_MAX
);
2830 switch (scan_balance
) {
2832 /* Scan lists relative to size */
2836 * Scan types proportional to swappiness and
2837 * their relative recent reclaim efficiency.
2838 * Make sure we don't miss the last page on
2839 * the offlined memory cgroups because of a
2842 scan
= mem_cgroup_online(memcg
) ?
2843 div64_u64(scan
* fraction
[file
], denominator
) :
2844 DIV64_U64_ROUND_UP(scan
* fraction
[file
],
2849 /* Scan one type exclusively */
2850 if ((scan_balance
== SCAN_FILE
) != file
)
2854 /* Look ma, no brain */
2863 * Anonymous LRU management is a waste if there is
2864 * ultimately no way to reclaim the memory.
2866 static bool can_age_anon_pages(struct pglist_data
*pgdat
,
2867 struct scan_control
*sc
)
2869 /* Aging the anon LRU is valuable if swap is present: */
2870 if (total_swap_pages
> 0)
2873 /* Also valuable if anon pages can be demoted: */
2874 return can_demote(pgdat
->node_id
, sc
);
2877 static void shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
2879 unsigned long nr
[NR_LRU_LISTS
];
2880 unsigned long targets
[NR_LRU_LISTS
];
2881 unsigned long nr_to_scan
;
2883 unsigned long nr_reclaimed
= 0;
2884 unsigned long nr_to_reclaim
= sc
->nr_to_reclaim
;
2885 struct blk_plug plug
;
2888 get_scan_count(lruvec
, sc
, nr
);
2890 /* Record the original scan target for proportional adjustments later */
2891 memcpy(targets
, nr
, sizeof(nr
));
2894 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2895 * event that can occur when there is little memory pressure e.g.
2896 * multiple streaming readers/writers. Hence, we do not abort scanning
2897 * when the requested number of pages are reclaimed when scanning at
2898 * DEF_PRIORITY on the assumption that the fact we are direct
2899 * reclaiming implies that kswapd is not keeping up and it is best to
2900 * do a batch of work at once. For memcg reclaim one check is made to
2901 * abort proportional reclaim if either the file or anon lru has already
2902 * dropped to zero at the first pass.
2904 scan_adjusted
= (!cgroup_reclaim(sc
) && !current_is_kswapd() &&
2905 sc
->priority
== DEF_PRIORITY
);
2907 blk_start_plug(&plug
);
2908 while (nr
[LRU_INACTIVE_ANON
] || nr
[LRU_ACTIVE_FILE
] ||
2909 nr
[LRU_INACTIVE_FILE
]) {
2910 unsigned long nr_anon
, nr_file
, percentage
;
2911 unsigned long nr_scanned
;
2913 for_each_evictable_lru(lru
) {
2915 nr_to_scan
= min(nr
[lru
], SWAP_CLUSTER_MAX
);
2916 nr
[lru
] -= nr_to_scan
;
2918 nr_reclaimed
+= shrink_list(lru
, nr_to_scan
,
2925 if (nr_reclaimed
< nr_to_reclaim
|| scan_adjusted
)
2929 * For kswapd and memcg, reclaim at least the number of pages
2930 * requested. Ensure that the anon and file LRUs are scanned
2931 * proportionally what was requested by get_scan_count(). We
2932 * stop reclaiming one LRU and reduce the amount scanning
2933 * proportional to the original scan target.
2935 nr_file
= nr
[LRU_INACTIVE_FILE
] + nr
[LRU_ACTIVE_FILE
];
2936 nr_anon
= nr
[LRU_INACTIVE_ANON
] + nr
[LRU_ACTIVE_ANON
];
2939 * It's just vindictive to attack the larger once the smaller
2940 * has gone to zero. And given the way we stop scanning the
2941 * smaller below, this makes sure that we only make one nudge
2942 * towards proportionality once we've got nr_to_reclaim.
2944 if (!nr_file
|| !nr_anon
)
2947 if (nr_file
> nr_anon
) {
2948 unsigned long scan_target
= targets
[LRU_INACTIVE_ANON
] +
2949 targets
[LRU_ACTIVE_ANON
] + 1;
2951 percentage
= nr_anon
* 100 / scan_target
;
2953 unsigned long scan_target
= targets
[LRU_INACTIVE_FILE
] +
2954 targets
[LRU_ACTIVE_FILE
] + 1;
2956 percentage
= nr_file
* 100 / scan_target
;
2959 /* Stop scanning the smaller of the LRU */
2961 nr
[lru
+ LRU_ACTIVE
] = 0;
2964 * Recalculate the other LRU scan count based on its original
2965 * scan target and the percentage scanning already complete
2967 lru
= (lru
== LRU_FILE
) ? LRU_BASE
: LRU_FILE
;
2968 nr_scanned
= targets
[lru
] - nr
[lru
];
2969 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
2970 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
2973 nr_scanned
= targets
[lru
] - nr
[lru
];
2974 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
2975 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
2977 scan_adjusted
= true;
2979 blk_finish_plug(&plug
);
2980 sc
->nr_reclaimed
+= nr_reclaimed
;
2983 * Even if we did not try to evict anon pages at all, we want to
2984 * rebalance the anon lru active/inactive ratio.
2986 if (can_age_anon_pages(lruvec_pgdat(lruvec
), sc
) &&
2987 inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
2988 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
2989 sc
, LRU_ACTIVE_ANON
);
2992 /* Use reclaim/compaction for costly allocs or under memory pressure */
2993 static bool in_reclaim_compaction(struct scan_control
*sc
)
2995 if (IS_ENABLED(CONFIG_COMPACTION
) && sc
->order
&&
2996 (sc
->order
> PAGE_ALLOC_COSTLY_ORDER
||
2997 sc
->priority
< DEF_PRIORITY
- 2))
3004 * Reclaim/compaction is used for high-order allocation requests. It reclaims
3005 * order-0 pages before compacting the zone. should_continue_reclaim() returns
3006 * true if more pages should be reclaimed such that when the page allocator
3007 * calls try_to_compact_pages() that it will have enough free pages to succeed.
3008 * It will give up earlier than that if there is difficulty reclaiming pages.
3010 static inline bool should_continue_reclaim(struct pglist_data
*pgdat
,
3011 unsigned long nr_reclaimed
,
3012 struct scan_control
*sc
)
3014 unsigned long pages_for_compaction
;
3015 unsigned long inactive_lru_pages
;
3018 /* If not in reclaim/compaction mode, stop */
3019 if (!in_reclaim_compaction(sc
))
3023 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
3024 * number of pages that were scanned. This will return to the caller
3025 * with the risk reclaim/compaction and the resulting allocation attempt
3026 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
3027 * allocations through requiring that the full LRU list has been scanned
3028 * first, by assuming that zero delta of sc->nr_scanned means full LRU
3029 * scan, but that approximation was wrong, and there were corner cases
3030 * where always a non-zero amount of pages were scanned.
3035 /* If compaction would go ahead or the allocation would succeed, stop */
3036 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
3037 struct zone
*zone
= &pgdat
->node_zones
[z
];
3038 if (!managed_zone(zone
))
3041 switch (compaction_suitable(zone
, sc
->order
, 0, sc
->reclaim_idx
)) {
3042 case COMPACT_SUCCESS
:
3043 case COMPACT_CONTINUE
:
3046 /* check next zone */
3052 * If we have not reclaimed enough pages for compaction and the
3053 * inactive lists are large enough, continue reclaiming
3055 pages_for_compaction
= compact_gap(sc
->order
);
3056 inactive_lru_pages
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
3057 if (can_reclaim_anon_pages(NULL
, pgdat
->node_id
, sc
))
3058 inactive_lru_pages
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
3060 return inactive_lru_pages
> pages_for_compaction
;
3063 static void shrink_node_memcgs(pg_data_t
*pgdat
, struct scan_control
*sc
)
3065 struct mem_cgroup
*target_memcg
= sc
->target_mem_cgroup
;
3066 struct mem_cgroup
*memcg
;
3068 memcg
= mem_cgroup_iter(target_memcg
, NULL
, NULL
);
3070 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
3071 unsigned long reclaimed
;
3072 unsigned long scanned
;
3075 * This loop can become CPU-bound when target memcgs
3076 * aren't eligible for reclaim - either because they
3077 * don't have any reclaimable pages, or because their
3078 * memory is explicitly protected. Avoid soft lockups.
3082 mem_cgroup_calculate_protection(target_memcg
, memcg
);
3084 if (mem_cgroup_below_min(memcg
)) {
3087 * If there is no reclaimable memory, OOM.
3090 } else if (mem_cgroup_below_low(memcg
)) {
3093 * Respect the protection only as long as
3094 * there is an unprotected supply
3095 * of reclaimable memory from other cgroups.
3097 if (!sc
->memcg_low_reclaim
) {
3098 sc
->memcg_low_skipped
= 1;
3101 memcg_memory_event(memcg
, MEMCG_LOW
);
3104 reclaimed
= sc
->nr_reclaimed
;
3105 scanned
= sc
->nr_scanned
;
3107 shrink_lruvec(lruvec
, sc
);
3109 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
,
3112 /* Record the group's reclaim efficiency */
3113 vmpressure(sc
->gfp_mask
, memcg
, false,
3114 sc
->nr_scanned
- scanned
,
3115 sc
->nr_reclaimed
- reclaimed
);
3117 } while ((memcg
= mem_cgroup_iter(target_memcg
, memcg
, NULL
)));
3120 static void shrink_node(pg_data_t
*pgdat
, struct scan_control
*sc
)
3122 struct reclaim_state
*reclaim_state
= current
->reclaim_state
;
3123 unsigned long nr_reclaimed
, nr_scanned
;
3124 struct lruvec
*target_lruvec
;
3125 bool reclaimable
= false;
3128 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
3132 * Flush the memory cgroup stats, so that we read accurate per-memcg
3133 * lruvec stats for heuristics.
3135 mem_cgroup_flush_stats();
3137 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
3139 nr_reclaimed
= sc
->nr_reclaimed
;
3140 nr_scanned
= sc
->nr_scanned
;
3143 * Determine the scan balance between anon and file LRUs.
3145 spin_lock_irq(&target_lruvec
->lru_lock
);
3146 sc
->anon_cost
= target_lruvec
->anon_cost
;
3147 sc
->file_cost
= target_lruvec
->file_cost
;
3148 spin_unlock_irq(&target_lruvec
->lru_lock
);
3151 * Target desirable inactive:active list ratios for the anon
3152 * and file LRU lists.
3154 if (!sc
->force_deactivate
) {
3155 unsigned long refaults
;
3157 refaults
= lruvec_page_state(target_lruvec
,
3158 WORKINGSET_ACTIVATE_ANON
);
3159 if (refaults
!= target_lruvec
->refaults
[0] ||
3160 inactive_is_low(target_lruvec
, LRU_INACTIVE_ANON
))
3161 sc
->may_deactivate
|= DEACTIVATE_ANON
;
3163 sc
->may_deactivate
&= ~DEACTIVATE_ANON
;
3166 * When refaults are being observed, it means a new
3167 * workingset is being established. Deactivate to get
3168 * rid of any stale active pages quickly.
3170 refaults
= lruvec_page_state(target_lruvec
,
3171 WORKINGSET_ACTIVATE_FILE
);
3172 if (refaults
!= target_lruvec
->refaults
[1] ||
3173 inactive_is_low(target_lruvec
, LRU_INACTIVE_FILE
))
3174 sc
->may_deactivate
|= DEACTIVATE_FILE
;
3176 sc
->may_deactivate
&= ~DEACTIVATE_FILE
;
3178 sc
->may_deactivate
= DEACTIVATE_ANON
| DEACTIVATE_FILE
;
3181 * If we have plenty of inactive file pages that aren't
3182 * thrashing, try to reclaim those first before touching
3185 file
= lruvec_page_state(target_lruvec
, NR_INACTIVE_FILE
);
3186 if (file
>> sc
->priority
&& !(sc
->may_deactivate
& DEACTIVATE_FILE
))
3187 sc
->cache_trim_mode
= 1;
3189 sc
->cache_trim_mode
= 0;
3192 * Prevent the reclaimer from falling into the cache trap: as
3193 * cache pages start out inactive, every cache fault will tip
3194 * the scan balance towards the file LRU. And as the file LRU
3195 * shrinks, so does the window for rotation from references.
3196 * This means we have a runaway feedback loop where a tiny
3197 * thrashing file LRU becomes infinitely more attractive than
3198 * anon pages. Try to detect this based on file LRU size.
3200 if (!cgroup_reclaim(sc
)) {
3201 unsigned long total_high_wmark
= 0;
3202 unsigned long free
, anon
;
3205 free
= sum_zone_node_page_state(pgdat
->node_id
, NR_FREE_PAGES
);
3206 file
= node_page_state(pgdat
, NR_ACTIVE_FILE
) +
3207 node_page_state(pgdat
, NR_INACTIVE_FILE
);
3209 for (z
= 0; z
< MAX_NR_ZONES
; z
++) {
3210 struct zone
*zone
= &pgdat
->node_zones
[z
];
3211 if (!managed_zone(zone
))
3214 total_high_wmark
+= high_wmark_pages(zone
);
3218 * Consider anon: if that's low too, this isn't a
3219 * runaway file reclaim problem, but rather just
3220 * extreme pressure. Reclaim as per usual then.
3222 anon
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
3225 file
+ free
<= total_high_wmark
&&
3226 !(sc
->may_deactivate
& DEACTIVATE_ANON
) &&
3227 anon
>> sc
->priority
;
3230 shrink_node_memcgs(pgdat
, sc
);
3232 if (reclaim_state
) {
3233 sc
->nr_reclaimed
+= reclaim_state
->reclaimed_slab
;
3234 reclaim_state
->reclaimed_slab
= 0;
3237 /* Record the subtree's reclaim efficiency */
3238 vmpressure(sc
->gfp_mask
, sc
->target_mem_cgroup
, true,
3239 sc
->nr_scanned
- nr_scanned
,
3240 sc
->nr_reclaimed
- nr_reclaimed
);
3242 if (sc
->nr_reclaimed
- nr_reclaimed
)
3245 if (current_is_kswapd()) {
3247 * If reclaim is isolating dirty pages under writeback,
3248 * it implies that the long-lived page allocation rate
3249 * is exceeding the page laundering rate. Either the
3250 * global limits are not being effective at throttling
3251 * processes due to the page distribution throughout
3252 * zones or there is heavy usage of a slow backing
3253 * device. The only option is to throttle from reclaim
3254 * context which is not ideal as there is no guarantee
3255 * the dirtying process is throttled in the same way
3256 * balance_dirty_pages() manages.
3258 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3259 * count the number of pages under pages flagged for
3260 * immediate reclaim and stall if any are encountered
3261 * in the nr_immediate check below.
3263 if (sc
->nr
.writeback
&& sc
->nr
.writeback
== sc
->nr
.taken
)
3264 set_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
3266 /* Allow kswapd to start writing pages during reclaim.*/
3267 if (sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
3268 set_bit(PGDAT_DIRTY
, &pgdat
->flags
);
3271 * If kswapd scans pages marked for immediate
3272 * reclaim and under writeback (nr_immediate), it
3273 * implies that pages are cycling through the LRU
3274 * faster than they are written so forcibly stall
3275 * until some pages complete writeback.
3277 if (sc
->nr
.immediate
)
3278 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_WRITEBACK
);
3282 * Tag a node/memcg as congested if all the dirty pages were marked
3283 * for writeback and immediate reclaim (counted in nr.congested).
3285 * Legacy memcg will stall in page writeback so avoid forcibly
3286 * stalling in reclaim_throttle().
3288 if ((current_is_kswapd() ||
3289 (cgroup_reclaim(sc
) && writeback_throttling_sane(sc
))) &&
3290 sc
->nr
.dirty
&& sc
->nr
.dirty
== sc
->nr
.congested
)
3291 set_bit(LRUVEC_CONGESTED
, &target_lruvec
->flags
);
3294 * Stall direct reclaim for IO completions if the lruvec is
3295 * node is congested. Allow kswapd to continue until it
3296 * starts encountering unqueued dirty pages or cycling through
3297 * the LRU too quickly.
3299 if (!current_is_kswapd() && current_may_throttle() &&
3300 !sc
->hibernation_mode
&&
3301 test_bit(LRUVEC_CONGESTED
, &target_lruvec
->flags
))
3302 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_CONGESTED
);
3304 if (should_continue_reclaim(pgdat
, sc
->nr_reclaimed
- nr_reclaimed
,
3309 * Kswapd gives up on balancing particular nodes after too
3310 * many failures to reclaim anything from them and goes to
3311 * sleep. On reclaim progress, reset the failure counter. A
3312 * successful direct reclaim run will revive a dormant kswapd.
3315 pgdat
->kswapd_failures
= 0;
3319 * Returns true if compaction should go ahead for a costly-order request, or
3320 * the allocation would already succeed without compaction. Return false if we
3321 * should reclaim first.
3323 static inline bool compaction_ready(struct zone
*zone
, struct scan_control
*sc
)
3325 unsigned long watermark
;
3326 enum compact_result suitable
;
3328 suitable
= compaction_suitable(zone
, sc
->order
, 0, sc
->reclaim_idx
);
3329 if (suitable
== COMPACT_SUCCESS
)
3330 /* Allocation should succeed already. Don't reclaim. */
3332 if (suitable
== COMPACT_SKIPPED
)
3333 /* Compaction cannot yet proceed. Do reclaim. */
3337 * Compaction is already possible, but it takes time to run and there
3338 * are potentially other callers using the pages just freed. So proceed
3339 * with reclaim to make a buffer of free pages available to give
3340 * compaction a reasonable chance of completing and allocating the page.
3341 * Note that we won't actually reclaim the whole buffer in one attempt
3342 * as the target watermark in should_continue_reclaim() is lower. But if
3343 * we are already above the high+gap watermark, don't reclaim at all.
3345 watermark
= high_wmark_pages(zone
) + compact_gap(sc
->order
);
3347 return zone_watermark_ok_safe(zone
, 0, watermark
, sc
->reclaim_idx
);
3350 static void consider_reclaim_throttle(pg_data_t
*pgdat
, struct scan_control
*sc
)
3353 * If reclaim is making progress greater than 12% efficiency then
3354 * wake all the NOPROGRESS throttled tasks.
3356 if (sc
->nr_reclaimed
> (sc
->nr_scanned
>> 3)) {
3357 wait_queue_head_t
*wqh
;
3359 wqh
= &pgdat
->reclaim_wait
[VMSCAN_THROTTLE_NOPROGRESS
];
3360 if (waitqueue_active(wqh
))
3367 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
3368 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
3369 * under writeback and marked for immediate reclaim at the tail of the
3372 if (current_is_kswapd() || cgroup_reclaim(sc
))
3375 /* Throttle if making no progress at high prioities. */
3376 if (sc
->priority
== 1 && !sc
->nr_reclaimed
)
3377 reclaim_throttle(pgdat
, VMSCAN_THROTTLE_NOPROGRESS
);
3381 * This is the direct reclaim path, for page-allocating processes. We only
3382 * try to reclaim pages from zones which will satisfy the caller's allocation
3385 * If a zone is deemed to be full of pinned pages then just give it a light
3386 * scan then give up on it.
3388 static void shrink_zones(struct zonelist
*zonelist
, struct scan_control
*sc
)
3392 unsigned long nr_soft_reclaimed
;
3393 unsigned long nr_soft_scanned
;
3395 pg_data_t
*last_pgdat
= NULL
;
3396 pg_data_t
*first_pgdat
= NULL
;
3399 * If the number of buffer_heads in the machine exceeds the maximum
3400 * allowed level, force direct reclaim to scan the highmem zone as
3401 * highmem pages could be pinning lowmem pages storing buffer_heads
3403 orig_mask
= sc
->gfp_mask
;
3404 if (buffer_heads_over_limit
) {
3405 sc
->gfp_mask
|= __GFP_HIGHMEM
;
3406 sc
->reclaim_idx
= gfp_zone(sc
->gfp_mask
);
3409 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
3410 sc
->reclaim_idx
, sc
->nodemask
) {
3412 * Take care memory controller reclaiming has small influence
3415 if (!cgroup_reclaim(sc
)) {
3416 if (!cpuset_zone_allowed(zone
,
3417 GFP_KERNEL
| __GFP_HARDWALL
))
3421 * If we already have plenty of memory free for
3422 * compaction in this zone, don't free any more.
3423 * Even though compaction is invoked for any
3424 * non-zero order, only frequent costly order
3425 * reclamation is disruptive enough to become a
3426 * noticeable problem, like transparent huge
3429 if (IS_ENABLED(CONFIG_COMPACTION
) &&
3430 sc
->order
> PAGE_ALLOC_COSTLY_ORDER
&&
3431 compaction_ready(zone
, sc
)) {
3432 sc
->compaction_ready
= true;
3437 * Shrink each node in the zonelist once. If the
3438 * zonelist is ordered by zone (not the default) then a
3439 * node may be shrunk multiple times but in that case
3440 * the user prefers lower zones being preserved.
3442 if (zone
->zone_pgdat
== last_pgdat
)
3446 * This steals pages from memory cgroups over softlimit
3447 * and returns the number of reclaimed pages and
3448 * scanned pages. This works for global memory pressure
3449 * and balancing, not for a memcg's limit.
3451 nr_soft_scanned
= 0;
3452 nr_soft_reclaimed
= mem_cgroup_soft_limit_reclaim(zone
->zone_pgdat
,
3453 sc
->order
, sc
->gfp_mask
,
3455 sc
->nr_reclaimed
+= nr_soft_reclaimed
;
3456 sc
->nr_scanned
+= nr_soft_scanned
;
3457 /* need some check for avoid more shrink_zone() */
3461 first_pgdat
= zone
->zone_pgdat
;
3463 /* See comment about same check for global reclaim above */
3464 if (zone
->zone_pgdat
== last_pgdat
)
3466 last_pgdat
= zone
->zone_pgdat
;
3467 shrink_node(zone
->zone_pgdat
, sc
);
3471 consider_reclaim_throttle(first_pgdat
, sc
);
3474 * Restore to original mask to avoid the impact on the caller if we
3475 * promoted it to __GFP_HIGHMEM.
3477 sc
->gfp_mask
= orig_mask
;
3480 static void snapshot_refaults(struct mem_cgroup
*target_memcg
, pg_data_t
*pgdat
)
3482 struct lruvec
*target_lruvec
;
3483 unsigned long refaults
;
3485 target_lruvec
= mem_cgroup_lruvec(target_memcg
, pgdat
);
3486 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_ANON
);
3487 target_lruvec
->refaults
[0] = refaults
;
3488 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_FILE
);
3489 target_lruvec
->refaults
[1] = refaults
;
3493 * This is the main entry point to direct page reclaim.
3495 * If a full scan of the inactive list fails to free enough memory then we
3496 * are "out of memory" and something needs to be killed.
3498 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3499 * high - the zone may be full of dirty or under-writeback pages, which this
3500 * caller can't do much about. We kick the writeback threads and take explicit
3501 * naps in the hope that some of these pages can be written. But if the
3502 * allocating task holds filesystem locks which prevent writeout this might not
3503 * work, and the allocation attempt will fail.
3505 * returns: 0, if no pages reclaimed
3506 * else, the number of pages reclaimed
3508 static unsigned long do_try_to_free_pages(struct zonelist
*zonelist
,
3509 struct scan_control
*sc
)
3511 int initial_priority
= sc
->priority
;
3512 pg_data_t
*last_pgdat
;
3516 delayacct_freepages_start();
3518 if (!cgroup_reclaim(sc
))
3519 __count_zid_vm_events(ALLOCSTALL
, sc
->reclaim_idx
, 1);
3522 vmpressure_prio(sc
->gfp_mask
, sc
->target_mem_cgroup
,
3525 shrink_zones(zonelist
, sc
);
3527 if (sc
->nr_reclaimed
>= sc
->nr_to_reclaim
)
3530 if (sc
->compaction_ready
)
3534 * If we're getting trouble reclaiming, start doing
3535 * writepage even in laptop mode.
3537 if (sc
->priority
< DEF_PRIORITY
- 2)
3538 sc
->may_writepage
= 1;
3539 } while (--sc
->priority
>= 0);
3542 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
, sc
->reclaim_idx
,
3544 if (zone
->zone_pgdat
== last_pgdat
)
3546 last_pgdat
= zone
->zone_pgdat
;
3548 snapshot_refaults(sc
->target_mem_cgroup
, zone
->zone_pgdat
);
3550 if (cgroup_reclaim(sc
)) {
3551 struct lruvec
*lruvec
;
3553 lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
,
3555 clear_bit(LRUVEC_CONGESTED
, &lruvec
->flags
);
3559 delayacct_freepages_end();
3561 if (sc
->nr_reclaimed
)
3562 return sc
->nr_reclaimed
;
3564 /* Aborted reclaim to try compaction? don't OOM, then */
3565 if (sc
->compaction_ready
)
3569 * We make inactive:active ratio decisions based on the node's
3570 * composition of memory, but a restrictive reclaim_idx or a
3571 * memory.low cgroup setting can exempt large amounts of
3572 * memory from reclaim. Neither of which are very common, so
3573 * instead of doing costly eligibility calculations of the
3574 * entire cgroup subtree up front, we assume the estimates are
3575 * good, and retry with forcible deactivation if that fails.
3577 if (sc
->skipped_deactivate
) {
3578 sc
->priority
= initial_priority
;
3579 sc
->force_deactivate
= 1;
3580 sc
->skipped_deactivate
= 0;
3584 /* Untapped cgroup reserves? Don't OOM, retry. */
3585 if (sc
->memcg_low_skipped
) {
3586 sc
->priority
= initial_priority
;
3587 sc
->force_deactivate
= 0;
3588 sc
->memcg_low_reclaim
= 1;
3589 sc
->memcg_low_skipped
= 0;
3596 static bool allow_direct_reclaim(pg_data_t
*pgdat
)
3599 unsigned long pfmemalloc_reserve
= 0;
3600 unsigned long free_pages
= 0;
3604 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
3607 for (i
= 0; i
<= ZONE_NORMAL
; i
++) {
3608 zone
= &pgdat
->node_zones
[i
];
3609 if (!managed_zone(zone
))
3612 if (!zone_reclaimable_pages(zone
))
3615 pfmemalloc_reserve
+= min_wmark_pages(zone
);
3616 free_pages
+= zone_page_state(zone
, NR_FREE_PAGES
);
3619 /* If there are no reserves (unexpected config) then do not throttle */
3620 if (!pfmemalloc_reserve
)
3623 wmark_ok
= free_pages
> pfmemalloc_reserve
/ 2;
3625 /* kswapd must be awake if processes are being throttled */
3626 if (!wmark_ok
&& waitqueue_active(&pgdat
->kswapd_wait
)) {
3627 if (READ_ONCE(pgdat
->kswapd_highest_zoneidx
) > ZONE_NORMAL
)
3628 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, ZONE_NORMAL
);
3630 wake_up_interruptible(&pgdat
->kswapd_wait
);
3637 * Throttle direct reclaimers if backing storage is backed by the network
3638 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3639 * depleted. kswapd will continue to make progress and wake the processes
3640 * when the low watermark is reached.
3642 * Returns true if a fatal signal was delivered during throttling. If this
3643 * happens, the page allocator should not consider triggering the OOM killer.
3645 static bool throttle_direct_reclaim(gfp_t gfp_mask
, struct zonelist
*zonelist
,
3646 nodemask_t
*nodemask
)
3650 pg_data_t
*pgdat
= NULL
;
3653 * Kernel threads should not be throttled as they may be indirectly
3654 * responsible for cleaning pages necessary for reclaim to make forward
3655 * progress. kjournald for example may enter direct reclaim while
3656 * committing a transaction where throttling it could forcing other
3657 * processes to block on log_wait_commit().
3659 if (current
->flags
& PF_KTHREAD
)
3663 * If a fatal signal is pending, this process should not throttle.
3664 * It should return quickly so it can exit and free its memory
3666 if (fatal_signal_pending(current
))
3670 * Check if the pfmemalloc reserves are ok by finding the first node
3671 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3672 * GFP_KERNEL will be required for allocating network buffers when
3673 * swapping over the network so ZONE_HIGHMEM is unusable.
3675 * Throttling is based on the first usable node and throttled processes
3676 * wait on a queue until kswapd makes progress and wakes them. There
3677 * is an affinity then between processes waking up and where reclaim
3678 * progress has been made assuming the process wakes on the same node.
3679 * More importantly, processes running on remote nodes will not compete
3680 * for remote pfmemalloc reserves and processes on different nodes
3681 * should make reasonable progress.
3683 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
3684 gfp_zone(gfp_mask
), nodemask
) {
3685 if (zone_idx(zone
) > ZONE_NORMAL
)
3688 /* Throttle based on the first usable node */
3689 pgdat
= zone
->zone_pgdat
;
3690 if (allow_direct_reclaim(pgdat
))
3695 /* If no zone was usable by the allocation flags then do not throttle */
3699 /* Account for the throttling */
3700 count_vm_event(PGSCAN_DIRECT_THROTTLE
);
3703 * If the caller cannot enter the filesystem, it's possible that it
3704 * is due to the caller holding an FS lock or performing a journal
3705 * transaction in the case of a filesystem like ext[3|4]. In this case,
3706 * it is not safe to block on pfmemalloc_wait as kswapd could be
3707 * blocked waiting on the same lock. Instead, throttle for up to a
3708 * second before continuing.
3710 if (!(gfp_mask
& __GFP_FS
))
3711 wait_event_interruptible_timeout(pgdat
->pfmemalloc_wait
,
3712 allow_direct_reclaim(pgdat
), HZ
);
3714 /* Throttle until kswapd wakes the process */
3715 wait_event_killable(zone
->zone_pgdat
->pfmemalloc_wait
,
3716 allow_direct_reclaim(pgdat
));
3718 if (fatal_signal_pending(current
))
3725 unsigned long try_to_free_pages(struct zonelist
*zonelist
, int order
,
3726 gfp_t gfp_mask
, nodemask_t
*nodemask
)
3728 unsigned long nr_reclaimed
;
3729 struct scan_control sc
= {
3730 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
3731 .gfp_mask
= current_gfp_context(gfp_mask
),
3732 .reclaim_idx
= gfp_zone(gfp_mask
),
3734 .nodemask
= nodemask
,
3735 .priority
= DEF_PRIORITY
,
3736 .may_writepage
= !laptop_mode
,
3742 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3743 * Confirm they are large enough for max values.
3745 BUILD_BUG_ON(MAX_ORDER
> S8_MAX
);
3746 BUILD_BUG_ON(DEF_PRIORITY
> S8_MAX
);
3747 BUILD_BUG_ON(MAX_NR_ZONES
> S8_MAX
);
3750 * Do not enter reclaim if fatal signal was delivered while throttled.
3751 * 1 is returned so that the page allocator does not OOM kill at this
3754 if (throttle_direct_reclaim(sc
.gfp_mask
, zonelist
, nodemask
))
3757 set_task_reclaim_state(current
, &sc
.reclaim_state
);
3758 trace_mm_vmscan_direct_reclaim_begin(order
, sc
.gfp_mask
);
3760 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
3762 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed
);
3763 set_task_reclaim_state(current
, NULL
);
3765 return nr_reclaimed
;
3770 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3771 unsigned long mem_cgroup_shrink_node(struct mem_cgroup
*memcg
,
3772 gfp_t gfp_mask
, bool noswap
,
3774 unsigned long *nr_scanned
)
3776 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
3777 struct scan_control sc
= {
3778 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
3779 .target_mem_cgroup
= memcg
,
3780 .may_writepage
= !laptop_mode
,
3782 .reclaim_idx
= MAX_NR_ZONES
- 1,
3783 .may_swap
= !noswap
,
3786 WARN_ON_ONCE(!current
->reclaim_state
);
3788 sc
.gfp_mask
= (gfp_mask
& GFP_RECLAIM_MASK
) |
3789 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
);
3791 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc
.order
,
3795 * NOTE: Although we can get the priority field, using it
3796 * here is not a good idea, since it limits the pages we can scan.
3797 * if we don't reclaim here, the shrink_node from balance_pgdat
3798 * will pick up pages from other mem cgroup's as well. We hack
3799 * the priority and make it zero.
3801 shrink_lruvec(lruvec
, &sc
);
3803 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc
.nr_reclaimed
);
3805 *nr_scanned
= sc
.nr_scanned
;
3807 return sc
.nr_reclaimed
;
3810 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup
*memcg
,
3811 unsigned long nr_pages
,
3815 unsigned long nr_reclaimed
;
3816 unsigned int noreclaim_flag
;
3817 struct scan_control sc
= {
3818 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
3819 .gfp_mask
= (current_gfp_context(gfp_mask
) & GFP_RECLAIM_MASK
) |
3820 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
),
3821 .reclaim_idx
= MAX_NR_ZONES
- 1,
3822 .target_mem_cgroup
= memcg
,
3823 .priority
= DEF_PRIORITY
,
3824 .may_writepage
= !laptop_mode
,
3826 .may_swap
= may_swap
,
3829 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3830 * equal pressure on all the nodes. This is based on the assumption that
3831 * the reclaim does not bail out early.
3833 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
3835 set_task_reclaim_state(current
, &sc
.reclaim_state
);
3836 trace_mm_vmscan_memcg_reclaim_begin(0, sc
.gfp_mask
);
3837 noreclaim_flag
= memalloc_noreclaim_save();
3839 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
3841 memalloc_noreclaim_restore(noreclaim_flag
);
3842 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed
);
3843 set_task_reclaim_state(current
, NULL
);
3845 return nr_reclaimed
;
3849 static void age_active_anon(struct pglist_data
*pgdat
,
3850 struct scan_control
*sc
)
3852 struct mem_cgroup
*memcg
;
3853 struct lruvec
*lruvec
;
3855 if (!can_age_anon_pages(pgdat
, sc
))
3858 lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
3859 if (!inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
3862 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
3864 lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
3865 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
3866 sc
, LRU_ACTIVE_ANON
);
3867 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
3871 static bool pgdat_watermark_boosted(pg_data_t
*pgdat
, int highest_zoneidx
)
3877 * Check for watermark boosts top-down as the higher zones
3878 * are more likely to be boosted. Both watermarks and boosts
3879 * should not be checked at the same time as reclaim would
3880 * start prematurely when there is no boosting and a lower
3883 for (i
= highest_zoneidx
; i
>= 0; i
--) {
3884 zone
= pgdat
->node_zones
+ i
;
3885 if (!managed_zone(zone
))
3888 if (zone
->watermark_boost
)
3896 * Returns true if there is an eligible zone balanced for the request order
3897 * and highest_zoneidx
3899 static bool pgdat_balanced(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
3902 unsigned long mark
= -1;
3906 * Check watermarks bottom-up as lower zones are more likely to
3909 for (i
= 0; i
<= highest_zoneidx
; i
++) {
3910 zone
= pgdat
->node_zones
+ i
;
3912 if (!managed_zone(zone
))
3915 if (sysctl_numa_balancing_mode
& NUMA_BALANCING_MEMORY_TIERING
)
3916 mark
= wmark_pages(zone
, WMARK_PROMO
);
3918 mark
= high_wmark_pages(zone
);
3919 if (zone_watermark_ok_safe(zone
, order
, mark
, highest_zoneidx
))
3924 * If a node has no managed zone within highest_zoneidx, it does not
3925 * need balancing by definition. This can happen if a zone-restricted
3926 * allocation tries to wake a remote kswapd.
3934 /* Clear pgdat state for congested, dirty or under writeback. */
3935 static void clear_pgdat_congested(pg_data_t
*pgdat
)
3937 struct lruvec
*lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
3939 clear_bit(LRUVEC_CONGESTED
, &lruvec
->flags
);
3940 clear_bit(PGDAT_DIRTY
, &pgdat
->flags
);
3941 clear_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
3945 * Prepare kswapd for sleeping. This verifies that there are no processes
3946 * waiting in throttle_direct_reclaim() and that watermarks have been met.
3948 * Returns true if kswapd is ready to sleep
3950 static bool prepare_kswapd_sleep(pg_data_t
*pgdat
, int order
,
3951 int highest_zoneidx
)
3954 * The throttled processes are normally woken up in balance_pgdat() as
3955 * soon as allow_direct_reclaim() is true. But there is a potential
3956 * race between when kswapd checks the watermarks and a process gets
3957 * throttled. There is also a potential race if processes get
3958 * throttled, kswapd wakes, a large process exits thereby balancing the
3959 * zones, which causes kswapd to exit balance_pgdat() before reaching
3960 * the wake up checks. If kswapd is going to sleep, no process should
3961 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3962 * the wake up is premature, processes will wake kswapd and get
3963 * throttled again. The difference from wake ups in balance_pgdat() is
3964 * that here we are under prepare_to_wait().
3966 if (waitqueue_active(&pgdat
->pfmemalloc_wait
))
3967 wake_up_all(&pgdat
->pfmemalloc_wait
);
3969 /* Hopeless node, leave it to direct reclaim */
3970 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
3973 if (pgdat_balanced(pgdat
, order
, highest_zoneidx
)) {
3974 clear_pgdat_congested(pgdat
);
3982 * kswapd shrinks a node of pages that are at or below the highest usable
3983 * zone that is currently unbalanced.
3985 * Returns true if kswapd scanned at least the requested number of pages to
3986 * reclaim or if the lack of progress was due to pages under writeback.
3987 * This is used to determine if the scanning priority needs to be raised.
3989 static bool kswapd_shrink_node(pg_data_t
*pgdat
,
3990 struct scan_control
*sc
)
3995 /* Reclaim a number of pages proportional to the number of zones */
3996 sc
->nr_to_reclaim
= 0;
3997 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
3998 zone
= pgdat
->node_zones
+ z
;
3999 if (!managed_zone(zone
))
4002 sc
->nr_to_reclaim
+= max(high_wmark_pages(zone
), SWAP_CLUSTER_MAX
);
4006 * Historically care was taken to put equal pressure on all zones but
4007 * now pressure is applied based on node LRU order.
4009 shrink_node(pgdat
, sc
);
4012 * Fragmentation may mean that the system cannot be rebalanced for
4013 * high-order allocations. If twice the allocation size has been
4014 * reclaimed then recheck watermarks only at order-0 to prevent
4015 * excessive reclaim. Assume that a process requested a high-order
4016 * can direct reclaim/compact.
4018 if (sc
->order
&& sc
->nr_reclaimed
>= compact_gap(sc
->order
))
4021 return sc
->nr_scanned
>= sc
->nr_to_reclaim
;
4024 /* Page allocator PCP high watermark is lowered if reclaim is active. */
4026 update_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
, bool active
)
4031 for (i
= 0; i
<= highest_zoneidx
; i
++) {
4032 zone
= pgdat
->node_zones
+ i
;
4034 if (!managed_zone(zone
))
4038 set_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
4040 clear_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
4045 set_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
4047 update_reclaim_active(pgdat
, highest_zoneidx
, true);
4051 clear_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
4053 update_reclaim_active(pgdat
, highest_zoneidx
, false);
4057 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4058 * that are eligible for use by the caller until at least one zone is
4061 * Returns the order kswapd finished reclaiming at.
4063 * kswapd scans the zones in the highmem->normal->dma direction. It skips
4064 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
4065 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
4066 * or lower is eligible for reclaim until at least one usable zone is
4069 static int balance_pgdat(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
4072 unsigned long nr_soft_reclaimed
;
4073 unsigned long nr_soft_scanned
;
4074 unsigned long pflags
;
4075 unsigned long nr_boost_reclaim
;
4076 unsigned long zone_boosts
[MAX_NR_ZONES
] = { 0, };
4079 struct scan_control sc
= {
4080 .gfp_mask
= GFP_KERNEL
,
4085 set_task_reclaim_state(current
, &sc
.reclaim_state
);
4086 psi_memstall_enter(&pflags
);
4087 __fs_reclaim_acquire(_THIS_IP_
);
4089 count_vm_event(PAGEOUTRUN
);
4092 * Account for the reclaim boost. Note that the zone boost is left in
4093 * place so that parallel allocations that are near the watermark will
4094 * stall or direct reclaim until kswapd is finished.
4096 nr_boost_reclaim
= 0;
4097 for (i
= 0; i
<= highest_zoneidx
; i
++) {
4098 zone
= pgdat
->node_zones
+ i
;
4099 if (!managed_zone(zone
))
4102 nr_boost_reclaim
+= zone
->watermark_boost
;
4103 zone_boosts
[i
] = zone
->watermark_boost
;
4105 boosted
= nr_boost_reclaim
;
4108 set_reclaim_active(pgdat
, highest_zoneidx
);
4109 sc
.priority
= DEF_PRIORITY
;
4111 unsigned long nr_reclaimed
= sc
.nr_reclaimed
;
4112 bool raise_priority
= true;
4116 sc
.reclaim_idx
= highest_zoneidx
;
4119 * If the number of buffer_heads exceeds the maximum allowed
4120 * then consider reclaiming from all zones. This has a dual
4121 * purpose -- on 64-bit systems it is expected that
4122 * buffer_heads are stripped during active rotation. On 32-bit
4123 * systems, highmem pages can pin lowmem memory and shrinking
4124 * buffers can relieve lowmem pressure. Reclaim may still not
4125 * go ahead if all eligible zones for the original allocation
4126 * request are balanced to avoid excessive reclaim from kswapd.
4128 if (buffer_heads_over_limit
) {
4129 for (i
= MAX_NR_ZONES
- 1; i
>= 0; i
--) {
4130 zone
= pgdat
->node_zones
+ i
;
4131 if (!managed_zone(zone
))
4140 * If the pgdat is imbalanced then ignore boosting and preserve
4141 * the watermarks for a later time and restart. Note that the
4142 * zone watermarks will be still reset at the end of balancing
4143 * on the grounds that the normal reclaim should be enough to
4144 * re-evaluate if boosting is required when kswapd next wakes.
4146 balanced
= pgdat_balanced(pgdat
, sc
.order
, highest_zoneidx
);
4147 if (!balanced
&& nr_boost_reclaim
) {
4148 nr_boost_reclaim
= 0;
4153 * If boosting is not active then only reclaim if there are no
4154 * eligible zones. Note that sc.reclaim_idx is not used as
4155 * buffer_heads_over_limit may have adjusted it.
4157 if (!nr_boost_reclaim
&& balanced
)
4160 /* Limit the priority of boosting to avoid reclaim writeback */
4161 if (nr_boost_reclaim
&& sc
.priority
== DEF_PRIORITY
- 2)
4162 raise_priority
= false;
4165 * Do not writeback or swap pages for boosted reclaim. The
4166 * intent is to relieve pressure not issue sub-optimal IO
4167 * from reclaim context. If no pages are reclaimed, the
4168 * reclaim will be aborted.
4170 sc
.may_writepage
= !laptop_mode
&& !nr_boost_reclaim
;
4171 sc
.may_swap
= !nr_boost_reclaim
;
4174 * Do some background aging of the anon list, to give
4175 * pages a chance to be referenced before reclaiming. All
4176 * pages are rotated regardless of classzone as this is
4177 * about consistent aging.
4179 age_active_anon(pgdat
, &sc
);
4182 * If we're getting trouble reclaiming, start doing writepage
4183 * even in laptop mode.
4185 if (sc
.priority
< DEF_PRIORITY
- 2)
4186 sc
.may_writepage
= 1;
4188 /* Call soft limit reclaim before calling shrink_node. */
4190 nr_soft_scanned
= 0;
4191 nr_soft_reclaimed
= mem_cgroup_soft_limit_reclaim(pgdat
, sc
.order
,
4192 sc
.gfp_mask
, &nr_soft_scanned
);
4193 sc
.nr_reclaimed
+= nr_soft_reclaimed
;
4196 * There should be no need to raise the scanning priority if
4197 * enough pages are already being scanned that that high
4198 * watermark would be met at 100% efficiency.
4200 if (kswapd_shrink_node(pgdat
, &sc
))
4201 raise_priority
= false;
4204 * If the low watermark is met there is no need for processes
4205 * to be throttled on pfmemalloc_wait as they should not be
4206 * able to safely make forward progress. Wake them
4208 if (waitqueue_active(&pgdat
->pfmemalloc_wait
) &&
4209 allow_direct_reclaim(pgdat
))
4210 wake_up_all(&pgdat
->pfmemalloc_wait
);
4212 /* Check if kswapd should be suspending */
4213 __fs_reclaim_release(_THIS_IP_
);
4214 ret
= try_to_freeze();
4215 __fs_reclaim_acquire(_THIS_IP_
);
4216 if (ret
|| kthread_should_stop())
4220 * Raise priority if scanning rate is too low or there was no
4221 * progress in reclaiming pages
4223 nr_reclaimed
= sc
.nr_reclaimed
- nr_reclaimed
;
4224 nr_boost_reclaim
-= min(nr_boost_reclaim
, nr_reclaimed
);
4227 * If reclaim made no progress for a boost, stop reclaim as
4228 * IO cannot be queued and it could be an infinite loop in
4229 * extreme circumstances.
4231 if (nr_boost_reclaim
&& !nr_reclaimed
)
4234 if (raise_priority
|| !nr_reclaimed
)
4236 } while (sc
.priority
>= 1);
4238 if (!sc
.nr_reclaimed
)
4239 pgdat
->kswapd_failures
++;
4242 clear_reclaim_active(pgdat
, highest_zoneidx
);
4244 /* If reclaim was boosted, account for the reclaim done in this pass */
4246 unsigned long flags
;
4248 for (i
= 0; i
<= highest_zoneidx
; i
++) {
4249 if (!zone_boosts
[i
])
4252 /* Increments are under the zone lock */
4253 zone
= pgdat
->node_zones
+ i
;
4254 spin_lock_irqsave(&zone
->lock
, flags
);
4255 zone
->watermark_boost
-= min(zone
->watermark_boost
, zone_boosts
[i
]);
4256 spin_unlock_irqrestore(&zone
->lock
, flags
);
4260 * As there is now likely space, wakeup kcompact to defragment
4263 wakeup_kcompactd(pgdat
, pageblock_order
, highest_zoneidx
);
4266 snapshot_refaults(NULL
, pgdat
);
4267 __fs_reclaim_release(_THIS_IP_
);
4268 psi_memstall_leave(&pflags
);
4269 set_task_reclaim_state(current
, NULL
);
4272 * Return the order kswapd stopped reclaiming at as
4273 * prepare_kswapd_sleep() takes it into account. If another caller
4274 * entered the allocator slow path while kswapd was awake, order will
4275 * remain at the higher level.
4281 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
4282 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
4283 * not a valid index then either kswapd runs for first time or kswapd couldn't
4284 * sleep after previous reclaim attempt (node is still unbalanced). In that
4285 * case return the zone index of the previous kswapd reclaim cycle.
4287 static enum zone_type
kswapd_highest_zoneidx(pg_data_t
*pgdat
,
4288 enum zone_type prev_highest_zoneidx
)
4290 enum zone_type curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
4292 return curr_idx
== MAX_NR_ZONES
? prev_highest_zoneidx
: curr_idx
;
4295 static void kswapd_try_to_sleep(pg_data_t
*pgdat
, int alloc_order
, int reclaim_order
,
4296 unsigned int highest_zoneidx
)
4301 if (freezing(current
) || kthread_should_stop())
4304 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
4307 * Try to sleep for a short interval. Note that kcompactd will only be
4308 * woken if it is possible to sleep for a short interval. This is
4309 * deliberate on the assumption that if reclaim cannot keep an
4310 * eligible zone balanced that it's also unlikely that compaction will
4313 if (prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
4315 * Compaction records what page blocks it recently failed to
4316 * isolate pages from and skips them in the future scanning.
4317 * When kswapd is going to sleep, it is reasonable to assume
4318 * that pages and compaction may succeed so reset the cache.
4320 reset_isolation_suitable(pgdat
);
4323 * We have freed the memory, now we should compact it to make
4324 * allocation of the requested order possible.
4326 wakeup_kcompactd(pgdat
, alloc_order
, highest_zoneidx
);
4328 remaining
= schedule_timeout(HZ
/10);
4331 * If woken prematurely then reset kswapd_highest_zoneidx and
4332 * order. The values will either be from a wakeup request or
4333 * the previous request that slept prematurely.
4336 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
,
4337 kswapd_highest_zoneidx(pgdat
,
4340 if (READ_ONCE(pgdat
->kswapd_order
) < reclaim_order
)
4341 WRITE_ONCE(pgdat
->kswapd_order
, reclaim_order
);
4344 finish_wait(&pgdat
->kswapd_wait
, &wait
);
4345 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
4349 * After a short sleep, check if it was a premature sleep. If not, then
4350 * go fully to sleep until explicitly woken up.
4353 prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
4354 trace_mm_vmscan_kswapd_sleep(pgdat
->node_id
);
4357 * vmstat counters are not perfectly accurate and the estimated
4358 * value for counters such as NR_FREE_PAGES can deviate from the
4359 * true value by nr_online_cpus * threshold. To avoid the zone
4360 * watermarks being breached while under pressure, we reduce the
4361 * per-cpu vmstat threshold while kswapd is awake and restore
4362 * them before going back to sleep.
4364 set_pgdat_percpu_threshold(pgdat
, calculate_normal_threshold
);
4366 if (!kthread_should_stop())
4369 set_pgdat_percpu_threshold(pgdat
, calculate_pressure_threshold
);
4372 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY
);
4374 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY
);
4376 finish_wait(&pgdat
->kswapd_wait
, &wait
);
4380 * The background pageout daemon, started as a kernel thread
4381 * from the init process.
4383 * This basically trickles out pages so that we have _some_
4384 * free memory available even if there is no other activity
4385 * that frees anything up. This is needed for things like routing
4386 * etc, where we otherwise might have all activity going on in
4387 * asynchronous contexts that cannot page things out.
4389 * If there are applications that are active memory-allocators
4390 * (most normal use), this basically shouldn't matter.
4392 static int kswapd(void *p
)
4394 unsigned int alloc_order
, reclaim_order
;
4395 unsigned int highest_zoneidx
= MAX_NR_ZONES
- 1;
4396 pg_data_t
*pgdat
= (pg_data_t
*)p
;
4397 struct task_struct
*tsk
= current
;
4398 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
4400 if (!cpumask_empty(cpumask
))
4401 set_cpus_allowed_ptr(tsk
, cpumask
);
4404 * Tell the memory management that we're a "memory allocator",
4405 * and that if we need more memory we should get access to it
4406 * regardless (see "__alloc_pages()"). "kswapd" should
4407 * never get caught in the normal page freeing logic.
4409 * (Kswapd normally doesn't need memory anyway, but sometimes
4410 * you need a small amount of memory in order to be able to
4411 * page out something else, and this flag essentially protects
4412 * us from recursively trying to free more memory as we're
4413 * trying to free the first piece of memory in the first place).
4415 tsk
->flags
|= PF_MEMALLOC
| PF_KSWAPD
;
4418 WRITE_ONCE(pgdat
->kswapd_order
, 0);
4419 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
4420 atomic_set(&pgdat
->nr_writeback_throttled
, 0);
4424 alloc_order
= reclaim_order
= READ_ONCE(pgdat
->kswapd_order
);
4425 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
4429 kswapd_try_to_sleep(pgdat
, alloc_order
, reclaim_order
,
4432 /* Read the new order and highest_zoneidx */
4433 alloc_order
= READ_ONCE(pgdat
->kswapd_order
);
4434 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
4436 WRITE_ONCE(pgdat
->kswapd_order
, 0);
4437 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
4439 ret
= try_to_freeze();
4440 if (kthread_should_stop())
4444 * We can speed up thawing tasks if we don't call balance_pgdat
4445 * after returning from the refrigerator
4451 * Reclaim begins at the requested order but if a high-order
4452 * reclaim fails then kswapd falls back to reclaiming for
4453 * order-0. If that happens, kswapd will consider sleeping
4454 * for the order it finished reclaiming at (reclaim_order)
4455 * but kcompactd is woken to compact for the original
4456 * request (alloc_order).
4458 trace_mm_vmscan_kswapd_wake(pgdat
->node_id
, highest_zoneidx
,
4460 reclaim_order
= balance_pgdat(pgdat
, alloc_order
,
4462 if (reclaim_order
< alloc_order
)
4463 goto kswapd_try_sleep
;
4466 tsk
->flags
&= ~(PF_MEMALLOC
| PF_KSWAPD
);
4472 * A zone is low on free memory or too fragmented for high-order memory. If
4473 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4474 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4475 * has failed or is not needed, still wake up kcompactd if only compaction is
4478 void wakeup_kswapd(struct zone
*zone
, gfp_t gfp_flags
, int order
,
4479 enum zone_type highest_zoneidx
)
4482 enum zone_type curr_idx
;
4484 if (!managed_zone(zone
))
4487 if (!cpuset_zone_allowed(zone
, gfp_flags
))
4490 pgdat
= zone
->zone_pgdat
;
4491 curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
4493 if (curr_idx
== MAX_NR_ZONES
|| curr_idx
< highest_zoneidx
)
4494 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, highest_zoneidx
);
4496 if (READ_ONCE(pgdat
->kswapd_order
) < order
)
4497 WRITE_ONCE(pgdat
->kswapd_order
, order
);
4499 if (!waitqueue_active(&pgdat
->kswapd_wait
))
4502 /* Hopeless node, leave it to direct reclaim if possible */
4503 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
||
4504 (pgdat_balanced(pgdat
, order
, highest_zoneidx
) &&
4505 !pgdat_watermark_boosted(pgdat
, highest_zoneidx
))) {
4507 * There may be plenty of free memory available, but it's too
4508 * fragmented for high-order allocations. Wake up kcompactd
4509 * and rely on compaction_suitable() to determine if it's
4510 * needed. If it fails, it will defer subsequent attempts to
4511 * ratelimit its work.
4513 if (!(gfp_flags
& __GFP_DIRECT_RECLAIM
))
4514 wakeup_kcompactd(pgdat
, order
, highest_zoneidx
);
4518 trace_mm_vmscan_wakeup_kswapd(pgdat
->node_id
, highest_zoneidx
, order
,
4520 wake_up_interruptible(&pgdat
->kswapd_wait
);
4523 #ifdef CONFIG_HIBERNATION
4525 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4528 * Rather than trying to age LRUs the aim is to preserve the overall
4529 * LRU order by reclaiming preferentially
4530 * inactive > active > active referenced > active mapped
4532 unsigned long shrink_all_memory(unsigned long nr_to_reclaim
)
4534 struct scan_control sc
= {
4535 .nr_to_reclaim
= nr_to_reclaim
,
4536 .gfp_mask
= GFP_HIGHUSER_MOVABLE
,
4537 .reclaim_idx
= MAX_NR_ZONES
- 1,
4538 .priority
= DEF_PRIORITY
,
4542 .hibernation_mode
= 1,
4544 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
4545 unsigned long nr_reclaimed
;
4546 unsigned int noreclaim_flag
;
4548 fs_reclaim_acquire(sc
.gfp_mask
);
4549 noreclaim_flag
= memalloc_noreclaim_save();
4550 set_task_reclaim_state(current
, &sc
.reclaim_state
);
4552 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
4554 set_task_reclaim_state(current
, NULL
);
4555 memalloc_noreclaim_restore(noreclaim_flag
);
4556 fs_reclaim_release(sc
.gfp_mask
);
4558 return nr_reclaimed
;
4560 #endif /* CONFIG_HIBERNATION */
4563 * This kswapd start function will be called by init and node-hot-add.
4564 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4566 void kswapd_run(int nid
)
4568 pg_data_t
*pgdat
= NODE_DATA(nid
);
4573 pgdat
->kswapd
= kthread_run(kswapd
, pgdat
, "kswapd%d", nid
);
4574 if (IS_ERR(pgdat
->kswapd
)) {
4575 /* failure at boot is fatal */
4576 BUG_ON(system_state
< SYSTEM_RUNNING
);
4577 pr_err("Failed to start kswapd on node %d\n", nid
);
4578 pgdat
->kswapd
= NULL
;
4583 * Called by memory hotplug when all memory in a node is offlined. Caller must
4584 * hold mem_hotplug_begin/end().
4586 void kswapd_stop(int nid
)
4588 struct task_struct
*kswapd
= NODE_DATA(nid
)->kswapd
;
4591 kthread_stop(kswapd
);
4592 NODE_DATA(nid
)->kswapd
= NULL
;
4596 static int __init
kswapd_init(void)
4601 for_each_node_state(nid
, N_MEMORY
)
4606 module_init(kswapd_init
)
4612 * If non-zero call node_reclaim when the number of free pages falls below
4615 int node_reclaim_mode __read_mostly
;
4618 * Priority for NODE_RECLAIM. This determines the fraction of pages
4619 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4622 #define NODE_RECLAIM_PRIORITY 4
4625 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4628 int sysctl_min_unmapped_ratio
= 1;
4631 * If the number of slab pages in a zone grows beyond this percentage then
4632 * slab reclaim needs to occur.
4634 int sysctl_min_slab_ratio
= 5;
4636 static inline unsigned long node_unmapped_file_pages(struct pglist_data
*pgdat
)
4638 unsigned long file_mapped
= node_page_state(pgdat
, NR_FILE_MAPPED
);
4639 unsigned long file_lru
= node_page_state(pgdat
, NR_INACTIVE_FILE
) +
4640 node_page_state(pgdat
, NR_ACTIVE_FILE
);
4643 * It's possible for there to be more file mapped pages than
4644 * accounted for by the pages on the file LRU lists because
4645 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4647 return (file_lru
> file_mapped
) ? (file_lru
- file_mapped
) : 0;
4650 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4651 static unsigned long node_pagecache_reclaimable(struct pglist_data
*pgdat
)
4653 unsigned long nr_pagecache_reclaimable
;
4654 unsigned long delta
= 0;
4657 * If RECLAIM_UNMAP is set, then all file pages are considered
4658 * potentially reclaimable. Otherwise, we have to worry about
4659 * pages like swapcache and node_unmapped_file_pages() provides
4662 if (node_reclaim_mode
& RECLAIM_UNMAP
)
4663 nr_pagecache_reclaimable
= node_page_state(pgdat
, NR_FILE_PAGES
);
4665 nr_pagecache_reclaimable
= node_unmapped_file_pages(pgdat
);
4667 /* If we can't clean pages, remove dirty pages from consideration */
4668 if (!(node_reclaim_mode
& RECLAIM_WRITE
))
4669 delta
+= node_page_state(pgdat
, NR_FILE_DIRTY
);
4671 /* Watch for any possible underflows due to delta */
4672 if (unlikely(delta
> nr_pagecache_reclaimable
))
4673 delta
= nr_pagecache_reclaimable
;
4675 return nr_pagecache_reclaimable
- delta
;
4679 * Try to free up some pages from this node through reclaim.
4681 static int __node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
4683 /* Minimum pages needed in order to stay on node */
4684 const unsigned long nr_pages
= 1 << order
;
4685 struct task_struct
*p
= current
;
4686 unsigned int noreclaim_flag
;
4687 struct scan_control sc
= {
4688 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
4689 .gfp_mask
= current_gfp_context(gfp_mask
),
4691 .priority
= NODE_RECLAIM_PRIORITY
,
4692 .may_writepage
= !!(node_reclaim_mode
& RECLAIM_WRITE
),
4693 .may_unmap
= !!(node_reclaim_mode
& RECLAIM_UNMAP
),
4695 .reclaim_idx
= gfp_zone(gfp_mask
),
4697 unsigned long pflags
;
4699 trace_mm_vmscan_node_reclaim_begin(pgdat
->node_id
, order
,
4703 psi_memstall_enter(&pflags
);
4704 fs_reclaim_acquire(sc
.gfp_mask
);
4706 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4708 noreclaim_flag
= memalloc_noreclaim_save();
4709 set_task_reclaim_state(p
, &sc
.reclaim_state
);
4711 if (node_pagecache_reclaimable(pgdat
) > pgdat
->min_unmapped_pages
) {
4713 * Free memory by calling shrink node with increasing
4714 * priorities until we have enough memory freed.
4717 shrink_node(pgdat
, &sc
);
4718 } while (sc
.nr_reclaimed
< nr_pages
&& --sc
.priority
>= 0);
4721 set_task_reclaim_state(p
, NULL
);
4722 memalloc_noreclaim_restore(noreclaim_flag
);
4723 fs_reclaim_release(sc
.gfp_mask
);
4724 psi_memstall_leave(&pflags
);
4726 trace_mm_vmscan_node_reclaim_end(sc
.nr_reclaimed
);
4728 return sc
.nr_reclaimed
>= nr_pages
;
4731 int node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
4736 * Node reclaim reclaims unmapped file backed pages and
4737 * slab pages if we are over the defined limits.
4739 * A small portion of unmapped file backed pages is needed for
4740 * file I/O otherwise pages read by file I/O will be immediately
4741 * thrown out if the node is overallocated. So we do not reclaim
4742 * if less than a specified percentage of the node is used by
4743 * unmapped file backed pages.
4745 if (node_pagecache_reclaimable(pgdat
) <= pgdat
->min_unmapped_pages
&&
4746 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) <=
4747 pgdat
->min_slab_pages
)
4748 return NODE_RECLAIM_FULL
;
4751 * Do not scan if the allocation should not be delayed.
4753 if (!gfpflags_allow_blocking(gfp_mask
) || (current
->flags
& PF_MEMALLOC
))
4754 return NODE_RECLAIM_NOSCAN
;
4757 * Only run node reclaim on the local node or on nodes that do not
4758 * have associated processors. This will favor the local processor
4759 * over remote processors and spread off node memory allocations
4760 * as wide as possible.
4762 if (node_state(pgdat
->node_id
, N_CPU
) && pgdat
->node_id
!= numa_node_id())
4763 return NODE_RECLAIM_NOSCAN
;
4765 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
))
4766 return NODE_RECLAIM_NOSCAN
;
4768 ret
= __node_reclaim(pgdat
, gfp_mask
, order
);
4769 clear_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
);
4772 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED
);
4779 * check_move_unevictable_pages - check pages for evictability and move to
4780 * appropriate zone lru list
4781 * @pvec: pagevec with lru pages to check
4783 * Checks pages for evictability, if an evictable page is in the unevictable
4784 * lru list, moves it to the appropriate evictable lru list. This function
4785 * should be only used for lru pages.
4787 void check_move_unevictable_pages(struct pagevec
*pvec
)
4789 struct lruvec
*lruvec
= NULL
;
4794 for (i
= 0; i
< pvec
->nr
; i
++) {
4795 struct page
*page
= pvec
->pages
[i
];
4796 struct folio
*folio
= page_folio(page
);
4799 if (PageTransTail(page
))
4802 nr_pages
= thp_nr_pages(page
);
4803 pgscanned
+= nr_pages
;
4805 /* block memcg migration during page moving between lru */
4806 if (!TestClearPageLRU(page
))
4809 lruvec
= folio_lruvec_relock_irq(folio
, lruvec
);
4810 if (page_evictable(page
) && PageUnevictable(page
)) {
4811 del_page_from_lru_list(page
, lruvec
);
4812 ClearPageUnevictable(page
);
4813 add_page_to_lru_list(page
, lruvec
);
4814 pgrescued
+= nr_pages
;
4820 __count_vm_events(UNEVICTABLE_PGRESCUED
, pgrescued
);
4821 __count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
4822 unlock_page_lruvec_irq(lruvec
);
4823 } else if (pgscanned
) {
4824 count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
4827 EXPORT_SYMBOL_GPL(check_move_unevictable_pages
);