xref: /linux/mm/swap.c (revision bba2c3615bd6cfee7456d1130f2e6b01b3f4e9ba)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/swap.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  */
7 
8 /*
9  * This file contains the default values for the operation of the
10  * Linux VM subsystem. Fine-tuning documentation can be found in
11  * Documentation/admin-guide/sysctl/vm.rst.
12  * Started 18.12.91
13  * Swap aging added 23.2.95, Stephen Tweedie.
14  * Buffermem limits added 12.3.98, Rik van Riel.
15  */
16 
17 #include <linux/mm.h>
18 #include <linux/sched.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/swap.h>
21 #include <linux/mman.h>
22 #include <linux/pagemap.h>
23 #include <linux/folio_batch.h>
24 #include <linux/init.h>
25 #include <linux/export.h>
26 #include <linux/mm_inline.h>
27 #include <linux/percpu_counter.h>
28 #include <linux/memremap.h>
29 #include <linux/percpu.h>
30 #include <linux/cpu.h>
31 #include <linux/notifier.h>
32 #include <linux/backing-dev.h>
33 #include <linux/memcontrol.h>
34 #include <linux/gfp.h>
35 #include <linux/uio.h>
36 #include <linux/hugetlb.h>
37 #include <linux/page_idle.h>
38 #include <linux/local_lock.h>
39 #include <linux/buffer_head.h>
40 
41 #include "internal.h"
42 
43 #define CREATE_TRACE_POINTS
44 #include <trace/events/pagemap.h>
45 
46 /* How many pages do we try to swap or page in/out together? As a power of 2 */
47 int page_cluster;
48 static const int page_cluster_max = 31;
49 
50 struct cpu_fbatches {
51 	/*
52 	 * The following folio batches are grouped together because they are protected
53 	 * by disabling preemption (and interrupts remain enabled).
54 	 */
55 	local_lock_t lock;
56 	struct folio_batch lru_add;
57 	struct folio_batch lru_deactivate_file;
58 	struct folio_batch lru_deactivate;
59 	struct folio_batch lru_lazyfree;
60 #ifdef CONFIG_SMP
61 	struct folio_batch lru_activate;
62 #endif
63 	/* Protecting the following batches which require disabling interrupts */
64 	local_lock_t lock_irq;
65 	struct folio_batch lru_move_tail;
66 };
67 
68 static DEFINE_PER_CPU(struct cpu_fbatches, cpu_fbatches) = {
69 	.lock = INIT_LOCAL_LOCK(lock),
70 	.lock_irq = INIT_LOCAL_LOCK(lock_irq),
71 };
72 
73 static void __page_cache_release(struct folio *folio, struct lruvec **lruvecp,
74 		unsigned long *flagsp)
75 {
76 	if (folio_test_lru(folio)) {
77 		folio_lruvec_relock_irqsave(folio, lruvecp, flagsp);
78 		lruvec_del_folio(*lruvecp, folio);
79 		__folio_clear_lru_flags(folio);
80 	}
81 }
82 
83 /*
84  * This path almost never happens for VM activity - pages are normally freed
85  * in batches.  But it gets used by networking - and for compound pages.
86  */
87 static void page_cache_release(struct folio *folio)
88 {
89 	struct lruvec *lruvec = NULL;
90 	unsigned long flags;
91 
92 	__page_cache_release(folio, &lruvec, &flags);
93 	if (lruvec)
94 		lruvec_unlock_irqrestore(lruvec, flags);
95 }
96 
97 void __folio_put(struct folio *folio)
98 {
99 	if (unlikely(folio_is_zone_device(folio))) {
100 		free_zone_device_folio(folio);
101 		return;
102 	}
103 
104 	if (folio_test_hugetlb(folio)) {
105 		free_huge_folio(folio);
106 		return;
107 	}
108 
109 	page_cache_release(folio);
110 	folio_unqueue_deferred_split(folio);
111 	mem_cgroup_uncharge(folio);
112 	free_frozen_pages(&folio->page, folio_order(folio));
113 }
114 EXPORT_SYMBOL(__folio_put);
115 
116 typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio);
117 
118 static void lru_add(struct lruvec *lruvec, struct folio *folio)
119 {
120 	int was_unevictable = folio_test_clear_unevictable(folio);
121 	long nr_pages = folio_nr_pages(folio);
122 
123 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
124 
125 	/*
126 	 * Is an smp_mb__after_atomic() still required here, before
127 	 * folio_evictable() tests the mlocked flag, to rule out the possibility
128 	 * of stranding an evictable folio on an unevictable LRU?  I think
129 	 * not, because __munlock_folio() only clears the mlocked flag
130 	 * while the LRU lock is held.
131 	 *
132 	 * (That is not true of __page_cache_release(), and not necessarily
133 	 * true of folios_put(): but those only clear the mlocked flag after
134 	 * folio_put_testzero() has excluded any other users of the folio.)
135 	 */
136 	if (folio_evictable(folio)) {
137 		if (was_unevictable)
138 			__count_vm_events(UNEVICTABLE_PGRESCUED, nr_pages);
139 	} else {
140 		folio_clear_active(folio);
141 		folio_set_unevictable(folio);
142 		/*
143 		 * folio->mlock_count = !!folio_test_mlocked(folio)?
144 		 * But that leaves __mlock_folio() in doubt whether another
145 		 * actor has already counted the mlock or not.  Err on the
146 		 * safe side, underestimate, let page reclaim fix it, rather
147 		 * than leaving a page on the unevictable LRU indefinitely.
148 		 */
149 		folio->mlock_count = 0;
150 		if (!was_unevictable)
151 			__count_vm_events(UNEVICTABLE_PGCULLED, nr_pages);
152 	}
153 
154 	lruvec_add_folio(lruvec, folio);
155 	trace_mm_lru_insertion(folio);
156 }
157 
158 static void folio_batch_move_lru(struct folio_batch *fbatch, move_fn_t move_fn)
159 {
160 	int i;
161 	struct lruvec *lruvec = NULL;
162 	unsigned long flags = 0;
163 	struct folio_batch free_fbatch;
164 	bool is_lru_add = (move_fn == lru_add);
165 
166 	/*
167 	 * If we're adding to the LRU, preemptively filter dead folios. Use
168 	 * this dedicated folio batch for temp storage and deferred cleanup.
169 	 */
170 	if (is_lru_add)
171 		folio_batch_init(&free_fbatch);
172 
173 	for (i = 0; i < folio_batch_count(fbatch); i++) {
174 		struct folio *folio = fbatch->folios[i];
175 
176 		/* block memcg migration while the folio moves between lru */
177 		if (!is_lru_add && !folio_test_clear_lru(folio))
178 			continue;
179 
180 		/*
181 		 * Filter dead folios by moving them from the add batch to the temp
182 		 * batch for freeing after this loop.
183 		 *
184 		 * We're bypassing normal cleanup. Clear flags that are not
185 		 * applicable to dead folios.
186 		 *
187 		 * Since the folio may be part of a huge page, unqueue from
188 		 * deferred split list to avoid a dangling list entry.
189 		 */
190 		if (is_lru_add && folio_ref_freeze(folio, 1)) {
191 			__folio_clear_active(folio);
192 			__folio_clear_unevictable(folio);
193 			folio_unqueue_deferred_split(folio);
194 			fbatch->folios[i] = NULL;
195 			folio_batch_add(&free_fbatch, folio);
196 			continue;
197 		}
198 
199 		folio_lruvec_relock_irqsave(folio, &lruvec, &flags);
200 		move_fn(lruvec, folio);
201 
202 		folio_set_lru(folio);
203 	}
204 
205 	if (lruvec)
206 		lruvec_unlock_irqrestore(lruvec, flags);
207 
208 	/* Cleanup filtered dead folios. */
209 	if (is_lru_add) {
210 		mem_cgroup_uncharge_folios(&free_fbatch);
211 		free_unref_folios(&free_fbatch);
212 	}
213 
214 	folios_put(fbatch);
215 }
216 
217 static void __folio_batch_add_and_move(struct folio_batch __percpu *fbatch,
218 		struct folio *folio, move_fn_t move_fn, bool disable_irq)
219 {
220 	unsigned long flags;
221 
222 	folio_get(folio);
223 
224 	if (disable_irq)
225 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
226 	else
227 		local_lock(&cpu_fbatches.lock);
228 
229 	if (!folio_batch_add(this_cpu_ptr(fbatch), folio) ||
230 			!folio_may_be_lru_cached(folio) || lru_cache_disabled())
231 		folio_batch_move_lru(this_cpu_ptr(fbatch), move_fn);
232 
233 	if (disable_irq)
234 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
235 	else
236 		local_unlock(&cpu_fbatches.lock);
237 }
238 
239 #define folio_batch_add_and_move(folio, op)		\
240 	__folio_batch_add_and_move(			\
241 		&cpu_fbatches.op,			\
242 		folio,					\
243 		op,					\
244 		offsetof(struct cpu_fbatches, op) >=	\
245 		offsetof(struct cpu_fbatches, lock_irq)	\
246 	)
247 
248 static void lru_move_tail(struct lruvec *lruvec, struct folio *folio)
249 {
250 	if (folio_test_unevictable(folio))
251 		return;
252 
253 	lruvec_del_folio(lruvec, folio);
254 	folio_clear_active(folio);
255 	lruvec_add_folio_tail(lruvec, folio);
256 	__count_vm_events(PGROTATED, folio_nr_pages(folio));
257 }
258 
259 /*
260  * Writeback is about to end against a folio which has been marked for
261  * immediate reclaim.  If it still appears to be reclaimable, move it
262  * to the tail of the inactive list.
263  *
264  * folio_rotate_reclaimable() must disable IRQs, to prevent nasty races.
265  */
266 void folio_rotate_reclaimable(struct folio *folio)
267 {
268 	if (folio_test_locked(folio) || folio_test_dirty(folio) ||
269 	    folio_test_unevictable(folio) || !folio_test_lru(folio))
270 		return;
271 
272 	folio_batch_add_and_move(folio, lru_move_tail);
273 }
274 
275 void lru_note_cost_unlock_irq(struct lruvec *lruvec, bool file,
276 		unsigned int nr_io, unsigned int nr_rotated)
277 		__releases(lruvec->lru_lock)
278 		__releases(rcu)
279 {
280 	unsigned long cost;
281 
282 	/*
283 	 * Reflect the relative cost of incurring IO and spending CPU
284 	 * time on rotations. This doesn't attempt to make a precise
285 	 * comparison, it just says: if reloads are about comparable
286 	 * between the LRU lists, or rotations are overwhelmingly
287 	 * different between them, adjust scan balance for CPU work.
288 	 */
289 	cost = nr_io * SWAP_CLUSTER_MAX + nr_rotated;
290 	if (!cost) {
291 		spin_unlock_irq(&lruvec->lru_lock);
292 		rcu_read_unlock();
293 		return;
294 	}
295 
296 	for (;;) {
297 		unsigned long lrusize;
298 
299 		/* Record cost event */
300 		if (file)
301 			lruvec->file_cost += cost;
302 		else
303 			lruvec->anon_cost += cost;
304 
305 		/*
306 		 * Decay previous events
307 		 *
308 		 * Because workloads change over time (and to avoid
309 		 * overflow) we keep these statistics as a floating
310 		 * average, which ends up weighing recent refaults
311 		 * more than old ones.
312 		 */
313 		lrusize = lruvec_page_state(lruvec, NR_INACTIVE_ANON) +
314 			  lruvec_page_state(lruvec, NR_ACTIVE_ANON) +
315 			  lruvec_page_state(lruvec, NR_INACTIVE_FILE) +
316 			  lruvec_page_state(lruvec, NR_ACTIVE_FILE);
317 
318 		if (lruvec->file_cost + lruvec->anon_cost > lrusize / 4) {
319 			lruvec->file_cost /= 2;
320 			lruvec->anon_cost /= 2;
321 		}
322 
323 		spin_unlock_irq(&lruvec->lru_lock);
324 		lruvec = parent_lruvec(lruvec);
325 		if (!lruvec) {
326 			rcu_read_unlock();
327 			break;
328 		}
329 		spin_lock_irq(&lruvec->lru_lock);
330 	}
331 }
332 
333 void lru_note_cost_refault(struct folio *folio)
334 {
335 	struct lruvec *lruvec;
336 
337 	lruvec = folio_lruvec_lock_irq(folio);
338 	lru_note_cost_unlock_irq(lruvec, folio_is_file_lru(folio),
339 				folio_nr_pages(folio), 0);
340 }
341 
342 static void lru_activate(struct lruvec *lruvec, struct folio *folio)
343 {
344 	long nr_pages = folio_nr_pages(folio);
345 
346 	if (folio_test_active(folio) || folio_test_unevictable(folio))
347 		return;
348 
349 
350 	lruvec_del_folio(lruvec, folio);
351 	folio_set_active(folio);
352 	lruvec_add_folio(lruvec, folio);
353 	trace_mm_lru_activate(folio);
354 
355 	__count_vm_events(PGACTIVATE, nr_pages);
356 	count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE, nr_pages);
357 }
358 
359 #ifdef CONFIG_SMP
360 static void folio_activate_drain(int cpu)
361 {
362 	struct folio_batch *fbatch = &per_cpu(cpu_fbatches.lru_activate, cpu);
363 
364 	if (folio_batch_count(fbatch))
365 		folio_batch_move_lru(fbatch, lru_activate);
366 }
367 
368 void folio_activate(struct folio *folio)
369 {
370 	if (folio_test_active(folio) || folio_test_unevictable(folio) ||
371 	    !folio_test_lru(folio))
372 		return;
373 
374 	folio_batch_add_and_move(folio, lru_activate);
375 }
376 
377 #else
378 static inline void folio_activate_drain(int cpu)
379 {
380 }
381 
382 void folio_activate(struct folio *folio)
383 {
384 	struct lruvec *lruvec;
385 
386 	if (!folio_test_clear_lru(folio))
387 		return;
388 
389 	lruvec = folio_lruvec_lock_irq(folio);
390 	lru_activate(lruvec, folio);
391 	lruvec_unlock_irq(lruvec);
392 	folio_set_lru(folio);
393 }
394 #endif
395 
396 static void __lru_cache_activate_folio(struct folio *folio)
397 {
398 	struct folio_batch *fbatch;
399 	int i;
400 
401 	local_lock(&cpu_fbatches.lock);
402 	fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
403 
404 	/*
405 	 * Search backwards on the optimistic assumption that the folio being
406 	 * activated has just been added to this batch. Note that only
407 	 * the local batch is examined as a !LRU folio could be in the
408 	 * process of being released, reclaimed, migrated or on a remote
409 	 * batch that is currently being drained. Furthermore, marking
410 	 * a remote batch's folio active potentially hits a race where
411 	 * a folio is marked active just after it is added to the inactive
412 	 * list causing accounting errors and BUG_ON checks to trigger.
413 	 */
414 	for (i = folio_batch_count(fbatch) - 1; i >= 0; i--) {
415 		struct folio *batch_folio = fbatch->folios[i];
416 
417 		if (batch_folio == folio) {
418 			folio_set_active(folio);
419 			break;
420 		}
421 	}
422 
423 	local_unlock(&cpu_fbatches.lock);
424 }
425 
426 #ifdef CONFIG_LRU_GEN
427 
428 static void lru_gen_inc_refs(struct folio *folio)
429 {
430 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f);
431 
432 	if (folio_test_unevictable(folio))
433 		return;
434 
435 	/* see the comment on LRU_REFS_FLAGS */
436 	if (!folio_test_referenced(folio)) {
437 		set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced));
438 		return;
439 	}
440 
441 	do {
442 		if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) {
443 			if (!folio_test_workingset(folio))
444 				folio_set_workingset(folio);
445 			return;
446 		}
447 
448 		new_flags = old_flags + BIT(LRU_REFS_PGOFF);
449 	} while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags));
450 }
451 
452 static bool lru_gen_clear_refs(struct folio *folio)
453 {
454 	int gen = folio_lru_gen(folio);
455 	int type = folio_is_file_lru(folio);
456 	unsigned long seq;
457 
458 	if (gen < 0)
459 		return true;
460 
461 	set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0);
462 
463 	rcu_read_lock();
464 	seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]);
465 	rcu_read_unlock();
466 	/* whether can do without shuffling under the LRU lock */
467 	return gen == lru_gen_from_seq(seq);
468 }
469 
470 #else /* !CONFIG_LRU_GEN */
471 
472 static void lru_gen_inc_refs(struct folio *folio)
473 {
474 }
475 
476 static bool lru_gen_clear_refs(struct folio *folio)
477 {
478 	return false;
479 }
480 
481 #endif /* CONFIG_LRU_GEN */
482 
483 /**
484  * folio_mark_accessed - Mark a folio as having seen activity.
485  * @folio: The folio to mark.
486  *
487  * This function will perform one of the following transitions:
488  *
489  * * inactive,unreferenced	->	inactive,referenced
490  * * inactive,referenced	->	active,unreferenced
491  * * active,unreferenced	->	active,referenced
492  *
493  * When a newly allocated folio is not yet visible, so safe for non-atomic ops,
494  * __folio_set_referenced() may be substituted for folio_mark_accessed().
495  */
496 void folio_mark_accessed(struct folio *folio)
497 {
498 	if (folio_test_dropbehind(folio))
499 		return;
500 	if (lru_gen_enabled()) {
501 		lru_gen_inc_refs(folio);
502 		return;
503 	}
504 
505 	if (!folio_test_referenced(folio)) {
506 		folio_set_referenced(folio);
507 	} else if (folio_test_unevictable(folio)) {
508 		/*
509 		 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
510 		 * this list is never rotated or maintained, so marking an
511 		 * unevictable page accessed has no effect.
512 		 */
513 	} else if (!folio_test_active(folio)) {
514 		/*
515 		 * If the folio is on the LRU, queue it for activation via
516 		 * cpu_fbatches.lru_activate. Otherwise, assume the folio is in a
517 		 * folio_batch, mark it active and it'll be moved to the active
518 		 * LRU on the next drain.
519 		 */
520 		if (folio_test_lru(folio))
521 			folio_activate(folio);
522 		else
523 			__lru_cache_activate_folio(folio);
524 		folio_clear_referenced(folio);
525 		workingset_activation(folio);
526 	}
527 	if (folio_test_idle(folio))
528 		folio_clear_idle(folio);
529 }
530 EXPORT_SYMBOL(folio_mark_accessed);
531 
532 /**
533  * folio_add_lru - Add a folio to an LRU list.
534  * @folio: The folio to be added to the LRU.
535  *
536  * Queue the folio for addition to the LRU. The decision on whether
537  * to add the page to the [in]active [file|anon] list is deferred until the
538  * folio_batch is drained. This gives a chance for the caller of folio_add_lru()
539  * have the folio added to the active list using folio_mark_accessed().
540  */
541 void folio_add_lru(struct folio *folio)
542 {
543 	VM_BUG_ON_FOLIO(folio_test_active(folio) &&
544 			folio_test_unevictable(folio), folio);
545 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
546 
547 	/*
548 	 * For refaulted workingset folios, set PG_active so they
549 	 * can be added to active generations.
550 	 * For prefaulted file folios, folio_mark_accessed() sets
551 	 * PG_referenced so lru_gen_folio_seq() places them into
552 	 * the second oldest generation.
553 	 */
554 	if (lru_gen_enabled() && !folio_test_unevictable(folio) &&
555 	    lru_gen_in_fault() && !(current->flags & PF_MEMALLOC)) {
556 		if (folio_test_workingset(folio))
557 			folio_set_active(folio);
558 		else if (!folio_test_referenced(folio))
559 			folio_mark_accessed(folio);
560 	}
561 
562 	folio_batch_add_and_move(folio, lru_add);
563 }
564 EXPORT_SYMBOL(folio_add_lru);
565 
566 /**
567  * folio_add_lru_vma() - Add a folio to the appropriate LRU list for this VMA.
568  * @folio: The folio to be added to the LRU.
569  * @vma: VMA in which the folio is mapped.
570  *
571  * If the VMA is mlocked, @folio is added to the unevictable list.
572  * Otherwise, it is treated the same way as folio_add_lru().
573  */
574 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
575 {
576 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
577 
578 	if (unlikely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED))
579 		mlock_new_folio(folio);
580 	else
581 		folio_add_lru(folio);
582 }
583 
584 /*
585  * If the folio cannot be invalidated, it is moved to the
586  * inactive list to speed up its reclaim.  It is moved to the
587  * head of the list, rather than the tail, to give the flusher
588  * threads some time to write it out, as this is much more
589  * effective than the single-page writeout from reclaim.
590  *
591  * If the folio isn't mapped and dirty/writeback, the folio
592  * could be reclaimed asap using the reclaim flag.
593  *
594  * 1. active, mapped folio -> none
595  * 2. active, dirty/writeback folio -> inactive, head, reclaim
596  * 3. inactive, mapped folio -> none
597  * 4. inactive, dirty/writeback folio -> inactive, head, reclaim
598  * 5. inactive, clean -> inactive, tail
599  * 6. Others -> none
600  *
601  * In 4, it moves to the head of the inactive list so the folio is
602  * written out by flusher threads as this is much more efficient
603  * than the single-page writeout from reclaim.
604  */
605 static void lru_deactivate_file(struct lruvec *lruvec, struct folio *folio)
606 {
607 	bool active = folio_test_active(folio) || lru_gen_enabled();
608 	long nr_pages = folio_nr_pages(folio);
609 
610 	if (folio_test_unevictable(folio))
611 		return;
612 
613 	/* Some processes are using the folio */
614 	if (folio_mapped(folio))
615 		return;
616 
617 	lruvec_del_folio(lruvec, folio);
618 	folio_clear_active(folio);
619 	folio_clear_referenced(folio);
620 
621 	if (folio_test_writeback(folio) || folio_test_dirty(folio)) {
622 		/*
623 		 * Setting the reclaim flag could race with
624 		 * folio_end_writeback() and confuse readahead.  But the
625 		 * race window is _really_ small and  it's not a critical
626 		 * problem.
627 		 */
628 		lruvec_add_folio(lruvec, folio);
629 		folio_set_reclaim(folio);
630 	} else {
631 		/*
632 		 * The folio's writeback ended while it was in the batch.
633 		 * We move that folio to the tail of the inactive list.
634 		 */
635 		lruvec_add_folio_tail(lruvec, folio);
636 		__count_vm_events(PGROTATED, nr_pages);
637 	}
638 
639 	if (active) {
640 		__count_vm_events(PGDEACTIVATE, nr_pages);
641 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
642 				     nr_pages);
643 	}
644 }
645 
646 static void lru_deactivate(struct lruvec *lruvec, struct folio *folio)
647 {
648 	long nr_pages = folio_nr_pages(folio);
649 
650 	if (folio_test_unevictable(folio) || !(folio_test_active(folio) || lru_gen_enabled()))
651 		return;
652 
653 	lruvec_del_folio(lruvec, folio);
654 	folio_clear_active(folio);
655 	folio_clear_referenced(folio);
656 	lruvec_add_folio(lruvec, folio);
657 
658 	__count_vm_events(PGDEACTIVATE, nr_pages);
659 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_pages);
660 }
661 
662 static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio)
663 {
664 	long nr_pages = folio_nr_pages(folio);
665 
666 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
667 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
668 		return;
669 
670 	lruvec_del_folio(lruvec, folio);
671 	folio_clear_active(folio);
672 	if (lru_gen_enabled())
673 		lru_gen_clear_refs(folio);
674 	else
675 		folio_clear_referenced(folio);
676 	/*
677 	 * Lazyfree folios are clean anonymous folios.  They have
678 	 * the swapbacked flag cleared, to distinguish them from normal
679 	 * anonymous folios
680 	 */
681 	folio_clear_swapbacked(folio);
682 	lruvec_add_folio(lruvec, folio);
683 
684 	__count_vm_events(PGLAZYFREE, nr_pages);
685 	count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE, nr_pages);
686 }
687 
688 /*
689  * Drain pages out of the cpu's folio_batch.
690  * Either "cpu" is the current CPU, and preemption has already been
691  * disabled; or "cpu" is being hot-unplugged, and is already dead.
692  */
693 void lru_add_drain_cpu(int cpu)
694 {
695 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
696 	struct folio_batch *fbatch = &fbatches->lru_add;
697 
698 	if (folio_batch_count(fbatch))
699 		folio_batch_move_lru(fbatch, lru_add);
700 
701 	fbatch = &fbatches->lru_move_tail;
702 	/* Disabling interrupts below acts as a compiler barrier. */
703 	if (data_race(folio_batch_count(fbatch))) {
704 		unsigned long flags;
705 
706 		/* No harm done if a racing interrupt already did this */
707 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
708 		folio_batch_move_lru(fbatch, lru_move_tail);
709 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
710 	}
711 
712 	fbatch = &fbatches->lru_deactivate_file;
713 	if (folio_batch_count(fbatch))
714 		folio_batch_move_lru(fbatch, lru_deactivate_file);
715 
716 	fbatch = &fbatches->lru_deactivate;
717 	if (folio_batch_count(fbatch))
718 		folio_batch_move_lru(fbatch, lru_deactivate);
719 
720 	fbatch = &fbatches->lru_lazyfree;
721 	if (folio_batch_count(fbatch))
722 		folio_batch_move_lru(fbatch, lru_lazyfree);
723 
724 	folio_activate_drain(cpu);
725 }
726 
727 /**
728  * deactivate_file_folio() - Deactivate a file folio.
729  * @folio: Folio to deactivate.
730  *
731  * This function hints to the VM that @folio is a good reclaim candidate,
732  * for example if its invalidation fails due to the folio being dirty
733  * or under writeback.
734  *
735  * Context: Caller holds a reference on the folio.
736  */
737 void deactivate_file_folio(struct folio *folio)
738 {
739 	/* Deactivating an unevictable folio will not accelerate reclaim */
740 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
741 		return;
742 
743 	if (lru_gen_enabled() && lru_gen_clear_refs(folio))
744 		return;
745 
746 	folio_batch_add_and_move(folio, lru_deactivate_file);
747 }
748 
749 /*
750  * folio_deactivate - deactivate a folio
751  * @folio: folio to deactivate
752  *
753  * folio_deactivate() moves @folio to the inactive list if @folio was on the
754  * active list and was not unevictable. This is done to accelerate the
755  * reclaim of @folio.
756  */
757 void folio_deactivate(struct folio *folio)
758 {
759 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
760 		return;
761 
762 	if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio))
763 		return;
764 
765 	folio_batch_add_and_move(folio, lru_deactivate);
766 }
767 
768 /**
769  * folio_mark_lazyfree - make an anon folio lazyfree
770  * @folio: folio to deactivate
771  *
772  * folio_mark_lazyfree() moves @folio to the inactive file list.
773  * This is done to accelerate the reclaim of @folio.
774  */
775 void folio_mark_lazyfree(struct folio *folio)
776 {
777 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
778 	    !folio_test_lru(folio) ||
779 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
780 		return;
781 
782 	folio_batch_add_and_move(folio, lru_lazyfree);
783 }
784 
785 void lru_add_drain(void)
786 {
787 	local_lock(&cpu_fbatches.lock);
788 	lru_add_drain_cpu(smp_processor_id());
789 	local_unlock(&cpu_fbatches.lock);
790 	mlock_drain_local();
791 }
792 
793 /*
794  * It's called from per-cpu workqueue context in SMP case so
795  * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
796  * the same cpu. It shouldn't be a problem in !SMP case since
797  * the core is only one and the locks will disable preemption.
798  */
799 static void lru_add_and_bh_lrus_drain(void)
800 {
801 	local_lock(&cpu_fbatches.lock);
802 	lru_add_drain_cpu(smp_processor_id());
803 	local_unlock(&cpu_fbatches.lock);
804 	invalidate_bh_lrus_cpu();
805 	mlock_drain_local();
806 }
807 
808 void lru_add_drain_cpu_zone(struct zone *zone)
809 {
810 	local_lock(&cpu_fbatches.lock);
811 	lru_add_drain_cpu(smp_processor_id());
812 	drain_local_pages(zone);
813 	local_unlock(&cpu_fbatches.lock);
814 	mlock_drain_local();
815 }
816 
817 #ifdef CONFIG_SMP
818 
819 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
820 
821 static void lru_add_drain_per_cpu(struct work_struct *dummy)
822 {
823 	lru_add_and_bh_lrus_drain();
824 }
825 
826 static bool cpu_needs_drain(unsigned int cpu)
827 {
828 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
829 
830 	/* Check these in order of likelihood that they're not zero */
831 	return folio_batch_count(&fbatches->lru_add) ||
832 		folio_batch_count(&fbatches->lru_move_tail) ||
833 		folio_batch_count(&fbatches->lru_deactivate_file) ||
834 		folio_batch_count(&fbatches->lru_deactivate) ||
835 		folio_batch_count(&fbatches->lru_lazyfree) ||
836 		folio_batch_count(&fbatches->lru_activate) ||
837 		need_mlock_drain(cpu) ||
838 		has_bh_in_lru(cpu, NULL);
839 }
840 
841 /*
842  * Doesn't need any cpu hotplug locking because we do rely on per-cpu
843  * kworkers being shut down before our page_alloc_cpu_dead callback is
844  * executed on the offlined cpu.
845  * Calling this function with cpu hotplug locks held can actually lead
846  * to obscure indirect dependencies via WQ context.
847  */
848 static inline void __lru_add_drain_all(bool force_all_cpus)
849 {
850 	/*
851 	 * lru_drain_gen - Global pages generation number
852 	 *
853 	 * (A) Definition: global lru_drain_gen = x implies that all generations
854 	 *     0 < n <= x are already *scheduled* for draining.
855 	 *
856 	 * This is an optimization for the highly-contended use case where a
857 	 * user space workload keeps constantly generating a flow of pages for
858 	 * each CPU.
859 	 */
860 	static unsigned int lru_drain_gen;
861 	static struct cpumask has_work;
862 	static DEFINE_MUTEX(lock);
863 	unsigned cpu, this_gen;
864 
865 	/*
866 	 * Make sure nobody triggers this path before mm_percpu_wq is fully
867 	 * initialized.
868 	 */
869 	if (WARN_ON(!mm_percpu_wq))
870 		return;
871 
872 	/*
873 	 * Guarantee folio_batch counter stores visible by this CPU
874 	 * are visible to other CPUs before loading the current drain
875 	 * generation.
876 	 */
877 	smp_mb();
878 
879 	/*
880 	 * (B) Locally cache global LRU draining generation number
881 	 *
882 	 * The read barrier ensures that the counter is loaded before the mutex
883 	 * is taken. It pairs with smp_mb() inside the mutex critical section
884 	 * at (D).
885 	 */
886 	this_gen = smp_load_acquire(&lru_drain_gen);
887 
888 	/* It helps everyone if we do our own local drain immediately. */
889 	lru_add_drain();
890 
891 	mutex_lock(&lock);
892 
893 	/*
894 	 * (C) Exit the draining operation if a newer generation, from another
895 	 * lru_add_drain_all(), was already scheduled for draining. Check (A).
896 	 */
897 	if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
898 		goto done;
899 
900 	/*
901 	 * (D) Increment global generation number
902 	 *
903 	 * Pairs with smp_load_acquire() at (B), outside of the critical
904 	 * section. Use a full memory barrier to guarantee that the
905 	 * new global drain generation number is stored before loading
906 	 * folio_batch counters.
907 	 *
908 	 * This pairing must be done here, before the for_each_online_cpu loop
909 	 * below which drains the page vectors.
910 	 *
911 	 * Let x, y, and z represent some system CPU numbers, where x < y < z.
912 	 * Assume CPU #z is in the middle of the for_each_online_cpu loop
913 	 * below and has already reached CPU #y's per-cpu data. CPU #x comes
914 	 * along, adds some pages to its per-cpu vectors, then calls
915 	 * lru_add_drain_all().
916 	 *
917 	 * If the paired barrier is done at any later step, e.g. after the
918 	 * loop, CPU #x will just exit at (C) and miss flushing out all of its
919 	 * added pages.
920 	 */
921 	WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
922 	smp_mb();
923 
924 	cpumask_clear(&has_work);
925 	for_each_online_cpu(cpu) {
926 		struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
927 
928 		if (cpu_needs_drain(cpu)) {
929 			INIT_WORK(work, lru_add_drain_per_cpu);
930 			queue_work_on(cpu, mm_percpu_wq, work);
931 			__cpumask_set_cpu(cpu, &has_work);
932 		}
933 	}
934 
935 	for_each_cpu(cpu, &has_work)
936 		flush_work(&per_cpu(lru_add_drain_work, cpu));
937 
938 done:
939 	mutex_unlock(&lock);
940 }
941 
942 void lru_add_drain_all(void)
943 {
944 	__lru_add_drain_all(false);
945 }
946 #else
947 void lru_add_drain_all(void)
948 {
949 	lru_add_drain();
950 }
951 #endif /* CONFIG_SMP */
952 
953 atomic_t lru_disable_count = ATOMIC_INIT(0);
954 
955 /*
956  * lru_cache_disable() needs to be called before we start compiling
957  * a list of folios to be migrated using folio_isolate_lru().
958  * It drains folios on LRU cache and then disable on all cpus until
959  * lru_cache_enable is called.
960  *
961  * Must be paired with a call to lru_cache_enable().
962  */
963 void lru_cache_disable(void)
964 {
965 	atomic_inc(&lru_disable_count);
966 	/*
967 	 * Readers of lru_disable_count are protected by either disabling
968 	 * preemption or rcu_read_lock:
969 	 *
970 	 * preempt_disable, local_irq_disable  [bh_lru_lock()]
971 	 * rcu_read_lock		       [rt_spin_lock CONFIG_PREEMPT_RT]
972 	 * preempt_disable		       [local_lock !CONFIG_PREEMPT_RT]
973 	 *
974 	 * Since v5.1 kernel, synchronize_rcu() is guaranteed to wait on
975 	 * preempt_disable() regions of code. So any CPU which sees
976 	 * lru_disable_count = 0 will have exited the critical
977 	 * section when synchronize_rcu() returns.
978 	 */
979 	synchronize_rcu_expedited();
980 #ifdef CONFIG_SMP
981 	__lru_add_drain_all(true);
982 #else
983 	lru_add_and_bh_lrus_drain();
984 #endif
985 }
986 
987 /**
988  * folios_put_refs - Reduce the reference count on a batch of folios.
989  * @folios: The folios.
990  * @refs: The number of refs to subtract from each folio.
991  *
992  * Like folio_put(), but for a batch of folios.  This is more efficient
993  * than writing the loop yourself as it will optimise the locks which need
994  * to be taken if the folios are freed.  The folios batch is returned
995  * empty and ready to be reused for another batch; there is no need
996  * to reinitialise it.  If @refs is NULL, we subtract one from each
997  * folio refcount.
998  *
999  * Context: May be called in process or interrupt context, but not in NMI
1000  * context.  May be called while holding a spinlock.
1001  */
1002 void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
1003 {
1004 	int i, j;
1005 	struct lruvec *lruvec = NULL;
1006 	unsigned long flags = 0;
1007 
1008 	for (i = 0, j = 0; i < folios->nr; i++) {
1009 		struct folio *folio = folios->folios[i];
1010 		unsigned int nr_refs = refs ? refs[i] : 1;
1011 
1012 		/* Folio batch entry may have been preemptively removed during drain. */
1013 		if (!folio)
1014 			continue;
1015 
1016 		if (is_huge_zero_folio(folio))
1017 			continue;
1018 
1019 		if (folio_is_zone_device(folio)) {
1020 			if (lruvec) {
1021 				lruvec_unlock_irqrestore(lruvec, flags);
1022 				lruvec = NULL;
1023 			}
1024 			if (folio_ref_sub_and_test(folio, nr_refs))
1025 				free_zone_device_folio(folio);
1026 			continue;
1027 		}
1028 
1029 		if (!folio_ref_sub_and_test(folio, nr_refs))
1030 			continue;
1031 
1032 		/* hugetlb has its own memcg */
1033 		if (folio_test_hugetlb(folio)) {
1034 			if (lruvec) {
1035 				lruvec_unlock_irqrestore(lruvec, flags);
1036 				lruvec = NULL;
1037 			}
1038 			free_huge_folio(folio);
1039 			continue;
1040 		}
1041 		folio_unqueue_deferred_split(folio);
1042 		__page_cache_release(folio, &lruvec, &flags);
1043 
1044 		if (j != i)
1045 			folios->folios[j] = folio;
1046 		j++;
1047 	}
1048 	if (lruvec)
1049 		lruvec_unlock_irqrestore(lruvec, flags);
1050 	if (!j) {
1051 		folio_batch_reinit(folios);
1052 		return;
1053 	}
1054 
1055 	folios->nr = j;
1056 	mem_cgroup_uncharge_folios(folios);
1057 	free_unref_folios(folios);
1058 }
1059 EXPORT_SYMBOL(folios_put_refs);
1060 
1061 /**
1062  * release_pages - batched put_page()
1063  * @arg: array of pages to release
1064  * @nr: number of pages
1065  *
1066  * Decrement the reference count on all the pages in @arg.  If it
1067  * fell to zero, remove the page from the LRU and free it.
1068  *
1069  * Note that the argument can be an array of pages, encoded pages,
1070  * or folio pointers. We ignore any encoded bits, and turn any of
1071  * them into just a folio that gets free'd.
1072  */
1073 void release_pages(release_pages_arg arg, int nr)
1074 {
1075 	struct folio_batch fbatch;
1076 	int refs[FOLIO_BATCH_SIZE];
1077 	struct encoded_page **encoded = arg.encoded_pages;
1078 	int i;
1079 
1080 	folio_batch_init(&fbatch);
1081 	for (i = 0; i < nr; i++) {
1082 		/* Turn any of the argument types into a folio */
1083 		struct folio *folio = page_folio(encoded_page_ptr(encoded[i]));
1084 
1085 		/* Is our next entry actually "nr_pages" -> "nr_refs" ? */
1086 		refs[fbatch.nr] = 1;
1087 		if (unlikely(encoded_page_flags(encoded[i]) &
1088 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
1089 			refs[fbatch.nr] = encoded_nr_pages(encoded[++i]);
1090 
1091 		if (folio_batch_add(&fbatch, folio) > 0)
1092 			continue;
1093 		folios_put_refs(&fbatch, refs);
1094 	}
1095 
1096 	if (fbatch.nr)
1097 		folios_put_refs(&fbatch, refs);
1098 }
1099 EXPORT_SYMBOL(release_pages);
1100 
1101 /*
1102  * The folios which we're about to release may be in the deferred lru-addition
1103  * queues.  That would prevent them from really being freed right now.  That's
1104  * OK from a correctness point of view but is inefficient - those folios may be
1105  * cache-warm and we want to give them back to the page allocator ASAP.
1106  *
1107  * So __folio_batch_release() will drain those queues here.
1108  * folio_batch_move_lru() calls folios_put() directly to avoid
1109  * mutual recursion.
1110  */
1111 void __folio_batch_release(struct folio_batch *fbatch)
1112 {
1113 	if (!fbatch->percpu_pvec_drained) {
1114 		lru_add_drain();
1115 		fbatch->percpu_pvec_drained = true;
1116 	}
1117 	folios_put(fbatch);
1118 }
1119 EXPORT_SYMBOL(__folio_batch_release);
1120 
1121 /**
1122  * folio_batch_remove_exceptionals() - Prune non-folios from a batch.
1123  * @fbatch: The batch to prune
1124  *
1125  * find_get_entries() fills a batch with both folios and shadow/swap/DAX
1126  * entries.  This function prunes all the non-folio entries from @fbatch
1127  * without leaving holes, so that it can be passed on to folio-only batch
1128  * operations.
1129  */
1130 void folio_batch_remove_exceptionals(struct folio_batch *fbatch)
1131 {
1132 	unsigned int i, j;
1133 
1134 	for (i = 0, j = 0; i < folio_batch_count(fbatch); i++) {
1135 		struct folio *folio = fbatch->folios[i];
1136 		if (!xa_is_value(folio))
1137 			fbatch->folios[j++] = folio;
1138 	}
1139 	fbatch->nr = j;
1140 }
1141 
1142 #ifdef CONFIG_MEMCG
1143 static void lruvec_reparent_lru(struct lruvec *child_lruvec,
1144 				struct lruvec *parent_lruvec,
1145 				enum lru_list lru, int nid)
1146 {
1147 	int zid;
1148 	struct zone *zone;
1149 
1150 	if (lru != LRU_UNEVICTABLE)
1151 		list_splice_tail_init(&child_lruvec->lists[lru], &parent_lruvec->lists[lru]);
1152 
1153 	for_each_managed_zone_pgdat(zone, NODE_DATA(nid), zid, MAX_NR_ZONES - 1) {
1154 		unsigned long size = mem_cgroup_get_zone_lru_size(child_lruvec, lru, zid);
1155 
1156 		mem_cgroup_update_lru_size(parent_lruvec, lru, zid, size);
1157 	}
1158 }
1159 
1160 void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid)
1161 {
1162 	enum lru_list lru;
1163 	struct lruvec *child_lruvec, *parent_lruvec;
1164 
1165 	child_lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
1166 	parent_lruvec = mem_cgroup_lruvec(parent, NODE_DATA(nid));
1167 	parent_lruvec->anon_cost += child_lruvec->anon_cost;
1168 	parent_lruvec->file_cost += child_lruvec->file_cost;
1169 
1170 	for_each_lru(lru)
1171 		lruvec_reparent_lru(child_lruvec, parent_lruvec, lru, nid);
1172 }
1173 #endif
1174 
1175 static const struct ctl_table swap_sysctl_table[] = {
1176 	{
1177 		.procname	= "page-cluster",
1178 		.data		= &page_cluster,
1179 		.maxlen		= sizeof(int),
1180 		.mode		= 0644,
1181 		.proc_handler	= proc_dointvec_minmax,
1182 		.extra1		= SYSCTL_ZERO,
1183 		.extra2		= (void *)&page_cluster_max,
1184 	}
1185 };
1186 
1187 /*
1188  * Perform any setup for the swap system
1189  */
1190 void __init swap_setup(void)
1191 {
1192 	unsigned long megs = PAGES_TO_MB(totalram_pages());
1193 
1194 	/* Use a smaller cluster for small-memory machines */
1195 	if (megs < 16)
1196 		page_cluster = 2;
1197 	else
1198 		page_cluster = 3;
1199 	/*
1200 	 * Right now other parts of the system means that we
1201 	 * _really_ don't want to cluster much more
1202 	 */
1203 
1204 	register_sysctl_init("vm", swap_sysctl_table);
1205 }
1206