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