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