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