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