]> git.karo-electronics.de Git - karo-tx-linux.git/blob - mm/vmscan.c
[PATCH] mm: make __put_page internal
[karo-tx-linux.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
37 #include <asm/tlbflush.h>
38 #include <asm/div64.h>
39
40 #include <linux/swapops.h>
41
42 #include "internal.h"
43
44 /* possible outcome of pageout() */
45 typedef enum {
46         /* failed to write page out, page is locked */
47         PAGE_KEEP,
48         /* move page to the active list, page is locked */
49         PAGE_ACTIVATE,
50         /* page has been sent to the disk successfully, page is unlocked */
51         PAGE_SUCCESS,
52         /* page is clean and locked */
53         PAGE_CLEAN,
54 } pageout_t;
55
56 struct scan_control {
57         /* Incremented by the number of inactive pages that were scanned */
58         unsigned long nr_scanned;
59
60         unsigned long nr_mapped;        /* From page_state */
61
62         /* This context's GFP mask */
63         gfp_t gfp_mask;
64
65         int may_writepage;
66
67         /* Can pages be swapped as part of reclaim? */
68         int may_swap;
69
70         /* This context's SWAP_CLUSTER_MAX. If freeing memory for
71          * suspend, we effectively ignore SWAP_CLUSTER_MAX.
72          * In this context, it doesn't matter that we scan the
73          * whole list at once. */
74         int swap_cluster_max;
75 };
76
77 /*
78  * The list of shrinker callbacks used by to apply pressure to
79  * ageable caches.
80  */
81 struct shrinker {
82         shrinker_t              shrinker;
83         struct list_head        list;
84         int                     seeks;  /* seeks to recreate an obj */
85         long                    nr;     /* objs pending delete */
86 };
87
88 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
89
90 #ifdef ARCH_HAS_PREFETCH
91 #define prefetch_prev_lru_page(_page, _base, _field)                    \
92         do {                                                            \
93                 if ((_page)->lru.prev != _base) {                       \
94                         struct page *prev;                              \
95                                                                         \
96                         prev = lru_to_page(&(_page->lru));              \
97                         prefetch(&prev->_field);                        \
98                 }                                                       \
99         } while (0)
100 #else
101 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
102 #endif
103
104 #ifdef ARCH_HAS_PREFETCHW
105 #define prefetchw_prev_lru_page(_page, _base, _field)                   \
106         do {                                                            \
107                 if ((_page)->lru.prev != _base) {                       \
108                         struct page *prev;                              \
109                                                                         \
110                         prev = lru_to_page(&(_page->lru));              \
111                         prefetchw(&prev->_field);                       \
112                 }                                                       \
113         } while (0)
114 #else
115 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
116 #endif
117
118 /*
119  * From 0 .. 100.  Higher means more swappy.
120  */
121 int vm_swappiness = 60;
122 static long total_memory;
123
124 static LIST_HEAD(shrinker_list);
125 static DECLARE_RWSEM(shrinker_rwsem);
126
127 /*
128  * Add a shrinker callback to be called from the vm
129  */
130 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
131 {
132         struct shrinker *shrinker;
133
134         shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
135         if (shrinker) {
136                 shrinker->shrinker = theshrinker;
137                 shrinker->seeks = seeks;
138                 shrinker->nr = 0;
139                 down_write(&shrinker_rwsem);
140                 list_add_tail(&shrinker->list, &shrinker_list);
141                 up_write(&shrinker_rwsem);
142         }
143         return shrinker;
144 }
145 EXPORT_SYMBOL(set_shrinker);
146
147 /*
148  * Remove one
149  */
150 void remove_shrinker(struct shrinker *shrinker)
151 {
152         down_write(&shrinker_rwsem);
153         list_del(&shrinker->list);
154         up_write(&shrinker_rwsem);
155         kfree(shrinker);
156 }
157 EXPORT_SYMBOL(remove_shrinker);
158
159 #define SHRINK_BATCH 128
160 /*
161  * Call the shrink functions to age shrinkable caches
162  *
163  * Here we assume it costs one seek to replace a lru page and that it also
164  * takes a seek to recreate a cache object.  With this in mind we age equal
165  * percentages of the lru and ageable caches.  This should balance the seeks
166  * generated by these structures.
167  *
168  * If the vm encounted mapped pages on the LRU it increase the pressure on
169  * slab to avoid swapping.
170  *
171  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
172  *
173  * `lru_pages' represents the number of on-LRU pages in all the zones which
174  * are eligible for the caller's allocation attempt.  It is used for balancing
175  * slab reclaim versus page reclaim.
176  *
177  * Returns the number of slab objects which we shrunk.
178  */
179 unsigned long shrink_slab(unsigned long scanned, gfp_t gfp_mask,
180                         unsigned long lru_pages)
181 {
182         struct shrinker *shrinker;
183         unsigned long ret = 0;
184
185         if (scanned == 0)
186                 scanned = SWAP_CLUSTER_MAX;
187
188         if (!down_read_trylock(&shrinker_rwsem))
189                 return 1;       /* Assume we'll be able to shrink next time */
190
191         list_for_each_entry(shrinker, &shrinker_list, list) {
192                 unsigned long long delta;
193                 unsigned long total_scan;
194                 unsigned long max_pass = (*shrinker->shrinker)(0, gfp_mask);
195
196                 delta = (4 * scanned) / shrinker->seeks;
197                 delta *= max_pass;
198                 do_div(delta, lru_pages + 1);
199                 shrinker->nr += delta;
200                 if (shrinker->nr < 0) {
201                         printk(KERN_ERR "%s: nr=%ld\n",
202                                         __FUNCTION__, shrinker->nr);
203                         shrinker->nr = max_pass;
204                 }
205
206                 /*
207                  * Avoid risking looping forever due to too large nr value:
208                  * never try to free more than twice the estimate number of
209                  * freeable entries.
210                  */
211                 if (shrinker->nr > max_pass * 2)
212                         shrinker->nr = max_pass * 2;
213
214                 total_scan = shrinker->nr;
215                 shrinker->nr = 0;
216
217                 while (total_scan >= SHRINK_BATCH) {
218                         long this_scan = SHRINK_BATCH;
219                         int shrink_ret;
220                         int nr_before;
221
222                         nr_before = (*shrinker->shrinker)(0, gfp_mask);
223                         shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
224                         if (shrink_ret == -1)
225                                 break;
226                         if (shrink_ret < nr_before)
227                                 ret += nr_before - shrink_ret;
228                         mod_page_state(slabs_scanned, this_scan);
229                         total_scan -= this_scan;
230
231                         cond_resched();
232                 }
233
234                 shrinker->nr += total_scan;
235         }
236         up_read(&shrinker_rwsem);
237         return ret;
238 }
239
240 /* Called without lock on whether page is mapped, so answer is unstable */
241 static inline int page_mapping_inuse(struct page *page)
242 {
243         struct address_space *mapping;
244
245         /* Page is in somebody's page tables. */
246         if (page_mapped(page))
247                 return 1;
248
249         /* Be more reluctant to reclaim swapcache than pagecache */
250         if (PageSwapCache(page))
251                 return 1;
252
253         mapping = page_mapping(page);
254         if (!mapping)
255                 return 0;
256
257         /* File is mmap'd by somebody? */
258         return mapping_mapped(mapping);
259 }
260
261 static inline int is_page_cache_freeable(struct page *page)
262 {
263         return page_count(page) - !!PagePrivate(page) == 2;
264 }
265
266 static int may_write_to_queue(struct backing_dev_info *bdi)
267 {
268         if (current->flags & PF_SWAPWRITE)
269                 return 1;
270         if (!bdi_write_congested(bdi))
271                 return 1;
272         if (bdi == current->backing_dev_info)
273                 return 1;
274         return 0;
275 }
276
277 /*
278  * We detected a synchronous write error writing a page out.  Probably
279  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
280  * fsync(), msync() or close().
281  *
282  * The tricky part is that after writepage we cannot touch the mapping: nothing
283  * prevents it from being freed up.  But we have a ref on the page and once
284  * that page is locked, the mapping is pinned.
285  *
286  * We're allowed to run sleeping lock_page() here because we know the caller has
287  * __GFP_FS.
288  */
289 static void handle_write_error(struct address_space *mapping,
290                                 struct page *page, int error)
291 {
292         lock_page(page);
293         if (page_mapping(page) == mapping) {
294                 if (error == -ENOSPC)
295                         set_bit(AS_ENOSPC, &mapping->flags);
296                 else
297                         set_bit(AS_EIO, &mapping->flags);
298         }
299         unlock_page(page);
300 }
301
302 /*
303  * pageout is called by shrink_page_list() for each dirty page.
304  * Calls ->writepage().
305  */
306 static pageout_t pageout(struct page *page, struct address_space *mapping)
307 {
308         /*
309          * If the page is dirty, only perform writeback if that write
310          * will be non-blocking.  To prevent this allocation from being
311          * stalled by pagecache activity.  But note that there may be
312          * stalls if we need to run get_block().  We could test
313          * PagePrivate for that.
314          *
315          * If this process is currently in generic_file_write() against
316          * this page's queue, we can perform writeback even if that
317          * will block.
318          *
319          * If the page is swapcache, write it back even if that would
320          * block, for some throttling. This happens by accident, because
321          * swap_backing_dev_info is bust: it doesn't reflect the
322          * congestion state of the swapdevs.  Easy to fix, if needed.
323          * See swapfile.c:page_queue_congested().
324          */
325         if (!is_page_cache_freeable(page))
326                 return PAGE_KEEP;
327         if (!mapping) {
328                 /*
329                  * Some data journaling orphaned pages can have
330                  * page->mapping == NULL while being dirty with clean buffers.
331                  */
332                 if (PagePrivate(page)) {
333                         if (try_to_free_buffers(page)) {
334                                 ClearPageDirty(page);
335                                 printk("%s: orphaned page\n", __FUNCTION__);
336                                 return PAGE_CLEAN;
337                         }
338                 }
339                 return PAGE_KEEP;
340         }
341         if (mapping->a_ops->writepage == NULL)
342                 return PAGE_ACTIVATE;
343         if (!may_write_to_queue(mapping->backing_dev_info))
344                 return PAGE_KEEP;
345
346         if (clear_page_dirty_for_io(page)) {
347                 int res;
348                 struct writeback_control wbc = {
349                         .sync_mode = WB_SYNC_NONE,
350                         .nr_to_write = SWAP_CLUSTER_MAX,
351                         .nonblocking = 1,
352                         .for_reclaim = 1,
353                 };
354
355                 SetPageReclaim(page);
356                 res = mapping->a_ops->writepage(page, &wbc);
357                 if (res < 0)
358                         handle_write_error(mapping, page, res);
359                 if (res == AOP_WRITEPAGE_ACTIVATE) {
360                         ClearPageReclaim(page);
361                         return PAGE_ACTIVATE;
362                 }
363                 if (!PageWriteback(page)) {
364                         /* synchronous write or broken a_ops? */
365                         ClearPageReclaim(page);
366                 }
367
368                 return PAGE_SUCCESS;
369         }
370
371         return PAGE_CLEAN;
372 }
373
374 static int remove_mapping(struct address_space *mapping, struct page *page)
375 {
376         if (!mapping)
377                 return 0;               /* truncate got there first */
378
379         write_lock_irq(&mapping->tree_lock);
380
381         /*
382          * The non-racy check for busy page.  It is critical to check
383          * PageDirty _after_ making sure that the page is freeable and
384          * not in use by anybody.       (pagecache + us == 2)
385          */
386         if (unlikely(page_count(page) != 2))
387                 goto cannot_free;
388         smp_rmb();
389         if (unlikely(PageDirty(page)))
390                 goto cannot_free;
391
392         if (PageSwapCache(page)) {
393                 swp_entry_t swap = { .val = page_private(page) };
394                 __delete_from_swap_cache(page);
395                 write_unlock_irq(&mapping->tree_lock);
396                 swap_free(swap);
397                 __put_page(page);       /* The pagecache ref */
398                 return 1;
399         }
400
401         __remove_from_page_cache(page);
402         write_unlock_irq(&mapping->tree_lock);
403         __put_page(page);
404         return 1;
405
406 cannot_free:
407         write_unlock_irq(&mapping->tree_lock);
408         return 0;
409 }
410
411 /*
412  * shrink_page_list() returns the number of reclaimed pages
413  */
414 static unsigned long shrink_page_list(struct list_head *page_list,
415                                         struct scan_control *sc)
416 {
417         LIST_HEAD(ret_pages);
418         struct pagevec freed_pvec;
419         int pgactivate = 0;
420         unsigned long nr_reclaimed = 0;
421
422         cond_resched();
423
424         pagevec_init(&freed_pvec, 1);
425         while (!list_empty(page_list)) {
426                 struct address_space *mapping;
427                 struct page *page;
428                 int may_enter_fs;
429                 int referenced;
430
431                 cond_resched();
432
433                 page = lru_to_page(page_list);
434                 list_del(&page->lru);
435
436                 if (TestSetPageLocked(page))
437                         goto keep;
438
439                 BUG_ON(PageActive(page));
440
441                 sc->nr_scanned++;
442
443                 if (!sc->may_swap && page_mapped(page))
444                         goto keep_locked;
445
446                 /* Double the slab pressure for mapped and swapcache pages */
447                 if (page_mapped(page) || PageSwapCache(page))
448                         sc->nr_scanned++;
449
450                 if (PageWriteback(page))
451                         goto keep_locked;
452
453                 referenced = page_referenced(page, 1);
454                 /* In active use or really unfreeable?  Activate it. */
455                 if (referenced && page_mapping_inuse(page))
456                         goto activate_locked;
457
458 #ifdef CONFIG_SWAP
459                 /*
460                  * Anonymous process memory has backing store?
461                  * Try to allocate it some swap space here.
462                  */
463                 if (PageAnon(page) && !PageSwapCache(page)) {
464                         if (!sc->may_swap)
465                                 goto keep_locked;
466                         if (!add_to_swap(page, GFP_ATOMIC))
467                                 goto activate_locked;
468                 }
469 #endif /* CONFIG_SWAP */
470
471                 mapping = page_mapping(page);
472                 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
473                         (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
474
475                 /*
476                  * The page is mapped into the page tables of one or more
477                  * processes. Try to unmap it here.
478                  */
479                 if (page_mapped(page) && mapping) {
480                         /*
481                          * No unmapping if we do not swap
482                          */
483                         if (!sc->may_swap)
484                                 goto keep_locked;
485
486                         switch (try_to_unmap(page, 0)) {
487                         case SWAP_FAIL:
488                                 goto activate_locked;
489                         case SWAP_AGAIN:
490                                 goto keep_locked;
491                         case SWAP_SUCCESS:
492                                 ; /* try to free the page below */
493                         }
494                 }
495
496                 if (PageDirty(page)) {
497                         if (referenced)
498                                 goto keep_locked;
499                         if (!may_enter_fs)
500                                 goto keep_locked;
501                         if (!sc->may_writepage)
502                                 goto keep_locked;
503
504                         /* Page is dirty, try to write it out here */
505                         switch(pageout(page, mapping)) {
506                         case PAGE_KEEP:
507                                 goto keep_locked;
508                         case PAGE_ACTIVATE:
509                                 goto activate_locked;
510                         case PAGE_SUCCESS:
511                                 if (PageWriteback(page) || PageDirty(page))
512                                         goto keep;
513                                 /*
514                                  * A synchronous write - probably a ramdisk.  Go
515                                  * ahead and try to reclaim the page.
516                                  */
517                                 if (TestSetPageLocked(page))
518                                         goto keep;
519                                 if (PageDirty(page) || PageWriteback(page))
520                                         goto keep_locked;
521                                 mapping = page_mapping(page);
522                         case PAGE_CLEAN:
523                                 ; /* try to free the page below */
524                         }
525                 }
526
527                 /*
528                  * If the page has buffers, try to free the buffer mappings
529                  * associated with this page. If we succeed we try to free
530                  * the page as well.
531                  *
532                  * We do this even if the page is PageDirty().
533                  * try_to_release_page() does not perform I/O, but it is
534                  * possible for a page to have PageDirty set, but it is actually
535                  * clean (all its buffers are clean).  This happens if the
536                  * buffers were written out directly, with submit_bh(). ext3
537                  * will do this, as well as the blockdev mapping. 
538                  * try_to_release_page() will discover that cleanness and will
539                  * drop the buffers and mark the page clean - it can be freed.
540                  *
541                  * Rarely, pages can have buffers and no ->mapping.  These are
542                  * the pages which were not successfully invalidated in
543                  * truncate_complete_page().  We try to drop those buffers here
544                  * and if that worked, and the page is no longer mapped into
545                  * process address space (page_count == 1) it can be freed.
546                  * Otherwise, leave the page on the LRU so it is swappable.
547                  */
548                 if (PagePrivate(page)) {
549                         if (!try_to_release_page(page, sc->gfp_mask))
550                                 goto activate_locked;
551                         if (!mapping && page_count(page) == 1)
552                                 goto free_it;
553                 }
554
555                 if (!remove_mapping(mapping, page))
556                         goto keep_locked;
557
558 free_it:
559                 unlock_page(page);
560                 nr_reclaimed++;
561                 if (!pagevec_add(&freed_pvec, page))
562                         __pagevec_release_nonlru(&freed_pvec);
563                 continue;
564
565 activate_locked:
566                 SetPageActive(page);
567                 pgactivate++;
568 keep_locked:
569                 unlock_page(page);
570 keep:
571                 list_add(&page->lru, &ret_pages);
572                 BUG_ON(PageLRU(page));
573         }
574         list_splice(&ret_pages, page_list);
575         if (pagevec_count(&freed_pvec))
576                 __pagevec_release_nonlru(&freed_pvec);
577         mod_page_state(pgactivate, pgactivate);
578         return nr_reclaimed;
579 }
580
581 #ifdef CONFIG_MIGRATION
582 static inline void move_to_lru(struct page *page)
583 {
584         list_del(&page->lru);
585         if (PageActive(page)) {
586                 /*
587                  * lru_cache_add_active checks that
588                  * the PG_active bit is off.
589                  */
590                 ClearPageActive(page);
591                 lru_cache_add_active(page);
592         } else {
593                 lru_cache_add(page);
594         }
595         put_page(page);
596 }
597
598 /*
599  * Add isolated pages on the list back to the LRU.
600  *
601  * returns the number of pages put back.
602  */
603 unsigned long putback_lru_pages(struct list_head *l)
604 {
605         struct page *page;
606         struct page *page2;
607         unsigned long count = 0;
608
609         list_for_each_entry_safe(page, page2, l, lru) {
610                 move_to_lru(page);
611                 count++;
612         }
613         return count;
614 }
615
616 /*
617  * Non migratable page
618  */
619 int fail_migrate_page(struct page *newpage, struct page *page)
620 {
621         return -EIO;
622 }
623 EXPORT_SYMBOL(fail_migrate_page);
624
625 /*
626  * swapout a single page
627  * page is locked upon entry, unlocked on exit
628  */
629 static int swap_page(struct page *page)
630 {
631         struct address_space *mapping = page_mapping(page);
632
633         if (page_mapped(page) && mapping)
634                 if (try_to_unmap(page, 1) != SWAP_SUCCESS)
635                         goto unlock_retry;
636
637         if (PageDirty(page)) {
638                 /* Page is dirty, try to write it out here */
639                 switch(pageout(page, mapping)) {
640                 case PAGE_KEEP:
641                 case PAGE_ACTIVATE:
642                         goto unlock_retry;
643
644                 case PAGE_SUCCESS:
645                         goto retry;
646
647                 case PAGE_CLEAN:
648                         ; /* try to free the page below */
649                 }
650         }
651
652         if (PagePrivate(page)) {
653                 if (!try_to_release_page(page, GFP_KERNEL) ||
654                     (!mapping && page_count(page) == 1))
655                         goto unlock_retry;
656         }
657
658         if (remove_mapping(mapping, page)) {
659                 /* Success */
660                 unlock_page(page);
661                 return 0;
662         }
663
664 unlock_retry:
665         unlock_page(page);
666
667 retry:
668         return -EAGAIN;
669 }
670 EXPORT_SYMBOL(swap_page);
671
672 /*
673  * Page migration was first developed in the context of the memory hotplug
674  * project. The main authors of the migration code are:
675  *
676  * IWAMOTO Toshihiro <iwamoto@valinux.co.jp>
677  * Hirokazu Takahashi <taka@valinux.co.jp>
678  * Dave Hansen <haveblue@us.ibm.com>
679  * Christoph Lameter <clameter@sgi.com>
680  */
681
682 /*
683  * Remove references for a page and establish the new page with the correct
684  * basic settings to be able to stop accesses to the page.
685  */
686 int migrate_page_remove_references(struct page *newpage,
687                                 struct page *page, int nr_refs)
688 {
689         struct address_space *mapping = page_mapping(page);
690         struct page **radix_pointer;
691
692         /*
693          * Avoid doing any of the following work if the page count
694          * indicates that the page is in use or truncate has removed
695          * the page.
696          */
697         if (!mapping || page_mapcount(page) + nr_refs != page_count(page))
698                 return -EAGAIN;
699
700         /*
701          * Establish swap ptes for anonymous pages or destroy pte
702          * maps for files.
703          *
704          * In order to reestablish file backed mappings the fault handlers
705          * will take the radix tree_lock which may then be used to stop
706          * processses from accessing this page until the new page is ready.
707          *
708          * A process accessing via a swap pte (an anonymous page) will take a
709          * page_lock on the old page which will block the process until the
710          * migration attempt is complete. At that time the PageSwapCache bit
711          * will be examined. If the page was migrated then the PageSwapCache
712          * bit will be clear and the operation to retrieve the page will be
713          * retried which will find the new page in the radix tree. Then a new
714          * direct mapping may be generated based on the radix tree contents.
715          *
716          * If the page was not migrated then the PageSwapCache bit
717          * is still set and the operation may continue.
718          */
719         if (try_to_unmap(page, 1) == SWAP_FAIL)
720                 /* A vma has VM_LOCKED set -> Permanent failure */
721                 return -EPERM;
722
723         /*
724          * Give up if we were unable to remove all mappings.
725          */
726         if (page_mapcount(page))
727                 return -EAGAIN;
728
729         write_lock_irq(&mapping->tree_lock);
730
731         radix_pointer = (struct page **)radix_tree_lookup_slot(
732                                                 &mapping->page_tree,
733                                                 page_index(page));
734
735         if (!page_mapping(page) || page_count(page) != nr_refs ||
736                         *radix_pointer != page) {
737                 write_unlock_irq(&mapping->tree_lock);
738                 return -EAGAIN;
739         }
740
741         /*
742          * Now we know that no one else is looking at the page.
743          *
744          * Certain minimal information about a page must be available
745          * in order for other subsystems to properly handle the page if they
746          * find it through the radix tree update before we are finished
747          * copying the page.
748          */
749         get_page(newpage);
750         newpage->index = page->index;
751         newpage->mapping = page->mapping;
752         if (PageSwapCache(page)) {
753                 SetPageSwapCache(newpage);
754                 set_page_private(newpage, page_private(page));
755         }
756
757         *radix_pointer = newpage;
758         __put_page(page);
759         write_unlock_irq(&mapping->tree_lock);
760
761         return 0;
762 }
763 EXPORT_SYMBOL(migrate_page_remove_references);
764
765 /*
766  * Copy the page to its new location
767  */
768 void migrate_page_copy(struct page *newpage, struct page *page)
769 {
770         copy_highpage(newpage, page);
771
772         if (PageError(page))
773                 SetPageError(newpage);
774         if (PageReferenced(page))
775                 SetPageReferenced(newpage);
776         if (PageUptodate(page))
777                 SetPageUptodate(newpage);
778         if (PageActive(page))
779                 SetPageActive(newpage);
780         if (PageChecked(page))
781                 SetPageChecked(newpage);
782         if (PageMappedToDisk(page))
783                 SetPageMappedToDisk(newpage);
784
785         if (PageDirty(page)) {
786                 clear_page_dirty_for_io(page);
787                 set_page_dirty(newpage);
788         }
789
790         ClearPageSwapCache(page);
791         ClearPageActive(page);
792         ClearPagePrivate(page);
793         set_page_private(page, 0);
794         page->mapping = NULL;
795
796         /*
797          * If any waiters have accumulated on the new page then
798          * wake them up.
799          */
800         if (PageWriteback(newpage))
801                 end_page_writeback(newpage);
802 }
803 EXPORT_SYMBOL(migrate_page_copy);
804
805 /*
806  * Common logic to directly migrate a single page suitable for
807  * pages that do not use PagePrivate.
808  *
809  * Pages are locked upon entry and exit.
810  */
811 int migrate_page(struct page *newpage, struct page *page)
812 {
813         int rc;
814
815         BUG_ON(PageWriteback(page));    /* Writeback must be complete */
816
817         rc = migrate_page_remove_references(newpage, page, 2);
818
819         if (rc)
820                 return rc;
821
822         migrate_page_copy(newpage, page);
823
824         /*
825          * Remove auxiliary swap entries and replace
826          * them with real ptes.
827          *
828          * Note that a real pte entry will allow processes that are not
829          * waiting on the page lock to use the new page via the page tables
830          * before the new page is unlocked.
831          */
832         remove_from_swap(newpage);
833         return 0;
834 }
835 EXPORT_SYMBOL(migrate_page);
836
837 /*
838  * migrate_pages
839  *
840  * Two lists are passed to this function. The first list
841  * contains the pages isolated from the LRU to be migrated.
842  * The second list contains new pages that the pages isolated
843  * can be moved to. If the second list is NULL then all
844  * pages are swapped out.
845  *
846  * The function returns after 10 attempts or if no pages
847  * are movable anymore because to has become empty
848  * or no retryable pages exist anymore.
849  *
850  * Return: Number of pages not migrated when "to" ran empty.
851  */
852 unsigned long migrate_pages(struct list_head *from, struct list_head *to,
853                   struct list_head *moved, struct list_head *failed)
854 {
855         unsigned long retry;
856         unsigned long nr_failed = 0;
857         int pass = 0;
858         struct page *page;
859         struct page *page2;
860         int swapwrite = current->flags & PF_SWAPWRITE;
861         int rc;
862
863         if (!swapwrite)
864                 current->flags |= PF_SWAPWRITE;
865
866 redo:
867         retry = 0;
868
869         list_for_each_entry_safe(page, page2, from, lru) {
870                 struct page *newpage = NULL;
871                 struct address_space *mapping;
872
873                 cond_resched();
874
875                 rc = 0;
876                 if (page_count(page) == 1)
877                         /* page was freed from under us. So we are done. */
878                         goto next;
879
880                 if (to && list_empty(to))
881                         break;
882
883                 /*
884                  * Skip locked pages during the first two passes to give the
885                  * functions holding the lock time to release the page. Later we
886                  * use lock_page() to have a higher chance of acquiring the
887                  * lock.
888                  */
889                 rc = -EAGAIN;
890                 if (pass > 2)
891                         lock_page(page);
892                 else
893                         if (TestSetPageLocked(page))
894                                 goto next;
895
896                 /*
897                  * Only wait on writeback if we have already done a pass where
898                  * we we may have triggered writeouts for lots of pages.
899                  */
900                 if (pass > 0) {
901                         wait_on_page_writeback(page);
902                 } else {
903                         if (PageWriteback(page))
904                                 goto unlock_page;
905                 }
906
907                 /*
908                  * Anonymous pages must have swap cache references otherwise
909                  * the information contained in the page maps cannot be
910                  * preserved.
911                  */
912                 if (PageAnon(page) && !PageSwapCache(page)) {
913                         if (!add_to_swap(page, GFP_KERNEL)) {
914                                 rc = -ENOMEM;
915                                 goto unlock_page;
916                         }
917                 }
918
919                 if (!to) {
920                         rc = swap_page(page);
921                         goto next;
922                 }
923
924                 newpage = lru_to_page(to);
925                 lock_page(newpage);
926
927                 /*
928                  * Pages are properly locked and writeback is complete.
929                  * Try to migrate the page.
930                  */
931                 mapping = page_mapping(page);
932                 if (!mapping)
933                         goto unlock_both;
934
935                 if (mapping->a_ops->migratepage) {
936                         /*
937                          * Most pages have a mapping and most filesystems
938                          * should provide a migration function. Anonymous
939                          * pages are part of swap space which also has its
940                          * own migration function. This is the most common
941                          * path for page migration.
942                          */
943                         rc = mapping->a_ops->migratepage(newpage, page);
944                         goto unlock_both;
945                 }
946
947                 /*
948                  * Default handling if a filesystem does not provide
949                  * a migration function. We can only migrate clean
950                  * pages so try to write out any dirty pages first.
951                  */
952                 if (PageDirty(page)) {
953                         switch (pageout(page, mapping)) {
954                         case PAGE_KEEP:
955                         case PAGE_ACTIVATE:
956                                 goto unlock_both;
957
958                         case PAGE_SUCCESS:
959                                 unlock_page(newpage);
960                                 goto next;
961
962                         case PAGE_CLEAN:
963                                 ; /* try to migrate the page below */
964                         }
965                 }
966
967                 /*
968                  * Buffers are managed in a filesystem specific way.
969                  * We must have no buffers or drop them.
970                  */
971                 if (!page_has_buffers(page) ||
972                     try_to_release_page(page, GFP_KERNEL)) {
973                         rc = migrate_page(newpage, page);
974                         goto unlock_both;
975                 }
976
977                 /*
978                  * On early passes with mapped pages simply
979                  * retry. There may be a lock held for some
980                  * buffers that may go away. Later
981                  * swap them out.
982                  */
983                 if (pass > 4) {
984                         /*
985                          * Persistently unable to drop buffers..... As a
986                          * measure of last resort we fall back to
987                          * swap_page().
988                          */
989                         unlock_page(newpage);
990                         newpage = NULL;
991                         rc = swap_page(page);
992                         goto next;
993                 }
994
995 unlock_both:
996                 unlock_page(newpage);
997
998 unlock_page:
999                 unlock_page(page);
1000
1001 next:
1002                 if (rc == -EAGAIN) {
1003                         retry++;
1004                 } else if (rc) {
1005                         /* Permanent failure */
1006                         list_move(&page->lru, failed);
1007                         nr_failed++;
1008                 } else {
1009                         if (newpage) {
1010                                 /* Successful migration. Return page to LRU */
1011                                 move_to_lru(newpage);
1012                         }
1013                         list_move(&page->lru, moved);
1014                 }
1015         }
1016         if (retry && pass++ < 10)
1017                 goto redo;
1018
1019         if (!swapwrite)
1020                 current->flags &= ~PF_SWAPWRITE;
1021
1022         return nr_failed + retry;
1023 }
1024
1025 /*
1026  * Isolate one page from the LRU lists and put it on the
1027  * indicated list with elevated refcount.
1028  *
1029  * Result:
1030  *  0 = page not on LRU list
1031  *  1 = page removed from LRU list and added to the specified list.
1032  */
1033 int isolate_lru_page(struct page *page)
1034 {
1035         int ret = 0;
1036
1037         if (PageLRU(page)) {
1038                 struct zone *zone = page_zone(page);
1039                 spin_lock_irq(&zone->lru_lock);
1040                 if (PageLRU(page)) {
1041                         ret = 1;
1042                         get_page(page);
1043                         ClearPageLRU(page);
1044                         if (PageActive(page))
1045                                 del_page_from_active_list(zone, page);
1046                         else
1047                                 del_page_from_inactive_list(zone, page);
1048                 }
1049                 spin_unlock_irq(&zone->lru_lock);
1050         }
1051
1052         return ret;
1053 }
1054 #endif
1055
1056 /*
1057  * zone->lru_lock is heavily contended.  Some of the functions that
1058  * shrink the lists perform better by taking out a batch of pages
1059  * and working on them outside the LRU lock.
1060  *
1061  * For pagecache intensive workloads, this function is the hottest
1062  * spot in the kernel (apart from copy_*_user functions).
1063  *
1064  * Appropriate locks must be held before calling this function.
1065  *
1066  * @nr_to_scan: The number of pages to look through on the list.
1067  * @src:        The LRU list to pull pages off.
1068  * @dst:        The temp list to put pages on to.
1069  * @scanned:    The number of pages that were scanned.
1070  *
1071  * returns how many pages were moved onto *@dst.
1072  */
1073 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1074                 struct list_head *src, struct list_head *dst,
1075                 unsigned long *scanned)
1076 {
1077         unsigned long nr_taken = 0;
1078         struct page *page;
1079         unsigned long scan;
1080
1081         for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
1082                 struct list_head *target;
1083                 page = lru_to_page(src);
1084                 prefetchw_prev_lru_page(page, src, flags);
1085
1086                 BUG_ON(!PageLRU(page));
1087
1088                 list_del(&page->lru);
1089                 target = src;
1090                 if (likely(get_page_unless_zero(page))) {
1091                         /*
1092                          * Be careful not to clear PageLRU until after we're
1093                          * sure the page is not being freed elsewhere -- the
1094                          * page release code relies on it.
1095                          */
1096                         ClearPageLRU(page);
1097                         target = dst;
1098                         nr_taken++;
1099                 } /* else it is being freed elsewhere */
1100
1101                 list_add(&page->lru, target);
1102         }
1103
1104         *scanned = scan;
1105         return nr_taken;
1106 }
1107
1108 /*
1109  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
1110  * of reclaimed pages
1111  */
1112 static unsigned long shrink_inactive_list(unsigned long max_scan,
1113                                 struct zone *zone, struct scan_control *sc)
1114 {
1115         LIST_HEAD(page_list);
1116         struct pagevec pvec;
1117         unsigned long nr_scanned = 0;
1118         unsigned long nr_reclaimed = 0;
1119
1120         pagevec_init(&pvec, 1);
1121
1122         lru_add_drain();
1123         spin_lock_irq(&zone->lru_lock);
1124         do {
1125                 struct page *page;
1126                 unsigned long nr_taken;
1127                 unsigned long nr_scan;
1128                 unsigned long nr_freed;
1129
1130                 nr_taken = isolate_lru_pages(sc->swap_cluster_max,
1131                                              &zone->inactive_list,
1132                                              &page_list, &nr_scan);
1133                 zone->nr_inactive -= nr_taken;
1134                 zone->pages_scanned += nr_scan;
1135                 spin_unlock_irq(&zone->lru_lock);
1136
1137                 nr_scanned += nr_scan;
1138                 nr_freed = shrink_page_list(&page_list, sc);
1139                 nr_reclaimed += nr_freed;
1140                 local_irq_disable();
1141                 if (current_is_kswapd()) {
1142                         __mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
1143                         __mod_page_state(kswapd_steal, nr_freed);
1144                 } else
1145                         __mod_page_state_zone(zone, pgscan_direct, nr_scan);
1146                 __mod_page_state_zone(zone, pgsteal, nr_freed);
1147
1148                 if (nr_taken == 0)
1149                         goto done;
1150
1151                 spin_lock(&zone->lru_lock);
1152                 /*
1153                  * Put back any unfreeable pages.
1154                  */
1155                 while (!list_empty(&page_list)) {
1156                         page = lru_to_page(&page_list);
1157                         BUG_ON(PageLRU(page));
1158                         SetPageLRU(page);
1159                         list_del(&page->lru);
1160                         if (PageActive(page))
1161                                 add_page_to_active_list(zone, page);
1162                         else
1163                                 add_page_to_inactive_list(zone, page);
1164                         if (!pagevec_add(&pvec, page)) {
1165                                 spin_unlock_irq(&zone->lru_lock);
1166                                 __pagevec_release(&pvec);
1167                                 spin_lock_irq(&zone->lru_lock);
1168                         }
1169                 }
1170         } while (nr_scanned < max_scan);
1171         spin_unlock(&zone->lru_lock);
1172 done:
1173         local_irq_enable();
1174         pagevec_release(&pvec);
1175         return nr_reclaimed;
1176 }
1177
1178 /*
1179  * This moves pages from the active list to the inactive list.
1180  *
1181  * We move them the other way if the page is referenced by one or more
1182  * processes, from rmap.
1183  *
1184  * If the pages are mostly unmapped, the processing is fast and it is
1185  * appropriate to hold zone->lru_lock across the whole operation.  But if
1186  * the pages are mapped, the processing is slow (page_referenced()) so we
1187  * should drop zone->lru_lock around each page.  It's impossible to balance
1188  * this, so instead we remove the pages from the LRU while processing them.
1189  * It is safe to rely on PG_active against the non-LRU pages in here because
1190  * nobody will play with that bit on a non-LRU page.
1191  *
1192  * The downside is that we have to touch page->_count against each page.
1193  * But we had to alter page->flags anyway.
1194  */
1195 static void shrink_active_list(unsigned long nr_pages, struct zone *zone,
1196                                 struct scan_control *sc)
1197 {
1198         unsigned long pgmoved;
1199         int pgdeactivate = 0;
1200         unsigned long pgscanned;
1201         LIST_HEAD(l_hold);      /* The pages which were snipped off */
1202         LIST_HEAD(l_inactive);  /* Pages to go onto the inactive_list */
1203         LIST_HEAD(l_active);    /* Pages to go onto the active_list */
1204         struct page *page;
1205         struct pagevec pvec;
1206         int reclaim_mapped = 0;
1207
1208         if (unlikely(sc->may_swap)) {
1209                 long mapped_ratio;
1210                 long distress;
1211                 long swap_tendency;
1212
1213                 /*
1214                  * `distress' is a measure of how much trouble we're having
1215                  * reclaiming pages.  0 -> no problems.  100 -> great trouble.
1216                  */
1217                 distress = 100 >> zone->prev_priority;
1218
1219                 /*
1220                  * The point of this algorithm is to decide when to start
1221                  * reclaiming mapped memory instead of just pagecache.  Work out
1222                  * how much memory
1223                  * is mapped.
1224                  */
1225                 mapped_ratio = (sc->nr_mapped * 100) / total_memory;
1226
1227                 /*
1228                  * Now decide how much we really want to unmap some pages.  The
1229                  * mapped ratio is downgraded - just because there's a lot of
1230                  * mapped memory doesn't necessarily mean that page reclaim
1231                  * isn't succeeding.
1232                  *
1233                  * The distress ratio is important - we don't want to start
1234                  * going oom.
1235                  *
1236                  * A 100% value of vm_swappiness overrides this algorithm
1237                  * altogether.
1238                  */
1239                 swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
1240
1241                 /*
1242                  * Now use this metric to decide whether to start moving mapped
1243                  * memory onto the inactive list.
1244                  */
1245                 if (swap_tendency >= 100)
1246                         reclaim_mapped = 1;
1247         }
1248
1249         lru_add_drain();
1250         spin_lock_irq(&zone->lru_lock);
1251         pgmoved = isolate_lru_pages(nr_pages, &zone->active_list,
1252                                     &l_hold, &pgscanned);
1253         zone->pages_scanned += pgscanned;
1254         zone->nr_active -= pgmoved;
1255         spin_unlock_irq(&zone->lru_lock);
1256
1257         while (!list_empty(&l_hold)) {
1258                 cond_resched();
1259                 page = lru_to_page(&l_hold);
1260                 list_del(&page->lru);
1261                 if (page_mapped(page)) {
1262                         if (!reclaim_mapped ||
1263                             (total_swap_pages == 0 && PageAnon(page)) ||
1264                             page_referenced(page, 0)) {
1265                                 list_add(&page->lru, &l_active);
1266                                 continue;
1267                         }
1268                 }
1269                 list_add(&page->lru, &l_inactive);
1270         }
1271
1272         pagevec_init(&pvec, 1);
1273         pgmoved = 0;
1274         spin_lock_irq(&zone->lru_lock);
1275         while (!list_empty(&l_inactive)) {
1276                 page = lru_to_page(&l_inactive);
1277                 prefetchw_prev_lru_page(page, &l_inactive, flags);
1278                 BUG_ON(PageLRU(page));
1279                 SetPageLRU(page);
1280                 BUG_ON(!PageActive(page));
1281                 ClearPageActive(page);
1282
1283                 list_move(&page->lru, &zone->inactive_list);
1284                 pgmoved++;
1285                 if (!pagevec_add(&pvec, page)) {
1286                         zone->nr_inactive += pgmoved;
1287                         spin_unlock_irq(&zone->lru_lock);
1288                         pgdeactivate += pgmoved;
1289                         pgmoved = 0;
1290                         if (buffer_heads_over_limit)
1291                                 pagevec_strip(&pvec);
1292                         __pagevec_release(&pvec);
1293                         spin_lock_irq(&zone->lru_lock);
1294                 }
1295         }
1296         zone->nr_inactive += pgmoved;
1297         pgdeactivate += pgmoved;
1298         if (buffer_heads_over_limit) {
1299                 spin_unlock_irq(&zone->lru_lock);
1300                 pagevec_strip(&pvec);
1301                 spin_lock_irq(&zone->lru_lock);
1302         }
1303
1304         pgmoved = 0;
1305         while (!list_empty(&l_active)) {
1306                 page = lru_to_page(&l_active);
1307                 prefetchw_prev_lru_page(page, &l_active, flags);
1308                 BUG_ON(PageLRU(page));
1309                 SetPageLRU(page);
1310                 BUG_ON(!PageActive(page));
1311                 list_move(&page->lru, &zone->active_list);
1312                 pgmoved++;
1313                 if (!pagevec_add(&pvec, page)) {
1314                         zone->nr_active += pgmoved;
1315                         pgmoved = 0;
1316                         spin_unlock_irq(&zone->lru_lock);
1317                         __pagevec_release(&pvec);
1318                         spin_lock_irq(&zone->lru_lock);
1319                 }
1320         }
1321         zone->nr_active += pgmoved;
1322         spin_unlock(&zone->lru_lock);
1323
1324         __mod_page_state_zone(zone, pgrefill, pgscanned);
1325         __mod_page_state(pgdeactivate, pgdeactivate);
1326         local_irq_enable();
1327
1328         pagevec_release(&pvec);
1329 }
1330
1331 /*
1332  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
1333  */
1334 static unsigned long shrink_zone(int priority, struct zone *zone,
1335                                 struct scan_control *sc)
1336 {
1337         unsigned long nr_active;
1338         unsigned long nr_inactive;
1339         unsigned long nr_to_scan;
1340         unsigned long nr_reclaimed = 0;
1341
1342         atomic_inc(&zone->reclaim_in_progress);
1343
1344         /*
1345          * Add one to `nr_to_scan' just to make sure that the kernel will
1346          * slowly sift through the active list.
1347          */
1348         zone->nr_scan_active += (zone->nr_active >> priority) + 1;
1349         nr_active = zone->nr_scan_active;
1350         if (nr_active >= sc->swap_cluster_max)
1351                 zone->nr_scan_active = 0;
1352         else
1353                 nr_active = 0;
1354
1355         zone->nr_scan_inactive += (zone->nr_inactive >> priority) + 1;
1356         nr_inactive = zone->nr_scan_inactive;
1357         if (nr_inactive >= sc->swap_cluster_max)
1358                 zone->nr_scan_inactive = 0;
1359         else
1360                 nr_inactive = 0;
1361
1362         while (nr_active || nr_inactive) {
1363                 if (nr_active) {
1364                         nr_to_scan = min(nr_active,
1365                                         (unsigned long)sc->swap_cluster_max);
1366                         nr_active -= nr_to_scan;
1367                         shrink_active_list(nr_to_scan, zone, sc);
1368                 }
1369
1370                 if (nr_inactive) {
1371                         nr_to_scan = min(nr_inactive,
1372                                         (unsigned long)sc->swap_cluster_max);
1373                         nr_inactive -= nr_to_scan;
1374                         nr_reclaimed += shrink_inactive_list(nr_to_scan, zone,
1375                                                                 sc);
1376                 }
1377         }
1378
1379         throttle_vm_writeout();
1380
1381         atomic_dec(&zone->reclaim_in_progress);
1382         return nr_reclaimed;
1383 }
1384
1385 /*
1386  * This is the direct reclaim path, for page-allocating processes.  We only
1387  * try to reclaim pages from zones which will satisfy the caller's allocation
1388  * request.
1389  *
1390  * We reclaim from a zone even if that zone is over pages_high.  Because:
1391  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
1392  *    allocation or
1393  * b) The zones may be over pages_high but they must go *over* pages_high to
1394  *    satisfy the `incremental min' zone defense algorithm.
1395  *
1396  * Returns the number of reclaimed pages.
1397  *
1398  * If a zone is deemed to be full of pinned pages then just give it a light
1399  * scan then give up on it.
1400  */
1401 static unsigned long shrink_zones(int priority, struct zone **zones,
1402                                         struct scan_control *sc)
1403 {
1404         unsigned long nr_reclaimed = 0;
1405         int i;
1406
1407         for (i = 0; zones[i] != NULL; i++) {
1408                 struct zone *zone = zones[i];
1409
1410                 if (!populated_zone(zone))
1411                         continue;
1412
1413                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1414                         continue;
1415
1416                 zone->temp_priority = priority;
1417                 if (zone->prev_priority > priority)
1418                         zone->prev_priority = priority;
1419
1420                 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1421                         continue;       /* Let kswapd poll it */
1422
1423                 nr_reclaimed += shrink_zone(priority, zone, sc);
1424         }
1425         return nr_reclaimed;
1426 }
1427  
1428 /*
1429  * This is the main entry point to direct page reclaim.
1430  *
1431  * If a full scan of the inactive list fails to free enough memory then we
1432  * are "out of memory" and something needs to be killed.
1433  *
1434  * If the caller is !__GFP_FS then the probability of a failure is reasonably
1435  * high - the zone may be full of dirty or under-writeback pages, which this
1436  * caller can't do much about.  We kick pdflush and take explicit naps in the
1437  * hope that some of these pages can be written.  But if the allocating task
1438  * holds filesystem locks which prevent writeout this might not work, and the
1439  * allocation attempt will fail.
1440  */
1441 unsigned long try_to_free_pages(struct zone **zones, gfp_t gfp_mask)
1442 {
1443         int priority;
1444         int ret = 0;
1445         unsigned long total_scanned = 0;
1446         unsigned long nr_reclaimed = 0;
1447         struct reclaim_state *reclaim_state = current->reclaim_state;
1448         unsigned long lru_pages = 0;
1449         int i;
1450         struct scan_control sc = {
1451                 .gfp_mask = gfp_mask,
1452                 .may_writepage = !laptop_mode,
1453                 .swap_cluster_max = SWAP_CLUSTER_MAX,
1454                 .may_swap = 1,
1455         };
1456
1457         inc_page_state(allocstall);
1458
1459         for (i = 0; zones[i] != NULL; i++) {
1460                 struct zone *zone = zones[i];
1461
1462                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1463                         continue;
1464
1465                 zone->temp_priority = DEF_PRIORITY;
1466                 lru_pages += zone->nr_active + zone->nr_inactive;
1467         }
1468
1469         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1470                 sc.nr_mapped = read_page_state(nr_mapped);
1471                 sc.nr_scanned = 0;
1472                 if (!priority)
1473                         disable_swap_token();
1474                 nr_reclaimed += shrink_zones(priority, zones, &sc);
1475                 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1476                 if (reclaim_state) {
1477                         nr_reclaimed += reclaim_state->reclaimed_slab;
1478                         reclaim_state->reclaimed_slab = 0;
1479                 }
1480                 total_scanned += sc.nr_scanned;
1481                 if (nr_reclaimed >= sc.swap_cluster_max) {
1482                         ret = 1;
1483                         goto out;
1484                 }
1485
1486                 /*
1487                  * Try to write back as many pages as we just scanned.  This
1488                  * tends to cause slow streaming writers to write data to the
1489                  * disk smoothly, at the dirtying rate, which is nice.   But
1490                  * that's undesirable in laptop mode, where we *want* lumpy
1491                  * writeout.  So in laptop mode, write out the whole world.
1492                  */
1493                 if (total_scanned > sc.swap_cluster_max +
1494                                         sc.swap_cluster_max / 2) {
1495                         wakeup_pdflush(laptop_mode ? 0 : total_scanned);
1496                         sc.may_writepage = 1;
1497                 }
1498
1499                 /* Take a nap, wait for some writeback to complete */
1500                 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1501                         blk_congestion_wait(WRITE, HZ/10);
1502         }
1503 out:
1504         for (i = 0; zones[i] != 0; i++) {
1505                 struct zone *zone = zones[i];
1506
1507                 if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1508                         continue;
1509
1510                 zone->prev_priority = zone->temp_priority;
1511         }
1512         return ret;
1513 }
1514
1515 /*
1516  * For kswapd, balance_pgdat() will work across all this node's zones until
1517  * they are all at pages_high.
1518  *
1519  * If `nr_pages' is non-zero then it is the number of pages which are to be
1520  * reclaimed, regardless of the zone occupancies.  This is a software suspend
1521  * special.
1522  *
1523  * Returns the number of pages which were actually freed.
1524  *
1525  * There is special handling here for zones which are full of pinned pages.
1526  * This can happen if the pages are all mlocked, or if they are all used by
1527  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
1528  * What we do is to detect the case where all pages in the zone have been
1529  * scanned twice and there has been zero successful reclaim.  Mark the zone as
1530  * dead and from now on, only perform a short scan.  Basically we're polling
1531  * the zone for when the problem goes away.
1532  *
1533  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
1534  * zones which have free_pages > pages_high, but once a zone is found to have
1535  * free_pages <= pages_high, we scan that zone and the lower zones regardless
1536  * of the number of free pages in the lower zones.  This interoperates with
1537  * the page allocator fallback scheme to ensure that aging of pages is balanced
1538  * across the zones.
1539  */
1540 static unsigned long balance_pgdat(pg_data_t *pgdat, unsigned long nr_pages,
1541                                 int order)
1542 {
1543         unsigned long to_free = nr_pages;
1544         int all_zones_ok;
1545         int priority;
1546         int i;
1547         unsigned long total_scanned;
1548         unsigned long nr_reclaimed;
1549         struct reclaim_state *reclaim_state = current->reclaim_state;
1550         struct scan_control sc = {
1551                 .gfp_mask = GFP_KERNEL,
1552                 .may_swap = 1,
1553                 .swap_cluster_max = nr_pages ? nr_pages : SWAP_CLUSTER_MAX,
1554         };
1555
1556 loop_again:
1557         total_scanned = 0;
1558         nr_reclaimed = 0;
1559         sc.may_writepage = !laptop_mode,
1560         sc.nr_mapped = read_page_state(nr_mapped);
1561
1562         inc_page_state(pageoutrun);
1563
1564         for (i = 0; i < pgdat->nr_zones; i++) {
1565                 struct zone *zone = pgdat->node_zones + i;
1566
1567                 zone->temp_priority = DEF_PRIORITY;
1568         }
1569
1570         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1571                 int end_zone = 0;       /* Inclusive.  0 = ZONE_DMA */
1572                 unsigned long lru_pages = 0;
1573
1574                 /* The swap token gets in the way of swapout... */
1575                 if (!priority)
1576                         disable_swap_token();
1577
1578                 all_zones_ok = 1;
1579
1580                 if (nr_pages == 0) {
1581                         /*
1582                          * Scan in the highmem->dma direction for the highest
1583                          * zone which needs scanning
1584                          */
1585                         for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1586                                 struct zone *zone = pgdat->node_zones + i;
1587
1588                                 if (!populated_zone(zone))
1589                                         continue;
1590
1591                                 if (zone->all_unreclaimable &&
1592                                                 priority != DEF_PRIORITY)
1593                                         continue;
1594
1595                                 if (!zone_watermark_ok(zone, order,
1596                                                 zone->pages_high, 0, 0)) {
1597                                         end_zone = i;
1598                                         goto scan;
1599                                 }
1600                         }
1601                         goto out;
1602                 } else {
1603                         end_zone = pgdat->nr_zones - 1;
1604                 }
1605 scan:
1606                 for (i = 0; i <= end_zone; i++) {
1607                         struct zone *zone = pgdat->node_zones + i;
1608
1609                         lru_pages += zone->nr_active + zone->nr_inactive;
1610                 }
1611
1612                 /*
1613                  * Now scan the zone in the dma->highmem direction, stopping
1614                  * at the last zone which needs scanning.
1615                  *
1616                  * We do this because the page allocator works in the opposite
1617                  * direction.  This prevents the page allocator from allocating
1618                  * pages behind kswapd's direction of progress, which would
1619                  * cause too much scanning of the lower zones.
1620                  */
1621                 for (i = 0; i <= end_zone; i++) {
1622                         struct zone *zone = pgdat->node_zones + i;
1623                         int nr_slab;
1624
1625                         if (!populated_zone(zone))
1626                                 continue;
1627
1628                         if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1629                                 continue;
1630
1631                         if (nr_pages == 0) {    /* Not software suspend */
1632                                 if (!zone_watermark_ok(zone, order,
1633                                                 zone->pages_high, end_zone, 0))
1634                                         all_zones_ok = 0;
1635                         }
1636                         zone->temp_priority = priority;
1637                         if (zone->prev_priority > priority)
1638                                 zone->prev_priority = priority;
1639                         sc.nr_scanned = 0;
1640                         nr_reclaimed += shrink_zone(priority, zone, &sc);
1641                         reclaim_state->reclaimed_slab = 0;
1642                         nr_slab = shrink_slab(sc.nr_scanned, GFP_KERNEL,
1643                                                 lru_pages);
1644                         nr_reclaimed += reclaim_state->reclaimed_slab;
1645                         total_scanned += sc.nr_scanned;
1646                         if (zone->all_unreclaimable)
1647                                 continue;
1648                         if (nr_slab == 0 && zone->pages_scanned >=
1649                                     (zone->nr_active + zone->nr_inactive) * 4)
1650                                 zone->all_unreclaimable = 1;
1651                         /*
1652                          * If we've done a decent amount of scanning and
1653                          * the reclaim ratio is low, start doing writepage
1654                          * even in laptop mode
1655                          */
1656                         if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1657                             total_scanned > nr_reclaimed + nr_reclaimed / 2)
1658                                 sc.may_writepage = 1;
1659                 }
1660                 if (nr_pages && to_free > nr_reclaimed)
1661                         continue;       /* swsusp: need to do more work */
1662                 if (all_zones_ok)
1663                         break;          /* kswapd: all done */
1664                 /*
1665                  * OK, kswapd is getting into trouble.  Take a nap, then take
1666                  * another pass across the zones.
1667                  */
1668                 if (total_scanned && priority < DEF_PRIORITY - 2)
1669                         blk_congestion_wait(WRITE, HZ/10);
1670
1671                 /*
1672                  * We do this so kswapd doesn't build up large priorities for
1673                  * example when it is freeing in parallel with allocators. It
1674                  * matches the direct reclaim path behaviour in terms of impact
1675                  * on zone->*_priority.
1676                  */
1677                 if ((nr_reclaimed >= SWAP_CLUSTER_MAX) && !nr_pages)
1678                         break;
1679         }
1680 out:
1681         for (i = 0; i < pgdat->nr_zones; i++) {
1682                 struct zone *zone = pgdat->node_zones + i;
1683
1684                 zone->prev_priority = zone->temp_priority;
1685         }
1686         if (!all_zones_ok) {
1687                 cond_resched();
1688                 goto loop_again;
1689         }
1690
1691         return nr_reclaimed;
1692 }
1693
1694 /*
1695  * The background pageout daemon, started as a kernel thread
1696  * from the init process. 
1697  *
1698  * This basically trickles out pages so that we have _some_
1699  * free memory available even if there is no other activity
1700  * that frees anything up. This is needed for things like routing
1701  * etc, where we otherwise might have all activity going on in
1702  * asynchronous contexts that cannot page things out.
1703  *
1704  * If there are applications that are active memory-allocators
1705  * (most normal use), this basically shouldn't matter.
1706  */
1707 static int kswapd(void *p)
1708 {
1709         unsigned long order;
1710         pg_data_t *pgdat = (pg_data_t*)p;
1711         struct task_struct *tsk = current;
1712         DEFINE_WAIT(wait);
1713         struct reclaim_state reclaim_state = {
1714                 .reclaimed_slab = 0,
1715         };
1716         cpumask_t cpumask;
1717
1718         daemonize("kswapd%d", pgdat->node_id);
1719         cpumask = node_to_cpumask(pgdat->node_id);
1720         if (!cpus_empty(cpumask))
1721                 set_cpus_allowed(tsk, cpumask);
1722         current->reclaim_state = &reclaim_state;
1723
1724         /*
1725          * Tell the memory management that we're a "memory allocator",
1726          * and that if we need more memory we should get access to it
1727          * regardless (see "__alloc_pages()"). "kswapd" should
1728          * never get caught in the normal page freeing logic.
1729          *
1730          * (Kswapd normally doesn't need memory anyway, but sometimes
1731          * you need a small amount of memory in order to be able to
1732          * page out something else, and this flag essentially protects
1733          * us from recursively trying to free more memory as we're
1734          * trying to free the first piece of memory in the first place).
1735          */
1736         tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
1737
1738         order = 0;
1739         for ( ; ; ) {
1740                 unsigned long new_order;
1741
1742                 try_to_freeze();
1743
1744                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1745                 new_order = pgdat->kswapd_max_order;
1746                 pgdat->kswapd_max_order = 0;
1747                 if (order < new_order) {
1748                         /*
1749                          * Don't sleep if someone wants a larger 'order'
1750                          * allocation
1751                          */
1752                         order = new_order;
1753                 } else {
1754                         schedule();
1755                         order = pgdat->kswapd_max_order;
1756                 }
1757                 finish_wait(&pgdat->kswapd_wait, &wait);
1758
1759                 balance_pgdat(pgdat, 0, order);
1760         }
1761         return 0;
1762 }
1763
1764 /*
1765  * A zone is low on free memory, so wake its kswapd task to service it.
1766  */
1767 void wakeup_kswapd(struct zone *zone, int order)
1768 {
1769         pg_data_t *pgdat;
1770
1771         if (!populated_zone(zone))
1772                 return;
1773
1774         pgdat = zone->zone_pgdat;
1775         if (zone_watermark_ok(zone, order, zone->pages_low, 0, 0))
1776                 return;
1777         if (pgdat->kswapd_max_order < order)
1778                 pgdat->kswapd_max_order = order;
1779         if (!cpuset_zone_allowed(zone, __GFP_HARDWALL))
1780                 return;
1781         if (!waitqueue_active(&pgdat->kswapd_wait))
1782                 return;
1783         wake_up_interruptible(&pgdat->kswapd_wait);
1784 }
1785
1786 #ifdef CONFIG_PM
1787 /*
1788  * Try to free `nr_pages' of memory, system-wide.  Returns the number of freed
1789  * pages.
1790  */
1791 unsigned long shrink_all_memory(unsigned long nr_pages)
1792 {
1793         pg_data_t *pgdat;
1794         unsigned long nr_to_free = nr_pages;
1795         unsigned long ret = 0;
1796         struct reclaim_state reclaim_state = {
1797                 .reclaimed_slab = 0,
1798         };
1799
1800         current->reclaim_state = &reclaim_state;
1801         for_each_pgdat(pgdat) {
1802                 unsigned long freed;
1803
1804                 freed = balance_pgdat(pgdat, nr_to_free, 0);
1805                 ret += freed;
1806                 nr_to_free -= freed;
1807                 if ((long)nr_to_free <= 0)
1808                         break;
1809         }
1810         current->reclaim_state = NULL;
1811         return ret;
1812 }
1813 #endif
1814
1815 #ifdef CONFIG_HOTPLUG_CPU
1816 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1817    not required for correctness.  So if the last cpu in a node goes
1818    away, we get changed to run anywhere: as the first one comes back,
1819    restore their cpu bindings. */
1820 static int __devinit cpu_callback(struct notifier_block *nfb,
1821                                   unsigned long action, void *hcpu)
1822 {
1823         pg_data_t *pgdat;
1824         cpumask_t mask;
1825
1826         if (action == CPU_ONLINE) {
1827                 for_each_pgdat(pgdat) {
1828                         mask = node_to_cpumask(pgdat->node_id);
1829                         if (any_online_cpu(mask) != NR_CPUS)
1830                                 /* One of our CPUs online: restore mask */
1831                                 set_cpus_allowed(pgdat->kswapd, mask);
1832                 }
1833         }
1834         return NOTIFY_OK;
1835 }
1836 #endif /* CONFIG_HOTPLUG_CPU */
1837
1838 static int __init kswapd_init(void)
1839 {
1840         pg_data_t *pgdat;
1841
1842         swap_setup();
1843         for_each_pgdat(pgdat) {
1844                 pid_t pid;
1845
1846                 pid = kernel_thread(kswapd, pgdat, CLONE_KERNEL);
1847                 BUG_ON(pid < 0);
1848                 pgdat->kswapd = find_task_by_pid(pid);
1849         }
1850         total_memory = nr_free_pagecache_pages();
1851         hotcpu_notifier(cpu_callback, 0);
1852         return 0;
1853 }
1854
1855 module_init(kswapd_init)
1856
1857 #ifdef CONFIG_NUMA
1858 /*
1859  * Zone reclaim mode
1860  *
1861  * If non-zero call zone_reclaim when the number of free pages falls below
1862  * the watermarks.
1863  *
1864  * In the future we may add flags to the mode. However, the page allocator
1865  * should only have to check that zone_reclaim_mode != 0 before calling
1866  * zone_reclaim().
1867  */
1868 int zone_reclaim_mode __read_mostly;
1869
1870 #define RECLAIM_OFF 0
1871 #define RECLAIM_ZONE (1<<0)     /* Run shrink_cache on the zone */
1872 #define RECLAIM_WRITE (1<<1)    /* Writeout pages during reclaim */
1873 #define RECLAIM_SWAP (1<<2)     /* Swap pages out during reclaim */
1874 #define RECLAIM_SLAB (1<<3)     /* Do a global slab shrink if the zone is out of memory */
1875
1876 /*
1877  * Mininum time between zone reclaim scans
1878  */
1879 int zone_reclaim_interval __read_mostly = 30*HZ;
1880
1881 /*
1882  * Priority for ZONE_RECLAIM. This determines the fraction of pages
1883  * of a node considered for each zone_reclaim. 4 scans 1/16th of
1884  * a zone.
1885  */
1886 #define ZONE_RECLAIM_PRIORITY 4
1887
1888 /*
1889  * Try to free up some pages from this zone through reclaim.
1890  */
1891 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1892 {
1893         /* Minimum pages needed in order to stay on node */
1894         const unsigned long nr_pages = 1 << order;
1895         struct task_struct *p = current;
1896         struct reclaim_state reclaim_state;
1897         int priority;
1898         unsigned long nr_reclaimed = 0;
1899         struct scan_control sc = {
1900                 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
1901                 .may_swap = !!(zone_reclaim_mode & RECLAIM_SWAP),
1902                 .nr_mapped = read_page_state(nr_mapped),
1903                 .swap_cluster_max = max_t(unsigned long, nr_pages,
1904                                         SWAP_CLUSTER_MAX),
1905                 .gfp_mask = gfp_mask,
1906         };
1907
1908         disable_swap_token();
1909         cond_resched();
1910         /*
1911          * We need to be able to allocate from the reserves for RECLAIM_SWAP
1912          * and we also need to be able to write out pages for RECLAIM_WRITE
1913          * and RECLAIM_SWAP.
1914          */
1915         p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
1916         reclaim_state.reclaimed_slab = 0;
1917         p->reclaim_state = &reclaim_state;
1918
1919         /*
1920          * Free memory by calling shrink zone with increasing priorities
1921          * until we have enough memory freed.
1922          */
1923         priority = ZONE_RECLAIM_PRIORITY;
1924         do {
1925                 nr_reclaimed += shrink_zone(priority, zone, &sc);
1926                 priority--;
1927         } while (priority >= 0 && nr_reclaimed < nr_pages);
1928
1929         if (nr_reclaimed < nr_pages && (zone_reclaim_mode & RECLAIM_SLAB)) {
1930                 /*
1931                  * shrink_slab() does not currently allow us to determine how
1932                  * many pages were freed in this zone. So we just shake the slab
1933                  * a bit and then go off node for this particular allocation
1934                  * despite possibly having freed enough memory to allocate in
1935                  * this zone.  If we freed local memory then the next
1936                  * allocations will be local again.
1937                  *
1938                  * shrink_slab will free memory on all zones and may take
1939                  * a long time.
1940                  */
1941                 shrink_slab(sc.nr_scanned, gfp_mask, order);
1942         }
1943
1944         p->reclaim_state = NULL;
1945         current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
1946
1947         if (nr_reclaimed == 0) {
1948                 /*
1949                  * We were unable to reclaim enough pages to stay on node.  We
1950                  * now allow off node accesses for a certain time period before
1951                  * trying again to reclaim pages from the local zone.
1952                  */
1953                 zone->last_unsuccessful_zone_reclaim = jiffies;
1954         }
1955
1956         return nr_reclaimed >= nr_pages;
1957 }
1958
1959 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
1960 {
1961         cpumask_t mask;
1962         int node_id;
1963
1964         /*
1965          * Do not reclaim if there was a recent unsuccessful attempt at zone
1966          * reclaim.  In that case we let allocations go off node for the
1967          * zone_reclaim_interval.  Otherwise we would scan for each off-node
1968          * page allocation.
1969          */
1970         if (time_before(jiffies,
1971                 zone->last_unsuccessful_zone_reclaim + zone_reclaim_interval))
1972                         return 0;
1973
1974         /*
1975          * Avoid concurrent zone reclaims, do not reclaim in a zone that does
1976          * not have reclaimable pages and if we should not delay the allocation
1977          * then do not scan.
1978          */
1979         if (!(gfp_mask & __GFP_WAIT) ||
1980                 zone->all_unreclaimable ||
1981                 atomic_read(&zone->reclaim_in_progress) > 0 ||
1982                 (current->flags & PF_MEMALLOC))
1983                         return 0;
1984
1985         /*
1986          * Only run zone reclaim on the local zone or on zones that do not
1987          * have associated processors. This will favor the local processor
1988          * over remote processors and spread off node memory allocations
1989          * as wide as possible.
1990          */
1991         node_id = zone->zone_pgdat->node_id;
1992         mask = node_to_cpumask(node_id);
1993         if (!cpus_empty(mask) && node_id != numa_node_id())
1994                 return 0;
1995         return __zone_reclaim(zone, gfp_mask, order);
1996 }
1997 #endif