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