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