]> pilppa.org Git - linux-2.6-omap-h63xx.git/blob - mm/vmscan.c
[PATCH] writeback: fix range handling
[linux-2.6-omap-h63xx.git] / mm / vmscan.c
1 /*
2  *  linux/mm/vmscan.c
3  *
4  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
5  *
6  *  Swap reorganised 29.12.95, Stephen Tweedie.
7  *  kswapd added: 7.1.96  sct
8  *  Removed kswapd_ctl limits, and swap out as many pages as needed
9  *  to bring the system back to freepages.high: 2.4.97, Rik van Riel.
10  *  Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
11  *  Multiqueue VM started 5.8.00, Rik van Riel.
12  */
13
14 #include <linux/mm.h>
15 #include <linux/module.h>
16 #include <linux/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/file.h>
23 #include <linux/writeback.h>
24 #include <linux/blkdev.h>
25 #include <linux/buffer_head.h>  /* for try_to_release_page(),
26                                         buffer_heads_over_limit */
27 #include <linux/mm_inline.h>
28 #include <linux/pagevec.h>
29 #include <linux/backing-dev.h>
30 #include <linux/rmap.h>
31 #include <linux/topology.h>
32 #include <linux/cpu.h>
33 #include <linux/cpuset.h>
34 #include <linux/notifier.h>
35 #include <linux/rwsem.h>
36 #include <linux/delay.h>
37
38 #include <asm/tlbflush.h>
39 #include <asm/div64.h>
40
41 #include <linux/swapops.h>
42
43 #include "internal.h"
44
45 struct scan_control {
46         /* Incremented by the number of inactive pages that were scanned */
47         unsigned long nr_scanned;
48
49         unsigned long nr_mapped;        /* From page_state */
50
51         /* This context's GFP mask */
52         gfp_t gfp_mask;
53
54         int may_writepage;
55
56         /* Can pages be swapped as part of reclaim? */
57         int may_swap;
58
59         /* This context's SWAP_CLUSTER_MAX. If freeing memory for
60          * suspend, we effectively ignore SWAP_CLUSTER_MAX.
61          * In this context, it doesn't matter that we scan the
62          * whole list at once. */
63         int swap_cluster_max;
64
65         int swappiness;
66 };
67
68 /*
69  * The list of shrinker callbacks used by to apply pressure to
70  * ageable caches.
71  */
72 struct shrinker {
73         shrinker_t              shrinker;
74         struct list_head        list;
75         int                     seeks;  /* seeks to recreate an obj */
76         long                    nr;     /* objs pending delete */
77 };
78
79 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
80
81 #ifdef ARCH_HAS_PREFETCH
82 #define prefetch_prev_lru_page(_page, _base, _field)                    \
83         do {                                                            \
84                 if ((_page)->lru.prev != _base) {                       \
85                         struct page *prev;                              \
86                                                                         \
87                         prev = lru_to_page(&(_page->lru));              \
88                         prefetch(&prev->_field);                        \
89                 }                                                       \
90         } while (0)
91 #else
92 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
93 #endif
94
95 #ifdef ARCH_HAS_PREFETCHW
96 #define prefetchw_prev_lru_page(_page, _base, _field)                   \
97         do {                                                            \
98                 if ((_page)->lru.prev != _base) {                       \
99                         struct page *prev;                              \
100                                                                         \
101                         prev = lru_to_page(&(_page->lru));              \
102                         prefetchw(&prev->_field);                       \
103                 }                                                       \
104         } while (0)
105 #else
106 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
107 #endif
108
109 /*
110  * From 0 .. 100.  Higher means more swappy.
111  */
112 int vm_swappiness = 60;
113 static long total_memory;
114
115 static LIST_HEAD(shrinker_list);
116 static DECLARE_RWSEM(shrinker_rwsem);
117
118 /*
119  * Add a shrinker callback to be called from the vm
120  */
121 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
122 {
123         struct shrinker *shrinker;
124
125         shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
126         if (shrinker) {
127                 shrinker->shrinker = theshrinker;
128                 shrinker->seeks = seeks;
129                 shrinker->nr = 0;
130                 down_write(&shrinker_rwsem);
131                 list_add_tail(&shrinker->list, &shrinker_list);
132                 up_write(&shrinker_rwsem);
133         }
134         return shrinker;
135 }
136 EXPORT_SYMBOL(set_shrinker);
137
138 /*
139  * Remove one
140  */
141 void remove_shrinker(struct shrinker *shrinker)
142 {
143         down_write(&shrinker_rwsem);
144         list_del(&shrinker->list);
145         up_write(&shrinker_rwsem);
146         kfree(shrinker);
147 }
148 EXPORT_SYMBOL(remove_shrinker);
149
150 #define SHRINK_BATCH 128
151 /*
152  * Call the shrink functions to age shrinkable caches
153  *
154  * Here we assume it costs one seek to replace a lru page and that it also
155  * takes a seek to recreate a cache object.  With this in mind we age equal
156  * percentages of the lru and ageable caches.  This should balance the seeks
157  * generated by these structures.
158  *
159  * If the vm encounted mapped pages on the LRU it increase the pressure on
160  * slab to avoid swapping.
161  *
162  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
163  *
164  * `lru_pages' represents the number of on-LRU pages in all the zones which
165  * are eligible for the caller's allocation attempt.  It is used for balancing
166  * slab reclaim versus page reclaim.
167  *
168  * Returns the number of slab objects which we shrunk.
169  */
170 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
171                         unsigned long lru_pages)
172 {
173         struct shrinker *shrinker;
174         unsigned long ret = 0;
175
176         if (scanned == 0)
177                 scanned = SWAP_CLUSTER_MAX;
178
179         if (!down_read_trylock(&shrinker_rwsem))
180                 return 1;       /* Assume we'll be able to shrink next time */
181
182         list_for_each_entry(shrinker, &shrinker_list, list) {
183                 unsigned long long delta;
184                 unsigned long total_scan;
185                 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
186
187                 delta = (4 * scanned) / shrinker->seeks;
188                 delta *= max_pass;
189                 do_div(delta, lru_pages + 1);
190                 shrinker->nr += delta;
191                 if (shrinker->nr < 0) {
192                         printk(KERN_ERR "%s: nr=%ld\n",
193                                         __FUNCTION__, shrinker->nr);
194                         shrinker->nr = max_pass;
195                 }
196
197                 /*
198                  * Avoid risking looping forever due to too large nr value:
199                  * never try to free more than twice the estimate number of
200                  * freeable entries.
201                  */
202                 if (shrinker->nr > max_pass * 2)
203                         shrinker->nr = max_pass * 2;
204
205                 total_scan = shrinker->nr;
206                 shrinker->nr = 0;
207
208                 while (total_scan >= SHRINK_BATCH) {
209                         long this_scan = SHRINK_BATCH;
210                         int shrink_ret;
211                         int nr_before;
212
213                         nr_before = (*shrinker->shrinker)(0, gfp_mask);
214                         shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
215                         if (shrink_ret == -1)
216                                 break;
217                         if (shrink_ret < nr_before)
218                                 ret += nr_before - shrink_ret;
219                         mod_page_state(slabs_scanned, this_scan);
220                         total_scan -= this_scan;
221
222                         cond_resched();
223                 }
224
225                 shrinker->nr += total_scan;
226         }
227         up_read(&shrinker_rwsem);
228         return ret;
229 }
230
231 /* Called without lock on whether page is mapped, so answer is unstable */
232 static inline int page_mapping_inuse(struct page *page)
233 {
234         struct address_space *mapping;
235
236         /* Page is in somebody's page tables. */
237         if (page_mapped(page))
238                 return 1;
239
240         /* Be more reluctant to reclaim swapcache than pagecache */
241         if (PageSwapCache(page))
242                 return 1;
243
244         mapping = page_mapping(page);
245         if (!mapping)
246                 return 0;
247
248         /* File is mmap'd by somebody? */
249         return mapping_mapped(mapping);
250 }
251
252 static inline int is_page_cache_freeable(struct page *page)
253 {
254         return page_count(page) - !!PagePrivate(page) == 2;
255 }
256
257 static int may_write_to_queue(struct backing_dev_info *bdi)
258 {
259         if (current->flags & PF_SWAPWRITE)
260                 return 1;
261         if (!bdi_write_congested(bdi))
262                 return 1;
263         if (bdi == current->backing_dev_info)
264                 return 1;
265         return 0;
266 }
267
268 /*
269  * We detected a synchronous write error writing a page out.  Probably
270  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
271  * fsync(), msync() or close().
272  *
273  * The tricky part is that after writepage we cannot touch the mapping: nothing
274  * prevents it from being freed up.  But we have a ref on the page and once
275  * that page is locked, the mapping is pinned.
276  *
277  * We're allowed to run sleeping lock_page() here because we know the caller has
278  * __GFP_FS.
279  */
280 static void handle_write_error(struct address_space *mapping,
281                                 struct page *page, int error)
282 {
283         lock_page(page);
284         if (page_mapping(page) == mapping) {
285                 if (error == -ENOSPC)
286                         set_bit(AS_ENOSPC, &mapping->flags);
287                 else
288                         set_bit(AS_EIO, &mapping->flags);
289         }
290         unlock_page(page);
291 }
292
293 /*
294  * pageout is called by shrink_page_list() for each dirty page.
295  * Calls ->writepage().
296  */
297 pageout_t pageout(struct page *page, struct address_space *mapping)
298 {
299         /*
300          * If the page is dirty, only perform writeback if that write
301          * will be non-blocking.  To prevent this allocation from being
302          * stalled by pagecache activity.  But note that there may be
303          * stalls if we need to run get_block().  We could test
304          * PagePrivate for that.
305          *
306          * If this process is currently in generic_file_write() against
307          * this page's queue, we can perform writeback even if that
308          * will block.
309          *
310          * If the page is swapcache, write it back even if that would
311          * block, for some throttling. This happens by accident, because
312          * swap_backing_dev_info is bust: it doesn't reflect the
313          * congestion state of the swapdevs.  Easy to fix, if needed.
314          * See swapfile.c:page_queue_congested().
315          */
316         if (!is_page_cache_freeable(page))
317                 return PAGE_KEEP;
318         if (!mapping) {
319                 /*
320                  * Some data journaling orphaned pages can have
321                  * page->mapping == NULL while being dirty with clean buffers.
322                  */
323                 if (PagePrivate(page)) {
324                         if (try_to_free_buffers(page)) {
325                                 ClearPageDirty(page);
326                                 printk("%s: orphaned page\n", __FUNCTION__);
327                                 return PAGE_CLEAN;
328                         }
329                 }
330                 return PAGE_KEEP;
331         }
332         if (mapping->a_ops->writepage == NULL)
333                 return PAGE_ACTIVATE;
334         if (!may_write_to_queue(mapping->backing_dev_info))
335                 return PAGE_KEEP;
336
337         if (clear_page_dirty_for_io(page)) {
338                 int res;
339                 struct writeback_control wbc = {
340                         .sync_mode = WB_SYNC_NONE,
341                         .nr_to_write = SWAP_CLUSTER_MAX,
342                         .range_start = 0,
343                         .range_end = LLONG_MAX,
344                         .nonblocking = 1,
345                         .for_reclaim = 1,
346                 };
347
348                 SetPageReclaim(page);
349                 res = mapping->a_ops->writepage(page, &wbc);
350                 if (res < 0)
351                         handle_write_error(mapping, page, res);
352                 if (res == AOP_WRITEPAGE_ACTIVATE) {
353                         ClearPageReclaim(page);
354                         return PAGE_ACTIVATE;
355                 }
356                 if (!PageWriteback(page)) {
357                         /* synchronous write or broken a_ops? */
358                         ClearPageReclaim(page);
359                 }
360
361                 return PAGE_SUCCESS;
362         }
363
364         return PAGE_CLEAN;
365 }
366
367 int remove_mapping(struct address_space *mapping, struct page *page)
368 {
369         if (!mapping)
370                 return 0;               /* truncate got there first */
371
372         write_lock_irq(&mapping->tree_lock);
373
374         /*
375          * The non-racy check for busy page.  It is critical to check
376          * PageDirty _after_ making sure that the page is freeable and
377          * not in use by anybody.       (pagecache + us == 2)
378          */
379         if (unlikely(page_count(page) != 2))
380                 goto cannot_free;
381         smp_rmb();
382         if (unlikely(PageDirty(page)))
383                 goto cannot_free;
384
385         if (PageSwapCache(page)) {
386                 swp_entry_t swap = { .val = page_private(page) };
387                 __delete_from_swap_cache(page);
388                 write_unlock_irq(&mapping->tree_lock);
389                 swap_free(swap);
390                 __put_page(page);       /* The pagecache ref */
391                 return 1;
392         }
393
394         __remove_from_page_cache(page);
395         write_unlock_irq(&mapping->tree_lock);
396         __put_page(page);
397         return 1;
398
399 cannot_free:
400         write_unlock_irq(&mapping->tree_lock);
401         return 0;
402 }
403
404 /*
405  * shrink_page_list() returns the number of reclaimed pages
406  */
407 static unsigned long shrink_page_list(struct list_head *page_list,
408                                         struct scan_control *sc)
409 {
410         LIST_HEAD(ret_pages);
411         struct pagevec freed_pvec;
412         int pgactivate = 0;
413         unsigned long nr_reclaimed = 0;
414
415         cond_resched();
416
417         pagevec_init(&freed_pvec, 1);
418         while (!list_empty(page_list)) {
419                 struct address_space *mapping;
420                 struct page *page;
421                 int may_enter_fs;
422                 int referenced;
423
424                 cond_resched();
425
426                 page = lru_to_page(page_list);
427                 list_del(&page->lru);
428
429                 if (TestSetPageLocked(page))
430                         goto keep;
431
432                 BUG_ON(PageActive(page));
433
434                 sc->nr_scanned++;
435
436                 if (!sc->may_swap && page_mapped(page))
437                         goto keep_locked;
438
439                 /* Double the slab pressure for mapped and swapcache pages */
440                 if (page_mapped(page) || PageSwapCache(page))
441                         sc->nr_scanned++;
442
443                 if (PageWriteback(page))
444                         goto keep_locked;
445
446                 referenced = page_referenced(page, 1);
447                 /* In active use or really unfreeable?  Activate it. */
448                 if (referenced && page_mapping_inuse(page))
449                         goto activate_locked;
450
451 #ifdef CONFIG_SWAP
452                 /*
453                  * Anonymous process memory has backing store?
454                  * Try to allocate it some swap space here.
455                  */
456                 if (PageAnon(page) && !PageSwapCache(page))
457                         if (!add_to_swap(page, GFP_ATOMIC))
458                                 goto activate_locked;
459 #endif /* CONFIG_SWAP */
460
461                 mapping = page_mapping(page);
462                 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
463                         (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
464
465                 /*
466                  * The page is mapped into the page tables of one or more
467                  * processes. Try to unmap it here.
468                  */
469                 if (page_mapped(page) && mapping) {
470                         switch (try_to_unmap(page, 0)) {
471                         case SWAP_FAIL:
472                                 goto activate_locked;
473                         case SWAP_AGAIN:
474                                 goto keep_locked;
475                         case SWAP_SUCCESS:
476                                 ; /* try to free the page below */
477                         }
478                 }
479
480                 if (PageDirty(page)) {
481                         if (referenced)
482                                 goto keep_locked;
483                         if (!may_enter_fs)
484                                 goto keep_locked;
485                         if (!sc->may_writepage)
486                                 goto keep_locked;
487
488                         /* Page is dirty, try to write it out here */
489                         switch(pageout(page, mapping)) {
490                         case PAGE_KEEP:
491                                 goto keep_locked;
492                         case PAGE_ACTIVATE:
493                                 goto activate_locked;
494                         case PAGE_SUCCESS:
495                                 if (PageWriteback(page) || PageDirty(page))
496                                         goto keep;
497                                 /*
498                                  * A synchronous write - probably a ramdisk.  Go
499                                  * ahead and try to reclaim the page.
500                                  */
501                                 if (TestSetPageLocked(page))
502                                         goto keep;
503                                 if (PageDirty(page) || PageWriteback(page))
504                                         goto keep_locked;
505                                 mapping = page_mapping(page);
506                         case PAGE_CLEAN:
507                                 ; /* try to free the page below */
508                         }
509                 }
510
511                 /*
512                  * If the page has buffers, try to free the buffer mappings
513                  * associated with this page. If we succeed we try to free
514                  * the page as well.
515                  *
516                  * We do this even if the page is PageDirty().
517                  * try_to_release_page() does not perform I/O, but it is
518                  * possible for a page to have PageDirty set, but it is actually
519                  * clean (all its buffers are clean).  This happens if the
520                  * buffers were written out directly, with submit_bh(). ext3
521                  * will do this, as well as the blockdev mapping. 
522                  * try_to_release_page() will discover that cleanness and will
523                  * drop the buffers and mark the page clean - it can be freed.
524                  *
525                  * Rarely, pages can have buffers and no ->mapping.  These are
526                  * the pages which were not successfully invalidated in
527                  * truncate_complete_page().  We try to drop those buffers here
528                  * and if that worked, and the page is no longer mapped into
529                  * process address space (page_count == 1) it can be freed.
530                  * Otherwise, leave the page on the LRU so it is swappable.
531                  */
532                 if (PagePrivate(page)) {
533                         if (!try_to_release_page(page, sc->gfp_mask))
534                                 goto activate_locked;
535                         if (!mapping && page_count(page) == 1)
536                                 goto free_it;
537                 }
538
539                 if (!remove_mapping(mapping, page))
540                         goto keep_locked;
541
542 free_it:
543                 unlock_page(page);
544                 nr_reclaimed++;
545                 if (!pagevec_add(&freed_pvec, page))
546                         __pagevec_release_nonlru(&freed_pvec);
547                 continue;
548
549 activate_locked:
550                 SetPageActive(page);
551                 pgactivate++;
552 keep_locked:
553                 unlock_page(page);
554 keep:
555                 list_add(&page->lru, &ret_pages);
556                 BUG_ON(PageLRU(page));
557         }
558         list_splice(&ret_pages, page_list);
559         if (pagevec_count(&freed_pvec))
560                 __pagevec_release_nonlru(&freed_pvec);
561         mod_page_state(pgactivate, pgactivate);
562         return nr_reclaimed;
563 }
564
565 /*
566  * zone->lru_lock is heavily contended.  Some of the functions that
567  * shrink the lists perform better by taking out a batch of pages
568  * and working on them outside the LRU lock.
569  *
570  * For pagecache intensive workloads, this function is the hottest
571  * spot in the kernel (apart from copy_*_user functions).
572  *
573  * Appropriate locks must be held before calling this function.
574  *
575  * @nr_to_scan: The number of pages to look through on the list.
576  * @src:        The LRU list to pull pages off.
577  * @dst:        The temp list to put pages on to.
578  * @scanned:    The number of pages that were scanned.
579  *
580  * returns how many pages were moved onto *@dst.
581  */
582 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
583                 struct list_head *src, struct list_head *dst,
584                 unsigned long *scanned)
585 {
586         unsigned long nr_taken = 0;
587         struct page *page;
588         unsigned long scan;
589
590         for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
591                 struct list_head *target;
592                 page = lru_to_page(src);
593                 prefetchw_prev_lru_page(page, src, flags);
594
595                 BUG_ON(!PageLRU(page));
596
597                 list_del(&page->lru);
598                 target = src;
599                 if (likely(get_page_unless_zero(page))) {
600                         /*
601                          * Be careful not to clear PageLRU until after we're
602                          * sure the page is not being freed elsewhere -- the
603                          * page release code relies on it.
604                          */
605                         ClearPageLRU(page);
606                         target = dst;
607                         nr_taken++;
608                 } /* else it is being freed elsewhere */
609
610                 list_add(&page->lru, target);
611         }
612
613         *scanned = scan;
614         return nr_taken;
615 }
616
617 /*
618  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
619  * of reclaimed pages
620  */
621 static unsigned long shrink_inactive_list(unsigned long max_scan,
622                                 struct zone *zone, struct scan_control *sc)
623 {
624         LIST_HEAD(page_list);
625         struct pagevec pvec;
626         unsigned long nr_scanned = 0;
627         unsigned long nr_reclaimed = 0;
628
629         pagevec_init(&pvec, 1);
630
631         lru_add_drain();
632         spin_lock_irq(&zone->lru_lock);
633         do {
634                 struct page *page;
635                 unsigned long nr_taken;
636                 unsigned long nr_scan;
637                 unsigned long nr_freed;
638
639                 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
640                                              &zone->inactive_list,
641                                              &page_list, &nr_scan);
642                 zone->nr_inactive -= nr_taken;
643                 zone->pages_scanned += nr_scan;
644                 spin_unlock_irq(&zone->lru_lock);
645
646                 nr_scanned += nr_scan;
647                 nr_freed = shrink_page_list(&page_list, sc);
648                 nr_reclaimed += nr_freed;
649                 local_irq_disable();
650                 if (current_is_kswapd()) {
651                         __mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
652                         __mod_page_state(kswapd_steal, nr_freed);
653                 } else
654                         __mod_page_state_zone(zone, pgscan_direct, nr_scan);
655                 __mod_page_state_zone(zone, pgsteal, nr_freed);
656
657                 if (nr_taken == 0)
658                         goto done;
659
660                 spin_lock(&zone->lru_lock);
661                 /*
662                  * Put back any unfreeable pages.
663                  */
664                 while (!list_empty(&page_list)) {
665                         page = lru_to_page(&page_list);
666                         BUG_ON(PageLRU(page));
667                         SetPageLRU(page);
668                         list_del(&page->lru);
669                         if (PageActive(page))
670                                 add_page_to_active_list(zone, page);
671                         else
672                                 add_page_to_inactive_list(zone, page);
673                         if (!pagevec_add(&pvec, page)) {
674                                 spin_unlock_irq(&zone->lru_lock);
675                                 __pagevec_release(&pvec);
676                                 spin_lock_irq(&zone->lru_lock);
677                         }
678                 }
679         } while (nr_scanned < max_scan);
680         spin_unlock(&zone->lru_lock);
681 done:
682         local_irq_enable();
683         pagevec_release(&pvec);
684         return nr_reclaimed;
685 }
686
687 /*
688  * This moves pages from the active list to the inactive list.
689  *
690  * We move them the other way if the page is referenced by one or more
691  * processes, from rmap.
692  *
693  * If the pages are mostly unmapped, the processing is fast and it is
694  * appropriate to hold zone->lru_lock across the whole operation.  But if
695  * the pages are mapped, the processing is slow (page_referenced()) so we
696  * should drop zone->lru_lock around each page.  It's impossible to balance
697  * this, so instead we remove the pages from the LRU while processing them.
698  * It is safe to rely on PG_active against the non-LRU pages in here because
699  * nobody will play with that bit on a non-LRU page.
700  *
701  * The downside is that we have to touch page->_count against each page.
702  * But we had to alter page->flags anyway.
703  */
704 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
705                                 struct scan_control *sc)
706 {
707         unsigned long pgmoved;
708         int pgdeactivate = 0;
709         unsigned long pgscanned;
710         LIST_HEAD(l_hold);      /* The pages which were snipped off */
711         LIST_HEAD(l_inactive);  /* Pages to go onto the inactive_list */
712         LIST_HEAD(l_active);    /* Pages to go onto the active_list */
713         struct page *page;
714         struct pagevec pvec;
715         int reclaim_mapped = 0;
716
717         if (sc->may_swap) {
718                 long mapped_ratio;
719                 long distress;
720                 long swap_tendency;
721
722                 /*
723                  * `distress' is a measure of how much trouble we're having
724                  * reclaiming pages.  0 -> no problems.  100 -> great trouble.
725                  */
726                 distress = 100 >> zone->prev_priority;
727
728                 /*
729                  * The point of this algorithm is to decide when to start
730                  * reclaiming mapped memory instead of just pagecache.  Work out
731                  * how much memory
732                  * is mapped.
733                  */
734                 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
735
736                 /*
737                  * Now decide how much we really want to unmap some pages.  The
738                  * mapped ratio is downgraded - just because there's a lot of
739                  * mapped memory doesn't necessarily mean that page reclaim
740                  * isn't succeeding.
741                  *
742                  * The distress ratio is important - we don't want to start
743                  * going oom.
744                  *
745                  * A 100% value of vm_swappiness overrides this algorithm
746                  * altogether.
747                  */
748                 swap_tendency = mapped_ratio / 2 + distress + sc->swappiness;
749
750                 /*
751                  * Now use this metric to decide whether to start moving mapped
752                  * memory onto the inactive list.
753                  */
754                 if (swap_tendency >= 100)
755                         reclaim_mapped = 1;
756         }
757
758         lru_add_drain();
759         spin_lock_irq(&zone->lru_lock);
760         pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
761                                     &l_hold, &pgscanned);
762         zone->pages_scanned += pgscanned;
763         zone->nr_active -= pgmoved;
764         spin_unlock_irq(&zone->lru_lock);
765
766         while (!list_empty(&l_hold)) {
767                 cond_resched();
768                 page = lru_to_page(&l_hold);
769                 list_del(&page->lru);
770                 if (page_mapped(page)) {
771                         if (!reclaim_mapped ||
772                             (total_swap_pages == 0 && PageAnon(page)) ||
773                             page_referenced(page, 0)) {
774                                 list_add(&page->lru, &l_active);
775                                 continue;
776                         }
777                 }
778                 list_add(&page->lru, &l_inactive);
779         }
780
781         pagevec_init(&pvec, 1);
782         pgmoved = 0;
783         spin_lock_irq(&zone->lru_lock);
784         while (!list_empty(&l_inactive)) {
785                 page = lru_to_page(&l_inactive);
786                 prefetchw_prev_lru_page(page, &l_inactive, flags);
787                 BUG_ON(PageLRU(page));
788                 SetPageLRU(page);
789                 BUG_ON(!PageActive(page));
790                 ClearPageActive(page);
791
792                 list_move(&page->lru, &zone->inactive_list);
793                 pgmoved++;
794                 if (!pagevec_add(&pvec, page)) {
795                         zone->nr_inactive += pgmoved;
796                         spin_unlock_irq(&zone->lru_lock);
797                         pgdeactivate += pgmoved;
798                         pgmoved = 0;
799                         if (buffer_heads_over_limit)
800                                 pagevec_strip(&pvec);
801                         __pagevec_release(&pvec);
802                         spin_lock_irq(&zone->lru_lock);
803                 }
804         }
805         zone->nr_inactive += pgmoved;
806         pgdeactivate += pgmoved;
807         if (buffer_heads_over_limit) {
808                 spin_unlock_irq(&zone->lru_lock);
809                 pagevec_strip(&pvec);
810                 spin_lock_irq(&zone->lru_lock);
811         }
812
813         pgmoved = 0;
814         while (!list_empty(&l_active)) {
815                 page = lru_to_page(&l_active);
816                 prefetchw_prev_lru_page(page, &l_active, flags);
817                 BUG_ON(PageLRU(page));
818                 SetPageLRU(page);
819                 BUG_ON(!PageActive(page));
820                 list_move(&page->lru, &zone->active_list);
821                 pgmoved++;
822                 if (!pagevec_add(&pvec, page)) {
823                         zone->nr_active += pgmoved;
824                         pgmoved = 0;
825                         spin_unlock_irq(&zone->lru_lock);
826                         __pagevec_release(&pvec);
827                         spin_lock_irq(&zone->lru_lock);
828                 }
829         }
830         zone->nr_active += pgmoved;
831         spin_unlock(&zone->lru_lock);
832
833         __mod_page_state_zone(zone, pgrefill, pgscanned);
834         __mod_page_state(pgdeactivate, pgdeactivate);
835         local_irq_enable();
836
837         pagevec_release(&pvec);
838 }
839
840 /*
841  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
842  */
843 static unsigned long shrink_zone(int priority, struct zone *zone,
844                                 struct scan_control *sc)
845 {
846         unsigned long nr_active;
847         unsigned long nr_inactive;
848         unsigned long nr_to_scan;
849         unsigned long nr_reclaimed = 0;
850
851         atomic_inc(&zone->reclaim_in_progress);
852
853         /*
854          * Add one to `nr_to_scan' just to make sure that the kernel will
855          * slowly sift through the active list.
856          */
857         zone->nr_scan_active += (zone->nr_active >> priority) + 1;
858         nr_active = zone->nr_scan_active;
859         if (nr_active >= sc->swap_cluster_max)
860                 zone->nr_scan_active = 0;
861         else
862                 nr_active = 0;
863
864         zone->nr_scan_inactive += (zone->nr_inactive >> priority) + 1;
865         nr_inactive = zone->nr_scan_inactive;
866         if (nr_inactive >= sc->swap_cluster_max)
867                 zone->nr_scan_inactive = 0;
868         else
869                 nr_inactive = 0;
870
871         while (nr_active || nr_inactive) {
872                 if (nr_active) {
873                         nr_to_scan = min(nr_active,
874                                         (unsigned long)sc->swap_cluster_max);
875                         nr_active -= nr_to_scan;
876                         shrink_active_list(nr_to_scan, zone, sc);
877                 }
878
879                 if (nr_inactive) {
880                         nr_to_scan = min(nr_inactive,
881                                         (unsigned long)sc->swap_cluster_max);
882                         nr_inactive -= nr_to_scan;
883                         nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
884                                                                 sc);
885                 }
886         }
887
888         throttle_vm_writeout();
889
890         atomic_dec(&zone->reclaim_in_progress);
891         return nr_reclaimed;
892 }
893
894 /*
895  * This is the direct reclaim path, for page-allocating processes.  We only
896  * try to reclaim pages from zones which will satisfy the caller's allocation
897  * request.
898  *
899  * We reclaim from a zone even if that zone is over pages_high.  Because:
900  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
901  *    allocation or
902  * b) The zones may be over pages_high but they must go *over* pages_high to
903  *    satisfy the `incremental min' zone defense algorithm.
904  *
905  * Returns the number of reclaimed pages.
906  *
907  * If a zone is deemed to be full of pinned pages then just give it a light
908  * scan then give up on it.
909  */
910 static unsigned long shrink_zones(int priority, struct zone **zones,
911                                         struct scan_control *sc)
912 {
913         unsigned long nr_reclaimed = 0;
914         int i;
915
916         for (i = 0; zones[i] != NULL; i++) {
917                 struct zone *zone = zones[i];
918
919                 if (!populated_zone(zone))
920                         continue;
921
922                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
923                         continue;
924
925                 zone->temp_priority = priority;
926                 if (zone->prev_priority > priority)
927                         zone->prev_priority = priority;
928
929                 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
930                         continue;       /* Let kswapd poll it */
931
932                 nr_reclaimed += shrink_zone(priority, zone, sc);
933         }
934         return nr_reclaimed;
935 }
936  
937 /*
938  * This is the main entry point to direct page reclaim.
939  *
940  * If a full scan of the inactive list fails to free enough memory then we
941  * are "out of memory" and something needs to be killed.
942  *
943  * If the caller is !__GFP_FS then the probability of a failure is reasonably
944  * high - the zone may be full of dirty or under-writeback pages, which this
945  * caller can't do much about.  We kick pdflush and take explicit naps in the
946  * hope that some of these pages can be written.  But if the allocating task
947  * holds filesystem locks which prevent writeout this might not work, and the
948  * allocation attempt will fail.
949  */
950 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
951 {
952         int priority;
953         int ret = 0;
954         unsigned long total_scanned = 0;
955         unsigned long nr_reclaimed = 0;
956         struct reclaim_state *reclaim_state = current->reclaim_state;
957         unsigned long lru_pages = 0;
958         int i;
959         struct scan_control sc = {
960                 .gfp_mask = gfp_mask,
961                 .may_writepage = !laptop_mode,
962                 .swap_cluster_max = SWAP_CLUSTER_MAX,
963                 .may_swap = 1,
964                 .swappiness = vm_swappiness,
965         };
966
967         inc_page_state(allocstall);
968
969         for (i = 0; zones[i] != NULL; i++) {
970                 struct zone *zone = zones[i];
971
972                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
973                         continue;
974
975                 zone->temp_priority = DEF_PRIORITY;
976                 lru_pages += zone->nr_active + zone->nr_inactive;
977         }
978
979         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
980                 sc.nr_mapped = read_page_state(nr_mapped);
981                 sc.nr_scanned = 0;
982                 if (!priority)
983                         disable_swap_token();
984                 nr_reclaimed += shrink_zones(priority, zones, &sc);
985                 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
986                 if (reclaim_state) {
987                         nr_reclaimed += reclaim_state->reclaimed_slab;
988                         reclaim_state->reclaimed_slab = 0;
989                 }
990                 total_scanned += sc.nr_scanned;
991                 if (nr_reclaimed >= sc.swap_cluster_max) {
992                         ret = 1;
993                         goto out;
994                 }
995
996                 /*
997                  * Try to write back as many pages as we just scanned.  This
998                  * tends to cause slow streaming writers to write data to the
999                  * disk smoothly, at the dirtying rate, which is nice.   But
1000                  * that's undesirable in laptop mode, where we *want* lumpy
1001                  * writeout.  So in laptop mode, write out the whole world.
1002                  */
1003                 if (total_scanned > sc.swap_cluster_max +
1004                                         sc.swap_cluster_max / 2) {
1005                         wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1006                         sc.may_writepage = 1;
1007                 }
1008
1009                 /* Take a nap, wait for some writeback to complete */
1010                 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1011                         blk_congestion_wait(WRITE, HZ/10);
1012         }
1013 out:
1014         for (i = 0; zones[i] != 0; i++) {
1015                 struct zone *zone = zones[i];
1016
1017                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1018                         continue;
1019
1020                 zone->prev_priority = zone->temp_priority;
1021         }
1022         return ret;
1023 }
1024
1025 /*
1026  * For kswapd, balance_pgdat() will work across all this node's zones until
1027  * they are all at pages_high.
1028  *
1029  * Returns the number of pages which were actually freed.
1030  *
1031  * There is special handling here for zones which are full of pinned pages.
1032  * This can happen if the pages are all mlocked, or if they are all used by
1033  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
1034  * What we do is to detect the case where all pages in the zone have been
1035  * scanned twice and there has been zero successful reclaim.  Mark the zone as
1036  * dead and from now on, only perform a short scan.  Basically we're polling
1037  * the zone for when the problem goes away.
1038  *
1039  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
1040  * zones which have free_pages > pages_high, but once a zone is found to have
1041  * free_pages <= pages_high, we scan that zone and the lower zones regardless
1042  * of the number of free pages in the lower zones.  This interoperates with
1043  * the page allocator fallback scheme to ensure that aging of pages is balanced
1044  * across the zones.
1045  */
1046 static unsigned long balance_pgdat(pg_data_t *pgdat, int order)
1047 {
1048         int all_zones_ok;
1049         int priority;
1050         int i;
1051         unsigned long total_scanned;
1052         unsigned long nr_reclaimed;
1053         struct reclaim_state *reclaim_state = current->reclaim_state;
1054         struct scan_control sc = {
1055                 .gfp_mask = GFP_KERNEL,
1056                 .may_swap = 1,
1057                 .swap_cluster_max = SWAP_CLUSTER_MAX,
1058                 .swappiness = vm_swappiness,
1059         };
1060
1061 loop_again:
1062         total_scanned = 0;
1063         nr_reclaimed = 0;
1064         sc.may_writepage = !laptop_mode;
1065         sc.nr_mapped = read_page_state(nr_mapped);
1066
1067         inc_page_state(pageoutrun);
1068
1069         for (i = 0; i < pgdat->nr_zones; i++) {
1070                 struct zone *zone = pgdat->node_zones + i;
1071
1072                 zone->temp_priority = DEF_PRIORITY;
1073         }
1074
1075         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1076                 int end_zone = 0;       /* Inclusive.  0 = ZONE_DMA */
1077                 unsigned long lru_pages = 0;
1078
1079                 /* The swap token gets in the way of swapout... */
1080                 if (!priority)
1081                         disable_swap_token();
1082
1083                 all_zones_ok = 1;
1084
1085                 /*
1086                  * Scan in the highmem->dma direction for the highest
1087                  * zone which needs scanning
1088                  */
1089                 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1090                         struct zone *zone = pgdat->node_zones + i;
1091
1092                         if (!populated_zone(zone))
1093                                 continue;
1094
1095                         if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1096                                 continue;
1097
1098                         if (!zone_watermark_ok(zone, order, zone->pages_high,
1099                                                0, 0)) {
1100                                 end_zone = i;
1101                                 goto scan;
1102                         }
1103                 }
1104                 goto out;
1105 scan:
1106                 for (i = 0; i <= end_zone; i++) {
1107                         struct zone *zone = pgdat->node_zones + i;
1108
1109                         lru_pages += zone->nr_active + zone->nr_inactive;
1110                 }
1111
1112                 /*
1113                  * Now scan the zone in the dma->highmem direction, stopping
1114                  * at the last zone which needs scanning.
1115                  *
1116                  * We do this because the page allocator works in the opposite
1117                  * direction.  This prevents the page allocator from allocating
1118                  * pages behind kswapd's direction of progress, which would
1119                  * cause too much scanning of the lower zones.
1120                  */
1121                 for (i = 0; i <= end_zone; i++) {
1122                         struct zone *zone = pgdat->node_zones + i;
1123                         int nr_slab;
1124
1125                         if (!populated_zone(zone))
1126                                 continue;
1127
1128                         if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1129                                 continue;
1130
1131                         if (!zone_watermark_ok(zone, order, zone->pages_high,
1132                                                end_zone, 0))
1133                                 all_zones_ok = 0;
1134                         zone->temp_priority = priority;
1135                         if (zone->prev_priority > priority)
1136                                 zone->prev_priority = priority;
1137                         sc.nr_scanned = 0;
1138                         nr_reclaimed += shrink_zone(priority, zone, &sc);
1139                         reclaim_state->reclaimed_slab = 0;
1140                         nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1141                                                 lru_pages);
1142                         nr_reclaimed += reclaim_state->reclaimed_slab;
1143                         total_scanned += sc.nr_scanned;
1144                         if (zone->all_unreclaimable)
1145                                 continue;
1146                         if (nr_slab == 0 && zone->pages_scanned >=
1147                                     (zone->nr_active + zone->nr_inactive) * 4)
1148                                 zone->all_unreclaimable = 1;
1149                         /*
1150                          * If we've done a decent amount of scanning and
1151                          * the reclaim ratio is low, start doing writepage
1152                          * even in laptop mode
1153                          */
1154                         if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1155                             total_scanned > nr_reclaimed + nr_reclaimed / 2)
1156                                 sc.may_writepage = 1;
1157                 }
1158                 if (all_zones_ok)
1159                         break;          /* kswapd: all done */
1160                 /*
1161                  * OK, kswapd is getting into trouble.  Take a nap, then take
1162                  * another pass across the zones.
1163                  */
1164                 if (total_scanned && priority < DEF_PRIORITY - 2)
1165                         blk_congestion_wait(WRITE, HZ/10);
1166
1167                 /*
1168                  * We do this so kswapd doesn't build up large priorities for
1169                  * example when it is freeing in parallel with allocators. It
1170                  * matches the direct reclaim path behaviour in terms of impact
1171                  * on zone->*_priority.
1172                  */
1173                 if (nr_reclaimed >= SWAP_CLUSTER_MAX)
1174                         break;
1175         }
1176 out:
1177         for (i = 0; i < pgdat->nr_zones; i++) {
1178                 struct zone *zone = pgdat->node_zones + i;
1179
1180                 zone->prev_priority = zone->temp_priority;
1181         }
1182         if (!all_zones_ok) {
1183                 cond_resched();
1184                 goto loop_again;
1185         }
1186
1187         return nr_reclaimed;
1188 }
1189
1190 /*
1191  * The background pageout daemon, started as a kernel thread
1192  * from the init process. 
1193  *
1194  * This basically trickles out pages so that we have _some_
1195  * free memory available even if there is no other activity
1196  * that frees anything up. This is needed for things like routing
1197  * etc, where we otherwise might have all activity going on in
1198  * asynchronous contexts that cannot page things out.
1199  *
1200  * If there are applications that are active memory-allocators
1201  * (most normal use), this basically shouldn't matter.
1202  */
1203 static int kswapd(void *p)
1204 {
1205         unsigned long order;
1206         pg_data_t *pgdat = (pg_data_t*)p;
1207         struct task_struct *tsk = current;
1208         DEFINE_WAIT(wait);
1209         struct reclaim_state reclaim_state = {
1210                 .reclaimed_slab = 0,
1211         };
1212         cpumask_t cpumask;
1213
1214         daemonize("kswapd%d", pgdat->node_id);
1215         cpumask = node_to_cpumask(pgdat->node_id);
1216         if (!cpus_empty(cpumask))
1217                 set_cpus_allowed(tsk, cpumask);
1218         current->reclaim_state = &reclaim_state;
1219
1220         /*
1221          * Tell the memory management that we're a "memory allocator",
1222          * and that if we need more memory we should get access to it
1223          * regardless (see "__alloc_pages()"). "kswapd" should
1224          * never get caught in the normal page freeing logic.
1225          *
1226          * (Kswapd normally doesn't need memory anyway, but sometimes
1227          * you need a small amount of memory in order to be able to
1228          * page out something else, and this flag essentially protects
1229          * us from recursively trying to free more memory as we're
1230          * trying to free the first piece of memory in the first place).
1231          */
1232         tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1233
1234         order = 0;
1235         for ( ; ; ) {
1236                 unsigned long new_order;
1237
1238                 try_to_freeze();
1239
1240                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1241                 new_order = pgdat->kswapd_max_order;
1242                 pgdat->kswapd_max_order = 0;
1243                 if (order < new_order) {
1244                         /*
1245                          * Don't sleep if someone wants a larger 'order'
1246                          * allocation
1247                          */
1248                         order = new_order;
1249                 } else {
1250                         schedule();
1251                         order = pgdat->kswapd_max_order;
1252                 }
1253                 finish_wait(&pgdat->kswapd_wait, &wait);
1254
1255                 balance_pgdat(pgdat, order);
1256         }
1257         return 0;
1258 }
1259
1260 /*
1261  * A zone is low on free memory, so wake its kswapd task to service it.
1262  */
1263 void wakeup_kswapd(struct zone *zone, int order)
1264 {
1265         pg_data_t *pgdat;
1266
1267         if (!populated_zone(zone))
1268                 return;
1269
1270         pgdat = zone->zone_pgdat;
1271         if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1272                 return;
1273         if (pgdat->kswapd_max_order < order)
1274                 pgdat->kswapd_max_order = order;
1275         if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1276                 return;
1277         if (!waitqueue_active(&pgdat->kswapd_wait))
1278                 return;
1279         wake_up_interruptible(&pgdat->kswapd_wait);
1280 }
1281
1282 #ifdef CONFIG_PM
1283 /*
1284  * Helper function for shrink_all_memory().  Tries to reclaim 'nr_pages' pages
1285  * from LRU lists system-wide, for given pass and priority, and returns the
1286  * number of reclaimed pages
1287  *
1288  * For pass > 3 we also try to shrink the LRU lists that contain a few pages
1289  */
1290 static unsigned long shrink_all_zones(unsigned long nr_pages, int pass,
1291                                       int prio, struct scan_control *sc)
1292 {
1293         struct zone *zone;
1294         unsigned long nr_to_scan, ret = 0;
1295
1296         for_each_zone(zone) {
1297
1298                 if (!populated_zone(zone))
1299                         continue;
1300
1301                 if (zone->all_unreclaimable && prio != DEF_PRIORITY)
1302                         continue;
1303
1304                 /* For pass = 0 we don't shrink the active list */
1305                 if (pass > 0) {
1306                         zone->nr_scan_active += (zone->nr_active >> prio) + 1;
1307                         if (zone->nr_scan_active >= nr_pages || pass > 3) {
1308                                 zone->nr_scan_active = 0;
1309                                 nr_to_scan = min(nr_pages, zone->nr_active);
1310                                 shrink_active_list(nr_to_scan, zone, sc);
1311                         }
1312                 }
1313
1314                 zone->nr_scan_inactive += (zone->nr_inactive >> prio) + 1;
1315                 if (zone->nr_scan_inactive >= nr_pages || pass > 3) {
1316                         zone->nr_scan_inactive = 0;
1317                         nr_to_scan = min(nr_pages, zone->nr_inactive);
1318                         ret += shrink_inactive_list(nr_to_scan, zone, sc);
1319                         if (ret >= nr_pages)
1320                                 return ret;
1321                 }
1322         }
1323
1324         return ret;
1325 }
1326
1327 /*
1328  * Try to free `nr_pages' of memory, system-wide, and return the number of
1329  * freed pages.
1330  *
1331  * Rather than trying to age LRUs the aim is to preserve the overall
1332  * LRU order by reclaiming preferentially
1333  * inactive > active > active referenced > active mapped
1334  */
1335 unsigned long shrink_all_memory(unsigned long nr_pages)
1336 {
1337         unsigned long lru_pages, nr_slab;
1338         unsigned long ret = 0;
1339         int pass;
1340         struct reclaim_state reclaim_state;
1341         struct zone *zone;
1342         struct scan_control sc = {
1343                 .gfp_mask = GFP_KERNEL,
1344                 .may_swap = 0,
1345                 .swap_cluster_max = nr_pages,
1346                 .may_writepage = 1,
1347                 .swappiness = vm_swappiness,
1348         };
1349
1350         current->reclaim_state = &reclaim_state;
1351
1352         lru_pages = 0;
1353         for_each_zone(zone)
1354                 lru_pages += zone->nr_active + zone->nr_inactive;
1355
1356         nr_slab = read_page_state(nr_slab);
1357         /* If slab caches are huge, it's better to hit them first */
1358         while (nr_slab >= lru_pages) {
1359                 reclaim_state.reclaimed_slab = 0;
1360                 shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1361                 if (!reclaim_state.reclaimed_slab)
1362                         break;
1363
1364                 ret += reclaim_state.reclaimed_slab;
1365                 if (ret >= nr_pages)
1366                         goto out;
1367
1368                 nr_slab -= reclaim_state.reclaimed_slab;
1369         }
1370
1371         /*
1372          * We try to shrink LRUs in 5 passes:
1373          * 0 = Reclaim from inactive_list only
1374          * 1 = Reclaim from active list but don't reclaim mapped
1375          * 2 = 2nd pass of type 1
1376          * 3 = Reclaim mapped (normal reclaim)
1377          * 4 = 2nd pass of type 3
1378          */
1379         for (pass = 0; pass < 5; pass++) {
1380                 int prio;
1381
1382                 /* Needed for shrinking slab caches later on */
1383                 if (!lru_pages)
1384                         for_each_zone(zone) {
1385                                 lru_pages += zone->nr_active;
1386                                 lru_pages += zone->nr_inactive;
1387                         }
1388
1389                 /* Force reclaiming mapped pages in the passes #3 and #4 */
1390                 if (pass > 2) {
1391                         sc.may_swap = 1;
1392                         sc.swappiness = 100;
1393                 }
1394
1395                 for (prio = DEF_PRIORITY; prio >= 0; prio--) {
1396                         unsigned long nr_to_scan = nr_pages - ret;
1397
1398                         sc.nr_mapped = read_page_state(nr_mapped);
1399                         sc.nr_scanned = 0;
1400
1401                         ret += shrink_all_zones(nr_to_scan, prio, pass, &sc);
1402                         if (ret >= nr_pages)
1403                                 goto out;
1404
1405                         reclaim_state.reclaimed_slab = 0;
1406                         shrink_slab(sc.nr_scanned, sc.gfp_mask, lru_pages);
1407                         ret += reclaim_state.reclaimed_slab;
1408                         if (ret >= nr_pages)
1409                                 goto out;
1410
1411                         if (sc.nr_scanned && prio < DEF_PRIORITY - 2)
1412                                 blk_congestion_wait(WRITE, HZ / 10);
1413                 }
1414
1415                 lru_pages = 0;
1416         }
1417
1418         /*
1419          * If ret = 0, we could not shrink LRUs, but there may be something
1420          * in slab caches
1421          */
1422         if (!ret)
1423                 do {
1424                         reclaim_state.reclaimed_slab = 0;
1425                         shrink_slab(nr_pages, sc.gfp_mask, lru_pages);
1426                         ret += reclaim_state.reclaimed_slab;
1427                 } while (ret < nr_pages && reclaim_state.reclaimed_slab > 0);
1428
1429 out:
1430         current->reclaim_state = NULL;
1431
1432         return ret;
1433 }
1434 #endif
1435
1436 #ifdef CONFIG_HOTPLUG_CPU
1437 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1438    not required for correctness.  So if the last cpu in a node goes
1439    away, we get changed to run anywhere: as the first one comes back,
1440    restore their cpu bindings. */
1441 static int cpu_callback(struct notifier_block *nfb,
1442                                   unsigned long action, void *hcpu)
1443 {
1444         pg_data_t *pgdat;
1445         cpumask_t mask;
1446
1447         if (action == CPU_ONLINE) {
1448                 for_each_online_pgdat(pgdat) {
1449                         mask = node_to_cpumask(pgdat->node_id);
1450                         if (any_online_cpu(mask) != NR_CPUS)
1451                                 /* One of our CPUs online: restore mask */
1452                                 set_cpus_allowed(pgdat->kswapd, mask);
1453                 }
1454         }
1455         return NOTIFY_OK;
1456 }
1457 #endif /* CONFIG_HOTPLUG_CPU */
1458
1459 static int __init kswapd_init(void)
1460 {
1461         pg_data_t *pgdat;
1462
1463         swap_setup();
1464         for_each_online_pgdat(pgdat) {
1465                 pid_t pid;
1466
1467                 pid = kernel_thread(kswapd, pgdat, CLONE_KERNEL);
1468                 BUG_ON(pid < 0);
1469                 read_lock(&tasklist_lock);
1470                 pgdat->kswapd = find_task_by_pid(pid);
1471                 read_unlock(&tasklist_lock);
1472         }
1473         total_memory = nr_free_pagecache_pages();
1474         hotcpu_notifier(cpu_callback, 0);
1475         return 0;
1476 }
1477
1478 module_init(kswapd_init)
1479
1480 #ifdef CONFIG_NUMA
1481 /*
1482  * Zone reclaim mode
1483  *
1484  * If non-zero call zone_reclaim when the number of free pages falls below
1485  * the watermarks.
1486  *
1487  * In the future we may add flags to the mode. However, the page allocator
1488  * should only have to check that zone_reclaim_mode != 0 before calling
1489  * zone_reclaim().
1490  */
1491 int zone_reclaim_mode __read_mostly;
1492
1493 #define RECLAIM_OFF 0
1494 #define RECLAIM_ZONE (1<<0)     /* Run shrink_cache on the zone */
1495 #define RECLAIM_WRITE (1<<1)    /* Writeout pages during reclaim */
1496 #define RECLAIM_SWAP (1<<2)     /* Swap pages out during reclaim */
1497 #define RECLAIM_SLAB (1<<3)     /* Do a global slab shrink if the zone is out of memory */
1498
1499 /*
1500  * Mininum time between zone reclaim scans
1501  */
1502 int zone_reclaim_interval __read_mostly = 30*HZ;
1503
1504 /*
1505  * Priority for ZONE_RECLAIM. This determines the fraction of pages
1506  * of a node considered for each zone_reclaim. 4 scans 1/16th of
1507  * a zone.
1508  */
1509 #define ZONE_RECLAIM_PRIORITY 4
1510
1511 /*
1512  * Try to free up some pages from this zone through reclaim.
1513  */
1514 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1515 {
1516         /* Minimum pages needed in order to stay on node */
1517         const unsigned long nr_pages = 1 << order;
1518         struct task_struct *p = current;
1519         struct reclaim_state reclaim_state;
1520         int priority;
1521         unsigned long nr_reclaimed = 0;
1522         struct scan_control sc = {
1523                 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1524                 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1525                 .nr_mapped = read_page_state(nr_mapped),
1526                 .swap_cluster_max = max_t(unsigned long, nr_pages,
1527                                         SWAP_CLUSTER_MAX),
1528                 .gfp_mask = gfp_mask,
1529                 .swappiness = vm_swappiness,
1530         };
1531
1532         disable_swap_token();
1533         cond_resched();
1534         /*
1535          * We need to be able to allocate from the reserves for RECLAIM_SWAP
1536          * and we also need to be able to write out pages for RECLAIM_WRITE
1537          * and RECLAIM_SWAP.
1538          */
1539         p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1540         reclaim_state.reclaimed_slab = 0;
1541         p->reclaim_state = &reclaim_state;
1542
1543         /*
1544          * Free memory by calling shrink zone with increasing priorities
1545          * until we have enough memory freed.
1546          */
1547         priority = ZONE_RECLAIM_PRIORITY;
1548         do {
1549                 nr_reclaimed += shrink_zone(priority, zone, &sc);
1550                 priority--;
1551         } while (priority >= 0 && nr_reclaimed < nr_pages);
1552
1553         if (nr_reclaimed < nr_pages && (zone_reclaim_mode & RECLAIM_SLAB)) {
1554                 /*
1555                  * shrink_slab() does not currently allow us to determine how
1556                  * many pages were freed in this zone. So we just shake the slab
1557                  * a bit and then go off node for this particular allocation
1558                  * despite possibly having freed enough memory to allocate in
1559                  * this zone.  If we freed local memory then the next
1560                  * allocations will be local again.
1561                  *
1562                  * shrink_slab will free memory on all zones and may take
1563                  * a long time.
1564                  */
1565                 shrink_slab(sc.nr_scanned, gfp_mask, order);
1566         }
1567
1568         p->reclaim_state = NULL;
1569         current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1570
1571         if (nr_reclaimed == 0) {
1572                 /*
1573                  * We were unable to reclaim enough pages to stay on node.  We
1574                  * now allow off node accesses for a certain time period before
1575                  * trying again to reclaim pages from the local zone.
1576                  */
1577                 zone->last_unsuccessful_zone_reclaim = jiffies;
1578         }
1579
1580         return nr_reclaimed >= nr_pages;
1581 }
1582
1583 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1584 {
1585         cpumask_t mask;
1586         int node_id;
1587
1588         /*
1589          * Do not reclaim if there was a recent unsuccessful attempt at zone
1590          * reclaim.  In that case we let allocations go off node for the
1591          * zone_reclaim_interval.  Otherwise we would scan for each off-node
1592          * page allocation.
1593          */
1594         if (time_before(jiffies,
1595                 zone->last_unsuccessful_zone_reclaim + zone_reclaim_interval))
1596                         return 0;
1597
1598         /*
1599          * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1600          * not have reclaimable pages and if we should not delay the allocation
1601          * then do not scan.
1602          */
1603         if (!(gfp_mask & __GFP_WAIT) ||
1604                 zone->all_unreclaimable ||
1605                 atomic_read(&zone->reclaim_in_progress) > 0 ||
1606                 (current->flags & PF_MEMALLOC))
1607                         return 0;
1608
1609         /*
1610          * Only run zone reclaim on the local zone or on zones that do not
1611          * have associated processors. This will favor the local processor
1612          * over remote processors and spread off node memory allocations
1613          * as wide as possible.
1614          */
1615         node_id = zone->zone_pgdat->node_id;
1616         mask = node_to_cpumask(node_id);
1617         if (!cpus_empty(mask) && node_id != numa_node_id())
1618                 return 0;
1619         return __zone_reclaim(zone, gfp_mask, order);
1620 }
1621 #endif