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