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