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