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