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