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