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