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