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