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