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