OSDN Git Service

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