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