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