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