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