mm: vmscan: turn shrink_node_memcg() into shrink_lruvec()
[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 scan_control *sc,
2285                            unsigned long *nr)
2286 {
2287         struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2288         int swappiness = mem_cgroup_swappiness(memcg);
2289         struct zone_reclaim_stat *reclaim_stat = &lruvec->reclaim_stat;
2290         u64 fraction[2];
2291         u64 denominator = 0;    /* gcc */
2292         struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2293         unsigned long anon_prio, file_prio;
2294         enum scan_balance scan_balance;
2295         unsigned long anon, file;
2296         unsigned long ap, fp;
2297         enum lru_list lru;
2298
2299         /* If we have no swap space, do not bother scanning anon pages. */
2300         if (!sc->may_swap || mem_cgroup_get_nr_swap_pages(memcg) <= 0) {
2301                 scan_balance = SCAN_FILE;
2302                 goto out;
2303         }
2304
2305         /*
2306          * Global reclaim will swap to prevent OOM even with no
2307          * swappiness, but memcg users want to use this knob to
2308          * disable swapping for individual groups completely when
2309          * using the memory controller's swap limit feature would be
2310          * too expensive.
2311          */
2312         if (cgroup_reclaim(sc) && !swappiness) {
2313                 scan_balance = SCAN_FILE;
2314                 goto out;
2315         }
2316
2317         /*
2318          * Do not apply any pressure balancing cleverness when the
2319          * system is close to OOM, scan both anon and file equally
2320          * (unless the swappiness setting disagrees with swapping).
2321          */
2322         if (!sc->priority && swappiness) {
2323                 scan_balance = SCAN_EQUAL;
2324                 goto out;
2325         }
2326
2327         /*
2328          * Prevent the reclaimer from falling into the cache trap: as
2329          * cache pages start out inactive, every cache fault will tip
2330          * the scan balance towards the file LRU.  And as the file LRU
2331          * shrinks, so does the window for rotation from references.
2332          * This means we have a runaway feedback loop where a tiny
2333          * thrashing file LRU becomes infinitely more attractive than
2334          * anon pages.  Try to detect this based on file LRU size.
2335          */
2336         if (!cgroup_reclaim(sc)) {
2337                 unsigned long pgdatfile;
2338                 unsigned long pgdatfree;
2339                 int z;
2340                 unsigned long total_high_wmark = 0;
2341
2342                 pgdatfree = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2343                 pgdatfile = node_page_state(pgdat, NR_ACTIVE_FILE) +
2344                            node_page_state(pgdat, NR_INACTIVE_FILE);
2345
2346                 for (z = 0; z < MAX_NR_ZONES; z++) {
2347                         struct zone *zone = &pgdat->node_zones[z];
2348                         if (!managed_zone(zone))
2349                                 continue;
2350
2351                         total_high_wmark += high_wmark_pages(zone);
2352                 }
2353
2354                 if (unlikely(pgdatfile + pgdatfree <= total_high_wmark)) {
2355                         /*
2356                          * Force SCAN_ANON if there are enough inactive
2357                          * anonymous pages on the LRU in eligible zones.
2358                          * Otherwise, the small LRU gets thrashed.
2359                          */
2360                         if (!inactive_list_is_low(lruvec, false, sc, false) &&
2361                             lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, sc->reclaim_idx)
2362                                         >> sc->priority) {
2363                                 scan_balance = SCAN_ANON;
2364                                 goto out;
2365                         }
2366                 }
2367         }
2368
2369         /*
2370          * If there is enough inactive page cache, i.e. if the size of the
2371          * inactive list is greater than that of the active list *and* the
2372          * inactive list actually has some pages to scan on this priority, we
2373          * do not reclaim anything from the anonymous working set right now.
2374          * Without the second condition we could end up never scanning an
2375          * lruvec even if it has plenty of old anonymous pages unless the
2376          * system is under heavy pressure.
2377          */
2378         if (!inactive_list_is_low(lruvec, true, sc, false) &&
2379             lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, sc->reclaim_idx) >> sc->priority) {
2380                 scan_balance = SCAN_FILE;
2381                 goto out;
2382         }
2383
2384         scan_balance = SCAN_FRACT;
2385
2386         /*
2387          * With swappiness at 100, anonymous and file have the same priority.
2388          * This scanning priority is essentially the inverse of IO cost.
2389          */
2390         anon_prio = swappiness;
2391         file_prio = 200 - anon_prio;
2392
2393         /*
2394          * OK, so we have swap space and a fair amount of page cache
2395          * pages.  We use the recently rotated / recently scanned
2396          * ratios to determine how valuable each cache is.
2397          *
2398          * Because workloads change over time (and to avoid overflow)
2399          * we keep these statistics as a floating average, which ends
2400          * up weighing recent references more than old ones.
2401          *
2402          * anon in [0], file in [1]
2403          */
2404
2405         anon  = lruvec_lru_size(lruvec, LRU_ACTIVE_ANON, MAX_NR_ZONES) +
2406                 lruvec_lru_size(lruvec, LRU_INACTIVE_ANON, MAX_NR_ZONES);
2407         file  = lruvec_lru_size(lruvec, LRU_ACTIVE_FILE, MAX_NR_ZONES) +
2408                 lruvec_lru_size(lruvec, LRU_INACTIVE_FILE, MAX_NR_ZONES);
2409
2410         spin_lock_irq(&pgdat->lru_lock);
2411         if (unlikely(reclaim_stat->recent_scanned[0] > anon / 4)) {
2412                 reclaim_stat->recent_scanned[0] /= 2;
2413                 reclaim_stat->recent_rotated[0] /= 2;
2414         }
2415
2416         if (unlikely(reclaim_stat->recent_scanned[1] > file / 4)) {
2417                 reclaim_stat->recent_scanned[1] /= 2;
2418                 reclaim_stat->recent_rotated[1] /= 2;
2419         }
2420
2421         /*
2422          * The amount of pressure on anon vs file pages is inversely
2423          * proportional to the fraction of recently scanned pages on
2424          * each list that were recently referenced and in active use.
2425          */
2426         ap = anon_prio * (reclaim_stat->recent_scanned[0] + 1);
2427         ap /= reclaim_stat->recent_rotated[0] + 1;
2428
2429         fp = file_prio * (reclaim_stat->recent_scanned[1] + 1);
2430         fp /= reclaim_stat->recent_rotated[1] + 1;
2431         spin_unlock_irq(&pgdat->lru_lock);
2432
2433         fraction[0] = ap;
2434         fraction[1] = fp;
2435         denominator = ap + fp + 1;
2436 out:
2437         for_each_evictable_lru(lru) {
2438                 int file = is_file_lru(lru);
2439                 unsigned long lruvec_size;
2440                 unsigned long scan;
2441                 unsigned long protection;
2442
2443                 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
2444                 protection = mem_cgroup_protection(memcg,
2445                                                    sc->memcg_low_reclaim);
2446
2447                 if (protection) {
2448                         /*
2449                          * Scale a cgroup's reclaim pressure by proportioning
2450                          * its current usage to its memory.low or memory.min
2451                          * setting.
2452                          *
2453                          * This is important, as otherwise scanning aggression
2454                          * becomes extremely binary -- from nothing as we
2455                          * approach the memory protection threshold, to totally
2456                          * nominal as we exceed it.  This results in requiring
2457                          * setting extremely liberal protection thresholds. It
2458                          * also means we simply get no protection at all if we
2459                          * set it too low, which is not ideal.
2460                          *
2461                          * If there is any protection in place, we reduce scan
2462                          * pressure by how much of the total memory used is
2463                          * within protection thresholds.
2464                          *
2465                          * There is one special case: in the first reclaim pass,
2466                          * we skip over all groups that are within their low
2467                          * protection. If that fails to reclaim enough pages to
2468                          * satisfy the reclaim goal, we come back and override
2469                          * the best-effort low protection. However, we still
2470                          * ideally want to honor how well-behaved groups are in
2471                          * that case instead of simply punishing them all
2472                          * equally. As such, we reclaim them based on how much
2473                          * memory they are using, reducing the scan pressure
2474                          * again by how much of the total memory used is under
2475                          * hard protection.
2476                          */
2477                         unsigned long cgroup_size = mem_cgroup_size(memcg);
2478
2479                         /* Avoid TOCTOU with earlier protection check */
2480                         cgroup_size = max(cgroup_size, protection);
2481
2482                         scan = lruvec_size - lruvec_size * protection /
2483                                 cgroup_size;
2484
2485                         /*
2486                          * Minimally target SWAP_CLUSTER_MAX pages to keep
2487                          * reclaim moving forwards, avoiding decremeting
2488                          * sc->priority further than desirable.
2489                          */
2490                         scan = max(scan, SWAP_CLUSTER_MAX);
2491                 } else {
2492                         scan = lruvec_size;
2493                 }
2494
2495                 scan >>= sc->priority;
2496
2497                 /*
2498                  * If the cgroup's already been deleted, make sure to
2499                  * scrape out the remaining cache.
2500                  */
2501                 if (!scan && !mem_cgroup_online(memcg))
2502                         scan = min(lruvec_size, SWAP_CLUSTER_MAX);
2503
2504                 switch (scan_balance) {
2505                 case SCAN_EQUAL:
2506                         /* Scan lists relative to size */
2507                         break;
2508                 case SCAN_FRACT:
2509                         /*
2510                          * Scan types proportional to swappiness and
2511                          * their relative recent reclaim efficiency.
2512                          * Make sure we don't miss the last page on
2513                          * the offlined memory cgroups because of a
2514                          * round-off error.
2515                          */
2516                         scan = mem_cgroup_online(memcg) ?
2517                                div64_u64(scan * fraction[file], denominator) :
2518                                DIV64_U64_ROUND_UP(scan * fraction[file],
2519                                                   denominator);
2520                         break;
2521                 case SCAN_FILE:
2522                 case SCAN_ANON:
2523                         /* Scan one type exclusively */
2524                         if ((scan_balance == SCAN_FILE) != file) {
2525                                 lruvec_size = 0;
2526                                 scan = 0;
2527                         }
2528                         break;
2529                 default:
2530                         /* Look ma, no brain */
2531                         BUG();
2532                 }
2533
2534                 nr[lru] = scan;
2535         }
2536 }
2537
2538 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
2539 {
2540         unsigned long nr[NR_LRU_LISTS];
2541         unsigned long targets[NR_LRU_LISTS];
2542         unsigned long nr_to_scan;
2543         enum lru_list lru;
2544         unsigned long nr_reclaimed = 0;
2545         unsigned long nr_to_reclaim = sc->nr_to_reclaim;
2546         struct blk_plug plug;
2547         bool scan_adjusted;
2548
2549         get_scan_count(lruvec, sc, nr);
2550
2551         /* Record the original scan target for proportional adjustments later */
2552         memcpy(targets, nr, sizeof(nr));
2553
2554         /*
2555          * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
2556          * event that can occur when there is little memory pressure e.g.
2557          * multiple streaming readers/writers. Hence, we do not abort scanning
2558          * when the requested number of pages are reclaimed when scanning at
2559          * DEF_PRIORITY on the assumption that the fact we are direct
2560          * reclaiming implies that kswapd is not keeping up and it is best to
2561          * do a batch of work at once. For memcg reclaim one check is made to
2562          * abort proportional reclaim if either the file or anon lru has already
2563          * dropped to zero at the first pass.
2564          */
2565         scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
2566                          sc->priority == DEF_PRIORITY);
2567
2568         blk_start_plug(&plug);
2569         while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
2570                                         nr[LRU_INACTIVE_FILE]) {
2571                 unsigned long nr_anon, nr_file, percentage;
2572                 unsigned long nr_scanned;
2573
2574                 for_each_evictable_lru(lru) {
2575                         if (nr[lru]) {
2576                                 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
2577                                 nr[lru] -= nr_to_scan;
2578
2579                                 nr_reclaimed += shrink_list(lru, nr_to_scan,
2580                                                             lruvec, sc);
2581                         }
2582                 }
2583
2584                 cond_resched();
2585
2586                 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
2587                         continue;
2588
2589                 /*
2590                  * For kswapd and memcg, reclaim at least the number of pages
2591                  * requested. Ensure that the anon and file LRUs are scanned
2592                  * proportionally what was requested by get_scan_count(). We
2593                  * stop reclaiming one LRU and reduce the amount scanning
2594                  * proportional to the original scan target.
2595                  */
2596                 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
2597                 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
2598
2599                 /*
2600                  * It's just vindictive to attack the larger once the smaller
2601                  * has gone to zero.  And given the way we stop scanning the
2602                  * smaller below, this makes sure that we only make one nudge
2603                  * towards proportionality once we've got nr_to_reclaim.
2604                  */
2605                 if (!nr_file || !nr_anon)
2606                         break;
2607
2608                 if (nr_file > nr_anon) {
2609                         unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
2610                                                 targets[LRU_ACTIVE_ANON] + 1;
2611                         lru = LRU_BASE;
2612                         percentage = nr_anon * 100 / scan_target;
2613                 } else {
2614                         unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
2615                                                 targets[LRU_ACTIVE_FILE] + 1;
2616                         lru = LRU_FILE;
2617                         percentage = nr_file * 100 / scan_target;
2618                 }
2619
2620                 /* Stop scanning the smaller of the LRU */
2621                 nr[lru] = 0;
2622                 nr[lru + LRU_ACTIVE] = 0;
2623
2624                 /*
2625                  * Recalculate the other LRU scan count based on its original
2626                  * scan target and the percentage scanning already complete
2627                  */
2628                 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
2629                 nr_scanned = targets[lru] - nr[lru];
2630                 nr[lru] = targets[lru] * (100 - percentage) / 100;
2631                 nr[lru] -= min(nr[lru], nr_scanned);
2632
2633                 lru += LRU_ACTIVE;
2634                 nr_scanned = targets[lru] - nr[lru];
2635                 nr[lru] = targets[lru] * (100 - percentage) / 100;
2636                 nr[lru] -= min(nr[lru], nr_scanned);
2637
2638                 scan_adjusted = true;
2639         }
2640         blk_finish_plug(&plug);
2641         sc->nr_reclaimed += nr_reclaimed;
2642
2643         /*
2644          * Even if we did not try to evict anon pages at all, we want to
2645          * rebalance the anon lru active/inactive ratio.
2646          */
2647         if (total_swap_pages && inactive_list_is_low(lruvec, false, sc, true))
2648                 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
2649                                    sc, LRU_ACTIVE_ANON);
2650 }
2651
2652 /* Use reclaim/compaction for costly allocs or under memory pressure */
2653 static bool in_reclaim_compaction(struct scan_control *sc)
2654 {
2655         if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
2656                         (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
2657                          sc->priority < DEF_PRIORITY - 2))
2658                 return true;
2659
2660         return false;
2661 }
2662
2663 /*
2664  * Reclaim/compaction is used for high-order allocation requests. It reclaims
2665  * order-0 pages before compacting the zone. should_continue_reclaim() returns
2666  * true if more pages should be reclaimed such that when the page allocator
2667  * calls try_to_compact_zone() that it will have enough free pages to succeed.
2668  * It will give up earlier than that if there is difficulty reclaiming pages.
2669  */
2670 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
2671                                         unsigned long nr_reclaimed,
2672                                         struct scan_control *sc)
2673 {
2674         unsigned long pages_for_compaction;
2675         unsigned long inactive_lru_pages;
2676         int z;
2677
2678         /* If not in reclaim/compaction mode, stop */
2679         if (!in_reclaim_compaction(sc))
2680                 return false;
2681
2682         /*
2683          * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
2684          * number of pages that were scanned. This will return to the caller
2685          * with the risk reclaim/compaction and the resulting allocation attempt
2686          * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
2687          * allocations through requiring that the full LRU list has been scanned
2688          * first, by assuming that zero delta of sc->nr_scanned means full LRU
2689          * scan, but that approximation was wrong, and there were corner cases
2690          * where always a non-zero amount of pages were scanned.
2691          */
2692         if (!nr_reclaimed)
2693                 return false;
2694
2695         /* If compaction would go ahead or the allocation would succeed, stop */
2696         for (z = 0; z <= sc->reclaim_idx; z++) {
2697                 struct zone *zone = &pgdat->node_zones[z];
2698                 if (!managed_zone(zone))
2699                         continue;
2700
2701                 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
2702                 case COMPACT_SUCCESS:
2703                 case COMPACT_CONTINUE:
2704                         return false;
2705                 default:
2706                         /* check next zone */
2707                         ;
2708                 }
2709         }
2710
2711         /*
2712          * If we have not reclaimed enough pages for compaction and the
2713          * inactive lists are large enough, continue reclaiming
2714          */
2715         pages_for_compaction = compact_gap(sc->order);
2716         inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
2717         if (get_nr_swap_pages() > 0)
2718                 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
2719
2720         return inactive_lru_pages > pages_for_compaction;
2721 }
2722
2723 static bool pgdat_memcg_congested(pg_data_t *pgdat, struct mem_cgroup *memcg)
2724 {
2725         return test_bit(PGDAT_CONGESTED, &pgdat->flags) ||
2726                 (memcg && memcg_congested(pgdat, memcg));
2727 }
2728
2729 static bool shrink_node(pg_data_t *pgdat, struct scan_control *sc)
2730 {
2731         struct reclaim_state *reclaim_state = current->reclaim_state;
2732         struct mem_cgroup *root = sc->target_mem_cgroup;
2733         unsigned long nr_reclaimed, nr_scanned;
2734         bool reclaimable = false;
2735         struct mem_cgroup *memcg;
2736 again:
2737         memset(&sc->nr, 0, sizeof(sc->nr));
2738
2739         nr_reclaimed = sc->nr_reclaimed;
2740         nr_scanned = sc->nr_scanned;
2741
2742         memcg = mem_cgroup_iter(root, NULL, NULL);
2743         do {
2744                 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
2745                 unsigned long reclaimed;
2746                 unsigned long scanned;
2747
2748                 switch (mem_cgroup_protected(root, memcg)) {
2749                 case MEMCG_PROT_MIN:
2750                         /*
2751                          * Hard protection.
2752                          * If there is no reclaimable memory, OOM.
2753                          */
2754                         continue;
2755                 case MEMCG_PROT_LOW:
2756                         /*
2757                          * Soft protection.
2758                          * Respect the protection only as long as
2759                          * there is an unprotected supply
2760                          * of reclaimable memory from other cgroups.
2761                          */
2762                         if (!sc->memcg_low_reclaim) {
2763                                 sc->memcg_low_skipped = 1;
2764                                 continue;
2765                         }
2766                         memcg_memory_event(memcg, MEMCG_LOW);
2767                         break;
2768                 case MEMCG_PROT_NONE:
2769                         /*
2770                          * All protection thresholds breached. We may
2771                          * still choose to vary the scan pressure
2772                          * applied based on by how much the cgroup in
2773                          * question has exceeded its protection
2774                          * thresholds (see get_scan_count).
2775                          */
2776                         break;
2777                 }
2778
2779                 reclaimed = sc->nr_reclaimed;
2780                 scanned = sc->nr_scanned;
2781
2782                 shrink_lruvec(lruvec, sc);
2783
2784                 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
2785                             sc->priority);
2786
2787                 /* Record the group's reclaim efficiency */
2788                 vmpressure(sc->gfp_mask, memcg, false,
2789                            sc->nr_scanned - scanned,
2790                            sc->nr_reclaimed - reclaimed);
2791
2792         } while ((memcg = mem_cgroup_iter(root, memcg, NULL)));
2793
2794         if (reclaim_state) {
2795                 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
2796                 reclaim_state->reclaimed_slab = 0;
2797         }
2798
2799         /* Record the subtree's reclaim efficiency */
2800         vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
2801                    sc->nr_scanned - nr_scanned,
2802                    sc->nr_reclaimed - nr_reclaimed);
2803
2804         if (sc->nr_reclaimed - nr_reclaimed)
2805                 reclaimable = true;
2806
2807         if (current_is_kswapd()) {
2808                 /*
2809                  * If reclaim is isolating dirty pages under writeback,
2810                  * it implies that the long-lived page allocation rate
2811                  * is exceeding the page laundering rate. Either the
2812                  * global limits are not being effective at throttling
2813                  * processes due to the page distribution throughout
2814                  * zones or there is heavy usage of a slow backing
2815                  * device. The only option is to throttle from reclaim
2816                  * context which is not ideal as there is no guarantee
2817                  * the dirtying process is throttled in the same way
2818                  * balance_dirty_pages() manages.
2819                  *
2820                  * Once a node is flagged PGDAT_WRITEBACK, kswapd will
2821                  * count the number of pages under pages flagged for
2822                  * immediate reclaim and stall if any are encountered
2823                  * in the nr_immediate check below.
2824                  */
2825                 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
2826                         set_bit(PGDAT_WRITEBACK, &pgdat->flags);
2827
2828                 /*
2829                  * Tag a node as congested if all the dirty pages
2830                  * scanned were backed by a congested BDI and
2831                  * wait_iff_congested will stall.
2832                  */
2833                 if (sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2834                         set_bit(PGDAT_CONGESTED, &pgdat->flags);
2835
2836                 /* Allow kswapd to start writing pages during reclaim.*/
2837                 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
2838                         set_bit(PGDAT_DIRTY, &pgdat->flags);
2839
2840                 /*
2841                  * If kswapd scans pages marked marked for immediate
2842                  * reclaim and under writeback (nr_immediate), it
2843                  * implies that pages are cycling through the LRU
2844                  * faster than they are written so also forcibly stall.
2845                  */
2846                 if (sc->nr.immediate)
2847                         congestion_wait(BLK_RW_ASYNC, HZ/10);
2848         }
2849
2850         /*
2851          * Legacy memcg will stall in page writeback so avoid forcibly
2852          * stalling in wait_iff_congested().
2853          */
2854         if (cgroup_reclaim(sc) && writeback_throttling_sane(sc) &&
2855             sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
2856                 set_memcg_congestion(pgdat, root, true);
2857
2858         /*
2859          * Stall direct reclaim for IO completions if underlying BDIs
2860          * and node is congested. Allow kswapd to continue until it
2861          * starts encountering unqueued dirty pages or cycling through
2862          * the LRU too quickly.
2863          */
2864         if (!sc->hibernation_mode && !current_is_kswapd() &&
2865             current_may_throttle() && pgdat_memcg_congested(pgdat, root))
2866                 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
2867
2868         if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
2869                                     sc))
2870                 goto again;
2871
2872         /*
2873          * Kswapd gives up on balancing particular nodes after too
2874          * many failures to reclaim anything from them and goes to
2875          * sleep. On reclaim progress, reset the failure counter. A
2876          * successful direct reclaim run will revive a dormant kswapd.
2877          */
2878         if (reclaimable)
2879                 pgdat->kswapd_failures = 0;
2880
2881         return reclaimable;
2882 }
2883
2884 /*
2885  * Returns true if compaction should go ahead for a costly-order request, or
2886  * the allocation would already succeed without compaction. Return false if we
2887  * should reclaim first.
2888  */
2889 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
2890 {
2891         unsigned long watermark;
2892         enum compact_result suitable;
2893
2894         suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
2895         if (suitable == COMPACT_SUCCESS)
2896                 /* Allocation should succeed already. Don't reclaim. */
2897                 return true;
2898         if (suitable == COMPACT_SKIPPED)
2899                 /* Compaction cannot yet proceed. Do reclaim. */
2900                 return false;
2901
2902         /*
2903          * Compaction is already possible, but it takes time to run and there
2904          * are potentially other callers using the pages just freed. So proceed
2905          * with reclaim to make a buffer of free pages available to give
2906          * compaction a reasonable chance of completing and allocating the page.
2907          * Note that we won't actually reclaim the whole buffer in one attempt
2908          * as the target watermark in should_continue_reclaim() is lower. But if
2909          * we are already above the high+gap watermark, don't reclaim at all.
2910          */
2911         watermark = high_wmark_pages(zone) + compact_gap(sc->order);
2912
2913         return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
2914 }
2915
2916 /*
2917  * This is the direct reclaim path, for page-allocating processes.  We only
2918  * try to reclaim pages from zones which will satisfy the caller's allocation
2919  * request.
2920  *
2921  * If a zone is deemed to be full of pinned pages then just give it a light
2922  * scan then give up on it.
2923  */
2924 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
2925 {
2926         struct zoneref *z;
2927         struct zone *zone;
2928         unsigned long nr_soft_reclaimed;
2929         unsigned long nr_soft_scanned;
2930         gfp_t orig_mask;
2931         pg_data_t *last_pgdat = NULL;
2932
2933         /*
2934          * If the number of buffer_heads in the machine exceeds the maximum
2935          * allowed level, force direct reclaim to scan the highmem zone as
2936          * highmem pages could be pinning lowmem pages storing buffer_heads
2937          */
2938         orig_mask = sc->gfp_mask;
2939         if (buffer_heads_over_limit) {
2940                 sc->gfp_mask |= __GFP_HIGHMEM;
2941                 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
2942         }
2943
2944         for_each_zone_zonelist_nodemask(zone, z, zonelist,
2945                                         sc->reclaim_idx, sc->nodemask) {
2946                 /*
2947                  * Take care memory controller reclaiming has small influence
2948                  * to global LRU.
2949                  */
2950                 if (!cgroup_reclaim(sc)) {
2951                         if (!cpuset_zone_allowed(zone,
2952                                                  GFP_KERNEL | __GFP_HARDWALL))
2953                                 continue;
2954
2955                         /*
2956                          * If we already have plenty of memory free for
2957                          * compaction in this zone, don't free any more.
2958                          * Even though compaction is invoked for any
2959                          * non-zero order, only frequent costly order
2960                          * reclamation is disruptive enough to become a
2961                          * noticeable problem, like transparent huge
2962                          * page allocations.
2963                          */
2964                         if (IS_ENABLED(CONFIG_COMPACTION) &&
2965                             sc->order > PAGE_ALLOC_COSTLY_ORDER &&
2966                             compaction_ready(zone, sc)) {
2967                                 sc->compaction_ready = true;
2968                                 continue;
2969                         }
2970
2971                         /*
2972                          * Shrink each node in the zonelist once. If the
2973                          * zonelist is ordered by zone (not the default) then a
2974                          * node may be shrunk multiple times but in that case
2975                          * the user prefers lower zones being preserved.
2976                          */
2977                         if (zone->zone_pgdat == last_pgdat)
2978                                 continue;
2979
2980                         /*
2981                          * This steals pages from memory cgroups over softlimit
2982                          * and returns the number of reclaimed pages and
2983                          * scanned pages. This works for global memory pressure
2984                          * and balancing, not for a memcg's limit.
2985                          */
2986                         nr_soft_scanned = 0;
2987                         nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
2988                                                 sc->order, sc->gfp_mask,
2989                                                 &nr_soft_scanned);
2990                         sc->nr_reclaimed += nr_soft_reclaimed;
2991                         sc->nr_scanned += nr_soft_scanned;
2992                         /* need some check for avoid more shrink_zone() */
2993                 }
2994
2995                 /* See comment about same check for global reclaim above */
2996                 if (zone->zone_pgdat == last_pgdat)
2997                         continue;
2998                 last_pgdat = zone->zone_pgdat;
2999                 shrink_node(zone->zone_pgdat, sc);
3000         }
3001
3002         /*
3003          * Restore to original mask to avoid the impact on the caller if we
3004          * promoted it to __GFP_HIGHMEM.
3005          */
3006         sc->gfp_mask = orig_mask;
3007 }
3008
3009 static void snapshot_refaults(struct mem_cgroup *root_memcg, pg_data_t *pgdat)
3010 {
3011         struct mem_cgroup *memcg;
3012
3013         memcg = mem_cgroup_iter(root_memcg, NULL, NULL);
3014         do {
3015                 unsigned long refaults;
3016                 struct lruvec *lruvec;
3017
3018                 lruvec = mem_cgroup_lruvec(memcg, pgdat);
3019                 refaults = lruvec_page_state_local(lruvec, WORKINGSET_ACTIVATE);
3020                 lruvec->refaults = refaults;
3021         } while ((memcg = mem_cgroup_iter(root_memcg, memcg, NULL)));
3022 }
3023
3024 /*
3025  * This is the main entry point to direct page reclaim.
3026  *
3027  * If a full scan of the inactive list fails to free enough memory then we
3028  * are "out of memory" and something needs to be killed.
3029  *
3030  * If the caller is !__GFP_FS then the probability of a failure is reasonably
3031  * high - the zone may be full of dirty or under-writeback pages, which this
3032  * caller can't do much about.  We kick the writeback threads and take explicit
3033  * naps in the hope that some of these pages can be written.  But if the
3034  * allocating task holds filesystem locks which prevent writeout this might not
3035  * work, and the allocation attempt will fail.
3036  *
3037  * returns:     0, if no pages reclaimed
3038  *              else, the number of pages reclaimed
3039  */
3040 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
3041                                           struct scan_control *sc)
3042 {
3043         int initial_priority = sc->priority;
3044         pg_data_t *last_pgdat;
3045         struct zoneref *z;
3046         struct zone *zone;
3047 retry:
3048         delayacct_freepages_start();
3049
3050         if (!cgroup_reclaim(sc))
3051                 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
3052
3053         do {
3054                 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
3055                                 sc->priority);
3056                 sc->nr_scanned = 0;
3057                 shrink_zones(zonelist, sc);
3058
3059                 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
3060                         break;
3061
3062                 if (sc->compaction_ready)
3063                         break;
3064
3065                 /*
3066                  * If we're getting trouble reclaiming, start doing
3067                  * writepage even in laptop mode.
3068                  */
3069                 if (sc->priority < DEF_PRIORITY - 2)
3070                         sc->may_writepage = 1;
3071         } while (--sc->priority >= 0);
3072
3073         last_pgdat = NULL;
3074         for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
3075                                         sc->nodemask) {
3076                 if (zone->zone_pgdat == last_pgdat)
3077                         continue;
3078                 last_pgdat = zone->zone_pgdat;
3079                 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
3080                 set_memcg_congestion(last_pgdat, sc->target_mem_cgroup, false);
3081         }
3082
3083         delayacct_freepages_end();
3084
3085         if (sc->nr_reclaimed)
3086                 return sc->nr_reclaimed;
3087
3088         /* Aborted reclaim to try compaction? don't OOM, then */
3089         if (sc->compaction_ready)
3090                 return 1;
3091
3092         /* Untapped cgroup reserves?  Don't OOM, retry. */
3093         if (sc->memcg_low_skipped) {
3094                 sc->priority = initial_priority;
3095                 sc->memcg_low_reclaim = 1;
3096                 sc->memcg_low_skipped = 0;
3097                 goto retry;
3098         }
3099
3100         return 0;
3101 }
3102
3103 static bool allow_direct_reclaim(pg_data_t *pgdat)
3104 {
3105         struct zone *zone;
3106         unsigned long pfmemalloc_reserve = 0;
3107         unsigned long free_pages = 0;
3108         int i;
3109         bool wmark_ok;
3110
3111         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3112                 return true;
3113
3114         for (i = 0; i <= ZONE_NORMAL; i++) {
3115                 zone = &pgdat->node_zones[i];
3116                 if (!managed_zone(zone))
3117                         continue;
3118
3119                 if (!zone_reclaimable_pages(zone))
3120                         continue;
3121
3122                 pfmemalloc_reserve += min_wmark_pages(zone);
3123                 free_pages += zone_page_state(zone, NR_FREE_PAGES);
3124         }
3125
3126         /* If there are no reserves (unexpected config) then do not throttle */
3127         if (!pfmemalloc_reserve)
3128                 return true;
3129
3130         wmark_ok = free_pages > pfmemalloc_reserve / 2;
3131
3132         /* kswapd must be awake if processes are being throttled */
3133         if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
3134                 pgdat->kswapd_classzone_idx = min(pgdat->kswapd_classzone_idx,
3135                                                 (enum zone_type)ZONE_NORMAL);
3136                 wake_up_interruptible(&pgdat->kswapd_wait);
3137         }
3138
3139         return wmark_ok;
3140 }
3141
3142 /*
3143  * Throttle direct reclaimers if backing storage is backed by the network
3144  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
3145  * depleted. kswapd will continue to make progress and wake the processes
3146  * when the low watermark is reached.
3147  *
3148  * Returns true if a fatal signal was delivered during throttling. If this
3149  * happens, the page allocator should not consider triggering the OOM killer.
3150  */
3151 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
3152                                         nodemask_t *nodemask)
3153 {
3154         struct zoneref *z;
3155         struct zone *zone;
3156         pg_data_t *pgdat = NULL;
3157
3158         /*
3159          * Kernel threads should not be throttled as they may be indirectly
3160          * responsible for cleaning pages necessary for reclaim to make forward
3161          * progress. kjournald for example may enter direct reclaim while
3162          * committing a transaction where throttling it could forcing other
3163          * processes to block on log_wait_commit().
3164          */
3165         if (current->flags & PF_KTHREAD)
3166                 goto out;
3167
3168         /*
3169          * If a fatal signal is pending, this process should not throttle.
3170          * It should return quickly so it can exit and free its memory
3171          */
3172         if (fatal_signal_pending(current))
3173                 goto out;
3174
3175         /*
3176          * Check if the pfmemalloc reserves are ok by finding the first node
3177          * with a usable ZONE_NORMAL or lower zone. The expectation is that
3178          * GFP_KERNEL will be required for allocating network buffers when
3179          * swapping over the network so ZONE_HIGHMEM is unusable.
3180          *
3181          * Throttling is based on the first usable node and throttled processes
3182          * wait on a queue until kswapd makes progress and wakes them. There
3183          * is an affinity then between processes waking up and where reclaim
3184          * progress has been made assuming the process wakes on the same node.
3185          * More importantly, processes running on remote nodes will not compete
3186          * for remote pfmemalloc reserves and processes on different nodes
3187          * should make reasonable progress.
3188          */
3189         for_each_zone_zonelist_nodemask(zone, z, zonelist,
3190                                         gfp_zone(gfp_mask), nodemask) {
3191                 if (zone_idx(zone) > ZONE_NORMAL)
3192                         continue;
3193
3194                 /* Throttle based on the first usable node */
3195                 pgdat = zone->zone_pgdat;
3196                 if (allow_direct_reclaim(pgdat))
3197                         goto out;
3198                 break;
3199         }
3200
3201         /* If no zone was usable by the allocation flags then do not throttle */
3202         if (!pgdat)
3203                 goto out;
3204
3205         /* Account for the throttling */
3206         count_vm_event(PGSCAN_DIRECT_THROTTLE);
3207
3208         /*
3209          * If the caller cannot enter the filesystem, it's possible that it
3210          * is due to the caller holding an FS lock or performing a journal
3211          * transaction in the case of a filesystem like ext[3|4]. In this case,
3212          * it is not safe to block on pfmemalloc_wait as kswapd could be
3213          * blocked waiting on the same lock. Instead, throttle for up to a
3214          * second before continuing.
3215          */
3216         if (!(gfp_mask & __GFP_FS)) {
3217                 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
3218                         allow_direct_reclaim(pgdat), HZ);
3219
3220                 goto check_pending;
3221         }
3222
3223         /* Throttle until kswapd wakes the process */
3224         wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
3225                 allow_direct_reclaim(pgdat));
3226
3227 check_pending:
3228         if (fatal_signal_pending(current))
3229                 return true;
3230
3231 out:
3232         return false;
3233 }
3234
3235 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
3236                                 gfp_t gfp_mask, nodemask_t *nodemask)
3237 {
3238         unsigned long nr_reclaimed;
3239         struct scan_control sc = {
3240                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3241                 .gfp_mask = current_gfp_context(gfp_mask),
3242                 .reclaim_idx = gfp_zone(gfp_mask),
3243                 .order = order,
3244                 .nodemask = nodemask,
3245                 .priority = DEF_PRIORITY,
3246                 .may_writepage = !laptop_mode,
3247                 .may_unmap = 1,
3248                 .may_swap = 1,
3249         };
3250
3251         /*
3252          * scan_control uses s8 fields for order, priority, and reclaim_idx.
3253          * Confirm they are large enough for max values.
3254          */
3255         BUILD_BUG_ON(MAX_ORDER > S8_MAX);
3256         BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
3257         BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
3258
3259         /*
3260          * Do not enter reclaim if fatal signal was delivered while throttled.
3261          * 1 is returned so that the page allocator does not OOM kill at this
3262          * point.
3263          */
3264         if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
3265                 return 1;
3266
3267         set_task_reclaim_state(current, &sc.reclaim_state);
3268         trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
3269
3270         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3271
3272         trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
3273         set_task_reclaim_state(current, NULL);
3274
3275         return nr_reclaimed;
3276 }
3277
3278 #ifdef CONFIG_MEMCG
3279
3280 /* Only used by soft limit reclaim. Do not reuse for anything else. */
3281 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
3282                                                 gfp_t gfp_mask, bool noswap,
3283                                                 pg_data_t *pgdat,
3284                                                 unsigned long *nr_scanned)
3285 {
3286         struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3287         struct scan_control sc = {
3288                 .nr_to_reclaim = SWAP_CLUSTER_MAX,
3289                 .target_mem_cgroup = memcg,
3290                 .may_writepage = !laptop_mode,
3291                 .may_unmap = 1,
3292                 .reclaim_idx = MAX_NR_ZONES - 1,
3293                 .may_swap = !noswap,
3294         };
3295
3296         WARN_ON_ONCE(!current->reclaim_state);
3297
3298         sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
3299                         (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
3300
3301         trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
3302                                                       sc.gfp_mask);
3303
3304         /*
3305          * NOTE: Although we can get the priority field, using it
3306          * here is not a good idea, since it limits the pages we can scan.
3307          * if we don't reclaim here, the shrink_node from balance_pgdat
3308          * will pick up pages from other mem cgroup's as well. We hack
3309          * the priority and make it zero.
3310          */
3311         shrink_lruvec(lruvec, &sc);
3312
3313         trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
3314
3315         *nr_scanned = sc.nr_scanned;
3316
3317         return sc.nr_reclaimed;
3318 }
3319
3320 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
3321                                            unsigned long nr_pages,
3322                                            gfp_t gfp_mask,
3323                                            bool may_swap)
3324 {
3325         struct zonelist *zonelist;
3326         unsigned long nr_reclaimed;
3327         unsigned long pflags;
3328         int nid;
3329         unsigned int noreclaim_flag;
3330         struct scan_control sc = {
3331                 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
3332                 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
3333                                 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
3334                 .reclaim_idx = MAX_NR_ZONES - 1,
3335                 .target_mem_cgroup = memcg,
3336                 .priority = DEF_PRIORITY,
3337                 .may_writepage = !laptop_mode,
3338                 .may_unmap = 1,
3339                 .may_swap = may_swap,
3340         };
3341
3342         set_task_reclaim_state(current, &sc.reclaim_state);
3343         /*
3344          * Unlike direct reclaim via alloc_pages(), memcg's reclaim doesn't
3345          * take care of from where we get pages. So the node where we start the
3346          * scan does not need to be the current node.
3347          */
3348         nid = mem_cgroup_select_victim_node(memcg);
3349
3350         zonelist = &NODE_DATA(nid)->node_zonelists[ZONELIST_FALLBACK];
3351
3352         trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
3353
3354         psi_memstall_enter(&pflags);
3355         noreclaim_flag = memalloc_noreclaim_save();
3356
3357         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
3358
3359         memalloc_noreclaim_restore(noreclaim_flag);
3360         psi_memstall_leave(&pflags);
3361
3362         trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
3363         set_task_reclaim_state(current, NULL);
3364
3365         return nr_reclaimed;
3366 }
3367 #endif
3368
3369 static void age_active_anon(struct pglist_data *pgdat,
3370                                 struct scan_control *sc)
3371 {
3372         struct mem_cgroup *memcg;
3373
3374         if (!total_swap_pages)
3375                 return;
3376
3377         memcg = mem_cgroup_iter(NULL, NULL, NULL);
3378         do {
3379                 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3380
3381                 if (inactive_list_is_low(lruvec, false, sc, true))
3382                         shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
3383                                            sc, LRU_ACTIVE_ANON);
3384
3385                 memcg = mem_cgroup_iter(NULL, memcg, NULL);
3386         } while (memcg);
3387 }
3388
3389 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int classzone_idx)
3390 {
3391         int i;
3392         struct zone *zone;
3393
3394         /*
3395          * Check for watermark boosts top-down as the higher zones
3396          * are more likely to be boosted. Both watermarks and boosts
3397          * should not be checked at the time time as reclaim would
3398          * start prematurely when there is no boosting and a lower
3399          * zone is balanced.
3400          */
3401         for (i = classzone_idx; i >= 0; i--) {
3402                 zone = pgdat->node_zones + i;
3403                 if (!managed_zone(zone))
3404                         continue;
3405
3406                 if (zone->watermark_boost)
3407                         return true;
3408         }
3409
3410         return false;
3411 }
3412
3413 /*
3414  * Returns true if there is an eligible zone balanced for the request order
3415  * and classzone_idx
3416  */
3417 static bool pgdat_balanced(pg_data_t *pgdat, int order, int classzone_idx)
3418 {
3419         int i;
3420         unsigned long mark = -1;
3421         struct zone *zone;
3422
3423         /*
3424          * Check watermarks bottom-up as lower zones are more likely to
3425          * meet watermarks.
3426          */
3427         for (i = 0; i <= classzone_idx; i++) {
3428                 zone = pgdat->node_zones + i;
3429
3430                 if (!managed_zone(zone))
3431                         continue;
3432
3433                 mark = high_wmark_pages(zone);
3434                 if (zone_watermark_ok_safe(zone, order, mark, classzone_idx))
3435                         return true;
3436         }
3437
3438         /*
3439          * If a node has no populated zone within classzone_idx, it does not
3440          * need balancing by definition. This can happen if a zone-restricted
3441          * allocation tries to wake a remote kswapd.
3442          */
3443         if (mark == -1)
3444                 return true;
3445
3446         return false;
3447 }
3448
3449 /* Clear pgdat state for congested, dirty or under writeback. */
3450 static void clear_pgdat_congested(pg_data_t *pgdat)
3451 {
3452         clear_bit(PGDAT_CONGESTED, &pgdat->flags);
3453         clear_bit(PGDAT_DIRTY, &pgdat->flags);
3454         clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
3455 }
3456
3457 /*
3458  * Prepare kswapd for sleeping. This verifies that there are no processes
3459  * waiting in throttle_direct_reclaim() and that watermarks have been met.
3460  *
3461  * Returns true if kswapd is ready to sleep
3462  */
3463 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order, int classzone_idx)
3464 {
3465         /*
3466          * The throttled processes are normally woken up in balance_pgdat() as
3467          * soon as allow_direct_reclaim() is true. But there is a potential
3468          * race between when kswapd checks the watermarks and a process gets
3469          * throttled. There is also a potential race if processes get
3470          * throttled, kswapd wakes, a large process exits thereby balancing the
3471          * zones, which causes kswapd to exit balance_pgdat() before reaching
3472          * the wake up checks. If kswapd is going to sleep, no process should
3473          * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
3474          * the wake up is premature, processes will wake kswapd and get
3475          * throttled again. The difference from wake ups in balance_pgdat() is
3476          * that here we are under prepare_to_wait().
3477          */
3478         if (waitqueue_active(&pgdat->pfmemalloc_wait))
3479                 wake_up_all(&pgdat->pfmemalloc_wait);
3480
3481         /* Hopeless node, leave it to direct reclaim */
3482         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
3483                 return true;
3484
3485         if (pgdat_balanced(pgdat, order, classzone_idx)) {
3486                 clear_pgdat_congested(pgdat);
3487                 return true;
3488         }
3489
3490         return false;
3491 }
3492
3493 /*
3494  * kswapd shrinks a node of pages that are at or below the highest usable
3495  * zone that is currently unbalanced.
3496  *
3497  * Returns true if kswapd scanned at least the requested number of pages to
3498  * reclaim or if the lack of progress was due to pages under writeback.
3499  * This is used to determine if the scanning priority needs to be raised.
3500  */
3501 static bool kswapd_shrink_node(pg_data_t *pgdat,
3502                                struct scan_control *sc)
3503 {
3504         struct zone *zone;
3505         int z;
3506
3507         /* Reclaim a number of pages proportional to the number of zones */
3508         sc->nr_to_reclaim = 0;
3509         for (z = 0; z <= sc->reclaim_idx; z++) {
3510                 zone = pgdat->node_zones + z;
3511                 if (!managed_zone(zone))
3512                         continue;
3513
3514                 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
3515         }
3516
3517         /*
3518          * Historically care was taken to put equal pressure on all zones but
3519          * now pressure is applied based on node LRU order.
3520          */
3521         shrink_node(pgdat, sc);
3522
3523         /*
3524          * Fragmentation may mean that the system cannot be rebalanced for
3525          * high-order allocations. If twice the allocation size has been
3526          * reclaimed then recheck watermarks only at order-0 to prevent
3527          * excessive reclaim. Assume that a process requested a high-order
3528          * can direct reclaim/compact.
3529          */
3530         if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
3531                 sc->order = 0;
3532
3533         return sc->nr_scanned >= sc->nr_to_reclaim;
3534 }
3535
3536 /*
3537  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
3538  * that are eligible for use by the caller until at least one zone is
3539  * balanced.
3540  *
3541  * Returns the order kswapd finished reclaiming at.
3542  *
3543  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
3544  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
3545  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
3546  * or lower is eligible for reclaim until at least one usable zone is
3547  * balanced.
3548  */
3549 static int balance_pgdat(pg_data_t *pgdat, int order, int classzone_idx)
3550 {
3551         int i;
3552         unsigned long nr_soft_reclaimed;
3553         unsigned long nr_soft_scanned;
3554         unsigned long pflags;
3555         unsigned long nr_boost_reclaim;
3556         unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
3557         bool boosted;
3558         struct zone *zone;
3559         struct scan_control sc = {
3560                 .gfp_mask = GFP_KERNEL,
3561                 .order = order,
3562                 .may_unmap = 1,
3563         };
3564
3565         set_task_reclaim_state(current, &sc.reclaim_state);
3566         psi_memstall_enter(&pflags);
3567         __fs_reclaim_acquire();
3568
3569         count_vm_event(PAGEOUTRUN);
3570
3571         /*
3572          * Account for the reclaim boost. Note that the zone boost is left in
3573          * place so that parallel allocations that are near the watermark will
3574          * stall or direct reclaim until kswapd is finished.
3575          */
3576         nr_boost_reclaim = 0;
3577         for (i = 0; i <= classzone_idx; i++) {
3578                 zone = pgdat->node_zones + i;
3579                 if (!managed_zone(zone))
3580                         continue;
3581
3582                 nr_boost_reclaim += zone->watermark_boost;
3583                 zone_boosts[i] = zone->watermark_boost;
3584         }
3585         boosted = nr_boost_reclaim;
3586
3587 restart:
3588         sc.priority = DEF_PRIORITY;
3589         do {
3590                 unsigned long nr_reclaimed = sc.nr_reclaimed;
3591                 bool raise_priority = true;
3592                 bool balanced;
3593                 bool ret;
3594
3595                 sc.reclaim_idx = classzone_idx;
3596
3597                 /*
3598                  * If the number of buffer_heads exceeds the maximum allowed
3599                  * then consider reclaiming from all zones. This has a dual
3600                  * purpose -- on 64-bit systems it is expected that
3601                  * buffer_heads are stripped during active rotation. On 32-bit
3602                  * systems, highmem pages can pin lowmem memory and shrinking
3603                  * buffers can relieve lowmem pressure. Reclaim may still not
3604                  * go ahead if all eligible zones for the original allocation
3605                  * request are balanced to avoid excessive reclaim from kswapd.
3606                  */
3607                 if (buffer_heads_over_limit) {
3608                         for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
3609                                 zone = pgdat->node_zones + i;
3610                                 if (!managed_zone(zone))
3611                                         continue;
3612
3613                                 sc.reclaim_idx = i;
3614                                 break;
3615                         }
3616                 }
3617
3618                 /*
3619                  * If the pgdat is imbalanced then ignore boosting and preserve
3620                  * the watermarks for a later time and restart. Note that the
3621                  * zone watermarks will be still reset at the end of balancing
3622                  * on the grounds that the normal reclaim should be enough to
3623                  * re-evaluate if boosting is required when kswapd next wakes.
3624                  */
3625                 balanced = pgdat_balanced(pgdat, sc.order, classzone_idx);
3626                 if (!balanced && nr_boost_reclaim) {
3627                         nr_boost_reclaim = 0;
3628                         goto restart;
3629                 }
3630
3631                 /*
3632                  * If boosting is not active then only reclaim if there are no
3633                  * eligible zones. Note that sc.reclaim_idx is not used as
3634                  * buffer_heads_over_limit may have adjusted it.
3635                  */
3636                 if (!nr_boost_reclaim && balanced)
3637                         goto out;
3638
3639                 /* Limit the priority of boosting to avoid reclaim writeback */
3640                 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
3641                         raise_priority = false;
3642
3643                 /*
3644                  * Do not writeback or swap pages for boosted reclaim. The
3645                  * intent is to relieve pressure not issue sub-optimal IO
3646                  * from reclaim context. If no pages are reclaimed, the
3647                  * reclaim will be aborted.
3648                  */
3649                 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
3650                 sc.may_swap = !nr_boost_reclaim;
3651
3652                 /*
3653                  * Do some background aging of the anon list, to give
3654                  * pages a chance to be referenced before reclaiming. All
3655                  * pages are rotated regardless of classzone as this is
3656                  * about consistent aging.
3657                  */
3658                 age_active_anon(pgdat, &sc);
3659
3660                 /*
3661                  * If we're getting trouble reclaiming, start doing writepage
3662                  * even in laptop mode.
3663                  */
3664                 if (sc.priority < DEF_PRIORITY - 2)
3665                         sc.may_writepage = 1;
3666
3667                 /* Call soft limit reclaim before calling shrink_node. */
3668                 sc.nr_scanned = 0;
3669                 nr_soft_scanned = 0;
3670                 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
3671                                                 sc.gfp_mask, &nr_soft_scanned);
3672                 sc.nr_reclaimed += nr_soft_reclaimed;
3673
3674                 /*
3675                  * There should be no need to raise the scanning priority if
3676                  * enough pages are already being scanned that that high
3677                  * watermark would be met at 100% efficiency.
3678                  */
3679                 if (kswapd_shrink_node(pgdat, &sc))
3680                         raise_priority = false;
3681
3682                 /*
3683                  * If the low watermark is met there is no need for processes
3684                  * to be throttled on pfmemalloc_wait as they should not be
3685                  * able to safely make forward progress. Wake them
3686                  */
3687                 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
3688                                 allow_direct_reclaim(pgdat))
3689                         wake_up_all(&pgdat->pfmemalloc_wait);
3690
3691                 /* Check if kswapd should be suspending */
3692                 __fs_reclaim_release();
3693                 ret = try_to_freeze();
3694                 __fs_reclaim_acquire();
3695                 if (ret || kthread_should_stop())
3696                         break;
3697
3698                 /*
3699                  * Raise priority if scanning rate is too low or there was no
3700                  * progress in reclaiming pages
3701                  */
3702                 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
3703                 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
3704
3705                 /*
3706                  * If reclaim made no progress for a boost, stop reclaim as
3707                  * IO cannot be queued and it could be an infinite loop in
3708                  * extreme circumstances.
3709                  */
3710                 if (nr_boost_reclaim && !nr_reclaimed)
3711                         break;
3712
3713                 if (raise_priority || !nr_reclaimed)
3714                         sc.priority--;
3715         } while (sc.priority >= 1);
3716
3717         if (!sc.nr_reclaimed)
3718                 pgdat->kswapd_failures++;
3719
3720 out:
3721         /* If reclaim was boosted, account for the reclaim done in this pass */
3722         if (boosted) {
3723                 unsigned long flags;
3724
3725                 for (i = 0; i <= classzone_idx; i++) {
3726                         if (!zone_boosts[i])
3727                                 continue;
3728
3729                         /* Increments are under the zone lock */
3730                         zone = pgdat->node_zones + i;
3731                         spin_lock_irqsave(&zone->lock, flags);
3732                         zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
3733                         spin_unlock_irqrestore(&zone->lock, flags);
3734                 }
3735
3736                 /*
3737                  * As there is now likely space, wakeup kcompact to defragment
3738                  * pageblocks.
3739                  */
3740                 wakeup_kcompactd(pgdat, pageblock_order, classzone_idx);
3741         }
3742
3743         snapshot_refaults(NULL, pgdat);
3744         __fs_reclaim_release();
3745         psi_memstall_leave(&pflags);
3746         set_task_reclaim_state(current, NULL);
3747
3748         /*
3749          * Return the order kswapd stopped reclaiming at as
3750          * prepare_kswapd_sleep() takes it into account. If another caller
3751          * entered the allocator slow path while kswapd was awake, order will
3752          * remain at the higher level.
3753          */
3754         return sc.order;
3755 }
3756
3757 /*
3758  * The pgdat->kswapd_classzone_idx is used to pass the highest zone index to be
3759  * reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is not
3760  * a valid index then either kswapd runs for first time or kswapd couldn't sleep
3761  * after previous reclaim attempt (node is still unbalanced). In that case
3762  * return the zone index of the previous kswapd reclaim cycle.
3763  */
3764 static enum zone_type kswapd_classzone_idx(pg_data_t *pgdat,
3765                                            enum zone_type prev_classzone_idx)
3766 {
3767         if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3768                 return prev_classzone_idx;
3769         return pgdat->kswapd_classzone_idx;
3770 }
3771
3772 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
3773                                 unsigned int classzone_idx)
3774 {
3775         long remaining = 0;
3776         DEFINE_WAIT(wait);
3777
3778         if (freezing(current) || kthread_should_stop())
3779                 return;
3780
3781         prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3782
3783         /*
3784          * Try to sleep for a short interval. Note that kcompactd will only be
3785          * woken if it is possible to sleep for a short interval. This is
3786          * deliberate on the assumption that if reclaim cannot keep an
3787          * eligible zone balanced that it's also unlikely that compaction will
3788          * succeed.
3789          */
3790         if (prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3791                 /*
3792                  * Compaction records what page blocks it recently failed to
3793                  * isolate pages from and skips them in the future scanning.
3794                  * When kswapd is going to sleep, it is reasonable to assume
3795                  * that pages and compaction may succeed so reset the cache.
3796                  */
3797                 reset_isolation_suitable(pgdat);
3798
3799                 /*
3800                  * We have freed the memory, now we should compact it to make
3801                  * allocation of the requested order possible.
3802                  */
3803                 wakeup_kcompactd(pgdat, alloc_order, classzone_idx);
3804
3805                 remaining = schedule_timeout(HZ/10);
3806
3807                 /*
3808                  * If woken prematurely then reset kswapd_classzone_idx and
3809                  * order. The values will either be from a wakeup request or
3810                  * the previous request that slept prematurely.
3811                  */
3812                 if (remaining) {
3813                         pgdat->kswapd_classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3814                         pgdat->kswapd_order = max(pgdat->kswapd_order, reclaim_order);
3815                 }
3816
3817                 finish_wait(&pgdat->kswapd_wait, &wait);
3818                 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
3819         }
3820
3821         /*
3822          * After a short sleep, check if it was a premature sleep. If not, then
3823          * go fully to sleep until explicitly woken up.
3824          */
3825         if (!remaining &&
3826             prepare_kswapd_sleep(pgdat, reclaim_order, classzone_idx)) {
3827                 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
3828
3829                 /*
3830                  * vmstat counters are not perfectly accurate and the estimated
3831                  * value for counters such as NR_FREE_PAGES can deviate from the
3832                  * true value by nr_online_cpus * threshold. To avoid the zone
3833                  * watermarks being breached while under pressure, we reduce the
3834                  * per-cpu vmstat threshold while kswapd is awake and restore
3835                  * them before going back to sleep.
3836                  */
3837                 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
3838
3839                 if (!kthread_should_stop())
3840                         schedule();
3841
3842                 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
3843         } else {
3844                 if (remaining)
3845                         count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
3846                 else
3847                         count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
3848         }
3849         finish_wait(&pgdat->kswapd_wait, &wait);
3850 }
3851
3852 /*
3853  * The background pageout daemon, started as a kernel thread
3854  * from the init process.
3855  *
3856  * This basically trickles out pages so that we have _some_
3857  * free memory available even if there is no other activity
3858  * that frees anything up. This is needed for things like routing
3859  * etc, where we otherwise might have all activity going on in
3860  * asynchronous contexts that cannot page things out.
3861  *
3862  * If there are applications that are active memory-allocators
3863  * (most normal use), this basically shouldn't matter.
3864  */
3865 static int kswapd(void *p)
3866 {
3867         unsigned int alloc_order, reclaim_order;
3868         unsigned int classzone_idx = MAX_NR_ZONES - 1;
3869         pg_data_t *pgdat = (pg_data_t*)p;
3870         struct task_struct *tsk = current;
3871         const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
3872
3873         if (!cpumask_empty(cpumask))
3874                 set_cpus_allowed_ptr(tsk, cpumask);
3875
3876         /*
3877          * Tell the memory management that we're a "memory allocator",
3878          * and that if we need more memory we should get access to it
3879          * regardless (see "__alloc_pages()"). "kswapd" should
3880          * never get caught in the normal page freeing logic.
3881          *
3882          * (Kswapd normally doesn't need memory anyway, but sometimes
3883          * you need a small amount of memory in order to be able to
3884          * page out something else, and this flag essentially protects
3885          * us from recursively trying to free more memory as we're
3886          * trying to free the first piece of memory in the first place).
3887          */
3888         tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
3889         set_freezable();
3890
3891         pgdat->kswapd_order = 0;
3892         pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
3893         for ( ; ; ) {
3894                 bool ret;
3895
3896                 alloc_order = reclaim_order = pgdat->kswapd_order;
3897                 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3898
3899 kswapd_try_sleep:
3900                 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
3901                                         classzone_idx);
3902
3903                 /* Read the new order and classzone_idx */
3904                 alloc_order = reclaim_order = pgdat->kswapd_order;
3905                 classzone_idx = kswapd_classzone_idx(pgdat, classzone_idx);
3906                 pgdat->kswapd_order = 0;
3907                 pgdat->kswapd_classzone_idx = MAX_NR_ZONES;
3908
3909                 ret = try_to_freeze();
3910                 if (kthread_should_stop())
3911                         break;
3912
3913                 /*
3914                  * We can speed up thawing tasks if we don't call balance_pgdat
3915                  * after returning from the refrigerator
3916                  */
3917                 if (ret)
3918                         continue;
3919
3920                 /*
3921                  * Reclaim begins at the requested order but if a high-order
3922                  * reclaim fails then kswapd falls back to reclaiming for
3923                  * order-0. If that happens, kswapd will consider sleeping
3924                  * for the order it finished reclaiming at (reclaim_order)
3925                  * but kcompactd is woken to compact for the original
3926                  * request (alloc_order).
3927                  */
3928                 trace_mm_vmscan_kswapd_wake(pgdat->node_id, classzone_idx,
3929                                                 alloc_order);
3930                 reclaim_order = balance_pgdat(pgdat, alloc_order, classzone_idx);
3931                 if (reclaim_order < alloc_order)
3932                         goto kswapd_try_sleep;
3933         }
3934
3935         tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
3936
3937         return 0;
3938 }
3939
3940 /*
3941  * A zone is low on free memory or too fragmented for high-order memory.  If
3942  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
3943  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
3944  * has failed or is not needed, still wake up kcompactd if only compaction is
3945  * needed.
3946  */
3947 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
3948                    enum zone_type classzone_idx)
3949 {
3950         pg_data_t *pgdat;
3951
3952         if (!managed_zone(zone))
3953                 return;
3954
3955         if (!cpuset_zone_allowed(zone, gfp_flags))
3956                 return;
3957         pgdat = zone->zone_pgdat;
3958
3959         if (pgdat->kswapd_classzone_idx == MAX_NR_ZONES)
3960                 pgdat->kswapd_classzone_idx = classzone_idx;
3961         else
3962                 pgdat->kswapd_classzone_idx = max(pgdat->kswapd_classzone_idx,
3963                                                   classzone_idx);
3964         pgdat->kswapd_order = max(pgdat->kswapd_order, order);
3965         if (!waitqueue_active(&pgdat->kswapd_wait))
3966                 return;
3967
3968         /* Hopeless node, leave it to direct reclaim if possible */
3969         if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
3970             (pgdat_balanced(pgdat, order, classzone_idx) &&
3971              !pgdat_watermark_boosted(pgdat, classzone_idx))) {
3972                 /*
3973                  * There may be plenty of free memory available, but it's too
3974                  * fragmented for high-order allocations.  Wake up kcompactd
3975                  * and rely on compaction_suitable() to determine if it's
3976                  * needed.  If it fails, it will defer subsequent attempts to
3977                  * ratelimit its work.
3978                  */
3979                 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
3980                         wakeup_kcompactd(pgdat, order, classzone_idx);
3981                 return;
3982         }
3983
3984         trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, classzone_idx, order,
3985                                       gfp_flags);
3986         wake_up_interruptible(&pgdat->kswapd_wait);
3987 }
3988
3989 #ifdef CONFIG_HIBERNATION
3990 /*
3991  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
3992  * freed pages.
3993  *
3994  * Rather than trying to age LRUs the aim is to preserve the overall
3995  * LRU order by reclaiming preferentially
3996  * inactive > active > active referenced > active mapped
3997  */
3998 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
3999 {
4000         struct scan_control sc = {
4001                 .nr_to_reclaim = nr_to_reclaim,
4002                 .gfp_mask = GFP_HIGHUSER_MOVABLE,
4003                 .reclaim_idx = MAX_NR_ZONES - 1,
4004                 .priority = DEF_PRIORITY,
4005                 .may_writepage = 1,
4006                 .may_unmap = 1,
4007                 .may_swap = 1,
4008                 .hibernation_mode = 1,
4009         };
4010         struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
4011         unsigned long nr_reclaimed;
4012         unsigned int noreclaim_flag;
4013
4014         fs_reclaim_acquire(sc.gfp_mask);
4015         noreclaim_flag = memalloc_noreclaim_save();
4016         set_task_reclaim_state(current, &sc.reclaim_state);
4017
4018         nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
4019
4020         set_task_reclaim_state(current, NULL);
4021         memalloc_noreclaim_restore(noreclaim_flag);
4022         fs_reclaim_release(sc.gfp_mask);
4023
4024         return nr_reclaimed;
4025 }
4026 #endif /* CONFIG_HIBERNATION */
4027
4028 /* It's optimal to keep kswapds on the same CPUs as their memory, but
4029    not required for correctness.  So if the last cpu in a node goes
4030    away, we get changed to run anywhere: as the first one comes back,
4031    restore their cpu bindings. */
4032 static int kswapd_cpu_online(unsigned int cpu)
4033 {
4034         int nid;
4035
4036         for_each_node_state(nid, N_MEMORY) {
4037                 pg_data_t *pgdat = NODE_DATA(nid);
4038                 const struct cpumask *mask;
4039
4040                 mask = cpumask_of_node(pgdat->node_id);
4041
4042                 if (cpumask_any_and(cpu_online_mask, mask) < nr_cpu_ids)
4043                         /* One of our CPUs online: restore mask */
4044                         set_cpus_allowed_ptr(pgdat->kswapd, mask);
4045         }
4046         return 0;
4047 }
4048
4049 /*
4050  * This kswapd start function will be called by init and node-hot-add.
4051  * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
4052  */
4053 int kswapd_run(int nid)
4054 {
4055         pg_data_t *pgdat = NODE_DATA(nid);
4056         int ret = 0;
4057
4058         if (pgdat->kswapd)
4059                 return 0;
4060
4061         pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
4062         if (IS_ERR(pgdat->kswapd)) {
4063                 /* failure at boot is fatal */
4064                 BUG_ON(system_state < SYSTEM_RUNNING);
4065                 pr_err("Failed to start kswapd on node %d\n", nid);
4066                 ret = PTR_ERR(pgdat->kswapd);
4067                 pgdat->kswapd = NULL;
4068         }
4069         return ret;
4070 }
4071
4072 /*
4073  * Called by memory hotplug when all memory in a node is offlined.  Caller must
4074  * hold mem_hotplug_begin/end().
4075  */
4076 void kswapd_stop(int nid)
4077 {
4078         struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
4079
4080         if (kswapd) {
4081                 kthread_stop(kswapd);
4082                 NODE_DATA(nid)->kswapd = NULL;
4083         }
4084 }
4085
4086 static int __init kswapd_init(void)
4087 {
4088         int nid, ret;
4089
4090         swap_setup();
4091         for_each_node_state(nid, N_MEMORY)
4092                 kswapd_run(nid);
4093         ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
4094                                         "mm/vmscan:online", kswapd_cpu_online,
4095                                         NULL);
4096         WARN_ON(ret < 0);
4097         return 0;
4098 }
4099
4100 module_init(kswapd_init)
4101
4102 #ifdef CONFIG_NUMA
4103 /*
4104  * Node reclaim mode
4105  *
4106  * If non-zero call node_reclaim when the number of free pages falls below
4107  * the watermarks.
4108  */
4109 int node_reclaim_mode __read_mostly;
4110
4111 #define RECLAIM_OFF 0
4112 #define RECLAIM_ZONE (1<<0)     /* Run shrink_inactive_list on the zone */
4113 #define RECLAIM_WRITE (1<<1)    /* Writeout pages during reclaim */
4114 #define RECLAIM_UNMAP (1<<2)    /* Unmap pages during reclaim */
4115
4116 /*
4117  * Priority for NODE_RECLAIM. This determines the fraction of pages
4118  * of a node considered for each zone_reclaim. 4 scans 1/16th of
4119  * a zone.
4120  */
4121 #define NODE_RECLAIM_PRIORITY 4
4122
4123 /*
4124  * Percentage of pages in a zone that must be unmapped for node_reclaim to
4125  * occur.
4126  */
4127 int sysctl_min_unmapped_ratio = 1;
4128
4129 /*
4130  * If the number of slab pages in a zone grows beyond this percentage then
4131  * slab reclaim needs to occur.
4132  */
4133 int sysctl_min_slab_ratio = 5;
4134
4135 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
4136 {
4137         unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
4138         unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
4139                 node_page_state(pgdat, NR_ACTIVE_FILE);
4140
4141         /*
4142          * It's possible for there to be more file mapped pages than
4143          * accounted for by the pages on the file LRU lists because
4144          * tmpfs pages accounted for as ANON can also be FILE_MAPPED
4145          */
4146         return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
4147 }
4148
4149 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
4150 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
4151 {
4152         unsigned long nr_pagecache_reclaimable;
4153         unsigned long delta = 0;
4154
4155         /*
4156          * If RECLAIM_UNMAP is set, then all file pages are considered
4157          * potentially reclaimable. Otherwise, we have to worry about
4158          * pages like swapcache and node_unmapped_file_pages() provides
4159          * a better estimate
4160          */
4161         if (node_reclaim_mode & RECLAIM_UNMAP)
4162                 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
4163         else
4164                 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
4165
4166         /* If we can't clean pages, remove dirty pages from consideration */
4167         if (!(node_reclaim_mode & RECLAIM_WRITE))
4168                 delta += node_page_state(pgdat, NR_FILE_DIRTY);
4169
4170         /* Watch for any possible underflows due to delta */
4171         if (unlikely(delta > nr_pagecache_reclaimable))
4172                 delta = nr_pagecache_reclaimable;
4173
4174         return nr_pagecache_reclaimable - delta;
4175 }
4176
4177 /*
4178  * Try to free up some pages from this node through reclaim.
4179  */
4180 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4181 {
4182         /* Minimum pages needed in order to stay on node */
4183         const unsigned long nr_pages = 1 << order;
4184         struct task_struct *p = current;
4185         unsigned int noreclaim_flag;
4186         struct scan_control sc = {
4187                 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
4188                 .gfp_mask = current_gfp_context(gfp_mask),
4189                 .order = order,
4190                 .priority = NODE_RECLAIM_PRIORITY,
4191                 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
4192                 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
4193                 .may_swap = 1,
4194                 .reclaim_idx = gfp_zone(gfp_mask),
4195         };
4196
4197         trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
4198                                            sc.gfp_mask);
4199
4200         cond_resched();
4201         fs_reclaim_acquire(sc.gfp_mask);
4202         /*
4203          * We need to be able to allocate from the reserves for RECLAIM_UNMAP
4204          * and we also need to be able to write out pages for RECLAIM_WRITE
4205          * and RECLAIM_UNMAP.
4206          */
4207         noreclaim_flag = memalloc_noreclaim_save();
4208         p->flags |= PF_SWAPWRITE;
4209         set_task_reclaim_state(p, &sc.reclaim_state);
4210
4211         if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
4212                 /*
4213                  * Free memory by calling shrink node with increasing
4214                  * priorities until we have enough memory freed.
4215                  */
4216                 do {
4217                         shrink_node(pgdat, &sc);
4218                 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
4219         }
4220
4221         set_task_reclaim_state(p, NULL);
4222         current->flags &= ~PF_SWAPWRITE;
4223         memalloc_noreclaim_restore(noreclaim_flag);
4224         fs_reclaim_release(sc.gfp_mask);
4225
4226         trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
4227
4228         return sc.nr_reclaimed >= nr_pages;
4229 }
4230
4231 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
4232 {
4233         int ret;
4234
4235         /*
4236          * Node reclaim reclaims unmapped file backed pages and
4237          * slab pages if we are over the defined limits.
4238          *
4239          * A small portion of unmapped file backed pages is needed for
4240          * file I/O otherwise pages read by file I/O will be immediately
4241          * thrown out if the node is overallocated. So we do not reclaim
4242          * if less than a specified percentage of the node is used by
4243          * unmapped file backed pages.
4244          */
4245         if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
4246             node_page_state(pgdat, NR_SLAB_RECLAIMABLE) <= pgdat->min_slab_pages)
4247                 return NODE_RECLAIM_FULL;
4248
4249         /*
4250          * Do not scan if the allocation should not be delayed.
4251          */
4252         if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
4253                 return NODE_RECLAIM_NOSCAN;
4254
4255         /*
4256          * Only run node reclaim on the local node or on nodes that do not
4257          * have associated processors. This will favor the local processor
4258          * over remote processors and spread off node memory allocations
4259          * as wide as possible.
4260          */
4261         if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
4262                 return NODE_RECLAIM_NOSCAN;
4263
4264         if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
4265                 return NODE_RECLAIM_NOSCAN;
4266
4267         ret = __node_reclaim(pgdat, gfp_mask, order);
4268         clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
4269
4270         if (!ret)
4271                 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
4272
4273         return ret;
4274 }
4275 #endif
4276
4277 /*
4278  * page_evictable - test whether a page is evictable
4279  * @page: the page to test
4280  *
4281  * Test whether page is evictable--i.e., should be placed on active/inactive
4282  * lists vs unevictable list.
4283  *
4284  * Reasons page might not be evictable:
4285  * (1) page's mapping marked unevictable
4286  * (2) page is part of an mlocked VMA
4287  *
4288  */
4289 int page_evictable(struct page *page)
4290 {
4291         int ret;
4292
4293         /* Prevent address_space of inode and swap cache from being freed */
4294         rcu_read_lock();
4295         ret = !mapping_unevictable(page_mapping(page)) && !PageMlocked(page);
4296         rcu_read_unlock();
4297         return ret;
4298 }
4299
4300 /**
4301  * check_move_unevictable_pages - check pages for evictability and move to
4302  * appropriate zone lru list
4303  * @pvec: pagevec with lru pages to check
4304  *
4305  * Checks pages for evictability, if an evictable page is in the unevictable
4306  * lru list, moves it to the appropriate evictable lru list. This function
4307  * should be only used for lru pages.
4308  */
4309 void check_move_unevictable_pages(struct pagevec *pvec)
4310 {
4311         struct lruvec *lruvec;
4312         struct pglist_data *pgdat = NULL;
4313         int pgscanned = 0;
4314         int pgrescued = 0;
4315         int i;
4316
4317         for (i = 0; i < pvec->nr; i++) {
4318                 struct page *page = pvec->pages[i];
4319                 struct pglist_data *pagepgdat = page_pgdat(page);
4320
4321                 pgscanned++;
4322                 if (pagepgdat != pgdat) {
4323                         if (pgdat)
4324                                 spin_unlock_irq(&pgdat->lru_lock);
4325                         pgdat = pagepgdat;
4326                         spin_lock_irq(&pgdat->lru_lock);
4327                 }
4328                 lruvec = mem_cgroup_page_lruvec(page, pgdat);
4329
4330                 if (!PageLRU(page) || !PageUnevictable(page))
4331                         continue;
4332
4333                 if (page_evictable(page)) {
4334                         enum lru_list lru = page_lru_base_type(page);
4335
4336                         VM_BUG_ON_PAGE(PageActive(page), page);
4337                         ClearPageUnevictable(page);
4338                         del_page_from_lru_list(page, lruvec, LRU_UNEVICTABLE);
4339                         add_page_to_lru_list(page, lruvec, lru);
4340                         pgrescued++;
4341                 }
4342         }
4343
4344         if (pgdat) {
4345                 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
4346                 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
4347                 spin_unlock_irq(&pgdat->lru_lock);
4348         }
4349 }
4350 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);