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