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