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