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