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