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