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