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