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