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