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