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