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