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                 page = lru_to_page(page_list);
375                 list_del(&page->lru);
376
377                 if (TestSetPageLocked(page))
378                         goto keep;
379
380                 BUG_ON(PageActive(page));
381
382                 sc->nr_scanned++;
383                 /* Double the slab pressure for mapped and swapcache pages */
384                 if (page_mapped(page) || PageSwapCache(page))
385                         sc->nr_scanned++;
386
387                 if (PageWriteback(page))
388                         goto keep_locked;
389
390                 referenced = page_referenced(page, 1, sc->priority <= 0);
391                 /* In active use or really unfreeable?  Activate it. */
392                 if (referenced && page_mapping_inuse(page))
393                         goto activate_locked;
394
395 #ifdef CONFIG_SWAP
396                 /*
397                  * Anonymous process memory has backing store?
398                  * Try to allocate it some swap space here.
399                  */
400                 if (PageAnon(page) && !PageSwapCache(page)) {
401                         if (!add_to_swap(page))
402                                 goto activate_locked;
403                 }
404 #endif /* CONFIG_SWAP */
405
406                 mapping = page_mapping(page);
407                 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
408                         (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
409
410                 /*
411                  * The page is mapped into the page tables of one or more
412                  * processes. Try to unmap it here.
413                  */
414                 if (page_mapped(page) && mapping) {
415                         switch (try_to_unmap(page)) {
416                         case SWAP_FAIL:
417                                 goto activate_locked;
418                         case SWAP_AGAIN:
419                                 goto keep_locked;
420                         case SWAP_SUCCESS:
421                                 ; /* try to free the page below */
422                         }
423                 }
424
425                 if (PageDirty(page)) {
426                         if (referenced)
427                                 goto keep_locked;
428                         if (!may_enter_fs)
429                                 goto keep_locked;
430                         if (laptop_mode && !sc->may_writepage)
431                                 goto keep_locked;
432
433                         /* Page is dirty, try to write it out here */
434                         switch(pageout(page, mapping)) {
435                         case PAGE_KEEP:
436                                 goto keep_locked;
437                         case PAGE_ACTIVATE:
438                                 goto activate_locked;
439                         case PAGE_SUCCESS:
440                                 if (PageWriteback(page) || PageDirty(page))
441                                         goto keep;
442                                 /*
443                                  * A synchronous write - probably a ramdisk.  Go
444                                  * ahead and try to reclaim the page.
445                                  */
446                                 if (TestSetPageLocked(page))
447                                         goto keep;
448                                 if (PageDirty(page) || PageWriteback(page))
449                                         goto keep_locked;
450                                 mapping = page_mapping(page);
451                         case PAGE_CLEAN:
452                                 ; /* try to free the page below */
453                         }
454                 }
455
456                 /*
457                  * If the page has buffers, try to free the buffer mappings
458                  * associated with this page. If we succeed we try to free
459                  * the page as well.
460                  *
461                  * We do this even if the page is PageDirty().
462                  * try_to_release_page() does not perform I/O, but it is
463                  * possible for a page to have PageDirty set, but it is actually
464                  * clean (all its buffers are clean).  This happens if the
465                  * buffers were written out directly, with submit_bh(). ext3
466                  * will do this, as well as the blockdev mapping. 
467                  * try_to_release_page() will discover that cleanness and will
468                  * drop the buffers and mark the page clean - it can be freed.
469                  *
470                  * Rarely, pages can have buffers and no ->mapping.  These are
471                  * the pages which were not successfully invalidated in
472                  * truncate_complete_page().  We try to drop those buffers here
473                  * and if that worked, and the page is no longer mapped into
474                  * process address space (page_count == 1) it can be freed.
475                  * Otherwise, leave the page on the LRU so it is swappable.
476                  */
477                 if (PagePrivate(page)) {
478                         if (!try_to_release_page(page, sc->gfp_mask))
479                                 goto activate_locked;
480                         if (!mapping && page_count(page) == 1)
481                                 goto free_it;
482                 }
483
484                 if (!mapping)
485                         goto keep_locked;       /* truncate got there first */
486
487                 spin_lock_irq(&mapping->tree_lock);
488
489                 /*
490                  * The non-racy check for busy page.  It is critical to check
491                  * PageDirty _after_ making sure that the page is freeable and
492                  * not in use by anybody.       (pagecache + us == 2)
493                  */
494                 if (page_count(page) != 2 || PageDirty(page)) {
495                         spin_unlock_irq(&mapping->tree_lock);
496                         goto keep_locked;
497                 }
498
499 #ifdef CONFIG_SWAP
500                 if (PageSwapCache(page)) {
501                         swp_entry_t swap = { .val = page->private };
502                         __delete_from_swap_cache(page);
503                         spin_unlock_irq(&mapping->tree_lock);
504                         swap_free(swap);
505                         __put_page(page);       /* The pagecache ref */
506                         goto free_it;
507                 }
508 #endif /* CONFIG_SWAP */
509
510                 __remove_from_page_cache(page);
511                 spin_unlock_irq(&mapping->tree_lock);
512                 __put_page(page);
513
514 free_it:
515                 unlock_page(page);
516                 reclaimed++;
517                 if (!pagevec_add(&freed_pvec, page))
518                         __pagevec_release_nonlru(&freed_pvec);
519                 continue;
520
521 activate_locked:
522                 SetPageActive(page);
523                 pgactivate++;
524 keep_locked:
525                 unlock_page(page);
526 keep:
527                 list_add(&page->lru, &ret_pages);
528                 BUG_ON(PageLRU(page));
529         }
530         list_splice(&ret_pages, page_list);
531         if (pagevec_count(&freed_pvec))
532                 __pagevec_release_nonlru(&freed_pvec);
533         mod_page_state(pgactivate, pgactivate);
534         sc->nr_reclaimed += reclaimed;
535         return reclaimed;
536 }
537
538 /*
539  * zone->lru_lock is heavily contented.  We relieve it by quickly privatising
540  * a batch of pages and working on them outside the lock.  Any pages which were
541  * not freed will be added back to the LRU.
542  *
543  * shrink_cache() adds the number of pages reclaimed to sc->nr_reclaimed
544  *
545  * For pagecache intensive workloads, the first loop here is the hottest spot
546  * in the kernel (apart from the copy_*_user functions).
547  */
548 static void shrink_cache(struct zone *zone, struct scan_control *sc)
549 {
550         LIST_HEAD(page_list);
551         struct pagevec pvec;
552         int max_scan = sc->nr_to_scan, nr_pass;
553         unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
554
555         pagevec_init(&pvec, 1);
556
557         lru_add_drain();
558         spin_lock_irq(&zone->lru_lock);
559 redo:
560         ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
561         nr_pass = zone->nr_inactive;
562         while (max_scan > 0) {
563                 struct page *page;
564                 int nr_taken = 0;
565                 int nr_scan = 0;
566                 int nr_freed;
567
568                 while (nr_pass-- && nr_scan++ < SWAP_CLUSTER_MAX &&
569                                 !list_empty(&zone->inactive_list)) {
570                         page = lru_to_page(&zone->inactive_list);
571
572                         prefetchw_prev_lru_page(page,
573                                                 &zone->inactive_list, flags);
574
575                         if (!TestClearPageLRU(page))
576                                 BUG();
577                         list_del(&page->lru);
578                         if (get_page_testone(page)) {
579                                 /*
580                                  * It is being freed elsewhere
581                                  */
582                                 __put_page(page);
583                                 SetPageLRU(page);
584                                 list_add(&page->lru, &zone->inactive_list);
585                                 continue;
586                         } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
587                                 __put_page(page);
588                                 SetPageLRU(page);
589 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
590                                 list_add_tail(&page->lru, &zone->inactive_list);
591 #else
592                                 list_add(&page->lru, &zone->inactive_list);
593 #endif
594                                 continue;
595                         }
596                         list_add(&page->lru, &page_list);
597                         ckrm_mem_dec_inactive(page);
598                         nr_taken++;
599                 }
600                 zone->nr_inactive -= nr_taken;
601                 spin_unlock_irq(&zone->lru_lock);
602
603                 if ((bit_flag == 0) && (nr_taken == 0))
604                         goto done;
605
606                 max_scan -= nr_scan;
607                 if (current_is_kswapd())
608                         mod_page_state_zone(zone, pgscan_kswapd, nr_scan);
609                 else
610                         mod_page_state_zone(zone, pgscan_direct, nr_scan);
611                 nr_freed = shrink_list(&page_list, sc);
612                 if (current_is_kswapd())
613                         mod_page_state(kswapd_steal, nr_freed);
614                 mod_page_state_zone(zone, pgsteal, nr_freed);
615                 sc->nr_to_reclaim -= nr_freed;
616
617                 spin_lock_irq(&zone->lru_lock);
618                 /*
619                  * Put back any unfreeable pages.
620                  */
621                 while (!list_empty(&page_list)) {
622                         page = lru_to_page(&page_list);
623                         if (TestSetPageLRU(page))
624                                 BUG();
625                         list_del(&page->lru);
626                         if (PageActive(page))
627                                 add_page_to_active_list(zone, page);
628                         else
629                                 add_page_to_inactive_list(zone, page);
630                         if (!pagevec_add(&pvec, page)) {
631                                 spin_unlock_irq(&zone->lru_lock);
632                                 __pagevec_release(&pvec);
633                                 spin_lock_irq(&zone->lru_lock);
634                         }
635                 }
636                 if (ckrm_flags && (nr_pass <= 0)) {
637                         goto redo;
638                 }
639         }
640         spin_unlock_irq(&zone->lru_lock);
641 done:
642         pagevec_release(&pvec);
643 }
644
645 /*
646  * This moves pages from the active list to the inactive list.
647  *
648  * We move them the other way if the page is referenced by one or more
649  * processes, from rmap.
650  *
651  * If the pages are mostly unmapped, the processing is fast and it is
652  * appropriate to hold zone->lru_lock across the whole operation.  But if
653  * the pages are mapped, the processing is slow (page_referenced()) so we
654  * should drop zone->lru_lock around each page.  It's impossible to balance
655  * this, so instead we remove the pages from the LRU while processing them.
656  * It is safe to rely on PG_active against the non-LRU pages in here because
657  * nobody will play with that bit on a non-LRU page.
658  *
659  * The downside is that we have to touch page->_count against each page.
660  * But we had to alter page->flags anyway.
661  */
662 static void
663 refill_inactive_zone(struct zone *zone, struct scan_control *sc)
664 {
665         int pgmoved;
666         int pgdeactivate = 0;
667         int pgscanned = 0;
668         int nr_pages = sc->nr_to_scan;
669         LIST_HEAD(l_hold);      /* The pages which were snipped off */
670         LIST_HEAD(l_inactive);  /* Pages to go onto the inactive_list */
671         LIST_HEAD(l_active);    /* Pages to go onto the active_list */
672         struct page *page;
673         struct pagevec pvec;
674         int reclaim_mapped = 0;
675         long mapped_ratio;
676         long distress;
677         long swap_tendency;
678         unsigned int ckrm_flags = sc->ckrm_flags, bit_flag;
679         int nr_pass;
680
681         lru_add_drain();
682         pgmoved = 0;
683         spin_lock_irq(&zone->lru_lock);
684 redo:
685         ckrm_get_reclaim_bits(&ckrm_flags, &bit_flag);
686         nr_pass = zone->nr_active;
687         while (pgscanned < nr_pages && !list_empty(&zone->active_list) &&
688                                                 nr_pass) {
689                 page = lru_to_page(&zone->active_list);
690                 prefetchw_prev_lru_page(page, &zone->active_list, flags);
691                 if (!TestClearPageLRU(page))
692                         BUG();
693                 list_del(&page->lru);
694                 if (get_page_testone(page)) {
695                         /*
696                          * It was already free!  release_pages() or put_page()
697                          * are about to remove it from the LRU and free it. So
698                          * put the refcount back and put the page back on the
699                          * LRU
700                          */
701                         __put_page(page);
702                         SetPageLRU(page);
703                         list_add(&page->lru, &zone->active_list);
704                         pgscanned++;
705                 } else if (bit_flag && !ckrm_kick_page(page, bit_flag)) {
706                         __put_page(page);
707                         SetPageLRU(page);
708 #ifdef CONFIG_CKRM_MEM_LRUORDER_CHANGE
709                         list_add_tail(&page->lru, &zone->active_list);
710 #else
711                         list_add(&page->lru, &zone->active_list);
712 #endif
713                 } else {
714                         list_add(&page->lru, &l_hold);
715                         ckrm_mem_dec_active(page);
716                         pgmoved++;
717                         pgscanned++;
718                 }
719                 if (!--nr_pass && ckrm_flags) {
720                         goto redo;
721                 }
722         }
723         zone->pages_scanned += pgscanned;
724         zone->nr_active -= pgmoved;
725         spin_unlock_irq(&zone->lru_lock);
726
727         /*
728          * `distress' is a measure of how much trouble we're having reclaiming
729          * pages.  0 -> no problems.  100 -> great trouble.
730          */
731         distress = 100 >> zone->prev_priority;
732
733         /*
734          * The point of this algorithm is to decide when to start reclaiming
735          * mapped memory instead of just pagecache.  Work out how much memory
736          * is mapped.
737          */
738         mapped_ratio = (sc->nr_mapped * 100) / total_memory;
739
740         /*
741          * Now decide how much we really want to unmap some pages.  The mapped
742          * ratio is downgraded - just because there's a lot of mapped memory
743          * doesn't necessarily mean that page reclaim isn't succeeding.
744          *
745          * The distress ratio is important - we don't want to start going oom.
746          *
747          * A 100% value of vm_swappiness overrides this algorithm altogether.
748          */
749         swap_tendency = mapped_ratio / 2 + distress + vm_swappiness;
750
751         /*
752          * Now use this metric to decide whether to start moving mapped memory
753          * onto the inactive list.
754          */
755         if (swap_tendency >= 100)
756                 reclaim_mapped = 1;
757
758         while (!list_empty(&l_hold)) {
759                 page = lru_to_page(&l_hold);
760                 list_del(&page->lru);
761                 if (page_mapped(page)) {
762                         if (!reclaim_mapped ||
763                             (total_swap_pages == 0 && PageAnon(page)) ||
764                             page_referenced(page, 0, sc->priority <= 0)) {
765                                 list_add(&page->lru, &l_active);
766                                 continue;
767                         }
768                 }
769                 list_add(&page->lru, &l_inactive);
770         }
771
772         pagevec_init(&pvec, 1);
773         pgmoved = 0;
774         spin_lock_irq(&zone->lru_lock);
775         while (!list_empty(&l_inactive)) {
776                 page = lru_to_page(&l_inactive);
777                 prefetchw_prev_lru_page(page, &l_inactive, flags);
778                 if (TestSetPageLRU(page))
779                         BUG();
780                 if (!TestClearPageActive(page))
781                         BUG();
782                 list_move(&page->lru, &zone->inactive_list);
783                 ckrm_mem_inc_inactive(page);
784                 pgmoved++;
785                 if (!pagevec_add(&pvec, page)) {
786                         zone->nr_inactive += pgmoved;
787                         spin_unlock_irq(&zone->lru_lock);
788                         pgdeactivate += pgmoved;
789                         pgmoved = 0;
790                         if (buffer_heads_over_limit)
791                                 pagevec_strip(&pvec);
792                         __pagevec_release(&pvec);
793                         spin_lock_irq(&zone->lru_lock);
794                 }
795         }
796         zone->nr_inactive += pgmoved;
797         pgdeactivate += pgmoved;
798         if (buffer_heads_over_limit) {
799                 spin_unlock_irq(&zone->lru_lock);
800                 pagevec_strip(&pvec);
801                 spin_lock_irq(&zone->lru_lock);
802         }
803
804         pgmoved = 0;
805         while (!list_empty(&l_active)) {
806                 page = lru_to_page(&l_active);
807                 prefetchw_prev_lru_page(page, &l_active, flags);
808                 if (TestSetPageLRU(page))
809                         BUG();
810                 BUG_ON(!PageActive(page));
811                 list_move(&page->lru, &zone->active_list);
812                 ckrm_mem_inc_active(page);
813                 pgmoved++;
814                 if (!pagevec_add(&pvec, page)) {
815                         zone->nr_active += pgmoved;
816                         pgmoved = 0;
817                         spin_unlock_irq(&zone->lru_lock);
818                         __pagevec_release(&pvec);
819                         spin_lock_irq(&zone->lru_lock);
820                 }
821         }
822         zone->nr_active += pgmoved;
823         spin_unlock_irq(&zone->lru_lock);
824         pagevec_release(&pvec);
825
826         mod_page_state_zone(zone, pgrefill, pgscanned);
827         mod_page_state(pgdeactivate, pgdeactivate);
828 }
829
830 /*
831  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
832  */
833 static void
834 shrink_zone(struct zone *zone, struct scan_control *sc)
835 {
836         unsigned long nr_active;
837         unsigned long nr_inactive;
838
839         /*
840          * Add one to `nr_to_scan' just to make sure that the kernel will
841          * slowly sift through the active list.
842          */
843         zone->nr_scan_active += (zone->nr_active >> sc->priority) + 1;
844         nr_active = zone->nr_scan_active;
845         if (nr_active >= SWAP_CLUSTER_MAX)
846                 zone->nr_scan_active = 0;
847         else
848                 nr_active = 0;
849
850         zone->nr_scan_inactive += (zone->nr_inactive >> sc->priority) + 1;
851         nr_inactive = zone->nr_scan_inactive;
852         if (nr_inactive >= SWAP_CLUSTER_MAX)
853                 zone->nr_scan_inactive = 0;
854         else
855                 nr_inactive = 0;
856
857         sc->nr_to_reclaim = SWAP_CLUSTER_MAX;
858
859         while (nr_active || nr_inactive) {
860                 sc->ckrm_flags = ckrm_setup_reclamation();
861                 if (nr_active) {
862                         sc->nr_to_scan = min(nr_active,
863                                         (unsigned long)SWAP_CLUSTER_MAX);
864                         nr_active -= sc->nr_to_scan;
865                         refill_inactive_zone(zone, sc);
866                 }
867
868                 if (nr_inactive) {
869                         sc->nr_to_scan = min(nr_inactive,
870                                         (unsigned long)SWAP_CLUSTER_MAX);
871                         nr_inactive -= sc->nr_to_scan;
872                         shrink_cache(zone, sc);
873                         if (sc->nr_to_reclaim <= 0)
874                                 break;
875                 }
876                 ckrm_teardown_reclamation();
877         }
878 }
879
880 #if defined(CONFIG_CKRM_RES_MEM) && defined(AT_LIMIT_SUPPORT)
881 // This function needs to be given more thought.
882 // Shrink the class to be at 90% of its limit
883 static void
884 ckrm_shrink_class(ckrm_mem_res_t *cls)
885 {
886         struct scan_control sc;
887         struct zone *zone;
888         int zindex = 0, active_credit = 0, inactive_credit = 0;
889
890         if (ckrm_test_set_shrink(cls)) { // set the SHRINK bit atomically
891                 // if it is already set somebody is working on it. so... leave
892                 return;
893         }
894         sc.nr_mapped = read_page_state(nr_mapped);
895         sc.nr_scanned = 0;
896         sc.ckrm_flags = ckrm_get_reclaim_flags(cls);
897         sc.nr_reclaimed = 0;
898         sc.priority = 0; // always very high priority
899
900         for_each_zone(zone) {
901                 int zone_total, zone_limit, active_limit, inactive_limit;
902                 int active_over, inactive_over;
903                 unsigned long nr_active, nr_inactive;
904                 u64 temp;
905
906                 zone->temp_priority = zone->prev_priority;
907                 zone->prev_priority = sc.priority;
908
909                 zone_total = zone->nr_active + zone->nr_inactive + zone->free_pages;
910
911                 temp = (u64) cls->pg_limit * zone_total;
912                 do_div(temp, ckrm_tot_lru_pages);
913                 zone_limit = (int) temp;
914                 active_limit = (6 * zone_limit) / 10; // 2/3rd in active list
915                 inactive_limit = (3 * zone_limit) / 10; // 1/3rd in inactive list
916
917                 active_over = cls->nr_active[zindex] - active_limit + active_credit;
918                 inactive_over = active_over +
919                                 (cls->nr_inactive[zindex] - inactive_limit) + inactive_credit;
920
921                 if (active_over > 0) {
922                         zone->nr_scan_active += active_over + 1;
923                         nr_active = zone->nr_scan_active;
924                         active_credit = 0;
925                 } else {
926                         active_credit += active_over;
927                         nr_active = 0;
928                 }
929
930                 if (inactive_over > 0) {
931                         zone->nr_scan_inactive += inactive_over;
932                         nr_inactive = zone->nr_scan_inactive;
933                         inactive_credit = 0;
934                 } else {
935                         inactive_credit += inactive_over;
936                         nr_inactive = 0;
937                 }
938                 while (nr_active || nr_inactive) {
939                         if (nr_active) {
940                                 sc.nr_to_scan = min(nr_active,
941                                                 (unsigned long)SWAP_CLUSTER_MAX);
942                                 nr_active -= sc.nr_to_scan;
943                                 refill_inactive_zone(zone, &sc);
944                         }
945         
946                         if (nr_inactive) {
947                                 sc.nr_to_scan = min(nr_inactive,
948                                                 (unsigned long)SWAP_CLUSTER_MAX);
949                                 nr_inactive -= sc.nr_to_scan;
950                                 shrink_cache(zone, &sc);
951                                 if (sc.nr_to_reclaim <= 0)
952                                         break;
953                         }
954                 }
955                 zone->prev_priority = zone->temp_priority;
956                 zindex++;
957         }
958         ckrm_clear_shrink(cls);
959 }
960
961 static void
962 ckrm_shrink_classes(void)
963 {
964         ckrm_mem_res_t *cls;
965
966         spin_lock(&ckrm_mem_lock);
967         while (!ckrm_shrink_list_empty()) {
968                 cls =  list_entry(ckrm_shrink_list.next, ckrm_mem_res_t,
969                                 shrink_list);
970                 spin_unlock(&ckrm_mem_lock);
971                 ckrm_shrink_class(cls);
972                 spin_lock(&ckrm_mem_lock);
973                 list_del(&cls->shrink_list);
974                 cls->flags &= ~MEM_AT_LIMIT;
975         }
976         spin_unlock(&ckrm_mem_lock);
977         throttle_vm_writeout();
978 }
979
980 #else
981
982 #if defined(CONFIG_CKRM_RES_MEM) && !defined(AT_LIMIT_SUPPORT)
983 #warning "disabling ckrm_at_limit -- setting ckrm_shrink_classes to noop "
984 #endif
985
986 #define ckrm_shrink_classes()   do { } while(0)
987 #endif
988
989 /*
990  * This is the direct reclaim path, for page-allocating processes.  We only
991  * try to reclaim pages from zones which will satisfy the caller's allocation
992  * request.
993  *
994  * We reclaim from a zone even if that zone is over pages_high.  Because:
995  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
996  *    allocation or
997  * b) The zones may be over pages_high but they must go *over* pages_high to
998  *    satisfy the `incremental min' zone defense algorithm.
999  *
1000  * Returns the number of reclaimed pages.
1001  *
1002  * If a zone is deemed to be full of pinned pages then just give it a light
1003  * scan then give up on it.
1004  */
1005 static void
1006 shrink_caches(struct zone **zones, struct scan_control *sc)
1007 {
1008         int i;
1009
1010         for (i = 0; zones[i] != NULL; i++) {
1011                 struct zone *zone = zones[i];
1012
1013                 if (zone->present_pages == 0)
1014                         continue;
1015
1016                 zone->temp_priority = sc->priority;
1017                 if (zone->prev_priority > sc->priority)
1018                         zone->prev_priority = sc->priority;
1019
1020                 if (zone->all_unreclaimable && sc->priority != DEF_PRIORITY)
1021                         continue;       /* Let kswapd poll it */
1022
1023                 shrink_zone(zone, sc);
1024         }
1025 }
1026  
1027 /*
1028  * This is the main entry point to direct page reclaim.
1029  *
1030  * If a full scan of the inactive list fails to free enough memory then we
1031  * are "out of memory" and something needs to be killed.
1032  *
1033  * If the caller is !__GFP_FS then the probability of a failure is reasonably
1034  * high - the zone may be full of dirty or under-writeback pages, which this
1035  * caller can't do much about.  We kick pdflush and take explicit naps in the
1036  * hope that some of these pages can be written.  But if the allocating task
1037  * holds filesystem locks which prevent writeout this might not work, and the
1038  * allocation attempt will fail.
1039  */
1040 int try_to_free_pages(struct zone **zones,
1041                 unsigned int gfp_mask, unsigned int order)
1042 {
1043         int priority;
1044         int ret = 0;
1045         int total_scanned = 0, total_reclaimed = 0;
1046         struct reclaim_state *reclaim_state = current->reclaim_state;
1047         struct scan_control sc;
1048         unsigned long lru_pages = 0;
1049         int i;
1050
1051         sc.gfp_mask = gfp_mask;
1052         sc.may_writepage = 0;
1053
1054         inc_page_state(allocstall);
1055
1056         for (i = 0; zones[i] != NULL; i++) {
1057                 struct zone *zone = zones[i];
1058
1059                 zone->temp_priority = DEF_PRIORITY;
1060                 lru_pages += zone->nr_active + zone->nr_inactive;
1061         }
1062
1063         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1064                 sc.nr_mapped = read_page_state(nr_mapped);
1065                 sc.nr_scanned = 0;
1066                 sc.nr_reclaimed = 0;
1067                 sc.priority = priority;
1068                 shrink_caches(zones, &sc);
1069                 shrink_slab(sc.nr_scanned, gfp_mask, lru_pages);
1070                 if (reclaim_state) {
1071                         sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1072                         reclaim_state->reclaimed_slab = 0;
1073                 }
1074                 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX) {
1075                         ret = 1;
1076                         goto out;
1077                 }
1078                 total_scanned += sc.nr_scanned;
1079                 total_reclaimed += sc.nr_reclaimed;
1080
1081                 /*
1082                  * Try to write back as many pages as we just scanned.  This
1083                  * tends to cause slow streaming writers to write data to the
1084                  * disk smoothly, at the dirtying rate, which is nice.   But
1085                  * that's undesirable in laptop mode, where we *want* lumpy
1086                  * writeout.  So in laptop mode, write out the whole world.
1087                  */
1088                 if (total_scanned > SWAP_CLUSTER_MAX + SWAP_CLUSTER_MAX/2) {
1089                         wakeup_bdflush(laptop_mode ? 0 : total_scanned);
1090                         sc.may_writepage = 1;
1091                 }
1092
1093                 /* Take a nap, wait for some writeback to complete */
1094                 if (sc.nr_scanned && priority < DEF_PRIORITY - 2)
1095                         blk_congestion_wait(WRITE, HZ/10);
1096         }
1097         if ((gfp_mask & __GFP_FS) && !(gfp_mask & __GFP_NORETRY))
1098                 out_of_memory(gfp_mask);
1099 out:
1100         for (i = 0; zones[i] != 0; i++)
1101                 zones[i]->prev_priority = zones[i]->temp_priority;
1102         return ret;
1103 }
1104
1105 /*
1106  * For kswapd, balance_pgdat() will work across all this node's zones until
1107  * they are all at pages_high.
1108  *
1109  * If `nr_pages' is non-zero then it is the number of pages which are to be
1110  * reclaimed, regardless of the zone occupancies.  This is a software suspend
1111  * special.
1112  *
1113  * Returns the number of pages which were actually freed.
1114  *
1115  * There is special handling here for zones which are full of pinned pages.
1116  * This can happen if the pages are all mlocked, or if they are all used by
1117  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
1118  * What we do is to detect the case where all pages in the zone have been
1119  * scanned twice and there has been zero successful reclaim.  Mark the zone as
1120  * dead and from now on, only perform a short scan.  Basically we're polling
1121  * the zone for when the problem goes away.
1122  *
1123  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
1124  * zones which have free_pages > pages_high, but once a zone is found to have
1125  * free_pages <= pages_high, we scan that zone and the lower zones regardless
1126  * of the number of free pages in the lower zones.  This interoperates with
1127  * the page allocator fallback scheme to ensure that aging of pages is balanced
1128  * across the zones.
1129  */
1130 static int balance_pgdat(pg_data_t *pgdat, int nr_pages)
1131 {
1132         int to_free = nr_pages;
1133         int all_zones_ok;
1134         int priority;
1135         int i;
1136         int total_scanned, total_reclaimed;
1137         struct reclaim_state *reclaim_state = current->reclaim_state;
1138         struct scan_control sc;
1139
1140 loop_again:
1141         total_scanned = 0;
1142         total_reclaimed = 0;
1143         sc.gfp_mask = GFP_KERNEL;
1144         sc.may_writepage = 0;
1145         sc.nr_mapped = read_page_state(nr_mapped);
1146
1147         inc_page_state(pageoutrun);
1148
1149         for (i = 0; i < pgdat->nr_zones; i++) {
1150                 struct zone *zone = pgdat->node_zones + i;
1151
1152                 zone->temp_priority = DEF_PRIORITY;
1153         }
1154
1155         for (priority = DEF_PRIORITY; priority >= 0; priority--) {
1156                 int end_zone = 0;       /* Inclusive.  0 = ZONE_DMA */
1157                 unsigned long lru_pages = 0;
1158
1159                 all_zones_ok = 1;
1160
1161                 if (nr_pages == 0) {
1162                         /*
1163                          * Scan in the highmem->dma direction for the highest
1164                          * zone which needs scanning
1165                          */
1166                         for (i = pgdat->nr_zones - 1; i >= 0; i--) {
1167                                 struct zone *zone = pgdat->node_zones + i;
1168
1169                                 if (zone->present_pages == 0)
1170                                         continue;
1171
1172                                 if (zone->all_unreclaimable &&
1173                                                 priority != DEF_PRIORITY)
1174                                         continue;
1175
1176                                 if (zone->free_pages <= zone->pages_high) {
1177                                         end_zone = i;
1178                                         goto scan;
1179                                 }
1180                         }
1181                         goto out;
1182                 } else {
1183                         end_zone = pgdat->nr_zones - 1;
1184                 }
1185 scan:
1186                 for (i = 0; i <= end_zone; i++) {
1187                         struct zone *zone = pgdat->node_zones + i;
1188
1189                         lru_pages += zone->nr_active + zone->nr_inactive;
1190                 }
1191
1192                 /*
1193                  * Now scan the zone in the dma->highmem direction, stopping
1194                  * at the last zone which needs scanning.
1195                  *
1196                  * We do this because the page allocator works in the opposite
1197                  * direction.  This prevents the page allocator from allocating
1198                  * pages behind kswapd's direction of progress, which would
1199                  * cause too much scanning of the lower zones.
1200                  */
1201                 for (i = 0; i <= end_zone; i++) {
1202                         struct zone *zone = pgdat->node_zones + i;
1203
1204                         if (zone->present_pages == 0)
1205                                 continue;
1206
1207                         if (zone->all_unreclaimable && priority != DEF_PRIORITY)
1208                                 continue;
1209
1210                         if (nr_pages == 0) {    /* Not software suspend */
1211                                 if (zone->free_pages <= zone->pages_high)
1212                                         all_zones_ok = 0;
1213                         }
1214                         zone->temp_priority = priority;
1215                         if (zone->prev_priority > priority)
1216                                 zone->prev_priority = priority;
1217                         sc.nr_scanned = 0;
1218                         sc.nr_reclaimed = 0;
1219                         sc.priority = priority;
1220                         shrink_zone(zone, &sc);
1221                         reclaim_state->reclaimed_slab = 0;
1222                         shrink_slab(sc.nr_scanned, GFP_KERNEL, lru_pages);
1223                         sc.nr_reclaimed += reclaim_state->reclaimed_slab;
1224                         total_reclaimed += sc.nr_reclaimed;
1225                         total_scanned += sc.nr_scanned;
1226                         if (zone->all_unreclaimable)
1227                                 continue;
1228                         if (zone->pages_scanned >= (zone->nr_active +
1229                                                         zone->nr_inactive) * 4)
1230                                 zone->all_unreclaimable = 1;
1231                         /*
1232                          * If we've done a decent amount of scanning and
1233                          * the reclaim ratio is low, start doing writepage
1234                          * even in laptop mode
1235                          */
1236                         if (total_scanned > SWAP_CLUSTER_MAX * 2 &&
1237                             total_scanned > total_reclaimed+total_reclaimed/2)
1238                                 sc.may_writepage = 1;
1239                 }
1240                 if (nr_pages && to_free > total_reclaimed)
1241                         continue;       /* swsusp: need to do more work */
1242                 if (all_zones_ok)
1243                         break;          /* kswapd: all done */
1244                 /*
1245                  * OK, kswapd is getting into trouble.  Take a nap, then take
1246                  * another pass across the zones.
1247                  */
1248                 if (total_scanned && priority < DEF_PRIORITY - 2)
1249                         blk_congestion_wait(WRITE, HZ/10);
1250
1251                 /*
1252                  * We do this so kswapd doesn't build up large priorities for
1253                  * example when it is freeing in parallel with allocators. It
1254                  * matches the direct reclaim path behaviour in terms of impact
1255                  * on zone->*_priority.
1256                  */
1257                 if (total_reclaimed >= SWAP_CLUSTER_MAX)
1258                         break;
1259         }
1260 out:
1261         for (i = 0; i < pgdat->nr_zones; i++) {
1262                 struct zone *zone = pgdat->node_zones + i;
1263
1264                 zone->prev_priority = zone->temp_priority;
1265         }
1266         if (!all_zones_ok) {
1267                 cond_resched();
1268                 goto loop_again;
1269         }
1270
1271         return total_reclaimed;
1272 }
1273
1274 /*
1275  * The background pageout daemon, started as a kernel thread
1276  * from the init process. 
1277  *
1278  * This basically trickles out pages so that we have _some_
1279  * free memory available even if there is no other activity
1280  * that frees anything up. This is needed for things like routing
1281  * etc, where we otherwise might have all activity going on in
1282  * asynchronous contexts that cannot page things out.
1283  *
1284  * If there are applications that are active memory-allocators
1285  * (most normal use), this basically shouldn't matter.
1286  */
1287 static int kswapd(void *p)
1288 {
1289         pg_data_t *pgdat = (pg_data_t*)p;
1290         struct task_struct *tsk = current;
1291         DEFINE_WAIT(wait);
1292         struct reclaim_state reclaim_state = {
1293                 .reclaimed_slab = 0,
1294         };
1295         cpumask_t cpumask;
1296
1297         daemonize("kswapd%d", pgdat->node_id);
1298         cpumask = node_to_cpumask(pgdat->node_id);
1299         if (!cpus_empty(cpumask))
1300                 set_cpus_allowed(tsk, cpumask);
1301         current->reclaim_state = &reclaim_state;
1302
1303         /*
1304          * Tell the memory management that we're a "memory allocator",
1305          * and that if we need more memory we should get access to it
1306          * regardless (see "__alloc_pages()"). "kswapd" should
1307          * never get caught in the normal page freeing logic.
1308          *
1309          * (Kswapd normally doesn't need memory anyway, but sometimes
1310          * you need a small amount of memory in order to be able to
1311          * page out something else, and this flag essentially protects
1312          * us from recursively trying to free more memory as we're
1313          * trying to free the first piece of memory in the first place).
1314          */
1315         tsk->flags |= PF_MEMALLOC|PF_KSWAPD;
1316
1317         for ( ; ; ) {
1318                 if (current->flags & PF_FREEZE)
1319                         refrigerator(PF_FREEZE);
1320                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
1321                 schedule();
1322                 finish_wait(&pgdat->kswapd_wait, &wait);
1323
1324                 if (!ckrm_shrink_list_empty())
1325                         ckrm_shrink_classes();
1326                 else
1327                 balance_pgdat(pgdat, 0);
1328         }
1329         return 0;
1330 }
1331
1332 /*
1333  * A zone is low on free memory, so wake its kswapd task to service it.
1334  */
1335 void wakeup_kswapd(struct zone *zone)
1336 {
1337         if (zone->present_pages == 0)
1338                 return;
1339         if ((zone->free_pages > zone->pages_low) && ckrm_shrink_list_empty())
1340                 return;
1341         if (!waitqueue_active(&zone->zone_pgdat->kswapd_wait))
1342                 return;
1343         wake_up_interruptible(&zone->zone_pgdat->kswapd_wait);
1344 }
1345
1346 #ifdef CONFIG_PM
1347 /*
1348  * Try to free `nr_pages' of memory, system-wide.  Returns the number of freed
1349  * pages.
1350  */
1351 int shrink_all_memory(int nr_pages)
1352 {
1353         pg_data_t *pgdat;
1354         int nr_to_free = nr_pages;
1355         int ret = 0;
1356         struct reclaim_state reclaim_state = {
1357                 .reclaimed_slab = 0,
1358         };
1359
1360         current->reclaim_state = &reclaim_state;
1361         for_each_pgdat(pgdat) {
1362                 int freed;
1363                 freed = balance_pgdat(pgdat, nr_to_free);
1364                 ret += freed;
1365                 nr_to_free -= freed;
1366                 if (nr_to_free <= 0)
1367                         break;
1368         }
1369         current->reclaim_state = NULL;
1370         return ret;
1371 }
1372 #endif
1373
1374 #ifdef CONFIG_HOTPLUG_CPU
1375 /* It's optimal to keep kswapds on the same CPUs as their memory, but
1376    not required for correctness.  So if the last cpu in a node goes
1377    away, we get changed to run anywhere: as the first one comes back,
1378    restore their cpu bindings. */
1379 static int __devinit cpu_callback(struct notifier_block *nfb,
1380                                   unsigned long action,
1381                                   void *hcpu)
1382 {
1383         pg_data_t *pgdat;
1384         cpumask_t mask;
1385
1386         if (action == CPU_ONLINE) {
1387                 for_each_pgdat(pgdat) {
1388                         mask = node_to_cpumask(pgdat->node_id);
1389                         if (any_online_cpu(mask) != NR_CPUS)
1390                                 /* One of our CPUs online: restore mask */
1391                                 set_cpus_allowed(pgdat->kswapd, mask);
1392                 }
1393         }
1394         return NOTIFY_OK;
1395 }
1396 #endif /* CONFIG_HOTPLUG_CPU */
1397
1398 static int __init kswapd_init(void)
1399 {
1400         pg_data_t *pgdat;
1401         swap_setup();
1402         for_each_pgdat(pgdat)
1403                 pgdat->kswapd
1404                 = find_task_by_real_pid(kernel_thread(kswapd, pgdat, CLONE_KERNEL));
1405         total_memory = nr_free_pagecache_pages();
1406         hotcpu_notifier(cpu_callback, 0);
1407         return 0;
1408 }
1409
1410 module_init(kswapd_init)