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