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