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