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