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