This commit was manufactured by cvs2svn to create tag
[linux-2.6.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/suspend.h>
25 #include <linux/blkdev.h>
26 #include <linux/buffer_head.h>  /* for try_to_release_page(),
27                                         buffer_heads_over_limit */
28 #include <linux/mm_inline.h>
29 #include <linux/pagevec.h>
30 #include <linux/backing-dev.h>
31 #include <linux/rmap.h>
32 #include <linux/topology.h>
33 #include <linux/cpu.h>
34 #include <linux/notifier.h>
35
36 #include <asm/pgalloc.h>
37 #include <asm/tlbflush.h>
38 #include <asm/div64.h>
39
40 #include <linux/swapops.h>
41
42 /*
43  * From 0 .. 100.  Higher means more swappy.
44  */
45 int vm_swappiness = 60;
46 static long total_memory;
47
48 #define lru_to_page(_head) (list_entry((_head)->prev, struct page, lru))
49
50 #ifdef ARCH_HAS_PREFETCH
51 #define prefetch_prev_lru_page(_page, _base, _field)                    \
52         do {                                                            \
53                 if ((_page)->lru.prev != _base) {                       \
54                         struct page *prev;                              \
55                                                                         \
56                         prev = lru_to_page(&(_page->lru));              \
57                         prefetch(&prev->_field);                        \
58                 }                                                       \
59         } while (0)
60 #else
61 #define prefetch_prev_lru_page(_page, _base, _field) do { } while (0)
62 #endif
63
64 #ifdef ARCH_HAS_PREFETCHW
65 #define prefetchw_prev_lru_page(_page, _base, _field)                   \
66         do {                                                            \
67                 if ((_page)->lru.prev != _base) {                       \
68                         struct page *prev;                              \
69                                                                         \
70                         prev = lru_to_page(&(_page->lru));                      \
71                         prefetchw(&prev->_field);                       \
72                 }                                                       \
73         } while (0)
74 #else
75 #define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
76 #endif
77
78 /*
79  * The list of shrinker callbacks used by to apply pressure to
80  * ageable caches.
81  */
82 struct shrinker {
83         shrinker_t              shrinker;
84         struct list_head        list;
85         int                     seeks;  /* seeks to recreate an obj */
86         long                    nr;     /* objs pending delete */
87 };
88
89 static LIST_HEAD(shrinker_list);
90 static DECLARE_MUTEX(shrinker_sem);
91
92 /*
93  * Add a shrinker callback to be called from the vm
94  */
95 struct shrinker *set_shrinker(int seeks, shrinker_t theshrinker)
96 {
97         struct shrinker *shrinker;
98
99         shrinker = kmalloc(sizeof(*shrinker), GFP_KERNEL);
100         if (shrinker) {
101                 shrinker->shrinker = theshrinker;
102                 shrinker->seeks = seeks;
103                 shrinker->nr = 0;
104                 down(&shrinker_sem);
105                 list_add(&shrinker->list, &shrinker_list);
106                 up(&shrinker_sem);
107         }
108         return shrinker;
109 }
110
111 EXPORT_SYMBOL(set_shrinker);
112
113 /*
114  * Remove one
115  */
116 void remove_shrinker(struct shrinker *shrinker)
117 {
118         down(&shrinker_sem);
119         list_del(&shrinker->list);
120         up(&shrinker_sem);
121         kfree(shrinker);
122 }
123
124 EXPORT_SYMBOL(remove_shrinker);
125  
126 #define SHRINK_BATCH 128
127 /*
128  * Call the shrink functions to age shrinkable caches
129  *
130  * Here we assume it costs one seek to replace a lru page and that it also
131  * takes a seek to recreate a cache object.  With this in mind we age equal
132  * percentages of the lru and ageable caches.  This should balance the seeks
133  * generated by these structures.
134  *
135  * If the vm encounted mapped pages on the LRU it increase the pressure on
136  * slab to avoid swapping.
137  *
138  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
139  */
140 static int shrink_slab(unsigned long scanned, unsigned int gfp_mask)
141 {
142         struct shrinker *shrinker;
143         long pages;
144
145         if (down_trylock(&shrinker_sem))
146                 return 0;
147
148         pages = nr_used_zone_pages();
149         list_for_each_entry(shrinker, &shrinker_list, list) {
150                 unsigned long long delta;
151
152                 delta = (4 * scanned) / shrinker->seeks;
153                 delta *= (*shrinker->shrinker)(0, gfp_mask);
154                 do_div(delta, pages + 1);
155                 shrinker->nr += delta;
156                 if (shrinker->nr < 0)
157                         shrinker->nr = LONG_MAX;        /* It wrapped! */
158
159                 if (shrinker->nr <= SHRINK_BATCH)
160                         continue;
161                 while (shrinker->nr) {
162                         long this_scan = shrinker->nr;
163                         int shrink_ret;
164
165                         if (this_scan > 128)
166                                 this_scan = 128;
167                         shrink_ret = (*shrinker->shrinker)(this_scan, gfp_mask);
168                         mod_page_state(slabs_scanned, this_scan);
169                         shrinker->nr -= this_scan;
170                         if (shrink_ret == -1)
171                                 break;
172                         cond_resched();
173                 }
174         }
175         up(&shrinker_sem);
176         return 0;
177 }
178
179 /* Must be called with page's rmap lock held. */
180 static inline int page_mapping_inuse(struct page *page)
181 {
182         struct address_space *mapping;
183
184         /* Page is in somebody's page tables. */
185         if (page_mapped(page))
186                 return 1;
187
188         /* Be more reluctant to reclaim swapcache than pagecache */
189         if (PageSwapCache(page))
190                 return 1;
191
192         mapping = page_mapping(page);
193         if (!mapping)
194                 return 0;
195
196         /* File is mmap'd by somebody? */
197         return mapping_mapped(mapping);
198 }
199
200 static inline int is_page_cache_freeable(struct page *page)
201 {
202         return page_count(page) - !!PagePrivate(page) == 2;
203 }
204
205 static int may_write_to_queue(struct backing_dev_info *bdi)
206 {
207         if (current_is_kswapd())
208                 return 1;
209         if (current_is_pdflush())       /* This is unlikely, but why not... */
210                 return 1;
211         if (!bdi_write_congested(bdi))
212                 return 1;
213         if (bdi == current->backing_dev_info)
214                 return 1;
215         return 0;
216 }
217
218 /*
219  * We detected a synchronous write error writing a page out.  Probably
220  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
221  * fsync(), msync() or close().
222  *
223  * The tricky part is that after writepage we cannot touch the mapping: nothing
224  * prevents it from being freed up.  But we have a ref on the page and once
225  * that page is locked, the mapping is pinned.
226  *
227  * We're allowed to run sleeping lock_page() here because we know the caller has
228  * __GFP_FS.
229  */
230 static void handle_write_error(struct address_space *mapping,
231                                 struct page *page, int error)
232 {
233         lock_page(page);
234         if (page_mapping(page) == mapping) {
235                 if (error == -ENOSPC)
236                         set_bit(AS_ENOSPC, &mapping->flags);
237                 else
238                         set_bit(AS_EIO, &mapping->flags);
239         }
240         unlock_page(page);
241 }
242
243 /*
244  * shrink_list returns the number of reclaimed pages
245  */
246 static int
247 shrink_list(struct list_head *page_list, unsigned int gfp_mask,
248                 int *nr_scanned, int do_writepage)
249 {
250         LIST_HEAD(ret_pages);
251         struct pagevec freed_pvec;
252         int pgactivate = 0;
253         int ret = 0;
254
255         cond_resched();
256
257         pagevec_init(&freed_pvec, 1);
258         while (!list_empty(page_list)) {
259                 struct address_space *mapping;
260                 struct page *page;
261                 int may_enter_fs;
262                 int referenced;
263
264                 page = lru_to_page(page_list);
265                 list_del(&page->lru);
266
267                 if (TestSetPageLocked(page))
268                         goto keep;
269
270                 /* Double the slab pressure for mapped and swapcache pages */
271                 if (page_mapped(page) || PageSwapCache(page))
272                         (*nr_scanned)++;
273
274                 BUG_ON(PageActive(page));
275
276                 if (PageWriteback(page))
277                         goto keep_locked;
278
279                 page_map_lock(page);
280                 referenced = page_referenced(page);
281                 if (referenced && page_mapping_inuse(page)) {
282                         /* In active use or really unfreeable.  Activate it. */
283                         page_map_unlock(page);
284                         goto activate_locked;
285                 }
286
287 #ifdef CONFIG_SWAP
288                 /*
289                  * Anonymous process memory has backing store?
290                  * Try to allocate it some swap space here.
291                  *
292                  * XXX: implement swap clustering ?
293                  */
294                 if (PageAnon(page) && !PageSwapCache(page)) {
295                         page_map_unlock(page);
296                         if (!add_to_swap(page))
297                                 goto activate_locked;
298                         page_map_lock(page);
299                 }
300 #endif /* CONFIG_SWAP */
301
302                 mapping = page_mapping(page);
303                 may_enter_fs = (gfp_mask & __GFP_FS) ||
304                         (PageSwapCache(page) && (gfp_mask & __GFP_IO));
305
306                 /*
307                  * The page is mapped into the page tables of one or more
308                  * processes. Try to unmap it here.
309                  */
310                 if (page_mapped(page) && mapping) {
311                         switch (try_to_unmap(page)) {
312                         case SWAP_FAIL:
313                                 page_map_unlock(page);
314                                 goto activate_locked;
315                         case SWAP_AGAIN:
316                                 page_map_unlock(page);
317                                 goto keep_locked;
318                         case SWAP_SUCCESS:
319                                 ; /* try to free the page below */
320                         }
321                 }
322                 page_map_unlock(page);
323
324                 /*
325                  * If the page is dirty, only perform writeback if that write
326                  * will be non-blocking.  To prevent this allocation from being
327                  * stalled by pagecache activity.  But note that there may be
328                  * stalls if we need to run get_block().  We could test
329                  * PagePrivate for that.
330                  *
331                  * If this process is currently in generic_file_write() against
332                  * this page's queue, we can perform writeback even if that
333                  * will block.
334                  *
335                  * If the page is swapcache, write it back even if that would
336                  * block, for some throttling. This happens by accident, because
337                  * swap_backing_dev_info is bust: it doesn't reflect the
338                  * congestion state of the swapdevs.  Easy to fix, if needed.
339                  * See swapfile.c:page_queue_congested().
340                  */
341                 if (PageDirty(page)) {
342                         if (referenced)
343                                 goto keep_locked;
344                         if (!is_page_cache_freeable(page))
345                                 goto keep_locked;
346                         if (!mapping)
347                                 goto keep_locked;
348                         if (mapping->a_ops->writepage == NULL)
349                                 goto activate_locked;
350                         if (!may_enter_fs)
351                                 goto keep_locked;
352                         if (!may_write_to_queue(mapping->backing_dev_info))
353                                 goto keep_locked;
354                         if (laptop_mode && !do_writepage)
355                                 goto keep_locked;
356                         if (clear_page_dirty_for_io(page)) {
357                                 int res;
358                                 struct writeback_control wbc = {
359                                         .sync_mode = WB_SYNC_NONE,
360                                         .nr_to_write = SWAP_CLUSTER_MAX,
361                                         .nonblocking = 1,
362                                         .for_reclaim = 1,
363                                 };
364
365                                 SetPageReclaim(page);
366                                 res = mapping->a_ops->writepage(page, &wbc);
367                                 if (res < 0)
368                                         handle_write_error(mapping, page, res);
369                                 if (res == WRITEPAGE_ACTIVATE) {
370                                         ClearPageReclaim(page);
371                                         goto activate_locked;
372                                 }
373                                 if (!PageWriteback(page)) {
374                                         /* synchronous write or broken a_ops? */
375                                         ClearPageReclaim(page);
376                                 }
377                                 goto keep;
378                         }
379                 }
380
381                 /*
382                  * If the page has buffers, try to free the buffer mappings
383                  * associated with this page. If we succeed we try to free
384                  * the page as well.
385                  *
386                  * We do this even if the page is PageDirty().
387                  * try_to_release_page() does not perform I/O, but it is
388                  * possible for a page to have PageDirty set, but it is actually
389                  * clean (all its buffers are clean).  This happens if the
390                  * buffers were written out directly, with submit_bh(). ext3
391                  * will do this, as well as the blockdev mapping. 
392                  * try_to_release_page() will discover that cleanness and will
393                  * drop the buffers and mark the page clean - it can be freed.
394                  *
395                  * Rarely, pages can have buffers and no ->mapping.  These are
396                  * the pages which were not successfully invalidated in
397                  * truncate_complete_page().  We try to drop those buffers here
398                  * and if that worked, and the page is no longer mapped into
399                  * process address space (page_count == 0) it can be freed.
400                  * Otherwise, leave the page on the LRU so it is swappable.
401                  */
402                 if (PagePrivate(page)) {
403                         if (!try_to_release_page(page, gfp_mask))
404                                 goto activate_locked;
405                         if (!mapping && page_count(page) == 1)
406                                 goto free_it;
407                 }
408
409                 if (!mapping)
410                         goto keep_locked;       /* truncate got there first */
411
412                 spin_lock_irq(&mapping->tree_lock);
413
414                 /*
415                  * The non-racy check for busy page.  It is critical to check
416                  * PageDirty _after_ making sure that the page is freeable and
417                  * not in use by anybody.       (pagecache + us == 2)
418                  */
419                 if (page_count(page) != 2 || PageDirty(page)) {
420                         spin_unlock_irq(&mapping->tree_lock);
421                         goto keep_locked;
422                 }
423
424 #ifdef CONFIG_SWAP
425                 if (PageSwapCache(page)) {
426                         swp_entry_t swap = { .val = page->private };
427                         __delete_from_swap_cache(page);
428                         spin_unlock_irq(&mapping->tree_lock);
429                         swap_free(swap);
430                         __put_page(page);       /* The pagecache ref */
431                         goto free_it;
432                 }
433 #endif /* CONFIG_SWAP */
434
435                 __remove_from_page_cache(page);
436                 spin_unlock_irq(&mapping->tree_lock);
437                 __put_page(page);
438
439 free_it:
440                 unlock_page(page);
441                 ret++;
442                 if (!pagevec_add(&freed_pvec, page))
443                         __pagevec_release_nonlru(&freed_pvec);
444                 continue;
445
446 activate_locked:
447                 SetPageActive(page);
448                 pgactivate++;
449 keep_locked:
450                 unlock_page(page);
451 keep:
452                 list_add(&page->lru, &ret_pages);
453                 BUG_ON(PageLRU(page));
454         }
455         list_splice(&ret_pages, page_list);
456         if (pagevec_count(&freed_pvec))
457                 __pagevec_release_nonlru(&freed_pvec);
458         mod_page_state(pgactivate, pgactivate);
459         return ret;
460 }
461
462 /*
463  * zone->lru_lock is heavily contented.  We relieve it by quickly privatising
464  * a batch of pages and working on them outside the lock.  Any pages which were
465  * not freed will be added back to the LRU.
466  *
467  * shrink_cache() is passed the number of pages to scan and returns the number
468  * of pages which were reclaimed.
469  *
470  * For pagecache intensive workloads, the first loop here is the hottest spot
471  * in the kernel (apart from the copy_*_user functions).
472  */
473 static int
474 shrink_cache(struct zone *zone, unsigned int gfp_mask,
475                 int max_scan, int *total_scanned, int do_writepage)
476 {
477         LIST_HEAD(page_list);
478         struct pagevec pvec;
479         int ret = 0;
480
481         pagevec_init(&pvec, 1);
482
483         lru_add_drain();
484         spin_lock_irq(&zone->lru_lock);
485         while (max_scan > 0) {
486                 struct page *page;
487                 int nr_taken = 0;
488                 int nr_scan = 0;
489                 int nr_freed;
490
491                 while (nr_scan++ < SWAP_CLUSTER_MAX &&
492                                 !list_empty(&zone->inactive_list)) {
493                         page = lru_to_page(&zone->inactive_list);
494
495                         prefetchw_prev_lru_page(page,
496                                                 &zone->inactive_list, flags);
497
498                         if (!TestClearPageLRU(page))
499                                 BUG();
500                         list_del(&page->lru);
501                         if (get_page_testone(page)) {
502                                 /*
503                                  * It is being freed elsewhere
504                                  */
505                                 __put_page(page);
506                                 SetPageLRU(page);
507                                 list_add(&page->lru, &zone->inactive_list);
508                                 continue;
509                         }
510                         list_add(&page->lru, &page_list);
511                         nr_taken++;
512                 }
513                 zone->nr_inactive -= nr_taken;
514                 zone->pages_scanned += nr_taken;
515                 spin_unlock_irq(&zone->lru_lock);
516
517                 if (nr_taken == 0)
518                         goto done;
519
520                 max_scan -= nr_scan;
521                 if (current_is_kswapd())
522                         mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
523                 else
524                         mod_page_state_zone(zone, pgscan_direct, nr_scan);
525                 nr_freed = shrink_list(&page_list, gfp_mask,
526                                         total_scanned, do_writepage);
527                 *total_scanned += nr_taken;
528                 if (current_is_kswapd())
529                         mod_page_state(kswapd_steal, nr_freed);
530                 mod_page_state_zone(zone, pgsteal, nr_freed);
531
532                 ret += nr_freed;
533                 if (nr_freed <= 0 && list_empty(&page_list))
534                         goto done;
535
536                 spin_lock_irq(&zone->lru_lock);
537                 /*
538                  * Put back any unfreeable pages.
539                  */
540                 while (!list_empty(&page_list)) {
541                         page = lru_to_page(&page_list);
542                         if (TestSetPageLRU(page))
543                                 BUG();
544                         list_del(&page->lru);
545                         if (PageActive(page))
546                                 add_page_to_active_list(zone, page);
547                         else
548                                 add_page_to_inactive_list(zone, page);
549                         if (!pagevec_add(&pvec, page)) {
550                                 spin_unlock_irq(&zone->lru_lock);
551                                 __pagevec_release(&pvec);
552                                 spin_lock_irq(&zone->lru_lock);
553                         }
554                 }
555         }
556         spin_unlock_irq(&zone->lru_lock);
557 done:
558         pagevec_release(&pvec);
559         return ret;
560 }
561
562 /*
563  * This moves pages from the active list to the inactive list.
564  *
565  * We move them the other way if the page is referenced by one or more
566  * processes, from rmap.
567  *
568  * If the pages are mostly unmapped, the processing is fast and it is
569  * appropriate to hold zone->lru_lock across the whole operation.  But if
570  * the pages are mapped, the processing is slow (page_referenced()) so we
571  * should drop zone->lru_lock around each page.  It's impossible to balance
572  * this, so instead we remove the pages from the LRU while processing them.
573  * It is safe to rely on PG_active against the non-LRU pages in here because
574  * nobody will play with that bit on a non-LRU page.
575  *
576  * The downside is that we have to touch page->_count against each page.
577  * But we had to alter page->flags anyway.
578  */
579 static void
580 refill_inactive_zone(struct zone *zone, const int nr_pages_in,
581                         struct page_state *ps)
582 {
583         int pgmoved;
584         int pgdeactivate = 0;
585         int nr_pages = nr_pages_in;
586         LIST_HEAD(l_hold);      /* The pages which were snipped off */
587         LIST_HEAD(l_inactive);  /* Pages to go onto the inactive_list */
588         LIST_HEAD(l_active);    /* Pages to go onto the active_list */
589         struct page *page;
590         struct pagevec pvec;
591         int reclaim_mapped = 0;
592         long mapped_ratio;
593         long distress;
594         long swap_tendency;
595
596         lru_add_drain();
597         pgmoved = 0;
598         spin_lock_irq(&zone->lru_lock);
599         while (nr_pages && !list_empty(&zone->active_list)) {
600                 page = lru_to_page(&zone->active_list);
601                 prefetchw_prev_lru_page(page, &zone->active_list, flags);
602                 if (!TestClearPageLRU(page))
603                         BUG();
604                 list_del(&page->lru);
605                 if (get_page_testone(page)) {
606                         /*
607                          * It was already free!  release_pages() or put_page()
608                          * are about to remove it from the LRU and free it. So
609                          * put the refcount back and put the page back on the
610                          * LRU
611                          */
612                         __put_page(page);
613                         SetPageLRU(page);
614                         list_add(&page->lru, &zone->active_list);
615                 } else {
616                         list_add(&page->lru, &l_hold);
617                         pgmoved++;
618                 }
619                 nr_pages--;
620         }
621         zone->nr_active -= pgmoved;
622         spin_unlock_irq(&zone->lru_lock);
623
624         /*
625          * `distress' is a measure of how much trouble we're having reclaiming
626          * pages.  0 -> no problems.  100 -> great trouble.
627          */
628         distress = 100 >> zone->prev_priority;
629
630         /*
631          * The point of this algorithm is to decide when to start reclaiming
632          * mapped memory instead of just pagecache.  Work out how much memory
633          * is mapped.
634          */
635         mapped_ratio = (ps->nr_mapped * 100) / total_memory;
636
637         /*
638          * Now decide how much we really want to unmap some pages.  The mapped
639          * ratio is downgraded - just because there's a lot of mapped memory
640          * doesn't necessarily mean that page reclaim isn't succeeding.
641          *
642          * The distress ratio is important - we don't want to start going oom.
643          *
644          * A 100% value of vm_swappiness overrides this algorithm altogether.
645          */
646         swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
647
648         /*
649          * Now use this metric to decide whether to start moving mapped memory
650          * onto the inactive list.
651          */
652         if (swap_tendency >= 100)
653                 reclaim_mapped = 1;
654
655         while (!list_empty(&l_hold)) {
656                 page = lru_to_page(&l_hold);
657                 list_del(&page->lru);
658                 if (page_mapped(page)) {
659                         if (!reclaim_mapped) {
660                                 list_add(&page->lru, &l_active);
661                                 continue;
662                         }
663                         page_map_lock(page);
664                         if (page_referenced(page)) {
665                                 page_map_unlock(page);
666                                 list_add(&page->lru, &l_active);
667                                 continue;
668                         }
669                         page_map_unlock(page);
670                 }
671                 /*
672                  * FIXME: need to consider page_count(page) here if/when we
673                  * reap orphaned pages via the LRU (Daniel's locking stuff)
674                  */
675                 if (total_swap_pages == 0 && PageAnon(page)) {
676                         list_add(&page->lru, &l_active);
677                         continue;
678                 }
679                 list_add(&page->lru, &l_inactive);
680         }
681
682         pagevec_init(&pvec, 1);
683         pgmoved = 0;
684         spin_lock_irq(&zone->lru_lock);
685         while (!list_empty(&l_inactive)) {
686                 page = lru_to_page(&l_inactive);
687                 prefetchw_prev_lru_page(page, &l_inactive, flags);
688                 if (TestSetPageLRU(page))
689                         BUG();
690                 if (!TestClearPageActive(page))
691                         BUG();
692                 list_move(&page->lru, &zone->inactive_list);
693                 pgmoved++;
694                 if (!pagevec_add(&pvec, page)) {
695                         zone->nr_inactive += pgmoved;
696                         spin_unlock_irq(&zone->lru_lock);
697                         pgdeactivate += pgmoved;
698                         pgmoved = 0;
699                         if (buffer_heads_over_limit)
700                                 pagevec_strip(&pvec);
701                         __pagevec_release(&pvec);
702                         spin_lock_irq(&zone->lru_lock);
703                 }
704         }
705         zone->nr_inactive += pgmoved;
706         pgdeactivate += pgmoved;
707         if (buffer_heads_over_limit) {
708                 spin_unlock_irq(&zone->lru_lock);
709                 pagevec_strip(&pvec);
710                 spin_lock_irq(&zone->lru_lock);
711         }
712
713         pgmoved = 0;
714         while (!list_empty(&l_active)) {
715                 page = lru_to_page(&l_active);
716                 prefetchw_prev_lru_page(page, &l_active, flags);
717                 if (TestSetPageLRU(page))
718                         BUG();
719                 BUG_ON(!PageActive(page));
720                 list_move(&page->lru, &zone->active_list);
721                 pgmoved++;
722                 if (!pagevec_add(&pvec, page)) {
723                         zone->nr_active += pgmoved;
724                         pgmoved = 0;
725                         spin_unlock_irq(&zone->lru_lock);
726                         __pagevec_release(&pvec);
727                         spin_lock_irq(&zone->lru_lock);
728                 }
729         }
730         zone->nr_active += pgmoved;
731         spin_unlock_irq(&zone->lru_lock);
732         pagevec_release(&pvec);
733
734         mod_page_state_zone(zone, pgrefill, nr_pages_in - nr_pages);
735         mod_page_state(pgdeactivate, pgdeactivate);
736 }
737
738 /*
739  * Scan `nr_pages' from this zone.  Returns the number of reclaimed pages.
740  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
741  */
742 static int
743 shrink_zone(struct zone *zone, int max_scan, unsigned int gfp_mask,
744                 int *total_scanned, struct page_state *ps, int do_writepage)
745 {
746         unsigned long scan_active;
747         int count;
748
749         /*
750          * Try to keep the active list 2/3 of the size of the cache.  And
751          * make sure that refill_inactive is given a decent number of pages.
752          *
753          * The "scan_active + 1" here is important.  With pagecache-intensive
754          * workloads the inactive list is huge, and `ratio' evaluates to zero
755          * all the time.  Which pins the active list memory.  So we add one to
756          * `scan_active' just to make sure that the kernel will slowly sift
757          * through the active list.
758          */
759         if (zone->nr_active >= 4*(zone->nr_inactive*2 + 1)) {
760                 /* Don't scan more than 4 times the inactive list scan size */
761                 scan_active = 4*max_scan;
762         } else {
763                 unsigned long long tmp;
764
765                 /* Cast to long long so the multiply doesn't overflow */
766
767                 tmp = (unsigned long long)max_scan * zone->nr_active;
768                 do_div(tmp, zone->nr_inactive*2 + 1);
769                 scan_active = (unsigned long)tmp;
770         }
771
772         atomic_add(scan_active + 1, &zone->nr_scan_active);
773         count = atomic_read(&zone->nr_scan_active);
774         if (count >= SWAP_CLUSTER_MAX) {
775                 atomic_set(&zone->nr_scan_active, 0);
776                 refill_inactive_zone(zone, count, ps);
777         }
778
779         atomic_add(max_scan, &zone->nr_scan_inactive);
780         count = atomic_read(&zone->nr_scan_inactive);
781         if (count >= SWAP_CLUSTER_MAX) {
782                 atomic_set(&zone->nr_scan_inactive, 0);
783                 return shrink_cache(zone, gfp_mask, count,
784                                         total_scanned, do_writepage);
785         }
786         return 0;
787 }
788
789 /*
790  * This is the direct reclaim path, for page-allocating processes.  We only
791  * try to reclaim pages from zones which will satisfy the caller's allocation
792  * request.
793  *
794  * We reclaim from a zone even if that zone is over pages_high.  Because:
795  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
796  *    allocation or
797  * b) The zones may be over pages_high but they must go *over* pages_high to
798  *    satisfy the `incremental min' zone defense algorithm.
799  *
800  * Returns the number of reclaimed pages.
801  *
802  * If a zone is deemed to be full of pinned pages then just give it a light
803  * scan then give up on it.
804  */
805 static int
806 shrink_caches(struct zone **zones, int priority, int *total_scanned,
807                 int gfp_mask, struct page_state *ps, int do_writepage)
808 {
809         int ret = 0;
810         int i;
811
812         for (i = 0; zones[i] != NULL; i++) {
813                 struct zone *zone = zones[i];
814                 int max_scan;
815
816                 if (zone->free_pages < zone->pages_high)
817                         zone->temp_priority = priority;
818
819                 if (zone->all_unreclaimable && priority != DEF_PRIORITY)
820                         continue;       /* Let kswapd poll it */
821
822                 max_scan = (zone->nr_active + zone->nr_inactive) >> priority;
823                 ret += shrink_zone(zone, max_scan, gfp_mask,
824                                         total_scanned, ps, do_writepage);
825         }
826         return ret;
827 }
828  
829 /*
830  * This is the main entry point to direct page reclaim.
831  *
832  * If a full scan of the inactive list fails to free enough memory then we
833  * are "out of memory" and something needs to be killed.
834  *
835  * If the caller is !__GFP_FS then the probability of a failure is reasonably
836  * high - the zone may be full of dirty or under-writeback pages, which this
837  * caller can't do much about.  So for !__GFP_FS callers, we just perform a
838  * small LRU walk and if that didn't work out, fail the allocation back to the
839  * caller.  GFP_NOFS allocators need to know how to deal with it.  Kicking
840  * bdflush, waiting and retrying will work.
841  *
842  * This is a fairly lame algorithm - it can result in excessive CPU burning and
843  * excessive rotation of the inactive list, which is _supposed_ to be an LRU,
844  * yes?
845  */
846 int try_to_free_pages(struct zone **zones,
847                 unsigned int gfp_mask, unsigned int order)
848 {
849         int priority;
850         int ret = 0;
851         int nr_reclaimed = 0;
852         struct reclaim_state *reclaim_state = current->reclaim_state;
853         int i;
854         unsigned long total_scanned = 0;
855         int do_writepage = 0;
856
857         inc_page_state(allocstall);
858
859         for (i = 0; zones[i] != 0; i++)
860                 zones[i]->temp_priority = DEF_PRIORITY;
861
862         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
863                 int scanned = 0;
864                 struct page_state ps;
865
866                 get_page_state(&ps);
867                 nr_reclaimed += shrink_caches(zones, priority, &scanned,
868                                                 gfp_mask, &ps, do_writepage);
869                 shrink_slab(scanned, gfp_mask);
870                 if (reclaim_state) {
871                         nr_reclaimed += reclaim_state->reclaimed_slab;
872                         reclaim_state->reclaimed_slab = 0;
873                 }
874                 if (nr_reclaimed >= SWAP_CLUSTER_MAX) {
875                         ret = 1;
876                         goto out;
877                 }
878                 if (!(gfp_mask & __GFP_FS))
879                         break;          /* Let the caller handle it */
880                 /*
881                  * Try to write back as many pages as we just scanned.  This
882                  * tends to cause slow streaming writers to write data to the
883                  * disk smoothly, at the dirtying rate, which is nice.   But
884                  * that's undesirable in laptop mode, where we *want* lumpy
885                  * writeout.  So in laptop mode, write out the whole world.
886                  */
887                 total_scanned += scanned;
888                 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
889                         wakeup_bdflush(laptop_mode ? 0 : total_scanned);
890                         do_writepage = 1;
891                 }
892
893                 /* Take a nap, wait for some writeback to complete */
894                 if (scanned && priority < DEF_PRIORITY - 2)
895                         blk_congestion_wait(WRITE, HZ/10);
896         }
897         if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
898                 out_of_memory();
899 out:
900         for (i = 0; zones[i] != 0; i++)
901                 zones[i]->prev_priority = zones[i]->temp_priority;
902         return ret;
903 }
904
905 /*
906  * For kswapd, balance_pgdat() will work across all this node's zones until
907  * they are all at pages_high.
908  *
909  * If `nr_pages' is non-zero then it is the number of pages which are to be
910  * reclaimed, regardless of the zone occupancies.  This is a software suspend
911  * special.
912  *
913  * Returns the number of pages which were actually freed.
914  *
915  * There is special handling here for zones which are full of pinned pages.
916  * This can happen if the pages are all mlocked, or if they are all used by
917  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
918  * What we do is to detect the case where all pages in the zone have been
919  * scanned twice and there has been zero successful reclaim.  Mark the zone as
920  * dead and from now on, only perform a short scan.  Basically we're polling
921  * the zone for when the problem goes away.
922  *
923  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
924  * zones which have free_pages > pages_high, but once a zone is found to have
925  * free_pages <= pages_high, we scan that zone and the lower zones regardless
926  * of the number of free pages in the lower zones.  This interoperates with
927  * the page allocator fallback scheme to ensure that aging of pages is balanced
928  * across the zones.
929  */
930 static int balance_pgdat(pg_data_t *pgdat, int nr_pages, struct page_state *ps)
931 {
932         int to_free = nr_pages;
933         int priority;
934         int i;
935         struct reclaim_state *reclaim_state = current->reclaim_state;
936         unsigned long total_scanned = 0;
937         unsigned long total_reclaimed = 0;
938         int do_writepage = 0;
939
940         inc_page_state(pageoutrun);
941
942         for (i = 0; i < pgdat->nr_zones; i++) {
943                 struct zone *zone = pgdat->node_zones + i;
944
945                 zone->temp_priority = DEF_PRIORITY;
946         }
947
948         for (priority = DEF_PRIORITY; priority; priority--) {
949                 int all_zones_ok = 1;
950                 int end_zone = 0;       /* Inclusive.  0 = ZONE_DMA */
951
952
953                 if (nr_pages == 0) {
954                         /*
955                          * Scan in the highmem->dma direction for the highest
956                          * zone which needs scanning
957                          */
958                         for (i = pgdat->nr_zones - 1; i >= 0; i--) {
959                                 struct zone *zone = pgdat->node_zones + i;
960
961                                 if (zone->all_unreclaimable &&
962                                                 priority != DEF_PRIORITY)
963                                         continue;
964
965                                 if (zone->free_pages <= zone->pages_high) {
966                                         end_zone = i;
967                                         goto scan;
968                                 }
969                         }
970                         goto out;
971                 } else {
972                         end_zone = pgdat->nr_zones - 1;
973                 }
974 scan:
975                 /*
976                  * Now scan the zone in the dma->highmem direction, stopping
977                  * at the last zone which needs scanning.
978                  *
979                  * We do this because the page allocator works in the opposite
980                  * direction.  This prevents the page allocator from allocating
981                  * pages behind kswapd's direction of progress, which would
982                  * cause too much scanning of the lower zones.
983                  */
984                 for (i = 0; i <= end_zone; i++) {
985                         struct zone *zone = pgdat->node_zones + i;
986                         int max_scan;
987                         int reclaimed;
988                         int scanned = 0;
989
990                         if (zone->all_unreclaimable && priority != DEF_PRIORITY)
991                                 continue;
992
993                         if (nr_pages == 0) {    /* Not software suspend */
994                                 if (zone->free_pages <= zone->pages_high)
995                                         all_zones_ok = 0;
996                         }
997                         zone->temp_priority = priority;
998                         max_scan = (zone->nr_active + zone->nr_inactive)
999                                                                 >> priority;
1000                         reclaimed = shrink_zone(zone, max_scan, GFP_KERNEL,
1001                                         &scanned, ps, do_writepage);
1002                         total_scanned += scanned;
1003                         reclaim_state->reclaimed_slab = 0;
1004                         shrink_slab(scanned, GFP_KERNEL);
1005                         reclaimed += reclaim_state->reclaimed_slab;
1006                         total_reclaimed += reclaimed;
1007                         to_free -= reclaimed;
1008                         if (zone->all_unreclaimable)
1009                                 continue;
1010                         if (zone->pages_scanned > zone->present_pages * 2)
1011                                 zone->all_unreclaimable = 1;
1012                         /*
1013                          * If we've done a decent amount of scanning and
1014                          * the reclaim ratio is low, start doing writepage
1015                          * even in laptop mode
1016                          */
1017                         if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1018                             total_scanned > total_reclaimed+total_reclaimed/2)
1019                                 do_writepage = 1;
1020                 }
1021                 if (nr_pages && to_free > 0)
1022                         continue;       /* swsusp: need to do more work */
1023                 if (all_zones_ok)
1024                         break;          /* kswapd: all done */
1025                 /*
1026                  * OK, kswapd is getting into trouble.  Take a nap, then take
1027                  * another pass across the zones.
1028                  */
1029                 if (total_scanned && priority < DEF_PRIORITY - 2)
1030                         blk_congestion_wait(WRITE, HZ/10);
1031         }
1032 out:
1033         for (i = 0; i < pgdat->nr_zones; i++) {
1034                 struct zone *zone = pgdat->node_zones + i;
1035
1036                 zone->prev_priority = zone->temp_priority;
1037         }
1038         return total_reclaimed;
1039 }
1040
1041 /*
1042  * The background pageout daemon, started as a kernel thread
1043  * from the init process. 
1044  *
1045  * This basically trickles out pages so that we have _some_
1046  * free memory available even if there is no other activity
1047  * that frees anything up. This is needed for things like routing
1048  * etc, where we otherwise might have all activity going on in
1049  * asynchronous contexts that cannot page things out.
1050  *
1051  * If there are applications that are active memory-allocators
1052  * (most normal use), this basically shouldn't matter.
1053  */
1054 int kswapd(void *p)
1055 {
1056         pg_data_t *pgdat = (pg_data_t*)p;
1057         struct task_struct *tsk = current;
1058         DEFINE_WAIT(wait);
1059         struct reclaim_state reclaim_state = {
1060                 .reclaimed_slab = 0,
1061         };
1062         cpumask_t cpumask;
1063
1064         daemonize("kswapd%d", pgdat->node_id);
1065         cpumask = node_to_cpumask(pgdat->node_id);
1066         if (!cpus_empty(cpumask))
1067                 set_cpus_allowed(tsk, cpumask);
1068         current->reclaim_state = &reclaim_state;
1069
1070         /*
1071          * Tell the memory management that we're a "memory allocator",
1072          * and that if we need more memory we should get access to it
1073          * regardless (see "__alloc_pages()"). "kswapd" should
1074          * never get caught in the normal page freeing logic.
1075          *
1076          * (Kswapd normally doesn't need memory anyway, but sometimes
1077          * you need a small amount of memory in order to be able to
1078          * page out something else, and this flag essentially protects
1079          * us from recursively trying to free more memory as we're
1080          * trying to free the first piece of memory in the first place).
1081          */
1082         tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1083
1084         for ( ; ; ) {
1085                 struct page_state ps;
1086
1087                 if (current->flags & PF_FREEZE)
1088                         refrigerator(PF_FREEZE);
1089                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1090                 schedule();
1091                 finish_wait(&pgdat->kswapd_wait, &wait);
1092                 get_page_state(&ps);
1093                 balance_pgdat(pgdat, 0, &ps);
1094         }
1095 }
1096
1097 /*
1098  * A zone is low on free memory, so wake its kswapd task to service it.
1099  */
1100 void wakeup_kswapd(struct zone *zone)
1101 {
1102         if (zone->free_pages > zone->pages_low)
1103                 return;
1104         if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1105                 return;
1106         wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1107 }
1108
1109 #ifdef CONFIG_PM
1110 /*
1111  * Try to free `nr_pages' of memory, system-wide.  Returns the number of freed
1112  * pages.
1113  */
1114 int shrink_all_memory(int nr_pages)
1115 {
1116         pg_data_t *pgdat;
1117         int nr_to_free = nr_pages;
1118         int ret = 0;
1119         struct reclaim_state reclaim_state = {
1120                 .reclaimed_slab = 0,
1121         };
1122
1123         current->reclaim_state = &reclaim_state;
1124         for_each_pgdat(pgdat) {
1125                 int freed;
1126                 struct page_state ps;
1127
1128                 get_page_state(&ps);
1129                 freed = balance_pgdat(pgdat, nr_to_free, &ps);
1130                 ret += freed;
1131                 nr_to_free -= freed;
1132                 if (nr_to_free <= 0)
1133                         break;
1134         }
1135         current->reclaim_state = NULL;
1136         return ret;
1137 }
1138 #endif
1139
1140 #ifdef CONFIG_HOTPLUG_CPU
1141 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1142    not required for correctness.  So if the last cpu in a node goes
1143    away, we get changed to run anywhere: as the first one comes back,
1144    restore their cpu bindings. */
1145 static int __devinit cpu_callback(struct notifier_block *nfb,
1146                                   unsigned long action,
1147                                   void *hcpu)
1148 {
1149         pg_data_t *pgdat;
1150         cpumask_t mask;
1151
1152         if (action == CPU_ONLINE) {
1153                 for_each_pgdat(pgdat) {
1154                         mask = node_to_cpumask(pgdat->node_id);
1155                         if (any_online_cpu(mask) != NR_CPUS)
1156                                 /* One of our CPUs online: restore mask */
1157                                 set_cpus_allowed(pgdat->kswapd, mask);
1158                 }
1159         }
1160         return NOTIFY_OK;
1161 }
1162 #endif /* CONFIG_HOTPLUG_CPU */
1163
1164 static int __init kswapd_init(void)
1165 {
1166         pg_data_t *pgdat;
1167         swap_setup();
1168         for_each_pgdat(pgdat)
1169                 pgdat->kswapd
1170                 = find_task_by_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1171         total_memory = nr_free_pagecache_pages();
1172         hotcpu_notifier(cpu_callback, 0);
1173         return 0;
1174 }
1175
1176 module_init(kswapd_init)