]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/vmscan.c
Revert "include/linux/mm_inline.h: fold __update_lru_size() into its sole caller"
[thirdparty/linux.git] / mm / vmscan.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
1da177e4 2/*
1da177e4
LT
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
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.
11 */
12
b1de0d13
MH
13#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
1da177e4 15#include <linux/mm.h>
5b3cc15a 16#include <linux/sched/mm.h>
1da177e4 17#include <linux/module.h>
5a0e3ad6 18#include <linux/gfp.h>
1da177e4
LT
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>
70ddf637 24#include <linux/vmpressure.h>
e129b5c2 25#include <linux/vmstat.h>
1da177e4
LT
26#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
07f67a8d 29#include <linux/buffer_head.h> /* for buffer_heads_over_limit */
1da177e4 30#include <linux/mm_inline.h>
1da177e4
LT
31#include <linux/backing-dev.h>
32#include <linux/rmap.h>
33#include <linux/topology.h>
34#include <linux/cpu.h>
35#include <linux/cpuset.h>
3e7d3449 36#include <linux/compaction.h>
1da177e4
LT
37#include <linux/notifier.h>
38#include <linux/rwsem.h>
248a0301 39#include <linux/delay.h>
3218ae14 40#include <linux/kthread.h>
7dfb7103 41#include <linux/freezer.h>
66e1707b 42#include <linux/memcontrol.h>
26aa2d19 43#include <linux/migrate.h>
873b4771 44#include <linux/delayacct.h>
af936a16 45#include <linux/sysctl.h>
929bea7c 46#include <linux/oom.h>
64e3d12f 47#include <linux/pagevec.h>
268bb0ce 48#include <linux/prefetch.h>
b1de0d13 49#include <linux/printk.h>
f9fe48be 50#include <linux/dax.h>
eb414681 51#include <linux/psi.h>
1da177e4
LT
52
53#include <asm/tlbflush.h>
54#include <asm/div64.h>
55
56#include <linux/swapops.h>
117aad1e 57#include <linux/balloon_compaction.h>
c574bbe9 58#include <linux/sched/sysctl.h>
1da177e4 59
0f8053a5 60#include "internal.h"
014bb1de 61#include "swap.h"
0f8053a5 62
33906bc5
MG
63#define CREATE_TRACE_POINTS
64#include <trace/events/vmscan.h>
65
1da177e4 66struct scan_control {
22fba335
KM
67 /* How many pages shrink_list() should reclaim */
68 unsigned long nr_to_reclaim;
69
ee814fe2
JW
70 /*
71 * Nodemask of nodes allowed by the caller. If NULL, all nodes
72 * are scanned.
73 */
74 nodemask_t *nodemask;
9e3b2f8c 75
f16015fb
JW
76 /*
77 * The memory cgroup that hit its limit and as a result is the
78 * primary target of this reclaim invocation.
79 */
80 struct mem_cgroup *target_mem_cgroup;
66e1707b 81
7cf111bc
JW
82 /*
83 * Scan pressure balancing between anon and file LRUs
84 */
85 unsigned long anon_cost;
86 unsigned long file_cost;
87
b91ac374
JW
88 /* Can active pages be deactivated as part of reclaim? */
89#define DEACTIVATE_ANON 1
90#define DEACTIVATE_FILE 2
91 unsigned int may_deactivate:2;
92 unsigned int force_deactivate:1;
93 unsigned int skipped_deactivate:1;
94
1276ad68 95 /* Writepage batching in laptop mode; RECLAIM_WRITE */
ee814fe2
JW
96 unsigned int may_writepage:1;
97
98 /* Can mapped pages be reclaimed? */
99 unsigned int may_unmap:1;
100
101 /* Can pages be swapped as part of reclaim? */
102 unsigned int may_swap:1;
103
73b73bac
YA
104 /* Proactive reclaim invoked by userspace through memory.reclaim */
105 unsigned int proactive:1;
106
d6622f63 107 /*
f56ce412
JW
108 * Cgroup memory below memory.low is protected as long as we
109 * don't threaten to OOM. If any cgroup is reclaimed at
110 * reduced force or passed over entirely due to its memory.low
111 * setting (memcg_low_skipped), and nothing is reclaimed as a
112 * result, then go back for one more cycle that reclaims the protected
113 * memory (memcg_low_reclaim) to avert OOM.
d6622f63
YX
114 */
115 unsigned int memcg_low_reclaim:1;
116 unsigned int memcg_low_skipped:1;
241994ed 117
ee814fe2
JW
118 unsigned int hibernation_mode:1;
119
120 /* One of the zones is ready for compaction */
121 unsigned int compaction_ready:1;
122
b91ac374
JW
123 /* There is easily reclaimable cold cache in the current node */
124 unsigned int cache_trim_mode:1;
125
53138cea
JW
126 /* The file pages on the current node are dangerously low */
127 unsigned int file_is_tiny:1;
128
26aa2d19
DH
129 /* Always discard instead of demoting to lower tier memory */
130 unsigned int no_demotion:1;
131
bb451fdf
GT
132 /* Allocation order */
133 s8 order;
134
135 /* Scan (total_size >> priority) pages at once */
136 s8 priority;
137
138 /* The highest zone to isolate pages for reclaim from */
139 s8 reclaim_idx;
140
141 /* This context's GFP mask */
142 gfp_t gfp_mask;
143
ee814fe2
JW
144 /* Incremented by the number of inactive pages that were scanned */
145 unsigned long nr_scanned;
146
147 /* Number of pages freed so far during a call to shrink_zones() */
148 unsigned long nr_reclaimed;
d108c772
AR
149
150 struct {
151 unsigned int dirty;
152 unsigned int unqueued_dirty;
153 unsigned int congested;
154 unsigned int writeback;
155 unsigned int immediate;
156 unsigned int file_taken;
157 unsigned int taken;
158 } nr;
e5ca8071
YS
159
160 /* for recording the reclaimed slab by now */
161 struct reclaim_state reclaim_state;
1da177e4
LT
162};
163
1da177e4 164#ifdef ARCH_HAS_PREFETCHW
166e3d32 165#define prefetchw_prev_lru_folio(_folio, _base, _field) \
1da177e4 166 do { \
166e3d32
MWO
167 if ((_folio)->lru.prev != _base) { \
168 struct folio *prev; \
1da177e4 169 \
166e3d32 170 prev = lru_to_folio(&(_folio->lru)); \
1da177e4
LT
171 prefetchw(&prev->_field); \
172 } \
173 } while (0)
174#else
166e3d32 175#define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
1da177e4
LT
176#endif
177
178/*
c843966c 179 * From 0 .. 200. Higher means more swappy.
1da177e4
LT
180 */
181int vm_swappiness = 60;
1da177e4 182
0a432dcb
YS
183static void set_task_reclaim_state(struct task_struct *task,
184 struct reclaim_state *rs)
185{
186 /* Check for an overwrite */
187 WARN_ON_ONCE(rs && task->reclaim_state);
188
189 /* Check for the nulling of an already-nulled member */
190 WARN_ON_ONCE(!rs && !task->reclaim_state);
191
192 task->reclaim_state = rs;
193}
194
5035ebc6
RG
195LIST_HEAD(shrinker_list);
196DECLARE_RWSEM(shrinker_rwsem);
1da177e4 197
0a432dcb 198#ifdef CONFIG_MEMCG
a2fb1261 199static int shrinker_nr_max;
2bfd3637 200
3c6f17e6 201/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
a2fb1261
YS
202static inline int shrinker_map_size(int nr_items)
203{
204 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
205}
2bfd3637 206
3c6f17e6
YS
207static inline int shrinker_defer_size(int nr_items)
208{
209 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
210}
211
468ab843
YS
212static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
213 int nid)
214{
215 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
216 lockdep_is_held(&shrinker_rwsem));
217}
218
e4262c4f 219static int expand_one_shrinker_info(struct mem_cgroup *memcg,
3c6f17e6
YS
220 int map_size, int defer_size,
221 int old_map_size, int old_defer_size)
2bfd3637 222{
e4262c4f 223 struct shrinker_info *new, *old;
2bfd3637
YS
224 struct mem_cgroup_per_node *pn;
225 int nid;
3c6f17e6 226 int size = map_size + defer_size;
2bfd3637 227
2bfd3637
YS
228 for_each_node(nid) {
229 pn = memcg->nodeinfo[nid];
468ab843 230 old = shrinker_info_protected(memcg, nid);
2bfd3637
YS
231 /* Not yet online memcg */
232 if (!old)
233 return 0;
234
235 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
236 if (!new)
237 return -ENOMEM;
238
3c6f17e6
YS
239 new->nr_deferred = (atomic_long_t *)(new + 1);
240 new->map = (void *)new->nr_deferred + defer_size;
241
242 /* map: set all old bits, clear all new bits */
243 memset(new->map, (int)0xff, old_map_size);
244 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
245 /* nr_deferred: copy old values, clear all new values */
246 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
247 memset((void *)new->nr_deferred + old_defer_size, 0,
248 defer_size - old_defer_size);
2bfd3637 249
e4262c4f 250 rcu_assign_pointer(pn->shrinker_info, new);
72673e86 251 kvfree_rcu(old, rcu);
2bfd3637
YS
252 }
253
254 return 0;
255}
256
e4262c4f 257void free_shrinker_info(struct mem_cgroup *memcg)
2bfd3637
YS
258{
259 struct mem_cgroup_per_node *pn;
e4262c4f 260 struct shrinker_info *info;
2bfd3637
YS
261 int nid;
262
2bfd3637
YS
263 for_each_node(nid) {
264 pn = memcg->nodeinfo[nid];
e4262c4f
YS
265 info = rcu_dereference_protected(pn->shrinker_info, true);
266 kvfree(info);
267 rcu_assign_pointer(pn->shrinker_info, NULL);
2bfd3637
YS
268 }
269}
270
e4262c4f 271int alloc_shrinker_info(struct mem_cgroup *memcg)
2bfd3637 272{
e4262c4f 273 struct shrinker_info *info;
2bfd3637 274 int nid, size, ret = 0;
3c6f17e6 275 int map_size, defer_size = 0;
2bfd3637 276
d27cf2aa 277 down_write(&shrinker_rwsem);
3c6f17e6
YS
278 map_size = shrinker_map_size(shrinker_nr_max);
279 defer_size = shrinker_defer_size(shrinker_nr_max);
280 size = map_size + defer_size;
2bfd3637 281 for_each_node(nid) {
e4262c4f
YS
282 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
283 if (!info) {
284 free_shrinker_info(memcg);
2bfd3637
YS
285 ret = -ENOMEM;
286 break;
287 }
3c6f17e6
YS
288 info->nr_deferred = (atomic_long_t *)(info + 1);
289 info->map = (void *)info->nr_deferred + defer_size;
e4262c4f 290 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2bfd3637 291 }
d27cf2aa 292 up_write(&shrinker_rwsem);
2bfd3637
YS
293
294 return ret;
295}
296
3c6f17e6
YS
297static inline bool need_expand(int nr_max)
298{
299 return round_up(nr_max, BITS_PER_LONG) >
300 round_up(shrinker_nr_max, BITS_PER_LONG);
301}
302
e4262c4f 303static int expand_shrinker_info(int new_id)
2bfd3637 304{
3c6f17e6 305 int ret = 0;
a2fb1261 306 int new_nr_max = new_id + 1;
3c6f17e6
YS
307 int map_size, defer_size = 0;
308 int old_map_size, old_defer_size = 0;
2bfd3637
YS
309 struct mem_cgroup *memcg;
310
3c6f17e6 311 if (!need_expand(new_nr_max))
a2fb1261 312 goto out;
2bfd3637 313
2bfd3637 314 if (!root_mem_cgroup)
d27cf2aa
YS
315 goto out;
316
317 lockdep_assert_held(&shrinker_rwsem);
2bfd3637 318
3c6f17e6
YS
319 map_size = shrinker_map_size(new_nr_max);
320 defer_size = shrinker_defer_size(new_nr_max);
321 old_map_size = shrinker_map_size(shrinker_nr_max);
322 old_defer_size = shrinker_defer_size(shrinker_nr_max);
323
2bfd3637
YS
324 memcg = mem_cgroup_iter(NULL, NULL, NULL);
325 do {
3c6f17e6
YS
326 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
327 old_map_size, old_defer_size);
2bfd3637
YS
328 if (ret) {
329 mem_cgroup_iter_break(NULL, memcg);
d27cf2aa 330 goto out;
2bfd3637
YS
331 }
332 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
d27cf2aa 333out:
2bfd3637 334 if (!ret)
a2fb1261 335 shrinker_nr_max = new_nr_max;
d27cf2aa 336
2bfd3637
YS
337 return ret;
338}
339
340void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
341{
342 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
e4262c4f 343 struct shrinker_info *info;
2bfd3637
YS
344
345 rcu_read_lock();
e4262c4f 346 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
2bfd3637
YS
347 /* Pairs with smp mb in shrink_slab() */
348 smp_mb__before_atomic();
e4262c4f 349 set_bit(shrinker_id, info->map);
2bfd3637
YS
350 rcu_read_unlock();
351 }
352}
353
b4c2b231 354static DEFINE_IDR(shrinker_idr);
b4c2b231
KT
355
356static int prealloc_memcg_shrinker(struct shrinker *shrinker)
357{
358 int id, ret = -ENOMEM;
359
476b30a0
YS
360 if (mem_cgroup_disabled())
361 return -ENOSYS;
362
b4c2b231
KT
363 down_write(&shrinker_rwsem);
364 /* This may call shrinker, so it must use down_read_trylock() */
41ca668a 365 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
b4c2b231
KT
366 if (id < 0)
367 goto unlock;
368
0a4465d3 369 if (id >= shrinker_nr_max) {
e4262c4f 370 if (expand_shrinker_info(id)) {
0a4465d3
KT
371 idr_remove(&shrinker_idr, id);
372 goto unlock;
373 }
0a4465d3 374 }
b4c2b231
KT
375 shrinker->id = id;
376 ret = 0;
377unlock:
378 up_write(&shrinker_rwsem);
379 return ret;
380}
381
382static void unregister_memcg_shrinker(struct shrinker *shrinker)
383{
384 int id = shrinker->id;
385
386 BUG_ON(id < 0);
387
41ca668a
YS
388 lockdep_assert_held(&shrinker_rwsem);
389
b4c2b231 390 idr_remove(&shrinker_idr, id);
b4c2b231 391}
b4c2b231 392
86750830
YS
393static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
394 struct mem_cgroup *memcg)
395{
396 struct shrinker_info *info;
397
398 info = shrinker_info_protected(memcg, nid);
399 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
400}
401
402static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
403 struct mem_cgroup *memcg)
404{
405 struct shrinker_info *info;
406
407 info = shrinker_info_protected(memcg, nid);
408 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
409}
410
a178015c
YS
411void reparent_shrinker_deferred(struct mem_cgroup *memcg)
412{
413 int i, nid;
414 long nr;
415 struct mem_cgroup *parent;
416 struct shrinker_info *child_info, *parent_info;
417
418 parent = parent_mem_cgroup(memcg);
419 if (!parent)
420 parent = root_mem_cgroup;
421
422 /* Prevent from concurrent shrinker_info expand */
423 down_read(&shrinker_rwsem);
424 for_each_node(nid) {
425 child_info = shrinker_info_protected(memcg, nid);
426 parent_info = shrinker_info_protected(parent, nid);
427 for (i = 0; i < shrinker_nr_max; i++) {
428 nr = atomic_long_read(&child_info->nr_deferred[i]);
429 atomic_long_add(nr, &parent_info->nr_deferred[i]);
430 }
431 }
432 up_read(&shrinker_rwsem);
433}
434
b5ead35e 435static bool cgroup_reclaim(struct scan_control *sc)
89b5fae5 436{
b5ead35e 437 return sc->target_mem_cgroup;
89b5fae5 438}
97c9341f
TH
439
440/**
b5ead35e 441 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
97c9341f
TH
442 * @sc: scan_control in question
443 *
444 * The normal page dirty throttling mechanism in balance_dirty_pages() is
445 * completely broken with the legacy memcg and direct stalling in
446 * shrink_page_list() is used for throttling instead, which lacks all the
447 * niceties such as fairness, adaptive pausing, bandwidth proportional
448 * allocation and configurability.
449 *
450 * This function tests whether the vmscan currently in progress can assume
451 * that the normal dirty throttling mechanism is operational.
452 */
b5ead35e 453static bool writeback_throttling_sane(struct scan_control *sc)
97c9341f 454{
b5ead35e 455 if (!cgroup_reclaim(sc))
97c9341f
TH
456 return true;
457#ifdef CONFIG_CGROUP_WRITEBACK
69234ace 458 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
97c9341f
TH
459 return true;
460#endif
461 return false;
462}
91a45470 463#else
0a432dcb
YS
464static int prealloc_memcg_shrinker(struct shrinker *shrinker)
465{
476b30a0 466 return -ENOSYS;
0a432dcb
YS
467}
468
469static void unregister_memcg_shrinker(struct shrinker *shrinker)
470{
471}
472
86750830
YS
473static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
474 struct mem_cgroup *memcg)
475{
476 return 0;
477}
478
479static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
480 struct mem_cgroup *memcg)
481{
482 return 0;
483}
484
b5ead35e 485static bool cgroup_reclaim(struct scan_control *sc)
89b5fae5 486{
b5ead35e 487 return false;
89b5fae5 488}
97c9341f 489
b5ead35e 490static bool writeback_throttling_sane(struct scan_control *sc)
97c9341f
TH
491{
492 return true;
493}
91a45470
KH
494#endif
495
86750830
YS
496static long xchg_nr_deferred(struct shrinker *shrinker,
497 struct shrink_control *sc)
498{
499 int nid = sc->nid;
500
501 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
502 nid = 0;
503
504 if (sc->memcg &&
505 (shrinker->flags & SHRINKER_MEMCG_AWARE))
506 return xchg_nr_deferred_memcg(nid, shrinker,
507 sc->memcg);
508
509 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
510}
511
512
513static long add_nr_deferred(long nr, struct shrinker *shrinker,
514 struct shrink_control *sc)
515{
516 int nid = sc->nid;
517
518 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
519 nid = 0;
520
521 if (sc->memcg &&
522 (shrinker->flags & SHRINKER_MEMCG_AWARE))
523 return add_nr_deferred_memcg(nr, nid, shrinker,
524 sc->memcg);
525
526 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
527}
528
26aa2d19
DH
529static bool can_demote(int nid, struct scan_control *sc)
530{
20b51af1
HY
531 if (!numa_demotion_enabled)
532 return false;
3f1509c5
JW
533 if (sc && sc->no_demotion)
534 return false;
26aa2d19
DH
535 if (next_demotion_node(nid) == NUMA_NO_NODE)
536 return false;
537
20b51af1 538 return true;
26aa2d19
DH
539}
540
a2a36488
KB
541static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
542 int nid,
543 struct scan_control *sc)
544{
545 if (memcg == NULL) {
546 /*
547 * For non-memcg reclaim, is there
548 * space in any swap device?
549 */
550 if (get_nr_swap_pages() > 0)
551 return true;
552 } else {
553 /* Is the memcg below its swap limit? */
554 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
555 return true;
556 }
557
558 /*
559 * The page can not be swapped.
560 *
561 * Can it be reclaimed from this node via demotion?
562 */
563 return can_demote(nid, sc);
564}
565
5a1c84b4
MG
566/*
567 * This misses isolated pages which are not accounted for to save counters.
568 * As the data only determines if reclaim or compaction continues, it is
569 * not expected that isolated pages will be a dominating factor.
570 */
571unsigned long zone_reclaimable_pages(struct zone *zone)
572{
573 unsigned long nr;
574
575 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
576 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
a2a36488 577 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
5a1c84b4
MG
578 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
579 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
580
581 return nr;
582}
583
fd538803
MH
584/**
585 * lruvec_lru_size - Returns the number of pages on the given LRU list.
586 * @lruvec: lru vector
587 * @lru: lru to use
8b3a899a 588 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
fd538803 589 */
2091339d
YZ
590static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
591 int zone_idx)
c9f299d9 592{
de3b0150 593 unsigned long size = 0;
fd538803
MH
594 int zid;
595
8b3a899a 596 for (zid = 0; zid <= zone_idx; zid++) {
fd538803 597 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
c9f299d9 598
fd538803
MH
599 if (!managed_zone(zone))
600 continue;
601
602 if (!mem_cgroup_disabled())
de3b0150 603 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
fd538803 604 else
de3b0150 605 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
fd538803 606 }
de3b0150 607 return size;
b4536f0c
MH
608}
609
1da177e4 610/*
1d3d4437 611 * Add a shrinker callback to be called from the vm.
1da177e4 612 */
e33c267a 613static int __prealloc_shrinker(struct shrinker *shrinker)
1da177e4 614{
476b30a0
YS
615 unsigned int size;
616 int err;
617
618 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
619 err = prealloc_memcg_shrinker(shrinker);
620 if (err != -ENOSYS)
621 return err;
1d3d4437 622
476b30a0
YS
623 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
624 }
625
626 size = sizeof(*shrinker->nr_deferred);
1d3d4437
GC
627 if (shrinker->flags & SHRINKER_NUMA_AWARE)
628 size *= nr_node_ids;
629
630 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
631 if (!shrinker->nr_deferred)
632 return -ENOMEM;
b4c2b231 633
8e04944f
TH
634 return 0;
635}
636
e33c267a
RG
637#ifdef CONFIG_SHRINKER_DEBUG
638int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
639{
640 va_list ap;
641 int err;
642
643 va_start(ap, fmt);
644 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
645 va_end(ap);
646 if (!shrinker->name)
647 return -ENOMEM;
648
649 err = __prealloc_shrinker(shrinker);
14773bfa 650 if (err) {
e33c267a 651 kfree_const(shrinker->name);
14773bfa
TH
652 shrinker->name = NULL;
653 }
e33c267a
RG
654
655 return err;
656}
657#else
658int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
659{
660 return __prealloc_shrinker(shrinker);
661}
662#endif
663
8e04944f
TH
664void free_prealloced_shrinker(struct shrinker *shrinker)
665{
e33c267a
RG
666#ifdef CONFIG_SHRINKER_DEBUG
667 kfree_const(shrinker->name);
14773bfa 668 shrinker->name = NULL;
e33c267a 669#endif
41ca668a
YS
670 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
671 down_write(&shrinker_rwsem);
b4c2b231 672 unregister_memcg_shrinker(shrinker);
41ca668a 673 up_write(&shrinker_rwsem);
476b30a0 674 return;
41ca668a 675 }
b4c2b231 676
8e04944f
TH
677 kfree(shrinker->nr_deferred);
678 shrinker->nr_deferred = NULL;
679}
1d3d4437 680
8e04944f
TH
681void register_shrinker_prepared(struct shrinker *shrinker)
682{
8e1f936b
RR
683 down_write(&shrinker_rwsem);
684 list_add_tail(&shrinker->list, &shrinker_list);
41ca668a 685 shrinker->flags |= SHRINKER_REGISTERED;
5035ebc6 686 shrinker_debugfs_add(shrinker);
8e1f936b 687 up_write(&shrinker_rwsem);
8e04944f
TH
688}
689
e33c267a 690static int __register_shrinker(struct shrinker *shrinker)
8e04944f 691{
e33c267a 692 int err = __prealloc_shrinker(shrinker);
8e04944f
TH
693
694 if (err)
695 return err;
696 register_shrinker_prepared(shrinker);
1d3d4437 697 return 0;
1da177e4 698}
e33c267a
RG
699
700#ifdef CONFIG_SHRINKER_DEBUG
701int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
702{
703 va_list ap;
704 int err;
705
706 va_start(ap, fmt);
707 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
708 va_end(ap);
709 if (!shrinker->name)
710 return -ENOMEM;
711
712 err = __register_shrinker(shrinker);
14773bfa 713 if (err) {
e33c267a 714 kfree_const(shrinker->name);
14773bfa
TH
715 shrinker->name = NULL;
716 }
e33c267a
RG
717 return err;
718}
719#else
720int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
721{
722 return __register_shrinker(shrinker);
723}
724#endif
8e1f936b 725EXPORT_SYMBOL(register_shrinker);
1da177e4
LT
726
727/*
728 * Remove one
729 */
8e1f936b 730void unregister_shrinker(struct shrinker *shrinker)
1da177e4 731{
41ca668a 732 if (!(shrinker->flags & SHRINKER_REGISTERED))
bb422a73 733 return;
41ca668a 734
1da177e4
LT
735 down_write(&shrinker_rwsem);
736 list_del(&shrinker->list);
41ca668a
YS
737 shrinker->flags &= ~SHRINKER_REGISTERED;
738 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
739 unregister_memcg_shrinker(shrinker);
5035ebc6 740 shrinker_debugfs_remove(shrinker);
1da177e4 741 up_write(&shrinker_rwsem);
41ca668a 742
ae393321 743 kfree(shrinker->nr_deferred);
bb422a73 744 shrinker->nr_deferred = NULL;
1da177e4 745}
8e1f936b 746EXPORT_SYMBOL(unregister_shrinker);
1da177e4 747
880121be
CK
748/**
749 * synchronize_shrinkers - Wait for all running shrinkers to complete.
750 *
751 * This is equivalent to calling unregister_shrink() and register_shrinker(),
752 * but atomically and with less overhead. This is useful to guarantee that all
753 * shrinker invocations have seen an update, before freeing memory, similar to
754 * rcu.
755 */
756void synchronize_shrinkers(void)
757{
758 down_write(&shrinker_rwsem);
759 up_write(&shrinker_rwsem);
760}
761EXPORT_SYMBOL(synchronize_shrinkers);
762
1da177e4 763#define SHRINK_BATCH 128
1d3d4437 764
cb731d6c 765static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
9092c71b 766 struct shrinker *shrinker, int priority)
1d3d4437
GC
767{
768 unsigned long freed = 0;
769 unsigned long long delta;
770 long total_scan;
d5bc5fd3 771 long freeable;
1d3d4437
GC
772 long nr;
773 long new_nr;
1d3d4437
GC
774 long batch_size = shrinker->batch ? shrinker->batch
775 : SHRINK_BATCH;
5f33a080 776 long scanned = 0, next_deferred;
1d3d4437 777
d5bc5fd3 778 freeable = shrinker->count_objects(shrinker, shrinkctl);
9b996468
KT
779 if (freeable == 0 || freeable == SHRINK_EMPTY)
780 return freeable;
1d3d4437
GC
781
782 /*
783 * copy the current shrinker scan count into a local variable
784 * and zero it so that other concurrent shrinker invocations
785 * don't also do this scanning work.
786 */
86750830 787 nr = xchg_nr_deferred(shrinker, shrinkctl);
1d3d4437 788
4b85afbd
JW
789 if (shrinker->seeks) {
790 delta = freeable >> priority;
791 delta *= 4;
792 do_div(delta, shrinker->seeks);
793 } else {
794 /*
795 * These objects don't require any IO to create. Trim
796 * them aggressively under memory pressure to keep
797 * them from causing refetches in the IO caches.
798 */
799 delta = freeable / 2;
800 }
172b06c3 801
18bb473e 802 total_scan = nr >> priority;
1d3d4437 803 total_scan += delta;
18bb473e 804 total_scan = min(total_scan, (2 * freeable));
1d3d4437
GC
805
806 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
9092c71b 807 freeable, delta, total_scan, priority);
1d3d4437 808
0b1fb40a
VD
809 /*
810 * Normally, we should not scan less than batch_size objects in one
811 * pass to avoid too frequent shrinker calls, but if the slab has less
812 * than batch_size objects in total and we are really tight on memory,
813 * we will try to reclaim all available objects, otherwise we can end
814 * up failing allocations although there are plenty of reclaimable
815 * objects spread over several slabs with usage less than the
816 * batch_size.
817 *
818 * We detect the "tight on memory" situations by looking at the total
819 * number of objects we want to scan (total_scan). If it is greater
d5bc5fd3 820 * than the total number of objects on slab (freeable), we must be
0b1fb40a
VD
821 * scanning at high prio and therefore should try to reclaim as much as
822 * possible.
823 */
824 while (total_scan >= batch_size ||
d5bc5fd3 825 total_scan >= freeable) {
a0b02131 826 unsigned long ret;
0b1fb40a 827 unsigned long nr_to_scan = min(batch_size, total_scan);
1d3d4437 828
0b1fb40a 829 shrinkctl->nr_to_scan = nr_to_scan;
d460acb5 830 shrinkctl->nr_scanned = nr_to_scan;
a0b02131
DC
831 ret = shrinker->scan_objects(shrinker, shrinkctl);
832 if (ret == SHRINK_STOP)
833 break;
834 freed += ret;
1d3d4437 835
d460acb5
CW
836 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
837 total_scan -= shrinkctl->nr_scanned;
838 scanned += shrinkctl->nr_scanned;
1d3d4437
GC
839
840 cond_resched();
841 }
842
18bb473e
YS
843 /*
844 * The deferred work is increased by any new work (delta) that wasn't
845 * done, decreased by old deferred work that was done now.
846 *
847 * And it is capped to two times of the freeable items.
848 */
849 next_deferred = max_t(long, (nr + delta - scanned), 0);
850 next_deferred = min(next_deferred, (2 * freeable));
851
1d3d4437
GC
852 /*
853 * move the unused scan count back into the shrinker in a
86750830 854 * manner that handles concurrent updates.
1d3d4437 855 */
86750830 856 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
1d3d4437 857
8efb4b59 858 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
1d3d4437 859 return freed;
1495f230
YH
860}
861
0a432dcb 862#ifdef CONFIG_MEMCG
b0dedc49
KT
863static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
864 struct mem_cgroup *memcg, int priority)
865{
e4262c4f 866 struct shrinker_info *info;
b8e57efa
KT
867 unsigned long ret, freed = 0;
868 int i;
b0dedc49 869
0a432dcb 870 if (!mem_cgroup_online(memcg))
b0dedc49
KT
871 return 0;
872
873 if (!down_read_trylock(&shrinker_rwsem))
874 return 0;
875
468ab843 876 info = shrinker_info_protected(memcg, nid);
e4262c4f 877 if (unlikely(!info))
b0dedc49
KT
878 goto unlock;
879
e4262c4f 880 for_each_set_bit(i, info->map, shrinker_nr_max) {
b0dedc49
KT
881 struct shrink_control sc = {
882 .gfp_mask = gfp_mask,
883 .nid = nid,
884 .memcg = memcg,
885 };
886 struct shrinker *shrinker;
887
888 shrinker = idr_find(&shrinker_idr, i);
41ca668a 889 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
7e010df5 890 if (!shrinker)
e4262c4f 891 clear_bit(i, info->map);
b0dedc49
KT
892 continue;
893 }
894
0a432dcb
YS
895 /* Call non-slab shrinkers even though kmem is disabled */
896 if (!memcg_kmem_enabled() &&
897 !(shrinker->flags & SHRINKER_NONSLAB))
898 continue;
899
b0dedc49 900 ret = do_shrink_slab(&sc, shrinker, priority);
f90280d6 901 if (ret == SHRINK_EMPTY) {
e4262c4f 902 clear_bit(i, info->map);
f90280d6
KT
903 /*
904 * After the shrinker reported that it had no objects to
905 * free, but before we cleared the corresponding bit in
906 * the memcg shrinker map, a new object might have been
907 * added. To make sure, we have the bit set in this
908 * case, we invoke the shrinker one more time and reset
909 * the bit if it reports that it is not empty anymore.
910 * The memory barrier here pairs with the barrier in
2bfd3637 911 * set_shrinker_bit():
f90280d6
KT
912 *
913 * list_lru_add() shrink_slab_memcg()
914 * list_add_tail() clear_bit()
915 * <MB> <MB>
916 * set_bit() do_shrink_slab()
917 */
918 smp_mb__after_atomic();
919 ret = do_shrink_slab(&sc, shrinker, priority);
920 if (ret == SHRINK_EMPTY)
921 ret = 0;
922 else
2bfd3637 923 set_shrinker_bit(memcg, nid, i);
f90280d6 924 }
b0dedc49
KT
925 freed += ret;
926
927 if (rwsem_is_contended(&shrinker_rwsem)) {
928 freed = freed ? : 1;
929 break;
930 }
931 }
932unlock:
933 up_read(&shrinker_rwsem);
934 return freed;
935}
0a432dcb 936#else /* CONFIG_MEMCG */
b0dedc49
KT
937static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
938 struct mem_cgroup *memcg, int priority)
939{
940 return 0;
941}
0a432dcb 942#endif /* CONFIG_MEMCG */
b0dedc49 943
6b4f7799 944/**
cb731d6c 945 * shrink_slab - shrink slab caches
6b4f7799
JW
946 * @gfp_mask: allocation context
947 * @nid: node whose slab caches to target
cb731d6c 948 * @memcg: memory cgroup whose slab caches to target
9092c71b 949 * @priority: the reclaim priority
1da177e4 950 *
6b4f7799 951 * Call the shrink functions to age shrinkable caches.
1da177e4 952 *
6b4f7799
JW
953 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
954 * unaware shrinkers will receive a node id of 0 instead.
1da177e4 955 *
aeed1d32
VD
956 * @memcg specifies the memory cgroup to target. Unaware shrinkers
957 * are called only if it is the root cgroup.
cb731d6c 958 *
9092c71b
JB
959 * @priority is sc->priority, we take the number of objects and >> by priority
960 * in order to get the scan target.
b15e0905 961 *
6b4f7799 962 * Returns the number of reclaimed slab objects.
1da177e4 963 */
cb731d6c
VD
964static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
965 struct mem_cgroup *memcg,
9092c71b 966 int priority)
1da177e4 967{
b8e57efa 968 unsigned long ret, freed = 0;
1da177e4
LT
969 struct shrinker *shrinker;
970
fa1e512f
YS
971 /*
972 * The root memcg might be allocated even though memcg is disabled
973 * via "cgroup_disable=memory" boot parameter. This could make
974 * mem_cgroup_is_root() return false, then just run memcg slab
975 * shrink, but skip global shrink. This may result in premature
976 * oom.
977 */
978 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
b0dedc49 979 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
cb731d6c 980
e830c63a 981 if (!down_read_trylock(&shrinker_rwsem))
f06590bd 982 goto out;
1da177e4
LT
983
984 list_for_each_entry(shrinker, &shrinker_list, list) {
6b4f7799
JW
985 struct shrink_control sc = {
986 .gfp_mask = gfp_mask,
987 .nid = nid,
cb731d6c 988 .memcg = memcg,
6b4f7799 989 };
ec97097b 990
9b996468
KT
991 ret = do_shrink_slab(&sc, shrinker, priority);
992 if (ret == SHRINK_EMPTY)
993 ret = 0;
994 freed += ret;
e496612c
MK
995 /*
996 * Bail out if someone want to register a new shrinker to
55b65a57 997 * prevent the registration from being stalled for long periods
e496612c
MK
998 * by parallel ongoing shrinking.
999 */
1000 if (rwsem_is_contended(&shrinker_rwsem)) {
1001 freed = freed ? : 1;
1002 break;
1003 }
1da177e4 1004 }
6b4f7799 1005
1da177e4 1006 up_read(&shrinker_rwsem);
f06590bd
MK
1007out:
1008 cond_resched();
24f7c6b9 1009 return freed;
1da177e4
LT
1010}
1011
e4b424b7 1012static void drop_slab_node(int nid)
cb731d6c
VD
1013{
1014 unsigned long freed;
1399af7e 1015 int shift = 0;
cb731d6c
VD
1016
1017 do {
1018 struct mem_cgroup *memcg = NULL;
1019
069c411d
CZ
1020 if (fatal_signal_pending(current))
1021 return;
1022
cb731d6c 1023 freed = 0;
aeed1d32 1024 memcg = mem_cgroup_iter(NULL, NULL, NULL);
cb731d6c 1025 do {
9092c71b 1026 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
cb731d6c 1027 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1399af7e 1028 } while ((freed >> shift++) > 1);
cb731d6c
VD
1029}
1030
1031void drop_slab(void)
1032{
1033 int nid;
1034
1035 for_each_online_node(nid)
1036 drop_slab_node(nid);
1037}
1038
e0cd5e7f 1039static inline int is_page_cache_freeable(struct folio *folio)
1da177e4 1040{
ceddc3a5
JW
1041 /*
1042 * A freeable page cache page is referenced only by the caller
67891fff
MW
1043 * that isolated the page, the page cache and optional buffer
1044 * heads at page->private.
ceddc3a5 1045 */
e0cd5e7f
MWO
1046 return folio_ref_count(folio) - folio_test_private(folio) ==
1047 1 + folio_nr_pages(folio);
1da177e4
LT
1048}
1049
1da177e4 1050/*
e0cd5e7f 1051 * We detected a synchronous write error writing a folio out. Probably
1da177e4
LT
1052 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1053 * fsync(), msync() or close().
1054 *
1055 * The tricky part is that after writepage we cannot touch the mapping: nothing
e0cd5e7f
MWO
1056 * prevents it from being freed up. But we have a ref on the folio and once
1057 * that folio is locked, the mapping is pinned.
1da177e4 1058 *
e0cd5e7f 1059 * We're allowed to run sleeping folio_lock() here because we know the caller has
1da177e4
LT
1060 * __GFP_FS.
1061 */
1062static void handle_write_error(struct address_space *mapping,
e0cd5e7f 1063 struct folio *folio, int error)
1da177e4 1064{
e0cd5e7f
MWO
1065 folio_lock(folio);
1066 if (folio_mapping(folio) == mapping)
3e9f45bd 1067 mapping_set_error(mapping, error);
e0cd5e7f 1068 folio_unlock(folio);
1da177e4
LT
1069}
1070
1b4e3f26
MG
1071static bool skip_throttle_noprogress(pg_data_t *pgdat)
1072{
1073 int reclaimable = 0, write_pending = 0;
1074 int i;
1075
1076 /*
1077 * If kswapd is disabled, reschedule if necessary but do not
1078 * throttle as the system is likely near OOM.
1079 */
1080 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1081 return true;
1082
1083 /*
1084 * If there are a lot of dirty/writeback pages then do not
1085 * throttle as throttling will occur when the pages cycle
1086 * towards the end of the LRU if still under writeback.
1087 */
1088 for (i = 0; i < MAX_NR_ZONES; i++) {
1089 struct zone *zone = pgdat->node_zones + i;
1090
36c26128 1091 if (!managed_zone(zone))
1b4e3f26
MG
1092 continue;
1093
1094 reclaimable += zone_reclaimable_pages(zone);
1095 write_pending += zone_page_state_snapshot(zone,
1096 NR_ZONE_WRITE_PENDING);
1097 }
1098 if (2 * write_pending <= reclaimable)
1099 return true;
1100
1101 return false;
1102}
1103
c3f4a9a2 1104void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
8cd7c588
MG
1105{
1106 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
c3f4a9a2 1107 long timeout, ret;
8cd7c588
MG
1108 DEFINE_WAIT(wait);
1109
1110 /*
1111 * Do not throttle IO workers, kthreads other than kswapd or
1112 * workqueues. They may be required for reclaim to make
1113 * forward progress (e.g. journalling workqueues or kthreads).
1114 */
1115 if (!current_is_kswapd() &&
b485c6f1
MG
1116 current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1117 cond_resched();
8cd7c588 1118 return;
b485c6f1 1119 }
8cd7c588 1120
c3f4a9a2
MG
1121 /*
1122 * These figures are pulled out of thin air.
1123 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1124 * parallel reclaimers which is a short-lived event so the timeout is
1125 * short. Failing to make progress or waiting on writeback are
1126 * potentially long-lived events so use a longer timeout. This is shaky
1127 * logic as a failure to make progress could be due to anything from
1128 * writeback to a slow device to excessive references pages at the tail
1129 * of the inactive LRU.
1130 */
1131 switch(reason) {
1132 case VMSCAN_THROTTLE_WRITEBACK:
1133 timeout = HZ/10;
1134
1135 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1136 WRITE_ONCE(pgdat->nr_reclaim_start,
1137 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1138 }
1139
1140 break;
1b4e3f26
MG
1141 case VMSCAN_THROTTLE_CONGESTED:
1142 fallthrough;
c3f4a9a2 1143 case VMSCAN_THROTTLE_NOPROGRESS:
1b4e3f26
MG
1144 if (skip_throttle_noprogress(pgdat)) {
1145 cond_resched();
1146 return;
1147 }
1148
1149 timeout = 1;
1150
c3f4a9a2
MG
1151 break;
1152 case VMSCAN_THROTTLE_ISOLATED:
1153 timeout = HZ/50;
1154 break;
1155 default:
1156 WARN_ON_ONCE(1);
1157 timeout = HZ;
1158 break;
8cd7c588
MG
1159 }
1160
1161 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1162 ret = schedule_timeout(timeout);
1163 finish_wait(wqh, &wait);
d818fca1 1164
c3f4a9a2 1165 if (reason == VMSCAN_THROTTLE_WRITEBACK)
d818fca1 1166 atomic_dec(&pgdat->nr_writeback_throttled);
8cd7c588
MG
1167
1168 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1169 jiffies_to_usecs(timeout - ret),
1170 reason);
1171}
1172
1173/*
1174 * Account for pages written if tasks are throttled waiting on dirty
1175 * pages to clean. If enough pages have been cleaned since throttling
1176 * started then wakeup the throttled tasks.
1177 */
512b7931 1178void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
8cd7c588
MG
1179 int nr_throttled)
1180{
1181 unsigned long nr_written;
1182
512b7931 1183 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
8cd7c588
MG
1184
1185 /*
1186 * This is an inaccurate read as the per-cpu deltas may not
1187 * be synchronised. However, given that the system is
1188 * writeback throttled, it is not worth taking the penalty
1189 * of getting an accurate count. At worst, the throttle
1190 * timeout guarantees forward progress.
1191 */
1192 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1193 READ_ONCE(pgdat->nr_reclaim_start);
1194
1195 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1196 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1197}
1198
04e62a29
CL
1199/* possible outcome of pageout() */
1200typedef enum {
1201 /* failed to write page out, page is locked */
1202 PAGE_KEEP,
1203 /* move page to the active list, page is locked */
1204 PAGE_ACTIVATE,
1205 /* page has been sent to the disk successfully, page is unlocked */
1206 PAGE_SUCCESS,
1207 /* page is clean and locked */
1208 PAGE_CLEAN,
1209} pageout_t;
1210
1da177e4 1211/*
1742f19f
AM
1212 * pageout is called by shrink_page_list() for each dirty page.
1213 * Calls ->writepage().
1da177e4 1214 */
2282679f
N
1215static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1216 struct swap_iocb **plug)
1da177e4
LT
1217{
1218 /*
e0cd5e7f 1219 * If the folio is dirty, only perform writeback if that write
1da177e4
LT
1220 * will be non-blocking. To prevent this allocation from being
1221 * stalled by pagecache activity. But note that there may be
1222 * stalls if we need to run get_block(). We could test
1223 * PagePrivate for that.
1224 *
8174202b 1225 * If this process is currently in __generic_file_write_iter() against
e0cd5e7f 1226 * this folio's queue, we can perform writeback even if that
1da177e4
LT
1227 * will block.
1228 *
e0cd5e7f 1229 * If the folio is swapcache, write it back even if that would
1da177e4
LT
1230 * block, for some throttling. This happens by accident, because
1231 * swap_backing_dev_info is bust: it doesn't reflect the
1232 * congestion state of the swapdevs. Easy to fix, if needed.
1da177e4 1233 */
e0cd5e7f 1234 if (!is_page_cache_freeable(folio))
1da177e4
LT
1235 return PAGE_KEEP;
1236 if (!mapping) {
1237 /*
e0cd5e7f
MWO
1238 * Some data journaling orphaned folios can have
1239 * folio->mapping == NULL while being dirty with clean buffers.
1da177e4 1240 */
e0cd5e7f 1241 if (folio_test_private(folio)) {
68189fef 1242 if (try_to_free_buffers(folio)) {
e0cd5e7f
MWO
1243 folio_clear_dirty(folio);
1244 pr_info("%s: orphaned folio\n", __func__);
1da177e4
LT
1245 return PAGE_CLEAN;
1246 }
1247 }
1248 return PAGE_KEEP;
1249 }
1250 if (mapping->a_ops->writepage == NULL)
1251 return PAGE_ACTIVATE;
1da177e4 1252
e0cd5e7f 1253 if (folio_clear_dirty_for_io(folio)) {
1da177e4
LT
1254 int res;
1255 struct writeback_control wbc = {
1256 .sync_mode = WB_SYNC_NONE,
1257 .nr_to_write = SWAP_CLUSTER_MAX,
111ebb6e
OH
1258 .range_start = 0,
1259 .range_end = LLONG_MAX,
1da177e4 1260 .for_reclaim = 1,
2282679f 1261 .swap_plug = plug,
1da177e4
LT
1262 };
1263
e0cd5e7f
MWO
1264 folio_set_reclaim(folio);
1265 res = mapping->a_ops->writepage(&folio->page, &wbc);
1da177e4 1266 if (res < 0)
e0cd5e7f 1267 handle_write_error(mapping, folio, res);
994fc28c 1268 if (res == AOP_WRITEPAGE_ACTIVATE) {
e0cd5e7f 1269 folio_clear_reclaim(folio);
1da177e4
LT
1270 return PAGE_ACTIVATE;
1271 }
c661b078 1272
e0cd5e7f 1273 if (!folio_test_writeback(folio)) {
1da177e4 1274 /* synchronous write or broken a_ops? */
e0cd5e7f 1275 folio_clear_reclaim(folio);
1da177e4 1276 }
e0cd5e7f
MWO
1277 trace_mm_vmscan_write_folio(folio);
1278 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1da177e4
LT
1279 return PAGE_SUCCESS;
1280 }
1281
1282 return PAGE_CLEAN;
1283}
1284
a649fd92 1285/*
e286781d
NP
1286 * Same as remove_mapping, but if the page is removed from the mapping, it
1287 * gets returned with a refcount of 0.
a649fd92 1288 */
be7c07d6 1289static int __remove_mapping(struct address_space *mapping, struct folio *folio,
b910718a 1290 bool reclaimed, struct mem_cgroup *target_memcg)
49d2e9cc 1291{
bd4c82c2 1292 int refcount;
aae466b0 1293 void *shadow = NULL;
c4843a75 1294
be7c07d6
MWO
1295 BUG_ON(!folio_test_locked(folio));
1296 BUG_ON(mapping != folio_mapping(folio));
49d2e9cc 1297
be7c07d6 1298 if (!folio_test_swapcache(folio))
51b8c1fe 1299 spin_lock(&mapping->host->i_lock);
30472509 1300 xa_lock_irq(&mapping->i_pages);
49d2e9cc 1301 /*
0fd0e6b0
NP
1302 * The non racy check for a busy page.
1303 *
1304 * Must be careful with the order of the tests. When someone has
1305 * a ref to the page, it may be possible that they dirty it then
1306 * drop the reference. So if PageDirty is tested before page_count
1307 * here, then the following race may occur:
1308 *
1309 * get_user_pages(&page);
1310 * [user mapping goes away]
1311 * write_to(page);
1312 * !PageDirty(page) [good]
1313 * SetPageDirty(page);
1314 * put_page(page);
1315 * !page_count(page) [good, discard it]
1316 *
1317 * [oops, our write_to data is lost]
1318 *
1319 * Reversing the order of the tests ensures such a situation cannot
1320 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
0139aa7b 1321 * load is not satisfied before that of page->_refcount.
0fd0e6b0
NP
1322 *
1323 * Note that if SetPageDirty is always performed via set_page_dirty,
b93b0163 1324 * and thus under the i_pages lock, then this ordering is not required.
49d2e9cc 1325 */
be7c07d6
MWO
1326 refcount = 1 + folio_nr_pages(folio);
1327 if (!folio_ref_freeze(folio, refcount))
49d2e9cc 1328 goto cannot_free;
1c4c3b99 1329 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
be7c07d6
MWO
1330 if (unlikely(folio_test_dirty(folio))) {
1331 folio_ref_unfreeze(folio, refcount);
49d2e9cc 1332 goto cannot_free;
e286781d 1333 }
49d2e9cc 1334
be7c07d6
MWO
1335 if (folio_test_swapcache(folio)) {
1336 swp_entry_t swap = folio_swap_entry(folio);
3ecb0087 1337 mem_cgroup_swapout(folio, swap);
aae466b0 1338 if (reclaimed && !mapping_exiting(mapping))
8927f647 1339 shadow = workingset_eviction(folio, target_memcg);
ceff9d33 1340 __delete_from_swap_cache(folio, swap, shadow);
30472509 1341 xa_unlock_irq(&mapping->i_pages);
be7c07d6 1342 put_swap_page(&folio->page, swap);
e286781d 1343 } else {
d2329aa0 1344 void (*free_folio)(struct folio *);
6072d13c 1345
d2329aa0 1346 free_folio = mapping->a_ops->free_folio;
a528910e
JW
1347 /*
1348 * Remember a shadow entry for reclaimed file cache in
1349 * order to detect refaults, thus thrashing, later on.
1350 *
1351 * But don't store shadows in an address space that is
238c3046 1352 * already exiting. This is not just an optimization,
a528910e
JW
1353 * inode reclaim needs to empty out the radix tree or
1354 * the nodes are lost. Don't plant shadows behind its
1355 * back.
f9fe48be
RZ
1356 *
1357 * We also don't store shadows for DAX mappings because the
1358 * only page cache pages found in these are zero pages
1359 * covering holes, and because we don't want to mix DAX
1360 * exceptional entries and shadow exceptional entries in the
b93b0163 1361 * same address_space.
a528910e 1362 */
be7c07d6 1363 if (reclaimed && folio_is_file_lru(folio) &&
f9fe48be 1364 !mapping_exiting(mapping) && !dax_mapping(mapping))
8927f647
MWO
1365 shadow = workingset_eviction(folio, target_memcg);
1366 __filemap_remove_folio(folio, shadow);
30472509 1367 xa_unlock_irq(&mapping->i_pages);
51b8c1fe
JW
1368 if (mapping_shrinkable(mapping))
1369 inode_add_lru(mapping->host);
1370 spin_unlock(&mapping->host->i_lock);
6072d13c 1371
d2329aa0
MWO
1372 if (free_folio)
1373 free_folio(folio);
49d2e9cc
CL
1374 }
1375
49d2e9cc
CL
1376 return 1;
1377
1378cannot_free:
30472509 1379 xa_unlock_irq(&mapping->i_pages);
be7c07d6 1380 if (!folio_test_swapcache(folio))
51b8c1fe 1381 spin_unlock(&mapping->host->i_lock);
49d2e9cc
CL
1382 return 0;
1383}
1384
5100da38
MWO
1385/**
1386 * remove_mapping() - Attempt to remove a folio from its mapping.
1387 * @mapping: The address space.
1388 * @folio: The folio to remove.
1389 *
1390 * If the folio is dirty, under writeback or if someone else has a ref
1391 * on it, removal will fail.
1392 * Return: The number of pages removed from the mapping. 0 if the folio
1393 * could not be removed.
1394 * Context: The caller should have a single refcount on the folio and
1395 * hold its lock.
e286781d 1396 */
5100da38 1397long remove_mapping(struct address_space *mapping, struct folio *folio)
e286781d 1398{
be7c07d6 1399 if (__remove_mapping(mapping, folio, false, NULL)) {
e286781d 1400 /*
5100da38 1401 * Unfreezing the refcount with 1 effectively
e286781d
NP
1402 * drops the pagecache ref for us without requiring another
1403 * atomic operation.
1404 */
be7c07d6 1405 folio_ref_unfreeze(folio, 1);
5100da38 1406 return folio_nr_pages(folio);
e286781d
NP
1407 }
1408 return 0;
1409}
1410
894bc310 1411/**
ca6d60f3
MWO
1412 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1413 * @folio: Folio to be returned to an LRU list.
894bc310 1414 *
ca6d60f3
MWO
1415 * Add previously isolated @folio to appropriate LRU list.
1416 * The folio may still be unevictable for other reasons.
894bc310 1417 *
ca6d60f3 1418 * Context: lru_lock must not be held, interrupts must be enabled.
894bc310 1419 */
ca6d60f3 1420void folio_putback_lru(struct folio *folio)
894bc310 1421{
ca6d60f3
MWO
1422 folio_add_lru(folio);
1423 folio_put(folio); /* drop ref from isolate */
894bc310
LS
1424}
1425
dfc8d636
JW
1426enum page_references {
1427 PAGEREF_RECLAIM,
1428 PAGEREF_RECLAIM_CLEAN,
64574746 1429 PAGEREF_KEEP,
dfc8d636
JW
1430 PAGEREF_ACTIVATE,
1431};
1432
d92013d1 1433static enum page_references folio_check_references(struct folio *folio,
dfc8d636
JW
1434 struct scan_control *sc)
1435{
d92013d1 1436 int referenced_ptes, referenced_folio;
dfc8d636 1437 unsigned long vm_flags;
dfc8d636 1438
b3ac0413
MWO
1439 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1440 &vm_flags);
d92013d1 1441 referenced_folio = folio_test_clear_referenced(folio);
dfc8d636 1442
dfc8d636 1443 /*
d92013d1
MWO
1444 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1445 * Let the folio, now marked Mlocked, be moved to the unevictable list.
dfc8d636
JW
1446 */
1447 if (vm_flags & VM_LOCKED)
47d4f3ee 1448 return PAGEREF_ACTIVATE;
dfc8d636 1449
6d4675e6
MK
1450 /* rmap lock contention: rotate */
1451 if (referenced_ptes == -1)
1452 return PAGEREF_KEEP;
1453
64574746 1454 if (referenced_ptes) {
64574746 1455 /*
d92013d1 1456 * All mapped folios start out with page table
64574746 1457 * references from the instantiating fault, so we need
9030fb0b 1458 * to look twice if a mapped file/anon folio is used more
64574746
JW
1459 * than once.
1460 *
1461 * Mark it and spare it for another trip around the
1462 * inactive list. Another page table reference will
1463 * lead to its activation.
1464 *
d92013d1
MWO
1465 * Note: the mark is set for activated folios as well
1466 * so that recently deactivated but used folios are
64574746
JW
1467 * quickly recovered.
1468 */
d92013d1 1469 folio_set_referenced(folio);
64574746 1470
d92013d1 1471 if (referenced_folio || referenced_ptes > 1)
64574746
JW
1472 return PAGEREF_ACTIVATE;
1473
c909e993 1474 /*
d92013d1 1475 * Activate file-backed executable folios after first usage.
c909e993 1476 */
f19a27e3 1477 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
c909e993
KK
1478 return PAGEREF_ACTIVATE;
1479
64574746
JW
1480 return PAGEREF_KEEP;
1481 }
dfc8d636 1482
d92013d1 1483 /* Reclaim if clean, defer dirty folios to writeback */
f19a27e3 1484 if (referenced_folio && folio_is_file_lru(folio))
64574746
JW
1485 return PAGEREF_RECLAIM_CLEAN;
1486
1487 return PAGEREF_RECLAIM;
dfc8d636
JW
1488}
1489
e2be15f6 1490/* Check if a page is dirty or under writeback */
e20c41b1 1491static void folio_check_dirty_writeback(struct folio *folio,
e2be15f6
MG
1492 bool *dirty, bool *writeback)
1493{
b4597226
MG
1494 struct address_space *mapping;
1495
e2be15f6
MG
1496 /*
1497 * Anonymous pages are not handled by flushers and must be written
32a331a7
ML
1498 * from reclaim context. Do not stall reclaim based on them.
1499 * MADV_FREE anonymous pages are put into inactive file list too.
1500 * They could be mistakenly treated as file lru. So further anon
1501 * test is needed.
e2be15f6 1502 */
e20c41b1
MWO
1503 if (!folio_is_file_lru(folio) ||
1504 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
e2be15f6
MG
1505 *dirty = false;
1506 *writeback = false;
1507 return;
1508 }
1509
e20c41b1
MWO
1510 /* By default assume that the folio flags are accurate */
1511 *dirty = folio_test_dirty(folio);
1512 *writeback = folio_test_writeback(folio);
b4597226
MG
1513
1514 /* Verify dirty/writeback state if the filesystem supports it */
e20c41b1 1515 if (!folio_test_private(folio))
b4597226
MG
1516 return;
1517
e20c41b1 1518 mapping = folio_mapping(folio);
b4597226 1519 if (mapping && mapping->a_ops->is_dirty_writeback)
520f301c 1520 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
e2be15f6
MG
1521}
1522
26aa2d19
DH
1523static struct page *alloc_demote_page(struct page *page, unsigned long node)
1524{
1525 struct migration_target_control mtc = {
1526 /*
1527 * Allocate from 'node', or fail quickly and quietly.
1528 * When this happens, 'page' will likely just be discarded
1529 * instead of migrated.
1530 */
1531 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1532 __GFP_THISNODE | __GFP_NOWARN |
1533 __GFP_NOMEMALLOC | GFP_NOWAIT,
1534 .nid = node
1535 };
1536
1537 return alloc_migration_target(page, (unsigned long)&mtc);
1538}
1539
1540/*
1541 * Take pages on @demote_list and attempt to demote them to
1542 * another node. Pages which are not demoted are left on
1543 * @demote_pages.
1544 */
1545static unsigned int demote_page_list(struct list_head *demote_pages,
1546 struct pglist_data *pgdat)
1547{
1548 int target_nid = next_demotion_node(pgdat->node_id);
1549 unsigned int nr_succeeded;
26aa2d19
DH
1550
1551 if (list_empty(demote_pages))
1552 return 0;
1553
1554 if (target_nid == NUMA_NO_NODE)
1555 return 0;
1556
1557 /* Demotion ignores all cpuset and mempolicy settings */
cb75463c 1558 migrate_pages(demote_pages, alloc_demote_page, NULL,
26aa2d19
DH
1559 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1560 &nr_succeeded);
1561
668e4147
YS
1562 if (current_is_kswapd())
1563 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1564 else
1565 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1566
26aa2d19
DH
1567 return nr_succeeded;
1568}
1569
c28a0e96 1570static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
d791ea67
N
1571{
1572 if (gfp_mask & __GFP_FS)
1573 return true;
c28a0e96 1574 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
d791ea67
N
1575 return false;
1576 /*
1577 * We can "enter_fs" for swap-cache with only __GFP_IO
1578 * providing this isn't SWP_FS_OPS.
1579 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1580 * but that will never affect SWP_FS_OPS, so the data_race
1581 * is safe.
1582 */
b98c359f 1583 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
d791ea67
N
1584}
1585
1da177e4 1586/*
1742f19f 1587 * shrink_page_list() returns the number of reclaimed pages
1da177e4 1588 */
730ec8c0
MS
1589static unsigned int shrink_page_list(struct list_head *page_list,
1590 struct pglist_data *pgdat,
1591 struct scan_control *sc,
730ec8c0
MS
1592 struct reclaim_stat *stat,
1593 bool ignore_references)
1da177e4
LT
1594{
1595 LIST_HEAD(ret_pages);
abe4c3b5 1596 LIST_HEAD(free_pages);
26aa2d19 1597 LIST_HEAD(demote_pages);
730ec8c0
MS
1598 unsigned int nr_reclaimed = 0;
1599 unsigned int pgactivate = 0;
26aa2d19 1600 bool do_demote_pass;
2282679f 1601 struct swap_iocb *plug = NULL;
1da177e4 1602
060f005f 1603 memset(stat, 0, sizeof(*stat));
1da177e4 1604 cond_resched();
26aa2d19 1605 do_demote_pass = can_demote(pgdat->node_id, sc);
1da177e4 1606
26aa2d19 1607retry:
1da177e4
LT
1608 while (!list_empty(page_list)) {
1609 struct address_space *mapping;
be7c07d6 1610 struct folio *folio;
8940b34a 1611 enum page_references references = PAGEREF_RECLAIM;
d791ea67 1612 bool dirty, writeback;
98879b3b 1613 unsigned int nr_pages;
1da177e4
LT
1614
1615 cond_resched();
1616
be7c07d6
MWO
1617 folio = lru_to_folio(page_list);
1618 list_del(&folio->lru);
1da177e4 1619
c28a0e96 1620 if (!folio_trylock(folio))
1da177e4
LT
1621 goto keep;
1622
c28a0e96 1623 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1da177e4 1624
c28a0e96 1625 nr_pages = folio_nr_pages(folio);
98879b3b 1626
c28a0e96 1627 /* Account the number of base pages */
98879b3b 1628 sc->nr_scanned += nr_pages;
80e43426 1629
c28a0e96 1630 if (unlikely(!folio_evictable(folio)))
ad6b6704 1631 goto activate_locked;
894bc310 1632
1bee2c16 1633 if (!sc->may_unmap && folio_mapped(folio))
80e43426
CL
1634 goto keep_locked;
1635
e2be15f6 1636 /*
894befec 1637 * The number of dirty pages determines if a node is marked
8cd7c588 1638 * reclaim_congested. kswapd will stall and start writing
c28a0e96 1639 * folios if the tail of the LRU is all dirty unqueued folios.
e2be15f6 1640 */
e20c41b1 1641 folio_check_dirty_writeback(folio, &dirty, &writeback);
e2be15f6 1642 if (dirty || writeback)
c79b7b96 1643 stat->nr_dirty += nr_pages;
e2be15f6
MG
1644
1645 if (dirty && !writeback)
c79b7b96 1646 stat->nr_unqueued_dirty += nr_pages;
e2be15f6 1647
d04e8acd 1648 /*
c28a0e96
MWO
1649 * Treat this folio as congested if folios are cycling
1650 * through the LRU so quickly that the folios marked
1651 * for immediate reclaim are making it to the end of
1652 * the LRU a second time.
d04e8acd 1653 */
c28a0e96 1654 if (writeback && folio_test_reclaim(folio))
c79b7b96 1655 stat->nr_congested += nr_pages;
e2be15f6 1656
283aba9f 1657 /*
d33e4e14 1658 * If a folio at the tail of the LRU is under writeback, there
283aba9f
MG
1659 * are three cases to consider.
1660 *
c28a0e96
MWO
1661 * 1) If reclaim is encountering an excessive number
1662 * of folios under writeback and this folio has both
1663 * the writeback and reclaim flags set, then it
d33e4e14
MWO
1664 * indicates that folios are being queued for I/O but
1665 * are being recycled through the LRU before the I/O
1666 * can complete. Waiting on the folio itself risks an
1667 * indefinite stall if it is impossible to writeback
1668 * the folio due to I/O error or disconnected storage
1669 * so instead note that the LRU is being scanned too
1670 * quickly and the caller can stall after the folio
1671 * list has been processed.
283aba9f 1672 *
d33e4e14 1673 * 2) Global or new memcg reclaim encounters a folio that is
ecf5fc6e
MH
1674 * not marked for immediate reclaim, or the caller does not
1675 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
d33e4e14 1676 * not to fs). In this case mark the folio for immediate
97c9341f 1677 * reclaim and continue scanning.
283aba9f 1678 *
d791ea67 1679 * Require may_enter_fs() because we would wait on fs, which
d33e4e14
MWO
1680 * may not have submitted I/O yet. And the loop driver might
1681 * enter reclaim, and deadlock if it waits on a folio for
283aba9f
MG
1682 * which it is needed to do the write (loop masks off
1683 * __GFP_IO|__GFP_FS for this reason); but more thought
1684 * would probably show more reasons.
1685 *
d33e4e14
MWO
1686 * 3) Legacy memcg encounters a folio that already has the
1687 * reclaim flag set. memcg does not have any dirty folio
283aba9f 1688 * throttling so we could easily OOM just because too many
d33e4e14 1689 * folios are in writeback and there is nothing else to
283aba9f 1690 * reclaim. Wait for the writeback to complete.
c55e8d03 1691 *
d33e4e14
MWO
1692 * In cases 1) and 2) we activate the folios to get them out of
1693 * the way while we continue scanning for clean folios on the
c55e8d03
JW
1694 * inactive list and refilling from the active list. The
1695 * observation here is that waiting for disk writes is more
1696 * expensive than potentially causing reloads down the line.
1697 * Since they're marked for immediate reclaim, they won't put
1698 * memory pressure on the cache working set any longer than it
1699 * takes to write them to disk.
283aba9f 1700 */
d33e4e14 1701 if (folio_test_writeback(folio)) {
283aba9f
MG
1702 /* Case 1 above */
1703 if (current_is_kswapd() &&
d33e4e14 1704 folio_test_reclaim(folio) &&
599d0c95 1705 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
c79b7b96 1706 stat->nr_immediate += nr_pages;
c55e8d03 1707 goto activate_locked;
283aba9f
MG
1708
1709 /* Case 2 above */
b5ead35e 1710 } else if (writeback_throttling_sane(sc) ||
d33e4e14 1711 !folio_test_reclaim(folio) ||
c28a0e96 1712 !may_enter_fs(folio, sc->gfp_mask)) {
c3b94f44 1713 /*
d33e4e14 1714 * This is slightly racy -
c28a0e96
MWO
1715 * folio_end_writeback() might have
1716 * just cleared the reclaim flag, then
1717 * setting the reclaim flag here ends up
1718 * interpreted as the readahead flag - but
1719 * that does not matter enough to care.
1720 * What we do want is for this folio to
1721 * have the reclaim flag set next time
1722 * memcg reclaim reaches the tests above,
1723 * so it will then wait for writeback to
1724 * avoid OOM; and it's also appropriate
d33e4e14 1725 * in global reclaim.
c3b94f44 1726 */
d33e4e14 1727 folio_set_reclaim(folio);
c79b7b96 1728 stat->nr_writeback += nr_pages;
c55e8d03 1729 goto activate_locked;
283aba9f
MG
1730
1731 /* Case 3 above */
1732 } else {
d33e4e14
MWO
1733 folio_unlock(folio);
1734 folio_wait_writeback(folio);
1735 /* then go back and try same folio again */
1736 list_add_tail(&folio->lru, page_list);
7fadc820 1737 continue;
e62e384e 1738 }
c661b078 1739 }
1da177e4 1740
8940b34a 1741 if (!ignore_references)
d92013d1 1742 references = folio_check_references(folio, sc);
02c6de8d 1743
dfc8d636
JW
1744 switch (references) {
1745 case PAGEREF_ACTIVATE:
1da177e4 1746 goto activate_locked;
64574746 1747 case PAGEREF_KEEP:
98879b3b 1748 stat->nr_ref_keep += nr_pages;
64574746 1749 goto keep_locked;
dfc8d636
JW
1750 case PAGEREF_RECLAIM:
1751 case PAGEREF_RECLAIM_CLEAN:
c28a0e96 1752 ; /* try to reclaim the folio below */
dfc8d636 1753 }
1da177e4 1754
26aa2d19 1755 /*
c28a0e96 1756 * Before reclaiming the folio, try to relocate
26aa2d19
DH
1757 * its contents to another node.
1758 */
1759 if (do_demote_pass &&
c28a0e96
MWO
1760 (thp_migration_supported() || !folio_test_large(folio))) {
1761 list_add(&folio->lru, &demote_pages);
1762 folio_unlock(folio);
26aa2d19
DH
1763 continue;
1764 }
1765
1da177e4
LT
1766 /*
1767 * Anonymous process memory has backing store?
1768 * Try to allocate it some swap space here.
c28a0e96 1769 * Lazyfree folio could be freed directly
1da177e4 1770 */
c28a0e96
MWO
1771 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1772 if (!folio_test_swapcache(folio)) {
bd4c82c2
HY
1773 if (!(sc->gfp_mask & __GFP_IO))
1774 goto keep_locked;
d4b4084a 1775 if (folio_maybe_dma_pinned(folio))
feb889fb 1776 goto keep_locked;
c28a0e96
MWO
1777 if (folio_test_large(folio)) {
1778 /* cannot split folio, skip it */
d4b4084a 1779 if (!can_split_folio(folio, NULL))
bd4c82c2
HY
1780 goto activate_locked;
1781 /*
c28a0e96 1782 * Split folios without a PMD map right
bd4c82c2
HY
1783 * away. Chances are some or all of the
1784 * tail pages can be freed without IO.
1785 */
d4b4084a 1786 if (!folio_entire_mapcount(folio) &&
346cf613
MWO
1787 split_folio_to_list(folio,
1788 page_list))
bd4c82c2
HY
1789 goto activate_locked;
1790 }
09c02e56
MWO
1791 if (!add_to_swap(folio)) {
1792 if (!folio_test_large(folio))
98879b3b 1793 goto activate_locked_split;
bd4c82c2 1794 /* Fallback to swap normal pages */
346cf613
MWO
1795 if (split_folio_to_list(folio,
1796 page_list))
bd4c82c2 1797 goto activate_locked;
fe490cc0
HY
1798#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1799 count_vm_event(THP_SWPOUT_FALLBACK);
1800#endif
09c02e56 1801 if (!add_to_swap(folio))
98879b3b 1802 goto activate_locked_split;
bd4c82c2 1803 }
bd4c82c2 1804 }
c28a0e96
MWO
1805 } else if (folio_test_swapbacked(folio) &&
1806 folio_test_large(folio)) {
1807 /* Split shmem folio */
346cf613 1808 if (split_folio_to_list(folio, page_list))
7751b2da 1809 goto keep_locked;
e2be15f6 1810 }
1da177e4 1811
98879b3b 1812 /*
c28a0e96
MWO
1813 * If the folio was split above, the tail pages will make
1814 * their own pass through this function and be accounted
1815 * then.
98879b3b 1816 */
c28a0e96 1817 if ((nr_pages > 1) && !folio_test_large(folio)) {
98879b3b
YS
1818 sc->nr_scanned -= (nr_pages - 1);
1819 nr_pages = 1;
1820 }
1821
1da177e4 1822 /*
1bee2c16 1823 * The folio is mapped into the page tables of one or more
1da177e4
LT
1824 * processes. Try to unmap it here.
1825 */
1bee2c16 1826 if (folio_mapped(folio)) {
013339df 1827 enum ttu_flags flags = TTU_BATCH_FLUSH;
1bee2c16 1828 bool was_swapbacked = folio_test_swapbacked(folio);
bd4c82c2 1829
1bee2c16 1830 if (folio_test_pmd_mappable(folio))
bd4c82c2 1831 flags |= TTU_SPLIT_HUGE_PMD;
1f318a9b 1832
869f7ee6 1833 try_to_unmap(folio, flags);
1bee2c16 1834 if (folio_mapped(folio)) {
98879b3b 1835 stat->nr_unmap_fail += nr_pages;
1bee2c16
MWO
1836 if (!was_swapbacked &&
1837 folio_test_swapbacked(folio))
1f318a9b 1838 stat->nr_lazyfree_fail += nr_pages;
1da177e4 1839 goto activate_locked;
1da177e4
LT
1840 }
1841 }
1842
5441d490 1843 mapping = folio_mapping(folio);
49bd2bf9 1844 if (folio_test_dirty(folio)) {
ee72886d 1845 /*
49bd2bf9 1846 * Only kswapd can writeback filesystem folios
4eda4823 1847 * to avoid risk of stack overflow. But avoid
49bd2bf9 1848 * injecting inefficient single-folio I/O into
4eda4823 1849 * flusher writeback as much as possible: only
49bd2bf9
MWO
1850 * write folios when we've encountered many
1851 * dirty folios, and when we've already scanned
1852 * the rest of the LRU for clean folios and see
1853 * the same dirty folios again (with the reclaim
1854 * flag set).
ee72886d 1855 */
49bd2bf9
MWO
1856 if (folio_is_file_lru(folio) &&
1857 (!current_is_kswapd() ||
1858 !folio_test_reclaim(folio) ||
4eda4823 1859 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
49ea7eb6
MG
1860 /*
1861 * Immediately reclaim when written back.
49bd2bf9
MWO
1862 * Similar in principle to deactivate_page()
1863 * except we already have the folio isolated
49ea7eb6
MG
1864 * and know it's dirty
1865 */
49bd2bf9
MWO
1866 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1867 nr_pages);
1868 folio_set_reclaim(folio);
49ea7eb6 1869
c55e8d03 1870 goto activate_locked;
ee72886d
MG
1871 }
1872
dfc8d636 1873 if (references == PAGEREF_RECLAIM_CLEAN)
1da177e4 1874 goto keep_locked;
c28a0e96 1875 if (!may_enter_fs(folio, sc->gfp_mask))
1da177e4 1876 goto keep_locked;
52a8363e 1877 if (!sc->may_writepage)
1da177e4
LT
1878 goto keep_locked;
1879
d950c947 1880 /*
49bd2bf9
MWO
1881 * Folio is dirty. Flush the TLB if a writable entry
1882 * potentially exists to avoid CPU writes after I/O
d950c947
MG
1883 * starts and then write it out here.
1884 */
1885 try_to_unmap_flush_dirty();
2282679f 1886 switch (pageout(folio, mapping, &plug)) {
1da177e4
LT
1887 case PAGE_KEEP:
1888 goto keep_locked;
1889 case PAGE_ACTIVATE:
1890 goto activate_locked;
1891 case PAGE_SUCCESS:
c79b7b96 1892 stat->nr_pageout += nr_pages;
96f8bf4f 1893
49bd2bf9 1894 if (folio_test_writeback(folio))
41ac1999 1895 goto keep;
49bd2bf9 1896 if (folio_test_dirty(folio))
1da177e4 1897 goto keep;
7d3579e8 1898
1da177e4
LT
1899 /*
1900 * A synchronous write - probably a ramdisk. Go
49bd2bf9 1901 * ahead and try to reclaim the folio.
1da177e4 1902 */
49bd2bf9 1903 if (!folio_trylock(folio))
1da177e4 1904 goto keep;
49bd2bf9
MWO
1905 if (folio_test_dirty(folio) ||
1906 folio_test_writeback(folio))
1da177e4 1907 goto keep_locked;
49bd2bf9 1908 mapping = folio_mapping(folio);
01359eb2 1909 fallthrough;
1da177e4 1910 case PAGE_CLEAN:
49bd2bf9 1911 ; /* try to free the folio below */
1da177e4
LT
1912 }
1913 }
1914
1915 /*
0a36111c
MWO
1916 * If the folio has buffers, try to free the buffer
1917 * mappings associated with this folio. If we succeed
1918 * we try to free the folio as well.
1da177e4 1919 *
0a36111c
MWO
1920 * We do this even if the folio is dirty.
1921 * filemap_release_folio() does not perform I/O, but it
1922 * is possible for a folio to have the dirty flag set,
1923 * but it is actually clean (all its buffers are clean).
1924 * This happens if the buffers were written out directly,
1925 * with submit_bh(). ext3 will do this, as well as
1926 * the blockdev mapping. filemap_release_folio() will
1927 * discover that cleanness and will drop the buffers
1928 * and mark the folio clean - it can be freed.
1da177e4 1929 *
0a36111c
MWO
1930 * Rarely, folios can have buffers and no ->mapping.
1931 * These are the folios which were not successfully
1932 * invalidated in truncate_cleanup_folio(). We try to
1933 * drop those buffers here and if that worked, and the
1934 * folio is no longer mapped into process address space
1935 * (refcount == 1) it can be freed. Otherwise, leave
1936 * the folio on the LRU so it is swappable.
1da177e4 1937 */
0a36111c
MWO
1938 if (folio_has_private(folio)) {
1939 if (!filemap_release_folio(folio, sc->gfp_mask))
1da177e4 1940 goto activate_locked;
0a36111c
MWO
1941 if (!mapping && folio_ref_count(folio) == 1) {
1942 folio_unlock(folio);
1943 if (folio_put_testzero(folio))
e286781d
NP
1944 goto free_it;
1945 else {
1946 /*
1947 * rare race with speculative reference.
1948 * the speculative reference will free
0a36111c 1949 * this folio shortly, so we may
e286781d
NP
1950 * increment nr_reclaimed here (and
1951 * leave it off the LRU).
1952 */
9aafcffc 1953 nr_reclaimed += nr_pages;
e286781d
NP
1954 continue;
1955 }
1956 }
1da177e4
LT
1957 }
1958
64daa5d8 1959 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
802a3a92 1960 /* follow __remove_mapping for reference */
64daa5d8 1961 if (!folio_ref_freeze(folio, 1))
802a3a92 1962 goto keep_locked;
d17be2d9 1963 /*
64daa5d8 1964 * The folio has only one reference left, which is
d17be2d9 1965 * from the isolation. After the caller puts the
64daa5d8
MWO
1966 * folio back on the lru and drops the reference, the
1967 * folio will be freed anyway. It doesn't matter
1968 * which lru it goes on. So we don't bother checking
1969 * the dirty flag here.
d17be2d9 1970 */
64daa5d8
MWO
1971 count_vm_events(PGLAZYFREED, nr_pages);
1972 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
be7c07d6 1973 } else if (!mapping || !__remove_mapping(mapping, folio, true,
b910718a 1974 sc->target_mem_cgroup))
802a3a92 1975 goto keep_locked;
9a1ea439 1976
c28a0e96 1977 folio_unlock(folio);
e286781d 1978free_it:
98879b3b 1979 /*
c28a0e96
MWO
1980 * Folio may get swapped out as a whole, need to account
1981 * all pages in it.
98879b3b
YS
1982 */
1983 nr_reclaimed += nr_pages;
abe4c3b5
MG
1984
1985 /*
1986 * Is there need to periodically free_page_list? It would
1987 * appear not as the counts should be low
1988 */
c28a0e96 1989 if (unlikely(folio_test_large(folio)))
5375336c 1990 destroy_large_folio(folio);
7ae88534 1991 else
c28a0e96 1992 list_add(&folio->lru, &free_pages);
1da177e4
LT
1993 continue;
1994
98879b3b
YS
1995activate_locked_split:
1996 /*
1997 * The tail pages that are failed to add into swap cache
1998 * reach here. Fixup nr_scanned and nr_pages.
1999 */
2000 if (nr_pages > 1) {
2001 sc->nr_scanned -= (nr_pages - 1);
2002 nr_pages = 1;
2003 }
1da177e4 2004activate_locked:
68a22394 2005 /* Not a candidate for swapping, so reclaim swap space. */
246b6480
MWO
2006 if (folio_test_swapcache(folio) &&
2007 (mem_cgroup_swap_full(&folio->page) ||
2008 folio_test_mlocked(folio)))
2009 try_to_free_swap(&folio->page);
2010 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2011 if (!folio_test_mlocked(folio)) {
2012 int type = folio_is_file_lru(folio);
2013 folio_set_active(folio);
98879b3b 2014 stat->nr_activate[type] += nr_pages;
246b6480 2015 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
ad6b6704 2016 }
1da177e4 2017keep_locked:
c28a0e96 2018 folio_unlock(folio);
1da177e4 2019keep:
c28a0e96
MWO
2020 list_add(&folio->lru, &ret_pages);
2021 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2022 folio_test_unevictable(folio), folio);
1da177e4 2023 }
26aa2d19
DH
2024 /* 'page_list' is always empty here */
2025
c28a0e96 2026 /* Migrate folios selected for demotion */
26aa2d19 2027 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
c28a0e96 2028 /* Folios that could not be demoted are still in @demote_pages */
26aa2d19 2029 if (!list_empty(&demote_pages)) {
c28a0e96 2030 /* Folios which weren't demoted go back on @page_list for retry: */
26aa2d19
DH
2031 list_splice_init(&demote_pages, page_list);
2032 do_demote_pass = false;
2033 goto retry;
2034 }
abe4c3b5 2035
98879b3b
YS
2036 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2037
747db954 2038 mem_cgroup_uncharge_list(&free_pages);
72b252ae 2039 try_to_unmap_flush();
2d4894b5 2040 free_unref_page_list(&free_pages);
abe4c3b5 2041
1da177e4 2042 list_splice(&ret_pages, page_list);
886cf190 2043 count_vm_events(PGACTIVATE, pgactivate);
060f005f 2044
2282679f
N
2045 if (plug)
2046 swap_write_unplug(plug);
05ff5137 2047 return nr_reclaimed;
1da177e4
LT
2048}
2049
730ec8c0 2050unsigned int reclaim_clean_pages_from_list(struct zone *zone,
b8cecb93 2051 struct list_head *folio_list)
02c6de8d
MK
2052{
2053 struct scan_control sc = {
2054 .gfp_mask = GFP_KERNEL,
02c6de8d
MK
2055 .may_unmap = 1,
2056 };
1f318a9b 2057 struct reclaim_stat stat;
730ec8c0 2058 unsigned int nr_reclaimed;
b8cecb93
MWO
2059 struct folio *folio, *next;
2060 LIST_HEAD(clean_folios);
2d2b8d2b 2061 unsigned int noreclaim_flag;
02c6de8d 2062
b8cecb93
MWO
2063 list_for_each_entry_safe(folio, next, folio_list, lru) {
2064 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2065 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2066 !folio_test_unevictable(folio)) {
2067 folio_clear_active(folio);
2068 list_move(&folio->lru, &clean_folios);
02c6de8d
MK
2069 }
2070 }
2071
2d2b8d2b
YZ
2072 /*
2073 * We should be safe here since we are only dealing with file pages and
2074 * we are not kswapd and therefore cannot write dirty file pages. But
2075 * call memalloc_noreclaim_save() anyway, just in case these conditions
2076 * change in the future.
2077 */
2078 noreclaim_flag = memalloc_noreclaim_save();
b8cecb93 2079 nr_reclaimed = shrink_page_list(&clean_folios, zone->zone_pgdat, &sc,
013339df 2080 &stat, true);
2d2b8d2b
YZ
2081 memalloc_noreclaim_restore(noreclaim_flag);
2082
b8cecb93 2083 list_splice(&clean_folios, folio_list);
2da9f630
NP
2084 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2085 -(long)nr_reclaimed);
1f318a9b
JK
2086 /*
2087 * Since lazyfree pages are isolated from file LRU from the beginning,
2088 * they will rotate back to anonymous LRU in the end if it failed to
2089 * discard so isolated count will be mismatched.
2090 * Compensate the isolated count for both LRU lists.
2091 */
2092 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2093 stat.nr_lazyfree_fail);
2094 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2da9f630 2095 -(long)stat.nr_lazyfree_fail);
1f318a9b 2096 return nr_reclaimed;
02c6de8d
MK
2097}
2098
7ee36a14
MG
2099/*
2100 * Update LRU sizes after isolating pages. The LRU size updates must
55b65a57 2101 * be complete before mem_cgroup_update_lru_size due to a sanity check.
7ee36a14
MG
2102 */
2103static __always_inline void update_lru_sizes(struct lruvec *lruvec,
b4536f0c 2104 enum lru_list lru, unsigned long *nr_zone_taken)
7ee36a14 2105{
7ee36a14
MG
2106 int zid;
2107
7ee36a14
MG
2108 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2109 if (!nr_zone_taken[zid])
2110 continue;
2111
a892cb6b 2112 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
b4536f0c
MH
2113 }
2114
7ee36a14
MG
2115}
2116
f611fab7 2117/*
15b44736
HD
2118 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2119 *
2120 * lruvec->lru_lock is heavily contended. Some of the functions that
1da177e4
LT
2121 * shrink the lists perform better by taking out a batch of pages
2122 * and working on them outside the LRU lock.
2123 *
2124 * For pagecache intensive workloads, this function is the hottest
2125 * spot in the kernel (apart from copy_*_user functions).
2126 *
15b44736 2127 * Lru_lock must be held before calling this function.
1da177e4 2128 *
791b48b6 2129 * @nr_to_scan: The number of eligible pages to look through on the list.
5dc35979 2130 * @lruvec: The LRU vector to pull pages from.
1da177e4 2131 * @dst: The temp list to put pages on to.
f626012d 2132 * @nr_scanned: The number of pages that were scanned.
fe2c2a10 2133 * @sc: The scan_control struct for this reclaim session
3cb99451 2134 * @lru: LRU list id for isolating
1da177e4
LT
2135 *
2136 * returns how many pages were moved onto *@dst.
2137 */
69e05944 2138static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
5dc35979 2139 struct lruvec *lruvec, struct list_head *dst,
fe2c2a10 2140 unsigned long *nr_scanned, struct scan_control *sc,
a9e7c39f 2141 enum lru_list lru)
1da177e4 2142{
75b00af7 2143 struct list_head *src = &lruvec->lists[lru];
69e05944 2144 unsigned long nr_taken = 0;
599d0c95 2145 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
7cc30fcf 2146 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
3db65812 2147 unsigned long skipped = 0;
791b48b6 2148 unsigned long scan, total_scan, nr_pages;
166e3d32 2149 LIST_HEAD(folios_skipped);
1da177e4 2150
98879b3b 2151 total_scan = 0;
791b48b6 2152 scan = 0;
98879b3b 2153 while (scan < nr_to_scan && !list_empty(src)) {
89f6c88a 2154 struct list_head *move_to = src;
166e3d32 2155 struct folio *folio;
5ad333eb 2156
166e3d32
MWO
2157 folio = lru_to_folio(src);
2158 prefetchw_prev_lru_folio(folio, src, flags);
1da177e4 2159
166e3d32 2160 nr_pages = folio_nr_pages(folio);
98879b3b
YS
2161 total_scan += nr_pages;
2162
166e3d32
MWO
2163 if (folio_zonenum(folio) > sc->reclaim_idx) {
2164 nr_skipped[folio_zonenum(folio)] += nr_pages;
2165 move_to = &folios_skipped;
89f6c88a 2166 goto move;
b2e18757
MG
2167 }
2168
791b48b6 2169 /*
166e3d32
MWO
2170 * Do not count skipped folios because that makes the function
2171 * return with no isolated folios if the LRU mostly contains
2172 * ineligible folios. This causes the VM to not reclaim any
2173 * folios, triggering a premature OOM.
2174 * Account all pages in a folio.
791b48b6 2175 */
98879b3b 2176 scan += nr_pages;
89f6c88a 2177
166e3d32 2178 if (!folio_test_lru(folio))
89f6c88a 2179 goto move;
166e3d32 2180 if (!sc->may_unmap && folio_mapped(folio))
89f6c88a
HD
2181 goto move;
2182
c2135f7c 2183 /*
166e3d32
MWO
2184 * Be careful not to clear the lru flag until after we're
2185 * sure the folio is not being freed elsewhere -- the
2186 * folio release code relies on it.
c2135f7c 2187 */
166e3d32 2188 if (unlikely(!folio_try_get(folio)))
89f6c88a 2189 goto move;
5ad333eb 2190
166e3d32
MWO
2191 if (!folio_test_clear_lru(folio)) {
2192 /* Another thread is already isolating this folio */
2193 folio_put(folio);
89f6c88a 2194 goto move;
5ad333eb 2195 }
c2135f7c
AS
2196
2197 nr_taken += nr_pages;
166e3d32 2198 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
89f6c88a
HD
2199 move_to = dst;
2200move:
166e3d32 2201 list_move(&folio->lru, move_to);
1da177e4
LT
2202 }
2203
b2e18757 2204 /*
166e3d32 2205 * Splice any skipped folios to the start of the LRU list. Note that
b2e18757
MG
2206 * this disrupts the LRU order when reclaiming for lower zones but
2207 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
166e3d32 2208 * scanning would soon rescan the same folios to skip and waste lots
b2cb6826 2209 * of cpu cycles.
b2e18757 2210 */
166e3d32 2211 if (!list_empty(&folios_skipped)) {
7cc30fcf
MG
2212 int zid;
2213
166e3d32 2214 list_splice(&folios_skipped, src);
7cc30fcf
MG
2215 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2216 if (!nr_skipped[zid])
2217 continue;
2218
2219 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1265e3a6 2220 skipped += nr_skipped[zid];
7cc30fcf
MG
2221 }
2222 }
791b48b6 2223 *nr_scanned = total_scan;
1265e3a6 2224 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
89f6c88a
HD
2225 total_scan, skipped, nr_taken,
2226 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
b4536f0c 2227 update_lru_sizes(lruvec, lru, nr_zone_taken);
1da177e4
LT
2228 return nr_taken;
2229}
2230
62695a84 2231/**
d1d8a3b4
MWO
2232 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2233 * @folio: Folio to isolate from its LRU list.
62695a84 2234 *
d1d8a3b4
MWO
2235 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2236 * corresponding to whatever LRU list the folio was on.
62695a84 2237 *
d1d8a3b4
MWO
2238 * The folio will have its LRU flag cleared. If it was found on the
2239 * active list, it will have the Active flag set. If it was found on the
2240 * unevictable list, it will have the Unevictable flag set. These flags
894bc310 2241 * may need to be cleared by the caller before letting the page go.
62695a84 2242 *
d1d8a3b4 2243 * Context:
a5d09bed 2244 *
62695a84 2245 * (1) Must be called with an elevated refcount on the page. This is a
d1d8a3b4 2246 * fundamental difference from isolate_lru_pages() (which is called
62695a84 2247 * without a stable reference).
d1d8a3b4
MWO
2248 * (2) The lru_lock must not be held.
2249 * (3) Interrupts must be enabled.
2250 *
2251 * Return: 0 if the folio was removed from an LRU list.
2252 * -EBUSY if the folio was not on an LRU list.
62695a84 2253 */
d1d8a3b4 2254int folio_isolate_lru(struct folio *folio)
62695a84
NP
2255{
2256 int ret = -EBUSY;
2257
d1d8a3b4 2258 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
0c917313 2259
d1d8a3b4 2260 if (folio_test_clear_lru(folio)) {
fa9add64 2261 struct lruvec *lruvec;
62695a84 2262
d1d8a3b4 2263 folio_get(folio);
e809c3fe 2264 lruvec = folio_lruvec_lock_irq(folio);
d1d8a3b4 2265 lruvec_del_folio(lruvec, folio);
6168d0da 2266 unlock_page_lruvec_irq(lruvec);
d25b5bd8 2267 ret = 0;
62695a84 2268 }
d25b5bd8 2269
62695a84
NP
2270 return ret;
2271}
2272
35cd7815 2273/*
d37dd5dc 2274 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
178821b8 2275 * then get rescheduled. When there are massive number of tasks doing page
d37dd5dc
FW
2276 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2277 * the LRU list will go small and be scanned faster than necessary, leading to
2278 * unnecessary swapping, thrashing and OOM.
35cd7815 2279 */
599d0c95 2280static int too_many_isolated(struct pglist_data *pgdat, int file,
35cd7815
RR
2281 struct scan_control *sc)
2282{
2283 unsigned long inactive, isolated;
d818fca1 2284 bool too_many;
35cd7815
RR
2285
2286 if (current_is_kswapd())
2287 return 0;
2288
b5ead35e 2289 if (!writeback_throttling_sane(sc))
35cd7815
RR
2290 return 0;
2291
2292 if (file) {
599d0c95
MG
2293 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2294 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
35cd7815 2295 } else {
599d0c95
MG
2296 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2297 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
35cd7815
RR
2298 }
2299
3cf23841
FW
2300 /*
2301 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2302 * won't get blocked by normal direct-reclaimers, forming a circular
2303 * deadlock.
2304 */
d0164adc 2305 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
3cf23841
FW
2306 inactive >>= 3;
2307
d818fca1
MG
2308 too_many = isolated > inactive;
2309
2310 /* Wake up tasks throttled due to too_many_isolated. */
2311 if (!too_many)
2312 wake_throttle_isolated(pgdat);
2313
2314 return too_many;
35cd7815
RR
2315}
2316
a222f341 2317/*
ff00a170
MWO
2318 * move_pages_to_lru() moves folios from private @list to appropriate LRU list.
2319 * On return, @list is reused as a list of folios to be freed by the caller.
a222f341
KT
2320 *
2321 * Returns the number of pages moved to the given lruvec.
2322 */
9ef56b78
MS
2323static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2324 struct list_head *list)
66635629 2325{
a222f341 2326 int nr_pages, nr_moved = 0;
ff00a170 2327 LIST_HEAD(folios_to_free);
66635629 2328
a222f341 2329 while (!list_empty(list)) {
ff00a170
MWO
2330 struct folio *folio = lru_to_folio(list);
2331
2332 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2333 list_del(&folio->lru);
2334 if (unlikely(!folio_evictable(folio))) {
6168d0da 2335 spin_unlock_irq(&lruvec->lru_lock);
ff00a170 2336 folio_putback_lru(folio);
6168d0da 2337 spin_lock_irq(&lruvec->lru_lock);
66635629
MG
2338 continue;
2339 }
fa9add64 2340
3d06afab 2341 /*
ff00a170 2342 * The folio_set_lru needs to be kept here for list integrity.
3d06afab
AS
2343 * Otherwise:
2344 * #0 move_pages_to_lru #1 release_pages
ff00a170
MWO
2345 * if (!folio_put_testzero())
2346 * if (folio_put_testzero())
2347 * !lru //skip lru_lock
2348 * folio_set_lru()
2349 * list_add(&folio->lru,)
2350 * list_add(&folio->lru,)
3d06afab 2351 */
ff00a170 2352 folio_set_lru(folio);
a222f341 2353
ff00a170
MWO
2354 if (unlikely(folio_put_testzero(folio))) {
2355 __folio_clear_lru_flags(folio);
2bcf8879 2356
ff00a170 2357 if (unlikely(folio_test_large(folio))) {
6168d0da 2358 spin_unlock_irq(&lruvec->lru_lock);
5375336c 2359 destroy_large_folio(folio);
6168d0da 2360 spin_lock_irq(&lruvec->lru_lock);
2bcf8879 2361 } else
ff00a170 2362 list_add(&folio->lru, &folios_to_free);
3d06afab
AS
2363
2364 continue;
66635629 2365 }
3d06afab 2366
afca9157
AS
2367 /*
2368 * All pages were isolated from the same lruvec (and isolation
2369 * inhibits memcg migration).
2370 */
ff00a170
MWO
2371 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2372 lruvec_add_folio(lruvec, folio);
2373 nr_pages = folio_nr_pages(folio);
3d06afab 2374 nr_moved += nr_pages;
ff00a170 2375 if (folio_test_active(folio))
3d06afab 2376 workingset_age_nonresident(lruvec, nr_pages);
66635629 2377 }
66635629 2378
3f79768f
HD
2379 /*
2380 * To save our caller's stack, now use input list for pages to free.
2381 */
ff00a170 2382 list_splice(&folios_to_free, list);
a222f341
KT
2383
2384 return nr_moved;
66635629
MG
2385}
2386
399ba0b9 2387/*
5829f7db
ML
2388 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2389 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2390 * we should not throttle. Otherwise it is safe to do so.
399ba0b9
N
2391 */
2392static int current_may_throttle(void)
2393{
b9b1335e 2394 return !(current->flags & PF_LOCAL_THROTTLE);
399ba0b9
N
2395}
2396
1da177e4 2397/*
b2e18757 2398 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1742f19f 2399 * of reclaimed pages
1da177e4 2400 */
9ef56b78 2401static unsigned long
1a93be0e 2402shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
9e3b2f8c 2403 struct scan_control *sc, enum lru_list lru)
1da177e4
LT
2404{
2405 LIST_HEAD(page_list);
e247dbce 2406 unsigned long nr_scanned;
730ec8c0 2407 unsigned int nr_reclaimed = 0;
e247dbce 2408 unsigned long nr_taken;
060f005f 2409 struct reclaim_stat stat;
497a6c1b 2410 bool file = is_file_lru(lru);
f46b7912 2411 enum vm_event_item item;
599d0c95 2412 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
db73ee0d 2413 bool stalled = false;
78dc583d 2414
599d0c95 2415 while (unlikely(too_many_isolated(pgdat, file, sc))) {
db73ee0d
MH
2416 if (stalled)
2417 return 0;
2418
2419 /* wait a bit for the reclaimer. */
db73ee0d 2420 stalled = true;
c3f4a9a2 2421 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
35cd7815
RR
2422
2423 /* We are about to die and free our memory. Return now. */
2424 if (fatal_signal_pending(current))
2425 return SWAP_CLUSTER_MAX;
2426 }
2427
1da177e4 2428 lru_add_drain();
f80c0673 2429
6168d0da 2430 spin_lock_irq(&lruvec->lru_lock);
b35ea17b 2431
5dc35979 2432 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
a9e7c39f 2433 &nr_scanned, sc, lru);
95d918fc 2434
599d0c95 2435 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
f46b7912 2436 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
b5ead35e 2437 if (!cgroup_reclaim(sc))
f46b7912
KT
2438 __count_vm_events(item, nr_scanned);
2439 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
497a6c1b
JW
2440 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2441
6168d0da 2442 spin_unlock_irq(&lruvec->lru_lock);
b35ea17b 2443
d563c050 2444 if (nr_taken == 0)
66635629 2445 return 0;
5ad333eb 2446
013339df 2447 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
c661b078 2448
6168d0da 2449 spin_lock_irq(&lruvec->lru_lock);
497a6c1b
JW
2450 move_pages_to_lru(lruvec, &page_list);
2451
2452 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
f46b7912 2453 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
b5ead35e 2454 if (!cgroup_reclaim(sc))
f46b7912
KT
2455 __count_vm_events(item, nr_reclaimed);
2456 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
497a6c1b 2457 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
6168d0da 2458 spin_unlock_irq(&lruvec->lru_lock);
3f79768f 2459
75cc3c91 2460 lru_note_cost(lruvec, file, stat.nr_pageout);
747db954 2461 mem_cgroup_uncharge_list(&page_list);
2d4894b5 2462 free_unref_page_list(&page_list);
e11da5b4 2463
1c610d5f
AR
2464 /*
2465 * If dirty pages are scanned that are not queued for IO, it
2466 * implies that flushers are not doing their job. This can
2467 * happen when memory pressure pushes dirty pages to the end of
2468 * the LRU before the dirty limits are breached and the dirty
2469 * data has expired. It can also happen when the proportion of
2470 * dirty pages grows not through writes but through memory
2471 * pressure reclaiming all the clean cache. And in some cases,
2472 * the flushers simply cannot keep up with the allocation
2473 * rate. Nudge the flusher threads in case they are asleep.
2474 */
2475 if (stat.nr_unqueued_dirty == nr_taken)
2476 wakeup_flusher_threads(WB_REASON_VMSCAN);
2477
d108c772
AR
2478 sc->nr.dirty += stat.nr_dirty;
2479 sc->nr.congested += stat.nr_congested;
2480 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2481 sc->nr.writeback += stat.nr_writeback;
2482 sc->nr.immediate += stat.nr_immediate;
2483 sc->nr.taken += nr_taken;
2484 if (file)
2485 sc->nr.file_taken += nr_taken;
8e950282 2486
599d0c95 2487 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
d51d1e64 2488 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
05ff5137 2489 return nr_reclaimed;
1da177e4
LT
2490}
2491
15b44736 2492/*
07f67a8d 2493 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
15b44736 2494 *
07f67a8d 2495 * We move them the other way if the folio is referenced by one or more
15b44736
HD
2496 * processes.
2497 *
07f67a8d 2498 * If the folios are mostly unmapped, the processing is fast and it is
15b44736 2499 * appropriate to hold lru_lock across the whole operation. But if
07f67a8d
MWO
2500 * the folios are mapped, the processing is slow (folio_referenced()), so
2501 * we should drop lru_lock around each folio. It's impossible to balance
2502 * this, so instead we remove the folios from the LRU while processing them.
2503 * It is safe to rely on the active flag against the non-LRU folios in here
2504 * because nobody will play with that bit on a non-LRU folio.
15b44736 2505 *
07f67a8d
MWO
2506 * The downside is that we have to touch folio->_refcount against each folio.
2507 * But we had to alter folio->flags anyway.
15b44736 2508 */
f626012d 2509static void shrink_active_list(unsigned long nr_to_scan,
1a93be0e 2510 struct lruvec *lruvec,
f16015fb 2511 struct scan_control *sc,
9e3b2f8c 2512 enum lru_list lru)
1da177e4 2513{
44c241f1 2514 unsigned long nr_taken;
f626012d 2515 unsigned long nr_scanned;
6fe6b7e3 2516 unsigned long vm_flags;
07f67a8d 2517 LIST_HEAD(l_hold); /* The folios which were snipped off */
8cab4754 2518 LIST_HEAD(l_active);
b69408e8 2519 LIST_HEAD(l_inactive);
9d998b4f
MH
2520 unsigned nr_deactivate, nr_activate;
2521 unsigned nr_rotated = 0;
3cb99451 2522 int file = is_file_lru(lru);
599d0c95 2523 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1da177e4
LT
2524
2525 lru_add_drain();
f80c0673 2526
6168d0da 2527 spin_lock_irq(&lruvec->lru_lock);
925b7673 2528
5dc35979 2529 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
a9e7c39f 2530 &nr_scanned, sc, lru);
89b5fae5 2531
599d0c95 2532 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1cfb419b 2533
912c0572
SB
2534 if (!cgroup_reclaim(sc))
2535 __count_vm_events(PGREFILL, nr_scanned);
2fa2690c 2536 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
9d5e6a9f 2537
6168d0da 2538 spin_unlock_irq(&lruvec->lru_lock);
1da177e4 2539
1da177e4 2540 while (!list_empty(&l_hold)) {
b3ac0413 2541 struct folio *folio;
b3ac0413 2542
1da177e4 2543 cond_resched();
b3ac0413
MWO
2544 folio = lru_to_folio(&l_hold);
2545 list_del(&folio->lru);
7e9cd484 2546
07f67a8d
MWO
2547 if (unlikely(!folio_evictable(folio))) {
2548 folio_putback_lru(folio);
894bc310
LS
2549 continue;
2550 }
2551
cc715d99 2552 if (unlikely(buffer_heads_over_limit)) {
36a3b14b
MWO
2553 if (folio_test_private(folio) && folio_trylock(folio)) {
2554 if (folio_test_private(folio))
07f67a8d
MWO
2555 filemap_release_folio(folio, 0);
2556 folio_unlock(folio);
cc715d99
MG
2557 }
2558 }
2559
6d4675e6 2560 /* Referenced or rmap lock contention: rotate */
b3ac0413 2561 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
6d4675e6 2562 &vm_flags) != 0) {
8cab4754 2563 /*
07f67a8d 2564 * Identify referenced, file-backed active folios and
8cab4754
WF
2565 * give them one more trip around the active list. So
2566 * that executable code get better chances to stay in
07f67a8d 2567 * memory under moderate memory pressure. Anon folios
8cab4754 2568 * are not likely to be evicted by use-once streaming
07f67a8d 2569 * IO, plus JVM can create lots of anon VM_EXEC folios,
8cab4754
WF
2570 * so we ignore them here.
2571 */
07f67a8d
MWO
2572 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2573 nr_rotated += folio_nr_pages(folio);
2574 list_add(&folio->lru, &l_active);
8cab4754
WF
2575 continue;
2576 }
2577 }
7e9cd484 2578
07f67a8d
MWO
2579 folio_clear_active(folio); /* we are de-activating */
2580 folio_set_workingset(folio);
2581 list_add(&folio->lru, &l_inactive);
1da177e4
LT
2582 }
2583
b555749a 2584 /*
07f67a8d 2585 * Move folios back to the lru list.
b555749a 2586 */
6168d0da 2587 spin_lock_irq(&lruvec->lru_lock);
556adecb 2588
a222f341
KT
2589 nr_activate = move_pages_to_lru(lruvec, &l_active);
2590 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
07f67a8d 2591 /* Keep all free folios in l_active list */
f372d89e 2592 list_splice(&l_inactive, &l_active);
9851ac13
KT
2593
2594 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2595 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2596
599d0c95 2597 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
6168d0da 2598 spin_unlock_irq(&lruvec->lru_lock);
2bcf8879 2599
f372d89e
KT
2600 mem_cgroup_uncharge_list(&l_active);
2601 free_unref_page_list(&l_active);
9d998b4f
MH
2602 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2603 nr_deactivate, nr_rotated, sc->priority, file);
1da177e4
LT
2604}
2605
1fe47c0b
ML
2606static unsigned int reclaim_page_list(struct list_head *page_list,
2607 struct pglist_data *pgdat)
1a4e58cc 2608{
1a4e58cc 2609 struct reclaim_stat dummy_stat;
1fe47c0b
ML
2610 unsigned int nr_reclaimed;
2611 struct folio *folio;
1a4e58cc
MK
2612 struct scan_control sc = {
2613 .gfp_mask = GFP_KERNEL,
1a4e58cc
MK
2614 .may_writepage = 1,
2615 .may_unmap = 1,
2616 .may_swap = 1,
26aa2d19 2617 .no_demotion = 1,
1a4e58cc
MK
2618 };
2619
1fe47c0b
ML
2620 nr_reclaimed = shrink_page_list(page_list, pgdat, &sc, &dummy_stat, false);
2621 while (!list_empty(page_list)) {
2622 folio = lru_to_folio(page_list);
2623 list_del(&folio->lru);
2624 folio_putback_lru(folio);
2625 }
2626
2627 return nr_reclaimed;
2628}
2629
a83f0551 2630unsigned long reclaim_pages(struct list_head *folio_list)
1fe47c0b 2631{
ed657e55 2632 int nid;
1fe47c0b 2633 unsigned int nr_reclaimed = 0;
a83f0551 2634 LIST_HEAD(node_folio_list);
1fe47c0b
ML
2635 unsigned int noreclaim_flag;
2636
a83f0551 2637 if (list_empty(folio_list))
1ae65e27
WY
2638 return nr_reclaimed;
2639
2d2b8d2b
YZ
2640 noreclaim_flag = memalloc_noreclaim_save();
2641
a83f0551 2642 nid = folio_nid(lru_to_folio(folio_list));
1ae65e27 2643 do {
a83f0551 2644 struct folio *folio = lru_to_folio(folio_list);
1a4e58cc 2645
a83f0551
MWO
2646 if (nid == folio_nid(folio)) {
2647 folio_clear_active(folio);
2648 list_move(&folio->lru, &node_folio_list);
1a4e58cc
MK
2649 continue;
2650 }
2651
a83f0551
MWO
2652 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
2653 nid = folio_nid(lru_to_folio(folio_list));
2654 } while (!list_empty(folio_list));
1a4e58cc 2655
a83f0551 2656 nr_reclaimed += reclaim_page_list(&node_folio_list, NODE_DATA(nid));
1a4e58cc 2657
2d2b8d2b
YZ
2658 memalloc_noreclaim_restore(noreclaim_flag);
2659
1a4e58cc
MK
2660 return nr_reclaimed;
2661}
2662
b91ac374
JW
2663static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2664 struct lruvec *lruvec, struct scan_control *sc)
2665{
2666 if (is_active_lru(lru)) {
2667 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2668 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2669 else
2670 sc->skipped_deactivate = 1;
2671 return 0;
2672 }
2673
2674 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2675}
2676
59dc76b0
RR
2677/*
2678 * The inactive anon list should be small enough that the VM never has
2679 * to do too much work.
14797e23 2680 *
59dc76b0
RR
2681 * The inactive file list should be small enough to leave most memory
2682 * to the established workingset on the scan-resistant active list,
2683 * but large enough to avoid thrashing the aggregate readahead window.
56e49d21 2684 *
59dc76b0
RR
2685 * Both inactive lists should also be large enough that each inactive
2686 * page has a chance to be referenced again before it is reclaimed.
56e49d21 2687 *
2a2e4885
JW
2688 * If that fails and refaulting is observed, the inactive list grows.
2689 *
59dc76b0 2690 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
3a50d14d 2691 * on this LRU, maintained by the pageout code. An inactive_ratio
59dc76b0 2692 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
56e49d21 2693 *
59dc76b0
RR
2694 * total target max
2695 * memory ratio inactive
2696 * -------------------------------------
2697 * 10MB 1 5MB
2698 * 100MB 1 50MB
2699 * 1GB 3 250MB
2700 * 10GB 10 0.9GB
2701 * 100GB 31 3GB
2702 * 1TB 101 10GB
2703 * 10TB 320 32GB
56e49d21 2704 */
b91ac374 2705static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
56e49d21 2706{
b91ac374 2707 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2a2e4885
JW
2708 unsigned long inactive, active;
2709 unsigned long inactive_ratio;
59dc76b0 2710 unsigned long gb;
e3790144 2711
b91ac374
JW
2712 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2713 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
f8d1a311 2714
b91ac374 2715 gb = (inactive + active) >> (30 - PAGE_SHIFT);
4002570c 2716 if (gb)
b91ac374
JW
2717 inactive_ratio = int_sqrt(10 * gb);
2718 else
2719 inactive_ratio = 1;
fd538803 2720
59dc76b0 2721 return inactive * inactive_ratio < active;
b39415b2
RR
2722}
2723
9a265114
JW
2724enum scan_balance {
2725 SCAN_EQUAL,
2726 SCAN_FRACT,
2727 SCAN_ANON,
2728 SCAN_FILE,
2729};
2730
f1e1a7be
YZ
2731static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2732{
2733 unsigned long file;
2734 struct lruvec *target_lruvec;
2735
2736 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2737
2738 /*
2739 * Flush the memory cgroup stats, so that we read accurate per-memcg
2740 * lruvec stats for heuristics.
2741 */
2742 mem_cgroup_flush_stats();
2743
2744 /*
2745 * Determine the scan balance between anon and file LRUs.
2746 */
2747 spin_lock_irq(&target_lruvec->lru_lock);
2748 sc->anon_cost = target_lruvec->anon_cost;
2749 sc->file_cost = target_lruvec->file_cost;
2750 spin_unlock_irq(&target_lruvec->lru_lock);
2751
2752 /*
2753 * Target desirable inactive:active list ratios for the anon
2754 * and file LRU lists.
2755 */
2756 if (!sc->force_deactivate) {
2757 unsigned long refaults;
2758
2759 /*
2760 * When refaults are being observed, it means a new
2761 * workingset is being established. Deactivate to get
2762 * rid of any stale active pages quickly.
2763 */
2764 refaults = lruvec_page_state(target_lruvec,
2765 WORKINGSET_ACTIVATE_ANON);
2766 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2767 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2768 sc->may_deactivate |= DEACTIVATE_ANON;
2769 else
2770 sc->may_deactivate &= ~DEACTIVATE_ANON;
2771
2772 refaults = lruvec_page_state(target_lruvec,
2773 WORKINGSET_ACTIVATE_FILE);
2774 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2775 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2776 sc->may_deactivate |= DEACTIVATE_FILE;
2777 else
2778 sc->may_deactivate &= ~DEACTIVATE_FILE;
2779 } else
2780 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2781
2782 /*
2783 * If we have plenty of inactive file pages that aren't
2784 * thrashing, try to reclaim those first before touching
2785 * anonymous pages.
2786 */
2787 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2788 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2789 sc->cache_trim_mode = 1;
2790 else
2791 sc->cache_trim_mode = 0;
2792
2793 /*
2794 * Prevent the reclaimer from falling into the cache trap: as
2795 * cache pages start out inactive, every cache fault will tip
2796 * the scan balance towards the file LRU. And as the file LRU
2797 * shrinks, so does the window for rotation from references.
2798 * This means we have a runaway feedback loop where a tiny
2799 * thrashing file LRU becomes infinitely more attractive than
2800 * anon pages. Try to detect this based on file LRU size.
2801 */
2802 if (!cgroup_reclaim(sc)) {
2803 unsigned long total_high_wmark = 0;
2804 unsigned long free, anon;
2805 int z;
2806
2807 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2808 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2809 node_page_state(pgdat, NR_INACTIVE_FILE);
2810
2811 for (z = 0; z < MAX_NR_ZONES; z++) {
2812 struct zone *zone = &pgdat->node_zones[z];
2813
2814 if (!managed_zone(zone))
2815 continue;
2816
2817 total_high_wmark += high_wmark_pages(zone);
2818 }
2819
2820 /*
2821 * Consider anon: if that's low too, this isn't a
2822 * runaway file reclaim problem, but rather just
2823 * extreme pressure. Reclaim as per usual then.
2824 */
2825 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2826
2827 sc->file_is_tiny =
2828 file + free <= total_high_wmark &&
2829 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2830 anon >> sc->priority;
2831 }
2832}
2833
4f98a2fe
RR
2834/*
2835 * Determine how aggressively the anon and file LRU lists should be
02e458d8 2836 * scanned.
4f98a2fe 2837 *
be7bd59d
WL
2838 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2839 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
4f98a2fe 2840 */
afaf07a6
JW
2841static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2842 unsigned long *nr)
4f98a2fe 2843{
a2a36488 2844 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
afaf07a6 2845 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
d483a5dd 2846 unsigned long anon_cost, file_cost, total_cost;
33377678 2847 int swappiness = mem_cgroup_swappiness(memcg);
ed017373 2848 u64 fraction[ANON_AND_FILE];
9a265114 2849 u64 denominator = 0; /* gcc */
9a265114 2850 enum scan_balance scan_balance;
4f98a2fe 2851 unsigned long ap, fp;
4111304d 2852 enum lru_list lru;
76a33fc3
SL
2853
2854 /* If we have no swap space, do not bother scanning anon pages. */
a2a36488 2855 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
9a265114 2856 scan_balance = SCAN_FILE;
76a33fc3
SL
2857 goto out;
2858 }
4f98a2fe 2859
10316b31
JW
2860 /*
2861 * Global reclaim will swap to prevent OOM even with no
2862 * swappiness, but memcg users want to use this knob to
2863 * disable swapping for individual groups completely when
2864 * using the memory controller's swap limit feature would be
2865 * too expensive.
2866 */
b5ead35e 2867 if (cgroup_reclaim(sc) && !swappiness) {
9a265114 2868 scan_balance = SCAN_FILE;
10316b31
JW
2869 goto out;
2870 }
2871
2872 /*
2873 * Do not apply any pressure balancing cleverness when the
2874 * system is close to OOM, scan both anon and file equally
2875 * (unless the swappiness setting disagrees with swapping).
2876 */
02695175 2877 if (!sc->priority && swappiness) {
9a265114 2878 scan_balance = SCAN_EQUAL;
10316b31
JW
2879 goto out;
2880 }
2881
62376251 2882 /*
53138cea 2883 * If the system is almost out of file pages, force-scan anon.
62376251 2884 */
b91ac374 2885 if (sc->file_is_tiny) {
53138cea
JW
2886 scan_balance = SCAN_ANON;
2887 goto out;
62376251
JW
2888 }
2889
7c5bd705 2890 /*
b91ac374
JW
2891 * If there is enough inactive page cache, we do not reclaim
2892 * anything from the anonymous working right now.
7c5bd705 2893 */
b91ac374 2894 if (sc->cache_trim_mode) {
9a265114 2895 scan_balance = SCAN_FILE;
7c5bd705
JW
2896 goto out;
2897 }
2898
9a265114 2899 scan_balance = SCAN_FRACT;
58c37f6e 2900 /*
314b57fb
JW
2901 * Calculate the pressure balance between anon and file pages.
2902 *
2903 * The amount of pressure we put on each LRU is inversely
2904 * proportional to the cost of reclaiming each list, as
2905 * determined by the share of pages that are refaulting, times
2906 * the relative IO cost of bringing back a swapped out
2907 * anonymous page vs reloading a filesystem page (swappiness).
2908 *
d483a5dd
JW
2909 * Although we limit that influence to ensure no list gets
2910 * left behind completely: at least a third of the pressure is
2911 * applied, before swappiness.
2912 *
314b57fb 2913 * With swappiness at 100, anon and file have equal IO cost.
58c37f6e 2914 */
d483a5dd
JW
2915 total_cost = sc->anon_cost + sc->file_cost;
2916 anon_cost = total_cost + sc->anon_cost;
2917 file_cost = total_cost + sc->file_cost;
2918 total_cost = anon_cost + file_cost;
58c37f6e 2919
d483a5dd
JW
2920 ap = swappiness * (total_cost + 1);
2921 ap /= anon_cost + 1;
4f98a2fe 2922
d483a5dd
JW
2923 fp = (200 - swappiness) * (total_cost + 1);
2924 fp /= file_cost + 1;
4f98a2fe 2925
76a33fc3
SL
2926 fraction[0] = ap;
2927 fraction[1] = fp;
a4fe1631 2928 denominator = ap + fp;
76a33fc3 2929out:
688035f7
JW
2930 for_each_evictable_lru(lru) {
2931 int file = is_file_lru(lru);
9783aa99 2932 unsigned long lruvec_size;
f56ce412 2933 unsigned long low, min;
688035f7 2934 unsigned long scan;
9783aa99
CD
2935
2936 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
f56ce412
JW
2937 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2938 &min, &low);
9783aa99 2939
f56ce412 2940 if (min || low) {
9783aa99
CD
2941 /*
2942 * Scale a cgroup's reclaim pressure by proportioning
2943 * its current usage to its memory.low or memory.min
2944 * setting.
2945 *
2946 * This is important, as otherwise scanning aggression
2947 * becomes extremely binary -- from nothing as we
2948 * approach the memory protection threshold, to totally
2949 * nominal as we exceed it. This results in requiring
2950 * setting extremely liberal protection thresholds. It
2951 * also means we simply get no protection at all if we
2952 * set it too low, which is not ideal.
1bc63fb1
CD
2953 *
2954 * If there is any protection in place, we reduce scan
2955 * pressure by how much of the total memory used is
2956 * within protection thresholds.
9783aa99 2957 *
9de7ca46
CD
2958 * There is one special case: in the first reclaim pass,
2959 * we skip over all groups that are within their low
2960 * protection. If that fails to reclaim enough pages to
2961 * satisfy the reclaim goal, we come back and override
2962 * the best-effort low protection. However, we still
2963 * ideally want to honor how well-behaved groups are in
2964 * that case instead of simply punishing them all
2965 * equally. As such, we reclaim them based on how much
1bc63fb1
CD
2966 * memory they are using, reducing the scan pressure
2967 * again by how much of the total memory used is under
2968 * hard protection.
9783aa99 2969 */
1bc63fb1 2970 unsigned long cgroup_size = mem_cgroup_size(memcg);
f56ce412
JW
2971 unsigned long protection;
2972
2973 /* memory.low scaling, make sure we retry before OOM */
2974 if (!sc->memcg_low_reclaim && low > min) {
2975 protection = low;
2976 sc->memcg_low_skipped = 1;
2977 } else {
2978 protection = min;
2979 }
1bc63fb1
CD
2980
2981 /* Avoid TOCTOU with earlier protection check */
2982 cgroup_size = max(cgroup_size, protection);
2983
2984 scan = lruvec_size - lruvec_size * protection /
32d4f4b7 2985 (cgroup_size + 1);
9783aa99
CD
2986
2987 /*
1bc63fb1 2988 * Minimally target SWAP_CLUSTER_MAX pages to keep
55b65a57 2989 * reclaim moving forwards, avoiding decrementing
9de7ca46 2990 * sc->priority further than desirable.
9783aa99 2991 */
1bc63fb1 2992 scan = max(scan, SWAP_CLUSTER_MAX);
9783aa99
CD
2993 } else {
2994 scan = lruvec_size;
2995 }
2996
2997 scan >>= sc->priority;
6b4f7799 2998
688035f7
JW
2999 /*
3000 * If the cgroup's already been deleted, make sure to
3001 * scrape out the remaining cache.
3002 */
3003 if (!scan && !mem_cgroup_online(memcg))
9783aa99 3004 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
6b4f7799 3005
688035f7
JW
3006 switch (scan_balance) {
3007 case SCAN_EQUAL:
3008 /* Scan lists relative to size */
3009 break;
3010 case SCAN_FRACT:
9a265114 3011 /*
688035f7
JW
3012 * Scan types proportional to swappiness and
3013 * their relative recent reclaim efficiency.
76073c64
GS
3014 * Make sure we don't miss the last page on
3015 * the offlined memory cgroups because of a
3016 * round-off error.
9a265114 3017 */
76073c64
GS
3018 scan = mem_cgroup_online(memcg) ?
3019 div64_u64(scan * fraction[file], denominator) :
3020 DIV64_U64_ROUND_UP(scan * fraction[file],
68600f62 3021 denominator);
688035f7
JW
3022 break;
3023 case SCAN_FILE:
3024 case SCAN_ANON:
3025 /* Scan one type exclusively */
e072bff6 3026 if ((scan_balance == SCAN_FILE) != file)
688035f7 3027 scan = 0;
688035f7
JW
3028 break;
3029 default:
3030 /* Look ma, no brain */
3031 BUG();
9a265114 3032 }
688035f7 3033
688035f7 3034 nr[lru] = scan;
76a33fc3 3035 }
6e08a369 3036}
4f98a2fe 3037
2f368a9f
DH
3038/*
3039 * Anonymous LRU management is a waste if there is
3040 * ultimately no way to reclaim the memory.
3041 */
3042static bool can_age_anon_pages(struct pglist_data *pgdat,
3043 struct scan_control *sc)
3044{
3045 /* Aging the anon LRU is valuable if swap is present: */
3046 if (total_swap_pages > 0)
3047 return true;
3048
3049 /* Also valuable if anon pages can be demoted: */
3050 return can_demote(pgdat->node_id, sc);
3051}
3052
afaf07a6 3053static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
9b4f98cd
JW
3054{
3055 unsigned long nr[NR_LRU_LISTS];
e82e0561 3056 unsigned long targets[NR_LRU_LISTS];
9b4f98cd
JW
3057 unsigned long nr_to_scan;
3058 enum lru_list lru;
3059 unsigned long nr_reclaimed = 0;
3060 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
3061 struct blk_plug plug;
1a501907 3062 bool scan_adjusted;
9b4f98cd 3063
afaf07a6 3064 get_scan_count(lruvec, sc, nr);
9b4f98cd 3065
e82e0561
MG
3066 /* Record the original scan target for proportional adjustments later */
3067 memcpy(targets, nr, sizeof(nr));
3068
1a501907
MG
3069 /*
3070 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
3071 * event that can occur when there is little memory pressure e.g.
3072 * multiple streaming readers/writers. Hence, we do not abort scanning
3073 * when the requested number of pages are reclaimed when scanning at
3074 * DEF_PRIORITY on the assumption that the fact we are direct
3075 * reclaiming implies that kswapd is not keeping up and it is best to
3076 * do a batch of work at once. For memcg reclaim one check is made to
3077 * abort proportional reclaim if either the file or anon lru has already
3078 * dropped to zero at the first pass.
3079 */
b5ead35e 3080 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
1a501907
MG
3081 sc->priority == DEF_PRIORITY);
3082
9b4f98cd
JW
3083 blk_start_plug(&plug);
3084 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
3085 nr[LRU_INACTIVE_FILE]) {
e82e0561
MG
3086 unsigned long nr_anon, nr_file, percentage;
3087 unsigned long nr_scanned;
3088
9b4f98cd
JW
3089 for_each_evictable_lru(lru) {
3090 if (nr[lru]) {
3091 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
3092 nr[lru] -= nr_to_scan;
3093
3094 nr_reclaimed += shrink_list(lru, nr_to_scan,
3b991208 3095 lruvec, sc);
9b4f98cd
JW
3096 }
3097 }
e82e0561 3098
bd041733
MH
3099 cond_resched();
3100
e82e0561
MG
3101 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3102 continue;
3103
e82e0561
MG
3104 /*
3105 * For kswapd and memcg, reclaim at least the number of pages
1a501907 3106 * requested. Ensure that the anon and file LRUs are scanned
e82e0561
MG
3107 * proportionally what was requested by get_scan_count(). We
3108 * stop reclaiming one LRU and reduce the amount scanning
3109 * proportional to the original scan target.
3110 */
3111 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3112 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3113
1a501907
MG
3114 /*
3115 * It's just vindictive to attack the larger once the smaller
3116 * has gone to zero. And given the way we stop scanning the
3117 * smaller below, this makes sure that we only make one nudge
3118 * towards proportionality once we've got nr_to_reclaim.
3119 */
3120 if (!nr_file || !nr_anon)
3121 break;
3122
e82e0561
MG
3123 if (nr_file > nr_anon) {
3124 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3125 targets[LRU_ACTIVE_ANON] + 1;
3126 lru = LRU_BASE;
3127 percentage = nr_anon * 100 / scan_target;
3128 } else {
3129 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
3130 targets[LRU_ACTIVE_FILE] + 1;
3131 lru = LRU_FILE;
3132 percentage = nr_file * 100 / scan_target;
3133 }
3134
3135 /* Stop scanning the smaller of the LRU */
3136 nr[lru] = 0;
3137 nr[lru + LRU_ACTIVE] = 0;
3138
3139 /*
3140 * Recalculate the other LRU scan count based on its original
3141 * scan target and the percentage scanning already complete
3142 */
3143 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
3144 nr_scanned = targets[lru] - nr[lru];
3145 nr[lru] = targets[lru] * (100 - percentage) / 100;
3146 nr[lru] -= min(nr[lru], nr_scanned);
3147
3148 lru += LRU_ACTIVE;
3149 nr_scanned = targets[lru] - nr[lru];
3150 nr[lru] = targets[lru] * (100 - percentage) / 100;
3151 nr[lru] -= min(nr[lru], nr_scanned);
3152
3153 scan_adjusted = true;
9b4f98cd
JW
3154 }
3155 blk_finish_plug(&plug);
3156 sc->nr_reclaimed += nr_reclaimed;
3157
3158 /*
3159 * Even if we did not try to evict anon pages at all, we want to
3160 * rebalance the anon lru active/inactive ratio.
3161 */
2f368a9f
DH
3162 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
3163 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
9b4f98cd
JW
3164 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3165 sc, LRU_ACTIVE_ANON);
9b4f98cd
JW
3166}
3167
23b9da55 3168/* Use reclaim/compaction for costly allocs or under memory pressure */
9e3b2f8c 3169static bool in_reclaim_compaction(struct scan_control *sc)
23b9da55 3170{
d84da3f9 3171 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
23b9da55 3172 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
9e3b2f8c 3173 sc->priority < DEF_PRIORITY - 2))
23b9da55
MG
3174 return true;
3175
3176 return false;
3177}
3178
3e7d3449 3179/*
23b9da55
MG
3180 * Reclaim/compaction is used for high-order allocation requests. It reclaims
3181 * order-0 pages before compacting the zone. should_continue_reclaim() returns
3182 * true if more pages should be reclaimed such that when the page allocator
df3a45f9 3183 * calls try_to_compact_pages() that it will have enough free pages to succeed.
23b9da55 3184 * It will give up earlier than that if there is difficulty reclaiming pages.
3e7d3449 3185 */
a9dd0a83 3186static inline bool should_continue_reclaim(struct pglist_data *pgdat,
3e7d3449 3187 unsigned long nr_reclaimed,
3e7d3449
MG
3188 struct scan_control *sc)
3189{
3190 unsigned long pages_for_compaction;
3191 unsigned long inactive_lru_pages;
a9dd0a83 3192 int z;
3e7d3449
MG
3193
3194 /* If not in reclaim/compaction mode, stop */
9e3b2f8c 3195 if (!in_reclaim_compaction(sc))
3e7d3449
MG
3196 return false;
3197
5ee04716
VB
3198 /*
3199 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
3200 * number of pages that were scanned. This will return to the caller
3201 * with the risk reclaim/compaction and the resulting allocation attempt
3202 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
3203 * allocations through requiring that the full LRU list has been scanned
3204 * first, by assuming that zero delta of sc->nr_scanned means full LRU
3205 * scan, but that approximation was wrong, and there were corner cases
3206 * where always a non-zero amount of pages were scanned.
3207 */
3208 if (!nr_reclaimed)
3209 return false;
3e7d3449 3210
3e7d3449 3211 /* If compaction would go ahead or the allocation would succeed, stop */
a9dd0a83
MG
3212 for (z = 0; z <= sc->reclaim_idx; z++) {
3213 struct zone *zone = &pgdat->node_zones[z];
6aa303de 3214 if (!managed_zone(zone))
a9dd0a83
MG
3215 continue;
3216
3217 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
cf378319 3218 case COMPACT_SUCCESS:
a9dd0a83
MG
3219 case COMPACT_CONTINUE:
3220 return false;
3221 default:
3222 /* check next zone */
3223 ;
3224 }
3e7d3449 3225 }
1c6c1597
HD
3226
3227 /*
3228 * If we have not reclaimed enough pages for compaction and the
3229 * inactive lists are large enough, continue reclaiming
3230 */
3231 pages_for_compaction = compact_gap(sc->order);
3232 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
a2a36488 3233 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
1c6c1597
HD
3234 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
3235
5ee04716 3236 return inactive_lru_pages > pages_for_compaction;
3e7d3449
MG
3237}
3238
0f6a5cff 3239static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
1da177e4 3240{
0f6a5cff 3241 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
d2af3397 3242 struct mem_cgroup *memcg;
1da177e4 3243
0f6a5cff 3244 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
d2af3397 3245 do {
afaf07a6 3246 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
d2af3397
JW
3247 unsigned long reclaimed;
3248 unsigned long scanned;
5660048c 3249
e3336cab
XP
3250 /*
3251 * This loop can become CPU-bound when target memcgs
3252 * aren't eligible for reclaim - either because they
3253 * don't have any reclaimable pages, or because their
3254 * memory is explicitly protected. Avoid soft lockups.
3255 */
3256 cond_resched();
3257
45c7f7e1
CD
3258 mem_cgroup_calculate_protection(target_memcg, memcg);
3259
3260 if (mem_cgroup_below_min(memcg)) {
d2af3397
JW
3261 /*
3262 * Hard protection.
3263 * If there is no reclaimable memory, OOM.
3264 */
3265 continue;
45c7f7e1 3266 } else if (mem_cgroup_below_low(memcg)) {
d2af3397
JW
3267 /*
3268 * Soft protection.
3269 * Respect the protection only as long as
3270 * there is an unprotected supply
3271 * of reclaimable memory from other cgroups.
3272 */
3273 if (!sc->memcg_low_reclaim) {
3274 sc->memcg_low_skipped = 1;
bf8d5d52 3275 continue;
241994ed 3276 }
d2af3397 3277 memcg_memory_event(memcg, MEMCG_LOW);
d2af3397 3278 }
241994ed 3279
d2af3397
JW
3280 reclaimed = sc->nr_reclaimed;
3281 scanned = sc->nr_scanned;
afaf07a6
JW
3282
3283 shrink_lruvec(lruvec, sc);
70ddf637 3284
d2af3397
JW
3285 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
3286 sc->priority);
6b4f7799 3287
d2af3397 3288 /* Record the group's reclaim efficiency */
73b73bac
YA
3289 if (!sc->proactive)
3290 vmpressure(sc->gfp_mask, memcg, false,
3291 sc->nr_scanned - scanned,
3292 sc->nr_reclaimed - reclaimed);
70ddf637 3293
0f6a5cff
JW
3294 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
3295}
3296
6c9e0907 3297static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
0f6a5cff
JW
3298{
3299 struct reclaim_state *reclaim_state = current->reclaim_state;
0f6a5cff 3300 unsigned long nr_reclaimed, nr_scanned;
1b05117d 3301 struct lruvec *target_lruvec;
0f6a5cff
JW
3302 bool reclaimable = false;
3303
1b05117d
JW
3304 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
3305
0f6a5cff
JW
3306again:
3307 memset(&sc->nr, 0, sizeof(sc->nr));
3308
3309 nr_reclaimed = sc->nr_reclaimed;
3310 nr_scanned = sc->nr_scanned;
3311
f1e1a7be 3312 prepare_scan_count(pgdat, sc);
53138cea 3313
0f6a5cff 3314 shrink_node_memcgs(pgdat, sc);
2344d7e4 3315
d2af3397
JW
3316 if (reclaim_state) {
3317 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
3318 reclaim_state->reclaimed_slab = 0;
3319 }
d108c772 3320
d2af3397 3321 /* Record the subtree's reclaim efficiency */
73b73bac
YA
3322 if (!sc->proactive)
3323 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
3324 sc->nr_scanned - nr_scanned,
3325 sc->nr_reclaimed - nr_reclaimed);
d108c772 3326
d2af3397
JW
3327 if (sc->nr_reclaimed - nr_reclaimed)
3328 reclaimable = true;
d108c772 3329
d2af3397
JW
3330 if (current_is_kswapd()) {
3331 /*
3332 * If reclaim is isolating dirty pages under writeback,
3333 * it implies that the long-lived page allocation rate
3334 * is exceeding the page laundering rate. Either the
3335 * global limits are not being effective at throttling
3336 * processes due to the page distribution throughout
3337 * zones or there is heavy usage of a slow backing
3338 * device. The only option is to throttle from reclaim
3339 * context which is not ideal as there is no guarantee
3340 * the dirtying process is throttled in the same way
3341 * balance_dirty_pages() manages.
3342 *
3343 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
3344 * count the number of pages under pages flagged for
3345 * immediate reclaim and stall if any are encountered
3346 * in the nr_immediate check below.
3347 */
3348 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
3349 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
d108c772 3350
d2af3397
JW
3351 /* Allow kswapd to start writing pages during reclaim.*/
3352 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
3353 set_bit(PGDAT_DIRTY, &pgdat->flags);
e3c1ac58 3354
d108c772 3355 /*
1eba09c1 3356 * If kswapd scans pages marked for immediate
d2af3397
JW
3357 * reclaim and under writeback (nr_immediate), it
3358 * implies that pages are cycling through the LRU
8cd7c588
MG
3359 * faster than they are written so forcibly stall
3360 * until some pages complete writeback.
d108c772 3361 */
d2af3397 3362 if (sc->nr.immediate)
c3f4a9a2 3363 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
d2af3397
JW
3364 }
3365
3366 /*
8cd7c588
MG
3367 * Tag a node/memcg as congested if all the dirty pages were marked
3368 * for writeback and immediate reclaim (counted in nr.congested).
1b05117d 3369 *
d2af3397 3370 * Legacy memcg will stall in page writeback so avoid forcibly
8cd7c588 3371 * stalling in reclaim_throttle().
d2af3397 3372 */
1b05117d
JW
3373 if ((current_is_kswapd() ||
3374 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
d2af3397 3375 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
1b05117d 3376 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
d2af3397
JW
3377
3378 /*
8cd7c588
MG
3379 * Stall direct reclaim for IO completions if the lruvec is
3380 * node is congested. Allow kswapd to continue until it
d2af3397
JW
3381 * starts encountering unqueued dirty pages or cycling through
3382 * the LRU too quickly.
3383 */
1b05117d
JW
3384 if (!current_is_kswapd() && current_may_throttle() &&
3385 !sc->hibernation_mode &&
3386 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
1b4e3f26 3387 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
d108c772 3388
d2af3397
JW
3389 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
3390 sc))
3391 goto again;
2344d7e4 3392
c73322d0
JW
3393 /*
3394 * Kswapd gives up on balancing particular nodes after too
3395 * many failures to reclaim anything from them and goes to
3396 * sleep. On reclaim progress, reset the failure counter. A
3397 * successful direct reclaim run will revive a dormant kswapd.
3398 */
3399 if (reclaimable)
3400 pgdat->kswapd_failures = 0;
f16015fb
JW
3401}
3402
53853e2d 3403/*
fdd4c614
VB
3404 * Returns true if compaction should go ahead for a costly-order request, or
3405 * the allocation would already succeed without compaction. Return false if we
3406 * should reclaim first.
53853e2d 3407 */
4f588331 3408static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
fe4b1b24 3409{
31483b6a 3410 unsigned long watermark;
fdd4c614 3411 enum compact_result suitable;
fe4b1b24 3412
fdd4c614
VB
3413 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
3414 if (suitable == COMPACT_SUCCESS)
3415 /* Allocation should succeed already. Don't reclaim. */
3416 return true;
3417 if (suitable == COMPACT_SKIPPED)
3418 /* Compaction cannot yet proceed. Do reclaim. */
3419 return false;
fe4b1b24 3420
53853e2d 3421 /*
fdd4c614
VB
3422 * Compaction is already possible, but it takes time to run and there
3423 * are potentially other callers using the pages just freed. So proceed
3424 * with reclaim to make a buffer of free pages available to give
3425 * compaction a reasonable chance of completing and allocating the page.
3426 * Note that we won't actually reclaim the whole buffer in one attempt
3427 * as the target watermark in should_continue_reclaim() is lower. But if
3428 * we are already above the high+gap watermark, don't reclaim at all.
53853e2d 3429 */
fdd4c614 3430 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
fe4b1b24 3431
fdd4c614 3432 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
fe4b1b24
MG
3433}
3434
69392a40
MG
3435static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
3436{
66ce520b
MG
3437 /*
3438 * If reclaim is making progress greater than 12% efficiency then
3439 * wake all the NOPROGRESS throttled tasks.
3440 */
3441 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
69392a40
MG
3442 wait_queue_head_t *wqh;
3443
3444 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
3445 if (waitqueue_active(wqh))
3446 wake_up(wqh);
3447
3448 return;
3449 }
3450
3451 /*
1b4e3f26
MG
3452 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
3453 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
3454 * under writeback and marked for immediate reclaim at the tail of the
3455 * LRU.
69392a40 3456 */
1b4e3f26 3457 if (current_is_kswapd() || cgroup_reclaim(sc))
69392a40
MG
3458 return;
3459
3460 /* Throttle if making no progress at high prioities. */
1b4e3f26 3461 if (sc->priority == 1 && !sc->nr_reclaimed)
c3f4a9a2 3462 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
69392a40
MG
3463}
3464
1da177e4
LT
3465/*
3466 * This is the direct reclaim path, for page-allocating processes. We only
3467 * try to reclaim pages from zones which will satisfy the caller's allocation
3468 * request.
3469 *
1da177e4
LT
3470 * If a zone is deemed to be full of pinned pages then just give it a light
3471 * scan then give up on it.
3472 */
0a0337e0 3473static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
1da177e4 3474{
dd1a239f 3475 struct zoneref *z;
54a6eb5c 3476 struct zone *zone;
0608f43d
AM
3477 unsigned long nr_soft_reclaimed;
3478 unsigned long nr_soft_scanned;
619d0d76 3479 gfp_t orig_mask;
79dafcdc 3480 pg_data_t *last_pgdat = NULL;
1b4e3f26 3481 pg_data_t *first_pgdat = NULL;
1cfb419b 3482
cc715d99
MG
3483 /*
3484 * If the number of buffer_heads in the machine exceeds the maximum
3485 * allowed level, force direct reclaim to scan the highmem zone as
3486 * highmem pages could be pinning lowmem pages storing buffer_heads
3487 */
619d0d76 3488 orig_mask = sc->gfp_mask;
b2e18757 3489 if (buffer_heads_over_limit) {
cc715d99 3490 sc->gfp_mask |= __GFP_HIGHMEM;
4f588331 3491 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
b2e18757 3492 }
cc715d99 3493
d4debc66 3494 for_each_zone_zonelist_nodemask(zone, z, zonelist,
b2e18757 3495 sc->reclaim_idx, sc->nodemask) {
1cfb419b
KH
3496 /*
3497 * Take care memory controller reclaiming has small influence
3498 * to global LRU.
3499 */
b5ead35e 3500 if (!cgroup_reclaim(sc)) {
344736f2
VD
3501 if (!cpuset_zone_allowed(zone,
3502 GFP_KERNEL | __GFP_HARDWALL))
1cfb419b 3503 continue;
65ec02cb 3504
0b06496a
JW
3505 /*
3506 * If we already have plenty of memory free for
3507 * compaction in this zone, don't free any more.
3508 * Even though compaction is invoked for any
3509 * non-zero order, only frequent costly order
3510 * reclamation is disruptive enough to become a
3511 * noticeable problem, like transparent huge
3512 * page allocations.
3513 */
3514 if (IS_ENABLED(CONFIG_COMPACTION) &&
3515 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
4f588331 3516 compaction_ready(zone, sc)) {
0b06496a
JW
3517 sc->compaction_ready = true;
3518 continue;
e0887c19 3519 }
0b06496a 3520
79dafcdc
MG
3521 /*
3522 * Shrink each node in the zonelist once. If the
3523 * zonelist is ordered by zone (not the default) then a
3524 * node may be shrunk multiple times but in that case
3525 * the user prefers lower zones being preserved.
3526 */
3527 if (zone->zone_pgdat == last_pgdat)
3528 continue;
3529
0608f43d
AM
3530 /*
3531 * This steals pages from memory cgroups over softlimit
3532 * and returns the number of reclaimed pages and
3533 * scanned pages. This works for global memory pressure
3534 * and balancing, not for a memcg's limit.
3535 */
3536 nr_soft_scanned = 0;
ef8f2327 3537 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
0608f43d
AM
3538 sc->order, sc->gfp_mask,
3539 &nr_soft_scanned);
3540 sc->nr_reclaimed += nr_soft_reclaimed;
3541 sc->nr_scanned += nr_soft_scanned;
ac34a1a3 3542 /* need some check for avoid more shrink_zone() */
1cfb419b 3543 }
408d8544 3544
1b4e3f26
MG
3545 if (!first_pgdat)
3546 first_pgdat = zone->zone_pgdat;
3547
79dafcdc
MG
3548 /* See comment about same check for global reclaim above */
3549 if (zone->zone_pgdat == last_pgdat)
3550 continue;
3551 last_pgdat = zone->zone_pgdat;
970a39a3 3552 shrink_node(zone->zone_pgdat, sc);
1da177e4 3553 }
e0c23279 3554
80082938
MG
3555 if (first_pgdat)
3556 consider_reclaim_throttle(first_pgdat, sc);
1b4e3f26 3557
619d0d76
WY
3558 /*
3559 * Restore to original mask to avoid the impact on the caller if we
3560 * promoted it to __GFP_HIGHMEM.
3561 */
3562 sc->gfp_mask = orig_mask;
1da177e4 3563}
4f98a2fe 3564
b910718a 3565static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
2a2e4885 3566{
b910718a
JW
3567 struct lruvec *target_lruvec;
3568 unsigned long refaults;
2a2e4885 3569
b910718a 3570 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
170b04b7 3571 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
e9c2dbc8 3572 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
170b04b7 3573 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
e9c2dbc8 3574 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
2a2e4885
JW
3575}
3576
1da177e4
LT
3577/*
3578 * This is the main entry point to direct page reclaim.
3579 *
3580 * If a full scan of the inactive list fails to free enough memory then we
3581 * are "out of memory" and something needs to be killed.
3582 *
3583 * If the caller is !__GFP_FS then the probability of a failure is reasonably
3584 * high - the zone may be full of dirty or under-writeback pages, which this
5b0830cb
JA
3585 * caller can't do much about. We kick the writeback threads and take explicit
3586 * naps in the hope that some of these pages can be written. But if the
3587 * allocating task holds filesystem locks which prevent writeout this might not
3588 * work, and the allocation attempt will fail.
a41f24ea
NA
3589 *
3590 * returns: 0, if no pages reclaimed
3591 * else, the number of pages reclaimed
1da177e4 3592 */
dac1d27b 3593static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3115cd91 3594 struct scan_control *sc)
1da177e4 3595{
241994ed 3596 int initial_priority = sc->priority;
2a2e4885
JW
3597 pg_data_t *last_pgdat;
3598 struct zoneref *z;
3599 struct zone *zone;
241994ed 3600retry:
873b4771
KK
3601 delayacct_freepages_start();
3602
b5ead35e 3603 if (!cgroup_reclaim(sc))
7cc30fcf 3604 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
1da177e4 3605
9e3b2f8c 3606 do {
73b73bac
YA
3607 if (!sc->proactive)
3608 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3609 sc->priority);
66e1707b 3610 sc->nr_scanned = 0;
0a0337e0 3611 shrink_zones(zonelist, sc);
c6a8a8c5 3612
bb21c7ce 3613 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
0b06496a
JW
3614 break;
3615
3616 if (sc->compaction_ready)
3617 break;
1da177e4 3618
0e50ce3b
MK
3619 /*
3620 * If we're getting trouble reclaiming, start doing
3621 * writepage even in laptop mode.
3622 */
3623 if (sc->priority < DEF_PRIORITY - 2)
3624 sc->may_writepage = 1;
0b06496a 3625 } while (--sc->priority >= 0);
bb21c7ce 3626
2a2e4885
JW
3627 last_pgdat = NULL;
3628 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3629 sc->nodemask) {
3630 if (zone->zone_pgdat == last_pgdat)
3631 continue;
3632 last_pgdat = zone->zone_pgdat;
1b05117d 3633
2a2e4885 3634 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
1b05117d
JW
3635
3636 if (cgroup_reclaim(sc)) {
3637 struct lruvec *lruvec;
3638
3639 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
3640 zone->zone_pgdat);
3641 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
3642 }
2a2e4885
JW
3643 }
3644
873b4771
KK
3645 delayacct_freepages_end();
3646
bb21c7ce
KM
3647 if (sc->nr_reclaimed)
3648 return sc->nr_reclaimed;
3649
0cee34fd 3650 /* Aborted reclaim to try compaction? don't OOM, then */
0b06496a 3651 if (sc->compaction_ready)
7335084d
MG
3652 return 1;
3653
b91ac374
JW
3654 /*
3655 * We make inactive:active ratio decisions based on the node's
3656 * composition of memory, but a restrictive reclaim_idx or a
3657 * memory.low cgroup setting can exempt large amounts of
3658 * memory from reclaim. Neither of which are very common, so
3659 * instead of doing costly eligibility calculations of the
3660 * entire cgroup subtree up front, we assume the estimates are
3661 * good, and retry with forcible deactivation if that fails.
3662 */
3663 if (sc->skipped_deactivate) {
3664 sc->priority = initial_priority;
3665 sc->force_deactivate = 1;
3666 sc->skipped_deactivate = 0;
3667 goto retry;
3668 }
3669
241994ed 3670 /* Untapped cgroup reserves? Don't OOM, retry. */
d6622f63 3671 if (sc->memcg_low_skipped) {
241994ed 3672 sc->priority = initial_priority;
b91ac374 3673 sc->force_deactivate = 0;
d6622f63
YX
3674 sc->memcg_low_reclaim = 1;
3675 sc->memcg_low_skipped = 0;
241994ed
JW
3676 goto retry;
3677 }
3678
bb21c7ce 3679 return 0;
1da177e4
LT
3680}
3681
c73322d0 3682static bool allow_direct_reclaim(pg_data_t *pgdat)
5515061d
MG
3683{
3684 struct zone *zone;
3685 unsigned long pfmemalloc_reserve = 0;
3686 unsigned long free_pages = 0;
3687 int i;
3688 bool wmark_ok;
3689
c73322d0
JW
3690 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3691 return true;
3692
5515061d
MG
3693 for (i = 0; i <= ZONE_NORMAL; i++) {
3694 zone = &pgdat->node_zones[i];
d450abd8
JW
3695 if (!managed_zone(zone))
3696 continue;
3697
3698 if (!zone_reclaimable_pages(zone))
675becce
MG
3699 continue;
3700
5515061d
MG
3701 pfmemalloc_reserve += min_wmark_pages(zone);
3702 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3703 }
3704
675becce
MG
3705 /* If there are no reserves (unexpected config) then do not throttle */
3706 if (!pfmemalloc_reserve)
3707 return true;
3708
5515061d
MG
3709 wmark_ok = free_pages > pfmemalloc_reserve / 2;
3710
3711 /* kswapd must be awake if processes are being throttled */
3712 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
97a225e6
JK
3713 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
3714 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
5644e1fb 3715
5515061d
MG
3716 wake_up_interruptible(&pgdat->kswapd_wait);
3717 }
3718
3719 return wmark_ok;
3720}
3721
3722/*
3723 * Throttle direct reclaimers if backing storage is backed by the network
3724 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3725 * depleted. kswapd will continue to make progress and wake the processes
50694c28
MG
3726 * when the low watermark is reached.
3727 *
3728 * Returns true if a fatal signal was delivered during throttling. If this
3729 * happens, the page allocator should not consider triggering the OOM killer.
5515061d 3730 */
50694c28 3731static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
5515061d
MG
3732 nodemask_t *nodemask)
3733{
675becce 3734 struct zoneref *z;
5515061d 3735 struct zone *zone;
675becce 3736 pg_data_t *pgdat = NULL;
5515061d
MG
3737
3738 /*
3739 * Kernel threads should not be throttled as they may be indirectly
3740 * responsible for cleaning pages necessary for reclaim to make forward
3741 * progress. kjournald for example may enter direct reclaim while
3742 * committing a transaction where throttling it could forcing other
3743 * processes to block on log_wait_commit().
3744 */
3745 if (current->flags & PF_KTHREAD)
50694c28
MG
3746 goto out;
3747
3748 /*
3749 * If a fatal signal is pending, this process should not throttle.
3750 * It should return quickly so it can exit and free its memory
3751 */
3752 if (fatal_signal_pending(current))
3753 goto out;
5515061d 3754
675becce
MG
3755 /*
3756 * Check if the pfmemalloc reserves are ok by finding the first node
3757 * with a usable ZONE_NORMAL or lower zone. The expectation is that
3758 * GFP_KERNEL will be required for allocating network buffers when
3759 * swapping over the network so ZONE_HIGHMEM is unusable.
3760 *
3761 * Throttling is based on the first usable node and throttled processes
3762 * wait on a queue until kswapd makes progress and wakes them. There
3763 * is an affinity then between processes waking up and where reclaim
3764 * progress has been made assuming the process wakes on the same node.
3765 * More importantly, processes running on remote nodes will not compete
3766 * for remote pfmemalloc reserves and processes on different nodes
3767 * should make reasonable progress.
3768 */
3769 for_each_zone_zonelist_nodemask(zone, z, zonelist,
17636faa 3770 gfp_zone(gfp_mask), nodemask) {
675becce
MG
3771 if (zone_idx(zone) > ZONE_NORMAL)
3772 continue;
3773
3774 /* Throttle based on the first usable node */
3775 pgdat = zone->zone_pgdat;
c73322d0 3776 if (allow_direct_reclaim(pgdat))
675becce
MG
3777 goto out;
3778 break;
3779 }
3780
3781 /* If no zone was usable by the allocation flags then do not throttle */
3782 if (!pgdat)
50694c28 3783 goto out;
5515061d 3784
68243e76
MG
3785 /* Account for the throttling */
3786 count_vm_event(PGSCAN_DIRECT_THROTTLE);
3787
5515061d
MG
3788 /*
3789 * If the caller cannot enter the filesystem, it's possible that it
3790 * is due to the caller holding an FS lock or performing a journal
3791 * transaction in the case of a filesystem like ext[3|4]. In this case,
3792 * it is not safe to block on pfmemalloc_wait as kswapd could be
3793 * blocked waiting on the same lock. Instead, throttle for up to a
3794 * second before continuing.
3795 */
2e786d9e 3796 if (!(gfp_mask & __GFP_FS))
5515061d 3797 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
c73322d0 3798 allow_direct_reclaim(pgdat), HZ);
2e786d9e
ML
3799 else
3800 /* Throttle until kswapd wakes the process */
3801 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3802 allow_direct_reclaim(pgdat));
50694c28 3803
50694c28
MG
3804 if (fatal_signal_pending(current))
3805 return true;
3806
3807out:
3808 return false;
5515061d
MG
3809}
3810
dac1d27b 3811unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
327c0e96 3812 gfp_t gfp_mask, nodemask_t *nodemask)
66e1707b 3813{
33906bc5 3814 unsigned long nr_reclaimed;
66e1707b 3815 struct scan_control sc = {
ee814fe2 3816 .nr_to_reclaim = SWAP_CLUSTER_MAX,
f2f43e56 3817 .gfp_mask = current_gfp_context(gfp_mask),
b2e18757 3818 .reclaim_idx = gfp_zone(gfp_mask),
ee814fe2
JW
3819 .order = order,
3820 .nodemask = nodemask,
3821 .priority = DEF_PRIORITY,
66e1707b 3822 .may_writepage = !laptop_mode,
a6dc60f8 3823 .may_unmap = 1,
2e2e4259 3824 .may_swap = 1,
66e1707b
BS
3825 };
3826
bb451fdf
GT
3827 /*
3828 * scan_control uses s8 fields for order, priority, and reclaim_idx.
3829 * Confirm they are large enough for max values.
3830 */
3831 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3832 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3833 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3834
5515061d 3835 /*
50694c28
MG
3836 * Do not enter reclaim if fatal signal was delivered while throttled.
3837 * 1 is returned so that the page allocator does not OOM kill at this
3838 * point.
5515061d 3839 */
f2f43e56 3840 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
5515061d
MG
3841 return 1;
3842
1732d2b0 3843 set_task_reclaim_state(current, &sc.reclaim_state);
3481c37f 3844 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
33906bc5 3845
3115cd91 3846 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
33906bc5
MG
3847
3848 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
1732d2b0 3849 set_task_reclaim_state(current, NULL);
33906bc5
MG
3850
3851 return nr_reclaimed;
66e1707b
BS
3852}
3853
c255a458 3854#ifdef CONFIG_MEMCG
66e1707b 3855
d2e5fb92 3856/* Only used by soft limit reclaim. Do not reuse for anything else. */
a9dd0a83 3857unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
4e416953 3858 gfp_t gfp_mask, bool noswap,
ef8f2327 3859 pg_data_t *pgdat,
0ae5e89c 3860 unsigned long *nr_scanned)
4e416953 3861{
afaf07a6 3862 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4e416953 3863 struct scan_control sc = {
b8f5c566 3864 .nr_to_reclaim = SWAP_CLUSTER_MAX,
ee814fe2 3865 .target_mem_cgroup = memcg,
4e416953
BS
3866 .may_writepage = !laptop_mode,
3867 .may_unmap = 1,
b2e18757 3868 .reclaim_idx = MAX_NR_ZONES - 1,
4e416953 3869 .may_swap = !noswap,
4e416953 3870 };
0ae5e89c 3871
d2e5fb92
MH
3872 WARN_ON_ONCE(!current->reclaim_state);
3873
4e416953
BS
3874 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3875 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
bdce6d9e 3876
9e3b2f8c 3877 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3481c37f 3878 sc.gfp_mask);
bdce6d9e 3879
4e416953
BS
3880 /*
3881 * NOTE: Although we can get the priority field, using it
3882 * here is not a good idea, since it limits the pages we can scan.
a9dd0a83 3883 * if we don't reclaim here, the shrink_node from balance_pgdat
4e416953
BS
3884 * will pick up pages from other mem cgroup's as well. We hack
3885 * the priority and make it zero.
3886 */
afaf07a6 3887 shrink_lruvec(lruvec, &sc);
bdce6d9e
KM
3888
3889 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3890
0ae5e89c 3891 *nr_scanned = sc.nr_scanned;
0308f7cf 3892
4e416953
BS
3893 return sc.nr_reclaimed;
3894}
3895
72835c86 3896unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
b70a2a21 3897 unsigned long nr_pages,
a7885eb8 3898 gfp_t gfp_mask,
73b73bac 3899 unsigned int reclaim_options)
66e1707b 3900{
bdce6d9e 3901 unsigned long nr_reclaimed;
499118e9 3902 unsigned int noreclaim_flag;
66e1707b 3903 struct scan_control sc = {
b70a2a21 3904 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7dea19f9 3905 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
a09ed5e0 3906 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
b2e18757 3907 .reclaim_idx = MAX_NR_ZONES - 1,
ee814fe2
JW
3908 .target_mem_cgroup = memcg,
3909 .priority = DEF_PRIORITY,
3910 .may_writepage = !laptop_mode,
3911 .may_unmap = 1,
73b73bac
YA
3912 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
3913 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
a09ed5e0 3914 };
889976db 3915 /*
fa40d1ee
SB
3916 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
3917 * equal pressure on all the nodes. This is based on the assumption that
3918 * the reclaim does not bail out early.
889976db 3919 */
fa40d1ee 3920 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
889976db 3921
fa40d1ee 3922 set_task_reclaim_state(current, &sc.reclaim_state);
3481c37f 3923 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
499118e9 3924 noreclaim_flag = memalloc_noreclaim_save();
eb414681 3925
3115cd91 3926 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
eb414681 3927
499118e9 3928 memalloc_noreclaim_restore(noreclaim_flag);
bdce6d9e 3929 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
1732d2b0 3930 set_task_reclaim_state(current, NULL);
bdce6d9e
KM
3931
3932 return nr_reclaimed;
66e1707b
BS
3933}
3934#endif
3935
1d82de61 3936static void age_active_anon(struct pglist_data *pgdat,
ef8f2327 3937 struct scan_control *sc)
f16015fb 3938{
b95a2f2d 3939 struct mem_cgroup *memcg;
b91ac374 3940 struct lruvec *lruvec;
f16015fb 3941
2f368a9f 3942 if (!can_age_anon_pages(pgdat, sc))
b95a2f2d
JW
3943 return;
3944
b91ac374
JW
3945 lruvec = mem_cgroup_lruvec(NULL, pgdat);
3946 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
3947 return;
3948
b95a2f2d
JW
3949 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3950 do {
b91ac374
JW
3951 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3952 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3953 sc, LRU_ACTIVE_ANON);
b95a2f2d
JW
3954 memcg = mem_cgroup_iter(NULL, memcg, NULL);
3955 } while (memcg);
f16015fb
JW
3956}
3957
97a225e6 3958static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
1c30844d
MG
3959{
3960 int i;
3961 struct zone *zone;
3962
3963 /*
3964 * Check for watermark boosts top-down as the higher zones
3965 * are more likely to be boosted. Both watermarks and boosts
1eba09c1 3966 * should not be checked at the same time as reclaim would
1c30844d
MG
3967 * start prematurely when there is no boosting and a lower
3968 * zone is balanced.
3969 */
97a225e6 3970 for (i = highest_zoneidx; i >= 0; i--) {
1c30844d
MG
3971 zone = pgdat->node_zones + i;
3972 if (!managed_zone(zone))
3973 continue;
3974
3975 if (zone->watermark_boost)
3976 return true;
3977 }
3978
3979 return false;
3980}
3981
e716f2eb
MG
3982/*
3983 * Returns true if there is an eligible zone balanced for the request order
97a225e6 3984 * and highest_zoneidx
e716f2eb 3985 */
97a225e6 3986static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
60cefed4 3987{
e716f2eb
MG
3988 int i;
3989 unsigned long mark = -1;
3990 struct zone *zone;
60cefed4 3991
1c30844d
MG
3992 /*
3993 * Check watermarks bottom-up as lower zones are more likely to
3994 * meet watermarks.
3995 */
97a225e6 3996 for (i = 0; i <= highest_zoneidx; i++) {
e716f2eb 3997 zone = pgdat->node_zones + i;
6256c6b4 3998
e716f2eb
MG
3999 if (!managed_zone(zone))
4000 continue;
4001
c574bbe9
HY
4002 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
4003 mark = wmark_pages(zone, WMARK_PROMO);
4004 else
4005 mark = high_wmark_pages(zone);
97a225e6 4006 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
e716f2eb
MG
4007 return true;
4008 }
4009
4010 /*
36c26128 4011 * If a node has no managed zone within highest_zoneidx, it does not
e716f2eb
MG
4012 * need balancing by definition. This can happen if a zone-restricted
4013 * allocation tries to wake a remote kswapd.
4014 */
4015 if (mark == -1)
4016 return true;
4017
4018 return false;
60cefed4
JW
4019}
4020
631b6e08
MG
4021/* Clear pgdat state for congested, dirty or under writeback. */
4022static void clear_pgdat_congested(pg_data_t *pgdat)
4023{
1b05117d
JW
4024 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4025
4026 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
631b6e08
MG
4027 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4028 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4029}
4030
5515061d
MG
4031/*
4032 * Prepare kswapd for sleeping. This verifies that there are no processes
4033 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4034 *
4035 * Returns true if kswapd is ready to sleep
4036 */
97a225e6
JK
4037static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
4038 int highest_zoneidx)
f50de2d3 4039{
5515061d 4040 /*
9e5e3661 4041 * The throttled processes are normally woken up in balance_pgdat() as
c73322d0 4042 * soon as allow_direct_reclaim() is true. But there is a potential
9e5e3661
VB
4043 * race between when kswapd checks the watermarks and a process gets
4044 * throttled. There is also a potential race if processes get
4045 * throttled, kswapd wakes, a large process exits thereby balancing the
4046 * zones, which causes kswapd to exit balance_pgdat() before reaching
4047 * the wake up checks. If kswapd is going to sleep, no process should
4048 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4049 * the wake up is premature, processes will wake kswapd and get
4050 * throttled again. The difference from wake ups in balance_pgdat() is
4051 * that here we are under prepare_to_wait().
5515061d 4052 */
9e5e3661
VB
4053 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4054 wake_up_all(&pgdat->pfmemalloc_wait);
f50de2d3 4055
c73322d0
JW
4056 /* Hopeless node, leave it to direct reclaim */
4057 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4058 return true;
4059
97a225e6 4060 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
e716f2eb
MG
4061 clear_pgdat_congested(pgdat);
4062 return true;
1d82de61
MG
4063 }
4064
333b0a45 4065 return false;
f50de2d3
MG
4066}
4067
75485363 4068/*
1d82de61
MG
4069 * kswapd shrinks a node of pages that are at or below the highest usable
4070 * zone that is currently unbalanced.
b8e83b94
MG
4071 *
4072 * Returns true if kswapd scanned at least the requested number of pages to
283aba9f
MG
4073 * reclaim or if the lack of progress was due to pages under writeback.
4074 * This is used to determine if the scanning priority needs to be raised.
75485363 4075 */
1d82de61 4076static bool kswapd_shrink_node(pg_data_t *pgdat,
accf6242 4077 struct scan_control *sc)
75485363 4078{
1d82de61
MG
4079 struct zone *zone;
4080 int z;
75485363 4081
1d82de61
MG
4082 /* Reclaim a number of pages proportional to the number of zones */
4083 sc->nr_to_reclaim = 0;
970a39a3 4084 for (z = 0; z <= sc->reclaim_idx; z++) {
1d82de61 4085 zone = pgdat->node_zones + z;
6aa303de 4086 if (!managed_zone(zone))
1d82de61 4087 continue;
7c954f6d 4088
1d82de61
MG
4089 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
4090 }
7c954f6d
MG
4091
4092 /*
1d82de61
MG
4093 * Historically care was taken to put equal pressure on all zones but
4094 * now pressure is applied based on node LRU order.
7c954f6d 4095 */
970a39a3 4096 shrink_node(pgdat, sc);
283aba9f 4097
7c954f6d 4098 /*
1d82de61
MG
4099 * Fragmentation may mean that the system cannot be rebalanced for
4100 * high-order allocations. If twice the allocation size has been
4101 * reclaimed then recheck watermarks only at order-0 to prevent
4102 * excessive reclaim. Assume that a process requested a high-order
4103 * can direct reclaim/compact.
7c954f6d 4104 */
9861a62c 4105 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
1d82de61 4106 sc->order = 0;
7c954f6d 4107
b8e83b94 4108 return sc->nr_scanned >= sc->nr_to_reclaim;
75485363
MG
4109}
4110
c49c2c47
MG
4111/* Page allocator PCP high watermark is lowered if reclaim is active. */
4112static inline void
4113update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4114{
4115 int i;
4116 struct zone *zone;
4117
4118 for (i = 0; i <= highest_zoneidx; i++) {
4119 zone = pgdat->node_zones + i;
4120
4121 if (!managed_zone(zone))
4122 continue;
4123
4124 if (active)
4125 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4126 else
4127 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4128 }
4129}
4130
4131static inline void
4132set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4133{
4134 update_reclaim_active(pgdat, highest_zoneidx, true);
4135}
4136
4137static inline void
4138clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4139{
4140 update_reclaim_active(pgdat, highest_zoneidx, false);
4141}
4142
1da177e4 4143/*
1d82de61
MG
4144 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4145 * that are eligible for use by the caller until at least one zone is
4146 * balanced.
1da177e4 4147 *
1d82de61 4148 * Returns the order kswapd finished reclaiming at.
1da177e4
LT
4149 *
4150 * kswapd scans the zones in the highmem->normal->dma direction. It skips
41858966 4151 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
8bb4e7a2 4152 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
1d82de61
MG
4153 * or lower is eligible for reclaim until at least one usable zone is
4154 * balanced.
1da177e4 4155 */
97a225e6 4156static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
1da177e4 4157{
1da177e4 4158 int i;
0608f43d
AM
4159 unsigned long nr_soft_reclaimed;
4160 unsigned long nr_soft_scanned;
eb414681 4161 unsigned long pflags;
1c30844d
MG
4162 unsigned long nr_boost_reclaim;
4163 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
4164 bool boosted;
1d82de61 4165 struct zone *zone;
179e9639
AM
4166 struct scan_control sc = {
4167 .gfp_mask = GFP_KERNEL,
ee814fe2 4168 .order = order,
a6dc60f8 4169 .may_unmap = 1,
179e9639 4170 };
93781325 4171
1732d2b0 4172 set_task_reclaim_state(current, &sc.reclaim_state);
eb414681 4173 psi_memstall_enter(&pflags);
4f3eaf45 4174 __fs_reclaim_acquire(_THIS_IP_);
93781325 4175
f8891e5e 4176 count_vm_event(PAGEOUTRUN);
1da177e4 4177
1c30844d
MG
4178 /*
4179 * Account for the reclaim boost. Note that the zone boost is left in
4180 * place so that parallel allocations that are near the watermark will
4181 * stall or direct reclaim until kswapd is finished.
4182 */
4183 nr_boost_reclaim = 0;
97a225e6 4184 for (i = 0; i <= highest_zoneidx; i++) {
1c30844d
MG
4185 zone = pgdat->node_zones + i;
4186 if (!managed_zone(zone))
4187 continue;
4188
4189 nr_boost_reclaim += zone->watermark_boost;
4190 zone_boosts[i] = zone->watermark_boost;
4191 }
4192 boosted = nr_boost_reclaim;
4193
4194restart:
c49c2c47 4195 set_reclaim_active(pgdat, highest_zoneidx);
1c30844d 4196 sc.priority = DEF_PRIORITY;
9e3b2f8c 4197 do {
c73322d0 4198 unsigned long nr_reclaimed = sc.nr_reclaimed;
b8e83b94 4199 bool raise_priority = true;
1c30844d 4200 bool balanced;
93781325 4201 bool ret;
b8e83b94 4202
97a225e6 4203 sc.reclaim_idx = highest_zoneidx;
1da177e4 4204
86c79f6b 4205 /*
84c7a777
MG
4206 * If the number of buffer_heads exceeds the maximum allowed
4207 * then consider reclaiming from all zones. This has a dual
4208 * purpose -- on 64-bit systems it is expected that
4209 * buffer_heads are stripped during active rotation. On 32-bit
4210 * systems, highmem pages can pin lowmem memory and shrinking
4211 * buffers can relieve lowmem pressure. Reclaim may still not
4212 * go ahead if all eligible zones for the original allocation
4213 * request are balanced to avoid excessive reclaim from kswapd.
86c79f6b
MG
4214 */
4215 if (buffer_heads_over_limit) {
4216 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
4217 zone = pgdat->node_zones + i;
6aa303de 4218 if (!managed_zone(zone))
86c79f6b 4219 continue;
cc715d99 4220
970a39a3 4221 sc.reclaim_idx = i;
e1dbeda6 4222 break;
1da177e4 4223 }
1da177e4 4224 }
dafcb73e 4225
86c79f6b 4226 /*
1c30844d
MG
4227 * If the pgdat is imbalanced then ignore boosting and preserve
4228 * the watermarks for a later time and restart. Note that the
4229 * zone watermarks will be still reset at the end of balancing
4230 * on the grounds that the normal reclaim should be enough to
4231 * re-evaluate if boosting is required when kswapd next wakes.
4232 */
97a225e6 4233 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
1c30844d
MG
4234 if (!balanced && nr_boost_reclaim) {
4235 nr_boost_reclaim = 0;
4236 goto restart;
4237 }
4238
4239 /*
4240 * If boosting is not active then only reclaim if there are no
4241 * eligible zones. Note that sc.reclaim_idx is not used as
4242 * buffer_heads_over_limit may have adjusted it.
86c79f6b 4243 */
1c30844d 4244 if (!nr_boost_reclaim && balanced)
e716f2eb 4245 goto out;
e1dbeda6 4246
1c30844d
MG
4247 /* Limit the priority of boosting to avoid reclaim writeback */
4248 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
4249 raise_priority = false;
4250
4251 /*
4252 * Do not writeback or swap pages for boosted reclaim. The
4253 * intent is to relieve pressure not issue sub-optimal IO
4254 * from reclaim context. If no pages are reclaimed, the
4255 * reclaim will be aborted.
4256 */
4257 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
4258 sc.may_swap = !nr_boost_reclaim;
1c30844d 4259
1d82de61
MG
4260 /*
4261 * Do some background aging of the anon list, to give
4262 * pages a chance to be referenced before reclaiming. All
4263 * pages are rotated regardless of classzone as this is
4264 * about consistent aging.
4265 */
ef8f2327 4266 age_active_anon(pgdat, &sc);
1d82de61 4267
b7ea3c41
MG
4268 /*
4269 * If we're getting trouble reclaiming, start doing writepage
4270 * even in laptop mode.
4271 */
047d72c3 4272 if (sc.priority < DEF_PRIORITY - 2)
b7ea3c41
MG
4273 sc.may_writepage = 1;
4274
1d82de61
MG
4275 /* Call soft limit reclaim before calling shrink_node. */
4276 sc.nr_scanned = 0;
4277 nr_soft_scanned = 0;
ef8f2327 4278 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
1d82de61
MG
4279 sc.gfp_mask, &nr_soft_scanned);
4280 sc.nr_reclaimed += nr_soft_reclaimed;
4281
1da177e4 4282 /*
1d82de61
MG
4283 * There should be no need to raise the scanning priority if
4284 * enough pages are already being scanned that that high
4285 * watermark would be met at 100% efficiency.
1da177e4 4286 */
970a39a3 4287 if (kswapd_shrink_node(pgdat, &sc))
1d82de61 4288 raise_priority = false;
5515061d
MG
4289
4290 /*
4291 * If the low watermark is met there is no need for processes
4292 * to be throttled on pfmemalloc_wait as they should not be
4293 * able to safely make forward progress. Wake them
4294 */
4295 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
c73322d0 4296 allow_direct_reclaim(pgdat))
cfc51155 4297 wake_up_all(&pgdat->pfmemalloc_wait);
5515061d 4298
b8e83b94 4299 /* Check if kswapd should be suspending */
4f3eaf45 4300 __fs_reclaim_release(_THIS_IP_);
93781325 4301 ret = try_to_freeze();
4f3eaf45 4302 __fs_reclaim_acquire(_THIS_IP_);
93781325 4303 if (ret || kthread_should_stop())
b8e83b94 4304 break;
8357376d 4305
73ce02e9 4306 /*
b8e83b94
MG
4307 * Raise priority if scanning rate is too low or there was no
4308 * progress in reclaiming pages
73ce02e9 4309 */
c73322d0 4310 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
1c30844d
MG
4311 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
4312
4313 /*
4314 * If reclaim made no progress for a boost, stop reclaim as
4315 * IO cannot be queued and it could be an infinite loop in
4316 * extreme circumstances.
4317 */
4318 if (nr_boost_reclaim && !nr_reclaimed)
4319 break;
4320
c73322d0 4321 if (raise_priority || !nr_reclaimed)
b8e83b94 4322 sc.priority--;
1d82de61 4323 } while (sc.priority >= 1);
1da177e4 4324
c73322d0
JW
4325 if (!sc.nr_reclaimed)
4326 pgdat->kswapd_failures++;
4327
b8e83b94 4328out:
c49c2c47
MG
4329 clear_reclaim_active(pgdat, highest_zoneidx);
4330
1c30844d
MG
4331 /* If reclaim was boosted, account for the reclaim done in this pass */
4332 if (boosted) {
4333 unsigned long flags;
4334
97a225e6 4335 for (i = 0; i <= highest_zoneidx; i++) {
1c30844d
MG
4336 if (!zone_boosts[i])
4337 continue;
4338
4339 /* Increments are under the zone lock */
4340 zone = pgdat->node_zones + i;
4341 spin_lock_irqsave(&zone->lock, flags);
4342 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
4343 spin_unlock_irqrestore(&zone->lock, flags);
4344 }
4345
4346 /*
4347 * As there is now likely space, wakeup kcompact to defragment
4348 * pageblocks.
4349 */
97a225e6 4350 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
1c30844d
MG
4351 }
4352
2a2e4885 4353 snapshot_refaults(NULL, pgdat);
4f3eaf45 4354 __fs_reclaim_release(_THIS_IP_);
eb414681 4355 psi_memstall_leave(&pflags);
1732d2b0 4356 set_task_reclaim_state(current, NULL);
e5ca8071 4357
0abdee2b 4358 /*
1d82de61
MG
4359 * Return the order kswapd stopped reclaiming at as
4360 * prepare_kswapd_sleep() takes it into account. If another caller
4361 * entered the allocator slow path while kswapd was awake, order will
4362 * remain at the higher level.
0abdee2b 4363 */
1d82de61 4364 return sc.order;
1da177e4
LT
4365}
4366
e716f2eb 4367/*
97a225e6
JK
4368 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
4369 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
4370 * not a valid index then either kswapd runs for first time or kswapd couldn't
4371 * sleep after previous reclaim attempt (node is still unbalanced). In that
4372 * case return the zone index of the previous kswapd reclaim cycle.
e716f2eb 4373 */
97a225e6
JK
4374static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
4375 enum zone_type prev_highest_zoneidx)
e716f2eb 4376{
97a225e6 4377 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
5644e1fb 4378
97a225e6 4379 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
e716f2eb
MG
4380}
4381
38087d9b 4382static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
97a225e6 4383 unsigned int highest_zoneidx)
f0bc0a60
KM
4384{
4385 long remaining = 0;
4386 DEFINE_WAIT(wait);
4387
4388 if (freezing(current) || kthread_should_stop())
4389 return;
4390
4391 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4392
333b0a45
SG
4393 /*
4394 * Try to sleep for a short interval. Note that kcompactd will only be
4395 * woken if it is possible to sleep for a short interval. This is
4396 * deliberate on the assumption that if reclaim cannot keep an
4397 * eligible zone balanced that it's also unlikely that compaction will
4398 * succeed.
4399 */
97a225e6 4400 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
fd901c95
VB
4401 /*
4402 * Compaction records what page blocks it recently failed to
4403 * isolate pages from and skips them in the future scanning.
4404 * When kswapd is going to sleep, it is reasonable to assume
4405 * that pages and compaction may succeed so reset the cache.
4406 */
4407 reset_isolation_suitable(pgdat);
4408
4409 /*
4410 * We have freed the memory, now we should compact it to make
4411 * allocation of the requested order possible.
4412 */
97a225e6 4413 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
fd901c95 4414
f0bc0a60 4415 remaining = schedule_timeout(HZ/10);
38087d9b
MG
4416
4417 /*
97a225e6 4418 * If woken prematurely then reset kswapd_highest_zoneidx and
38087d9b
MG
4419 * order. The values will either be from a wakeup request or
4420 * the previous request that slept prematurely.
4421 */
4422 if (remaining) {
97a225e6
JK
4423 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
4424 kswapd_highest_zoneidx(pgdat,
4425 highest_zoneidx));
5644e1fb
QC
4426
4427 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
4428 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
38087d9b
MG
4429 }
4430
f0bc0a60
KM
4431 finish_wait(&pgdat->kswapd_wait, &wait);
4432 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
4433 }
4434
4435 /*
4436 * After a short sleep, check if it was a premature sleep. If not, then
4437 * go fully to sleep until explicitly woken up.
4438 */
d9f21d42 4439 if (!remaining &&
97a225e6 4440 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
f0bc0a60
KM
4441 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
4442
4443 /*
4444 * vmstat counters are not perfectly accurate and the estimated
4445 * value for counters such as NR_FREE_PAGES can deviate from the
4446 * true value by nr_online_cpus * threshold. To avoid the zone
4447 * watermarks being breached while under pressure, we reduce the
4448 * per-cpu vmstat threshold while kswapd is awake and restore
4449 * them before going back to sleep.
4450 */
4451 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
1c7e7f6c
AK
4452
4453 if (!kthread_should_stop())
4454 schedule();
4455
f0bc0a60
KM
4456 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
4457 } else {
4458 if (remaining)
4459 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
4460 else
4461 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
4462 }
4463 finish_wait(&pgdat->kswapd_wait, &wait);
4464}
4465
1da177e4
LT
4466/*
4467 * The background pageout daemon, started as a kernel thread
4f98a2fe 4468 * from the init process.
1da177e4
LT
4469 *
4470 * This basically trickles out pages so that we have _some_
4471 * free memory available even if there is no other activity
4472 * that frees anything up. This is needed for things like routing
4473 * etc, where we otherwise might have all activity going on in
4474 * asynchronous contexts that cannot page things out.
4475 *
4476 * If there are applications that are active memory-allocators
4477 * (most normal use), this basically shouldn't matter.
4478 */
4479static int kswapd(void *p)
4480{
e716f2eb 4481 unsigned int alloc_order, reclaim_order;
97a225e6 4482 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
68d68ff6 4483 pg_data_t *pgdat = (pg_data_t *)p;
1da177e4 4484 struct task_struct *tsk = current;
a70f7302 4485 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1da177e4 4486
174596a0 4487 if (!cpumask_empty(cpumask))
c5f59f08 4488 set_cpus_allowed_ptr(tsk, cpumask);
1da177e4
LT
4489
4490 /*
4491 * Tell the memory management that we're a "memory allocator",
4492 * and that if we need more memory we should get access to it
4493 * regardless (see "__alloc_pages()"). "kswapd" should
4494 * never get caught in the normal page freeing logic.
4495 *
4496 * (Kswapd normally doesn't need memory anyway, but sometimes
4497 * you need a small amount of memory in order to be able to
4498 * page out something else, and this flag essentially protects
4499 * us from recursively trying to free more memory as we're
4500 * trying to free the first piece of memory in the first place).
4501 */
b698f0a1 4502 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
83144186 4503 set_freezable();
1da177e4 4504
5644e1fb 4505 WRITE_ONCE(pgdat->kswapd_order, 0);
97a225e6 4506 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
8cd7c588 4507 atomic_set(&pgdat->nr_writeback_throttled, 0);
1da177e4 4508 for ( ; ; ) {
6f6313d4 4509 bool ret;
3e1d1d28 4510
5644e1fb 4511 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
97a225e6
JK
4512 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4513 highest_zoneidx);
e716f2eb 4514
38087d9b
MG
4515kswapd_try_sleep:
4516 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
97a225e6 4517 highest_zoneidx);
215ddd66 4518
97a225e6 4519 /* Read the new order and highest_zoneidx */
2b47a24c 4520 alloc_order = READ_ONCE(pgdat->kswapd_order);
97a225e6
JK
4521 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
4522 highest_zoneidx);
5644e1fb 4523 WRITE_ONCE(pgdat->kswapd_order, 0);
97a225e6 4524 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
1da177e4 4525
8fe23e05
DR
4526 ret = try_to_freeze();
4527 if (kthread_should_stop())
4528 break;
4529
4530 /*
4531 * We can speed up thawing tasks if we don't call balance_pgdat
4532 * after returning from the refrigerator
4533 */
38087d9b
MG
4534 if (ret)
4535 continue;
4536
4537 /*
4538 * Reclaim begins at the requested order but if a high-order
4539 * reclaim fails then kswapd falls back to reclaiming for
4540 * order-0. If that happens, kswapd will consider sleeping
4541 * for the order it finished reclaiming at (reclaim_order)
4542 * but kcompactd is woken to compact for the original
4543 * request (alloc_order).
4544 */
97a225e6 4545 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
e5146b12 4546 alloc_order);
97a225e6
JK
4547 reclaim_order = balance_pgdat(pgdat, alloc_order,
4548 highest_zoneidx);
38087d9b
MG
4549 if (reclaim_order < alloc_order)
4550 goto kswapd_try_sleep;
1da177e4 4551 }
b0a8cc58 4552
b698f0a1 4553 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
71abdc15 4554
1da177e4
LT
4555 return 0;
4556}
4557
4558/*
5ecd9d40
DR
4559 * A zone is low on free memory or too fragmented for high-order memory. If
4560 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
4561 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
4562 * has failed or is not needed, still wake up kcompactd if only compaction is
4563 * needed.
1da177e4 4564 */
5ecd9d40 4565void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
97a225e6 4566 enum zone_type highest_zoneidx)
1da177e4
LT
4567{
4568 pg_data_t *pgdat;
5644e1fb 4569 enum zone_type curr_idx;
1da177e4 4570
6aa303de 4571 if (!managed_zone(zone))
1da177e4
LT
4572 return;
4573
5ecd9d40 4574 if (!cpuset_zone_allowed(zone, gfp_flags))
1da177e4 4575 return;
5644e1fb 4576
88f5acf8 4577 pgdat = zone->zone_pgdat;
97a225e6 4578 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
5644e1fb 4579
97a225e6
JK
4580 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
4581 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
5644e1fb
QC
4582
4583 if (READ_ONCE(pgdat->kswapd_order) < order)
4584 WRITE_ONCE(pgdat->kswapd_order, order);
dffcac2c 4585
8d0986e2 4586 if (!waitqueue_active(&pgdat->kswapd_wait))
1da177e4 4587 return;
e1a55637 4588
5ecd9d40
DR
4589 /* Hopeless node, leave it to direct reclaim if possible */
4590 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
97a225e6
JK
4591 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
4592 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
5ecd9d40
DR
4593 /*
4594 * There may be plenty of free memory available, but it's too
4595 * fragmented for high-order allocations. Wake up kcompactd
4596 * and rely on compaction_suitable() to determine if it's
4597 * needed. If it fails, it will defer subsequent attempts to
4598 * ratelimit its work.
4599 */
4600 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
97a225e6 4601 wakeup_kcompactd(pgdat, order, highest_zoneidx);
e716f2eb 4602 return;
5ecd9d40 4603 }
88f5acf8 4604
97a225e6 4605 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
5ecd9d40 4606 gfp_flags);
8d0986e2 4607 wake_up_interruptible(&pgdat->kswapd_wait);
1da177e4
LT
4608}
4609
c6f37f12 4610#ifdef CONFIG_HIBERNATION
1da177e4 4611/*
7b51755c 4612 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
d6277db4
RW
4613 * freed pages.
4614 *
4615 * Rather than trying to age LRUs the aim is to preserve the overall
4616 * LRU order by reclaiming preferentially
4617 * inactive > active > active referenced > active mapped
1da177e4 4618 */
7b51755c 4619unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
1da177e4 4620{
d6277db4 4621 struct scan_control sc = {
ee814fe2 4622 .nr_to_reclaim = nr_to_reclaim,
7b51755c 4623 .gfp_mask = GFP_HIGHUSER_MOVABLE,
b2e18757 4624 .reclaim_idx = MAX_NR_ZONES - 1,
ee814fe2 4625 .priority = DEF_PRIORITY,
d6277db4 4626 .may_writepage = 1,
ee814fe2
JW
4627 .may_unmap = 1,
4628 .may_swap = 1,
7b51755c 4629 .hibernation_mode = 1,
1da177e4 4630 };
a09ed5e0 4631 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7b51755c 4632 unsigned long nr_reclaimed;
499118e9 4633 unsigned int noreclaim_flag;
1da177e4 4634
d92a8cfc 4635 fs_reclaim_acquire(sc.gfp_mask);
93781325 4636 noreclaim_flag = memalloc_noreclaim_save();
1732d2b0 4637 set_task_reclaim_state(current, &sc.reclaim_state);
d6277db4 4638
3115cd91 4639 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
d979677c 4640
1732d2b0 4641 set_task_reclaim_state(current, NULL);
499118e9 4642 memalloc_noreclaim_restore(noreclaim_flag);
93781325 4643 fs_reclaim_release(sc.gfp_mask);
d6277db4 4644
7b51755c 4645 return nr_reclaimed;
1da177e4 4646}
c6f37f12 4647#endif /* CONFIG_HIBERNATION */
1da177e4 4648
3218ae14
YG
4649/*
4650 * This kswapd start function will be called by init and node-hot-add.
3218ae14 4651 */
b87c517a 4652void kswapd_run(int nid)
3218ae14
YG
4653{
4654 pg_data_t *pgdat = NODE_DATA(nid);
3218ae14 4655
b4a0215e
KW
4656 pgdat_kswapd_lock(pgdat);
4657 if (!pgdat->kswapd) {
4658 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4659 if (IS_ERR(pgdat->kswapd)) {
4660 /* failure at boot is fatal */
4661 BUG_ON(system_state < SYSTEM_RUNNING);
4662 pr_err("Failed to start kswapd on node %d\n", nid);
4663 pgdat->kswapd = NULL;
4664 }
3218ae14 4665 }
b4a0215e 4666 pgdat_kswapd_unlock(pgdat);
3218ae14
YG
4667}
4668
8fe23e05 4669/*
d8adde17 4670 * Called by memory hotplug when all memory in a node is offlined. Caller must
e8da368a 4671 * be holding mem_hotplug_begin/done().
8fe23e05
DR
4672 */
4673void kswapd_stop(int nid)
4674{
b4a0215e
KW
4675 pg_data_t *pgdat = NODE_DATA(nid);
4676 struct task_struct *kswapd;
8fe23e05 4677
b4a0215e
KW
4678 pgdat_kswapd_lock(pgdat);
4679 kswapd = pgdat->kswapd;
d8adde17 4680 if (kswapd) {
8fe23e05 4681 kthread_stop(kswapd);
b4a0215e 4682 pgdat->kswapd = NULL;
d8adde17 4683 }
b4a0215e 4684 pgdat_kswapd_unlock(pgdat);
8fe23e05
DR
4685}
4686
1da177e4
LT
4687static int __init kswapd_init(void)
4688{
6b700b5b 4689 int nid;
69e05944 4690
1da177e4 4691 swap_setup();
48fb2e24 4692 for_each_node_state(nid, N_MEMORY)
3218ae14 4693 kswapd_run(nid);
1da177e4
LT
4694 return 0;
4695}
4696
4697module_init(kswapd_init)
9eeff239
CL
4698
4699#ifdef CONFIG_NUMA
4700/*
a5f5f91d 4701 * Node reclaim mode
9eeff239 4702 *
a5f5f91d 4703 * If non-zero call node_reclaim when the number of free pages falls below
9eeff239 4704 * the watermarks.
9eeff239 4705 */
a5f5f91d 4706int node_reclaim_mode __read_mostly;
9eeff239 4707
a92f7126 4708/*
a5f5f91d 4709 * Priority for NODE_RECLAIM. This determines the fraction of pages
a92f7126
CL
4710 * of a node considered for each zone_reclaim. 4 scans 1/16th of
4711 * a zone.
4712 */
a5f5f91d 4713#define NODE_RECLAIM_PRIORITY 4
a92f7126 4714
9614634f 4715/*
a5f5f91d 4716 * Percentage of pages in a zone that must be unmapped for node_reclaim to
9614634f
CL
4717 * occur.
4718 */
4719int sysctl_min_unmapped_ratio = 1;
4720
0ff38490
CL
4721/*
4722 * If the number of slab pages in a zone grows beyond this percentage then
4723 * slab reclaim needs to occur.
4724 */
4725int sysctl_min_slab_ratio = 5;
4726
11fb9989 4727static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
90afa5de 4728{
11fb9989
MG
4729 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4730 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4731 node_page_state(pgdat, NR_ACTIVE_FILE);
90afa5de
MG
4732
4733 /*
4734 * It's possible for there to be more file mapped pages than
4735 * accounted for by the pages on the file LRU lists because
4736 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4737 */
4738 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4739}
4740
4741/* Work out how many page cache pages we can reclaim in this reclaim_mode */
a5f5f91d 4742static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
90afa5de 4743{
d031a157
AM
4744 unsigned long nr_pagecache_reclaimable;
4745 unsigned long delta = 0;
90afa5de
MG
4746
4747 /*
95bbc0c7 4748 * If RECLAIM_UNMAP is set, then all file pages are considered
90afa5de 4749 * potentially reclaimable. Otherwise, we have to worry about
11fb9989 4750 * pages like swapcache and node_unmapped_file_pages() provides
90afa5de
MG
4751 * a better estimate
4752 */
a5f5f91d
MG
4753 if (node_reclaim_mode & RECLAIM_UNMAP)
4754 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
90afa5de 4755 else
a5f5f91d 4756 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
90afa5de
MG
4757
4758 /* If we can't clean pages, remove dirty pages from consideration */
a5f5f91d
MG
4759 if (!(node_reclaim_mode & RECLAIM_WRITE))
4760 delta += node_page_state(pgdat, NR_FILE_DIRTY);
90afa5de
MG
4761
4762 /* Watch for any possible underflows due to delta */
4763 if (unlikely(delta > nr_pagecache_reclaimable))
4764 delta = nr_pagecache_reclaimable;
4765
4766 return nr_pagecache_reclaimable - delta;
4767}
4768
9eeff239 4769/*
a5f5f91d 4770 * Try to free up some pages from this node through reclaim.
9eeff239 4771 */
a5f5f91d 4772static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
9eeff239 4773{
7fb2d46d 4774 /* Minimum pages needed in order to stay on node */
69e05944 4775 const unsigned long nr_pages = 1 << order;
9eeff239 4776 struct task_struct *p = current;
499118e9 4777 unsigned int noreclaim_flag;
179e9639 4778 struct scan_control sc = {
62b726c1 4779 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
f2f43e56 4780 .gfp_mask = current_gfp_context(gfp_mask),
bd2f6199 4781 .order = order,
a5f5f91d
MG
4782 .priority = NODE_RECLAIM_PRIORITY,
4783 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4784 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
ee814fe2 4785 .may_swap = 1,
f2f43e56 4786 .reclaim_idx = gfp_zone(gfp_mask),
179e9639 4787 };
57f29762 4788 unsigned long pflags;
9eeff239 4789
132bb8cf
YS
4790 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4791 sc.gfp_mask);
4792
9eeff239 4793 cond_resched();
57f29762 4794 psi_memstall_enter(&pflags);
93781325 4795 fs_reclaim_acquire(sc.gfp_mask);
d4f7796e 4796 /*
95bbc0c7 4797 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
d4f7796e 4798 */
499118e9 4799 noreclaim_flag = memalloc_noreclaim_save();
1732d2b0 4800 set_task_reclaim_state(p, &sc.reclaim_state);
c84db23c 4801
d8ff6fde
ML
4802 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
4803 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
0ff38490 4804 /*
894befec 4805 * Free memory by calling shrink node with increasing
0ff38490
CL
4806 * priorities until we have enough memory freed.
4807 */
0ff38490 4808 do {
970a39a3 4809 shrink_node(pgdat, &sc);
9e3b2f8c 4810 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
0ff38490 4811 }
c84db23c 4812
1732d2b0 4813 set_task_reclaim_state(p, NULL);
499118e9 4814 memalloc_noreclaim_restore(noreclaim_flag);
93781325 4815 fs_reclaim_release(sc.gfp_mask);
57f29762 4816 psi_memstall_leave(&pflags);
132bb8cf
YS
4817
4818 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4819
a79311c1 4820 return sc.nr_reclaimed >= nr_pages;
9eeff239 4821}
179e9639 4822
a5f5f91d 4823int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
179e9639 4824{
d773ed6b 4825 int ret;
179e9639
AM
4826
4827 /*
a5f5f91d 4828 * Node reclaim reclaims unmapped file backed pages and
0ff38490 4829 * slab pages if we are over the defined limits.
34aa1330 4830 *
9614634f
CL
4831 * A small portion of unmapped file backed pages is needed for
4832 * file I/O otherwise pages read by file I/O will be immediately
a5f5f91d
MG
4833 * thrown out if the node is overallocated. So we do not reclaim
4834 * if less than a specified percentage of the node is used by
9614634f 4835 * unmapped file backed pages.
179e9639 4836 */
a5f5f91d 4837 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
d42f3245
RG
4838 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
4839 pgdat->min_slab_pages)
a5f5f91d 4840 return NODE_RECLAIM_FULL;
179e9639
AM
4841
4842 /*
d773ed6b 4843 * Do not scan if the allocation should not be delayed.
179e9639 4844 */
d0164adc 4845 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
a5f5f91d 4846 return NODE_RECLAIM_NOSCAN;
179e9639
AM
4847
4848 /*
a5f5f91d 4849 * Only run node reclaim on the local node or on nodes that do not
179e9639
AM
4850 * have associated processors. This will favor the local processor
4851 * over remote processors and spread off node memory allocations
4852 * as wide as possible.
4853 */
a5f5f91d
MG
4854 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4855 return NODE_RECLAIM_NOSCAN;
d773ed6b 4856
a5f5f91d
MG
4857 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4858 return NODE_RECLAIM_NOSCAN;
fa5e084e 4859
a5f5f91d
MG
4860 ret = __node_reclaim(pgdat, gfp_mask, order);
4861 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
d773ed6b 4862
24cf7251
MG
4863 if (!ret)
4864 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4865
d773ed6b 4866 return ret;
179e9639 4867}
9eeff239 4868#endif
894bc310 4869
77414d19
MWO
4870void check_move_unevictable_pages(struct pagevec *pvec)
4871{
4872 struct folio_batch fbatch;
4873 unsigned i;
4874
4875 folio_batch_init(&fbatch);
4876 for (i = 0; i < pvec->nr; i++) {
4877 struct page *page = pvec->pages[i];
4878
4879 if (PageTransTail(page))
4880 continue;
4881 folio_batch_add(&fbatch, page_folio(page));
4882 }
4883 check_move_unevictable_folios(&fbatch);
4884}
4885EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
4886
89e004ea 4887/**
77414d19
MWO
4888 * check_move_unevictable_folios - Move evictable folios to appropriate zone
4889 * lru list
4890 * @fbatch: Batch of lru folios to check.
89e004ea 4891 *
77414d19 4892 * Checks folios for evictability, if an evictable folio is in the unevictable
64e3d12f 4893 * lru list, moves it to the appropriate evictable lru list. This function
77414d19 4894 * should be only used for lru folios.
89e004ea 4895 */
77414d19 4896void check_move_unevictable_folios(struct folio_batch *fbatch)
89e004ea 4897{
6168d0da 4898 struct lruvec *lruvec = NULL;
24513264
HD
4899 int pgscanned = 0;
4900 int pgrescued = 0;
4901 int i;
89e004ea 4902
77414d19
MWO
4903 for (i = 0; i < fbatch->nr; i++) {
4904 struct folio *folio = fbatch->folios[i];
4905 int nr_pages = folio_nr_pages(folio);
8d8869ca 4906
8d8869ca 4907 pgscanned += nr_pages;
89e004ea 4908
77414d19
MWO
4909 /* block memcg migration while the folio moves between lrus */
4910 if (!folio_test_clear_lru(folio))
d25b5bd8
AS
4911 continue;
4912
0de340cb 4913 lruvec = folio_lruvec_relock_irq(folio, lruvec);
77414d19
MWO
4914 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
4915 lruvec_del_folio(lruvec, folio);
4916 folio_clear_unevictable(folio);
4917 lruvec_add_folio(lruvec, folio);
8d8869ca 4918 pgrescued += nr_pages;
89e004ea 4919 }
77414d19 4920 folio_set_lru(folio);
24513264 4921 }
89e004ea 4922
6168d0da 4923 if (lruvec) {
24513264
HD
4924 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4925 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
6168d0da 4926 unlock_page_lruvec_irq(lruvec);
d25b5bd8
AS
4927 } else if (pgscanned) {
4928 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
89e004ea 4929 }
89e004ea 4930}
77414d19 4931EXPORT_SYMBOL_GPL(check_move_unevictable_folios);