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