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