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