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