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/delayacct.h>
45 #include <linux/sysctl.h>
46 #include <linux/oom.h>
47 #include <linux/pagevec.h>
48 #include <linux/prefetch.h>
49 #include <linux/printk.h>
50 #include <linux/dax.h>
51 #include <linux/psi.h>
53 #include <asm/tlbflush.h>
54 #include <asm/div64.h>
56 #include <linux/swapops.h>
57 #include <linux/balloon_compaction.h>
61 #define CREATE_TRACE_POINTS
62 #include <trace/events/vmscan.h>
65 /* How many pages shrink_list() should reclaim */
66 unsigned long nr_to_reclaim
;
69 * Nodemask of nodes allowed by the caller. If NULL, all nodes
75 * The memory cgroup that hit its limit and as a result is the
76 * primary target of this reclaim invocation.
78 struct mem_cgroup
*target_mem_cgroup
;
81 * Scan pressure balancing between anon and file LRUs
83 unsigned long anon_cost
;
84 unsigned long file_cost
;
86 /* Can active pages be deactivated as part of reclaim? */
87 #define DEACTIVATE_ANON 1
88 #define DEACTIVATE_FILE 2
89 unsigned int may_deactivate
:2;
90 unsigned int force_deactivate
:1;
91 unsigned int skipped_deactivate
:1;
93 /* Writepage batching in laptop mode; RECLAIM_WRITE */
94 unsigned int may_writepage
:1;
96 /* Can mapped pages be reclaimed? */
97 unsigned int may_unmap
:1;
99 /* Can pages be swapped as part of reclaim? */
100 unsigned int may_swap
:1;
103 * Cgroups are not reclaimed below their configured memory.low,
104 * unless we threaten to OOM. If any cgroups are skipped due to
105 * memory.low and nothing was reclaimed, go back for memory.low.
107 unsigned int memcg_low_reclaim
:1;
108 unsigned int memcg_low_skipped
:1;
110 unsigned int hibernation_mode
:1;
112 /* One of the zones is ready for compaction */
113 unsigned int compaction_ready
:1;
115 /* There is easily reclaimable cold cache in the current node */
116 unsigned int cache_trim_mode
:1;
118 /* The file pages on the current node are dangerously low */
119 unsigned int file_is_tiny
:1;
121 /* Allocation order */
124 /* Scan (total_size >> priority) pages at once */
127 /* The highest zone to isolate pages for reclaim from */
130 /* This context's GFP mask */
133 /* Incremented by the number of inactive pages that were scanned */
134 unsigned long nr_scanned
;
136 /* Number of pages freed so far during a call to shrink_zones() */
137 unsigned long nr_reclaimed
;
141 unsigned int unqueued_dirty
;
142 unsigned int congested
;
143 unsigned int writeback
;
144 unsigned int immediate
;
145 unsigned int file_taken
;
149 /* for recording the reclaimed slab by now */
150 struct reclaim_state reclaim_state
;
153 #ifdef ARCH_HAS_PREFETCHW
154 #define prefetchw_prev_lru_page(_page, _base, _field) \
156 if ((_page)->lru.prev != _base) { \
159 prev = lru_to_page(&(_page->lru)); \
160 prefetchw(&prev->_field); \
164 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
168 * From 0 .. 200. Higher means more swappy.
170 int vm_swappiness
= 60;
172 static void set_task_reclaim_state(struct task_struct
*task
,
173 struct reclaim_state
*rs
)
175 /* Check for an overwrite */
176 WARN_ON_ONCE(rs
&& task
->reclaim_state
);
178 /* Check for the nulling of an already-nulled member */
179 WARN_ON_ONCE(!rs
&& !task
->reclaim_state
);
181 task
->reclaim_state
= rs
;
184 static LIST_HEAD(shrinker_list
);
185 static DECLARE_RWSEM(shrinker_rwsem
);
188 static int shrinker_nr_max
;
190 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
191 static inline int shrinker_map_size(int nr_items
)
193 return (DIV_ROUND_UP(nr_items
, BITS_PER_LONG
) * sizeof(unsigned long));
196 static inline int shrinker_defer_size(int nr_items
)
198 return (round_up(nr_items
, BITS_PER_LONG
) * sizeof(atomic_long_t
));
201 static struct shrinker_info
*shrinker_info_protected(struct mem_cgroup
*memcg
,
204 return rcu_dereference_protected(memcg
->nodeinfo
[nid
]->shrinker_info
,
205 lockdep_is_held(&shrinker_rwsem
));
208 static int expand_one_shrinker_info(struct mem_cgroup
*memcg
,
209 int map_size
, int defer_size
,
210 int old_map_size
, int old_defer_size
)
212 struct shrinker_info
*new, *old
;
213 struct mem_cgroup_per_node
*pn
;
215 int size
= map_size
+ defer_size
;
218 pn
= memcg
->nodeinfo
[nid
];
219 old
= shrinker_info_protected(memcg
, nid
);
220 /* Not yet online memcg */
224 new = kvmalloc_node(sizeof(*new) + size
, GFP_KERNEL
, nid
);
228 new->nr_deferred
= (atomic_long_t
*)(new + 1);
229 new->map
= (void *)new->nr_deferred
+ defer_size
;
231 /* map: set all old bits, clear all new bits */
232 memset(new->map
, (int)0xff, old_map_size
);
233 memset((void *)new->map
+ old_map_size
, 0, map_size
- old_map_size
);
234 /* nr_deferred: copy old values, clear all new values */
235 memcpy(new->nr_deferred
, old
->nr_deferred
, old_defer_size
);
236 memset((void *)new->nr_deferred
+ old_defer_size
, 0,
237 defer_size
- old_defer_size
);
239 rcu_assign_pointer(pn
->shrinker_info
, new);
240 kvfree_rcu(old
, rcu
);
246 void free_shrinker_info(struct mem_cgroup
*memcg
)
248 struct mem_cgroup_per_node
*pn
;
249 struct shrinker_info
*info
;
253 pn
= memcg
->nodeinfo
[nid
];
254 info
= rcu_dereference_protected(pn
->shrinker_info
, true);
256 rcu_assign_pointer(pn
->shrinker_info
, NULL
);
260 int alloc_shrinker_info(struct mem_cgroup
*memcg
)
262 struct shrinker_info
*info
;
263 int nid
, size
, ret
= 0;
264 int map_size
, defer_size
= 0;
266 down_write(&shrinker_rwsem
);
267 map_size
= shrinker_map_size(shrinker_nr_max
);
268 defer_size
= shrinker_defer_size(shrinker_nr_max
);
269 size
= map_size
+ defer_size
;
271 info
= kvzalloc_node(sizeof(*info
) + size
, GFP_KERNEL
, nid
);
273 free_shrinker_info(memcg
);
277 info
->nr_deferred
= (atomic_long_t
*)(info
+ 1);
278 info
->map
= (void *)info
->nr_deferred
+ defer_size
;
279 rcu_assign_pointer(memcg
->nodeinfo
[nid
]->shrinker_info
, info
);
281 up_write(&shrinker_rwsem
);
286 static inline bool need_expand(int nr_max
)
288 return round_up(nr_max
, BITS_PER_LONG
) >
289 round_up(shrinker_nr_max
, BITS_PER_LONG
);
292 static int expand_shrinker_info(int new_id
)
295 int new_nr_max
= new_id
+ 1;
296 int map_size
, defer_size
= 0;
297 int old_map_size
, old_defer_size
= 0;
298 struct mem_cgroup
*memcg
;
300 if (!need_expand(new_nr_max
))
303 if (!root_mem_cgroup
)
306 lockdep_assert_held(&shrinker_rwsem
);
308 map_size
= shrinker_map_size(new_nr_max
);
309 defer_size
= shrinker_defer_size(new_nr_max
);
310 old_map_size
= shrinker_map_size(shrinker_nr_max
);
311 old_defer_size
= shrinker_defer_size(shrinker_nr_max
);
313 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
315 ret
= expand_one_shrinker_info(memcg
, map_size
, defer_size
,
316 old_map_size
, old_defer_size
);
318 mem_cgroup_iter_break(NULL
, memcg
);
321 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
324 shrinker_nr_max
= new_nr_max
;
329 void set_shrinker_bit(struct mem_cgroup
*memcg
, int nid
, int shrinker_id
)
331 if (shrinker_id
>= 0 && memcg
&& !mem_cgroup_is_root(memcg
)) {
332 struct shrinker_info
*info
;
335 info
= rcu_dereference(memcg
->nodeinfo
[nid
]->shrinker_info
);
336 /* Pairs with smp mb in shrink_slab() */
337 smp_mb__before_atomic();
338 set_bit(shrinker_id
, info
->map
);
343 static DEFINE_IDR(shrinker_idr
);
345 static int prealloc_memcg_shrinker(struct shrinker
*shrinker
)
347 int id
, ret
= -ENOMEM
;
349 if (mem_cgroup_disabled())
352 down_write(&shrinker_rwsem
);
353 /* This may call shrinker, so it must use down_read_trylock() */
354 id
= idr_alloc(&shrinker_idr
, shrinker
, 0, 0, GFP_KERNEL
);
358 if (id
>= shrinker_nr_max
) {
359 if (expand_shrinker_info(id
)) {
360 idr_remove(&shrinker_idr
, id
);
367 up_write(&shrinker_rwsem
);
371 static void unregister_memcg_shrinker(struct shrinker
*shrinker
)
373 int id
= shrinker
->id
;
377 lockdep_assert_held(&shrinker_rwsem
);
379 idr_remove(&shrinker_idr
, id
);
382 static long xchg_nr_deferred_memcg(int nid
, struct shrinker
*shrinker
,
383 struct mem_cgroup
*memcg
)
385 struct shrinker_info
*info
;
387 info
= shrinker_info_protected(memcg
, nid
);
388 return atomic_long_xchg(&info
->nr_deferred
[shrinker
->id
], 0);
391 static long add_nr_deferred_memcg(long nr
, 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_add_return(nr
, &info
->nr_deferred
[shrinker
->id
]);
400 void reparent_shrinker_deferred(struct mem_cgroup
*memcg
)
404 struct mem_cgroup
*parent
;
405 struct shrinker_info
*child_info
, *parent_info
;
407 parent
= parent_mem_cgroup(memcg
);
409 parent
= root_mem_cgroup
;
411 /* Prevent from concurrent shrinker_info expand */
412 down_read(&shrinker_rwsem
);
414 child_info
= shrinker_info_protected(memcg
, nid
);
415 parent_info
= shrinker_info_protected(parent
, nid
);
416 for (i
= 0; i
< shrinker_nr_max
; i
++) {
417 nr
= atomic_long_read(&child_info
->nr_deferred
[i
]);
418 atomic_long_add(nr
, &parent_info
->nr_deferred
[i
]);
421 up_read(&shrinker_rwsem
);
424 static bool cgroup_reclaim(struct scan_control
*sc
)
426 return sc
->target_mem_cgroup
;
430 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
431 * @sc: scan_control in question
433 * The normal page dirty throttling mechanism in balance_dirty_pages() is
434 * completely broken with the legacy memcg and direct stalling in
435 * shrink_page_list() is used for throttling instead, which lacks all the
436 * niceties such as fairness, adaptive pausing, bandwidth proportional
437 * allocation and configurability.
439 * This function tests whether the vmscan currently in progress can assume
440 * that the normal dirty throttling mechanism is operational.
442 static bool writeback_throttling_sane(struct scan_control
*sc
)
444 if (!cgroup_reclaim(sc
))
446 #ifdef CONFIG_CGROUP_WRITEBACK
447 if (cgroup_subsys_on_dfl(memory_cgrp_subsys
))
453 static int prealloc_memcg_shrinker(struct shrinker
*shrinker
)
458 static void unregister_memcg_shrinker(struct shrinker
*shrinker
)
462 static long xchg_nr_deferred_memcg(int nid
, struct shrinker
*shrinker
,
463 struct mem_cgroup
*memcg
)
468 static long add_nr_deferred_memcg(long nr
, int nid
, struct shrinker
*shrinker
,
469 struct mem_cgroup
*memcg
)
474 static bool cgroup_reclaim(struct scan_control
*sc
)
479 static bool writeback_throttling_sane(struct scan_control
*sc
)
485 static long xchg_nr_deferred(struct shrinker
*shrinker
,
486 struct shrink_control
*sc
)
490 if (!(shrinker
->flags
& SHRINKER_NUMA_AWARE
))
494 (shrinker
->flags
& SHRINKER_MEMCG_AWARE
))
495 return xchg_nr_deferred_memcg(nid
, shrinker
,
498 return atomic_long_xchg(&shrinker
->nr_deferred
[nid
], 0);
502 static long add_nr_deferred(long nr
, struct shrinker
*shrinker
,
503 struct shrink_control
*sc
)
507 if (!(shrinker
->flags
& SHRINKER_NUMA_AWARE
))
511 (shrinker
->flags
& SHRINKER_MEMCG_AWARE
))
512 return add_nr_deferred_memcg(nr
, nid
, shrinker
,
515 return atomic_long_add_return(nr
, &shrinker
->nr_deferred
[nid
]);
519 * This misses isolated pages which are not accounted for to save counters.
520 * As the data only determines if reclaim or compaction continues, it is
521 * not expected that isolated pages will be a dominating factor.
523 unsigned long zone_reclaimable_pages(struct zone
*zone
)
527 nr
= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_FILE
) +
528 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_FILE
);
529 if (get_nr_swap_pages() > 0)
530 nr
+= zone_page_state_snapshot(zone
, NR_ZONE_INACTIVE_ANON
) +
531 zone_page_state_snapshot(zone
, NR_ZONE_ACTIVE_ANON
);
537 * lruvec_lru_size - Returns the number of pages on the given LRU list.
538 * @lruvec: lru vector
540 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
542 static unsigned long lruvec_lru_size(struct lruvec
*lruvec
, enum lru_list lru
,
545 unsigned long size
= 0;
548 for (zid
= 0; zid
<= zone_idx
&& zid
< MAX_NR_ZONES
; zid
++) {
549 struct zone
*zone
= &lruvec_pgdat(lruvec
)->node_zones
[zid
];
551 if (!managed_zone(zone
))
554 if (!mem_cgroup_disabled())
555 size
+= mem_cgroup_get_zone_lru_size(lruvec
, lru
, zid
);
557 size
+= zone_page_state(zone
, NR_ZONE_LRU_BASE
+ lru
);
563 * Add a shrinker callback to be called from the vm.
565 int prealloc_shrinker(struct shrinker
*shrinker
)
570 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
) {
571 err
= prealloc_memcg_shrinker(shrinker
);
575 shrinker
->flags
&= ~SHRINKER_MEMCG_AWARE
;
578 size
= sizeof(*shrinker
->nr_deferred
);
579 if (shrinker
->flags
& SHRINKER_NUMA_AWARE
)
582 shrinker
->nr_deferred
= kzalloc(size
, GFP_KERNEL
);
583 if (!shrinker
->nr_deferred
)
589 void free_prealloced_shrinker(struct shrinker
*shrinker
)
591 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
) {
592 down_write(&shrinker_rwsem
);
593 unregister_memcg_shrinker(shrinker
);
594 up_write(&shrinker_rwsem
);
598 kfree(shrinker
->nr_deferred
);
599 shrinker
->nr_deferred
= NULL
;
602 void register_shrinker_prepared(struct shrinker
*shrinker
)
604 down_write(&shrinker_rwsem
);
605 list_add_tail(&shrinker
->list
, &shrinker_list
);
606 shrinker
->flags
|= SHRINKER_REGISTERED
;
607 up_write(&shrinker_rwsem
);
610 int register_shrinker(struct shrinker
*shrinker
)
612 int err
= prealloc_shrinker(shrinker
);
616 register_shrinker_prepared(shrinker
);
619 EXPORT_SYMBOL(register_shrinker
);
624 void unregister_shrinker(struct shrinker
*shrinker
)
626 if (!(shrinker
->flags
& SHRINKER_REGISTERED
))
629 down_write(&shrinker_rwsem
);
630 list_del(&shrinker
->list
);
631 shrinker
->flags
&= ~SHRINKER_REGISTERED
;
632 if (shrinker
->flags
& SHRINKER_MEMCG_AWARE
)
633 unregister_memcg_shrinker(shrinker
);
634 up_write(&shrinker_rwsem
);
636 kfree(shrinker
->nr_deferred
);
637 shrinker
->nr_deferred
= NULL
;
639 EXPORT_SYMBOL(unregister_shrinker
);
641 #define SHRINK_BATCH 128
643 static unsigned long do_shrink_slab(struct shrink_control
*shrinkctl
,
644 struct shrinker
*shrinker
, int priority
)
646 unsigned long freed
= 0;
647 unsigned long long delta
;
652 long batch_size
= shrinker
->batch
? shrinker
->batch
654 long scanned
= 0, next_deferred
;
656 freeable
= shrinker
->count_objects(shrinker
, shrinkctl
);
657 if (freeable
== 0 || freeable
== SHRINK_EMPTY
)
661 * copy the current shrinker scan count into a local variable
662 * and zero it so that other concurrent shrinker invocations
663 * don't also do this scanning work.
665 nr
= xchg_nr_deferred(shrinker
, shrinkctl
);
667 if (shrinker
->seeks
) {
668 delta
= freeable
>> priority
;
670 do_div(delta
, shrinker
->seeks
);
673 * These objects don't require any IO to create. Trim
674 * them aggressively under memory pressure to keep
675 * them from causing refetches in the IO caches.
677 delta
= freeable
/ 2;
680 total_scan
= nr
>> priority
;
682 total_scan
= min(total_scan
, (2 * freeable
));
684 trace_mm_shrink_slab_start(shrinker
, shrinkctl
, nr
,
685 freeable
, delta
, total_scan
, priority
);
688 * Normally, we should not scan less than batch_size objects in one
689 * pass to avoid too frequent shrinker calls, but if the slab has less
690 * than batch_size objects in total and we are really tight on memory,
691 * we will try to reclaim all available objects, otherwise we can end
692 * up failing allocations although there are plenty of reclaimable
693 * objects spread over several slabs with usage less than the
696 * We detect the "tight on memory" situations by looking at the total
697 * number of objects we want to scan (total_scan). If it is greater
698 * than the total number of objects on slab (freeable), we must be
699 * scanning at high prio and therefore should try to reclaim as much as
702 while (total_scan
>= batch_size
||
703 total_scan
>= freeable
) {
705 unsigned long nr_to_scan
= min(batch_size
, total_scan
);
707 shrinkctl
->nr_to_scan
= nr_to_scan
;
708 shrinkctl
->nr_scanned
= nr_to_scan
;
709 ret
= shrinker
->scan_objects(shrinker
, shrinkctl
);
710 if (ret
== SHRINK_STOP
)
714 count_vm_events(SLABS_SCANNED
, shrinkctl
->nr_scanned
);
715 total_scan
-= shrinkctl
->nr_scanned
;
716 scanned
+= shrinkctl
->nr_scanned
;
722 * The deferred work is increased by any new work (delta) that wasn't
723 * done, decreased by old deferred work that was done now.
725 * And it is capped to two times of the freeable items.
727 next_deferred
= max_t(long, (nr
+ delta
- scanned
), 0);
728 next_deferred
= min(next_deferred
, (2 * freeable
));
731 * move the unused scan count back into the shrinker in a
732 * manner that handles concurrent updates.
734 new_nr
= add_nr_deferred(next_deferred
, shrinker
, shrinkctl
);
736 trace_mm_shrink_slab_end(shrinker
, shrinkctl
->nid
, freed
, nr
, new_nr
, total_scan
);
741 static unsigned long shrink_slab_memcg(gfp_t gfp_mask
, int nid
,
742 struct mem_cgroup
*memcg
, int priority
)
744 struct shrinker_info
*info
;
745 unsigned long ret
, freed
= 0;
748 if (!mem_cgroup_online(memcg
))
751 if (!down_read_trylock(&shrinker_rwsem
))
754 info
= shrinker_info_protected(memcg
, nid
);
758 for_each_set_bit(i
, info
->map
, shrinker_nr_max
) {
759 struct shrink_control sc
= {
760 .gfp_mask
= gfp_mask
,
764 struct shrinker
*shrinker
;
766 shrinker
= idr_find(&shrinker_idr
, i
);
767 if (unlikely(!shrinker
|| !(shrinker
->flags
& SHRINKER_REGISTERED
))) {
769 clear_bit(i
, info
->map
);
773 /* Call non-slab shrinkers even though kmem is disabled */
774 if (!memcg_kmem_enabled() &&
775 !(shrinker
->flags
& SHRINKER_NONSLAB
))
778 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
779 if (ret
== SHRINK_EMPTY
) {
780 clear_bit(i
, info
->map
);
782 * After the shrinker reported that it had no objects to
783 * free, but before we cleared the corresponding bit in
784 * the memcg shrinker map, a new object might have been
785 * added. To make sure, we have the bit set in this
786 * case, we invoke the shrinker one more time and reset
787 * the bit if it reports that it is not empty anymore.
788 * The memory barrier here pairs with the barrier in
789 * set_shrinker_bit():
791 * list_lru_add() shrink_slab_memcg()
792 * list_add_tail() clear_bit()
794 * set_bit() do_shrink_slab()
796 smp_mb__after_atomic();
797 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
798 if (ret
== SHRINK_EMPTY
)
801 set_shrinker_bit(memcg
, nid
, i
);
805 if (rwsem_is_contended(&shrinker_rwsem
)) {
811 up_read(&shrinker_rwsem
);
814 #else /* CONFIG_MEMCG */
815 static unsigned long shrink_slab_memcg(gfp_t gfp_mask
, int nid
,
816 struct mem_cgroup
*memcg
, int priority
)
820 #endif /* CONFIG_MEMCG */
823 * shrink_slab - shrink slab caches
824 * @gfp_mask: allocation context
825 * @nid: node whose slab caches to target
826 * @memcg: memory cgroup whose slab caches to target
827 * @priority: the reclaim priority
829 * Call the shrink functions to age shrinkable caches.
831 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
832 * unaware shrinkers will receive a node id of 0 instead.
834 * @memcg specifies the memory cgroup to target. Unaware shrinkers
835 * are called only if it is the root cgroup.
837 * @priority is sc->priority, we take the number of objects and >> by priority
838 * in order to get the scan target.
840 * Returns the number of reclaimed slab objects.
842 static unsigned long shrink_slab(gfp_t gfp_mask
, int nid
,
843 struct mem_cgroup
*memcg
,
846 unsigned long ret
, freed
= 0;
847 struct shrinker
*shrinker
;
850 * The root memcg might be allocated even though memcg is disabled
851 * via "cgroup_disable=memory" boot parameter. This could make
852 * mem_cgroup_is_root() return false, then just run memcg slab
853 * shrink, but skip global shrink. This may result in premature
856 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg
))
857 return shrink_slab_memcg(gfp_mask
, nid
, memcg
, priority
);
859 if (!down_read_trylock(&shrinker_rwsem
))
862 list_for_each_entry(shrinker
, &shrinker_list
, list
) {
863 struct shrink_control sc
= {
864 .gfp_mask
= gfp_mask
,
869 ret
= do_shrink_slab(&sc
, shrinker
, priority
);
870 if (ret
== SHRINK_EMPTY
)
874 * Bail out if someone want to register a new shrinker to
875 * prevent the registration from being stalled for long periods
876 * by parallel ongoing shrinking.
878 if (rwsem_is_contended(&shrinker_rwsem
)) {
884 up_read(&shrinker_rwsem
);
890 void drop_slab_node(int nid
)
895 struct mem_cgroup
*memcg
= NULL
;
897 if (fatal_signal_pending(current
))
901 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
903 freed
+= shrink_slab(GFP_KERNEL
, nid
, memcg
, 0);
904 } while ((memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
)) != NULL
);
905 } while (freed
> 10);
912 for_each_online_node(nid
)
916 static inline int is_page_cache_freeable(struct page
*page
)
919 * A freeable page cache page is referenced only by the caller
920 * that isolated the page, the page cache and optional buffer
921 * heads at page->private.
923 int page_cache_pins
= thp_nr_pages(page
);
924 return page_count(page
) - page_has_private(page
) == 1 + page_cache_pins
;
927 static int may_write_to_inode(struct inode
*inode
)
929 if (current
->flags
& PF_SWAPWRITE
)
931 if (!inode_write_congested(inode
))
933 if (inode_to_bdi(inode
) == current
->backing_dev_info
)
939 * We detected a synchronous write error writing a page out. Probably
940 * -ENOSPC. We need to propagate that into the address_space for a subsequent
941 * fsync(), msync() or close().
943 * The tricky part is that after writepage we cannot touch the mapping: nothing
944 * prevents it from being freed up. But we have a ref on the page and once
945 * that page is locked, the mapping is pinned.
947 * We're allowed to run sleeping lock_page() here because we know the caller has
950 static void handle_write_error(struct address_space
*mapping
,
951 struct page
*page
, int error
)
954 if (page_mapping(page
) == mapping
)
955 mapping_set_error(mapping
, error
);
959 /* possible outcome of pageout() */
961 /* failed to write page out, page is locked */
963 /* move page to the active list, page is locked */
965 /* page has been sent to the disk successfully, page is unlocked */
967 /* page is clean and locked */
972 * pageout is called by shrink_page_list() for each dirty page.
973 * Calls ->writepage().
975 static pageout_t
pageout(struct page
*page
, struct address_space
*mapping
)
978 * If the page is dirty, only perform writeback if that write
979 * will be non-blocking. To prevent this allocation from being
980 * stalled by pagecache activity. But note that there may be
981 * stalls if we need to run get_block(). We could test
982 * PagePrivate for that.
984 * If this process is currently in __generic_file_write_iter() against
985 * this page's queue, we can perform writeback even if that
988 * If the page is swapcache, write it back even if that would
989 * block, for some throttling. This happens by accident, because
990 * swap_backing_dev_info is bust: it doesn't reflect the
991 * congestion state of the swapdevs. Easy to fix, if needed.
993 if (!is_page_cache_freeable(page
))
997 * Some data journaling orphaned pages can have
998 * page->mapping == NULL while being dirty with clean buffers.
1000 if (page_has_private(page
)) {
1001 if (try_to_free_buffers(page
)) {
1002 ClearPageDirty(page
);
1003 pr_info("%s: orphaned page\n", __func__
);
1009 if (mapping
->a_ops
->writepage
== NULL
)
1010 return PAGE_ACTIVATE
;
1011 if (!may_write_to_inode(mapping
->host
))
1014 if (clear_page_dirty_for_io(page
)) {
1016 struct writeback_control wbc
= {
1017 .sync_mode
= WB_SYNC_NONE
,
1018 .nr_to_write
= SWAP_CLUSTER_MAX
,
1020 .range_end
= LLONG_MAX
,
1024 SetPageReclaim(page
);
1025 res
= mapping
->a_ops
->writepage(page
, &wbc
);
1027 handle_write_error(mapping
, page
, res
);
1028 if (res
== AOP_WRITEPAGE_ACTIVATE
) {
1029 ClearPageReclaim(page
);
1030 return PAGE_ACTIVATE
;
1033 if (!PageWriteback(page
)) {
1034 /* synchronous write or broken a_ops? */
1035 ClearPageReclaim(page
);
1037 trace_mm_vmscan_writepage(page
);
1038 inc_node_page_state(page
, NR_VMSCAN_WRITE
);
1039 return PAGE_SUCCESS
;
1046 * Same as remove_mapping, but if the page is removed from the mapping, it
1047 * gets returned with a refcount of 0.
1049 static int __remove_mapping(struct address_space
*mapping
, struct page
*page
,
1050 bool reclaimed
, struct mem_cgroup
*target_memcg
)
1052 unsigned long flags
;
1054 void *shadow
= NULL
;
1056 BUG_ON(!PageLocked(page
));
1057 BUG_ON(mapping
!= page_mapping(page
));
1059 xa_lock_irqsave(&mapping
->i_pages
, flags
);
1061 * The non racy check for a busy page.
1063 * Must be careful with the order of the tests. When someone has
1064 * a ref to the page, it may be possible that they dirty it then
1065 * drop the reference. So if PageDirty is tested before page_count
1066 * here, then the following race may occur:
1068 * get_user_pages(&page);
1069 * [user mapping goes away]
1071 * !PageDirty(page) [good]
1072 * SetPageDirty(page);
1074 * !page_count(page) [good, discard it]
1076 * [oops, our write_to data is lost]
1078 * Reversing the order of the tests ensures such a situation cannot
1079 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
1080 * load is not satisfied before that of page->_refcount.
1082 * Note that if SetPageDirty is always performed via set_page_dirty,
1083 * and thus under the i_pages lock, then this ordering is not required.
1085 refcount
= 1 + compound_nr(page
);
1086 if (!page_ref_freeze(page
, refcount
))
1088 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
1089 if (unlikely(PageDirty(page
))) {
1090 page_ref_unfreeze(page
, refcount
);
1094 if (PageSwapCache(page
)) {
1095 swp_entry_t swap
= { .val
= page_private(page
) };
1096 mem_cgroup_swapout(page
, swap
);
1097 if (reclaimed
&& !mapping_exiting(mapping
))
1098 shadow
= workingset_eviction(page
, target_memcg
);
1099 __delete_from_swap_cache(page
, swap
, shadow
);
1100 xa_unlock_irqrestore(&mapping
->i_pages
, flags
);
1101 put_swap_page(page
, swap
);
1103 void (*freepage
)(struct page
*);
1105 freepage
= mapping
->a_ops
->freepage
;
1107 * Remember a shadow entry for reclaimed file cache in
1108 * order to detect refaults, thus thrashing, later on.
1110 * But don't store shadows in an address space that is
1111 * already exiting. This is not just an optimization,
1112 * inode reclaim needs to empty out the radix tree or
1113 * the nodes are lost. Don't plant shadows behind its
1116 * We also don't store shadows for DAX mappings because the
1117 * only page cache pages found in these are zero pages
1118 * covering holes, and because we don't want to mix DAX
1119 * exceptional entries and shadow exceptional entries in the
1120 * same address_space.
1122 if (reclaimed
&& page_is_file_lru(page
) &&
1123 !mapping_exiting(mapping
) && !dax_mapping(mapping
))
1124 shadow
= workingset_eviction(page
, target_memcg
);
1125 __delete_from_page_cache(page
, shadow
);
1126 xa_unlock_irqrestore(&mapping
->i_pages
, flags
);
1128 if (freepage
!= NULL
)
1135 xa_unlock_irqrestore(&mapping
->i_pages
, flags
);
1140 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1141 * someone else has a ref on the page, abort and return 0. If it was
1142 * successfully detached, return 1. Assumes the caller has a single ref on
1145 int remove_mapping(struct address_space
*mapping
, struct page
*page
)
1147 if (__remove_mapping(mapping
, page
, false, NULL
)) {
1149 * Unfreezing the refcount with 1 rather than 2 effectively
1150 * drops the pagecache ref for us without requiring another
1153 page_ref_unfreeze(page
, 1);
1160 * putback_lru_page - put previously isolated page onto appropriate LRU list
1161 * @page: page to be put back to appropriate lru list
1163 * Add previously isolated @page to appropriate LRU list.
1164 * Page may still be unevictable for other reasons.
1166 * lru_lock must not be held, interrupts must be enabled.
1168 void putback_lru_page(struct page
*page
)
1170 lru_cache_add(page
);
1171 put_page(page
); /* drop ref from isolate */
1174 enum page_references
{
1176 PAGEREF_RECLAIM_CLEAN
,
1181 static enum page_references
page_check_references(struct page
*page
,
1182 struct scan_control
*sc
)
1184 int referenced_ptes
, referenced_page
;
1185 unsigned long vm_flags
;
1187 referenced_ptes
= page_referenced(page
, 1, sc
->target_mem_cgroup
,
1189 referenced_page
= TestClearPageReferenced(page
);
1192 * Mlock lost the isolation race with us. Let try_to_unmap()
1193 * move the page to the unevictable list.
1195 if (vm_flags
& VM_LOCKED
)
1196 return PAGEREF_RECLAIM
;
1198 if (referenced_ptes
) {
1200 * All mapped pages start out with page table
1201 * references from the instantiating fault, so we need
1202 * to look twice if a mapped file page is used more
1205 * Mark it and spare it for another trip around the
1206 * inactive list. Another page table reference will
1207 * lead to its activation.
1209 * Note: the mark is set for activated pages as well
1210 * so that recently deactivated but used pages are
1211 * quickly recovered.
1213 SetPageReferenced(page
);
1215 if (referenced_page
|| referenced_ptes
> 1)
1216 return PAGEREF_ACTIVATE
;
1219 * Activate file-backed executable pages after first usage.
1221 if ((vm_flags
& VM_EXEC
) && !PageSwapBacked(page
))
1222 return PAGEREF_ACTIVATE
;
1224 return PAGEREF_KEEP
;
1227 /* Reclaim if clean, defer dirty pages to writeback */
1228 if (referenced_page
&& !PageSwapBacked(page
))
1229 return PAGEREF_RECLAIM_CLEAN
;
1231 return PAGEREF_RECLAIM
;
1234 /* Check if a page is dirty or under writeback */
1235 static void page_check_dirty_writeback(struct page
*page
,
1236 bool *dirty
, bool *writeback
)
1238 struct address_space
*mapping
;
1241 * Anonymous pages are not handled by flushers and must be written
1242 * from reclaim context. Do not stall reclaim based on them
1244 if (!page_is_file_lru(page
) ||
1245 (PageAnon(page
) && !PageSwapBacked(page
))) {
1251 /* By default assume that the page flags are accurate */
1252 *dirty
= PageDirty(page
);
1253 *writeback
= PageWriteback(page
);
1255 /* Verify dirty/writeback state if the filesystem supports it */
1256 if (!page_has_private(page
))
1259 mapping
= page_mapping(page
);
1260 if (mapping
&& mapping
->a_ops
->is_dirty_writeback
)
1261 mapping
->a_ops
->is_dirty_writeback(page
, dirty
, writeback
);
1265 * shrink_page_list() returns the number of reclaimed pages
1267 static unsigned int shrink_page_list(struct list_head
*page_list
,
1268 struct pglist_data
*pgdat
,
1269 struct scan_control
*sc
,
1270 struct reclaim_stat
*stat
,
1271 bool ignore_references
)
1273 LIST_HEAD(ret_pages
);
1274 LIST_HEAD(free_pages
);
1275 unsigned int nr_reclaimed
= 0;
1276 unsigned int pgactivate
= 0;
1278 memset(stat
, 0, sizeof(*stat
));
1281 while (!list_empty(page_list
)) {
1282 struct address_space
*mapping
;
1284 enum page_references references
= PAGEREF_RECLAIM
;
1285 bool dirty
, writeback
, may_enter_fs
;
1286 unsigned int nr_pages
;
1290 page
= lru_to_page(page_list
);
1291 list_del(&page
->lru
);
1293 if (!trylock_page(page
))
1296 VM_BUG_ON_PAGE(PageActive(page
), page
);
1298 nr_pages
= compound_nr(page
);
1300 /* Account the number of base pages even though THP */
1301 sc
->nr_scanned
+= nr_pages
;
1303 if (unlikely(!page_evictable(page
)))
1304 goto activate_locked
;
1306 if (!sc
->may_unmap
&& page_mapped(page
))
1309 may_enter_fs
= (sc
->gfp_mask
& __GFP_FS
) ||
1310 (PageSwapCache(page
) && (sc
->gfp_mask
& __GFP_IO
));
1313 * The number of dirty pages determines if a node is marked
1314 * reclaim_congested which affects wait_iff_congested. kswapd
1315 * will stall and start writing pages if the tail of the LRU
1316 * is all dirty unqueued pages.
1318 page_check_dirty_writeback(page
, &dirty
, &writeback
);
1319 if (dirty
|| writeback
)
1322 if (dirty
&& !writeback
)
1323 stat
->nr_unqueued_dirty
++;
1326 * Treat this page as congested if the underlying BDI is or if
1327 * pages are cycling through the LRU so quickly that the
1328 * pages marked for immediate reclaim are making it to the
1329 * end of the LRU a second time.
1331 mapping
= page_mapping(page
);
1332 if (((dirty
|| writeback
) && mapping
&&
1333 inode_write_congested(mapping
->host
)) ||
1334 (writeback
&& PageReclaim(page
)))
1335 stat
->nr_congested
++;
1338 * If a page at the tail of the LRU is under writeback, there
1339 * are three cases to consider.
1341 * 1) If reclaim is encountering an excessive number of pages
1342 * under writeback and this page is both under writeback and
1343 * PageReclaim then it indicates that pages are being queued
1344 * for IO but are being recycled through the LRU before the
1345 * IO can complete. Waiting on the page itself risks an
1346 * indefinite stall if it is impossible to writeback the
1347 * page due to IO error or disconnected storage so instead
1348 * note that the LRU is being scanned too quickly and the
1349 * caller can stall after page list has been processed.
1351 * 2) Global or new memcg reclaim encounters a page that is
1352 * not marked for immediate reclaim, or the caller does not
1353 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1354 * not to fs). In this case mark the page for immediate
1355 * reclaim and continue scanning.
1357 * Require may_enter_fs because we would wait on fs, which
1358 * may not have submitted IO yet. And the loop driver might
1359 * enter reclaim, and deadlock if it waits on a page for
1360 * which it is needed to do the write (loop masks off
1361 * __GFP_IO|__GFP_FS for this reason); but more thought
1362 * would probably show more reasons.
1364 * 3) Legacy memcg encounters a page that is already marked
1365 * PageReclaim. memcg does not have any dirty pages
1366 * throttling so we could easily OOM just because too many
1367 * pages are in writeback and there is nothing else to
1368 * reclaim. Wait for the writeback to complete.
1370 * In cases 1) and 2) we activate the pages to get them out of
1371 * the way while we continue scanning for clean pages on the
1372 * inactive list and refilling from the active list. The
1373 * observation here is that waiting for disk writes is more
1374 * expensive than potentially causing reloads down the line.
1375 * Since they're marked for immediate reclaim, they won't put
1376 * memory pressure on the cache working set any longer than it
1377 * takes to write them to disk.
1379 if (PageWriteback(page
)) {
1381 if (current_is_kswapd() &&
1382 PageReclaim(page
) &&
1383 test_bit(PGDAT_WRITEBACK
, &pgdat
->flags
)) {
1384 stat
->nr_immediate
++;
1385 goto activate_locked
;
1388 } else if (writeback_throttling_sane(sc
) ||
1389 !PageReclaim(page
) || !may_enter_fs
) {
1391 * This is slightly racy - end_page_writeback()
1392 * might have just cleared PageReclaim, then
1393 * setting PageReclaim here end up interpreted
1394 * as PageReadahead - but that does not matter
1395 * enough to care. What we do want is for this
1396 * page to have PageReclaim set next time memcg
1397 * reclaim reaches the tests above, so it will
1398 * then wait_on_page_writeback() to avoid OOM;
1399 * and it's also appropriate in global reclaim.
1401 SetPageReclaim(page
);
1402 stat
->nr_writeback
++;
1403 goto activate_locked
;
1408 wait_on_page_writeback(page
);
1409 /* then go back and try same page again */
1410 list_add_tail(&page
->lru
, page_list
);
1415 if (!ignore_references
)
1416 references
= page_check_references(page
, sc
);
1418 switch (references
) {
1419 case PAGEREF_ACTIVATE
:
1420 goto activate_locked
;
1422 stat
->nr_ref_keep
+= nr_pages
;
1424 case PAGEREF_RECLAIM
:
1425 case PAGEREF_RECLAIM_CLEAN
:
1426 ; /* try to reclaim the page below */
1430 * Anonymous process memory has backing store?
1431 * Try to allocate it some swap space here.
1432 * Lazyfree page could be freed directly
1434 if (PageAnon(page
) && PageSwapBacked(page
)) {
1435 if (!PageSwapCache(page
)) {
1436 if (!(sc
->gfp_mask
& __GFP_IO
))
1438 if (page_maybe_dma_pinned(page
))
1440 if (PageTransHuge(page
)) {
1441 /* cannot split THP, skip it */
1442 if (!can_split_huge_page(page
, NULL
))
1443 goto activate_locked
;
1445 * Split pages without a PMD map right
1446 * away. Chances are some or all of the
1447 * tail pages can be freed without IO.
1449 if (!compound_mapcount(page
) &&
1450 split_huge_page_to_list(page
,
1452 goto activate_locked
;
1454 if (!add_to_swap(page
)) {
1455 if (!PageTransHuge(page
))
1456 goto activate_locked_split
;
1457 /* Fallback to swap normal pages */
1458 if (split_huge_page_to_list(page
,
1460 goto activate_locked
;
1461 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1462 count_vm_event(THP_SWPOUT_FALLBACK
);
1464 if (!add_to_swap(page
))
1465 goto activate_locked_split
;
1468 may_enter_fs
= true;
1470 /* Adding to swap updated mapping */
1471 mapping
= page_mapping(page
);
1473 } else if (unlikely(PageTransHuge(page
))) {
1474 /* Split file THP */
1475 if (split_huge_page_to_list(page
, page_list
))
1480 * THP may get split above, need minus tail pages and update
1481 * nr_pages to avoid accounting tail pages twice.
1483 * The tail pages that are added into swap cache successfully
1486 if ((nr_pages
> 1) && !PageTransHuge(page
)) {
1487 sc
->nr_scanned
-= (nr_pages
- 1);
1492 * The page is mapped into the page tables of one or more
1493 * processes. Try to unmap it here.
1495 if (page_mapped(page
)) {
1496 enum ttu_flags flags
= TTU_BATCH_FLUSH
;
1497 bool was_swapbacked
= PageSwapBacked(page
);
1499 if (unlikely(PageTransHuge(page
)))
1500 flags
|= TTU_SPLIT_HUGE_PMD
;
1502 try_to_unmap(page
, flags
);
1503 if (page_mapped(page
)) {
1504 stat
->nr_unmap_fail
+= nr_pages
;
1505 if (!was_swapbacked
&& PageSwapBacked(page
))
1506 stat
->nr_lazyfree_fail
+= nr_pages
;
1507 goto activate_locked
;
1511 if (PageDirty(page
)) {
1513 * Only kswapd can writeback filesystem pages
1514 * to avoid risk of stack overflow. But avoid
1515 * injecting inefficient single-page IO into
1516 * flusher writeback as much as possible: only
1517 * write pages when we've encountered many
1518 * dirty pages, and when we've already scanned
1519 * the rest of the LRU for clean pages and see
1520 * the same dirty pages again (PageReclaim).
1522 if (page_is_file_lru(page
) &&
1523 (!current_is_kswapd() || !PageReclaim(page
) ||
1524 !test_bit(PGDAT_DIRTY
, &pgdat
->flags
))) {
1526 * Immediately reclaim when written back.
1527 * Similar in principal to deactivate_page()
1528 * except we already have the page isolated
1529 * and know it's dirty
1531 inc_node_page_state(page
, NR_VMSCAN_IMMEDIATE
);
1532 SetPageReclaim(page
);
1534 goto activate_locked
;
1537 if (references
== PAGEREF_RECLAIM_CLEAN
)
1541 if (!sc
->may_writepage
)
1545 * Page is dirty. Flush the TLB if a writable entry
1546 * potentially exists to avoid CPU writes after IO
1547 * starts and then write it out here.
1549 try_to_unmap_flush_dirty();
1550 switch (pageout(page
, mapping
)) {
1554 goto activate_locked
;
1556 stat
->nr_pageout
+= thp_nr_pages(page
);
1558 if (PageWriteback(page
))
1560 if (PageDirty(page
))
1564 * A synchronous write - probably a ramdisk. Go
1565 * ahead and try to reclaim the page.
1567 if (!trylock_page(page
))
1569 if (PageDirty(page
) || PageWriteback(page
))
1571 mapping
= page_mapping(page
);
1574 ; /* try to free the page below */
1579 * If the page has buffers, try to free the buffer mappings
1580 * associated with this page. If we succeed we try to free
1583 * We do this even if the page is PageDirty().
1584 * try_to_release_page() does not perform I/O, but it is
1585 * possible for a page to have PageDirty set, but it is actually
1586 * clean (all its buffers are clean). This happens if the
1587 * buffers were written out directly, with submit_bh(). ext3
1588 * will do this, as well as the blockdev mapping.
1589 * try_to_release_page() will discover that cleanness and will
1590 * drop the buffers and mark the page clean - it can be freed.
1592 * Rarely, pages can have buffers and no ->mapping. These are
1593 * the pages which were not successfully invalidated in
1594 * truncate_cleanup_page(). We try to drop those buffers here
1595 * and if that worked, and the page is no longer mapped into
1596 * process address space (page_count == 1) it can be freed.
1597 * Otherwise, leave the page on the LRU so it is swappable.
1599 if (page_has_private(page
)) {
1600 if (!try_to_release_page(page
, sc
->gfp_mask
))
1601 goto activate_locked
;
1602 if (!mapping
&& page_count(page
) == 1) {
1604 if (put_page_testzero(page
))
1608 * rare race with speculative reference.
1609 * the speculative reference will free
1610 * this page shortly, so we may
1611 * increment nr_reclaimed here (and
1612 * leave it off the LRU).
1620 if (PageAnon(page
) && !PageSwapBacked(page
)) {
1621 /* follow __remove_mapping for reference */
1622 if (!page_ref_freeze(page
, 1))
1624 if (PageDirty(page
)) {
1625 page_ref_unfreeze(page
, 1);
1629 count_vm_event(PGLAZYFREED
);
1630 count_memcg_page_event(page
, PGLAZYFREED
);
1631 } else if (!mapping
|| !__remove_mapping(mapping
, page
, true,
1632 sc
->target_mem_cgroup
))
1638 * THP may get swapped out in a whole, need account
1641 nr_reclaimed
+= nr_pages
;
1644 * Is there need to periodically free_page_list? It would
1645 * appear not as the counts should be low
1647 if (unlikely(PageTransHuge(page
)))
1648 destroy_compound_page(page
);
1650 list_add(&page
->lru
, &free_pages
);
1653 activate_locked_split
:
1655 * The tail pages that are failed to add into swap cache
1656 * reach here. Fixup nr_scanned and nr_pages.
1659 sc
->nr_scanned
-= (nr_pages
- 1);
1663 /* Not a candidate for swapping, so reclaim swap space. */
1664 if (PageSwapCache(page
) && (mem_cgroup_swap_full(page
) ||
1666 try_to_free_swap(page
);
1667 VM_BUG_ON_PAGE(PageActive(page
), page
);
1668 if (!PageMlocked(page
)) {
1669 int type
= page_is_file_lru(page
);
1670 SetPageActive(page
);
1671 stat
->nr_activate
[type
] += nr_pages
;
1672 count_memcg_page_event(page
, PGACTIVATE
);
1677 list_add(&page
->lru
, &ret_pages
);
1678 VM_BUG_ON_PAGE(PageLRU(page
) || PageUnevictable(page
), page
);
1681 pgactivate
= stat
->nr_activate
[0] + stat
->nr_activate
[1];
1683 mem_cgroup_uncharge_list(&free_pages
);
1684 try_to_unmap_flush();
1685 free_unref_page_list(&free_pages
);
1687 list_splice(&ret_pages
, page_list
);
1688 count_vm_events(PGACTIVATE
, pgactivate
);
1690 return nr_reclaimed
;
1693 unsigned int reclaim_clean_pages_from_list(struct zone
*zone
,
1694 struct list_head
*page_list
)
1696 struct scan_control sc
= {
1697 .gfp_mask
= GFP_KERNEL
,
1698 .priority
= DEF_PRIORITY
,
1701 struct reclaim_stat stat
;
1702 unsigned int nr_reclaimed
;
1703 struct page
*page
, *next
;
1704 LIST_HEAD(clean_pages
);
1705 unsigned int noreclaim_flag
;
1707 list_for_each_entry_safe(page
, next
, page_list
, lru
) {
1708 if (!PageHuge(page
) && page_is_file_lru(page
) &&
1709 !PageDirty(page
) && !__PageMovable(page
) &&
1710 !PageUnevictable(page
)) {
1711 ClearPageActive(page
);
1712 list_move(&page
->lru
, &clean_pages
);
1717 * We should be safe here since we are only dealing with file pages and
1718 * we are not kswapd and therefore cannot write dirty file pages. But
1719 * call memalloc_noreclaim_save() anyway, just in case these conditions
1720 * change in the future.
1722 noreclaim_flag
= memalloc_noreclaim_save();
1723 nr_reclaimed
= shrink_page_list(&clean_pages
, zone
->zone_pgdat
, &sc
,
1725 memalloc_noreclaim_restore(noreclaim_flag
);
1727 list_splice(&clean_pages
, page_list
);
1728 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1729 -(long)nr_reclaimed
);
1731 * Since lazyfree pages are isolated from file LRU from the beginning,
1732 * they will rotate back to anonymous LRU in the end if it failed to
1733 * discard so isolated count will be mismatched.
1734 * Compensate the isolated count for both LRU lists.
1736 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_ANON
,
1737 stat
.nr_lazyfree_fail
);
1738 mod_node_page_state(zone
->zone_pgdat
, NR_ISOLATED_FILE
,
1739 -(long)stat
.nr_lazyfree_fail
);
1740 return nr_reclaimed
;
1744 * Attempt to remove the specified page from its LRU. Only take this page
1745 * if it is of the appropriate PageActive status. Pages which are being
1746 * freed elsewhere are also ignored.
1748 * page: page to consider
1749 * mode: one of the LRU isolation modes defined above
1751 * returns true on success, false on failure.
1753 bool __isolate_lru_page_prepare(struct page
*page
, isolate_mode_t mode
)
1755 /* Only take pages on the LRU. */
1759 /* Compaction should not handle unevictable pages but CMA can do so */
1760 if (PageUnevictable(page
) && !(mode
& ISOLATE_UNEVICTABLE
))
1764 * To minimise LRU disruption, the caller can indicate that it only
1765 * wants to isolate pages it will be able to operate on without
1766 * blocking - clean pages for the most part.
1768 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1769 * that it is possible to migrate without blocking
1771 if (mode
& ISOLATE_ASYNC_MIGRATE
) {
1772 /* All the caller can do on PageWriteback is block */
1773 if (PageWriteback(page
))
1776 if (PageDirty(page
)) {
1777 struct address_space
*mapping
;
1781 * Only pages without mappings or that have a
1782 * ->migratepage callback are possible to migrate
1783 * without blocking. However, we can be racing with
1784 * truncation so it's necessary to lock the page
1785 * to stabilise the mapping as truncation holds
1786 * the page lock until after the page is removed
1787 * from the page cache.
1789 if (!trylock_page(page
))
1792 mapping
= page_mapping(page
);
1793 migrate_dirty
= !mapping
|| mapping
->a_ops
->migratepage
;
1800 if ((mode
& ISOLATE_UNMAPPED
) && page_mapped(page
))
1807 * Update LRU sizes after isolating pages. The LRU size updates must
1808 * be complete before mem_cgroup_update_lru_size due to a sanity check.
1810 static __always_inline
void update_lru_sizes(struct lruvec
*lruvec
,
1811 enum lru_list lru
, unsigned long *nr_zone_taken
)
1815 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1816 if (!nr_zone_taken
[zid
])
1819 update_lru_size(lruvec
, lru
, zid
, -nr_zone_taken
[zid
]);
1825 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1827 * lruvec->lru_lock is heavily contended. Some of the functions that
1828 * shrink the lists perform better by taking out a batch of pages
1829 * and working on them outside the LRU lock.
1831 * For pagecache intensive workloads, this function is the hottest
1832 * spot in the kernel (apart from copy_*_user functions).
1834 * Lru_lock must be held before calling this function.
1836 * @nr_to_scan: The number of eligible pages to look through on the list.
1837 * @lruvec: The LRU vector to pull pages from.
1838 * @dst: The temp list to put pages on to.
1839 * @nr_scanned: The number of pages that were scanned.
1840 * @sc: The scan_control struct for this reclaim session
1841 * @lru: LRU list id for isolating
1843 * returns how many pages were moved onto *@dst.
1845 static unsigned long isolate_lru_pages(unsigned long nr_to_scan
,
1846 struct lruvec
*lruvec
, struct list_head
*dst
,
1847 unsigned long *nr_scanned
, struct scan_control
*sc
,
1850 struct list_head
*src
= &lruvec
->lists
[lru
];
1851 unsigned long nr_taken
= 0;
1852 unsigned long nr_zone_taken
[MAX_NR_ZONES
] = { 0 };
1853 unsigned long nr_skipped
[MAX_NR_ZONES
] = { 0, };
1854 unsigned long skipped
= 0;
1855 unsigned long scan
, total_scan
, nr_pages
;
1856 LIST_HEAD(pages_skipped
);
1857 isolate_mode_t mode
= (sc
->may_unmap
? 0 : ISOLATE_UNMAPPED
);
1861 while (scan
< nr_to_scan
&& !list_empty(src
)) {
1864 page
= lru_to_page(src
);
1865 prefetchw_prev_lru_page(page
, src
, flags
);
1867 nr_pages
= compound_nr(page
);
1868 total_scan
+= nr_pages
;
1870 if (page_zonenum(page
) > sc
->reclaim_idx
) {
1871 list_move(&page
->lru
, &pages_skipped
);
1872 nr_skipped
[page_zonenum(page
)] += nr_pages
;
1877 * Do not count skipped pages because that makes the function
1878 * return with no isolated pages if the LRU mostly contains
1879 * ineligible pages. This causes the VM to not reclaim any
1880 * pages, triggering a premature OOM.
1882 * Account all tail pages of THP. This would not cause
1883 * premature OOM since __isolate_lru_page() returns -EBUSY
1884 * only when the page is being freed somewhere else.
1887 if (!__isolate_lru_page_prepare(page
, mode
)) {
1888 /* It is being freed elsewhere */
1889 list_move(&page
->lru
, src
);
1893 * Be careful not to clear PageLRU until after we're
1894 * sure the page is not being freed elsewhere -- the
1895 * page release code relies on it.
1897 if (unlikely(!get_page_unless_zero(page
))) {
1898 list_move(&page
->lru
, src
);
1902 if (!TestClearPageLRU(page
)) {
1903 /* Another thread is already isolating this page */
1905 list_move(&page
->lru
, src
);
1909 nr_taken
+= nr_pages
;
1910 nr_zone_taken
[page_zonenum(page
)] += nr_pages
;
1911 list_move(&page
->lru
, dst
);
1915 * Splice any skipped pages to the start of the LRU list. Note that
1916 * this disrupts the LRU order when reclaiming for lower zones but
1917 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
1918 * scanning would soon rescan the same pages to skip and put the
1919 * system at risk of premature OOM.
1921 if (!list_empty(&pages_skipped
)) {
1924 list_splice(&pages_skipped
, src
);
1925 for (zid
= 0; zid
< MAX_NR_ZONES
; zid
++) {
1926 if (!nr_skipped
[zid
])
1929 __count_zid_vm_events(PGSCAN_SKIP
, zid
, nr_skipped
[zid
]);
1930 skipped
+= nr_skipped
[zid
];
1933 *nr_scanned
= total_scan
;
1934 trace_mm_vmscan_lru_isolate(sc
->reclaim_idx
, sc
->order
, nr_to_scan
,
1935 total_scan
, skipped
, nr_taken
, mode
, lru
);
1936 update_lru_sizes(lruvec
, lru
, nr_zone_taken
);
1941 * isolate_lru_page - tries to isolate a page from its LRU list
1942 * @page: page to isolate from its LRU list
1944 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1945 * vmstat statistic corresponding to whatever LRU list the page was on.
1947 * Returns 0 if the page was removed from an LRU list.
1948 * Returns -EBUSY if the page was not on an LRU list.
1950 * The returned page will have PageLRU() cleared. If it was found on
1951 * the active list, it will have PageActive set. If it was found on
1952 * the unevictable list, it will have the PageUnevictable bit set. That flag
1953 * may need to be cleared by the caller before letting the page go.
1955 * The vmstat statistic corresponding to the list on which the page was
1956 * found will be decremented.
1960 * (1) Must be called with an elevated refcount on the page. This is a
1961 * fundamental difference from isolate_lru_pages (which is called
1962 * without a stable reference).
1963 * (2) the lru_lock must not be held.
1964 * (3) interrupts must be enabled.
1966 int isolate_lru_page(struct page
*page
)
1970 VM_BUG_ON_PAGE(!page_count(page
), page
);
1971 WARN_RATELIMIT(PageTail(page
), "trying to isolate tail page");
1973 if (TestClearPageLRU(page
)) {
1974 struct lruvec
*lruvec
;
1977 lruvec
= lock_page_lruvec_irq(page
);
1978 del_page_from_lru_list(page
, lruvec
);
1979 unlock_page_lruvec_irq(lruvec
);
1987 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1988 * then get rescheduled. When there are massive number of tasks doing page
1989 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1990 * the LRU list will go small and be scanned faster than necessary, leading to
1991 * unnecessary swapping, thrashing and OOM.
1993 static int too_many_isolated(struct pglist_data
*pgdat
, int file
,
1994 struct scan_control
*sc
)
1996 unsigned long inactive
, isolated
;
1998 if (current_is_kswapd())
2001 if (!writeback_throttling_sane(sc
))
2005 inactive
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
2006 isolated
= node_page_state(pgdat
, NR_ISOLATED_FILE
);
2008 inactive
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2009 isolated
= node_page_state(pgdat
, NR_ISOLATED_ANON
);
2013 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2014 * won't get blocked by normal direct-reclaimers, forming a circular
2017 if ((sc
->gfp_mask
& (__GFP_IO
| __GFP_FS
)) == (__GFP_IO
| __GFP_FS
))
2020 return isolated
> inactive
;
2024 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2025 * On return, @list is reused as a list of pages to be freed by the caller.
2027 * Returns the number of pages moved to the given lruvec.
2029 static unsigned int move_pages_to_lru(struct lruvec
*lruvec
,
2030 struct list_head
*list
)
2032 int nr_pages
, nr_moved
= 0;
2033 LIST_HEAD(pages_to_free
);
2036 while (!list_empty(list
)) {
2037 page
= lru_to_page(list
);
2038 VM_BUG_ON_PAGE(PageLRU(page
), page
);
2039 list_del(&page
->lru
);
2040 if (unlikely(!page_evictable(page
))) {
2041 spin_unlock_irq(&lruvec
->lru_lock
);
2042 putback_lru_page(page
);
2043 spin_lock_irq(&lruvec
->lru_lock
);
2048 * The SetPageLRU needs to be kept here for list integrity.
2050 * #0 move_pages_to_lru #1 release_pages
2051 * if !put_page_testzero
2052 * if (put_page_testzero())
2053 * !PageLRU //skip lru_lock
2055 * list_add(&page->lru,)
2056 * list_add(&page->lru,)
2060 if (unlikely(put_page_testzero(page
))) {
2061 __clear_page_lru_flags(page
);
2063 if (unlikely(PageCompound(page
))) {
2064 spin_unlock_irq(&lruvec
->lru_lock
);
2065 destroy_compound_page(page
);
2066 spin_lock_irq(&lruvec
->lru_lock
);
2068 list_add(&page
->lru
, &pages_to_free
);
2074 * All pages were isolated from the same lruvec (and isolation
2075 * inhibits memcg migration).
2077 VM_BUG_ON_PAGE(!page_matches_lruvec(page
, lruvec
), page
);
2078 add_page_to_lru_list(page
, lruvec
);
2079 nr_pages
= thp_nr_pages(page
);
2080 nr_moved
+= nr_pages
;
2081 if (PageActive(page
))
2082 workingset_age_nonresident(lruvec
, nr_pages
);
2086 * To save our caller's stack, now use input list for pages to free.
2088 list_splice(&pages_to_free
, list
);
2094 * If a kernel thread (such as nfsd for loop-back mounts) services
2095 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
2096 * In that case we should only throttle if the backing device it is
2097 * writing to is congested. In other cases it is safe to throttle.
2099 static int current_may_throttle(void)
2101 return !(current
->flags
& PF_LOCAL_THROTTLE
) ||
2102 current
->backing_dev_info
== NULL
||
2103 bdi_write_congested(current
->backing_dev_info
);
2107 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
2108 * of reclaimed pages
2110 static unsigned long
2111 shrink_inactive_list(unsigned long nr_to_scan
, struct lruvec
*lruvec
,
2112 struct scan_control
*sc
, enum lru_list lru
)
2114 LIST_HEAD(page_list
);
2115 unsigned long nr_scanned
;
2116 unsigned int nr_reclaimed
= 0;
2117 unsigned long nr_taken
;
2118 struct reclaim_stat stat
;
2119 bool file
= is_file_lru(lru
);
2120 enum vm_event_item item
;
2121 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2122 bool stalled
= false;
2124 while (unlikely(too_many_isolated(pgdat
, file
, sc
))) {
2128 /* wait a bit for the reclaimer. */
2132 /* We are about to die and free our memory. Return now. */
2133 if (fatal_signal_pending(current
))
2134 return SWAP_CLUSTER_MAX
;
2139 spin_lock_irq(&lruvec
->lru_lock
);
2141 nr_taken
= isolate_lru_pages(nr_to_scan
, lruvec
, &page_list
,
2142 &nr_scanned
, sc
, lru
);
2144 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2145 item
= current_is_kswapd() ? PGSCAN_KSWAPD
: PGSCAN_DIRECT
;
2146 if (!cgroup_reclaim(sc
))
2147 __count_vm_events(item
, nr_scanned
);
2148 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_scanned
);
2149 __count_vm_events(PGSCAN_ANON
+ file
, nr_scanned
);
2151 spin_unlock_irq(&lruvec
->lru_lock
);
2156 nr_reclaimed
= shrink_page_list(&page_list
, pgdat
, sc
, &stat
, false);
2158 spin_lock_irq(&lruvec
->lru_lock
);
2159 move_pages_to_lru(lruvec
, &page_list
);
2161 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2162 item
= current_is_kswapd() ? PGSTEAL_KSWAPD
: PGSTEAL_DIRECT
;
2163 if (!cgroup_reclaim(sc
))
2164 __count_vm_events(item
, nr_reclaimed
);
2165 __count_memcg_events(lruvec_memcg(lruvec
), item
, nr_reclaimed
);
2166 __count_vm_events(PGSTEAL_ANON
+ file
, nr_reclaimed
);
2167 spin_unlock_irq(&lruvec
->lru_lock
);
2169 lru_note_cost(lruvec
, file
, stat
.nr_pageout
);
2170 mem_cgroup_uncharge_list(&page_list
);
2171 free_unref_page_list(&page_list
);
2174 * If dirty pages are scanned that are not queued for IO, it
2175 * implies that flushers are not doing their job. This can
2176 * happen when memory pressure pushes dirty pages to the end of
2177 * the LRU before the dirty limits are breached and the dirty
2178 * data has expired. It can also happen when the proportion of
2179 * dirty pages grows not through writes but through memory
2180 * pressure reclaiming all the clean cache. And in some cases,
2181 * the flushers simply cannot keep up with the allocation
2182 * rate. Nudge the flusher threads in case they are asleep.
2184 if (stat
.nr_unqueued_dirty
== nr_taken
)
2185 wakeup_flusher_threads(WB_REASON_VMSCAN
);
2187 sc
->nr
.dirty
+= stat
.nr_dirty
;
2188 sc
->nr
.congested
+= stat
.nr_congested
;
2189 sc
->nr
.unqueued_dirty
+= stat
.nr_unqueued_dirty
;
2190 sc
->nr
.writeback
+= stat
.nr_writeback
;
2191 sc
->nr
.immediate
+= stat
.nr_immediate
;
2192 sc
->nr
.taken
+= nr_taken
;
2194 sc
->nr
.file_taken
+= nr_taken
;
2196 trace_mm_vmscan_lru_shrink_inactive(pgdat
->node_id
,
2197 nr_scanned
, nr_reclaimed
, &stat
, sc
->priority
, file
);
2198 return nr_reclaimed
;
2202 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2204 * We move them the other way if the page is referenced by one or more
2207 * If the pages are mostly unmapped, the processing is fast and it is
2208 * appropriate to hold lru_lock across the whole operation. But if
2209 * the pages are mapped, the processing is slow (page_referenced()), so
2210 * we should drop lru_lock around each page. It's impossible to balance
2211 * this, so instead we remove the pages from the LRU while processing them.
2212 * It is safe to rely on PG_active against the non-LRU pages in here because
2213 * nobody will play with that bit on a non-LRU page.
2215 * The downside is that we have to touch page->_refcount against each page.
2216 * But we had to alter page->flags anyway.
2218 static void shrink_active_list(unsigned long nr_to_scan
,
2219 struct lruvec
*lruvec
,
2220 struct scan_control
*sc
,
2223 unsigned long nr_taken
;
2224 unsigned long nr_scanned
;
2225 unsigned long vm_flags
;
2226 LIST_HEAD(l_hold
); /* The pages which were snipped off */
2227 LIST_HEAD(l_active
);
2228 LIST_HEAD(l_inactive
);
2230 unsigned nr_deactivate
, nr_activate
;
2231 unsigned nr_rotated
= 0;
2232 int file
= is_file_lru(lru
);
2233 struct pglist_data
*pgdat
= lruvec_pgdat(lruvec
);
2237 spin_lock_irq(&lruvec
->lru_lock
);
2239 nr_taken
= isolate_lru_pages(nr_to_scan
, lruvec
, &l_hold
,
2240 &nr_scanned
, sc
, lru
);
2242 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, nr_taken
);
2244 if (!cgroup_reclaim(sc
))
2245 __count_vm_events(PGREFILL
, nr_scanned
);
2246 __count_memcg_events(lruvec_memcg(lruvec
), PGREFILL
, nr_scanned
);
2248 spin_unlock_irq(&lruvec
->lru_lock
);
2250 while (!list_empty(&l_hold
)) {
2252 page
= lru_to_page(&l_hold
);
2253 list_del(&page
->lru
);
2255 if (unlikely(!page_evictable(page
))) {
2256 putback_lru_page(page
);
2260 if (unlikely(buffer_heads_over_limit
)) {
2261 if (page_has_private(page
) && trylock_page(page
)) {
2262 if (page_has_private(page
))
2263 try_to_release_page(page
, 0);
2268 if (page_referenced(page
, 0, sc
->target_mem_cgroup
,
2271 * Identify referenced, file-backed active pages and
2272 * give them one more trip around the active list. So
2273 * that executable code get better chances to stay in
2274 * memory under moderate memory pressure. Anon pages
2275 * are not likely to be evicted by use-once streaming
2276 * IO, plus JVM can create lots of anon VM_EXEC pages,
2277 * so we ignore them here.
2279 if ((vm_flags
& VM_EXEC
) && page_is_file_lru(page
)) {
2280 nr_rotated
+= thp_nr_pages(page
);
2281 list_add(&page
->lru
, &l_active
);
2286 ClearPageActive(page
); /* we are de-activating */
2287 SetPageWorkingset(page
);
2288 list_add(&page
->lru
, &l_inactive
);
2292 * Move pages back to the lru list.
2294 spin_lock_irq(&lruvec
->lru_lock
);
2296 nr_activate
= move_pages_to_lru(lruvec
, &l_active
);
2297 nr_deactivate
= move_pages_to_lru(lruvec
, &l_inactive
);
2298 /* Keep all free pages in l_active list */
2299 list_splice(&l_inactive
, &l_active
);
2301 __count_vm_events(PGDEACTIVATE
, nr_deactivate
);
2302 __count_memcg_events(lruvec_memcg(lruvec
), PGDEACTIVATE
, nr_deactivate
);
2304 __mod_node_page_state(pgdat
, NR_ISOLATED_ANON
+ file
, -nr_taken
);
2305 spin_unlock_irq(&lruvec
->lru_lock
);
2307 mem_cgroup_uncharge_list(&l_active
);
2308 free_unref_page_list(&l_active
);
2309 trace_mm_vmscan_lru_shrink_active(pgdat
->node_id
, nr_taken
, nr_activate
,
2310 nr_deactivate
, nr_rotated
, sc
->priority
, file
);
2313 unsigned long reclaim_pages(struct list_head
*page_list
)
2315 int nid
= NUMA_NO_NODE
;
2316 unsigned int nr_reclaimed
= 0;
2317 LIST_HEAD(node_page_list
);
2318 struct reclaim_stat dummy_stat
;
2320 unsigned int noreclaim_flag
;
2321 struct scan_control sc
= {
2322 .gfp_mask
= GFP_KERNEL
,
2323 .priority
= DEF_PRIORITY
,
2329 noreclaim_flag
= memalloc_noreclaim_save();
2331 while (!list_empty(page_list
)) {
2332 page
= lru_to_page(page_list
);
2333 if (nid
== NUMA_NO_NODE
) {
2334 nid
= page_to_nid(page
);
2335 INIT_LIST_HEAD(&node_page_list
);
2338 if (nid
== page_to_nid(page
)) {
2339 ClearPageActive(page
);
2340 list_move(&page
->lru
, &node_page_list
);
2344 nr_reclaimed
+= shrink_page_list(&node_page_list
,
2346 &sc
, &dummy_stat
, false);
2347 while (!list_empty(&node_page_list
)) {
2348 page
= lru_to_page(&node_page_list
);
2349 list_del(&page
->lru
);
2350 putback_lru_page(page
);
2356 if (!list_empty(&node_page_list
)) {
2357 nr_reclaimed
+= shrink_page_list(&node_page_list
,
2359 &sc
, &dummy_stat
, false);
2360 while (!list_empty(&node_page_list
)) {
2361 page
= lru_to_page(&node_page_list
);
2362 list_del(&page
->lru
);
2363 putback_lru_page(page
);
2367 memalloc_noreclaim_restore(noreclaim_flag
);
2369 return nr_reclaimed
;
2372 static unsigned long shrink_list(enum lru_list lru
, unsigned long nr_to_scan
,
2373 struct lruvec
*lruvec
, struct scan_control
*sc
)
2375 if (is_active_lru(lru
)) {
2376 if (sc
->may_deactivate
& (1 << is_file_lru(lru
)))
2377 shrink_active_list(nr_to_scan
, lruvec
, sc
, lru
);
2379 sc
->skipped_deactivate
= 1;
2383 return shrink_inactive_list(nr_to_scan
, lruvec
, sc
, lru
);
2387 * The inactive anon list should be small enough that the VM never has
2388 * to do too much work.
2390 * The inactive file list should be small enough to leave most memory
2391 * to the established workingset on the scan-resistant active list,
2392 * but large enough to avoid thrashing the aggregate readahead window.
2394 * Both inactive lists should also be large enough that each inactive
2395 * page has a chance to be referenced again before it is reclaimed.
2397 * If that fails and refaulting is observed, the inactive list grows.
2399 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
2400 * on this LRU, maintained by the pageout code. An inactive_ratio
2401 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2404 * memory ratio inactive
2405 * -------------------------------------
2414 static bool inactive_is_low(struct lruvec
*lruvec
, enum lru_list inactive_lru
)
2416 enum lru_list active_lru
= inactive_lru
+ LRU_ACTIVE
;
2417 unsigned long inactive
, active
;
2418 unsigned long inactive_ratio
;
2421 inactive
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ inactive_lru
);
2422 active
= lruvec_page_state(lruvec
, NR_LRU_BASE
+ active_lru
);
2424 gb
= (inactive
+ active
) >> (30 - PAGE_SHIFT
);
2426 inactive_ratio
= int_sqrt(10 * gb
);
2430 return inactive
* inactive_ratio
< active
;
2441 * Determine how aggressively the anon and file LRU lists should be
2442 * scanned. The relative value of each set of LRU lists is determined
2443 * by looking at the fraction of the pages scanned we did rotate back
2444 * onto the active list instead of evict.
2446 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2447 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
2449 static void get_scan_count(struct lruvec
*lruvec
, struct scan_control
*sc
,
2452 struct mem_cgroup
*memcg
= lruvec_memcg(lruvec
);
2453 unsigned long anon_cost
, file_cost
, total_cost
;
2454 int swappiness
= mem_cgroup_swappiness(memcg
);
2455 u64 fraction
[ANON_AND_FILE
];
2456 u64 denominator
= 0; /* gcc */
2457 enum scan_balance scan_balance
;
2458 unsigned long ap
, fp
;
2461 /* If we have no swap space, do not bother scanning anon pages. */
2462 if (!sc
->may_swap
|| mem_cgroup_get_nr_swap_pages(memcg
) <= 0) {
2463 scan_balance
= SCAN_FILE
;
2468 * Global reclaim will swap to prevent OOM even with no
2469 * swappiness, but memcg users want to use this knob to
2470 * disable swapping for individual groups completely when
2471 * using the memory controller's swap limit feature would be
2474 if (cgroup_reclaim(sc
) && !swappiness
) {
2475 scan_balance
= SCAN_FILE
;
2480 * Do not apply any pressure balancing cleverness when the
2481 * system is close to OOM, scan both anon and file equally
2482 * (unless the swappiness setting disagrees with swapping).
2484 if (!sc
->priority
&& swappiness
) {
2485 scan_balance
= SCAN_EQUAL
;
2490 * If the system is almost out of file pages, force-scan anon.
2492 if (sc
->file_is_tiny
) {
2493 scan_balance
= SCAN_ANON
;
2498 * If there is enough inactive page cache, we do not reclaim
2499 * anything from the anonymous working right now.
2501 if (sc
->cache_trim_mode
) {
2502 scan_balance
= SCAN_FILE
;
2506 scan_balance
= SCAN_FRACT
;
2508 * Calculate the pressure balance between anon and file pages.
2510 * The amount of pressure we put on each LRU is inversely
2511 * proportional to the cost of reclaiming each list, as
2512 * determined by the share of pages that are refaulting, times
2513 * the relative IO cost of bringing back a swapped out
2514 * anonymous page vs reloading a filesystem page (swappiness).
2516 * Although we limit that influence to ensure no list gets
2517 * left behind completely: at least a third of the pressure is
2518 * applied, before swappiness.
2520 * With swappiness at 100, anon and file have equal IO cost.
2522 total_cost
= sc
->anon_cost
+ sc
->file_cost
;
2523 anon_cost
= total_cost
+ sc
->anon_cost
;
2524 file_cost
= total_cost
+ sc
->file_cost
;
2525 total_cost
= anon_cost
+ file_cost
;
2527 ap
= swappiness
* (total_cost
+ 1);
2528 ap
/= anon_cost
+ 1;
2530 fp
= (200 - swappiness
) * (total_cost
+ 1);
2531 fp
/= file_cost
+ 1;
2535 denominator
= ap
+ fp
;
2537 for_each_evictable_lru(lru
) {
2538 int file
= is_file_lru(lru
);
2539 unsigned long lruvec_size
;
2541 unsigned long protection
;
2543 lruvec_size
= lruvec_lru_size(lruvec
, lru
, sc
->reclaim_idx
);
2544 protection
= mem_cgroup_protection(sc
->target_mem_cgroup
,
2546 sc
->memcg_low_reclaim
);
2550 * Scale a cgroup's reclaim pressure by proportioning
2551 * its current usage to its memory.low or memory.min
2554 * This is important, as otherwise scanning aggression
2555 * becomes extremely binary -- from nothing as we
2556 * approach the memory protection threshold, to totally
2557 * nominal as we exceed it. This results in requiring
2558 * setting extremely liberal protection thresholds. It
2559 * also means we simply get no protection at all if we
2560 * set it too low, which is not ideal.
2562 * If there is any protection in place, we reduce scan
2563 * pressure by how much of the total memory used is
2564 * within protection thresholds.
2566 * There is one special case: in the first reclaim pass,
2567 * we skip over all groups that are within their low
2568 * protection. If that fails to reclaim enough pages to
2569 * satisfy the reclaim goal, we come back and override
2570 * the best-effort low protection. However, we still
2571 * ideally want to honor how well-behaved groups are in
2572 * that case instead of simply punishing them all
2573 * equally. As such, we reclaim them based on how much
2574 * memory they are using, reducing the scan pressure
2575 * again by how much of the total memory used is under
2578 unsigned long cgroup_size
= mem_cgroup_size(memcg
);
2580 /* Avoid TOCTOU with earlier protection check */
2581 cgroup_size
= max(cgroup_size
, protection
);
2583 scan
= lruvec_size
- lruvec_size
* protection
/
2587 * Minimally target SWAP_CLUSTER_MAX pages to keep
2588 * reclaim moving forwards, avoiding decrementing
2589 * sc->priority further than desirable.
2591 scan
= max(scan
, SWAP_CLUSTER_MAX
);
2596 scan
>>= sc
->priority
;
2599 * If the cgroup's already been deleted, make sure to
2600 * scrape out the remaining cache.
2602 if (!scan
&& !mem_cgroup_online(memcg
))
2603 scan
= min(lruvec_size
, SWAP_CLUSTER_MAX
);
2605 switch (scan_balance
) {
2607 /* Scan lists relative to size */
2611 * Scan types proportional to swappiness and
2612 * their relative recent reclaim efficiency.
2613 * Make sure we don't miss the last page on
2614 * the offlined memory cgroups because of a
2617 scan
= mem_cgroup_online(memcg
) ?
2618 div64_u64(scan
* fraction
[file
], denominator
) :
2619 DIV64_U64_ROUND_UP(scan
* fraction
[file
],
2624 /* Scan one type exclusively */
2625 if ((scan_balance
== SCAN_FILE
) != file
)
2629 /* Look ma, no brain */
2637 static void shrink_lruvec(struct lruvec
*lruvec
, struct scan_control
*sc
)
2639 unsigned long nr
[NR_LRU_LISTS
];
2640 unsigned long targets
[NR_LRU_LISTS
];
2641 unsigned long nr_to_scan
;
2643 unsigned long nr_reclaimed
= 0;
2644 unsigned long nr_to_reclaim
= sc
->nr_to_reclaim
;
2645 struct blk_plug plug
;
2648 get_scan_count(lruvec
, sc
, nr
);
2650 /* Record the original scan target for proportional adjustments later */
2651 memcpy(targets
, nr
, sizeof(nr
));
2654 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2655 * event that can occur when there is little memory pressure e.g.
2656 * multiple streaming readers/writers. Hence, we do not abort scanning
2657 * when the requested number of pages are reclaimed when scanning at
2658 * DEF_PRIORITY on the assumption that the fact we are direct
2659 * reclaiming implies that kswapd is not keeping up and it is best to
2660 * do a batch of work at once. For memcg reclaim one check is made to
2661 * abort proportional reclaim if either the file or anon lru has already
2662 * dropped to zero at the first pass.
2664 scan_adjusted
= (!cgroup_reclaim(sc
) && !current_is_kswapd() &&
2665 sc
->priority
== DEF_PRIORITY
);
2667 blk_start_plug(&plug
);
2668 while (nr
[LRU_INACTIVE_ANON
] || nr
[LRU_ACTIVE_FILE
] ||
2669 nr
[LRU_INACTIVE_FILE
]) {
2670 unsigned long nr_anon
, nr_file
, percentage
;
2671 unsigned long nr_scanned
;
2673 for_each_evictable_lru(lru
) {
2675 nr_to_scan
= min(nr
[lru
], SWAP_CLUSTER_MAX
);
2676 nr
[lru
] -= nr_to_scan
;
2678 nr_reclaimed
+= shrink_list(lru
, nr_to_scan
,
2685 if (nr_reclaimed
< nr_to_reclaim
|| scan_adjusted
)
2689 * For kswapd and memcg, reclaim at least the number of pages
2690 * requested. Ensure that the anon and file LRUs are scanned
2691 * proportionally what was requested by get_scan_count(). We
2692 * stop reclaiming one LRU and reduce the amount scanning
2693 * proportional to the original scan target.
2695 nr_file
= nr
[LRU_INACTIVE_FILE
] + nr
[LRU_ACTIVE_FILE
];
2696 nr_anon
= nr
[LRU_INACTIVE_ANON
] + nr
[LRU_ACTIVE_ANON
];
2699 * It's just vindictive to attack the larger once the smaller
2700 * has gone to zero. And given the way we stop scanning the
2701 * smaller below, this makes sure that we only make one nudge
2702 * towards proportionality once we've got nr_to_reclaim.
2704 if (!nr_file
|| !nr_anon
)
2707 if (nr_file
> nr_anon
) {
2708 unsigned long scan_target
= targets
[LRU_INACTIVE_ANON
] +
2709 targets
[LRU_ACTIVE_ANON
] + 1;
2711 percentage
= nr_anon
* 100 / scan_target
;
2713 unsigned long scan_target
= targets
[LRU_INACTIVE_FILE
] +
2714 targets
[LRU_ACTIVE_FILE
] + 1;
2716 percentage
= nr_file
* 100 / scan_target
;
2719 /* Stop scanning the smaller of the LRU */
2721 nr
[lru
+ LRU_ACTIVE
] = 0;
2724 * Recalculate the other LRU scan count based on its original
2725 * scan target and the percentage scanning already complete
2727 lru
= (lru
== LRU_FILE
) ? LRU_BASE
: LRU_FILE
;
2728 nr_scanned
= targets
[lru
] - nr
[lru
];
2729 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
2730 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
2733 nr_scanned
= targets
[lru
] - nr
[lru
];
2734 nr
[lru
] = targets
[lru
] * (100 - percentage
) / 100;
2735 nr
[lru
] -= min(nr
[lru
], nr_scanned
);
2737 scan_adjusted
= true;
2739 blk_finish_plug(&plug
);
2740 sc
->nr_reclaimed
+= nr_reclaimed
;
2743 * Even if we did not try to evict anon pages at all, we want to
2744 * rebalance the anon lru active/inactive ratio.
2746 if (total_swap_pages
&& inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
2747 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
2748 sc
, LRU_ACTIVE_ANON
);
2751 /* Use reclaim/compaction for costly allocs or under memory pressure */
2752 static bool in_reclaim_compaction(struct scan_control
*sc
)
2754 if (IS_ENABLED(CONFIG_COMPACTION
) && sc
->order
&&
2755 (sc
->order
> PAGE_ALLOC_COSTLY_ORDER
||
2756 sc
->priority
< DEF_PRIORITY
- 2))
2763 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2764 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2765 * true if more pages should be reclaimed such that when the page allocator
2766 * calls try_to_compact_pages() that it will have enough free pages to succeed.
2767 * It will give up earlier than that if there is difficulty reclaiming pages.
2769 static inline bool should_continue_reclaim(struct pglist_data
*pgdat
,
2770 unsigned long nr_reclaimed
,
2771 struct scan_control
*sc
)
2773 unsigned long pages_for_compaction
;
2774 unsigned long inactive_lru_pages
;
2777 /* If not in reclaim/compaction mode, stop */
2778 if (!in_reclaim_compaction(sc
))
2782 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
2783 * number of pages that were scanned. This will return to the caller
2784 * with the risk reclaim/compaction and the resulting allocation attempt
2785 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
2786 * allocations through requiring that the full LRU list has been scanned
2787 * first, by assuming that zero delta of sc->nr_scanned means full LRU
2788 * scan, but that approximation was wrong, and there were corner cases
2789 * where always a non-zero amount of pages were scanned.
2794 /* If compaction would go ahead or the allocation would succeed, stop */
2795 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
2796 struct zone
*zone
= &pgdat
->node_zones
[z
];
2797 if (!managed_zone(zone
))
2800 switch (compaction_suitable(zone
, sc
->order
, 0, sc
->reclaim_idx
)) {
2801 case COMPACT_SUCCESS
:
2802 case COMPACT_CONTINUE
:
2805 /* check next zone */
2811 * If we have not reclaimed enough pages for compaction and the
2812 * inactive lists are large enough, continue reclaiming
2814 pages_for_compaction
= compact_gap(sc
->order
);
2815 inactive_lru_pages
= node_page_state(pgdat
, NR_INACTIVE_FILE
);
2816 if (get_nr_swap_pages() > 0)
2817 inactive_lru_pages
+= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2819 return inactive_lru_pages
> pages_for_compaction
;
2822 static void shrink_node_memcgs(pg_data_t
*pgdat
, struct scan_control
*sc
)
2824 struct mem_cgroup
*target_memcg
= sc
->target_mem_cgroup
;
2825 struct mem_cgroup
*memcg
;
2827 memcg
= mem_cgroup_iter(target_memcg
, NULL
, NULL
);
2829 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
2830 unsigned long reclaimed
;
2831 unsigned long scanned
;
2834 * This loop can become CPU-bound when target memcgs
2835 * aren't eligible for reclaim - either because they
2836 * don't have any reclaimable pages, or because their
2837 * memory is explicitly protected. Avoid soft lockups.
2841 mem_cgroup_calculate_protection(target_memcg
, memcg
);
2843 if (mem_cgroup_below_min(memcg
)) {
2846 * If there is no reclaimable memory, OOM.
2849 } else if (mem_cgroup_below_low(memcg
)) {
2852 * Respect the protection only as long as
2853 * there is an unprotected supply
2854 * of reclaimable memory from other cgroups.
2856 if (!sc
->memcg_low_reclaim
) {
2857 sc
->memcg_low_skipped
= 1;
2860 memcg_memory_event(memcg
, MEMCG_LOW
);
2863 reclaimed
= sc
->nr_reclaimed
;
2864 scanned
= sc
->nr_scanned
;
2866 shrink_lruvec(lruvec
, sc
);
2868 shrink_slab(sc
->gfp_mask
, pgdat
->node_id
, memcg
,
2871 /* Record the group's reclaim efficiency */
2872 vmpressure(sc
->gfp_mask
, memcg
, false,
2873 sc
->nr_scanned
- scanned
,
2874 sc
->nr_reclaimed
- reclaimed
);
2876 } while ((memcg
= mem_cgroup_iter(target_memcg
, memcg
, NULL
)));
2879 static void shrink_node(pg_data_t
*pgdat
, struct scan_control
*sc
)
2881 struct reclaim_state
*reclaim_state
= current
->reclaim_state
;
2882 unsigned long nr_reclaimed
, nr_scanned
;
2883 struct lruvec
*target_lruvec
;
2884 bool reclaimable
= false;
2887 target_lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
, pgdat
);
2890 memset(&sc
->nr
, 0, sizeof(sc
->nr
));
2892 nr_reclaimed
= sc
->nr_reclaimed
;
2893 nr_scanned
= sc
->nr_scanned
;
2896 * Determine the scan balance between anon and file LRUs.
2898 spin_lock_irq(&target_lruvec
->lru_lock
);
2899 sc
->anon_cost
= target_lruvec
->anon_cost
;
2900 sc
->file_cost
= target_lruvec
->file_cost
;
2901 spin_unlock_irq(&target_lruvec
->lru_lock
);
2904 * Target desirable inactive:active list ratios for the anon
2905 * and file LRU lists.
2907 if (!sc
->force_deactivate
) {
2908 unsigned long refaults
;
2910 refaults
= lruvec_page_state(target_lruvec
,
2911 WORKINGSET_ACTIVATE_ANON
);
2912 if (refaults
!= target_lruvec
->refaults
[0] ||
2913 inactive_is_low(target_lruvec
, LRU_INACTIVE_ANON
))
2914 sc
->may_deactivate
|= DEACTIVATE_ANON
;
2916 sc
->may_deactivate
&= ~DEACTIVATE_ANON
;
2919 * When refaults are being observed, it means a new
2920 * workingset is being established. Deactivate to get
2921 * rid of any stale active pages quickly.
2923 refaults
= lruvec_page_state(target_lruvec
,
2924 WORKINGSET_ACTIVATE_FILE
);
2925 if (refaults
!= target_lruvec
->refaults
[1] ||
2926 inactive_is_low(target_lruvec
, LRU_INACTIVE_FILE
))
2927 sc
->may_deactivate
|= DEACTIVATE_FILE
;
2929 sc
->may_deactivate
&= ~DEACTIVATE_FILE
;
2931 sc
->may_deactivate
= DEACTIVATE_ANON
| DEACTIVATE_FILE
;
2934 * If we have plenty of inactive file pages that aren't
2935 * thrashing, try to reclaim those first before touching
2938 file
= lruvec_page_state(target_lruvec
, NR_INACTIVE_FILE
);
2939 if (file
>> sc
->priority
&& !(sc
->may_deactivate
& DEACTIVATE_FILE
))
2940 sc
->cache_trim_mode
= 1;
2942 sc
->cache_trim_mode
= 0;
2945 * Prevent the reclaimer from falling into the cache trap: as
2946 * cache pages start out inactive, every cache fault will tip
2947 * the scan balance towards the file LRU. And as the file LRU
2948 * shrinks, so does the window for rotation from references.
2949 * This means we have a runaway feedback loop where a tiny
2950 * thrashing file LRU becomes infinitely more attractive than
2951 * anon pages. Try to detect this based on file LRU size.
2953 if (!cgroup_reclaim(sc
)) {
2954 unsigned long total_high_wmark
= 0;
2955 unsigned long free
, anon
;
2958 free
= sum_zone_node_page_state(pgdat
->node_id
, NR_FREE_PAGES
);
2959 file
= node_page_state(pgdat
, NR_ACTIVE_FILE
) +
2960 node_page_state(pgdat
, NR_INACTIVE_FILE
);
2962 for (z
= 0; z
< MAX_NR_ZONES
; z
++) {
2963 struct zone
*zone
= &pgdat
->node_zones
[z
];
2964 if (!managed_zone(zone
))
2967 total_high_wmark
+= high_wmark_pages(zone
);
2971 * Consider anon: if that's low too, this isn't a
2972 * runaway file reclaim problem, but rather just
2973 * extreme pressure. Reclaim as per usual then.
2975 anon
= node_page_state(pgdat
, NR_INACTIVE_ANON
);
2978 file
+ free
<= total_high_wmark
&&
2979 !(sc
->may_deactivate
& DEACTIVATE_ANON
) &&
2980 anon
>> sc
->priority
;
2983 shrink_node_memcgs(pgdat
, sc
);
2985 if (reclaim_state
) {
2986 sc
->nr_reclaimed
+= reclaim_state
->reclaimed_slab
;
2987 reclaim_state
->reclaimed_slab
= 0;
2990 /* Record the subtree's reclaim efficiency */
2991 vmpressure(sc
->gfp_mask
, sc
->target_mem_cgroup
, true,
2992 sc
->nr_scanned
- nr_scanned
,
2993 sc
->nr_reclaimed
- nr_reclaimed
);
2995 if (sc
->nr_reclaimed
- nr_reclaimed
)
2998 if (current_is_kswapd()) {
3000 * If reclaim is isolating dirty pages under writeback,
3001 * it implies that the long-lived page allocation rate
3002 * is exceeding the page laundering rate. Either the
3003 * global limits are not being effective at throttling
3004 * processes due to the page distribution throughout
3005 * zones or there is heavy usage of a slow backing
3006 * device. The only option is to throttle from reclaim
3007 * context which is not ideal as there is no guarantee
3008 * the dirtying process is throttled in the same way
3009 * balance_dirty_pages() manages.
3011 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3012 * count the number of pages under pages flagged for
3013 * immediate reclaim and stall if any are encountered
3014 * in the nr_immediate check below.
3016 if (sc
->nr
.writeback
&& sc
->nr
.writeback
== sc
->nr
.taken
)
3017 set_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
3019 /* Allow kswapd to start writing pages during reclaim.*/
3020 if (sc
->nr
.unqueued_dirty
== sc
->nr
.file_taken
)
3021 set_bit(PGDAT_DIRTY
, &pgdat
->flags
);
3024 * If kswapd scans pages marked for immediate
3025 * reclaim and under writeback (nr_immediate), it
3026 * implies that pages are cycling through the LRU
3027 * faster than they are written so also forcibly stall.
3029 if (sc
->nr
.immediate
)
3030 congestion_wait(BLK_RW_ASYNC
, HZ
/10);
3034 * Tag a node/memcg as congested if all the dirty pages
3035 * scanned were backed by a congested BDI and
3036 * wait_iff_congested will stall.
3038 * Legacy memcg will stall in page writeback so avoid forcibly
3039 * stalling in wait_iff_congested().
3041 if ((current_is_kswapd() ||
3042 (cgroup_reclaim(sc
) && writeback_throttling_sane(sc
))) &&
3043 sc
->nr
.dirty
&& sc
->nr
.dirty
== sc
->nr
.congested
)
3044 set_bit(LRUVEC_CONGESTED
, &target_lruvec
->flags
);
3047 * Stall direct reclaim for IO completions if underlying BDIs
3048 * and node is congested. Allow kswapd to continue until it
3049 * starts encountering unqueued dirty pages or cycling through
3050 * the LRU too quickly.
3052 if (!current_is_kswapd() && current_may_throttle() &&
3053 !sc
->hibernation_mode
&&
3054 test_bit(LRUVEC_CONGESTED
, &target_lruvec
->flags
))
3055 wait_iff_congested(BLK_RW_ASYNC
, HZ
/10);
3057 if (should_continue_reclaim(pgdat
, sc
->nr_reclaimed
- nr_reclaimed
,
3062 * Kswapd gives up on balancing particular nodes after too
3063 * many failures to reclaim anything from them and goes to
3064 * sleep. On reclaim progress, reset the failure counter. A
3065 * successful direct reclaim run will revive a dormant kswapd.
3068 pgdat
->kswapd_failures
= 0;
3072 * Returns true if compaction should go ahead for a costly-order request, or
3073 * the allocation would already succeed without compaction. Return false if we
3074 * should reclaim first.
3076 static inline bool compaction_ready(struct zone
*zone
, struct scan_control
*sc
)
3078 unsigned long watermark
;
3079 enum compact_result suitable
;
3081 suitable
= compaction_suitable(zone
, sc
->order
, 0, sc
->reclaim_idx
);
3082 if (suitable
== COMPACT_SUCCESS
)
3083 /* Allocation should succeed already. Don't reclaim. */
3085 if (suitable
== COMPACT_SKIPPED
)
3086 /* Compaction cannot yet proceed. Do reclaim. */
3090 * Compaction is already possible, but it takes time to run and there
3091 * are potentially other callers using the pages just freed. So proceed
3092 * with reclaim to make a buffer of free pages available to give
3093 * compaction a reasonable chance of completing and allocating the page.
3094 * Note that we won't actually reclaim the whole buffer in one attempt
3095 * as the target watermark in should_continue_reclaim() is lower. But if
3096 * we are already above the high+gap watermark, don't reclaim at all.
3098 watermark
= high_wmark_pages(zone
) + compact_gap(sc
->order
);
3100 return zone_watermark_ok_safe(zone
, 0, watermark
, sc
->reclaim_idx
);
3104 * This is the direct reclaim path, for page-allocating processes. We only
3105 * try to reclaim pages from zones which will satisfy the caller's allocation
3108 * If a zone is deemed to be full of pinned pages then just give it a light
3109 * scan then give up on it.
3111 static void shrink_zones(struct zonelist
*zonelist
, struct scan_control
*sc
)
3115 unsigned long nr_soft_reclaimed
;
3116 unsigned long nr_soft_scanned
;
3118 pg_data_t
*last_pgdat
= NULL
;
3121 * If the number of buffer_heads in the machine exceeds the maximum
3122 * allowed level, force direct reclaim to scan the highmem zone as
3123 * highmem pages could be pinning lowmem pages storing buffer_heads
3125 orig_mask
= sc
->gfp_mask
;
3126 if (buffer_heads_over_limit
) {
3127 sc
->gfp_mask
|= __GFP_HIGHMEM
;
3128 sc
->reclaim_idx
= gfp_zone(sc
->gfp_mask
);
3131 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
3132 sc
->reclaim_idx
, sc
->nodemask
) {
3134 * Take care memory controller reclaiming has small influence
3137 if (!cgroup_reclaim(sc
)) {
3138 if (!cpuset_zone_allowed(zone
,
3139 GFP_KERNEL
| __GFP_HARDWALL
))
3143 * If we already have plenty of memory free for
3144 * compaction in this zone, don't free any more.
3145 * Even though compaction is invoked for any
3146 * non-zero order, only frequent costly order
3147 * reclamation is disruptive enough to become a
3148 * noticeable problem, like transparent huge
3151 if (IS_ENABLED(CONFIG_COMPACTION
) &&
3152 sc
->order
> PAGE_ALLOC_COSTLY_ORDER
&&
3153 compaction_ready(zone
, sc
)) {
3154 sc
->compaction_ready
= true;
3159 * Shrink each node in the zonelist once. If the
3160 * zonelist is ordered by zone (not the default) then a
3161 * node may be shrunk multiple times but in that case
3162 * the user prefers lower zones being preserved.
3164 if (zone
->zone_pgdat
== last_pgdat
)
3168 * This steals pages from memory cgroups over softlimit
3169 * and returns the number of reclaimed pages and
3170 * scanned pages. This works for global memory pressure
3171 * and balancing, not for a memcg's limit.
3173 nr_soft_scanned
= 0;
3174 nr_soft_reclaimed
= mem_cgroup_soft_limit_reclaim(zone
->zone_pgdat
,
3175 sc
->order
, sc
->gfp_mask
,
3177 sc
->nr_reclaimed
+= nr_soft_reclaimed
;
3178 sc
->nr_scanned
+= nr_soft_scanned
;
3179 /* need some check for avoid more shrink_zone() */
3182 /* See comment about same check for global reclaim above */
3183 if (zone
->zone_pgdat
== last_pgdat
)
3185 last_pgdat
= zone
->zone_pgdat
;
3186 shrink_node(zone
->zone_pgdat
, sc
);
3190 * Restore to original mask to avoid the impact on the caller if we
3191 * promoted it to __GFP_HIGHMEM.
3193 sc
->gfp_mask
= orig_mask
;
3196 static void snapshot_refaults(struct mem_cgroup
*target_memcg
, pg_data_t
*pgdat
)
3198 struct lruvec
*target_lruvec
;
3199 unsigned long refaults
;
3201 target_lruvec
= mem_cgroup_lruvec(target_memcg
, pgdat
);
3202 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_ANON
);
3203 target_lruvec
->refaults
[0] = refaults
;
3204 refaults
= lruvec_page_state(target_lruvec
, WORKINGSET_ACTIVATE_FILE
);
3205 target_lruvec
->refaults
[1] = refaults
;
3209 * This is the main entry point to direct page reclaim.
3211 * If a full scan of the inactive list fails to free enough memory then we
3212 * are "out of memory" and something needs to be killed.
3214 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3215 * high - the zone may be full of dirty or under-writeback pages, which this
3216 * caller can't do much about. We kick the writeback threads and take explicit
3217 * naps in the hope that some of these pages can be written. But if the
3218 * allocating task holds filesystem locks which prevent writeout this might not
3219 * work, and the allocation attempt will fail.
3221 * returns: 0, if no pages reclaimed
3222 * else, the number of pages reclaimed
3224 static unsigned long do_try_to_free_pages(struct zonelist
*zonelist
,
3225 struct scan_control
*sc
)
3227 int initial_priority
= sc
->priority
;
3228 pg_data_t
*last_pgdat
;
3232 delayacct_freepages_start();
3234 if (!cgroup_reclaim(sc
))
3235 __count_zid_vm_events(ALLOCSTALL
, sc
->reclaim_idx
, 1);
3238 vmpressure_prio(sc
->gfp_mask
, sc
->target_mem_cgroup
,
3241 shrink_zones(zonelist
, sc
);
3243 if (sc
->nr_reclaimed
>= sc
->nr_to_reclaim
)
3246 if (sc
->compaction_ready
)
3250 * If we're getting trouble reclaiming, start doing
3251 * writepage even in laptop mode.
3253 if (sc
->priority
< DEF_PRIORITY
- 2)
3254 sc
->may_writepage
= 1;
3255 } while (--sc
->priority
>= 0);
3258 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
, sc
->reclaim_idx
,
3260 if (zone
->zone_pgdat
== last_pgdat
)
3262 last_pgdat
= zone
->zone_pgdat
;
3264 snapshot_refaults(sc
->target_mem_cgroup
, zone
->zone_pgdat
);
3266 if (cgroup_reclaim(sc
)) {
3267 struct lruvec
*lruvec
;
3269 lruvec
= mem_cgroup_lruvec(sc
->target_mem_cgroup
,
3271 clear_bit(LRUVEC_CONGESTED
, &lruvec
->flags
);
3275 delayacct_freepages_end();
3277 if (sc
->nr_reclaimed
)
3278 return sc
->nr_reclaimed
;
3280 /* Aborted reclaim to try compaction? don't OOM, then */
3281 if (sc
->compaction_ready
)
3285 * We make inactive:active ratio decisions based on the node's
3286 * composition of memory, but a restrictive reclaim_idx or a
3287 * memory.low cgroup setting can exempt large amounts of
3288 * memory from reclaim. Neither of which are very common, so
3289 * instead of doing costly eligibility calculations of the
3290 * entire cgroup subtree up front, we assume the estimates are
3291 * good, and retry with forcible deactivation if that fails.
3293 if (sc
->skipped_deactivate
) {
3294 sc
->priority
= initial_priority
;
3295 sc
->force_deactivate
= 1;
3296 sc
->skipped_deactivate
= 0;
3300 /* Untapped cgroup reserves? Don't OOM, retry. */
3301 if (sc
->memcg_low_skipped
) {
3302 sc
->priority
= initial_priority
;
3303 sc
->force_deactivate
= 0;
3304 sc
->memcg_low_reclaim
= 1;
3305 sc
->memcg_low_skipped
= 0;
3312 static bool allow_direct_reclaim(pg_data_t
*pgdat
)
3315 unsigned long pfmemalloc_reserve
= 0;
3316 unsigned long free_pages
= 0;
3320 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
3323 for (i
= 0; i
<= ZONE_NORMAL
; i
++) {
3324 zone
= &pgdat
->node_zones
[i
];
3325 if (!managed_zone(zone
))
3328 if (!zone_reclaimable_pages(zone
))
3331 pfmemalloc_reserve
+= min_wmark_pages(zone
);
3332 free_pages
+= zone_page_state(zone
, NR_FREE_PAGES
);
3335 /* If there are no reserves (unexpected config) then do not throttle */
3336 if (!pfmemalloc_reserve
)
3339 wmark_ok
= free_pages
> pfmemalloc_reserve
/ 2;
3341 /* kswapd must be awake if processes are being throttled */
3342 if (!wmark_ok
&& waitqueue_active(&pgdat
->kswapd_wait
)) {
3343 if (READ_ONCE(pgdat
->kswapd_highest_zoneidx
) > ZONE_NORMAL
)
3344 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, ZONE_NORMAL
);
3346 wake_up_interruptible(&pgdat
->kswapd_wait
);
3353 * Throttle direct reclaimers if backing storage is backed by the network
3354 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3355 * depleted. kswapd will continue to make progress and wake the processes
3356 * when the low watermark is reached.
3358 * Returns true if a fatal signal was delivered during throttling. If this
3359 * happens, the page allocator should not consider triggering the OOM killer.
3361 static bool throttle_direct_reclaim(gfp_t gfp_mask
, struct zonelist
*zonelist
,
3362 nodemask_t
*nodemask
)
3366 pg_data_t
*pgdat
= NULL
;
3369 * Kernel threads should not be throttled as they may be indirectly
3370 * responsible for cleaning pages necessary for reclaim to make forward
3371 * progress. kjournald for example may enter direct reclaim while
3372 * committing a transaction where throttling it could forcing other
3373 * processes to block on log_wait_commit().
3375 if (current
->flags
& PF_KTHREAD
)
3379 * If a fatal signal is pending, this process should not throttle.
3380 * It should return quickly so it can exit and free its memory
3382 if (fatal_signal_pending(current
))
3386 * Check if the pfmemalloc reserves are ok by finding the first node
3387 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3388 * GFP_KERNEL will be required for allocating network buffers when
3389 * swapping over the network so ZONE_HIGHMEM is unusable.
3391 * Throttling is based on the first usable node and throttled processes
3392 * wait on a queue until kswapd makes progress and wakes them. There
3393 * is an affinity then between processes waking up and where reclaim
3394 * progress has been made assuming the process wakes on the same node.
3395 * More importantly, processes running on remote nodes will not compete
3396 * for remote pfmemalloc reserves and processes on different nodes
3397 * should make reasonable progress.
3399 for_each_zone_zonelist_nodemask(zone
, z
, zonelist
,
3400 gfp_zone(gfp_mask
), nodemask
) {
3401 if (zone_idx(zone
) > ZONE_NORMAL
)
3404 /* Throttle based on the first usable node */
3405 pgdat
= zone
->zone_pgdat
;
3406 if (allow_direct_reclaim(pgdat
))
3411 /* If no zone was usable by the allocation flags then do not throttle */
3415 /* Account for the throttling */
3416 count_vm_event(PGSCAN_DIRECT_THROTTLE
);
3419 * If the caller cannot enter the filesystem, it's possible that it
3420 * is due to the caller holding an FS lock or performing a journal
3421 * transaction in the case of a filesystem like ext[3|4]. In this case,
3422 * it is not safe to block on pfmemalloc_wait as kswapd could be
3423 * blocked waiting on the same lock. Instead, throttle for up to a
3424 * second before continuing.
3426 if (!(gfp_mask
& __GFP_FS
)) {
3427 wait_event_interruptible_timeout(pgdat
->pfmemalloc_wait
,
3428 allow_direct_reclaim(pgdat
), HZ
);
3433 /* Throttle until kswapd wakes the process */
3434 wait_event_killable(zone
->zone_pgdat
->pfmemalloc_wait
,
3435 allow_direct_reclaim(pgdat
));
3438 if (fatal_signal_pending(current
))
3445 unsigned long try_to_free_pages(struct zonelist
*zonelist
, int order
,
3446 gfp_t gfp_mask
, nodemask_t
*nodemask
)
3448 unsigned long nr_reclaimed
;
3449 struct scan_control sc
= {
3450 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
3451 .gfp_mask
= current_gfp_context(gfp_mask
),
3452 .reclaim_idx
= gfp_zone(gfp_mask
),
3454 .nodemask
= nodemask
,
3455 .priority
= DEF_PRIORITY
,
3456 .may_writepage
= !laptop_mode
,
3462 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3463 * Confirm they are large enough for max values.
3465 BUILD_BUG_ON(MAX_ORDER
> S8_MAX
);
3466 BUILD_BUG_ON(DEF_PRIORITY
> S8_MAX
);
3467 BUILD_BUG_ON(MAX_NR_ZONES
> S8_MAX
);
3470 * Do not enter reclaim if fatal signal was delivered while throttled.
3471 * 1 is returned so that the page allocator does not OOM kill at this
3474 if (throttle_direct_reclaim(sc
.gfp_mask
, zonelist
, nodemask
))
3477 set_task_reclaim_state(current
, &sc
.reclaim_state
);
3478 trace_mm_vmscan_direct_reclaim_begin(order
, sc
.gfp_mask
);
3480 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
3482 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed
);
3483 set_task_reclaim_state(current
, NULL
);
3485 return nr_reclaimed
;
3490 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3491 unsigned long mem_cgroup_shrink_node(struct mem_cgroup
*memcg
,
3492 gfp_t gfp_mask
, bool noswap
,
3494 unsigned long *nr_scanned
)
3496 struct lruvec
*lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
3497 struct scan_control sc
= {
3498 .nr_to_reclaim
= SWAP_CLUSTER_MAX
,
3499 .target_mem_cgroup
= memcg
,
3500 .may_writepage
= !laptop_mode
,
3502 .reclaim_idx
= MAX_NR_ZONES
- 1,
3503 .may_swap
= !noswap
,
3506 WARN_ON_ONCE(!current
->reclaim_state
);
3508 sc
.gfp_mask
= (gfp_mask
& GFP_RECLAIM_MASK
) |
3509 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
);
3511 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc
.order
,
3515 * NOTE: Although we can get the priority field, using it
3516 * here is not a good idea, since it limits the pages we can scan.
3517 * if we don't reclaim here, the shrink_node from balance_pgdat
3518 * will pick up pages from other mem cgroup's as well. We hack
3519 * the priority and make it zero.
3521 shrink_lruvec(lruvec
, &sc
);
3523 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc
.nr_reclaimed
);
3525 *nr_scanned
= sc
.nr_scanned
;
3527 return sc
.nr_reclaimed
;
3530 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup
*memcg
,
3531 unsigned long nr_pages
,
3535 unsigned long nr_reclaimed
;
3536 unsigned int noreclaim_flag
;
3537 struct scan_control sc
= {
3538 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
3539 .gfp_mask
= (current_gfp_context(gfp_mask
) & GFP_RECLAIM_MASK
) |
3540 (GFP_HIGHUSER_MOVABLE
& ~GFP_RECLAIM_MASK
),
3541 .reclaim_idx
= MAX_NR_ZONES
- 1,
3542 .target_mem_cgroup
= memcg
,
3543 .priority
= DEF_PRIORITY
,
3544 .may_writepage
= !laptop_mode
,
3546 .may_swap
= may_swap
,
3549 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3550 * equal pressure on all the nodes. This is based on the assumption that
3551 * the reclaim does not bail out early.
3553 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
3555 set_task_reclaim_state(current
, &sc
.reclaim_state
);
3556 trace_mm_vmscan_memcg_reclaim_begin(0, sc
.gfp_mask
);
3557 noreclaim_flag
= memalloc_noreclaim_save();
3559 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
3561 memalloc_noreclaim_restore(noreclaim_flag
);
3562 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed
);
3563 set_task_reclaim_state(current
, NULL
);
3565 return nr_reclaimed
;
3569 static void age_active_anon(struct pglist_data
*pgdat
,
3570 struct scan_control
*sc
)
3572 struct mem_cgroup
*memcg
;
3573 struct lruvec
*lruvec
;
3575 if (!total_swap_pages
)
3578 lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
3579 if (!inactive_is_low(lruvec
, LRU_INACTIVE_ANON
))
3582 memcg
= mem_cgroup_iter(NULL
, NULL
, NULL
);
3584 lruvec
= mem_cgroup_lruvec(memcg
, pgdat
);
3585 shrink_active_list(SWAP_CLUSTER_MAX
, lruvec
,
3586 sc
, LRU_ACTIVE_ANON
);
3587 memcg
= mem_cgroup_iter(NULL
, memcg
, NULL
);
3591 static bool pgdat_watermark_boosted(pg_data_t
*pgdat
, int highest_zoneidx
)
3597 * Check for watermark boosts top-down as the higher zones
3598 * are more likely to be boosted. Both watermarks and boosts
3599 * should not be checked at the same time as reclaim would
3600 * start prematurely when there is no boosting and a lower
3603 for (i
= highest_zoneidx
; i
>= 0; i
--) {
3604 zone
= pgdat
->node_zones
+ i
;
3605 if (!managed_zone(zone
))
3608 if (zone
->watermark_boost
)
3616 * Returns true if there is an eligible zone balanced for the request order
3617 * and highest_zoneidx
3619 static bool pgdat_balanced(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
3622 unsigned long mark
= -1;
3626 * Check watermarks bottom-up as lower zones are more likely to
3629 for (i
= 0; i
<= highest_zoneidx
; i
++) {
3630 zone
= pgdat
->node_zones
+ i
;
3632 if (!managed_zone(zone
))
3635 mark
= high_wmark_pages(zone
);
3636 if (zone_watermark_ok_safe(zone
, order
, mark
, highest_zoneidx
))
3641 * If a node has no populated zone within highest_zoneidx, it does not
3642 * need balancing by definition. This can happen if a zone-restricted
3643 * allocation tries to wake a remote kswapd.
3651 /* Clear pgdat state for congested, dirty or under writeback. */
3652 static void clear_pgdat_congested(pg_data_t
*pgdat
)
3654 struct lruvec
*lruvec
= mem_cgroup_lruvec(NULL
, pgdat
);
3656 clear_bit(LRUVEC_CONGESTED
, &lruvec
->flags
);
3657 clear_bit(PGDAT_DIRTY
, &pgdat
->flags
);
3658 clear_bit(PGDAT_WRITEBACK
, &pgdat
->flags
);
3662 * Prepare kswapd for sleeping. This verifies that there are no processes
3663 * waiting in throttle_direct_reclaim() and that watermarks have been met.
3665 * Returns true if kswapd is ready to sleep
3667 static bool prepare_kswapd_sleep(pg_data_t
*pgdat
, int order
,
3668 int highest_zoneidx
)
3671 * The throttled processes are normally woken up in balance_pgdat() as
3672 * soon as allow_direct_reclaim() is true. But there is a potential
3673 * race between when kswapd checks the watermarks and a process gets
3674 * throttled. There is also a potential race if processes get
3675 * throttled, kswapd wakes, a large process exits thereby balancing the
3676 * zones, which causes kswapd to exit balance_pgdat() before reaching
3677 * the wake up checks. If kswapd is going to sleep, no process should
3678 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3679 * the wake up is premature, processes will wake kswapd and get
3680 * throttled again. The difference from wake ups in balance_pgdat() is
3681 * that here we are under prepare_to_wait().
3683 if (waitqueue_active(&pgdat
->pfmemalloc_wait
))
3684 wake_up_all(&pgdat
->pfmemalloc_wait
);
3686 /* Hopeless node, leave it to direct reclaim */
3687 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
)
3690 if (pgdat_balanced(pgdat
, order
, highest_zoneidx
)) {
3691 clear_pgdat_congested(pgdat
);
3699 * kswapd shrinks a node of pages that are at or below the highest usable
3700 * zone that is currently unbalanced.
3702 * Returns true if kswapd scanned at least the requested number of pages to
3703 * reclaim or if the lack of progress was due to pages under writeback.
3704 * This is used to determine if the scanning priority needs to be raised.
3706 static bool kswapd_shrink_node(pg_data_t
*pgdat
,
3707 struct scan_control
*sc
)
3712 /* Reclaim a number of pages proportional to the number of zones */
3713 sc
->nr_to_reclaim
= 0;
3714 for (z
= 0; z
<= sc
->reclaim_idx
; z
++) {
3715 zone
= pgdat
->node_zones
+ z
;
3716 if (!managed_zone(zone
))
3719 sc
->nr_to_reclaim
+= max(high_wmark_pages(zone
), SWAP_CLUSTER_MAX
);
3723 * Historically care was taken to put equal pressure on all zones but
3724 * now pressure is applied based on node LRU order.
3726 shrink_node(pgdat
, sc
);
3729 * Fragmentation may mean that the system cannot be rebalanced for
3730 * high-order allocations. If twice the allocation size has been
3731 * reclaimed then recheck watermarks only at order-0 to prevent
3732 * excessive reclaim. Assume that a process requested a high-order
3733 * can direct reclaim/compact.
3735 if (sc
->order
&& sc
->nr_reclaimed
>= compact_gap(sc
->order
))
3738 return sc
->nr_scanned
>= sc
->nr_to_reclaim
;
3741 /* Page allocator PCP high watermark is lowered if reclaim is active. */
3743 update_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
, bool active
)
3748 for (i
= 0; i
<= highest_zoneidx
; i
++) {
3749 zone
= pgdat
->node_zones
+ i
;
3751 if (!managed_zone(zone
))
3755 set_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
3757 clear_bit(ZONE_RECLAIM_ACTIVE
, &zone
->flags
);
3762 set_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
3764 update_reclaim_active(pgdat
, highest_zoneidx
, true);
3768 clear_reclaim_active(pg_data_t
*pgdat
, int highest_zoneidx
)
3770 update_reclaim_active(pgdat
, highest_zoneidx
, false);
3774 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3775 * that are eligible for use by the caller until at least one zone is
3778 * Returns the order kswapd finished reclaiming at.
3780 * kswapd scans the zones in the highmem->normal->dma direction. It skips
3781 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3782 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
3783 * or lower is eligible for reclaim until at least one usable zone is
3786 static int balance_pgdat(pg_data_t
*pgdat
, int order
, int highest_zoneidx
)
3789 unsigned long nr_soft_reclaimed
;
3790 unsigned long nr_soft_scanned
;
3791 unsigned long pflags
;
3792 unsigned long nr_boost_reclaim
;
3793 unsigned long zone_boosts
[MAX_NR_ZONES
] = { 0, };
3796 struct scan_control sc
= {
3797 .gfp_mask
= GFP_KERNEL
,
3802 set_task_reclaim_state(current
, &sc
.reclaim_state
);
3803 psi_memstall_enter(&pflags
);
3804 __fs_reclaim_acquire();
3806 count_vm_event(PAGEOUTRUN
);
3809 * Account for the reclaim boost. Note that the zone boost is left in
3810 * place so that parallel allocations that are near the watermark will
3811 * stall or direct reclaim until kswapd is finished.
3813 nr_boost_reclaim
= 0;
3814 for (i
= 0; i
<= highest_zoneidx
; i
++) {
3815 zone
= pgdat
->node_zones
+ i
;
3816 if (!managed_zone(zone
))
3819 nr_boost_reclaim
+= zone
->watermark_boost
;
3820 zone_boosts
[i
] = zone
->watermark_boost
;
3822 boosted
= nr_boost_reclaim
;
3825 set_reclaim_active(pgdat
, highest_zoneidx
);
3826 sc
.priority
= DEF_PRIORITY
;
3828 unsigned long nr_reclaimed
= sc
.nr_reclaimed
;
3829 bool raise_priority
= true;
3833 sc
.reclaim_idx
= highest_zoneidx
;
3836 * If the number of buffer_heads exceeds the maximum allowed
3837 * then consider reclaiming from all zones. This has a dual
3838 * purpose -- on 64-bit systems it is expected that
3839 * buffer_heads are stripped during active rotation. On 32-bit
3840 * systems, highmem pages can pin lowmem memory and shrinking
3841 * buffers can relieve lowmem pressure. Reclaim may still not
3842 * go ahead if all eligible zones for the original allocation
3843 * request are balanced to avoid excessive reclaim from kswapd.
3845 if (buffer_heads_over_limit
) {
3846 for (i
= MAX_NR_ZONES
- 1; i
>= 0; i
--) {
3847 zone
= pgdat
->node_zones
+ i
;
3848 if (!managed_zone(zone
))
3857 * If the pgdat is imbalanced then ignore boosting and preserve
3858 * the watermarks for a later time and restart. Note that the
3859 * zone watermarks will be still reset at the end of balancing
3860 * on the grounds that the normal reclaim should be enough to
3861 * re-evaluate if boosting is required when kswapd next wakes.
3863 balanced
= pgdat_balanced(pgdat
, sc
.order
, highest_zoneidx
);
3864 if (!balanced
&& nr_boost_reclaim
) {
3865 nr_boost_reclaim
= 0;
3870 * If boosting is not active then only reclaim if there are no
3871 * eligible zones. Note that sc.reclaim_idx is not used as
3872 * buffer_heads_over_limit may have adjusted it.
3874 if (!nr_boost_reclaim
&& balanced
)
3877 /* Limit the priority of boosting to avoid reclaim writeback */
3878 if (nr_boost_reclaim
&& sc
.priority
== DEF_PRIORITY
- 2)
3879 raise_priority
= false;
3882 * Do not writeback or swap pages for boosted reclaim. The
3883 * intent is to relieve pressure not issue sub-optimal IO
3884 * from reclaim context. If no pages are reclaimed, the
3885 * reclaim will be aborted.
3887 sc
.may_writepage
= !laptop_mode
&& !nr_boost_reclaim
;
3888 sc
.may_swap
= !nr_boost_reclaim
;
3891 * Do some background aging of the anon list, to give
3892 * pages a chance to be referenced before reclaiming. All
3893 * pages are rotated regardless of classzone as this is
3894 * about consistent aging.
3896 age_active_anon(pgdat
, &sc
);
3899 * If we're getting trouble reclaiming, start doing writepage
3900 * even in laptop mode.
3902 if (sc
.priority
< DEF_PRIORITY
- 2)
3903 sc
.may_writepage
= 1;
3905 /* Call soft limit reclaim before calling shrink_node. */
3907 nr_soft_scanned
= 0;
3908 nr_soft_reclaimed
= mem_cgroup_soft_limit_reclaim(pgdat
, sc
.order
,
3909 sc
.gfp_mask
, &nr_soft_scanned
);
3910 sc
.nr_reclaimed
+= nr_soft_reclaimed
;
3913 * There should be no need to raise the scanning priority if
3914 * enough pages are already being scanned that that high
3915 * watermark would be met at 100% efficiency.
3917 if (kswapd_shrink_node(pgdat
, &sc
))
3918 raise_priority
= false;
3921 * If the low watermark is met there is no need for processes
3922 * to be throttled on pfmemalloc_wait as they should not be
3923 * able to safely make forward progress. Wake them
3925 if (waitqueue_active(&pgdat
->pfmemalloc_wait
) &&
3926 allow_direct_reclaim(pgdat
))
3927 wake_up_all(&pgdat
->pfmemalloc_wait
);
3929 /* Check if kswapd should be suspending */
3930 __fs_reclaim_release();
3931 ret
= try_to_freeze();
3932 __fs_reclaim_acquire();
3933 if (ret
|| kthread_should_stop())
3937 * Raise priority if scanning rate is too low or there was no
3938 * progress in reclaiming pages
3940 nr_reclaimed
= sc
.nr_reclaimed
- nr_reclaimed
;
3941 nr_boost_reclaim
-= min(nr_boost_reclaim
, nr_reclaimed
);
3944 * If reclaim made no progress for a boost, stop reclaim as
3945 * IO cannot be queued and it could be an infinite loop in
3946 * extreme circumstances.
3948 if (nr_boost_reclaim
&& !nr_reclaimed
)
3951 if (raise_priority
|| !nr_reclaimed
)
3953 } while (sc
.priority
>= 1);
3955 if (!sc
.nr_reclaimed
)
3956 pgdat
->kswapd_failures
++;
3959 clear_reclaim_active(pgdat
, highest_zoneidx
);
3961 /* If reclaim was boosted, account for the reclaim done in this pass */
3963 unsigned long flags
;
3965 for (i
= 0; i
<= highest_zoneidx
; i
++) {
3966 if (!zone_boosts
[i
])
3969 /* Increments are under the zone lock */
3970 zone
= pgdat
->node_zones
+ i
;
3971 spin_lock_irqsave(&zone
->lock
, flags
);
3972 zone
->watermark_boost
-= min(zone
->watermark_boost
, zone_boosts
[i
]);
3973 spin_unlock_irqrestore(&zone
->lock
, flags
);
3977 * As there is now likely space, wakeup kcompact to defragment
3980 wakeup_kcompactd(pgdat
, pageblock_order
, highest_zoneidx
);
3983 snapshot_refaults(NULL
, pgdat
);
3984 __fs_reclaim_release();
3985 psi_memstall_leave(&pflags
);
3986 set_task_reclaim_state(current
, NULL
);
3989 * Return the order kswapd stopped reclaiming at as
3990 * prepare_kswapd_sleep() takes it into account. If another caller
3991 * entered the allocator slow path while kswapd was awake, order will
3992 * remain at the higher level.
3998 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
3999 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
4000 * not a valid index then either kswapd runs for first time or kswapd couldn't
4001 * sleep after previous reclaim attempt (node is still unbalanced). In that
4002 * case return the zone index of the previous kswapd reclaim cycle.
4004 static enum zone_type
kswapd_highest_zoneidx(pg_data_t
*pgdat
,
4005 enum zone_type prev_highest_zoneidx
)
4007 enum zone_type curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
4009 return curr_idx
== MAX_NR_ZONES
? prev_highest_zoneidx
: curr_idx
;
4012 static void kswapd_try_to_sleep(pg_data_t
*pgdat
, int alloc_order
, int reclaim_order
,
4013 unsigned int highest_zoneidx
)
4018 if (freezing(current
) || kthread_should_stop())
4021 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
4024 * Try to sleep for a short interval. Note that kcompactd will only be
4025 * woken if it is possible to sleep for a short interval. This is
4026 * deliberate on the assumption that if reclaim cannot keep an
4027 * eligible zone balanced that it's also unlikely that compaction will
4030 if (prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
4032 * Compaction records what page blocks it recently failed to
4033 * isolate pages from and skips them in the future scanning.
4034 * When kswapd is going to sleep, it is reasonable to assume
4035 * that pages and compaction may succeed so reset the cache.
4037 reset_isolation_suitable(pgdat
);
4040 * We have freed the memory, now we should compact it to make
4041 * allocation of the requested order possible.
4043 wakeup_kcompactd(pgdat
, alloc_order
, highest_zoneidx
);
4045 remaining
= schedule_timeout(HZ
/10);
4048 * If woken prematurely then reset kswapd_highest_zoneidx and
4049 * order. The values will either be from a wakeup request or
4050 * the previous request that slept prematurely.
4053 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
,
4054 kswapd_highest_zoneidx(pgdat
,
4057 if (READ_ONCE(pgdat
->kswapd_order
) < reclaim_order
)
4058 WRITE_ONCE(pgdat
->kswapd_order
, reclaim_order
);
4061 finish_wait(&pgdat
->kswapd_wait
, &wait
);
4062 prepare_to_wait(&pgdat
->kswapd_wait
, &wait
, TASK_INTERRUPTIBLE
);
4066 * After a short sleep, check if it was a premature sleep. If not, then
4067 * go fully to sleep until explicitly woken up.
4070 prepare_kswapd_sleep(pgdat
, reclaim_order
, highest_zoneidx
)) {
4071 trace_mm_vmscan_kswapd_sleep(pgdat
->node_id
);
4074 * vmstat counters are not perfectly accurate and the estimated
4075 * value for counters such as NR_FREE_PAGES can deviate from the
4076 * true value by nr_online_cpus * threshold. To avoid the zone
4077 * watermarks being breached while under pressure, we reduce the
4078 * per-cpu vmstat threshold while kswapd is awake and restore
4079 * them before going back to sleep.
4081 set_pgdat_percpu_threshold(pgdat
, calculate_normal_threshold
);
4083 if (!kthread_should_stop())
4086 set_pgdat_percpu_threshold(pgdat
, calculate_pressure_threshold
);
4089 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY
);
4091 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY
);
4093 finish_wait(&pgdat
->kswapd_wait
, &wait
);
4097 * The background pageout daemon, started as a kernel thread
4098 * from the init process.
4100 * This basically trickles out pages so that we have _some_
4101 * free memory available even if there is no other activity
4102 * that frees anything up. This is needed for things like routing
4103 * etc, where we otherwise might have all activity going on in
4104 * asynchronous contexts that cannot page things out.
4106 * If there are applications that are active memory-allocators
4107 * (most normal use), this basically shouldn't matter.
4109 static int kswapd(void *p
)
4111 unsigned int alloc_order
, reclaim_order
;
4112 unsigned int highest_zoneidx
= MAX_NR_ZONES
- 1;
4113 pg_data_t
*pgdat
= (pg_data_t
*)p
;
4114 struct task_struct
*tsk
= current
;
4115 const struct cpumask
*cpumask
= cpumask_of_node(pgdat
->node_id
);
4117 if (!cpumask_empty(cpumask
))
4118 set_cpus_allowed_ptr(tsk
, cpumask
);
4121 * Tell the memory management that we're a "memory allocator",
4122 * and that if we need more memory we should get access to it
4123 * regardless (see "__alloc_pages()"). "kswapd" should
4124 * never get caught in the normal page freeing logic.
4126 * (Kswapd normally doesn't need memory anyway, but sometimes
4127 * you need a small amount of memory in order to be able to
4128 * page out something else, and this flag essentially protects
4129 * us from recursively trying to free more memory as we're
4130 * trying to free the first piece of memory in the first place).
4132 tsk
->flags
|= PF_MEMALLOC
| PF_SWAPWRITE
| PF_KSWAPD
;
4135 WRITE_ONCE(pgdat
->kswapd_order
, 0);
4136 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
4140 alloc_order
= reclaim_order
= READ_ONCE(pgdat
->kswapd_order
);
4141 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
4145 kswapd_try_to_sleep(pgdat
, alloc_order
, reclaim_order
,
4148 /* Read the new order and highest_zoneidx */
4149 alloc_order
= READ_ONCE(pgdat
->kswapd_order
);
4150 highest_zoneidx
= kswapd_highest_zoneidx(pgdat
,
4152 WRITE_ONCE(pgdat
->kswapd_order
, 0);
4153 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, MAX_NR_ZONES
);
4155 ret
= try_to_freeze();
4156 if (kthread_should_stop())
4160 * We can speed up thawing tasks if we don't call balance_pgdat
4161 * after returning from the refrigerator
4167 * Reclaim begins at the requested order but if a high-order
4168 * reclaim fails then kswapd falls back to reclaiming for
4169 * order-0. If that happens, kswapd will consider sleeping
4170 * for the order it finished reclaiming at (reclaim_order)
4171 * but kcompactd is woken to compact for the original
4172 * request (alloc_order).
4174 trace_mm_vmscan_kswapd_wake(pgdat
->node_id
, highest_zoneidx
,
4176 reclaim_order
= balance_pgdat(pgdat
, alloc_order
,
4178 if (reclaim_order
< alloc_order
)
4179 goto kswapd_try_sleep
;
4182 tsk
->flags
&= ~(PF_MEMALLOC
| PF_SWAPWRITE
| PF_KSWAPD
);
4188 * A zone is low on free memory or too fragmented for high-order memory. If
4189 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4190 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4191 * has failed or is not needed, still wake up kcompactd if only compaction is
4194 void wakeup_kswapd(struct zone
*zone
, gfp_t gfp_flags
, int order
,
4195 enum zone_type highest_zoneidx
)
4198 enum zone_type curr_idx
;
4200 if (!managed_zone(zone
))
4203 if (!cpuset_zone_allowed(zone
, gfp_flags
))
4206 pgdat
= zone
->zone_pgdat
;
4207 curr_idx
= READ_ONCE(pgdat
->kswapd_highest_zoneidx
);
4209 if (curr_idx
== MAX_NR_ZONES
|| curr_idx
< highest_zoneidx
)
4210 WRITE_ONCE(pgdat
->kswapd_highest_zoneidx
, highest_zoneidx
);
4212 if (READ_ONCE(pgdat
->kswapd_order
) < order
)
4213 WRITE_ONCE(pgdat
->kswapd_order
, order
);
4215 if (!waitqueue_active(&pgdat
->kswapd_wait
))
4218 /* Hopeless node, leave it to direct reclaim if possible */
4219 if (pgdat
->kswapd_failures
>= MAX_RECLAIM_RETRIES
||
4220 (pgdat_balanced(pgdat
, order
, highest_zoneidx
) &&
4221 !pgdat_watermark_boosted(pgdat
, highest_zoneidx
))) {
4223 * There may be plenty of free memory available, but it's too
4224 * fragmented for high-order allocations. Wake up kcompactd
4225 * and rely on compaction_suitable() to determine if it's
4226 * needed. If it fails, it will defer subsequent attempts to
4227 * ratelimit its work.
4229 if (!(gfp_flags
& __GFP_DIRECT_RECLAIM
))
4230 wakeup_kcompactd(pgdat
, order
, highest_zoneidx
);
4234 trace_mm_vmscan_wakeup_kswapd(pgdat
->node_id
, highest_zoneidx
, order
,
4236 wake_up_interruptible(&pgdat
->kswapd_wait
);
4239 #ifdef CONFIG_HIBERNATION
4241 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
4244 * Rather than trying to age LRUs the aim is to preserve the overall
4245 * LRU order by reclaiming preferentially
4246 * inactive > active > active referenced > active mapped
4248 unsigned long shrink_all_memory(unsigned long nr_to_reclaim
)
4250 struct scan_control sc
= {
4251 .nr_to_reclaim
= nr_to_reclaim
,
4252 .gfp_mask
= GFP_HIGHUSER_MOVABLE
,
4253 .reclaim_idx
= MAX_NR_ZONES
- 1,
4254 .priority
= DEF_PRIORITY
,
4258 .hibernation_mode
= 1,
4260 struct zonelist
*zonelist
= node_zonelist(numa_node_id(), sc
.gfp_mask
);
4261 unsigned long nr_reclaimed
;
4262 unsigned int noreclaim_flag
;
4264 fs_reclaim_acquire(sc
.gfp_mask
);
4265 noreclaim_flag
= memalloc_noreclaim_save();
4266 set_task_reclaim_state(current
, &sc
.reclaim_state
);
4268 nr_reclaimed
= do_try_to_free_pages(zonelist
, &sc
);
4270 set_task_reclaim_state(current
, NULL
);
4271 memalloc_noreclaim_restore(noreclaim_flag
);
4272 fs_reclaim_release(sc
.gfp_mask
);
4274 return nr_reclaimed
;
4276 #endif /* CONFIG_HIBERNATION */
4279 * This kswapd start function will be called by init and node-hot-add.
4280 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4282 int kswapd_run(int nid
)
4284 pg_data_t
*pgdat
= NODE_DATA(nid
);
4290 pgdat
->kswapd
= kthread_run(kswapd
, pgdat
, "kswapd%d", nid
);
4291 if (IS_ERR(pgdat
->kswapd
)) {
4292 /* failure at boot is fatal */
4293 BUG_ON(system_state
< SYSTEM_RUNNING
);
4294 pr_err("Failed to start kswapd on node %d\n", nid
);
4295 ret
= PTR_ERR(pgdat
->kswapd
);
4296 pgdat
->kswapd
= NULL
;
4302 * Called by memory hotplug when all memory in a node is offlined. Caller must
4303 * hold mem_hotplug_begin/end().
4305 void kswapd_stop(int nid
)
4307 struct task_struct
*kswapd
= NODE_DATA(nid
)->kswapd
;
4310 kthread_stop(kswapd
);
4311 NODE_DATA(nid
)->kswapd
= NULL
;
4315 static int __init
kswapd_init(void)
4320 for_each_node_state(nid
, N_MEMORY
)
4325 module_init(kswapd_init
)
4331 * If non-zero call node_reclaim when the number of free pages falls below
4334 int node_reclaim_mode __read_mostly
;
4337 * Priority for NODE_RECLAIM. This determines the fraction of pages
4338 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4341 #define NODE_RECLAIM_PRIORITY 4
4344 * Percentage of pages in a zone that must be unmapped for node_reclaim to
4347 int sysctl_min_unmapped_ratio
= 1;
4350 * If the number of slab pages in a zone grows beyond this percentage then
4351 * slab reclaim needs to occur.
4353 int sysctl_min_slab_ratio
= 5;
4355 static inline unsigned long node_unmapped_file_pages(struct pglist_data
*pgdat
)
4357 unsigned long file_mapped
= node_page_state(pgdat
, NR_FILE_MAPPED
);
4358 unsigned long file_lru
= node_page_state(pgdat
, NR_INACTIVE_FILE
) +
4359 node_page_state(pgdat
, NR_ACTIVE_FILE
);
4362 * It's possible for there to be more file mapped pages than
4363 * accounted for by the pages on the file LRU lists because
4364 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4366 return (file_lru
> file_mapped
) ? (file_lru
- file_mapped
) : 0;
4369 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4370 static unsigned long node_pagecache_reclaimable(struct pglist_data
*pgdat
)
4372 unsigned long nr_pagecache_reclaimable
;
4373 unsigned long delta
= 0;
4376 * If RECLAIM_UNMAP is set, then all file pages are considered
4377 * potentially reclaimable. Otherwise, we have to worry about
4378 * pages like swapcache and node_unmapped_file_pages() provides
4381 if (node_reclaim_mode
& RECLAIM_UNMAP
)
4382 nr_pagecache_reclaimable
= node_page_state(pgdat
, NR_FILE_PAGES
);
4384 nr_pagecache_reclaimable
= node_unmapped_file_pages(pgdat
);
4386 /* If we can't clean pages, remove dirty pages from consideration */
4387 if (!(node_reclaim_mode
& RECLAIM_WRITE
))
4388 delta
+= node_page_state(pgdat
, NR_FILE_DIRTY
);
4390 /* Watch for any possible underflows due to delta */
4391 if (unlikely(delta
> nr_pagecache_reclaimable
))
4392 delta
= nr_pagecache_reclaimable
;
4394 return nr_pagecache_reclaimable
- delta
;
4398 * Try to free up some pages from this node through reclaim.
4400 static int __node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
4402 /* Minimum pages needed in order to stay on node */
4403 const unsigned long nr_pages
= 1 << order
;
4404 struct task_struct
*p
= current
;
4405 unsigned int noreclaim_flag
;
4406 struct scan_control sc
= {
4407 .nr_to_reclaim
= max(nr_pages
, SWAP_CLUSTER_MAX
),
4408 .gfp_mask
= current_gfp_context(gfp_mask
),
4410 .priority
= NODE_RECLAIM_PRIORITY
,
4411 .may_writepage
= !!(node_reclaim_mode
& RECLAIM_WRITE
),
4412 .may_unmap
= !!(node_reclaim_mode
& RECLAIM_UNMAP
),
4414 .reclaim_idx
= gfp_zone(gfp_mask
),
4417 trace_mm_vmscan_node_reclaim_begin(pgdat
->node_id
, order
,
4421 fs_reclaim_acquire(sc
.gfp_mask
);
4423 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4424 * and we also need to be able to write out pages for RECLAIM_WRITE
4425 * and RECLAIM_UNMAP.
4427 noreclaim_flag
= memalloc_noreclaim_save();
4428 p
->flags
|= PF_SWAPWRITE
;
4429 set_task_reclaim_state(p
, &sc
.reclaim_state
);
4431 if (node_pagecache_reclaimable(pgdat
) > pgdat
->min_unmapped_pages
) {
4433 * Free memory by calling shrink node with increasing
4434 * priorities until we have enough memory freed.
4437 shrink_node(pgdat
, &sc
);
4438 } while (sc
.nr_reclaimed
< nr_pages
&& --sc
.priority
>= 0);
4441 set_task_reclaim_state(p
, NULL
);
4442 current
->flags
&= ~PF_SWAPWRITE
;
4443 memalloc_noreclaim_restore(noreclaim_flag
);
4444 fs_reclaim_release(sc
.gfp_mask
);
4446 trace_mm_vmscan_node_reclaim_end(sc
.nr_reclaimed
);
4448 return sc
.nr_reclaimed
>= nr_pages
;
4451 int node_reclaim(struct pglist_data
*pgdat
, gfp_t gfp_mask
, unsigned int order
)
4456 * Node reclaim reclaims unmapped file backed pages and
4457 * slab pages if we are over the defined limits.
4459 * A small portion of unmapped file backed pages is needed for
4460 * file I/O otherwise pages read by file I/O will be immediately
4461 * thrown out if the node is overallocated. So we do not reclaim
4462 * if less than a specified percentage of the node is used by
4463 * unmapped file backed pages.
4465 if (node_pagecache_reclaimable(pgdat
) <= pgdat
->min_unmapped_pages
&&
4466 node_page_state_pages(pgdat
, NR_SLAB_RECLAIMABLE_B
) <=
4467 pgdat
->min_slab_pages
)
4468 return NODE_RECLAIM_FULL
;
4471 * Do not scan if the allocation should not be delayed.
4473 if (!gfpflags_allow_blocking(gfp_mask
) || (current
->flags
& PF_MEMALLOC
))
4474 return NODE_RECLAIM_NOSCAN
;
4477 * Only run node reclaim on the local node or on nodes that do not
4478 * have associated processors. This will favor the local processor
4479 * over remote processors and spread off node memory allocations
4480 * as wide as possible.
4482 if (node_state(pgdat
->node_id
, N_CPU
) && pgdat
->node_id
!= numa_node_id())
4483 return NODE_RECLAIM_NOSCAN
;
4485 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
))
4486 return NODE_RECLAIM_NOSCAN
;
4488 ret
= __node_reclaim(pgdat
, gfp_mask
, order
);
4489 clear_bit(PGDAT_RECLAIM_LOCKED
, &pgdat
->flags
);
4492 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED
);
4499 * check_move_unevictable_pages - check pages for evictability and move to
4500 * appropriate zone lru list
4501 * @pvec: pagevec with lru pages to check
4503 * Checks pages for evictability, if an evictable page is in the unevictable
4504 * lru list, moves it to the appropriate evictable lru list. This function
4505 * should be only used for lru pages.
4507 void check_move_unevictable_pages(struct pagevec
*pvec
)
4509 struct lruvec
*lruvec
= NULL
;
4514 for (i
= 0; i
< pvec
->nr
; i
++) {
4515 struct page
*page
= pvec
->pages
[i
];
4518 if (PageTransTail(page
))
4521 nr_pages
= thp_nr_pages(page
);
4522 pgscanned
+= nr_pages
;
4524 /* block memcg migration during page moving between lru */
4525 if (!TestClearPageLRU(page
))
4528 lruvec
= relock_page_lruvec_irq(page
, lruvec
);
4529 if (page_evictable(page
) && PageUnevictable(page
)) {
4530 del_page_from_lru_list(page
, lruvec
);
4531 ClearPageUnevictable(page
);
4532 add_page_to_lru_list(page
, lruvec
);
4533 pgrescued
+= nr_pages
;
4539 __count_vm_events(UNEVICTABLE_PGRESCUED
, pgrescued
);
4540 __count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
4541 unlock_page_lruvec_irq(lruvec
);
4542 } else if (pgscanned
) {
4543 count_vm_events(UNEVICTABLE_PGSCANNED
, pgscanned
);
4546 EXPORT_SYMBOL_GPL(check_move_unevictable_pages
);