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