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