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