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