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