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