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