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