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