mm: vmscan: Fix up build warning
[firefly-linux-kernel-4.4.55.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/gfp.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/vmpressure.h>
23 #include <linux/vmstat.h>
24 #include <linux/file.h>
25 #include <linux/writeback.h>
26 #include <linux/blkdev.h>
27 #include <linux/buffer_head.h>  /* for try_to_release_page(),
28                                         buffer_heads_over_limit */
29 #include <linux/mm_inline.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/cpuset.h>
35 #include <linux/compaction.h>
36 #include <linux/notifier.h>
37 #include <linux/rwsem.h>
38 #include <linux/delay.h>
39 #include <linux/kthread.h>
40 #include <linux/freezer.h>
41 #include <linux/memcontrol.h>
42 #include <linux/delayacct.h>
43 #include <linux/sysctl.h>
44 #include <linux/oom.h>
45 #include <linux/prefetch.h>
46 #include <linux/debugfs.h>
47
48 #include <asm/tlbflush.h>
49 #include <asm/div64.h>
50
51 #include <linux/swapops.h>
52
53 #include "internal.h"
54
55 #define CREATE_TRACE_POINTS
56 #include <trace/events/vmscan.h>
57
58 struct scan_control {
59         /* Incremented by the number of inactive pages that were scanned */
60         unsigned long nr_scanned;
61
62         /* Number of pages freed so far during a call to shrink_zones() */
63         unsigned long nr_reclaimed;
64
65         /* How many pages shrink_list() should reclaim */
66         unsigned long nr_to_reclaim;
67
68         unsigned long hibernation_mode;
69
70         /* This context's GFP mask */
71         gfp_t gfp_mask;
72
73         int may_writepage;
74
75         /* Can mapped pages be reclaimed? */
76         int may_unmap;
77
78         /* Can pages be swapped as part of reclaim? */
79         int may_swap;
80
81         int order;
82
83         /* Scan (total_size >> priority) pages at once */
84         int priority;
85
86         /*
87          * The memory cgroup that hit its limit and as a result is the
88          * primary target of this reclaim invocation.
89          */
90         struct mem_cgroup *target_mem_cgroup;
91
92         /*
93          * Nodemask of nodes allowed by the caller. If NULL, all nodes
94          * are scanned.
95          */
96         nodemask_t      *nodemask;
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 unsigned long vm_total_pages;   /* The total number of pages which the VM controls */
134
135 static LIST_HEAD(shrinker_list);
136 static DECLARE_RWSEM(shrinker_rwsem);
137
138 #ifdef CONFIG_MEMCG
139 static bool global_reclaim(struct scan_control *sc)
140 {
141         return !sc->target_mem_cgroup;
142 }
143 #else
144 static bool global_reclaim(struct scan_control *sc)
145 {
146         return true;
147 }
148 #endif
149
150 static unsigned long get_lru_size(struct lruvec *lruvec, enum lru_list lru)
151 {
152         if (!mem_cgroup_disabled())
153                 return mem_cgroup_get_lru_size(lruvec, lru);
154
155         return zone_page_state(lruvec_zone(lruvec), NR_LRU_BASE + lru);
156 }
157
158 struct dentry *debug_file;
159
160 static int debug_shrinker_show(struct seq_file *s, void *unused)
161 {
162         struct shrinker *shrinker;
163         struct shrink_control sc;
164
165         sc.gfp_mask = -1;
166         sc.nr_to_scan = 0;
167
168         down_read(&shrinker_rwsem);
169         list_for_each_entry(shrinker, &shrinker_list, list) {
170                 int num_objs;
171
172                 num_objs = shrinker->shrink(shrinker, &sc);
173                 seq_printf(s, "%pf %d\n", shrinker->shrink, num_objs);
174         }
175         up_read(&shrinker_rwsem);
176         return 0;
177 }
178
179 static int debug_shrinker_open(struct inode *inode, struct file *file)
180 {
181         return single_open(file, debug_shrinker_show, inode->i_private);
182 }
183
184 static const struct file_operations debug_shrinker_fops = {
185         .open = debug_shrinker_open,
186         .read = seq_read,
187         .llseek = seq_lseek,
188         .release = single_release,
189 };
190
191 /*
192  * Add a shrinker callback to be called from the vm
193  */
194 void register_shrinker(struct shrinker *shrinker)
195 {
196         atomic_long_set(&shrinker->nr_in_batch, 0);
197         down_write(&shrinker_rwsem);
198         list_add_tail(&shrinker->list, &shrinker_list);
199         up_write(&shrinker_rwsem);
200 }
201 EXPORT_SYMBOL(register_shrinker);
202
203 static int __init add_shrinker_debug(void)
204 {
205         debugfs_create_file("shrinker", 0644, NULL, NULL,
206                             &debug_shrinker_fops);
207         return 0;
208 }
209
210 late_initcall(add_shrinker_debug);
211
212 /*
213  * Remove one
214  */
215 void unregister_shrinker(struct shrinker *shrinker)
216 {
217         down_write(&shrinker_rwsem);
218         list_del(&shrinker->list);
219         up_write(&shrinker_rwsem);
220 }
221 EXPORT_SYMBOL(unregister_shrinker);
222
223 static inline int do_shrinker_shrink(struct shrinker *shrinker,
224                                      struct shrink_control *sc,
225                                      unsigned long nr_to_scan)
226 {
227         sc->nr_to_scan = nr_to_scan;
228         return (*shrinker->shrink)(shrinker, sc);
229 }
230
231 #define SHRINK_BATCH 128
232 /*
233  * Call the shrink functions to age shrinkable caches
234  *
235  * Here we assume it costs one seek to replace a lru page and that it also
236  * takes a seek to recreate a cache object.  With this in mind we age equal
237  * percentages of the lru and ageable caches.  This should balance the seeks
238  * generated by these structures.
239  *
240  * If the vm encountered mapped pages on the LRU it increase the pressure on
241  * slab to avoid swapping.
242  *
243  * We do weird things to avoid (scanned*seeks*entries) overflowing 32 bits.
244  *
245  * `lru_pages' represents the number of on-LRU pages in all the zones which
246  * are eligible for the caller's allocation attempt.  It is used for balancing
247  * slab reclaim versus page reclaim.
248  *
249  * Returns the number of slab objects which we shrunk.
250  */
251 unsigned long shrink_slab(struct shrink_control *shrink,
252                           unsigned long nr_pages_scanned,
253                           unsigned long lru_pages)
254 {
255         struct shrinker *shrinker;
256         unsigned long ret = 0;
257
258         if (nr_pages_scanned == 0)
259                 nr_pages_scanned = SWAP_CLUSTER_MAX;
260
261         if (!down_read_trylock(&shrinker_rwsem)) {
262                 /* Assume we'll be able to shrink next time */
263                 ret = 1;
264                 goto out;
265         }
266
267         list_for_each_entry(shrinker, &shrinker_list, list) {
268                 unsigned long long delta;
269                 long total_scan;
270                 long max_pass;
271                 int shrink_ret = 0;
272                 long nr;
273                 long new_nr;
274                 long batch_size = shrinker->batch ? shrinker->batch
275                                                   : SHRINK_BATCH;
276
277                 max_pass = do_shrinker_shrink(shrinker, shrink, 0);
278                 if (max_pass <= 0)
279                         continue;
280
281                 /*
282                  * copy the current shrinker scan count into a local variable
283                  * and zero it so that other concurrent shrinker invocations
284                  * don't also do this scanning work.
285                  */
286                 nr = atomic_long_xchg(&shrinker->nr_in_batch, 0);
287
288                 total_scan = nr;
289                 delta = (4 * nr_pages_scanned) / shrinker->seeks;
290                 delta *= max_pass;
291                 do_div(delta, lru_pages + 1);
292                 total_scan += delta;
293                 if (total_scan < 0) {
294                         printk(KERN_ERR "shrink_slab: %pF negative objects to "
295                                "delete nr=%ld\n",
296                                shrinker->shrink, total_scan);
297                         total_scan = max_pass;
298                 }
299
300                 /*
301                  * We need to avoid excessive windup on filesystem shrinkers
302                  * due to large numbers of GFP_NOFS allocations causing the
303                  * shrinkers to return -1 all the time. This results in a large
304                  * nr being built up so when a shrink that can do some work
305                  * comes along it empties the entire cache due to nr >>>
306                  * max_pass.  This is bad for sustaining a working set in
307                  * memory.
308                  *
309                  * Hence only allow the shrinker to scan the entire cache when
310                  * a large delta change is calculated directly.
311                  */
312                 if (delta < max_pass / 4)
313                         total_scan = min(total_scan, max_pass / 2);
314
315                 /*
316                  * Avoid risking looping forever due to too large nr value:
317                  * never try to free more than twice the estimate number of
318                  * freeable entries.
319                  */
320                 if (total_scan > max_pass * 2)
321                         total_scan = max_pass * 2;
322
323                 trace_mm_shrink_slab_start(shrinker, shrink, nr,
324                                         nr_pages_scanned, lru_pages,
325                                         max_pass, delta, total_scan);
326
327                 while (total_scan >= batch_size) {
328                         int nr_before;
329
330                         nr_before = do_shrinker_shrink(shrinker, shrink, 0);
331                         shrink_ret = do_shrinker_shrink(shrinker, shrink,
332                                                         batch_size);
333                         if (shrink_ret == -1)
334                                 break;
335                         if (shrink_ret < nr_before)
336                                 ret += nr_before - shrink_ret;
337                         count_vm_events(SLABS_SCANNED, batch_size);
338                         total_scan -= batch_size;
339
340                         cond_resched();
341                 }
342
343                 /*
344                  * move the unused scan count back into the shrinker in a
345                  * manner that handles concurrent updates. If we exhausted the
346                  * scan, there is no need to do an update.
347                  */
348                 if (total_scan > 0)
349                         new_nr = atomic_long_add_return(total_scan,
350                                         &shrinker->nr_in_batch);
351                 else
352                         new_nr = atomic_long_read(&shrinker->nr_in_batch);
353
354                 trace_mm_shrink_slab_end(shrinker, shrink_ret, nr, new_nr);
355         }
356         up_read(&shrinker_rwsem);
357 out:
358         cond_resched();
359         return ret;
360 }
361
362 static inline int is_page_cache_freeable(struct page *page)
363 {
364         /*
365          * A freeable page cache page is referenced only by the caller
366          * that isolated the page, the page cache radix tree and
367          * optional buffer heads at page->private.
368          */
369         return page_count(page) - page_has_private(page) == 2;
370 }
371
372 static int may_write_to_queue(struct backing_dev_info *bdi,
373                               struct scan_control *sc)
374 {
375         if (current->flags & PF_SWAPWRITE)
376                 return 1;
377         if (!bdi_write_congested(bdi))
378                 return 1;
379         if (bdi == current->backing_dev_info)
380                 return 1;
381         return 0;
382 }
383
384 /*
385  * We detected a synchronous write error writing a page out.  Probably
386  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
387  * fsync(), msync() or close().
388  *
389  * The tricky part is that after writepage we cannot touch the mapping: nothing
390  * prevents it from being freed up.  But we have a ref on the page and once
391  * that page is locked, the mapping is pinned.
392  *
393  * We're allowed to run sleeping lock_page() here because we know the caller has
394  * __GFP_FS.
395  */
396 static void handle_write_error(struct address_space *mapping,
397                                 struct page *page, int error)
398 {
399         lock_page(page);
400         if (page_mapping(page) == mapping)
401                 mapping_set_error(mapping, error);
402         unlock_page(page);
403 }
404
405 /* possible outcome of pageout() */
406 typedef enum {
407         /* failed to write page out, page is locked */
408         PAGE_KEEP,
409         /* move page to the active list, page is locked */
410         PAGE_ACTIVATE,
411         /* page has been sent to the disk successfully, page is unlocked */
412         PAGE_SUCCESS,
413         /* page is clean and locked */
414         PAGE_CLEAN,
415 } pageout_t;
416
417 /*
418  * pageout is called by shrink_page_list() for each dirty page.
419  * Calls ->writepage().
420  */
421 static pageout_t pageout(struct page *page, struct address_space *mapping,
422                          struct scan_control *sc)
423 {
424         /*
425          * If the page is dirty, only perform writeback if that write
426          * will be non-blocking.  To prevent this allocation from being
427          * stalled by pagecache activity.  But note that there may be
428          * stalls if we need to run get_block().  We could test
429          * PagePrivate for that.
430          *
431          * If this process is currently in __generic_file_aio_write() against
432          * this page's queue, we can perform writeback even if that
433          * will block.
434          *
435          * If the page is swapcache, write it back even if that would
436          * block, for some throttling. This happens by accident, because
437          * swap_backing_dev_info is bust: it doesn't reflect the
438          * congestion state of the swapdevs.  Easy to fix, if needed.
439          */
440         if (!is_page_cache_freeable(page))
441                 return PAGE_KEEP;
442         if (!mapping) {
443                 /*
444                  * Some data journaling orphaned pages can have
445                  * page->mapping == NULL while being dirty with clean buffers.
446                  */
447                 if (page_has_private(page)) {
448                         if (try_to_free_buffers(page)) {
449                                 ClearPageDirty(page);
450                                 printk("%s: orphaned page\n", __func__);
451                                 return PAGE_CLEAN;
452                         }
453                 }
454                 return PAGE_KEEP;
455         }
456         if (mapping->a_ops->writepage == NULL)
457                 return PAGE_ACTIVATE;
458         if (!may_write_to_queue(mapping->backing_dev_info, sc))
459                 return PAGE_KEEP;
460
461         if (clear_page_dirty_for_io(page)) {
462                 int res;
463                 struct writeback_control wbc = {
464                         .sync_mode = WB_SYNC_NONE,
465                         .nr_to_write = SWAP_CLUSTER_MAX,
466                         .range_start = 0,
467                         .range_end = LLONG_MAX,
468                         .for_reclaim = 1,
469                 };
470
471                 SetPageReclaim(page);
472                 res = mapping->a_ops->writepage(page, &wbc);
473                 if (res < 0)
474                         handle_write_error(mapping, page, res);
475                 if (res == AOP_WRITEPAGE_ACTIVATE) {
476                         ClearPageReclaim(page);
477                         return PAGE_ACTIVATE;
478                 }
479
480                 if (!PageWriteback(page)) {
481                         /* synchronous write or broken a_ops? */
482                         ClearPageReclaim(page);
483                 }
484                 trace_mm_vmscan_writepage(page, trace_reclaim_flags(page));
485                 inc_zone_page_state(page, NR_VMSCAN_WRITE);
486                 return PAGE_SUCCESS;
487         }
488
489         return PAGE_CLEAN;
490 }
491
492 /*
493  * Same as remove_mapping, but if the page is removed from the mapping, it
494  * gets returned with a refcount of 0.
495  */
496 static int __remove_mapping(struct address_space *mapping, struct page *page)
497 {
498         BUG_ON(!PageLocked(page));
499         BUG_ON(mapping != page_mapping(page));
500
501         spin_lock_irq(&mapping->tree_lock);
502         /*
503          * The non racy check for a busy page.
504          *
505          * Must be careful with the order of the tests. When someone has
506          * a ref to the page, it may be possible that they dirty it then
507          * drop the reference. So if PageDirty is tested before page_count
508          * here, then the following race may occur:
509          *
510          * get_user_pages(&page);
511          * [user mapping goes away]
512          * write_to(page);
513          *                              !PageDirty(page)    [good]
514          * SetPageDirty(page);
515          * put_page(page);
516          *                              !page_count(page)   [good, discard it]
517          *
518          * [oops, our write_to data is lost]
519          *
520          * Reversing the order of the tests ensures such a situation cannot
521          * escape unnoticed. The smp_rmb is needed to ensure the page->flags
522          * load is not satisfied before that of page->_count.
523          *
524          * Note that if SetPageDirty is always performed via set_page_dirty,
525          * and thus under tree_lock, then this ordering is not required.
526          */
527         if (!page_freeze_refs(page, 2))
528                 goto cannot_free;
529         /* note: atomic_cmpxchg in page_freeze_refs provides the smp_rmb */
530         if (unlikely(PageDirty(page))) {
531                 page_unfreeze_refs(page, 2);
532                 goto cannot_free;
533         }
534
535         if (PageSwapCache(page)) {
536                 swp_entry_t swap = { .val = page_private(page) };
537                 __delete_from_swap_cache(page);
538                 spin_unlock_irq(&mapping->tree_lock);
539                 swapcache_free(swap, page);
540         } else {
541                 void (*freepage)(struct page *);
542
543                 freepage = mapping->a_ops->freepage;
544
545                 __delete_from_page_cache(page);
546                 spin_unlock_irq(&mapping->tree_lock);
547                 mem_cgroup_uncharge_cache_page(page);
548
549                 if (freepage != NULL)
550                         freepage(page);
551         }
552
553         return 1;
554
555 cannot_free:
556         spin_unlock_irq(&mapping->tree_lock);
557         return 0;
558 }
559
560 /*
561  * Attempt to detach a locked page from its ->mapping.  If it is dirty or if
562  * someone else has a ref on the page, abort and return 0.  If it was
563  * successfully detached, return 1.  Assumes the caller has a single ref on
564  * this page.
565  */
566 int remove_mapping(struct address_space *mapping, struct page *page)
567 {
568         if (__remove_mapping(mapping, page)) {
569                 /*
570                  * Unfreezing the refcount with 1 rather than 2 effectively
571                  * drops the pagecache ref for us without requiring another
572                  * atomic operation.
573                  */
574                 page_unfreeze_refs(page, 1);
575                 return 1;
576         }
577         return 0;
578 }
579
580 /**
581  * putback_lru_page - put previously isolated page onto appropriate LRU list
582  * @page: page to be put back to appropriate lru list
583  *
584  * Add previously isolated @page to appropriate LRU list.
585  * Page may still be unevictable for other reasons.
586  *
587  * lru_lock must not be held, interrupts must be enabled.
588  */
589 void putback_lru_page(struct page *page)
590 {
591         int lru;
592         int active = !!TestClearPageActive(page);
593         int was_unevictable = PageUnevictable(page);
594
595         VM_BUG_ON(PageLRU(page));
596
597 redo:
598         ClearPageUnevictable(page);
599
600         if (page_evictable(page)) {
601                 /*
602                  * For evictable pages, we can use the cache.
603                  * In event of a race, worst case is we end up with an
604                  * unevictable page on [in]active list.
605                  * We know how to handle that.
606                  */
607                 lru = active + page_lru_base_type(page);
608                 lru_cache_add_lru(page, lru);
609         } else {
610                 /*
611                  * Put unevictable pages directly on zone's unevictable
612                  * list.
613                  */
614                 lru = LRU_UNEVICTABLE;
615                 add_page_to_unevictable_list(page);
616                 /*
617                  * When racing with an mlock or AS_UNEVICTABLE clearing
618                  * (page is unlocked) make sure that if the other thread
619                  * does not observe our setting of PG_lru and fails
620                  * isolation/check_move_unevictable_pages,
621                  * we see PG_mlocked/AS_UNEVICTABLE cleared below and move
622                  * the page back to the evictable list.
623                  *
624                  * The other side is TestClearPageMlocked() or shmem_lock().
625                  */
626                 smp_mb();
627         }
628
629         /*
630          * page's status can change while we move it among lru. If an evictable
631          * page is on unevictable list, it never be freed. To avoid that,
632          * check after we added it to the list, again.
633          */
634         if (lru == LRU_UNEVICTABLE && page_evictable(page)) {
635                 if (!isolate_lru_page(page)) {
636                         put_page(page);
637                         goto redo;
638                 }
639                 /* This means someone else dropped this page from LRU
640                  * So, it will be freed or putback to LRU again. There is
641                  * nothing to do here.
642                  */
643         }
644
645         if (was_unevictable && lru != LRU_UNEVICTABLE)
646                 count_vm_event(UNEVICTABLE_PGRESCUED);
647         else if (!was_unevictable && lru == LRU_UNEVICTABLE)
648                 count_vm_event(UNEVICTABLE_PGCULLED);
649
650         put_page(page);         /* drop ref from isolate */
651 }
652
653 enum page_references {
654         PAGEREF_RECLAIM,
655         PAGEREF_RECLAIM_CLEAN,
656         PAGEREF_KEEP,
657         PAGEREF_ACTIVATE,
658 };
659
660 static enum page_references page_check_references(struct page *page,
661                                                   struct scan_control *sc)
662 {
663         int referenced_ptes, referenced_page;
664         unsigned long vm_flags;
665
666         referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
667                                           &vm_flags);
668         referenced_page = TestClearPageReferenced(page);
669
670         /*
671          * Mlock lost the isolation race with us.  Let try_to_unmap()
672          * move the page to the unevictable list.
673          */
674         if (vm_flags & VM_LOCKED)
675                 return PAGEREF_RECLAIM;
676
677         if (referenced_ptes) {
678                 if (PageSwapBacked(page))
679                         return PAGEREF_ACTIVATE;
680                 /*
681                  * All mapped pages start out with page table
682                  * references from the instantiating fault, so we need
683                  * to look twice if a mapped file page is used more
684                  * than once.
685                  *
686                  * Mark it and spare it for another trip around the
687                  * inactive list.  Another page table reference will
688                  * lead to its activation.
689                  *
690                  * Note: the mark is set for activated pages as well
691                  * so that recently deactivated but used pages are
692                  * quickly recovered.
693                  */
694                 SetPageReferenced(page);
695
696                 if (referenced_page || referenced_ptes > 1)
697                         return PAGEREF_ACTIVATE;
698
699                 /*
700                  * Activate file-backed executable pages after first usage.
701                  */
702                 if (vm_flags & VM_EXEC)
703                         return PAGEREF_ACTIVATE;
704
705                 return PAGEREF_KEEP;
706         }
707
708         /* Reclaim if clean, defer dirty pages to writeback */
709         if (referenced_page && !PageSwapBacked(page))
710                 return PAGEREF_RECLAIM_CLEAN;
711
712         return PAGEREF_RECLAIM;
713 }
714
715 /*
716  * shrink_page_list() returns the number of reclaimed pages
717  */
718 static unsigned long shrink_page_list(struct list_head *page_list,
719                                       struct zone *zone,
720                                       struct scan_control *sc,
721                                       enum ttu_flags ttu_flags,
722                                       unsigned long *ret_nr_dirty,
723                                       unsigned long *ret_nr_writeback,
724                                       bool force_reclaim)
725 {
726         LIST_HEAD(ret_pages);
727         LIST_HEAD(free_pages);
728         int pgactivate = 0;
729         unsigned long nr_dirty = 0;
730         unsigned long nr_congested = 0;
731         unsigned long nr_reclaimed = 0;
732         unsigned long nr_writeback = 0;
733
734         cond_resched();
735
736         mem_cgroup_uncharge_start();
737         while (!list_empty(page_list)) {
738                 struct address_space *mapping;
739                 struct page *page;
740                 int may_enter_fs;
741                 enum page_references references = PAGEREF_RECLAIM_CLEAN;
742
743                 cond_resched();
744
745                 page = lru_to_page(page_list);
746                 list_del(&page->lru);
747
748                 if (!trylock_page(page))
749                         goto keep;
750
751                 VM_BUG_ON(PageActive(page));
752                 VM_BUG_ON(page_zone(page) != zone);
753
754                 sc->nr_scanned++;
755
756                 if (unlikely(!page_evictable(page)))
757                         goto cull_mlocked;
758
759                 if (!sc->may_unmap && page_mapped(page))
760                         goto keep_locked;
761
762                 /* Double the slab pressure for mapped and swapcache pages */
763                 if (page_mapped(page) || PageSwapCache(page))
764                         sc->nr_scanned++;
765
766                 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
767                         (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
768
769                 if (PageWriteback(page)) {
770                         /*
771                          * memcg doesn't have any dirty pages throttling so we
772                          * could easily OOM just because too many pages are in
773                          * writeback and there is nothing else to reclaim.
774                          *
775                          * Check __GFP_IO, certainly because a loop driver
776                          * thread might enter reclaim, and deadlock if it waits
777                          * on a page for which it is needed to do the write
778                          * (loop masks off __GFP_IO|__GFP_FS for this reason);
779                          * but more thought would probably show more reasons.
780                          *
781                          * Don't require __GFP_FS, since we're not going into
782                          * the FS, just waiting on its writeback completion.
783                          * Worryingly, ext4 gfs2 and xfs allocate pages with
784                          * grab_cache_page_write_begin(,,AOP_FLAG_NOFS), so
785                          * testing may_enter_fs here is liable to OOM on them.
786                          */
787                         if (global_reclaim(sc) ||
788                             !PageReclaim(page) || !(sc->gfp_mask & __GFP_IO)) {
789                                 /*
790                                  * This is slightly racy - end_page_writeback()
791                                  * might have just cleared PageReclaim, then
792                                  * setting PageReclaim here end up interpreted
793                                  * as PageReadahead - but that does not matter
794                                  * enough to care.  What we do want is for this
795                                  * page to have PageReclaim set next time memcg
796                                  * reclaim reaches the tests above, so it will
797                                  * then wait_on_page_writeback() to avoid OOM;
798                                  * and it's also appropriate in global reclaim.
799                                  */
800                                 SetPageReclaim(page);
801                                 nr_writeback++;
802                                 goto keep_locked;
803                         }
804                         wait_on_page_writeback(page);
805                 }
806
807                 if (!force_reclaim)
808                         references = page_check_references(page, sc);
809
810                 switch (references) {
811                 case PAGEREF_ACTIVATE:
812                         goto activate_locked;
813                 case PAGEREF_KEEP:
814                         goto keep_locked;
815                 case PAGEREF_RECLAIM:
816                 case PAGEREF_RECLAIM_CLEAN:
817                         ; /* try to reclaim the page below */
818                 }
819
820                 /*
821                  * Anonymous process memory has backing store?
822                  * Try to allocate it some swap space here.
823                  */
824                 if (PageAnon(page) && !PageSwapCache(page)) {
825                         if (!(sc->gfp_mask & __GFP_IO))
826                                 goto keep_locked;
827                         if (!add_to_swap(page, page_list))
828                                 goto activate_locked;
829                         may_enter_fs = 1;
830                 }
831
832                 mapping = page_mapping(page);
833
834                 /*
835                  * The page is mapped into the page tables of one or more
836                  * processes. Try to unmap it here.
837                  */
838                 if (page_mapped(page) && mapping) {
839                         switch (try_to_unmap(page, ttu_flags)) {
840                         case SWAP_FAIL:
841                                 goto activate_locked;
842                         case SWAP_AGAIN:
843                                 goto keep_locked;
844                         case SWAP_MLOCK:
845                                 goto cull_mlocked;
846                         case SWAP_SUCCESS:
847                                 ; /* try to free the page below */
848                         }
849                 }
850
851                 if (PageDirty(page)) {
852                         nr_dirty++;
853
854                         /*
855                          * Only kswapd can writeback filesystem pages to
856                          * avoid risk of stack overflow but do not writeback
857                          * unless under significant pressure.
858                          */
859                         if (page_is_file_cache(page) &&
860                                         (!current_is_kswapd() ||
861                                          sc->priority >= DEF_PRIORITY - 2)) {
862                                 /*
863                                  * Immediately reclaim when written back.
864                                  * Similar in principal to deactivate_page()
865                                  * except we already have the page isolated
866                                  * and know it's dirty
867                                  */
868                                 inc_zone_page_state(page, NR_VMSCAN_IMMEDIATE);
869                                 SetPageReclaim(page);
870
871                                 goto keep_locked;
872                         }
873
874                         if (references == PAGEREF_RECLAIM_CLEAN)
875                                 goto keep_locked;
876                         if (!may_enter_fs)
877                                 goto keep_locked;
878                         if (!sc->may_writepage)
879                                 goto keep_locked;
880
881                         /* Page is dirty, try to write it out here */
882                         switch (pageout(page, mapping, sc)) {
883                         case PAGE_KEEP:
884                                 nr_congested++;
885                                 goto keep_locked;
886                         case PAGE_ACTIVATE:
887                                 goto activate_locked;
888                         case PAGE_SUCCESS:
889                                 if (PageWriteback(page))
890                                         goto keep;
891                                 if (PageDirty(page))
892                                         goto keep;
893
894                                 /*
895                                  * A synchronous write - probably a ramdisk.  Go
896                                  * ahead and try to reclaim the page.
897                                  */
898                                 if (!trylock_page(page))
899                                         goto keep;
900                                 if (PageDirty(page) || PageWriteback(page))
901                                         goto keep_locked;
902                                 mapping = page_mapping(page);
903                         case PAGE_CLEAN:
904                                 ; /* try to free the page below */
905                         }
906                 }
907
908                 /*
909                  * If the page has buffers, try to free the buffer mappings
910                  * associated with this page. If we succeed we try to free
911                  * the page as well.
912                  *
913                  * We do this even if the page is PageDirty().
914                  * try_to_release_page() does not perform I/O, but it is
915                  * possible for a page to have PageDirty set, but it is actually
916                  * clean (all its buffers are clean).  This happens if the
917                  * buffers were written out directly, with submit_bh(). ext3
918                  * will do this, as well as the blockdev mapping.
919                  * try_to_release_page() will discover that cleanness and will
920                  * drop the buffers and mark the page clean - it can be freed.
921                  *
922                  * Rarely, pages can have buffers and no ->mapping.  These are
923                  * the pages which were not successfully invalidated in
924                  * truncate_complete_page().  We try to drop those buffers here
925                  * and if that worked, and the page is no longer mapped into
926                  * process address space (page_count == 1) it can be freed.
927                  * Otherwise, leave the page on the LRU so it is swappable.
928                  */
929                 if (page_has_private(page)) {
930                         if (!try_to_release_page(page, sc->gfp_mask))
931                                 goto activate_locked;
932                         if (!mapping && page_count(page) == 1) {
933                                 unlock_page(page);
934                                 if (put_page_testzero(page))
935                                         goto free_it;
936                                 else {
937                                         /*
938                                          * rare race with speculative reference.
939                                          * the speculative reference will free
940                                          * this page shortly, so we may
941                                          * increment nr_reclaimed here (and
942                                          * leave it off the LRU).
943                                          */
944                                         nr_reclaimed++;
945                                         continue;
946                                 }
947                         }
948                 }
949
950                 if (!mapping || !__remove_mapping(mapping, page))
951                         goto keep_locked;
952
953                 /*
954                  * At this point, we have no other references and there is
955                  * no way to pick any more up (removed from LRU, removed
956                  * from pagecache). Can use non-atomic bitops now (and
957                  * we obviously don't have to worry about waking up a process
958                  * waiting on the page lock, because there are no references.
959                  */
960                 __clear_page_locked(page);
961 free_it:
962                 nr_reclaimed++;
963
964                 /*
965                  * Is there need to periodically free_page_list? It would
966                  * appear not as the counts should be low
967                  */
968                 list_add(&page->lru, &free_pages);
969                 continue;
970
971 cull_mlocked:
972                 if (PageSwapCache(page))
973                         try_to_free_swap(page);
974                 unlock_page(page);
975                 putback_lru_page(page);
976                 continue;
977
978 activate_locked:
979                 /* Not a candidate for swapping, so reclaim swap space. */
980                 if (PageSwapCache(page) && vm_swap_full())
981                         try_to_free_swap(page);
982                 VM_BUG_ON(PageActive(page));
983                 SetPageActive(page);
984                 pgactivate++;
985 keep_locked:
986                 unlock_page(page);
987 keep:
988                 list_add(&page->lru, &ret_pages);
989                 VM_BUG_ON(PageLRU(page) || PageUnevictable(page));
990         }
991
992         /*
993          * Tag a zone as congested if all the dirty pages encountered were
994          * backed by a congested BDI. In this case, reclaimers should just
995          * back off and wait for congestion to clear because further reclaim
996          * will encounter the same problem
997          */
998         if (nr_dirty && nr_dirty == nr_congested && global_reclaim(sc))
999                 zone_set_flag(zone, ZONE_CONGESTED);
1000
1001         free_hot_cold_page_list(&free_pages, 1);
1002
1003         list_splice(&ret_pages, page_list);
1004         count_vm_events(PGACTIVATE, pgactivate);
1005         mem_cgroup_uncharge_end();
1006         *ret_nr_dirty += nr_dirty;
1007         *ret_nr_writeback += nr_writeback;
1008         return nr_reclaimed;
1009 }
1010
1011 unsigned long reclaim_clean_pages_from_list(struct zone *zone,
1012                                             struct list_head *page_list)
1013 {
1014         struct scan_control sc = {
1015                 .gfp_mask = GFP_KERNEL,
1016                 .priority = DEF_PRIORITY,
1017                 .may_unmap = 1,
1018         };
1019         unsigned long ret, dummy1, dummy2;
1020         struct page *page, *next;
1021         LIST_HEAD(clean_pages);
1022
1023         list_for_each_entry_safe(page, next, page_list, lru) {
1024                 if (page_is_file_cache(page) && !PageDirty(page)) {
1025                         ClearPageActive(page);
1026                         list_move(&page->lru, &clean_pages);
1027                 }
1028         }
1029
1030         ret = shrink_page_list(&clean_pages, zone, &sc,
1031                                 TTU_UNMAP|TTU_IGNORE_ACCESS,
1032                                 &dummy1, &dummy2, true);
1033         list_splice(&clean_pages, page_list);
1034         __mod_zone_page_state(zone, NR_ISOLATED_FILE, -ret);
1035         return ret;
1036 }
1037
1038 /*
1039  * Attempt to remove the specified page from its LRU.  Only take this page
1040  * if it is of the appropriate PageActive status.  Pages which are being
1041  * freed elsewhere are also ignored.
1042  *
1043  * page:        page to consider
1044  * mode:        one of the LRU isolation modes defined above
1045  *
1046  * returns 0 on success, -ve errno on failure.
1047  */
1048 int __isolate_lru_page(struct page *page, isolate_mode_t mode)
1049 {
1050         int ret = -EINVAL;
1051
1052         /* Only take pages on the LRU. */
1053         if (!PageLRU(page))
1054                 return ret;
1055
1056         /* Compaction should not handle unevictable pages but CMA can do so */
1057         if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
1058                 return ret;
1059
1060         ret = -EBUSY;
1061
1062         /*
1063          * To minimise LRU disruption, the caller can indicate that it only
1064          * wants to isolate pages it will be able to operate on without
1065          * blocking - clean pages for the most part.
1066          *
1067          * ISOLATE_CLEAN means that only clean pages should be isolated. This
1068          * is used by reclaim when it is cannot write to backing storage
1069          *
1070          * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1071          * that it is possible to migrate without blocking
1072          */
1073         if (mode & (ISOLATE_CLEAN|ISOLATE_ASYNC_MIGRATE)) {
1074                 /* All the caller can do on PageWriteback is block */
1075                 if (PageWriteback(page))
1076                         return ret;
1077
1078                 if (PageDirty(page)) {
1079                         struct address_space *mapping;
1080
1081                         /* ISOLATE_CLEAN means only clean pages */
1082                         if (mode & ISOLATE_CLEAN)
1083                                 return ret;
1084
1085                         /*
1086                          * Only pages without mappings or that have a
1087                          * ->migratepage callback are possible to migrate
1088                          * without blocking
1089                          */
1090                         mapping = page_mapping(page);
1091                         if (mapping && !mapping->a_ops->migratepage)
1092                                 return ret;
1093                 }
1094         }
1095
1096         if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
1097                 return ret;
1098
1099         if (likely(get_page_unless_zero(page))) {
1100                 /*
1101                  * Be careful not to clear PageLRU until after we're
1102                  * sure the page is not being freed elsewhere -- the
1103                  * page release code relies on it.
1104                  */
1105                 ClearPageLRU(page);
1106                 ret = 0;
1107         }
1108
1109         return ret;
1110 }
1111
1112 /*
1113  * zone->lru_lock is heavily contended.  Some of the functions that
1114  * shrink the lists perform better by taking out a batch of pages
1115  * and working on them outside the LRU lock.
1116  *
1117  * For pagecache intensive workloads, this function is the hottest
1118  * spot in the kernel (apart from copy_*_user functions).
1119  *
1120  * Appropriate locks must be held before calling this function.
1121  *
1122  * @nr_to_scan: The number of pages to look through on the list.
1123  * @lruvec:     The LRU vector to pull pages from.
1124  * @dst:        The temp list to put pages on to.
1125  * @nr_scanned: The number of pages that were scanned.
1126  * @sc:         The scan_control struct for this reclaim session
1127  * @mode:       One of the LRU isolation modes
1128  * @lru:        LRU list id for isolating
1129  *
1130  * returns how many pages were moved onto *@dst.
1131  */
1132 static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
1133                 struct lruvec *lruvec, struct list_head *dst,
1134                 unsigned long *nr_scanned, struct scan_control *sc,
1135                 isolate_mode_t mode, enum lru_list lru)
1136 {
1137         struct list_head *src = &lruvec->lists[lru];
1138         unsigned long nr_taken = 0;
1139         unsigned long scan;
1140
1141         for (scan = 0; scan < nr_to_scan && !list_empty(src); scan++) {
1142                 struct page *page;
1143                 int nr_pages;
1144
1145                 page = lru_to_page(src);
1146                 prefetchw_prev_lru_page(page, src, flags);
1147
1148                 VM_BUG_ON(!PageLRU(page));
1149
1150                 switch (__isolate_lru_page(page, mode)) {
1151                 case 0:
1152                         nr_pages = hpage_nr_pages(page);
1153                         mem_cgroup_update_lru_size(lruvec, lru, -nr_pages);
1154                         list_move(&page->lru, dst);
1155                         nr_taken += nr_pages;
1156                         break;
1157
1158                 case -EBUSY:
1159                         /* else it is being freed elsewhere */
1160                         list_move(&page->lru, src);
1161                         continue;
1162
1163                 default:
1164                         BUG();
1165                 }
1166         }
1167
1168         *nr_scanned = scan;
1169         trace_mm_vmscan_lru_isolate(sc->order, nr_to_scan, scan,
1170                                     nr_taken, mode, is_file_lru(lru));
1171         return nr_taken;
1172 }
1173
1174 /**
1175  * isolate_lru_page - tries to isolate a page from its LRU list
1176  * @page: page to isolate from its LRU list
1177  *
1178  * Isolates a @page from an LRU list, clears PageLRU and adjusts the
1179  * vmstat statistic corresponding to whatever LRU list the page was on.
1180  *
1181  * Returns 0 if the page was removed from an LRU list.
1182  * Returns -EBUSY if the page was not on an LRU list.
1183  *
1184  * The returned page will have PageLRU() cleared.  If it was found on
1185  * the active list, it will have PageActive set.  If it was found on
1186  * the unevictable list, it will have the PageUnevictable bit set. That flag
1187  * may need to be cleared by the caller before letting the page go.
1188  *
1189  * The vmstat statistic corresponding to the list on which the page was
1190  * found will be decremented.
1191  *
1192  * Restrictions:
1193  * (1) Must be called with an elevated refcount on the page. This is a
1194  *     fundamentnal difference from isolate_lru_pages (which is called
1195  *     without a stable reference).
1196  * (2) the lru_lock must not be held.
1197  * (3) interrupts must be enabled.
1198  */
1199 int isolate_lru_page(struct page *page)
1200 {
1201         int ret = -EBUSY;
1202
1203         VM_BUG_ON(!page_count(page));
1204
1205         if (PageLRU(page)) {
1206                 struct zone *zone = page_zone(page);
1207                 struct lruvec *lruvec;
1208
1209                 spin_lock_irq(&zone->lru_lock);
1210                 lruvec = mem_cgroup_page_lruvec(page, zone);
1211                 if (PageLRU(page)) {
1212                         int lru = page_lru(page);
1213                         get_page(page);
1214                         ClearPageLRU(page);
1215                         del_page_from_lru_list(page, lruvec, lru);
1216                         ret = 0;
1217                 }
1218                 spin_unlock_irq(&zone->lru_lock);
1219         }
1220         return ret;
1221 }
1222
1223 /*
1224  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
1225  * then get resheduled. When there are massive number of tasks doing page
1226  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
1227  * the LRU list will go small and be scanned faster than necessary, leading to
1228  * unnecessary swapping, thrashing and OOM.
1229  */
1230 static int too_many_isolated(struct zone *zone, int file,
1231                 struct scan_control *sc)
1232 {
1233         unsigned long inactive, isolated;
1234
1235         if (current_is_kswapd())
1236                 return 0;
1237
1238         if (!global_reclaim(sc))
1239                 return 0;
1240
1241         if (file) {
1242                 inactive = zone_page_state(zone, NR_INACTIVE_FILE);
1243                 isolated = zone_page_state(zone, NR_ISOLATED_FILE);
1244         } else {
1245                 inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1246                 isolated = zone_page_state(zone, NR_ISOLATED_ANON);
1247         }
1248
1249         /*
1250          * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
1251          * won't get blocked by normal direct-reclaimers, forming a circular
1252          * deadlock.
1253          */
1254         if ((sc->gfp_mask & GFP_IOFS) == GFP_IOFS)
1255                 inactive >>= 3;
1256
1257         return isolated > inactive;
1258 }
1259
1260 static noinline_for_stack void
1261 putback_inactive_pages(struct lruvec *lruvec, struct list_head *page_list)
1262 {
1263         struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1264         struct zone *zone = lruvec_zone(lruvec);
1265         LIST_HEAD(pages_to_free);
1266
1267         /*
1268          * Put back any unfreeable pages.
1269          */
1270         while (!list_empty(page_list)) {
1271                 struct page *page = lru_to_page(page_list);
1272                 int lru;
1273
1274                 VM_BUG_ON(PageLRU(page));
1275                 list_del(&page->lru);
1276                 if (unlikely(!page_evictable(page))) {
1277                         spin_unlock_irq(&zone->lru_lock);
1278                         putback_lru_page(page);
1279                         spin_lock_irq(&zone->lru_lock);
1280                         continue;
1281                 }
1282
1283                 lruvec = mem_cgroup_page_lruvec(page, zone);
1284
1285                 SetPageLRU(page);
1286                 lru = page_lru(page);
1287                 add_page_to_lru_list(page, lruvec, lru);
1288
1289                 if (is_active_lru(lru)) {
1290                         int file = is_file_lru(lru);
1291                         int numpages = hpage_nr_pages(page);
1292                         reclaim_stat->recent_rotated[file] += numpages;
1293                 }
1294                 if (put_page_testzero(page)) {
1295                         __ClearPageLRU(page);
1296                         __ClearPageActive(page);
1297                         del_page_from_lru_list(page, lruvec, lru);
1298
1299                         if (unlikely(PageCompound(page))) {
1300                                 spin_unlock_irq(&zone->lru_lock);
1301                                 (*get_compound_page_dtor(page))(page);
1302                                 spin_lock_irq(&zone->lru_lock);
1303                         } else
1304                                 list_add(&page->lru, &pages_to_free);
1305                 }
1306         }
1307
1308         /*
1309          * To save our caller's stack, now use input list for pages to free.
1310          */
1311         list_splice(&pages_to_free, page_list);
1312 }
1313
1314 /*
1315  * shrink_inactive_list() is a helper for shrink_zone().  It returns the number
1316  * of reclaimed pages
1317  */
1318 static noinline_for_stack unsigned long
1319 shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
1320                      struct scan_control *sc, enum lru_list lru)
1321 {
1322         LIST_HEAD(page_list);
1323         unsigned long nr_scanned;
1324         unsigned long nr_reclaimed = 0;
1325         unsigned long nr_taken;
1326         unsigned long nr_dirty = 0;
1327         unsigned long nr_writeback = 0;
1328         isolate_mode_t isolate_mode = 0;
1329         int file = is_file_lru(lru);
1330         struct zone *zone = lruvec_zone(lruvec);
1331         struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1332
1333         while (unlikely(too_many_isolated(zone, file, sc))) {
1334                 congestion_wait(BLK_RW_ASYNC, HZ/10);
1335
1336                 /* We are about to die and free our memory. Return now. */
1337                 if (fatal_signal_pending(current))
1338                         return SWAP_CLUSTER_MAX;
1339         }
1340
1341         lru_add_drain();
1342
1343         if (!sc->may_unmap)
1344                 isolate_mode |= ISOLATE_UNMAPPED;
1345         if (!sc->may_writepage)
1346                 isolate_mode |= ISOLATE_CLEAN;
1347
1348         spin_lock_irq(&zone->lru_lock);
1349
1350         nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
1351                                      &nr_scanned, sc, isolate_mode, lru);
1352
1353         __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1354         __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1355
1356         if (global_reclaim(sc)) {
1357                 zone->pages_scanned += nr_scanned;
1358                 if (current_is_kswapd())
1359                         __count_zone_vm_events(PGSCAN_KSWAPD, zone, nr_scanned);
1360                 else
1361                         __count_zone_vm_events(PGSCAN_DIRECT, zone, nr_scanned);
1362         }
1363         spin_unlock_irq(&zone->lru_lock);
1364
1365         if (nr_taken == 0)
1366                 return 0;
1367
1368         nr_reclaimed = shrink_page_list(&page_list, zone, sc, TTU_UNMAP,
1369                                         &nr_dirty, &nr_writeback, false);
1370
1371         spin_lock_irq(&zone->lru_lock);
1372
1373         reclaim_stat->recent_scanned[file] += nr_taken;
1374
1375         if (global_reclaim(sc)) {
1376                 if (current_is_kswapd())
1377                         __count_zone_vm_events(PGSTEAL_KSWAPD, zone,
1378                                                nr_reclaimed);
1379                 else
1380                         __count_zone_vm_events(PGSTEAL_DIRECT, zone,
1381                                                nr_reclaimed);
1382         }
1383
1384         putback_inactive_pages(lruvec, &page_list);
1385
1386         __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1387
1388         spin_unlock_irq(&zone->lru_lock);
1389
1390         free_hot_cold_page_list(&page_list, 1);
1391
1392         /*
1393          * If reclaim is isolating dirty pages under writeback, it implies
1394          * that the long-lived page allocation rate is exceeding the page
1395          * laundering rate. Either the global limits are not being effective
1396          * at throttling processes due to the page distribution throughout
1397          * zones or there is heavy usage of a slow backing device. The
1398          * only option is to throttle from reclaim context which is not ideal
1399          * as there is no guarantee the dirtying process is throttled in the
1400          * same way balance_dirty_pages() manages.
1401          *
1402          * This scales the number of dirty pages that must be under writeback
1403          * before throttling depending on priority. It is a simple backoff
1404          * function that has the most effect in the range DEF_PRIORITY to
1405          * DEF_PRIORITY-2 which is the priority reclaim is considered to be
1406          * in trouble and reclaim is considered to be in trouble.
1407          *
1408          * DEF_PRIORITY   100% isolated pages must be PageWriteback to throttle
1409          * DEF_PRIORITY-1  50% must be PageWriteback
1410          * DEF_PRIORITY-2  25% must be PageWriteback, kswapd in trouble
1411          * ...
1412          * DEF_PRIORITY-6 For SWAP_CLUSTER_MAX isolated pages, throttle if any
1413          *                     isolated page is PageWriteback
1414          */
1415         if (nr_writeback && nr_writeback >=
1416                         (nr_taken >> (DEF_PRIORITY - sc->priority)))
1417                 wait_iff_congested(zone, BLK_RW_ASYNC, HZ/10);
1418
1419         trace_mm_vmscan_lru_shrink_inactive(zone->zone_pgdat->node_id,
1420                 zone_idx(zone),
1421                 nr_scanned, nr_reclaimed,
1422                 sc->priority,
1423                 trace_shrink_flags(file));
1424         return nr_reclaimed;
1425 }
1426
1427 /*
1428  * This moves pages from the active list to the inactive list.
1429  *
1430  * We move them the other way if the page is referenced by one or more
1431  * processes, from rmap.
1432  *
1433  * If the pages are mostly unmapped, the processing is fast and it is
1434  * appropriate to hold zone->lru_lock across the whole operation.  But if
1435  * the pages are mapped, the processing is slow (page_referenced()) so we
1436  * should drop zone->lru_lock around each page.  It's impossible to balance
1437  * this, so instead we remove the pages from the LRU while processing them.
1438  * It is safe to rely on PG_active against the non-LRU pages in here because
1439  * nobody will play with that bit on a non-LRU page.
1440  *
1441  * The downside is that we have to touch page->_count against each page.
1442  * But we had to alter page->flags anyway.
1443  */
1444
1445 static void move_active_pages_to_lru(struct lruvec *lruvec,
1446                                      struct list_head *list,
1447                                      struct list_head *pages_to_free,
1448                                      enum lru_list lru)
1449 {
1450         struct zone *zone = lruvec_zone(lruvec);
1451         unsigned long pgmoved = 0;
1452         struct page *page;
1453         int nr_pages;
1454
1455         while (!list_empty(list)) {
1456                 page = lru_to_page(list);
1457                 lruvec = mem_cgroup_page_lruvec(page, zone);
1458
1459                 VM_BUG_ON(PageLRU(page));
1460                 SetPageLRU(page);
1461
1462                 nr_pages = hpage_nr_pages(page);
1463                 mem_cgroup_update_lru_size(lruvec, lru, nr_pages);
1464                 list_move(&page->lru, &lruvec->lists[lru]);
1465                 pgmoved += nr_pages;
1466
1467                 if (put_page_testzero(page)) {
1468                         __ClearPageLRU(page);
1469                         __ClearPageActive(page);
1470                         del_page_from_lru_list(page, lruvec, lru);
1471
1472                         if (unlikely(PageCompound(page))) {
1473                                 spin_unlock_irq(&zone->lru_lock);
1474                                 (*get_compound_page_dtor(page))(page);
1475                                 spin_lock_irq(&zone->lru_lock);
1476                         } else
1477                                 list_add(&page->lru, pages_to_free);
1478                 }
1479         }
1480         __mod_zone_page_state(zone, NR_LRU_BASE + lru, pgmoved);
1481         if (!is_active_lru(lru))
1482                 __count_vm_events(PGDEACTIVATE, pgmoved);
1483 }
1484
1485 static void shrink_active_list(unsigned long nr_to_scan,
1486                                struct lruvec *lruvec,
1487                                struct scan_control *sc,
1488                                enum lru_list lru)
1489 {
1490         unsigned long nr_taken;
1491         unsigned long nr_scanned;
1492         unsigned long vm_flags;
1493         LIST_HEAD(l_hold);      /* The pages which were snipped off */
1494         LIST_HEAD(l_active);
1495         LIST_HEAD(l_inactive);
1496         struct page *page;
1497         struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1498         unsigned long nr_rotated = 0;
1499         isolate_mode_t isolate_mode = 0;
1500         int file = is_file_lru(lru);
1501         struct zone *zone = lruvec_zone(lruvec);
1502
1503         lru_add_drain();
1504
1505         if (!sc->may_unmap)
1506                 isolate_mode |= ISOLATE_UNMAPPED;
1507         if (!sc->may_writepage)
1508                 isolate_mode |= ISOLATE_CLEAN;
1509
1510         spin_lock_irq(&zone->lru_lock);
1511
1512         nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
1513                                      &nr_scanned, sc, isolate_mode, lru);
1514         if (global_reclaim(sc))
1515                 zone->pages_scanned += nr_scanned;
1516
1517         reclaim_stat->recent_scanned[file] += nr_taken;
1518
1519         __count_zone_vm_events(PGREFILL, zone, nr_scanned);
1520         __mod_zone_page_state(zone, NR_LRU_BASE + lru, -nr_taken);
1521         __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, nr_taken);
1522         spin_unlock_irq(&zone->lru_lock);
1523
1524         while (!list_empty(&l_hold)) {
1525                 cond_resched();
1526                 page = lru_to_page(&l_hold);
1527                 list_del(&page->lru);
1528
1529                 if (unlikely(!page_evictable(page))) {
1530                         putback_lru_page(page);
1531                         continue;
1532                 }
1533
1534                 if (unlikely(buffer_heads_over_limit)) {
1535                         if (page_has_private(page) && trylock_page(page)) {
1536                                 if (page_has_private(page))
1537                                         try_to_release_page(page, 0);
1538                                 unlock_page(page);
1539                         }
1540                 }
1541
1542                 if (page_referenced(page, 0, sc->target_mem_cgroup,
1543                                     &vm_flags)) {
1544                         nr_rotated += hpage_nr_pages(page);
1545                         /*
1546                          * Identify referenced, file-backed active pages and
1547                          * give them one more trip around the active list. So
1548                          * that executable code get better chances to stay in
1549                          * memory under moderate memory pressure.  Anon pages
1550                          * are not likely to be evicted by use-once streaming
1551                          * IO, plus JVM can create lots of anon VM_EXEC pages,
1552                          * so we ignore them here.
1553                          */
1554                         if ((vm_flags & VM_EXEC) && page_is_file_cache(page)) {
1555                                 list_add(&page->lru, &l_active);
1556                                 continue;
1557                         }
1558                 }
1559
1560                 ClearPageActive(page);  /* we are de-activating */
1561                 list_add(&page->lru, &l_inactive);
1562         }
1563
1564         /*
1565          * Move pages back to the lru list.
1566          */
1567         spin_lock_irq(&zone->lru_lock);
1568         /*
1569          * Count referenced pages from currently used mappings as rotated,
1570          * even though only some of them are actually re-activated.  This
1571          * helps balance scan pressure between file and anonymous pages in
1572          * get_scan_ratio.
1573          */
1574         reclaim_stat->recent_rotated[file] += nr_rotated;
1575
1576         move_active_pages_to_lru(lruvec, &l_active, &l_hold, lru);
1577         move_active_pages_to_lru(lruvec, &l_inactive, &l_hold, lru - LRU_ACTIVE);
1578         __mod_zone_page_state(zone, NR_ISOLATED_ANON + file, -nr_taken);
1579         spin_unlock_irq(&zone->lru_lock);
1580
1581         free_hot_cold_page_list(&l_hold, 1);
1582 }
1583
1584 #ifdef CONFIG_SWAP
1585 static int inactive_anon_is_low_global(struct zone *zone)
1586 {
1587         unsigned long active, inactive;
1588
1589         active = zone_page_state(zone, NR_ACTIVE_ANON);
1590         inactive = zone_page_state(zone, NR_INACTIVE_ANON);
1591
1592         if (inactive * zone->inactive_ratio < active)
1593                 return 1;
1594
1595         return 0;
1596 }
1597
1598 /**
1599  * inactive_anon_is_low - check if anonymous pages need to be deactivated
1600  * @lruvec: LRU vector to check
1601  *
1602  * Returns true if the zone does not have enough inactive anon pages,
1603  * meaning some active anon pages need to be deactivated.
1604  */
1605 static int inactive_anon_is_low(struct lruvec *lruvec)
1606 {
1607         /*
1608          * If we don't have swap space, anonymous page deactivation
1609          * is pointless.
1610          */
1611         if (!total_swap_pages)
1612                 return 0;
1613
1614         if (!mem_cgroup_disabled())
1615                 return mem_cgroup_inactive_anon_is_low(lruvec);
1616
1617         return inactive_anon_is_low_global(lruvec_zone(lruvec));
1618 }
1619 #else
1620 static inline int inactive_anon_is_low(struct lruvec *lruvec)
1621 {
1622         return 0;
1623 }
1624 #endif
1625
1626 /**
1627  * inactive_file_is_low - check if file pages need to be deactivated
1628  * @lruvec: LRU vector to check
1629  *
1630  * When the system is doing streaming IO, memory pressure here
1631  * ensures that active file pages get deactivated, until more
1632  * than half of the file pages are on the inactive list.
1633  *
1634  * Once we get to that situation, protect the system's working
1635  * set from being evicted by disabling active file page aging.
1636  *
1637  * This uses a different ratio than the anonymous pages, because
1638  * the page cache uses a use-once replacement algorithm.
1639  */
1640 static int inactive_file_is_low(struct lruvec *lruvec)
1641 {
1642         unsigned long inactive;
1643         unsigned long active;
1644
1645         inactive = get_lru_size(lruvec, LRU_INACTIVE_FILE);
1646         active = get_lru_size(lruvec, LRU_ACTIVE_FILE);
1647
1648         return active > inactive;
1649 }
1650
1651 static int inactive_list_is_low(struct lruvec *lruvec, enum lru_list lru)
1652 {
1653         if (is_file_lru(lru))
1654                 return inactive_file_is_low(lruvec);
1655         else
1656                 return inactive_anon_is_low(lruvec);
1657 }
1658
1659 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
1660                                  struct lruvec *lruvec, struct scan_control *sc)
1661 {
1662         if (is_active_lru(lru)) {
1663                 if (inactive_list_is_low(lruvec, lru))
1664                         shrink_active_list(nr_to_scan, lruvec, sc, lru);
1665                 return 0;
1666         }
1667
1668         return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
1669 }
1670
1671 static int vmscan_swappiness(struct scan_control *sc)
1672 {
1673         if (global_reclaim(sc))
1674                 return vm_swappiness;
1675         return mem_cgroup_swappiness(sc->target_mem_cgroup);
1676 }
1677
1678 enum scan_balance {
1679         SCAN_EQUAL,
1680         SCAN_FRACT,
1681         SCAN_ANON,
1682         SCAN_FILE,
1683 };
1684
1685 /*
1686  * Determine how aggressively the anon and file LRU lists should be
1687  * scanned.  The relative value of each set of LRU lists is determined
1688  * by looking at the fraction of the pages scanned we did rotate back
1689  * onto the active list instead of evict.
1690  *
1691  * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
1692  * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
1693  */
1694 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
1695                            unsigned long *nr)
1696 {
1697         struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
1698         u64 fraction[2];
1699         u64 denominator = 0;    /* gcc */
1700         struct zone *zone = lruvec_zone(lruvec);
1701         unsigned long anon_prio, file_prio;
1702         enum scan_balance scan_balance;
1703         unsigned long anon, file, free;
1704         bool force_scan = false;
1705         unsigned long ap, fp;
1706         enum lru_list lru;
1707
1708         /*
1709          * If the zone or memcg is small, nr[l] can be 0.  This
1710          * results in no scanning on this priority and a potential
1711          * priority drop.  Global direct reclaim can go to the next
1712          * zone and tends to have no problems. Global kswapd is for
1713          * zone balancing and it needs to scan a minimum amount. When
1714          * reclaiming for a memcg, a priority drop can cause high
1715          * latencies, so it's better to scan a minimum amount there as
1716          * well.
1717          */
1718         if (current_is_kswapd() && zone->all_unreclaimable)
1719                 force_scan = true;
1720         if (!global_reclaim(sc))
1721                 force_scan = true;
1722
1723         /* If we have no swap space, do not bother scanning anon pages. */
1724         if (!sc->may_swap || (get_nr_swap_pages() <= 0)) {
1725                 scan_balance = SCAN_FILE;
1726                 goto out;
1727         }
1728
1729         /*
1730          * Global reclaim will swap to prevent OOM even with no
1731          * swappiness, but memcg users want to use this knob to
1732          * disable swapping for individual groups completely when
1733          * using the memory controller's swap limit feature would be
1734          * too expensive.
1735          */
1736         if (!global_reclaim(sc) && !vmscan_swappiness(sc)) {
1737                 scan_balance = SCAN_FILE;
1738                 goto out;
1739         }
1740
1741         /*
1742          * Do not apply any pressure balancing cleverness when the
1743          * system is close to OOM, scan both anon and file equally
1744          * (unless the swappiness setting disagrees with swapping).
1745          */
1746         if (!sc->priority && vmscan_swappiness(sc)) {
1747                 scan_balance = SCAN_EQUAL;
1748                 goto out;
1749         }
1750
1751         anon  = get_lru_size(lruvec, LRU_ACTIVE_ANON) +
1752                 get_lru_size(lruvec, LRU_INACTIVE_ANON);
1753         file  = get_lru_size(lruvec, LRU_ACTIVE_FILE) +
1754                 get_lru_size(lruvec, LRU_INACTIVE_FILE);
1755
1756         /*
1757          * If it's foreseeable that reclaiming the file cache won't be
1758          * enough to get the zone back into a desirable shape, we have
1759          * to swap.  Better start now and leave the - probably heavily
1760          * thrashing - remaining file pages alone.
1761          */
1762         if (global_reclaim(sc)) {
1763                 free = zone_page_state(zone, NR_FREE_PAGES);
1764                 if (unlikely(file + free <= high_wmark_pages(zone))) {
1765                         scan_balance = SCAN_ANON;
1766                         goto out;
1767                 }
1768         }
1769
1770         /*
1771          * There is enough inactive page cache, do not reclaim
1772          * anything from the anonymous working set right now.
1773          */
1774         if (!inactive_file_is_low(lruvec)) {
1775                 scan_balance = SCAN_FILE;
1776                 goto out;
1777         }
1778
1779         scan_balance = SCAN_FRACT;
1780
1781         /*
1782          * With swappiness at 100, anonymous and file have the same priority.
1783          * This scanning priority is essentially the inverse of IO cost.
1784          */
1785         anon_prio = vmscan_swappiness(sc);
1786         file_prio = 200 - anon_prio;
1787
1788         /*
1789          * OK, so we have swap space and a fair amount of page cache
1790          * pages.  We use the recently rotated / recently scanned
1791          * ratios to determine how valuable each cache is.
1792          *
1793          * Because workloads change over time (and to avoid overflow)
1794          * we keep these statistics as a floating average, which ends
1795          * up weighing recent references more than old ones.
1796          *
1797          * anon in [0], file in [1]
1798          */
1799         spin_lock_irq(&zone->lru_lock);
1800         if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
1801                 reclaim_stat->recent_scanned[0] /= 2;
1802                 reclaim_stat->recent_rotated[0] /= 2;
1803         }
1804
1805         if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
1806                 reclaim_stat->recent_scanned[1] /= 2;
1807                 reclaim_stat->recent_rotated[1] /= 2;
1808         }
1809
1810         /*
1811          * The amount of pressure on anon vs file pages is inversely
1812          * proportional to the fraction of recently scanned pages on
1813          * each list that were recently referenced and in active use.
1814          */
1815         ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
1816         ap /= reclaim_stat->recent_rotated[0] + 1;
1817
1818         fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
1819         fp /= reclaim_stat->recent_rotated[1] + 1;
1820         spin_unlock_irq(&zone->lru_lock);
1821
1822         fraction[0] = ap;
1823         fraction[1] = fp;
1824         denominator = ap + fp + 1;
1825 out:
1826         for_each_evictable_lru(lru) {
1827                 int file = is_file_lru(lru);
1828                 unsigned long size;
1829                 unsigned long scan;
1830
1831                 size = get_lru_size(lruvec, lru);
1832                 scan = size >> sc->priority;
1833
1834                 if (!scan && force_scan)
1835                         scan = min(size, SWAP_CLUSTER_MAX);
1836
1837                 switch (scan_balance) {
1838                 case SCAN_EQUAL:
1839                         /* Scan lists relative to size */
1840                         break;
1841                 case SCAN_FRACT:
1842                         /*
1843                          * Scan types proportional to swappiness and
1844                          * their relative recent reclaim efficiency.
1845                          */
1846                         scan = div64_u64(scan * fraction[file], denominator);
1847                         break;
1848                 case SCAN_FILE:
1849                 case SCAN_ANON:
1850                         /* Scan one type exclusively */
1851                         if ((scan_balance == SCAN_FILE) != file)
1852                                 scan = 0;
1853                         break;
1854                 default:
1855                         /* Look ma, no brain */
1856                         BUG();
1857                 }
1858                 nr[lru] = scan;
1859         }
1860 }
1861
1862 /*
1863  * This is a basic per-zone page freer.  Used by both kswapd and direct reclaim.
1864  */
1865 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
1866 {
1867         unsigned long nr[NR_LRU_LISTS];
1868         unsigned long nr_to_scan;
1869         enum lru_list lru;
1870         unsigned long nr_reclaimed = 0;
1871         unsigned long nr_to_reclaim = sc->nr_to_reclaim;
1872         struct blk_plug plug;
1873
1874         get_scan_count(lruvec, sc, nr);
1875
1876         blk_start_plug(&plug);
1877         while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
1878                                         nr[LRU_INACTIVE_FILE]) {
1879                 for_each_evictable_lru(lru) {
1880                         if (nr[lru]) {
1881                                 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
1882                                 nr[lru] -= nr_to_scan;
1883
1884                                 nr_reclaimed += shrink_list(lru, nr_to_scan,
1885                                                             lruvec, sc);
1886                         }
1887                 }
1888                 /*
1889                  * On large memory systems, scan >> priority can become
1890                  * really large. This is fine for the starting priority;
1891                  * we want to put equal scanning pressure on each zone.
1892                  * However, if the VM has a harder time of freeing pages,
1893                  * with multiple processes reclaiming pages, the total
1894                  * freeing target can get unreasonably large.
1895                  */
1896                 if (nr_reclaimed >= nr_to_reclaim &&
1897                     sc->priority < DEF_PRIORITY)
1898                         break;
1899         }
1900         blk_finish_plug(&plug);
1901         sc->nr_reclaimed += nr_reclaimed;
1902
1903         /*
1904          * Even if we did not try to evict anon pages at all, we want to
1905          * rebalance the anon lru active/inactive ratio.
1906          */
1907         if (inactive_anon_is_low(lruvec))
1908                 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
1909                                    sc, LRU_ACTIVE_ANON);
1910
1911         throttle_vm_writeout(sc->gfp_mask);
1912 }
1913
1914 /* Use reclaim/compaction for costly allocs or under memory pressure */
1915 static bool in_reclaim_compaction(struct scan_control *sc)
1916 {
1917         if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
1918                         (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
1919                          sc->priority < DEF_PRIORITY - 2))
1920                 return true;
1921
1922         return false;
1923 }
1924
1925 /*
1926  * Reclaim/compaction is used for high-order allocation requests. It reclaims
1927  * order-0 pages before compacting the zone. should_continue_reclaim() returns
1928  * true if more pages should be reclaimed such that when the page allocator
1929  * calls try_to_compact_zone() that it will have enough free pages to succeed.
1930  * It will give up earlier than that if there is difficulty reclaiming pages.
1931  */
1932 static inline bool should_continue_reclaim(struct zone *zone,
1933                                         unsigned long nr_reclaimed,
1934                                         unsigned long nr_scanned,
1935                                         struct scan_control *sc)
1936 {
1937         unsigned long pages_for_compaction;
1938         unsigned long inactive_lru_pages;
1939
1940         /* If not in reclaim/compaction mode, stop */
1941         if (!in_reclaim_compaction(sc))
1942                 return false;
1943
1944         /* Consider stopping depending on scan and reclaim activity */
1945         if (sc->gfp_mask & __GFP_REPEAT) {
1946                 /*
1947                  * For __GFP_REPEAT allocations, stop reclaiming if the
1948                  * full LRU list has been scanned and we are still failing
1949                  * to reclaim pages. This full LRU scan is potentially
1950                  * expensive but a __GFP_REPEAT caller really wants to succeed
1951                  */
1952                 if (!nr_reclaimed && !nr_scanned)
1953                         return false;
1954         } else {
1955                 /*
1956                  * For non-__GFP_REPEAT allocations which can presumably
1957                  * fail without consequence, stop if we failed to reclaim
1958                  * any pages from the last SWAP_CLUSTER_MAX number of
1959                  * pages that were scanned. This will return to the
1960                  * caller faster at the risk reclaim/compaction and
1961                  * the resulting allocation attempt fails
1962                  */
1963                 if (!nr_reclaimed)
1964                         return false;
1965         }
1966
1967         /*
1968          * If we have not reclaimed enough pages for compaction and the
1969          * inactive lists are large enough, continue reclaiming
1970          */
1971         pages_for_compaction = (2UL << sc->order);
1972         inactive_lru_pages = zone_page_state(zone, NR_INACTIVE_FILE);
1973         if (get_nr_swap_pages() > 0)
1974                 inactive_lru_pages += zone_page_state(zone, NR_INACTIVE_ANON);
1975         if (sc->nr_reclaimed < pages_for_compaction &&
1976                         inactive_lru_pages > pages_for_compaction)
1977                 return true;
1978
1979         /* If compaction would go ahead or the allocation would succeed, stop */
1980         switch (compaction_suitable(zone, sc->order)) {
1981         case COMPACT_PARTIAL:
1982         case COMPACT_CONTINUE:
1983                 return false;
1984         default:
1985                 return true;
1986         }
1987 }
1988
1989 static void shrink_zone(struct zone *zone, struct scan_control *sc)
1990 {
1991         unsigned long nr_reclaimed, nr_scanned;
1992
1993         do {
1994                 struct mem_cgroup *root = sc->target_mem_cgroup;
1995                 struct mem_cgroup_reclaim_cookie reclaim = {
1996                         .zone = zone,
1997                         .priority = sc->priority,
1998                 };
1999                 struct mem_cgroup *memcg;
2000
2001                 nr_reclaimed = sc->nr_reclaimed;
2002                 nr_scanned = sc->nr_scanned;
2003
2004                 memcg = mem_cgroup_iter(root, NULL, &reclaim);
2005                 do {
2006                         struct lruvec *lruvec;
2007
2008                         lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2009
2010                         shrink_lruvec(lruvec, sc);
2011
2012                         /*
2013                          * Direct reclaim and kswapd have to scan all memory
2014                          * cgroups to fulfill the overall scan target for the
2015                          * zone.
2016                          *
2017                          * Limit reclaim, on the other hand, only cares about
2018                          * nr_to_reclaim pages to be reclaimed and it will
2019                          * retry with decreasing priority if one round over the
2020                          * whole hierarchy is not sufficient.
2021                          */
2022                         if (!global_reclaim(sc) &&
2023                                         sc->nr_reclaimed >= sc->nr_to_reclaim) {
2024                                 mem_cgroup_iter_break(root, memcg);
2025                                 break;
2026                         }
2027                         memcg = mem_cgroup_iter(root, memcg, &reclaim);
2028                 } while (memcg);
2029
2030                 vmpressure(sc->gfp_mask, sc->target_mem_cgroup,
2031                            sc->nr_scanned - nr_scanned,
2032                            sc->nr_reclaimed - nr_reclaimed);
2033
2034         } while (should_continue_reclaim(zone, sc->nr_reclaimed - nr_reclaimed,
2035                                          sc->nr_scanned - nr_scanned, sc));
2036 }
2037
2038 /* Returns true if compaction should go ahead for a high-order request */
2039 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2040 {
2041         unsigned long balance_gap, watermark;
2042         bool watermark_ok;
2043
2044         /* Do not consider compaction for orders reclaim is meant to satisfy */
2045         if (sc->order <= PAGE_ALLOC_COSTLY_ORDER)
2046                 return false;
2047
2048         /*
2049          * Compaction takes time to run and there are potentially other
2050          * callers using the pages just freed. Continue reclaiming until
2051          * there is a buffer of free pages available to give compaction
2052          * a reasonable chance of completing and allocating the page
2053          */
2054         balance_gap = min(low_wmark_pages(zone),
2055                 (zone->managed_pages + KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2056                         KSWAPD_ZONE_BALANCE_GAP_RATIO);
2057         watermark = high_wmark_pages(zone) + balance_gap + (2UL << sc->order);
2058         watermark_ok = zone_watermark_ok_safe(zone, 0, watermark, 0, 0);
2059
2060         /*
2061          * If compaction is deferred, reclaim up to a point where
2062          * compaction will have a chance of success when re-enabled
2063          */
2064         if (compaction_deferred(zone, sc->order))
2065                 return watermark_ok;
2066
2067         /* If compaction is not ready to start, keep reclaiming */
2068         if (!compaction_suitable(zone, sc->order))
2069                 return false;
2070
2071         return watermark_ok;
2072 }
2073
2074 /*
2075  * This is the direct reclaim path, for page-allocating processes.  We only
2076  * try to reclaim pages from zones which will satisfy the caller's allocation
2077  * request.
2078  *
2079  * We reclaim from a zone even if that zone is over high_wmark_pages(zone).
2080  * Because:
2081  * a) The caller may be trying to free *extra* pages to satisfy a higher-order
2082  *    allocation or
2083  * b) The target zone may be at high_wmark_pages(zone) but the lower zones
2084  *    must go *over* high_wmark_pages(zone) to satisfy the `incremental min'
2085  *    zone defense algorithm.
2086  *
2087  * If a zone is deemed to be full of pinned pages then just give it a light
2088  * scan then give up on it.
2089  *
2090  * This function returns true if a zone is being reclaimed for a costly
2091  * high-order allocation and compaction is ready to begin. This indicates to
2092  * the caller that it should consider retrying the allocation instead of
2093  * further reclaim.
2094  */
2095 static bool shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
2096 {
2097         struct zoneref *z;
2098         struct zone *zone;
2099         unsigned long nr_soft_reclaimed;
2100         unsigned long nr_soft_scanned;
2101         bool aborted_reclaim = false;
2102
2103         /*
2104          * If the number of buffer_heads in the machine exceeds the maximum
2105          * allowed level, force direct reclaim to scan the highmem zone as
2106          * highmem pages could be pinning lowmem pages storing buffer_heads
2107          */
2108         if (buffer_heads_over_limit)
2109                 sc->gfp_mask |= __GFP_HIGHMEM;
2110
2111         for_each_zone_zonelist_nodemask(zone, z, zonelist,
2112                                         gfp_zone(sc->gfp_mask), sc->nodemask) {
2113                 if (!populated_zone(zone))
2114                         continue;
2115                 /*
2116                  * Take care memory controller reclaiming has small influence
2117                  * to global LRU.
2118                  */
2119                 if (global_reclaim(sc)) {
2120                         if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2121                                 continue;
2122                         if (zone->all_unreclaimable &&
2123                                         sc->priority != DEF_PRIORITY)
2124                                 continue;       /* Let kswapd poll it */
2125                         if (IS_ENABLED(CONFIG_COMPACTION)) {
2126                                 /*
2127                                  * If we already have plenty of memory free for
2128                                  * compaction in this zone, don't free any more.
2129                                  * Even though compaction is invoked for any
2130                                  * non-zero order, only frequent costly order
2131                                  * reclamation is disruptive enough to become a
2132                                  * noticeable problem, like transparent huge
2133                                  * page allocations.
2134                                  */
2135                                 if (compaction_ready(zone, sc)) {
2136                                         aborted_reclaim = true;
2137                                         continue;
2138                                 }
2139                         }
2140                         /*
2141                          * This steals pages from memory cgroups over softlimit
2142                          * and returns the number of reclaimed pages and
2143                          * scanned pages. This works for global memory pressure
2144                          * and balancing, not for a memcg's limit.
2145                          */
2146                         nr_soft_scanned = 0;
2147                         nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2148                                                 sc->order, sc->gfp_mask,
2149                                                 &nr_soft_scanned);
2150                         sc->nr_reclaimed += nr_soft_reclaimed;
2151                         sc->nr_scanned += nr_soft_scanned;
2152                         /* need some check for avoid more shrink_zone() */
2153                 }
2154
2155                 shrink_zone(zone, sc);
2156         }
2157
2158         return aborted_reclaim;
2159 }
2160
2161 static bool zone_reclaimable(struct zone *zone)
2162 {
2163         return zone->pages_scanned < zone_reclaimable_pages(zone) * 6;
2164 }
2165
2166 /* All zones in zonelist are unreclaimable? */
2167 static bool all_unreclaimable(struct zonelist *zonelist,
2168                 struct scan_control *sc)
2169 {
2170         struct zoneref *z;
2171         struct zone *zone;
2172
2173         for_each_zone_zonelist_nodemask(zone, z, zonelist,
2174                         gfp_zone(sc->gfp_mask), sc->nodemask) {
2175                 if (!populated_zone(zone))
2176                         continue;
2177                 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2178                         continue;
2179                 if (!zone->all_unreclaimable)
2180                         return false;
2181         }
2182
2183         return true;
2184 }
2185
2186 /*
2187  * This is the main entry point to direct page reclaim.
2188  *
2189  * If a full scan of the inactive list fails to free enough memory then we
2190  * are "out of memory" and something needs to be killed.
2191  *
2192  * If the caller is !__GFP_FS then the probability of a failure is reasonably
2193  * high - the zone may be full of dirty or under-writeback pages, which this
2194  * caller can't do much about.  We kick the writeback threads and take explicit
2195  * naps in the hope that some of these pages can be written.  But if the
2196  * allocating task holds filesystem locks which prevent writeout this might not
2197  * work, and the allocation attempt will fail.
2198  *
2199  * returns:     0, if no pages reclaimed
2200  *              else, the number of pages reclaimed
2201  */
2202 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
2203                                         struct scan_control *sc,
2204                                         struct shrink_control *shrink)
2205 {
2206         unsigned long total_scanned = 0;
2207         struct reclaim_state *reclaim_state = current->reclaim_state;
2208         struct zoneref *z;
2209         struct zone *zone;
2210         unsigned long writeback_threshold;
2211         bool aborted_reclaim;
2212
2213         delayacct_freepages_start();
2214
2215         if (global_reclaim(sc))
2216                 count_vm_event(ALLOCSTALL);
2217
2218         do {
2219                 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
2220                                 sc->priority);
2221                 sc->nr_scanned = 0;
2222                 aborted_reclaim = shrink_zones(zonelist, sc);
2223
2224                 /*
2225                  * Don't shrink slabs when reclaiming memory from
2226                  * over limit cgroups
2227                  */
2228                 if (global_reclaim(sc)) {
2229                         unsigned long lru_pages = 0;
2230                         for_each_zone_zonelist(zone, z, zonelist,
2231                                         gfp_zone(sc->gfp_mask)) {
2232                                 if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
2233                                         continue;
2234
2235                                 lru_pages += zone_reclaimable_pages(zone);
2236                         }
2237
2238                         shrink_slab(shrink, sc->nr_scanned, lru_pages);
2239                         if (reclaim_state) {
2240                                 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2241                                 reclaim_state->reclaimed_slab = 0;
2242                         }
2243                 }
2244                 total_scanned += sc->nr_scanned;
2245                 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
2246                         goto out;
2247
2248                 /*
2249                  * If we're getting trouble reclaiming, start doing
2250                  * writepage even in laptop mode.
2251                  */
2252                 if (sc->priority < DEF_PRIORITY - 2)
2253                         sc->may_writepage = 1;
2254
2255                 /*
2256                  * Try to write back as many pages as we just scanned.  This
2257                  * tends to cause slow streaming writers to write data to the
2258                  * disk smoothly, at the dirtying rate, which is nice.   But
2259                  * that's undesirable in laptop mode, where we *want* lumpy
2260                  * writeout.  So in laptop mode, write out the whole world.
2261                  */
2262                 writeback_threshold = sc->nr_to_reclaim + sc->nr_to_reclaim / 2;
2263                 if (total_scanned > writeback_threshold) {
2264                         wakeup_flusher_threads(laptop_mode ? 0 : total_scanned,
2265                                                 WB_REASON_TRY_TO_FREE_PAGES);
2266                         sc->may_writepage = 1;
2267                 }
2268
2269                 /* Take a nap, wait for some writeback to complete */
2270                 if (!sc->hibernation_mode && sc->nr_scanned &&
2271                     sc->priority < DEF_PRIORITY - 2) {
2272                         struct zone *preferred_zone;
2273
2274                         first_zones_zonelist(zonelist, gfp_zone(sc->gfp_mask),
2275                                                 &cpuset_current_mems_allowed,
2276                                                 &preferred_zone);
2277                         wait_iff_congested(preferred_zone, BLK_RW_ASYNC, HZ/10);
2278                 }
2279         } while (--sc->priority >= 0);
2280
2281 out:
2282         delayacct_freepages_end();
2283
2284         if (sc->nr_reclaimed)
2285                 return sc->nr_reclaimed;
2286
2287         /*
2288          * As hibernation is going on, kswapd is freezed so that it can't mark
2289          * the zone into all_unreclaimable. Thus bypassing all_unreclaimable
2290          * check.
2291          */
2292         if (oom_killer_disabled)
2293                 return 0;
2294
2295         /* Aborted reclaim to try compaction? don't OOM, then */
2296         if (aborted_reclaim)
2297                 return 1;
2298
2299         /* top priority shrink_zones still had more to do? don't OOM, then */
2300         if (global_reclaim(sc) && !all_unreclaimable(zonelist, sc))
2301                 return 1;
2302
2303         return 0;
2304 }
2305
2306 static bool pfmemalloc_watermark_ok(pg_data_t *pgdat)
2307 {
2308         struct zone *zone;
2309         unsigned long pfmemalloc_reserve = 0;
2310         unsigned long free_pages = 0;
2311         int i;
2312         bool wmark_ok;
2313
2314         for (i = 0; i <= ZONE_NORMAL; i++) {
2315                 zone = &pgdat->node_zones[i];
2316                 pfmemalloc_reserve += min_wmark_pages(zone);
2317                 free_pages += zone_page_state(zone, NR_FREE_PAGES);
2318         }
2319
2320         wmark_ok = free_pages > pfmemalloc_reserve / 2;
2321
2322         /* kswapd must be awake if processes are being throttled */
2323         if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
2324                 pgdat->classzone_idx = min(pgdat->classzone_idx,
2325                                                 (enum zone_type)ZONE_NORMAL);
2326                 wake_up_interruptible(&pgdat->kswapd_wait);
2327         }
2328
2329         return wmark_ok;
2330 }
2331
2332 /*
2333  * Throttle direct reclaimers if backing storage is backed by the network
2334  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
2335  * depleted. kswapd will continue to make progress and wake the processes
2336  * when the low watermark is reached.
2337  *
2338  * Returns true if a fatal signal was delivered during throttling. If this
2339  * happens, the page allocator should not consider triggering the OOM killer.
2340  */
2341 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
2342                                         nodemask_t *nodemask)
2343 {
2344         struct zone *zone;
2345         int high_zoneidx = gfp_zone(gfp_mask);
2346         pg_data_t *pgdat;
2347
2348         /*
2349          * Kernel threads should not be throttled as they may be indirectly
2350          * responsible for cleaning pages necessary for reclaim to make forward
2351          * progress. kjournald for example may enter direct reclaim while
2352          * committing a transaction where throttling it could forcing other
2353          * processes to block on log_wait_commit().
2354          */
2355         if (current->flags & PF_KTHREAD)
2356                 goto out;
2357
2358         /*
2359          * If a fatal signal is pending, this process should not throttle.
2360          * It should return quickly so it can exit and free its memory
2361          */
2362         if (fatal_signal_pending(current))
2363                 goto out;
2364
2365         /* Check if the pfmemalloc reserves are ok */
2366         first_zones_zonelist(zonelist, high_zoneidx, NULL, &zone);
2367         pgdat = zone->zone_pgdat;
2368         if (pfmemalloc_watermark_ok(pgdat))
2369                 goto out;
2370
2371         /* Account for the throttling */
2372         count_vm_event(PGSCAN_DIRECT_THROTTLE);
2373
2374         /*
2375          * If the caller cannot enter the filesystem, it's possible that it
2376          * is due to the caller holding an FS lock or performing a journal
2377          * transaction in the case of a filesystem like ext[3|4]. In this case,
2378          * it is not safe to block on pfmemalloc_wait as kswapd could be
2379          * blocked waiting on the same lock. Instead, throttle for up to a
2380          * second before continuing.
2381          */
2382         if (!(gfp_mask & __GFP_FS)) {
2383                 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
2384                         pfmemalloc_watermark_ok(pgdat), HZ);
2385
2386                 goto check_pending;
2387         }
2388
2389         /* Throttle until kswapd wakes the process */
2390         wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
2391                 pfmemalloc_watermark_ok(pgdat));
2392
2393 check_pending:
2394         if (fatal_signal_pending(current))
2395                 return true;
2396
2397 out:
2398         return false;
2399 }
2400
2401 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
2402                                 gfp_t gfp_mask, nodemask_t *nodemask)
2403 {
2404         unsigned long nr_reclaimed;
2405         struct scan_control sc = {
2406                 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
2407                 .may_writepage = !laptop_mode,
2408                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2409                 .may_unmap = 1,
2410                 .may_swap = 1,
2411                 .order = order,
2412                 .priority = DEF_PRIORITY,
2413                 .target_mem_cgroup = NULL,
2414                 .nodemask = nodemask,
2415         };
2416         struct shrink_control shrink = {
2417                 .gfp_mask = sc.gfp_mask,
2418         };
2419
2420         /*
2421          * Do not enter reclaim if fatal signal was delivered while throttled.
2422          * 1 is returned so that the page allocator does not OOM kill at this
2423          * point.
2424          */
2425         if (throttle_direct_reclaim(gfp_mask, zonelist, nodemask))
2426                 return 1;
2427
2428         trace_mm_vmscan_direct_reclaim_begin(order,
2429                                 sc.may_writepage,
2430                                 gfp_mask);
2431
2432         nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2433
2434         trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
2435
2436         return nr_reclaimed;
2437 }
2438
2439 #ifdef CONFIG_MEMCG
2440
2441 unsigned long mem_cgroup_shrink_node_zone(struct mem_cgroup *memcg,
2442                                                 gfp_t gfp_mask, bool noswap,
2443                                                 struct zone *zone,
2444                                                 unsigned long *nr_scanned)
2445 {
2446         struct scan_control sc = {
2447                 .nr_scanned = 0,
2448                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2449                 .may_writepage = !laptop_mode,
2450                 .may_unmap = 1,
2451                 .may_swap = !noswap,
2452                 .order = 0,
2453                 .priority = 0,
2454                 .target_mem_cgroup = memcg,
2455         };
2456         struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2457
2458         sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2459                         (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
2460
2461         trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
2462                                                       sc.may_writepage,
2463                                                       sc.gfp_mask);
2464
2465         /*
2466          * NOTE: Although we can get the priority field, using it
2467          * here is not a good idea, since it limits the pages we can scan.
2468          * if we don't reclaim here, the shrink_zone from balance_pgdat
2469          * will pick up pages from other mem cgroup's as well. We hack
2470          * the priority and make it zero.
2471          */
2472         shrink_lruvec(lruvec, &sc);
2473
2474         trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
2475
2476         *nr_scanned = sc.nr_scanned;
2477         return sc.nr_reclaimed;
2478 }
2479
2480 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
2481                                            gfp_t gfp_mask,
2482                                            bool noswap)
2483 {
2484         struct zonelist *zonelist;
2485         unsigned long nr_reclaimed;
2486         int nid;
2487         struct scan_control sc = {
2488                 .may_writepage = !laptop_mode,
2489                 .may_unmap = 1,
2490                 .may_swap = !noswap,
2491                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
2492                 .order = 0,
2493                 .priority = DEF_PRIORITY,
2494                 .target_mem_cgroup = memcg,
2495                 .nodemask = NULL, /* we don't care the placement */
2496                 .gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
2497                                 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
2498         };
2499         struct shrink_control shrink = {
2500                 .gfp_mask = sc.gfp_mask,
2501         };
2502
2503         /*
2504          * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
2505          * take care of from where we get pages. So the node where we start the
2506          * scan does not need to be the current node.
2507          */
2508         nid = mem_cgroup_select_victim_node(memcg);
2509
2510         zonelist = NODE_DATA(nid)->node_zonelists;
2511
2512         trace_mm_vmscan_memcg_reclaim_begin(0,
2513                                             sc.may_writepage,
2514                                             sc.gfp_mask);
2515
2516         nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
2517
2518         trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
2519
2520         return nr_reclaimed;
2521 }
2522 #endif
2523
2524 static void age_active_anon(struct zone *zone, struct scan_control *sc)
2525 {
2526         struct mem_cgroup *memcg;
2527
2528         if (!total_swap_pages)
2529                 return;
2530
2531         memcg = mem_cgroup_iter(NULL, NULL, NULL);
2532         do {
2533                 struct lruvec *lruvec = mem_cgroup_zone_lruvec(zone, memcg);
2534
2535                 if (inactive_anon_is_low(lruvec))
2536                         shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2537                                            sc, LRU_ACTIVE_ANON);
2538
2539                 memcg = mem_cgroup_iter(NULL, memcg, NULL);
2540         } while (memcg);
2541 }
2542
2543 static bool zone_balanced(struct zone *zone, int order,
2544                           unsigned long balance_gap, int classzone_idx)
2545 {
2546         if (!zone_watermark_ok_safe(zone, order, high_wmark_pages(zone) +
2547                                     balance_gap, classzone_idx, 0))
2548                 return false;
2549
2550         if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2551             !compaction_suitable(zone, order))
2552                 return false;
2553
2554         return true;
2555 }
2556
2557 /*
2558  * pgdat_balanced() is used when checking if a node is balanced.
2559  *
2560  * For order-0, all zones must be balanced!
2561  *
2562  * For high-order allocations only zones that meet watermarks and are in a
2563  * zone allowed by the callers classzone_idx are added to balanced_pages. The
2564  * total of balanced pages must be at least 25% of the zones allowed by
2565  * classzone_idx for the node to be considered balanced. Forcing all zones to
2566  * be balanced for high orders can cause excessive reclaim when there are
2567  * imbalanced zones.
2568  * The choice of 25% is due to
2569  *   o a 16M DMA zone that is balanced will not balance a zone on any
2570  *     reasonable sized machine
2571  *   o On all other machines, the top zone must be at least a reasonable
2572  *     percentage of the middle zones. For example, on 32-bit x86, highmem
2573  *     would need to be at least 256M for it to be balance a whole node.
2574  *     Similarly, on x86-64 the Normal zone would need to be at least 1G
2575  *     to balance a node on its own. These seemed like reasonable ratios.
2576  */
2577 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
2578 {
2579         unsigned long managed_pages = 0;
2580         unsigned long balanced_pages = 0;
2581         int i;
2582
2583         /* Check the watermark levels */
2584         for (i = 0; i <= classzone_idx; i++) {
2585                 struct zone *zone = pgdat->node_zones + i;
2586
2587                 if (!populated_zone(zone))
2588                         continue;
2589
2590                 managed_pages += zone->managed_pages;
2591
2592                 /*
2593                  * A special case here:
2594                  *
2595                  * balance_pgdat() skips over all_unreclaimable after
2596                  * DEF_PRIORITY. Effectively, it considers them balanced so
2597                  * they must be considered balanced here as well!
2598                  */
2599                 if (zone->all_unreclaimable) {
2600                         balanced_pages += zone->managed_pages;
2601                         continue;
2602                 }
2603
2604                 if (zone_balanced(zone, order, 0, i))
2605                         balanced_pages += zone->managed_pages;
2606                 else if (!order)
2607                         return false;
2608         }
2609
2610         if (order)
2611                 return balanced_pages >= (managed_pages >> 2);
2612         else
2613                 return true;
2614 }
2615
2616 /*
2617  * Prepare kswapd for sleeping. This verifies that there are no processes
2618  * waiting in throttle_direct_reclaim() and that watermarks have been met.
2619  *
2620  * Returns true if kswapd is ready to sleep
2621  */
2622 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, long remaining,
2623                                         int classzone_idx)
2624 {
2625         /* If a direct reclaimer woke kswapd within HZ/10, it's premature */
2626         if (remaining)
2627                 return false;
2628
2629         /*
2630          * There is a potential race between when kswapd checks its watermarks
2631          * and a process gets throttled. There is also a potential race if
2632          * processes get throttled, kswapd wakes, a large process exits therby
2633          * balancing the zones that causes kswapd to miss a wakeup. If kswapd
2634          * is going to sleep, no process should be sleeping on pfmemalloc_wait
2635          * so wake them now if necessary. If necessary, processes will wake
2636          * kswapd and get throttled again
2637          */
2638         if (waitqueue_active(&pgdat->pfmemalloc_wait)) {
2639                 wake_up(&pgdat->pfmemalloc_wait);
2640                 return false;
2641         }
2642
2643         return pgdat_balanced(pgdat, order, classzone_idx);
2644 }
2645
2646 /*
2647  * For kswapd, balance_pgdat() will work across all this node's zones until
2648  * they are all at high_wmark_pages(zone).
2649  *
2650  * Returns the final order kswapd was reclaiming at
2651  *
2652  * There is special handling here for zones which are full of pinned pages.
2653  * This can happen if the pages are all mlocked, or if they are all used by
2654  * device drivers (say, ZONE_DMA).  Or if they are all in use by hugetlb.
2655  * What we do is to detect the case where all pages in the zone have been
2656  * scanned twice and there has been zero successful reclaim.  Mark the zone as
2657  * dead and from now on, only perform a short scan.  Basically we're polling
2658  * the zone for when the problem goes away.
2659  *
2660  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
2661  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
2662  * found to have free_pages <= high_wmark_pages(zone), we scan that zone and the
2663  * lower zones regardless of the number of free pages in the lower zones. This
2664  * interoperates with the page allocator fallback scheme to ensure that aging
2665  * of pages is balanced across the zones.
2666  */
2667 static unsigned long balance_pgdat(pg_data_t *pgdat, int order,
2668                                                         int *classzone_idx)
2669 {
2670         bool pgdat_is_balanced = false;
2671         int i;
2672         int end_zone = 0;       /* Inclusive.  0 = ZONE_DMA */
2673         struct reclaim_state *reclaim_state = current->reclaim_state;
2674         unsigned long nr_soft_reclaimed;
2675         unsigned long nr_soft_scanned;
2676         struct scan_control sc = {
2677                 .gfp_mask = GFP_KERNEL,
2678                 .may_unmap = 1,
2679                 .may_swap = 1,
2680                 /*
2681                  * kswapd doesn't want to be bailed out while reclaim. because
2682                  * we want to put equal scanning pressure on each zone.
2683                  */
2684                 .nr_to_reclaim = ULONG_MAX,
2685                 .order = order,
2686                 .target_mem_cgroup = NULL,
2687         };
2688         struct shrink_control shrink = {
2689                 .gfp_mask = sc.gfp_mask,
2690         };
2691 loop_again:
2692         sc.priority = DEF_PRIORITY;
2693         sc.nr_reclaimed = 0;
2694         sc.may_writepage = !laptop_mode;
2695         count_vm_event(PAGEOUTRUN);
2696
2697         do {
2698                 unsigned long lru_pages = 0;
2699
2700                 /*
2701                  * Scan in the highmem->dma direction for the highest
2702                  * zone which needs scanning
2703                  */
2704                 for (i = pgdat->nr_zones - 1; i >= 0; i--) {
2705                         struct zone *zone = pgdat->node_zones + i;
2706
2707                         if (!populated_zone(zone))
2708                                 continue;
2709
2710                         if (zone->all_unreclaimable &&
2711                             sc.priority != DEF_PRIORITY)
2712                                 continue;
2713
2714                         /*
2715                          * Do some background aging of the anon list, to give
2716                          * pages a chance to be referenced before reclaiming.
2717                          */
2718                         age_active_anon(zone, &sc);
2719
2720                         /*
2721                          * If the number of buffer_heads in the machine
2722                          * exceeds the maximum allowed level and this node
2723                          * has a highmem zone, force kswapd to reclaim from
2724                          * it to relieve lowmem pressure.
2725                          */
2726                         if (buffer_heads_over_limit && is_highmem_idx(i)) {
2727                                 end_zone = i;
2728                                 break;
2729                         }
2730
2731                         if (!zone_balanced(zone, order, 0, 0)) {
2732                                 end_zone = i;
2733                                 break;
2734                         } else {
2735                                 /* If balanced, clear the congested flag */
2736                                 zone_clear_flag(zone, ZONE_CONGESTED);
2737                         }
2738                 }
2739
2740                 if (i < 0) {
2741                         pgdat_is_balanced = true;
2742                         goto out;
2743                 }
2744
2745                 for (i = 0; i <= end_zone; i++) {
2746                         struct zone *zone = pgdat->node_zones + i;
2747
2748                         lru_pages += zone_reclaimable_pages(zone);
2749                 }
2750
2751                 /*
2752                  * Now scan the zone in the dma->highmem direction, stopping
2753                  * at the last zone which needs scanning.
2754                  *
2755                  * We do this because the page allocator works in the opposite
2756                  * direction.  This prevents the page allocator from allocating
2757                  * pages behind kswapd's direction of progress, which would
2758                  * cause too much scanning of the lower zones.
2759                  */
2760                 for (i = 0; i <= end_zone; i++) {
2761                         struct zone *zone = pgdat->node_zones + i;
2762                         int nr_slab, testorder;
2763                         unsigned long balance_gap;
2764
2765                         if (!populated_zone(zone))
2766                                 continue;
2767
2768                         if (zone->all_unreclaimable &&
2769                             sc.priority != DEF_PRIORITY)
2770                                 continue;
2771
2772                         sc.nr_scanned = 0;
2773
2774                         nr_soft_scanned = 0;
2775                         /*
2776                          * Call soft limit reclaim before calling shrink_zone.
2777                          */
2778                         nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone,
2779                                                         order, sc.gfp_mask,
2780                                                         &nr_soft_scanned);
2781                         sc.nr_reclaimed += nr_soft_reclaimed;
2782
2783                         /*
2784                          * We put equal pressure on every zone, unless
2785                          * one zone has way too many pages free
2786                          * already. The "too many pages" is defined
2787                          * as the high wmark plus a "gap" where the
2788                          * gap is either the low watermark or 1%
2789                          * of the zone, whichever is smaller.
2790                          */
2791                         balance_gap = min(low_wmark_pages(zone),
2792                                 (zone->managed_pages +
2793                                         KSWAPD_ZONE_BALANCE_GAP_RATIO-1) /
2794                                 KSWAPD_ZONE_BALANCE_GAP_RATIO);
2795                         /*
2796                          * Kswapd reclaims only single pages with compaction
2797                          * enabled. Trying too hard to reclaim until contiguous
2798                          * free pages have become available can hurt performance
2799                          * by evicting too much useful data from memory.
2800                          * Do not reclaim more than needed for compaction.
2801                          */
2802                         testorder = order;
2803                         if (IS_ENABLED(CONFIG_COMPACTION) && order &&
2804                                         compaction_suitable(zone, order) !=
2805                                                 COMPACT_SKIPPED)
2806                                 testorder = 0;
2807
2808                         if ((buffer_heads_over_limit && is_highmem_idx(i)) ||
2809                             !zone_balanced(zone, testorder,
2810                                            balance_gap, end_zone)) {
2811                                 shrink_zone(zone, &sc);
2812
2813                                 reclaim_state->reclaimed_slab = 0;
2814                                 nr_slab = shrink_slab(&shrink, sc.nr_scanned, lru_pages);
2815                                 sc.nr_reclaimed += reclaim_state->reclaimed_slab;
2816
2817                                 if (nr_slab == 0 && !zone_reclaimable(zone))
2818                                         zone->all_unreclaimable = 1;
2819                         }
2820
2821                         /*
2822                          * If we're getting trouble reclaiming, start doing
2823                          * writepage even in laptop mode.
2824                          */
2825                         if (sc.priority < DEF_PRIORITY - 2)
2826                                 sc.may_writepage = 1;
2827
2828                         if (zone->all_unreclaimable) {
2829                                 if (end_zone && end_zone == i)
2830                                         end_zone--;
2831                                 continue;
2832                         }
2833
2834                         if (zone_balanced(zone, testorder, 0, end_zone))
2835                                 /*
2836                                  * If a zone reaches its high watermark,
2837                                  * consider it to be no longer congested. It's
2838                                  * possible there are dirty pages backed by
2839                                  * congested BDIs but as pressure is relieved,
2840                                  * speculatively avoid congestion waits
2841                                  */
2842                                 zone_clear_flag(zone, ZONE_CONGESTED);
2843                 }
2844
2845                 /*
2846                  * If the low watermark is met there is no need for processes
2847                  * to be throttled on pfmemalloc_wait as they should not be
2848                  * able to safely make forward progress. Wake them
2849                  */
2850                 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
2851                                 pfmemalloc_watermark_ok(pgdat))
2852                         wake_up(&pgdat->pfmemalloc_wait);
2853
2854                 if (pgdat_balanced(pgdat, order, *classzone_idx)) {
2855                         pgdat_is_balanced = true;
2856                         break;          /* kswapd: all done */
2857                 }
2858
2859                 /*
2860                  * We do this so kswapd doesn't build up large priorities for
2861                  * example when it is freeing in parallel with allocators. It
2862                  * matches the direct reclaim path behaviour in terms of impact
2863                  * on zone->*_priority.
2864                  */
2865                 if (sc.nr_reclaimed >= SWAP_CLUSTER_MAX)
2866                         break;
2867         } while (--sc.priority >= 0);
2868
2869 out:
2870         if (!pgdat_is_balanced) {
2871                 cond_resched();
2872
2873                 try_to_freeze();
2874
2875                 /*
2876                  * Fragmentation may mean that the system cannot be
2877                  * rebalanced for high-order allocations in all zones.
2878                  * At this point, if nr_reclaimed < SWAP_CLUSTER_MAX,
2879                  * it means the zones have been fully scanned and are still
2880                  * not balanced. For high-order allocations, there is
2881                  * little point trying all over again as kswapd may
2882                  * infinite loop.
2883                  *
2884                  * Instead, recheck all watermarks at order-0 as they
2885                  * are the most important. If watermarks are ok, kswapd will go
2886                  * back to sleep. High-order users can still perform direct
2887                  * reclaim if they wish.
2888                  */
2889                 if (sc.nr_reclaimed < SWAP_CLUSTER_MAX)
2890                         order = sc.order = 0;
2891
2892                 goto loop_again;
2893         }
2894
2895         /*
2896          * If kswapd was reclaiming at a higher order, it has the option of
2897          * sleeping without all zones being balanced. Before it does, it must
2898          * ensure that the watermarks for order-0 on *all* zones are met and
2899          * that the congestion flags are cleared. The congestion flag must
2900          * be cleared as kswapd is the only mechanism that clears the flag
2901          * and it is potentially going to sleep here.
2902          */
2903         if (order) {
2904                 int zones_need_compaction = 1;
2905
2906                 for (i = 0; i <= end_zone; i++) {
2907                         struct zone *zone = pgdat->node_zones + i;
2908
2909                         if (!populated_zone(zone))
2910                                 continue;
2911
2912                         /* Check if the memory needs to be defragmented. */
2913                         if (zone_watermark_ok(zone, order,
2914                                     low_wmark_pages(zone), *classzone_idx, 0))
2915                                 zones_need_compaction = 0;
2916                 }
2917
2918                 if (zones_need_compaction)
2919                         compact_pgdat(pgdat, order);
2920         }
2921
2922         /*
2923          * Return the order we were reclaiming at so prepare_kswapd_sleep()
2924          * makes a decision on the order we were last reclaiming at. However,
2925          * if another caller entered the allocator slow path while kswapd
2926          * was awake, order will remain at the higher level
2927          */
2928         *classzone_idx = end_zone;
2929         return order;
2930 }
2931
2932 static void kswapd_try_to_sleep(pg_data_t *pgdat, int order, int classzone_idx)
2933 {
2934         long remaining = 0;
2935         DEFINE_WAIT(wait);
2936
2937         if (freezing(current) || kthread_should_stop())
2938                 return;
2939
2940         prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2941
2942         /* Try to sleep for a short interval */
2943         if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2944                 remaining = schedule_timeout(HZ/10);
2945                 finish_wait(&pgdat->kswapd_wait, &wait);
2946                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
2947         }
2948
2949         /*
2950          * After a short sleep, check if it was a premature sleep. If not, then
2951          * go fully to sleep until explicitly woken up.
2952          */
2953         if (prepare_kswapd_sleep(pgdat, order, remaining, classzone_idx)) {
2954                 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
2955
2956                 /*
2957                  * vmstat counters are not perfectly accurate and the estimated
2958                  * value for counters such as NR_FREE_PAGES can deviate from the
2959                  * true value by nr_online_cpus * threshold. To avoid the zone
2960                  * watermarks being breached while under pressure, we reduce the
2961                  * per-cpu vmstat threshold while kswapd is awake and restore
2962                  * them before going back to sleep.
2963                  */
2964                 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
2965
2966                 /*
2967                  * Compaction records what page blocks it recently failed to
2968                  * isolate pages from and skips them in the future scanning.
2969                  * When kswapd is going to sleep, it is reasonable to assume
2970                  * that pages and compaction may succeed so reset the cache.
2971                  */
2972                 reset_isolation_suitable(pgdat);
2973
2974                 if (!kthread_should_stop())
2975                         schedule();
2976
2977                 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
2978         } else {
2979                 if (remaining)
2980                         count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
2981                 else
2982                         count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
2983         }
2984         finish_wait(&pgdat->kswapd_wait, &wait);
2985 }
2986
2987 /*
2988  * The background pageout daemon, started as a kernel thread
2989  * from the init process.
2990  *
2991  * This basically trickles out pages so that we have _some_
2992  * free memory available even if there is no other activity
2993  * that frees anything up. This is needed for things like routing
2994  * etc, where we otherwise might have all activity going on in
2995  * asynchronous contexts that cannot page things out.
2996  *
2997  * If there are applications that are active memory-allocators
2998  * (most normal use), this basically shouldn't matter.
2999  */
3000 static int kswapd(void *p)
3001 {
3002         unsigned long order, new_order;
3003         unsigned balanced_order;
3004         int classzone_idx, new_classzone_idx;
3005         int balanced_classzone_idx;
3006         pg_data_t *pgdat = (pg_data_t*)p;
3007         struct task_struct *tsk = current;
3008
3009         struct reclaim_state reclaim_state = {
3010                 .reclaimed_slab = 0,
3011         };
3012         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3013
3014         lockdep_set_current_reclaim_state(GFP_KERNEL);
3015
3016         if (!cpumask_empty(cpumask))
3017                 set_cpus_allowed_ptr(tsk, cpumask);
3018         current->reclaim_state = &reclaim_state;
3019
3020         /*
3021          * Tell the memory management that we're a "memory allocator",
3022          * and that if we need more memory we should get access to it
3023          * regardless (see "__alloc_pages()"). "kswapd" should
3024          * never get caught in the normal page freeing logic.
3025          *
3026          * (Kswapd normally doesn't need memory anyway, but sometimes
3027          * you need a small amount of memory in order to be able to
3028          * page out something else, and this flag essentially protects
3029          * us from recursively trying to free more memory as we're
3030          * trying to free the first piece of memory in the first place).
3031          */
3032         tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
3033         set_freezable();
3034
3035         order = new_order = 0;
3036         balanced_order = 0;
3037         classzone_idx = new_classzone_idx = pgdat->nr_zones - 1;
3038         balanced_classzone_idx = classzone_idx;
3039         for ( ; ; ) {
3040                 bool ret;
3041
3042                 /*
3043                  * If the last balance_pgdat was unsuccessful it's unlikely a
3044                  * new request of a similar or harder type will succeed soon
3045                  * so consider going to sleep on the basis we reclaimed at
3046                  */
3047                 if (balanced_classzone_idx >= new_classzone_idx &&
3048                                         balanced_order == new_order) {
3049                         new_order = pgdat->kswapd_max_order;
3050                         new_classzone_idx = pgdat->classzone_idx;
3051                         pgdat->kswapd_max_order =  0;
3052                         pgdat->classzone_idx = pgdat->nr_zones - 1;
3053                 }
3054
3055                 if (order < new_order || classzone_idx > new_classzone_idx) {
3056                         /*
3057                          * Don't sleep if someone wants a larger 'order'
3058                          * allocation or has tigher zone constraints
3059                          */
3060                         order = new_order;
3061                         classzone_idx = new_classzone_idx;
3062                 } else {
3063                         kswapd_try_to_sleep(pgdat, balanced_order,
3064                                                 balanced_classzone_idx);
3065                         order = pgdat->kswapd_max_order;
3066                         classzone_idx = pgdat->classzone_idx;
3067                         new_order = order;
3068                         new_classzone_idx = classzone_idx;
3069                         pgdat->kswapd_max_order = 0;
3070                         pgdat->classzone_idx = pgdat->nr_zones - 1;
3071                 }
3072
3073                 ret = try_to_freeze();
3074                 if (kthread_should_stop())
3075                         break;
3076
3077                 /*
3078                  * We can speed up thawing tasks if we don't call balance_pgdat
3079                  * after returning from the refrigerator
3080                  */
3081                 if (!ret) {
3082                         trace_mm_vmscan_kswapd_wake(pgdat->node_id, order);
3083                         balanced_classzone_idx = classzone_idx;
3084                         balanced_order = balance_pgdat(pgdat, order,
3085                                                 &balanced_classzone_idx);
3086                 }
3087         }
3088
3089         current->reclaim_state = NULL;
3090         return 0;
3091 }
3092
3093 /*
3094  * A zone is low on free memory, so wake its kswapd task to service it.
3095  */
3096 void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx)
3097 {
3098         pg_data_t *pgdat;
3099
3100         if (!populated_zone(zone))
3101                 return;
3102
3103         if (!cpuset_zone_allowed_hardwall(zone, GFP_KERNEL))
3104                 return;
3105         pgdat = zone->zone_pgdat;
3106         if (pgdat->kswapd_max_order < order) {
3107                 pgdat->kswapd_max_order = order;
3108                 pgdat->classzone_idx = min(pgdat->classzone_idx, classzone_idx);
3109         }
3110         if (!waitqueue_active(&pgdat->kswapd_wait))
3111                 return;
3112         if (zone_watermark_ok_safe(zone, order, low_wmark_pages(zone), 0, 0))
3113                 return;
3114
3115         trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, zone_idx(zone), order);
3116         wake_up_interruptible(&pgdat->kswapd_wait);
3117 }
3118
3119 /*
3120  * The reclaimable count would be mostly accurate.
3121  * The less reclaimable pages may be
3122  * - mlocked pages, which will be moved to unevictable list when encountered
3123  * - mapped pages, which may require several travels to be reclaimed
3124  * - dirty pages, which is not "instantly" reclaimable
3125  */
3126 unsigned long global_reclaimable_pages(void)
3127 {
3128         int nr;
3129
3130         nr = global_page_state(NR_ACTIVE_FILE) +
3131              global_page_state(NR_INACTIVE_FILE);
3132
3133         if (get_nr_swap_pages() > 0)
3134                 nr += global_page_state(NR_ACTIVE_ANON) +
3135                       global_page_state(NR_INACTIVE_ANON);
3136
3137         return nr;
3138 }
3139
3140 unsigned long zone_reclaimable_pages(struct zone *zone)
3141 {
3142         int nr;
3143
3144         nr = zone_page_state(zone, NR_ACTIVE_FILE) +
3145              zone_page_state(zone, NR_INACTIVE_FILE);
3146
3147         if (get_nr_swap_pages() > 0)
3148                 nr += zone_page_state(zone, NR_ACTIVE_ANON) +
3149                       zone_page_state(zone, NR_INACTIVE_ANON);
3150
3151         return nr;
3152 }
3153
3154 #ifdef CONFIG_HIBERNATION
3155 /*
3156  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3157  * freed pages.
3158  *
3159  * Rather than trying to age LRUs the aim is to preserve the overall
3160  * LRU order by reclaiming preferentially
3161  * inactive > active > active referenced > active mapped
3162  */
3163 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
3164 {
3165         struct reclaim_state reclaim_state;
3166         struct scan_control sc = {
3167                 .gfp_mask = GFP_HIGHUSER_MOVABLE,
3168                 .may_swap = 1,
3169                 .may_unmap = 1,
3170                 .may_writepage = 1,
3171                 .nr_to_reclaim = nr_to_reclaim,
3172                 .hibernation_mode = 1,
3173                 .order = 0,
3174                 .priority = DEF_PRIORITY,
3175         };
3176         struct shrink_control shrink = {
3177                 .gfp_mask = sc.gfp_mask,
3178         };
3179         struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
3180         struct task_struct *p = current;
3181         unsigned long nr_reclaimed;
3182
3183         p->flags |= PF_MEMALLOC;
3184         lockdep_set_current_reclaim_state(sc.gfp_mask);
3185         reclaim_state.reclaimed_slab = 0;
3186         p->reclaim_state = &reclaim_state;
3187
3188         nr_reclaimed = do_try_to_free_pages(zonelist, &sc, &shrink);
3189
3190         p->reclaim_state = NULL;
3191         lockdep_clear_current_reclaim_state();
3192         p->flags &= ~PF_MEMALLOC;
3193
3194         return nr_reclaimed;
3195 }
3196 #endif /* CONFIG_HIBERNATION */
3197
3198 /* It's optimal to keep kswapds on the same CPUs as their memory, but
3199    not required for correctness.  So if the last cpu in a node goes
3200    away, we get changed to run anywhere: as the first one comes back,
3201    restore their cpu bindings. */
3202 static int cpu_callback(struct notifier_block *nfb, unsigned long action,
3203                         void *hcpu)
3204 {
3205         int nid;
3206
3207         if (action == CPU_ONLINE || action == CPU_ONLINE_FROZEN) {
3208                 for_each_node_state(nid, N_MEMORY) {
3209                         pg_data_t *pgdat = NODE_DATA(nid);
3210                         const struct cpumask *mask;
3211
3212                         mask = cpumask_of_node(pgdat->node_id);
3213
3214                         if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
3215                                 /* One of our CPUs online: restore mask */
3216                                 set_cpus_allowed_ptr(pgdat->kswapd, mask);
3217                 }
3218         }
3219         return NOTIFY_OK;
3220 }
3221
3222 /*
3223  * This kswapd start function will be called by init and node-hot-add.
3224  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
3225  */
3226 int kswapd_run(int nid)
3227 {
3228         pg_data_t *pgdat = NODE_DATA(nid);
3229         int ret = 0;
3230
3231         if (pgdat->kswapd)
3232                 return 0;
3233
3234         pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
3235         if (IS_ERR(pgdat->kswapd)) {
3236                 /* failure at boot is fatal */
3237                 BUG_ON(system_state == SYSTEM_BOOTING);
3238                 pr_err("Failed to start kswapd on node %d\n", nid);
3239                 ret = PTR_ERR(pgdat->kswapd);
3240                 pgdat->kswapd = NULL;
3241         }
3242         return ret;
3243 }
3244
3245 /*
3246  * Called by memory hotplug when all memory in a node is offlined.  Caller must
3247  * hold lock_memory_hotplug().
3248  */
3249 void kswapd_stop(int nid)
3250 {
3251         struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
3252
3253         if (kswapd) {
3254                 kthread_stop(kswapd);
3255                 NODE_DATA(nid)->kswapd = NULL;
3256         }
3257 }
3258
3259 static int __init kswapd_init(void)
3260 {
3261         int nid;
3262
3263         swap_setup();
3264         for_each_node_state(nid, N_MEMORY)
3265                 kswapd_run(nid);
3266         hotcpu_notifier(cpu_callback, 0);
3267         return 0;
3268 }
3269
3270 module_init(kswapd_init)
3271
3272 #ifdef CONFIG_NUMA
3273 /*
3274  * Zone reclaim mode
3275  *
3276  * If non-zero call zone_reclaim when the number of free pages falls below
3277  * the watermarks.
3278  */
3279 int zone_reclaim_mode __read_mostly;
3280
3281 #define RECLAIM_OFF 0
3282 #define RECLAIM_ZONE (1<<0)     /* Run shrink_inactive_list on the zone */
3283 #define RECLAIM_WRITE (1<<1)    /* Writeout pages during reclaim */
3284 #define RECLAIM_SWAP (1<<2)     /* Swap pages out during reclaim */
3285
3286 /*
3287  * Priority for ZONE_RECLAIM. This determines the fraction of pages
3288  * of a node considered for each zone_reclaim. 4 scans 1/16th of
3289  * a zone.
3290  */
3291 #define ZONE_RECLAIM_PRIORITY 4
3292
3293 /*
3294  * Percentage of pages in a zone that must be unmapped for zone_reclaim to
3295  * occur.
3296  */
3297 int sysctl_min_unmapped_ratio = 1;
3298
3299 /*
3300  * If the number of slab pages in a zone grows beyond this percentage then
3301  * slab reclaim needs to occur.
3302  */
3303 int sysctl_min_slab_ratio = 5;
3304
3305 static inline unsigned long zone_unmapped_file_pages(struct zone *zone)
3306 {
3307         unsigned long file_mapped = zone_page_state(zone, NR_FILE_MAPPED);
3308         unsigned long file_lru = zone_page_state(zone, NR_INACTIVE_FILE) +
3309                 zone_page_state(zone, NR_ACTIVE_FILE);
3310
3311         /*
3312          * It's possible for there to be more file mapped pages than
3313          * accounted for by the pages on the file LRU lists because
3314          * tmpfs pages accounted for as ANON can also be FILE_MAPPED
3315          */
3316         return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
3317 }
3318
3319 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
3320 static long zone_pagecache_reclaimable(struct zone *zone)
3321 {
3322         long nr_pagecache_reclaimable;
3323         long delta = 0;
3324
3325         /*
3326          * If RECLAIM_SWAP is set, then all file pages are considered
3327          * potentially reclaimable. Otherwise, we have to worry about
3328          * pages like swapcache and zone_unmapped_file_pages() provides
3329          * a better estimate
3330          */
3331         if (zone_reclaim_mode & RECLAIM_SWAP)
3332                 nr_pagecache_reclaimable = zone_page_state(zone, NR_FILE_PAGES);
3333         else
3334                 nr_pagecache_reclaimable = zone_unmapped_file_pages(zone);
3335
3336         /* If we can't clean pages, remove dirty pages from consideration */
3337         if (!(zone_reclaim_mode & RECLAIM_WRITE))
3338                 delta += zone_page_state(zone, NR_FILE_DIRTY);
3339
3340         /* Watch for any possible underflows due to delta */
3341         if (unlikely(delta > nr_pagecache_reclaimable))
3342                 delta = nr_pagecache_reclaimable;
3343
3344         return nr_pagecache_reclaimable - delta;
3345 }
3346
3347 /*
3348  * Try to free up some pages from this zone through reclaim.
3349  */
3350 static int __zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3351 {
3352         /* Minimum pages needed in order to stay on node */
3353         const unsigned long nr_pages = 1 << order;
3354         struct task_struct *p = current;
3355         struct reclaim_state reclaim_state;
3356         struct scan_control sc = {
3357                 .may_writepage = !!(zone_reclaim_mode & RECLAIM_WRITE),
3358                 .may_unmap = !!(zone_reclaim_mode & RECLAIM_SWAP),
3359                 .may_swap = 1,
3360                 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3361                 .gfp_mask = (gfp_mask = memalloc_noio_flags(gfp_mask)),
3362                 .order = order,
3363                 .priority = ZONE_RECLAIM_PRIORITY,
3364         };
3365         struct shrink_control shrink = {
3366                 .gfp_mask = sc.gfp_mask,
3367         };
3368         unsigned long nr_slab_pages0, nr_slab_pages1;
3369
3370         cond_resched();
3371         /*
3372          * We need to be able to allocate from the reserves for RECLAIM_SWAP
3373          * and we also need to be able to write out pages for RECLAIM_WRITE
3374          * and RECLAIM_SWAP.
3375          */
3376         p->flags |= PF_MEMALLOC | PF_SWAPWRITE;
3377         lockdep_set_current_reclaim_state(gfp_mask);
3378         reclaim_state.reclaimed_slab = 0;
3379         p->reclaim_state = &reclaim_state;
3380
3381         if (zone_pagecache_reclaimable(zone) > zone->min_unmapped_pages) {
3382                 /*
3383                  * Free memory by calling shrink zone with increasing
3384                  * priorities until we have enough memory freed.
3385                  */
3386                 do {
3387                         shrink_zone(zone, &sc);
3388                 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
3389         }
3390
3391         nr_slab_pages0 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3392         if (nr_slab_pages0 > zone->min_slab_pages) {
3393                 /*
3394                  * shrink_slab() does not currently allow us to determine how
3395                  * many pages were freed in this zone. So we take the current
3396                  * number of slab pages and shake the slab until it is reduced
3397                  * by the same nr_pages that we used for reclaiming unmapped
3398                  * pages.
3399                  *
3400                  * Note that shrink_slab will free memory on all zones and may
3401                  * take a long time.
3402                  */
3403                 for (;;) {
3404                         unsigned long lru_pages = zone_reclaimable_pages(zone);
3405
3406                         /* No reclaimable slab or very low memory pressure */
3407                         if (!shrink_slab(&shrink, sc.nr_scanned, lru_pages))
3408                                 break;
3409
3410                         /* Freed enough memory */
3411                         nr_slab_pages1 = zone_page_state(zone,
3412                                                         NR_SLAB_RECLAIMABLE);
3413                         if (nr_slab_pages1 + nr_pages <= nr_slab_pages0)
3414                                 break;
3415                 }
3416
3417                 /*
3418                  * Update nr_reclaimed by the number of slab pages we
3419                  * reclaimed from this zone.
3420                  */
3421                 nr_slab_pages1 = zone_page_state(zone, NR_SLAB_RECLAIMABLE);
3422                 if (nr_slab_pages1 < nr_slab_pages0)
3423                         sc.nr_reclaimed += nr_slab_pages0 - nr_slab_pages1;
3424         }
3425
3426         p->reclaim_state = NULL;
3427         current->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE);
3428         lockdep_clear_current_reclaim_state();
3429         return sc.nr_reclaimed >= nr_pages;
3430 }
3431
3432 int zone_reclaim(struct zone *zone, gfp_t gfp_mask, unsigned int order)
3433 {
3434         int node_id;
3435         int ret;
3436
3437         /*
3438          * Zone reclaim reclaims unmapped file backed pages and
3439          * slab pages if we are over the defined limits.
3440          *
3441          * A small portion of unmapped file backed pages is needed for
3442          * file I/O otherwise pages read by file I/O will be immediately
3443          * thrown out if the zone is overallocated. So we do not reclaim
3444          * if less than a specified percentage of the zone is used by
3445          * unmapped file backed pages.
3446          */
3447         if (zone_pagecache_reclaimable(zone) <= zone->min_unmapped_pages &&
3448             zone_page_state(zone, NR_SLAB_RECLAIMABLE) <= zone->min_slab_pages)
3449                 return ZONE_RECLAIM_FULL;
3450
3451         if (zone->all_unreclaimable)
3452                 return ZONE_RECLAIM_FULL;
3453
3454         /*
3455          * Do not scan if the allocation should not be delayed.
3456          */
3457         if (!(gfp_mask & __GFP_WAIT) || (current->flags & PF_MEMALLOC))
3458                 return ZONE_RECLAIM_NOSCAN;
3459
3460         /*
3461          * Only run zone reclaim on the local zone or on zones that do not
3462          * have associated processors. This will favor the local processor
3463          * over remote processors and spread off node memory allocations
3464          * as wide as possible.
3465          */
3466         node_id = zone_to_nid(zone);
3467         if (node_state(node_id, N_CPU) && node_id != numa_node_id())
3468                 return ZONE_RECLAIM_NOSCAN;
3469
3470         if (zone_test_and_set_flag(zone, ZONE_RECLAIM_LOCKED))
3471                 return ZONE_RECLAIM_NOSCAN;
3472
3473         ret = __zone_reclaim(zone, gfp_mask, order);
3474         zone_clear_flag(zone, ZONE_RECLAIM_LOCKED);
3475
3476         if (!ret)
3477                 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
3478
3479         return ret;
3480 }
3481 #endif
3482
3483 /*
3484  * page_evictable - test whether a page is evictable
3485  * @page: the page to test
3486  *
3487  * Test whether page is evictable--i.e., should be placed on active/inactive
3488  * lists vs unevictable list.
3489  *
3490  * Reasons page might not be evictable:
3491  * (1) page's mapping marked unevictable
3492  * (2) page is part of an mlocked VMA
3493  *
3494  */
3495 int page_evictable(struct page *page)
3496 {
3497         return !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
3498 }
3499
3500 #ifdef CONFIG_SHMEM
3501 /**
3502  * check_move_unevictable_pages - check pages for evictability and move to appropriate zone lru list
3503  * @pages:      array of pages to check
3504  * @nr_pages:   number of pages to check
3505  *
3506  * Checks pages for evictability and moves them to the appropriate lru list.
3507  *
3508  * This function is only used for SysV IPC SHM_UNLOCK.
3509  */
3510 void check_move_unevictable_pages(struct page **pages, int nr_pages)
3511 {
3512         struct lruvec *lruvec;
3513         struct zone *zone = NULL;
3514         int pgscanned = 0;
3515         int pgrescued = 0;
3516         int i;
3517
3518         for (i = 0; i < nr_pages; i++) {
3519                 struct page *page = pages[i];
3520                 struct zone *pagezone;
3521
3522                 pgscanned++;
3523                 pagezone = page_zone(page);
3524                 if (pagezone != zone) {
3525                         if (zone)
3526                                 spin_unlock_irq(&zone->lru_lock);
3527                         zone = pagezone;
3528                         spin_lock_irq(&zone->lru_lock);
3529                 }
3530                 lruvec = mem_cgroup_page_lruvec(page, zone);
3531
3532                 if (!PageLRU(page) || !PageUnevictable(page))
3533                         continue;
3534
3535                 if (page_evictable(page)) {
3536                         enum lru_list lru = page_lru_base_type(page);
3537
3538                         VM_BUG_ON(PageActive(page));
3539                         ClearPageUnevictable(page);
3540                         del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
3541                         add_page_to_lru_list(page, lruvec, lru);
3542                         pgrescued++;
3543                 }
3544         }
3545
3546         if (zone) {
3547                 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
3548                 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
3549                 spin_unlock_irq(&zone->lru_lock);
3550         }
3551 }
3552 #endif /* CONFIG_SHMEM */
3553
3554 static void warn_scan_unevictable_pages(void)
3555 {
3556         printk_once(KERN_WARNING
3557                     "%s: The scan_unevictable_pages sysctl/node-interface has been "
3558                     "disabled for lack of a legitimate use case.  If you have "
3559                     "one, please send an email to linux-mm@kvack.org.\n",
3560                     current->comm);
3561 }
3562
3563 /*
3564  * scan_unevictable_pages [vm] sysctl handler.  On demand re-scan of
3565  * all nodes' unevictable lists for evictable pages
3566  */
3567 unsigned long scan_unevictable_pages;
3568
3569 int scan_unevictable_handler(struct ctl_table *table, int write,
3570                            void __user *buffer,
3571                            size_t *length, loff_t *ppos)
3572 {
3573         warn_scan_unevictable_pages();
3574         proc_doulongvec_minmax(table, write, buffer, length, ppos);
3575         scan_unevictable_pages = 0;
3576         return 0;
3577 }
3578
3579 #ifdef CONFIG_NUMA
3580 /*
3581  * per node 'scan_unevictable_pages' attribute.  On demand re-scan of
3582  * a specified node's per zone unevictable lists for evictable pages.
3583  */
3584
3585 static ssize_t read_scan_unevictable_node(struct device *dev,
3586                                           struct device_attribute *attr,
3587                                           char *buf)
3588 {
3589         warn_scan_unevictable_pages();
3590         return sprintf(buf, "0\n");     /* always zero; should fit... */
3591 }
3592
3593 static ssize_t write_scan_unevictable_node(struct device *dev,
3594                                            struct device_attribute *attr,
3595                                         const char *buf, size_t count)
3596 {
3597         warn_scan_unevictable_pages();
3598         return 1;
3599 }
3600
3601
3602 static DEVICE_ATTR(scan_unevictable_pages, S_IRUGO | S_IWUSR,
3603                         read_scan_unevictable_node,
3604                         write_scan_unevictable_node);
3605
3606 int scan_unevictable_register_node(struct node *node)
3607 {
3608         return device_create_file(&node->dev, &dev_attr_scan_unevictable_pages);
3609 }
3610
3611 void scan_unevictable_unregister_node(struct node *node)
3612 {
3613         device_remove_file(&node->dev, &dev_attr_scan_unevictable_pages);
3614 }
3615 #endif