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