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