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