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