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