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