xref: /openbmc/linux/mm/vmscan.c (revision 7348cc91821b0cb24dfb00e578047f68299a50ab)
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 buffer_heads_over_limit */
30 #include <linux/mm_inline.h>
31 #include <linux/backing-dev.h>
32 #include <linux/rmap.h>
33 #include <linux/topology.h>
34 #include <linux/cpu.h>
35 #include <linux/cpuset.h>
36 #include <linux/compaction.h>
37 #include <linux/notifier.h>
38 #include <linux/rwsem.h>
39 #include <linux/delay.h>
40 #include <linux/kthread.h>
41 #include <linux/freezer.h>
42 #include <linux/memcontrol.h>
43 #include <linux/migrate.h>
44 #include <linux/delayacct.h>
45 #include <linux/sysctl.h>
46 #include <linux/memory-tiers.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 #include <linux/pagewalk.h>
54 #include <linux/shmem_fs.h>
55 #include <linux/ctype.h>
56 #include <linux/debugfs.h>
57 #include <linux/khugepaged.h>
58 
59 #include <asm/tlbflush.h>
60 #include <asm/div64.h>
61 
62 #include <linux/swapops.h>
63 #include <linux/balloon_compaction.h>
64 #include <linux/sched/sysctl.h>
65 
66 #include "internal.h"
67 #include "swap.h"
68 
69 #define CREATE_TRACE_POINTS
70 #include <trace/events/vmscan.h>
71 
72 struct scan_control {
73 	/* How many pages shrink_list() should reclaim */
74 	unsigned long nr_to_reclaim;
75 
76 	/*
77 	 * Nodemask of nodes allowed by the caller. If NULL, all nodes
78 	 * are scanned.
79 	 */
80 	nodemask_t	*nodemask;
81 
82 	/*
83 	 * The memory cgroup that hit its limit and as a result is the
84 	 * primary target of this reclaim invocation.
85 	 */
86 	struct mem_cgroup *target_mem_cgroup;
87 
88 	/*
89 	 * Scan pressure balancing between anon and file LRUs
90 	 */
91 	unsigned long	anon_cost;
92 	unsigned long	file_cost;
93 
94 	/* Can active folios be deactivated as part of reclaim? */
95 #define DEACTIVATE_ANON 1
96 #define DEACTIVATE_FILE 2
97 	unsigned int may_deactivate:2;
98 	unsigned int force_deactivate:1;
99 	unsigned int skipped_deactivate:1;
100 
101 	/* Writepage batching in laptop mode; RECLAIM_WRITE */
102 	unsigned int may_writepage:1;
103 
104 	/* Can mapped folios be reclaimed? */
105 	unsigned int may_unmap:1;
106 
107 	/* Can folios be swapped as part of reclaim? */
108 	unsigned int may_swap:1;
109 
110 	/* Proactive reclaim invoked by userspace through memory.reclaim */
111 	unsigned int proactive:1;
112 
113 	/*
114 	 * Cgroup memory below memory.low is protected as long as we
115 	 * don't threaten to OOM. If any cgroup is reclaimed at
116 	 * reduced force or passed over entirely due to its memory.low
117 	 * setting (memcg_low_skipped), and nothing is reclaimed as a
118 	 * result, then go back for one more cycle that reclaims the protected
119 	 * memory (memcg_low_reclaim) to avert OOM.
120 	 */
121 	unsigned int memcg_low_reclaim:1;
122 	unsigned int memcg_low_skipped:1;
123 
124 	unsigned int hibernation_mode:1;
125 
126 	/* One of the zones is ready for compaction */
127 	unsigned int compaction_ready:1;
128 
129 	/* There is easily reclaimable cold cache in the current node */
130 	unsigned int cache_trim_mode:1;
131 
132 	/* The file folios on the current node are dangerously low */
133 	unsigned int file_is_tiny:1;
134 
135 	/* Always discard instead of demoting to lower tier memory */
136 	unsigned int no_demotion:1;
137 
138 #ifdef CONFIG_LRU_GEN
139 	/* help kswapd make better choices among multiple memcgs */
140 	unsigned long last_reclaimed;
141 #endif
142 
143 	/* Allocation order */
144 	s8 order;
145 
146 	/* Scan (total_size >> priority) pages at once */
147 	s8 priority;
148 
149 	/* The highest zone to isolate folios for reclaim from */
150 	s8 reclaim_idx;
151 
152 	/* This context's GFP mask */
153 	gfp_t gfp_mask;
154 
155 	/* Incremented by the number of inactive pages that were scanned */
156 	unsigned long nr_scanned;
157 
158 	/* Number of pages freed so far during a call to shrink_zones() */
159 	unsigned long nr_reclaimed;
160 
161 	struct {
162 		unsigned int dirty;
163 		unsigned int unqueued_dirty;
164 		unsigned int congested;
165 		unsigned int writeback;
166 		unsigned int immediate;
167 		unsigned int file_taken;
168 		unsigned int taken;
169 	} nr;
170 
171 	/* for recording the reclaimed slab by now */
172 	struct reclaim_state reclaim_state;
173 };
174 
175 #ifdef ARCH_HAS_PREFETCHW
176 #define prefetchw_prev_lru_folio(_folio, _base, _field)			\
177 	do {								\
178 		if ((_folio)->lru.prev != _base) {			\
179 			struct folio *prev;				\
180 									\
181 			prev = lru_to_folio(&(_folio->lru));		\
182 			prefetchw(&prev->_field);			\
183 		}							\
184 	} while (0)
185 #else
186 #define prefetchw_prev_lru_folio(_folio, _base, _field) do { } while (0)
187 #endif
188 
189 /*
190  * From 0 .. 200.  Higher means more swappy.
191  */
192 int vm_swappiness = 60;
193 
194 static void set_task_reclaim_state(struct task_struct *task,
195 				   struct reclaim_state *rs)
196 {
197 	/* Check for an overwrite */
198 	WARN_ON_ONCE(rs && task->reclaim_state);
199 
200 	/* Check for the nulling of an already-nulled member */
201 	WARN_ON_ONCE(!rs && !task->reclaim_state);
202 
203 	task->reclaim_state = rs;
204 }
205 
206 LIST_HEAD(shrinker_list);
207 DECLARE_RWSEM(shrinker_rwsem);
208 
209 #ifdef CONFIG_MEMCG
210 static int shrinker_nr_max;
211 
212 /* The shrinker_info is expanded in a batch of BITS_PER_LONG */
213 static inline int shrinker_map_size(int nr_items)
214 {
215 	return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
216 }
217 
218 static inline int shrinker_defer_size(int nr_items)
219 {
220 	return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
221 }
222 
223 static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
224 						     int nid)
225 {
226 	return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
227 					 lockdep_is_held(&shrinker_rwsem));
228 }
229 
230 static int expand_one_shrinker_info(struct mem_cgroup *memcg,
231 				    int map_size, int defer_size,
232 				    int old_map_size, int old_defer_size)
233 {
234 	struct shrinker_info *new, *old;
235 	struct mem_cgroup_per_node *pn;
236 	int nid;
237 	int size = map_size + defer_size;
238 
239 	for_each_node(nid) {
240 		pn = memcg->nodeinfo[nid];
241 		old = shrinker_info_protected(memcg, nid);
242 		/* Not yet online memcg */
243 		if (!old)
244 			return 0;
245 
246 		new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
247 		if (!new)
248 			return -ENOMEM;
249 
250 		new->nr_deferred = (atomic_long_t *)(new + 1);
251 		new->map = (void *)new->nr_deferred + defer_size;
252 
253 		/* map: set all old bits, clear all new bits */
254 		memset(new->map, (int)0xff, old_map_size);
255 		memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
256 		/* nr_deferred: copy old values, clear all new values */
257 		memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
258 		memset((void *)new->nr_deferred + old_defer_size, 0,
259 		       defer_size - old_defer_size);
260 
261 		rcu_assign_pointer(pn->shrinker_info, new);
262 		kvfree_rcu(old, rcu);
263 	}
264 
265 	return 0;
266 }
267 
268 void free_shrinker_info(struct mem_cgroup *memcg)
269 {
270 	struct mem_cgroup_per_node *pn;
271 	struct shrinker_info *info;
272 	int nid;
273 
274 	for_each_node(nid) {
275 		pn = memcg->nodeinfo[nid];
276 		info = rcu_dereference_protected(pn->shrinker_info, true);
277 		kvfree(info);
278 		rcu_assign_pointer(pn->shrinker_info, NULL);
279 	}
280 }
281 
282 int alloc_shrinker_info(struct mem_cgroup *memcg)
283 {
284 	struct shrinker_info *info;
285 	int nid, size, ret = 0;
286 	int map_size, defer_size = 0;
287 
288 	down_write(&shrinker_rwsem);
289 	map_size = shrinker_map_size(shrinker_nr_max);
290 	defer_size = shrinker_defer_size(shrinker_nr_max);
291 	size = map_size + defer_size;
292 	for_each_node(nid) {
293 		info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
294 		if (!info) {
295 			free_shrinker_info(memcg);
296 			ret = -ENOMEM;
297 			break;
298 		}
299 		info->nr_deferred = (atomic_long_t *)(info + 1);
300 		info->map = (void *)info->nr_deferred + defer_size;
301 		rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
302 	}
303 	up_write(&shrinker_rwsem);
304 
305 	return ret;
306 }
307 
308 static inline bool need_expand(int nr_max)
309 {
310 	return round_up(nr_max, BITS_PER_LONG) >
311 	       round_up(shrinker_nr_max, BITS_PER_LONG);
312 }
313 
314 static int expand_shrinker_info(int new_id)
315 {
316 	int ret = 0;
317 	int new_nr_max = new_id + 1;
318 	int map_size, defer_size = 0;
319 	int old_map_size, old_defer_size = 0;
320 	struct mem_cgroup *memcg;
321 
322 	if (!need_expand(new_nr_max))
323 		goto out;
324 
325 	if (!root_mem_cgroup)
326 		goto out;
327 
328 	lockdep_assert_held(&shrinker_rwsem);
329 
330 	map_size = shrinker_map_size(new_nr_max);
331 	defer_size = shrinker_defer_size(new_nr_max);
332 	old_map_size = shrinker_map_size(shrinker_nr_max);
333 	old_defer_size = shrinker_defer_size(shrinker_nr_max);
334 
335 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
336 	do {
337 		ret = expand_one_shrinker_info(memcg, map_size, defer_size,
338 					       old_map_size, old_defer_size);
339 		if (ret) {
340 			mem_cgroup_iter_break(NULL, memcg);
341 			goto out;
342 		}
343 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
344 out:
345 	if (!ret)
346 		shrinker_nr_max = new_nr_max;
347 
348 	return ret;
349 }
350 
351 void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
352 {
353 	if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
354 		struct shrinker_info *info;
355 
356 		rcu_read_lock();
357 		info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
358 		/* Pairs with smp mb in shrink_slab() */
359 		smp_mb__before_atomic();
360 		set_bit(shrinker_id, info->map);
361 		rcu_read_unlock();
362 	}
363 }
364 
365 static DEFINE_IDR(shrinker_idr);
366 
367 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
368 {
369 	int id, ret = -ENOMEM;
370 
371 	if (mem_cgroup_disabled())
372 		return -ENOSYS;
373 
374 	down_write(&shrinker_rwsem);
375 	/* This may call shrinker, so it must use down_read_trylock() */
376 	id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
377 	if (id < 0)
378 		goto unlock;
379 
380 	if (id >= shrinker_nr_max) {
381 		if (expand_shrinker_info(id)) {
382 			idr_remove(&shrinker_idr, id);
383 			goto unlock;
384 		}
385 	}
386 	shrinker->id = id;
387 	ret = 0;
388 unlock:
389 	up_write(&shrinker_rwsem);
390 	return ret;
391 }
392 
393 static void unregister_memcg_shrinker(struct shrinker *shrinker)
394 {
395 	int id = shrinker->id;
396 
397 	BUG_ON(id < 0);
398 
399 	lockdep_assert_held(&shrinker_rwsem);
400 
401 	idr_remove(&shrinker_idr, id);
402 }
403 
404 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
405 				   struct mem_cgroup *memcg)
406 {
407 	struct shrinker_info *info;
408 
409 	info = shrinker_info_protected(memcg, nid);
410 	return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
411 }
412 
413 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
414 				  struct mem_cgroup *memcg)
415 {
416 	struct shrinker_info *info;
417 
418 	info = shrinker_info_protected(memcg, nid);
419 	return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
420 }
421 
422 void reparent_shrinker_deferred(struct mem_cgroup *memcg)
423 {
424 	int i, nid;
425 	long nr;
426 	struct mem_cgroup *parent;
427 	struct shrinker_info *child_info, *parent_info;
428 
429 	parent = parent_mem_cgroup(memcg);
430 	if (!parent)
431 		parent = root_mem_cgroup;
432 
433 	/* Prevent from concurrent shrinker_info expand */
434 	down_read(&shrinker_rwsem);
435 	for_each_node(nid) {
436 		child_info = shrinker_info_protected(memcg, nid);
437 		parent_info = shrinker_info_protected(parent, nid);
438 		for (i = 0; i < shrinker_nr_max; i++) {
439 			nr = atomic_long_read(&child_info->nr_deferred[i]);
440 			atomic_long_add(nr, &parent_info->nr_deferred[i]);
441 		}
442 	}
443 	up_read(&shrinker_rwsem);
444 }
445 
446 static bool cgroup_reclaim(struct scan_control *sc)
447 {
448 	return sc->target_mem_cgroup;
449 }
450 
451 static bool global_reclaim(struct scan_control *sc)
452 {
453 	return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
454 }
455 
456 /**
457  * writeback_throttling_sane - is the usual dirty throttling mechanism available?
458  * @sc: scan_control in question
459  *
460  * The normal page dirty throttling mechanism in balance_dirty_pages() is
461  * completely broken with the legacy memcg and direct stalling in
462  * shrink_folio_list() is used for throttling instead, which lacks all the
463  * niceties such as fairness, adaptive pausing, bandwidth proportional
464  * allocation and configurability.
465  *
466  * This function tests whether the vmscan currently in progress can assume
467  * that the normal dirty throttling mechanism is operational.
468  */
469 static bool writeback_throttling_sane(struct scan_control *sc)
470 {
471 	if (!cgroup_reclaim(sc))
472 		return true;
473 #ifdef CONFIG_CGROUP_WRITEBACK
474 	if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
475 		return true;
476 #endif
477 	return false;
478 }
479 #else
480 static int prealloc_memcg_shrinker(struct shrinker *shrinker)
481 {
482 	return -ENOSYS;
483 }
484 
485 static void unregister_memcg_shrinker(struct shrinker *shrinker)
486 {
487 }
488 
489 static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
490 				   struct mem_cgroup *memcg)
491 {
492 	return 0;
493 }
494 
495 static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
496 				  struct mem_cgroup *memcg)
497 {
498 	return 0;
499 }
500 
501 static bool cgroup_reclaim(struct scan_control *sc)
502 {
503 	return false;
504 }
505 
506 static bool global_reclaim(struct scan_control *sc)
507 {
508 	return true;
509 }
510 
511 static bool writeback_throttling_sane(struct scan_control *sc)
512 {
513 	return true;
514 }
515 #endif
516 
517 static long xchg_nr_deferred(struct shrinker *shrinker,
518 			     struct shrink_control *sc)
519 {
520 	int nid = sc->nid;
521 
522 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
523 		nid = 0;
524 
525 	if (sc->memcg &&
526 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
527 		return xchg_nr_deferred_memcg(nid, shrinker,
528 					      sc->memcg);
529 
530 	return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
531 }
532 
533 
534 static long add_nr_deferred(long nr, struct shrinker *shrinker,
535 			    struct shrink_control *sc)
536 {
537 	int nid = sc->nid;
538 
539 	if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
540 		nid = 0;
541 
542 	if (sc->memcg &&
543 	    (shrinker->flags & SHRINKER_MEMCG_AWARE))
544 		return add_nr_deferred_memcg(nr, nid, shrinker,
545 					     sc->memcg);
546 
547 	return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
548 }
549 
550 static bool can_demote(int nid, struct scan_control *sc)
551 {
552 	if (!numa_demotion_enabled)
553 		return false;
554 	if (sc && sc->no_demotion)
555 		return false;
556 	if (next_demotion_node(nid) == NUMA_NO_NODE)
557 		return false;
558 
559 	return true;
560 }
561 
562 static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
563 					  int nid,
564 					  struct scan_control *sc)
565 {
566 	if (memcg == NULL) {
567 		/*
568 		 * For non-memcg reclaim, is there
569 		 * space in any swap device?
570 		 */
571 		if (get_nr_swap_pages() > 0)
572 			return true;
573 	} else {
574 		/* Is the memcg below its swap limit? */
575 		if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
576 			return true;
577 	}
578 
579 	/*
580 	 * The page can not be swapped.
581 	 *
582 	 * Can it be reclaimed from this node via demotion?
583 	 */
584 	return can_demote(nid, sc);
585 }
586 
587 /*
588  * This misses isolated folios which are not accounted for to save counters.
589  * As the data only determines if reclaim or compaction continues, it is
590  * not expected that isolated folios will be a dominating factor.
591  */
592 unsigned long zone_reclaimable_pages(struct zone *zone)
593 {
594 	unsigned long nr;
595 
596 	nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
597 		zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
598 	if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
599 		nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
600 			zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
601 
602 	return nr;
603 }
604 
605 /**
606  * lruvec_lru_size -  Returns the number of pages on the given LRU list.
607  * @lruvec: lru vector
608  * @lru: lru to use
609  * @zone_idx: zones to consider (use MAX_NR_ZONES - 1 for the whole LRU list)
610  */
611 static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
612 				     int zone_idx)
613 {
614 	unsigned long size = 0;
615 	int zid;
616 
617 	for (zid = 0; zid <= zone_idx; zid++) {
618 		struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
619 
620 		if (!managed_zone(zone))
621 			continue;
622 
623 		if (!mem_cgroup_disabled())
624 			size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
625 		else
626 			size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
627 	}
628 	return size;
629 }
630 
631 /*
632  * Add a shrinker callback to be called from the vm.
633  */
634 static int __prealloc_shrinker(struct shrinker *shrinker)
635 {
636 	unsigned int size;
637 	int err;
638 
639 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
640 		err = prealloc_memcg_shrinker(shrinker);
641 		if (err != -ENOSYS)
642 			return err;
643 
644 		shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
645 	}
646 
647 	size = sizeof(*shrinker->nr_deferred);
648 	if (shrinker->flags & SHRINKER_NUMA_AWARE)
649 		size *= nr_node_ids;
650 
651 	shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
652 	if (!shrinker->nr_deferred)
653 		return -ENOMEM;
654 
655 	return 0;
656 }
657 
658 #ifdef CONFIG_SHRINKER_DEBUG
659 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
660 {
661 	va_list ap;
662 	int err;
663 
664 	va_start(ap, fmt);
665 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
666 	va_end(ap);
667 	if (!shrinker->name)
668 		return -ENOMEM;
669 
670 	err = __prealloc_shrinker(shrinker);
671 	if (err) {
672 		kfree_const(shrinker->name);
673 		shrinker->name = NULL;
674 	}
675 
676 	return err;
677 }
678 #else
679 int prealloc_shrinker(struct shrinker *shrinker, const char *fmt, ...)
680 {
681 	return __prealloc_shrinker(shrinker);
682 }
683 #endif
684 
685 void free_prealloced_shrinker(struct shrinker *shrinker)
686 {
687 #ifdef CONFIG_SHRINKER_DEBUG
688 	kfree_const(shrinker->name);
689 	shrinker->name = NULL;
690 #endif
691 	if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
692 		down_write(&shrinker_rwsem);
693 		unregister_memcg_shrinker(shrinker);
694 		up_write(&shrinker_rwsem);
695 		return;
696 	}
697 
698 	kfree(shrinker->nr_deferred);
699 	shrinker->nr_deferred = NULL;
700 }
701 
702 void register_shrinker_prepared(struct shrinker *shrinker)
703 {
704 	down_write(&shrinker_rwsem);
705 	list_add_tail(&shrinker->list, &shrinker_list);
706 	shrinker->flags |= SHRINKER_REGISTERED;
707 	shrinker_debugfs_add(shrinker);
708 	up_write(&shrinker_rwsem);
709 }
710 
711 static int __register_shrinker(struct shrinker *shrinker)
712 {
713 	int err = __prealloc_shrinker(shrinker);
714 
715 	if (err)
716 		return err;
717 	register_shrinker_prepared(shrinker);
718 	return 0;
719 }
720 
721 #ifdef CONFIG_SHRINKER_DEBUG
722 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
723 {
724 	va_list ap;
725 	int err;
726 
727 	va_start(ap, fmt);
728 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
729 	va_end(ap);
730 	if (!shrinker->name)
731 		return -ENOMEM;
732 
733 	err = __register_shrinker(shrinker);
734 	if (err) {
735 		kfree_const(shrinker->name);
736 		shrinker->name = NULL;
737 	}
738 	return err;
739 }
740 #else
741 int register_shrinker(struct shrinker *shrinker, const char *fmt, ...)
742 {
743 	return __register_shrinker(shrinker);
744 }
745 #endif
746 EXPORT_SYMBOL(register_shrinker);
747 
748 /*
749  * Remove one
750  */
751 void unregister_shrinker(struct shrinker *shrinker)
752 {
753 	if (!(shrinker->flags & SHRINKER_REGISTERED))
754 		return;
755 
756 	down_write(&shrinker_rwsem);
757 	list_del(&shrinker->list);
758 	shrinker->flags &= ~SHRINKER_REGISTERED;
759 	if (shrinker->flags & SHRINKER_MEMCG_AWARE)
760 		unregister_memcg_shrinker(shrinker);
761 	shrinker_debugfs_remove(shrinker);
762 	up_write(&shrinker_rwsem);
763 
764 	kfree(shrinker->nr_deferred);
765 	shrinker->nr_deferred = NULL;
766 }
767 EXPORT_SYMBOL(unregister_shrinker);
768 
769 /**
770  * synchronize_shrinkers - Wait for all running shrinkers to complete.
771  *
772  * This is equivalent to calling unregister_shrink() and register_shrinker(),
773  * but atomically and with less overhead. This is useful to guarantee that all
774  * shrinker invocations have seen an update, before freeing memory, similar to
775  * rcu.
776  */
777 void synchronize_shrinkers(void)
778 {
779 	down_write(&shrinker_rwsem);
780 	up_write(&shrinker_rwsem);
781 }
782 EXPORT_SYMBOL(synchronize_shrinkers);
783 
784 #define SHRINK_BATCH 128
785 
786 static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
787 				    struct shrinker *shrinker, int priority)
788 {
789 	unsigned long freed = 0;
790 	unsigned long long delta;
791 	long total_scan;
792 	long freeable;
793 	long nr;
794 	long new_nr;
795 	long batch_size = shrinker->batch ? shrinker->batch
796 					  : SHRINK_BATCH;
797 	long scanned = 0, next_deferred;
798 
799 	freeable = shrinker->count_objects(shrinker, shrinkctl);
800 	if (freeable == 0 || freeable == SHRINK_EMPTY)
801 		return freeable;
802 
803 	/*
804 	 * copy the current shrinker scan count into a local variable
805 	 * and zero it so that other concurrent shrinker invocations
806 	 * don't also do this scanning work.
807 	 */
808 	nr = xchg_nr_deferred(shrinker, shrinkctl);
809 
810 	if (shrinker->seeks) {
811 		delta = freeable >> priority;
812 		delta *= 4;
813 		do_div(delta, shrinker->seeks);
814 	} else {
815 		/*
816 		 * These objects don't require any IO to create. Trim
817 		 * them aggressively under memory pressure to keep
818 		 * them from causing refetches in the IO caches.
819 		 */
820 		delta = freeable / 2;
821 	}
822 
823 	total_scan = nr >> priority;
824 	total_scan += delta;
825 	total_scan = min(total_scan, (2 * freeable));
826 
827 	trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
828 				   freeable, delta, total_scan, priority);
829 
830 	/*
831 	 * Normally, we should not scan less than batch_size objects in one
832 	 * pass to avoid too frequent shrinker calls, but if the slab has less
833 	 * than batch_size objects in total and we are really tight on memory,
834 	 * we will try to reclaim all available objects, otherwise we can end
835 	 * up failing allocations although there are plenty of reclaimable
836 	 * objects spread over several slabs with usage less than the
837 	 * batch_size.
838 	 *
839 	 * We detect the "tight on memory" situations by looking at the total
840 	 * number of objects we want to scan (total_scan). If it is greater
841 	 * than the total number of objects on slab (freeable), we must be
842 	 * scanning at high prio and therefore should try to reclaim as much as
843 	 * possible.
844 	 */
845 	while (total_scan >= batch_size ||
846 	       total_scan >= freeable) {
847 		unsigned long ret;
848 		unsigned long nr_to_scan = min(batch_size, total_scan);
849 
850 		shrinkctl->nr_to_scan = nr_to_scan;
851 		shrinkctl->nr_scanned = nr_to_scan;
852 		ret = shrinker->scan_objects(shrinker, shrinkctl);
853 		if (ret == SHRINK_STOP)
854 			break;
855 		freed += ret;
856 
857 		count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
858 		total_scan -= shrinkctl->nr_scanned;
859 		scanned += shrinkctl->nr_scanned;
860 
861 		cond_resched();
862 	}
863 
864 	/*
865 	 * The deferred work is increased by any new work (delta) that wasn't
866 	 * done, decreased by old deferred work that was done now.
867 	 *
868 	 * And it is capped to two times of the freeable items.
869 	 */
870 	next_deferred = max_t(long, (nr + delta - scanned), 0);
871 	next_deferred = min(next_deferred, (2 * freeable));
872 
873 	/*
874 	 * move the unused scan count back into the shrinker in a
875 	 * manner that handles concurrent updates.
876 	 */
877 	new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
878 
879 	trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
880 	return freed;
881 }
882 
883 #ifdef CONFIG_MEMCG
884 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
885 			struct mem_cgroup *memcg, int priority)
886 {
887 	struct shrinker_info *info;
888 	unsigned long ret, freed = 0;
889 	int i;
890 
891 	if (!mem_cgroup_online(memcg))
892 		return 0;
893 
894 	if (!down_read_trylock(&shrinker_rwsem))
895 		return 0;
896 
897 	info = shrinker_info_protected(memcg, nid);
898 	if (unlikely(!info))
899 		goto unlock;
900 
901 	for_each_set_bit(i, info->map, shrinker_nr_max) {
902 		struct shrink_control sc = {
903 			.gfp_mask = gfp_mask,
904 			.nid = nid,
905 			.memcg = memcg,
906 		};
907 		struct shrinker *shrinker;
908 
909 		shrinker = idr_find(&shrinker_idr, i);
910 		if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
911 			if (!shrinker)
912 				clear_bit(i, info->map);
913 			continue;
914 		}
915 
916 		/* Call non-slab shrinkers even though kmem is disabled */
917 		if (!memcg_kmem_enabled() &&
918 		    !(shrinker->flags & SHRINKER_NONSLAB))
919 			continue;
920 
921 		ret = do_shrink_slab(&sc, shrinker, priority);
922 		if (ret == SHRINK_EMPTY) {
923 			clear_bit(i, info->map);
924 			/*
925 			 * After the shrinker reported that it had no objects to
926 			 * free, but before we cleared the corresponding bit in
927 			 * the memcg shrinker map, a new object might have been
928 			 * added. To make sure, we have the bit set in this
929 			 * case, we invoke the shrinker one more time and reset
930 			 * the bit if it reports that it is not empty anymore.
931 			 * The memory barrier here pairs with the barrier in
932 			 * set_shrinker_bit():
933 			 *
934 			 * list_lru_add()     shrink_slab_memcg()
935 			 *   list_add_tail()    clear_bit()
936 			 *   <MB>               <MB>
937 			 *   set_bit()          do_shrink_slab()
938 			 */
939 			smp_mb__after_atomic();
940 			ret = do_shrink_slab(&sc, shrinker, priority);
941 			if (ret == SHRINK_EMPTY)
942 				ret = 0;
943 			else
944 				set_shrinker_bit(memcg, nid, i);
945 		}
946 		freed += ret;
947 
948 		if (rwsem_is_contended(&shrinker_rwsem)) {
949 			freed = freed ? : 1;
950 			break;
951 		}
952 	}
953 unlock:
954 	up_read(&shrinker_rwsem);
955 	return freed;
956 }
957 #else /* CONFIG_MEMCG */
958 static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
959 			struct mem_cgroup *memcg, int priority)
960 {
961 	return 0;
962 }
963 #endif /* CONFIG_MEMCG */
964 
965 /**
966  * shrink_slab - shrink slab caches
967  * @gfp_mask: allocation context
968  * @nid: node whose slab caches to target
969  * @memcg: memory cgroup whose slab caches to target
970  * @priority: the reclaim priority
971  *
972  * Call the shrink functions to age shrinkable caches.
973  *
974  * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
975  * unaware shrinkers will receive a node id of 0 instead.
976  *
977  * @memcg specifies the memory cgroup to target. Unaware shrinkers
978  * are called only if it is the root cgroup.
979  *
980  * @priority is sc->priority, we take the number of objects and >> by priority
981  * in order to get the scan target.
982  *
983  * Returns the number of reclaimed slab objects.
984  */
985 static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
986 				 struct mem_cgroup *memcg,
987 				 int priority)
988 {
989 	unsigned long ret, freed = 0;
990 	struct shrinker *shrinker;
991 
992 	/*
993 	 * The root memcg might be allocated even though memcg is disabled
994 	 * via "cgroup_disable=memory" boot parameter.  This could make
995 	 * mem_cgroup_is_root() return false, then just run memcg slab
996 	 * shrink, but skip global shrink.  This may result in premature
997 	 * oom.
998 	 */
999 	if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
1000 		return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
1001 
1002 	if (!down_read_trylock(&shrinker_rwsem))
1003 		goto out;
1004 
1005 	list_for_each_entry(shrinker, &shrinker_list, list) {
1006 		struct shrink_control sc = {
1007 			.gfp_mask = gfp_mask,
1008 			.nid = nid,
1009 			.memcg = memcg,
1010 		};
1011 
1012 		ret = do_shrink_slab(&sc, shrinker, priority);
1013 		if (ret == SHRINK_EMPTY)
1014 			ret = 0;
1015 		freed += ret;
1016 		/*
1017 		 * Bail out if someone want to register a new shrinker to
1018 		 * prevent the registration from being stalled for long periods
1019 		 * by parallel ongoing shrinking.
1020 		 */
1021 		if (rwsem_is_contended(&shrinker_rwsem)) {
1022 			freed = freed ? : 1;
1023 			break;
1024 		}
1025 	}
1026 
1027 	up_read(&shrinker_rwsem);
1028 out:
1029 	cond_resched();
1030 	return freed;
1031 }
1032 
1033 static unsigned long drop_slab_node(int nid)
1034 {
1035 	unsigned long freed = 0;
1036 	struct mem_cgroup *memcg = NULL;
1037 
1038 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
1039 	do {
1040 		freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
1041 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
1042 
1043 	return freed;
1044 }
1045 
1046 void drop_slab(void)
1047 {
1048 	int nid;
1049 	int shift = 0;
1050 	unsigned long freed;
1051 
1052 	do {
1053 		freed = 0;
1054 		for_each_online_node(nid) {
1055 			if (fatal_signal_pending(current))
1056 				return;
1057 
1058 			freed += drop_slab_node(nid);
1059 		}
1060 	} while ((freed >> shift++) > 1);
1061 }
1062 
1063 static int reclaimer_offset(void)
1064 {
1065 	BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1066 			PGDEMOTE_DIRECT - PGDEMOTE_KSWAPD);
1067 	BUILD_BUG_ON(PGSTEAL_DIRECT - PGSTEAL_KSWAPD !=
1068 			PGSCAN_DIRECT - PGSCAN_KSWAPD);
1069 	BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1070 			PGDEMOTE_KHUGEPAGED - PGDEMOTE_KSWAPD);
1071 	BUILD_BUG_ON(PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD !=
1072 			PGSCAN_KHUGEPAGED - PGSCAN_KSWAPD);
1073 
1074 	if (current_is_kswapd())
1075 		return 0;
1076 	if (current_is_khugepaged())
1077 		return PGSTEAL_KHUGEPAGED - PGSTEAL_KSWAPD;
1078 	return PGSTEAL_DIRECT - PGSTEAL_KSWAPD;
1079 }
1080 
1081 static inline int is_page_cache_freeable(struct folio *folio)
1082 {
1083 	/*
1084 	 * A freeable page cache folio is referenced only by the caller
1085 	 * that isolated the folio, the page cache and optional filesystem
1086 	 * private data at folio->private.
1087 	 */
1088 	return folio_ref_count(folio) - folio_test_private(folio) ==
1089 		1 + folio_nr_pages(folio);
1090 }
1091 
1092 /*
1093  * We detected a synchronous write error writing a folio out.  Probably
1094  * -ENOSPC.  We need to propagate that into the address_space for a subsequent
1095  * fsync(), msync() or close().
1096  *
1097  * The tricky part is that after writepage we cannot touch the mapping: nothing
1098  * prevents it from being freed up.  But we have a ref on the folio and once
1099  * that folio is locked, the mapping is pinned.
1100  *
1101  * We're allowed to run sleeping folio_lock() here because we know the caller has
1102  * __GFP_FS.
1103  */
1104 static void handle_write_error(struct address_space *mapping,
1105 				struct folio *folio, int error)
1106 {
1107 	folio_lock(folio);
1108 	if (folio_mapping(folio) == mapping)
1109 		mapping_set_error(mapping, error);
1110 	folio_unlock(folio);
1111 }
1112 
1113 static bool skip_throttle_noprogress(pg_data_t *pgdat)
1114 {
1115 	int reclaimable = 0, write_pending = 0;
1116 	int i;
1117 
1118 	/*
1119 	 * If kswapd is disabled, reschedule if necessary but do not
1120 	 * throttle as the system is likely near OOM.
1121 	 */
1122 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
1123 		return true;
1124 
1125 	/*
1126 	 * If there are a lot of dirty/writeback folios then do not
1127 	 * throttle as throttling will occur when the folios cycle
1128 	 * towards the end of the LRU if still under writeback.
1129 	 */
1130 	for (i = 0; i < MAX_NR_ZONES; i++) {
1131 		struct zone *zone = pgdat->node_zones + i;
1132 
1133 		if (!managed_zone(zone))
1134 			continue;
1135 
1136 		reclaimable += zone_reclaimable_pages(zone);
1137 		write_pending += zone_page_state_snapshot(zone,
1138 						  NR_ZONE_WRITE_PENDING);
1139 	}
1140 	if (2 * write_pending <= reclaimable)
1141 		return true;
1142 
1143 	return false;
1144 }
1145 
1146 void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason)
1147 {
1148 	wait_queue_head_t *wqh = &pgdat->reclaim_wait[reason];
1149 	long timeout, ret;
1150 	DEFINE_WAIT(wait);
1151 
1152 	/*
1153 	 * Do not throttle IO workers, kthreads other than kswapd or
1154 	 * workqueues. They may be required for reclaim to make
1155 	 * forward progress (e.g. journalling workqueues or kthreads).
1156 	 */
1157 	if (!current_is_kswapd() &&
1158 	    current->flags & (PF_IO_WORKER|PF_KTHREAD)) {
1159 		cond_resched();
1160 		return;
1161 	}
1162 
1163 	/*
1164 	 * These figures are pulled out of thin air.
1165 	 * VMSCAN_THROTTLE_ISOLATED is a transient condition based on too many
1166 	 * parallel reclaimers which is a short-lived event so the timeout is
1167 	 * short. Failing to make progress or waiting on writeback are
1168 	 * potentially long-lived events so use a longer timeout. This is shaky
1169 	 * logic as a failure to make progress could be due to anything from
1170 	 * writeback to a slow device to excessive referenced folios at the tail
1171 	 * of the inactive LRU.
1172 	 */
1173 	switch(reason) {
1174 	case VMSCAN_THROTTLE_WRITEBACK:
1175 		timeout = HZ/10;
1176 
1177 		if (atomic_inc_return(&pgdat->nr_writeback_throttled) == 1) {
1178 			WRITE_ONCE(pgdat->nr_reclaim_start,
1179 				node_page_state(pgdat, NR_THROTTLED_WRITTEN));
1180 		}
1181 
1182 		break;
1183 	case VMSCAN_THROTTLE_CONGESTED:
1184 		fallthrough;
1185 	case VMSCAN_THROTTLE_NOPROGRESS:
1186 		if (skip_throttle_noprogress(pgdat)) {
1187 			cond_resched();
1188 			return;
1189 		}
1190 
1191 		timeout = 1;
1192 
1193 		break;
1194 	case VMSCAN_THROTTLE_ISOLATED:
1195 		timeout = HZ/50;
1196 		break;
1197 	default:
1198 		WARN_ON_ONCE(1);
1199 		timeout = HZ;
1200 		break;
1201 	}
1202 
1203 	prepare_to_wait(wqh, &wait, TASK_UNINTERRUPTIBLE);
1204 	ret = schedule_timeout(timeout);
1205 	finish_wait(wqh, &wait);
1206 
1207 	if (reason == VMSCAN_THROTTLE_WRITEBACK)
1208 		atomic_dec(&pgdat->nr_writeback_throttled);
1209 
1210 	trace_mm_vmscan_throttled(pgdat->node_id, jiffies_to_usecs(timeout),
1211 				jiffies_to_usecs(timeout - ret),
1212 				reason);
1213 }
1214 
1215 /*
1216  * Account for folios written if tasks are throttled waiting on dirty
1217  * folios to clean. If enough folios have been cleaned since throttling
1218  * started then wakeup the throttled tasks.
1219  */
1220 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
1221 							int nr_throttled)
1222 {
1223 	unsigned long nr_written;
1224 
1225 	node_stat_add_folio(folio, NR_THROTTLED_WRITTEN);
1226 
1227 	/*
1228 	 * This is an inaccurate read as the per-cpu deltas may not
1229 	 * be synchronised. However, given that the system is
1230 	 * writeback throttled, it is not worth taking the penalty
1231 	 * of getting an accurate count. At worst, the throttle
1232 	 * timeout guarantees forward progress.
1233 	 */
1234 	nr_written = node_page_state(pgdat, NR_THROTTLED_WRITTEN) -
1235 		READ_ONCE(pgdat->nr_reclaim_start);
1236 
1237 	if (nr_written > SWAP_CLUSTER_MAX * nr_throttled)
1238 		wake_up(&pgdat->reclaim_wait[VMSCAN_THROTTLE_WRITEBACK]);
1239 }
1240 
1241 /* possible outcome of pageout() */
1242 typedef enum {
1243 	/* failed to write folio out, folio is locked */
1244 	PAGE_KEEP,
1245 	/* move folio to the active list, folio is locked */
1246 	PAGE_ACTIVATE,
1247 	/* folio has been sent to the disk successfully, folio is unlocked */
1248 	PAGE_SUCCESS,
1249 	/* folio is clean and locked */
1250 	PAGE_CLEAN,
1251 } pageout_t;
1252 
1253 /*
1254  * pageout is called by shrink_folio_list() for each dirty folio.
1255  * Calls ->writepage().
1256  */
1257 static pageout_t pageout(struct folio *folio, struct address_space *mapping,
1258 			 struct swap_iocb **plug)
1259 {
1260 	/*
1261 	 * If the folio is dirty, only perform writeback if that write
1262 	 * will be non-blocking.  To prevent this allocation from being
1263 	 * stalled by pagecache activity.  But note that there may be
1264 	 * stalls if we need to run get_block().  We could test
1265 	 * PagePrivate for that.
1266 	 *
1267 	 * If this process is currently in __generic_file_write_iter() against
1268 	 * this folio's queue, we can perform writeback even if that
1269 	 * will block.
1270 	 *
1271 	 * If the folio is swapcache, write it back even if that would
1272 	 * block, for some throttling. This happens by accident, because
1273 	 * swap_backing_dev_info is bust: it doesn't reflect the
1274 	 * congestion state of the swapdevs.  Easy to fix, if needed.
1275 	 */
1276 	if (!is_page_cache_freeable(folio))
1277 		return PAGE_KEEP;
1278 	if (!mapping) {
1279 		/*
1280 		 * Some data journaling orphaned folios can have
1281 		 * folio->mapping == NULL while being dirty with clean buffers.
1282 		 */
1283 		if (folio_test_private(folio)) {
1284 			if (try_to_free_buffers(folio)) {
1285 				folio_clear_dirty(folio);
1286 				pr_info("%s: orphaned folio\n", __func__);
1287 				return PAGE_CLEAN;
1288 			}
1289 		}
1290 		return PAGE_KEEP;
1291 	}
1292 	if (mapping->a_ops->writepage == NULL)
1293 		return PAGE_ACTIVATE;
1294 
1295 	if (folio_clear_dirty_for_io(folio)) {
1296 		int res;
1297 		struct writeback_control wbc = {
1298 			.sync_mode = WB_SYNC_NONE,
1299 			.nr_to_write = SWAP_CLUSTER_MAX,
1300 			.range_start = 0,
1301 			.range_end = LLONG_MAX,
1302 			.for_reclaim = 1,
1303 			.swap_plug = plug,
1304 		};
1305 
1306 		folio_set_reclaim(folio);
1307 		res = mapping->a_ops->writepage(&folio->page, &wbc);
1308 		if (res < 0)
1309 			handle_write_error(mapping, folio, res);
1310 		if (res == AOP_WRITEPAGE_ACTIVATE) {
1311 			folio_clear_reclaim(folio);
1312 			return PAGE_ACTIVATE;
1313 		}
1314 
1315 		if (!folio_test_writeback(folio)) {
1316 			/* synchronous write or broken a_ops? */
1317 			folio_clear_reclaim(folio);
1318 		}
1319 		trace_mm_vmscan_write_folio(folio);
1320 		node_stat_add_folio(folio, NR_VMSCAN_WRITE);
1321 		return PAGE_SUCCESS;
1322 	}
1323 
1324 	return PAGE_CLEAN;
1325 }
1326 
1327 /*
1328  * Same as remove_mapping, but if the folio is removed from the mapping, it
1329  * gets returned with a refcount of 0.
1330  */
1331 static int __remove_mapping(struct address_space *mapping, struct folio *folio,
1332 			    bool reclaimed, struct mem_cgroup *target_memcg)
1333 {
1334 	int refcount;
1335 	void *shadow = NULL;
1336 
1337 	BUG_ON(!folio_test_locked(folio));
1338 	BUG_ON(mapping != folio_mapping(folio));
1339 
1340 	if (!folio_test_swapcache(folio))
1341 		spin_lock(&mapping->host->i_lock);
1342 	xa_lock_irq(&mapping->i_pages);
1343 	/*
1344 	 * The non racy check for a busy folio.
1345 	 *
1346 	 * Must be careful with the order of the tests. When someone has
1347 	 * a ref to the folio, it may be possible that they dirty it then
1348 	 * drop the reference. So if the dirty flag is tested before the
1349 	 * refcount here, then the following race may occur:
1350 	 *
1351 	 * get_user_pages(&page);
1352 	 * [user mapping goes away]
1353 	 * write_to(page);
1354 	 *				!folio_test_dirty(folio)    [good]
1355 	 * folio_set_dirty(folio);
1356 	 * folio_put(folio);
1357 	 *				!refcount(folio)   [good, discard it]
1358 	 *
1359 	 * [oops, our write_to data is lost]
1360 	 *
1361 	 * Reversing the order of the tests ensures such a situation cannot
1362 	 * escape unnoticed. The smp_rmb is needed to ensure the folio->flags
1363 	 * load is not satisfied before that of folio->_refcount.
1364 	 *
1365 	 * Note that if the dirty flag is always set via folio_mark_dirty,
1366 	 * and thus under the i_pages lock, then this ordering is not required.
1367 	 */
1368 	refcount = 1 + folio_nr_pages(folio);
1369 	if (!folio_ref_freeze(folio, refcount))
1370 		goto cannot_free;
1371 	/* note: atomic_cmpxchg in folio_ref_freeze provides the smp_rmb */
1372 	if (unlikely(folio_test_dirty(folio))) {
1373 		folio_ref_unfreeze(folio, refcount);
1374 		goto cannot_free;
1375 	}
1376 
1377 	if (folio_test_swapcache(folio)) {
1378 		swp_entry_t swap = folio_swap_entry(folio);
1379 
1380 		if (reclaimed && !mapping_exiting(mapping))
1381 			shadow = workingset_eviction(folio, target_memcg);
1382 		__delete_from_swap_cache(folio, swap, shadow);
1383 		mem_cgroup_swapout(folio, swap);
1384 		xa_unlock_irq(&mapping->i_pages);
1385 		put_swap_folio(folio, swap);
1386 	} else {
1387 		void (*free_folio)(struct folio *);
1388 
1389 		free_folio = mapping->a_ops->free_folio;
1390 		/*
1391 		 * Remember a shadow entry for reclaimed file cache in
1392 		 * order to detect refaults, thus thrashing, later on.
1393 		 *
1394 		 * But don't store shadows in an address space that is
1395 		 * already exiting.  This is not just an optimization,
1396 		 * inode reclaim needs to empty out the radix tree or
1397 		 * the nodes are lost.  Don't plant shadows behind its
1398 		 * back.
1399 		 *
1400 		 * We also don't store shadows for DAX mappings because the
1401 		 * only page cache folios found in these are zero pages
1402 		 * covering holes, and because we don't want to mix DAX
1403 		 * exceptional entries and shadow exceptional entries in the
1404 		 * same address_space.
1405 		 */
1406 		if (reclaimed && folio_is_file_lru(folio) &&
1407 		    !mapping_exiting(mapping) && !dax_mapping(mapping))
1408 			shadow = workingset_eviction(folio, target_memcg);
1409 		__filemap_remove_folio(folio, shadow);
1410 		xa_unlock_irq(&mapping->i_pages);
1411 		if (mapping_shrinkable(mapping))
1412 			inode_add_lru(mapping->host);
1413 		spin_unlock(&mapping->host->i_lock);
1414 
1415 		if (free_folio)
1416 			free_folio(folio);
1417 	}
1418 
1419 	return 1;
1420 
1421 cannot_free:
1422 	xa_unlock_irq(&mapping->i_pages);
1423 	if (!folio_test_swapcache(folio))
1424 		spin_unlock(&mapping->host->i_lock);
1425 	return 0;
1426 }
1427 
1428 /**
1429  * remove_mapping() - Attempt to remove a folio from its mapping.
1430  * @mapping: The address space.
1431  * @folio: The folio to remove.
1432  *
1433  * If the folio is dirty, under writeback or if someone else has a ref
1434  * on it, removal will fail.
1435  * Return: The number of pages removed from the mapping.  0 if the folio
1436  * could not be removed.
1437  * Context: The caller should have a single refcount on the folio and
1438  * hold its lock.
1439  */
1440 long remove_mapping(struct address_space *mapping, struct folio *folio)
1441 {
1442 	if (__remove_mapping(mapping, folio, false, NULL)) {
1443 		/*
1444 		 * Unfreezing the refcount with 1 effectively
1445 		 * drops the pagecache ref for us without requiring another
1446 		 * atomic operation.
1447 		 */
1448 		folio_ref_unfreeze(folio, 1);
1449 		return folio_nr_pages(folio);
1450 	}
1451 	return 0;
1452 }
1453 
1454 /**
1455  * folio_putback_lru - Put previously isolated folio onto appropriate LRU list.
1456  * @folio: Folio to be returned to an LRU list.
1457  *
1458  * Add previously isolated @folio to appropriate LRU list.
1459  * The folio may still be unevictable for other reasons.
1460  *
1461  * Context: lru_lock must not be held, interrupts must be enabled.
1462  */
1463 void folio_putback_lru(struct folio *folio)
1464 {
1465 	folio_add_lru(folio);
1466 	folio_put(folio);		/* drop ref from isolate */
1467 }
1468 
1469 enum folio_references {
1470 	FOLIOREF_RECLAIM,
1471 	FOLIOREF_RECLAIM_CLEAN,
1472 	FOLIOREF_KEEP,
1473 	FOLIOREF_ACTIVATE,
1474 };
1475 
1476 static enum folio_references folio_check_references(struct folio *folio,
1477 						  struct scan_control *sc)
1478 {
1479 	int referenced_ptes, referenced_folio;
1480 	unsigned long vm_flags;
1481 
1482 	referenced_ptes = folio_referenced(folio, 1, sc->target_mem_cgroup,
1483 					   &vm_flags);
1484 	referenced_folio = folio_test_clear_referenced(folio);
1485 
1486 	/*
1487 	 * The supposedly reclaimable folio was found to be in a VM_LOCKED vma.
1488 	 * Let the folio, now marked Mlocked, be moved to the unevictable list.
1489 	 */
1490 	if (vm_flags & VM_LOCKED)
1491 		return FOLIOREF_ACTIVATE;
1492 
1493 	/* rmap lock contention: rotate */
1494 	if (referenced_ptes == -1)
1495 		return FOLIOREF_KEEP;
1496 
1497 	if (referenced_ptes) {
1498 		/*
1499 		 * All mapped folios start out with page table
1500 		 * references from the instantiating fault, so we need
1501 		 * to look twice if a mapped file/anon folio is used more
1502 		 * than once.
1503 		 *
1504 		 * Mark it and spare it for another trip around the
1505 		 * inactive list.  Another page table reference will
1506 		 * lead to its activation.
1507 		 *
1508 		 * Note: the mark is set for activated folios as well
1509 		 * so that recently deactivated but used folios are
1510 		 * quickly recovered.
1511 		 */
1512 		folio_set_referenced(folio);
1513 
1514 		if (referenced_folio || referenced_ptes > 1)
1515 			return FOLIOREF_ACTIVATE;
1516 
1517 		/*
1518 		 * Activate file-backed executable folios after first usage.
1519 		 */
1520 		if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio))
1521 			return FOLIOREF_ACTIVATE;
1522 
1523 		return FOLIOREF_KEEP;
1524 	}
1525 
1526 	/* Reclaim if clean, defer dirty folios to writeback */
1527 	if (referenced_folio && folio_is_file_lru(folio))
1528 		return FOLIOREF_RECLAIM_CLEAN;
1529 
1530 	return FOLIOREF_RECLAIM;
1531 }
1532 
1533 /* Check if a folio is dirty or under writeback */
1534 static void folio_check_dirty_writeback(struct folio *folio,
1535 				       bool *dirty, bool *writeback)
1536 {
1537 	struct address_space *mapping;
1538 
1539 	/*
1540 	 * Anonymous folios are not handled by flushers and must be written
1541 	 * from reclaim context. Do not stall reclaim based on them.
1542 	 * MADV_FREE anonymous folios are put into inactive file list too.
1543 	 * They could be mistakenly treated as file lru. So further anon
1544 	 * test is needed.
1545 	 */
1546 	if (!folio_is_file_lru(folio) ||
1547 	    (folio_test_anon(folio) && !folio_test_swapbacked(folio))) {
1548 		*dirty = false;
1549 		*writeback = false;
1550 		return;
1551 	}
1552 
1553 	/* By default assume that the folio flags are accurate */
1554 	*dirty = folio_test_dirty(folio);
1555 	*writeback = folio_test_writeback(folio);
1556 
1557 	/* Verify dirty/writeback state if the filesystem supports it */
1558 	if (!folio_test_private(folio))
1559 		return;
1560 
1561 	mapping = folio_mapping(folio);
1562 	if (mapping && mapping->a_ops->is_dirty_writeback)
1563 		mapping->a_ops->is_dirty_writeback(folio, dirty, writeback);
1564 }
1565 
1566 static struct page *alloc_demote_page(struct page *page, unsigned long private)
1567 {
1568 	struct page *target_page;
1569 	nodemask_t *allowed_mask;
1570 	struct migration_target_control *mtc;
1571 
1572 	mtc = (struct migration_target_control *)private;
1573 
1574 	allowed_mask = mtc->nmask;
1575 	/*
1576 	 * make sure we allocate from the target node first also trying to
1577 	 * demote or reclaim pages from the target node via kswapd if we are
1578 	 * low on free memory on target node. If we don't do this and if
1579 	 * we have free memory on the slower(lower) memtier, we would start
1580 	 * allocating pages from slower(lower) memory tiers without even forcing
1581 	 * a demotion of cold pages from the target memtier. This can result
1582 	 * in the kernel placing hot pages in slower(lower) memory tiers.
1583 	 */
1584 	mtc->nmask = NULL;
1585 	mtc->gfp_mask |= __GFP_THISNODE;
1586 	target_page = alloc_migration_target(page, (unsigned long)mtc);
1587 	if (target_page)
1588 		return target_page;
1589 
1590 	mtc->gfp_mask &= ~__GFP_THISNODE;
1591 	mtc->nmask = allowed_mask;
1592 
1593 	return alloc_migration_target(page, (unsigned long)mtc);
1594 }
1595 
1596 /*
1597  * Take folios on @demote_folios and attempt to demote them to another node.
1598  * Folios which are not demoted are left on @demote_folios.
1599  */
1600 static unsigned int demote_folio_list(struct list_head *demote_folios,
1601 				     struct pglist_data *pgdat)
1602 {
1603 	int target_nid = next_demotion_node(pgdat->node_id);
1604 	unsigned int nr_succeeded;
1605 	nodemask_t allowed_mask;
1606 
1607 	struct migration_target_control mtc = {
1608 		/*
1609 		 * Allocate from 'node', or fail quickly and quietly.
1610 		 * When this happens, 'page' will likely just be discarded
1611 		 * instead of migrated.
1612 		 */
1613 		.gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) | __GFP_NOWARN |
1614 			__GFP_NOMEMALLOC | GFP_NOWAIT,
1615 		.nid = target_nid,
1616 		.nmask = &allowed_mask
1617 	};
1618 
1619 	if (list_empty(demote_folios))
1620 		return 0;
1621 
1622 	if (target_nid == NUMA_NO_NODE)
1623 		return 0;
1624 
1625 	node_get_allowed_targets(pgdat, &allowed_mask);
1626 
1627 	/* Demotion ignores all cpuset and mempolicy settings */
1628 	migrate_pages(demote_folios, alloc_demote_page, NULL,
1629 		      (unsigned long)&mtc, MIGRATE_ASYNC, MR_DEMOTION,
1630 		      &nr_succeeded);
1631 
1632 	__count_vm_events(PGDEMOTE_KSWAPD + reclaimer_offset(), nr_succeeded);
1633 
1634 	return nr_succeeded;
1635 }
1636 
1637 static bool may_enter_fs(struct folio *folio, gfp_t gfp_mask)
1638 {
1639 	if (gfp_mask & __GFP_FS)
1640 		return true;
1641 	if (!folio_test_swapcache(folio) || !(gfp_mask & __GFP_IO))
1642 		return false;
1643 	/*
1644 	 * We can "enter_fs" for swap-cache with only __GFP_IO
1645 	 * providing this isn't SWP_FS_OPS.
1646 	 * ->flags can be updated non-atomicially (scan_swap_map_slots),
1647 	 * but that will never affect SWP_FS_OPS, so the data_race
1648 	 * is safe.
1649 	 */
1650 	return !data_race(folio_swap_flags(folio) & SWP_FS_OPS);
1651 }
1652 
1653 /*
1654  * shrink_folio_list() returns the number of reclaimed pages
1655  */
1656 static unsigned int shrink_folio_list(struct list_head *folio_list,
1657 		struct pglist_data *pgdat, struct scan_control *sc,
1658 		struct reclaim_stat *stat, bool ignore_references)
1659 {
1660 	LIST_HEAD(ret_folios);
1661 	LIST_HEAD(free_folios);
1662 	LIST_HEAD(demote_folios);
1663 	unsigned int nr_reclaimed = 0;
1664 	unsigned int pgactivate = 0;
1665 	bool do_demote_pass;
1666 	struct swap_iocb *plug = NULL;
1667 
1668 	memset(stat, 0, sizeof(*stat));
1669 	cond_resched();
1670 	do_demote_pass = can_demote(pgdat->node_id, sc);
1671 
1672 retry:
1673 	while (!list_empty(folio_list)) {
1674 		struct address_space *mapping;
1675 		struct folio *folio;
1676 		enum folio_references references = FOLIOREF_RECLAIM;
1677 		bool dirty, writeback;
1678 		unsigned int nr_pages;
1679 
1680 		cond_resched();
1681 
1682 		folio = lru_to_folio(folio_list);
1683 		list_del(&folio->lru);
1684 
1685 		if (!folio_trylock(folio))
1686 			goto keep;
1687 
1688 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
1689 
1690 		nr_pages = folio_nr_pages(folio);
1691 
1692 		/* Account the number of base pages */
1693 		sc->nr_scanned += nr_pages;
1694 
1695 		if (unlikely(!folio_evictable(folio)))
1696 			goto activate_locked;
1697 
1698 		if (!sc->may_unmap && folio_mapped(folio))
1699 			goto keep_locked;
1700 
1701 		/* folio_update_gen() tried to promote this page? */
1702 		if (lru_gen_enabled() && !ignore_references &&
1703 		    folio_mapped(folio) && folio_test_referenced(folio))
1704 			goto keep_locked;
1705 
1706 		/*
1707 		 * The number of dirty pages determines if a node is marked
1708 		 * reclaim_congested. kswapd will stall and start writing
1709 		 * folios if the tail of the LRU is all dirty unqueued folios.
1710 		 */
1711 		folio_check_dirty_writeback(folio, &dirty, &writeback);
1712 		if (dirty || writeback)
1713 			stat->nr_dirty += nr_pages;
1714 
1715 		if (dirty && !writeback)
1716 			stat->nr_unqueued_dirty += nr_pages;
1717 
1718 		/*
1719 		 * Treat this folio as congested if folios are cycling
1720 		 * through the LRU so quickly that the folios marked
1721 		 * for immediate reclaim are making it to the end of
1722 		 * the LRU a second time.
1723 		 */
1724 		if (writeback && folio_test_reclaim(folio))
1725 			stat->nr_congested += nr_pages;
1726 
1727 		/*
1728 		 * If a folio at the tail of the LRU is under writeback, there
1729 		 * are three cases to consider.
1730 		 *
1731 		 * 1) If reclaim is encountering an excessive number
1732 		 *    of folios under writeback and this folio has both
1733 		 *    the writeback and reclaim flags set, then it
1734 		 *    indicates that folios are being queued for I/O but
1735 		 *    are being recycled through the LRU before the I/O
1736 		 *    can complete. Waiting on the folio itself risks an
1737 		 *    indefinite stall if it is impossible to writeback
1738 		 *    the folio due to I/O error or disconnected storage
1739 		 *    so instead note that the LRU is being scanned too
1740 		 *    quickly and the caller can stall after the folio
1741 		 *    list has been processed.
1742 		 *
1743 		 * 2) Global or new memcg reclaim encounters a folio that is
1744 		 *    not marked for immediate reclaim, or the caller does not
1745 		 *    have __GFP_FS (or __GFP_IO if it's simply going to swap,
1746 		 *    not to fs). In this case mark the folio for immediate
1747 		 *    reclaim and continue scanning.
1748 		 *
1749 		 *    Require may_enter_fs() because we would wait on fs, which
1750 		 *    may not have submitted I/O yet. And the loop driver might
1751 		 *    enter reclaim, and deadlock if it waits on a folio for
1752 		 *    which it is needed to do the write (loop masks off
1753 		 *    __GFP_IO|__GFP_FS for this reason); but more thought
1754 		 *    would probably show more reasons.
1755 		 *
1756 		 * 3) Legacy memcg encounters a folio that already has the
1757 		 *    reclaim flag set. memcg does not have any dirty folio
1758 		 *    throttling so we could easily OOM just because too many
1759 		 *    folios are in writeback and there is nothing else to
1760 		 *    reclaim. Wait for the writeback to complete.
1761 		 *
1762 		 * In cases 1) and 2) we activate the folios to get them out of
1763 		 * the way while we continue scanning for clean folios on the
1764 		 * inactive list and refilling from the active list. The
1765 		 * observation here is that waiting for disk writes is more
1766 		 * expensive than potentially causing reloads down the line.
1767 		 * Since they're marked for immediate reclaim, they won't put
1768 		 * memory pressure on the cache working set any longer than it
1769 		 * takes to write them to disk.
1770 		 */
1771 		if (folio_test_writeback(folio)) {
1772 			/* Case 1 above */
1773 			if (current_is_kswapd() &&
1774 			    folio_test_reclaim(folio) &&
1775 			    test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
1776 				stat->nr_immediate += nr_pages;
1777 				goto activate_locked;
1778 
1779 			/* Case 2 above */
1780 			} else if (writeback_throttling_sane(sc) ||
1781 			    !folio_test_reclaim(folio) ||
1782 			    !may_enter_fs(folio, sc->gfp_mask)) {
1783 				/*
1784 				 * This is slightly racy -
1785 				 * folio_end_writeback() might have
1786 				 * just cleared the reclaim flag, then
1787 				 * setting the reclaim flag here ends up
1788 				 * interpreted as the readahead flag - but
1789 				 * that does not matter enough to care.
1790 				 * What we do want is for this folio to
1791 				 * have the reclaim flag set next time
1792 				 * memcg reclaim reaches the tests above,
1793 				 * so it will then wait for writeback to
1794 				 * avoid OOM; and it's also appropriate
1795 				 * in global reclaim.
1796 				 */
1797 				folio_set_reclaim(folio);
1798 				stat->nr_writeback += nr_pages;
1799 				goto activate_locked;
1800 
1801 			/* Case 3 above */
1802 			} else {
1803 				folio_unlock(folio);
1804 				folio_wait_writeback(folio);
1805 				/* then go back and try same folio again */
1806 				list_add_tail(&folio->lru, folio_list);
1807 				continue;
1808 			}
1809 		}
1810 
1811 		if (!ignore_references)
1812 			references = folio_check_references(folio, sc);
1813 
1814 		switch (references) {
1815 		case FOLIOREF_ACTIVATE:
1816 			goto activate_locked;
1817 		case FOLIOREF_KEEP:
1818 			stat->nr_ref_keep += nr_pages;
1819 			goto keep_locked;
1820 		case FOLIOREF_RECLAIM:
1821 		case FOLIOREF_RECLAIM_CLEAN:
1822 			; /* try to reclaim the folio below */
1823 		}
1824 
1825 		/*
1826 		 * Before reclaiming the folio, try to relocate
1827 		 * its contents to another node.
1828 		 */
1829 		if (do_demote_pass &&
1830 		    (thp_migration_supported() || !folio_test_large(folio))) {
1831 			list_add(&folio->lru, &demote_folios);
1832 			folio_unlock(folio);
1833 			continue;
1834 		}
1835 
1836 		/*
1837 		 * Anonymous process memory has backing store?
1838 		 * Try to allocate it some swap space here.
1839 		 * Lazyfree folio could be freed directly
1840 		 */
1841 		if (folio_test_anon(folio) && folio_test_swapbacked(folio)) {
1842 			if (!folio_test_swapcache(folio)) {
1843 				if (!(sc->gfp_mask & __GFP_IO))
1844 					goto keep_locked;
1845 				if (folio_maybe_dma_pinned(folio))
1846 					goto keep_locked;
1847 				if (folio_test_large(folio)) {
1848 					/* cannot split folio, skip it */
1849 					if (!can_split_folio(folio, NULL))
1850 						goto activate_locked;
1851 					/*
1852 					 * Split folios without a PMD map right
1853 					 * away. Chances are some or all of the
1854 					 * tail pages can be freed without IO.
1855 					 */
1856 					if (!folio_entire_mapcount(folio) &&
1857 					    split_folio_to_list(folio,
1858 								folio_list))
1859 						goto activate_locked;
1860 				}
1861 				if (!add_to_swap(folio)) {
1862 					if (!folio_test_large(folio))
1863 						goto activate_locked_split;
1864 					/* Fallback to swap normal pages */
1865 					if (split_folio_to_list(folio,
1866 								folio_list))
1867 						goto activate_locked;
1868 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1869 					count_vm_event(THP_SWPOUT_FALLBACK);
1870 #endif
1871 					if (!add_to_swap(folio))
1872 						goto activate_locked_split;
1873 				}
1874 			}
1875 		} else if (folio_test_swapbacked(folio) &&
1876 			   folio_test_large(folio)) {
1877 			/* Split shmem folio */
1878 			if (split_folio_to_list(folio, folio_list))
1879 				goto keep_locked;
1880 		}
1881 
1882 		/*
1883 		 * If the folio was split above, the tail pages will make
1884 		 * their own pass through this function and be accounted
1885 		 * then.
1886 		 */
1887 		if ((nr_pages > 1) && !folio_test_large(folio)) {
1888 			sc->nr_scanned -= (nr_pages - 1);
1889 			nr_pages = 1;
1890 		}
1891 
1892 		/*
1893 		 * The folio is mapped into the page tables of one or more
1894 		 * processes. Try to unmap it here.
1895 		 */
1896 		if (folio_mapped(folio)) {
1897 			enum ttu_flags flags = TTU_BATCH_FLUSH;
1898 			bool was_swapbacked = folio_test_swapbacked(folio);
1899 
1900 			if (folio_test_pmd_mappable(folio))
1901 				flags |= TTU_SPLIT_HUGE_PMD;
1902 
1903 			try_to_unmap(folio, flags);
1904 			if (folio_mapped(folio)) {
1905 				stat->nr_unmap_fail += nr_pages;
1906 				if (!was_swapbacked &&
1907 				    folio_test_swapbacked(folio))
1908 					stat->nr_lazyfree_fail += nr_pages;
1909 				goto activate_locked;
1910 			}
1911 		}
1912 
1913 		mapping = folio_mapping(folio);
1914 		if (folio_test_dirty(folio)) {
1915 			/*
1916 			 * Only kswapd can writeback filesystem folios
1917 			 * to avoid risk of stack overflow. But avoid
1918 			 * injecting inefficient single-folio I/O into
1919 			 * flusher writeback as much as possible: only
1920 			 * write folios when we've encountered many
1921 			 * dirty folios, and when we've already scanned
1922 			 * the rest of the LRU for clean folios and see
1923 			 * the same dirty folios again (with the reclaim
1924 			 * flag set).
1925 			 */
1926 			if (folio_is_file_lru(folio) &&
1927 			    (!current_is_kswapd() ||
1928 			     !folio_test_reclaim(folio) ||
1929 			     !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
1930 				/*
1931 				 * Immediately reclaim when written back.
1932 				 * Similar in principle to folio_deactivate()
1933 				 * except we already have the folio isolated
1934 				 * and know it's dirty
1935 				 */
1936 				node_stat_mod_folio(folio, NR_VMSCAN_IMMEDIATE,
1937 						nr_pages);
1938 				folio_set_reclaim(folio);
1939 
1940 				goto activate_locked;
1941 			}
1942 
1943 			if (references == FOLIOREF_RECLAIM_CLEAN)
1944 				goto keep_locked;
1945 			if (!may_enter_fs(folio, sc->gfp_mask))
1946 				goto keep_locked;
1947 			if (!sc->may_writepage)
1948 				goto keep_locked;
1949 
1950 			/*
1951 			 * Folio is dirty. Flush the TLB if a writable entry
1952 			 * potentially exists to avoid CPU writes after I/O
1953 			 * starts and then write it out here.
1954 			 */
1955 			try_to_unmap_flush_dirty();
1956 			switch (pageout(folio, mapping, &plug)) {
1957 			case PAGE_KEEP:
1958 				goto keep_locked;
1959 			case PAGE_ACTIVATE:
1960 				goto activate_locked;
1961 			case PAGE_SUCCESS:
1962 				stat->nr_pageout += nr_pages;
1963 
1964 				if (folio_test_writeback(folio))
1965 					goto keep;
1966 				if (folio_test_dirty(folio))
1967 					goto keep;
1968 
1969 				/*
1970 				 * A synchronous write - probably a ramdisk.  Go
1971 				 * ahead and try to reclaim the folio.
1972 				 */
1973 				if (!folio_trylock(folio))
1974 					goto keep;
1975 				if (folio_test_dirty(folio) ||
1976 				    folio_test_writeback(folio))
1977 					goto keep_locked;
1978 				mapping = folio_mapping(folio);
1979 				fallthrough;
1980 			case PAGE_CLEAN:
1981 				; /* try to free the folio below */
1982 			}
1983 		}
1984 
1985 		/*
1986 		 * If the folio has buffers, try to free the buffer
1987 		 * mappings associated with this folio. If we succeed
1988 		 * we try to free the folio as well.
1989 		 *
1990 		 * We do this even if the folio is dirty.
1991 		 * filemap_release_folio() does not perform I/O, but it
1992 		 * is possible for a folio to have the dirty flag set,
1993 		 * but it is actually clean (all its buffers are clean).
1994 		 * This happens if the buffers were written out directly,
1995 		 * with submit_bh(). ext3 will do this, as well as
1996 		 * the blockdev mapping.  filemap_release_folio() will
1997 		 * discover that cleanness and will drop the buffers
1998 		 * and mark the folio clean - it can be freed.
1999 		 *
2000 		 * Rarely, folios can have buffers and no ->mapping.
2001 		 * These are the folios which were not successfully
2002 		 * invalidated in truncate_cleanup_folio().  We try to
2003 		 * drop those buffers here and if that worked, and the
2004 		 * folio is no longer mapped into process address space
2005 		 * (refcount == 1) it can be freed.  Otherwise, leave
2006 		 * the folio on the LRU so it is swappable.
2007 		 */
2008 		if (folio_has_private(folio)) {
2009 			if (!filemap_release_folio(folio, sc->gfp_mask))
2010 				goto activate_locked;
2011 			if (!mapping && folio_ref_count(folio) == 1) {
2012 				folio_unlock(folio);
2013 				if (folio_put_testzero(folio))
2014 					goto free_it;
2015 				else {
2016 					/*
2017 					 * rare race with speculative reference.
2018 					 * the speculative reference will free
2019 					 * this folio shortly, so we may
2020 					 * increment nr_reclaimed here (and
2021 					 * leave it off the LRU).
2022 					 */
2023 					nr_reclaimed += nr_pages;
2024 					continue;
2025 				}
2026 			}
2027 		}
2028 
2029 		if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
2030 			/* follow __remove_mapping for reference */
2031 			if (!folio_ref_freeze(folio, 1))
2032 				goto keep_locked;
2033 			/*
2034 			 * The folio has only one reference left, which is
2035 			 * from the isolation. After the caller puts the
2036 			 * folio back on the lru and drops the reference, the
2037 			 * folio will be freed anyway. It doesn't matter
2038 			 * which lru it goes on. So we don't bother checking
2039 			 * the dirty flag here.
2040 			 */
2041 			count_vm_events(PGLAZYFREED, nr_pages);
2042 			count_memcg_folio_events(folio, PGLAZYFREED, nr_pages);
2043 		} else if (!mapping || !__remove_mapping(mapping, folio, true,
2044 							 sc->target_mem_cgroup))
2045 			goto keep_locked;
2046 
2047 		folio_unlock(folio);
2048 free_it:
2049 		/*
2050 		 * Folio may get swapped out as a whole, need to account
2051 		 * all pages in it.
2052 		 */
2053 		nr_reclaimed += nr_pages;
2054 
2055 		/*
2056 		 * Is there need to periodically free_folio_list? It would
2057 		 * appear not as the counts should be low
2058 		 */
2059 		if (unlikely(folio_test_large(folio)))
2060 			destroy_large_folio(folio);
2061 		else
2062 			list_add(&folio->lru, &free_folios);
2063 		continue;
2064 
2065 activate_locked_split:
2066 		/*
2067 		 * The tail pages that are failed to add into swap cache
2068 		 * reach here.  Fixup nr_scanned and nr_pages.
2069 		 */
2070 		if (nr_pages > 1) {
2071 			sc->nr_scanned -= (nr_pages - 1);
2072 			nr_pages = 1;
2073 		}
2074 activate_locked:
2075 		/* Not a candidate for swapping, so reclaim swap space. */
2076 		if (folio_test_swapcache(folio) &&
2077 		    (mem_cgroup_swap_full(folio) || folio_test_mlocked(folio)))
2078 			folio_free_swap(folio);
2079 		VM_BUG_ON_FOLIO(folio_test_active(folio), folio);
2080 		if (!folio_test_mlocked(folio)) {
2081 			int type = folio_is_file_lru(folio);
2082 			folio_set_active(folio);
2083 			stat->nr_activate[type] += nr_pages;
2084 			count_memcg_folio_events(folio, PGACTIVATE, nr_pages);
2085 		}
2086 keep_locked:
2087 		folio_unlock(folio);
2088 keep:
2089 		list_add(&folio->lru, &ret_folios);
2090 		VM_BUG_ON_FOLIO(folio_test_lru(folio) ||
2091 				folio_test_unevictable(folio), folio);
2092 	}
2093 	/* 'folio_list' is always empty here */
2094 
2095 	/* Migrate folios selected for demotion */
2096 	nr_reclaimed += demote_folio_list(&demote_folios, pgdat);
2097 	/* Folios that could not be demoted are still in @demote_folios */
2098 	if (!list_empty(&demote_folios)) {
2099 		/* Folios which weren't demoted go back on @folio_list */
2100 		list_splice_init(&demote_folios, folio_list);
2101 
2102 		/*
2103 		 * goto retry to reclaim the undemoted folios in folio_list if
2104 		 * desired.
2105 		 *
2106 		 * Reclaiming directly from top tier nodes is not often desired
2107 		 * due to it breaking the LRU ordering: in general memory
2108 		 * should be reclaimed from lower tier nodes and demoted from
2109 		 * top tier nodes.
2110 		 *
2111 		 * However, disabling reclaim from top tier nodes entirely
2112 		 * would cause ooms in edge scenarios where lower tier memory
2113 		 * is unreclaimable for whatever reason, eg memory being
2114 		 * mlocked or too hot to reclaim. We can disable reclaim
2115 		 * from top tier nodes in proactive reclaim though as that is
2116 		 * not real memory pressure.
2117 		 */
2118 		if (!sc->proactive) {
2119 			do_demote_pass = false;
2120 			goto retry;
2121 		}
2122 	}
2123 
2124 	pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
2125 
2126 	mem_cgroup_uncharge_list(&free_folios);
2127 	try_to_unmap_flush();
2128 	free_unref_page_list(&free_folios);
2129 
2130 	list_splice(&ret_folios, folio_list);
2131 	count_vm_events(PGACTIVATE, pgactivate);
2132 
2133 	if (plug)
2134 		swap_write_unplug(plug);
2135 	return nr_reclaimed;
2136 }
2137 
2138 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
2139 					   struct list_head *folio_list)
2140 {
2141 	struct scan_control sc = {
2142 		.gfp_mask = GFP_KERNEL,
2143 		.may_unmap = 1,
2144 	};
2145 	struct reclaim_stat stat;
2146 	unsigned int nr_reclaimed;
2147 	struct folio *folio, *next;
2148 	LIST_HEAD(clean_folios);
2149 	unsigned int noreclaim_flag;
2150 
2151 	list_for_each_entry_safe(folio, next, folio_list, lru) {
2152 		if (!folio_test_hugetlb(folio) && folio_is_file_lru(folio) &&
2153 		    !folio_test_dirty(folio) && !__folio_test_movable(folio) &&
2154 		    !folio_test_unevictable(folio)) {
2155 			folio_clear_active(folio);
2156 			list_move(&folio->lru, &clean_folios);
2157 		}
2158 	}
2159 
2160 	/*
2161 	 * We should be safe here since we are only dealing with file pages and
2162 	 * we are not kswapd and therefore cannot write dirty file pages. But
2163 	 * call memalloc_noreclaim_save() anyway, just in case these conditions
2164 	 * change in the future.
2165 	 */
2166 	noreclaim_flag = memalloc_noreclaim_save();
2167 	nr_reclaimed = shrink_folio_list(&clean_folios, zone->zone_pgdat, &sc,
2168 					&stat, true);
2169 	memalloc_noreclaim_restore(noreclaim_flag);
2170 
2171 	list_splice(&clean_folios, folio_list);
2172 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2173 			    -(long)nr_reclaimed);
2174 	/*
2175 	 * Since lazyfree pages are isolated from file LRU from the beginning,
2176 	 * they will rotate back to anonymous LRU in the end if it failed to
2177 	 * discard so isolated count will be mismatched.
2178 	 * Compensate the isolated count for both LRU lists.
2179 	 */
2180 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
2181 			    stat.nr_lazyfree_fail);
2182 	mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
2183 			    -(long)stat.nr_lazyfree_fail);
2184 	return nr_reclaimed;
2185 }
2186 
2187 /*
2188  * Update LRU sizes after isolating pages. The LRU size updates must
2189  * be complete before mem_cgroup_update_lru_size due to a sanity check.
2190  */
2191 static __always_inline void update_lru_sizes(struct lruvec *lruvec,
2192 			enum lru_list lru, unsigned long *nr_zone_taken)
2193 {
2194 	int zid;
2195 
2196 	for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2197 		if (!nr_zone_taken[zid])
2198 			continue;
2199 
2200 		update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
2201 	}
2202 
2203 }
2204 
2205 /*
2206  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
2207  *
2208  * lruvec->lru_lock is heavily contended.  Some of the functions that
2209  * shrink the lists perform better by taking out a batch of pages
2210  * and working on them outside the LRU lock.
2211  *
2212  * For pagecache intensive workloads, this function is the hottest
2213  * spot in the kernel (apart from copy_*_user functions).
2214  *
2215  * Lru_lock must be held before calling this function.
2216  *
2217  * @nr_to_scan:	The number of eligible pages to look through on the list.
2218  * @lruvec:	The LRU vector to pull pages from.
2219  * @dst:	The temp list to put pages on to.
2220  * @nr_scanned:	The number of pages that were scanned.
2221  * @sc:		The scan_control struct for this reclaim session
2222  * @lru:	LRU list id for isolating
2223  *
2224  * returns how many pages were moved onto *@dst.
2225  */
2226 static unsigned long isolate_lru_folios(unsigned long nr_to_scan,
2227 		struct lruvec *lruvec, struct list_head *dst,
2228 		unsigned long *nr_scanned, struct scan_control *sc,
2229 		enum lru_list lru)
2230 {
2231 	struct list_head *src = &lruvec->lists[lru];
2232 	unsigned long nr_taken = 0;
2233 	unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
2234 	unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
2235 	unsigned long skipped = 0;
2236 	unsigned long scan, total_scan, nr_pages;
2237 	LIST_HEAD(folios_skipped);
2238 
2239 	total_scan = 0;
2240 	scan = 0;
2241 	while (scan < nr_to_scan && !list_empty(src)) {
2242 		struct list_head *move_to = src;
2243 		struct folio *folio;
2244 
2245 		folio = lru_to_folio(src);
2246 		prefetchw_prev_lru_folio(folio, src, flags);
2247 
2248 		nr_pages = folio_nr_pages(folio);
2249 		total_scan += nr_pages;
2250 
2251 		if (folio_zonenum(folio) > sc->reclaim_idx) {
2252 			nr_skipped[folio_zonenum(folio)] += nr_pages;
2253 			move_to = &folios_skipped;
2254 			goto move;
2255 		}
2256 
2257 		/*
2258 		 * Do not count skipped folios because that makes the function
2259 		 * return with no isolated folios if the LRU mostly contains
2260 		 * ineligible folios.  This causes the VM to not reclaim any
2261 		 * folios, triggering a premature OOM.
2262 		 * Account all pages in a folio.
2263 		 */
2264 		scan += nr_pages;
2265 
2266 		if (!folio_test_lru(folio))
2267 			goto move;
2268 		if (!sc->may_unmap && folio_mapped(folio))
2269 			goto move;
2270 
2271 		/*
2272 		 * Be careful not to clear the lru flag until after we're
2273 		 * sure the folio is not being freed elsewhere -- the
2274 		 * folio release code relies on it.
2275 		 */
2276 		if (unlikely(!folio_try_get(folio)))
2277 			goto move;
2278 
2279 		if (!folio_test_clear_lru(folio)) {
2280 			/* Another thread is already isolating this folio */
2281 			folio_put(folio);
2282 			goto move;
2283 		}
2284 
2285 		nr_taken += nr_pages;
2286 		nr_zone_taken[folio_zonenum(folio)] += nr_pages;
2287 		move_to = dst;
2288 move:
2289 		list_move(&folio->lru, move_to);
2290 	}
2291 
2292 	/*
2293 	 * Splice any skipped folios to the start of the LRU list. Note that
2294 	 * this disrupts the LRU order when reclaiming for lower zones but
2295 	 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2296 	 * scanning would soon rescan the same folios to skip and waste lots
2297 	 * of cpu cycles.
2298 	 */
2299 	if (!list_empty(&folios_skipped)) {
2300 		int zid;
2301 
2302 		list_splice(&folios_skipped, src);
2303 		for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2304 			if (!nr_skipped[zid])
2305 				continue;
2306 
2307 			__count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
2308 			skipped += nr_skipped[zid];
2309 		}
2310 	}
2311 	*nr_scanned = total_scan;
2312 	trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
2313 				    total_scan, skipped, nr_taken,
2314 				    sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
2315 	update_lru_sizes(lruvec, lru, nr_zone_taken);
2316 	return nr_taken;
2317 }
2318 
2319 /**
2320  * folio_isolate_lru() - Try to isolate a folio from its LRU list.
2321  * @folio: Folio to isolate from its LRU list.
2322  *
2323  * Isolate a @folio from an LRU list and adjust the vmstat statistic
2324  * corresponding to whatever LRU list the folio was on.
2325  *
2326  * The folio will have its LRU flag cleared.  If it was found on the
2327  * active list, it will have the Active flag set.  If it was found on the
2328  * unevictable list, it will have the Unevictable flag set.  These flags
2329  * may need to be cleared by the caller before letting the page go.
2330  *
2331  * Context:
2332  *
2333  * (1) Must be called with an elevated refcount on the folio. This is a
2334  *     fundamental difference from isolate_lru_folios() (which is called
2335  *     without a stable reference).
2336  * (2) The lru_lock must not be held.
2337  * (3) Interrupts must be enabled.
2338  *
2339  * Return: 0 if the folio was removed from an LRU list.
2340  * -EBUSY if the folio was not on an LRU list.
2341  */
2342 int folio_isolate_lru(struct folio *folio)
2343 {
2344 	int ret = -EBUSY;
2345 
2346 	VM_BUG_ON_FOLIO(!folio_ref_count(folio), folio);
2347 
2348 	if (folio_test_clear_lru(folio)) {
2349 		struct lruvec *lruvec;
2350 
2351 		folio_get(folio);
2352 		lruvec = folio_lruvec_lock_irq(folio);
2353 		lruvec_del_folio(lruvec, folio);
2354 		unlock_page_lruvec_irq(lruvec);
2355 		ret = 0;
2356 	}
2357 
2358 	return ret;
2359 }
2360 
2361 /*
2362  * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
2363  * then get rescheduled. When there are massive number of tasks doing page
2364  * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2365  * the LRU list will go small and be scanned faster than necessary, leading to
2366  * unnecessary swapping, thrashing and OOM.
2367  */
2368 static int too_many_isolated(struct pglist_data *pgdat, int file,
2369 		struct scan_control *sc)
2370 {
2371 	unsigned long inactive, isolated;
2372 	bool too_many;
2373 
2374 	if (current_is_kswapd())
2375 		return 0;
2376 
2377 	if (!writeback_throttling_sane(sc))
2378 		return 0;
2379 
2380 	if (file) {
2381 		inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2382 		isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
2383 	} else {
2384 		inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2385 		isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
2386 	}
2387 
2388 	/*
2389 	 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2390 	 * won't get blocked by normal direct-reclaimers, forming a circular
2391 	 * deadlock.
2392 	 */
2393 	if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
2394 		inactive >>= 3;
2395 
2396 	too_many = isolated > inactive;
2397 
2398 	/* Wake up tasks throttled due to too_many_isolated. */
2399 	if (!too_many)
2400 		wake_throttle_isolated(pgdat);
2401 
2402 	return too_many;
2403 }
2404 
2405 /*
2406  * move_folios_to_lru() moves folios from private @list to appropriate LRU list.
2407  * On return, @list is reused as a list of folios to be freed by the caller.
2408  *
2409  * Returns the number of pages moved to the given lruvec.
2410  */
2411 static unsigned int move_folios_to_lru(struct lruvec *lruvec,
2412 		struct list_head *list)
2413 {
2414 	int nr_pages, nr_moved = 0;
2415 	LIST_HEAD(folios_to_free);
2416 
2417 	while (!list_empty(list)) {
2418 		struct folio *folio = lru_to_folio(list);
2419 
2420 		VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
2421 		list_del(&folio->lru);
2422 		if (unlikely(!folio_evictable(folio))) {
2423 			spin_unlock_irq(&lruvec->lru_lock);
2424 			folio_putback_lru(folio);
2425 			spin_lock_irq(&lruvec->lru_lock);
2426 			continue;
2427 		}
2428 
2429 		/*
2430 		 * The folio_set_lru needs to be kept here for list integrity.
2431 		 * Otherwise:
2432 		 *   #0 move_folios_to_lru             #1 release_pages
2433 		 *   if (!folio_put_testzero())
2434 		 *				      if (folio_put_testzero())
2435 		 *				        !lru //skip lru_lock
2436 		 *     folio_set_lru()
2437 		 *     list_add(&folio->lru,)
2438 		 *                                        list_add(&folio->lru,)
2439 		 */
2440 		folio_set_lru(folio);
2441 
2442 		if (unlikely(folio_put_testzero(folio))) {
2443 			__folio_clear_lru_flags(folio);
2444 
2445 			if (unlikely(folio_test_large(folio))) {
2446 				spin_unlock_irq(&lruvec->lru_lock);
2447 				destroy_large_folio(folio);
2448 				spin_lock_irq(&lruvec->lru_lock);
2449 			} else
2450 				list_add(&folio->lru, &folios_to_free);
2451 
2452 			continue;
2453 		}
2454 
2455 		/*
2456 		 * All pages were isolated from the same lruvec (and isolation
2457 		 * inhibits memcg migration).
2458 		 */
2459 		VM_BUG_ON_FOLIO(!folio_matches_lruvec(folio, lruvec), folio);
2460 		lruvec_add_folio(lruvec, folio);
2461 		nr_pages = folio_nr_pages(folio);
2462 		nr_moved += nr_pages;
2463 		if (folio_test_active(folio))
2464 			workingset_age_nonresident(lruvec, nr_pages);
2465 	}
2466 
2467 	/*
2468 	 * To save our caller's stack, now use input list for pages to free.
2469 	 */
2470 	list_splice(&folios_to_free, list);
2471 
2472 	return nr_moved;
2473 }
2474 
2475 /*
2476  * If a kernel thread (such as nfsd for loop-back mounts) services a backing
2477  * device by writing to the page cache it sets PF_LOCAL_THROTTLE. In this case
2478  * we should not throttle.  Otherwise it is safe to do so.
2479  */
2480 static int current_may_throttle(void)
2481 {
2482 	return !(current->flags & PF_LOCAL_THROTTLE);
2483 }
2484 
2485 /*
2486  * shrink_inactive_list() is a helper for shrink_node().  It returns the number
2487  * of reclaimed pages
2488  */
2489 static unsigned long shrink_inactive_list(unsigned long nr_to_scan,
2490 		struct lruvec *lruvec, struct scan_control *sc,
2491 		enum lru_list lru)
2492 {
2493 	LIST_HEAD(folio_list);
2494 	unsigned long nr_scanned;
2495 	unsigned int nr_reclaimed = 0;
2496 	unsigned long nr_taken;
2497 	struct reclaim_stat stat;
2498 	bool file = is_file_lru(lru);
2499 	enum vm_event_item item;
2500 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2501 	bool stalled = false;
2502 
2503 	while (unlikely(too_many_isolated(pgdat, file, sc))) {
2504 		if (stalled)
2505 			return 0;
2506 
2507 		/* wait a bit for the reclaimer. */
2508 		stalled = true;
2509 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_ISOLATED);
2510 
2511 		/* We are about to die and free our memory. Return now. */
2512 		if (fatal_signal_pending(current))
2513 			return SWAP_CLUSTER_MAX;
2514 	}
2515 
2516 	lru_add_drain();
2517 
2518 	spin_lock_irq(&lruvec->lru_lock);
2519 
2520 	nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &folio_list,
2521 				     &nr_scanned, sc, lru);
2522 
2523 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2524 	item = PGSCAN_KSWAPD + reclaimer_offset();
2525 	if (!cgroup_reclaim(sc))
2526 		__count_vm_events(item, nr_scanned);
2527 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
2528 	__count_vm_events(PGSCAN_ANON + file, nr_scanned);
2529 
2530 	spin_unlock_irq(&lruvec->lru_lock);
2531 
2532 	if (nr_taken == 0)
2533 		return 0;
2534 
2535 	nr_reclaimed = shrink_folio_list(&folio_list, pgdat, sc, &stat, false);
2536 
2537 	spin_lock_irq(&lruvec->lru_lock);
2538 	move_folios_to_lru(lruvec, &folio_list);
2539 
2540 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2541 	item = PGSTEAL_KSWAPD + reclaimer_offset();
2542 	if (!cgroup_reclaim(sc))
2543 		__count_vm_events(item, nr_reclaimed);
2544 	__count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
2545 	__count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
2546 	spin_unlock_irq(&lruvec->lru_lock);
2547 
2548 	lru_note_cost(lruvec, file, stat.nr_pageout, nr_scanned - nr_reclaimed);
2549 	mem_cgroup_uncharge_list(&folio_list);
2550 	free_unref_page_list(&folio_list);
2551 
2552 	/*
2553 	 * If dirty folios are scanned that are not queued for IO, it
2554 	 * implies that flushers are not doing their job. This can
2555 	 * happen when memory pressure pushes dirty folios to the end of
2556 	 * the LRU before the dirty limits are breached and the dirty
2557 	 * data has expired. It can also happen when the proportion of
2558 	 * dirty folios grows not through writes but through memory
2559 	 * pressure reclaiming all the clean cache. And in some cases,
2560 	 * the flushers simply cannot keep up with the allocation
2561 	 * rate. Nudge the flusher threads in case they are asleep.
2562 	 */
2563 	if (stat.nr_unqueued_dirty == nr_taken) {
2564 		wakeup_flusher_threads(WB_REASON_VMSCAN);
2565 		/*
2566 		 * For cgroupv1 dirty throttling is achieved by waking up
2567 		 * the kernel flusher here and later waiting on folios
2568 		 * which are in writeback to finish (see shrink_folio_list()).
2569 		 *
2570 		 * Flusher may not be able to issue writeback quickly
2571 		 * enough for cgroupv1 writeback throttling to work
2572 		 * on a large system.
2573 		 */
2574 		if (!writeback_throttling_sane(sc))
2575 			reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
2576 	}
2577 
2578 	sc->nr.dirty += stat.nr_dirty;
2579 	sc->nr.congested += stat.nr_congested;
2580 	sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2581 	sc->nr.writeback += stat.nr_writeback;
2582 	sc->nr.immediate += stat.nr_immediate;
2583 	sc->nr.taken += nr_taken;
2584 	if (file)
2585 		sc->nr.file_taken += nr_taken;
2586 
2587 	trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
2588 			nr_scanned, nr_reclaimed, &stat, sc->priority, file);
2589 	return nr_reclaimed;
2590 }
2591 
2592 /*
2593  * shrink_active_list() moves folios from the active LRU to the inactive LRU.
2594  *
2595  * We move them the other way if the folio is referenced by one or more
2596  * processes.
2597  *
2598  * If the folios are mostly unmapped, the processing is fast and it is
2599  * appropriate to hold lru_lock across the whole operation.  But if
2600  * the folios are mapped, the processing is slow (folio_referenced()), so
2601  * we should drop lru_lock around each folio.  It's impossible to balance
2602  * this, so instead we remove the folios from the LRU while processing them.
2603  * It is safe to rely on the active flag against the non-LRU folios in here
2604  * because nobody will play with that bit on a non-LRU folio.
2605  *
2606  * The downside is that we have to touch folio->_refcount against each folio.
2607  * But we had to alter folio->flags anyway.
2608  */
2609 static void shrink_active_list(unsigned long nr_to_scan,
2610 			       struct lruvec *lruvec,
2611 			       struct scan_control *sc,
2612 			       enum lru_list lru)
2613 {
2614 	unsigned long nr_taken;
2615 	unsigned long nr_scanned;
2616 	unsigned long vm_flags;
2617 	LIST_HEAD(l_hold);	/* The folios which were snipped off */
2618 	LIST_HEAD(l_active);
2619 	LIST_HEAD(l_inactive);
2620 	unsigned nr_deactivate, nr_activate;
2621 	unsigned nr_rotated = 0;
2622 	int file = is_file_lru(lru);
2623 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2624 
2625 	lru_add_drain();
2626 
2627 	spin_lock_irq(&lruvec->lru_lock);
2628 
2629 	nr_taken = isolate_lru_folios(nr_to_scan, lruvec, &l_hold,
2630 				     &nr_scanned, sc, lru);
2631 
2632 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
2633 
2634 	if (!cgroup_reclaim(sc))
2635 		__count_vm_events(PGREFILL, nr_scanned);
2636 	__count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
2637 
2638 	spin_unlock_irq(&lruvec->lru_lock);
2639 
2640 	while (!list_empty(&l_hold)) {
2641 		struct folio *folio;
2642 
2643 		cond_resched();
2644 		folio = lru_to_folio(&l_hold);
2645 		list_del(&folio->lru);
2646 
2647 		if (unlikely(!folio_evictable(folio))) {
2648 			folio_putback_lru(folio);
2649 			continue;
2650 		}
2651 
2652 		if (unlikely(buffer_heads_over_limit)) {
2653 			if (folio_test_private(folio) && folio_trylock(folio)) {
2654 				if (folio_test_private(folio))
2655 					filemap_release_folio(folio, 0);
2656 				folio_unlock(folio);
2657 			}
2658 		}
2659 
2660 		/* Referenced or rmap lock contention: rotate */
2661 		if (folio_referenced(folio, 0, sc->target_mem_cgroup,
2662 				     &vm_flags) != 0) {
2663 			/*
2664 			 * Identify referenced, file-backed active folios and
2665 			 * give them one more trip around the active list. So
2666 			 * that executable code get better chances to stay in
2667 			 * memory under moderate memory pressure.  Anon folios
2668 			 * are not likely to be evicted by use-once streaming
2669 			 * IO, plus JVM can create lots of anon VM_EXEC folios,
2670 			 * so we ignore them here.
2671 			 */
2672 			if ((vm_flags & VM_EXEC) && folio_is_file_lru(folio)) {
2673 				nr_rotated += folio_nr_pages(folio);
2674 				list_add(&folio->lru, &l_active);
2675 				continue;
2676 			}
2677 		}
2678 
2679 		folio_clear_active(folio);	/* we are de-activating */
2680 		folio_set_workingset(folio);
2681 		list_add(&folio->lru, &l_inactive);
2682 	}
2683 
2684 	/*
2685 	 * Move folios back to the lru list.
2686 	 */
2687 	spin_lock_irq(&lruvec->lru_lock);
2688 
2689 	nr_activate = move_folios_to_lru(lruvec, &l_active);
2690 	nr_deactivate = move_folios_to_lru(lruvec, &l_inactive);
2691 	/* Keep all free folios in l_active list */
2692 	list_splice(&l_inactive, &l_active);
2693 
2694 	__count_vm_events(PGDEACTIVATE, nr_deactivate);
2695 	__count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2696 
2697 	__mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
2698 	spin_unlock_irq(&lruvec->lru_lock);
2699 
2700 	if (nr_rotated)
2701 		lru_note_cost(lruvec, file, 0, nr_rotated);
2702 	mem_cgroup_uncharge_list(&l_active);
2703 	free_unref_page_list(&l_active);
2704 	trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2705 			nr_deactivate, nr_rotated, sc->priority, file);
2706 }
2707 
2708 static unsigned int reclaim_folio_list(struct list_head *folio_list,
2709 				      struct pglist_data *pgdat)
2710 {
2711 	struct reclaim_stat dummy_stat;
2712 	unsigned int nr_reclaimed;
2713 	struct folio *folio;
2714 	struct scan_control sc = {
2715 		.gfp_mask = GFP_KERNEL,
2716 		.may_writepage = 1,
2717 		.may_unmap = 1,
2718 		.may_swap = 1,
2719 		.no_demotion = 1,
2720 	};
2721 
2722 	nr_reclaimed = shrink_folio_list(folio_list, pgdat, &sc, &dummy_stat, false);
2723 	while (!list_empty(folio_list)) {
2724 		folio = lru_to_folio(folio_list);
2725 		list_del(&folio->lru);
2726 		folio_putback_lru(folio);
2727 	}
2728 
2729 	return nr_reclaimed;
2730 }
2731 
2732 unsigned long reclaim_pages(struct list_head *folio_list)
2733 {
2734 	int nid;
2735 	unsigned int nr_reclaimed = 0;
2736 	LIST_HEAD(node_folio_list);
2737 	unsigned int noreclaim_flag;
2738 
2739 	if (list_empty(folio_list))
2740 		return nr_reclaimed;
2741 
2742 	noreclaim_flag = memalloc_noreclaim_save();
2743 
2744 	nid = folio_nid(lru_to_folio(folio_list));
2745 	do {
2746 		struct folio *folio = lru_to_folio(folio_list);
2747 
2748 		if (nid == folio_nid(folio)) {
2749 			folio_clear_active(folio);
2750 			list_move(&folio->lru, &node_folio_list);
2751 			continue;
2752 		}
2753 
2754 		nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2755 		nid = folio_nid(lru_to_folio(folio_list));
2756 	} while (!list_empty(folio_list));
2757 
2758 	nr_reclaimed += reclaim_folio_list(&node_folio_list, NODE_DATA(nid));
2759 
2760 	memalloc_noreclaim_restore(noreclaim_flag);
2761 
2762 	return nr_reclaimed;
2763 }
2764 
2765 static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2766 				 struct lruvec *lruvec, struct scan_control *sc)
2767 {
2768 	if (is_active_lru(lru)) {
2769 		if (sc->may_deactivate & (1 << is_file_lru(lru)))
2770 			shrink_active_list(nr_to_scan, lruvec, sc, lru);
2771 		else
2772 			sc->skipped_deactivate = 1;
2773 		return 0;
2774 	}
2775 
2776 	return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2777 }
2778 
2779 /*
2780  * The inactive anon list should be small enough that the VM never has
2781  * to do too much work.
2782  *
2783  * The inactive file list should be small enough to leave most memory
2784  * to the established workingset on the scan-resistant active list,
2785  * but large enough to avoid thrashing the aggregate readahead window.
2786  *
2787  * Both inactive lists should also be large enough that each inactive
2788  * folio has a chance to be referenced again before it is reclaimed.
2789  *
2790  * If that fails and refaulting is observed, the inactive list grows.
2791  *
2792  * The inactive_ratio is the target ratio of ACTIVE to INACTIVE folios
2793  * on this LRU, maintained by the pageout code. An inactive_ratio
2794  * of 3 means 3:1 or 25% of the folios are kept on the inactive list.
2795  *
2796  * total     target    max
2797  * memory    ratio     inactive
2798  * -------------------------------------
2799  *   10MB       1         5MB
2800  *  100MB       1        50MB
2801  *    1GB       3       250MB
2802  *   10GB      10       0.9GB
2803  *  100GB      31         3GB
2804  *    1TB     101        10GB
2805  *   10TB     320        32GB
2806  */
2807 static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
2808 {
2809 	enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
2810 	unsigned long inactive, active;
2811 	unsigned long inactive_ratio;
2812 	unsigned long gb;
2813 
2814 	inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2815 	active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
2816 
2817 	gb = (inactive + active) >> (30 - PAGE_SHIFT);
2818 	if (gb)
2819 		inactive_ratio = int_sqrt(10 * gb);
2820 	else
2821 		inactive_ratio = 1;
2822 
2823 	return inactive * inactive_ratio < active;
2824 }
2825 
2826 enum scan_balance {
2827 	SCAN_EQUAL,
2828 	SCAN_FRACT,
2829 	SCAN_ANON,
2830 	SCAN_FILE,
2831 };
2832 
2833 static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2834 {
2835 	unsigned long file;
2836 	struct lruvec *target_lruvec;
2837 
2838 	if (lru_gen_enabled())
2839 		return;
2840 
2841 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2842 
2843 	/*
2844 	 * Flush the memory cgroup stats, so that we read accurate per-memcg
2845 	 * lruvec stats for heuristics.
2846 	 */
2847 	mem_cgroup_flush_stats();
2848 
2849 	/*
2850 	 * Determine the scan balance between anon and file LRUs.
2851 	 */
2852 	spin_lock_irq(&target_lruvec->lru_lock);
2853 	sc->anon_cost = target_lruvec->anon_cost;
2854 	sc->file_cost = target_lruvec->file_cost;
2855 	spin_unlock_irq(&target_lruvec->lru_lock);
2856 
2857 	/*
2858 	 * Target desirable inactive:active list ratios for the anon
2859 	 * and file LRU lists.
2860 	 */
2861 	if (!sc->force_deactivate) {
2862 		unsigned long refaults;
2863 
2864 		/*
2865 		 * When refaults are being observed, it means a new
2866 		 * workingset is being established. Deactivate to get
2867 		 * rid of any stale active pages quickly.
2868 		 */
2869 		refaults = lruvec_page_state(target_lruvec,
2870 				WORKINGSET_ACTIVATE_ANON);
2871 		if (refaults != target_lruvec->refaults[WORKINGSET_ANON] ||
2872 			inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2873 			sc->may_deactivate |= DEACTIVATE_ANON;
2874 		else
2875 			sc->may_deactivate &= ~DEACTIVATE_ANON;
2876 
2877 		refaults = lruvec_page_state(target_lruvec,
2878 				WORKINGSET_ACTIVATE_FILE);
2879 		if (refaults != target_lruvec->refaults[WORKINGSET_FILE] ||
2880 		    inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2881 			sc->may_deactivate |= DEACTIVATE_FILE;
2882 		else
2883 			sc->may_deactivate &= ~DEACTIVATE_FILE;
2884 	} else
2885 		sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2886 
2887 	/*
2888 	 * If we have plenty of inactive file pages that aren't
2889 	 * thrashing, try to reclaim those first before touching
2890 	 * anonymous pages.
2891 	 */
2892 	file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2893 	if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2894 		sc->cache_trim_mode = 1;
2895 	else
2896 		sc->cache_trim_mode = 0;
2897 
2898 	/*
2899 	 * Prevent the reclaimer from falling into the cache trap: as
2900 	 * cache pages start out inactive, every cache fault will tip
2901 	 * the scan balance towards the file LRU.  And as the file LRU
2902 	 * shrinks, so does the window for rotation from references.
2903 	 * This means we have a runaway feedback loop where a tiny
2904 	 * thrashing file LRU becomes infinitely more attractive than
2905 	 * anon pages.  Try to detect this based on file LRU size.
2906 	 */
2907 	if (!cgroup_reclaim(sc)) {
2908 		unsigned long total_high_wmark = 0;
2909 		unsigned long free, anon;
2910 		int z;
2911 
2912 		free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2913 		file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2914 			   node_page_state(pgdat, NR_INACTIVE_FILE);
2915 
2916 		for (z = 0; z < MAX_NR_ZONES; z++) {
2917 			struct zone *zone = &pgdat->node_zones[z];
2918 
2919 			if (!managed_zone(zone))
2920 				continue;
2921 
2922 			total_high_wmark += high_wmark_pages(zone);
2923 		}
2924 
2925 		/*
2926 		 * Consider anon: if that's low too, this isn't a
2927 		 * runaway file reclaim problem, but rather just
2928 		 * extreme pressure. Reclaim as per usual then.
2929 		 */
2930 		anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2931 
2932 		sc->file_is_tiny =
2933 			file + free <= total_high_wmark &&
2934 			!(sc->may_deactivate & DEACTIVATE_ANON) &&
2935 			anon >> sc->priority;
2936 	}
2937 }
2938 
2939 /*
2940  * Determine how aggressively the anon and file LRU lists should be
2941  * scanned.
2942  *
2943  * nr[0] = anon inactive folios to scan; nr[1] = anon active folios to scan
2944  * nr[2] = file inactive folios to scan; nr[3] = file active folios to scan
2945  */
2946 static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2947 			   unsigned long *nr)
2948 {
2949 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2950 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2951 	unsigned long anon_cost, file_cost, total_cost;
2952 	int swappiness = mem_cgroup_swappiness(memcg);
2953 	u64 fraction[ANON_AND_FILE];
2954 	u64 denominator = 0;	/* gcc */
2955 	enum scan_balance scan_balance;
2956 	unsigned long ap, fp;
2957 	enum lru_list lru;
2958 
2959 	/* If we have no swap space, do not bother scanning anon folios. */
2960 	if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
2961 		scan_balance = SCAN_FILE;
2962 		goto out;
2963 	}
2964 
2965 	/*
2966 	 * Global reclaim will swap to prevent OOM even with no
2967 	 * swappiness, but memcg users want to use this knob to
2968 	 * disable swapping for individual groups completely when
2969 	 * using the memory controller's swap limit feature would be
2970 	 * too expensive.
2971 	 */
2972 	if (cgroup_reclaim(sc) && !swappiness) {
2973 		scan_balance = SCAN_FILE;
2974 		goto out;
2975 	}
2976 
2977 	/*
2978 	 * Do not apply any pressure balancing cleverness when the
2979 	 * system is close to OOM, scan both anon and file equally
2980 	 * (unless the swappiness setting disagrees with swapping).
2981 	 */
2982 	if (!sc->priority && swappiness) {
2983 		scan_balance = SCAN_EQUAL;
2984 		goto out;
2985 	}
2986 
2987 	/*
2988 	 * If the system is almost out of file pages, force-scan anon.
2989 	 */
2990 	if (sc->file_is_tiny) {
2991 		scan_balance = SCAN_ANON;
2992 		goto out;
2993 	}
2994 
2995 	/*
2996 	 * If there is enough inactive page cache, we do not reclaim
2997 	 * anything from the anonymous working right now.
2998 	 */
2999 	if (sc->cache_trim_mode) {
3000 		scan_balance = SCAN_FILE;
3001 		goto out;
3002 	}
3003 
3004 	scan_balance = SCAN_FRACT;
3005 	/*
3006 	 * Calculate the pressure balance between anon and file pages.
3007 	 *
3008 	 * The amount of pressure we put on each LRU is inversely
3009 	 * proportional to the cost of reclaiming each list, as
3010 	 * determined by the share of pages that are refaulting, times
3011 	 * the relative IO cost of bringing back a swapped out
3012 	 * anonymous page vs reloading a filesystem page (swappiness).
3013 	 *
3014 	 * Although we limit that influence to ensure no list gets
3015 	 * left behind completely: at least a third of the pressure is
3016 	 * applied, before swappiness.
3017 	 *
3018 	 * With swappiness at 100, anon and file have equal IO cost.
3019 	 */
3020 	total_cost = sc->anon_cost + sc->file_cost;
3021 	anon_cost = total_cost + sc->anon_cost;
3022 	file_cost = total_cost + sc->file_cost;
3023 	total_cost = anon_cost + file_cost;
3024 
3025 	ap = swappiness * (total_cost + 1);
3026 	ap /= anon_cost + 1;
3027 
3028 	fp = (200 - swappiness) * (total_cost + 1);
3029 	fp /= file_cost + 1;
3030 
3031 	fraction[0] = ap;
3032 	fraction[1] = fp;
3033 	denominator = ap + fp;
3034 out:
3035 	for_each_evictable_lru(lru) {
3036 		int file = is_file_lru(lru);
3037 		unsigned long lruvec_size;
3038 		unsigned long low, min;
3039 		unsigned long scan;
3040 
3041 		lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
3042 		mem_cgroup_protection(sc->target_mem_cgroup, memcg,
3043 				      &min, &low);
3044 
3045 		if (min || low) {
3046 			/*
3047 			 * Scale a cgroup's reclaim pressure by proportioning
3048 			 * its current usage to its memory.low or memory.min
3049 			 * setting.
3050 			 *
3051 			 * This is important, as otherwise scanning aggression
3052 			 * becomes extremely binary -- from nothing as we
3053 			 * approach the memory protection threshold, to totally
3054 			 * nominal as we exceed it.  This results in requiring
3055 			 * setting extremely liberal protection thresholds. It
3056 			 * also means we simply get no protection at all if we
3057 			 * set it too low, which is not ideal.
3058 			 *
3059 			 * If there is any protection in place, we reduce scan
3060 			 * pressure by how much of the total memory used is
3061 			 * within protection thresholds.
3062 			 *
3063 			 * There is one special case: in the first reclaim pass,
3064 			 * we skip over all groups that are within their low
3065 			 * protection. If that fails to reclaim enough pages to
3066 			 * satisfy the reclaim goal, we come back and override
3067 			 * the best-effort low protection. However, we still
3068 			 * ideally want to honor how well-behaved groups are in
3069 			 * that case instead of simply punishing them all
3070 			 * equally. As such, we reclaim them based on how much
3071 			 * memory they are using, reducing the scan pressure
3072 			 * again by how much of the total memory used is under
3073 			 * hard protection.
3074 			 */
3075 			unsigned long cgroup_size = mem_cgroup_size(memcg);
3076 			unsigned long protection;
3077 
3078 			/* memory.low scaling, make sure we retry before OOM */
3079 			if (!sc->memcg_low_reclaim && low > min) {
3080 				protection = low;
3081 				sc->memcg_low_skipped = 1;
3082 			} else {
3083 				protection = min;
3084 			}
3085 
3086 			/* Avoid TOCTOU with earlier protection check */
3087 			cgroup_size = max(cgroup_size, protection);
3088 
3089 			scan = lruvec_size - lruvec_size * protection /
3090 				(cgroup_size + 1);
3091 
3092 			/*
3093 			 * Minimally target SWAP_CLUSTER_MAX pages to keep
3094 			 * reclaim moving forwards, avoiding decrementing
3095 			 * sc->priority further than desirable.
3096 			 */
3097 			scan = max(scan, SWAP_CLUSTER_MAX);
3098 		} else {
3099 			scan = lruvec_size;
3100 		}
3101 
3102 		scan >>= sc->priority;
3103 
3104 		/*
3105 		 * If the cgroup's already been deleted, make sure to
3106 		 * scrape out the remaining cache.
3107 		 */
3108 		if (!scan && !mem_cgroup_online(memcg))
3109 			scan = min(lruvec_size, SWAP_CLUSTER_MAX);
3110 
3111 		switch (scan_balance) {
3112 		case SCAN_EQUAL:
3113 			/* Scan lists relative to size */
3114 			break;
3115 		case SCAN_FRACT:
3116 			/*
3117 			 * Scan types proportional to swappiness and
3118 			 * their relative recent reclaim efficiency.
3119 			 * Make sure we don't miss the last page on
3120 			 * the offlined memory cgroups because of a
3121 			 * round-off error.
3122 			 */
3123 			scan = mem_cgroup_online(memcg) ?
3124 			       div64_u64(scan * fraction[file], denominator) :
3125 			       DIV64_U64_ROUND_UP(scan * fraction[file],
3126 						  denominator);
3127 			break;
3128 		case SCAN_FILE:
3129 		case SCAN_ANON:
3130 			/* Scan one type exclusively */
3131 			if ((scan_balance == SCAN_FILE) != file)
3132 				scan = 0;
3133 			break;
3134 		default:
3135 			/* Look ma, no brain */
3136 			BUG();
3137 		}
3138 
3139 		nr[lru] = scan;
3140 	}
3141 }
3142 
3143 /*
3144  * Anonymous LRU management is a waste if there is
3145  * ultimately no way to reclaim the memory.
3146  */
3147 static bool can_age_anon_pages(struct pglist_data *pgdat,
3148 			       struct scan_control *sc)
3149 {
3150 	/* Aging the anon LRU is valuable if swap is present: */
3151 	if (total_swap_pages > 0)
3152 		return true;
3153 
3154 	/* Also valuable if anon pages can be demoted: */
3155 	return can_demote(pgdat->node_id, sc);
3156 }
3157 
3158 #ifdef CONFIG_LRU_GEN
3159 
3160 #ifdef CONFIG_LRU_GEN_ENABLED
3161 DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
3162 #define get_cap(cap)	static_branch_likely(&lru_gen_caps[cap])
3163 #else
3164 DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
3165 #define get_cap(cap)	static_branch_unlikely(&lru_gen_caps[cap])
3166 #endif
3167 
3168 /******************************************************************************
3169  *                          shorthand helpers
3170  ******************************************************************************/
3171 
3172 #define LRU_REFS_FLAGS	(BIT(PG_referenced) | BIT(PG_workingset))
3173 
3174 #define DEFINE_MAX_SEQ(lruvec)						\
3175 	unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
3176 
3177 #define DEFINE_MIN_SEQ(lruvec)						\
3178 	unsigned long min_seq[ANON_AND_FILE] = {			\
3179 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]),	\
3180 		READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]),	\
3181 	}
3182 
3183 #define for_each_gen_type_zone(gen, type, zone)				\
3184 	for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++)			\
3185 		for ((type) = 0; (type) < ANON_AND_FILE; (type)++)	\
3186 			for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3187 
3188 static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
3189 {
3190 	struct pglist_data *pgdat = NODE_DATA(nid);
3191 
3192 #ifdef CONFIG_MEMCG
3193 	if (memcg) {
3194 		struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3195 
3196 		/* see the comment in mem_cgroup_lruvec() */
3197 		if (!lruvec->pgdat)
3198 			lruvec->pgdat = pgdat;
3199 
3200 		return lruvec;
3201 	}
3202 #endif
3203 	VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3204 
3205 	return &pgdat->__lruvec;
3206 }
3207 
3208 static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3209 {
3210 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3211 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3212 
3213 	if (!can_demote(pgdat->node_id, sc) &&
3214 	    mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3215 		return 0;
3216 
3217 	return mem_cgroup_swappiness(memcg);
3218 }
3219 
3220 static int get_nr_gens(struct lruvec *lruvec, int type)
3221 {
3222 	return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3223 }
3224 
3225 static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3226 {
3227 	/* see the comment on lru_gen_folio */
3228 	return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3229 	       get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3230 	       get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3231 }
3232 
3233 /******************************************************************************
3234  *                          mm_struct list
3235  ******************************************************************************/
3236 
3237 static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3238 {
3239 	static struct lru_gen_mm_list mm_list = {
3240 		.fifo = LIST_HEAD_INIT(mm_list.fifo),
3241 		.lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3242 	};
3243 
3244 #ifdef CONFIG_MEMCG
3245 	if (memcg)
3246 		return &memcg->mm_list;
3247 #endif
3248 	VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3249 
3250 	return &mm_list;
3251 }
3252 
3253 void lru_gen_add_mm(struct mm_struct *mm)
3254 {
3255 	int nid;
3256 	struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3257 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3258 
3259 	VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3260 #ifdef CONFIG_MEMCG
3261 	VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3262 	mm->lru_gen.memcg = memcg;
3263 #endif
3264 	spin_lock(&mm_list->lock);
3265 
3266 	for_each_node_state(nid, N_MEMORY) {
3267 		struct lruvec *lruvec = get_lruvec(memcg, nid);
3268 
3269 		/* the first addition since the last iteration */
3270 		if (lruvec->mm_state.tail == &mm_list->fifo)
3271 			lruvec->mm_state.tail = &mm->lru_gen.list;
3272 	}
3273 
3274 	list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3275 
3276 	spin_unlock(&mm_list->lock);
3277 }
3278 
3279 void lru_gen_del_mm(struct mm_struct *mm)
3280 {
3281 	int nid;
3282 	struct lru_gen_mm_list *mm_list;
3283 	struct mem_cgroup *memcg = NULL;
3284 
3285 	if (list_empty(&mm->lru_gen.list))
3286 		return;
3287 
3288 #ifdef CONFIG_MEMCG
3289 	memcg = mm->lru_gen.memcg;
3290 #endif
3291 	mm_list = get_mm_list(memcg);
3292 
3293 	spin_lock(&mm_list->lock);
3294 
3295 	for_each_node(nid) {
3296 		struct lruvec *lruvec = get_lruvec(memcg, nid);
3297 
3298 		/* where the last iteration ended (exclusive) */
3299 		if (lruvec->mm_state.tail == &mm->lru_gen.list)
3300 			lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3301 
3302 		/* where the current iteration continues (inclusive) */
3303 		if (lruvec->mm_state.head != &mm->lru_gen.list)
3304 			continue;
3305 
3306 		lruvec->mm_state.head = lruvec->mm_state.head->next;
3307 		/* the deletion ends the current iteration */
3308 		if (lruvec->mm_state.head == &mm_list->fifo)
3309 			WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3310 	}
3311 
3312 	list_del_init(&mm->lru_gen.list);
3313 
3314 	spin_unlock(&mm_list->lock);
3315 
3316 #ifdef CONFIG_MEMCG
3317 	mem_cgroup_put(mm->lru_gen.memcg);
3318 	mm->lru_gen.memcg = NULL;
3319 #endif
3320 }
3321 
3322 #ifdef CONFIG_MEMCG
3323 void lru_gen_migrate_mm(struct mm_struct *mm)
3324 {
3325 	struct mem_cgroup *memcg;
3326 	struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3327 
3328 	VM_WARN_ON_ONCE(task->mm != mm);
3329 	lockdep_assert_held(&task->alloc_lock);
3330 
3331 	/* for mm_update_next_owner() */
3332 	if (mem_cgroup_disabled())
3333 		return;
3334 
3335 	rcu_read_lock();
3336 	memcg = mem_cgroup_from_task(task);
3337 	rcu_read_unlock();
3338 	if (memcg == mm->lru_gen.memcg)
3339 		return;
3340 
3341 	VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3342 	VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3343 
3344 	lru_gen_del_mm(mm);
3345 	lru_gen_add_mm(mm);
3346 }
3347 #endif
3348 
3349 /*
3350  * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3351  * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3352  * bits in a bitmap, k is the number of hash functions and n is the number of
3353  * inserted items.
3354  *
3355  * Page table walkers use one of the two filters to reduce their search space.
3356  * To get rid of non-leaf entries that no longer have enough leaf entries, the
3357  * aging uses the double-buffering technique to flip to the other filter each
3358  * time it produces a new generation. For non-leaf entries that have enough
3359  * leaf entries, the aging carries them over to the next generation in
3360  * walk_pmd_range(); the eviction also report them when walking the rmap
3361  * in lru_gen_look_around().
3362  *
3363  * For future optimizations:
3364  * 1. It's not necessary to keep both filters all the time. The spare one can be
3365  *    freed after the RCU grace period and reallocated if needed again.
3366  * 2. And when reallocating, it's worth scaling its size according to the number
3367  *    of inserted entries in the other filter, to reduce the memory overhead on
3368  *    small systems and false positives on large systems.
3369  * 3. Jenkins' hash function is an alternative to Knuth's.
3370  */
3371 #define BLOOM_FILTER_SHIFT	15
3372 
3373 static inline int filter_gen_from_seq(unsigned long seq)
3374 {
3375 	return seq % NR_BLOOM_FILTERS;
3376 }
3377 
3378 static void get_item_key(void *item, int *key)
3379 {
3380 	u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3381 
3382 	BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3383 
3384 	key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3385 	key[1] = hash >> BLOOM_FILTER_SHIFT;
3386 }
3387 
3388 static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3389 {
3390 	unsigned long *filter;
3391 	int gen = filter_gen_from_seq(seq);
3392 
3393 	filter = lruvec->mm_state.filters[gen];
3394 	if (filter) {
3395 		bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3396 		return;
3397 	}
3398 
3399 	filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3400 			       __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3401 	WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3402 }
3403 
3404 static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3405 {
3406 	int key[2];
3407 	unsigned long *filter;
3408 	int gen = filter_gen_from_seq(seq);
3409 
3410 	filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3411 	if (!filter)
3412 		return;
3413 
3414 	get_item_key(item, key);
3415 
3416 	if (!test_bit(key[0], filter))
3417 		set_bit(key[0], filter);
3418 	if (!test_bit(key[1], filter))
3419 		set_bit(key[1], filter);
3420 }
3421 
3422 static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3423 {
3424 	int key[2];
3425 	unsigned long *filter;
3426 	int gen = filter_gen_from_seq(seq);
3427 
3428 	filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3429 	if (!filter)
3430 		return true;
3431 
3432 	get_item_key(item, key);
3433 
3434 	return test_bit(key[0], filter) && test_bit(key[1], filter);
3435 }
3436 
3437 static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3438 {
3439 	int i;
3440 	int hist;
3441 
3442 	lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3443 
3444 	if (walk) {
3445 		hist = lru_hist_from_seq(walk->max_seq);
3446 
3447 		for (i = 0; i < NR_MM_STATS; i++) {
3448 			WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3449 				   lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3450 			walk->mm_stats[i] = 0;
3451 		}
3452 	}
3453 
3454 	if (NR_HIST_GENS > 1 && last) {
3455 		hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3456 
3457 		for (i = 0; i < NR_MM_STATS; i++)
3458 			WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3459 	}
3460 }
3461 
3462 static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3463 {
3464 	int type;
3465 	unsigned long size = 0;
3466 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3467 	int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3468 
3469 	if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3470 		return true;
3471 
3472 	clear_bit(key, &mm->lru_gen.bitmap);
3473 
3474 	for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3475 		size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3476 			       get_mm_counter(mm, MM_ANONPAGES) +
3477 			       get_mm_counter(mm, MM_SHMEMPAGES);
3478 	}
3479 
3480 	if (size < MIN_LRU_BATCH)
3481 		return true;
3482 
3483 	return !mmget_not_zero(mm);
3484 }
3485 
3486 static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3487 			    struct mm_struct **iter)
3488 {
3489 	bool first = false;
3490 	bool last = true;
3491 	struct mm_struct *mm = NULL;
3492 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3493 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3494 	struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3495 
3496 	/*
3497 	 * There are four interesting cases for this page table walker:
3498 	 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3499 	 *    there is nothing left to do.
3500 	 * 2. It's the first of the current generation, and it needs to reset
3501 	 *    the Bloom filter for the next generation.
3502 	 * 3. It reaches the end of mm_list, and it needs to increment
3503 	 *    mm_state->seq; the iteration is done.
3504 	 * 4. It's the last of the current generation, and it needs to reset the
3505 	 *    mm stats counters for the next generation.
3506 	 */
3507 	spin_lock(&mm_list->lock);
3508 
3509 	VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3510 	VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3511 	VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3512 
3513 	if (walk->max_seq <= mm_state->seq) {
3514 		if (!*iter)
3515 			last = false;
3516 		goto done;
3517 	}
3518 
3519 	if (!mm_state->nr_walkers) {
3520 		VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3521 
3522 		mm_state->head = mm_list->fifo.next;
3523 		first = true;
3524 	}
3525 
3526 	while (!mm && mm_state->head != &mm_list->fifo) {
3527 		mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3528 
3529 		mm_state->head = mm_state->head->next;
3530 
3531 		/* force scan for those added after the last iteration */
3532 		if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3533 			mm_state->tail = mm_state->head;
3534 			walk->force_scan = true;
3535 		}
3536 
3537 		if (should_skip_mm(mm, walk))
3538 			mm = NULL;
3539 	}
3540 
3541 	if (mm_state->head == &mm_list->fifo)
3542 		WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3543 done:
3544 	if (*iter && !mm)
3545 		mm_state->nr_walkers--;
3546 	if (!*iter && mm)
3547 		mm_state->nr_walkers++;
3548 
3549 	if (mm_state->nr_walkers)
3550 		last = false;
3551 
3552 	if (*iter || last)
3553 		reset_mm_stats(lruvec, walk, last);
3554 
3555 	spin_unlock(&mm_list->lock);
3556 
3557 	if (mm && first)
3558 		reset_bloom_filter(lruvec, walk->max_seq + 1);
3559 
3560 	if (*iter)
3561 		mmput_async(*iter);
3562 
3563 	*iter = mm;
3564 
3565 	return last;
3566 }
3567 
3568 static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3569 {
3570 	bool success = false;
3571 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3572 	struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3573 	struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3574 
3575 	spin_lock(&mm_list->lock);
3576 
3577 	VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3578 
3579 	if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3580 		VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3581 
3582 		WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3583 		reset_mm_stats(lruvec, NULL, true);
3584 		success = true;
3585 	}
3586 
3587 	spin_unlock(&mm_list->lock);
3588 
3589 	return success;
3590 }
3591 
3592 /******************************************************************************
3593  *                          refault feedback loop
3594  ******************************************************************************/
3595 
3596 /*
3597  * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3598  *
3599  * The P term is refaulted/(evicted+protected) from a tier in the generation
3600  * currently being evicted; the I term is the exponential moving average of the
3601  * P term over the generations previously evicted, using the smoothing factor
3602  * 1/2; the D term isn't supported.
3603  *
3604  * The setpoint (SP) is always the first tier of one type; the process variable
3605  * (PV) is either any tier of the other type or any other tier of the same
3606  * type.
3607  *
3608  * The error is the difference between the SP and the PV; the correction is to
3609  * turn off protection when SP>PV or turn on protection when SP<PV.
3610  *
3611  * For future optimizations:
3612  * 1. The D term may discount the other two terms over time so that long-lived
3613  *    generations can resist stale information.
3614  */
3615 struct ctrl_pos {
3616 	unsigned long refaulted;
3617 	unsigned long total;
3618 	int gain;
3619 };
3620 
3621 static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3622 			  struct ctrl_pos *pos)
3623 {
3624 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
3625 	int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3626 
3627 	pos->refaulted = lrugen->avg_refaulted[type][tier] +
3628 			 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3629 	pos->total = lrugen->avg_total[type][tier] +
3630 		     atomic_long_read(&lrugen->evicted[hist][type][tier]);
3631 	if (tier)
3632 		pos->total += lrugen->protected[hist][type][tier - 1];
3633 	pos->gain = gain;
3634 }
3635 
3636 static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3637 {
3638 	int hist, tier;
3639 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
3640 	bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3641 	unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3642 
3643 	lockdep_assert_held(&lruvec->lru_lock);
3644 
3645 	if (!carryover && !clear)
3646 		return;
3647 
3648 	hist = lru_hist_from_seq(seq);
3649 
3650 	for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3651 		if (carryover) {
3652 			unsigned long sum;
3653 
3654 			sum = lrugen->avg_refaulted[type][tier] +
3655 			      atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3656 			WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3657 
3658 			sum = lrugen->avg_total[type][tier] +
3659 			      atomic_long_read(&lrugen->evicted[hist][type][tier]);
3660 			if (tier)
3661 				sum += lrugen->protected[hist][type][tier - 1];
3662 			WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3663 		}
3664 
3665 		if (clear) {
3666 			atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3667 			atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3668 			if (tier)
3669 				WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3670 		}
3671 	}
3672 }
3673 
3674 static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3675 {
3676 	/*
3677 	 * Return true if the PV has a limited number of refaults or a lower
3678 	 * refaulted/total than the SP.
3679 	 */
3680 	return pv->refaulted < MIN_LRU_BATCH ||
3681 	       pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3682 	       (sp->refaulted + 1) * pv->total * pv->gain;
3683 }
3684 
3685 /******************************************************************************
3686  *                          the aging
3687  ******************************************************************************/
3688 
3689 /* promote pages accessed through page tables */
3690 static int folio_update_gen(struct folio *folio, int gen)
3691 {
3692 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3693 
3694 	VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3695 	VM_WARN_ON_ONCE(!rcu_read_lock_held());
3696 
3697 	do {
3698 		/* lru_gen_del_folio() has isolated this page? */
3699 		if (!(old_flags & LRU_GEN_MASK)) {
3700 			/* for shrink_folio_list() */
3701 			new_flags = old_flags | BIT(PG_referenced);
3702 			continue;
3703 		}
3704 
3705 		new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3706 		new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3707 	} while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3708 
3709 	return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3710 }
3711 
3712 /* protect pages accessed multiple times through file descriptors */
3713 static int folio_inc_gen(struct lruvec *lruvec, struct folio *folio, bool reclaiming)
3714 {
3715 	int type = folio_is_file_lru(folio);
3716 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
3717 	int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3718 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
3719 
3720 	VM_WARN_ON_ONCE_FOLIO(!(old_flags & LRU_GEN_MASK), folio);
3721 
3722 	do {
3723 		new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3724 		/* folio_update_gen() has promoted this page? */
3725 		if (new_gen >= 0 && new_gen != old_gen)
3726 			return new_gen;
3727 
3728 		new_gen = (old_gen + 1) % MAX_NR_GENS;
3729 
3730 		new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3731 		new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3732 		/* for folio_end_writeback() */
3733 		if (reclaiming)
3734 			new_flags |= BIT(PG_reclaim);
3735 	} while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
3736 
3737 	lru_gen_update_size(lruvec, folio, old_gen, new_gen);
3738 
3739 	return new_gen;
3740 }
3741 
3742 static void update_batch_size(struct lru_gen_mm_walk *walk, struct folio *folio,
3743 			      int old_gen, int new_gen)
3744 {
3745 	int type = folio_is_file_lru(folio);
3746 	int zone = folio_zonenum(folio);
3747 	int delta = folio_nr_pages(folio);
3748 
3749 	VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3750 	VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3751 
3752 	walk->batched++;
3753 
3754 	walk->nr_pages[old_gen][type][zone] -= delta;
3755 	walk->nr_pages[new_gen][type][zone] += delta;
3756 }
3757 
3758 static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3759 {
3760 	int gen, type, zone;
3761 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
3762 
3763 	walk->batched = 0;
3764 
3765 	for_each_gen_type_zone(gen, type, zone) {
3766 		enum lru_list lru = type * LRU_INACTIVE_FILE;
3767 		int delta = walk->nr_pages[gen][type][zone];
3768 
3769 		if (!delta)
3770 			continue;
3771 
3772 		walk->nr_pages[gen][type][zone] = 0;
3773 		WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3774 			   lrugen->nr_pages[gen][type][zone] + delta);
3775 
3776 		if (lru_gen_is_active(lruvec, gen))
3777 			lru += LRU_ACTIVE;
3778 		__update_lru_size(lruvec, lru, zone, delta);
3779 	}
3780 }
3781 
3782 static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3783 {
3784 	struct address_space *mapping;
3785 	struct vm_area_struct *vma = args->vma;
3786 	struct lru_gen_mm_walk *walk = args->private;
3787 
3788 	if (!vma_is_accessible(vma))
3789 		return true;
3790 
3791 	if (is_vm_hugetlb_page(vma))
3792 		return true;
3793 
3794 	if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3795 		return true;
3796 
3797 	if (vma == get_gate_vma(vma->vm_mm))
3798 		return true;
3799 
3800 	if (vma_is_anonymous(vma))
3801 		return !walk->can_swap;
3802 
3803 	if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3804 		return true;
3805 
3806 	mapping = vma->vm_file->f_mapping;
3807 	if (mapping_unevictable(mapping))
3808 		return true;
3809 
3810 	if (shmem_mapping(mapping))
3811 		return !walk->can_swap;
3812 
3813 	/* to exclude special mappings like dax, etc. */
3814 	return !mapping->a_ops->read_folio;
3815 }
3816 
3817 /*
3818  * Some userspace memory allocators map many single-page VMAs. Instead of
3819  * returning back to the PGD table for each of such VMAs, finish an entire PMD
3820  * table to reduce zigzags and improve cache performance.
3821  */
3822 static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3823 			 unsigned long *vm_start, unsigned long *vm_end)
3824 {
3825 	unsigned long start = round_up(*vm_end, size);
3826 	unsigned long end = (start | ~mask) + 1;
3827 	VMA_ITERATOR(vmi, args->mm, start);
3828 
3829 	VM_WARN_ON_ONCE(mask & size);
3830 	VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3831 
3832 	for_each_vma(vmi, args->vma) {
3833 		if (end && end <= args->vma->vm_start)
3834 			return false;
3835 
3836 		if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args))
3837 			continue;
3838 
3839 		*vm_start = max(start, args->vma->vm_start);
3840 		*vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3841 
3842 		return true;
3843 	}
3844 
3845 	return false;
3846 }
3847 
3848 static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3849 {
3850 	unsigned long pfn = pte_pfn(pte);
3851 
3852 	VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3853 
3854 	if (!pte_present(pte) || is_zero_pfn(pfn))
3855 		return -1;
3856 
3857 	if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3858 		return -1;
3859 
3860 	if (WARN_ON_ONCE(!pfn_valid(pfn)))
3861 		return -1;
3862 
3863 	return pfn;
3864 }
3865 
3866 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3867 static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3868 {
3869 	unsigned long pfn = pmd_pfn(pmd);
3870 
3871 	VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3872 
3873 	if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3874 		return -1;
3875 
3876 	if (WARN_ON_ONCE(pmd_devmap(pmd)))
3877 		return -1;
3878 
3879 	if (WARN_ON_ONCE(!pfn_valid(pfn)))
3880 		return -1;
3881 
3882 	return pfn;
3883 }
3884 #endif
3885 
3886 static struct folio *get_pfn_folio(unsigned long pfn, struct mem_cgroup *memcg,
3887 				   struct pglist_data *pgdat, bool can_swap)
3888 {
3889 	struct folio *folio;
3890 
3891 	/* try to avoid unnecessary memory loads */
3892 	if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3893 		return NULL;
3894 
3895 	folio = pfn_folio(pfn);
3896 	if (folio_nid(folio) != pgdat->node_id)
3897 		return NULL;
3898 
3899 	if (folio_memcg_rcu(folio) != memcg)
3900 		return NULL;
3901 
3902 	/* file VMAs can contain anon pages from COW */
3903 	if (!folio_is_file_lru(folio) && !can_swap)
3904 		return NULL;
3905 
3906 	return folio;
3907 }
3908 
3909 static bool suitable_to_scan(int total, int young)
3910 {
3911 	int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3912 
3913 	/* suitable if the average number of young PTEs per cacheline is >=1 */
3914 	return young * n >= total;
3915 }
3916 
3917 static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3918 			   struct mm_walk *args)
3919 {
3920 	int i;
3921 	pte_t *pte;
3922 	spinlock_t *ptl;
3923 	unsigned long addr;
3924 	int total = 0;
3925 	int young = 0;
3926 	struct lru_gen_mm_walk *walk = args->private;
3927 	struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3928 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3929 	int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3930 
3931 	VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3932 
3933 	ptl = pte_lockptr(args->mm, pmd);
3934 	if (!spin_trylock(ptl))
3935 		return false;
3936 
3937 	arch_enter_lazy_mmu_mode();
3938 
3939 	pte = pte_offset_map(pmd, start & PMD_MASK);
3940 restart:
3941 	for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3942 		unsigned long pfn;
3943 		struct folio *folio;
3944 
3945 		total++;
3946 		walk->mm_stats[MM_LEAF_TOTAL]++;
3947 
3948 		pfn = get_pte_pfn(pte[i], args->vma, addr);
3949 		if (pfn == -1)
3950 			continue;
3951 
3952 		if (!pte_young(pte[i])) {
3953 			walk->mm_stats[MM_LEAF_OLD]++;
3954 			continue;
3955 		}
3956 
3957 		folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
3958 		if (!folio)
3959 			continue;
3960 
3961 		if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3962 			VM_WARN_ON_ONCE(true);
3963 
3964 		young++;
3965 		walk->mm_stats[MM_LEAF_YOUNG]++;
3966 
3967 		if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
3968 		    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
3969 		      !folio_test_swapcache(folio)))
3970 			folio_mark_dirty(folio);
3971 
3972 		old_gen = folio_update_gen(folio, new_gen);
3973 		if (old_gen >= 0 && old_gen != new_gen)
3974 			update_batch_size(walk, folio, old_gen, new_gen);
3975 	}
3976 
3977 	if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3978 		goto restart;
3979 
3980 	pte_unmap(pte);
3981 
3982 	arch_leave_lazy_mmu_mode();
3983 	spin_unlock(ptl);
3984 
3985 	return suitable_to_scan(total, young);
3986 }
3987 
3988 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3989 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3990 				  struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3991 {
3992 	int i;
3993 	pmd_t *pmd;
3994 	spinlock_t *ptl;
3995 	struct lru_gen_mm_walk *walk = args->private;
3996 	struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3997 	struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3998 	int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3999 
4000 	VM_WARN_ON_ONCE(pud_leaf(*pud));
4001 
4002 	/* try to batch at most 1+MIN_LRU_BATCH+1 entries */
4003 	if (*start == -1) {
4004 		*start = next;
4005 		return;
4006 	}
4007 
4008 	i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
4009 	if (i && i <= MIN_LRU_BATCH) {
4010 		__set_bit(i - 1, bitmap);
4011 		return;
4012 	}
4013 
4014 	pmd = pmd_offset(pud, *start);
4015 
4016 	ptl = pmd_lockptr(args->mm, pmd);
4017 	if (!spin_trylock(ptl))
4018 		goto done;
4019 
4020 	arch_enter_lazy_mmu_mode();
4021 
4022 	do {
4023 		unsigned long pfn;
4024 		struct folio *folio;
4025 		unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
4026 
4027 		pfn = get_pmd_pfn(pmd[i], vma, addr);
4028 		if (pfn == -1)
4029 			goto next;
4030 
4031 		if (!pmd_trans_huge(pmd[i])) {
4032 			if (arch_has_hw_nonleaf_pmd_young() &&
4033 			    get_cap(LRU_GEN_NONLEAF_YOUNG))
4034 				pmdp_test_and_clear_young(vma, addr, pmd + i);
4035 			goto next;
4036 		}
4037 
4038 		folio = get_pfn_folio(pfn, memcg, pgdat, walk->can_swap);
4039 		if (!folio)
4040 			goto next;
4041 
4042 		if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
4043 			goto next;
4044 
4045 		walk->mm_stats[MM_LEAF_YOUNG]++;
4046 
4047 		if (pmd_dirty(pmd[i]) && !folio_test_dirty(folio) &&
4048 		    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4049 		      !folio_test_swapcache(folio)))
4050 			folio_mark_dirty(folio);
4051 
4052 		old_gen = folio_update_gen(folio, new_gen);
4053 		if (old_gen >= 0 && old_gen != new_gen)
4054 			update_batch_size(walk, folio, old_gen, new_gen);
4055 next:
4056 		i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
4057 	} while (i <= MIN_LRU_BATCH);
4058 
4059 	arch_leave_lazy_mmu_mode();
4060 	spin_unlock(ptl);
4061 done:
4062 	*start = -1;
4063 	bitmap_zero(bitmap, MIN_LRU_BATCH);
4064 }
4065 #else
4066 static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
4067 				  struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
4068 {
4069 }
4070 #endif
4071 
4072 static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
4073 			   struct mm_walk *args)
4074 {
4075 	int i;
4076 	pmd_t *pmd;
4077 	unsigned long next;
4078 	unsigned long addr;
4079 	struct vm_area_struct *vma;
4080 	unsigned long pos = -1;
4081 	struct lru_gen_mm_walk *walk = args->private;
4082 	unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4083 
4084 	VM_WARN_ON_ONCE(pud_leaf(*pud));
4085 
4086 	/*
4087 	 * Finish an entire PMD in two passes: the first only reaches to PTE
4088 	 * tables to avoid taking the PMD lock; the second, if necessary, takes
4089 	 * the PMD lock to clear the accessed bit in PMD entries.
4090 	 */
4091 	pmd = pmd_offset(pud, start & PUD_MASK);
4092 restart:
4093 	/* walk_pte_range() may call get_next_vma() */
4094 	vma = args->vma;
4095 	for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
4096 		pmd_t val = pmdp_get_lockless(pmd + i);
4097 
4098 		next = pmd_addr_end(addr, end);
4099 
4100 		if (!pmd_present(val) || is_huge_zero_pmd(val)) {
4101 			walk->mm_stats[MM_LEAF_TOTAL]++;
4102 			continue;
4103 		}
4104 
4105 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4106 		if (pmd_trans_huge(val)) {
4107 			unsigned long pfn = pmd_pfn(val);
4108 			struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
4109 
4110 			walk->mm_stats[MM_LEAF_TOTAL]++;
4111 
4112 			if (!pmd_young(val)) {
4113 				walk->mm_stats[MM_LEAF_OLD]++;
4114 				continue;
4115 			}
4116 
4117 			/* try to avoid unnecessary memory loads */
4118 			if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4119 				continue;
4120 
4121 			walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4122 			continue;
4123 		}
4124 #endif
4125 		walk->mm_stats[MM_NONLEAF_TOTAL]++;
4126 
4127 		if (arch_has_hw_nonleaf_pmd_young() &&
4128 		    get_cap(LRU_GEN_NONLEAF_YOUNG)) {
4129 			if (!pmd_young(val))
4130 				continue;
4131 
4132 			walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
4133 		}
4134 
4135 		if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
4136 			continue;
4137 
4138 		walk->mm_stats[MM_NONLEAF_FOUND]++;
4139 
4140 		if (!walk_pte_range(&val, addr, next, args))
4141 			continue;
4142 
4143 		walk->mm_stats[MM_NONLEAF_ADDED]++;
4144 
4145 		/* carry over to the next generation */
4146 		update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
4147 	}
4148 
4149 	walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
4150 
4151 	if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
4152 		goto restart;
4153 }
4154 
4155 static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
4156 			  struct mm_walk *args)
4157 {
4158 	int i;
4159 	pud_t *pud;
4160 	unsigned long addr;
4161 	unsigned long next;
4162 	struct lru_gen_mm_walk *walk = args->private;
4163 
4164 	VM_WARN_ON_ONCE(p4d_leaf(*p4d));
4165 
4166 	pud = pud_offset(p4d, start & P4D_MASK);
4167 restart:
4168 	for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
4169 		pud_t val = READ_ONCE(pud[i]);
4170 
4171 		next = pud_addr_end(addr, end);
4172 
4173 		if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4174 			continue;
4175 
4176 		walk_pmd_range(&val, addr, next, args);
4177 
4178 		/* a racy check to curtail the waiting time */
4179 		if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
4180 			return 1;
4181 
4182 		if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4183 			end = (addr | ~PUD_MASK) + 1;
4184 			goto done;
4185 		}
4186 	}
4187 
4188 	if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4189 		goto restart;
4190 
4191 	end = round_up(end, P4D_SIZE);
4192 done:
4193 	if (!end || !args->vma)
4194 		return 1;
4195 
4196 	walk->next_addr = max(end, args->vma->vm_start);
4197 
4198 	return -EAGAIN;
4199 }
4200 
4201 static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4202 {
4203 	static const struct mm_walk_ops mm_walk_ops = {
4204 		.test_walk = should_skip_vma,
4205 		.p4d_entry = walk_pud_range,
4206 	};
4207 
4208 	int err;
4209 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4210 
4211 	walk->next_addr = FIRST_USER_ADDRESS;
4212 
4213 	do {
4214 		err = -EBUSY;
4215 
4216 		/* folio_update_gen() requires stable folio_memcg() */
4217 		if (!mem_cgroup_trylock_pages(memcg))
4218 			break;
4219 
4220 		/* the caller might be holding the lock for write */
4221 		if (mmap_read_trylock(mm)) {
4222 			err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4223 
4224 			mmap_read_unlock(mm);
4225 		}
4226 
4227 		mem_cgroup_unlock_pages();
4228 
4229 		if (walk->batched) {
4230 			spin_lock_irq(&lruvec->lru_lock);
4231 			reset_batch_size(lruvec, walk);
4232 			spin_unlock_irq(&lruvec->lru_lock);
4233 		}
4234 
4235 		cond_resched();
4236 	} while (err == -EAGAIN);
4237 }
4238 
4239 static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4240 {
4241 	struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4242 
4243 	if (pgdat && current_is_kswapd()) {
4244 		VM_WARN_ON_ONCE(walk);
4245 
4246 		walk = &pgdat->mm_walk;
4247 	} else if (!pgdat && !walk) {
4248 		VM_WARN_ON_ONCE(current_is_kswapd());
4249 
4250 		walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4251 	}
4252 
4253 	current->reclaim_state->mm_walk = walk;
4254 
4255 	return walk;
4256 }
4257 
4258 static void clear_mm_walk(void)
4259 {
4260 	struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4261 
4262 	VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4263 	VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4264 
4265 	current->reclaim_state->mm_walk = NULL;
4266 
4267 	if (!current_is_kswapd())
4268 		kfree(walk);
4269 }
4270 
4271 static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
4272 {
4273 	int zone;
4274 	int remaining = MAX_LRU_BATCH;
4275 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4276 	int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
4277 
4278 	if (type == LRU_GEN_ANON && !can_swap)
4279 		goto done;
4280 
4281 	/* prevent cold/hot inversion if force_scan is true */
4282 	for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4283 		struct list_head *head = &lrugen->folios[old_gen][type][zone];
4284 
4285 		while (!list_empty(head)) {
4286 			struct folio *folio = lru_to_folio(head);
4287 
4288 			VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4289 			VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4290 			VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4291 			VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4292 
4293 			new_gen = folio_inc_gen(lruvec, folio, false);
4294 			list_move_tail(&folio->lru, &lrugen->folios[new_gen][type][zone]);
4295 
4296 			if (!--remaining)
4297 				return false;
4298 		}
4299 	}
4300 done:
4301 	reset_ctrl_pos(lruvec, type, true);
4302 	WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4303 
4304 	return true;
4305 }
4306 
4307 static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4308 {
4309 	int gen, type, zone;
4310 	bool success = false;
4311 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4312 	DEFINE_MIN_SEQ(lruvec);
4313 
4314 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4315 
4316 	/* find the oldest populated generation */
4317 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4318 		while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4319 			gen = lru_gen_from_seq(min_seq[type]);
4320 
4321 			for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4322 				if (!list_empty(&lrugen->folios[gen][type][zone]))
4323 					goto next;
4324 			}
4325 
4326 			min_seq[type]++;
4327 		}
4328 next:
4329 		;
4330 	}
4331 
4332 	/* see the comment on lru_gen_folio */
4333 	if (can_swap) {
4334 		min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4335 		min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4336 	}
4337 
4338 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4339 		if (min_seq[type] == lrugen->min_seq[type])
4340 			continue;
4341 
4342 		reset_ctrl_pos(lruvec, type, true);
4343 		WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4344 		success = true;
4345 	}
4346 
4347 	return success;
4348 }
4349 
4350 static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
4351 {
4352 	int prev, next;
4353 	int type, zone;
4354 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4355 
4356 	spin_lock_irq(&lruvec->lru_lock);
4357 
4358 	VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4359 
4360 	for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4361 		if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4362 			continue;
4363 
4364 		VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
4365 
4366 		while (!inc_min_seq(lruvec, type, can_swap)) {
4367 			spin_unlock_irq(&lruvec->lru_lock);
4368 			cond_resched();
4369 			spin_lock_irq(&lruvec->lru_lock);
4370 		}
4371 	}
4372 
4373 	/*
4374 	 * Update the active/inactive LRU sizes for compatibility. Both sides of
4375 	 * the current max_seq need to be covered, since max_seq+1 can overlap
4376 	 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4377 	 * overlap, cold/hot inversion happens.
4378 	 */
4379 	prev = lru_gen_from_seq(lrugen->max_seq - 1);
4380 	next = lru_gen_from_seq(lrugen->max_seq + 1);
4381 
4382 	for (type = 0; type < ANON_AND_FILE; type++) {
4383 		for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4384 			enum lru_list lru = type * LRU_INACTIVE_FILE;
4385 			long delta = lrugen->nr_pages[prev][type][zone] -
4386 				     lrugen->nr_pages[next][type][zone];
4387 
4388 			if (!delta)
4389 				continue;
4390 
4391 			__update_lru_size(lruvec, lru, zone, delta);
4392 			__update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4393 		}
4394 	}
4395 
4396 	for (type = 0; type < ANON_AND_FILE; type++)
4397 		reset_ctrl_pos(lruvec, type, false);
4398 
4399 	WRITE_ONCE(lrugen->timestamps[next], jiffies);
4400 	/* make sure preceding modifications appear */
4401 	smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
4402 
4403 	spin_unlock_irq(&lruvec->lru_lock);
4404 }
4405 
4406 static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4407 			       struct scan_control *sc, bool can_swap, bool force_scan)
4408 {
4409 	bool success;
4410 	struct lru_gen_mm_walk *walk;
4411 	struct mm_struct *mm = NULL;
4412 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4413 
4414 	VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4415 
4416 	/* see the comment in iterate_mm_list() */
4417 	if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4418 		success = false;
4419 		goto done;
4420 	}
4421 
4422 	/*
4423 	 * If the hardware doesn't automatically set the accessed bit, fallback
4424 	 * to lru_gen_look_around(), which only clears the accessed bit in a
4425 	 * handful of PTEs. Spreading the work out over a period of time usually
4426 	 * is less efficient, but it avoids bursty page faults.
4427 	 */
4428 	if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
4429 		success = iterate_mm_list_nowalk(lruvec, max_seq);
4430 		goto done;
4431 	}
4432 
4433 	walk = set_mm_walk(NULL);
4434 	if (!walk) {
4435 		success = iterate_mm_list_nowalk(lruvec, max_seq);
4436 		goto done;
4437 	}
4438 
4439 	walk->lruvec = lruvec;
4440 	walk->max_seq = max_seq;
4441 	walk->can_swap = can_swap;
4442 	walk->force_scan = force_scan;
4443 
4444 	do {
4445 		success = iterate_mm_list(lruvec, walk, &mm);
4446 		if (mm)
4447 			walk_mm(lruvec, mm, walk);
4448 
4449 		cond_resched();
4450 	} while (mm);
4451 done:
4452 	if (!success) {
4453 		if (sc->priority <= DEF_PRIORITY - 2)
4454 			wait_event_killable(lruvec->mm_state.wait,
4455 					    max_seq < READ_ONCE(lrugen->max_seq));
4456 
4457 		return max_seq < READ_ONCE(lrugen->max_seq);
4458 	}
4459 
4460 	VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4461 
4462 	inc_max_seq(lruvec, can_swap, force_scan);
4463 	/* either this sees any waiters or they will see updated max_seq */
4464 	if (wq_has_sleeper(&lruvec->mm_state.wait))
4465 		wake_up_all(&lruvec->mm_state.wait);
4466 
4467 	return true;
4468 }
4469 
4470 static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4471 			     struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4472 {
4473 	int gen, type, zone;
4474 	unsigned long old = 0;
4475 	unsigned long young = 0;
4476 	unsigned long total = 0;
4477 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4478 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4479 	DEFINE_MIN_SEQ(lruvec);
4480 
4481 	/* whether this lruvec is completely out of cold folios */
4482 	if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4483 		*nr_to_scan = 0;
4484 		return true;
4485 	}
4486 
4487 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4488 		unsigned long seq;
4489 
4490 		for (seq = min_seq[type]; seq <= max_seq; seq++) {
4491 			unsigned long size = 0;
4492 
4493 			gen = lru_gen_from_seq(seq);
4494 
4495 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
4496 				size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4497 
4498 			total += size;
4499 			if (seq == max_seq)
4500 				young += size;
4501 			else if (seq + MIN_NR_GENS == max_seq)
4502 				old += size;
4503 		}
4504 	}
4505 
4506 	/* try to scrape all its memory if this memcg was deleted */
4507 	*nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4508 
4509 	/*
4510 	 * The aging tries to be lazy to reduce the overhead, while the eviction
4511 	 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4512 	 * ideal number of generations is MIN_NR_GENS+1.
4513 	 */
4514 	if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4515 		return false;
4516 
4517 	/*
4518 	 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4519 	 * of the total number of pages for each generation. A reasonable range
4520 	 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4521 	 * aging cares about the upper bound of hot pages, while the eviction
4522 	 * cares about the lower bound of cold pages.
4523 	 */
4524 	if (young * MIN_NR_GENS > total)
4525 		return true;
4526 	if (old * (MIN_NR_GENS + 2) < total)
4527 		return true;
4528 
4529 	return false;
4530 }
4531 
4532 static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
4533 {
4534 	int gen, type, zone;
4535 	unsigned long total = 0;
4536 	bool can_swap = get_swappiness(lruvec, sc);
4537 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4538 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4539 	DEFINE_MAX_SEQ(lruvec);
4540 	DEFINE_MIN_SEQ(lruvec);
4541 
4542 	for (type = !can_swap; type < ANON_AND_FILE; type++) {
4543 		unsigned long seq;
4544 
4545 		for (seq = min_seq[type]; seq <= max_seq; seq++) {
4546 			gen = lru_gen_from_seq(seq);
4547 
4548 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
4549 				total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4550 		}
4551 	}
4552 
4553 	/* whether the size is big enough to be helpful */
4554 	return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4555 }
4556 
4557 static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4558 				  unsigned long min_ttl)
4559 {
4560 	int gen;
4561 	unsigned long birth;
4562 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4563 	DEFINE_MIN_SEQ(lruvec);
4564 
4565 	VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4566 
4567 	/* see the comment on lru_gen_folio */
4568 	gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4569 	birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4570 
4571 	if (time_is_after_jiffies(birth + min_ttl))
4572 		return false;
4573 
4574 	if (!lruvec_is_sizable(lruvec, sc))
4575 		return false;
4576 
4577 	mem_cgroup_calculate_protection(NULL, memcg);
4578 
4579 	return !mem_cgroup_below_min(NULL, memcg);
4580 }
4581 
4582 /* to protect the working set of the last N jiffies */
4583 static unsigned long lru_gen_min_ttl __read_mostly;
4584 
4585 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4586 {
4587 	struct mem_cgroup *memcg;
4588 	unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
4589 
4590 	VM_WARN_ON_ONCE(!current_is_kswapd());
4591 
4592 	sc->last_reclaimed = sc->nr_reclaimed;
4593 
4594 	/* check the order to exclude compaction-induced reclaim */
4595 	if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
4596 		return;
4597 
4598 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
4599 	do {
4600 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4601 
4602 		if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4603 			mem_cgroup_iter_break(NULL, memcg);
4604 			return;
4605 		}
4606 
4607 		cond_resched();
4608 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4609 
4610 	/*
4611 	 * The main goal is to OOM kill if every generation from all memcgs is
4612 	 * younger than min_ttl. However, another possibility is all memcgs are
4613 	 * either too small or below min.
4614 	 */
4615 	if (mutex_trylock(&oom_lock)) {
4616 		struct oom_control oc = {
4617 			.gfp_mask = sc->gfp_mask,
4618 		};
4619 
4620 		out_of_memory(&oc);
4621 
4622 		mutex_unlock(&oom_lock);
4623 	}
4624 }
4625 
4626 /*
4627  * This function exploits spatial locality when shrink_folio_list() walks the
4628  * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4629  * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4630  * the PTE table to the Bloom filter. This forms a feedback loop between the
4631  * eviction and the aging.
4632  */
4633 void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4634 {
4635 	int i;
4636 	pte_t *pte;
4637 	unsigned long start;
4638 	unsigned long end;
4639 	unsigned long addr;
4640 	struct lru_gen_mm_walk *walk;
4641 	int young = 0;
4642 	unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4643 	struct folio *folio = pfn_folio(pvmw->pfn);
4644 	struct mem_cgroup *memcg = folio_memcg(folio);
4645 	struct pglist_data *pgdat = folio_pgdat(folio);
4646 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4647 	DEFINE_MAX_SEQ(lruvec);
4648 	int old_gen, new_gen = lru_gen_from_seq(max_seq);
4649 
4650 	lockdep_assert_held(pvmw->ptl);
4651 	VM_WARN_ON_ONCE_FOLIO(folio_test_lru(folio), folio);
4652 
4653 	if (spin_is_contended(pvmw->ptl))
4654 		return;
4655 
4656 	/* avoid taking the LRU lock under the PTL when possible */
4657 	walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4658 
4659 	start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4660 	end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4661 
4662 	if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4663 		if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4664 			end = start + MIN_LRU_BATCH * PAGE_SIZE;
4665 		else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4666 			start = end - MIN_LRU_BATCH * PAGE_SIZE;
4667 		else {
4668 			start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4669 			end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4670 		}
4671 	}
4672 
4673 	pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4674 
4675 	rcu_read_lock();
4676 	arch_enter_lazy_mmu_mode();
4677 
4678 	for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4679 		unsigned long pfn;
4680 
4681 		pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4682 		if (pfn == -1)
4683 			continue;
4684 
4685 		if (!pte_young(pte[i]))
4686 			continue;
4687 
4688 		folio = get_pfn_folio(pfn, memcg, pgdat, !walk || walk->can_swap);
4689 		if (!folio)
4690 			continue;
4691 
4692 		if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4693 			VM_WARN_ON_ONCE(true);
4694 
4695 		young++;
4696 
4697 		if (pte_dirty(pte[i]) && !folio_test_dirty(folio) &&
4698 		    !(folio_test_anon(folio) && folio_test_swapbacked(folio) &&
4699 		      !folio_test_swapcache(folio)))
4700 			folio_mark_dirty(folio);
4701 
4702 		old_gen = folio_lru_gen(folio);
4703 		if (old_gen < 0)
4704 			folio_set_referenced(folio);
4705 		else if (old_gen != new_gen)
4706 			__set_bit(i, bitmap);
4707 	}
4708 
4709 	arch_leave_lazy_mmu_mode();
4710 	rcu_read_unlock();
4711 
4712 	/* feedback from rmap walkers to page table walkers */
4713 	if (suitable_to_scan(i, young))
4714 		update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4715 
4716 	if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
4717 		for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4718 			folio = pfn_folio(pte_pfn(pte[i]));
4719 			folio_activate(folio);
4720 		}
4721 		return;
4722 	}
4723 
4724 	/* folio_update_gen() requires stable folio_memcg() */
4725 	if (!mem_cgroup_trylock_pages(memcg))
4726 		return;
4727 
4728 	if (!walk) {
4729 		spin_lock_irq(&lruvec->lru_lock);
4730 		new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4731 	}
4732 
4733 	for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4734 		folio = pfn_folio(pte_pfn(pte[i]));
4735 		if (folio_memcg_rcu(folio) != memcg)
4736 			continue;
4737 
4738 		old_gen = folio_update_gen(folio, new_gen);
4739 		if (old_gen < 0 || old_gen == new_gen)
4740 			continue;
4741 
4742 		if (walk)
4743 			update_batch_size(walk, folio, old_gen, new_gen);
4744 		else
4745 			lru_gen_update_size(lruvec, folio, old_gen, new_gen);
4746 	}
4747 
4748 	if (!walk)
4749 		spin_unlock_irq(&lruvec->lru_lock);
4750 
4751 	mem_cgroup_unlock_pages();
4752 }
4753 
4754 /******************************************************************************
4755  *                          the eviction
4756  ******************************************************************************/
4757 
4758 static bool sort_folio(struct lruvec *lruvec, struct folio *folio, int tier_idx)
4759 {
4760 	bool success;
4761 	int gen = folio_lru_gen(folio);
4762 	int type = folio_is_file_lru(folio);
4763 	int zone = folio_zonenum(folio);
4764 	int delta = folio_nr_pages(folio);
4765 	int refs = folio_lru_refs(folio);
4766 	int tier = lru_tier_from_refs(refs);
4767 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4768 
4769 	VM_WARN_ON_ONCE_FOLIO(gen >= MAX_NR_GENS, folio);
4770 
4771 	/* unevictable */
4772 	if (!folio_evictable(folio)) {
4773 		success = lru_gen_del_folio(lruvec, folio, true);
4774 		VM_WARN_ON_ONCE_FOLIO(!success, folio);
4775 		folio_set_unevictable(folio);
4776 		lruvec_add_folio(lruvec, folio);
4777 		__count_vm_events(UNEVICTABLE_PGCULLED, delta);
4778 		return true;
4779 	}
4780 
4781 	/* dirty lazyfree */
4782 	if (type == LRU_GEN_FILE && folio_test_anon(folio) && folio_test_dirty(folio)) {
4783 		success = lru_gen_del_folio(lruvec, folio, true);
4784 		VM_WARN_ON_ONCE_FOLIO(!success, folio);
4785 		folio_set_swapbacked(folio);
4786 		lruvec_add_folio_tail(lruvec, folio);
4787 		return true;
4788 	}
4789 
4790 	/* promoted */
4791 	if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4792 		list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4793 		return true;
4794 	}
4795 
4796 	/* protected */
4797 	if (tier > tier_idx) {
4798 		int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4799 
4800 		gen = folio_inc_gen(lruvec, folio, false);
4801 		list_move_tail(&folio->lru, &lrugen->folios[gen][type][zone]);
4802 
4803 		WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4804 			   lrugen->protected[hist][type][tier - 1] + delta);
4805 		__mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4806 		return true;
4807 	}
4808 
4809 	/* waiting for writeback */
4810 	if (folio_test_locked(folio) || folio_test_writeback(folio) ||
4811 	    (type == LRU_GEN_FILE && folio_test_dirty(folio))) {
4812 		gen = folio_inc_gen(lruvec, folio, true);
4813 		list_move(&folio->lru, &lrugen->folios[gen][type][zone]);
4814 		return true;
4815 	}
4816 
4817 	return false;
4818 }
4819 
4820 static bool isolate_folio(struct lruvec *lruvec, struct folio *folio, struct scan_control *sc)
4821 {
4822 	bool success;
4823 
4824 	/* unmapping inhibited */
4825 	if (!sc->may_unmap && folio_mapped(folio))
4826 		return false;
4827 
4828 	/* swapping inhibited */
4829 	if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4830 	    (folio_test_dirty(folio) ||
4831 	     (folio_test_anon(folio) && !folio_test_swapcache(folio))))
4832 		return false;
4833 
4834 	/* raced with release_pages() */
4835 	if (!folio_try_get(folio))
4836 		return false;
4837 
4838 	/* raced with another isolation */
4839 	if (!folio_test_clear_lru(folio)) {
4840 		folio_put(folio);
4841 		return false;
4842 	}
4843 
4844 	/* see the comment on MAX_NR_TIERS */
4845 	if (!folio_test_referenced(folio))
4846 		set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4847 
4848 	/* for shrink_folio_list() */
4849 	folio_clear_reclaim(folio);
4850 	folio_clear_referenced(folio);
4851 
4852 	success = lru_gen_del_folio(lruvec, folio, true);
4853 	VM_WARN_ON_ONCE_FOLIO(!success, folio);
4854 
4855 	return true;
4856 }
4857 
4858 static int scan_folios(struct lruvec *lruvec, struct scan_control *sc,
4859 		       int type, int tier, struct list_head *list)
4860 {
4861 	int gen, zone;
4862 	enum vm_event_item item;
4863 	int sorted = 0;
4864 	int scanned = 0;
4865 	int isolated = 0;
4866 	int remaining = MAX_LRU_BATCH;
4867 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
4868 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4869 
4870 	VM_WARN_ON_ONCE(!list_empty(list));
4871 
4872 	if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4873 		return 0;
4874 
4875 	gen = lru_gen_from_seq(lrugen->min_seq[type]);
4876 
4877 	for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4878 		LIST_HEAD(moved);
4879 		int skipped = 0;
4880 		struct list_head *head = &lrugen->folios[gen][type][zone];
4881 
4882 		while (!list_empty(head)) {
4883 			struct folio *folio = lru_to_folio(head);
4884 			int delta = folio_nr_pages(folio);
4885 
4886 			VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
4887 			VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
4888 			VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
4889 			VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
4890 
4891 			scanned += delta;
4892 
4893 			if (sort_folio(lruvec, folio, tier))
4894 				sorted += delta;
4895 			else if (isolate_folio(lruvec, folio, sc)) {
4896 				list_add(&folio->lru, list);
4897 				isolated += delta;
4898 			} else {
4899 				list_move(&folio->lru, &moved);
4900 				skipped += delta;
4901 			}
4902 
4903 			if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4904 				break;
4905 		}
4906 
4907 		if (skipped) {
4908 			list_splice(&moved, head);
4909 			__count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4910 		}
4911 
4912 		if (!remaining || isolated >= MIN_LRU_BATCH)
4913 			break;
4914 	}
4915 
4916 	item = PGSCAN_KSWAPD + reclaimer_offset();
4917 	if (!cgroup_reclaim(sc)) {
4918 		__count_vm_events(item, isolated);
4919 		__count_vm_events(PGREFILL, sorted);
4920 	}
4921 	__count_memcg_events(memcg, item, isolated);
4922 	__count_memcg_events(memcg, PGREFILL, sorted);
4923 	__count_vm_events(PGSCAN_ANON + type, isolated);
4924 
4925 	/*
4926 	 * There might not be eligible pages due to reclaim_idx, may_unmap and
4927 	 * may_writepage. Check the remaining to prevent livelock if it's not
4928 	 * making progress.
4929 	 */
4930 	return isolated || !remaining ? scanned : 0;
4931 }
4932 
4933 static int get_tier_idx(struct lruvec *lruvec, int type)
4934 {
4935 	int tier;
4936 	struct ctrl_pos sp, pv;
4937 
4938 	/*
4939 	 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4940 	 * This value is chosen because any other tier would have at least twice
4941 	 * as many refaults as the first tier.
4942 	 */
4943 	read_ctrl_pos(lruvec, type, 0, 1, &sp);
4944 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4945 		read_ctrl_pos(lruvec, type, tier, 2, &pv);
4946 		if (!positive_ctrl_err(&sp, &pv))
4947 			break;
4948 	}
4949 
4950 	return tier - 1;
4951 }
4952 
4953 static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4954 {
4955 	int type, tier;
4956 	struct ctrl_pos sp, pv;
4957 	int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4958 
4959 	/*
4960 	 * Compare the first tier of anon with that of file to determine which
4961 	 * type to scan. Also need to compare other tiers of the selected type
4962 	 * with the first tier of the other type to determine the last tier (of
4963 	 * the selected type) to evict.
4964 	 */
4965 	read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4966 	read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4967 	type = positive_ctrl_err(&sp, &pv);
4968 
4969 	read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4970 	for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4971 		read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4972 		if (!positive_ctrl_err(&sp, &pv))
4973 			break;
4974 	}
4975 
4976 	*tier_idx = tier - 1;
4977 
4978 	return type;
4979 }
4980 
4981 static int isolate_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4982 			  int *type_scanned, struct list_head *list)
4983 {
4984 	int i;
4985 	int type;
4986 	int scanned;
4987 	int tier = -1;
4988 	DEFINE_MIN_SEQ(lruvec);
4989 
4990 	/*
4991 	 * Try to make the obvious choice first. When anon and file are both
4992 	 * available from the same generation, interpret swappiness 1 as file
4993 	 * first and 200 as anon first.
4994 	 */
4995 	if (!swappiness)
4996 		type = LRU_GEN_FILE;
4997 	else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4998 		type = LRU_GEN_ANON;
4999 	else if (swappiness == 1)
5000 		type = LRU_GEN_FILE;
5001 	else if (swappiness == 200)
5002 		type = LRU_GEN_ANON;
5003 	else
5004 		type = get_type_to_scan(lruvec, swappiness, &tier);
5005 
5006 	for (i = !swappiness; i < ANON_AND_FILE; i++) {
5007 		if (tier < 0)
5008 			tier = get_tier_idx(lruvec, type);
5009 
5010 		scanned = scan_folios(lruvec, sc, type, tier, list);
5011 		if (scanned)
5012 			break;
5013 
5014 		type = !type;
5015 		tier = -1;
5016 	}
5017 
5018 	*type_scanned = type;
5019 
5020 	return scanned;
5021 }
5022 
5023 static int evict_folios(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
5024 {
5025 	int type;
5026 	int scanned;
5027 	int reclaimed;
5028 	LIST_HEAD(list);
5029 	LIST_HEAD(clean);
5030 	struct folio *folio;
5031 	struct folio *next;
5032 	enum vm_event_item item;
5033 	struct reclaim_stat stat;
5034 	struct lru_gen_mm_walk *walk;
5035 	bool skip_retry = false;
5036 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5037 	struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5038 
5039 	spin_lock_irq(&lruvec->lru_lock);
5040 
5041 	scanned = isolate_folios(lruvec, sc, swappiness, &type, &list);
5042 
5043 	scanned += try_to_inc_min_seq(lruvec, swappiness);
5044 
5045 	if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
5046 		scanned = 0;
5047 
5048 	spin_unlock_irq(&lruvec->lru_lock);
5049 
5050 	if (list_empty(&list))
5051 		return scanned;
5052 retry:
5053 	reclaimed = shrink_folio_list(&list, pgdat, sc, &stat, false);
5054 	sc->nr_reclaimed += reclaimed;
5055 
5056 	list_for_each_entry_safe_reverse(folio, next, &list, lru) {
5057 		if (!folio_evictable(folio)) {
5058 			list_del(&folio->lru);
5059 			folio_putback_lru(folio);
5060 			continue;
5061 		}
5062 
5063 		if (folio_test_reclaim(folio) &&
5064 		    (folio_test_dirty(folio) || folio_test_writeback(folio))) {
5065 			/* restore LRU_REFS_FLAGS cleared by isolate_folio() */
5066 			if (folio_test_workingset(folio))
5067 				folio_set_referenced(folio);
5068 			continue;
5069 		}
5070 
5071 		if (skip_retry || folio_test_active(folio) || folio_test_referenced(folio) ||
5072 		    folio_mapped(folio) || folio_test_locked(folio) ||
5073 		    folio_test_dirty(folio) || folio_test_writeback(folio)) {
5074 			/* don't add rejected folios to the oldest generation */
5075 			set_mask_bits(&folio->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
5076 				      BIT(PG_active));
5077 			continue;
5078 		}
5079 
5080 		/* retry folios that may have missed folio_rotate_reclaimable() */
5081 		list_move(&folio->lru, &clean);
5082 		sc->nr_scanned -= folio_nr_pages(folio);
5083 	}
5084 
5085 	spin_lock_irq(&lruvec->lru_lock);
5086 
5087 	move_folios_to_lru(lruvec, &list);
5088 
5089 	walk = current->reclaim_state->mm_walk;
5090 	if (walk && walk->batched)
5091 		reset_batch_size(lruvec, walk);
5092 
5093 	item = PGSTEAL_KSWAPD + reclaimer_offset();
5094 	if (!cgroup_reclaim(sc))
5095 		__count_vm_events(item, reclaimed);
5096 	__count_memcg_events(memcg, item, reclaimed);
5097 	__count_vm_events(PGSTEAL_ANON + type, reclaimed);
5098 
5099 	spin_unlock_irq(&lruvec->lru_lock);
5100 
5101 	mem_cgroup_uncharge_list(&list);
5102 	free_unref_page_list(&list);
5103 
5104 	INIT_LIST_HEAD(&list);
5105 	list_splice_init(&clean, &list);
5106 
5107 	if (!list_empty(&list)) {
5108 		skip_retry = true;
5109 		goto retry;
5110 	}
5111 
5112 	return scanned;
5113 }
5114 
5115 /*
5116  * For future optimizations:
5117  * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
5118  *    reclaim.
5119  */
5120 static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
5121 				    bool can_swap)
5122 {
5123 	unsigned long nr_to_scan;
5124 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5125 	DEFINE_MAX_SEQ(lruvec);
5126 
5127 	if (mem_cgroup_below_min(sc->target_mem_cgroup, memcg) ||
5128 	    (mem_cgroup_below_low(sc->target_mem_cgroup, memcg) &&
5129 	     !sc->memcg_low_reclaim))
5130 		return 0;
5131 
5132 	if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
5133 		return nr_to_scan;
5134 
5135 	/* skip the aging path at the default priority */
5136 	if (sc->priority == DEF_PRIORITY)
5137 		return nr_to_scan;
5138 
5139 	try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false);
5140 
5141 	/* skip this lruvec as it's low on cold folios */
5142 	return 0;
5143 }
5144 
5145 static unsigned long get_nr_to_reclaim(struct scan_control *sc)
5146 {
5147 	/* don't abort memcg reclaim to ensure fairness */
5148 	if (!global_reclaim(sc))
5149 		return -1;
5150 
5151 	/* discount the previous progress for kswapd */
5152 	if (current_is_kswapd())
5153 		return sc->nr_to_reclaim + sc->last_reclaimed;
5154 
5155 	return max(sc->nr_to_reclaim, compact_gap(sc->order));
5156 }
5157 
5158 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5159 {
5160 	struct blk_plug plug;
5161 	unsigned long scanned = 0;
5162 	unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5163 
5164 	lru_add_drain();
5165 
5166 	blk_start_plug(&plug);
5167 
5168 	set_mm_walk(lruvec_pgdat(lruvec));
5169 
5170 	while (true) {
5171 		int delta;
5172 		int swappiness;
5173 		unsigned long nr_to_scan;
5174 
5175 		if (sc->may_swap)
5176 			swappiness = get_swappiness(lruvec, sc);
5177 		else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
5178 			swappiness = 1;
5179 		else
5180 			swappiness = 0;
5181 
5182 		nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
5183 		if (!nr_to_scan)
5184 			break;
5185 
5186 		delta = evict_folios(lruvec, sc, swappiness);
5187 		if (!delta)
5188 			break;
5189 
5190 		scanned += delta;
5191 		if (scanned >= nr_to_scan)
5192 			break;
5193 
5194 		if (sc->nr_reclaimed >= nr_to_reclaim)
5195 			break;
5196 
5197 		cond_resched();
5198 	}
5199 
5200 	clear_mm_walk();
5201 
5202 	blk_finish_plug(&plug);
5203 }
5204 
5205 /******************************************************************************
5206  *                          state change
5207  ******************************************************************************/
5208 
5209 static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5210 {
5211 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
5212 
5213 	if (lrugen->enabled) {
5214 		enum lru_list lru;
5215 
5216 		for_each_evictable_lru(lru) {
5217 			if (!list_empty(&lruvec->lists[lru]))
5218 				return false;
5219 		}
5220 	} else {
5221 		int gen, type, zone;
5222 
5223 		for_each_gen_type_zone(gen, type, zone) {
5224 			if (!list_empty(&lrugen->folios[gen][type][zone]))
5225 				return false;
5226 		}
5227 	}
5228 
5229 	return true;
5230 }
5231 
5232 static bool fill_evictable(struct lruvec *lruvec)
5233 {
5234 	enum lru_list lru;
5235 	int remaining = MAX_LRU_BATCH;
5236 
5237 	for_each_evictable_lru(lru) {
5238 		int type = is_file_lru(lru);
5239 		bool active = is_active_lru(lru);
5240 		struct list_head *head = &lruvec->lists[lru];
5241 
5242 		while (!list_empty(head)) {
5243 			bool success;
5244 			struct folio *folio = lru_to_folio(head);
5245 
5246 			VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5247 			VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio) != active, folio);
5248 			VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5249 			VM_WARN_ON_ONCE_FOLIO(folio_lru_gen(folio) != -1, folio);
5250 
5251 			lruvec_del_folio(lruvec, folio);
5252 			success = lru_gen_add_folio(lruvec, folio, false);
5253 			VM_WARN_ON_ONCE(!success);
5254 
5255 			if (!--remaining)
5256 				return false;
5257 		}
5258 	}
5259 
5260 	return true;
5261 }
5262 
5263 static bool drain_evictable(struct lruvec *lruvec)
5264 {
5265 	int gen, type, zone;
5266 	int remaining = MAX_LRU_BATCH;
5267 
5268 	for_each_gen_type_zone(gen, type, zone) {
5269 		struct list_head *head = &lruvec->lrugen.folios[gen][type][zone];
5270 
5271 		while (!list_empty(head)) {
5272 			bool success;
5273 			struct folio *folio = lru_to_folio(head);
5274 
5275 			VM_WARN_ON_ONCE_FOLIO(folio_test_unevictable(folio), folio);
5276 			VM_WARN_ON_ONCE_FOLIO(folio_test_active(folio), folio);
5277 			VM_WARN_ON_ONCE_FOLIO(folio_is_file_lru(folio) != type, folio);
5278 			VM_WARN_ON_ONCE_FOLIO(folio_zonenum(folio) != zone, folio);
5279 
5280 			success = lru_gen_del_folio(lruvec, folio, false);
5281 			VM_WARN_ON_ONCE(!success);
5282 			lruvec_add_folio(lruvec, folio);
5283 
5284 			if (!--remaining)
5285 				return false;
5286 		}
5287 	}
5288 
5289 	return true;
5290 }
5291 
5292 static void lru_gen_change_state(bool enabled)
5293 {
5294 	static DEFINE_MUTEX(state_mutex);
5295 
5296 	struct mem_cgroup *memcg;
5297 
5298 	cgroup_lock();
5299 	cpus_read_lock();
5300 	get_online_mems();
5301 	mutex_lock(&state_mutex);
5302 
5303 	if (enabled == lru_gen_enabled())
5304 		goto unlock;
5305 
5306 	if (enabled)
5307 		static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5308 	else
5309 		static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5310 
5311 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
5312 	do {
5313 		int nid;
5314 
5315 		for_each_node(nid) {
5316 			struct lruvec *lruvec = get_lruvec(memcg, nid);
5317 
5318 			spin_lock_irq(&lruvec->lru_lock);
5319 
5320 			VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5321 			VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5322 
5323 			lruvec->lrugen.enabled = enabled;
5324 
5325 			while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5326 				spin_unlock_irq(&lruvec->lru_lock);
5327 				cond_resched();
5328 				spin_lock_irq(&lruvec->lru_lock);
5329 			}
5330 
5331 			spin_unlock_irq(&lruvec->lru_lock);
5332 		}
5333 
5334 		cond_resched();
5335 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5336 unlock:
5337 	mutex_unlock(&state_mutex);
5338 	put_online_mems();
5339 	cpus_read_unlock();
5340 	cgroup_unlock();
5341 }
5342 
5343 /******************************************************************************
5344  *                          sysfs interface
5345  ******************************************************************************/
5346 
5347 static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5348 {
5349 	return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5350 }
5351 
5352 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5353 static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5354 			     const char *buf, size_t len)
5355 {
5356 	unsigned int msecs;
5357 
5358 	if (kstrtouint(buf, 0, &msecs))
5359 		return -EINVAL;
5360 
5361 	WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5362 
5363 	return len;
5364 }
5365 
5366 static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5367 	min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5368 );
5369 
5370 static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5371 {
5372 	unsigned int caps = 0;
5373 
5374 	if (get_cap(LRU_GEN_CORE))
5375 		caps |= BIT(LRU_GEN_CORE);
5376 
5377 	if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5378 		caps |= BIT(LRU_GEN_MM_WALK);
5379 
5380 	if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
5381 		caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5382 
5383 	return sysfs_emit(buf, "0x%04x\n", caps);
5384 }
5385 
5386 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5387 static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5388 			     const char *buf, size_t len)
5389 {
5390 	int i;
5391 	unsigned int caps;
5392 
5393 	if (tolower(*buf) == 'n')
5394 		caps = 0;
5395 	else if (tolower(*buf) == 'y')
5396 		caps = -1;
5397 	else if (kstrtouint(buf, 0, &caps))
5398 		return -EINVAL;
5399 
5400 	for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5401 		bool enabled = caps & BIT(i);
5402 
5403 		if (i == LRU_GEN_CORE)
5404 			lru_gen_change_state(enabled);
5405 		else if (enabled)
5406 			static_branch_enable(&lru_gen_caps[i]);
5407 		else
5408 			static_branch_disable(&lru_gen_caps[i]);
5409 	}
5410 
5411 	return len;
5412 }
5413 
5414 static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5415 	enabled, 0644, show_enabled, store_enabled
5416 );
5417 
5418 static struct attribute *lru_gen_attrs[] = {
5419 	&lru_gen_min_ttl_attr.attr,
5420 	&lru_gen_enabled_attr.attr,
5421 	NULL
5422 };
5423 
5424 static struct attribute_group lru_gen_attr_group = {
5425 	.name = "lru_gen",
5426 	.attrs = lru_gen_attrs,
5427 };
5428 
5429 /******************************************************************************
5430  *                          debugfs interface
5431  ******************************************************************************/
5432 
5433 static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5434 {
5435 	struct mem_cgroup *memcg;
5436 	loff_t nr_to_skip = *pos;
5437 
5438 	m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5439 	if (!m->private)
5440 		return ERR_PTR(-ENOMEM);
5441 
5442 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
5443 	do {
5444 		int nid;
5445 
5446 		for_each_node_state(nid, N_MEMORY) {
5447 			if (!nr_to_skip--)
5448 				return get_lruvec(memcg, nid);
5449 		}
5450 	} while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5451 
5452 	return NULL;
5453 }
5454 
5455 static void lru_gen_seq_stop(struct seq_file *m, void *v)
5456 {
5457 	if (!IS_ERR_OR_NULL(v))
5458 		mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5459 
5460 	kvfree(m->private);
5461 	m->private = NULL;
5462 }
5463 
5464 static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5465 {
5466 	int nid = lruvec_pgdat(v)->node_id;
5467 	struct mem_cgroup *memcg = lruvec_memcg(v);
5468 
5469 	++*pos;
5470 
5471 	nid = next_memory_node(nid);
5472 	if (nid == MAX_NUMNODES) {
5473 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
5474 		if (!memcg)
5475 			return NULL;
5476 
5477 		nid = first_memory_node;
5478 	}
5479 
5480 	return get_lruvec(memcg, nid);
5481 }
5482 
5483 static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5484 				  unsigned long max_seq, unsigned long *min_seq,
5485 				  unsigned long seq)
5486 {
5487 	int i;
5488 	int type, tier;
5489 	int hist = lru_hist_from_seq(seq);
5490 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
5491 
5492 	for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5493 		seq_printf(m, "            %10d", tier);
5494 		for (type = 0; type < ANON_AND_FILE; type++) {
5495 			const char *s = "   ";
5496 			unsigned long n[3] = {};
5497 
5498 			if (seq == max_seq) {
5499 				s = "RT ";
5500 				n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5501 				n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5502 			} else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5503 				s = "rep";
5504 				n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5505 				n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5506 				if (tier)
5507 					n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5508 			}
5509 
5510 			for (i = 0; i < 3; i++)
5511 				seq_printf(m, " %10lu%c", n[i], s[i]);
5512 		}
5513 		seq_putc(m, '\n');
5514 	}
5515 
5516 	seq_puts(m, "                      ");
5517 	for (i = 0; i < NR_MM_STATS; i++) {
5518 		const char *s = "      ";
5519 		unsigned long n = 0;
5520 
5521 		if (seq == max_seq && NR_HIST_GENS == 1) {
5522 			s = "LOYNFA";
5523 			n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5524 		} else if (seq != max_seq && NR_HIST_GENS > 1) {
5525 			s = "loynfa";
5526 			n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5527 		}
5528 
5529 		seq_printf(m, " %10lu%c", n, s[i]);
5530 	}
5531 	seq_putc(m, '\n');
5532 }
5533 
5534 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5535 static int lru_gen_seq_show(struct seq_file *m, void *v)
5536 {
5537 	unsigned long seq;
5538 	bool full = !debugfs_real_fops(m->file)->write;
5539 	struct lruvec *lruvec = v;
5540 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
5541 	int nid = lruvec_pgdat(lruvec)->node_id;
5542 	struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5543 	DEFINE_MAX_SEQ(lruvec);
5544 	DEFINE_MIN_SEQ(lruvec);
5545 
5546 	if (nid == first_memory_node) {
5547 		const char *path = memcg ? m->private : "";
5548 
5549 #ifdef CONFIG_MEMCG
5550 		if (memcg)
5551 			cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5552 #endif
5553 		seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5554 	}
5555 
5556 	seq_printf(m, " node %5d\n", nid);
5557 
5558 	if (!full)
5559 		seq = min_seq[LRU_GEN_ANON];
5560 	else if (max_seq >= MAX_NR_GENS)
5561 		seq = max_seq - MAX_NR_GENS + 1;
5562 	else
5563 		seq = 0;
5564 
5565 	for (; seq <= max_seq; seq++) {
5566 		int type, zone;
5567 		int gen = lru_gen_from_seq(seq);
5568 		unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5569 
5570 		seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5571 
5572 		for (type = 0; type < ANON_AND_FILE; type++) {
5573 			unsigned long size = 0;
5574 			char mark = full && seq < min_seq[type] ? 'x' : ' ';
5575 
5576 			for (zone = 0; zone < MAX_NR_ZONES; zone++)
5577 				size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5578 
5579 			seq_printf(m, " %10lu%c", size, mark);
5580 		}
5581 
5582 		seq_putc(m, '\n');
5583 
5584 		if (full)
5585 			lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5586 	}
5587 
5588 	return 0;
5589 }
5590 
5591 static const struct seq_operations lru_gen_seq_ops = {
5592 	.start = lru_gen_seq_start,
5593 	.stop = lru_gen_seq_stop,
5594 	.next = lru_gen_seq_next,
5595 	.show = lru_gen_seq_show,
5596 };
5597 
5598 static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5599 		     bool can_swap, bool force_scan)
5600 {
5601 	DEFINE_MAX_SEQ(lruvec);
5602 	DEFINE_MIN_SEQ(lruvec);
5603 
5604 	if (seq < max_seq)
5605 		return 0;
5606 
5607 	if (seq > max_seq)
5608 		return -EINVAL;
5609 
5610 	if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5611 		return -ERANGE;
5612 
5613 	try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5614 
5615 	return 0;
5616 }
5617 
5618 static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5619 			int swappiness, unsigned long nr_to_reclaim)
5620 {
5621 	DEFINE_MAX_SEQ(lruvec);
5622 
5623 	if (seq + MIN_NR_GENS > max_seq)
5624 		return -EINVAL;
5625 
5626 	sc->nr_reclaimed = 0;
5627 
5628 	while (!signal_pending(current)) {
5629 		DEFINE_MIN_SEQ(lruvec);
5630 
5631 		if (seq < min_seq[!swappiness])
5632 			return 0;
5633 
5634 		if (sc->nr_reclaimed >= nr_to_reclaim)
5635 			return 0;
5636 
5637 		if (!evict_folios(lruvec, sc, swappiness))
5638 			return 0;
5639 
5640 		cond_resched();
5641 	}
5642 
5643 	return -EINTR;
5644 }
5645 
5646 static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5647 		   struct scan_control *sc, int swappiness, unsigned long opt)
5648 {
5649 	struct lruvec *lruvec;
5650 	int err = -EINVAL;
5651 	struct mem_cgroup *memcg = NULL;
5652 
5653 	if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5654 		return -EINVAL;
5655 
5656 	if (!mem_cgroup_disabled()) {
5657 		rcu_read_lock();
5658 		memcg = mem_cgroup_from_id(memcg_id);
5659 #ifdef CONFIG_MEMCG
5660 		if (memcg && !css_tryget(&memcg->css))
5661 			memcg = NULL;
5662 #endif
5663 		rcu_read_unlock();
5664 
5665 		if (!memcg)
5666 			return -EINVAL;
5667 	}
5668 
5669 	if (memcg_id != mem_cgroup_id(memcg))
5670 		goto done;
5671 
5672 	lruvec = get_lruvec(memcg, nid);
5673 
5674 	if (swappiness < 0)
5675 		swappiness = get_swappiness(lruvec, sc);
5676 	else if (swappiness > 200)
5677 		goto done;
5678 
5679 	switch (cmd) {
5680 	case '+':
5681 		err = run_aging(lruvec, seq, sc, swappiness, opt);
5682 		break;
5683 	case '-':
5684 		err = run_eviction(lruvec, seq, sc, swappiness, opt);
5685 		break;
5686 	}
5687 done:
5688 	mem_cgroup_put(memcg);
5689 
5690 	return err;
5691 }
5692 
5693 /* see Documentation/admin-guide/mm/multigen_lru.rst for details */
5694 static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5695 				 size_t len, loff_t *pos)
5696 {
5697 	void *buf;
5698 	char *cur, *next;
5699 	unsigned int flags;
5700 	struct blk_plug plug;
5701 	int err = -EINVAL;
5702 	struct scan_control sc = {
5703 		.may_writepage = true,
5704 		.may_unmap = true,
5705 		.may_swap = true,
5706 		.reclaim_idx = MAX_NR_ZONES - 1,
5707 		.gfp_mask = GFP_KERNEL,
5708 	};
5709 
5710 	buf = kvmalloc(len + 1, GFP_KERNEL);
5711 	if (!buf)
5712 		return -ENOMEM;
5713 
5714 	if (copy_from_user(buf, src, len)) {
5715 		kvfree(buf);
5716 		return -EFAULT;
5717 	}
5718 
5719 	set_task_reclaim_state(current, &sc.reclaim_state);
5720 	flags = memalloc_noreclaim_save();
5721 	blk_start_plug(&plug);
5722 	if (!set_mm_walk(NULL)) {
5723 		err = -ENOMEM;
5724 		goto done;
5725 	}
5726 
5727 	next = buf;
5728 	next[len] = '\0';
5729 
5730 	while ((cur = strsep(&next, ",;\n"))) {
5731 		int n;
5732 		int end;
5733 		char cmd;
5734 		unsigned int memcg_id;
5735 		unsigned int nid;
5736 		unsigned long seq;
5737 		unsigned int swappiness = -1;
5738 		unsigned long opt = -1;
5739 
5740 		cur = skip_spaces(cur);
5741 		if (!*cur)
5742 			continue;
5743 
5744 		n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5745 			   &seq, &end, &swappiness, &end, &opt, &end);
5746 		if (n < 4 || cur[end]) {
5747 			err = -EINVAL;
5748 			break;
5749 		}
5750 
5751 		err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5752 		if (err)
5753 			break;
5754 	}
5755 done:
5756 	clear_mm_walk();
5757 	blk_finish_plug(&plug);
5758 	memalloc_noreclaim_restore(flags);
5759 	set_task_reclaim_state(current, NULL);
5760 
5761 	kvfree(buf);
5762 
5763 	return err ? : len;
5764 }
5765 
5766 static int lru_gen_seq_open(struct inode *inode, struct file *file)
5767 {
5768 	return seq_open(file, &lru_gen_seq_ops);
5769 }
5770 
5771 static const struct file_operations lru_gen_rw_fops = {
5772 	.open = lru_gen_seq_open,
5773 	.read = seq_read,
5774 	.write = lru_gen_seq_write,
5775 	.llseek = seq_lseek,
5776 	.release = seq_release,
5777 };
5778 
5779 static const struct file_operations lru_gen_ro_fops = {
5780 	.open = lru_gen_seq_open,
5781 	.read = seq_read,
5782 	.llseek = seq_lseek,
5783 	.release = seq_release,
5784 };
5785 
5786 /******************************************************************************
5787  *                          initialization
5788  ******************************************************************************/
5789 
5790 void lru_gen_init_lruvec(struct lruvec *lruvec)
5791 {
5792 	int i;
5793 	int gen, type, zone;
5794 	struct lru_gen_folio *lrugen = &lruvec->lrugen;
5795 
5796 	lrugen->max_seq = MIN_NR_GENS + 1;
5797 	lrugen->enabled = lru_gen_enabled();
5798 
5799 	for (i = 0; i <= MIN_NR_GENS + 1; i++)
5800 		lrugen->timestamps[i] = jiffies;
5801 
5802 	for_each_gen_type_zone(gen, type, zone)
5803 		INIT_LIST_HEAD(&lrugen->folios[gen][type][zone]);
5804 
5805 	lruvec->mm_state.seq = MIN_NR_GENS;
5806 	init_waitqueue_head(&lruvec->mm_state.wait);
5807 }
5808 
5809 #ifdef CONFIG_MEMCG
5810 void lru_gen_init_memcg(struct mem_cgroup *memcg)
5811 {
5812 	INIT_LIST_HEAD(&memcg->mm_list.fifo);
5813 	spin_lock_init(&memcg->mm_list.lock);
5814 }
5815 
5816 void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5817 {
5818 	int i;
5819 	int nid;
5820 
5821 	for_each_node(nid) {
5822 		struct lruvec *lruvec = get_lruvec(memcg, nid);
5823 
5824 		VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5825 					   sizeof(lruvec->lrugen.nr_pages)));
5826 
5827 		for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5828 			bitmap_free(lruvec->mm_state.filters[i]);
5829 			lruvec->mm_state.filters[i] = NULL;
5830 		}
5831 	}
5832 }
5833 #endif
5834 
5835 static int __init init_lru_gen(void)
5836 {
5837 	BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5838 	BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5839 
5840 	if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5841 		pr_err("lru_gen: failed to create sysfs group\n");
5842 
5843 	debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5844 	debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5845 
5846 	return 0;
5847 };
5848 late_initcall(init_lru_gen);
5849 
5850 #else /* !CONFIG_LRU_GEN */
5851 
5852 static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5853 {
5854 }
5855 
5856 static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5857 {
5858 }
5859 
5860 #endif /* CONFIG_LRU_GEN */
5861 
5862 static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5863 {
5864 	unsigned long nr[NR_LRU_LISTS];
5865 	unsigned long targets[NR_LRU_LISTS];
5866 	unsigned long nr_to_scan;
5867 	enum lru_list lru;
5868 	unsigned long nr_reclaimed = 0;
5869 	unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5870 	bool proportional_reclaim;
5871 	struct blk_plug plug;
5872 
5873 	if (lru_gen_enabled()) {
5874 		lru_gen_shrink_lruvec(lruvec, sc);
5875 		return;
5876 	}
5877 
5878 	get_scan_count(lruvec, sc, nr);
5879 
5880 	/* Record the original scan target for proportional adjustments later */
5881 	memcpy(targets, nr, sizeof(nr));
5882 
5883 	/*
5884 	 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5885 	 * event that can occur when there is little memory pressure e.g.
5886 	 * multiple streaming readers/writers. Hence, we do not abort scanning
5887 	 * when the requested number of pages are reclaimed when scanning at
5888 	 * DEF_PRIORITY on the assumption that the fact we are direct
5889 	 * reclaiming implies that kswapd is not keeping up and it is best to
5890 	 * do a batch of work at once. For memcg reclaim one check is made to
5891 	 * abort proportional reclaim if either the file or anon lru has already
5892 	 * dropped to zero at the first pass.
5893 	 */
5894 	proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5895 				sc->priority == DEF_PRIORITY);
5896 
5897 	blk_start_plug(&plug);
5898 	while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5899 					nr[LRU_INACTIVE_FILE]) {
5900 		unsigned long nr_anon, nr_file, percentage;
5901 		unsigned long nr_scanned;
5902 
5903 		for_each_evictable_lru(lru) {
5904 			if (nr[lru]) {
5905 				nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5906 				nr[lru] -= nr_to_scan;
5907 
5908 				nr_reclaimed += shrink_list(lru, nr_to_scan,
5909 							    lruvec, sc);
5910 			}
5911 		}
5912 
5913 		cond_resched();
5914 
5915 		if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
5916 			continue;
5917 
5918 		/*
5919 		 * For kswapd and memcg, reclaim at least the number of pages
5920 		 * requested. Ensure that the anon and file LRUs are scanned
5921 		 * proportionally what was requested by get_scan_count(). We
5922 		 * stop reclaiming one LRU and reduce the amount scanning
5923 		 * proportional to the original scan target.
5924 		 */
5925 		nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5926 		nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5927 
5928 		/*
5929 		 * It's just vindictive to attack the larger once the smaller
5930 		 * has gone to zero.  And given the way we stop scanning the
5931 		 * smaller below, this makes sure that we only make one nudge
5932 		 * towards proportionality once we've got nr_to_reclaim.
5933 		 */
5934 		if (!nr_file || !nr_anon)
5935 			break;
5936 
5937 		if (nr_file > nr_anon) {
5938 			unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5939 						targets[LRU_ACTIVE_ANON] + 1;
5940 			lru = LRU_BASE;
5941 			percentage = nr_anon * 100 / scan_target;
5942 		} else {
5943 			unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5944 						targets[LRU_ACTIVE_FILE] + 1;
5945 			lru = LRU_FILE;
5946 			percentage = nr_file * 100 / scan_target;
5947 		}
5948 
5949 		/* Stop scanning the smaller of the LRU */
5950 		nr[lru] = 0;
5951 		nr[lru + LRU_ACTIVE] = 0;
5952 
5953 		/*
5954 		 * Recalculate the other LRU scan count based on its original
5955 		 * scan target and the percentage scanning already complete
5956 		 */
5957 		lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5958 		nr_scanned = targets[lru] - nr[lru];
5959 		nr[lru] = targets[lru] * (100 - percentage) / 100;
5960 		nr[lru] -= min(nr[lru], nr_scanned);
5961 
5962 		lru += LRU_ACTIVE;
5963 		nr_scanned = targets[lru] - nr[lru];
5964 		nr[lru] = targets[lru] * (100 - percentage) / 100;
5965 		nr[lru] -= min(nr[lru], nr_scanned);
5966 	}
5967 	blk_finish_plug(&plug);
5968 	sc->nr_reclaimed += nr_reclaimed;
5969 
5970 	/*
5971 	 * Even if we did not try to evict anon pages at all, we want to
5972 	 * rebalance the anon lru active/inactive ratio.
5973 	 */
5974 	if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5975 	    inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5976 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5977 				   sc, LRU_ACTIVE_ANON);
5978 }
5979 
5980 /* Use reclaim/compaction for costly allocs or under memory pressure */
5981 static bool in_reclaim_compaction(struct scan_control *sc)
5982 {
5983 	if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
5984 			(sc->order > PAGE_ALLOC_COSTLY_ORDER ||
5985 			 sc->priority < DEF_PRIORITY - 2))
5986 		return true;
5987 
5988 	return false;
5989 }
5990 
5991 /*
5992  * Reclaim/compaction is used for high-order allocation requests. It reclaims
5993  * order-0 pages before compacting the zone. should_continue_reclaim() returns
5994  * true if more pages should be reclaimed such that when the page allocator
5995  * calls try_to_compact_pages() that it will have enough free pages to succeed.
5996  * It will give up earlier than that if there is difficulty reclaiming pages.
5997  */
5998 static inline bool should_continue_reclaim(struct pglist_data *pgdat,
5999 					unsigned long nr_reclaimed,
6000 					struct scan_control *sc)
6001 {
6002 	unsigned long pages_for_compaction;
6003 	unsigned long inactive_lru_pages;
6004 	int z;
6005 
6006 	/* If not in reclaim/compaction mode, stop */
6007 	if (!in_reclaim_compaction(sc))
6008 		return false;
6009 
6010 	/*
6011 	 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6012 	 * number of pages that were scanned. This will return to the caller
6013 	 * with the risk reclaim/compaction and the resulting allocation attempt
6014 	 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6015 	 * allocations through requiring that the full LRU list has been scanned
6016 	 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6017 	 * scan, but that approximation was wrong, and there were corner cases
6018 	 * where always a non-zero amount of pages were scanned.
6019 	 */
6020 	if (!nr_reclaimed)
6021 		return false;
6022 
6023 	/* If compaction would go ahead or the allocation would succeed, stop */
6024 	for (z = 0; z <= sc->reclaim_idx; z++) {
6025 		struct zone *zone = &pgdat->node_zones[z];
6026 		if (!managed_zone(zone))
6027 			continue;
6028 
6029 		switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
6030 		case COMPACT_SUCCESS:
6031 		case COMPACT_CONTINUE:
6032 			return false;
6033 		default:
6034 			/* check next zone */
6035 			;
6036 		}
6037 	}
6038 
6039 	/*
6040 	 * If we have not reclaimed enough pages for compaction and the
6041 	 * inactive lists are large enough, continue reclaiming
6042 	 */
6043 	pages_for_compaction = compact_gap(sc->order);
6044 	inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
6045 	if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
6046 		inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6047 
6048 	return inactive_lru_pages > pages_for_compaction;
6049 }
6050 
6051 static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
6052 {
6053 	struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
6054 	struct mem_cgroup *memcg;
6055 
6056 	memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
6057 	do {
6058 		struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6059 		unsigned long reclaimed;
6060 		unsigned long scanned;
6061 
6062 		/*
6063 		 * This loop can become CPU-bound when target memcgs
6064 		 * aren't eligible for reclaim - either because they
6065 		 * don't have any reclaimable pages, or because their
6066 		 * memory is explicitly protected. Avoid soft lockups.
6067 		 */
6068 		cond_resched();
6069 
6070 		mem_cgroup_calculate_protection(target_memcg, memcg);
6071 
6072 		if (mem_cgroup_below_min(target_memcg, memcg)) {
6073 			/*
6074 			 * Hard protection.
6075 			 * If there is no reclaimable memory, OOM.
6076 			 */
6077 			continue;
6078 		} else if (mem_cgroup_below_low(target_memcg, memcg)) {
6079 			/*
6080 			 * Soft protection.
6081 			 * Respect the protection only as long as
6082 			 * there is an unprotected supply
6083 			 * of reclaimable memory from other cgroups.
6084 			 */
6085 			if (!sc->memcg_low_reclaim) {
6086 				sc->memcg_low_skipped = 1;
6087 				continue;
6088 			}
6089 			memcg_memory_event(memcg, MEMCG_LOW);
6090 		}
6091 
6092 		reclaimed = sc->nr_reclaimed;
6093 		scanned = sc->nr_scanned;
6094 
6095 		shrink_lruvec(lruvec, sc);
6096 
6097 		shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6098 			    sc->priority);
6099 
6100 		/* Record the group's reclaim efficiency */
6101 		if (!sc->proactive)
6102 			vmpressure(sc->gfp_mask, memcg, false,
6103 				   sc->nr_scanned - scanned,
6104 				   sc->nr_reclaimed - reclaimed);
6105 
6106 	} while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6107 }
6108 
6109 static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
6110 {
6111 	struct reclaim_state *reclaim_state = current->reclaim_state;
6112 	unsigned long nr_reclaimed, nr_scanned;
6113 	struct lruvec *target_lruvec;
6114 	bool reclaimable = false;
6115 
6116 	target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6117 
6118 again:
6119 	memset(&sc->nr, 0, sizeof(sc->nr));
6120 
6121 	nr_reclaimed = sc->nr_reclaimed;
6122 	nr_scanned = sc->nr_scanned;
6123 
6124 	prepare_scan_count(pgdat, sc);
6125 
6126 	shrink_node_memcgs(pgdat, sc);
6127 
6128 	if (reclaim_state) {
6129 		sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6130 		reclaim_state->reclaimed_slab = 0;
6131 	}
6132 
6133 	/* Record the subtree's reclaim efficiency */
6134 	if (!sc->proactive)
6135 		vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6136 			   sc->nr_scanned - nr_scanned,
6137 			   sc->nr_reclaimed - nr_reclaimed);
6138 
6139 	if (sc->nr_reclaimed - nr_reclaimed)
6140 		reclaimable = true;
6141 
6142 	if (current_is_kswapd()) {
6143 		/*
6144 		 * If reclaim is isolating dirty pages under writeback,
6145 		 * it implies that the long-lived page allocation rate
6146 		 * is exceeding the page laundering rate. Either the
6147 		 * global limits are not being effective at throttling
6148 		 * processes due to the page distribution throughout
6149 		 * zones or there is heavy usage of a slow backing
6150 		 * device. The only option is to throttle from reclaim
6151 		 * context which is not ideal as there is no guarantee
6152 		 * the dirtying process is throttled in the same way
6153 		 * balance_dirty_pages() manages.
6154 		 *
6155 		 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6156 		 * count the number of pages under pages flagged for
6157 		 * immediate reclaim and stall if any are encountered
6158 		 * in the nr_immediate check below.
6159 		 */
6160 		if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6161 			set_bit(PGDAT_WRITEBACK, &pgdat->flags);
6162 
6163 		/* Allow kswapd to start writing pages during reclaim.*/
6164 		if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6165 			set_bit(PGDAT_DIRTY, &pgdat->flags);
6166 
6167 		/*
6168 		 * If kswapd scans pages marked for immediate
6169 		 * reclaim and under writeback (nr_immediate), it
6170 		 * implies that pages are cycling through the LRU
6171 		 * faster than they are written so forcibly stall
6172 		 * until some pages complete writeback.
6173 		 */
6174 		if (sc->nr.immediate)
6175 			reclaim_throttle(pgdat, VMSCAN_THROTTLE_WRITEBACK);
6176 	}
6177 
6178 	/*
6179 	 * Tag a node/memcg as congested if all the dirty pages were marked
6180 	 * for writeback and immediate reclaim (counted in nr.congested).
6181 	 *
6182 	 * Legacy memcg will stall in page writeback so avoid forcibly
6183 	 * stalling in reclaim_throttle().
6184 	 */
6185 	if ((current_is_kswapd() ||
6186 	     (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
6187 	    sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
6188 		set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
6189 
6190 	/*
6191 	 * Stall direct reclaim for IO completions if the lruvec is
6192 	 * node is congested. Allow kswapd to continue until it
6193 	 * starts encountering unqueued dirty pages or cycling through
6194 	 * the LRU too quickly.
6195 	 */
6196 	if (!current_is_kswapd() && current_may_throttle() &&
6197 	    !sc->hibernation_mode &&
6198 	    test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
6199 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_CONGESTED);
6200 
6201 	if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6202 				    sc))
6203 		goto again;
6204 
6205 	/*
6206 	 * Kswapd gives up on balancing particular nodes after too
6207 	 * many failures to reclaim anything from them and goes to
6208 	 * sleep. On reclaim progress, reset the failure counter. A
6209 	 * successful direct reclaim run will revive a dormant kswapd.
6210 	 */
6211 	if (reclaimable)
6212 		pgdat->kswapd_failures = 0;
6213 }
6214 
6215 /*
6216  * Returns true if compaction should go ahead for a costly-order request, or
6217  * the allocation would already succeed without compaction. Return false if we
6218  * should reclaim first.
6219  */
6220 static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
6221 {
6222 	unsigned long watermark;
6223 	enum compact_result suitable;
6224 
6225 	suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6226 	if (suitable == COMPACT_SUCCESS)
6227 		/* Allocation should succeed already. Don't reclaim. */
6228 		return true;
6229 	if (suitable == COMPACT_SKIPPED)
6230 		/* Compaction cannot yet proceed. Do reclaim. */
6231 		return false;
6232 
6233 	/*
6234 	 * Compaction is already possible, but it takes time to run and there
6235 	 * are potentially other callers using the pages just freed. So proceed
6236 	 * with reclaim to make a buffer of free pages available to give
6237 	 * compaction a reasonable chance of completing and allocating the page.
6238 	 * Note that we won't actually reclaim the whole buffer in one attempt
6239 	 * as the target watermark in should_continue_reclaim() is lower. But if
6240 	 * we are already above the high+gap watermark, don't reclaim at all.
6241 	 */
6242 	watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6243 
6244 	return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
6245 }
6246 
6247 static void consider_reclaim_throttle(pg_data_t *pgdat, struct scan_control *sc)
6248 {
6249 	/*
6250 	 * If reclaim is making progress greater than 12% efficiency then
6251 	 * wake all the NOPROGRESS throttled tasks.
6252 	 */
6253 	if (sc->nr_reclaimed > (sc->nr_scanned >> 3)) {
6254 		wait_queue_head_t *wqh;
6255 
6256 		wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_NOPROGRESS];
6257 		if (waitqueue_active(wqh))
6258 			wake_up(wqh);
6259 
6260 		return;
6261 	}
6262 
6263 	/*
6264 	 * Do not throttle kswapd or cgroup reclaim on NOPROGRESS as it will
6265 	 * throttle on VMSCAN_THROTTLE_WRITEBACK if there are too many pages
6266 	 * under writeback and marked for immediate reclaim at the tail of the
6267 	 * LRU.
6268 	 */
6269 	if (current_is_kswapd() || cgroup_reclaim(sc))
6270 		return;
6271 
6272 	/* Throttle if making no progress at high prioities. */
6273 	if (sc->priority == 1 && !sc->nr_reclaimed)
6274 		reclaim_throttle(pgdat, VMSCAN_THROTTLE_NOPROGRESS);
6275 }
6276 
6277 /*
6278  * This is the direct reclaim path, for page-allocating processes.  We only
6279  * try to reclaim pages from zones which will satisfy the caller's allocation
6280  * request.
6281  *
6282  * If a zone is deemed to be full of pinned pages then just give it a light
6283  * scan then give up on it.
6284  */
6285 static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
6286 {
6287 	struct zoneref *z;
6288 	struct zone *zone;
6289 	unsigned long nr_soft_reclaimed;
6290 	unsigned long nr_soft_scanned;
6291 	gfp_t orig_mask;
6292 	pg_data_t *last_pgdat = NULL;
6293 	pg_data_t *first_pgdat = NULL;
6294 
6295 	/*
6296 	 * If the number of buffer_heads in the machine exceeds the maximum
6297 	 * allowed level, force direct reclaim to scan the highmem zone as
6298 	 * highmem pages could be pinning lowmem pages storing buffer_heads
6299 	 */
6300 	orig_mask = sc->gfp_mask;
6301 	if (buffer_heads_over_limit) {
6302 		sc->gfp_mask |= __GFP_HIGHMEM;
6303 		sc->reclaim_idx = gfp_zone(sc->gfp_mask);
6304 	}
6305 
6306 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
6307 					sc->reclaim_idx, sc->nodemask) {
6308 		/*
6309 		 * Take care memory controller reclaiming has small influence
6310 		 * to global LRU.
6311 		 */
6312 		if (!cgroup_reclaim(sc)) {
6313 			if (!cpuset_zone_allowed(zone,
6314 						 GFP_KERNEL | __GFP_HARDWALL))
6315 				continue;
6316 
6317 			/*
6318 			 * If we already have plenty of memory free for
6319 			 * compaction in this zone, don't free any more.
6320 			 * Even though compaction is invoked for any
6321 			 * non-zero order, only frequent costly order
6322 			 * reclamation is disruptive enough to become a
6323 			 * noticeable problem, like transparent huge
6324 			 * page allocations.
6325 			 */
6326 			if (IS_ENABLED(CONFIG_COMPACTION) &&
6327 			    sc->order > PAGE_ALLOC_COSTLY_ORDER &&
6328 			    compaction_ready(zone, sc)) {
6329 				sc->compaction_ready = true;
6330 				continue;
6331 			}
6332 
6333 			/*
6334 			 * Shrink each node in the zonelist once. If the
6335 			 * zonelist is ordered by zone (not the default) then a
6336 			 * node may be shrunk multiple times but in that case
6337 			 * the user prefers lower zones being preserved.
6338 			 */
6339 			if (zone->zone_pgdat == last_pgdat)
6340 				continue;
6341 
6342 			/*
6343 			 * This steals pages from memory cgroups over softlimit
6344 			 * and returns the number of reclaimed pages and
6345 			 * scanned pages. This works for global memory pressure
6346 			 * and balancing, not for a memcg's limit.
6347 			 */
6348 			nr_soft_scanned = 0;
6349 			nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
6350 						sc->order, sc->gfp_mask,
6351 						&nr_soft_scanned);
6352 			sc->nr_reclaimed += nr_soft_reclaimed;
6353 			sc->nr_scanned += nr_soft_scanned;
6354 			/* need some check for avoid more shrink_zone() */
6355 		}
6356 
6357 		if (!first_pgdat)
6358 			first_pgdat = zone->zone_pgdat;
6359 
6360 		/* See comment about same check for global reclaim above */
6361 		if (zone->zone_pgdat == last_pgdat)
6362 			continue;
6363 		last_pgdat = zone->zone_pgdat;
6364 		shrink_node(zone->zone_pgdat, sc);
6365 	}
6366 
6367 	if (first_pgdat)
6368 		consider_reclaim_throttle(first_pgdat, sc);
6369 
6370 	/*
6371 	 * Restore to original mask to avoid the impact on the caller if we
6372 	 * promoted it to __GFP_HIGHMEM.
6373 	 */
6374 	sc->gfp_mask = orig_mask;
6375 }
6376 
6377 static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
6378 {
6379 	struct lruvec *target_lruvec;
6380 	unsigned long refaults;
6381 
6382 	if (lru_gen_enabled())
6383 		return;
6384 
6385 	target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
6386 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6387 	target_lruvec->refaults[WORKINGSET_ANON] = refaults;
6388 	refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6389 	target_lruvec->refaults[WORKINGSET_FILE] = refaults;
6390 }
6391 
6392 /*
6393  * This is the main entry point to direct page reclaim.
6394  *
6395  * If a full scan of the inactive list fails to free enough memory then we
6396  * are "out of memory" and something needs to be killed.
6397  *
6398  * If the caller is !__GFP_FS then the probability of a failure is reasonably
6399  * high - the zone may be full of dirty or under-writeback pages, which this
6400  * caller can't do much about.  We kick the writeback threads and take explicit
6401  * naps in the hope that some of these pages can be written.  But if the
6402  * allocating task holds filesystem locks which prevent writeout this might not
6403  * work, and the allocation attempt will fail.
6404  *
6405  * returns:	0, if no pages reclaimed
6406  * 		else, the number of pages reclaimed
6407  */
6408 static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
6409 					  struct scan_control *sc)
6410 {
6411 	int initial_priority = sc->priority;
6412 	pg_data_t *last_pgdat;
6413 	struct zoneref *z;
6414 	struct zone *zone;
6415 retry:
6416 	delayacct_freepages_start();
6417 
6418 	if (!cgroup_reclaim(sc))
6419 		__count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
6420 
6421 	do {
6422 		if (!sc->proactive)
6423 			vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6424 					sc->priority);
6425 		sc->nr_scanned = 0;
6426 		shrink_zones(zonelist, sc);
6427 
6428 		if (sc->nr_reclaimed >= sc->nr_to_reclaim)
6429 			break;
6430 
6431 		if (sc->compaction_ready)
6432 			break;
6433 
6434 		/*
6435 		 * If we're getting trouble reclaiming, start doing
6436 		 * writepage even in laptop mode.
6437 		 */
6438 		if (sc->priority < DEF_PRIORITY - 2)
6439 			sc->may_writepage = 1;
6440 	} while (--sc->priority >= 0);
6441 
6442 	last_pgdat = NULL;
6443 	for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6444 					sc->nodemask) {
6445 		if (zone->zone_pgdat == last_pgdat)
6446 			continue;
6447 		last_pgdat = zone->zone_pgdat;
6448 
6449 		snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
6450 
6451 		if (cgroup_reclaim(sc)) {
6452 			struct lruvec *lruvec;
6453 
6454 			lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6455 						   zone->zone_pgdat);
6456 			clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6457 		}
6458 	}
6459 
6460 	delayacct_freepages_end();
6461 
6462 	if (sc->nr_reclaimed)
6463 		return sc->nr_reclaimed;
6464 
6465 	/* Aborted reclaim to try compaction? don't OOM, then */
6466 	if (sc->compaction_ready)
6467 		return 1;
6468 
6469 	/*
6470 	 * We make inactive:active ratio decisions based on the node's
6471 	 * composition of memory, but a restrictive reclaim_idx or a
6472 	 * memory.low cgroup setting can exempt large amounts of
6473 	 * memory from reclaim. Neither of which are very common, so
6474 	 * instead of doing costly eligibility calculations of the
6475 	 * entire cgroup subtree up front, we assume the estimates are
6476 	 * good, and retry with forcible deactivation if that fails.
6477 	 */
6478 	if (sc->skipped_deactivate) {
6479 		sc->priority = initial_priority;
6480 		sc->force_deactivate = 1;
6481 		sc->skipped_deactivate = 0;
6482 		goto retry;
6483 	}
6484 
6485 	/* Untapped cgroup reserves?  Don't OOM, retry. */
6486 	if (sc->memcg_low_skipped) {
6487 		sc->priority = initial_priority;
6488 		sc->force_deactivate = 0;
6489 		sc->memcg_low_reclaim = 1;
6490 		sc->memcg_low_skipped = 0;
6491 		goto retry;
6492 	}
6493 
6494 	return 0;
6495 }
6496 
6497 static bool allow_direct_reclaim(pg_data_t *pgdat)
6498 {
6499 	struct zone *zone;
6500 	unsigned long pfmemalloc_reserve = 0;
6501 	unsigned long free_pages = 0;
6502 	int i;
6503 	bool wmark_ok;
6504 
6505 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6506 		return true;
6507 
6508 	for (i = 0; i <= ZONE_NORMAL; i++) {
6509 		zone = &pgdat->node_zones[i];
6510 		if (!managed_zone(zone))
6511 			continue;
6512 
6513 		if (!zone_reclaimable_pages(zone))
6514 			continue;
6515 
6516 		pfmemalloc_reserve += min_wmark_pages(zone);
6517 		free_pages += zone_page_state(zone, NR_FREE_PAGES);
6518 	}
6519 
6520 	/* If there are no reserves (unexpected config) then do not throttle */
6521 	if (!pfmemalloc_reserve)
6522 		return true;
6523 
6524 	wmark_ok = free_pages > pfmemalloc_reserve / 2;
6525 
6526 	/* kswapd must be awake if processes are being throttled */
6527 	if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
6528 		if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6529 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
6530 
6531 		wake_up_interruptible(&pgdat->kswapd_wait);
6532 	}
6533 
6534 	return wmark_ok;
6535 }
6536 
6537 /*
6538  * Throttle direct reclaimers if backing storage is backed by the network
6539  * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6540  * depleted. kswapd will continue to make progress and wake the processes
6541  * when the low watermark is reached.
6542  *
6543  * Returns true if a fatal signal was delivered during throttling. If this
6544  * happens, the page allocator should not consider triggering the OOM killer.
6545  */
6546 static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
6547 					nodemask_t *nodemask)
6548 {
6549 	struct zoneref *z;
6550 	struct zone *zone;
6551 	pg_data_t *pgdat = NULL;
6552 
6553 	/*
6554 	 * Kernel threads should not be throttled as they may be indirectly
6555 	 * responsible for cleaning pages necessary for reclaim to make forward
6556 	 * progress. kjournald for example may enter direct reclaim while
6557 	 * committing a transaction where throttling it could forcing other
6558 	 * processes to block on log_wait_commit().
6559 	 */
6560 	if (current->flags & PF_KTHREAD)
6561 		goto out;
6562 
6563 	/*
6564 	 * If a fatal signal is pending, this process should not throttle.
6565 	 * It should return quickly so it can exit and free its memory
6566 	 */
6567 	if (fatal_signal_pending(current))
6568 		goto out;
6569 
6570 	/*
6571 	 * Check if the pfmemalloc reserves are ok by finding the first node
6572 	 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6573 	 * GFP_KERNEL will be required for allocating network buffers when
6574 	 * swapping over the network so ZONE_HIGHMEM is unusable.
6575 	 *
6576 	 * Throttling is based on the first usable node and throttled processes
6577 	 * wait on a queue until kswapd makes progress and wakes them. There
6578 	 * is an affinity then between processes waking up and where reclaim
6579 	 * progress has been made assuming the process wakes on the same node.
6580 	 * More importantly, processes running on remote nodes will not compete
6581 	 * for remote pfmemalloc reserves and processes on different nodes
6582 	 * should make reasonable progress.
6583 	 */
6584 	for_each_zone_zonelist_nodemask(zone, z, zonelist,
6585 					gfp_zone(gfp_mask), nodemask) {
6586 		if (zone_idx(zone) > ZONE_NORMAL)
6587 			continue;
6588 
6589 		/* Throttle based on the first usable node */
6590 		pgdat = zone->zone_pgdat;
6591 		if (allow_direct_reclaim(pgdat))
6592 			goto out;
6593 		break;
6594 	}
6595 
6596 	/* If no zone was usable by the allocation flags then do not throttle */
6597 	if (!pgdat)
6598 		goto out;
6599 
6600 	/* Account for the throttling */
6601 	count_vm_event(PGSCAN_DIRECT_THROTTLE);
6602 
6603 	/*
6604 	 * If the caller cannot enter the filesystem, it's possible that it
6605 	 * is due to the caller holding an FS lock or performing a journal
6606 	 * transaction in the case of a filesystem like ext[3|4]. In this case,
6607 	 * it is not safe to block on pfmemalloc_wait as kswapd could be
6608 	 * blocked waiting on the same lock. Instead, throttle for up to a
6609 	 * second before continuing.
6610 	 */
6611 	if (!(gfp_mask & __GFP_FS))
6612 		wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
6613 			allow_direct_reclaim(pgdat), HZ);
6614 	else
6615 		/* Throttle until kswapd wakes the process */
6616 		wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6617 			allow_direct_reclaim(pgdat));
6618 
6619 	if (fatal_signal_pending(current))
6620 		return true;
6621 
6622 out:
6623 	return false;
6624 }
6625 
6626 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
6627 				gfp_t gfp_mask, nodemask_t *nodemask)
6628 {
6629 	unsigned long nr_reclaimed;
6630 	struct scan_control sc = {
6631 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
6632 		.gfp_mask = current_gfp_context(gfp_mask),
6633 		.reclaim_idx = gfp_zone(gfp_mask),
6634 		.order = order,
6635 		.nodemask = nodemask,
6636 		.priority = DEF_PRIORITY,
6637 		.may_writepage = !laptop_mode,
6638 		.may_unmap = 1,
6639 		.may_swap = 1,
6640 	};
6641 
6642 	/*
6643 	 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6644 	 * Confirm they are large enough for max values.
6645 	 */
6646 	BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6647 	BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6648 	BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6649 
6650 	/*
6651 	 * Do not enter reclaim if fatal signal was delivered while throttled.
6652 	 * 1 is returned so that the page allocator does not OOM kill at this
6653 	 * point.
6654 	 */
6655 	if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
6656 		return 1;
6657 
6658 	set_task_reclaim_state(current, &sc.reclaim_state);
6659 	trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
6660 
6661 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6662 
6663 	trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
6664 	set_task_reclaim_state(current, NULL);
6665 
6666 	return nr_reclaimed;
6667 }
6668 
6669 #ifdef CONFIG_MEMCG
6670 
6671 /* Only used by soft limit reclaim. Do not reuse for anything else. */
6672 unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
6673 						gfp_t gfp_mask, bool noswap,
6674 						pg_data_t *pgdat,
6675 						unsigned long *nr_scanned)
6676 {
6677 	struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
6678 	struct scan_control sc = {
6679 		.nr_to_reclaim = SWAP_CLUSTER_MAX,
6680 		.target_mem_cgroup = memcg,
6681 		.may_writepage = !laptop_mode,
6682 		.may_unmap = 1,
6683 		.reclaim_idx = MAX_NR_ZONES - 1,
6684 		.may_swap = !noswap,
6685 	};
6686 
6687 	WARN_ON_ONCE(!current->reclaim_state);
6688 
6689 	sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6690 			(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
6691 
6692 	trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
6693 						      sc.gfp_mask);
6694 
6695 	/*
6696 	 * NOTE: Although we can get the priority field, using it
6697 	 * here is not a good idea, since it limits the pages we can scan.
6698 	 * if we don't reclaim here, the shrink_node from balance_pgdat
6699 	 * will pick up pages from other mem cgroup's as well. We hack
6700 	 * the priority and make it zero.
6701 	 */
6702 	shrink_lruvec(lruvec, &sc);
6703 
6704 	trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6705 
6706 	*nr_scanned = sc.nr_scanned;
6707 
6708 	return sc.nr_reclaimed;
6709 }
6710 
6711 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
6712 					   unsigned long nr_pages,
6713 					   gfp_t gfp_mask,
6714 					   unsigned int reclaim_options,
6715 					   nodemask_t *nodemask)
6716 {
6717 	unsigned long nr_reclaimed;
6718 	unsigned int noreclaim_flag;
6719 	struct scan_control sc = {
6720 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
6721 		.gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
6722 				(GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
6723 		.reclaim_idx = MAX_NR_ZONES - 1,
6724 		.target_mem_cgroup = memcg,
6725 		.priority = DEF_PRIORITY,
6726 		.may_writepage = !laptop_mode,
6727 		.may_unmap = 1,
6728 		.may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6729 		.proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
6730 		.nodemask = nodemask,
6731 	};
6732 	/*
6733 	 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6734 	 * equal pressure on all the nodes. This is based on the assumption that
6735 	 * the reclaim does not bail out early.
6736 	 */
6737 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
6738 
6739 	set_task_reclaim_state(current, &sc.reclaim_state);
6740 	trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
6741 	noreclaim_flag = memalloc_noreclaim_save();
6742 
6743 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
6744 
6745 	memalloc_noreclaim_restore(noreclaim_flag);
6746 	trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
6747 	set_task_reclaim_state(current, NULL);
6748 
6749 	return nr_reclaimed;
6750 }
6751 #endif
6752 
6753 static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
6754 {
6755 	struct mem_cgroup *memcg;
6756 	struct lruvec *lruvec;
6757 
6758 	if (lru_gen_enabled()) {
6759 		lru_gen_age_node(pgdat, sc);
6760 		return;
6761 	}
6762 
6763 	if (!can_age_anon_pages(pgdat, sc))
6764 		return;
6765 
6766 	lruvec = mem_cgroup_lruvec(NULL, pgdat);
6767 	if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6768 		return;
6769 
6770 	memcg = mem_cgroup_iter(NULL, NULL, NULL);
6771 	do {
6772 		lruvec = mem_cgroup_lruvec(memcg, pgdat);
6773 		shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6774 				   sc, LRU_ACTIVE_ANON);
6775 		memcg = mem_cgroup_iter(NULL, memcg, NULL);
6776 	} while (memcg);
6777 }
6778 
6779 static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
6780 {
6781 	int i;
6782 	struct zone *zone;
6783 
6784 	/*
6785 	 * Check for watermark boosts top-down as the higher zones
6786 	 * are more likely to be boosted. Both watermarks and boosts
6787 	 * should not be checked at the same time as reclaim would
6788 	 * start prematurely when there is no boosting and a lower
6789 	 * zone is balanced.
6790 	 */
6791 	for (i = highest_zoneidx; i >= 0; i--) {
6792 		zone = pgdat->node_zones + i;
6793 		if (!managed_zone(zone))
6794 			continue;
6795 
6796 		if (zone->watermark_boost)
6797 			return true;
6798 	}
6799 
6800 	return false;
6801 }
6802 
6803 /*
6804  * Returns true if there is an eligible zone balanced for the request order
6805  * and highest_zoneidx
6806  */
6807 static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
6808 {
6809 	int i;
6810 	unsigned long mark = -1;
6811 	struct zone *zone;
6812 
6813 	/*
6814 	 * Check watermarks bottom-up as lower zones are more likely to
6815 	 * meet watermarks.
6816 	 */
6817 	for (i = 0; i <= highest_zoneidx; i++) {
6818 		zone = pgdat->node_zones + i;
6819 
6820 		if (!managed_zone(zone))
6821 			continue;
6822 
6823 		if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING)
6824 			mark = wmark_pages(zone, WMARK_PROMO);
6825 		else
6826 			mark = high_wmark_pages(zone);
6827 		if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
6828 			return true;
6829 	}
6830 
6831 	/*
6832 	 * If a node has no managed zone within highest_zoneidx, it does not
6833 	 * need balancing by definition. This can happen if a zone-restricted
6834 	 * allocation tries to wake a remote kswapd.
6835 	 */
6836 	if (mark == -1)
6837 		return true;
6838 
6839 	return false;
6840 }
6841 
6842 /* Clear pgdat state for congested, dirty or under writeback. */
6843 static void clear_pgdat_congested(pg_data_t *pgdat)
6844 {
6845 	struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6846 
6847 	clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6848 	clear_bit(PGDAT_DIRTY, &pgdat->flags);
6849 	clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6850 }
6851 
6852 /*
6853  * Prepare kswapd for sleeping. This verifies that there are no processes
6854  * waiting in throttle_direct_reclaim() and that watermarks have been met.
6855  *
6856  * Returns true if kswapd is ready to sleep
6857  */
6858 static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6859 				int highest_zoneidx)
6860 {
6861 	/*
6862 	 * The throttled processes are normally woken up in balance_pgdat() as
6863 	 * soon as allow_direct_reclaim() is true. But there is a potential
6864 	 * race between when kswapd checks the watermarks and a process gets
6865 	 * throttled. There is also a potential race if processes get
6866 	 * throttled, kswapd wakes, a large process exits thereby balancing the
6867 	 * zones, which causes kswapd to exit balance_pgdat() before reaching
6868 	 * the wake up checks. If kswapd is going to sleep, no process should
6869 	 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6870 	 * the wake up is premature, processes will wake kswapd and get
6871 	 * throttled again. The difference from wake ups in balance_pgdat() is
6872 	 * that here we are under prepare_to_wait().
6873 	 */
6874 	if (waitqueue_active(&pgdat->pfmemalloc_wait))
6875 		wake_up_all(&pgdat->pfmemalloc_wait);
6876 
6877 	/* Hopeless node, leave it to direct reclaim */
6878 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6879 		return true;
6880 
6881 	if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
6882 		clear_pgdat_congested(pgdat);
6883 		return true;
6884 	}
6885 
6886 	return false;
6887 }
6888 
6889 /*
6890  * kswapd shrinks a node of pages that are at or below the highest usable
6891  * zone that is currently unbalanced.
6892  *
6893  * Returns true if kswapd scanned at least the requested number of pages to
6894  * reclaim or if the lack of progress was due to pages under writeback.
6895  * This is used to determine if the scanning priority needs to be raised.
6896  */
6897 static bool kswapd_shrink_node(pg_data_t *pgdat,
6898 			       struct scan_control *sc)
6899 {
6900 	struct zone *zone;
6901 	int z;
6902 
6903 	/* Reclaim a number of pages proportional to the number of zones */
6904 	sc->nr_to_reclaim = 0;
6905 	for (z = 0; z <= sc->reclaim_idx; z++) {
6906 		zone = pgdat->node_zones + z;
6907 		if (!managed_zone(zone))
6908 			continue;
6909 
6910 		sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
6911 	}
6912 
6913 	/*
6914 	 * Historically care was taken to put equal pressure on all zones but
6915 	 * now pressure is applied based on node LRU order.
6916 	 */
6917 	shrink_node(pgdat, sc);
6918 
6919 	/*
6920 	 * Fragmentation may mean that the system cannot be rebalanced for
6921 	 * high-order allocations. If twice the allocation size has been
6922 	 * reclaimed then recheck watermarks only at order-0 to prevent
6923 	 * excessive reclaim. Assume that a process requested a high-order
6924 	 * can direct reclaim/compact.
6925 	 */
6926 	if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
6927 		sc->order = 0;
6928 
6929 	return sc->nr_scanned >= sc->nr_to_reclaim;
6930 }
6931 
6932 /* Page allocator PCP high watermark is lowered if reclaim is active. */
6933 static inline void
6934 update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6935 {
6936 	int i;
6937 	struct zone *zone;
6938 
6939 	for (i = 0; i <= highest_zoneidx; i++) {
6940 		zone = pgdat->node_zones + i;
6941 
6942 		if (!managed_zone(zone))
6943 			continue;
6944 
6945 		if (active)
6946 			set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6947 		else
6948 			clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6949 	}
6950 }
6951 
6952 static inline void
6953 set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6954 {
6955 	update_reclaim_active(pgdat, highest_zoneidx, true);
6956 }
6957 
6958 static inline void
6959 clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6960 {
6961 	update_reclaim_active(pgdat, highest_zoneidx, false);
6962 }
6963 
6964 /*
6965  * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6966  * that are eligible for use by the caller until at least one zone is
6967  * balanced.
6968  *
6969  * Returns the order kswapd finished reclaiming at.
6970  *
6971  * kswapd scans the zones in the highmem->normal->dma direction.  It skips
6972  * zones which have free_pages > high_wmark_pages(zone), but once a zone is
6973  * found to have free_pages <= high_wmark_pages(zone), any page in that zone
6974  * or lower is eligible for reclaim until at least one usable zone is
6975  * balanced.
6976  */
6977 static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
6978 {
6979 	int i;
6980 	unsigned long nr_soft_reclaimed;
6981 	unsigned long nr_soft_scanned;
6982 	unsigned long pflags;
6983 	unsigned long nr_boost_reclaim;
6984 	unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6985 	bool boosted;
6986 	struct zone *zone;
6987 	struct scan_control sc = {
6988 		.gfp_mask = GFP_KERNEL,
6989 		.order = order,
6990 		.may_unmap = 1,
6991 	};
6992 
6993 	set_task_reclaim_state(current, &sc.reclaim_state);
6994 	psi_memstall_enter(&pflags);
6995 	__fs_reclaim_acquire(_THIS_IP_);
6996 
6997 	count_vm_event(PAGEOUTRUN);
6998 
6999 	/*
7000 	 * Account for the reclaim boost. Note that the zone boost is left in
7001 	 * place so that parallel allocations that are near the watermark will
7002 	 * stall or direct reclaim until kswapd is finished.
7003 	 */
7004 	nr_boost_reclaim = 0;
7005 	for (i = 0; i <= highest_zoneidx; i++) {
7006 		zone = pgdat->node_zones + i;
7007 		if (!managed_zone(zone))
7008 			continue;
7009 
7010 		nr_boost_reclaim += zone->watermark_boost;
7011 		zone_boosts[i] = zone->watermark_boost;
7012 	}
7013 	boosted = nr_boost_reclaim;
7014 
7015 restart:
7016 	set_reclaim_active(pgdat, highest_zoneidx);
7017 	sc.priority = DEF_PRIORITY;
7018 	do {
7019 		unsigned long nr_reclaimed = sc.nr_reclaimed;
7020 		bool raise_priority = true;
7021 		bool balanced;
7022 		bool ret;
7023 
7024 		sc.reclaim_idx = highest_zoneidx;
7025 
7026 		/*
7027 		 * If the number of buffer_heads exceeds the maximum allowed
7028 		 * then consider reclaiming from all zones. This has a dual
7029 		 * purpose -- on 64-bit systems it is expected that
7030 		 * buffer_heads are stripped during active rotation. On 32-bit
7031 		 * systems, highmem pages can pin lowmem memory and shrinking
7032 		 * buffers can relieve lowmem pressure. Reclaim may still not
7033 		 * go ahead if all eligible zones for the original allocation
7034 		 * request are balanced to avoid excessive reclaim from kswapd.
7035 		 */
7036 		if (buffer_heads_over_limit) {
7037 			for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7038 				zone = pgdat->node_zones + i;
7039 				if (!managed_zone(zone))
7040 					continue;
7041 
7042 				sc.reclaim_idx = i;
7043 				break;
7044 			}
7045 		}
7046 
7047 		/*
7048 		 * If the pgdat is imbalanced then ignore boosting and preserve
7049 		 * the watermarks for a later time and restart. Note that the
7050 		 * zone watermarks will be still reset at the end of balancing
7051 		 * on the grounds that the normal reclaim should be enough to
7052 		 * re-evaluate if boosting is required when kswapd next wakes.
7053 		 */
7054 		balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
7055 		if (!balanced && nr_boost_reclaim) {
7056 			nr_boost_reclaim = 0;
7057 			goto restart;
7058 		}
7059 
7060 		/*
7061 		 * If boosting is not active then only reclaim if there are no
7062 		 * eligible zones. Note that sc.reclaim_idx is not used as
7063 		 * buffer_heads_over_limit may have adjusted it.
7064 		 */
7065 		if (!nr_boost_reclaim && balanced)
7066 			goto out;
7067 
7068 		/* Limit the priority of boosting to avoid reclaim writeback */
7069 		if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7070 			raise_priority = false;
7071 
7072 		/*
7073 		 * Do not writeback or swap pages for boosted reclaim. The
7074 		 * intent is to relieve pressure not issue sub-optimal IO
7075 		 * from reclaim context. If no pages are reclaimed, the
7076 		 * reclaim will be aborted.
7077 		 */
7078 		sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7079 		sc.may_swap = !nr_boost_reclaim;
7080 
7081 		/*
7082 		 * Do some background aging, to give pages a chance to be
7083 		 * referenced before reclaiming. All pages are rotated
7084 		 * regardless of classzone as this is about consistent aging.
7085 		 */
7086 		kswapd_age_node(pgdat, &sc);
7087 
7088 		/*
7089 		 * If we're getting trouble reclaiming, start doing writepage
7090 		 * even in laptop mode.
7091 		 */
7092 		if (sc.priority < DEF_PRIORITY - 2)
7093 			sc.may_writepage = 1;
7094 
7095 		/* Call soft limit reclaim before calling shrink_node. */
7096 		sc.nr_scanned = 0;
7097 		nr_soft_scanned = 0;
7098 		nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
7099 						sc.gfp_mask, &nr_soft_scanned);
7100 		sc.nr_reclaimed += nr_soft_reclaimed;
7101 
7102 		/*
7103 		 * There should be no need to raise the scanning priority if
7104 		 * enough pages are already being scanned that that high
7105 		 * watermark would be met at 100% efficiency.
7106 		 */
7107 		if (kswapd_shrink_node(pgdat, &sc))
7108 			raise_priority = false;
7109 
7110 		/*
7111 		 * If the low watermark is met there is no need for processes
7112 		 * to be throttled on pfmemalloc_wait as they should not be
7113 		 * able to safely make forward progress. Wake them
7114 		 */
7115 		if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
7116 				allow_direct_reclaim(pgdat))
7117 			wake_up_all(&pgdat->pfmemalloc_wait);
7118 
7119 		/* Check if kswapd should be suspending */
7120 		__fs_reclaim_release(_THIS_IP_);
7121 		ret = try_to_freeze();
7122 		__fs_reclaim_acquire(_THIS_IP_);
7123 		if (ret || kthread_should_stop())
7124 			break;
7125 
7126 		/*
7127 		 * Raise priority if scanning rate is too low or there was no
7128 		 * progress in reclaiming pages
7129 		 */
7130 		nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
7131 		nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7132 
7133 		/*
7134 		 * If reclaim made no progress for a boost, stop reclaim as
7135 		 * IO cannot be queued and it could be an infinite loop in
7136 		 * extreme circumstances.
7137 		 */
7138 		if (nr_boost_reclaim && !nr_reclaimed)
7139 			break;
7140 
7141 		if (raise_priority || !nr_reclaimed)
7142 			sc.priority--;
7143 	} while (sc.priority >= 1);
7144 
7145 	if (!sc.nr_reclaimed)
7146 		pgdat->kswapd_failures++;
7147 
7148 out:
7149 	clear_reclaim_active(pgdat, highest_zoneidx);
7150 
7151 	/* If reclaim was boosted, account for the reclaim done in this pass */
7152 	if (boosted) {
7153 		unsigned long flags;
7154 
7155 		for (i = 0; i <= highest_zoneidx; i++) {
7156 			if (!zone_boosts[i])
7157 				continue;
7158 
7159 			/* Increments are under the zone lock */
7160 			zone = pgdat->node_zones + i;
7161 			spin_lock_irqsave(&zone->lock, flags);
7162 			zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7163 			spin_unlock_irqrestore(&zone->lock, flags);
7164 		}
7165 
7166 		/*
7167 		 * As there is now likely space, wakeup kcompact to defragment
7168 		 * pageblocks.
7169 		 */
7170 		wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
7171 	}
7172 
7173 	snapshot_refaults(NULL, pgdat);
7174 	__fs_reclaim_release(_THIS_IP_);
7175 	psi_memstall_leave(&pflags);
7176 	set_task_reclaim_state(current, NULL);
7177 
7178 	/*
7179 	 * Return the order kswapd stopped reclaiming at as
7180 	 * prepare_kswapd_sleep() takes it into account. If another caller
7181 	 * entered the allocator slow path while kswapd was awake, order will
7182 	 * remain at the higher level.
7183 	 */
7184 	return sc.order;
7185 }
7186 
7187 /*
7188  * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7189  * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7190  * not a valid index then either kswapd runs for first time or kswapd couldn't
7191  * sleep after previous reclaim attempt (node is still unbalanced). In that
7192  * case return the zone index of the previous kswapd reclaim cycle.
7193  */
7194 static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7195 					   enum zone_type prev_highest_zoneidx)
7196 {
7197 	enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7198 
7199 	return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
7200 }
7201 
7202 static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
7203 				unsigned int highest_zoneidx)
7204 {
7205 	long remaining = 0;
7206 	DEFINE_WAIT(wait);
7207 
7208 	if (freezing(current) || kthread_should_stop())
7209 		return;
7210 
7211 	prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7212 
7213 	/*
7214 	 * Try to sleep for a short interval. Note that kcompactd will only be
7215 	 * woken if it is possible to sleep for a short interval. This is
7216 	 * deliberate on the assumption that if reclaim cannot keep an
7217 	 * eligible zone balanced that it's also unlikely that compaction will
7218 	 * succeed.
7219 	 */
7220 	if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7221 		/*
7222 		 * Compaction records what page blocks it recently failed to
7223 		 * isolate pages from and skips them in the future scanning.
7224 		 * When kswapd is going to sleep, it is reasonable to assume
7225 		 * that pages and compaction may succeed so reset the cache.
7226 		 */
7227 		reset_isolation_suitable(pgdat);
7228 
7229 		/*
7230 		 * We have freed the memory, now we should compact it to make
7231 		 * allocation of the requested order possible.
7232 		 */
7233 		wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
7234 
7235 		remaining = schedule_timeout(HZ/10);
7236 
7237 		/*
7238 		 * If woken prematurely then reset kswapd_highest_zoneidx and
7239 		 * order. The values will either be from a wakeup request or
7240 		 * the previous request that slept prematurely.
7241 		 */
7242 		if (remaining) {
7243 			WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7244 					kswapd_highest_zoneidx(pgdat,
7245 							highest_zoneidx));
7246 
7247 			if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7248 				WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
7249 		}
7250 
7251 		finish_wait(&pgdat->kswapd_wait, &wait);
7252 		prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7253 	}
7254 
7255 	/*
7256 	 * After a short sleep, check if it was a premature sleep. If not, then
7257 	 * go fully to sleep until explicitly woken up.
7258 	 */
7259 	if (!remaining &&
7260 	    prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
7261 		trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7262 
7263 		/*
7264 		 * vmstat counters are not perfectly accurate and the estimated
7265 		 * value for counters such as NR_FREE_PAGES can deviate from the
7266 		 * true value by nr_online_cpus * threshold. To avoid the zone
7267 		 * watermarks being breached while under pressure, we reduce the
7268 		 * per-cpu vmstat threshold while kswapd is awake and restore
7269 		 * them before going back to sleep.
7270 		 */
7271 		set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
7272 
7273 		if (!kthread_should_stop())
7274 			schedule();
7275 
7276 		set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7277 	} else {
7278 		if (remaining)
7279 			count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7280 		else
7281 			count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7282 	}
7283 	finish_wait(&pgdat->kswapd_wait, &wait);
7284 }
7285 
7286 /*
7287  * The background pageout daemon, started as a kernel thread
7288  * from the init process.
7289  *
7290  * This basically trickles out pages so that we have _some_
7291  * free memory available even if there is no other activity
7292  * that frees anything up. This is needed for things like routing
7293  * etc, where we otherwise might have all activity going on in
7294  * asynchronous contexts that cannot page things out.
7295  *
7296  * If there are applications that are active memory-allocators
7297  * (most normal use), this basically shouldn't matter.
7298  */
7299 static int kswapd(void *p)
7300 {
7301 	unsigned int alloc_order, reclaim_order;
7302 	unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
7303 	pg_data_t *pgdat = (pg_data_t *)p;
7304 	struct task_struct *tsk = current;
7305 	const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
7306 
7307 	if (!cpumask_empty(cpumask))
7308 		set_cpus_allowed_ptr(tsk, cpumask);
7309 
7310 	/*
7311 	 * Tell the memory management that we're a "memory allocator",
7312 	 * and that if we need more memory we should get access to it
7313 	 * regardless (see "__alloc_pages()"). "kswapd" should
7314 	 * never get caught in the normal page freeing logic.
7315 	 *
7316 	 * (Kswapd normally doesn't need memory anyway, but sometimes
7317 	 * you need a small amount of memory in order to be able to
7318 	 * page out something else, and this flag essentially protects
7319 	 * us from recursively trying to free more memory as we're
7320 	 * trying to free the first piece of memory in the first place).
7321 	 */
7322 	tsk->flags |= PF_MEMALLOC | PF_KSWAPD;
7323 	set_freezable();
7324 
7325 	WRITE_ONCE(pgdat->kswapd_order, 0);
7326 	WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7327 	atomic_set(&pgdat->nr_writeback_throttled, 0);
7328 	for ( ; ; ) {
7329 		bool ret;
7330 
7331 		alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
7332 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7333 							highest_zoneidx);
7334 
7335 kswapd_try_sleep:
7336 		kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
7337 					highest_zoneidx);
7338 
7339 		/* Read the new order and highest_zoneidx */
7340 		alloc_order = READ_ONCE(pgdat->kswapd_order);
7341 		highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7342 							highest_zoneidx);
7343 		WRITE_ONCE(pgdat->kswapd_order, 0);
7344 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
7345 
7346 		ret = try_to_freeze();
7347 		if (kthread_should_stop())
7348 			break;
7349 
7350 		/*
7351 		 * We can speed up thawing tasks if we don't call balance_pgdat
7352 		 * after returning from the refrigerator
7353 		 */
7354 		if (ret)
7355 			continue;
7356 
7357 		/*
7358 		 * Reclaim begins at the requested order but if a high-order
7359 		 * reclaim fails then kswapd falls back to reclaiming for
7360 		 * order-0. If that happens, kswapd will consider sleeping
7361 		 * for the order it finished reclaiming at (reclaim_order)
7362 		 * but kcompactd is woken to compact for the original
7363 		 * request (alloc_order).
7364 		 */
7365 		trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
7366 						alloc_order);
7367 		reclaim_order = balance_pgdat(pgdat, alloc_order,
7368 						highest_zoneidx);
7369 		if (reclaim_order < alloc_order)
7370 			goto kswapd_try_sleep;
7371 	}
7372 
7373 	tsk->flags &= ~(PF_MEMALLOC | PF_KSWAPD);
7374 
7375 	return 0;
7376 }
7377 
7378 /*
7379  * A zone is low on free memory or too fragmented for high-order memory.  If
7380  * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7381  * pgdat.  It will wake up kcompactd after reclaiming memory.  If kswapd reclaim
7382  * has failed or is not needed, still wake up kcompactd if only compaction is
7383  * needed.
7384  */
7385 void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
7386 		   enum zone_type highest_zoneidx)
7387 {
7388 	pg_data_t *pgdat;
7389 	enum zone_type curr_idx;
7390 
7391 	if (!managed_zone(zone))
7392 		return;
7393 
7394 	if (!cpuset_zone_allowed(zone, gfp_flags))
7395 		return;
7396 
7397 	pgdat = zone->zone_pgdat;
7398 	curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
7399 
7400 	if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7401 		WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
7402 
7403 	if (READ_ONCE(pgdat->kswapd_order) < order)
7404 		WRITE_ONCE(pgdat->kswapd_order, order);
7405 
7406 	if (!waitqueue_active(&pgdat->kswapd_wait))
7407 		return;
7408 
7409 	/* Hopeless node, leave it to direct reclaim if possible */
7410 	if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
7411 	    (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7412 	     !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
7413 		/*
7414 		 * There may be plenty of free memory available, but it's too
7415 		 * fragmented for high-order allocations.  Wake up kcompactd
7416 		 * and rely on compaction_suitable() to determine if it's
7417 		 * needed.  If it fails, it will defer subsequent attempts to
7418 		 * ratelimit its work.
7419 		 */
7420 		if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
7421 			wakeup_kcompactd(pgdat, order, highest_zoneidx);
7422 		return;
7423 	}
7424 
7425 	trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
7426 				      gfp_flags);
7427 	wake_up_interruptible(&pgdat->kswapd_wait);
7428 }
7429 
7430 #ifdef CONFIG_HIBERNATION
7431 /*
7432  * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
7433  * freed pages.
7434  *
7435  * Rather than trying to age LRUs the aim is to preserve the overall
7436  * LRU order by reclaiming preferentially
7437  * inactive > active > active referenced > active mapped
7438  */
7439 unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
7440 {
7441 	struct scan_control sc = {
7442 		.nr_to_reclaim = nr_to_reclaim,
7443 		.gfp_mask = GFP_HIGHUSER_MOVABLE,
7444 		.reclaim_idx = MAX_NR_ZONES - 1,
7445 		.priority = DEF_PRIORITY,
7446 		.may_writepage = 1,
7447 		.may_unmap = 1,
7448 		.may_swap = 1,
7449 		.hibernation_mode = 1,
7450 	};
7451 	struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
7452 	unsigned long nr_reclaimed;
7453 	unsigned int noreclaim_flag;
7454 
7455 	fs_reclaim_acquire(sc.gfp_mask);
7456 	noreclaim_flag = memalloc_noreclaim_save();
7457 	set_task_reclaim_state(current, &sc.reclaim_state);
7458 
7459 	nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
7460 
7461 	set_task_reclaim_state(current, NULL);
7462 	memalloc_noreclaim_restore(noreclaim_flag);
7463 	fs_reclaim_release(sc.gfp_mask);
7464 
7465 	return nr_reclaimed;
7466 }
7467 #endif /* CONFIG_HIBERNATION */
7468 
7469 /*
7470  * This kswapd start function will be called by init and node-hot-add.
7471  */
7472 void kswapd_run(int nid)
7473 {
7474 	pg_data_t *pgdat = NODE_DATA(nid);
7475 
7476 	pgdat_kswapd_lock(pgdat);
7477 	if (!pgdat->kswapd) {
7478 		pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7479 		if (IS_ERR(pgdat->kswapd)) {
7480 			/* failure at boot is fatal */
7481 			BUG_ON(system_state < SYSTEM_RUNNING);
7482 			pr_err("Failed to start kswapd on node %d\n", nid);
7483 			pgdat->kswapd = NULL;
7484 		}
7485 	}
7486 	pgdat_kswapd_unlock(pgdat);
7487 }
7488 
7489 /*
7490  * Called by memory hotplug when all memory in a node is offlined.  Caller must
7491  * be holding mem_hotplug_begin/done().
7492  */
7493 void kswapd_stop(int nid)
7494 {
7495 	pg_data_t *pgdat = NODE_DATA(nid);
7496 	struct task_struct *kswapd;
7497 
7498 	pgdat_kswapd_lock(pgdat);
7499 	kswapd = pgdat->kswapd;
7500 	if (kswapd) {
7501 		kthread_stop(kswapd);
7502 		pgdat->kswapd = NULL;
7503 	}
7504 	pgdat_kswapd_unlock(pgdat);
7505 }
7506 
7507 static int __init kswapd_init(void)
7508 {
7509 	int nid;
7510 
7511 	swap_setup();
7512 	for_each_node_state(nid, N_MEMORY)
7513  		kswapd_run(nid);
7514 	return 0;
7515 }
7516 
7517 module_init(kswapd_init)
7518 
7519 #ifdef CONFIG_NUMA
7520 /*
7521  * Node reclaim mode
7522  *
7523  * If non-zero call node_reclaim when the number of free pages falls below
7524  * the watermarks.
7525  */
7526 int node_reclaim_mode __read_mostly;
7527 
7528 /*
7529  * Priority for NODE_RECLAIM. This determines the fraction of pages
7530  * of a node considered for each zone_reclaim. 4 scans 1/16th of
7531  * a zone.
7532  */
7533 #define NODE_RECLAIM_PRIORITY 4
7534 
7535 /*
7536  * Percentage of pages in a zone that must be unmapped for node_reclaim to
7537  * occur.
7538  */
7539 int sysctl_min_unmapped_ratio = 1;
7540 
7541 /*
7542  * If the number of slab pages in a zone grows beyond this percentage then
7543  * slab reclaim needs to occur.
7544  */
7545 int sysctl_min_slab_ratio = 5;
7546 
7547 static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
7548 {
7549 	unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7550 	unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7551 		node_page_state(pgdat, NR_ACTIVE_FILE);
7552 
7553 	/*
7554 	 * It's possible for there to be more file mapped pages than
7555 	 * accounted for by the pages on the file LRU lists because
7556 	 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7557 	 */
7558 	return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7559 }
7560 
7561 /* Work out how many page cache pages we can reclaim in this reclaim_mode */
7562 static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
7563 {
7564 	unsigned long nr_pagecache_reclaimable;
7565 	unsigned long delta = 0;
7566 
7567 	/*
7568 	 * If RECLAIM_UNMAP is set, then all file pages are considered
7569 	 * potentially reclaimable. Otherwise, we have to worry about
7570 	 * pages like swapcache and node_unmapped_file_pages() provides
7571 	 * a better estimate
7572 	 */
7573 	if (node_reclaim_mode & RECLAIM_UNMAP)
7574 		nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
7575 	else
7576 		nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
7577 
7578 	/* If we can't clean pages, remove dirty pages from consideration */
7579 	if (!(node_reclaim_mode & RECLAIM_WRITE))
7580 		delta += node_page_state(pgdat, NR_FILE_DIRTY);
7581 
7582 	/* Watch for any possible underflows due to delta */
7583 	if (unlikely(delta > nr_pagecache_reclaimable))
7584 		delta = nr_pagecache_reclaimable;
7585 
7586 	return nr_pagecache_reclaimable - delta;
7587 }
7588 
7589 /*
7590  * Try to free up some pages from this node through reclaim.
7591  */
7592 static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7593 {
7594 	/* Minimum pages needed in order to stay on node */
7595 	const unsigned long nr_pages = 1 << order;
7596 	struct task_struct *p = current;
7597 	unsigned int noreclaim_flag;
7598 	struct scan_control sc = {
7599 		.nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
7600 		.gfp_mask = current_gfp_context(gfp_mask),
7601 		.order = order,
7602 		.priority = NODE_RECLAIM_PRIORITY,
7603 		.may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7604 		.may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
7605 		.may_swap = 1,
7606 		.reclaim_idx = gfp_zone(gfp_mask),
7607 	};
7608 	unsigned long pflags;
7609 
7610 	trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7611 					   sc.gfp_mask);
7612 
7613 	cond_resched();
7614 	psi_memstall_enter(&pflags);
7615 	fs_reclaim_acquire(sc.gfp_mask);
7616 	/*
7617 	 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
7618 	 */
7619 	noreclaim_flag = memalloc_noreclaim_save();
7620 	set_task_reclaim_state(p, &sc.reclaim_state);
7621 
7622 	if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages ||
7623 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) > pgdat->min_slab_pages) {
7624 		/*
7625 		 * Free memory by calling shrink node with increasing
7626 		 * priorities until we have enough memory freed.
7627 		 */
7628 		do {
7629 			shrink_node(pgdat, &sc);
7630 		} while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
7631 	}
7632 
7633 	set_task_reclaim_state(p, NULL);
7634 	memalloc_noreclaim_restore(noreclaim_flag);
7635 	fs_reclaim_release(sc.gfp_mask);
7636 	psi_memstall_leave(&pflags);
7637 
7638 	trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7639 
7640 	return sc.nr_reclaimed >= nr_pages;
7641 }
7642 
7643 int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
7644 {
7645 	int ret;
7646 
7647 	/*
7648 	 * Node reclaim reclaims unmapped file backed pages and
7649 	 * slab pages if we are over the defined limits.
7650 	 *
7651 	 * A small portion of unmapped file backed pages is needed for
7652 	 * file I/O otherwise pages read by file I/O will be immediately
7653 	 * thrown out if the node is overallocated. So we do not reclaim
7654 	 * if less than a specified percentage of the node is used by
7655 	 * unmapped file backed pages.
7656 	 */
7657 	if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
7658 	    node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7659 	    pgdat->min_slab_pages)
7660 		return NODE_RECLAIM_FULL;
7661 
7662 	/*
7663 	 * Do not scan if the allocation should not be delayed.
7664 	 */
7665 	if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
7666 		return NODE_RECLAIM_NOSCAN;
7667 
7668 	/*
7669 	 * Only run node reclaim on the local node or on nodes that do not
7670 	 * have associated processors. This will favor the local processor
7671 	 * over remote processors and spread off node memory allocations
7672 	 * as wide as possible.
7673 	 */
7674 	if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7675 		return NODE_RECLAIM_NOSCAN;
7676 
7677 	if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7678 		return NODE_RECLAIM_NOSCAN;
7679 
7680 	ret = __node_reclaim(pgdat, gfp_mask, order);
7681 	clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
7682 
7683 	if (!ret)
7684 		count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7685 
7686 	return ret;
7687 }
7688 #endif
7689 
7690 void check_move_unevictable_pages(struct pagevec *pvec)
7691 {
7692 	struct folio_batch fbatch;
7693 	unsigned i;
7694 
7695 	folio_batch_init(&fbatch);
7696 	for (i = 0; i < pvec->nr; i++) {
7697 		struct page *page = pvec->pages[i];
7698 
7699 		if (PageTransTail(page))
7700 			continue;
7701 		folio_batch_add(&fbatch, page_folio(page));
7702 	}
7703 	check_move_unevictable_folios(&fbatch);
7704 }
7705 EXPORT_SYMBOL_GPL(check_move_unevictable_pages);
7706 
7707 /**
7708  * check_move_unevictable_folios - Move evictable folios to appropriate zone
7709  * lru list
7710  * @fbatch: Batch of lru folios to check.
7711  *
7712  * Checks folios for evictability, if an evictable folio is in the unevictable
7713  * lru list, moves it to the appropriate evictable lru list. This function
7714  * should be only used for lru folios.
7715  */
7716 void check_move_unevictable_folios(struct folio_batch *fbatch)
7717 {
7718 	struct lruvec *lruvec = NULL;
7719 	int pgscanned = 0;
7720 	int pgrescued = 0;
7721 	int i;
7722 
7723 	for (i = 0; i < fbatch->nr; i++) {
7724 		struct folio *folio = fbatch->folios[i];
7725 		int nr_pages = folio_nr_pages(folio);
7726 
7727 		pgscanned += nr_pages;
7728 
7729 		/* block memcg migration while the folio moves between lrus */
7730 		if (!folio_test_clear_lru(folio))
7731 			continue;
7732 
7733 		lruvec = folio_lruvec_relock_irq(folio, lruvec);
7734 		if (folio_evictable(folio) && folio_test_unevictable(folio)) {
7735 			lruvec_del_folio(lruvec, folio);
7736 			folio_clear_unevictable(folio);
7737 			lruvec_add_folio(lruvec, folio);
7738 			pgrescued += nr_pages;
7739 		}
7740 		folio_set_lru(folio);
7741 	}
7742 
7743 	if (lruvec) {
7744 		__count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7745 		__count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7746 		unlock_page_lruvec_irq(lruvec);
7747 	} else if (pgscanned) {
7748 		count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
7749 	}
7750 }
7751 EXPORT_SYMBOL_GPL(check_move_unevictable_folios);
7752