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