]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/vmscan.c
Revert "mm: vmscan: make memcg slab shrink lockless"
[thirdparty/linux.git] / mm / vmscan.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
1da177e4 2/*
1da177e4
LT
3 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
b1de0d13
MH
13#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
1da177e4 15#include <linux/mm.h>
5b3cc15a 16#include <linux/sched/mm.h>
1da177e4 17#include <linux/module.h>
5a0e3ad6 18#include <linux/gfp.h>
1da177e4
LT
19#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
70ddf637 24#include <linux/vmpressure.h>
e129b5c2 25#include <linux/vmstat.h>
1da177e4
LT
26#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
07f67a8d 29#include <linux/buffer_head.h> /* for buffer_heads_over_limit */
1da177e4 30#include <linux/mm_inline.h>
1da177e4
LT
31#include <linux/backing-dev.h>
32#include <linux/rmap.h>
33#include <linux/topology.h>
34#include <linux/cpu.h>
35#include <linux/cpuset.h>
3e7d3449 36#include <linux/compaction.h>
1da177e4 37#include <linux/notifier.h>
47a7c01c 38#include <linux/rwsem.h>
248a0301 39#include <linux/delay.h>
3218ae14 40#include <linux/kthread.h>
7dfb7103 41#include <linux/freezer.h>
66e1707b 42#include <linux/memcontrol.h>
26aa2d19 43#include <linux/migrate.h>
873b4771 44#include <linux/delayacct.h>
af936a16 45#include <linux/sysctl.h>
91952440 46#include <linux/memory-tiers.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>
bd74fdae
YZ
53#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
354ed597 55#include <linux/ctype.h>
d6c3af7d 56#include <linux/debugfs.h>
57e9cc50 57#include <linux/khugepaged.h>
e4dde56c
YZ
58#include <linux/rculist_nulls.h>
59#include <linux/random.h>
f95bdb70 60#include <linux/srcu.h>
1da177e4
LT
61
62#include <asm/tlbflush.h>
63#include <asm/div64.h>
64
65#include <linux/swapops.h>
117aad1e 66#include <linux/balloon_compaction.h>
c574bbe9 67#include <linux/sched/sysctl.h>
1da177e4 68
0f8053a5 69#include "internal.h"
014bb1de 70#include "swap.h"
0f8053a5 71
33906bc5
MG
72#define CREATE_TRACE_POINTS
73#include <trace/events/vmscan.h>
74
1da177e4 75struct scan_control {
22fba335
KM
76 /* How many pages shrink_list() should reclaim */
77 unsigned long nr_to_reclaim;
78
ee814fe2
JW
79 /*
80 * Nodemask of nodes allowed by the caller. If NULL, all nodes
81 * are scanned.
82 */
83 nodemask_t *nodemask;
9e3b2f8c 84
f16015fb
JW
85 /*
86 * The memory cgroup that hit its limit and as a result is the
87 * primary target of this reclaim invocation.
88 */
89 struct mem_cgroup *target_mem_cgroup;
66e1707b 90
7cf111bc
JW
91 /*
92 * Scan pressure balancing between anon and file LRUs
93 */
94 unsigned long anon_cost;
95 unsigned long file_cost;
96
49fd9b6d 97 /* Can active folios be deactivated as part of reclaim? */
b91ac374
JW
98#define DEACTIVATE_ANON 1
99#define DEACTIVATE_FILE 2
100 unsigned int may_deactivate:2;
101 unsigned int force_deactivate:1;
102 unsigned int skipped_deactivate:1;
103
1276ad68 104 /* Writepage batching in laptop mode; RECLAIM_WRITE */
ee814fe2
JW
105 unsigned int may_writepage:1;
106
49fd9b6d 107 /* Can mapped folios be reclaimed? */
ee814fe2
JW
108 unsigned int may_unmap:1;
109
49fd9b6d 110 /* Can folios be swapped as part of reclaim? */
ee814fe2
JW
111 unsigned int may_swap:1;
112
73b73bac
YA
113 /* Proactive reclaim invoked by userspace through memory.reclaim */
114 unsigned int proactive:1;
115
d6622f63 116 /*
f56ce412
JW
117 * Cgroup memory below memory.low is protected as long as we
118 * don't threaten to OOM. If any cgroup is reclaimed at
119 * reduced force or passed over entirely due to its memory.low
120 * setting (memcg_low_skipped), and nothing is reclaimed as a
121 * result, then go back for one more cycle that reclaims the protected
122 * memory (memcg_low_reclaim) to avert OOM.
d6622f63
YX
123 */
124 unsigned int memcg_low_reclaim:1;
125 unsigned int memcg_low_skipped:1;
241994ed 126
ee814fe2
JW
127 unsigned int hibernation_mode:1;
128
129 /* One of the zones is ready for compaction */
130 unsigned int compaction_ready:1;
131
b91ac374
JW
132 /* There is easily reclaimable cold cache in the current node */
133 unsigned int cache_trim_mode:1;
134
49fd9b6d 135 /* The file folios on the current node are dangerously low */
53138cea
JW
136 unsigned int file_is_tiny:1;
137
26aa2d19
DH
138 /* Always discard instead of demoting to lower tier memory */
139 unsigned int no_demotion:1;
140
bb451fdf
GT
141 /* Allocation order */
142 s8 order;
143
144 /* Scan (total_size >> priority) pages at once */
145 s8 priority;
146
49fd9b6d 147 /* The highest zone to isolate folios for reclaim from */
bb451fdf
GT
148 s8 reclaim_idx;
149
150 /* This context's GFP mask */
151 gfp_t gfp_mask;
152
ee814fe2
JW
153 /* Incremented by the number of inactive pages that were scanned */
154 unsigned long nr_scanned;
155
156 /* Number of pages freed so far during a call to shrink_zones() */
157 unsigned long nr_reclaimed;
d108c772
AR
158
159 struct {
160 unsigned int dirty;
161 unsigned int unqueued_dirty;
162 unsigned int congested;
163 unsigned int writeback;
164 unsigned int immediate;
165 unsigned int file_taken;
166 unsigned int taken;
167 } nr;
e5ca8071
YS
168
169 /* for recording the reclaimed slab by now */
170 struct reclaim_state reclaim_state;
1da177e4
LT
171};
172
1da177e4 173#ifdef ARCH_HAS_PREFETCHW
166e3d32 174#define prefetchw_prev_lru_folio(_folio, _base, _field) \
1da177e4 175 do { \
166e3d32
MWO
176 if ((_folio)->lru.prev != _base) { \
177 struct folio *prev; \
1da177e4 178 \
166e3d32 179 prev = lru_to_folio(&(_folio->lru)); \
1da177e4
LT
180 prefetchw(&prev->_field); \
181 } \
182 } while (0)
183#else
166e3d32 184#define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
1da177e4
LT
185#endif
186
187/*
c843966c 188 * From 0 .. 200. Higher means more swappy.
1da177e4
LT
189 */
190int vm_swappiness = 60;
1da177e4 191
5035ebc6 192LIST_HEAD(shrinker_list);
47a7c01c 193DECLARE_RWSEM(shrinker_rwsem);
f95bdb70 194DEFINE_SRCU(shrinker_srcu);
1da177e4 195
0a432dcb 196#ifdef CONFIG_MEMCG
a2fb1261 197static int shrinker_nr_max;
2bfd3637 198
3c6f17e6 199/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
a2fb1261
YS
200static inline int shrinker_map_size(int nr_items)
201{
202 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
203}
2bfd3637 204
3c6f17e6
YS
205static inline int shrinker_defer_size(int nr_items)
206{
207 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
208}
209
468ab843
YS
210static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
211 int nid)
212{
7cee3603
QZ
213 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
214 lockdep_is_held(&shrinker_rwsem));
468ab843
YS
215}
216
e4262c4f 217static int expand_one_shrinker_info(struct mem_cgroup *memcg,
3c6f17e6 218 int map_size, int defer_size,
42c9db39
QZ
219 int old_map_size, int old_defer_size,
220 int new_nr_max)
2bfd3637 221{
e4262c4f 222 struct shrinker_info *new, *old;
2bfd3637
YS
223 struct mem_cgroup_per_node *pn;
224 int nid;
3c6f17e6 225 int size = map_size + defer_size;
2bfd3637 226
2bfd3637
YS
227 for_each_node(nid) {
228 pn = memcg->nodeinfo[nid];
468ab843 229 old = shrinker_info_protected(memcg, nid);
2bfd3637
YS
230 /* Not yet online memcg */
231 if (!old)
232 return 0;
233
42c9db39
QZ
234 /* Already expanded this shrinker_info */
235 if (new_nr_max <= old->map_nr_max)
236 continue;
237
2bfd3637
YS
238 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
239 if (!new)
240 return -ENOMEM;
241
3c6f17e6
YS
242 new->nr_deferred = (atomic_long_t *)(new + 1);
243 new->map = (void *)new->nr_deferred + defer_size;
42c9db39 244 new->map_nr_max = new_nr_max;
3c6f17e6
YS
245
246 /* map: set all old bits, clear all new bits */
247 memset(new->map, (int)0xff, old_map_size);
248 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
249 /* nr_deferred: copy old values, clear all new values */
250 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
251 memset((void *)new->nr_deferred + old_defer_size, 0,
252 defer_size - old_defer_size);
2bfd3637 253
e4262c4f 254 rcu_assign_pointer(pn->shrinker_info, new);
7cee3603 255 kvfree_rcu(old, rcu);
2bfd3637
YS
256 }
257
258 return 0;
259}
260
e4262c4f 261void free_shrinker_info(struct mem_cgroup *memcg)
2bfd3637
YS
262{
263 struct mem_cgroup_per_node *pn;
e4262c4f 264 struct shrinker_info *info;
2bfd3637
YS
265 int nid;
266
2bfd3637
YS
267 for_each_node(nid) {
268 pn = memcg->nodeinfo[nid];
e4262c4f
YS
269 info = rcu_dereference_protected(pn->shrinker_info, true);
270 kvfree(info);
271 rcu_assign_pointer(pn->shrinker_info, NULL);
2bfd3637
YS
272 }
273}
274
e4262c4f 275int alloc_shrinker_info(struct mem_cgroup *memcg)
2bfd3637 276{
e4262c4f 277 struct shrinker_info *info;
2bfd3637 278 int nid, size, ret = 0;
3c6f17e6 279 int map_size, defer_size = 0;
2bfd3637 280
47a7c01c 281 down_write(&shrinker_rwsem);
3c6f17e6
YS
282 map_size = shrinker_map_size(shrinker_nr_max);
283 defer_size = shrinker_defer_size(shrinker_nr_max);
284 size = map_size + defer_size;
2bfd3637 285 for_each_node(nid) {
e4262c4f
YS
286 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
287 if (!info) {
288 free_shrinker_info(memcg);
2bfd3637
YS
289 ret = -ENOMEM;
290 break;
291 }
3c6f17e6
YS
292 info->nr_deferred = (atomic_long_t *)(info + 1);
293 info->map = (void *)info->nr_deferred + defer_size;
42c9db39 294 info->map_nr_max = shrinker_nr_max;
e4262c4f 295 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
2bfd3637 296 }
47a7c01c 297 up_write(&shrinker_rwsem);
2bfd3637
YS
298
299 return ret;
300}
301
e4262c4f 302static int expand_shrinker_info(int new_id)
2bfd3637 303{
3c6f17e6 304 int ret = 0;
42c9db39 305 int new_nr_max = round_up(new_id + 1, BITS_PER_LONG);
3c6f17e6
YS
306 int map_size, defer_size = 0;
307 int old_map_size, old_defer_size = 0;
2bfd3637
YS
308 struct mem_cgroup *memcg;
309
2bfd3637 310 if (!root_mem_cgroup)
d27cf2aa
YS
311 goto out;
312
47a7c01c 313 lockdep_assert_held(&shrinker_rwsem);
2bfd3637 314
3c6f17e6
YS
315 map_size = shrinker_map_size(new_nr_max);
316 defer_size = shrinker_defer_size(new_nr_max);
317 old_map_size = shrinker_map_size(shrinker_nr_max);
318 old_defer_size = shrinker_defer_size(shrinker_nr_max);
319
2bfd3637
YS
320 memcg = mem_cgroup_iter(NULL, NULL, NULL);
321 do {
3c6f17e6 322 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
42c9db39
QZ
323 old_map_size, old_defer_size,
324 new_nr_max);
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 341
7cee3603
QZ
342 rcu_read_lock();
343 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
42c9db39
QZ
344 if (!WARN_ON_ONCE(shrinker_id >= info->map_nr_max)) {
345 /* Pairs with smp mb in shrink_slab() */
346 smp_mb__before_atomic();
347 set_bit(shrinker_id, info->map);
348 }
7cee3603 349 rcu_read_unlock();
2bfd3637
YS
350 }
351}
352
b4c2b231 353static DEFINE_IDR(shrinker_idr);
b4c2b231
KT
354
355static int prealloc_memcg_shrinker(struct shrinker *shrinker)
356{
357 int id, ret = -ENOMEM;
358
476b30a0
YS
359 if (mem_cgroup_disabled())
360 return -ENOSYS;
361
47a7c01c 362 down_write(&shrinker_rwsem);
7cee3603 363 /* This may call shrinker, so it must use down_read_trylock() */
41ca668a 364 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
b4c2b231
KT
365 if (id < 0)
366 goto unlock;
367
0a4465d3 368 if (id >= shrinker_nr_max) {
e4262c4f 369 if (expand_shrinker_info(id)) {
0a4465d3
KT
370 idr_remove(&shrinker_idr, id);
371 goto unlock;
372 }
0a4465d3 373 }
b4c2b231
KT
374 shrinker->id = id;
375 ret = 0;
376unlock:
47a7c01c 377 up_write(&shrinker_rwsem);
b4c2b231
KT
378 return ret;
379}
380
381static void unregister_memcg_shrinker(struct shrinker *shrinker)
382{
383 int id = shrinker->id;
384
385 BUG_ON(id < 0);
386
47a7c01c 387 lockdep_assert_held(&shrinker_rwsem);
41ca668a 388
b4c2b231 389 idr_remove(&shrinker_idr, id);
b4c2b231 390}
b4c2b231 391
86750830
YS
392static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
393 struct mem_cgroup *memcg)
394{
395 struct shrinker_info *info;
396
7cee3603 397 info = shrinker_info_protected(memcg, nid);
86750830
YS
398 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
399}
400
401static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
402 struct mem_cgroup *memcg)
403{
404 struct shrinker_info *info;
405
7cee3603 406 info = shrinker_info_protected(memcg, nid);
86750830
YS
407 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
408}
409
a178015c
YS
410void reparent_shrinker_deferred(struct mem_cgroup *memcg)
411{
412 int i, nid;
413 long nr;
414 struct mem_cgroup *parent;
415 struct shrinker_info *child_info, *parent_info;
416
417 parent = parent_mem_cgroup(memcg);
418 if (!parent)
419 parent = root_mem_cgroup;
420
421 /* Prevent from concurrent shrinker_info expand */
c534f7cc 422 down_read(&shrinker_rwsem);
a178015c
YS
423 for_each_node(nid) {
424 child_info = shrinker_info_protected(memcg, nid);
425 parent_info = shrinker_info_protected(parent, nid);
42c9db39 426 for (i = 0; i < child_info->map_nr_max; i++) {
a178015c
YS
427 nr = atomic_long_read(&child_info->nr_deferred[i]);
428 atomic_long_add(nr, &parent_info->nr_deferred[i]);
429 }
430 }
c534f7cc 431 up_read(&shrinker_rwsem);
a178015c
YS
432}
433
b5ead35e 434static bool cgroup_reclaim(struct scan_control *sc)
89b5fae5 435{
b5ead35e 436 return sc->target_mem_cgroup;
89b5fae5 437}
97c9341f 438
a579086c
YZ
439static bool global_reclaim(struct scan_control *sc)
440{
441 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
442}
443
97c9341f 444/**
b5ead35e 445 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
97c9341f
TH
446 * @sc: scan_control in question
447 *
448 * The normal page dirty throttling mechanism in balance_dirty_pages() is
449 * completely broken with the legacy memcg and direct stalling in
49fd9b6d 450 * shrink_folio_list() is used for throttling instead, which lacks all the
97c9341f
TH
451 * niceties such as fairness, adaptive pausing, bandwidth proportional
452 * allocation and configurability.
453 *
454 * This function tests whether the vmscan currently in progress can assume
455 * that the normal dirty throttling mechanism is operational.
456 */
b5ead35e 457static bool writeback_throttling_sane(struct scan_control *sc)
97c9341f 458{
b5ead35e 459 if (!cgroup_reclaim(sc))
97c9341f
TH
460 return true;
461#ifdef CONFIG_CGROUP_WRITEBACK
69234ace 462 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
97c9341f
TH
463 return true;
464#endif
465 return false;
466}
91a45470 467#else
0a432dcb
YS
468static int prealloc_memcg_shrinker(struct shrinker *shrinker)
469{
476b30a0 470 return -ENOSYS;
0a432dcb
YS
471}
472
473static void unregister_memcg_shrinker(struct shrinker *shrinker)
474{
475}
476
86750830
YS
477static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
478 struct mem_cgroup *memcg)
479{
480 return 0;
481}
482
483static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
484 struct mem_cgroup *memcg)
485{
486 return 0;
487}
488
b5ead35e 489static bool cgroup_reclaim(struct scan_control *sc)
89b5fae5 490{
b5ead35e 491 return false;
89b5fae5 492}
97c9341f 493
a579086c
YZ
494static bool global_reclaim(struct scan_control *sc)
495{
496 return true;
497}
498
b5ead35e 499static bool writeback_throttling_sane(struct scan_control *sc)
97c9341f
TH
500{
501 return true;
502}
91a45470
KH
503#endif
504
ef05e689
YA
505static void set_task_reclaim_state(struct task_struct *task,
506 struct reclaim_state *rs)
507{
508 /* Check for an overwrite */
509 WARN_ON_ONCE(rs && task->reclaim_state);
510
511 /* Check for the nulling of an already-nulled member */
512 WARN_ON_ONCE(!rs && !task->reclaim_state);
513
514 task->reclaim_state = rs;
515}
516
583c27a1
YA
517/*
518 * flush_reclaim_state(): add pages reclaimed outside of LRU-based reclaim to
519 * scan_control->nr_reclaimed.
520 */
521static void flush_reclaim_state(struct scan_control *sc)
522{
523 /*
524 * Currently, reclaim_state->reclaimed includes three types of pages
525 * freed outside of vmscan:
526 * (1) Slab pages.
527 * (2) Clean file pages from pruned inodes (on highmem systems).
528 * (3) XFS freed buffer pages.
529 *
530 * For all of these cases, we cannot universally link the pages to a
531 * single memcg. For example, a memcg-aware shrinker can free one object
532 * charged to the target memcg, causing an entire page to be freed.
533 * If we count the entire page as reclaimed from the memcg, we end up
534 * overestimating the reclaimed amount (potentially under-reclaiming).
535 *
536 * Only count such pages for global reclaim to prevent under-reclaiming
537 * from the target memcg; preventing unnecessary retries during memcg
538 * charging and false positives from proactive reclaim.
539 *
540 * For uncommon cases where the freed pages were actually mostly
541 * charged to the target memcg, we end up underestimating the reclaimed
542 * amount. This should be fine. The freed pages will be uncharged
543 * anyway, even if they are not counted here properly, and we will be
544 * able to make forward progress in charging (which is usually in a
545 * retry loop).
546 *
547 * We can go one step further, and report the uncharged objcg pages in
548 * memcg reclaim, to make reporting more accurate and reduce
549 * underestimation, but it's probably not worth the complexity for now.
550 */
551 if (current->reclaim_state && global_reclaim(sc)) {
552 sc->nr_reclaimed += current->reclaim_state->reclaimed;
553 current->reclaim_state->reclaimed = 0;
554 }
555}
556
86750830
YS
557static long xchg_nr_deferred(struct shrinker *shrinker,
558 struct shrink_control *sc)
559{
560 int nid = sc->nid;
561
562 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
563 nid = 0;
564
565 if (sc->memcg &&
566 (shrinker->flags & SHRINKER_MEMCG_AWARE))
567 return xchg_nr_deferred_memcg(nid, shrinker,
568 sc->memcg);
569
570 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
571}
572
573
574static long add_nr_deferred(long nr, struct shrinker *shrinker,
575 struct shrink_control *sc)
576{
577 int nid = sc->nid;
578
579 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
580 nid = 0;
581
582 if (sc->memcg &&
583 (shrinker->flags & SHRINKER_MEMCG_AWARE))
584 return add_nr_deferred_memcg(nr, nid, shrinker,
585 sc->memcg);
586
587 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
588}
589
26aa2d19
DH
590static bool can_demote(int nid, struct scan_control *sc)
591{
20b51af1
HY
592 if (!numa_demotion_enabled)
593 return false;
3f1509c5
JW
594 if (sc && sc->no_demotion)
595 return false;
26aa2d19
DH
596 if (next_demotion_node(nid) == NUMA_NO_NODE)
597 return false;
598
20b51af1 599 return true;
26aa2d19
DH
600}
601
a2a36488
KB
602static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
603 int nid,
604 struct scan_control *sc)
605{
606 if (memcg == NULL) {
607 /*
608 * For non-memcg reclaim, is there
609 * space in any swap device?
610 */
611 if (get_nr_swap_pages() > 0)
612 return true;
613 } else {
614 /* Is the memcg below its swap limit? */
615 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
616 return true;
617 }
618
619 /*
620 * The page can not be swapped.
621 *
622 * Can it be reclaimed from this node via demotion?
623 */
624 return can_demote(nid, sc);
625}
626
5a1c84b4 627/*
49fd9b6d 628 * This misses isolated folios which are not accounted for to save counters.
5a1c84b4 629 * As the data only determines if reclaim or compaction continues, it is
49fd9b6d 630 * not expected that isolated folios will be a dominating factor.
5a1c84b4
MG
631 */
632unsigned long zone_reclaimable_pages(struct zone *zone)
633{
634 unsigned long nr;
635
636 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
637 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
a2a36488 638 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
5a1c84b4
MG
639 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
640 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
641
642 return nr;
643}
644
fd538803
MH
645/**
646 * lruvec_lru_size - Returns the number of pages on the given LRU list.
647 * @lruvec: lru vector
648 * @lru: lru to use
8b3a899a 649 * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
fd538803 650 */
2091339d
YZ
651static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
652 int zone_idx)
c9f299d9 653{
de3b0150 654 unsigned long size = 0;
fd538803
MH
655 int zid;
656
8b3a899a 657 for (zid = 0; zid <= zone_idx; zid++) {
fd538803 658 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
c9f299d9 659
fd538803
MH
660 if (!managed_zone(zone))
661 continue;
662
663 if (!mem_cgroup_disabled())
de3b0150 664 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
fd538803 665 else
de3b0150 666 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
fd538803 667 }
de3b0150 668 return size;
b4536f0c
MH
669}
670
1da177e4 671/*
1d3d4437 672 * Add a shrinker callback to be called from the vm.
1da177e4 673 */
e33c267a 674static int __prealloc_shrinker(struct shrinker *shrinker)
1da177e4 675{
476b30a0
YS
676 unsigned int size;
677 int err;
678
679 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
680 err = prealloc_memcg_shrinker(shrinker);
681 if (err != -ENOSYS)
682 return err;
1d3d4437 683
476b30a0
YS
684 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
685 }
686
687 size = sizeof(*shrinker->nr_deferred);
1d3d4437
GC
688 if (shrinker->flags & SHRINKER_NUMA_AWARE)
689 size *= nr_node_ids;
690
691 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
692 if (!shrinker->nr_deferred)
693 return -ENOMEM;
b4c2b231 694
8e04944f
TH
695 return 0;
696}
697
e33c267a
RG
698#ifdef CONFIG_SHRINKER_DEBUG
699int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
700{
701 va_list ap;
702 int err;
703
704 va_start(ap, fmt);
705 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
706 va_end(ap);
707 if (!shrinker->name)
708 return -ENOMEM;
709
710 err = __prealloc_shrinker(shrinker);
14773bfa 711 if (err) {
e33c267a 712 kfree_const(shrinker->name);
14773bfa
TH
713 shrinker->name = NULL;
714 }
e33c267a
RG
715
716 return err;
717}
718#else
719int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
720{
721 return __prealloc_shrinker(shrinker);
722}
723#endif
724
8e04944f
TH
725void free_prealloced_shrinker(struct shrinker *shrinker)
726{
e33c267a
RG
727#ifdef CONFIG_SHRINKER_DEBUG
728 kfree_const(shrinker->name);
14773bfa 729 shrinker->name = NULL;
e33c267a 730#endif
41ca668a 731 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
47a7c01c 732 down_write(&shrinker_rwsem);
b4c2b231 733 unregister_memcg_shrinker(shrinker);
47a7c01c 734 up_write(&shrinker_rwsem);
476b30a0 735 return;
41ca668a 736 }
b4c2b231 737
8e04944f
TH
738 kfree(shrinker->nr_deferred);
739 shrinker->nr_deferred = NULL;
740}
1d3d4437 741
8e04944f
TH
742void register_shrinker_prepared(struct shrinker *shrinker)
743{
47a7c01c 744 down_write(&shrinker_rwsem);
f95bdb70 745 list_add_tail_rcu(&shrinker->list, &shrinker_list);
41ca668a 746 shrinker->flags |= SHRINKER_REGISTERED;
5035ebc6 747 shrinker_debugfs_add(shrinker);
47a7c01c 748 up_write(&shrinker_rwsem);
8e04944f
TH
749}
750
e33c267a 751static int __register_shrinker(struct shrinker *shrinker)
8e04944f 752{
e33c267a 753 int err = __prealloc_shrinker(shrinker);
8e04944f
TH
754
755 if (err)
756 return err;
757 register_shrinker_prepared(shrinker);
1d3d4437 758 return 0;
1da177e4 759}
e33c267a
RG
760
761#ifdef CONFIG_SHRINKER_DEBUG
762int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
763{
764 va_list ap;
765 int err;
766
767 va_start(ap, fmt);
768 shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
769 va_end(ap);
770 if (!shrinker->name)
771 return -ENOMEM;
772
773 err = __register_shrinker(shrinker);
14773bfa 774 if (err) {
e33c267a 775 kfree_const(shrinker->name);
14773bfa
TH
776 shrinker->name = NULL;
777 }
e33c267a
RG
778 return err;
779}
780#else
781int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
782{
783 return __register_shrinker(shrinker);
784}
785#endif
8e1f936b 786EXPORT_SYMBOL(register_shrinker);
1da177e4
LT
787
788/*
789 * Remove one
790 */
8e1f936b 791void unregister_shrinker(struct shrinker *shrinker)
1da177e4 792{
badc28d4 793 struct dentry *debugfs_entry;
26e239b3 794 int debugfs_id;
badc28d4 795
41ca668a 796 if (!(shrinker->flags & SHRINKER_REGISTERED))
bb422a73 797 return;
41ca668a 798
47a7c01c 799 down_write(&shrinker_rwsem);
f95bdb70 800 list_del_rcu(&shrinker->list);
41ca668a
YS
801 shrinker->flags &= ~SHRINKER_REGISTERED;
802 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
803 unregister_memcg_shrinker(shrinker);
26e239b3 804 debugfs_entry = shrinker_debugfs_detach(shrinker, &debugfs_id);
47a7c01c 805 up_write(&shrinker_rwsem);
41ca668a 806
f95bdb70 807 synchronize_srcu(&shrinker_srcu);
41ca668a 808
26e239b3 809 shrinker_debugfs_remove(debugfs_entry, debugfs_id);
badc28d4 810
ae393321 811 kfree(shrinker->nr_deferred);
bb422a73 812 shrinker->nr_deferred = NULL;
1da177e4 813}
8e1f936b 814EXPORT_SYMBOL(unregister_shrinker);
1da177e4 815
880121be
CK
816/**
817 * synchronize_shrinkers - Wait for all running shrinkers to complete.
818 *
07252b0f
QZ
819 * This is equivalent to calling unregister_shrink() and register_shrinker(),
820 * but atomically and with less overhead. This is useful to guarantee that all
821 * shrinker invocations have seen an update, before freeing memory, similar to
822 * rcu.
880121be
CK
823 */
824void synchronize_shrinkers(void)
825{
07252b0f
QZ
826 down_write(&shrinker_rwsem);
827 up_write(&shrinker_rwsem);
f95bdb70 828 synchronize_srcu(&shrinker_srcu);
880121be
CK
829}
830EXPORT_SYMBOL(synchronize_shrinkers);
831
1da177e4 832#define SHRINK_BATCH 128
1d3d4437 833
cb731d6c 834static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
9092c71b 835 struct shrinker *shrinker, int priority)
1d3d4437
GC
836{
837 unsigned long freed = 0;
838 unsigned long long delta;
839 long total_scan;
d5bc5fd3 840 long freeable;
1d3d4437
GC
841 long nr;
842 long new_nr;
1d3d4437
GC
843 long batch_size = shrinker->batch ? shrinker->batch
844 : SHRINK_BATCH;
5f33a080 845 long scanned = 0, next_deferred;
1d3d4437 846
d5bc5fd3 847 freeable = shrinker->count_objects(shrinker, shrinkctl);
9b996468
KT
848 if (freeable == 0 || freeable == SHRINK_EMPTY)
849 return freeable;
1d3d4437
GC
850
851 /*
852 * copy the current shrinker scan count into a local variable
853 * and zero it so that other concurrent shrinker invocations
854 * don't also do this scanning work.
855 */
86750830 856 nr = xchg_nr_deferred(shrinker, shrinkctl);
1d3d4437 857
4b85afbd
JW
858 if (shrinker->seeks) {
859 delta = freeable >> priority;
860 delta *= 4;
861 do_div(delta, shrinker->seeks);
862 } else {
863 /*
864 * These objects don't require any IO to create. Trim
865 * them aggressively under memory pressure to keep
866 * them from causing refetches in the IO caches.
867 */
868 delta = freeable / 2;
869 }
172b06c3 870
18bb473e 871 total_scan = nr >> priority;
1d3d4437 872 total_scan += delta;
18bb473e 873 total_scan = min(total_scan, (2 * freeable));
1d3d4437
GC
874
875 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
9092c71b 876 freeable, delta, total_scan, priority);
1d3d4437 877
0b1fb40a
VD
878 /*
879 * Normally, we should not scan less than batch_size objects in one
880 * pass to avoid too frequent shrinker calls, but if the slab has less
881 * than batch_size objects in total and we are really tight on memory,
882 * we will try to reclaim all available objects, otherwise we can end
883 * up failing allocations although there are plenty of reclaimable
884 * objects spread over several slabs with usage less than the
885 * batch_size.
886 *
887 * We detect the "tight on memory" situations by looking at the total
888 * number of objects we want to scan (total_scan). If it is greater
d5bc5fd3 889 * than the total number of objects on slab (freeable), we must be
0b1fb40a
VD
890 * scanning at high prio and therefore should try to reclaim as much as
891 * possible.
892 */
893 while (total_scan >= batch_size ||
d5bc5fd3 894 total_scan >= freeable) {
a0b02131 895 unsigned long ret;
0b1fb40a 896 unsigned long nr_to_scan = min(batch_size, total_scan);
1d3d4437 897
0b1fb40a 898 shrinkctl->nr_to_scan = nr_to_scan;
d460acb5 899 shrinkctl->nr_scanned = nr_to_scan;
a0b02131
DC
900 ret = shrinker->scan_objects(shrinker, shrinkctl);
901 if (ret == SHRINK_STOP)
902 break;
903 freed += ret;
1d3d4437 904
d460acb5
CW
905 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
906 total_scan -= shrinkctl->nr_scanned;
907 scanned += shrinkctl->nr_scanned;
1d3d4437
GC
908
909 cond_resched();
910 }
911
18bb473e
YS
912 /*
913 * The deferred work is increased by any new work (delta) that wasn't
914 * done, decreased by old deferred work that was done now.
915 *
916 * And it is capped to two times of the freeable items.
917 */
918 next_deferred = max_t(long, (nr + delta - scanned), 0);
919 next_deferred = min(next_deferred, (2 * freeable));
920
1d3d4437
GC
921 /*
922 * move the unused scan count back into the shrinker in a
86750830 923 * manner that handles concurrent updates.
1d3d4437 924 */
86750830 925 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
1d3d4437 926
8efb4b59 927 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
1d3d4437 928 return freed;
1495f230
YH
929}
930
0a432dcb 931#ifdef CONFIG_MEMCG
b0dedc49
KT
932static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
933 struct mem_cgroup *memcg, int priority)
934{
e4262c4f 935 struct shrinker_info *info;
b8e57efa 936 unsigned long ret, freed = 0;
d6ecbcd7 937 int i;
b0dedc49 938
0a432dcb 939 if (!mem_cgroup_online(memcg))
b0dedc49
KT
940 return 0;
941
7cee3603
QZ
942 if (!down_read_trylock(&shrinker_rwsem))
943 return 0;
944
945 info = shrinker_info_protected(memcg, nid);
e4262c4f 946 if (unlikely(!info))
b0dedc49
KT
947 goto unlock;
948
d6ecbcd7 949 for_each_set_bit(i, info->map, info->map_nr_max) {
b0dedc49
KT
950 struct shrink_control sc = {
951 .gfp_mask = gfp_mask,
952 .nid = nid,
953 .memcg = memcg,
954 };
955 struct shrinker *shrinker;
956
957 shrinker = idr_find(&shrinker_idr, i);
41ca668a 958 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
7e010df5 959 if (!shrinker)
e4262c4f 960 clear_bit(i, info->map);
b0dedc49
KT
961 continue;
962 }
963
0a432dcb 964 /* Call non-slab shrinkers even though kmem is disabled */
f7a449f7 965 if (!memcg_kmem_online() &&
0a432dcb
YS
966 !(shrinker->flags & SHRINKER_NONSLAB))
967 continue;
968
b0dedc49 969 ret = do_shrink_slab(&sc, shrinker, priority);
f90280d6 970 if (ret == SHRINK_EMPTY) {
e4262c4f 971 clear_bit(i, info->map);
f90280d6
KT
972 /*
973 * After the shrinker reported that it had no objects to
974 * free, but before we cleared the corresponding bit in
975 * the memcg shrinker map, a new object might have been
976 * added. To make sure, we have the bit set in this
977 * case, we invoke the shrinker one more time and reset
978 * the bit if it reports that it is not empty anymore.
979 * The memory barrier here pairs with the barrier in
2bfd3637 980 * set_shrinker_bit():
f90280d6
KT
981 *
982 * list_lru_add() shrink_slab_memcg()
983 * list_add_tail() clear_bit()
984 * <MB> <MB>
985 * set_bit() do_shrink_slab()
986 */
987 smp_mb__after_atomic();
988 ret = do_shrink_slab(&sc, shrinker, priority);
989 if (ret == SHRINK_EMPTY)
990 ret = 0;
991 else
2bfd3637 992 set_shrinker_bit(memcg, nid, i);
f90280d6 993 }
b0dedc49 994 freed += ret;
7cee3603
QZ
995
996 if (rwsem_is_contended(&shrinker_rwsem)) {
997 freed = freed ? : 1;
998 break;
999 }
b0dedc49
KT
1000 }
1001unlock:
7cee3603 1002 up_read(&shrinker_rwsem);
b0dedc49
KT
1003 return freed;
1004}
0a432dcb 1005#else /* CONFIG_MEMCG */
b0dedc49
KT
1006static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
1007 struct mem_cgroup *memcg, int priority)
1008{
1009 return 0;
1010}
0a432dcb 1011#endif /* CONFIG_MEMCG */
b0dedc49 1012
6b4f7799 1013/**
cb731d6c 1014 * shrink_slab - shrink slab caches
6b4f7799
JW
1015 * @gfp_mask: allocation context
1016 * @nid: node whose slab caches to target
cb731d6c 1017 * @memcg: memory cgroup whose slab caches to target
9092c71b 1018 * @priority: the reclaim priority
1da177e4 1019 *
6b4f7799 1020 * Call the shrink functions to age shrinkable caches.
1da177e4 1021 *
6b4f7799
JW
1022 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
1023 * unaware shrinkers will receive a node id of 0 instead.
1da177e4 1024 *
aeed1d32
VD
1025 * @memcg specifies the memory cgroup to target. Unaware shrinkers
1026 * are called only if it is the root cgroup.
cb731d6c 1027 *
9092c71b
JB
1028 * @priority is sc->priority, we take the number of objects and >> by priority
1029 * in order to get the scan target.
b15e0905 1030 *
6b4f7799 1031 * Returns the number of reclaimed slab objects.
1da177e4 1032 */
cb731d6c
VD
1033static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
1034 struct mem_cgroup *memcg,
9092c71b 1035 int priority)
1da177e4 1036{
b8e57efa 1037 unsigned long ret, freed = 0;
1da177e4 1038 struct shrinker *shrinker;
d6ecbcd7 1039 int srcu_idx;
1da177e4 1040
fa1e512f
YS
1041 /*
1042 * The root memcg might be allocated even though memcg is disabled
1043 * via "cgroup_disable=memory" boot parameter. This could make
1044 * mem_cgroup_is_root() return false, then just run memcg slab
1045 * shrink, but skip global shrink. This may result in premature
1046 * oom.
1047 */
1048 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
b0dedc49 1049 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
cb731d6c 1050
f95bdb70 1051 srcu_idx = srcu_read_lock(&shrinker_srcu);
1da177e4 1052
f95bdb70
QZ
1053 list_for_each_entry_srcu(shrinker, &shrinker_list, list,
1054 srcu_read_lock_held(&shrinker_srcu)) {
6b4f7799
JW
1055 struct shrink_control sc = {
1056 .gfp_mask = gfp_mask,
1057 .nid = nid,
cb731d6c 1058 .memcg = memcg,
6b4f7799 1059 };
ec97097b 1060
9b996468
KT
1061 ret = do_shrink_slab(&sc, shrinker, priority);
1062 if (ret == SHRINK_EMPTY)
1063 ret = 0;
1064 freed += ret;
1da177e4 1065 }
6b4f7799 1066
f95bdb70 1067 srcu_read_unlock(&shrinker_srcu, srcu_idx);
f06590bd 1068 cond_resched();
24f7c6b9 1069 return freed;
1da177e4
LT
1070}
1071
e83b39d6 1072static unsigned long drop_slab_node(int nid)
cb731d6c 1073{
e83b39d6
JK
1074 unsigned long freed = 0;
1075 struct mem_cgroup *memcg = NULL;
cb731d6c 1076
e83b39d6 1077 memcg = mem_cgroup_iter(NULL, NULL, NULL);
cb731d6c 1078 do {
e83b39d6
JK
1079 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1080 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
069c411d 1081
e83b39d6 1082 return freed;
cb731d6c
VD
1083}
1084
1085void drop_slab(void)
1086{
1087 int nid;
e83b39d6
JK
1088 int shift = 0;
1089 unsigned long freed;
1090
1091 do {
1092 freed = 0;
1093 for_each_online_node(nid) {
1094 if (fatal_signal_pending(current))
1095 return;
cb731d6c 1096
e83b39d6
JK
1097 freed += drop_slab_node(nid);
1098 }
1099 } while ((freed >> shift++) > 1);
cb731d6c
VD
1100}
1101
57e9cc50
JW
1102static int reclaimer_offset(void)
1103{
1104 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1105 PGDEMOTE_DIRECT - PGDEMOTE_KSWAPD);
1106 BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1107 PGSCAN_DIRECT - PGSCAN_KSWAPD);
1108 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1109 PGDEMOTE_KHUGEPAGED - PGDEMOTE_KSWAPD);
1110 BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1111 PGSCAN_KHUGEPAGED - PGSCAN_KSWAPD);
1112
1113 if (current_is_kswapd())
1114 return 0;
1115 if (current_is_khugepaged())
1116 return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
1117 return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
1118}
1119
e0cd5e7f 1120static inline int is_page_cache_freeable(struct folio *folio)
1da177e4 1121{
ceddc3a5 1122 /*
49fd9b6d
MWO
1123 * A freeable page cache folio is referenced only by the caller
1124 * that isolated the folio, the page cache and optional filesystem
1125 * private data at folio->private.
ceddc3a5 1126 */
e0cd5e7f
MWO
1127 return folio_ref_count(folio) - folio_test_private(folio) ==
1128 1 + folio_nr_pages(folio);
1da177e4
LT
1129}
1130
1da177e4 1131/*
e0cd5e7f 1132 * We detected a synchronous write error writing a folio out. Probably
1da177e4
LT
1133 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1134 * fsync(), msync() or close().
1135 *
1136 * The tricky part is that after writepage we cannot touch the mapping: nothing
e0cd5e7f
MWO
1137 * prevents it from being freed up. But we have a ref on the folio and once
1138 * that folio is locked, the mapping is pinned.
1da177e4 1139 *
e0cd5e7f 1140 * We're allowed to run sleeping folio_lock() here because we know the caller has
1da177e4
LT
1141 * __GFP_FS.
1142 */
1143static void handle_write_error(struct address_space *mapping,
e0cd5e7f 1144 struct folio *folio, int error)
1da177e4 1145{
e0cd5e7f
MWO
1146 folio_lock(folio);
1147 if (folio_mapping(folio) == mapping)
3e9f45bd 1148 mapping_set_error(mapping, error);
e0cd5e7f 1149 folio_unlock(folio);
1da177e4
LT
1150}
1151
1b4e3f26
MG
1152static bool skip_throttle_noprogress(pg_data_t *pgdat)
1153{
1154 int reclaimable = 0, write_pending = 0;
1155 int i;
1156
1157 /*
1158 * If kswapd is disabled, reschedule if necessary but do not
1159 * throttle as the system is likely near OOM.
1160 */
1161 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1162 return true;
1163
1164 /*
49fd9b6d
MWO
1165 * If there are a lot of dirty/writeback folios then do not
1166 * throttle as throttling will occur when the folios cycle
1b4e3f26
MG
1167 * towards the end of the LRU if still under writeback.
1168 */
1169 for (i = 0; i < MAX_NR_ZONES; i++) {
1170 struct zone *zone = pgdat->node_zones + i;
1171
36c26128 1172 if (!managed_zone(zone))
1b4e3f26
MG
1173 continue;
1174
1175 reclaimable += zone_reclaimable_pages(zone);
1176 write_pending += zone_page_state_snapshot(zone,
1177 NR_ZONE_WRITE_PENDING);
1178 }
1179 if (2 * write_pending <= reclaimable)
1180 return true;
1181
1182 return false;
1183}
1184
c3f4a9a2 1185void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
8cd7c588
MG
1186{
1187 wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
c3f4a9a2 1188 long timeout, ret;
8cd7c588
MG
1189 DEFINE_WAIT(wait);
1190
1191 /*
54e6842d 1192 * Do not throttle user workers, kthreads other than kswapd or
8cd7c588
MG
1193 * workqueues. They may be required for reclaim to make
1194 * forward progress (e.g. journalling workqueues or kthreads).
1195 */
1196 if (!current_is_kswapd() &&
54e6842d 1197 current->flags & (PF_USER_WORKER|PF_KTHREAD)) {
b485c6f1 1198 cond_resched();
8cd7c588 1199 return;
b485c6f1 1200 }
8cd7c588 1201
c3f4a9a2
MG
1202 /*
1203 * These figures are pulled out of thin air.
1204 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1205 * parallel reclaimers which is a short-lived event so the timeout is
1206 * short. Failing to make progress or waiting on writeback are
1207 * potentially long-lived events so use a longer timeout. This is shaky
1208 * logic as a failure to make progress could be due to anything from
49fd9b6d 1209 * writeback to a slow device to excessive referenced folios at the tail
c3f4a9a2
MG
1210 * of the inactive LRU.
1211 */
1212 switch(reason) {
1213 case VMSCAN_THROTTLE_WRITEBACK:
1214 timeout = HZ/10;
1215
1216 if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1217 WRITE_ONCE(pgdat->nr_reclaim_start,
1218 node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1219 }
1220
1221 break;
1b4e3f26
MG
1222 case VMSCAN_THROTTLE_CONGESTED:
1223 fallthrough;
c3f4a9a2 1224 case VMSCAN_THROTTLE_NOPROGRESS:
1b4e3f26
MG
1225 if (skip_throttle_noprogress(pgdat)) {
1226 cond_resched();
1227 return;
1228 }
1229
1230 timeout = 1;
1231
c3f4a9a2
MG
1232 break;
1233 case VMSCAN_THROTTLE_ISOLATED:
1234 timeout = HZ/50;
1235 break;
1236 default:
1237 WARN_ON_ONCE(1);
1238 timeout = HZ;
1239 break;
8cd7c588
MG
1240 }
1241
1242 prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1243 ret = schedule_timeout(timeout);
1244 finish_wait(wqh, &wait);
d818fca1 1245
c3f4a9a2 1246 if (reason == VMSCAN_THROTTLE_WRITEBACK)
d818fca1 1247 atomic_dec(&pgdat->nr_writeback_throttled);
8cd7c588
MG
1248
1249 trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1250 jiffies_to_usecs(timeout - ret),
1251 reason);
1252}
1253
1254/*
49fd9b6d
MWO
1255 * Account for folios written if tasks are throttled waiting on dirty
1256 * folios to clean. If enough folios have been cleaned since throttling
8cd7c588
MG
1257 * started then wakeup the throttled tasks.
1258 */
512b7931 1259void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
8cd7c588
MG
1260 int nr_throttled)
1261{
1262 unsigned long nr_written;
1263
512b7931 1264 node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
8cd7c588
MG
1265
1266 /*
1267 * This is an inaccurate read as the per-cpu deltas may not
1268 * be synchronised. However, given that the system is
1269 * writeback throttled, it is not worth taking the penalty
1270 * of getting an accurate count. At worst, the throttle
1271 * timeout guarantees forward progress.
1272 */
1273 nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1274 READ_ONCE(pgdat->nr_reclaim_start);
1275
1276 if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1277 wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1278}
1279
04e62a29
CL
1280/* possible outcome of pageout() */
1281typedef enum {
49fd9b6d 1282 /* failed to write folio out, folio is locked */
04e62a29 1283 PAGE_KEEP,
49fd9b6d 1284 /* move folio to the active list, folio is locked */
04e62a29 1285 PAGE_ACTIVATE,
49fd9b6d 1286 /* folio has been sent to the disk successfully, folio is unlocked */
04e62a29 1287 PAGE_SUCCESS,
49fd9b6d 1288 /* folio is clean and locked */
04e62a29
CL
1289 PAGE_CLEAN,
1290} pageout_t;
1291
1da177e4 1292/*
49fd9b6d 1293 * pageout is called by shrink_folio_list() for each dirty folio.
1742f19f 1294 * Calls ->writepage().
1da177e4 1295 */
2282679f
N
1296static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1297 struct swap_iocb **plug)
1da177e4
LT
1298{
1299 /*
e0cd5e7f 1300 * If the folio is dirty, only perform writeback if that write
1da177e4
LT
1301 * will be non-blocking. To prevent this allocation from being
1302 * stalled by pagecache activity. But note that there may be
1303 * stalls if we need to run get_block(). We could test
1304 * PagePrivate for that.
1305 *
8174202b 1306 * If this process is currently in __generic_file_write_iter() against
e0cd5e7f 1307 * this folio's queue, we can perform writeback even if that
1da177e4
LT
1308 * will block.
1309 *
e0cd5e7f 1310 * If the folio is swapcache, write it back even if that would
1da177e4
LT
1311 * block, for some throttling. This happens by accident, because
1312 * swap_backing_dev_info is bust: it doesn't reflect the
1313 * congestion state of the swapdevs. Easy to fix, if needed.
1da177e4 1314 */
e0cd5e7f 1315 if (!is_page_cache_freeable(folio))
1da177e4
LT
1316 return PAGE_KEEP;
1317 if (!mapping) {
1318 /*
e0cd5e7f
MWO
1319 * Some data journaling orphaned folios can have
1320 * folio->mapping == NULL while being dirty with clean buffers.
1da177e4 1321 */
e0cd5e7f 1322 if (folio_test_private(folio)) {
68189fef 1323 if (try_to_free_buffers(folio)) {
e0cd5e7f
MWO
1324 folio_clear_dirty(folio);
1325 pr_info("%s: orphaned folio\n", __func__);
1da177e4
LT
1326 return PAGE_CLEAN;
1327 }
1328 }
1329 return PAGE_KEEP;
1330 }
1331 if (mapping->a_ops->writepage == NULL)
1332 return PAGE_ACTIVATE;
1da177e4 1333
e0cd5e7f 1334 if (folio_clear_dirty_for_io(folio)) {
1da177e4
LT
1335 int res;
1336 struct writeback_control wbc = {
1337 .sync_mode = WB_SYNC_NONE,
1338 .nr_to_write = SWAP_CLUSTER_MAX,
111ebb6e
OH
1339 .range_start = 0,
1340 .range_end = LLONG_MAX,
1da177e4 1341 .for_reclaim = 1,
2282679f 1342 .swap_plug = plug,
1da177e4
LT
1343 };
1344
e0cd5e7f
MWO
1345 folio_set_reclaim(folio);
1346 res = mapping->a_ops->writepage(&folio->page, &wbc);
1da177e4 1347 if (res < 0)
e0cd5e7f 1348 handle_write_error(mapping, folio, res);
994fc28c 1349 if (res == AOP_WRITEPAGE_ACTIVATE) {
e0cd5e7f 1350 folio_clear_reclaim(folio);
1da177e4
LT
1351 return PAGE_ACTIVATE;
1352 }
c661b078 1353
e0cd5e7f 1354 if (!folio_test_writeback(folio)) {
1da177e4 1355 /* synchronous write or broken a_ops? */
e0cd5e7f 1356 folio_clear_reclaim(folio);
1da177e4 1357 }
e0cd5e7f
MWO
1358 trace_mm_vmscan_write_folio(folio);
1359 node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1da177e4
LT
1360 return PAGE_SUCCESS;
1361 }
1362
1363 return PAGE_CLEAN;
1364}
1365
a649fd92 1366/*
49fd9b6d 1367 * Same as remove_mapping, but if the folio is removed from the mapping, it
e286781d 1368 * gets returned with a refcount of 0.
a649fd92 1369 */
be7c07d6 1370static int __remove_mapping(struct address_space *mapping, struct folio *folio,
b910718a 1371 bool reclaimed, struct mem_cgroup *target_memcg)
49d2e9cc 1372{
bd4c82c2 1373 int refcount;
aae466b0 1374 void *shadow = NULL;
c4843a75 1375
be7c07d6
MWO
1376 BUG_ON(!folio_test_locked(folio));
1377 BUG_ON(mapping != folio_mapping(folio));
49d2e9cc 1378
be7c07d6 1379 if (!folio_test_swapcache(folio))
51b8c1fe 1380 spin_lock(&mapping->host->i_lock);
30472509 1381 xa_lock_irq(&mapping->i_pages);
49d2e9cc 1382 /*
49fd9b6d 1383 * The non racy check for a busy folio.
0fd0e6b0
NP
1384 *
1385 * Must be careful with the order of the tests. When someone has
49fd9b6d
MWO
1386 * a ref to the folio, it may be possible that they dirty it then
1387 * drop the reference. So if the dirty flag is tested before the
1388 * refcount here, then the following race may occur:
0fd0e6b0
NP
1389 *
1390 * get_user_pages(&page);
1391 * [user mapping goes away]
1392 * write_to(page);
49fd9b6d
MWO
1393 * !folio_test_dirty(folio) [good]
1394 * folio_set_dirty(folio);
1395 * folio_put(folio);
1396 * !refcount(folio) [good, discard it]
0fd0e6b0
NP
1397 *
1398 * [oops, our write_to data is lost]
1399 *
1400 * Reversing the order of the tests ensures such a situation cannot
49fd9b6d
MWO
1401 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
1402 * load is not satisfied before that of folio->_refcount.
0fd0e6b0 1403 *
49fd9b6d 1404 * Note that if the dirty flag is always set via folio_mark_dirty,
b93b0163 1405 * and thus under the i_pages lock, then this ordering is not required.
49d2e9cc 1406 */
be7c07d6
MWO
1407 refcount = 1 + folio_nr_pages(folio);
1408 if (!folio_ref_freeze(folio, refcount))
49d2e9cc 1409 goto cannot_free;
49fd9b6d 1410 /* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
be7c07d6
MWO
1411 if (unlikely(folio_test_dirty(folio))) {
1412 folio_ref_unfreeze(folio, refcount);
49d2e9cc 1413 goto cannot_free;
e286781d 1414 }
49d2e9cc 1415
be7c07d6
MWO
1416 if (folio_test_swapcache(folio)) {
1417 swp_entry_t swap = folio_swap_entry(folio);
ac35a490 1418
aae466b0 1419 if (reclaimed && !mapping_exiting(mapping))
8927f647 1420 shadow = workingset_eviction(folio, target_memcg);
ceff9d33 1421 __delete_from_swap_cache(folio, swap, shadow);
c449deb2 1422 mem_cgroup_swapout(folio, swap);
30472509 1423 xa_unlock_irq(&mapping->i_pages);
4081f744 1424 put_swap_folio(folio, swap);
e286781d 1425 } else {
d2329aa0 1426 void (*free_folio)(struct folio *);
6072d13c 1427
d2329aa0 1428 free_folio = mapping->a_ops->free_folio;
a528910e
JW
1429 /*
1430 * Remember a shadow entry for reclaimed file cache in
1431 * order to detect refaults, thus thrashing, later on.
1432 *
1433 * But don't store shadows in an address space that is
238c3046 1434 * already exiting. This is not just an optimization,
a528910e
JW
1435 * inode reclaim needs to empty out the radix tree or
1436 * the nodes are lost. Don't plant shadows behind its
1437 * back.
f9fe48be
RZ
1438 *
1439 * We also don't store shadows for DAX mappings because the
49fd9b6d 1440 * only page cache folios found in these are zero pages
f9fe48be
RZ
1441 * covering holes, and because we don't want to mix DAX
1442 * exceptional entries and shadow exceptional entries in the
b93b0163 1443 * same address_space.
a528910e 1444 */
be7c07d6 1445 if (reclaimed && folio_is_file_lru(folio) &&
f9fe48be 1446 !mapping_exiting(mapping) && !dax_mapping(mapping))
8927f647
MWO
1447 shadow = workingset_eviction(folio, target_memcg);
1448 __filemap_remove_folio(folio, shadow);
30472509 1449 xa_unlock_irq(&mapping->i_pages);
51b8c1fe
JW
1450 if (mapping_shrinkable(mapping))
1451 inode_add_lru(mapping->host);
1452 spin_unlock(&mapping->host->i_lock);
6072d13c 1453
d2329aa0
MWO
1454 if (free_folio)
1455 free_folio(folio);
49d2e9cc
CL
1456 }
1457
49d2e9cc
CL
1458 return 1;
1459
1460cannot_free:
30472509 1461 xa_unlock_irq(&mapping->i_pages);
be7c07d6 1462 if (!folio_test_swapcache(folio))
51b8c1fe 1463 spin_unlock(&mapping->host->i_lock);
49d2e9cc
CL
1464 return 0;
1465}
1466
5100da38
MWO
1467/**
1468 * remove_mapping() - Attempt to remove a folio from its mapping.
1469 * @mapping: The address space.
1470 * @folio: The folio to remove.
1471 *
1472 * If the folio is dirty, under writeback or if someone else has a ref
1473 * on it, removal will fail.
1474 * Return: The number of pages removed from the mapping. 0 if the folio
1475 * could not be removed.
1476 * Context: The caller should have a single refcount on the folio and
1477 * hold its lock.
e286781d 1478 */
5100da38 1479long remove_mapping(struct address_space *mapping, struct folio *folio)
e286781d 1480{
be7c07d6 1481 if (__remove_mapping(mapping, folio, false, NULL)) {
e286781d 1482 /*
5100da38 1483 * Unfreezing the refcount with 1 effectively
e286781d
NP
1484 * drops the pagecache ref for us without requiring another
1485 * atomic operation.
1486 */
be7c07d6 1487 folio_ref_unfreeze(folio, 1);
5100da38 1488 return folio_nr_pages(folio);
e286781d
NP
1489 }
1490 return 0;
1491}
1492
894bc310 1493/**
ca6d60f3
MWO
1494 * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1495 * @folio: Folio to be returned to an LRU list.
894bc310 1496 *
ca6d60f3
MWO
1497 * Add previously isolated @folio to appropriate LRU list.
1498 * The folio may still be unevictable for other reasons.
894bc310 1499 *
ca6d60f3 1500 * Context: lru_lock must not be held, interrupts must be enabled.
894bc310 1501 */
ca6d60f3 1502void folio_putback_lru(struct folio *folio)
894bc310 1503{
ca6d60f3
MWO
1504 folio_add_lru(folio);
1505 folio_put(folio); /* drop ref from isolate */
894bc310
LS
1506}
1507
49fd9b6d
MWO
1508enum folio_references {
1509 FOLIOREF_RECLAIM,
1510 FOLIOREF_RECLAIM_CLEAN,
1511 FOLIOREF_KEEP,
1512 FOLIOREF_ACTIVATE,
dfc8d636
JW
1513};
1514
49fd9b6d 1515static enum folio_references folio_check_references(struct folio *folio,
dfc8d636
JW
1516 struct scan_control *sc)
1517{
d92013d1 1518 int referenced_ptes, referenced_folio;
dfc8d636 1519 unsigned long vm_flags;
dfc8d636 1520
b3ac0413
MWO
1521 referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1522 &vm_flags);
d92013d1 1523 referenced_folio = folio_test_clear_referenced(folio);
dfc8d636 1524
dfc8d636 1525 /*
d92013d1
MWO
1526 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1527 * Let the folio, now marked Mlocked, be moved to the unevictable list.
dfc8d636
JW
1528 */
1529 if (vm_flags & VM_LOCKED)
49fd9b6d 1530 return FOLIOREF_ACTIVATE;
dfc8d636 1531
6d4675e6
MK
1532 /* rmap lock contention: rotate */
1533 if (referenced_ptes == -1)
49fd9b6d 1534 return FOLIOREF_KEEP;
6d4675e6 1535
64574746 1536 if (referenced_ptes) {
64574746 1537 /*
d92013d1 1538 * All mapped folios start out with page table
64574746 1539 * references from the instantiating fault, so we need
9030fb0b 1540 * to look twice if a mapped file/anon folio is used more
64574746
JW
1541 * than once.
1542 *
1543 * Mark it and spare it for another trip around the
1544 * inactive list. Another page table reference will
1545 * lead to its activation.
1546 *
d92013d1
MWO
1547 * Note: the mark is set for activated folios as well
1548 * so that recently deactivated but used folios are
64574746
JW
1549 * quickly recovered.
1550 */
d92013d1 1551 folio_set_referenced(folio);
64574746 1552
d92013d1 1553 if (referenced_folio || referenced_ptes > 1)
49fd9b6d 1554 return FOLIOREF_ACTIVATE;
64574746 1555
c909e993 1556 /*
d92013d1 1557 * Activate file-backed executable folios after first usage.
c909e993 1558 */
f19a27e3 1559 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
49fd9b6d 1560 return FOLIOREF_ACTIVATE;
c909e993 1561
49fd9b6d 1562 return FOLIOREF_KEEP;
64574746 1563 }
dfc8d636 1564
d92013d1 1565 /* Reclaim if clean, defer dirty folios to writeback */
f19a27e3 1566 if (referenced_folio && folio_is_file_lru(folio))
49fd9b6d 1567 return FOLIOREF_RECLAIM_CLEAN;
64574746 1568
49fd9b6d 1569 return FOLIOREF_RECLAIM;
dfc8d636
JW
1570}
1571
49fd9b6d 1572/* Check if a folio is dirty or under writeback */
e20c41b1 1573static void folio_check_dirty_writeback(struct folio *folio,
e2be15f6
MG
1574 bool *dirty, bool *writeback)
1575{
b4597226
MG
1576 struct address_space *mapping;
1577
e2be15f6 1578 /*
49fd9b6d 1579 * Anonymous folios are not handled by flushers and must be written
32a331a7 1580 * from reclaim context. Do not stall reclaim based on them.
49fd9b6d 1581 * MADV_FREE anonymous folios are put into inactive file list too.
32a331a7
ML
1582 * They could be mistakenly treated as file lru. So further anon
1583 * test is needed.
e2be15f6 1584 */
e20c41b1
MWO
1585 if (!folio_is_file_lru(folio) ||
1586 (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
e2be15f6
MG
1587 *dirty = false;
1588 *writeback = false;
1589 return;
1590 }
1591
e20c41b1
MWO
1592 /* By default assume that the folio flags are accurate */
1593 *dirty = folio_test_dirty(folio);
1594 *writeback = folio_test_writeback(folio);
b4597226
MG
1595
1596 /* Verify dirty/writeback state if the filesystem supports it */
e20c41b1 1597 if (!folio_test_private(folio))
b4597226
MG
1598 return;
1599
e20c41b1 1600 mapping = folio_mapping(folio);
b4597226 1601 if (mapping && mapping->a_ops->is_dirty_writeback)
520f301c 1602 mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
e2be15f6
MG
1603}
1604
32008027 1605static struct page *alloc_demote_page(struct page *page, unsigned long private)
26aa2d19 1606{
32008027
JG
1607 struct page *target_page;
1608 nodemask_t *allowed_mask;
1609 struct migration_target_control *mtc;
1610
1611 mtc = (struct migration_target_control *)private;
1612
1613 allowed_mask = mtc->nmask;
1614 /*
1615 * make sure we allocate from the target node first also trying to
1616 * demote or reclaim pages from the target node via kswapd if we are
1617 * low on free memory on target node. If we don't do this and if
1618 * we have free memory on the slower(lower) memtier, we would start
1619 * allocating pages from slower(lower) memory tiers without even forcing
1620 * a demotion of cold pages from the target memtier. This can result
1621 * in the kernel placing hot pages in slower(lower) memory tiers.
1622 */
1623 mtc->nmask = NULL;
1624 mtc->gfp_mask |= __GFP_THISNODE;
1625 target_page = alloc_migration_target(page, (unsigned long)mtc);
1626 if (target_page)
1627 return target_page;
26aa2d19 1628
32008027
JG
1629 mtc->gfp_mask &= ~__GFP_THISNODE;
1630 mtc->nmask = allowed_mask;
1631
1632 return alloc_migration_target(page, (unsigned long)mtc);
26aa2d19
DH
1633}
1634
1635/*
49fd9b6d
MWO
1636 * Take folios on @demote_folios and attempt to demote them to another node.
1637 * Folios which are not demoted are left on @demote_folios.
26aa2d19 1638 */
49fd9b6d 1639static unsigned int demote_folio_list(struct list_head *demote_folios,
26aa2d19
DH
1640 struct pglist_data *pgdat)
1641{
1642 int target_nid = next_demotion_node(pgdat->node_id);
1643 unsigned int nr_succeeded;
32008027
JG
1644 nodemask_t allowed_mask;
1645
1646 struct migration_target_control mtc = {
1647 /*
1648 * Allocate from 'node', or fail quickly and quietly.
1649 * When this happens, 'page' will likely just be discarded
1650 * instead of migrated.
1651 */
1652 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1653 __GFP_NOMEMALLOC | GFP_NOWAIT,
1654 .nid = target_nid,
1655 .nmask = &allowed_mask
1656 };
26aa2d19 1657
49fd9b6d 1658 if (list_empty(demote_folios))
26aa2d19
DH
1659 return 0;
1660
1661 if (target_nid == NUMA_NO_NODE)
1662 return 0;
1663
32008027
JG
1664 node_get_allowed_targets(pgdat, &allowed_mask);
1665
26aa2d19 1666 /* Demotion ignores all cpuset and mempolicy settings */
49fd9b6d 1667 migrate_pages(demote_folios, alloc_demote_page, NULL,
32008027
JG
1668 (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1669 &nr_succeeded);
26aa2d19 1670
57e9cc50 1671 __count_vm_events(PGDEMOTE_KSWAPD + reclaimer_offset(), nr_succeeded);
668e4147 1672
26aa2d19
DH
1673 return nr_succeeded;
1674}
1675
c28a0e96 1676static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
d791ea67
N
1677{
1678 if (gfp_mask & __GFP_FS)
1679 return true;
c28a0e96 1680 if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
d791ea67
N
1681 return false;
1682 /*
1683 * We can "enter_fs" for swap-cache with only __GFP_IO
1684 * providing this isn't SWP_FS_OPS.
1685 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1686 * but that will never affect SWP_FS_OPS, so the data_race
1687 * is safe.
1688 */
b98c359f 1689 return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
d791ea67
N
1690}
1691
1da177e4 1692/*
49fd9b6d 1693 * shrink_folio_list() returns the number of reclaimed pages
1da177e4 1694 */
49fd9b6d
MWO
1695static unsigned int shrink_folio_list(struct list_head *folio_list,
1696 struct pglist_data *pgdat, struct scan_control *sc,
1697 struct reclaim_stat *stat, bool ignore_references)
1698{
1699 LIST_HEAD(ret_folios);
1700 LIST_HEAD(free_folios);
1701 LIST_HEAD(demote_folios);
730ec8c0
MS
1702 unsigned int nr_reclaimed = 0;
1703 unsigned int pgactivate = 0;
26aa2d19 1704 bool do_demote_pass;
2282679f 1705 struct swap_iocb *plug = NULL;
1da177e4 1706
060f005f 1707 memset(stat, 0, sizeof(*stat));
1da177e4 1708 cond_resched();
26aa2d19 1709 do_demote_pass = can_demote(pgdat->node_id, sc);
1da177e4 1710
26aa2d19 1711retry:
49fd9b6d 1712 while (!list_empty(folio_list)) {
1da177e4 1713 struct address_space *mapping;
be7c07d6 1714 struct folio *folio;
49fd9b6d 1715 enum folio_references references = FOLIOREF_RECLAIM;
d791ea67 1716 bool dirty, writeback;
98879b3b 1717 unsigned int nr_pages;
1da177e4
LT
1718
1719 cond_resched();
1720
49fd9b6d 1721 folio = lru_to_folio(folio_list);
be7c07d6 1722 list_del(&folio->lru);
1da177e4 1723
c28a0e96 1724 if (!folio_trylock(folio))
1da177e4
LT
1725 goto keep;
1726
c28a0e96 1727 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1da177e4 1728
c28a0e96 1729 nr_pages = folio_nr_pages(folio);
98879b3b 1730
c28a0e96 1731 /* Account the number of base pages */
98879b3b 1732 sc->nr_scanned += nr_pages;
80e43426 1733
c28a0e96 1734 if (unlikely(!folio_evictable(folio)))
ad6b6704 1735 goto activate_locked;
894bc310 1736
1bee2c16 1737 if (!sc->may_unmap && folio_mapped(folio))
80e43426
CL
1738 goto keep_locked;
1739
018ee47f
YZ
1740 /* folio_update_gen() tried to promote this page? */
1741 if (lru_gen_enabled() && !ignore_references &&
1742 folio_mapped(folio) && folio_test_referenced(folio))
1743 goto keep_locked;
1744
e2be15f6 1745 /*
894befec 1746 * The number of dirty pages determines if a node is marked
8cd7c588 1747 * reclaim_congested. kswapd will stall and start writing
c28a0e96 1748 * folios if the tail of the LRU is all dirty unqueued folios.
e2be15f6 1749 */
e20c41b1 1750 folio_check_dirty_writeback(folio, &dirty, &writeback);
e2be15f6 1751 if (dirty || writeback)
c79b7b96 1752 stat->nr_dirty += nr_pages;
e2be15f6
MG
1753
1754 if (dirty && !writeback)
c79b7b96 1755 stat->nr_unqueued_dirty += nr_pages;
e2be15f6 1756
d04e8acd 1757 /*
c28a0e96
MWO
1758 * Treat this folio as congested if folios are cycling
1759 * through the LRU so quickly that the folios marked
1760 * for immediate reclaim are making it to the end of
1761 * the LRU a second time.
d04e8acd 1762 */
c28a0e96 1763 if (writeback && folio_test_reclaim(folio))
c79b7b96 1764 stat->nr_congested += nr_pages;
e2be15f6 1765
283aba9f 1766 /*
d33e4e14 1767 * If a folio at the tail of the LRU is under writeback, there
283aba9f
MG
1768 * are three cases to consider.
1769 *
c28a0e96
MWO
1770 * 1) If reclaim is encountering an excessive number
1771 * of folios under writeback and this folio has both
1772 * the writeback and reclaim flags set, then it
d33e4e14
MWO
1773 * indicates that folios are being queued for I/O but
1774 * are being recycled through the LRU before the I/O
1775 * can complete. Waiting on the folio itself risks an
1776 * indefinite stall if it is impossible to writeback
1777 * the folio due to I/O error or disconnected storage
1778 * so instead note that the LRU is being scanned too
1779 * quickly and the caller can stall after the folio
1780 * list has been processed.
283aba9f 1781 *
d33e4e14 1782 * 2) Global or new memcg reclaim encounters a folio that is
ecf5fc6e
MH
1783 * not marked for immediate reclaim, or the caller does not
1784 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
d33e4e14 1785 * not to fs). In this case mark the folio for immediate
97c9341f 1786 * reclaim and continue scanning.
283aba9f 1787 *
d791ea67 1788 * Require may_enter_fs() because we would wait on fs, which
d33e4e14
MWO
1789 * may not have submitted I/O yet. And the loop driver might
1790 * enter reclaim, and deadlock if it waits on a folio for
283aba9f
MG
1791 * which it is needed to do the write (loop masks off
1792 * __GFP_IO|__GFP_FS for this reason); but more thought
1793 * would probably show more reasons.
1794 *
d33e4e14
MWO
1795 * 3) Legacy memcg encounters a folio that already has the
1796 * reclaim flag set. memcg does not have any dirty folio
283aba9f 1797 * throttling so we could easily OOM just because too many
d33e4e14 1798 * folios are in writeback and there is nothing else to
283aba9f 1799 * reclaim. Wait for the writeback to complete.
c55e8d03 1800 *
d33e4e14
MWO
1801 * In cases 1) and 2) we activate the folios to get them out of
1802 * the way while we continue scanning for clean folios on the
c55e8d03
JW
1803 * inactive list and refilling from the active list. The
1804 * observation here is that waiting for disk writes is more
1805 * expensive than potentially causing reloads down the line.
1806 * Since they're marked for immediate reclaim, they won't put
1807 * memory pressure on the cache working set any longer than it
1808 * takes to write them to disk.
283aba9f 1809 */
d33e4e14 1810 if (folio_test_writeback(folio)) {
283aba9f
MG
1811 /* Case 1 above */
1812 if (current_is_kswapd() &&
d33e4e14 1813 folio_test_reclaim(folio) &&
599d0c95 1814 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
c79b7b96 1815 stat->nr_immediate += nr_pages;
c55e8d03 1816 goto activate_locked;
283aba9f
MG
1817
1818 /* Case 2 above */
b5ead35e 1819 } else if (writeback_throttling_sane(sc) ||
d33e4e14 1820 !folio_test_reclaim(folio) ||
c28a0e96 1821 !may_enter_fs(folio, sc->gfp_mask)) {
c3b94f44 1822 /*
d33e4e14 1823 * This is slightly racy -
c28a0e96
MWO
1824 * folio_end_writeback() might have
1825 * just cleared the reclaim flag, then
1826 * setting the reclaim flag here ends up
1827 * interpreted as the readahead flag - but
1828 * that does not matter enough to care.
1829 * What we do want is for this folio to
1830 * have the reclaim flag set next time
1831 * memcg reclaim reaches the tests above,
1832 * so it will then wait for writeback to
1833 * avoid OOM; and it's also appropriate
d33e4e14 1834 * in global reclaim.
c3b94f44 1835 */
d33e4e14 1836 folio_set_reclaim(folio);
c79b7b96 1837 stat->nr_writeback += nr_pages;
c55e8d03 1838 goto activate_locked;
283aba9f
MG
1839
1840 /* Case 3 above */
1841 } else {
d33e4e14
MWO
1842 folio_unlock(folio);
1843 folio_wait_writeback(folio);
1844 /* then go back and try same folio again */
49fd9b6d 1845 list_add_tail(&folio->lru, folio_list);
7fadc820 1846 continue;
e62e384e 1847 }
c661b078 1848 }
1da177e4 1849
8940b34a 1850 if (!ignore_references)
d92013d1 1851 references = folio_check_references(folio, sc);
02c6de8d 1852
dfc8d636 1853 switch (references) {
49fd9b6d 1854 case FOLIOREF_ACTIVATE:
1da177e4 1855 goto activate_locked;
49fd9b6d 1856 case FOLIOREF_KEEP:
98879b3b 1857 stat->nr_ref_keep += nr_pages;
64574746 1858 goto keep_locked;
49fd9b6d
MWO
1859 case FOLIOREF_RECLAIM:
1860 case FOLIOREF_RECLAIM_CLEAN:
c28a0e96 1861 ; /* try to reclaim the folio below */
dfc8d636 1862 }
1da177e4 1863
26aa2d19 1864 /*
c28a0e96 1865 * Before reclaiming the folio, try to relocate
26aa2d19
DH
1866 * its contents to another node.
1867 */
1868 if (do_demote_pass &&
c28a0e96 1869 (thp_migration_supported() || !folio_test_large(folio))) {
49fd9b6d 1870 list_add(&folio->lru, &demote_folios);
c28a0e96 1871 folio_unlock(folio);
26aa2d19
DH
1872 continue;
1873 }
1874
1da177e4
LT
1875 /*
1876 * Anonymous process memory has backing store?
1877 * Try to allocate it some swap space here.
c28a0e96 1878 * Lazyfree folio could be freed directly
1da177e4 1879 */
c28a0e96
MWO
1880 if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1881 if (!folio_test_swapcache(folio)) {
bd4c82c2
HY
1882 if (!(sc->gfp_mask & __GFP_IO))
1883 goto keep_locked;
d4b4084a 1884 if (folio_maybe_dma_pinned(folio))
feb889fb 1885 goto keep_locked;
c28a0e96
MWO
1886 if (folio_test_large(folio)) {
1887 /* cannot split folio, skip it */
d4b4084a 1888 if (!can_split_folio(folio, NULL))
bd4c82c2
HY
1889 goto activate_locked;
1890 /*
c28a0e96 1891 * Split folios without a PMD map right
bd4c82c2
HY
1892 * away. Chances are some or all of the
1893 * tail pages can be freed without IO.
1894 */
d4b4084a 1895 if (!folio_entire_mapcount(folio) &&
346cf613 1896 split_folio_to_list(folio,
49fd9b6d 1897 folio_list))
bd4c82c2
HY
1898 goto activate_locked;
1899 }
09c02e56
MWO
1900 if (!add_to_swap(folio)) {
1901 if (!folio_test_large(folio))
98879b3b 1902 goto activate_locked_split;
bd4c82c2 1903 /* Fallback to swap normal pages */
346cf613 1904 if (split_folio_to_list(folio,
49fd9b6d 1905 folio_list))
bd4c82c2 1906 goto activate_locked;
fe490cc0
HY
1907#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1908 count_vm_event(THP_SWPOUT_FALLBACK);
1909#endif
09c02e56 1910 if (!add_to_swap(folio))
98879b3b 1911 goto activate_locked_split;
bd4c82c2 1912 }
bd4c82c2 1913 }
c28a0e96
MWO
1914 } else if (folio_test_swapbacked(folio) &&
1915 folio_test_large(folio)) {
1916 /* Split shmem folio */
49fd9b6d 1917 if (split_folio_to_list(folio, folio_list))
7751b2da 1918 goto keep_locked;
e2be15f6 1919 }
1da177e4 1920
98879b3b 1921 /*
c28a0e96
MWO
1922 * If the folio was split above, the tail pages will make
1923 * their own pass through this function and be accounted
1924 * then.
98879b3b 1925 */
c28a0e96 1926 if ((nr_pages > 1) && !folio_test_large(folio)) {
98879b3b
YS
1927 sc->nr_scanned -= (nr_pages - 1);
1928 nr_pages = 1;
1929 }
1930
1da177e4 1931 /*
1bee2c16 1932 * The folio is mapped into the page tables of one or more
1da177e4
LT
1933 * processes. Try to unmap it here.
1934 */
1bee2c16 1935 if (folio_mapped(folio)) {
013339df 1936 enum ttu_flags flags = TTU_BATCH_FLUSH;
1bee2c16 1937 bool was_swapbacked = folio_test_swapbacked(folio);
bd4c82c2 1938
1bee2c16 1939 if (folio_test_pmd_mappable(folio))
bd4c82c2 1940 flags |= TTU_SPLIT_HUGE_PMD;
1f318a9b 1941
869f7ee6 1942 try_to_unmap(folio, flags);
1bee2c16 1943 if (folio_mapped(folio)) {
98879b3b 1944 stat->nr_unmap_fail += nr_pages;
1bee2c16
MWO
1945 if (!was_swapbacked &&
1946 folio_test_swapbacked(folio))
1f318a9b 1947 stat->nr_lazyfree_fail += nr_pages;
1da177e4 1948 goto activate_locked;
1da177e4
LT
1949 }
1950 }
1951
d824ec2a
JK
1952 /*
1953 * Folio is unmapped now so it cannot be newly pinned anymore.
1954 * No point in trying to reclaim folio if it is pinned.
1955 * Furthermore we don't want to reclaim underlying fs metadata
1956 * if the folio is pinned and thus potentially modified by the
1957 * pinning process as that may upset the filesystem.
1958 */
1959 if (folio_maybe_dma_pinned(folio))
1960 goto activate_locked;
1961
5441d490 1962 mapping = folio_mapping(folio);
49bd2bf9 1963 if (folio_test_dirty(folio)) {
ee72886d 1964 /*
49bd2bf9 1965 * Only kswapd can writeback filesystem folios
4eda4823 1966 * to avoid risk of stack overflow. But avoid
49bd2bf9 1967 * injecting inefficient single-folio I/O into
4eda4823 1968 * flusher writeback as much as possible: only
49bd2bf9
MWO
1969 * write folios when we've encountered many
1970 * dirty folios, and when we've already scanned
1971 * the rest of the LRU for clean folios and see
1972 * the same dirty folios again (with the reclaim
1973 * flag set).
ee72886d 1974 */
49bd2bf9
MWO
1975 if (folio_is_file_lru(folio) &&
1976 (!current_is_kswapd() ||
1977 !folio_test_reclaim(folio) ||
4eda4823 1978 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
49ea7eb6
MG
1979 /*
1980 * Immediately reclaim when written back.
5a9e3474 1981 * Similar in principle to folio_deactivate()
49bd2bf9 1982 * except we already have the folio isolated
49ea7eb6
MG
1983 * and know it's dirty
1984 */
49bd2bf9
MWO
1985 node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1986 nr_pages);
1987 folio_set_reclaim(folio);
49ea7eb6 1988
c55e8d03 1989 goto activate_locked;
ee72886d
MG
1990 }
1991
49fd9b6d 1992 if (references == FOLIOREF_RECLAIM_CLEAN)
1da177e4 1993 goto keep_locked;
c28a0e96 1994 if (!may_enter_fs(folio, sc->gfp_mask))
1da177e4 1995 goto keep_locked;
52a8363e 1996 if (!sc->may_writepage)
1da177e4
LT
1997 goto keep_locked;
1998
d950c947 1999 /*
49bd2bf9
MWO
2000 * Folio is dirty. Flush the TLB if a writable entry
2001 * potentially exists to avoid CPU writes after I/O
d950c947
MG
2002 * starts and then write it out here.
2003 */
2004 try_to_unmap_flush_dirty();
2282679f 2005 switch (pageout(folio, mapping, &plug)) {
1da177e4
LT
2006 case PAGE_KEEP:
2007 goto keep_locked;
2008 case PAGE_ACTIVATE:
2009 goto activate_locked;
2010 case PAGE_SUCCESS:
c79b7b96 2011 stat->nr_pageout += nr_pages;
96f8bf4f 2012
49bd2bf9 2013 if (folio_test_writeback(folio))
41ac1999 2014 goto keep;
49bd2bf9 2015 if (folio_test_dirty(folio))
1da177e4 2016 goto keep;
7d3579e8 2017
1da177e4
LT
2018 /*
2019 * A synchronous write - probably a ramdisk. Go
49bd2bf9 2020 * ahead and try to reclaim the folio.
1da177e4 2021 */
49bd2bf9 2022 if (!folio_trylock(folio))
1da177e4 2023 goto keep;
49bd2bf9
MWO
2024 if (folio_test_dirty(folio) ||
2025 folio_test_writeback(folio))
1da177e4 2026 goto keep_locked;
49bd2bf9 2027 mapping = folio_mapping(folio);
01359eb2 2028 fallthrough;
1da177e4 2029 case PAGE_CLEAN:
49bd2bf9 2030 ; /* try to free the folio below */
1da177e4
LT
2031 }
2032 }
2033
2034 /*
0a36111c
MWO
2035 * If the folio has buffers, try to free the buffer
2036 * mappings associated with this folio. If we succeed
2037 * we try to free the folio as well.
1da177e4 2038 *
0a36111c
MWO
2039 * We do this even if the folio is dirty.
2040 * filemap_release_folio() does not perform I/O, but it
2041 * is possible for a folio to have the dirty flag set,
2042 * but it is actually clean (all its buffers are clean).
2043 * This happens if the buffers were written out directly,
2044 * with submit_bh(). ext3 will do this, as well as
2045 * the blockdev mapping. filemap_release_folio() will
2046 * discover that cleanness and will drop the buffers
2047 * and mark the folio clean - it can be freed.
1da177e4 2048 *
0a36111c
MWO
2049 * Rarely, folios can have buffers and no ->mapping.
2050 * These are the folios which were not successfully
2051 * invalidated in truncate_cleanup_folio(). We try to
2052 * drop those buffers here and if that worked, and the
2053 * folio is no longer mapped into process address space
2054 * (refcount == 1) it can be freed. Otherwise, leave
2055 * the folio on the LRU so it is swappable.
1da177e4 2056 */
0a36111c
MWO
2057 if (folio_has_private(folio)) {
2058 if (!filemap_release_folio(folio, sc->gfp_mask))
1da177e4 2059 goto activate_locked;
0a36111c
MWO
2060 if (!mapping && folio_ref_count(folio) == 1) {
2061 folio_unlock(folio);
2062 if (folio_put_testzero(folio))
e286781d
NP
2063 goto free_it;
2064 else {
2065 /*
2066 * rare race with speculative reference.
2067 * the speculative reference will free
0a36111c 2068 * this folio shortly, so we may
e286781d
NP
2069 * increment nr_reclaimed here (and
2070 * leave it off the LRU).
2071 */
9aafcffc 2072 nr_reclaimed += nr_pages;
e286781d
NP
2073 continue;
2074 }
2075 }
1da177e4
LT
2076 }
2077
64daa5d8 2078 if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
802a3a92 2079 /* follow __remove_mapping for reference */
64daa5d8 2080 if (!folio_ref_freeze(folio, 1))
802a3a92 2081 goto keep_locked;
d17be2d9 2082 /*
64daa5d8 2083 * The folio has only one reference left, which is
d17be2d9 2084 * from the isolation. After the caller puts the
64daa5d8
MWO
2085 * folio back on the lru and drops the reference, the
2086 * folio will be freed anyway. It doesn't matter
2087 * which lru it goes on. So we don't bother checking
2088 * the dirty flag here.
d17be2d9 2089 */
64daa5d8
MWO
2090 count_vm_events(PGLAZYFREED, nr_pages);
2091 count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
be7c07d6 2092 } else if (!mapping || !__remove_mapping(mapping, folio, true,
b910718a 2093 sc->target_mem_cgroup))
802a3a92 2094 goto keep_locked;
9a1ea439 2095
c28a0e96 2096 folio_unlock(folio);
e286781d 2097free_it:
98879b3b 2098 /*
c28a0e96
MWO
2099 * Folio may get swapped out as a whole, need to account
2100 * all pages in it.
98879b3b
YS
2101 */
2102 nr_reclaimed += nr_pages;
abe4c3b5
MG
2103
2104 /*
49fd9b6d 2105 * Is there need to periodically free_folio_list? It would
abe4c3b5
MG
2106 * appear not as the counts should be low
2107 */
c28a0e96 2108 if (unlikely(folio_test_large(folio)))
5375336c 2109 destroy_large_folio(folio);
7ae88534 2110 else
49fd9b6d 2111 list_add(&folio->lru, &free_folios);
1da177e4
LT
2112 continue;
2113
98879b3b
YS
2114activate_locked_split:
2115 /*
2116 * The tail pages that are failed to add into swap cache
2117 * reach here. Fixup nr_scanned and nr_pages.
2118 */
2119 if (nr_pages > 1) {
2120 sc->nr_scanned -= (nr_pages - 1);
2121 nr_pages = 1;
2122 }
1da177e4 2123activate_locked:
68a22394 2124 /* Not a candidate for swapping, so reclaim swap space. */
246b6480 2125 if (folio_test_swapcache(folio) &&
9202d527 2126 (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
bdb0ed54 2127 folio_free_swap(folio);
246b6480
MWO
2128 VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2129 if (!folio_test_mlocked(folio)) {
2130 int type = folio_is_file_lru(folio);
2131 folio_set_active(folio);
98879b3b 2132 stat->nr_activate[type] += nr_pages;
246b6480 2133 count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
ad6b6704 2134 }
1da177e4 2135keep_locked:
c28a0e96 2136 folio_unlock(folio);
1da177e4 2137keep:
49fd9b6d 2138 list_add(&folio->lru, &ret_folios);
c28a0e96
MWO
2139 VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2140 folio_test_unevictable(folio), folio);
1da177e4 2141 }
49fd9b6d 2142 /* 'folio_list' is always empty here */
26aa2d19 2143
c28a0e96 2144 /* Migrate folios selected for demotion */
49fd9b6d
MWO
2145 nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
2146 /* Folios that could not be demoted are still in @demote_folios */
2147 if (!list_empty(&demote_folios)) {
6b426d07 2148 /* Folios which weren't demoted go back on @folio_list */
49fd9b6d 2149 list_splice_init(&demote_folios, folio_list);
6b426d07
MA
2150
2151 /*
2152 * goto retry to reclaim the undemoted folios in folio_list if
2153 * desired.
2154 *
2155 * Reclaiming directly from top tier nodes is not often desired
2156 * due to it breaking the LRU ordering: in general memory
2157 * should be reclaimed from lower tier nodes and demoted from
2158 * top tier nodes.
2159 *
2160 * However, disabling reclaim from top tier nodes entirely
2161 * would cause ooms in edge scenarios where lower tier memory
2162 * is unreclaimable for whatever reason, eg memory being
2163 * mlocked or too hot to reclaim. We can disable reclaim
2164 * from top tier nodes in proactive reclaim though as that is
2165 * not real memory pressure.
2166 */
2167 if (!sc->proactive) {
2168 do_demote_pass = false;
2169 goto retry;
2170 }
26aa2d19 2171 }
abe4c3b5 2172
98879b3b
YS
2173 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2174
49fd9b6d 2175 mem_cgroup_uncharge_list(&free_folios);
72b252ae 2176 try_to_unmap_flush();
49fd9b6d 2177 free_unref_page_list(&free_folios);
abe4c3b5 2178
49fd9b6d 2179 list_splice(&ret_folios, folio_list);
886cf190 2180 count_vm_events(PGACTIVATE, pgactivate);
060f005f 2181
2282679f
N
2182 if (plug)
2183 swap_write_unplug(plug);
05ff5137 2184 return nr_reclaimed;
1da177e4
LT
2185}
2186
730ec8c0 2187unsigned int reclaim_clean_pages_from_list(struct zone *zone,
49fd9b6d 2188 struct list_head *folio_list)
02c6de8d
MK
2189{
2190 struct scan_control sc = {
2191 .gfp_mask = GFP_KERNEL,
02c6de8d
MK
2192 .may_unmap = 1,
2193 };
1f318a9b 2194 struct reclaim_stat stat;
730ec8c0 2195 unsigned int nr_reclaimed;
b8cecb93
MWO
2196 struct folio *folio, *next;
2197 LIST_HEAD(clean_folios);
2d2b8d2b 2198 unsigned int noreclaim_flag;
02c6de8d 2199
b8cecb93
MWO
2200 list_for_each_entry_safe(folio, next, folio_list, lru) {
2201 if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2202 !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2203 !folio_test_unevictable(folio)) {
2204 folio_clear_active(folio);
2205 list_move(&folio->lru, &clean_folios);
02c6de8d
MK
2206 }
2207 }
2208
2d2b8d2b
YZ
2209 /*
2210 * We should be safe here since we are only dealing with file pages and
2211 * we are not kswapd and therefore cannot write dirty file pages. But
2212 * call memalloc_noreclaim_save() anyway, just in case these conditions
2213 * change in the future.
2214 */
2215 noreclaim_flag = memalloc_noreclaim_save();
49fd9b6d 2216 nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
013339df 2217 &stat, true);
2d2b8d2b
YZ
2218 memalloc_noreclaim_restore(noreclaim_flag);
2219
b8cecb93 2220 list_splice(&clean_folios, folio_list);
2da9f630
NP
2221 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2222 -(long)nr_reclaimed);
1f318a9b
JK
2223 /*
2224 * Since lazyfree pages are isolated from file LRU from the beginning,
2225 * they will rotate back to anonymous LRU in the end if it failed to
2226 * discard so isolated count will be mismatched.
2227 * Compensate the isolated count for both LRU lists.
2228 */
2229 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2230 stat.nr_lazyfree_fail);
2231 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2da9f630 2232 -(long)stat.nr_lazyfree_fail);
1f318a9b 2233 return nr_reclaimed;
02c6de8d
MK
2234}
2235
7ee36a14
MG
2236/*
2237 * Update LRU sizes after isolating pages. The LRU size updates must
55b65a57 2238 * be complete before mem_cgroup_update_lru_size due to a sanity check.
7ee36a14
MG
2239 */
2240static __always_inline void update_lru_sizes(struct lruvec *lruvec,
b4536f0c 2241 enum lru_list lru, unsigned long *nr_zone_taken)
7ee36a14 2242{
7ee36a14
MG
2243 int zid;
2244
7ee36a14
MG
2245 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2246 if (!nr_zone_taken[zid])
2247 continue;
2248
a892cb6b 2249 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
b4536f0c
MH
2250 }
2251
7ee36a14
MG
2252}
2253
f611fab7 2254/*
15b44736
HD
2255 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2256 *
2257 * lruvec->lru_lock is heavily contended. Some of the functions that
1da177e4
LT
2258 * shrink the lists perform better by taking out a batch of pages
2259 * and working on them outside the LRU lock.
2260 *
2261 * For pagecache intensive workloads, this function is the hottest
2262 * spot in the kernel (apart from copy_*_user functions).
2263 *
15b44736 2264 * Lru_lock must be held before calling this function.
1da177e4 2265 *
791b48b6 2266 * @nr_to_scan: The number of eligible pages to look through on the list.
5dc35979 2267 * @lruvec: The LRU vector to pull pages from.
1da177e4 2268 * @dst: The temp list to put pages on to.
f626012d 2269 * @nr_scanned: The number of pages that were scanned.
fe2c2a10 2270 * @sc: The scan_control struct for this reclaim session
3cb99451 2271 * @lru: LRU list id for isolating
1da177e4
LT
2272 *
2273 * returns how many pages were moved onto *@dst.
2274 */
49fd9b6d 2275static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
5dc35979 2276 struct lruvec *lruvec, struct list_head *dst,
fe2c2a10 2277 unsigned long *nr_scanned, struct scan_control *sc,
a9e7c39f 2278 enum lru_list lru)
1da177e4 2279{
75b00af7 2280 struct list_head *src = &lruvec->lists[lru];
69e05944 2281 unsigned long nr_taken = 0;
599d0c95 2282 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
7cc30fcf 2283 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
3db65812 2284 unsigned long skipped = 0;
791b48b6 2285 unsigned long scan, total_scan, nr_pages;
166e3d32 2286 LIST_HEAD(folios_skipped);
1da177e4 2287
98879b3b 2288 total_scan = 0;
791b48b6 2289 scan = 0;
98879b3b 2290 while (scan < nr_to_scan && !list_empty(src)) {
89f6c88a 2291 struct list_head *move_to = src;
166e3d32 2292 struct folio *folio;
5ad333eb 2293
166e3d32
MWO
2294 folio = lru_to_folio(src);
2295 prefetchw_prev_lru_folio(folio, src, flags);
1da177e4 2296
166e3d32 2297 nr_pages = folio_nr_pages(folio);
98879b3b
YS
2298 total_scan += nr_pages;
2299
166e3d32
MWO
2300 if (folio_zonenum(folio) > sc->reclaim_idx) {
2301 nr_skipped[folio_zonenum(folio)] += nr_pages;
2302 move_to = &folios_skipped;
89f6c88a 2303 goto move;
b2e18757
MG
2304 }
2305
791b48b6 2306 /*
166e3d32
MWO
2307 * Do not count skipped folios because that makes the function
2308 * return with no isolated folios if the LRU mostly contains
2309 * ineligible folios. This causes the VM to not reclaim any
2310 * folios, triggering a premature OOM.
2311 * Account all pages in a folio.
791b48b6 2312 */
98879b3b 2313 scan += nr_pages;
89f6c88a 2314
166e3d32 2315 if (!folio_test_lru(folio))
89f6c88a 2316 goto move;
166e3d32 2317 if (!sc->may_unmap && folio_mapped(folio))
89f6c88a
HD
2318 goto move;
2319
c2135f7c 2320 /*
166e3d32
MWO
2321 * Be careful not to clear the lru flag until after we're
2322 * sure the folio is not being freed elsewhere -- the
2323 * folio release code relies on it.
c2135f7c 2324 */
166e3d32 2325 if (unlikely(!folio_try_get(folio)))
89f6c88a 2326 goto move;
5ad333eb 2327
166e3d32
MWO
2328 if (!folio_test_clear_lru(folio)) {
2329 /* Another thread is already isolating this folio */
2330 folio_put(folio);
89f6c88a 2331 goto move;
5ad333eb 2332 }
c2135f7c
AS
2333
2334 nr_taken += nr_pages;
166e3d32 2335 nr_zone_taken[folio_zonenum(folio)] += nr_pages;
89f6c88a
HD
2336 move_to = dst;
2337move:
166e3d32 2338 list_move(&folio->lru, move_to);
1da177e4
LT
2339 }
2340
b2e18757 2341 /*
166e3d32 2342 * Splice any skipped folios to the start of the LRU list. Note that
b2e18757
MG
2343 * this disrupts the LRU order when reclaiming for lower zones but
2344 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
166e3d32 2345 * scanning would soon rescan the same folios to skip and waste lots
b2cb6826 2346 * of cpu cycles.
b2e18757 2347 */
166e3d32 2348 if (!list_empty(&folios_skipped)) {
7cc30fcf
MG
2349 int zid;
2350
166e3d32 2351 list_splice(&folios_skipped, src);
7cc30fcf
MG
2352 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2353 if (!nr_skipped[zid])
2354 continue;
2355
2356 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
1265e3a6 2357 skipped += nr_skipped[zid];
7cc30fcf
MG
2358 }
2359 }
791b48b6 2360 *nr_scanned = total_scan;
1265e3a6 2361 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
89f6c88a
HD
2362 total_scan, skipped, nr_taken,
2363 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
b4536f0c 2364 update_lru_sizes(lruvec, lru, nr_zone_taken);
1da177e4
LT
2365 return nr_taken;
2366}
2367
62695a84 2368/**
d1d8a3b4
MWO
2369 * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2370 * @folio: Folio to isolate from its LRU list.
62695a84 2371 *
d1d8a3b4
MWO
2372 * Isolate a @folio from an LRU list and adjust the vmstat statistic
2373 * corresponding to whatever LRU list the folio was on.
62695a84 2374 *
d1d8a3b4
MWO
2375 * The folio will have its LRU flag cleared. If it was found on the
2376 * active list, it will have the Active flag set. If it was found on the
2377 * unevictable list, it will have the Unevictable flag set. These flags
894bc310 2378 * may need to be cleared by the caller before letting the page go.
62695a84 2379 *
d1d8a3b4 2380 * Context:
a5d09bed 2381 *
49fd9b6d
MWO
2382 * (1) Must be called with an elevated refcount on the folio. This is a
2383 * fundamental difference from isolate_lru_folios() (which is called
62695a84 2384 * without a stable reference).
d1d8a3b4
MWO
2385 * (2) The lru_lock must not be held.
2386 * (3) Interrupts must be enabled.
2387 *
be2d5756
BW
2388 * Return: true if the folio was removed from an LRU list.
2389 * false if the folio was not on an LRU list.
62695a84 2390 */
be2d5756 2391bool folio_isolate_lru(struct folio *folio)
62695a84 2392{
be2d5756 2393 bool ret = false;
62695a84 2394
d1d8a3b4 2395 VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
0c917313 2396
d1d8a3b4 2397 if (folio_test_clear_lru(folio)) {
fa9add64 2398 struct lruvec *lruvec;
62695a84 2399
d1d8a3b4 2400 folio_get(folio);
e809c3fe 2401 lruvec = folio_lruvec_lock_irq(folio);
d1d8a3b4 2402 lruvec_del_folio(lruvec, folio);
6168d0da 2403 unlock_page_lruvec_irq(lruvec);
be2d5756 2404 ret = true;
62695a84 2405 }
d25b5bd8 2406
62695a84
NP
2407 return ret;
2408}
2409
35cd7815 2410/*
d37dd5dc 2411 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
178821b8 2412 * then get rescheduled. When there are massive number of tasks doing page
d37dd5dc
FW
2413 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2414 * the LRU list will go small and be scanned faster than necessary, leading to
2415 * unnecessary swapping, thrashing and OOM.
35cd7815 2416 */
599d0c95 2417static int too_many_isolated(struct pglist_data *pgdat, int file,
35cd7815
RR
2418 struct scan_control *sc)
2419{
2420 unsigned long inactive, isolated;
d818fca1 2421 bool too_many;
35cd7815
RR
2422
2423 if (current_is_kswapd())
2424 return 0;
2425
b5ead35e 2426 if (!writeback_throttling_sane(sc))
35cd7815
RR
2427 return 0;
2428
2429 if (file) {
599d0c95
MG
2430 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2431 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
35cd7815 2432 } else {
599d0c95
MG
2433 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2434 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
35cd7815
RR
2435 }
2436
3cf23841
FW
2437 /*
2438 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2439 * won't get blocked by normal direct-reclaimers, forming a circular
2440 * deadlock.
2441 */
d0164adc 2442 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
3cf23841
FW
2443 inactive >>= 3;
2444
d818fca1
MG
2445 too_many = isolated > inactive;
2446
2447 /* Wake up tasks throttled due to too_many_isolated. */
2448 if (!too_many)
2449 wake_throttle_isolated(pgdat);
2450
2451 return too_many;
35cd7815
RR
2452}
2453
a222f341 2454/*
49fd9b6d 2455 * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
ff00a170 2456 * On return, @list is reused as a list of folios to be freed by the caller.
a222f341
KT
2457 *
2458 * Returns the number of pages moved to the given lruvec.
2459 */
49fd9b6d
MWO
2460static unsigned int move_folios_to_lru(struct lruvec *lruvec,
2461 struct list_head *list)
66635629 2462{
a222f341 2463 int nr_pages, nr_moved = 0;
ff00a170 2464 LIST_HEAD(folios_to_free);
66635629 2465
a222f341 2466 while (!list_empty(list)) {
ff00a170
MWO
2467 struct folio *folio = lru_to_folio(list);
2468
2469 VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2470 list_del(&folio->lru);
2471 if (unlikely(!folio_evictable(folio))) {
6168d0da 2472 spin_unlock_irq(&lruvec->lru_lock);
ff00a170 2473 folio_putback_lru(folio);
6168d0da 2474 spin_lock_irq(&lruvec->lru_lock);
66635629
MG
2475 continue;
2476 }
fa9add64 2477
3d06afab 2478 /*
ff00a170 2479 * The folio_set_lru needs to be kept here for list integrity.
3d06afab 2480 * Otherwise:
49fd9b6d 2481 * #0 move_folios_to_lru #1 release_pages
ff00a170
MWO
2482 * if (!folio_put_testzero())
2483 * if (folio_put_testzero())
2484 * !lru //skip lru_lock
2485 * folio_set_lru()
2486 * list_add(&folio->lru,)
2487 * list_add(&folio->lru,)
3d06afab 2488 */
ff00a170 2489 folio_set_lru(folio);
a222f341 2490
ff00a170
MWO
2491 if (unlikely(folio_put_testzero(folio))) {
2492 __folio_clear_lru_flags(folio);
2bcf8879 2493
ff00a170 2494 if (unlikely(folio_test_large(folio))) {
6168d0da 2495 spin_unlock_irq(&lruvec->lru_lock);
5375336c 2496 destroy_large_folio(folio);
6168d0da 2497 spin_lock_irq(&lruvec->lru_lock);
2bcf8879 2498 } else
ff00a170 2499 list_add(&folio->lru, &folios_to_free);
3d06afab
AS
2500
2501 continue;
66635629 2502 }
3d06afab 2503
afca9157
AS
2504 /*
2505 * All pages were isolated from the same lruvec (and isolation
2506 * inhibits memcg migration).
2507 */
ff00a170
MWO
2508 VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2509 lruvec_add_folio(lruvec, folio);
2510 nr_pages = folio_nr_pages(folio);
3d06afab 2511 nr_moved += nr_pages;
ff00a170 2512 if (folio_test_active(folio))
3d06afab 2513 workingset_age_nonresident(lruvec, nr_pages);
66635629 2514 }
66635629 2515
3f79768f
HD
2516 /*
2517 * To save our caller's stack, now use input list for pages to free.
2518 */
ff00a170 2519 list_splice(&folios_to_free, list);
a222f341
KT
2520
2521 return nr_moved;
66635629
MG
2522}
2523
399ba0b9 2524/*
5829f7db
ML
2525 * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2526 * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2527 * we should not throttle. Otherwise it is safe to do so.
399ba0b9
N
2528 */
2529static int current_may_throttle(void)
2530{
b9b1335e 2531 return !(current->flags & PF_LOCAL_THROTTLE);
399ba0b9
N
2532}
2533
1da177e4 2534/*
b2e18757 2535 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
1742f19f 2536 * of reclaimed pages
1da177e4 2537 */
49fd9b6d
MWO
2538static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
2539 struct lruvec *lruvec, struct scan_control *sc,
2540 enum lru_list lru)
1da177e4 2541{
49fd9b6d 2542 LIST_HEAD(folio_list);
e247dbce 2543 unsigned long nr_scanned;
730ec8c0 2544 unsigned int nr_reclaimed = 0;
e247dbce 2545 unsigned long nr_taken;
060f005f 2546 struct reclaim_stat stat;
497a6c1b 2547 bool file = is_file_lru(lru);
f46b7912 2548 enum vm_event_item item;
599d0c95 2549 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
db73ee0d 2550 bool stalled = false;
78dc583d 2551
599d0c95 2552 while (unlikely(too_many_isolated(pgdat, file, sc))) {
db73ee0d
MH
2553 if (stalled)
2554 return 0;
2555
2556 /* wait a bit for the reclaimer. */
db73ee0d 2557 stalled = true;
c3f4a9a2 2558 reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
35cd7815
RR
2559
2560 /* We are about to die and free our memory. Return now. */
2561 if (fatal_signal_pending(current))
2562 return SWAP_CLUSTER_MAX;
2563 }
2564
1da177e4 2565 lru_add_drain();
f80c0673 2566
6168d0da 2567 spin_lock_irq(&lruvec->lru_lock);
b35ea17b 2568
49fd9b6d 2569 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
a9e7c39f 2570 &nr_scanned, sc, lru);
95d918fc 2571
599d0c95 2572 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
57e9cc50 2573 item = PGSCAN_KSWAPD + reclaimer_offset();
b5ead35e 2574 if (!cgroup_reclaim(sc))
f46b7912
KT
2575 __count_vm_events(item, nr_scanned);
2576 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
497a6c1b
JW
2577 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2578
6168d0da 2579 spin_unlock_irq(&lruvec->lru_lock);
b35ea17b 2580
d563c050 2581 if (nr_taken == 0)
66635629 2582 return 0;
5ad333eb 2583
49fd9b6d 2584 nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
c661b078 2585
6168d0da 2586 spin_lock_irq(&lruvec->lru_lock);
49fd9b6d 2587 move_folios_to_lru(lruvec, &folio_list);
497a6c1b
JW
2588
2589 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
57e9cc50 2590 item = PGSTEAL_KSWAPD + reclaimer_offset();
b5ead35e 2591 if (!cgroup_reclaim(sc))
f46b7912
KT
2592 __count_vm_events(item, nr_reclaimed);
2593 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
497a6c1b 2594 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
6168d0da 2595 spin_unlock_irq(&lruvec->lru_lock);
3f79768f 2596
0538a82c 2597 lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
49fd9b6d
MWO
2598 mem_cgroup_uncharge_list(&folio_list);
2599 free_unref_page_list(&folio_list);
e11da5b4 2600
1c610d5f 2601 /*
49fd9b6d 2602 * If dirty folios are scanned that are not queued for IO, it
1c610d5f 2603 * implies that flushers are not doing their job. This can
49fd9b6d 2604 * happen when memory pressure pushes dirty folios to the end of
1c610d5f
AR
2605 * the LRU before the dirty limits are breached and the dirty
2606 * data has expired. It can also happen when the proportion of
49fd9b6d 2607 * dirty folios grows not through writes but through memory
1c610d5f
AR
2608 * pressure reclaiming all the clean cache. And in some cases,
2609 * the flushers simply cannot keep up with the allocation
2610 * rate. Nudge the flusher threads in case they are asleep.
2611 */
81a70c21 2612 if (stat.nr_unqueued_dirty == nr_taken) {
1c610d5f 2613 wakeup_flusher_threads(WB_REASON_VMSCAN);
81a70c21
AK
2614 /*
2615 * For cgroupv1 dirty throttling is achieved by waking up
2616 * the kernel flusher here and later waiting on folios
2617 * which are in writeback to finish (see shrink_folio_list()).
2618 *
2619 * Flusher may not be able to issue writeback quickly
2620 * enough for cgroupv1 writeback throttling to work
2621 * on a large system.
2622 */
2623 if (!writeback_throttling_sane(sc))
2624 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2625 }
1c610d5f 2626
d108c772
AR
2627 sc->nr.dirty += stat.nr_dirty;
2628 sc->nr.congested += stat.nr_congested;
2629 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2630 sc->nr.writeback += stat.nr_writeback;
2631 sc->nr.immediate += stat.nr_immediate;
2632 sc->nr.taken += nr_taken;
2633 if (file)
2634 sc->nr.file_taken += nr_taken;
8e950282 2635
599d0c95 2636 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
d51d1e64 2637 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
05ff5137 2638 return nr_reclaimed;
1da177e4
LT
2639}
2640
15b44736 2641/*
07f67a8d 2642 * shrink_active_list() moves folios from the active LRU to the inactive LRU.
15b44736 2643 *
07f67a8d 2644 * We move them the other way if the folio is referenced by one or more
15b44736
HD
2645 * processes.
2646 *
07f67a8d 2647 * If the folios are mostly unmapped, the processing is fast and it is
15b44736 2648 * appropriate to hold lru_lock across the whole operation. But if
07f67a8d
MWO
2649 * the folios are mapped, the processing is slow (folio_referenced()), so
2650 * we should drop lru_lock around each folio. It's impossible to balance
2651 * this, so instead we remove the folios from the LRU while processing them.
2652 * It is safe to rely on the active flag against the non-LRU folios in here
2653 * because nobody will play with that bit on a non-LRU folio.
15b44736 2654 *
07f67a8d
MWO
2655 * The downside is that we have to touch folio->_refcount against each folio.
2656 * But we had to alter folio->flags anyway.
15b44736 2657 */
f626012d 2658static void shrink_active_list(unsigned long nr_to_scan,
1a93be0e 2659 struct lruvec *lruvec,
f16015fb 2660 struct scan_control *sc,
9e3b2f8c 2661 enum lru_list lru)
1da177e4 2662{
44c241f1 2663 unsigned long nr_taken;
f626012d 2664 unsigned long nr_scanned;
6fe6b7e3 2665 unsigned long vm_flags;
07f67a8d 2666 LIST_HEAD(l_hold); /* The folios which were snipped off */
8cab4754 2667 LIST_HEAD(l_active);
b69408e8 2668 LIST_HEAD(l_inactive);
9d998b4f
MH
2669 unsigned nr_deactivate, nr_activate;
2670 unsigned nr_rotated = 0;
3cb99451 2671 int file = is_file_lru(lru);
599d0c95 2672 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
1da177e4
LT
2673
2674 lru_add_drain();
f80c0673 2675
6168d0da 2676 spin_lock_irq(&lruvec->lru_lock);
925b7673 2677
49fd9b6d 2678 nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
a9e7c39f 2679 &nr_scanned, sc, lru);
89b5fae5 2680
599d0c95 2681 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
1cfb419b 2682
912c0572
SB
2683 if (!cgroup_reclaim(sc))
2684 __count_vm_events(PGREFILL, nr_scanned);
2fa2690c 2685 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
9d5e6a9f 2686
6168d0da 2687 spin_unlock_irq(&lruvec->lru_lock);
1da177e4 2688
1da177e4 2689 while (!list_empty(&l_hold)) {
b3ac0413 2690 struct folio *folio;
b3ac0413 2691
1da177e4 2692 cond_resched();
b3ac0413
MWO
2693 folio = lru_to_folio(&l_hold);
2694 list_del(&folio->lru);
7e9cd484 2695
07f67a8d
MWO
2696 if (unlikely(!folio_evictable(folio))) {
2697 folio_putback_lru(folio);
894bc310
LS
2698 continue;
2699 }
2700
cc715d99 2701 if (unlikely(buffer_heads_over_limit)) {
36a3b14b
MWO
2702 if (folio_test_private(folio) && folio_trylock(folio)) {
2703 if (folio_test_private(folio))
07f67a8d
MWO
2704 filemap_release_folio(folio, 0);
2705 folio_unlock(folio);
cc715d99
MG
2706 }
2707 }
2708
6d4675e6 2709 /* Referenced or rmap lock contention: rotate */
b3ac0413 2710 if (folio_referenced(folio, 0, sc->target_mem_cgroup,
6d4675e6 2711 &vm_flags) != 0) {
8cab4754 2712 /*
07f67a8d 2713 * Identify referenced, file-backed active folios and
8cab4754
WF
2714 * give them one more trip around the active list. So
2715 * that executable code get better chances to stay in
07f67a8d 2716 * memory under moderate memory pressure. Anon folios
8cab4754 2717 * are not likely to be evicted by use-once streaming
07f67a8d 2718 * IO, plus JVM can create lots of anon VM_EXEC folios,
8cab4754
WF
2719 * so we ignore them here.
2720 */
07f67a8d
MWO
2721 if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2722 nr_rotated += folio_nr_pages(folio);
2723 list_add(&folio->lru, &l_active);
8cab4754
WF
2724 continue;
2725 }
2726 }
7e9cd484 2727
07f67a8d
MWO
2728 folio_clear_active(folio); /* we are de-activating */
2729 folio_set_workingset(folio);
2730 list_add(&folio->lru, &l_inactive);
1da177e4
LT
2731 }
2732
b555749a 2733 /*
07f67a8d 2734 * Move folios back to the lru list.
b555749a 2735 */
6168d0da 2736 spin_lock_irq(&lruvec->lru_lock);
556adecb 2737
49fd9b6d
MWO
2738 nr_activate = move_folios_to_lru(lruvec, &l_active);
2739 nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
07f67a8d 2740 /* Keep all free folios in l_active list */
f372d89e 2741 list_splice(&l_inactive, &l_active);
9851ac13
KT
2742
2743 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2744 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2745
599d0c95 2746 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
6168d0da 2747 spin_unlock_irq(&lruvec->lru_lock);
2bcf8879 2748
0538a82c
JW
2749 if (nr_rotated)
2750 lru_note_cost(lruvec, file, 0, nr_rotated);
f372d89e
KT
2751 mem_cgroup_uncharge_list(&l_active);
2752 free_unref_page_list(&l_active);
9d998b4f
MH
2753 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2754 nr_deactivate, nr_rotated, sc->priority, file);
1da177e4
LT
2755}
2756
49fd9b6d 2757static unsigned int reclaim_folio_list(struct list_head *folio_list,
1fe47c0b 2758 struct pglist_data *pgdat)
1a4e58cc 2759{
1a4e58cc 2760 struct reclaim_stat dummy_stat;
1fe47c0b
ML
2761 unsigned int nr_reclaimed;
2762 struct folio *folio;
1a4e58cc
MK
2763 struct scan_control sc = {
2764 .gfp_mask = GFP_KERNEL,
1a4e58cc
MK
2765 .may_writepage = 1,
2766 .may_unmap = 1,
2767 .may_swap = 1,
26aa2d19 2768 .no_demotion = 1,
1a4e58cc
MK
2769 };
2770
49fd9b6d
MWO
2771 nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2772 while (!list_empty(folio_list)) {
2773 folio = lru_to_folio(folio_list);
1fe47c0b
ML
2774 list_del(&folio->lru);
2775 folio_putback_lru(folio);
2776 }
2777
2778 return nr_reclaimed;
2779}
2780
a83f0551 2781unsigned long reclaim_pages(struct list_head *folio_list)
1fe47c0b 2782{
ed657e55 2783 int nid;
1fe47c0b 2784 unsigned int nr_reclaimed = 0;
a83f0551 2785 LIST_HEAD(node_folio_list);
1fe47c0b
ML
2786 unsigned int noreclaim_flag;
2787
a83f0551 2788 if (list_empty(folio_list))
1ae65e27
WY
2789 return nr_reclaimed;
2790
2d2b8d2b
YZ
2791 noreclaim_flag = memalloc_noreclaim_save();
2792
a83f0551 2793 nid = folio_nid(lru_to_folio(folio_list));
1ae65e27 2794 do {
a83f0551 2795 struct folio *folio = lru_to_folio(folio_list);
1a4e58cc 2796
a83f0551
MWO
2797 if (nid == folio_nid(folio)) {
2798 folio_clear_active(folio);
2799 list_move(&folio->lru, &node_folio_list);
1a4e58cc
MK
2800 continue;
2801 }
2802
49fd9b6d 2803 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
a83f0551
MWO
2804 nid = folio_nid(lru_to_folio(folio_list));
2805 } while (!list_empty(folio_list));
1a4e58cc 2806
49fd9b6d 2807 nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
1a4e58cc 2808
2d2b8d2b
YZ
2809 memalloc_noreclaim_restore(noreclaim_flag);
2810
1a4e58cc
MK
2811 return nr_reclaimed;
2812}
2813
b91ac374
JW
2814static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2815 struct lruvec *lruvec, struct scan_control *sc)
2816{
2817 if (is_active_lru(lru)) {
2818 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2819 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2820 else
2821 sc->skipped_deactivate = 1;
2822 return 0;
2823 }
2824
2825 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2826}
2827
59dc76b0
RR
2828/*
2829 * The inactive anon list should be small enough that the VM never has
2830 * to do too much work.
14797e23 2831 *
59dc76b0
RR
2832 * The inactive file list should be small enough to leave most memory
2833 * to the established workingset on the scan-resistant active list,
2834 * but large enough to avoid thrashing the aggregate readahead window.
56e49d21 2835 *
59dc76b0 2836 * Both inactive lists should also be large enough that each inactive
49fd9b6d 2837 * folio has a chance to be referenced again before it is reclaimed.
56e49d21 2838 *
2a2e4885
JW
2839 * If that fails and refaulting is observed, the inactive list grows.
2840 *
49fd9b6d 2841 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
3a50d14d 2842 * on this LRU, maintained by the pageout code. An inactive_ratio
49fd9b6d 2843 * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
56e49d21 2844 *
59dc76b0
RR
2845 * total target max
2846 * memory ratio inactive
2847 * -------------------------------------
2848 * 10MB 1 5MB
2849 * 100MB 1 50MB
2850 * 1GB 3 250MB
2851 * 10GB 10 0.9GB
2852 * 100GB 31 3GB
2853 * 1TB 101 10GB
2854 * 10TB 320 32GB
56e49d21 2855 */
b91ac374 2856static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
56e49d21 2857{
b91ac374 2858 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2a2e4885
JW
2859 unsigned long inactive, active;
2860 unsigned long inactive_ratio;
59dc76b0 2861 unsigned long gb;
e3790144 2862
b91ac374
JW
2863 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2864 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
f8d1a311 2865
b91ac374 2866 gb = (inactive + active) >> (30 - PAGE_SHIFT);
4002570c 2867 if (gb)
b91ac374
JW
2868 inactive_ratio = int_sqrt(10 * gb);
2869 else
2870 inactive_ratio = 1;
fd538803 2871
59dc76b0 2872 return inactive * inactive_ratio < active;
b39415b2
RR
2873}
2874
9a265114
JW
2875enum scan_balance {
2876 SCAN_EQUAL,
2877 SCAN_FRACT,
2878 SCAN_ANON,
2879 SCAN_FILE,
2880};
2881
f1e1a7be
YZ
2882static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2883{
2884 unsigned long file;
2885 struct lruvec *target_lruvec;
2886
ac35a490
YZ
2887 if (lru_gen_enabled())
2888 return;
2889
f1e1a7be
YZ
2890 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2891
2892 /*
2893 * Flush the memory cgroup stats, so that we read accurate per-memcg
2894 * lruvec stats for heuristics.
2895 */
2896 mem_cgroup_flush_stats();
2897
2898 /*
2899 * Determine the scan balance between anon and file LRUs.
2900 */
2901 spin_lock_irq(&target_lruvec->lru_lock);
2902 sc->anon_cost = target_lruvec->anon_cost;
2903 sc->file_cost = target_lruvec->file_cost;
2904 spin_unlock_irq(&target_lruvec->lru_lock);
2905
2906 /*
2907 * Target desirable inactive:active list ratios for the anon
2908 * and file LRU lists.
2909 */
2910 if (!sc->force_deactivate) {
2911 unsigned long refaults;
2912
2913 /*
2914 * When refaults are being observed, it means a new
2915 * workingset is being established. Deactivate to get
2916 * rid of any stale active pages quickly.
2917 */
2918 refaults = lruvec_page_state(target_lruvec,
2919 WORKINGSET_ACTIVATE_ANON);
2920 if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2921 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2922 sc->may_deactivate |= DEACTIVATE_ANON;
2923 else
2924 sc->may_deactivate &= ~DEACTIVATE_ANON;
2925
2926 refaults = lruvec_page_state(target_lruvec,
2927 WORKINGSET_ACTIVATE_FILE);
2928 if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2929 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2930 sc->may_deactivate |= DEACTIVATE_FILE;
2931 else
2932 sc->may_deactivate &= ~DEACTIVATE_FILE;
2933 } else
2934 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2935
2936 /*
2937 * If we have plenty of inactive file pages that aren't
2938 * thrashing, try to reclaim those first before touching
2939 * anonymous pages.
2940 */
2941 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2942 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2943 sc->cache_trim_mode = 1;
2944 else
2945 sc->cache_trim_mode = 0;
2946
2947 /*
2948 * Prevent the reclaimer from falling into the cache trap: as
2949 * cache pages start out inactive, every cache fault will tip
2950 * the scan balance towards the file LRU. And as the file LRU
2951 * shrinks, so does the window for rotation from references.
2952 * This means we have a runaway feedback loop where a tiny
2953 * thrashing file LRU becomes infinitely more attractive than
2954 * anon pages. Try to detect this based on file LRU size.
2955 */
2956 if (!cgroup_reclaim(sc)) {
2957 unsigned long total_high_wmark = 0;
2958 unsigned long free, anon;
2959 int z;
2960
2961 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2962 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2963 node_page_state(pgdat, NR_INACTIVE_FILE);
2964
2965 for (z = 0; z < MAX_NR_ZONES; z++) {
2966 struct zone *zone = &pgdat->node_zones[z];
2967
2968 if (!managed_zone(zone))
2969 continue;
2970
2971 total_high_wmark += high_wmark_pages(zone);
2972 }
2973
2974 /*
2975 * Consider anon: if that's low too, this isn't a
2976 * runaway file reclaim problem, but rather just
2977 * extreme pressure. Reclaim as per usual then.
2978 */
2979 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2980
2981 sc->file_is_tiny =
2982 file + free <= total_high_wmark &&
2983 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2984 anon >> sc->priority;
2985 }
2986}
2987
4f98a2fe
RR
2988/*
2989 * Determine how aggressively the anon and file LRU lists should be
02e458d8 2990 * scanned.
4f98a2fe 2991 *
49fd9b6d
MWO
2992 * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2993 * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
4f98a2fe 2994 */
afaf07a6
JW
2995static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2996 unsigned long *nr)
4f98a2fe 2997{
a2a36488 2998 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
afaf07a6 2999 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
d483a5dd 3000 unsigned long anon_cost, file_cost, total_cost;
33377678 3001 int swappiness = mem_cgroup_swappiness(memcg);
ed017373 3002 u64 fraction[ANON_AND_FILE];
9a265114 3003 u64 denominator = 0; /* gcc */
9a265114 3004 enum scan_balance scan_balance;
4f98a2fe 3005 unsigned long ap, fp;
4111304d 3006 enum lru_list lru;
76a33fc3 3007
49fd9b6d 3008 /* If we have no swap space, do not bother scanning anon folios. */
a2a36488 3009 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
9a265114 3010 scan_balance = SCAN_FILE;
76a33fc3
SL
3011 goto out;
3012 }
4f98a2fe 3013
10316b31
JW
3014 /*
3015 * Global reclaim will swap to prevent OOM even with no
3016 * swappiness, but memcg users want to use this knob to
3017 * disable swapping for individual groups completely when
3018 * using the memory controller's swap limit feature would be
3019 * too expensive.
3020 */
b5ead35e 3021 if (cgroup_reclaim(sc) && !swappiness) {
9a265114 3022 scan_balance = SCAN_FILE;
10316b31
JW
3023 goto out;
3024 }
3025
3026 /*
3027 * Do not apply any pressure balancing cleverness when the
3028 * system is close to OOM, scan both anon and file equally
3029 * (unless the swappiness setting disagrees with swapping).
3030 */
02695175 3031 if (!sc->priority && swappiness) {
9a265114 3032 scan_balance = SCAN_EQUAL;
10316b31
JW
3033 goto out;
3034 }
3035
62376251 3036 /*
53138cea 3037 * If the system is almost out of file pages, force-scan anon.
62376251 3038 */
b91ac374 3039 if (sc->file_is_tiny) {
53138cea
JW
3040 scan_balance = SCAN_ANON;
3041 goto out;
62376251
JW
3042 }
3043
7c5bd705 3044 /*
b91ac374
JW
3045 * If there is enough inactive page cache, we do not reclaim
3046 * anything from the anonymous working right now.
7c5bd705 3047 */
b91ac374 3048 if (sc->cache_trim_mode) {
9a265114 3049 scan_balance = SCAN_FILE;
7c5bd705
JW
3050 goto out;
3051 }
3052
9a265114 3053 scan_balance = SCAN_FRACT;
58c37f6e 3054 /*
314b57fb
JW
3055 * Calculate the pressure balance between anon and file pages.
3056 *
3057 * The amount of pressure we put on each LRU is inversely
3058 * proportional to the cost of reclaiming each list, as
3059 * determined by the share of pages that are refaulting, times
3060 * the relative IO cost of bringing back a swapped out
3061 * anonymous page vs reloading a filesystem page (swappiness).
3062 *
d483a5dd
JW
3063 * Although we limit that influence to ensure no list gets
3064 * left behind completely: at least a third of the pressure is
3065 * applied, before swappiness.
3066 *
314b57fb 3067 * With swappiness at 100, anon and file have equal IO cost.
58c37f6e 3068 */
d483a5dd
JW
3069 total_cost = sc->anon_cost + sc->file_cost;
3070 anon_cost = total_cost + sc->anon_cost;
3071 file_cost = total_cost + sc->file_cost;
3072 total_cost = anon_cost + file_cost;
58c37f6e 3073
d483a5dd
JW
3074 ap = swappiness * (total_cost + 1);
3075 ap /= anon_cost + 1;
4f98a2fe 3076
d483a5dd
JW
3077 fp = (200 - swappiness) * (total_cost + 1);
3078 fp /= file_cost + 1;
4f98a2fe 3079
76a33fc3
SL
3080 fraction[0] = ap;
3081 fraction[1] = fp;
a4fe1631 3082 denominator = ap + fp;
76a33fc3 3083out:
688035f7
JW
3084 for_each_evictable_lru(lru) {
3085 int file = is_file_lru(lru);
9783aa99 3086 unsigned long lruvec_size;
f56ce412 3087 unsigned long low, min;
688035f7 3088 unsigned long scan;
9783aa99
CD
3089
3090 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
f56ce412
JW
3091 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
3092 &min, &low);
9783aa99 3093
f56ce412 3094 if (min || low) {
9783aa99
CD
3095 /*
3096 * Scale a cgroup's reclaim pressure by proportioning
3097 * its current usage to its memory.low or memory.min
3098 * setting.
3099 *
3100 * This is important, as otherwise scanning aggression
3101 * becomes extremely binary -- from nothing as we
3102 * approach the memory protection threshold, to totally
3103 * nominal as we exceed it. This results in requiring
3104 * setting extremely liberal protection thresholds. It
3105 * also means we simply get no protection at all if we
3106 * set it too low, which is not ideal.
1bc63fb1
CD
3107 *
3108 * If there is any protection in place, we reduce scan
3109 * pressure by how much of the total memory used is
3110 * within protection thresholds.
9783aa99 3111 *
9de7ca46
CD
3112 * There is one special case: in the first reclaim pass,
3113 * we skip over all groups that are within their low
3114 * protection. If that fails to reclaim enough pages to
3115 * satisfy the reclaim goal, we come back and override
3116 * the best-effort low protection. However, we still
3117 * ideally want to honor how well-behaved groups are in
3118 * that case instead of simply punishing them all
3119 * equally. As such, we reclaim them based on how much
1bc63fb1
CD
3120 * memory they are using, reducing the scan pressure
3121 * again by how much of the total memory used is under
3122 * hard protection.
9783aa99 3123 */
1bc63fb1 3124 unsigned long cgroup_size = mem_cgroup_size(memcg);
f56ce412
JW
3125 unsigned long protection;
3126
3127 /* memory.low scaling, make sure we retry before OOM */
3128 if (!sc->memcg_low_reclaim && low > min) {
3129 protection = low;
3130 sc->memcg_low_skipped = 1;
3131 } else {
3132 protection = min;
3133 }
1bc63fb1
CD
3134
3135 /* Avoid TOCTOU with earlier protection check */
3136 cgroup_size = max(cgroup_size, protection);
3137
3138 scan = lruvec_size - lruvec_size * protection /
32d4f4b7 3139 (cgroup_size + 1);
9783aa99
CD
3140
3141 /*
1bc63fb1 3142 * Minimally target SWAP_CLUSTER_MAX pages to keep
55b65a57 3143 * reclaim moving forwards, avoiding decrementing
9de7ca46 3144 * sc->priority further than desirable.
9783aa99 3145 */
1bc63fb1 3146 scan = max(scan, SWAP_CLUSTER_MAX);
9783aa99
CD
3147 } else {
3148 scan = lruvec_size;
3149 }
3150
3151 scan >>= sc->priority;
6b4f7799 3152
688035f7
JW
3153 /*
3154 * If the cgroup's already been deleted, make sure to
3155 * scrape out the remaining cache.
3156 */
3157 if (!scan && !mem_cgroup_online(memcg))
9783aa99 3158 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
6b4f7799 3159
688035f7
JW
3160 switch (scan_balance) {
3161 case SCAN_EQUAL:
3162 /* Scan lists relative to size */
3163 break;
3164 case SCAN_FRACT:
9a265114 3165 /*
688035f7
JW
3166 * Scan types proportional to swappiness and
3167 * their relative recent reclaim efficiency.
76073c64
GS
3168 * Make sure we don't miss the last page on
3169 * the offlined memory cgroups because of a
3170 * round-off error.
9a265114 3171 */
76073c64
GS
3172 scan = mem_cgroup_online(memcg) ?
3173 div64_u64(scan * fraction[file], denominator) :
3174 DIV64_U64_ROUND_UP(scan * fraction[file],
68600f62 3175 denominator);
688035f7
JW
3176 break;
3177 case SCAN_FILE:
3178 case SCAN_ANON:
3179 /* Scan one type exclusively */
e072bff6 3180 if ((scan_balance == SCAN_FILE) != file)
688035f7 3181 scan = 0;
688035f7
JW
3182 break;
3183 default:
3184 /* Look ma, no brain */
3185 BUG();
9a265114 3186 }
688035f7 3187
688035f7 3188 nr[lru] = scan;
76a33fc3 3189 }
6e08a369 3190}
4f98a2fe 3191
2f368a9f
DH
3192/*
3193 * Anonymous LRU management is a waste if there is
3194 * ultimately no way to reclaim the memory.
3195 */
3196static bool can_age_anon_pages(struct pglist_data *pgdat,
3197 struct scan_control *sc)
3198{
3199 /* Aging the anon LRU is valuable if swap is present: */
3200 if (total_swap_pages > 0)
3201 return true;
3202
3203 /* Also valuable if anon pages can be demoted: */
3204 return can_demote(pgdat->node_id, sc);
3205}
3206
ec1c86b2
YZ
3207#ifdef CONFIG_LRU_GEN
3208
354ed597
YZ
3209#ifdef CONFIG_LRU_GEN_ENABLED
3210DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3211#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
3212#else
3213DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3214#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
3215#endif
3216
ec1c86b2
YZ
3217/******************************************************************************
3218 * shorthand helpers
3219 ******************************************************************************/
3220
ac35a490
YZ
3221#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
3222
3223#define DEFINE_MAX_SEQ(lruvec) \
3224 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3225
3226#define DEFINE_MIN_SEQ(lruvec) \
3227 unsigned long min_seq[ANON_AND_FILE] = { \
3228 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3229 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3230 }
3231
ec1c86b2
YZ
3232#define for_each_gen_type_zone(gen, type, zone) \
3233 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3234 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3235 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3236
e4dde56c
YZ
3237#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
3238#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
3239
bd74fdae 3240static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
ec1c86b2
YZ
3241{
3242 struct pglist_data *pgdat = NODE_DATA(nid);
3243
3244#ifdef CONFIG_MEMCG
3245 if (memcg) {
3246 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3247
931b6a8b 3248 /* see the comment in mem_cgroup_lruvec() */
ec1c86b2
YZ
3249 if (!lruvec->pgdat)
3250 lruvec->pgdat = pgdat;
3251
3252 return lruvec;
3253 }
3254#endif
3255 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3256
931b6a8b 3257 return &pgdat->__lruvec;
ec1c86b2
YZ
3258}
3259
ac35a490
YZ
3260static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3261{
3262 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3263 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3264
e9d4e1ee
YZ
3265 if (!sc->may_swap)
3266 return 0;
3267
ac35a490
YZ
3268 if (!can_demote(pgdat->node_id, sc) &&
3269 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3270 return 0;
3271
3272 return mem_cgroup_swappiness(memcg);
3273}
3274
3275static int get_nr_gens(struct lruvec *lruvec, int type)
3276{
3277 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3278}
3279
3280static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3281{
391655fe 3282 /* see the comment on lru_gen_folio */
ac35a490
YZ
3283 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3284 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3285 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3286}
3287
ccbbbb85
A
3288/******************************************************************************
3289 * Bloom filters
3290 ******************************************************************************/
3291
3292/*
3293 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3294 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3295 * bits in a bitmap, k is the number of hash functions and n is the number of
3296 * inserted items.
3297 *
3298 * Page table walkers use one of the two filters to reduce their search space.
3299 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3300 * aging uses the double-buffering technique to flip to the other filter each
3301 * time it produces a new generation. For non-leaf entries that have enough
3302 * leaf entries, the aging carries them over to the next generation in
3303 * walk_pmd_range(); the eviction also report them when walking the rmap
3304 * in lru_gen_look_around().
3305 *
3306 * For future optimizations:
3307 * 1. It's not necessary to keep both filters all the time. The spare one can be
3308 * freed after the RCU grace period and reallocated if needed again.
3309 * 2. And when reallocating, it's worth scaling its size according to the number
3310 * of inserted entries in the other filter, to reduce the memory overhead on
3311 * small systems and false positives on large systems.
3312 * 3. Jenkins' hash function is an alternative to Knuth's.
3313 */
3314#define BLOOM_FILTER_SHIFT 15
3315
3316static inline int filter_gen_from_seq(unsigned long seq)
3317{
3318 return seq % NR_BLOOM_FILTERS;
3319}
3320
3321static void get_item_key(void *item, int *key)
3322{
3323 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3324
3325 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3326
3327 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3328 key[1] = hash >> BLOOM_FILTER_SHIFT;
3329}
3330
3331static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3332{
3333 int key[2];
3334 unsigned long *filter;
3335 int gen = filter_gen_from_seq(seq);
3336
3337 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3338 if (!filter)
3339 return true;
3340
3341 get_item_key(item, key);
3342
3343 return test_bit(key[0], filter) && test_bit(key[1], filter);
3344}
3345
3346static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3347{
3348 int key[2];
3349 unsigned long *filter;
3350 int gen = filter_gen_from_seq(seq);
3351
3352 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3353 if (!filter)
3354 return;
3355
3356 get_item_key(item, key);
3357
3358 if (!test_bit(key[0], filter))
3359 set_bit(key[0], filter);
3360 if (!test_bit(key[1], filter))
3361 set_bit(key[1], filter);
3362}
3363
3364static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3365{
3366 unsigned long *filter;
3367 int gen = filter_gen_from_seq(seq);
3368
3369 filter = lruvec->mm_state.filters[gen];
3370 if (filter) {
3371 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3372 return;
3373 }
3374
3375 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3376 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3377 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3378}
3379
bd74fdae
YZ
3380/******************************************************************************
3381 * mm_struct list
3382 ******************************************************************************/
3383
3384static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3385{
3386 static struct lru_gen_mm_list mm_list = {
3387 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3388 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3389 };
3390
3391#ifdef CONFIG_MEMCG
3392 if (memcg)
3393 return &memcg->mm_list;
3394#endif
3395 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3396
3397 return &mm_list;
3398}
3399
3400void lru_gen_add_mm(struct mm_struct *mm)
3401{
3402 int nid;
3403 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3404 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3405
3406 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3407#ifdef CONFIG_MEMCG
3408 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3409 mm->lru_gen.memcg = memcg;
3410#endif
3411 spin_lock(&mm_list->lock);
3412
3413 for_each_node_state(nid, N_MEMORY) {
3414 struct lruvec *lruvec = get_lruvec(memcg, nid);
3415
bd74fdae
YZ
3416 /* the first addition since the last iteration */
3417 if (lruvec->mm_state.tail == &mm_list->fifo)
3418 lruvec->mm_state.tail = &mm->lru_gen.list;
3419 }
3420
3421 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3422
3423 spin_unlock(&mm_list->lock);
3424}
3425
3426void lru_gen_del_mm(struct mm_struct *mm)
3427{
3428 int nid;
3429 struct lru_gen_mm_list *mm_list;
3430 struct mem_cgroup *memcg = NULL;
3431
3432 if (list_empty(&mm->lru_gen.list))
3433 return;
3434
3435#ifdef CONFIG_MEMCG
3436 memcg = mm->lru_gen.memcg;
3437#endif
3438 mm_list = get_mm_list(memcg);
3439
3440 spin_lock(&mm_list->lock);
3441
3442 for_each_node(nid) {
3443 struct lruvec *lruvec = get_lruvec(memcg, nid);
3444
7f63cf2d
KS
3445 /* where the current iteration continues after */
3446 if (lruvec->mm_state.head == &mm->lru_gen.list)
3447 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3448
3449 /* where the last iteration ended before */
bd74fdae
YZ
3450 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3451 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
bd74fdae
YZ
3452 }
3453
3454 list_del_init(&mm->lru_gen.list);
3455
3456 spin_unlock(&mm_list->lock);
3457
3458#ifdef CONFIG_MEMCG
3459 mem_cgroup_put(mm->lru_gen.memcg);
3460 mm->lru_gen.memcg = NULL;
3461#endif
3462}
3463
3464#ifdef CONFIG_MEMCG
3465void lru_gen_migrate_mm(struct mm_struct *mm)
3466{
3467 struct mem_cgroup *memcg;
3468 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3469
3470 VM_WARN_ON_ONCE(task->mm != mm);
3471 lockdep_assert_held(&task->alloc_lock);
3472
3473 /* for mm_update_next_owner() */
3474 if (mem_cgroup_disabled())
3475 return;
3476
de08eaa6
YZ
3477 /* migration can happen before addition */
3478 if (!mm->lru_gen.memcg)
3479 return;
3480
bd74fdae
YZ
3481 rcu_read_lock();
3482 memcg = mem_cgroup_from_task(task);
3483 rcu_read_unlock();
3484 if (memcg == mm->lru_gen.memcg)
3485 return;
3486
bd74fdae
YZ
3487 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3488
3489 lru_gen_del_mm(mm);
3490 lru_gen_add_mm(mm);
3491}
3492#endif
3493
bd74fdae
YZ
3494static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3495{
3496 int i;
3497 int hist;
3498
3499 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3500
3501 if (walk) {
3502 hist = lru_hist_from_seq(walk->max_seq);
3503
3504 for (i = 0; i < NR_MM_STATS; i++) {
3505 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3506 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3507 walk->mm_stats[i] = 0;
3508 }
3509 }
3510
3511 if (NR_HIST_GENS > 1 && last) {
3512 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3513
3514 for (i = 0; i < NR_MM_STATS; i++)
3515 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3516 }
3517}
3518
3519static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3520{
3521 int type;
3522 unsigned long size = 0;
3523 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3524 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3525
3526 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3527 return true;
3528
3529 clear_bit(key, &mm->lru_gen.bitmap);
3530
3531 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3532 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3533 get_mm_counter(mm, MM_ANONPAGES) +
3534 get_mm_counter(mm, MM_SHMEMPAGES);
3535 }
3536
3537 if (size < MIN_LRU_BATCH)
3538 return true;
3539
3540 return !mmget_not_zero(mm);
3541}
3542
3543static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3544 struct mm_struct **iter)
3545{
3546 bool first = false;
7f63cf2d 3547 bool last = false;
bd74fdae
YZ
3548 struct mm_struct *mm = NULL;
3549 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3550 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3551 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3552
3553 /*
7f63cf2d
KS
3554 * mm_state->seq is incremented after each iteration of mm_list. There
3555 * are three interesting cases for this page table walker:
3556 * 1. It tries to start a new iteration with a stale max_seq: there is
3557 * nothing left to do.
3558 * 2. It started the next iteration: it needs to reset the Bloom filter
3559 * so that a fresh set of PTE tables can be recorded.
3560 * 3. It ended the current iteration: it needs to reset the mm stats
3561 * counters and tell its caller to increment max_seq.
bd74fdae
YZ
3562 */
3563 spin_lock(&mm_list->lock);
3564
3565 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
bd74fdae 3566
7f63cf2d 3567 if (walk->max_seq <= mm_state->seq)
bd74fdae 3568 goto done;
bd74fdae 3569
7f63cf2d
KS
3570 if (!mm_state->head)
3571 mm_state->head = &mm_list->fifo;
bd74fdae 3572
7f63cf2d 3573 if (mm_state->head == &mm_list->fifo)
bd74fdae 3574 first = true;
bd74fdae 3575
7f63cf2d 3576 do {
bd74fdae 3577 mm_state->head = mm_state->head->next;
7f63cf2d
KS
3578 if (mm_state->head == &mm_list->fifo) {
3579 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3580 last = true;
3581 break;
3582 }
bd74fdae
YZ
3583
3584 /* force scan for those added after the last iteration */
7f63cf2d
KS
3585 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3586 mm_state->tail = mm_state->head->next;
bd74fdae
YZ
3587 walk->force_scan = true;
3588 }
3589
7f63cf2d 3590 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
bd74fdae
YZ
3591 if (should_skip_mm(mm, walk))
3592 mm = NULL;
7f63cf2d 3593 } while (!mm);
bd74fdae 3594done:
bd74fdae
YZ
3595 if (*iter || last)
3596 reset_mm_stats(lruvec, walk, last);
3597
3598 spin_unlock(&mm_list->lock);
3599
3600 if (mm && first)
3601 reset_bloom_filter(lruvec, walk->max_seq + 1);
3602
3603 if (*iter)
3604 mmput_async(*iter);
3605
3606 *iter = mm;
3607
3608 return last;
3609}
3610
3611static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3612{
3613 bool success = false;
3614 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3615 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3616 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3617
3618 spin_lock(&mm_list->lock);
3619
3620 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3621
7f63cf2d
KS
3622 if (max_seq > mm_state->seq) {
3623 mm_state->head = NULL;
3624 mm_state->tail = NULL;
bd74fdae
YZ
3625 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3626 reset_mm_stats(lruvec, NULL, true);
3627 success = true;
3628 }
3629
3630 spin_unlock(&mm_list->lock);
3631
3632 return success;
3633}
3634
ac35a490 3635/******************************************************************************
32d32ef1 3636 * PID controller
ac35a490
YZ
3637 ******************************************************************************/
3638
3639/*
3640 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3641 *
3642 * The P term is refaulted/(evicted+protected) from a tier in the generation
3643 * currently being evicted; the I term is the exponential moving average of the
3644 * P term over the generations previously evicted, using the smoothing factor
3645 * 1/2; the D term isn't supported.
3646 *
3647 * The setpoint (SP) is always the first tier of one type; the process variable
3648 * (PV) is either any tier of the other type or any other tier of the same
3649 * type.
3650 *
3651 * The error is the difference between the SP and the PV; the correction is to
3652 * turn off protection when SP>PV or turn on protection when SP<PV.
3653 *
3654 * For future optimizations:
3655 * 1. The D term may discount the other two terms over time so that long-lived
3656 * generations can resist stale information.
3657 */
3658struct ctrl_pos {
3659 unsigned long refaulted;
3660 unsigned long total;
3661 int gain;
3662};
3663
3664static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3665 struct ctrl_pos *pos)
3666{
391655fe 3667 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
3668 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3669
3670 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3671 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3672 pos->total = lrugen->avg_total[type][tier] +
3673 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3674 if (tier)
3675 pos->total += lrugen->protected[hist][type][tier - 1];
3676 pos->gain = gain;
3677}
3678
3679static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3680{
3681 int hist, tier;
391655fe 3682 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
3683 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3684 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3685
3686 lockdep_assert_held(&lruvec->lru_lock);
3687
3688 if (!carryover && !clear)
3689 return;
3690
3691 hist = lru_hist_from_seq(seq);
3692
3693 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3694 if (carryover) {
3695 unsigned long sum;
3696
3697 sum = lrugen->avg_refaulted[type][tier] +
3698 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3699 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3700
3701 sum = lrugen->avg_total[type][tier] +
3702 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3703 if (tier)
3704 sum += lrugen->protected[hist][type][tier - 1];
3705 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3706 }
3707
3708 if (clear) {
3709 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3710 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3711 if (tier)
3712 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3713 }
3714 }
3715}
3716
3717static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3718{
3719 /*
3720 * Return true if the PV has a limited number of refaults or a lower
3721 * refaulted/total than the SP.
3722 */
3723 return pv->refaulted < MIN_LRU_BATCH ||
3724 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3725 (sp->refaulted + 1) * pv->total * pv->gain;
3726}
3727
3728/******************************************************************************
3729 * the aging
3730 ******************************************************************************/
3731
018ee47f
YZ
3732/* promote pages accessed through page tables */
3733static int folio_update_gen(struct folio *folio, int gen)
3734{
3735 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3736
3737 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3738 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3739
3740 do {
3741 /* lru_gen_del_folio() has isolated this page? */
3742 if (!(old_flags & LRU_GEN_MASK)) {
49fd9b6d 3743 /* for shrink_folio_list() */
018ee47f
YZ
3744 new_flags = old_flags | BIT(PG_referenced);
3745 continue;
3746 }
3747
3748 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3749 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3750 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3751
3752 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3753}
3754
ac35a490
YZ
3755/* protect pages accessed multiple times through file descriptors */
3756static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3757{
3758 int type = folio_is_file_lru(folio);
391655fe 3759 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
3760 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3761 unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3762
3763 VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3764
3765 do {
018ee47f
YZ
3766 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3767 /* folio_update_gen() has promoted this page? */
3768 if (new_gen >= 0 && new_gen != old_gen)
3769 return new_gen;
3770
ac35a490
YZ
3771 new_gen = (old_gen + 1) % MAX_NR_GENS;
3772
3773 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3774 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3775 /* for folio_end_writeback() */
3776 if (reclaiming)
3777 new_flags |= BIT(PG_reclaim);
3778 } while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3779
3780 lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3781
3782 return new_gen;
3783}
3784
bd74fdae
YZ
3785static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3786 int old_gen, int new_gen)
3787{
3788 int type = folio_is_file_lru(folio);
3789 int zone = folio_zonenum(folio);
3790 int delta = folio_nr_pages(folio);
3791
3792 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3793 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3794
3795 walk->batched++;
3796
3797 walk->nr_pages[old_gen][type][zone] -= delta;
3798 walk->nr_pages[new_gen][type][zone] += delta;
3799}
3800
3801static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3802{
3803 int gen, type, zone;
391655fe 3804 struct lru_gen_folio *lrugen = &lruvec->lrugen;
bd74fdae
YZ
3805
3806 walk->batched = 0;
3807
3808 for_each_gen_type_zone(gen, type, zone) {
3809 enum lru_list lru = type * LRU_INACTIVE_FILE;
3810 int delta = walk->nr_pages[gen][type][zone];
3811
3812 if (!delta)
3813 continue;
3814
3815 walk->nr_pages[gen][type][zone] = 0;
3816 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3817 lrugen->nr_pages[gen][type][zone] + delta);
3818
3819 if (lru_gen_is_active(lruvec, gen))
3820 lru += LRU_ACTIVE;
3821 __update_lru_size(lruvec, lru, zone, delta);
3822 }
3823}
3824
3825static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3826{
3827 struct address_space *mapping;
3828 struct vm_area_struct *vma = args->vma;
3829 struct lru_gen_mm_walk *walk = args->private;
3830
3831 if (!vma_is_accessible(vma))
3832 return true;
3833
3834 if (is_vm_hugetlb_page(vma))
3835 return true;
3836
8788f678
YZ
3837 if (!vma_has_recency(vma))
3838 return true;
3839
3840 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
bd74fdae
YZ
3841 return true;
3842
3843 if (vma == get_gate_vma(vma->vm_mm))
3844 return true;
3845
3846 if (vma_is_anonymous(vma))
3847 return !walk->can_swap;
3848
3849 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3850 return true;
3851
3852 mapping = vma->vm_file->f_mapping;
3853 if (mapping_unevictable(mapping))
3854 return true;
3855
3856 if (shmem_mapping(mapping))
3857 return !walk->can_swap;
3858
3859 /* to exclude special mappings like dax, etc. */
3860 return !mapping->a_ops->read_folio;
3861}
3862
3863/*
3864 * Some userspace memory allocators map many single-page VMAs. Instead of
3865 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3866 * table to reduce zigzags and improve cache performance.
3867 */
3868static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3869 unsigned long *vm_start, unsigned long *vm_end)
3870{
3871 unsigned long start = round_up(*vm_end, size);
3872 unsigned long end = (start | ~mask) + 1;
78ba531f 3873 VMA_ITERATOR(vmi, args->mm, start);
bd74fdae
YZ
3874
3875 VM_WARN_ON_ONCE(mask & size);
3876 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3877
78ba531f 3878 for_each_vma(vmi, args->vma) {
bd74fdae
YZ
3879 if (end && end <= args->vma->vm_start)
3880 return false;
3881
78ba531f 3882 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
bd74fdae 3883 continue;
bd74fdae
YZ
3884
3885 *vm_start = max(start, args->vma->vm_start);
3886 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3887
3888 return true;
3889 }
3890
3891 return false;
3892}
3893
018ee47f
YZ
3894static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3895{
3896 unsigned long pfn = pte_pfn(pte);
3897
3898 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3899
3900 if (!pte_present(pte) || is_zero_pfn(pfn))
3901 return -1;
3902
3903 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3904 return -1;
3905
3906 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3907 return -1;
3908
3909 return pfn;
3910}
3911
bd74fdae
YZ
3912#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3913static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3914{
3915 unsigned long pfn = pmd_pfn(pmd);
3916
3917 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3918
3919 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3920 return -1;
3921
3922 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3923 return -1;
3924
3925 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3926 return -1;
3927
3928 return pfn;
3929}
3930#endif
3931
018ee47f 3932static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
bd74fdae 3933 struct pglist_data *pgdat, bool can_swap)
018ee47f
YZ
3934{
3935 struct folio *folio;
3936
3937 /* try to avoid unnecessary memory loads */
3938 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3939 return NULL;
3940
3941 folio = pfn_folio(pfn);
3942 if (folio_nid(folio) != pgdat->node_id)
3943 return NULL;
3944
3945 if (folio_memcg_rcu(folio) != memcg)
3946 return NULL;
3947
bd74fdae
YZ
3948 /* file VMAs can contain anon pages from COW */
3949 if (!folio_is_file_lru(folio) && !can_swap)
3950 return NULL;
3951
018ee47f
YZ
3952 return folio;
3953}
3954
bd74fdae
YZ
3955static bool suitable_to_scan(int total, int young)
3956{
3957 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3958
3959 /* suitable if the average number of young PTEs per cacheline is >=1 */
3960 return young * n >= total;
3961}
3962
3963static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3964 struct mm_walk *args)
3965{
3966 int i;
3967 pte_t *pte;
3968 spinlock_t *ptl;
3969 unsigned long addr;
3970 int total = 0;
3971 int young = 0;
3972 struct lru_gen_mm_walk *walk = args->private;
3973 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3974 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3975 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3976
3977 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3978
3979 ptl = pte_lockptr(args->mm, pmd);
3980 if (!spin_trylock(ptl))
3981 return false;
3982
3983 arch_enter_lazy_mmu_mode();
3984
3985 pte = pte_offset_map(pmd, start & PMD_MASK);
3986restart:
3987 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3988 unsigned long pfn;
3989 struct folio *folio;
3990
3991 total++;
3992 walk->mm_stats[MM_LEAF_TOTAL]++;
3993
3994 pfn = get_pte_pfn(pte[i], args->vma, addr);
3995 if (pfn == -1)
3996 continue;
3997
3998 if (!pte_young(pte[i])) {
3999 walk->mm_stats[MM_LEAF_OLD]++;
4000 continue;
4001 }
4002
4003 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4004 if (!folio)
4005 continue;
4006
4007 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
4008 VM_WARN_ON_ONCE(true);
4009
4010 young++;
4011 walk->mm_stats[MM_LEAF_YOUNG]++;
4012
4013 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4014 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4015 !folio_test_swapcache(folio)))
4016 folio_mark_dirty(folio);
4017
4018 old_gen = folio_update_gen(folio, new_gen);
4019 if (old_gen >= 0 && old_gen != new_gen)
4020 update_batch_size(walk, folio, old_gen, new_gen);
4021 }
4022
4023 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
4024 goto restart;
4025
4026 pte_unmap(pte);
4027
4028 arch_leave_lazy_mmu_mode();
4029 spin_unlock(ptl);
4030
4031 return suitable_to_scan(total, young);
4032}
4033
4034#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
b5ff4133
A
4035static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
4036 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
bd74fdae
YZ
4037{
4038 int i;
4039 pmd_t *pmd;
4040 spinlock_t *ptl;
4041 struct lru_gen_mm_walk *walk = args->private;
4042 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
4043 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4044 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
4045
4046 VM_WARN_ON_ONCE(pud_leaf(*pud));
4047
4048 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
b5ff4133
A
4049 if (*first == -1) {
4050 *first = addr;
4051 bitmap_zero(bitmap, MIN_LRU_BATCH);
bd74fdae
YZ
4052 return;
4053 }
4054
b5ff4133 4055 i = addr == -1 ? 0 : pmd_index(addr) - pmd_index(*first);
bd74fdae
YZ
4056 if (i && i <= MIN_LRU_BATCH) {
4057 __set_bit(i - 1, bitmap);
4058 return;
4059 }
4060
b5ff4133 4061 pmd = pmd_offset(pud, *first);
bd74fdae
YZ
4062
4063 ptl = pmd_lockptr(args->mm, pmd);
4064 if (!spin_trylock(ptl))
4065 goto done;
4066
4067 arch_enter_lazy_mmu_mode();
4068
4069 do {
4070 unsigned long pfn;
4071 struct folio *folio;
b5ff4133
A
4072
4073 /* don't round down the first address */
4074 addr = i ? (*first & PMD_MASK) + i * PMD_SIZE : *first;
bd74fdae
YZ
4075
4076 pfn = get_pmd_pfn(pmd[i], vma, addr);
4077 if (pfn == -1)
4078 goto next;
4079
4080 if (!pmd_trans_huge(pmd[i])) {
b5ff4133 4081 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
bd74fdae
YZ
4082 pmdp_test_and_clear_young(vma, addr, pmd + i);
4083 goto next;
4084 }
4085
4086 folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4087 if (!folio)
4088 goto next;
4089
4090 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
4091 goto next;
4092
4093 walk->mm_stats[MM_LEAF_YOUNG]++;
4094
4095 if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
4096 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4097 !folio_test_swapcache(folio)))
4098 folio_mark_dirty(folio);
4099
4100 old_gen = folio_update_gen(folio, new_gen);
4101 if (old_gen >= 0 && old_gen != new_gen)
4102 update_batch_size(walk, folio, old_gen, new_gen);
4103next:
4104 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
4105 } while (i <= MIN_LRU_BATCH);
4106
4107 arch_leave_lazy_mmu_mode();
4108 spin_unlock(ptl);
4109done:
b5ff4133 4110 *first = -1;
bd74fdae
YZ
4111}
4112#else
b5ff4133
A
4113static void walk_pmd_range_locked(pud_t *pud, unsigned long addr, struct vm_area_struct *vma,
4114 struct mm_walk *args, unsigned long *bitmap, unsigned long *first)
bd74fdae
YZ
4115{
4116}
4117#endif
4118
4119static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
4120 struct mm_walk *args)
4121{
4122 int i;
4123 pmd_t *pmd;
4124 unsigned long next;
4125 unsigned long addr;
4126 struct vm_area_struct *vma;
b5ff4133
A
4127 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)];
4128 unsigned long first = -1;
bd74fdae 4129 struct lru_gen_mm_walk *walk = args->private;
bd74fdae
YZ
4130
4131 VM_WARN_ON_ONCE(pud_leaf(*pud));
4132
4133 /*
4134 * Finish an entire PMD in two passes: the first only reaches to PTE
4135 * tables to avoid taking the PMD lock; the second, if necessary, takes
4136 * the PMD lock to clear the accessed bit in PMD entries.
4137 */
4138 pmd = pmd_offset(pud, start & PUD_MASK);
4139restart:
4140 /* walk_pte_range() may call get_next_vma() */
4141 vma = args->vma;
4142 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
dab6e717 4143 pmd_t val = pmdp_get_lockless(pmd + i);
bd74fdae
YZ
4144
4145 next = pmd_addr_end(addr, end);
4146
4147 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4148 walk->mm_stats[MM_LEAF_TOTAL]++;
4149 continue;
4150 }
4151
4152#ifdef CONFIG_TRANSPARENT_HUGEPAGE
4153 if (pmd_trans_huge(val)) {
4154 unsigned long pfn = pmd_pfn(val);
4155 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4156
4157 walk->mm_stats[MM_LEAF_TOTAL]++;
4158
4159 if (!pmd_young(val)) {
4160 walk->mm_stats[MM_LEAF_OLD]++;
4161 continue;
4162 }
4163
4164 /* try to avoid unnecessary memory loads */
4165 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4166 continue;
4167
b5ff4133 4168 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
bd74fdae
YZ
4169 continue;
4170 }
4171#endif
4172 walk->mm_stats[MM_NONLEAF_TOTAL]++;
4173
b5ff4133 4174 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG)) {
354ed597
YZ
4175 if (!pmd_young(val))
4176 continue;
bd74fdae 4177
b5ff4133 4178 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &first);
354ed597 4179 }
4aaf269c 4180
bd74fdae
YZ
4181 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4182 continue;
4183
4184 walk->mm_stats[MM_NONLEAF_FOUND]++;
4185
4186 if (!walk_pte_range(&val, addr, next, args))
4187 continue;
4188
4189 walk->mm_stats[MM_NONLEAF_ADDED]++;
4190
4191 /* carry over to the next generation */
4192 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4193 }
4194
b5ff4133 4195 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &first);
bd74fdae
YZ
4196
4197 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4198 goto restart;
4199}
4200
4201static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4202 struct mm_walk *args)
4203{
4204 int i;
4205 pud_t *pud;
4206 unsigned long addr;
4207 unsigned long next;
4208 struct lru_gen_mm_walk *walk = args->private;
4209
4210 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4211
4212 pud = pud_offset(p4d, start & P4D_MASK);
4213restart:
4214 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4215 pud_t val = READ_ONCE(pud[i]);
4216
4217 next = pud_addr_end(addr, end);
4218
4219 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4220 continue;
4221
4222 walk_pmd_range(&val, addr, next, args);
4223
bd74fdae
YZ
4224 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4225 end = (addr | ~PUD_MASK) + 1;
4226 goto done;
4227 }
4228 }
4229
4230 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4231 goto restart;
4232
4233 end = round_up(end, P4D_SIZE);
4234done:
4235 if (!end || !args->vma)
4236 return 1;
4237
4238 walk->next_addr = max(end, args->vma->vm_start);
4239
4240 return -EAGAIN;
4241}
4242
4243static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4244{
4245 static const struct mm_walk_ops mm_walk_ops = {
4246 .test_walk = should_skip_vma,
4247 .p4d_entry = walk_pud_range,
4248 };
4249
4250 int err;
4251 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4252
4253 walk->next_addr = FIRST_USER_ADDRESS;
4254
4255 do {
7f63cf2d
KS
4256 DEFINE_MAX_SEQ(lruvec);
4257
bd74fdae
YZ
4258 err = -EBUSY;
4259
7f63cf2d
KS
4260 /* another thread might have called inc_max_seq() */
4261 if (walk->max_seq != max_seq)
4262 break;
4263
bd74fdae
YZ
4264 /* folio_update_gen() requires stable folio_memcg() */
4265 if (!mem_cgroup_trylock_pages(memcg))
4266 break;
4267
4268 /* the caller might be holding the lock for write */
4269 if (mmap_read_trylock(mm)) {
4270 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4271
4272 mmap_read_unlock(mm);
4273 }
4274
4275 mem_cgroup_unlock_pages();
4276
4277 if (walk->batched) {
4278 spin_lock_irq(&lruvec->lru_lock);
4279 reset_batch_size(lruvec, walk);
4280 spin_unlock_irq(&lruvec->lru_lock);
4281 }
4282
4283 cond_resched();
4284 } while (err == -EAGAIN);
4285}
4286
e9d4e1ee 4287static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
bd74fdae
YZ
4288{
4289 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4290
4291 if (pgdat && current_is_kswapd()) {
4292 VM_WARN_ON_ONCE(walk);
4293
4294 walk = &pgdat->mm_walk;
e9d4e1ee 4295 } else if (!walk && force_alloc) {
bd74fdae
YZ
4296 VM_WARN_ON_ONCE(current_is_kswapd());
4297
4298 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4299 }
4300
4301 current->reclaim_state->mm_walk = walk;
4302
4303 return walk;
4304}
4305
4306static void clear_mm_walk(void)
4307{
4308 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4309
4310 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4311 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4312
4313 current->reclaim_state->mm_walk = NULL;
4314
4315 if (!current_is_kswapd())
4316 kfree(walk);
4317}
4318
d6c3af7d 4319static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
ac35a490 4320{
d6c3af7d
YZ
4321 int zone;
4322 int remaining = MAX_LRU_BATCH;
391655fe 4323 struct lru_gen_folio *lrugen = &lruvec->lrugen;
d6c3af7d
YZ
4324 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4325
4326 if (type == LRU_GEN_ANON && !can_swap)
4327 goto done;
4328
4329 /* prevent cold/hot inversion if force_scan is true */
4330 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6df1b221 4331 struct list_head *head = &lrugen->folios[old_gen][type][zone];
d6c3af7d
YZ
4332
4333 while (!list_empty(head)) {
4334 struct folio *folio = lru_to_folio(head);
4335
4336 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4337 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4338 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4339 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
ac35a490 4340
d6c3af7d 4341 new_gen = folio_inc_gen(lruvec, folio, false);
6df1b221 4342 list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
d6c3af7d
YZ
4343
4344 if (!--remaining)
4345 return false;
4346 }
4347 }
4348done:
ac35a490
YZ
4349 reset_ctrl_pos(lruvec, type, true);
4350 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
d6c3af7d
YZ
4351
4352 return true;
ac35a490
YZ
4353}
4354
4355static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4356{
4357 int gen, type, zone;
4358 bool success = false;
391655fe 4359 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
4360 DEFINE_MIN_SEQ(lruvec);
4361
4362 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4363
4364 /* find the oldest populated generation */
4365 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4366 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4367 gen = lru_gen_from_seq(min_seq[type]);
4368
4369 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
6df1b221 4370 if (!list_empty(&lrugen->folios[gen][type][zone]))
ac35a490
YZ
4371 goto next;
4372 }
4373
4374 min_seq[type]++;
4375 }
4376next:
4377 ;
4378 }
4379
391655fe 4380 /* see the comment on lru_gen_folio */
ac35a490
YZ
4381 if (can_swap) {
4382 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4383 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4384 }
4385
4386 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4387 if (min_seq[type] == lrugen->min_seq[type])
4388 continue;
4389
4390 reset_ctrl_pos(lruvec, type, true);
4391 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4392 success = true;
4393 }
4394
4395 return success;
4396}
4397
d6c3af7d 4398static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
ac35a490
YZ
4399{
4400 int prev, next;
4401 int type, zone;
391655fe 4402 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
4403
4404 spin_lock_irq(&lruvec->lru_lock);
4405
4406 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4407
ac35a490
YZ
4408 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4409 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4410 continue;
4411
d6c3af7d 4412 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
ac35a490 4413
d6c3af7d
YZ
4414 while (!inc_min_seq(lruvec, type, can_swap)) {
4415 spin_unlock_irq(&lruvec->lru_lock);
4416 cond_resched();
4417 spin_lock_irq(&lruvec->lru_lock);
4418 }
ac35a490
YZ
4419 }
4420
4421 /*
4422 * Update the active/inactive LRU sizes for compatibility. Both sides of
4423 * the current max_seq need to be covered, since max_seq+1 can overlap
4424 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4425 * overlap, cold/hot inversion happens.
4426 */
4427 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4428 next = lru_gen_from_seq(lrugen->max_seq + 1);
4429
4430 for (type = 0; type < ANON_AND_FILE; type++) {
4431 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4432 enum lru_list lru = type * LRU_INACTIVE_FILE;
4433 long delta = lrugen->nr_pages[prev][type][zone] -
4434 lrugen->nr_pages[next][type][zone];
4435
4436 if (!delta)
4437 continue;
4438
4439 __update_lru_size(lruvec, lru, zone, delta);
4440 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4441 }
4442 }
4443
4444 for (type = 0; type < ANON_AND_FILE; type++)
4445 reset_ctrl_pos(lruvec, type, false);
4446
1332a809 4447 WRITE_ONCE(lrugen->timestamps[next], jiffies);
ac35a490
YZ
4448 /* make sure preceding modifications appear */
4449 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
bd74fdae 4450
ac35a490
YZ
4451 spin_unlock_irq(&lruvec->lru_lock);
4452}
4453
bd74fdae 4454static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
d6c3af7d 4455 struct scan_control *sc, bool can_swap, bool force_scan)
bd74fdae
YZ
4456{
4457 bool success;
4458 struct lru_gen_mm_walk *walk;
4459 struct mm_struct *mm = NULL;
391655fe 4460 struct lru_gen_folio *lrugen = &lruvec->lrugen;
bd74fdae
YZ
4461
4462 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4463
4464 /* see the comment in iterate_mm_list() */
4465 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4466 success = false;
4467 goto done;
4468 }
4469
4470 /*
4471 * If the hardware doesn't automatically set the accessed bit, fallback
4472 * to lru_gen_look_around(), which only clears the accessed bit in a
4473 * handful of PTEs. Spreading the work out over a period of time usually
4474 * is less efficient, but it avoids bursty page faults.
4475 */
f386e931 4476 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
bd74fdae
YZ
4477 success = iterate_mm_list_nowalk(lruvec, max_seq);
4478 goto done;
4479 }
4480
e9d4e1ee 4481 walk = set_mm_walk(NULL, true);
bd74fdae
YZ
4482 if (!walk) {
4483 success = iterate_mm_list_nowalk(lruvec, max_seq);
4484 goto done;
4485 }
4486
4487 walk->lruvec = lruvec;
4488 walk->max_seq = max_seq;
4489 walk->can_swap = can_swap;
d6c3af7d 4490 walk->force_scan = force_scan;
bd74fdae
YZ
4491
4492 do {
4493 success = iterate_mm_list(lruvec, walk, &mm);
4494 if (mm)
4495 walk_mm(lruvec, mm, walk);
bd74fdae
YZ
4496 } while (mm);
4497done:
7f63cf2d
KS
4498 if (success)
4499 inc_max_seq(lruvec, can_swap, force_scan);
bd74fdae 4500
7f63cf2d 4501 return success;
bd74fdae
YZ
4502}
4503
7b8144e6
A
4504/******************************************************************************
4505 * working set protection
4506 ******************************************************************************/
4507
7348cc91 4508static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
ac35a490 4509{
7348cc91
YZ
4510 int gen, type, zone;
4511 unsigned long total = 0;
4512 bool can_swap = get_swappiness(lruvec, sc);
4513 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
4514 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4515 DEFINE_MAX_SEQ(lruvec);
4516 DEFINE_MIN_SEQ(lruvec);
4517
7348cc91
YZ
4518 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4519 unsigned long seq;
ac35a490 4520
7348cc91
YZ
4521 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4522 gen = lru_gen_from_seq(seq);
ac35a490 4523
7348cc91
YZ
4524 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4525 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4526 }
4527 }
ac35a490 4528
7348cc91
YZ
4529 /* whether the size is big enough to be helpful */
4530 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4531}
1332a809 4532
7348cc91
YZ
4533static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4534 unsigned long min_ttl)
4535{
4536 int gen;
4537 unsigned long birth;
4538 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4539 DEFINE_MIN_SEQ(lruvec);
1332a809 4540
7348cc91
YZ
4541 /* see the comment on lru_gen_folio */
4542 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4543 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
1332a809 4544
7348cc91
YZ
4545 if (time_is_after_jiffies(birth + min_ttl))
4546 return false;
1332a809 4547
7348cc91
YZ
4548 if (!lruvec_is_sizable(lruvec, sc))
4549 return false;
4550
4551 mem_cgroup_calculate_protection(NULL, memcg);
4552
4553 return !mem_cgroup_below_min(NULL, memcg);
ac35a490
YZ
4554}
4555
1332a809
YZ
4556/* to protect the working set of the last N jiffies */
4557static unsigned long lru_gen_min_ttl __read_mostly;
4558
ac35a490
YZ
4559static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4560{
4561 struct mem_cgroup *memcg;
1332a809 4562 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
ac35a490
YZ
4563
4564 VM_WARN_ON_ONCE(!current_is_kswapd());
4565
7348cc91
YZ
4566 /* check the order to exclude compaction-induced reclaim */
4567 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
f76c8337 4568 return;
bd74fdae 4569
ac35a490
YZ
4570 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4571 do {
4572 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4573
7348cc91
YZ
4574 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4575 mem_cgroup_iter_break(NULL, memcg);
4576 return;
4577 }
ac35a490
YZ
4578
4579 cond_resched();
4580 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
bd74fdae 4581
1332a809
YZ
4582 /*
4583 * The main goal is to OOM kill if every generation from all memcgs is
4584 * younger than min_ttl. However, another possibility is all memcgs are
7348cc91 4585 * either too small or below min.
1332a809
YZ
4586 */
4587 if (mutex_trylock(&oom_lock)) {
4588 struct oom_control oc = {
4589 .gfp_mask = sc->gfp_mask,
4590 };
4591
4592 out_of_memory(&oc);
4593
4594 mutex_unlock(&oom_lock);
4595 }
ac35a490
YZ
4596}
4597
db19a43d
A
4598/******************************************************************************
4599 * rmap/PT walk feedback
4600 ******************************************************************************/
4601
018ee47f 4602/*
49fd9b6d 4603 * This function exploits spatial locality when shrink_folio_list() walks the
bd74fdae
YZ
4604 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4605 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4606 * the PTE table to the Bloom filter. This forms a feedback loop between the
4607 * eviction and the aging.
018ee47f
YZ
4608 */
4609void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4610{
4611 int i;
018ee47f
YZ
4612 unsigned long start;
4613 unsigned long end;
bd74fdae
YZ
4614 struct lru_gen_mm_walk *walk;
4615 int young = 0;
abf08672
A
4616 pte_t *pte = pvmw->pte;
4617 unsigned long addr = pvmw->address;
018ee47f
YZ
4618 struct folio *folio = pfn_folio(pvmw->pfn);
4619 struct mem_cgroup *memcg = folio_memcg(folio);
4620 struct pglist_data *pgdat = folio_pgdat(folio);
4621 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4622 DEFINE_MAX_SEQ(lruvec);
4623 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4624
4625 lockdep_assert_held(pvmw->ptl);
4626 VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4627
4628 if (spin_is_contended(pvmw->ptl))
4629 return;
4630
bd74fdae
YZ
4631 /* avoid taking the LRU lock under the PTL when possible */
4632 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4633
abf08672
A
4634 start = max(addr & PMD_MASK, pvmw->vma->vm_start);
4635 end = min(addr | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
018ee47f
YZ
4636
4637 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
abf08672 4638 if (addr - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
018ee47f 4639 end = start + MIN_LRU_BATCH * PAGE_SIZE;
abf08672 4640 else if (end - addr < MIN_LRU_BATCH * PAGE_SIZE / 2)
018ee47f
YZ
4641 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4642 else {
abf08672
A
4643 start = addr - MIN_LRU_BATCH * PAGE_SIZE / 2;
4644 end = addr + MIN_LRU_BATCH * PAGE_SIZE / 2;
018ee47f
YZ
4645 }
4646 }
4647
abf08672
A
4648 /* folio_update_gen() requires stable folio_memcg() */
4649 if (!mem_cgroup_trylock_pages(memcg))
4650 return;
018ee47f 4651
018ee47f
YZ
4652 arch_enter_lazy_mmu_mode();
4653
abf08672
A
4654 pte -= (addr - start) / PAGE_SIZE;
4655
018ee47f
YZ
4656 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4657 unsigned long pfn;
4658
4659 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4660 if (pfn == -1)
4661 continue;
4662
4663 if (!pte_young(pte[i]))
4664 continue;
4665
bd74fdae 4666 folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
018ee47f
YZ
4667 if (!folio)
4668 continue;
4669
4670 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4671 VM_WARN_ON_ONCE(true);
4672
bd74fdae
YZ
4673 young++;
4674
018ee47f
YZ
4675 if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4676 !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4677 !folio_test_swapcache(folio)))
4678 folio_mark_dirty(folio);
4679
abf08672
A
4680 if (walk) {
4681 old_gen = folio_update_gen(folio, new_gen);
4682 if (old_gen >= 0 && old_gen != new_gen)
4683 update_batch_size(walk, folio, old_gen, new_gen);
4684
4685 continue;
4686 }
4687
018ee47f
YZ
4688 old_gen = folio_lru_gen(folio);
4689 if (old_gen < 0)
4690 folio_set_referenced(folio);
4691 else if (old_gen != new_gen)
abf08672 4692 folio_activate(folio);
018ee47f
YZ
4693 }
4694
4695 arch_leave_lazy_mmu_mode();
abf08672 4696 mem_cgroup_unlock_pages();
018ee47f 4697
bd74fdae
YZ
4698 /* feedback from rmap walkers to page table walkers */
4699 if (suitable_to_scan(i, young))
4700 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
018ee47f
YZ
4701}
4702
36c7b4db
A
4703/******************************************************************************
4704 * memcg LRU
4705 ******************************************************************************/
4706
4707/* see the comment on MEMCG_NR_GENS */
4708enum {
4709 MEMCG_LRU_NOP,
4710 MEMCG_LRU_HEAD,
4711 MEMCG_LRU_TAIL,
4712 MEMCG_LRU_OLD,
4713 MEMCG_LRU_YOUNG,
4714};
4715
4716#ifdef CONFIG_MEMCG
4717
4718static int lru_gen_memcg_seg(struct lruvec *lruvec)
4719{
4720 return READ_ONCE(lruvec->lrugen.seg);
4721}
4722
4723static void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
4724{
4725 int seg;
4726 int old, new;
4727 int bin = get_random_u32_below(MEMCG_NR_BINS);
4728 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4729
4730 spin_lock(&pgdat->memcg_lru.lock);
4731
4732 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4733
4734 seg = 0;
4735 new = old = lruvec->lrugen.gen;
4736
4737 /* see the comment on MEMCG_NR_GENS */
4738 if (op == MEMCG_LRU_HEAD)
4739 seg = MEMCG_LRU_HEAD;
4740 else if (op == MEMCG_LRU_TAIL)
4741 seg = MEMCG_LRU_TAIL;
4742 else if (op == MEMCG_LRU_OLD)
4743 new = get_memcg_gen(pgdat->memcg_lru.seq);
4744 else if (op == MEMCG_LRU_YOUNG)
4745 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
4746 else
4747 VM_WARN_ON_ONCE(true);
4748
4749 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4750
4751 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
4752 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4753 else
4754 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
4755
4756 pgdat->memcg_lru.nr_memcgs[old]--;
4757 pgdat->memcg_lru.nr_memcgs[new]++;
4758
4759 lruvec->lrugen.gen = new;
4760 WRITE_ONCE(lruvec->lrugen.seg, seg);
4761
4762 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
4763 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4764
4765 spin_unlock(&pgdat->memcg_lru.lock);
4766}
4767
4768void lru_gen_online_memcg(struct mem_cgroup *memcg)
4769{
4770 int gen;
4771 int nid;
4772 int bin = get_random_u32_below(MEMCG_NR_BINS);
4773
4774 for_each_node(nid) {
4775 struct pglist_data *pgdat = NODE_DATA(nid);
4776 struct lruvec *lruvec = get_lruvec(memcg, nid);
4777
4778 spin_lock(&pgdat->memcg_lru.lock);
4779
4780 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
4781
4782 gen = get_memcg_gen(pgdat->memcg_lru.seq);
4783
4784 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
4785 pgdat->memcg_lru.nr_memcgs[gen]++;
4786
4787 lruvec->lrugen.gen = gen;
4788
4789 spin_unlock(&pgdat->memcg_lru.lock);
4790 }
4791}
4792
4793void lru_gen_offline_memcg(struct mem_cgroup *memcg)
4794{
4795 int nid;
4796
4797 for_each_node(nid) {
4798 struct lruvec *lruvec = get_lruvec(memcg, nid);
4799
4800 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
4801 }
4802}
4803
4804void lru_gen_release_memcg(struct mem_cgroup *memcg)
4805{
4806 int gen;
4807 int nid;
4808
4809 for_each_node(nid) {
4810 struct pglist_data *pgdat = NODE_DATA(nid);
4811 struct lruvec *lruvec = get_lruvec(memcg, nid);
4812
4813 spin_lock(&pgdat->memcg_lru.lock);
4814
4815 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
4816
4817 gen = lruvec->lrugen.gen;
4818
4819 hlist_nulls_del_rcu(&lruvec->lrugen.list);
4820 pgdat->memcg_lru.nr_memcgs[gen]--;
4821
4822 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
4823 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
4824
4825 spin_unlock(&pgdat->memcg_lru.lock);
4826 }
4827}
4828
4829void lru_gen_soft_reclaim(struct lruvec *lruvec)
4830{
4831 /* see the comment on MEMCG_NR_GENS */
4832 if (lru_gen_memcg_seg(lruvec) != MEMCG_LRU_HEAD)
4833 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_HEAD);
4834}
4835
4836#else /* !CONFIG_MEMCG */
4837
4838static int lru_gen_memcg_seg(struct lruvec *lruvec)
4839{
4840 return 0;
4841}
4842
4843#endif
4844
ac35a490
YZ
4845/******************************************************************************
4846 * the eviction
4847 ******************************************************************************/
4848
4849static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4850{
4851 bool success;
4852 int gen = folio_lru_gen(folio);
4853 int type = folio_is_file_lru(folio);
4854 int zone = folio_zonenum(folio);
4855 int delta = folio_nr_pages(folio);
4856 int refs = folio_lru_refs(folio);
4857 int tier = lru_tier_from_refs(refs);
391655fe 4858 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
4859
4860 VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4861
4862 /* unevictable */
4863 if (!folio_evictable(folio)) {
4864 success = lru_gen_del_folio(lruvec, folio, true);
4865 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4866 folio_set_unevictable(folio);
4867 lruvec_add_folio(lruvec, folio);
4868 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4869 return true;
4870 }
4871
4872 /* dirty lazyfree */
4873 if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4874 success = lru_gen_del_folio(lruvec, folio, true);
4875 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4876 folio_set_swapbacked(folio);
4877 lruvec_add_folio_tail(lruvec, folio);
4878 return true;
4879 }
4880
018ee47f
YZ
4881 /* promoted */
4882 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
6df1b221 4883 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
018ee47f
YZ
4884 return true;
4885 }
4886
ac35a490
YZ
4887 /* protected */
4888 if (tier > tier_idx) {
4889 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4890
4891 gen = folio_inc_gen(lruvec, folio, false);
6df1b221 4892 list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
ac35a490
YZ
4893
4894 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4895 lrugen->protected[hist][type][tier - 1] + delta);
4896 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4897 return true;
4898 }
4899
4900 /* waiting for writeback */
4901 if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4902 (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4903 gen = folio_inc_gen(lruvec, folio, true);
6df1b221 4904 list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
ac35a490
YZ
4905 return true;
4906 }
4907
4908 return false;
4909}
4910
4911static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4912{
4913 bool success;
4914
ac35a490 4915 /* swapping inhibited */
e9d4e1ee 4916 if (!(sc->gfp_mask & __GFP_IO) &&
ac35a490
YZ
4917 (folio_test_dirty(folio) ||
4918 (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4919 return false;
4920
4921 /* raced with release_pages() */
4922 if (!folio_try_get(folio))
4923 return false;
4924
4925 /* raced with another isolation */
4926 if (!folio_test_clear_lru(folio)) {
4927 folio_put(folio);
4928 return false;
4929 }
4930
4931 /* see the comment on MAX_NR_TIERS */
4932 if (!folio_test_referenced(folio))
4933 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4934
49fd9b6d 4935 /* for shrink_folio_list() */
ac35a490
YZ
4936 folio_clear_reclaim(folio);
4937 folio_clear_referenced(folio);
4938
4939 success = lru_gen_del_folio(lruvec, folio, true);
4940 VM_WARN_ON_ONCE_FOLIO(!success, folio);
4941
4942 return true;
4943}
4944
4945static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4946 int type, int tier, struct list_head *list)
4947{
4948 int gen, zone;
4949 enum vm_event_item item;
4950 int sorted = 0;
4951 int scanned = 0;
4952 int isolated = 0;
4953 int remaining = MAX_LRU_BATCH;
391655fe 4954 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ac35a490
YZ
4955 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4956
4957 VM_WARN_ON_ONCE(!list_empty(list));
4958
4959 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4960 return 0;
4961
4962 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4963
4964 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4965 LIST_HEAD(moved);
4966 int skipped = 0;
6df1b221 4967 struct list_head *head = &lrugen->folios[gen][type][zone];
ac35a490
YZ
4968
4969 while (!list_empty(head)) {
4970 struct folio *folio = lru_to_folio(head);
4971 int delta = folio_nr_pages(folio);
4972
4973 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4974 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4975 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4976 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4977
4978 scanned += delta;
4979
4980 if (sort_folio(lruvec, folio, tier))
4981 sorted += delta;
4982 else if (isolate_folio(lruvec, folio, sc)) {
4983 list_add(&folio->lru, list);
4984 isolated += delta;
4985 } else {
4986 list_move(&folio->lru, &moved);
4987 skipped += delta;
4988 }
4989
4990 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4991 break;
4992 }
4993
4994 if (skipped) {
4995 list_splice(&moved, head);
4996 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4997 }
4998
4999 if (!remaining || isolated >= MIN_LRU_BATCH)
5000 break;
5001 }
5002
57e9cc50 5003 item = PGSCAN_KSWAPD + reclaimer_offset();
ac35a490
YZ
5004 if (!cgroup_reclaim(sc)) {
5005 __count_vm_events(item, isolated);
5006 __count_vm_events(PGREFILL, sorted);
5007 }
5008 __count_memcg_events(memcg, item, isolated);
5009 __count_memcg_events(memcg, PGREFILL, sorted);
5010 __count_vm_events(PGSCAN_ANON + type, isolated);
5011
5012 /*
e9d4e1ee
YZ
5013 * There might not be eligible folios due to reclaim_idx. Check the
5014 * remaining to prevent livelock if it's not making progress.
ac35a490
YZ
5015 */
5016 return isolated || !remaining ? scanned : 0;
5017}
5018
5019static int get_tier_idx(struct lruvec *lruvec, int type)
5020{
5021 int tier;
5022 struct ctrl_pos sp, pv;
5023
5024 /*
5025 * To leave a margin for fluctuations, use a larger gain factor (1:2).
5026 * This value is chosen because any other tier would have at least twice
5027 * as many refaults as the first tier.
5028 */
5029 read_ctrl_pos(lruvec, type, 0, 1, &sp);
5030 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5031 read_ctrl_pos(lruvec, type, tier, 2, &pv);
5032 if (!positive_ctrl_err(&sp, &pv))
5033 break;
5034 }
5035
5036 return tier - 1;
5037}
5038
5039static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
5040{
5041 int type, tier;
5042 struct ctrl_pos sp, pv;
5043 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
5044
5045 /*
5046 * Compare the first tier of anon with that of file to determine which
5047 * type to scan. Also need to compare other tiers of the selected type
5048 * with the first tier of the other type to determine the last tier (of
5049 * the selected type) to evict.
5050 */
5051 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
5052 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
5053 type = positive_ctrl_err(&sp, &pv);
5054
5055 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
5056 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
5057 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
5058 if (!positive_ctrl_err(&sp, &pv))
5059 break;
5060 }
5061
5062 *tier_idx = tier - 1;
5063
5064 return type;
5065}
5066
5067static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
5068 int *type_scanned, struct list_head *list)
5069{
5070 int i;
5071 int type;
5072 int scanned;
5073 int tier = -1;
5074 DEFINE_MIN_SEQ(lruvec);
5075
5076 /*
5077 * Try to make the obvious choice first. When anon and file are both
5078 * available from the same generation, interpret swappiness 1 as file
5079 * first and 200 as anon first.
5080 */
5081 if (!swappiness)
5082 type = LRU_GEN_FILE;
5083 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
5084 type = LRU_GEN_ANON;
5085 else if (swappiness == 1)
5086 type = LRU_GEN_FILE;
5087 else if (swappiness == 200)
5088 type = LRU_GEN_ANON;
5089 else
5090 type = get_type_to_scan(lruvec, swappiness, &tier);
5091
5092 for (i = !swappiness; i < ANON_AND_FILE; i++) {
5093 if (tier < 0)
5094 tier = get_tier_idx(lruvec, type);
5095
5096 scanned = scan_folios(lruvec, sc, type, tier, list);
5097 if (scanned)
5098 break;
5099
5100 type = !type;
5101 tier = -1;
5102 }
5103
5104 *type_scanned = type;
5105
5106 return scanned;
5107}
5108
a579086c 5109static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
ac35a490
YZ
5110{
5111 int type;
5112 int scanned;
5113 int reclaimed;
5114 LIST_HEAD(list);
359a5e14 5115 LIST_HEAD(clean);
ac35a490 5116 struct folio *folio;
359a5e14 5117 struct folio *next;
ac35a490
YZ
5118 enum vm_event_item item;
5119 struct reclaim_stat stat;
bd74fdae 5120 struct lru_gen_mm_walk *walk;
359a5e14 5121 bool skip_retry = false;
ac35a490
YZ
5122 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5123 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5124
5125 spin_lock_irq(&lruvec->lru_lock);
5126
5127 scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5128
5129 scanned += try_to_inc_min_seq(lruvec, swappiness);
5130
5131 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5132 scanned = 0;
5133
5134 spin_unlock_irq(&lruvec->lru_lock);
5135
5136 if (list_empty(&list))
5137 return scanned;
359a5e14 5138retry:
49fd9b6d 5139 reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
359a5e14 5140 sc->nr_reclaimed += reclaimed;
ac35a490 5141
359a5e14
YZ
5142 list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5143 if (!folio_evictable(folio)) {
5144 list_del(&folio->lru);
5145 folio_putback_lru(folio);
5146 continue;
5147 }
ac35a490 5148
ac35a490 5149 if (folio_test_reclaim(folio) &&
359a5e14
YZ
5150 (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5151 /* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5152 if (folio_test_workingset(folio))
5153 folio_set_referenced(folio);
5154 continue;
5155 }
5156
5157 if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5158 folio_mapped(folio) || folio_test_locked(folio) ||
5159 folio_test_dirty(folio) || folio_test_writeback(folio)) {
5160 /* don't add rejected folios to the oldest generation */
5161 set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5162 BIT(PG_active));
5163 continue;
5164 }
5165
5166 /* retry folios that may have missed folio_rotate_reclaimable() */
5167 list_move(&folio->lru, &clean);
5168 sc->nr_scanned -= folio_nr_pages(folio);
ac35a490
YZ
5169 }
5170
5171 spin_lock_irq(&lruvec->lru_lock);
5172
49fd9b6d 5173 move_folios_to_lru(lruvec, &list);
ac35a490 5174
bd74fdae
YZ
5175 walk = current->reclaim_state->mm_walk;
5176 if (walk && walk->batched)
5177 reset_batch_size(lruvec, walk);
5178
57e9cc50 5179 item = PGSTEAL_KSWAPD + reclaimer_offset();
ac35a490
YZ
5180 if (!cgroup_reclaim(sc))
5181 __count_vm_events(item, reclaimed);
5182 __count_memcg_events(memcg, item, reclaimed);
5183 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
5184
5185 spin_unlock_irq(&lruvec->lru_lock);
5186
5187 mem_cgroup_uncharge_list(&list);
5188 free_unref_page_list(&list);
5189
359a5e14
YZ
5190 INIT_LIST_HEAD(&list);
5191 list_splice_init(&clean, &list);
5192
5193 if (!list_empty(&list)) {
5194 skip_retry = true;
5195 goto retry;
5196 }
ac35a490
YZ
5197
5198 return scanned;
5199}
5200
77d4459a
YZ
5201static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
5202 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
5203{
5204 int gen, type, zone;
5205 unsigned long old = 0;
5206 unsigned long young = 0;
5207 unsigned long total = 0;
5208 struct lru_gen_folio *lrugen = &lruvec->lrugen;
5209 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5210 DEFINE_MIN_SEQ(lruvec);
5211
5212 /* whether this lruvec is completely out of cold folios */
5213 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
5214 *nr_to_scan = 0;
5215 return true;
5216 }
5217
5218 for (type = !can_swap; type < ANON_AND_FILE; type++) {
5219 unsigned long seq;
5220
5221 for (seq = min_seq[type]; seq <= max_seq; seq++) {
5222 unsigned long size = 0;
5223
5224 gen = lru_gen_from_seq(seq);
5225
5226 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5227 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5228
5229 total += size;
5230 if (seq == max_seq)
5231 young += size;
5232 else if (seq + MIN_NR_GENS == max_seq)
5233 old += size;
5234 }
5235 }
5236
5237 /* try to scrape all its memory if this memcg was deleted */
5238 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
5239
5240 /*
5241 * The aging tries to be lazy to reduce the overhead, while the eviction
5242 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
5243 * ideal number of generations is MIN_NR_GENS+1.
5244 */
5245 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
5246 return false;
5247
5248 /*
5249 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
5250 * of the total number of pages for each generation. A reasonable range
5251 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
5252 * aging cares about the upper bound of hot pages, while the eviction
5253 * cares about the lower bound of cold pages.
5254 */
5255 if (young * MIN_NR_GENS > total)
5256 return true;
5257 if (old * (MIN_NR_GENS + 2) < total)
5258 return true;
5259
5260 return false;
5261}
5262
bd74fdae
YZ
5263/*
5264 * For future optimizations:
5265 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5266 * reclaim.
5267 */
e4dde56c 5268static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
ac35a490 5269{
ac35a490
YZ
5270 unsigned long nr_to_scan;
5271 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5272 DEFINE_MAX_SEQ(lruvec);
ac35a490 5273
e9d4e1ee 5274 if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg))
ac35a490
YZ
5275 return 0;
5276
7348cc91 5277 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
ac35a490
YZ
5278 return nr_to_scan;
5279
5280 /* skip the aging path at the default priority */
5281 if (sc->priority == DEF_PRIORITY)
7348cc91 5282 return nr_to_scan;
ac35a490 5283
7348cc91 5284 /* skip this lruvec as it's low on cold folios */
e4dde56c 5285 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
ac35a490
YZ
5286}
5287
a579086c 5288static unsigned long get_nr_to_reclaim(struct scan_control *sc)
f76c8337 5289{
a579086c
YZ
5290 /* don't abort memcg reclaim to ensure fairness */
5291 if (!global_reclaim(sc))
5292 return -1;
f76c8337 5293
a579086c 5294 return max(sc->nr_to_reclaim, compact_gap(sc->order));
f76c8337
YZ
5295}
5296
e4dde56c 5297static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
ac35a490 5298{
e4dde56c 5299 long nr_to_scan;
ac35a490 5300 unsigned long scanned = 0;
a579086c 5301 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
e9d4e1ee
YZ
5302 int swappiness = get_swappiness(lruvec, sc);
5303
5304 /* clean file folios are more likely to exist */
5305 if (swappiness && !(sc->gfp_mask & __GFP_IO))
5306 swappiness = 1;
ac35a490 5307
ac35a490
YZ
5308 while (true) {
5309 int delta;
ac35a490 5310
7348cc91 5311 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
e4dde56c 5312 if (nr_to_scan <= 0)
7348cc91 5313 break;
ac35a490 5314
a579086c 5315 delta = evict_folios(lruvec, sc, swappiness);
ac35a490 5316 if (!delta)
7348cc91 5317 break;
ac35a490
YZ
5318
5319 scanned += delta;
5320 if (scanned >= nr_to_scan)
5321 break;
5322
a579086c 5323 if (sc->nr_reclaimed >= nr_to_reclaim)
f76c8337
YZ
5324 break;
5325
ac35a490
YZ
5326 cond_resched();
5327 }
5328
e4dde56c
YZ
5329 /* whether try_to_inc_max_seq() was successful */
5330 return nr_to_scan < 0;
5331}
5332
5333static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
5334{
5335 bool success;
5336 unsigned long scanned = sc->nr_scanned;
5337 unsigned long reclaimed = sc->nr_reclaimed;
5338 int seg = lru_gen_memcg_seg(lruvec);
5339 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5340 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5341
5342 /* see the comment on MEMCG_NR_GENS */
5343 if (!lruvec_is_sizable(lruvec, sc))
5344 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5345
5346 mem_cgroup_calculate_protection(NULL, memcg);
5347
5348 if (mem_cgroup_below_min(NULL, memcg))
5349 return MEMCG_LRU_YOUNG;
5350
5351 if (mem_cgroup_below_low(NULL, memcg)) {
5352 /* see the comment on MEMCG_NR_GENS */
5353 if (seg != MEMCG_LRU_TAIL)
5354 return MEMCG_LRU_TAIL;
5355
5356 memcg_memory_event(memcg, MEMCG_LOW);
5357 }
5358
5359 success = try_to_shrink_lruvec(lruvec, sc);
5360
5361 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5362
5363 if (!sc->proactive)
5364 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5365 sc->nr_reclaimed - reclaimed);
5366
583c27a1 5367 flush_reclaim_state(sc);
e4dde56c
YZ
5368
5369 return success ? MEMCG_LRU_YOUNG : 0;
5370}
5371
5372#ifdef CONFIG_MEMCG
5373
5374static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5375{
9f550d78 5376 int op;
e4dde56c
YZ
5377 int gen;
5378 int bin;
5379 int first_bin;
5380 struct lruvec *lruvec;
5381 struct lru_gen_folio *lrugen;
9f550d78 5382 struct mem_cgroup *memcg;
e4dde56c 5383 const struct hlist_nulls_node *pos;
e4dde56c
YZ
5384 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5385
5386 bin = first_bin = get_random_u32_below(MEMCG_NR_BINS);
5387restart:
9f550d78
YZ
5388 op = 0;
5389 memcg = NULL;
e4dde56c
YZ
5390 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5391
5392 rcu_read_lock();
5393
5394 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5395 if (op)
5396 lru_gen_rotate_memcg(lruvec, op);
5397
5398 mem_cgroup_put(memcg);
5399
5400 lruvec = container_of(lrugen, struct lruvec, lrugen);
5401 memcg = lruvec_memcg(lruvec);
5402
5403 if (!mem_cgroup_tryget(memcg)) {
5404 op = 0;
5405 memcg = NULL;
5406 continue;
5407 }
5408
5409 rcu_read_unlock();
5410
5411 op = shrink_one(lruvec, sc);
5412
e4dde56c 5413 rcu_read_lock();
9f550d78
YZ
5414
5415 if (sc->nr_reclaimed >= nr_to_reclaim)
5416 break;
e4dde56c
YZ
5417 }
5418
5419 rcu_read_unlock();
5420
9f550d78
YZ
5421 if (op)
5422 lru_gen_rotate_memcg(lruvec, op);
5423
5424 mem_cgroup_put(memcg);
5425
5426 if (sc->nr_reclaimed >= nr_to_reclaim)
5427 return;
5428
e4dde56c
YZ
5429 /* restart if raced with lru_gen_rotate_memcg() */
5430 if (gen != get_nulls_value(pos))
5431 goto restart;
5432
5433 /* try the rest of the bins of the current generation */
5434 bin = get_memcg_bin(bin + 1);
5435 if (bin != first_bin)
5436 goto restart;
e4dde56c
YZ
5437}
5438
5439static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5440{
5441 struct blk_plug plug;
5442
5443 VM_WARN_ON_ONCE(global_reclaim(sc));
e9d4e1ee 5444 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
e4dde56c
YZ
5445
5446 lru_add_drain();
5447
5448 blk_start_plug(&plug);
5449
e9d4e1ee 5450 set_mm_walk(NULL, sc->proactive);
e4dde56c
YZ
5451
5452 if (try_to_shrink_lruvec(lruvec, sc))
5453 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5454
5455 clear_mm_walk();
5456
5457 blk_finish_plug(&plug);
5458}
5459
5460#else /* !CONFIG_MEMCG */
5461
5462static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5463{
5464 BUILD_BUG();
5465}
5466
5467static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5468{
5469 BUILD_BUG();
5470}
5471
5472#endif
5473
5474static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5475{
5476 int priority;
5477 unsigned long reclaimable;
5478 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5479
5480 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5481 return;
5482 /*
5483 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5484 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5485 * estimated reclaimed_to_scanned_ratio = inactive / total.
5486 */
5487 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5488 if (get_swappiness(lruvec, sc))
5489 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5490
5491 reclaimable /= MEMCG_NR_GENS;
5492
5493 /* round down reclaimable and round up sc->nr_to_reclaim */
5494 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5495
5496 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5497}
5498
5499static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5500{
5501 struct blk_plug plug;
5502 unsigned long reclaimed = sc->nr_reclaimed;
5503
5504 VM_WARN_ON_ONCE(!global_reclaim(sc));
5505
e9d4e1ee
YZ
5506 /*
5507 * Unmapped clean folios are already prioritized. Scanning for more of
5508 * them is likely futile and can cause high reclaim latency when there
5509 * is a large number of memcgs.
5510 */
5511 if (!sc->may_writepage || !sc->may_unmap)
5512 goto done;
5513
e4dde56c
YZ
5514 lru_add_drain();
5515
5516 blk_start_plug(&plug);
5517
e9d4e1ee 5518 set_mm_walk(pgdat, sc->proactive);
e4dde56c
YZ
5519
5520 set_initial_priority(pgdat, sc);
5521
5522 if (current_is_kswapd())
5523 sc->nr_reclaimed = 0;
5524
5525 if (mem_cgroup_disabled())
5526 shrink_one(&pgdat->__lruvec, sc);
5527 else
5528 shrink_many(pgdat, sc);
5529
5530 if (current_is_kswapd())
5531 sc->nr_reclaimed += reclaimed;
5532
bd74fdae
YZ
5533 clear_mm_walk();
5534
ac35a490 5535 blk_finish_plug(&plug);
e9d4e1ee 5536done:
e4dde56c
YZ
5537 /* kswapd should never fail */
5538 pgdat->kswapd_failures = 0;
5539}
5540
354ed597
YZ
5541/******************************************************************************
5542 * state change
5543 ******************************************************************************/
5544
5545static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5546{
391655fe 5547 struct lru_gen_folio *lrugen = &lruvec->lrugen;
354ed597
YZ
5548
5549 if (lrugen->enabled) {
5550 enum lru_list lru;
5551
5552 for_each_evictable_lru(lru) {
5553 if (!list_empty(&lruvec->lists[lru]))
5554 return false;
5555 }
5556 } else {
5557 int gen, type, zone;
5558
5559 for_each_gen_type_zone(gen, type, zone) {
6df1b221 5560 if (!list_empty(&lrugen->folios[gen][type][zone]))
354ed597
YZ
5561 return false;
5562 }
5563 }
5564
5565 return true;
5566}
5567
5568static bool fill_evictable(struct lruvec *lruvec)
5569{
5570 enum lru_list lru;
5571 int remaining = MAX_LRU_BATCH;
5572
5573 for_each_evictable_lru(lru) {
5574 int type = is_file_lru(lru);
5575 bool active = is_active_lru(lru);
5576 struct list_head *head = &lruvec->lists[lru];
5577
5578 while (!list_empty(head)) {
5579 bool success;
5580 struct folio *folio = lru_to_folio(head);
5581
5582 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5583 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5584 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5585 VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5586
5587 lruvec_del_folio(lruvec, folio);
5588 success = lru_gen_add_folio(lruvec, folio, false);
5589 VM_WARN_ON_ONCE(!success);
5590
5591 if (!--remaining)
5592 return false;
5593 }
5594 }
5595
5596 return true;
5597}
5598
5599static bool drain_evictable(struct lruvec *lruvec)
5600{
5601 int gen, type, zone;
5602 int remaining = MAX_LRU_BATCH;
5603
5604 for_each_gen_type_zone(gen, type, zone) {
6df1b221 5605 struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
354ed597
YZ
5606
5607 while (!list_empty(head)) {
5608 bool success;
5609 struct folio *folio = lru_to_folio(head);
5610
5611 VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5612 VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5613 VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5614 VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5615
5616 success = lru_gen_del_folio(lruvec, folio, false);
5617 VM_WARN_ON_ONCE(!success);
5618 lruvec_add_folio(lruvec, folio);
5619
5620 if (!--remaining)
5621 return false;
5622 }
5623 }
5624
5625 return true;
5626}
5627
5628static void lru_gen_change_state(bool enabled)
5629{
5630 static DEFINE_MUTEX(state_mutex);
5631
5632 struct mem_cgroup *memcg;
5633
5634 cgroup_lock();
5635 cpus_read_lock();
5636 get_online_mems();
5637 mutex_lock(&state_mutex);
5638
5639 if (enabled == lru_gen_enabled())
5640 goto unlock;
5641
5642 if (enabled)
5643 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5644 else
5645 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5646
5647 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5648 do {
5649 int nid;
5650
5651 for_each_node(nid) {
5652 struct lruvec *lruvec = get_lruvec(memcg, nid);
5653
354ed597
YZ
5654 spin_lock_irq(&lruvec->lru_lock);
5655
5656 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5657 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5658
5659 lruvec->lrugen.enabled = enabled;
5660
5661 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5662 spin_unlock_irq(&lruvec->lru_lock);
5663 cond_resched();
5664 spin_lock_irq(&lruvec->lru_lock);
5665 }
5666
5667 spin_unlock_irq(&lruvec->lru_lock);
5668 }
5669
5670 cond_resched();
5671 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5672unlock:
5673 mutex_unlock(&state_mutex);
5674 put_online_mems();
5675 cpus_read_unlock();
5676 cgroup_unlock();
5677}
5678
5679/******************************************************************************
5680 * sysfs interface
5681 ******************************************************************************/
5682
9a52b2f3 5683static ssize_t min_ttl_ms_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
1332a809 5684{
9a52b2f3 5685 return sysfs_emit(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
1332a809
YZ
5686}
5687
07017acb 5688/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
9a52b2f3
A
5689static ssize_t min_ttl_ms_store(struct kobject *kobj, struct kobj_attribute *attr,
5690 const char *buf, size_t len)
1332a809
YZ
5691{
5692 unsigned int msecs;
5693
5694 if (kstrtouint(buf, 0, &msecs))
5695 return -EINVAL;
5696
5697 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5698
5699 return len;
5700}
5701
9a52b2f3 5702static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR_RW(min_ttl_ms);
1332a809 5703
9a52b2f3 5704static ssize_t enabled_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
354ed597
YZ
5705{
5706 unsigned int caps = 0;
5707
5708 if (get_cap(LRU_GEN_CORE))
5709 caps |= BIT(LRU_GEN_CORE);
5710
5711 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5712 caps |= BIT(LRU_GEN_MM_WALK);
5713
4aaf269c 5714 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
354ed597
YZ
5715 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5716
8ef9c32a 5717 return sysfs_emit(buf, "0x%04x\n", caps);
354ed597
YZ
5718}
5719
07017acb 5720/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
9a52b2f3 5721static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
354ed597
YZ
5722 const char *buf, size_t len)
5723{
5724 int i;
5725 unsigned int caps;
5726
5727 if (tolower(*buf) == 'n')
5728 caps = 0;
5729 else if (tolower(*buf) == 'y')
5730 caps = -1;
5731 else if (kstrtouint(buf, 0, &caps))
5732 return -EINVAL;
5733
5734 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5735 bool enabled = caps & BIT(i);
5736
5737 if (i == LRU_GEN_CORE)
5738 lru_gen_change_state(enabled);
5739 else if (enabled)
5740 static_branch_enable(&lru_gen_caps[i]);
5741 else
5742 static_branch_disable(&lru_gen_caps[i]);
5743 }
5744
5745 return len;
5746}
5747
9a52b2f3 5748static struct kobj_attribute lru_gen_enabled_attr = __ATTR_RW(enabled);
354ed597
YZ
5749
5750static struct attribute *lru_gen_attrs[] = {
1332a809 5751 &lru_gen_min_ttl_attr.attr,
354ed597
YZ
5752 &lru_gen_enabled_attr.attr,
5753 NULL
5754};
5755
9a52b2f3 5756static const struct attribute_group lru_gen_attr_group = {
354ed597
YZ
5757 .name = "lru_gen",
5758 .attrs = lru_gen_attrs,
5759};
5760
d6c3af7d
YZ
5761/******************************************************************************
5762 * debugfs interface
5763 ******************************************************************************/
5764
5765static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5766{
5767 struct mem_cgroup *memcg;
5768 loff_t nr_to_skip = *pos;
5769
5770 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5771 if (!m->private)
5772 return ERR_PTR(-ENOMEM);
5773
5774 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5775 do {
5776 int nid;
5777
5778 for_each_node_state(nid, N_MEMORY) {
5779 if (!nr_to_skip--)
5780 return get_lruvec(memcg, nid);
5781 }
5782 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5783
5784 return NULL;
5785}
5786
5787static void lru_gen_seq_stop(struct seq_file *m, void *v)
5788{
5789 if (!IS_ERR_OR_NULL(v))
5790 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5791
5792 kvfree(m->private);
5793 m->private = NULL;
5794}
5795
5796static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5797{
5798 int nid = lruvec_pgdat(v)->node_id;
5799 struct mem_cgroup *memcg = lruvec_memcg(v);
5800
5801 ++*pos;
5802
5803 nid = next_memory_node(nid);
5804 if (nid == MAX_NUMNODES) {
5805 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5806 if (!memcg)
5807 return NULL;
5808
5809 nid = first_memory_node;
5810 }
5811
5812 return get_lruvec(memcg, nid);
5813}
5814
5815static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5816 unsigned long max_seq, unsigned long *min_seq,
5817 unsigned long seq)
5818{
5819 int i;
5820 int type, tier;
5821 int hist = lru_hist_from_seq(seq);
391655fe 5822 struct lru_gen_folio *lrugen = &lruvec->lrugen;
d6c3af7d
YZ
5823
5824 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5825 seq_printf(m, " %10d", tier);
5826 for (type = 0; type < ANON_AND_FILE; type++) {
5827 const char *s = " ";
5828 unsigned long n[3] = {};
5829
5830 if (seq == max_seq) {
5831 s = "RT ";
5832 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5833 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5834 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5835 s = "rep";
5836 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5837 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5838 if (tier)
5839 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5840 }
5841
5842 for (i = 0; i < 3; i++)
5843 seq_printf(m, " %10lu%c", n[i], s[i]);
5844 }
5845 seq_putc(m, '\n');
5846 }
5847
5848 seq_puts(m, " ");
5849 for (i = 0; i < NR_MM_STATS; i++) {
5850 const char *s = " ";
5851 unsigned long n = 0;
5852
5853 if (seq == max_seq && NR_HIST_GENS == 1) {
5854 s = "LOYNFA";
5855 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5856 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5857 s = "loynfa";
5858 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5859 }
5860
5861 seq_printf(m, " %10lu%c", n, s[i]);
5862 }
5863 seq_putc(m, '\n');
5864}
5865
07017acb 5866/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
d6c3af7d
YZ
5867static int lru_gen_seq_show(struct seq_file *m, void *v)
5868{
5869 unsigned long seq;
5870 bool full = !debugfs_real_fops(m->file)->write;
5871 struct lruvec *lruvec = v;
391655fe 5872 struct lru_gen_folio *lrugen = &lruvec->lrugen;
d6c3af7d
YZ
5873 int nid = lruvec_pgdat(lruvec)->node_id;
5874 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5875 DEFINE_MAX_SEQ(lruvec);
5876 DEFINE_MIN_SEQ(lruvec);
5877
5878 if (nid == first_memory_node) {
5879 const char *path = memcg ? m->private : "";
5880
5881#ifdef CONFIG_MEMCG
5882 if (memcg)
5883 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5884#endif
5885 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5886 }
5887
5888 seq_printf(m, " node %5d\n", nid);
5889
5890 if (!full)
5891 seq = min_seq[LRU_GEN_ANON];
5892 else if (max_seq >= MAX_NR_GENS)
5893 seq = max_seq - MAX_NR_GENS + 1;
5894 else
5895 seq = 0;
5896
5897 for (; seq <= max_seq; seq++) {
5898 int type, zone;
5899 int gen = lru_gen_from_seq(seq);
5900 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5901
5902 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5903
5904 for (type = 0; type < ANON_AND_FILE; type++) {
5905 unsigned long size = 0;
5906 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5907
5908 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5909 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5910
5911 seq_printf(m, " %10lu%c", size, mark);
5912 }
5913
5914 seq_putc(m, '\n');
5915
5916 if (full)
5917 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5918 }
5919
5920 return 0;
5921}
5922
5923static const struct seq_operations lru_gen_seq_ops = {
5924 .start = lru_gen_seq_start,
5925 .stop = lru_gen_seq_stop,
5926 .next = lru_gen_seq_next,
5927 .show = lru_gen_seq_show,
5928};
5929
5930static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5931 bool can_swap, bool force_scan)
5932{
5933 DEFINE_MAX_SEQ(lruvec);
5934 DEFINE_MIN_SEQ(lruvec);
5935
5936 if (seq < max_seq)
5937 return 0;
5938
5939 if (seq > max_seq)
5940 return -EINVAL;
5941
5942 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5943 return -ERANGE;
5944
5945 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5946
5947 return 0;
5948}
5949
5950static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5951 int swappiness, unsigned long nr_to_reclaim)
5952{
5953 DEFINE_MAX_SEQ(lruvec);
5954
5955 if (seq + MIN_NR_GENS > max_seq)
5956 return -EINVAL;
5957
5958 sc->nr_reclaimed = 0;
5959
5960 while (!signal_pending(current)) {
5961 DEFINE_MIN_SEQ(lruvec);
5962
5963 if (seq < min_seq[!swappiness])
5964 return 0;
5965
5966 if (sc->nr_reclaimed >= nr_to_reclaim)
5967 return 0;
5968
a579086c 5969 if (!evict_folios(lruvec, sc, swappiness))
d6c3af7d
YZ
5970 return 0;
5971
5972 cond_resched();
5973 }
5974
5975 return -EINTR;
5976}
5977
5978static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5979 struct scan_control *sc, int swappiness, unsigned long opt)
5980{
5981 struct lruvec *lruvec;
5982 int err = -EINVAL;
5983 struct mem_cgroup *memcg = NULL;
5984
5985 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5986 return -EINVAL;
5987
5988 if (!mem_cgroup_disabled()) {
5989 rcu_read_lock();
e4dde56c 5990
d6c3af7d 5991 memcg = mem_cgroup_from_id(memcg_id);
e4dde56c 5992 if (!mem_cgroup_tryget(memcg))
d6c3af7d 5993 memcg = NULL;
e4dde56c 5994
d6c3af7d
YZ
5995 rcu_read_unlock();
5996
5997 if (!memcg)
5998 return -EINVAL;
5999 }
6000
6001 if (memcg_id != mem_cgroup_id(memcg))
6002 goto done;
6003
6004 lruvec = get_lruvec(memcg, nid);
6005
6006 if (swappiness < 0)
6007 swappiness = get_swappiness(lruvec, sc);
6008 else if (swappiness > 200)
6009 goto done;
6010
6011 switch (cmd) {
6012 case '+':
6013 err = run_aging(lruvec, seq, sc, swappiness, opt);
6014 break;
6015 case '-':
6016 err = run_eviction(lruvec, seq, sc, swappiness, opt);
6017 break;
6018 }
6019done:
6020 mem_cgroup_put(memcg);
6021
6022 return err;
6023}
6024
07017acb 6025/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
d6c3af7d
YZ
6026static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
6027 size_t len, loff_t *pos)
6028{
6029 void *buf;
6030 char *cur, *next;
6031 unsigned int flags;
6032 struct blk_plug plug;
6033 int err = -EINVAL;
6034 struct scan_control sc = {
6035 .may_writepage = true,
6036 .may_unmap = true,
6037 .may_swap = true,
6038 .reclaim_idx = MAX_NR_ZONES - 1,
6039 .gfp_mask = GFP_KERNEL,
6040 };
6041
6042 buf = kvmalloc(len + 1, GFP_KERNEL);
6043 if (!buf)
6044 return -ENOMEM;
6045
6046 if (copy_from_user(buf, src, len)) {
6047 kvfree(buf);
6048 return -EFAULT;
6049 }
6050
6051 set_task_reclaim_state(current, &sc.reclaim_state);
6052 flags = memalloc_noreclaim_save();
6053 blk_start_plug(&plug);
e9d4e1ee 6054 if (!set_mm_walk(NULL, true)) {
d6c3af7d
YZ
6055 err = -ENOMEM;
6056 goto done;
6057 }
6058
6059 next = buf;
6060 next[len] = '\0';
6061
6062 while ((cur = strsep(&next, ",;\n"))) {
6063 int n;
6064 int end;
6065 char cmd;
6066 unsigned int memcg_id;
6067 unsigned int nid;
6068 unsigned long seq;
6069 unsigned int swappiness = -1;
6070 unsigned long opt = -1;
6071
6072 cur = skip_spaces(cur);
6073 if (!*cur)
6074 continue;
6075
6076 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
6077 &seq, &end, &swappiness, &end, &opt, &end);
6078 if (n < 4 || cur[end]) {
6079 err = -EINVAL;
6080 break;
6081 }
6082
6083 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
6084 if (err)
6085 break;
6086 }
6087done:
6088 clear_mm_walk();
6089 blk_finish_plug(&plug);
6090 memalloc_noreclaim_restore(flags);
6091 set_task_reclaim_state(current, NULL);
6092
6093 kvfree(buf);
6094
6095 return err ? : len;
6096}
6097
6098static int lru_gen_seq_open(struct inode *inode, struct file *file)
6099{
6100 return seq_open(file, &lru_gen_seq_ops);
6101}
6102
6103static const struct file_operations lru_gen_rw_fops = {
6104 .open = lru_gen_seq_open,
6105 .read = seq_read,
6106 .write = lru_gen_seq_write,
6107 .llseek = seq_lseek,
6108 .release = seq_release,
6109};
6110
6111static const struct file_operations lru_gen_ro_fops = {
6112 .open = lru_gen_seq_open,
6113 .read = seq_read,
6114 .llseek = seq_lseek,
6115 .release = seq_release,
6116};
6117
ec1c86b2
YZ
6118/******************************************************************************
6119 * initialization
6120 ******************************************************************************/
6121
6122void lru_gen_init_lruvec(struct lruvec *lruvec)
6123{
1332a809 6124 int i;
ec1c86b2 6125 int gen, type, zone;
391655fe 6126 struct lru_gen_folio *lrugen = &lruvec->lrugen;
ec1c86b2
YZ
6127
6128 lrugen->max_seq = MIN_NR_GENS + 1;
354ed597 6129 lrugen->enabled = lru_gen_enabled();
ec1c86b2 6130
1332a809
YZ
6131 for (i = 0; i <= MIN_NR_GENS + 1; i++)
6132 lrugen->timestamps[i] = jiffies;
6133
ec1c86b2 6134 for_each_gen_type_zone(gen, type, zone)
6df1b221 6135 INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
bd74fdae
YZ
6136
6137 lruvec->mm_state.seq = MIN_NR_GENS;
ec1c86b2
YZ
6138}
6139
6140#ifdef CONFIG_MEMCG
e4dde56c
YZ
6141
6142void lru_gen_init_pgdat(struct pglist_data *pgdat)
6143{
6144 int i, j;
6145
6146 spin_lock_init(&pgdat->memcg_lru.lock);
6147
6148 for (i = 0; i < MEMCG_NR_GENS; i++) {
6149 for (j = 0; j < MEMCG_NR_BINS; j++)
6150 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
6151 }
6152}
6153
ec1c86b2
YZ
6154void lru_gen_init_memcg(struct mem_cgroup *memcg)
6155{
bd74fdae
YZ
6156 INIT_LIST_HEAD(&memcg->mm_list.fifo);
6157 spin_lock_init(&memcg->mm_list.lock);
ec1c86b2
YZ
6158}
6159
6160void lru_gen_exit_memcg(struct mem_cgroup *memcg)
6161{
bd74fdae 6162 int i;
ec1c86b2
YZ
6163 int nid;
6164
37cc9997
A
6165 VM_WARN_ON_ONCE(!list_empty(&memcg->mm_list.fifo));
6166
ec1c86b2
YZ
6167 for_each_node(nid) {
6168 struct lruvec *lruvec = get_lruvec(memcg, nid);
6169
6170 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
6171 sizeof(lruvec->lrugen.nr_pages)));
bd74fdae 6172
37cc9997
A
6173 lruvec->lrugen.list.next = LIST_POISON1;
6174
bd74fdae
YZ
6175 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
6176 bitmap_free(lruvec->mm_state.filters[i]);
6177 lruvec->mm_state.filters[i] = NULL;
6178 }
ec1c86b2
YZ
6179 }
6180}
e4dde56c 6181
e4dde56c 6182#endif /* CONFIG_MEMCG */
ec1c86b2
YZ
6183
6184static int __init init_lru_gen(void)
6185{
6186 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
6187 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
6188
354ed597
YZ
6189 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
6190 pr_err("lru_gen: failed to create sysfs group\n");
6191
d6c3af7d
YZ
6192 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
6193 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
6194
ec1c86b2
YZ
6195 return 0;
6196};
6197late_initcall(init_lru_gen);
6198
ac35a490
YZ
6199#else /* !CONFIG_LRU_GEN */
6200
6201static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6202{
6203}
6204
6205static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
6206{
6207}
6208
e4dde56c
YZ
6209static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
6210{
6211}
6212
ec1c86b2
YZ
6213#endif /* CONFIG_LRU_GEN */
6214
afaf07a6 6215static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
9b4f98cd
JW
6216{
6217 unsigned long nr[NR_LRU_LISTS];
e82e0561 6218 unsigned long targets[NR_LRU_LISTS];
9b4f98cd
JW
6219 unsigned long nr_to_scan;
6220 enum lru_list lru;
6221 unsigned long nr_reclaimed = 0;
6222 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
f53af428 6223 bool proportional_reclaim;
9b4f98cd
JW
6224 struct blk_plug plug;
6225
e4dde56c 6226 if (lru_gen_enabled() && !global_reclaim(sc)) {
ac35a490
YZ
6227 lru_gen_shrink_lruvec(lruvec, sc);
6228 return;
6229 }
6230
afaf07a6 6231 get_scan_count(lruvec, sc, nr);
9b4f98cd 6232
e82e0561
MG
6233 /* Record the original scan target for proportional adjustments later */
6234 memcpy(targets, nr, sizeof(nr));
6235
1a501907
MG
6236 /*
6237 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6238 * event that can occur when there is little memory pressure e.g.
6239 * multiple streaming readers/writers. Hence, we do not abort scanning
6240 * when the requested number of pages are reclaimed when scanning at
6241 * DEF_PRIORITY on the assumption that the fact we are direct
6242 * reclaiming implies that kswapd is not keeping up and it is best to
6243 * do a batch of work at once. For memcg reclaim one check is made to
6244 * abort proportional reclaim if either the file or anon lru has already
6245 * dropped to zero at the first pass.
6246 */
f53af428
JW
6247 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6248 sc->priority == DEF_PRIORITY);
1a501907 6249
9b4f98cd
JW
6250 blk_start_plug(&plug);
6251 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6252 nr[LRU_INACTIVE_FILE]) {
e82e0561
MG
6253 unsigned long nr_anon, nr_file, percentage;
6254 unsigned long nr_scanned;
6255
9b4f98cd
JW
6256 for_each_evictable_lru(lru) {
6257 if (nr[lru]) {
6258 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6259 nr[lru] -= nr_to_scan;
6260
6261 nr_reclaimed += shrink_list(lru, nr_to_scan,
3b991208 6262 lruvec, sc);
9b4f98cd
JW
6263 }
6264 }
e82e0561 6265
bd041733
MH
6266 cond_resched();
6267
f53af428 6268 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
e82e0561
MG
6269 continue;
6270
e82e0561
MG
6271 /*
6272 * For kswapd and memcg, reclaim at least the number of pages
1a501907 6273 * requested. Ensure that the anon and file LRUs are scanned
e82e0561
MG
6274 * proportionally what was requested by get_scan_count(). We
6275 * stop reclaiming one LRU and reduce the amount scanning
6276 * proportional to the original scan target.
6277 */
6278 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6279 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6280
1a501907
MG
6281 /*
6282 * It's just vindictive to attack the larger once the smaller
6283 * has gone to zero. And given the way we stop scanning the
6284 * smaller below, this makes sure that we only make one nudge
6285 * towards proportionality once we've got nr_to_reclaim.
6286 */
6287 if (!nr_file || !nr_anon)
6288 break;
6289
e82e0561
MG
6290 if (nr_file > nr_anon) {
6291 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6292 targets[LRU_ACTIVE_ANON] + 1;
6293 lru = LRU_BASE;
6294 percentage = nr_anon * 100 / scan_target;
6295 } else {
6296 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6297 targets[LRU_ACTIVE_FILE] + 1;
6298 lru = LRU_FILE;
6299 percentage = nr_file * 100 / scan_target;
6300 }
6301
6302 /* Stop scanning the smaller of the LRU */
6303 nr[lru] = 0;
6304 nr[lru + LRU_ACTIVE] = 0;
6305
6306 /*
6307 * Recalculate the other LRU scan count based on its original
6308 * scan target and the percentage scanning already complete
6309 */
6310 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6311 nr_scanned = targets[lru] - nr[lru];
6312 nr[lru] = targets[lru] * (100 - percentage) / 100;
6313 nr[lru] -= min(nr[lru], nr_scanned);
6314
6315 lru += LRU_ACTIVE;
6316 nr_scanned = targets[lru] - nr[lru];
6317 nr[lru] = targets[lru] * (100 - percentage) / 100;
6318 nr[lru] -= min(nr[lru], nr_scanned);
9b4f98cd
JW
6319 }
6320 blk_finish_plug(&plug);
6321 sc->nr_reclaimed += nr_reclaimed;
6322
6323 /*
6324 * Even if we did not try to evict anon pages at all, we want to
6325 * rebalance the anon lru active/inactive ratio.
6326 */
2f368a9f
DH
6327 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6328 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
9b4f98cd
JW
6329 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6330 sc, LRU_ACTIVE_ANON);
9b4f98cd
JW
6331}
6332
23b9da55 6333/* Use reclaim/compaction for costly allocs or under memory pressure */
9e3b2f8c 6334static bool in_reclaim_compaction(struct scan_control *sc)
23b9da55 6335{
d84da3f9 6336 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
23b9da55 6337 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
9e3b2f8c 6338 sc->priority < DEF_PRIORITY - 2))
23b9da55
MG
6339 return true;
6340
6341 return false;
6342}
6343
3e7d3449 6344/*
23b9da55
MG
6345 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6346 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6347 * true if more pages should be reclaimed such that when the page allocator
df3a45f9 6348 * calls try_to_compact_pages() that it will have enough free pages to succeed.
23b9da55 6349 * It will give up earlier than that if there is difficulty reclaiming pages.
3e7d3449 6350 */
a9dd0a83 6351static inline bool should_continue_reclaim(struct pglist_data *pgdat,
3e7d3449 6352 unsigned long nr_reclaimed,
3e7d3449
MG
6353 struct scan_control *sc)
6354{
6355 unsigned long pages_for_compaction;
6356 unsigned long inactive_lru_pages;
a9dd0a83 6357 int z;
3e7d3449
MG
6358
6359 /* If not in reclaim/compaction mode, stop */
9e3b2f8c 6360 if (!in_reclaim_compaction(sc))
3e7d3449
MG
6361 return false;
6362
5ee04716
VB
6363 /*
6364 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6365 * number of pages that were scanned. This will return to the caller
6366 * with the risk reclaim/compaction and the resulting allocation attempt
6367 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6368 * allocations through requiring that the full LRU list has been scanned
6369 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6370 * scan, but that approximation was wrong, and there were corner cases
6371 * where always a non-zero amount of pages were scanned.
6372 */
6373 if (!nr_reclaimed)
6374 return false;
3e7d3449 6375
3e7d3449 6376 /* If compaction would go ahead or the allocation would succeed, stop */
a9dd0a83
MG
6377 for (z = 0; z <= sc->reclaim_idx; z++) {
6378 struct zone *zone = &pgdat->node_zones[z];
6aa303de 6379 if (!managed_zone(zone))
a9dd0a83
MG
6380 continue;
6381
6382 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
cf378319 6383 case COMPACT_SUCCESS:
a9dd0a83
MG
6384 case COMPACT_CONTINUE:
6385 return false;
6386 default:
6387 /* check next zone */
6388 ;
6389 }
3e7d3449 6390 }
1c6c1597
HD
6391
6392 /*
6393 * If we have not reclaimed enough pages for compaction and the
6394 * inactive lists are large enough, continue reclaiming
6395 */
6396 pages_for_compaction = compact_gap(sc->order);
6397 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
a2a36488 6398 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
1c6c1597
HD
6399 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6400
5ee04716 6401 return inactive_lru_pages > pages_for_compaction;
3e7d3449
MG
6402}
6403
0f6a5cff 6404static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
1da177e4 6405{
0f6a5cff 6406 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
d2af3397 6407 struct mem_cgroup *memcg;
1da177e4 6408
0f6a5cff 6409 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
d2af3397 6410 do {
afaf07a6 6411 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
d2af3397
JW
6412 unsigned long reclaimed;
6413 unsigned long scanned;
5660048c 6414
e3336cab
XP
6415 /*
6416 * This loop can become CPU-bound when target memcgs
6417 * aren't eligible for reclaim - either because they
6418 * don't have any reclaimable pages, or because their
6419 * memory is explicitly protected. Avoid soft lockups.
6420 */
6421 cond_resched();
6422
45c7f7e1
CD
6423 mem_cgroup_calculate_protection(target_memcg, memcg);
6424
adb82130 6425 if (mem_cgroup_below_min(target_memcg, memcg)) {
d2af3397
JW
6426 /*
6427 * Hard protection.
6428 * If there is no reclaimable memory, OOM.
6429 */
6430 continue;
adb82130 6431 } else if (mem_cgroup_below_low(target_memcg, memcg)) {
d2af3397
JW
6432 /*
6433 * Soft protection.
6434 * Respect the protection only as long as
6435 * there is an unprotected supply
6436 * of reclaimable memory from other cgroups.
6437 */
6438 if (!sc->memcg_low_reclaim) {
6439 sc->memcg_low_skipped = 1;
bf8d5d52 6440 continue;
241994ed 6441 }
d2af3397 6442 memcg_memory_event(memcg, MEMCG_LOW);
d2af3397 6443 }
241994ed 6444
d2af3397
JW
6445 reclaimed = sc->nr_reclaimed;
6446 scanned = sc->nr_scanned;
afaf07a6
JW
6447
6448 shrink_lruvec(lruvec, sc);
70ddf637 6449
d2af3397
JW
6450 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6451 sc->priority);
6b4f7799 6452
d2af3397 6453 /* Record the group's reclaim efficiency */
73b73bac
YA
6454 if (!sc->proactive)
6455 vmpressure(sc->gfp_mask, memcg, false,
6456 sc->nr_scanned - scanned,
6457 sc->nr_reclaimed - reclaimed);
70ddf637 6458
0f6a5cff
JW
6459 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6460}
6461
6c9e0907 6462static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
0f6a5cff 6463{
54c4fe08 6464 unsigned long nr_reclaimed, nr_scanned, nr_node_reclaimed;
1b05117d 6465 struct lruvec *target_lruvec;
0f6a5cff
JW
6466 bool reclaimable = false;
6467
e4dde56c
YZ
6468 if (lru_gen_enabled() && global_reclaim(sc)) {
6469 lru_gen_shrink_node(pgdat, sc);
6470 return;
6471 }
6472
1b05117d
JW
6473 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6474
0f6a5cff
JW
6475again:
6476 memset(&sc->nr, 0, sizeof(sc->nr));
6477
6478 nr_reclaimed = sc->nr_reclaimed;
6479 nr_scanned = sc->nr_scanned;
6480
f1e1a7be 6481 prepare_scan_count(pgdat, sc);
53138cea 6482
0f6a5cff 6483 shrink_node_memcgs(pgdat, sc);
2344d7e4 6484
583c27a1 6485 flush_reclaim_state(sc);
d108c772 6486
54c4fe08 6487 nr_node_reclaimed = sc->nr_reclaimed - nr_reclaimed;
d108c772 6488
d2af3397 6489 /* Record the subtree's reclaim efficiency */
73b73bac
YA
6490 if (!sc->proactive)
6491 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
54c4fe08 6492 sc->nr_scanned - nr_scanned, nr_node_reclaimed);
d108c772 6493
54c4fe08 6494 if (nr_node_reclaimed)
d2af3397 6495 reclaimable = true;
d108c772 6496
d2af3397
JW
6497 if (current_is_kswapd()) {
6498 /*
6499 * If reclaim is isolating dirty pages under writeback,
6500 * it implies that the long-lived page allocation rate
6501 * is exceeding the page laundering rate. Either the
6502 * global limits are not being effective at throttling
6503 * processes due to the page distribution throughout
6504 * zones or there is heavy usage of a slow backing
6505 * device. The only option is to throttle from reclaim
6506 * context which is not ideal as there is no guarantee
6507 * the dirtying process is throttled in the same way
6508 * balance_dirty_pages() manages.
6509 *
6510 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6511 * count the number of pages under pages flagged for
6512 * immediate reclaim and stall if any are encountered
6513 * in the nr_immediate check below.
6514 */
6515 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6516 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
d108c772 6517
d2af3397
JW
6518 /* Allow kswapd to start writing pages during reclaim.*/
6519 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6520 set_bit(PGDAT_DIRTY, &pgdat->flags);
e3c1ac58 6521
d108c772 6522 /*
1eba09c1 6523 * If kswapd scans pages marked for immediate
d2af3397
JW
6524 * reclaim and under writeback (nr_immediate), it
6525 * implies that pages are cycling through the LRU
8cd7c588
MG
6526 * faster than they are written so forcibly stall
6527 * until some pages complete writeback.
d108c772 6528 */
d2af3397 6529 if (sc->nr.immediate)
c3f4a9a2 6530 reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
d2af3397
JW
6531 }
6532
6533 /*
8cd7c588
MG
6534 * Tag a node/memcg as congested if all the dirty pages were marked
6535 * for writeback and immediate reclaim (counted in nr.congested).
1b05117d 6536 *
d2af3397 6537 * Legacy memcg will stall in page writeback so avoid forcibly
8cd7c588 6538 * stalling in reclaim_throttle().
d2af3397 6539 */
1b05117d
JW
6540 if ((current_is_kswapd() ||
6541 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
d2af3397 6542 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
1b05117d 6543 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
d2af3397
JW
6544
6545 /*
8cd7c588
MG
6546 * Stall direct reclaim for IO completions if the lruvec is
6547 * node is congested. Allow kswapd to continue until it
d2af3397
JW
6548 * starts encountering unqueued dirty pages or cycling through
6549 * the LRU too quickly.
6550 */
1b05117d
JW
6551 if (!current_is_kswapd() && current_may_throttle() &&
6552 !sc->hibernation_mode &&
6553 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
1b4e3f26 6554 reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
d108c772 6555
54c4fe08 6556 if (should_continue_reclaim(pgdat, nr_node_reclaimed, sc))
d2af3397 6557 goto again;
2344d7e4 6558
c73322d0
JW
6559 /*
6560 * Kswapd gives up on balancing particular nodes after too
6561 * many failures to reclaim anything from them and goes to
6562 * sleep. On reclaim progress, reset the failure counter. A
6563 * successful direct reclaim run will revive a dormant kswapd.
6564 */
6565 if (reclaimable)
6566 pgdat->kswapd_failures = 0;
f16015fb
JW
6567}
6568
53853e2d 6569/*
fdd4c614
VB
6570 * Returns true if compaction should go ahead for a costly-order request, or
6571 * the allocation would already succeed without compaction. Return false if we
6572 * should reclaim first.
53853e2d 6573 */
4f588331 6574static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
fe4b1b24 6575{
31483b6a 6576 unsigned long watermark;
fdd4c614 6577 enum compact_result suitable;
fe4b1b24 6578
fdd4c614
VB
6579 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6580 if (suitable == COMPACT_SUCCESS)
6581 /* Allocation should succeed already. Don't reclaim. */
6582 return true;
6583 if (suitable == COMPACT_SKIPPED)
6584 /* Compaction cannot yet proceed. Do reclaim. */
6585 return false;
fe4b1b24 6586
53853e2d 6587 /*
fdd4c614
VB
6588 * Compaction is already possible, but it takes time to run and there
6589 * are potentially other callers using the pages just freed. So proceed
6590 * with reclaim to make a buffer of free pages available to give
6591 * compaction a reasonable chance of completing and allocating the page.
6592 * Note that we won't actually reclaim the whole buffer in one attempt
6593 * as the target watermark in should_continue_reclaim() is lower. But if
6594 * we are already above the high+gap watermark, don't reclaim at all.
53853e2d 6595 */
fdd4c614 6596 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
fe4b1b24 6597
fdd4c614 6598 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
fe4b1b24
MG
6599}
6600
69392a40
MG
6601static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6602{
66ce520b
MG
6603 /*
6604 * If reclaim is making progress greater than 12% efficiency then
6605 * wake all the NOPROGRESS throttled tasks.
6606 */
6607 if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
69392a40
MG
6608 wait_queue_head_t *wqh;
6609
6610 wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6611 if (waitqueue_active(wqh))
6612 wake_up(wqh);
6613
6614 return;
6615 }
6616
6617 /*
1b4e3f26
MG
6618 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6619 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6620 * under writeback and marked for immediate reclaim at the tail of the
6621 * LRU.
69392a40 6622 */
1b4e3f26 6623 if (current_is_kswapd() || cgroup_reclaim(sc))
69392a40
MG
6624 return;
6625
6626 /* Throttle if making no progress at high prioities. */
1b4e3f26 6627 if (sc->priority == 1 && !sc->nr_reclaimed)
c3f4a9a2 6628 reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
69392a40
MG
6629}
6630
1da177e4
LT
6631/*
6632 * This is the direct reclaim path, for page-allocating processes. We only
6633 * try to reclaim pages from zones which will satisfy the caller's allocation
6634 * request.
6635 *
1da177e4
LT
6636 * If a zone is deemed to be full of pinned pages then just give it a light
6637 * scan then give up on it.
6638 */
0a0337e0 6639static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
1da177e4 6640{
dd1a239f 6641 struct zoneref *z;
54a6eb5c 6642 struct zone *zone;
0608f43d
AM
6643 unsigned long nr_soft_reclaimed;
6644 unsigned long nr_soft_scanned;
619d0d76 6645 gfp_t orig_mask;
79dafcdc 6646 pg_data_t *last_pgdat = NULL;
1b4e3f26 6647 pg_data_t *first_pgdat = NULL;
1cfb419b 6648
cc715d99
MG
6649 /*
6650 * If the number of buffer_heads in the machine exceeds the maximum
6651 * allowed level, force direct reclaim to scan the highmem zone as
6652 * highmem pages could be pinning lowmem pages storing buffer_heads
6653 */
619d0d76 6654 orig_mask = sc->gfp_mask;
b2e18757 6655 if (buffer_heads_over_limit) {
cc715d99 6656 sc->gfp_mask |= __GFP_HIGHMEM;
4f588331 6657 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
b2e18757 6658 }
cc715d99 6659
d4debc66 6660 for_each_zone_zonelist_nodemask(zone, z, zonelist,
b2e18757 6661 sc->reclaim_idx, sc->nodemask) {
1cfb419b
KH
6662 /*
6663 * Take care memory controller reclaiming has small influence
6664 * to global LRU.
6665 */
b5ead35e 6666 if (!cgroup_reclaim(sc)) {
344736f2
VD
6667 if (!cpuset_zone_allowed(zone,
6668 GFP_KERNEL | __GFP_HARDWALL))
1cfb419b 6669 continue;
65ec02cb 6670
0b06496a
JW
6671 /*
6672 * If we already have plenty of memory free for
6673 * compaction in this zone, don't free any more.
6674 * Even though compaction is invoked for any
6675 * non-zero order, only frequent costly order
6676 * reclamation is disruptive enough to become a
6677 * noticeable problem, like transparent huge
6678 * page allocations.
6679 */
6680 if (IS_ENABLED(CONFIG_COMPACTION) &&
6681 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
4f588331 6682 compaction_ready(zone, sc)) {
0b06496a
JW
6683 sc->compaction_ready = true;
6684 continue;
e0887c19 6685 }
0b06496a 6686
79dafcdc
MG
6687 /*
6688 * Shrink each node in the zonelist once. If the
6689 * zonelist is ordered by zone (not the default) then a
6690 * node may be shrunk multiple times but in that case
6691 * the user prefers lower zones being preserved.
6692 */
6693 if (zone->zone_pgdat == last_pgdat)
6694 continue;
6695
0608f43d
AM
6696 /*
6697 * This steals pages from memory cgroups over softlimit
6698 * and returns the number of reclaimed pages and
6699 * scanned pages. This works for global memory pressure
6700 * and balancing, not for a memcg's limit.
6701 */
6702 nr_soft_scanned = 0;
ef8f2327 6703 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
0608f43d
AM
6704 sc->order, sc->gfp_mask,
6705 &nr_soft_scanned);
6706 sc->nr_reclaimed += nr_soft_reclaimed;
6707 sc->nr_scanned += nr_soft_scanned;
ac34a1a3 6708 /* need some check for avoid more shrink_zone() */
1cfb419b 6709 }
408d8544 6710
1b4e3f26
MG
6711 if (!first_pgdat)
6712 first_pgdat = zone->zone_pgdat;
6713
79dafcdc
MG
6714 /* See comment about same check for global reclaim above */
6715 if (zone->zone_pgdat == last_pgdat)
6716 continue;
6717 last_pgdat = zone->zone_pgdat;
970a39a3 6718 shrink_node(zone->zone_pgdat, sc);
1da177e4 6719 }
e0c23279 6720
80082938
MG
6721 if (first_pgdat)
6722 consider_reclaim_throttle(first_pgdat, sc);
1b4e3f26 6723
619d0d76
WY
6724 /*
6725 * Restore to original mask to avoid the impact on the caller if we
6726 * promoted it to __GFP_HIGHMEM.
6727 */
6728 sc->gfp_mask = orig_mask;
1da177e4 6729}
4f98a2fe 6730
b910718a 6731static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
2a2e4885 6732{
b910718a
JW
6733 struct lruvec *target_lruvec;
6734 unsigned long refaults;
2a2e4885 6735
ac35a490
YZ
6736 if (lru_gen_enabled())
6737 return;
6738
b910718a 6739 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
170b04b7 6740 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
e9c2dbc8 6741 target_lruvec->refaults[WORKINGSET_ANON] = refaults;
170b04b7 6742 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
e9c2dbc8 6743 target_lruvec->refaults[WORKINGSET_FILE] = refaults;
2a2e4885
JW
6744}
6745
1da177e4
LT
6746/*
6747 * This is the main entry point to direct page reclaim.
6748 *
6749 * If a full scan of the inactive list fails to free enough memory then we
6750 * are "out of memory" and something needs to be killed.
6751 *
6752 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6753 * high - the zone may be full of dirty or under-writeback pages, which this
5b0830cb
JA
6754 * caller can't do much about. We kick the writeback threads and take explicit
6755 * naps in the hope that some of these pages can be written. But if the
6756 * allocating task holds filesystem locks which prevent writeout this might not
6757 * work, and the allocation attempt will fail.
a41f24ea
NA
6758 *
6759 * returns: 0, if no pages reclaimed
6760 * else, the number of pages reclaimed
1da177e4 6761 */
dac1d27b 6762static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3115cd91 6763 struct scan_control *sc)
1da177e4 6764{
241994ed 6765 int initial_priority = sc->priority;
2a2e4885
JW
6766 pg_data_t *last_pgdat;
6767 struct zoneref *z;
6768 struct zone *zone;
241994ed 6769retry:
873b4771
KK
6770 delayacct_freepages_start();
6771
b5ead35e 6772 if (!cgroup_reclaim(sc))
7cc30fcf 6773 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
1da177e4 6774
9e3b2f8c 6775 do {
73b73bac
YA
6776 if (!sc->proactive)
6777 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6778 sc->priority);
66e1707b 6779 sc->nr_scanned = 0;
0a0337e0 6780 shrink_zones(zonelist, sc);
c6a8a8c5 6781
bb21c7ce 6782 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
0b06496a
JW
6783 break;
6784
6785 if (sc->compaction_ready)
6786 break;
1da177e4 6787
0e50ce3b
MK
6788 /*
6789 * If we're getting trouble reclaiming, start doing
6790 * writepage even in laptop mode.
6791 */
6792 if (sc->priority < DEF_PRIORITY - 2)
6793 sc->may_writepage = 1;
0b06496a 6794 } while (--sc->priority >= 0);
bb21c7ce 6795
2a2e4885
JW
6796 last_pgdat = NULL;
6797 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6798 sc->nodemask) {
6799 if (zone->zone_pgdat == last_pgdat)
6800 continue;
6801 last_pgdat = zone->zone_pgdat;
1b05117d 6802
2a2e4885 6803 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
1b05117d
JW
6804
6805 if (cgroup_reclaim(sc)) {
6806 struct lruvec *lruvec;
6807
6808 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6809 zone->zone_pgdat);
6810 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6811 }
2a2e4885
JW
6812 }
6813
873b4771
KK
6814 delayacct_freepages_end();
6815
bb21c7ce
KM
6816 if (sc->nr_reclaimed)
6817 return sc->nr_reclaimed;
6818
0cee34fd 6819 /* Aborted reclaim to try compaction? don't OOM, then */
0b06496a 6820 if (sc->compaction_ready)
7335084d
MG
6821 return 1;
6822
b91ac374
JW
6823 /*
6824 * We make inactive:active ratio decisions based on the node's
6825 * composition of memory, but a restrictive reclaim_idx or a
6826 * memory.low cgroup setting can exempt large amounts of
6827 * memory from reclaim. Neither of which are very common, so
6828 * instead of doing costly eligibility calculations of the
6829 * entire cgroup subtree up front, we assume the estimates are
6830 * good, and retry with forcible deactivation if that fails.
6831 */
6832 if (sc->skipped_deactivate) {
6833 sc->priority = initial_priority;
6834 sc->force_deactivate = 1;
6835 sc->skipped_deactivate = 0;
6836 goto retry;
6837 }
6838
241994ed 6839 /* Untapped cgroup reserves? Don't OOM, retry. */
d6622f63 6840 if (sc->memcg_low_skipped) {
241994ed 6841 sc->priority = initial_priority;
b91ac374 6842 sc->force_deactivate = 0;
d6622f63
YX
6843 sc->memcg_low_reclaim = 1;
6844 sc->memcg_low_skipped = 0;
241994ed
JW
6845 goto retry;
6846 }
6847
bb21c7ce 6848 return 0;
1da177e4
LT
6849}
6850
c73322d0 6851static bool allow_direct_reclaim(pg_data_t *pgdat)
5515061d
MG
6852{
6853 struct zone *zone;
6854 unsigned long pfmemalloc_reserve = 0;
6855 unsigned long free_pages = 0;
6856 int i;
6857 bool wmark_ok;
6858
c73322d0
JW
6859 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6860 return true;
6861
5515061d
MG
6862 for (i = 0; i <= ZONE_NORMAL; i++) {
6863 zone = &pgdat->node_zones[i];
d450abd8
JW
6864 if (!managed_zone(zone))
6865 continue;
6866
6867 if (!zone_reclaimable_pages(zone))
675becce
MG
6868 continue;
6869
5515061d
MG
6870 pfmemalloc_reserve += min_wmark_pages(zone);
6871 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6872 }
6873
675becce
MG
6874 /* If there are no reserves (unexpected config) then do not throttle */
6875 if (!pfmemalloc_reserve)
6876 return true;
6877
5515061d
MG
6878 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6879
6880 /* kswapd must be awake if processes are being throttled */
6881 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
97a225e6
JK
6882 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6883 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
5644e1fb 6884
5515061d
MG
6885 wake_up_interruptible(&pgdat->kswapd_wait);
6886 }
6887
6888 return wmark_ok;
6889}
6890
6891/*
6892 * Throttle direct reclaimers if backing storage is backed by the network
6893 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6894 * depleted. kswapd will continue to make progress and wake the processes
50694c28
MG
6895 * when the low watermark is reached.
6896 *
6897 * Returns true if a fatal signal was delivered during throttling. If this
6898 * happens, the page allocator should not consider triggering the OOM killer.
5515061d 6899 */
50694c28 6900static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
5515061d
MG
6901 nodemask_t *nodemask)
6902{
675becce 6903 struct zoneref *z;
5515061d 6904 struct zone *zone;
675becce 6905 pg_data_t *pgdat = NULL;
5515061d
MG
6906
6907 /*
6908 * Kernel threads should not be throttled as they may be indirectly
6909 * responsible for cleaning pages necessary for reclaim to make forward
6910 * progress. kjournald for example may enter direct reclaim while
6911 * committing a transaction where throttling it could forcing other
6912 * processes to block on log_wait_commit().
6913 */
6914 if (current->flags & PF_KTHREAD)
50694c28
MG
6915 goto out;
6916
6917 /*
6918 * If a fatal signal is pending, this process should not throttle.
6919 * It should return quickly so it can exit and free its memory
6920 */
6921 if (fatal_signal_pending(current))
6922 goto out;
5515061d 6923
675becce
MG
6924 /*
6925 * Check if the pfmemalloc reserves are ok by finding the first node
6926 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6927 * GFP_KERNEL will be required for allocating network buffers when
6928 * swapping over the network so ZONE_HIGHMEM is unusable.
6929 *
6930 * Throttling is based on the first usable node and throttled processes
6931 * wait on a queue until kswapd makes progress and wakes them. There
6932 * is an affinity then between processes waking up and where reclaim
6933 * progress has been made assuming the process wakes on the same node.
6934 * More importantly, processes running on remote nodes will not compete
6935 * for remote pfmemalloc reserves and processes on different nodes
6936 * should make reasonable progress.
6937 */
6938 for_each_zone_zonelist_nodemask(zone, z, zonelist,
17636faa 6939 gfp_zone(gfp_mask), nodemask) {
675becce
MG
6940 if (zone_idx(zone) > ZONE_NORMAL)
6941 continue;
6942
6943 /* Throttle based on the first usable node */
6944 pgdat = zone->zone_pgdat;
c73322d0 6945 if (allow_direct_reclaim(pgdat))
675becce
MG
6946 goto out;
6947 break;
6948 }
6949
6950 /* If no zone was usable by the allocation flags then do not throttle */
6951 if (!pgdat)
50694c28 6952 goto out;
5515061d 6953
68243e76
MG
6954 /* Account for the throttling */
6955 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6956
5515061d
MG
6957 /*
6958 * If the caller cannot enter the filesystem, it's possible that it
6959 * is due to the caller holding an FS lock or performing a journal
6960 * transaction in the case of a filesystem like ext[3|4]. In this case,
6961 * it is not safe to block on pfmemalloc_wait as kswapd could be
6962 * blocked waiting on the same lock. Instead, throttle for up to a
6963 * second before continuing.
6964 */
2e786d9e 6965 if (!(gfp_mask & __GFP_FS))
5515061d 6966 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
c73322d0 6967 allow_direct_reclaim(pgdat), HZ);
2e786d9e
ML
6968 else
6969 /* Throttle until kswapd wakes the process */
6970 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6971 allow_direct_reclaim(pgdat));
50694c28 6972
50694c28
MG
6973 if (fatal_signal_pending(current))
6974 return true;
6975
6976out:
6977 return false;
5515061d
MG
6978}
6979
dac1d27b 6980unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
327c0e96 6981 gfp_t gfp_mask, nodemask_t *nodemask)
66e1707b 6982{
33906bc5 6983 unsigned long nr_reclaimed;
66e1707b 6984 struct scan_control sc = {
ee814fe2 6985 .nr_to_reclaim = SWAP_CLUSTER_MAX,
f2f43e56 6986 .gfp_mask = current_gfp_context(gfp_mask),
b2e18757 6987 .reclaim_idx = gfp_zone(gfp_mask),
ee814fe2
JW
6988 .order = order,
6989 .nodemask = nodemask,
6990 .priority = DEF_PRIORITY,
66e1707b 6991 .may_writepage = !laptop_mode,
a6dc60f8 6992 .may_unmap = 1,
2e2e4259 6993 .may_swap = 1,
66e1707b
BS
6994 };
6995
bb451fdf
GT
6996 /*
6997 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6998 * Confirm they are large enough for max values.
6999 */
23baf831 7000 BUILD_BUG_ON(MAX_ORDER >= S8_MAX);
bb451fdf
GT
7001 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
7002 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
7003
5515061d 7004 /*
50694c28
MG
7005 * Do not enter reclaim if fatal signal was delivered while throttled.
7006 * 1 is returned so that the page allocator does not OOM kill at this
7007 * point.
5515061d 7008 */
f2f43e56 7009 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
5515061d
MG
7010 return 1;
7011
1732d2b0 7012 set_task_reclaim_state(current, &sc.reclaim_state);
3481c37f 7013 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
33906bc5 7014
3115cd91 7015 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
33906bc5
MG
7016
7017 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
1732d2b0 7018 set_task_reclaim_state(current, NULL);
33906bc5
MG
7019
7020 return nr_reclaimed;
66e1707b
BS
7021}
7022
c255a458 7023#ifdef CONFIG_MEMCG
66e1707b 7024
d2e5fb92 7025/* Only used by soft limit reclaim. Do not reuse for anything else. */
a9dd0a83 7026unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
4e416953 7027 gfp_t gfp_mask, bool noswap,
ef8f2327 7028 pg_data_t *pgdat,
0ae5e89c 7029 unsigned long *nr_scanned)
4e416953 7030{
afaf07a6 7031 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4e416953 7032 struct scan_control sc = {
b8f5c566 7033 .nr_to_reclaim = SWAP_CLUSTER_MAX,
ee814fe2 7034 .target_mem_cgroup = memcg,
4e416953
BS
7035 .may_writepage = !laptop_mode,
7036 .may_unmap = 1,
b2e18757 7037 .reclaim_idx = MAX_NR_ZONES - 1,
4e416953 7038 .may_swap = !noswap,
4e416953 7039 };
0ae5e89c 7040
d2e5fb92
MH
7041 WARN_ON_ONCE(!current->reclaim_state);
7042
4e416953
BS
7043 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
7044 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
bdce6d9e 7045
9e3b2f8c 7046 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3481c37f 7047 sc.gfp_mask);
bdce6d9e 7048
4e416953
BS
7049 /*
7050 * NOTE: Although we can get the priority field, using it
7051 * here is not a good idea, since it limits the pages we can scan.
a9dd0a83 7052 * if we don't reclaim here, the shrink_node from balance_pgdat
4e416953
BS
7053 * will pick up pages from other mem cgroup's as well. We hack
7054 * the priority and make it zero.
7055 */
afaf07a6 7056 shrink_lruvec(lruvec, &sc);
bdce6d9e
KM
7057
7058 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
7059
0ae5e89c 7060 *nr_scanned = sc.nr_scanned;
0308f7cf 7061
4e416953
BS
7062 return sc.nr_reclaimed;
7063}
7064
72835c86 7065unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
b70a2a21 7066 unsigned long nr_pages,
a7885eb8 7067 gfp_t gfp_mask,
55ab834a 7068 unsigned int reclaim_options)
66e1707b 7069{
bdce6d9e 7070 unsigned long nr_reclaimed;
499118e9 7071 unsigned int noreclaim_flag;
66e1707b 7072 struct scan_control sc = {
b70a2a21 7073 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7dea19f9 7074 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
a09ed5e0 7075 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
b2e18757 7076 .reclaim_idx = MAX_NR_ZONES - 1,
ee814fe2
JW
7077 .target_mem_cgroup = memcg,
7078 .priority = DEF_PRIORITY,
7079 .may_writepage = !laptop_mode,
7080 .may_unmap = 1,
73b73bac
YA
7081 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
7082 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
a09ed5e0 7083 };
889976db 7084 /*
fa40d1ee
SB
7085 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
7086 * equal pressure on all the nodes. This is based on the assumption that
7087 * the reclaim does not bail out early.
889976db 7088 */
fa40d1ee 7089 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
889976db 7090
fa40d1ee 7091 set_task_reclaim_state(current, &sc.reclaim_state);
3481c37f 7092 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
499118e9 7093 noreclaim_flag = memalloc_noreclaim_save();
eb414681 7094
3115cd91 7095 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
eb414681 7096
499118e9 7097 memalloc_noreclaim_restore(noreclaim_flag);
bdce6d9e 7098 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
1732d2b0 7099 set_task_reclaim_state(current, NULL);
bdce6d9e
KM
7100
7101 return nr_reclaimed;
66e1707b
BS
7102}
7103#endif
7104
ac35a490 7105static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
f16015fb 7106{
b95a2f2d 7107 struct mem_cgroup *memcg;
b91ac374 7108 struct lruvec *lruvec;
f16015fb 7109
ac35a490
YZ
7110 if (lru_gen_enabled()) {
7111 lru_gen_age_node(pgdat, sc);
7112 return;
7113 }
7114
2f368a9f 7115 if (!can_age_anon_pages(pgdat, sc))
b95a2f2d
JW
7116 return;
7117
b91ac374
JW
7118 lruvec = mem_cgroup_lruvec(NULL, pgdat);
7119 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
7120 return;
7121
b95a2f2d
JW
7122 memcg = mem_cgroup_iter(NULL, NULL, NULL);
7123 do {
b91ac374
JW
7124 lruvec = mem_cgroup_lruvec(memcg, pgdat);
7125 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
7126 sc, LRU_ACTIVE_ANON);
b95a2f2d
JW
7127 memcg = mem_cgroup_iter(NULL, memcg, NULL);
7128 } while (memcg);
f16015fb
JW
7129}
7130
97a225e6 7131static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
1c30844d
MG
7132{
7133 int i;
7134 struct zone *zone;
7135
7136 /*
7137 * Check for watermark boosts top-down as the higher zones
7138 * are more likely to be boosted. Both watermarks and boosts
1eba09c1 7139 * should not be checked at the same time as reclaim would
1c30844d
MG
7140 * start prematurely when there is no boosting and a lower
7141 * zone is balanced.
7142 */
97a225e6 7143 for (i = highest_zoneidx; i >= 0; i--) {
1c30844d
MG
7144 zone = pgdat->node_zones + i;
7145 if (!managed_zone(zone))
7146 continue;
7147
7148 if (zone->watermark_boost)
7149 return true;
7150 }
7151
7152 return false;
7153}
7154
e716f2eb
MG
7155/*
7156 * Returns true if there is an eligible zone balanced for the request order
97a225e6 7157 * and highest_zoneidx
e716f2eb 7158 */
97a225e6 7159static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
60cefed4 7160{
e716f2eb
MG
7161 int i;
7162 unsigned long mark = -1;
7163 struct zone *zone;
60cefed4 7164
1c30844d
MG
7165 /*
7166 * Check watermarks bottom-up as lower zones are more likely to
7167 * meet watermarks.
7168 */
97a225e6 7169 for (i = 0; i <= highest_zoneidx; i++) {
e716f2eb 7170 zone = pgdat->node_zones + i;
6256c6b4 7171
e716f2eb
MG
7172 if (!managed_zone(zone))
7173 continue;
7174
c574bbe9
HY
7175 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
7176 mark = wmark_pages(zone, WMARK_PROMO);
7177 else
7178 mark = high_wmark_pages(zone);
97a225e6 7179 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
e716f2eb
MG
7180 return true;
7181 }
7182
7183 /*
36c26128 7184 * If a node has no managed zone within highest_zoneidx, it does not
e716f2eb
MG
7185 * need balancing by definition. This can happen if a zone-restricted
7186 * allocation tries to wake a remote kswapd.
7187 */
7188 if (mark == -1)
7189 return true;
7190
7191 return false;
60cefed4
JW
7192}
7193
631b6e08
MG
7194/* Clear pgdat state for congested, dirty or under writeback. */
7195static void clear_pgdat_congested(pg_data_t *pgdat)
7196{
1b05117d
JW
7197 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
7198
7199 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
631b6e08
MG
7200 clear_bit(PGDAT_DIRTY, &pgdat->flags);
7201 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
7202}
7203
5515061d
MG
7204/*
7205 * Prepare kswapd for sleeping. This verifies that there are no processes
7206 * waiting in throttle_direct_reclaim() and that watermarks have been met.
7207 *
7208 * Returns true if kswapd is ready to sleep
7209 */
97a225e6
JK
7210static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
7211 int highest_zoneidx)
f50de2d3 7212{
5515061d 7213 /*
9e5e3661 7214 * The throttled processes are normally woken up in balance_pgdat() as
c73322d0 7215 * soon as allow_direct_reclaim() is true. But there is a potential
9e5e3661
VB
7216 * race between when kswapd checks the watermarks and a process gets
7217 * throttled. There is also a potential race if processes get
7218 * throttled, kswapd wakes, a large process exits thereby balancing the
7219 * zones, which causes kswapd to exit balance_pgdat() before reaching
7220 * the wake up checks. If kswapd is going to sleep, no process should
7221 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
7222 * the wake up is premature, processes will wake kswapd and get
7223 * throttled again. The difference from wake ups in balance_pgdat() is
7224 * that here we are under prepare_to_wait().
5515061d 7225 */
9e5e3661
VB
7226 if (waitqueue_active(&pgdat->pfmemalloc_wait))
7227 wake_up_all(&pgdat->pfmemalloc_wait);
f50de2d3 7228
c73322d0
JW
7229 /* Hopeless node, leave it to direct reclaim */
7230 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
7231 return true;
7232
97a225e6 7233 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
e716f2eb
MG
7234 clear_pgdat_congested(pgdat);
7235 return true;
1d82de61
MG
7236 }
7237
333b0a45 7238 return false;
f50de2d3
MG
7239}
7240
75485363 7241/*
1d82de61
MG
7242 * kswapd shrinks a node of pages that are at or below the highest usable
7243 * zone that is currently unbalanced.
b8e83b94
MG
7244 *
7245 * Returns true if kswapd scanned at least the requested number of pages to
283aba9f
MG
7246 * reclaim or if the lack of progress was due to pages under writeback.
7247 * This is used to determine if the scanning priority needs to be raised.
75485363 7248 */
1d82de61 7249static bool kswapd_shrink_node(pg_data_t *pgdat,
accf6242 7250 struct scan_control *sc)
75485363 7251{
1d82de61
MG
7252 struct zone *zone;
7253 int z;
75485363 7254
1d82de61
MG
7255 /* Reclaim a number of pages proportional to the number of zones */
7256 sc->nr_to_reclaim = 0;
970a39a3 7257 for (z = 0; z <= sc->reclaim_idx; z++) {
1d82de61 7258 zone = pgdat->node_zones + z;
6aa303de 7259 if (!managed_zone(zone))
1d82de61 7260 continue;
7c954f6d 7261
1d82de61
MG
7262 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
7263 }
7c954f6d
MG
7264
7265 /*
1d82de61
MG
7266 * Historically care was taken to put equal pressure on all zones but
7267 * now pressure is applied based on node LRU order.
7c954f6d 7268 */
970a39a3 7269 shrink_node(pgdat, sc);
283aba9f 7270
7c954f6d 7271 /*
1d82de61
MG
7272 * Fragmentation may mean that the system cannot be rebalanced for
7273 * high-order allocations. If twice the allocation size has been
7274 * reclaimed then recheck watermarks only at order-0 to prevent
7275 * excessive reclaim. Assume that a process requested a high-order
7276 * can direct reclaim/compact.
7c954f6d 7277 */
9861a62c 7278 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
1d82de61 7279 sc->order = 0;
7c954f6d 7280
b8e83b94 7281 return sc->nr_scanned >= sc->nr_to_reclaim;
75485363
MG
7282}
7283
c49c2c47
MG
7284/* Page allocator PCP high watermark is lowered if reclaim is active. */
7285static inline void
7286update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7287{
7288 int i;
7289 struct zone *zone;
7290
7291 for (i = 0; i <= highest_zoneidx; i++) {
7292 zone = pgdat->node_zones + i;
7293
7294 if (!managed_zone(zone))
7295 continue;
7296
7297 if (active)
7298 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7299 else
7300 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7301 }
7302}
7303
7304static inline void
7305set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7306{
7307 update_reclaim_active(pgdat, highest_zoneidx, true);
7308}
7309
7310static inline void
7311clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7312{
7313 update_reclaim_active(pgdat, highest_zoneidx, false);
7314}
7315
1da177e4 7316/*
1d82de61
MG
7317 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7318 * that are eligible for use by the caller until at least one zone is
7319 * balanced.
1da177e4 7320 *
1d82de61 7321 * Returns the order kswapd finished reclaiming at.
1da177e4
LT
7322 *
7323 * kswapd scans the zones in the highmem->normal->dma direction. It skips
41858966 7324 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
8bb4e7a2 7325 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
1d82de61
MG
7326 * or lower is eligible for reclaim until at least one usable zone is
7327 * balanced.
1da177e4 7328 */
97a225e6 7329static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
1da177e4 7330{
1da177e4 7331 int i;
0608f43d
AM
7332 unsigned long nr_soft_reclaimed;
7333 unsigned long nr_soft_scanned;
eb414681 7334 unsigned long pflags;
1c30844d
MG
7335 unsigned long nr_boost_reclaim;
7336 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7337 bool boosted;
1d82de61 7338 struct zone *zone;
179e9639
AM
7339 struct scan_control sc = {
7340 .gfp_mask = GFP_KERNEL,
ee814fe2 7341 .order = order,
a6dc60f8 7342 .may_unmap = 1,
179e9639 7343 };
93781325 7344
1732d2b0 7345 set_task_reclaim_state(current, &sc.reclaim_state);
eb414681 7346 psi_memstall_enter(&pflags);
4f3eaf45 7347 __fs_reclaim_acquire(_THIS_IP_);
93781325 7348
f8891e5e 7349 count_vm_event(PAGEOUTRUN);
1da177e4 7350
1c30844d
MG
7351 /*
7352 * Account for the reclaim boost. Note that the zone boost is left in
7353 * place so that parallel allocations that are near the watermark will
7354 * stall or direct reclaim until kswapd is finished.
7355 */
7356 nr_boost_reclaim = 0;
97a225e6 7357 for (i = 0; i <= highest_zoneidx; i++) {
1c30844d
MG
7358 zone = pgdat->node_zones + i;
7359 if (!managed_zone(zone))
7360 continue;
7361
7362 nr_boost_reclaim += zone->watermark_boost;
7363 zone_boosts[i] = zone->watermark_boost;
7364 }
7365 boosted = nr_boost_reclaim;
7366
7367restart:
c49c2c47 7368 set_reclaim_active(pgdat, highest_zoneidx);
1c30844d 7369 sc.priority = DEF_PRIORITY;
9e3b2f8c 7370 do {
c73322d0 7371 unsigned long nr_reclaimed = sc.nr_reclaimed;
b8e83b94 7372 bool raise_priority = true;
1c30844d 7373 bool balanced;
93781325 7374 bool ret;
b8e83b94 7375
97a225e6 7376 sc.reclaim_idx = highest_zoneidx;
1da177e4 7377
86c79f6b 7378 /*
84c7a777
MG
7379 * If the number of buffer_heads exceeds the maximum allowed
7380 * then consider reclaiming from all zones. This has a dual
7381 * purpose -- on 64-bit systems it is expected that
7382 * buffer_heads are stripped during active rotation. On 32-bit
7383 * systems, highmem pages can pin lowmem memory and shrinking
7384 * buffers can relieve lowmem pressure. Reclaim may still not
7385 * go ahead if all eligible zones for the original allocation
7386 * request are balanced to avoid excessive reclaim from kswapd.
86c79f6b
MG
7387 */
7388 if (buffer_heads_over_limit) {
7389 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7390 zone = pgdat->node_zones + i;
6aa303de 7391 if (!managed_zone(zone))
86c79f6b 7392 continue;
cc715d99 7393
970a39a3 7394 sc.reclaim_idx = i;
e1dbeda6 7395 break;
1da177e4 7396 }
1da177e4 7397 }
dafcb73e 7398
86c79f6b 7399 /*
1c30844d
MG
7400 * If the pgdat is imbalanced then ignore boosting and preserve
7401 * the watermarks for a later time and restart. Note that the
7402 * zone watermarks will be still reset at the end of balancing
7403 * on the grounds that the normal reclaim should be enough to
7404 * re-evaluate if boosting is required when kswapd next wakes.
7405 */
97a225e6 7406 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
1c30844d
MG
7407 if (!balanced && nr_boost_reclaim) {
7408 nr_boost_reclaim = 0;
7409 goto restart;
7410 }
7411
7412 /*
7413 * If boosting is not active then only reclaim if there are no
7414 * eligible zones. Note that sc.reclaim_idx is not used as
7415 * buffer_heads_over_limit may have adjusted it.
86c79f6b 7416 */
1c30844d 7417 if (!nr_boost_reclaim && balanced)
e716f2eb 7418 goto out;
e1dbeda6 7419
1c30844d
MG
7420 /* Limit the priority of boosting to avoid reclaim writeback */
7421 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7422 raise_priority = false;
7423
7424 /*
7425 * Do not writeback or swap pages for boosted reclaim. The
7426 * intent is to relieve pressure not issue sub-optimal IO
7427 * from reclaim context. If no pages are reclaimed, the
7428 * reclaim will be aborted.
7429 */
7430 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7431 sc.may_swap = !nr_boost_reclaim;
1c30844d 7432
1d82de61 7433 /*
ac35a490
YZ
7434 * Do some background aging, to give pages a chance to be
7435 * referenced before reclaiming. All pages are rotated
7436 * regardless of classzone as this is about consistent aging.
1d82de61 7437 */
ac35a490 7438 kswapd_age_node(pgdat, &sc);
1d82de61 7439
b7ea3c41
MG
7440 /*
7441 * If we're getting trouble reclaiming, start doing writepage
7442 * even in laptop mode.
7443 */
047d72c3 7444 if (sc.priority < DEF_PRIORITY - 2)
b7ea3c41
MG
7445 sc.may_writepage = 1;
7446
1d82de61
MG
7447 /* Call soft limit reclaim before calling shrink_node. */
7448 sc.nr_scanned = 0;
7449 nr_soft_scanned = 0;
ef8f2327 7450 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
1d82de61
MG
7451 sc.gfp_mask, &nr_soft_scanned);
7452 sc.nr_reclaimed += nr_soft_reclaimed;
7453
1da177e4 7454 /*
1d82de61
MG
7455 * There should be no need to raise the scanning priority if
7456 * enough pages are already being scanned that that high
7457 * watermark would be met at 100% efficiency.
1da177e4 7458 */
970a39a3 7459 if (kswapd_shrink_node(pgdat, &sc))
1d82de61 7460 raise_priority = false;
5515061d
MG
7461
7462 /*
7463 * If the low watermark is met there is no need for processes
7464 * to be throttled on pfmemalloc_wait as they should not be
7465 * able to safely make forward progress. Wake them
7466 */
7467 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
c73322d0 7468 allow_direct_reclaim(pgdat))
cfc51155 7469 wake_up_all(&pgdat->pfmemalloc_wait);
5515061d 7470
b8e83b94 7471 /* Check if kswapd should be suspending */
4f3eaf45 7472 __fs_reclaim_release(_THIS_IP_);
93781325 7473 ret = try_to_freeze();
4f3eaf45 7474 __fs_reclaim_acquire(_THIS_IP_);
93781325 7475 if (ret || kthread_should_stop())
b8e83b94 7476 break;
8357376d 7477
73ce02e9 7478 /*
b8e83b94
MG
7479 * Raise priority if scanning rate is too low or there was no
7480 * progress in reclaiming pages
73ce02e9 7481 */
c73322d0 7482 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
1c30844d
MG
7483 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7484
7485 /*
7486 * If reclaim made no progress for a boost, stop reclaim as
7487 * IO cannot be queued and it could be an infinite loop in
7488 * extreme circumstances.
7489 */
7490 if (nr_boost_reclaim && !nr_reclaimed)
7491 break;
7492
c73322d0 7493 if (raise_priority || !nr_reclaimed)
b8e83b94 7494 sc.priority--;
1d82de61 7495 } while (sc.priority >= 1);
1da177e4 7496
c73322d0
JW
7497 if (!sc.nr_reclaimed)
7498 pgdat->kswapd_failures++;
7499
b8e83b94 7500out:
c49c2c47
MG
7501 clear_reclaim_active(pgdat, highest_zoneidx);
7502
1c30844d
MG
7503 /* If reclaim was boosted, account for the reclaim done in this pass */
7504 if (boosted) {
7505 unsigned long flags;
7506
97a225e6 7507 for (i = 0; i <= highest_zoneidx; i++) {
1c30844d
MG
7508 if (!zone_boosts[i])
7509 continue;
7510
7511 /* Increments are under the zone lock */
7512 zone = pgdat->node_zones + i;
7513 spin_lock_irqsave(&zone->lock, flags);
7514 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7515 spin_unlock_irqrestore(&zone->lock, flags);
7516 }
7517
7518 /*
7519 * As there is now likely space, wakeup kcompact to defragment
7520 * pageblocks.
7521 */
97a225e6 7522 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
1c30844d
MG
7523 }
7524
2a2e4885 7525 snapshot_refaults(NULL, pgdat);
4f3eaf45 7526 __fs_reclaim_release(_THIS_IP_);
eb414681 7527 psi_memstall_leave(&pflags);
1732d2b0 7528 set_task_reclaim_state(current, NULL);
e5ca8071 7529
0abdee2b 7530 /*
1d82de61
MG
7531 * Return the order kswapd stopped reclaiming at as
7532 * prepare_kswapd_sleep() takes it into account. If another caller
7533 * entered the allocator slow path while kswapd was awake, order will
7534 * remain at the higher level.
0abdee2b 7535 */
1d82de61 7536 return sc.order;
1da177e4
LT
7537}
7538
e716f2eb 7539/*
97a225e6
JK
7540 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7541 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7542 * not a valid index then either kswapd runs for first time or kswapd couldn't
7543 * sleep after previous reclaim attempt (node is still unbalanced). In that
7544 * case return the zone index of the previous kswapd reclaim cycle.
e716f2eb 7545 */
97a225e6
JK
7546static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7547 enum zone_type prev_highest_zoneidx)
e716f2eb 7548{
97a225e6 7549 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
5644e1fb 7550
97a225e6 7551 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
e716f2eb
MG
7552}
7553
38087d9b 7554static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
97a225e6 7555 unsigned int highest_zoneidx)
f0bc0a60
KM
7556{
7557 long remaining = 0;
7558 DEFINE_WAIT(wait);
7559
7560 if (freezing(current) || kthread_should_stop())
7561 return;
7562
7563 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7564
333b0a45
SG
7565 /*
7566 * Try to sleep for a short interval. Note that kcompactd will only be
7567 * woken if it is possible to sleep for a short interval. This is
7568 * deliberate on the assumption that if reclaim cannot keep an
7569 * eligible zone balanced that it's also unlikely that compaction will
7570 * succeed.
7571 */
97a225e6 7572 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
fd901c95
VB
7573 /*
7574 * Compaction records what page blocks it recently failed to
7575 * isolate pages from and skips them in the future scanning.
7576 * When kswapd is going to sleep, it is reasonable to assume
7577 * that pages and compaction may succeed so reset the cache.
7578 */
7579 reset_isolation_suitable(pgdat);
7580
7581 /*
7582 * We have freed the memory, now we should compact it to make
7583 * allocation of the requested order possible.
7584 */
97a225e6 7585 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
fd901c95 7586
f0bc0a60 7587 remaining = schedule_timeout(HZ/10);
38087d9b
MG
7588
7589 /*
97a225e6 7590 * If woken prematurely then reset kswapd_highest_zoneidx and
38087d9b
MG
7591 * order. The values will either be from a wakeup request or
7592 * the previous request that slept prematurely.
7593 */
7594 if (remaining) {
97a225e6
JK
7595 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7596 kswapd_highest_zoneidx(pgdat,
7597 highest_zoneidx));
5644e1fb
QC
7598
7599 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7600 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
38087d9b
MG
7601 }
7602
f0bc0a60
KM
7603 finish_wait(&pgdat->kswapd_wait, &wait);
7604 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7605 }
7606
7607 /*
7608 * After a short sleep, check if it was a premature sleep. If not, then
7609 * go fully to sleep until explicitly woken up.
7610 */
d9f21d42 7611 if (!remaining &&
97a225e6 7612 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
f0bc0a60
KM
7613 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7614
7615 /*
7616 * vmstat counters are not perfectly accurate and the estimated
7617 * value for counters such as NR_FREE_PAGES can deviate from the
7618 * true value by nr_online_cpus * threshold. To avoid the zone
7619 * watermarks being breached while under pressure, we reduce the
7620 * per-cpu vmstat threshold while kswapd is awake and restore
7621 * them before going back to sleep.
7622 */
7623 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
1c7e7f6c
AK
7624
7625 if (!kthread_should_stop())
7626 schedule();
7627
f0bc0a60
KM
7628 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7629 } else {
7630 if (remaining)
7631 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7632 else
7633 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7634 }
7635 finish_wait(&pgdat->kswapd_wait, &wait);
7636}
7637
1da177e4
LT
7638/*
7639 * The background pageout daemon, started as a kernel thread
4f98a2fe 7640 * from the init process.
1da177e4
LT
7641 *
7642 * This basically trickles out pages so that we have _some_
7643 * free memory available even if there is no other activity
7644 * that frees anything up. This is needed for things like routing
7645 * etc, where we otherwise might have all activity going on in
7646 * asynchronous contexts that cannot page things out.
7647 *
7648 * If there are applications that are active memory-allocators
7649 * (most normal use), this basically shouldn't matter.
7650 */
7651static int kswapd(void *p)
7652{
e716f2eb 7653 unsigned int alloc_order, reclaim_order;
97a225e6 7654 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
68d68ff6 7655 pg_data_t *pgdat = (pg_data_t *)p;
1da177e4 7656 struct task_struct *tsk = current;
a70f7302 7657 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1da177e4 7658
174596a0 7659 if (!cpumask_empty(cpumask))
c5f59f08 7660 set_cpus_allowed_ptr(tsk, cpumask);
1da177e4
LT
7661
7662 /*
7663 * Tell the memory management that we're a "memory allocator",
7664 * and that if we need more memory we should get access to it
7665 * regardless (see "__alloc_pages()"). "kswapd" should
7666 * never get caught in the normal page freeing logic.
7667 *
7668 * (Kswapd normally doesn't need memory anyway, but sometimes
7669 * you need a small amount of memory in order to be able to
7670 * page out something else, and this flag essentially protects
7671 * us from recursively trying to free more memory as we're
7672 * trying to free the first piece of memory in the first place).
7673 */
b698f0a1 7674 tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
83144186 7675 set_freezable();
1da177e4 7676
5644e1fb 7677 WRITE_ONCE(pgdat->kswapd_order, 0);
97a225e6 7678 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
8cd7c588 7679 atomic_set(&pgdat->nr_writeback_throttled, 0);
1da177e4 7680 for ( ; ; ) {
6f6313d4 7681 bool ret;
3e1d1d28 7682
5644e1fb 7683 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
97a225e6
JK
7684 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7685 highest_zoneidx);
e716f2eb 7686
38087d9b
MG
7687kswapd_try_sleep:
7688 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
97a225e6 7689 highest_zoneidx);
215ddd66 7690
97a225e6 7691 /* Read the new order and highest_zoneidx */
2b47a24c 7692 alloc_order = READ_ONCE(pgdat->kswapd_order);
97a225e6
JK
7693 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7694 highest_zoneidx);
5644e1fb 7695 WRITE_ONCE(pgdat->kswapd_order, 0);
97a225e6 7696 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
1da177e4 7697
8fe23e05
DR
7698 ret = try_to_freeze();
7699 if (kthread_should_stop())
7700 break;
7701
7702 /*
7703 * We can speed up thawing tasks if we don't call balance_pgdat
7704 * after returning from the refrigerator
7705 */
38087d9b
MG
7706 if (ret)
7707 continue;
7708
7709 /*
7710 * Reclaim begins at the requested order but if a high-order
7711 * reclaim fails then kswapd falls back to reclaiming for
7712 * order-0. If that happens, kswapd will consider sleeping
7713 * for the order it finished reclaiming at (reclaim_order)
7714 * but kcompactd is woken to compact for the original
7715 * request (alloc_order).
7716 */
97a225e6 7717 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
e5146b12 7718 alloc_order);
97a225e6
JK
7719 reclaim_order = balance_pgdat(pgdat, alloc_order,
7720 highest_zoneidx);
38087d9b
MG
7721 if (reclaim_order < alloc_order)
7722 goto kswapd_try_sleep;
1da177e4 7723 }
b0a8cc58 7724
b698f0a1 7725 tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
71abdc15 7726
1da177e4
LT
7727 return 0;
7728}
7729
7730/*
5ecd9d40
DR
7731 * A zone is low on free memory or too fragmented for high-order memory. If
7732 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7733 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7734 * has failed or is not needed, still wake up kcompactd if only compaction is
7735 * needed.
1da177e4 7736 */
5ecd9d40 7737void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
97a225e6 7738 enum zone_type highest_zoneidx)
1da177e4
LT
7739{
7740 pg_data_t *pgdat;
5644e1fb 7741 enum zone_type curr_idx;
1da177e4 7742
6aa303de 7743 if (!managed_zone(zone))
1da177e4
LT
7744 return;
7745
5ecd9d40 7746 if (!cpuset_zone_allowed(zone, gfp_flags))
1da177e4 7747 return;
5644e1fb 7748
88f5acf8 7749 pgdat = zone->zone_pgdat;
97a225e6 7750 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
5644e1fb 7751
97a225e6
JK
7752 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7753 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
5644e1fb
QC
7754
7755 if (READ_ONCE(pgdat->kswapd_order) < order)
7756 WRITE_ONCE(pgdat->kswapd_order, order);
dffcac2c 7757
8d0986e2 7758 if (!waitqueue_active(&pgdat->kswapd_wait))
1da177e4 7759 return;
e1a55637 7760
5ecd9d40
DR
7761 /* Hopeless node, leave it to direct reclaim if possible */
7762 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
97a225e6
JK
7763 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7764 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
5ecd9d40
DR
7765 /*
7766 * There may be plenty of free memory available, but it's too
7767 * fragmented for high-order allocations. Wake up kcompactd
7768 * and rely on compaction_suitable() to determine if it's
7769 * needed. If it fails, it will defer subsequent attempts to
7770 * ratelimit its work.
7771 */
7772 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
97a225e6 7773 wakeup_kcompactd(pgdat, order, highest_zoneidx);
e716f2eb 7774 return;
5ecd9d40 7775 }
88f5acf8 7776
97a225e6 7777 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
5ecd9d40 7778 gfp_flags);
8d0986e2 7779 wake_up_interruptible(&pgdat->kswapd_wait);
1da177e4
LT
7780}
7781
c6f37f12 7782#ifdef CONFIG_HIBERNATION
1da177e4 7783/*
7b51755c 7784 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
d6277db4
RW
7785 * freed pages.
7786 *
7787 * Rather than trying to age LRUs the aim is to preserve the overall
7788 * LRU order by reclaiming preferentially
7789 * inactive > active > active referenced > active mapped
1da177e4 7790 */
7b51755c 7791unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
1da177e4 7792{
d6277db4 7793 struct scan_control sc = {
ee814fe2 7794 .nr_to_reclaim = nr_to_reclaim,
7b51755c 7795 .gfp_mask = GFP_HIGHUSER_MOVABLE,
b2e18757 7796 .reclaim_idx = MAX_NR_ZONES - 1,
ee814fe2 7797 .priority = DEF_PRIORITY,
d6277db4 7798 .may_writepage = 1,
ee814fe2
JW
7799 .may_unmap = 1,
7800 .may_swap = 1,
7b51755c 7801 .hibernation_mode = 1,
1da177e4 7802 };
a09ed5e0 7803 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7b51755c 7804 unsigned long nr_reclaimed;
499118e9 7805 unsigned int noreclaim_flag;
1da177e4 7806
d92a8cfc 7807 fs_reclaim_acquire(sc.gfp_mask);
93781325 7808 noreclaim_flag = memalloc_noreclaim_save();
1732d2b0 7809 set_task_reclaim_state(current, &sc.reclaim_state);
d6277db4 7810
3115cd91 7811 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
d979677c 7812
1732d2b0 7813 set_task_reclaim_state(current, NULL);
499118e9 7814 memalloc_noreclaim_restore(noreclaim_flag);
93781325 7815 fs_reclaim_release(sc.gfp_mask);
d6277db4 7816
7b51755c 7817 return nr_reclaimed;
1da177e4 7818}
c6f37f12 7819#endif /* CONFIG_HIBERNATION */
1da177e4 7820
3218ae14
YG
7821/*
7822 * This kswapd start function will be called by init and node-hot-add.
3218ae14 7823 */
b87c517a 7824void kswapd_run(int nid)
3218ae14
YG
7825{
7826 pg_data_t *pgdat = NODE_DATA(nid);
3218ae14 7827
b4a0215e
KW
7828 pgdat_kswapd_lock(pgdat);
7829 if (!pgdat->kswapd) {
7830 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7831 if (IS_ERR(pgdat->kswapd)) {
7832 /* failure at boot is fatal */
7833 BUG_ON(system_state < SYSTEM_RUNNING);
7834 pr_err("Failed to start kswapd on node %d\n", nid);
7835 pgdat->kswapd = NULL;
7836 }
3218ae14 7837 }
b4a0215e 7838 pgdat_kswapd_unlock(pgdat);
3218ae14
YG
7839}
7840
8fe23e05 7841/*
d8adde17 7842 * Called by memory hotplug when all memory in a node is offlined. Caller must
e8da368a 7843 * be holding mem_hotplug_begin/done().
8fe23e05
DR
7844 */
7845void kswapd_stop(int nid)
7846{
b4a0215e
KW
7847 pg_data_t *pgdat = NODE_DATA(nid);
7848 struct task_struct *kswapd;
8fe23e05 7849
b4a0215e
KW
7850 pgdat_kswapd_lock(pgdat);
7851 kswapd = pgdat->kswapd;
d8adde17 7852 if (kswapd) {
8fe23e05 7853 kthread_stop(kswapd);
b4a0215e 7854 pgdat->kswapd = NULL;
d8adde17 7855 }
b4a0215e 7856 pgdat_kswapd_unlock(pgdat);
8fe23e05
DR
7857}
7858
1da177e4
LT
7859static int __init kswapd_init(void)
7860{
6b700b5b 7861 int nid;
69e05944 7862
1da177e4 7863 swap_setup();
48fb2e24 7864 for_each_node_state(nid, N_MEMORY)
3218ae14 7865 kswapd_run(nid);
1da177e4
LT
7866 return 0;
7867}
7868
7869module_init(kswapd_init)
9eeff239
CL
7870
7871#ifdef CONFIG_NUMA
7872/*
a5f5f91d 7873 * Node reclaim mode
9eeff239 7874 *
a5f5f91d 7875 * If non-zero call node_reclaim when the number of free pages falls below
9eeff239 7876 * the watermarks.
9eeff239 7877 */
a5f5f91d 7878int node_reclaim_mode __read_mostly;
9eeff239 7879
a92f7126 7880/*
a5f5f91d 7881 * Priority for NODE_RECLAIM. This determines the fraction of pages
a92f7126
CL
7882 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7883 * a zone.
7884 */
a5f5f91d 7885#define NODE_RECLAIM_PRIORITY 4
a92f7126 7886
9614634f 7887/*
a5f5f91d 7888 * Percentage of pages in a zone that must be unmapped for node_reclaim to
9614634f
CL
7889 * occur.
7890 */
7891int sysctl_min_unmapped_ratio = 1;
7892
0ff38490
CL
7893/*
7894 * If the number of slab pages in a zone grows beyond this percentage then
7895 * slab reclaim needs to occur.
7896 */
7897int sysctl_min_slab_ratio = 5;
7898
11fb9989 7899static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
90afa5de 7900{
11fb9989
MG
7901 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7902 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7903 node_page_state(pgdat, NR_ACTIVE_FILE);
90afa5de
MG
7904
7905 /*
7906 * It's possible for there to be more file mapped pages than
7907 * accounted for by the pages on the file LRU lists because
7908 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7909 */
7910 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7911}
7912
7913/* Work out how many page cache pages we can reclaim in this reclaim_mode */
a5f5f91d 7914static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
90afa5de 7915{
d031a157
AM
7916 unsigned long nr_pagecache_reclaimable;
7917 unsigned long delta = 0;
90afa5de
MG
7918
7919 /*
95bbc0c7 7920 * If RECLAIM_UNMAP is set, then all file pages are considered
90afa5de 7921 * potentially reclaimable. Otherwise, we have to worry about
11fb9989 7922 * pages like swapcache and node_unmapped_file_pages() provides
90afa5de
MG
7923 * a better estimate
7924 */
a5f5f91d
MG
7925 if (node_reclaim_mode & RECLAIM_UNMAP)
7926 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
90afa5de 7927 else
a5f5f91d 7928 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
90afa5de
MG
7929
7930 /* If we can't clean pages, remove dirty pages from consideration */
a5f5f91d
MG
7931 if (!(node_reclaim_mode & RECLAIM_WRITE))
7932 delta += node_page_state(pgdat, NR_FILE_DIRTY);
90afa5de
MG
7933
7934 /* Watch for any possible underflows due to delta */
7935 if (unlikely(delta > nr_pagecache_reclaimable))
7936 delta = nr_pagecache_reclaimable;
7937
7938 return nr_pagecache_reclaimable - delta;
7939}
7940
9eeff239 7941/*
a5f5f91d 7942 * Try to free up some pages from this node through reclaim.
9eeff239 7943 */
a5f5f91d 7944static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
9eeff239 7945{
7fb2d46d 7946 /* Minimum pages needed in order to stay on node */
69e05944 7947 const unsigned long nr_pages = 1 << order;
9eeff239 7948 struct task_struct *p = current;
499118e9 7949 unsigned int noreclaim_flag;
179e9639 7950 struct scan_control sc = {
62b726c1 7951 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
f2f43e56 7952 .gfp_mask = current_gfp_context(gfp_mask),
bd2f6199 7953 .order = order,
a5f5f91d
MG
7954 .priority = NODE_RECLAIM_PRIORITY,
7955 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7956 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
ee814fe2 7957 .may_swap = 1,
f2f43e56 7958 .reclaim_idx = gfp_zone(gfp_mask),
179e9639 7959 };
57f29762 7960 unsigned long pflags;
9eeff239 7961
132bb8cf
YS
7962 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7963 sc.gfp_mask);
7964
9eeff239 7965 cond_resched();
57f29762 7966 psi_memstall_enter(&pflags);
93781325 7967 fs_reclaim_acquire(sc.gfp_mask);
d4f7796e 7968 /*
95bbc0c7 7969 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
d4f7796e 7970 */
499118e9 7971 noreclaim_flag = memalloc_noreclaim_save();
1732d2b0 7972 set_task_reclaim_state(p, &sc.reclaim_state);
c84db23c 7973
d8ff6fde
ML
7974 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7975 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
0ff38490 7976 /*
894befec 7977 * Free memory by calling shrink node with increasing
0ff38490
CL
7978 * priorities until we have enough memory freed.
7979 */
0ff38490 7980 do {
970a39a3 7981 shrink_node(pgdat, &sc);
9e3b2f8c 7982 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
0ff38490 7983 }
c84db23c 7984
1732d2b0 7985 set_task_reclaim_state(p, NULL);
499118e9 7986 memalloc_noreclaim_restore(noreclaim_flag);
93781325 7987 fs_reclaim_release(sc.gfp_mask);
57f29762 7988 psi_memstall_leave(&pflags);
132bb8cf
YS
7989
7990 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7991
a79311c1 7992 return sc.nr_reclaimed >= nr_pages;
9eeff239 7993}
179e9639 7994
a5f5f91d 7995int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
179e9639 7996{
d773ed6b 7997 int ret;
179e9639
AM
7998
7999 /*
a5f5f91d 8000 * Node reclaim reclaims unmapped file backed pages and
0ff38490 8001 * slab pages if we are over the defined limits.
34aa1330 8002 *
9614634f
CL
8003 * A small portion of unmapped file backed pages is needed for
8004 * file I/O otherwise pages read by file I/O will be immediately
a5f5f91d
MG
8005 * thrown out if the node is overallocated. So we do not reclaim
8006 * if less than a specified percentage of the node is used by
9614634f 8007 * unmapped file backed pages.
179e9639 8008 */
a5f5f91d 8009 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
d42f3245
RG
8010 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
8011 pgdat->min_slab_pages)
a5f5f91d 8012 return NODE_RECLAIM_FULL;
179e9639
AM
8013
8014 /*
d773ed6b 8015 * Do not scan if the allocation should not be delayed.
179e9639 8016 */
d0164adc 8017 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
a5f5f91d 8018 return NODE_RECLAIM_NOSCAN;
179e9639
AM
8019
8020 /*
a5f5f91d 8021 * Only run node reclaim on the local node or on nodes that do not
179e9639
AM
8022 * have associated processors. This will favor the local processor
8023 * over remote processors and spread off node memory allocations
8024 * as wide as possible.
8025 */
a5f5f91d
MG
8026 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
8027 return NODE_RECLAIM_NOSCAN;
d773ed6b 8028
a5f5f91d
MG
8029 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
8030 return NODE_RECLAIM_NOSCAN;
fa5e084e 8031
a5f5f91d
MG
8032 ret = __node_reclaim(pgdat, gfp_mask, order);
8033 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
d773ed6b 8034
24cf7251
MG
8035 if (!ret)
8036 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
8037
d773ed6b 8038 return ret;
179e9639 8039}
9eeff239 8040#endif
894bc310 8041
77414d19
MWO
8042void check_move_unevictable_pages(struct pagevec *pvec)
8043{
8044 struct folio_batch fbatch;
8045 unsigned i;
8046
8047 folio_batch_init(&fbatch);
8048 for (i = 0; i < pvec->nr; i++) {
8049 struct page *page = pvec->pages[i];
8050
8051 if (PageTransTail(page))
8052 continue;
8053 folio_batch_add(&fbatch, page_folio(page));
8054 }
8055 check_move_unevictable_folios(&fbatch);
8056}
8057EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
8058
89e004ea 8059/**
77414d19
MWO
8060 * check_move_unevictable_folios - Move evictable folios to appropriate zone
8061 * lru list
8062 * @fbatch: Batch of lru folios to check.
89e004ea 8063 *
77414d19 8064 * Checks folios for evictability, if an evictable folio is in the unevictable
64e3d12f 8065 * lru list, moves it to the appropriate evictable lru list. This function
77414d19 8066 * should be only used for lru folios.
89e004ea 8067 */
77414d19 8068void check_move_unevictable_folios(struct folio_batch *fbatch)
89e004ea 8069{
6168d0da 8070 struct lruvec *lruvec = NULL;
24513264
HD
8071 int pgscanned = 0;
8072 int pgrescued = 0;
8073 int i;
89e004ea 8074
77414d19
MWO
8075 for (i = 0; i < fbatch->nr; i++) {
8076 struct folio *folio = fbatch->folios[i];
8077 int nr_pages = folio_nr_pages(folio);
8d8869ca 8078
8d8869ca 8079 pgscanned += nr_pages;
89e004ea 8080
77414d19
MWO
8081 /* block memcg migration while the folio moves between lrus */
8082 if (!folio_test_clear_lru(folio))
d25b5bd8
AS
8083 continue;
8084
0de340cb 8085 lruvec = folio_lruvec_relock_irq(folio, lruvec);
77414d19
MWO
8086 if (folio_evictable(folio) && folio_test_unevictable(folio)) {
8087 lruvec_del_folio(lruvec, folio);
8088 folio_clear_unevictable(folio);
8089 lruvec_add_folio(lruvec, folio);
8d8869ca 8090 pgrescued += nr_pages;
89e004ea 8091 }
77414d19 8092 folio_set_lru(folio);
24513264 8093 }
89e004ea 8094
6168d0da 8095 if (lruvec) {
24513264
HD
8096 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
8097 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
6168d0da 8098 unlock_page_lruvec_irq(lruvec);
d25b5bd8
AS
8099 } else if (pgscanned) {
8100 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
89e004ea 8101 }
89e004ea 8102}
77414d19 8103EXPORT_SYMBOL_GPL(check_move_unevictable_folios);