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