]> git.ipfire.org Git - thirdparty/linux.git/blame - mm/vmscan.c
shrinker: add node awareness
[thirdparty/linux.git] / mm / vmscan.c
CommitLineData
1da177e4
LT
1/*
2 * linux/mm/vmscan.c
3 *
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 *
6 * Swap reorganised 29.12.95, Stephen Tweedie.
7 * kswapd added: 7.1.96 sct
8 * Removed kswapd_ctl limits, and swap out as many pages as needed
9 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
10 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
11 * Multiqueue VM started 5.8.00, Rik van Riel.
12 */
13
14#include <linux/mm.h>
15#include <linux/module.h>
5a0e3ad6 16#include <linux/gfp.h>
1da177e4
LT
17#include <linux/kernel_stat.h>
18#include <linux/swap.h>
19#include <linux/pagemap.h>
20#include <linux/init.h>
21#include <linux/highmem.h>
70ddf637 22#include <linux/vmpressure.h>
e129b5c2 23#include <linux/vmstat.h>
1da177e4
LT
24#include <linux/file.h>
25#include <linux/writeback.h>
26#include <linux/blkdev.h>
27#include <linux/buffer_head.h> /* for try_to_release_page(),
28 buffer_heads_over_limit */
29#include <linux/mm_inline.h>
1da177e4
LT
30#include <linux/backing-dev.h>
31#include <linux/rmap.h>
32#include <linux/topology.h>
33#include <linux/cpu.h>
34#include <linux/cpuset.h>
3e7d3449 35#include <linux/compaction.h>
1da177e4
LT
36#include <linux/notifier.h>
37#include <linux/rwsem.h>
248a0301 38#include <linux/delay.h>
3218ae14 39#include <linux/kthread.h>
7dfb7103 40#include <linux/freezer.h>
66e1707b 41#include <linux/memcontrol.h>
873b4771 42#include <linux/delayacct.h>
af936a16 43#include <linux/sysctl.h>
929bea7c 44#include <linux/oom.h>
268bb0ce 45#include <linux/prefetch.h>
1da177e4
LT
46
47#include <asm/tlbflush.h>
48#include <asm/div64.h>
49
50#include <linux/swapops.h>
51
0f8053a5
NP
52#include "internal.h"
53
33906bc5
MG
54#define CREATE_TRACE_POINTS
55#include <trace/events/vmscan.h>
56
1da177e4 57struct scan_control {
1da177e4
LT
58 /* Incremented by the number of inactive pages that were scanned */
59 unsigned long nr_scanned;
60
a79311c1
RR
61 /* Number of pages freed so far during a call to shrink_zones() */
62 unsigned long nr_reclaimed;
63
22fba335
KM
64 /* How many pages shrink_list() should reclaim */
65 unsigned long nr_to_reclaim;
66
7b51755c
KM
67 unsigned long hibernation_mode;
68
1da177e4 69 /* This context's GFP mask */
6daa0e28 70 gfp_t gfp_mask;
1da177e4
LT
71
72 int may_writepage;
73
a6dc60f8
JW
74 /* Can mapped pages be reclaimed? */
75 int may_unmap;
f1fd1067 76
2e2e4259
KM
77 /* Can pages be swapped as part of reclaim? */
78 int may_swap;
79
5ad333eb 80 int order;
66e1707b 81
9e3b2f8c
KK
82 /* Scan (total_size >> priority) pages at once */
83 int priority;
84
f16015fb
JW
85 /*
86 * The memory cgroup that hit its limit and as a result is the
87 * primary target of this reclaim invocation.
88 */
89 struct mem_cgroup *target_mem_cgroup;
66e1707b 90
327c0e96
KH
91 /*
92 * Nodemask of nodes allowed by the caller. If NULL, all nodes
93 * are scanned.
94 */
95 nodemask_t *nodemask;
1da177e4
LT
96};
97
1da177e4
LT
98#define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
99
100#ifdef ARCH_HAS_PREFETCH
101#define prefetch_prev_lru_page(_page, _base, _field) \
102 do { \
103 if ((_page)->lru.prev != _base) { \
104 struct page *prev; \
105 \
106 prev = lru_to_page(&(_page->lru)); \
107 prefetch(&prev->_field); \
108 } \
109 } while (0)
110#else
111#define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
112#endif
113
114#ifdef ARCH_HAS_PREFETCHW
115#define prefetchw_prev_lru_page(_page, _base, _field) \
116 do { \
117 if ((_page)->lru.prev != _base) { \
118 struct page *prev; \
119 \
120 prev = lru_to_page(&(_page->lru)); \
121 prefetchw(&prev->_field); \
122 } \
123 } while (0)
124#else
125#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
126#endif
127
128/*
129 * From 0 .. 100. Higher means more swappy.
130 */
131int vm_swappiness = 60;
b21e0b90 132unsigned long vm_total_pages; /* The total number of pages which the VM controls */
1da177e4
LT
133
134static LIST_HEAD(shrinker_list);
135static DECLARE_RWSEM(shrinker_rwsem);
136
c255a458 137#ifdef CONFIG_MEMCG
89b5fae5
JW
138static bool global_reclaim(struct scan_control *sc)
139{
f16015fb 140 return !sc->target_mem_cgroup;
89b5fae5 141}
91a45470 142#else
89b5fae5
JW
143static bool global_reclaim(struct scan_control *sc)
144{
145 return true;
146}
91a45470
KH
147#endif
148
4d7dcca2 149static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
c9f299d9 150{
c3c787e8 151 if (!mem_cgroup_disabled())
4d7dcca2 152 return mem_cgroup_get_lru_size(lruvec, lru);
a3d8e054 153
074291fe 154 return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
c9f299d9
KM
155}
156
1da177e4
LT
157/*
158 * Add a shrinker callback to be called from the vm
159 */
8e1f936b 160void register_shrinker(struct shrinker *shrinker)
1da177e4 161{
83aeeada 162 atomic_long_set(&shrinker->nr_in_batch, 0);
8e1f936b
RR
163 down_write(&shrinker_rwsem);
164 list_add_tail(&shrinker->list, &shrinker_list);
165 up_write(&shrinker_rwsem);
1da177e4 166}
8e1f936b 167EXPORT_SYMBOL(register_shrinker);
1da177e4
LT
168
169/*
170 * Remove one
171 */
8e1f936b 172void unregister_shrinker(struct shrinker *shrinker)
1da177e4
LT
173{
174 down_write(&shrinker_rwsem);
175 list_del(&shrinker->list);
176 up_write(&shrinker_rwsem);
1da177e4 177}
8e1f936b 178EXPORT_SYMBOL(unregister_shrinker);
1da177e4 179
1495f230
YH
180static inline int do_shrinker_shrink(struct shrinker *shrinker,
181 struct shrink_control *sc,
182 unsigned long nr_to_scan)
183{
184 sc->nr_to_scan = nr_to_scan;
185 return (*shrinker->shrink)(shrinker, sc);
186}
187
1da177e4
LT
188#define SHRINK_BATCH 128
189/*
190 * Call the shrink functions to age shrinkable caches
191 *
192 * Here we assume it costs one seek to replace a lru page and that it also
193 * takes a seek to recreate a cache object. With this in mind we age equal
194 * percentages of the lru and ageable caches. This should balance the seeks
195 * generated by these structures.
196 *
183ff22b 197 * If the vm encountered mapped pages on the LRU it increase the pressure on
1da177e4
LT
198 * slab to avoid swapping.
199 *
200 * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
201 *
202 * `lru_pages' represents the number of on-LRU pages in all the zones which
203 * are eligible for the caller's allocation attempt. It is used for balancing
204 * slab reclaim versus page reclaim.
b15e0905 205 *
206 * Returns the number of slab objects which we shrunk.
1da177e4 207 */
24f7c6b9 208unsigned long shrink_slab(struct shrink_control *shrinkctl,
1495f230 209 unsigned long nr_pages_scanned,
a09ed5e0 210 unsigned long lru_pages)
1da177e4
LT
211{
212 struct shrinker *shrinker;
24f7c6b9 213 unsigned long freed = 0;
1da177e4 214
1495f230
YH
215 if (nr_pages_scanned == 0)
216 nr_pages_scanned = SWAP_CLUSTER_MAX;
1da177e4 217
f06590bd 218 if (!down_read_trylock(&shrinker_rwsem)) {
24f7c6b9
DC
219 /*
220 * If we would return 0, our callers would understand that we
221 * have nothing else to shrink and give up trying. By returning
222 * 1 we keep it going and assume we'll be able to shrink next
223 * time.
224 */
225 freed = 1;
f06590bd
MK
226 goto out;
227 }
1da177e4
LT
228
229 list_for_each_entry(shrinker, &shrinker_list, list) {
230 unsigned long long delta;
635697c6
KK
231 long total_scan;
232 long max_pass;
acf92b48
DC
233 long nr;
234 long new_nr;
e9299f50
DC
235 long batch_size = shrinker->batch ? shrinker->batch
236 : SHRINK_BATCH;
1da177e4 237
24f7c6b9
DC
238 if (shrinker->count_objects)
239 max_pass = shrinker->count_objects(shrinker, shrinkctl);
240 else
241 max_pass = do_shrinker_shrink(shrinker, shrinkctl, 0);
242 if (max_pass == 0)
635697c6
KK
243 continue;
244
acf92b48
DC
245 /*
246 * copy the current shrinker scan count into a local variable
247 * and zero it so that other concurrent shrinker invocations
248 * don't also do this scanning work.
249 */
83aeeada 250 nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
acf92b48
DC
251
252 total_scan = nr;
1495f230 253 delta = (4 * nr_pages_scanned) / shrinker->seeks;
ea164d73 254 delta *= max_pass;
1da177e4 255 do_div(delta, lru_pages + 1);
acf92b48
DC
256 total_scan += delta;
257 if (total_scan < 0) {
24f7c6b9
DC
258 printk(KERN_ERR
259 "shrink_slab: %pF negative objects to delete nr=%ld\n",
acf92b48
DC
260 shrinker->shrink, total_scan);
261 total_scan = max_pass;
ea164d73
AA
262 }
263
3567b59a
DC
264 /*
265 * We need to avoid excessive windup on filesystem shrinkers
266 * due to large numbers of GFP_NOFS allocations causing the
267 * shrinkers to return -1 all the time. This results in a large
268 * nr being built up so when a shrink that can do some work
269 * comes along it empties the entire cache due to nr >>>
270 * max_pass. This is bad for sustaining a working set in
271 * memory.
272 *
273 * Hence only allow the shrinker to scan the entire cache when
274 * a large delta change is calculated directly.
275 */
276 if (delta < max_pass / 4)
277 total_scan = min(total_scan, max_pass / 2);
278
ea164d73
AA
279 /*
280 * Avoid risking looping forever due to too large nr value:
281 * never try to free more than twice the estimate number of
282 * freeable entries.
283 */
acf92b48
DC
284 if (total_scan > max_pass * 2)
285 total_scan = max_pass * 2;
1da177e4 286
24f7c6b9 287 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
09576073
DC
288 nr_pages_scanned, lru_pages,
289 max_pass, delta, total_scan);
290
e9299f50 291 while (total_scan >= batch_size) {
24f7c6b9
DC
292
293 if (shrinker->scan_objects) {
294 unsigned long ret;
295 shrinkctl->nr_to_scan = batch_size;
296 ret = shrinker->scan_objects(shrinker, shrinkctl);
297
298 if (ret == SHRINK_STOP)
299 break;
300 freed += ret;
301 } else {
302 int nr_before;
303 long ret;
304
305 nr_before = do_shrinker_shrink(shrinker, shrinkctl, 0);
306 ret = do_shrinker_shrink(shrinker, shrinkctl,
307 batch_size);
308 if (ret == -1)
309 break;
310 if (ret < nr_before)
311 freed += nr_before - ret;
312 }
313
e9299f50
DC
314 count_vm_events(SLABS_SCANNED, batch_size);
315 total_scan -= batch_size;
1da177e4
LT
316
317 cond_resched();
318 }
319
acf92b48
DC
320 /*
321 * move the unused scan count back into the shrinker in a
322 * manner that handles concurrent updates. If we exhausted the
323 * scan, there is no need to do an update.
324 */
83aeeada
KK
325 if (total_scan > 0)
326 new_nr = atomic_long_add_return(total_scan,
327 &shrinker->nr_in_batch);
328 else
329 new_nr = atomic_long_read(&shrinker->nr_in_batch);
acf92b48 330
24f7c6b9 331 trace_mm_shrink_slab_end(shrinker, freed, nr, new_nr);
1da177e4
LT
332 }
333 up_read(&shrinker_rwsem);
f06590bd
MK
334out:
335 cond_resched();
24f7c6b9 336 return freed;
1da177e4
LT
337}
338
1da177e4
LT
339static inline int is_page_cache_freeable(struct page *page)
340{
ceddc3a5
JW
341 /*
342 * A freeable page cache page is referenced only by the caller
343 * that isolated the page, the page cache radix tree and
344 * optional buffer heads at page->private.
345 */
edcf4748 346 return page_count(page) - page_has_private(page) == 2;
1da177e4
LT
347}
348
7d3579e8
KM
349static int may_write_to_queue(struct backing_dev_info *bdi,
350 struct scan_control *sc)
1da177e4 351{
930d9152 352 if (current->flags & PF_SWAPWRITE)
1da177e4
LT
353 return 1;
354 if (!bdi_write_congested(bdi))
355 return 1;
356 if (bdi == current->backing_dev_info)
357 return 1;
358 return 0;
359}
360
361/*
362 * We detected a synchronous write error writing a page out. Probably
363 * -ENOSPC. We need to propagate that into the address_space for a subsequent
364 * fsync(), msync() or close().
365 *
366 * The tricky part is that after writepage we cannot touch the mapping: nothing
367 * prevents it from being freed up. But we have a ref on the page and once
368 * that page is locked, the mapping is pinned.
369 *
370 * We're allowed to run sleeping lock_page() here because we know the caller has
371 * __GFP_FS.
372 */
373static void handle_write_error(struct address_space *mapping,
374 struct page *page, int error)
375{
7eaceacc 376 lock_page(page);
3e9f45bd
GC
377 if (page_mapping(page) == mapping)
378 mapping_set_error(mapping, error);
1da177e4
LT
379 unlock_page(page);
380}
381
04e62a29
CL
382/* possible outcome of pageout() */
383typedef enum {
384 /* failed to write page out, page is locked */
385 PAGE_KEEP,
386 /* move page to the active list, page is locked */
387 PAGE_ACTIVATE,
388 /* page has been sent to the disk successfully, page is unlocked */
389 PAGE_SUCCESS,
390 /* page is clean and locked */
391 PAGE_CLEAN,
392} pageout_t;
393
1da177e4 394/*
1742f19f
AM
395 * pageout is called by shrink_page_list() for each dirty page.
396 * Calls ->writepage().
1da177e4 397 */
c661b078 398static pageout_t pageout(struct page *page, struct address_space *mapping,
7d3579e8 399 struct scan_control *sc)
1da177e4
LT
400{
401 /*
402 * If the page is dirty, only perform writeback if that write
403 * will be non-blocking. To prevent this allocation from being
404 * stalled by pagecache activity. But note that there may be
405 * stalls if we need to run get_block(). We could test
406 * PagePrivate for that.
407 *
6aceb53b 408 * If this process is currently in __generic_file_aio_write() against
1da177e4
LT
409 * this page's queue, we can perform writeback even if that
410 * will block.
411 *
412 * If the page is swapcache, write it back even if that would
413 * block, for some throttling. This happens by accident, because
414 * swap_backing_dev_info is bust: it doesn't reflect the
415 * congestion state of the swapdevs. Easy to fix, if needed.
1da177e4
LT
416 */
417 if (!is_page_cache_freeable(page))
418 return PAGE_KEEP;
419 if (!mapping) {
420 /*
421 * Some data journaling orphaned pages can have
422 * page->mapping == NULL while being dirty with clean buffers.
423 */
266cf658 424 if (page_has_private(page)) {
1da177e4
LT
425 if (try_to_free_buffers(page)) {
426 ClearPageDirty(page);
d40cee24 427 printk("%s: orphaned page\n", __func__);
1da177e4
LT
428 return PAGE_CLEAN;
429 }
430 }
431 return PAGE_KEEP;
432 }
433 if (mapping->a_ops->writepage == NULL)
434 return PAGE_ACTIVATE;
0e093d99 435 if (!may_write_to_queue(mapping->backing_dev_info, sc))
1da177e4
LT
436 return PAGE_KEEP;
437
438 if (clear_page_dirty_for_io(page)) {
439 int res;
440 struct writeback_control wbc = {
441 .sync_mode = WB_SYNC_NONE,
442 .nr_to_write = SWAP_CLUSTER_MAX,
111ebb6e
OH
443 .range_start = 0,
444 .range_end = LLONG_MAX,
1da177e4
LT
445 .for_reclaim = 1,
446 };
447
448 SetPageReclaim(page);
449 res = mapping->a_ops->writepage(page, &wbc);
450 if (res < 0)
451 handle_write_error(mapping, page, res);
994fc28c 452 if (res == AOP_WRITEPAGE_ACTIVATE) {
1da177e4
LT
453 ClearPageReclaim(page);
454 return PAGE_ACTIVATE;
455 }
c661b078 456
1da177e4
LT
457 if (!PageWriteback(page)) {
458 /* synchronous write or broken a_ops? */
459 ClearPageReclaim(page);
460 }
23b9da55 461 trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
e129b5c2 462 inc_zone_page_state(page, NR_VMSCAN_WRITE);
1da177e4
LT
463 return PAGE_SUCCESS;
464 }
465
466 return PAGE_CLEAN;
467}
468
a649fd92 469/*
e286781d
NP
470 * Same as remove_mapping, but if the page is removed from the mapping, it
471 * gets returned with a refcount of 0.
a649fd92 472 */
e286781d 473static int __remove_mapping(struct address_space *mapping, struct page *page)
49d2e9cc 474{
28e4d965
NP
475 BUG_ON(!PageLocked(page));
476 BUG_ON(mapping != page_mapping(page));
49d2e9cc 477
19fd6231 478 spin_lock_irq(&mapping->tree_lock);
49d2e9cc 479 /*
0fd0e6b0
NP
480 * The non racy check for a busy page.
481 *
482 * Must be careful with the order of the tests. When someone has
483 * a ref to the page, it may be possible that they dirty it then
484 * drop the reference. So if PageDirty is tested before page_count
485 * here, then the following race may occur:
486 *
487 * get_user_pages(&page);
488 * [user mapping goes away]
489 * write_to(page);
490 * !PageDirty(page) [good]
491 * SetPageDirty(page);
492 * put_page(page);
493 * !page_count(page) [good, discard it]
494 *
495 * [oops, our write_to data is lost]
496 *
497 * Reversing the order of the tests ensures such a situation cannot
498 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
499 * load is not satisfied before that of page->_count.
500 *
501 * Note that if SetPageDirty is always performed via set_page_dirty,
502 * and thus under tree_lock, then this ordering is not required.
49d2e9cc 503 */
e286781d 504 if (!page_freeze_refs(page, 2))
49d2e9cc 505 goto cannot_free;
e286781d
NP
506 /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
507 if (unlikely(PageDirty(page))) {
508 page_unfreeze_refs(page, 2);
49d2e9cc 509 goto cannot_free;
e286781d 510 }
49d2e9cc
CL
511
512 if (PageSwapCache(page)) {
513 swp_entry_t swap = { .val = page_private(page) };
514 __delete_from_swap_cache(page);
19fd6231 515 spin_unlock_irq(&mapping->tree_lock);
cb4b86ba 516 swapcache_free(swap, page);
e286781d 517 } else {
6072d13c
LT
518 void (*freepage)(struct page *);
519
520 freepage = mapping->a_ops->freepage;
521
e64a782f 522 __delete_from_page_cache(page);
19fd6231 523 spin_unlock_irq(&mapping->tree_lock);
e767e056 524 mem_cgroup_uncharge_cache_page(page);
6072d13c
LT
525
526 if (freepage != NULL)
527 freepage(page);
49d2e9cc
CL
528 }
529
49d2e9cc
CL
530 return 1;
531
532cannot_free:
19fd6231 533 spin_unlock_irq(&mapping->tree_lock);
49d2e9cc
CL
534 return 0;
535}
536
e286781d
NP
537/*
538 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
539 * someone else has a ref on the page, abort and return 0. If it was
540 * successfully detached, return 1. Assumes the caller has a single ref on
541 * this page.
542 */
543int remove_mapping(struct address_space *mapping, struct page *page)
544{
545 if (__remove_mapping(mapping, page)) {
546 /*
547 * Unfreezing the refcount with 1 rather than 2 effectively
548 * drops the pagecache ref for us without requiring another
549 * atomic operation.
550 */
551 page_unfreeze_refs(page, 1);
552 return 1;
553 }
554 return 0;
555}
556
894bc310
LS
557/**
558 * putback_lru_page - put previously isolated page onto appropriate LRU list
559 * @page: page to be put back to appropriate lru list
560 *
561 * Add previously isolated @page to appropriate LRU list.
562 * Page may still be unevictable for other reasons.
563 *
564 * lru_lock must not be held, interrupts must be enabled.
565 */
894bc310
LS
566void putback_lru_page(struct page *page)
567{
568 int lru;
bbfd28ee 569 int was_unevictable = PageUnevictable(page);
894bc310
LS
570
571 VM_BUG_ON(PageLRU(page));
572
573redo:
574 ClearPageUnevictable(page);
575
39b5f29a 576 if (page_evictable(page)) {
894bc310
LS
577 /*
578 * For evictable pages, we can use the cache.
579 * In event of a race, worst case is we end up with an
580 * unevictable page on [in]active list.
581 * We know how to handle that.
582 */
c53954a0
MG
583 lru = page_lru_base_type(page);
584 lru_cache_add(page);
894bc310
LS
585 } else {
586 /*
587 * Put unevictable pages directly on zone's unevictable
588 * list.
589 */
590 lru = LRU_UNEVICTABLE;
591 add_page_to_unevictable_list(page);
6a7b9548 592 /*
21ee9f39
MK
593 * When racing with an mlock or AS_UNEVICTABLE clearing
594 * (page is unlocked) make sure that if the other thread
595 * does not observe our setting of PG_lru and fails
24513264 596 * isolation/check_move_unevictable_pages,
21ee9f39 597 * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
6a7b9548
JW
598 * the page back to the evictable list.
599 *
21ee9f39 600 * The other side is TestClearPageMlocked() or shmem_lock().
6a7b9548
JW
601 */
602 smp_mb();
894bc310 603 }
894bc310
LS
604
605 /*
606 * page's status can change while we move it among lru. If an evictable
607 * page is on unevictable list, it never be freed. To avoid that,
608 * check after we added it to the list, again.
609 */
39b5f29a 610 if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
894bc310
LS
611 if (!isolate_lru_page(page)) {
612 put_page(page);
613 goto redo;
614 }
615 /* This means someone else dropped this page from LRU
616 * So, it will be freed or putback to LRU again. There is
617 * nothing to do here.
618 */
619 }
620
bbfd28ee
LS
621 if (was_unevictable && lru != LRU_UNEVICTABLE)
622 count_vm_event(UNEVICTABLE_PGRESCUED);
623 else if (!was_unevictable && lru == LRU_UNEVICTABLE)
624 count_vm_event(UNEVICTABLE_PGCULLED);
625
894bc310
LS
626 put_page(page); /* drop ref from isolate */
627}
628
dfc8d636
JW
629enum page_references {
630 PAGEREF_RECLAIM,
631 PAGEREF_RECLAIM_CLEAN,
64574746 632 PAGEREF_KEEP,
dfc8d636
JW
633 PAGEREF_ACTIVATE,
634};
635
636static enum page_references page_check_references(struct page *page,
637 struct scan_control *sc)
638{
64574746 639 int referenced_ptes, referenced_page;
dfc8d636 640 unsigned long vm_flags;
dfc8d636 641
c3ac9a8a
JW
642 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
643 &vm_flags);
64574746 644 referenced_page = TestClearPageReferenced(page);
dfc8d636 645
dfc8d636
JW
646 /*
647 * Mlock lost the isolation race with us. Let try_to_unmap()
648 * move the page to the unevictable list.
649 */
650 if (vm_flags & VM_LOCKED)
651 return PAGEREF_RECLAIM;
652
64574746 653 if (referenced_ptes) {
e4898273 654 if (PageSwapBacked(page))
64574746
JW
655 return PAGEREF_ACTIVATE;
656 /*
657 * All mapped pages start out with page table
658 * references from the instantiating fault, so we need
659 * to look twice if a mapped file page is used more
660 * than once.
661 *
662 * Mark it and spare it for another trip around the
663 * inactive list. Another page table reference will
664 * lead to its activation.
665 *
666 * Note: the mark is set for activated pages as well
667 * so that recently deactivated but used pages are
668 * quickly recovered.
669 */
670 SetPageReferenced(page);
671
34dbc67a 672 if (referenced_page || referenced_ptes > 1)
64574746
JW
673 return PAGEREF_ACTIVATE;
674
c909e993
KK
675 /*
676 * Activate file-backed executable pages after first usage.
677 */
678 if (vm_flags & VM_EXEC)
679 return PAGEREF_ACTIVATE;
680
64574746
JW
681 return PAGEREF_KEEP;
682 }
dfc8d636
JW
683
684 /* Reclaim if clean, defer dirty pages to writeback */
2e30244a 685 if (referenced_page && !PageSwapBacked(page))
64574746
JW
686 return PAGEREF_RECLAIM_CLEAN;
687
688 return PAGEREF_RECLAIM;
dfc8d636
JW
689}
690
e2be15f6
MG
691/* Check if a page is dirty or under writeback */
692static void page_check_dirty_writeback(struct page *page,
693 bool *dirty, bool *writeback)
694{
b4597226
MG
695 struct address_space *mapping;
696
e2be15f6
MG
697 /*
698 * Anonymous pages are not handled by flushers and must be written
699 * from reclaim context. Do not stall reclaim based on them
700 */
701 if (!page_is_file_cache(page)) {
702 *dirty = false;
703 *writeback = false;
704 return;
705 }
706
707 /* By default assume that the page flags are accurate */
708 *dirty = PageDirty(page);
709 *writeback = PageWriteback(page);
b4597226
MG
710
711 /* Verify dirty/writeback state if the filesystem supports it */
712 if (!page_has_private(page))
713 return;
714
715 mapping = page_mapping(page);
716 if (mapping && mapping->a_ops->is_dirty_writeback)
717 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
e2be15f6
MG
718}
719
1da177e4 720/*
1742f19f 721 * shrink_page_list() returns the number of reclaimed pages
1da177e4 722 */
1742f19f 723static unsigned long shrink_page_list(struct list_head *page_list,
6a18adb3 724 struct zone *zone,
f84f6e2b 725 struct scan_control *sc,
02c6de8d 726 enum ttu_flags ttu_flags,
8e950282 727 unsigned long *ret_nr_dirty,
d43006d5 728 unsigned long *ret_nr_unqueued_dirty,
8e950282 729 unsigned long *ret_nr_congested,
02c6de8d 730 unsigned long *ret_nr_writeback,
b1a6f21e 731 unsigned long *ret_nr_immediate,
02c6de8d 732 bool force_reclaim)
1da177e4
LT
733{
734 LIST_HEAD(ret_pages);
abe4c3b5 735 LIST_HEAD(free_pages);
1da177e4 736 int pgactivate = 0;
d43006d5 737 unsigned long nr_unqueued_dirty = 0;
0e093d99
MG
738 unsigned long nr_dirty = 0;
739 unsigned long nr_congested = 0;
05ff5137 740 unsigned long nr_reclaimed = 0;
92df3a72 741 unsigned long nr_writeback = 0;
b1a6f21e 742 unsigned long nr_immediate = 0;
1da177e4
LT
743
744 cond_resched();
745
69980e31 746 mem_cgroup_uncharge_start();
1da177e4
LT
747 while (!list_empty(page_list)) {
748 struct address_space *mapping;
749 struct page *page;
750 int may_enter_fs;
02c6de8d 751 enum page_references references = PAGEREF_RECLAIM_CLEAN;
e2be15f6 752 bool dirty, writeback;
1da177e4
LT
753
754 cond_resched();
755
756 page = lru_to_page(page_list);
757 list_del(&page->lru);
758
529ae9aa 759 if (!trylock_page(page))
1da177e4
LT
760 goto keep;
761
725d704e 762 VM_BUG_ON(PageActive(page));
6a18adb3 763 VM_BUG_ON(page_zone(page) != zone);
1da177e4
LT
764
765 sc->nr_scanned++;
80e43426 766
39b5f29a 767 if (unlikely(!page_evictable(page)))
b291f000 768 goto cull_mlocked;
894bc310 769
a6dc60f8 770 if (!sc->may_unmap && page_mapped(page))
80e43426
CL
771 goto keep_locked;
772
1da177e4
LT
773 /* Double the slab pressure for mapped and swapcache pages */
774 if (page_mapped(page) || PageSwapCache(page))
775 sc->nr_scanned++;
776
c661b078
AW
777 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
778 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
779
e2be15f6
MG
780 /*
781 * The number of dirty pages determines if a zone is marked
782 * reclaim_congested which affects wait_iff_congested. kswapd
783 * will stall and start writing pages if the tail of the LRU
784 * is all dirty unqueued pages.
785 */
786 page_check_dirty_writeback(page, &dirty, &writeback);
787 if (dirty || writeback)
788 nr_dirty++;
789
790 if (dirty && !writeback)
791 nr_unqueued_dirty++;
792
d04e8acd
MG
793 /*
794 * Treat this page as congested if the underlying BDI is or if
795 * pages are cycling through the LRU so quickly that the
796 * pages marked for immediate reclaim are making it to the
797 * end of the LRU a second time.
798 */
e2be15f6 799 mapping = page_mapping(page);
d04e8acd
MG
800 if ((mapping && bdi_write_congested(mapping->backing_dev_info)) ||
801 (writeback && PageReclaim(page)))
e2be15f6
MG
802 nr_congested++;
803
283aba9f
MG
804 /*
805 * If a page at the tail of the LRU is under writeback, there
806 * are three cases to consider.
807 *
808 * 1) If reclaim is encountering an excessive number of pages
809 * under writeback and this page is both under writeback and
810 * PageReclaim then it indicates that pages are being queued
811 * for IO but are being recycled through the LRU before the
812 * IO can complete. Waiting on the page itself risks an
813 * indefinite stall if it is impossible to writeback the
814 * page due to IO error or disconnected storage so instead
b1a6f21e
MG
815 * note that the LRU is being scanned too quickly and the
816 * caller can stall after page list has been processed.
283aba9f
MG
817 *
818 * 2) Global reclaim encounters a page, memcg encounters a
819 * page that is not marked for immediate reclaim or
820 * the caller does not have __GFP_IO. In this case mark
821 * the page for immediate reclaim and continue scanning.
822 *
823 * __GFP_IO is checked because a loop driver thread might
824 * enter reclaim, and deadlock if it waits on a page for
825 * which it is needed to do the write (loop masks off
826 * __GFP_IO|__GFP_FS for this reason); but more thought
827 * would probably show more reasons.
828 *
829 * Don't require __GFP_FS, since we're not going into the
830 * FS, just waiting on its writeback completion. Worryingly,
831 * ext4 gfs2 and xfs allocate pages with
832 * grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so testing
833 * may_enter_fs here is liable to OOM on them.
834 *
835 * 3) memcg encounters a page that is not already marked
836 * PageReclaim. memcg does not have any dirty pages
837 * throttling so we could easily OOM just because too many
838 * pages are in writeback and there is nothing else to
839 * reclaim. Wait for the writeback to complete.
840 */
c661b078 841 if (PageWriteback(page)) {
283aba9f
MG
842 /* Case 1 above */
843 if (current_is_kswapd() &&
844 PageReclaim(page) &&
845 zone_is_reclaim_writeback(zone)) {
b1a6f21e
MG
846 nr_immediate++;
847 goto keep_locked;
283aba9f
MG
848
849 /* Case 2 above */
850 } else if (global_reclaim(sc) ||
c3b94f44
HD
851 !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
852 /*
853 * This is slightly racy - end_page_writeback()
854 * might have just cleared PageReclaim, then
855 * setting PageReclaim here end up interpreted
856 * as PageReadahead - but that does not matter
857 * enough to care. What we do want is for this
858 * page to have PageReclaim set next time memcg
859 * reclaim reaches the tests above, so it will
860 * then wait_on_page_writeback() to avoid OOM;
861 * and it's also appropriate in global reclaim.
862 */
863 SetPageReclaim(page);
e62e384e 864 nr_writeback++;
283aba9f 865
c3b94f44 866 goto keep_locked;
283aba9f
MG
867
868 /* Case 3 above */
869 } else {
870 wait_on_page_writeback(page);
e62e384e 871 }
c661b078 872 }
1da177e4 873
02c6de8d
MK
874 if (!force_reclaim)
875 references = page_check_references(page, sc);
876
dfc8d636
JW
877 switch (references) {
878 case PAGEREF_ACTIVATE:
1da177e4 879 goto activate_locked;
64574746
JW
880 case PAGEREF_KEEP:
881 goto keep_locked;
dfc8d636
JW
882 case PAGEREF_RECLAIM:
883 case PAGEREF_RECLAIM_CLEAN:
884 ; /* try to reclaim the page below */
885 }
1da177e4 886
1da177e4
LT
887 /*
888 * Anonymous process memory has backing store?
889 * Try to allocate it some swap space here.
890 */
b291f000 891 if (PageAnon(page) && !PageSwapCache(page)) {
63eb6b93
HD
892 if (!(sc->gfp_mask & __GFP_IO))
893 goto keep_locked;
5bc7b8ac 894 if (!add_to_swap(page, page_list))
1da177e4 895 goto activate_locked;
63eb6b93 896 may_enter_fs = 1;
1da177e4 897
e2be15f6
MG
898 /* Adding to swap updated mapping */
899 mapping = page_mapping(page);
900 }
1da177e4
LT
901
902 /*
903 * The page is mapped into the page tables of one or more
904 * processes. Try to unmap it here.
905 */
906 if (page_mapped(page) && mapping) {
02c6de8d 907 switch (try_to_unmap(page, ttu_flags)) {
1da177e4
LT
908 case SWAP_FAIL:
909 goto activate_locked;
910 case SWAP_AGAIN:
911 goto keep_locked;
b291f000
NP
912 case SWAP_MLOCK:
913 goto cull_mlocked;
1da177e4
LT
914 case SWAP_SUCCESS:
915 ; /* try to free the page below */
916 }
917 }
918
919 if (PageDirty(page)) {
ee72886d
MG
920 /*
921 * Only kswapd can writeback filesystem pages to
d43006d5
MG
922 * avoid risk of stack overflow but only writeback
923 * if many dirty pages have been encountered.
ee72886d 924 */
f84f6e2b 925 if (page_is_file_cache(page) &&
9e3b2f8c 926 (!current_is_kswapd() ||
d43006d5 927 !zone_is_reclaim_dirty(zone))) {
49ea7eb6
MG
928 /*
929 * Immediately reclaim when written back.
930 * Similar in principal to deactivate_page()
931 * except we already have the page isolated
932 * and know it's dirty
933 */
934 inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
935 SetPageReclaim(page);
936
ee72886d
MG
937 goto keep_locked;
938 }
939
dfc8d636 940 if (references == PAGEREF_RECLAIM_CLEAN)
1da177e4 941 goto keep_locked;
4dd4b920 942 if (!may_enter_fs)
1da177e4 943 goto keep_locked;
52a8363e 944 if (!sc->may_writepage)
1da177e4
LT
945 goto keep_locked;
946
947 /* Page is dirty, try to write it out here */
7d3579e8 948 switch (pageout(page, mapping, sc)) {
1da177e4
LT
949 case PAGE_KEEP:
950 goto keep_locked;
951 case PAGE_ACTIVATE:
952 goto activate_locked;
953 case PAGE_SUCCESS:
7d3579e8 954 if (PageWriteback(page))
41ac1999 955 goto keep;
7d3579e8 956 if (PageDirty(page))
1da177e4 957 goto keep;
7d3579e8 958
1da177e4
LT
959 /*
960 * A synchronous write - probably a ramdisk. Go
961 * ahead and try to reclaim the page.
962 */
529ae9aa 963 if (!trylock_page(page))
1da177e4
LT
964 goto keep;
965 if (PageDirty(page) || PageWriteback(page))
966 goto keep_locked;
967 mapping = page_mapping(page);
968 case PAGE_CLEAN:
969 ; /* try to free the page below */
970 }
971 }
972
973 /*
974 * If the page has buffers, try to free the buffer mappings
975 * associated with this page. If we succeed we try to free
976 * the page as well.
977 *
978 * We do this even if the page is PageDirty().
979 * try_to_release_page() does not perform I/O, but it is
980 * possible for a page to have PageDirty set, but it is actually
981 * clean (all its buffers are clean). This happens if the
982 * buffers were written out directly, with submit_bh(). ext3
894bc310 983 * will do this, as well as the blockdev mapping.
1da177e4
LT
984 * try_to_release_page() will discover that cleanness and will
985 * drop the buffers and mark the page clean - it can be freed.
986 *
987 * Rarely, pages can have buffers and no ->mapping. These are
988 * the pages which were not successfully invalidated in
989 * truncate_complete_page(). We try to drop those buffers here
990 * and if that worked, and the page is no longer mapped into
991 * process address space (page_count == 1) it can be freed.
992 * Otherwise, leave the page on the LRU so it is swappable.
993 */
266cf658 994 if (page_has_private(page)) {
1da177e4
LT
995 if (!try_to_release_page(page, sc->gfp_mask))
996 goto activate_locked;
e286781d
NP
997 if (!mapping && page_count(page) == 1) {
998 unlock_page(page);
999 if (put_page_testzero(page))
1000 goto free_it;
1001 else {
1002 /*
1003 * rare race with speculative reference.
1004 * the speculative reference will free
1005 * this page shortly, so we may
1006 * increment nr_reclaimed here (and
1007 * leave it off the LRU).
1008 */
1009 nr_reclaimed++;
1010 continue;
1011 }
1012 }
1da177e4
LT
1013 }
1014
e286781d 1015 if (!mapping || !__remove_mapping(mapping, page))
49d2e9cc 1016 goto keep_locked;
1da177e4 1017
a978d6f5
NP
1018 /*
1019 * At this point, we have no other references and there is
1020 * no way to pick any more up (removed from LRU, removed
1021 * from pagecache). Can use non-atomic bitops now (and
1022 * we obviously don't have to worry about waking up a process
1023 * waiting on the page lock, because there are no references.
1024 */
1025 __clear_page_locked(page);
e286781d 1026free_it:
05ff5137 1027 nr_reclaimed++;
abe4c3b5
MG
1028
1029 /*
1030 * Is there need to periodically free_page_list? It would
1031 * appear not as the counts should be low
1032 */
1033 list_add(&page->lru, &free_pages);
1da177e4
LT
1034 continue;
1035
b291f000 1036cull_mlocked:
63d6c5ad
HD
1037 if (PageSwapCache(page))
1038 try_to_free_swap(page);
b291f000
NP
1039 unlock_page(page);
1040 putback_lru_page(page);
1041 continue;
1042
1da177e4 1043activate_locked:
68a22394
RR
1044 /* Not a candidate for swapping, so reclaim swap space. */
1045 if (PageSwapCache(page) && vm_swap_full())
a2c43eed 1046 try_to_free_swap(page);
894bc310 1047 VM_BUG_ON(PageActive(page));
1da177e4
LT
1048 SetPageActive(page);
1049 pgactivate++;
1050keep_locked:
1051 unlock_page(page);
1052keep:
1053 list_add(&page->lru, &ret_pages);
b291f000 1054 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
1da177e4 1055 }
abe4c3b5 1056
cc59850e 1057 free_hot_cold_page_list(&free_pages, 1);
abe4c3b5 1058
1da177e4 1059 list_splice(&ret_pages, page_list);
f8891e5e 1060 count_vm_events(PGACTIVATE, pgactivate);
69980e31 1061 mem_cgroup_uncharge_end();
8e950282
MG
1062 *ret_nr_dirty += nr_dirty;
1063 *ret_nr_congested += nr_congested;
d43006d5 1064 *ret_nr_unqueued_dirty += nr_unqueued_dirty;
92df3a72 1065 *ret_nr_writeback += nr_writeback;
b1a6f21e 1066 *ret_nr_immediate += nr_immediate;
05ff5137 1067 return nr_reclaimed;
1da177e4
LT
1068}
1069
02c6de8d
MK
1070unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1071 struct list_head *page_list)
1072{
1073 struct scan_control sc = {
1074 .gfp_mask = GFP_KERNEL,
1075 .priority = DEF_PRIORITY,
1076 .may_unmap = 1,
1077 };
8e950282 1078 unsigned long ret, dummy1, dummy2, dummy3, dummy4, dummy5;
02c6de8d
MK
1079 struct page *page, *next;
1080 LIST_HEAD(clean_pages);
1081
1082 list_for_each_entry_safe(page, next, page_list, lru) {
1083 if (page_is_file_cache(page) && !PageDirty(page)) {
1084 ClearPageActive(page);
1085 list_move(&page->lru, &clean_pages);
1086 }
1087 }
1088
1089 ret = shrink_page_list(&clean_pages, zone, &sc,
8e950282
MG
1090 TTU_UNMAP|TTU_IGNORE_ACCESS,
1091 &dummy1, &dummy2, &dummy3, &dummy4, &dummy5, true);
02c6de8d
MK
1092 list_splice(&clean_pages, page_list);
1093 __mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
1094 return ret;
1095}
1096
5ad333eb
AW
1097/*
1098 * Attempt to remove the specified page from its LRU. Only take this page
1099 * if it is of the appropriate PageActive status. Pages which are being
1100 * freed elsewhere are also ignored.
1101 *
1102 * page: page to consider
1103 * mode: one of the LRU isolation modes defined above
1104 *
1105 * returns 0 on success, -ve errno on failure.
1106 */
f3fd4a61 1107int __isolate_lru_page(struct page *page, isolate_mode_t mode)
5ad333eb
AW
1108{
1109 int ret = -EINVAL;
1110
1111 /* Only take pages on the LRU. */
1112 if (!PageLRU(page))
1113 return ret;
1114
e46a2879
MK
1115 /* Compaction should not handle unevictable pages but CMA can do so */
1116 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
894bc310
LS
1117 return ret;
1118
5ad333eb 1119 ret = -EBUSY;
08e552c6 1120
c8244935
MG
1121 /*
1122 * To minimise LRU disruption, the caller can indicate that it only
1123 * wants to isolate pages it will be able to operate on without
1124 * blocking - clean pages for the most part.
1125 *
1126 * ISOLATE_CLEAN means that only clean pages should be isolated. This
1127 * is used by reclaim when it is cannot write to backing storage
1128 *
1129 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1130 * that it is possible to migrate without blocking
1131 */
1132 if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1133 /* All the caller can do on PageWriteback is block */
1134 if (PageWriteback(page))
1135 return ret;
1136
1137 if (PageDirty(page)) {
1138 struct address_space *mapping;
1139
1140 /* ISOLATE_CLEAN means only clean pages */
1141 if (mode & ISOLATE_CLEAN)
1142 return ret;
1143
1144 /*
1145 * Only pages without mappings or that have a
1146 * ->migratepage callback are possible to migrate
1147 * without blocking
1148 */
1149 mapping = page_mapping(page);
1150 if (mapping && !mapping->a_ops->migratepage)
1151 return ret;
1152 }
1153 }
39deaf85 1154
f80c0673
MK
1155 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1156 return ret;
1157
5ad333eb
AW
1158 if (likely(get_page_unless_zero(page))) {
1159 /*
1160 * Be careful not to clear PageLRU until after we're
1161 * sure the page is not being freed elsewhere -- the
1162 * page release code relies on it.
1163 */
1164 ClearPageLRU(page);
1165 ret = 0;
1166 }
1167
1168 return ret;
1169}
1170
1da177e4
LT
1171/*
1172 * zone->lru_lock is heavily contended. Some of the functions that
1173 * shrink the lists perform better by taking out a batch of pages
1174 * and working on them outside the LRU lock.
1175 *
1176 * For pagecache intensive workloads, this function is the hottest
1177 * spot in the kernel (apart from copy_*_user functions).
1178 *
1179 * Appropriate locks must be held before calling this function.
1180 *
1181 * @nr_to_scan: The number of pages to look through on the list.
5dc35979 1182 * @lruvec: The LRU vector to pull pages from.
1da177e4 1183 * @dst: The temp list to put pages on to.
f626012d 1184 * @nr_scanned: The number of pages that were scanned.
fe2c2a10 1185 * @sc: The scan_control struct for this reclaim session
5ad333eb 1186 * @mode: One of the LRU isolation modes
3cb99451 1187 * @lru: LRU list id for isolating
1da177e4
LT
1188 *
1189 * returns how many pages were moved onto *@dst.
1190 */
69e05944 1191static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
5dc35979 1192 struct lruvec *lruvec, struct list_head *dst,
fe2c2a10 1193 unsigned long *nr_scanned, struct scan_control *sc,
3cb99451 1194 isolate_mode_t mode, enum lru_list lru)
1da177e4 1195{
75b00af7 1196 struct list_head *src = &lruvec->lists[lru];
69e05944 1197 unsigned long nr_taken = 0;
c9b02d97 1198 unsigned long scan;
1da177e4 1199
c9b02d97 1200 for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
5ad333eb 1201 struct page *page;
fa9add64 1202 int nr_pages;
5ad333eb 1203
1da177e4
LT
1204 page = lru_to_page(src);
1205 prefetchw_prev_lru_page(page, src, flags);
1206
725d704e 1207 VM_BUG_ON(!PageLRU(page));
8d438f96 1208
f3fd4a61 1209 switch (__isolate_lru_page(page, mode)) {
5ad333eb 1210 case 0:
fa9add64
HD
1211 nr_pages = hpage_nr_pages(page);
1212 mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
5ad333eb 1213 list_move(&page->lru, dst);
fa9add64 1214 nr_taken += nr_pages;
5ad333eb
AW
1215 break;
1216
1217 case -EBUSY:
1218 /* else it is being freed elsewhere */
1219 list_move(&page->lru, src);
1220 continue;
46453a6e 1221
5ad333eb
AW
1222 default:
1223 BUG();
1224 }
1da177e4
LT
1225 }
1226
f626012d 1227 *nr_scanned = scan;
75b00af7
HD
1228 trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
1229 nr_taken, mode, is_file_lru(lru));
1da177e4
LT
1230 return nr_taken;
1231}
1232
62695a84
NP
1233/**
1234 * isolate_lru_page - tries to isolate a page from its LRU list
1235 * @page: page to isolate from its LRU list
1236 *
1237 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1238 * vmstat statistic corresponding to whatever LRU list the page was on.
1239 *
1240 * Returns 0 if the page was removed from an LRU list.
1241 * Returns -EBUSY if the page was not on an LRU list.
1242 *
1243 * The returned page will have PageLRU() cleared. If it was found on
894bc310
LS
1244 * the active list, it will have PageActive set. If it was found on
1245 * the unevictable list, it will have the PageUnevictable bit set. That flag
1246 * may need to be cleared by the caller before letting the page go.
62695a84
NP
1247 *
1248 * The vmstat statistic corresponding to the list on which the page was
1249 * found will be decremented.
1250 *
1251 * Restrictions:
1252 * (1) Must be called with an elevated refcount on the page. This is a
1253 * fundamentnal difference from isolate_lru_pages (which is called
1254 * without a stable reference).
1255 * (2) the lru_lock must not be held.
1256 * (3) interrupts must be enabled.
1257 */
1258int isolate_lru_page(struct page *page)
1259{
1260 int ret = -EBUSY;
1261
0c917313
KK
1262 VM_BUG_ON(!page_count(page));
1263
62695a84
NP
1264 if (PageLRU(page)) {
1265 struct zone *zone = page_zone(page);
fa9add64 1266 struct lruvec *lruvec;
62695a84
NP
1267
1268 spin_lock_irq(&zone->lru_lock);
fa9add64 1269 lruvec = mem_cgroup_page_lruvec(page, zone);
0c917313 1270 if (PageLRU(page)) {
894bc310 1271 int lru = page_lru(page);
0c917313 1272 get_page(page);
62695a84 1273 ClearPageLRU(page);
fa9add64
HD
1274 del_page_from_lru_list(page, lruvec, lru);
1275 ret = 0;
62695a84
NP
1276 }
1277 spin_unlock_irq(&zone->lru_lock);
1278 }
1279 return ret;
1280}
1281
35cd7815 1282/*
d37dd5dc
FW
1283 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1284 * then get resheduled. When there are massive number of tasks doing page
1285 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1286 * the LRU list will go small and be scanned faster than necessary, leading to
1287 * unnecessary swapping, thrashing and OOM.
35cd7815
RR
1288 */
1289static int too_many_isolated(struct zone *zone, int file,
1290 struct scan_control *sc)
1291{
1292 unsigned long inactive, isolated;
1293
1294 if (current_is_kswapd())
1295 return 0;
1296
89b5fae5 1297 if (!global_reclaim(sc))
35cd7815
RR
1298 return 0;
1299
1300 if (file) {
1301 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1302 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1303 } else {
1304 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1305 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1306 }
1307
3cf23841
FW
1308 /*
1309 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1310 * won't get blocked by normal direct-reclaimers, forming a circular
1311 * deadlock.
1312 */
1313 if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
1314 inactive >>= 3;
1315
35cd7815
RR
1316 return isolated > inactive;
1317}
1318
66635629 1319static noinline_for_stack void
75b00af7 1320putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
66635629 1321{
27ac81d8
KK
1322 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1323 struct zone *zone = lruvec_zone(lruvec);
3f79768f 1324 LIST_HEAD(pages_to_free);
66635629 1325
66635629
MG
1326 /*
1327 * Put back any unfreeable pages.
1328 */
66635629 1329 while (!list_empty(page_list)) {
3f79768f 1330 struct page *page = lru_to_page(page_list);
66635629 1331 int lru;
3f79768f 1332
66635629
MG
1333 VM_BUG_ON(PageLRU(page));
1334 list_del(&page->lru);
39b5f29a 1335 if (unlikely(!page_evictable(page))) {
66635629
MG
1336 spin_unlock_irq(&zone->lru_lock);
1337 putback_lru_page(page);
1338 spin_lock_irq(&zone->lru_lock);
1339 continue;
1340 }
fa9add64
HD
1341
1342 lruvec = mem_cgroup_page_lruvec(page, zone);
1343
7a608572 1344 SetPageLRU(page);
66635629 1345 lru = page_lru(page);
fa9add64
HD
1346 add_page_to_lru_list(page, lruvec, lru);
1347
66635629
MG
1348 if (is_active_lru(lru)) {
1349 int file = is_file_lru(lru);
9992af10
RR
1350 int numpages = hpage_nr_pages(page);
1351 reclaim_stat->recent_rotated[file] += numpages;
66635629 1352 }
2bcf8879
HD
1353 if (put_page_testzero(page)) {
1354 __ClearPageLRU(page);
1355 __ClearPageActive(page);
fa9add64 1356 del_page_from_lru_list(page, lruvec, lru);
2bcf8879
HD
1357
1358 if (unlikely(PageCompound(page))) {
1359 spin_unlock_irq(&zone->lru_lock);
1360 (*get_compound_page_dtor(page))(page);
1361 spin_lock_irq(&zone->lru_lock);
1362 } else
1363 list_add(&page->lru, &pages_to_free);
66635629
MG
1364 }
1365 }
66635629 1366
3f79768f
HD
1367 /*
1368 * To save our caller's stack, now use input list for pages to free.
1369 */
1370 list_splice(&pages_to_free, page_list);
66635629
MG
1371}
1372
1da177e4 1373/*
1742f19f
AM
1374 * shrink_inactive_list() is a helper for shrink_zone(). It returns the number
1375 * of reclaimed pages
1da177e4 1376 */
66635629 1377static noinline_for_stack unsigned long
1a93be0e 1378shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
9e3b2f8c 1379 struct scan_control *sc, enum lru_list lru)
1da177e4
LT
1380{
1381 LIST_HEAD(page_list);
e247dbce 1382 unsigned long nr_scanned;
05ff5137 1383 unsigned long nr_reclaimed = 0;
e247dbce 1384 unsigned long nr_taken;
8e950282
MG
1385 unsigned long nr_dirty = 0;
1386 unsigned long nr_congested = 0;
e2be15f6 1387 unsigned long nr_unqueued_dirty = 0;
92df3a72 1388 unsigned long nr_writeback = 0;
b1a6f21e 1389 unsigned long nr_immediate = 0;
f3fd4a61 1390 isolate_mode_t isolate_mode = 0;
3cb99451 1391 int file = is_file_lru(lru);
1a93be0e
KK
1392 struct zone *zone = lruvec_zone(lruvec);
1393 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
78dc583d 1394
35cd7815 1395 while (unlikely(too_many_isolated(zone, file, sc))) {
58355c78 1396 congestion_wait(BLK_RW_ASYNC, HZ/10);
35cd7815
RR
1397
1398 /* We are about to die and free our memory. Return now. */
1399 if (fatal_signal_pending(current))
1400 return SWAP_CLUSTER_MAX;
1401 }
1402
1da177e4 1403 lru_add_drain();
f80c0673
MK
1404
1405 if (!sc->may_unmap)
61317289 1406 isolate_mode |= ISOLATE_UNMAPPED;
f80c0673 1407 if (!sc->may_writepage)
61317289 1408 isolate_mode |= ISOLATE_CLEAN;
f80c0673 1409
1da177e4 1410 spin_lock_irq(&zone->lru_lock);
b35ea17b 1411
5dc35979
KK
1412 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1413 &nr_scanned, sc, isolate_mode, lru);
95d918fc
KK
1414
1415 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1416 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1417
89b5fae5 1418 if (global_reclaim(sc)) {
e247dbce
KM
1419 zone->pages_scanned += nr_scanned;
1420 if (current_is_kswapd())
75b00af7 1421 __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
e247dbce 1422 else
75b00af7 1423 __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
e247dbce 1424 }
d563c050 1425 spin_unlock_irq(&zone->lru_lock);
b35ea17b 1426
d563c050 1427 if (nr_taken == 0)
66635629 1428 return 0;
5ad333eb 1429
02c6de8d 1430 nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
8e950282
MG
1431 &nr_dirty, &nr_unqueued_dirty, &nr_congested,
1432 &nr_writeback, &nr_immediate,
1433 false);
c661b078 1434
3f79768f
HD
1435 spin_lock_irq(&zone->lru_lock);
1436
95d918fc 1437 reclaim_stat->recent_scanned[file] += nr_taken;
d563c050 1438
904249aa
YH
1439 if (global_reclaim(sc)) {
1440 if (current_is_kswapd())
1441 __count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1442 nr_reclaimed);
1443 else
1444 __count_zone_vm_events(PGSTEAL_DIRECT, zone,
1445 nr_reclaimed);
1446 }
a74609fa 1447
27ac81d8 1448 putback_inactive_pages(lruvec, &page_list);
3f79768f 1449
95d918fc 1450 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
3f79768f
HD
1451
1452 spin_unlock_irq(&zone->lru_lock);
1453
1454 free_hot_cold_page_list(&page_list, 1);
e11da5b4 1455
92df3a72
MG
1456 /*
1457 * If reclaim is isolating dirty pages under writeback, it implies
1458 * that the long-lived page allocation rate is exceeding the page
1459 * laundering rate. Either the global limits are not being effective
1460 * at throttling processes due to the page distribution throughout
1461 * zones or there is heavy usage of a slow backing device. The
1462 * only option is to throttle from reclaim context which is not ideal
1463 * as there is no guarantee the dirtying process is throttled in the
1464 * same way balance_dirty_pages() manages.
1465 *
8e950282
MG
1466 * Once a zone is flagged ZONE_WRITEBACK, kswapd will count the number
1467 * of pages under pages flagged for immediate reclaim and stall if any
1468 * are encountered in the nr_immediate check below.
92df3a72 1469 */
918fc718 1470 if (nr_writeback && nr_writeback == nr_taken)
283aba9f 1471 zone_set_flag(zone, ZONE_WRITEBACK);
92df3a72 1472
d43006d5 1473 /*
b1a6f21e
MG
1474 * memcg will stall in page writeback so only consider forcibly
1475 * stalling for global reclaim
d43006d5 1476 */
b1a6f21e 1477 if (global_reclaim(sc)) {
8e950282
MG
1478 /*
1479 * Tag a zone as congested if all the dirty pages scanned were
1480 * backed by a congested BDI and wait_iff_congested will stall.
1481 */
1482 if (nr_dirty && nr_dirty == nr_congested)
1483 zone_set_flag(zone, ZONE_CONGESTED);
1484
b1a6f21e
MG
1485 /*
1486 * If dirty pages are scanned that are not queued for IO, it
1487 * implies that flushers are not keeping up. In this case, flag
1488 * the zone ZONE_TAIL_LRU_DIRTY and kswapd will start writing
1489 * pages from reclaim context. It will forcibly stall in the
1490 * next check.
1491 */
1492 if (nr_unqueued_dirty == nr_taken)
1493 zone_set_flag(zone, ZONE_TAIL_LRU_DIRTY);
1494
1495 /*
1496 * In addition, if kswapd scans pages marked marked for
1497 * immediate reclaim and under writeback (nr_immediate), it
1498 * implies that pages are cycling through the LRU faster than
1499 * they are written so also forcibly stall.
1500 */
1501 if (nr_unqueued_dirty == nr_taken || nr_immediate)
1502 congestion_wait(BLK_RW_ASYNC, HZ/10);
e2be15f6 1503 }
d43006d5 1504
8e950282
MG
1505 /*
1506 * Stall direct reclaim for IO completions if underlying BDIs or zone
1507 * is congested. Allow kswapd to continue until it starts encountering
1508 * unqueued dirty pages or cycling through the LRU too quickly.
1509 */
1510 if (!sc->hibernation_mode && !current_is_kswapd())
1511 wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1512
e11da5b4
MG
1513 trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1514 zone_idx(zone),
1515 nr_scanned, nr_reclaimed,
9e3b2f8c 1516 sc->priority,
23b9da55 1517 trace_shrink_flags(file));
05ff5137 1518 return nr_reclaimed;
1da177e4
LT
1519}
1520
1521/*
1522 * This moves pages from the active list to the inactive list.
1523 *
1524 * We move them the other way if the page is referenced by one or more
1525 * processes, from rmap.
1526 *
1527 * If the pages are mostly unmapped, the processing is fast and it is
1528 * appropriate to hold zone->lru_lock across the whole operation. But if
1529 * the pages are mapped, the processing is slow (page_referenced()) so we
1530 * should drop zone->lru_lock around each page. It's impossible to balance
1531 * this, so instead we remove the pages from the LRU while processing them.
1532 * It is safe to rely on PG_active against the non-LRU pages in here because
1533 * nobody will play with that bit on a non-LRU page.
1534 *
1535 * The downside is that we have to touch page->_count against each page.
1536 * But we had to alter page->flags anyway.
1537 */
1cfb419b 1538
fa9add64 1539static void move_active_pages_to_lru(struct lruvec *lruvec,
3eb4140f 1540 struct list_head *list,
2bcf8879 1541 struct list_head *pages_to_free,
3eb4140f
WF
1542 enum lru_list lru)
1543{
fa9add64 1544 struct zone *zone = lruvec_zone(lruvec);
3eb4140f 1545 unsigned long pgmoved = 0;
3eb4140f 1546 struct page *page;
fa9add64 1547 int nr_pages;
3eb4140f 1548
3eb4140f
WF
1549 while (!list_empty(list)) {
1550 page = lru_to_page(list);
fa9add64 1551 lruvec = mem_cgroup_page_lruvec(page, zone);
3eb4140f
WF
1552
1553 VM_BUG_ON(PageLRU(page));
1554 SetPageLRU(page);
1555
fa9add64
HD
1556 nr_pages = hpage_nr_pages(page);
1557 mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
925b7673 1558 list_move(&page->lru, &lruvec->lists[lru]);
fa9add64 1559 pgmoved += nr_pages;
3eb4140f 1560
2bcf8879
HD
1561 if (put_page_testzero(page)) {
1562 __ClearPageLRU(page);
1563 __ClearPageActive(page);
fa9add64 1564 del_page_from_lru_list(page, lruvec, lru);
2bcf8879
HD
1565
1566 if (unlikely(PageCompound(page))) {
1567 spin_unlock_irq(&zone->lru_lock);
1568 (*get_compound_page_dtor(page))(page);
1569 spin_lock_irq(&zone->lru_lock);
1570 } else
1571 list_add(&page->lru, pages_to_free);
3eb4140f
WF
1572 }
1573 }
1574 __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1575 if (!is_active_lru(lru))
1576 __count_vm_events(PGDEACTIVATE, pgmoved);
1577}
1cfb419b 1578
f626012d 1579static void shrink_active_list(unsigned long nr_to_scan,
1a93be0e 1580 struct lruvec *lruvec,
f16015fb 1581 struct scan_control *sc,
9e3b2f8c 1582 enum lru_list lru)
1da177e4 1583{
44c241f1 1584 unsigned long nr_taken;
f626012d 1585 unsigned long nr_scanned;
6fe6b7e3 1586 unsigned long vm_flags;
1da177e4 1587 LIST_HEAD(l_hold); /* The pages which were snipped off */
8cab4754 1588 LIST_HEAD(l_active);
b69408e8 1589 LIST_HEAD(l_inactive);
1da177e4 1590 struct page *page;
1a93be0e 1591 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
44c241f1 1592 unsigned long nr_rotated = 0;
f3fd4a61 1593 isolate_mode_t isolate_mode = 0;
3cb99451 1594 int file = is_file_lru(lru);
1a93be0e 1595 struct zone *zone = lruvec_zone(lruvec);
1da177e4
LT
1596
1597 lru_add_drain();
f80c0673
MK
1598
1599 if (!sc->may_unmap)
61317289 1600 isolate_mode |= ISOLATE_UNMAPPED;
f80c0673 1601 if (!sc->may_writepage)
61317289 1602 isolate_mode |= ISOLATE_CLEAN;
f80c0673 1603
1da177e4 1604 spin_lock_irq(&zone->lru_lock);
925b7673 1605
5dc35979
KK
1606 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
1607 &nr_scanned, sc, isolate_mode, lru);
89b5fae5 1608 if (global_reclaim(sc))
f626012d 1609 zone->pages_scanned += nr_scanned;
89b5fae5 1610
b7c46d15 1611 reclaim_stat->recent_scanned[file] += nr_taken;
1cfb419b 1612
f626012d 1613 __count_zone_vm_events(PGREFILL, zone, nr_scanned);
3cb99451 1614 __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
a731286d 1615 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1da177e4
LT
1616 spin_unlock_irq(&zone->lru_lock);
1617
1da177e4
LT
1618 while (!list_empty(&l_hold)) {
1619 cond_resched();
1620 page = lru_to_page(&l_hold);
1621 list_del(&page->lru);
7e9cd484 1622
39b5f29a 1623 if (unlikely(!page_evictable(page))) {
894bc310
LS
1624 putback_lru_page(page);
1625 continue;
1626 }
1627
cc715d99
MG
1628 if (unlikely(buffer_heads_over_limit)) {
1629 if (page_has_private(page) && trylock_page(page)) {
1630 if (page_has_private(page))
1631 try_to_release_page(page, 0);
1632 unlock_page(page);
1633 }
1634 }
1635
c3ac9a8a
JW
1636 if (page_referenced(page, 0, sc->target_mem_cgroup,
1637 &vm_flags)) {
9992af10 1638 nr_rotated += hpage_nr_pages(page);
8cab4754
WF
1639 /*
1640 * Identify referenced, file-backed active pages and
1641 * give them one more trip around the active list. So
1642 * that executable code get better chances to stay in
1643 * memory under moderate memory pressure. Anon pages
1644 * are not likely to be evicted by use-once streaming
1645 * IO, plus JVM can create lots of anon VM_EXEC pages,
1646 * so we ignore them here.
1647 */
41e20983 1648 if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
8cab4754
WF
1649 list_add(&page->lru, &l_active);
1650 continue;
1651 }
1652 }
7e9cd484 1653
5205e56e 1654 ClearPageActive(page); /* we are de-activating */
1da177e4
LT
1655 list_add(&page->lru, &l_inactive);
1656 }
1657
b555749a 1658 /*
8cab4754 1659 * Move pages back to the lru list.
b555749a 1660 */
2a1dc509 1661 spin_lock_irq(&zone->lru_lock);
556adecb 1662 /*
8cab4754
WF
1663 * Count referenced pages from currently used mappings as rotated,
1664 * even though only some of them are actually re-activated. This
1665 * helps balance scan pressure between file and anonymous pages in
1666 * get_scan_ratio.
7e9cd484 1667 */
b7c46d15 1668 reclaim_stat->recent_rotated[file] += nr_rotated;
556adecb 1669
fa9add64
HD
1670 move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1671 move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
a731286d 1672 __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
f8891e5e 1673 spin_unlock_irq(&zone->lru_lock);
2bcf8879
HD
1674
1675 free_hot_cold_page_list(&l_hold, 1);
1da177e4
LT
1676}
1677
74e3f3c3 1678#ifdef CONFIG_SWAP
14797e23 1679static int inactive_anon_is_low_global(struct zone *zone)
f89eb90e
KM
1680{
1681 unsigned long active, inactive;
1682
1683 active = zone_page_state(zone, NR_ACTIVE_ANON);
1684 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1685
1686 if (inactive * zone->inactive_ratio < active)
1687 return 1;
1688
1689 return 0;
1690}
1691
14797e23
KM
1692/**
1693 * inactive_anon_is_low - check if anonymous pages need to be deactivated
c56d5c7d 1694 * @lruvec: LRU vector to check
14797e23
KM
1695 *
1696 * Returns true if the zone does not have enough inactive anon pages,
1697 * meaning some active anon pages need to be deactivated.
1698 */
c56d5c7d 1699static int inactive_anon_is_low(struct lruvec *lruvec)
14797e23 1700{
74e3f3c3
MK
1701 /*
1702 * If we don't have swap space, anonymous page deactivation
1703 * is pointless.
1704 */
1705 if (!total_swap_pages)
1706 return 0;
1707
c3c787e8 1708 if (!mem_cgroup_disabled())
c56d5c7d 1709 return mem_cgroup_inactive_anon_is_low(lruvec);
f16015fb 1710
c56d5c7d 1711 return inactive_anon_is_low_global(lruvec_zone(lruvec));
14797e23 1712}
74e3f3c3 1713#else
c56d5c7d 1714static inline int inactive_anon_is_low(struct lruvec *lruvec)
74e3f3c3
MK
1715{
1716 return 0;
1717}
1718#endif
14797e23 1719
56e49d21
RR
1720/**
1721 * inactive_file_is_low - check if file pages need to be deactivated
c56d5c7d 1722 * @lruvec: LRU vector to check
56e49d21
RR
1723 *
1724 * When the system is doing streaming IO, memory pressure here
1725 * ensures that active file pages get deactivated, until more
1726 * than half of the file pages are on the inactive list.
1727 *
1728 * Once we get to that situation, protect the system's working
1729 * set from being evicted by disabling active file page aging.
1730 *
1731 * This uses a different ratio than the anonymous pages, because
1732 * the page cache uses a use-once replacement algorithm.
1733 */
c56d5c7d 1734static int inactive_file_is_low(struct lruvec *lruvec)
56e49d21 1735{
e3790144
JW
1736 unsigned long inactive;
1737 unsigned long active;
1738
1739 inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1740 active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
56e49d21 1741
e3790144 1742 return active > inactive;
56e49d21
RR
1743}
1744
75b00af7 1745static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
b39415b2 1746{
75b00af7 1747 if (is_file_lru(lru))
c56d5c7d 1748 return inactive_file_is_low(lruvec);
b39415b2 1749 else
c56d5c7d 1750 return inactive_anon_is_low(lruvec);
b39415b2
RR
1751}
1752
4f98a2fe 1753static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1a93be0e 1754 struct lruvec *lruvec, struct scan_control *sc)
b69408e8 1755{
b39415b2 1756 if (is_active_lru(lru)) {
75b00af7 1757 if (inactive_list_is_low(lruvec, lru))
1a93be0e 1758 shrink_active_list(nr_to_scan, lruvec, sc, lru);
556adecb
RR
1759 return 0;
1760 }
1761
1a93be0e 1762 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
4f98a2fe
RR
1763}
1764
3d58ab5c 1765static int vmscan_swappiness(struct scan_control *sc)
1f4c025b 1766{
89b5fae5 1767 if (global_reclaim(sc))
1f4c025b 1768 return vm_swappiness;
3d58ab5c 1769 return mem_cgroup_swappiness(sc->target_mem_cgroup);
1f4c025b
KH
1770}
1771
9a265114
JW
1772enum scan_balance {
1773 SCAN_EQUAL,
1774 SCAN_FRACT,
1775 SCAN_ANON,
1776 SCAN_FILE,
1777};
1778
4f98a2fe
RR
1779/*
1780 * Determine how aggressively the anon and file LRU lists should be
1781 * scanned. The relative value of each set of LRU lists is determined
1782 * by looking at the fraction of the pages scanned we did rotate back
1783 * onto the active list instead of evict.
1784 *
be7bd59d
WL
1785 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1786 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
4f98a2fe 1787 */
90126375 1788static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
9e3b2f8c 1789 unsigned long *nr)
4f98a2fe 1790{
9a265114
JW
1791 struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1792 u64 fraction[2];
1793 u64 denominator = 0; /* gcc */
1794 struct zone *zone = lruvec_zone(lruvec);
4f98a2fe 1795 unsigned long anon_prio, file_prio;
9a265114
JW
1796 enum scan_balance scan_balance;
1797 unsigned long anon, file, free;
1798 bool force_scan = false;
4f98a2fe 1799 unsigned long ap, fp;
4111304d 1800 enum lru_list lru;
246e87a9 1801
f11c0ca5
JW
1802 /*
1803 * If the zone or memcg is small, nr[l] can be 0. This
1804 * results in no scanning on this priority and a potential
1805 * priority drop. Global direct reclaim can go to the next
1806 * zone and tends to have no problems. Global kswapd is for
1807 * zone balancing and it needs to scan a minimum amount. When
1808 * reclaiming for a memcg, a priority drop can cause high
1809 * latencies, so it's better to scan a minimum amount there as
1810 * well.
1811 */
90126375 1812 if (current_is_kswapd() && zone->all_unreclaimable)
a4d3e9e7 1813 force_scan = true;
89b5fae5 1814 if (!global_reclaim(sc))
a4d3e9e7 1815 force_scan = true;
76a33fc3
SL
1816
1817 /* If we have no swap space, do not bother scanning anon pages. */
ec8acf20 1818 if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
9a265114 1819 scan_balance = SCAN_FILE;
76a33fc3
SL
1820 goto out;
1821 }
4f98a2fe 1822
10316b31
JW
1823 /*
1824 * Global reclaim will swap to prevent OOM even with no
1825 * swappiness, but memcg users want to use this knob to
1826 * disable swapping for individual groups completely when
1827 * using the memory controller's swap limit feature would be
1828 * too expensive.
1829 */
1830 if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
9a265114 1831 scan_balance = SCAN_FILE;
10316b31
JW
1832 goto out;
1833 }
1834
1835 /*
1836 * Do not apply any pressure balancing cleverness when the
1837 * system is close to OOM, scan both anon and file equally
1838 * (unless the swappiness setting disagrees with swapping).
1839 */
1840 if (!sc->priority && vmscan_swappiness(sc)) {
9a265114 1841 scan_balance = SCAN_EQUAL;
10316b31
JW
1842 goto out;
1843 }
1844
4d7dcca2
HD
1845 anon = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
1846 get_lru_size(lruvec, LRU_INACTIVE_ANON);
1847 file = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
1848 get_lru_size(lruvec, LRU_INACTIVE_FILE);
a4d3e9e7 1849
11d16c25
JW
1850 /*
1851 * If it's foreseeable that reclaiming the file cache won't be
1852 * enough to get the zone back into a desirable shape, we have
1853 * to swap. Better start now and leave the - probably heavily
1854 * thrashing - remaining file pages alone.
1855 */
89b5fae5 1856 if (global_reclaim(sc)) {
11d16c25 1857 free = zone_page_state(zone, NR_FREE_PAGES);
90126375 1858 if (unlikely(file + free <= high_wmark_pages(zone))) {
9a265114 1859 scan_balance = SCAN_ANON;
76a33fc3 1860 goto out;
eeee9a8c 1861 }
4f98a2fe
RR
1862 }
1863
7c5bd705
JW
1864 /*
1865 * There is enough inactive page cache, do not reclaim
1866 * anything from the anonymous working set right now.
1867 */
1868 if (!inactive_file_is_low(lruvec)) {
9a265114 1869 scan_balance = SCAN_FILE;
7c5bd705
JW
1870 goto out;
1871 }
1872
9a265114
JW
1873 scan_balance = SCAN_FRACT;
1874
58c37f6e
KM
1875 /*
1876 * With swappiness at 100, anonymous and file have the same priority.
1877 * This scanning priority is essentially the inverse of IO cost.
1878 */
3d58ab5c 1879 anon_prio = vmscan_swappiness(sc);
75b00af7 1880 file_prio = 200 - anon_prio;
58c37f6e 1881
4f98a2fe
RR
1882 /*
1883 * OK, so we have swap space and a fair amount of page cache
1884 * pages. We use the recently rotated / recently scanned
1885 * ratios to determine how valuable each cache is.
1886 *
1887 * Because workloads change over time (and to avoid overflow)
1888 * we keep these statistics as a floating average, which ends
1889 * up weighing recent references more than old ones.
1890 *
1891 * anon in [0], file in [1]
1892 */
90126375 1893 spin_lock_irq(&zone->lru_lock);
6e901571 1894 if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
6e901571
KM
1895 reclaim_stat->recent_scanned[0] /= 2;
1896 reclaim_stat->recent_rotated[0] /= 2;
4f98a2fe
RR
1897 }
1898
6e901571 1899 if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
6e901571
KM
1900 reclaim_stat->recent_scanned[1] /= 2;
1901 reclaim_stat->recent_rotated[1] /= 2;
4f98a2fe
RR
1902 }
1903
4f98a2fe 1904 /*
00d8089c
RR
1905 * The amount of pressure on anon vs file pages is inversely
1906 * proportional to the fraction of recently scanned pages on
1907 * each list that were recently referenced and in active use.
4f98a2fe 1908 */
fe35004f 1909 ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
6e901571 1910 ap /= reclaim_stat->recent_rotated[0] + 1;
4f98a2fe 1911
fe35004f 1912 fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
6e901571 1913 fp /= reclaim_stat->recent_rotated[1] + 1;
90126375 1914 spin_unlock_irq(&zone->lru_lock);
4f98a2fe 1915
76a33fc3
SL
1916 fraction[0] = ap;
1917 fraction[1] = fp;
1918 denominator = ap + fp + 1;
1919out:
4111304d
HD
1920 for_each_evictable_lru(lru) {
1921 int file = is_file_lru(lru);
d778df51 1922 unsigned long size;
76a33fc3 1923 unsigned long scan;
6e08a369 1924
d778df51 1925 size = get_lru_size(lruvec, lru);
10316b31 1926 scan = size >> sc->priority;
9a265114 1927
10316b31
JW
1928 if (!scan && force_scan)
1929 scan = min(size, SWAP_CLUSTER_MAX);
9a265114
JW
1930
1931 switch (scan_balance) {
1932 case SCAN_EQUAL:
1933 /* Scan lists relative to size */
1934 break;
1935 case SCAN_FRACT:
1936 /*
1937 * Scan types proportional to swappiness and
1938 * their relative recent reclaim efficiency.
1939 */
1940 scan = div64_u64(scan * fraction[file], denominator);
1941 break;
1942 case SCAN_FILE:
1943 case SCAN_ANON:
1944 /* Scan one type exclusively */
1945 if ((scan_balance == SCAN_FILE) != file)
1946 scan = 0;
1947 break;
1948 default:
1949 /* Look ma, no brain */
1950 BUG();
1951 }
4111304d 1952 nr[lru] = scan;
76a33fc3 1953 }
6e08a369 1954}
4f98a2fe 1955
9b4f98cd
JW
1956/*
1957 * This is a basic per-zone page freer. Used by both kswapd and direct reclaim.
1958 */
1959static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
1960{
1961 unsigned long nr[NR_LRU_LISTS];
e82e0561 1962 unsigned long targets[NR_LRU_LISTS];
9b4f98cd
JW
1963 unsigned long nr_to_scan;
1964 enum lru_list lru;
1965 unsigned long nr_reclaimed = 0;
1966 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1967 struct blk_plug plug;
e82e0561 1968 bool scan_adjusted = false;
9b4f98cd
JW
1969
1970 get_scan_count(lruvec, sc, nr);
1971
e82e0561
MG
1972 /* Record the original scan target for proportional adjustments later */
1973 memcpy(targets, nr, sizeof(nr));
1974
9b4f98cd
JW
1975 blk_start_plug(&plug);
1976 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1977 nr[LRU_INACTIVE_FILE]) {
e82e0561
MG
1978 unsigned long nr_anon, nr_file, percentage;
1979 unsigned long nr_scanned;
1980
9b4f98cd
JW
1981 for_each_evictable_lru(lru) {
1982 if (nr[lru]) {
1983 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
1984 nr[lru] -= nr_to_scan;
1985
1986 nr_reclaimed += shrink_list(lru, nr_to_scan,
1987 lruvec, sc);
1988 }
1989 }
e82e0561
MG
1990
1991 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
1992 continue;
1993
9b4f98cd 1994 /*
e82e0561
MG
1995 * For global direct reclaim, reclaim only the number of pages
1996 * requested. Less care is taken to scan proportionally as it
1997 * is more important to minimise direct reclaim stall latency
1998 * than it is to properly age the LRU lists.
9b4f98cd 1999 */
e82e0561 2000 if (global_reclaim(sc) && !current_is_kswapd())
9b4f98cd 2001 break;
e82e0561
MG
2002
2003 /*
2004 * For kswapd and memcg, reclaim at least the number of pages
2005 * requested. Ensure that the anon and file LRUs shrink
2006 * proportionally what was requested by get_scan_count(). We
2007 * stop reclaiming one LRU and reduce the amount scanning
2008 * proportional to the original scan target.
2009 */
2010 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2011 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2012
2013 if (nr_file > nr_anon) {
2014 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2015 targets[LRU_ACTIVE_ANON] + 1;
2016 lru = LRU_BASE;
2017 percentage = nr_anon * 100 / scan_target;
2018 } else {
2019 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2020 targets[LRU_ACTIVE_FILE] + 1;
2021 lru = LRU_FILE;
2022 percentage = nr_file * 100 / scan_target;
2023 }
2024
2025 /* Stop scanning the smaller of the LRU */
2026 nr[lru] = 0;
2027 nr[lru + LRU_ACTIVE] = 0;
2028
2029 /*
2030 * Recalculate the other LRU scan count based on its original
2031 * scan target and the percentage scanning already complete
2032 */
2033 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2034 nr_scanned = targets[lru] - nr[lru];
2035 nr[lru] = targets[lru] * (100 - percentage) / 100;
2036 nr[lru] -= min(nr[lru], nr_scanned);
2037
2038 lru += LRU_ACTIVE;
2039 nr_scanned = targets[lru] - nr[lru];
2040 nr[lru] = targets[lru] * (100 - percentage) / 100;
2041 nr[lru] -= min(nr[lru], nr_scanned);
2042
2043 scan_adjusted = true;
9b4f98cd
JW
2044 }
2045 blk_finish_plug(&plug);
2046 sc->nr_reclaimed += nr_reclaimed;
2047
2048 /*
2049 * Even if we did not try to evict anon pages at all, we want to
2050 * rebalance the anon lru active/inactive ratio.
2051 */
2052 if (inactive_anon_is_low(lruvec))
2053 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2054 sc, LRU_ACTIVE_ANON);
2055
2056 throttle_vm_writeout(sc->gfp_mask);
2057}
2058
23b9da55 2059/* Use reclaim/compaction for costly allocs or under memory pressure */
9e3b2f8c 2060static bool in_reclaim_compaction(struct scan_control *sc)
23b9da55 2061{
d84da3f9 2062 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
23b9da55 2063 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
9e3b2f8c 2064 sc->priority < DEF_PRIORITY - 2))
23b9da55
MG
2065 return true;
2066
2067 return false;
2068}
2069
3e7d3449 2070/*
23b9da55
MG
2071 * Reclaim/compaction is used for high-order allocation requests. It reclaims
2072 * order-0 pages before compacting the zone. should_continue_reclaim() returns
2073 * true if more pages should be reclaimed such that when the page allocator
2074 * calls try_to_compact_zone() that it will have enough free pages to succeed.
2075 * It will give up earlier than that if there is difficulty reclaiming pages.
3e7d3449 2076 */
9b4f98cd 2077static inline bool should_continue_reclaim(struct zone *zone,
3e7d3449
MG
2078 unsigned long nr_reclaimed,
2079 unsigned long nr_scanned,
2080 struct scan_control *sc)
2081{
2082 unsigned long pages_for_compaction;
2083 unsigned long inactive_lru_pages;
2084
2085 /* If not in reclaim/compaction mode, stop */
9e3b2f8c 2086 if (!in_reclaim_compaction(sc))
3e7d3449
MG
2087 return false;
2088
2876592f
MG
2089 /* Consider stopping depending on scan and reclaim activity */
2090 if (sc->gfp_mask & __GFP_REPEAT) {
2091 /*
2092 * For __GFP_REPEAT allocations, stop reclaiming if the
2093 * full LRU list has been scanned and we are still failing
2094 * to reclaim pages. This full LRU scan is potentially
2095 * expensive but a __GFP_REPEAT caller really wants to succeed
2096 */
2097 if (!nr_reclaimed && !nr_scanned)
2098 return false;
2099 } else {
2100 /*
2101 * For non-__GFP_REPEAT allocations which can presumably
2102 * fail without consequence, stop if we failed to reclaim
2103 * any pages from the last SWAP_CLUSTER_MAX number of
2104 * pages that were scanned. This will return to the
2105 * caller faster at the risk reclaim/compaction and
2106 * the resulting allocation attempt fails
2107 */
2108 if (!nr_reclaimed)
2109 return false;
2110 }
3e7d3449
MG
2111
2112 /*
2113 * If we have not reclaimed enough pages for compaction and the
2114 * inactive lists are large enough, continue reclaiming
2115 */
2116 pages_for_compaction = (2UL << sc->order);
9b4f98cd 2117 inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
ec8acf20 2118 if (get_nr_swap_pages() > 0)
9b4f98cd 2119 inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
3e7d3449
MG
2120 if (sc->nr_reclaimed < pages_for_compaction &&
2121 inactive_lru_pages > pages_for_compaction)
2122 return true;
2123
2124 /* If compaction would go ahead or the allocation would succeed, stop */
9b4f98cd 2125 switch (compaction_suitable(zone, sc->order)) {
3e7d3449
MG
2126 case COMPACT_PARTIAL:
2127 case COMPACT_CONTINUE:
2128 return false;
2129 default:
2130 return true;
2131 }
2132}
2133
9b4f98cd 2134static void shrink_zone(struct zone *zone, struct scan_control *sc)
1da177e4 2135{
f0fdc5e8 2136 unsigned long nr_reclaimed, nr_scanned;
1da177e4 2137
9b4f98cd
JW
2138 do {
2139 struct mem_cgroup *root = sc->target_mem_cgroup;
2140 struct mem_cgroup_reclaim_cookie reclaim = {
2141 .zone = zone,
2142 .priority = sc->priority,
2143 };
2144 struct mem_cgroup *memcg;
3e7d3449 2145
9b4f98cd
JW
2146 nr_reclaimed = sc->nr_reclaimed;
2147 nr_scanned = sc->nr_scanned;
1da177e4 2148
9b4f98cd
JW
2149 memcg = mem_cgroup_iter(root, NULL, &reclaim);
2150 do {
2151 struct lruvec *lruvec;
5660048c 2152
9b4f98cd 2153 lruvec = mem_cgroup_zone_lruvec(zone, memcg);
f9be23d6 2154
9b4f98cd 2155 shrink_lruvec(lruvec, sc);
f16015fb 2156
9b4f98cd 2157 /*
a394cb8e
MH
2158 * Direct reclaim and kswapd have to scan all memory
2159 * cgroups to fulfill the overall scan target for the
9b4f98cd 2160 * zone.
a394cb8e
MH
2161 *
2162 * Limit reclaim, on the other hand, only cares about
2163 * nr_to_reclaim pages to be reclaimed and it will
2164 * retry with decreasing priority if one round over the
2165 * whole hierarchy is not sufficient.
9b4f98cd 2166 */
a394cb8e
MH
2167 if (!global_reclaim(sc) &&
2168 sc->nr_reclaimed >= sc->nr_to_reclaim) {
9b4f98cd
JW
2169 mem_cgroup_iter_break(root, memcg);
2170 break;
2171 }
2172 memcg = mem_cgroup_iter(root, memcg, &reclaim);
2173 } while (memcg);
70ddf637
AV
2174
2175 vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
2176 sc->nr_scanned - nr_scanned,
2177 sc->nr_reclaimed - nr_reclaimed);
2178
9b4f98cd
JW
2179 } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
2180 sc->nr_scanned - nr_scanned, sc));
f16015fb
JW
2181}
2182
fe4b1b24
MG
2183/* Returns true if compaction should go ahead for a high-order request */
2184static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2185{
2186 unsigned long balance_gap, watermark;
2187 bool watermark_ok;
2188
2189 /* Do not consider compaction for orders reclaim is meant to satisfy */
2190 if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2191 return false;
2192
2193 /*
2194 * Compaction takes time to run and there are potentially other
2195 * callers using the pages just freed. Continue reclaiming until
2196 * there is a buffer of free pages available to give compaction
2197 * a reasonable chance of completing and allocating the page
2198 */
2199 balance_gap = min(low_wmark_pages(zone),
b40da049 2200 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
fe4b1b24
MG
2201 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2202 watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2203 watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2204
2205 /*
2206 * If compaction is deferred, reclaim up to a point where
2207 * compaction will have a chance of success when re-enabled
2208 */
aff62249 2209 if (compaction_deferred(zone, sc->order))
fe4b1b24
MG
2210 return watermark_ok;
2211
2212 /* If compaction is not ready to start, keep reclaiming */
2213 if (!compaction_suitable(zone, sc->order))
2214 return false;
2215
2216 return watermark_ok;
2217}
2218
1da177e4
LT
2219/*
2220 * This is the direct reclaim path, for page-allocating processes. We only
2221 * try to reclaim pages from zones which will satisfy the caller's allocation
2222 * request.
2223 *
41858966
MG
2224 * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
2225 * Because:
1da177e4
LT
2226 * a) The caller may be trying to free *extra* pages to satisfy a higher-order
2227 * allocation or
41858966
MG
2228 * b) The target zone may be at high_wmark_pages(zone) but the lower zones
2229 * must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
2230 * zone defense algorithm.
1da177e4 2231 *
1da177e4
LT
2232 * If a zone is deemed to be full of pinned pages then just give it a light
2233 * scan then give up on it.
e0c23279
MG
2234 *
2235 * This function returns true if a zone is being reclaimed for a costly
fe4b1b24 2236 * high-order allocation and compaction is ready to begin. This indicates to
0cee34fd
MG
2237 * the caller that it should consider retrying the allocation instead of
2238 * further reclaim.
1da177e4 2239 */
9e3b2f8c 2240static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
1da177e4 2241{
dd1a239f 2242 struct zoneref *z;
54a6eb5c 2243 struct zone *zone;
d149e3b2
YH
2244 unsigned long nr_soft_reclaimed;
2245 unsigned long nr_soft_scanned;
0cee34fd 2246 bool aborted_reclaim = false;
1cfb419b 2247
cc715d99
MG
2248 /*
2249 * If the number of buffer_heads in the machine exceeds the maximum
2250 * allowed level, force direct reclaim to scan the highmem zone as
2251 * highmem pages could be pinning lowmem pages storing buffer_heads
2252 */
2253 if (buffer_heads_over_limit)
2254 sc->gfp_mask |= __GFP_HIGHMEM;
2255
d4debc66
MG
2256 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2257 gfp_zone(sc->gfp_mask), sc->nodemask) {
f3fe6512 2258 if (!populated_zone(zone))
1da177e4 2259 continue;
1cfb419b
KH
2260 /*
2261 * Take care memory controller reclaiming has small influence
2262 * to global LRU.
2263 */
89b5fae5 2264 if (global_reclaim(sc)) {
1cfb419b
KH
2265 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2266 continue;
9e3b2f8c
KK
2267 if (zone->all_unreclaimable &&
2268 sc->priority != DEF_PRIORITY)
1cfb419b 2269 continue; /* Let kswapd poll it */
d84da3f9 2270 if (IS_ENABLED(CONFIG_COMPACTION)) {
e0887c19 2271 /*
e0c23279
MG
2272 * If we already have plenty of memory free for
2273 * compaction in this zone, don't free any more.
2274 * Even though compaction is invoked for any
2275 * non-zero order, only frequent costly order
2276 * reclamation is disruptive enough to become a
c7cfa37b
CA
2277 * noticeable problem, like transparent huge
2278 * page allocations.
e0887c19 2279 */
fe4b1b24 2280 if (compaction_ready(zone, sc)) {
0cee34fd 2281 aborted_reclaim = true;
e0887c19 2282 continue;
e0c23279 2283 }
e0887c19 2284 }
ac34a1a3
KH
2285 /*
2286 * This steals pages from memory cgroups over softlimit
2287 * and returns the number of reclaimed pages and
2288 * scanned pages. This works for global memory pressure
2289 * and balancing, not for a memcg's limit.
2290 */
2291 nr_soft_scanned = 0;
2292 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2293 sc->order, sc->gfp_mask,
2294 &nr_soft_scanned);
2295 sc->nr_reclaimed += nr_soft_reclaimed;
2296 sc->nr_scanned += nr_soft_scanned;
2297 /* need some check for avoid more shrink_zone() */
1cfb419b 2298 }
408d8544 2299
9e3b2f8c 2300 shrink_zone(zone, sc);
1da177e4 2301 }
e0c23279 2302
0cee34fd 2303 return aborted_reclaim;
d1908362
MK
2304}
2305
2306static bool zone_reclaimable(struct zone *zone)
2307{
2308 return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2309}
2310
929bea7c 2311/* All zones in zonelist are unreclaimable? */
d1908362
MK
2312static bool all_unreclaimable(struct zonelist *zonelist,
2313 struct scan_control *sc)
2314{
2315 struct zoneref *z;
2316 struct zone *zone;
d1908362
MK
2317
2318 for_each_zone_zonelist_nodemask(zone, z, zonelist,
2319 gfp_zone(sc->gfp_mask), sc->nodemask) {
2320 if (!populated_zone(zone))
2321 continue;
2322 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2323 continue;
929bea7c
KM
2324 if (!zone->all_unreclaimable)
2325 return false;
d1908362
MK
2326 }
2327
929bea7c 2328 return true;
1da177e4 2329}
4f98a2fe 2330
1da177e4
LT
2331/*
2332 * This is the main entry point to direct page reclaim.
2333 *
2334 * If a full scan of the inactive list fails to free enough memory then we
2335 * are "out of memory" and something needs to be killed.
2336 *
2337 * If the caller is !__GFP_FS then the probability of a failure is reasonably
2338 * high - the zone may be full of dirty or under-writeback pages, which this
5b0830cb
JA
2339 * caller can't do much about. We kick the writeback threads and take explicit
2340 * naps in the hope that some of these pages can be written. But if the
2341 * allocating task holds filesystem locks which prevent writeout this might not
2342 * work, and the allocation attempt will fail.
a41f24ea
NA
2343 *
2344 * returns: 0, if no pages reclaimed
2345 * else, the number of pages reclaimed
1da177e4 2346 */
dac1d27b 2347static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
a09ed5e0
YH
2348 struct scan_control *sc,
2349 struct shrink_control *shrink)
1da177e4 2350{
69e05944 2351 unsigned long total_scanned = 0;
1da177e4 2352 struct reclaim_state *reclaim_state = current->reclaim_state;
dd1a239f 2353 struct zoneref *z;
54a6eb5c 2354 struct zone *zone;
22fba335 2355 unsigned long writeback_threshold;
0cee34fd 2356 bool aborted_reclaim;
1da177e4 2357
873b4771
KK
2358 delayacct_freepages_start();
2359
89b5fae5 2360 if (global_reclaim(sc))
1cfb419b 2361 count_vm_event(ALLOCSTALL);
1da177e4 2362
9e3b2f8c 2363 do {
70ddf637
AV
2364 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
2365 sc->priority);
66e1707b 2366 sc->nr_scanned = 0;
9e3b2f8c 2367 aborted_reclaim = shrink_zones(zonelist, sc);
e0c23279 2368
66e1707b 2369 /*
5a1c9cbc
MG
2370 * Don't shrink slabs when reclaiming memory from over limit
2371 * cgroups but do shrink slab at least once when aborting
2372 * reclaim for compaction to avoid unevenly scanning file/anon
2373 * LRU pages over slab pages.
66e1707b 2374 */
89b5fae5 2375 if (global_reclaim(sc)) {
c6a8a8c5 2376 unsigned long lru_pages = 0;
0ce3d744
DC
2377
2378 nodes_clear(shrink->nodes_to_scan);
d4debc66
MG
2379 for_each_zone_zonelist(zone, z, zonelist,
2380 gfp_zone(sc->gfp_mask)) {
c6a8a8c5
KM
2381 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2382 continue;
2383
2384 lru_pages += zone_reclaimable_pages(zone);
0ce3d744
DC
2385 node_set(zone_to_nid(zone),
2386 shrink->nodes_to_scan);
c6a8a8c5
KM
2387 }
2388
1495f230 2389 shrink_slab(shrink, sc->nr_scanned, lru_pages);
91a45470 2390 if (reclaim_state) {
a79311c1 2391 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
91a45470
KH
2392 reclaim_state->reclaimed_slab = 0;
2393 }
1da177e4 2394 }
66e1707b 2395 total_scanned += sc->nr_scanned;
bb21c7ce 2396 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
1da177e4 2397 goto out;
1da177e4 2398
0e50ce3b
MK
2399 /*
2400 * If we're getting trouble reclaiming, start doing
2401 * writepage even in laptop mode.
2402 */
2403 if (sc->priority < DEF_PRIORITY - 2)
2404 sc->may_writepage = 1;
2405
1da177e4
LT
2406 /*
2407 * Try to write back as many pages as we just scanned. This
2408 * tends to cause slow streaming writers to write data to the
2409 * disk smoothly, at the dirtying rate, which is nice. But
2410 * that's undesirable in laptop mode, where we *want* lumpy
2411 * writeout. So in laptop mode, write out the whole world.
2412 */
22fba335
KM
2413 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
2414 if (total_scanned > writeback_threshold) {
0e175a18
CW
2415 wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
2416 WB_REASON_TRY_TO_FREE_PAGES);
66e1707b 2417 sc->may_writepage = 1;
1da177e4 2418 }
5a1c9cbc 2419 } while (--sc->priority >= 0 && !aborted_reclaim);
bb21c7ce 2420
1da177e4 2421out:
873b4771
KK
2422 delayacct_freepages_end();
2423
bb21c7ce
KM
2424 if (sc->nr_reclaimed)
2425 return sc->nr_reclaimed;
2426
929bea7c
KM
2427 /*
2428 * As hibernation is going on, kswapd is freezed so that it can't mark
2429 * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2430 * check.
2431 */
2432 if (oom_killer_disabled)
2433 return 0;
2434
0cee34fd
MG
2435 /* Aborted reclaim to try compaction? don't OOM, then */
2436 if (aborted_reclaim)
7335084d
MG
2437 return 1;
2438
bb21c7ce 2439 /* top priority shrink_zones still had more to do? don't OOM, then */
89b5fae5 2440 if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
bb21c7ce
KM
2441 return 1;
2442
2443 return 0;
1da177e4
LT
2444}
2445
5515061d
MG
2446static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
2447{
2448 struct zone *zone;
2449 unsigned long pfmemalloc_reserve = 0;
2450 unsigned long free_pages = 0;
2451 int i;
2452 bool wmark_ok;
2453
2454 for (i = 0; i <= ZONE_NORMAL; i++) {
2455 zone = &pgdat->node_zones[i];
2456 pfmemalloc_reserve += min_wmark_pages(zone);
2457 free_pages += zone_page_state(zone, NR_FREE_PAGES);
2458 }
2459
2460 wmark_ok = free_pages > pfmemalloc_reserve / 2;
2461
2462 /* kswapd must be awake if processes are being throttled */
2463 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
2464 pgdat->classzone_idx = min(pgdat->classzone_idx,
2465 (enum zone_type)ZONE_NORMAL);
2466 wake_up_interruptible(&pgdat->kswapd_wait);
2467 }
2468
2469 return wmark_ok;
2470}
2471
2472/*
2473 * Throttle direct reclaimers if backing storage is backed by the network
2474 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
2475 * depleted. kswapd will continue to make progress and wake the processes
50694c28
MG
2476 * when the low watermark is reached.
2477 *
2478 * Returns true if a fatal signal was delivered during throttling. If this
2479 * happens, the page allocator should not consider triggering the OOM killer.
5515061d 2480 */
50694c28 2481static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
5515061d
MG
2482 nodemask_t *nodemask)
2483{
2484 struct zone *zone;
2485 int high_zoneidx = gfp_zone(gfp_mask);
2486 pg_data_t *pgdat;
2487
2488 /*
2489 * Kernel threads should not be throttled as they may be indirectly
2490 * responsible for cleaning pages necessary for reclaim to make forward
2491 * progress. kjournald for example may enter direct reclaim while
2492 * committing a transaction where throttling it could forcing other
2493 * processes to block on log_wait_commit().
2494 */
2495 if (current->flags & PF_KTHREAD)
50694c28
MG
2496 goto out;
2497
2498 /*
2499 * If a fatal signal is pending, this process should not throttle.
2500 * It should return quickly so it can exit and free its memory
2501 */
2502 if (fatal_signal_pending(current))
2503 goto out;
5515061d
MG
2504
2505 /* Check if the pfmemalloc reserves are ok */
2506 first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
2507 pgdat = zone->zone_pgdat;
2508 if (pfmemalloc_watermark_ok(pgdat))
50694c28 2509 goto out;
5515061d 2510
68243e76
MG
2511 /* Account for the throttling */
2512 count_vm_event(PGSCAN_DIRECT_THROTTLE);
2513
5515061d
MG
2514 /*
2515 * If the caller cannot enter the filesystem, it's possible that it
2516 * is due to the caller holding an FS lock or performing a journal
2517 * transaction in the case of a filesystem like ext[3|4]. In this case,
2518 * it is not safe to block on pfmemalloc_wait as kswapd could be
2519 * blocked waiting on the same lock. Instead, throttle for up to a
2520 * second before continuing.
2521 */
2522 if (!(gfp_mask & __GFP_FS)) {
2523 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2524 pfmemalloc_watermark_ok(pgdat), HZ);
50694c28
MG
2525
2526 goto check_pending;
5515061d
MG
2527 }
2528
2529 /* Throttle until kswapd wakes the process */
2530 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2531 pfmemalloc_watermark_ok(pgdat));
50694c28
MG
2532
2533check_pending:
2534 if (fatal_signal_pending(current))
2535 return true;
2536
2537out:
2538 return false;
5515061d
MG
2539}
2540
dac1d27b 2541unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
327c0e96 2542 gfp_t gfp_mask, nodemask_t *nodemask)
66e1707b 2543{
33906bc5 2544 unsigned long nr_reclaimed;
66e1707b 2545 struct scan_control sc = {
21caf2fc 2546 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
66e1707b 2547 .may_writepage = !laptop_mode,
22fba335 2548 .nr_to_reclaim = SWAP_CLUSTER_MAX,
a6dc60f8 2549 .may_unmap = 1,
2e2e4259 2550 .may_swap = 1,
66e1707b 2551 .order = order,
9e3b2f8c 2552 .priority = DEF_PRIORITY,
f16015fb 2553 .target_mem_cgroup = NULL,
327c0e96 2554 .nodemask = nodemask,
66e1707b 2555 };
a09ed5e0
YH
2556 struct shrink_control shrink = {
2557 .gfp_mask = sc.gfp_mask,
2558 };
66e1707b 2559
5515061d 2560 /*
50694c28
MG
2561 * Do not enter reclaim if fatal signal was delivered while throttled.
2562 * 1 is returned so that the page allocator does not OOM kill at this
2563 * point.
5515061d 2564 */
50694c28 2565 if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
5515061d
MG
2566 return 1;
2567
33906bc5
MG
2568 trace_mm_vmscan_direct_reclaim_begin(order,
2569 sc.may_writepage,
2570 gfp_mask);
2571
a09ed5e0 2572 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
33906bc5
MG
2573
2574 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
2575
2576 return nr_reclaimed;
66e1707b
BS
2577}
2578
c255a458 2579#ifdef CONFIG_MEMCG
66e1707b 2580
72835c86 2581unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
4e416953 2582 gfp_t gfp_mask, bool noswap,
0ae5e89c
YH
2583 struct zone *zone,
2584 unsigned long *nr_scanned)
4e416953
BS
2585{
2586 struct scan_control sc = {
0ae5e89c 2587 .nr_scanned = 0,
b8f5c566 2588 .nr_to_reclaim = SWAP_CLUSTER_MAX,
4e416953
BS
2589 .may_writepage = !laptop_mode,
2590 .may_unmap = 1,
2591 .may_swap = !noswap,
4e416953 2592 .order = 0,
9e3b2f8c 2593 .priority = 0,
72835c86 2594 .target_mem_cgroup = memcg,
4e416953 2595 };
f9be23d6 2596 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
0ae5e89c 2597
4e416953
BS
2598 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2599 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
bdce6d9e 2600
9e3b2f8c 2601 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
bdce6d9e
KM
2602 sc.may_writepage,
2603 sc.gfp_mask);
2604
4e416953
BS
2605 /*
2606 * NOTE: Although we can get the priority field, using it
2607 * here is not a good idea, since it limits the pages we can scan.
2608 * if we don't reclaim here, the shrink_zone from balance_pgdat
2609 * will pick up pages from other mem cgroup's as well. We hack
2610 * the priority and make it zero.
2611 */
f9be23d6 2612 shrink_lruvec(lruvec, &sc);
bdce6d9e
KM
2613
2614 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2615
0ae5e89c 2616 *nr_scanned = sc.nr_scanned;
4e416953
BS
2617 return sc.nr_reclaimed;
2618}
2619
72835c86 2620unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
a7885eb8 2621 gfp_t gfp_mask,
185efc0f 2622 bool noswap)
66e1707b 2623{
4e416953 2624 struct zonelist *zonelist;
bdce6d9e 2625 unsigned long nr_reclaimed;
889976db 2626 int nid;
66e1707b 2627 struct scan_control sc = {
66e1707b 2628 .may_writepage = !laptop_mode,
a6dc60f8 2629 .may_unmap = 1,
2e2e4259 2630 .may_swap = !noswap,
22fba335 2631 .nr_to_reclaim = SWAP_CLUSTER_MAX,
66e1707b 2632 .order = 0,
9e3b2f8c 2633 .priority = DEF_PRIORITY,
72835c86 2634 .target_mem_cgroup = memcg,
327c0e96 2635 .nodemask = NULL, /* we don't care the placement */
a09ed5e0
YH
2636 .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2637 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2638 };
2639 struct shrink_control shrink = {
2640 .gfp_mask = sc.gfp_mask,
66e1707b 2641 };
66e1707b 2642
889976db
YH
2643 /*
2644 * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2645 * take care of from where we get pages. So the node where we start the
2646 * scan does not need to be the current node.
2647 */
72835c86 2648 nid = mem_cgroup_select_victim_node(memcg);
889976db
YH
2649
2650 zonelist = NODE_DATA(nid)->node_zonelists;
bdce6d9e
KM
2651
2652 trace_mm_vmscan_memcg_reclaim_begin(0,
2653 sc.may_writepage,
2654 sc.gfp_mask);
2655
a09ed5e0 2656 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
bdce6d9e
KM
2657
2658 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2659
2660 return nr_reclaimed;
66e1707b
BS
2661}
2662#endif
2663
9e3b2f8c 2664static void age_active_anon(struct zone *zone, struct scan_control *sc)
f16015fb 2665{
b95a2f2d 2666 struct mem_cgroup *memcg;
f16015fb 2667
b95a2f2d
JW
2668 if (!total_swap_pages)
2669 return;
2670
2671 memcg = mem_cgroup_iter(NULL, NULL, NULL);
2672 do {
c56d5c7d 2673 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
b95a2f2d 2674
c56d5c7d 2675 if (inactive_anon_is_low(lruvec))
1a93be0e 2676 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
9e3b2f8c 2677 sc, LRU_ACTIVE_ANON);
b95a2f2d
JW
2678
2679 memcg = mem_cgroup_iter(NULL, memcg, NULL);
2680 } while (memcg);
f16015fb
JW
2681}
2682
60cefed4
JW
2683static bool zone_balanced(struct zone *zone, int order,
2684 unsigned long balance_gap, int classzone_idx)
2685{
2686 if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
2687 balance_gap, classzone_idx, 0))
2688 return false;
2689
d84da3f9
KS
2690 if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2691 !compaction_suitable(zone, order))
60cefed4
JW
2692 return false;
2693
2694 return true;
2695}
2696
1741c877 2697/*
4ae0a48b
ZC
2698 * pgdat_balanced() is used when checking if a node is balanced.
2699 *
2700 * For order-0, all zones must be balanced!
2701 *
2702 * For high-order allocations only zones that meet watermarks and are in a
2703 * zone allowed by the callers classzone_idx are added to balanced_pages. The
2704 * total of balanced pages must be at least 25% of the zones allowed by
2705 * classzone_idx for the node to be considered balanced. Forcing all zones to
2706 * be balanced for high orders can cause excessive reclaim when there are
2707 * imbalanced zones.
1741c877
MG
2708 * The choice of 25% is due to
2709 * o a 16M DMA zone that is balanced will not balance a zone on any
2710 * reasonable sized machine
2711 * o On all other machines, the top zone must be at least a reasonable
25985edc 2712 * percentage of the middle zones. For example, on 32-bit x86, highmem
1741c877
MG
2713 * would need to be at least 256M for it to be balance a whole node.
2714 * Similarly, on x86-64 the Normal zone would need to be at least 1G
2715 * to balance a node on its own. These seemed like reasonable ratios.
2716 */
4ae0a48b 2717static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
1741c877 2718{
b40da049 2719 unsigned long managed_pages = 0;
4ae0a48b 2720 unsigned long balanced_pages = 0;
1741c877
MG
2721 int i;
2722
4ae0a48b
ZC
2723 /* Check the watermark levels */
2724 for (i = 0; i <= classzone_idx; i++) {
2725 struct zone *zone = pgdat->node_zones + i;
1741c877 2726
4ae0a48b
ZC
2727 if (!populated_zone(zone))
2728 continue;
2729
b40da049 2730 managed_pages += zone->managed_pages;
4ae0a48b
ZC
2731
2732 /*
2733 * A special case here:
2734 *
2735 * balance_pgdat() skips over all_unreclaimable after
2736 * DEF_PRIORITY. Effectively, it considers them balanced so
2737 * they must be considered balanced here as well!
2738 */
2739 if (zone->all_unreclaimable) {
b40da049 2740 balanced_pages += zone->managed_pages;
4ae0a48b
ZC
2741 continue;
2742 }
2743
2744 if (zone_balanced(zone, order, 0, i))
b40da049 2745 balanced_pages += zone->managed_pages;
4ae0a48b
ZC
2746 else if (!order)
2747 return false;
2748 }
2749
2750 if (order)
b40da049 2751 return balanced_pages >= (managed_pages >> 2);
4ae0a48b
ZC
2752 else
2753 return true;
1741c877
MG
2754}
2755
5515061d
MG
2756/*
2757 * Prepare kswapd for sleeping. This verifies that there are no processes
2758 * waiting in throttle_direct_reclaim() and that watermarks have been met.
2759 *
2760 * Returns true if kswapd is ready to sleep
2761 */
2762static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
dc83edd9 2763 int classzone_idx)
f50de2d3 2764{
f50de2d3
MG
2765 /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2766 if (remaining)
5515061d
MG
2767 return false;
2768
2769 /*
2770 * There is a potential race between when kswapd checks its watermarks
2771 * and a process gets throttled. There is also a potential race if
2772 * processes get throttled, kswapd wakes, a large process exits therby
2773 * balancing the zones that causes kswapd to miss a wakeup. If kswapd
2774 * is going to sleep, no process should be sleeping on pfmemalloc_wait
2775 * so wake them now if necessary. If necessary, processes will wake
2776 * kswapd and get throttled again
2777 */
2778 if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
2779 wake_up(&pgdat->pfmemalloc_wait);
2780 return false;
2781 }
f50de2d3 2782
4ae0a48b 2783 return pgdat_balanced(pgdat, order, classzone_idx);
f50de2d3
MG
2784}
2785
75485363
MG
2786/*
2787 * kswapd shrinks the zone by the number of pages required to reach
2788 * the high watermark.
b8e83b94
MG
2789 *
2790 * Returns true if kswapd scanned at least the requested number of pages to
283aba9f
MG
2791 * reclaim or if the lack of progress was due to pages under writeback.
2792 * This is used to determine if the scanning priority needs to be raised.
75485363 2793 */
b8e83b94 2794static bool kswapd_shrink_zone(struct zone *zone,
7c954f6d 2795 int classzone_idx,
75485363 2796 struct scan_control *sc,
2ab44f43
MG
2797 unsigned long lru_pages,
2798 unsigned long *nr_attempted)
75485363
MG
2799{
2800 unsigned long nr_slab;
7c954f6d
MG
2801 int testorder = sc->order;
2802 unsigned long balance_gap;
75485363
MG
2803 struct reclaim_state *reclaim_state = current->reclaim_state;
2804 struct shrink_control shrink = {
2805 .gfp_mask = sc->gfp_mask,
2806 };
7c954f6d 2807 bool lowmem_pressure;
75485363
MG
2808
2809 /* Reclaim above the high watermark. */
2810 sc->nr_to_reclaim = max(SWAP_CLUSTER_MAX, high_wmark_pages(zone));
7c954f6d
MG
2811
2812 /*
2813 * Kswapd reclaims only single pages with compaction enabled. Trying
2814 * too hard to reclaim until contiguous free pages have become
2815 * available can hurt performance by evicting too much useful data
2816 * from memory. Do not reclaim more than needed for compaction.
2817 */
2818 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2819 compaction_suitable(zone, sc->order) !=
2820 COMPACT_SKIPPED)
2821 testorder = 0;
2822
2823 /*
2824 * We put equal pressure on every zone, unless one zone has way too
2825 * many pages free already. The "too many pages" is defined as the
2826 * high wmark plus a "gap" where the gap is either the low
2827 * watermark or 1% of the zone, whichever is smaller.
2828 */
2829 balance_gap = min(low_wmark_pages(zone),
2830 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2831 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2832
2833 /*
2834 * If there is no low memory pressure or the zone is balanced then no
2835 * reclaim is necessary
2836 */
2837 lowmem_pressure = (buffer_heads_over_limit && is_highmem(zone));
2838 if (!lowmem_pressure && zone_balanced(zone, testorder,
2839 balance_gap, classzone_idx))
2840 return true;
2841
75485363 2842 shrink_zone(zone, sc);
0ce3d744
DC
2843 nodes_clear(shrink.nodes_to_scan);
2844 node_set(zone_to_nid(zone), shrink.nodes_to_scan);
75485363
MG
2845
2846 reclaim_state->reclaimed_slab = 0;
2847 nr_slab = shrink_slab(&shrink, sc->nr_scanned, lru_pages);
2848 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2849
2ab44f43
MG
2850 /* Account for the number of pages attempted to reclaim */
2851 *nr_attempted += sc->nr_to_reclaim;
2852
75485363
MG
2853 if (nr_slab == 0 && !zone_reclaimable(zone))
2854 zone->all_unreclaimable = 1;
b8e83b94 2855
283aba9f
MG
2856 zone_clear_flag(zone, ZONE_WRITEBACK);
2857
7c954f6d
MG
2858 /*
2859 * If a zone reaches its high watermark, consider it to be no longer
2860 * congested. It's possible there are dirty pages backed by congested
2861 * BDIs but as pressure is relieved, speculatively avoid congestion
2862 * waits.
2863 */
2864 if (!zone->all_unreclaimable &&
2865 zone_balanced(zone, testorder, 0, classzone_idx)) {
2866 zone_clear_flag(zone, ZONE_CONGESTED);
2867 zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
2868 }
2869
b8e83b94 2870 return sc->nr_scanned >= sc->nr_to_reclaim;
75485363
MG
2871}
2872
1da177e4
LT
2873/*
2874 * For kswapd, balance_pgdat() will work across all this node's zones until
41858966 2875 * they are all at high_wmark_pages(zone).
1da177e4 2876 *
0abdee2b 2877 * Returns the final order kswapd was reclaiming at
1da177e4
LT
2878 *
2879 * There is special handling here for zones which are full of pinned pages.
2880 * This can happen if the pages are all mlocked, or if they are all used by
2881 * device drivers (say, ZONE_DMA). Or if they are all in use by hugetlb.
2882 * What we do is to detect the case where all pages in the zone have been
2883 * scanned twice and there has been zero successful reclaim. Mark the zone as
2884 * dead and from now on, only perform a short scan. Basically we're polling
2885 * the zone for when the problem goes away.
2886 *
2887 * kswapd scans the zones in the highmem->normal->dma direction. It skips
41858966
MG
2888 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
2889 * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
2890 * lower zones regardless of the number of free pages in the lower zones. This
2891 * interoperates with the page allocator fallback scheme to ensure that aging
2892 * of pages is balanced across the zones.
1da177e4 2893 */
99504748 2894static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
dc83edd9 2895 int *classzone_idx)
1da177e4 2896{
1da177e4 2897 int i;
99504748 2898 int end_zone = 0; /* Inclusive. 0 = ZONE_DMA */
0ae5e89c
YH
2899 unsigned long nr_soft_reclaimed;
2900 unsigned long nr_soft_scanned;
179e9639
AM
2901 struct scan_control sc = {
2902 .gfp_mask = GFP_KERNEL,
b8e83b94 2903 .priority = DEF_PRIORITY,
a6dc60f8 2904 .may_unmap = 1,
2e2e4259 2905 .may_swap = 1,
b8e83b94 2906 .may_writepage = !laptop_mode,
5ad333eb 2907 .order = order,
f16015fb 2908 .target_mem_cgroup = NULL,
179e9639 2909 };
f8891e5e 2910 count_vm_event(PAGEOUTRUN);
1da177e4 2911
9e3b2f8c 2912 do {
1da177e4 2913 unsigned long lru_pages = 0;
2ab44f43 2914 unsigned long nr_attempted = 0;
b8e83b94 2915 bool raise_priority = true;
2ab44f43 2916 bool pgdat_needs_compaction = (order > 0);
b8e83b94
MG
2917
2918 sc.nr_reclaimed = 0;
1da177e4 2919
d6277db4
RW
2920 /*
2921 * Scan in the highmem->dma direction for the highest
2922 * zone which needs scanning
2923 */
2924 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2925 struct zone *zone = pgdat->node_zones + i;
1da177e4 2926
d6277db4
RW
2927 if (!populated_zone(zone))
2928 continue;
1da177e4 2929
9e3b2f8c
KK
2930 if (zone->all_unreclaimable &&
2931 sc.priority != DEF_PRIORITY)
d6277db4 2932 continue;
1da177e4 2933
556adecb
RR
2934 /*
2935 * Do some background aging of the anon list, to give
2936 * pages a chance to be referenced before reclaiming.
2937 */
9e3b2f8c 2938 age_active_anon(zone, &sc);
556adecb 2939
cc715d99
MG
2940 /*
2941 * If the number of buffer_heads in the machine
2942 * exceeds the maximum allowed level and this node
2943 * has a highmem zone, force kswapd to reclaim from
2944 * it to relieve lowmem pressure.
2945 */
2946 if (buffer_heads_over_limit && is_highmem_idx(i)) {
2947 end_zone = i;
2948 break;
2949 }
2950
60cefed4 2951 if (!zone_balanced(zone, order, 0, 0)) {
d6277db4 2952 end_zone = i;
e1dbeda6 2953 break;
439423f6 2954 } else {
d43006d5
MG
2955 /*
2956 * If balanced, clear the dirty and congested
2957 * flags
2958 */
439423f6 2959 zone_clear_flag(zone, ZONE_CONGESTED);
d43006d5 2960 zone_clear_flag(zone, ZONE_TAIL_LRU_DIRTY);
1da177e4 2961 }
1da177e4 2962 }
dafcb73e 2963
b8e83b94 2964 if (i < 0)
e1dbeda6
AM
2965 goto out;
2966
1da177e4
LT
2967 for (i = 0; i <= end_zone; i++) {
2968 struct zone *zone = pgdat->node_zones + i;
2969
2ab44f43
MG
2970 if (!populated_zone(zone))
2971 continue;
2972
adea02a1 2973 lru_pages += zone_reclaimable_pages(zone);
2ab44f43
MG
2974
2975 /*
2976 * If any zone is currently balanced then kswapd will
2977 * not call compaction as it is expected that the
2978 * necessary pages are already available.
2979 */
2980 if (pgdat_needs_compaction &&
2981 zone_watermark_ok(zone, order,
2982 low_wmark_pages(zone),
2983 *classzone_idx, 0))
2984 pgdat_needs_compaction = false;
1da177e4
LT
2985 }
2986
b7ea3c41
MG
2987 /*
2988 * If we're getting trouble reclaiming, start doing writepage
2989 * even in laptop mode.
2990 */
2991 if (sc.priority < DEF_PRIORITY - 2)
2992 sc.may_writepage = 1;
2993
1da177e4
LT
2994 /*
2995 * Now scan the zone in the dma->highmem direction, stopping
2996 * at the last zone which needs scanning.
2997 *
2998 * We do this because the page allocator works in the opposite
2999 * direction. This prevents the page allocator from allocating
3000 * pages behind kswapd's direction of progress, which would
3001 * cause too much scanning of the lower zones.
3002 */
3003 for (i = 0; i <= end_zone; i++) {
3004 struct zone *zone = pgdat->node_zones + i;
3005
f3fe6512 3006 if (!populated_zone(zone))
1da177e4
LT
3007 continue;
3008
9e3b2f8c
KK
3009 if (zone->all_unreclaimable &&
3010 sc.priority != DEF_PRIORITY)
1da177e4
LT
3011 continue;
3012
1da177e4 3013 sc.nr_scanned = 0;
4e416953 3014
0ae5e89c 3015 nr_soft_scanned = 0;
4e416953
BS
3016 /*
3017 * Call soft limit reclaim before calling shrink_zone.
4e416953 3018 */
0ae5e89c
YH
3019 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
3020 order, sc.gfp_mask,
3021 &nr_soft_scanned);
3022 sc.nr_reclaimed += nr_soft_reclaimed;
00918b6a 3023
32a4330d 3024 /*
7c954f6d
MG
3025 * There should be no need to raise the scanning
3026 * priority if enough pages are already being scanned
3027 * that that high watermark would be met at 100%
3028 * efficiency.
fe2c2a10 3029 */
7c954f6d
MG
3030 if (kswapd_shrink_zone(zone, end_zone, &sc,
3031 lru_pages, &nr_attempted))
3032 raise_priority = false;
1da177e4 3033 }
5515061d
MG
3034
3035 /*
3036 * If the low watermark is met there is no need for processes
3037 * to be throttled on pfmemalloc_wait as they should not be
3038 * able to safely make forward progress. Wake them
3039 */
3040 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3041 pfmemalloc_watermark_ok(pgdat))
3042 wake_up(&pgdat->pfmemalloc_wait);
3043
1da177e4 3044 /*
b8e83b94
MG
3045 * Fragmentation may mean that the system cannot be rebalanced
3046 * for high-order allocations in all zones. If twice the
3047 * allocation size has been reclaimed and the zones are still
3048 * not balanced then recheck the watermarks at order-0 to
3049 * prevent kswapd reclaiming excessively. Assume that a
3050 * process requested a high-order can direct reclaim/compact.
1da177e4 3051 */
b8e83b94
MG
3052 if (order && sc.nr_reclaimed >= 2UL << order)
3053 order = sc.order = 0;
8357376d 3054
b8e83b94
MG
3055 /* Check if kswapd should be suspending */
3056 if (try_to_freeze() || kthread_should_stop())
3057 break;
8357376d 3058
2ab44f43
MG
3059 /*
3060 * Compact if necessary and kswapd is reclaiming at least the
3061 * high watermark number of pages as requsted
3062 */
3063 if (pgdat_needs_compaction && sc.nr_reclaimed > nr_attempted)
3064 compact_pgdat(pgdat, order);
3065
73ce02e9 3066 /*
b8e83b94
MG
3067 * Raise priority if scanning rate is too low or there was no
3068 * progress in reclaiming pages
73ce02e9 3069 */
b8e83b94
MG
3070 if (raise_priority || !sc.nr_reclaimed)
3071 sc.priority--;
9aa41348 3072 } while (sc.priority >= 1 &&
b8e83b94 3073 !pgdat_balanced(pgdat, order, *classzone_idx));
1da177e4 3074
b8e83b94 3075out:
0abdee2b 3076 /*
5515061d 3077 * Return the order we were reclaiming at so prepare_kswapd_sleep()
0abdee2b
MG
3078 * makes a decision on the order we were last reclaiming at. However,
3079 * if another caller entered the allocator slow path while kswapd
3080 * was awake, order will remain at the higher level
3081 */
dc83edd9 3082 *classzone_idx = end_zone;
0abdee2b 3083 return order;
1da177e4
LT
3084}
3085
dc83edd9 3086static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
f0bc0a60
KM
3087{
3088 long remaining = 0;
3089 DEFINE_WAIT(wait);
3090
3091 if (freezing(current) || kthread_should_stop())
3092 return;
3093
3094 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3095
3096 /* Try to sleep for a short interval */
5515061d 3097 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
f0bc0a60
KM
3098 remaining = schedule_timeout(HZ/10);
3099 finish_wait(&pgdat->kswapd_wait, &wait);
3100 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3101 }
3102
3103 /*
3104 * After a short sleep, check if it was a premature sleep. If not, then
3105 * go fully to sleep until explicitly woken up.
3106 */
5515061d 3107 if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
f0bc0a60
KM
3108 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3109
3110 /*
3111 * vmstat counters are not perfectly accurate and the estimated
3112 * value for counters such as NR_FREE_PAGES can deviate from the
3113 * true value by nr_online_cpus * threshold. To avoid the zone
3114 * watermarks being breached while under pressure, we reduce the
3115 * per-cpu vmstat threshold while kswapd is awake and restore
3116 * them before going back to sleep.
3117 */
3118 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
1c7e7f6c 3119
62997027
MG
3120 /*
3121 * Compaction records what page blocks it recently failed to
3122 * isolate pages from and skips them in the future scanning.
3123 * When kswapd is going to sleep, it is reasonable to assume
3124 * that pages and compaction may succeed so reset the cache.
3125 */
3126 reset_isolation_suitable(pgdat);
3127
1c7e7f6c
AK
3128 if (!kthread_should_stop())
3129 schedule();
3130
f0bc0a60
KM
3131 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3132 } else {
3133 if (remaining)
3134 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3135 else
3136 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3137 }
3138 finish_wait(&pgdat->kswapd_wait, &wait);
3139}
3140
1da177e4
LT
3141/*
3142 * The background pageout daemon, started as a kernel thread
4f98a2fe 3143 * from the init process.
1da177e4
LT
3144 *
3145 * This basically trickles out pages so that we have _some_
3146 * free memory available even if there is no other activity
3147 * that frees anything up. This is needed for things like routing
3148 * etc, where we otherwise might have all activity going on in
3149 * asynchronous contexts that cannot page things out.
3150 *
3151 * If there are applications that are active memory-allocators
3152 * (most normal use), this basically shouldn't matter.
3153 */
3154static int kswapd(void *p)
3155{
215ddd66 3156 unsigned long order, new_order;
d2ebd0f6 3157 unsigned balanced_order;
215ddd66 3158 int classzone_idx, new_classzone_idx;
d2ebd0f6 3159 int balanced_classzone_idx;
1da177e4
LT
3160 pg_data_t *pgdat = (pg_data_t*)p;
3161 struct task_struct *tsk = current;
f0bc0a60 3162
1da177e4
LT
3163 struct reclaim_state reclaim_state = {
3164 .reclaimed_slab = 0,
3165 };
a70f7302 3166 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
1da177e4 3167
cf40bd16
NP
3168 lockdep_set_current_reclaim_state(GFP_KERNEL);
3169
174596a0 3170 if (!cpumask_empty(cpumask))
c5f59f08 3171 set_cpus_allowed_ptr(tsk, cpumask);
1da177e4
LT
3172 current->reclaim_state = &reclaim_state;
3173
3174 /*
3175 * Tell the memory management that we're a "memory allocator",
3176 * and that if we need more memory we should get access to it
3177 * regardless (see "__alloc_pages()"). "kswapd" should
3178 * never get caught in the normal page freeing logic.
3179 *
3180 * (Kswapd normally doesn't need memory anyway, but sometimes
3181 * you need a small amount of memory in order to be able to
3182 * page out something else, and this flag essentially protects
3183 * us from recursively trying to free more memory as we're
3184 * trying to free the first piece of memory in the first place).
3185 */
930d9152 3186 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
83144186 3187 set_freezable();
1da177e4 3188
215ddd66 3189 order = new_order = 0;
d2ebd0f6 3190 balanced_order = 0;
215ddd66 3191 classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
d2ebd0f6 3192 balanced_classzone_idx = classzone_idx;
1da177e4 3193 for ( ; ; ) {
6f6313d4 3194 bool ret;
3e1d1d28 3195
215ddd66
MG
3196 /*
3197 * If the last balance_pgdat was unsuccessful it's unlikely a
3198 * new request of a similar or harder type will succeed soon
3199 * so consider going to sleep on the basis we reclaimed at
3200 */
d2ebd0f6
AS
3201 if (balanced_classzone_idx >= new_classzone_idx &&
3202 balanced_order == new_order) {
215ddd66
MG
3203 new_order = pgdat->kswapd_max_order;
3204 new_classzone_idx = pgdat->classzone_idx;
3205 pgdat->kswapd_max_order = 0;
3206 pgdat->classzone_idx = pgdat->nr_zones - 1;
3207 }
3208
99504748 3209 if (order < new_order || classzone_idx > new_classzone_idx) {
1da177e4
LT
3210 /*
3211 * Don't sleep if someone wants a larger 'order'
99504748 3212 * allocation or has tigher zone constraints
1da177e4
LT
3213 */
3214 order = new_order;
99504748 3215 classzone_idx = new_classzone_idx;
1da177e4 3216 } else {
d2ebd0f6
AS
3217 kswapd_try_to_sleep(pgdat, balanced_order,
3218 balanced_classzone_idx);
1da177e4 3219 order = pgdat->kswapd_max_order;
99504748 3220 classzone_idx = pgdat->classzone_idx;
f0dfcde0
AS
3221 new_order = order;
3222 new_classzone_idx = classzone_idx;
4d40502e 3223 pgdat->kswapd_max_order = 0;
215ddd66 3224 pgdat->classzone_idx = pgdat->nr_zones - 1;
1da177e4 3225 }
1da177e4 3226
8fe23e05
DR
3227 ret = try_to_freeze();
3228 if (kthread_should_stop())
3229 break;
3230
3231 /*
3232 * We can speed up thawing tasks if we don't call balance_pgdat
3233 * after returning from the refrigerator
3234 */
33906bc5
MG
3235 if (!ret) {
3236 trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
d2ebd0f6
AS
3237 balanced_classzone_idx = classzone_idx;
3238 balanced_order = balance_pgdat(pgdat, order,
3239 &balanced_classzone_idx);
33906bc5 3240 }
1da177e4 3241 }
b0a8cc58
TY
3242
3243 current->reclaim_state = NULL;
1da177e4
LT
3244 return 0;
3245}
3246
3247/*
3248 * A zone is low on free memory, so wake its kswapd task to service it.
3249 */
99504748 3250void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
1da177e4
LT
3251{
3252 pg_data_t *pgdat;
3253
f3fe6512 3254 if (!populated_zone(zone))
1da177e4
LT
3255 return;
3256
88f5acf8 3257 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
1da177e4 3258 return;
88f5acf8 3259 pgdat = zone->zone_pgdat;
99504748 3260 if (pgdat->kswapd_max_order < order) {
1da177e4 3261 pgdat->kswapd_max_order = order;
99504748
MG
3262 pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
3263 }
8d0986e2 3264 if (!waitqueue_active(&pgdat->kswapd_wait))
1da177e4 3265 return;
88f5acf8
MG
3266 if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
3267 return;
3268
3269 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
8d0986e2 3270 wake_up_interruptible(&pgdat->kswapd_wait);
1da177e4
LT
3271}
3272
adea02a1
WF
3273/*
3274 * The reclaimable count would be mostly accurate.
3275 * The less reclaimable pages may be
3276 * - mlocked pages, which will be moved to unevictable list when encountered
3277 * - mapped pages, which may require several travels to be reclaimed
3278 * - dirty pages, which is not "instantly" reclaimable
3279 */
3280unsigned long global_reclaimable_pages(void)
4f98a2fe 3281{
adea02a1
WF
3282 int nr;
3283
3284 nr = global_page_state(NR_ACTIVE_FILE) +
3285 global_page_state(NR_INACTIVE_FILE);
3286
ec8acf20 3287 if (get_nr_swap_pages() > 0)
adea02a1
WF
3288 nr += global_page_state(NR_ACTIVE_ANON) +
3289 global_page_state(NR_INACTIVE_ANON);
3290
3291 return nr;
3292}
3293
3294unsigned long zone_reclaimable_pages(struct zone *zone)
3295{
3296 int nr;
3297
3298 nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3299 zone_page_state(zone, NR_INACTIVE_FILE);
3300
ec8acf20 3301 if (get_nr_swap_pages() > 0)
adea02a1
WF
3302 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3303 zone_page_state(zone, NR_INACTIVE_ANON);
3304
3305 return nr;
4f98a2fe
RR
3306}
3307
c6f37f12 3308#ifdef CONFIG_HIBERNATION
1da177e4 3309/*
7b51755c 3310 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
d6277db4
RW
3311 * freed pages.
3312 *
3313 * Rather than trying to age LRUs the aim is to preserve the overall
3314 * LRU order by reclaiming preferentially
3315 * inactive > active > active referenced > active mapped
1da177e4 3316 */
7b51755c 3317unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
1da177e4 3318{
d6277db4 3319 struct reclaim_state reclaim_state;
d6277db4 3320 struct scan_control sc = {
7b51755c
KM
3321 .gfp_mask = GFP_HIGHUSER_MOVABLE,
3322 .may_swap = 1,
3323 .may_unmap = 1,
d6277db4 3324 .may_writepage = 1,
7b51755c
KM
3325 .nr_to_reclaim = nr_to_reclaim,
3326 .hibernation_mode = 1,
7b51755c 3327 .order = 0,
9e3b2f8c 3328 .priority = DEF_PRIORITY,
1da177e4 3329 };
a09ed5e0
YH
3330 struct shrink_control shrink = {
3331 .gfp_mask = sc.gfp_mask,
3332 };
3333 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7b51755c
KM
3334 struct task_struct *p = current;
3335 unsigned long nr_reclaimed;
1da177e4 3336
7b51755c
KM
3337 p->flags |= PF_MEMALLOC;
3338 lockdep_set_current_reclaim_state(sc.gfp_mask);
3339 reclaim_state.reclaimed_slab = 0;
3340 p->reclaim_state = &reclaim_state;
d6277db4 3341
a09ed5e0 3342 nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
d979677c 3343
7b51755c
KM
3344 p->reclaim_state = NULL;
3345 lockdep_clear_current_reclaim_state();
3346 p->flags &= ~PF_MEMALLOC;
d6277db4 3347
7b51755c 3348 return nr_reclaimed;
1da177e4 3349}
c6f37f12 3350#endif /* CONFIG_HIBERNATION */
1da177e4 3351
1da177e4
LT
3352/* It's optimal to keep kswapds on the same CPUs as their memory, but
3353 not required for correctness. So if the last cpu in a node goes
3354 away, we get changed to run anywhere: as the first one comes back,
3355 restore their cpu bindings. */
fcb35a9b
GKH
3356static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3357 void *hcpu)
1da177e4 3358{
58c0a4a7 3359 int nid;
1da177e4 3360
8bb78442 3361 if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
48fb2e24 3362 for_each_node_state(nid, N_MEMORY) {
c5f59f08 3363 pg_data_t *pgdat = NODE_DATA(nid);
a70f7302
RR
3364 const struct cpumask *mask;
3365
3366 mask = cpumask_of_node(pgdat->node_id);
c5f59f08 3367
3e597945 3368 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
1da177e4 3369 /* One of our CPUs online: restore mask */
c5f59f08 3370 set_cpus_allowed_ptr(pgdat->kswapd, mask);
1da177e4
LT
3371 }
3372 }
3373 return NOTIFY_OK;
3374}
1da177e4 3375
3218ae14
YG
3376/*
3377 * This kswapd start function will be called by init and node-hot-add.
3378 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
3379 */
3380int kswapd_run(int nid)
3381{
3382 pg_data_t *pgdat = NODE_DATA(nid);
3383 int ret = 0;
3384
3385 if (pgdat->kswapd)
3386 return 0;
3387
3388 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
3389 if (IS_ERR(pgdat->kswapd)) {
3390 /* failure at boot is fatal */
3391 BUG_ON(system_state == SYSTEM_BOOTING);
d5dc0ad9
GS
3392 pr_err("Failed to start kswapd on node %d\n", nid);
3393 ret = PTR_ERR(pgdat->kswapd);
d72515b8 3394 pgdat->kswapd = NULL;
3218ae14
YG
3395 }
3396 return ret;
3397}
3398
8fe23e05 3399/*
d8adde17
JL
3400 * Called by memory hotplug when all memory in a node is offlined. Caller must
3401 * hold lock_memory_hotplug().
8fe23e05
DR
3402 */
3403void kswapd_stop(int nid)
3404{
3405 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
3406
d8adde17 3407 if (kswapd) {
8fe23e05 3408 kthread_stop(kswapd);
d8adde17
JL
3409 NODE_DATA(nid)->kswapd = NULL;
3410 }
8fe23e05
DR
3411}
3412
1da177e4
LT
3413static int __init kswapd_init(void)
3414{
3218ae14 3415 int nid;
69e05944 3416
1da177e4 3417 swap_setup();
48fb2e24 3418 for_each_node_state(nid, N_MEMORY)
3218ae14 3419 kswapd_run(nid);
1da177e4
LT
3420 hotcpu_notifier(cpu_callback, 0);
3421 return 0;
3422}
3423
3424module_init(kswapd_init)
9eeff239
CL
3425
3426#ifdef CONFIG_NUMA
3427/*
3428 * Zone reclaim mode
3429 *
3430 * If non-zero call zone_reclaim when the number of free pages falls below
3431 * the watermarks.
9eeff239
CL
3432 */
3433int zone_reclaim_mode __read_mostly;
3434
1b2ffb78 3435#define RECLAIM_OFF 0
7d03431c 3436#define RECLAIM_ZONE (1<<0) /* Run shrink_inactive_list on the zone */
1b2ffb78
CL
3437#define RECLAIM_WRITE (1<<1) /* Writeout pages during reclaim */
3438#define RECLAIM_SWAP (1<<2) /* Swap pages out during reclaim */
3439
a92f7126
CL
3440/*
3441 * Priority for ZONE_RECLAIM. This determines the fraction of pages
3442 * of a node considered for each zone_reclaim. 4 scans 1/16th of
3443 * a zone.
3444 */
3445#define ZONE_RECLAIM_PRIORITY 4
3446
9614634f
CL
3447/*
3448 * Percentage of pages in a zone that must be unmapped for zone_reclaim to
3449 * occur.
3450 */
3451int sysctl_min_unmapped_ratio = 1;
3452
0ff38490
CL
3453/*
3454 * If the number of slab pages in a zone grows beyond this percentage then
3455 * slab reclaim needs to occur.
3456 */
3457int sysctl_min_slab_ratio = 5;
3458
90afa5de
MG
3459static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
3460{
3461 unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
3462 unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
3463 zone_page_state(zone, NR_ACTIVE_FILE);
3464
3465 /*
3466 * It's possible for there to be more file mapped pages than
3467 * accounted for by the pages on the file LRU lists because
3468 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
3469 */
3470 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
3471}
3472
3473/* Work out how many page cache pages we can reclaim in this reclaim_mode */
3474static long zone_pagecache_reclaimable(struct zone *zone)
3475{
3476 long nr_pagecache_reclaimable;
3477 long delta = 0;
3478
3479 /*
3480 * If RECLAIM_SWAP is set, then all file pages are considered
3481 * potentially reclaimable. Otherwise, we have to worry about
3482 * pages like swapcache and zone_unmapped_file_pages() provides
3483 * a better estimate
3484 */
3485 if (zone_reclaim_mode & RECLAIM_SWAP)
3486 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
3487 else
3488 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
3489
3490 /* If we can't clean pages, remove dirty pages from consideration */
3491 if (!(zone_reclaim_mode & RECLAIM_WRITE))
3492 delta += zone_page_state(zone, NR_FILE_DIRTY);
3493
3494 /* Watch for any possible underflows due to delta */
3495 if (unlikely(delta > nr_pagecache_reclaimable))
3496 delta = nr_pagecache_reclaimable;
3497
3498 return nr_pagecache_reclaimable - delta;
3499}
3500
9eeff239
CL
3501/*
3502 * Try to free up some pages from this zone through reclaim.
3503 */
179e9639 3504static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
9eeff239 3505{
7fb2d46d 3506 /* Minimum pages needed in order to stay on node */
69e05944 3507 const unsigned long nr_pages = 1 << order;
9eeff239
CL
3508 struct task_struct *p = current;
3509 struct reclaim_state reclaim_state;
179e9639
AM
3510 struct scan_control sc = {
3511 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
a6dc60f8 3512 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
2e2e4259 3513 .may_swap = 1,
62b726c1 3514 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
21caf2fc 3515 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
bd2f6199 3516 .order = order,
9e3b2f8c 3517 .priority = ZONE_RECLAIM_PRIORITY,
179e9639 3518 };
a09ed5e0
YH
3519 struct shrink_control shrink = {
3520 .gfp_mask = sc.gfp_mask,
3521 };
15748048 3522 unsigned long nr_slab_pages0, nr_slab_pages1;
9eeff239 3523
9eeff239 3524 cond_resched();
d4f7796e
CL
3525 /*
3526 * We need to be able to allocate from the reserves for RECLAIM_SWAP
3527 * and we also need to be able to write out pages for RECLAIM_WRITE
3528 * and RECLAIM_SWAP.
3529 */
3530 p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
76ca542d 3531 lockdep_set_current_reclaim_state(gfp_mask);
9eeff239
CL
3532 reclaim_state.reclaimed_slab = 0;
3533 p->reclaim_state = &reclaim_state;
c84db23c 3534
90afa5de 3535 if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
0ff38490
CL
3536 /*
3537 * Free memory by calling shrink zone with increasing
3538 * priorities until we have enough memory freed.
3539 */
0ff38490 3540 do {
9e3b2f8c
KK
3541 shrink_zone(zone, &sc);
3542 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
0ff38490 3543 }
c84db23c 3544
15748048
KM
3545 nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3546 if (nr_slab_pages0 > zone->min_slab_pages) {
2a16e3f4 3547 /*
7fb2d46d 3548 * shrink_slab() does not currently allow us to determine how
0ff38490
CL
3549 * many pages were freed in this zone. So we take the current
3550 * number of slab pages and shake the slab until it is reduced
3551 * by the same nr_pages that we used for reclaiming unmapped
3552 * pages.
2a16e3f4 3553 */
0ce3d744
DC
3554 nodes_clear(shrink.nodes_to_scan);
3555 node_set(zone_to_nid(zone), shrink.nodes_to_scan);
4dc4b3d9
KM
3556 for (;;) {
3557 unsigned long lru_pages = zone_reclaimable_pages(zone);
3558
3559 /* No reclaimable slab or very low memory pressure */
1495f230 3560 if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
4dc4b3d9
KM
3561 break;
3562
3563 /* Freed enough memory */
3564 nr_slab_pages1 = zone_page_state(zone,
3565 NR_SLAB_RECLAIMABLE);
3566 if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
3567 break;
3568 }
83e33a47
CL
3569
3570 /*
3571 * Update nr_reclaimed by the number of slab pages we
3572 * reclaimed from this zone.
3573 */
15748048
KM
3574 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3575 if (nr_slab_pages1 < nr_slab_pages0)
3576 sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
2a16e3f4
CL
3577 }
3578
9eeff239 3579 p->reclaim_state = NULL;
d4f7796e 3580 current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
76ca542d 3581 lockdep_clear_current_reclaim_state();
a79311c1 3582 return sc.nr_reclaimed >= nr_pages;
9eeff239 3583}
179e9639
AM
3584
3585int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3586{
179e9639 3587 int node_id;
d773ed6b 3588 int ret;
179e9639
AM
3589
3590 /*
0ff38490
CL
3591 * Zone reclaim reclaims unmapped file backed pages and
3592 * slab pages if we are over the defined limits.
34aa1330 3593 *
9614634f
CL
3594 * A small portion of unmapped file backed pages is needed for
3595 * file I/O otherwise pages read by file I/O will be immediately
3596 * thrown out if the zone is overallocated. So we do not reclaim
3597 * if less than a specified percentage of the zone is used by
3598 * unmapped file backed pages.
179e9639 3599 */
90afa5de
MG
3600 if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
3601 zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
fa5e084e 3602 return ZONE_RECLAIM_FULL;
179e9639 3603
93e4a89a 3604 if (zone->all_unreclaimable)
fa5e084e 3605 return ZONE_RECLAIM_FULL;
d773ed6b 3606
179e9639 3607 /*
d773ed6b 3608 * Do not scan if the allocation should not be delayed.
179e9639 3609 */
d773ed6b 3610 if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
fa5e084e 3611 return ZONE_RECLAIM_NOSCAN;
179e9639
AM
3612
3613 /*
3614 * Only run zone reclaim on the local zone or on zones that do not
3615 * have associated processors. This will favor the local processor
3616 * over remote processors and spread off node memory allocations
3617 * as wide as possible.
3618 */
89fa3024 3619 node_id = zone_to_nid(zone);
37c0708d 3620 if (node_state(node_id, N_CPU) && node_id != numa_node_id())
fa5e084e 3621 return ZONE_RECLAIM_NOSCAN;
d773ed6b
DR
3622
3623 if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
fa5e084e
MG
3624 return ZONE_RECLAIM_NOSCAN;
3625
d773ed6b
DR
3626 ret = __zone_reclaim(zone, gfp_mask, order);
3627 zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3628
24cf7251
MG
3629 if (!ret)
3630 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
3631
d773ed6b 3632 return ret;
179e9639 3633}
9eeff239 3634#endif
894bc310 3635
894bc310
LS
3636/*
3637 * page_evictable - test whether a page is evictable
3638 * @page: the page to test
894bc310
LS
3639 *
3640 * Test whether page is evictable--i.e., should be placed on active/inactive
39b5f29a 3641 * lists vs unevictable list.
894bc310
LS
3642 *
3643 * Reasons page might not be evictable:
ba9ddf49 3644 * (1) page's mapping marked unevictable
b291f000 3645 * (2) page is part of an mlocked VMA
ba9ddf49 3646 *
894bc310 3647 */
39b5f29a 3648int page_evictable(struct page *page)
894bc310 3649{
39b5f29a 3650 return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
894bc310 3651}
89e004ea 3652
85046579 3653#ifdef CONFIG_SHMEM
89e004ea 3654/**
24513264
HD
3655 * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
3656 * @pages: array of pages to check
3657 * @nr_pages: number of pages to check
89e004ea 3658 *
24513264 3659 * Checks pages for evictability and moves them to the appropriate lru list.
85046579
HD
3660 *
3661 * This function is only used for SysV IPC SHM_UNLOCK.
89e004ea 3662 */
24513264 3663void check_move_unevictable_pages(struct page **pages, int nr_pages)
89e004ea 3664{
925b7673 3665 struct lruvec *lruvec;
24513264
HD
3666 struct zone *zone = NULL;
3667 int pgscanned = 0;
3668 int pgrescued = 0;
3669 int i;
89e004ea 3670
24513264
HD
3671 for (i = 0; i < nr_pages; i++) {
3672 struct page *page = pages[i];
3673 struct zone *pagezone;
89e004ea 3674
24513264
HD
3675 pgscanned++;
3676 pagezone = page_zone(page);
3677 if (pagezone != zone) {
3678 if (zone)
3679 spin_unlock_irq(&zone->lru_lock);
3680 zone = pagezone;
3681 spin_lock_irq(&zone->lru_lock);
3682 }
fa9add64 3683 lruvec = mem_cgroup_page_lruvec(page, zone);
89e004ea 3684
24513264
HD
3685 if (!PageLRU(page) || !PageUnevictable(page))
3686 continue;
89e004ea 3687
39b5f29a 3688 if (page_evictable(page)) {
24513264
HD
3689 enum lru_list lru = page_lru_base_type(page);
3690
3691 VM_BUG_ON(PageActive(page));
3692 ClearPageUnevictable(page);
fa9add64
HD
3693 del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3694 add_page_to_lru_list(page, lruvec, lru);
24513264 3695 pgrescued++;
89e004ea 3696 }
24513264 3697 }
89e004ea 3698
24513264
HD
3699 if (zone) {
3700 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
3701 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3702 spin_unlock_irq(&zone->lru_lock);
89e004ea 3703 }
89e004ea 3704}
85046579 3705#endif /* CONFIG_SHMEM */
af936a16 3706
264e56d8 3707static void warn_scan_unevictable_pages(void)
af936a16 3708{
264e56d8 3709 printk_once(KERN_WARNING
25bd91bd 3710 "%s: The scan_unevictable_pages sysctl/node-interface has been "
264e56d8 3711 "disabled for lack of a legitimate use case. If you have "
25bd91bd
KM
3712 "one, please send an email to linux-mm@kvack.org.\n",
3713 current->comm);
af936a16
LS
3714}
3715
3716/*
3717 * scan_unevictable_pages [vm] sysctl handler. On demand re-scan of
3718 * all nodes' unevictable lists for evictable pages
3719 */
3720unsigned long scan_unevictable_pages;
3721
3722int scan_unevictable_handler(struct ctl_table *table, int write,
8d65af78 3723 void __user *buffer,
af936a16
LS
3724 size_t *length, loff_t *ppos)
3725{
264e56d8 3726 warn_scan_unevictable_pages();
8d65af78 3727 proc_doulongvec_minmax(table, write, buffer, length, ppos);
af936a16
LS
3728 scan_unevictable_pages = 0;
3729 return 0;
3730}
3731
e4455abb 3732#ifdef CONFIG_NUMA
af936a16
LS
3733/*
3734 * per node 'scan_unevictable_pages' attribute. On demand re-scan of
3735 * a specified node's per zone unevictable lists for evictable pages.
3736 */
3737
10fbcf4c
KS
3738static ssize_t read_scan_unevictable_node(struct device *dev,
3739 struct device_attribute *attr,
af936a16
LS
3740 char *buf)
3741{
264e56d8 3742 warn_scan_unevictable_pages();
af936a16
LS
3743 return sprintf(buf, "0\n"); /* always zero; should fit... */
3744}
3745
10fbcf4c
KS
3746static ssize_t write_scan_unevictable_node(struct device *dev,
3747 struct device_attribute *attr,
af936a16
LS
3748 const char *buf, size_t count)
3749{
264e56d8 3750 warn_scan_unevictable_pages();
af936a16
LS
3751 return 1;
3752}
3753
3754
10fbcf4c 3755static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
af936a16
LS
3756 read_scan_unevictable_node,
3757 write_scan_unevictable_node);
3758
3759int scan_unevictable_register_node(struct node *node)
3760{
10fbcf4c 3761 return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
af936a16
LS
3762}
3763
3764void scan_unevictable_unregister_node(struct node *node)
3765{
10fbcf4c 3766 device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
af936a16 3767}
e4455abb 3768#endif