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