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