xref: /linux/mm/swap.c (revision b7e32ae6664285e156e9f0cd821e63e19798baf7)
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/pagevec.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 		unlock_page_lruvec_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 
164 	for (i = 0; i < folio_batch_count(fbatch); i++) {
165 		struct folio *folio = fbatch->folios[i];
166 
167 		/* block memcg migration while the folio moves between lru */
168 		if (move_fn != lru_add && !folio_test_clear_lru(folio))
169 			continue;
170 
171 		folio_lruvec_relock_irqsave(folio, &lruvec, &flags);
172 		move_fn(lruvec, folio);
173 
174 		folio_set_lru(folio);
175 	}
176 
177 	if (lruvec)
178 		unlock_page_lruvec_irqrestore(lruvec, flags);
179 	folios_put(fbatch);
180 }
181 
182 static void __folio_batch_add_and_move(struct folio_batch __percpu *fbatch,
183 		struct folio *folio, move_fn_t move_fn, bool disable_irq)
184 {
185 	unsigned long flags;
186 
187 	folio_get(folio);
188 
189 	if (disable_irq)
190 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
191 	else
192 		local_lock(&cpu_fbatches.lock);
193 
194 	if (!folio_batch_add(this_cpu_ptr(fbatch), folio) ||
195 			!folio_may_be_lru_cached(folio) || lru_cache_disabled())
196 		folio_batch_move_lru(this_cpu_ptr(fbatch), move_fn);
197 
198 	if (disable_irq)
199 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
200 	else
201 		local_unlock(&cpu_fbatches.lock);
202 }
203 
204 #define folio_batch_add_and_move(folio, op)		\
205 	__folio_batch_add_and_move(			\
206 		&cpu_fbatches.op,			\
207 		folio,					\
208 		op,					\
209 		offsetof(struct cpu_fbatches, op) >=	\
210 		offsetof(struct cpu_fbatches, lock_irq)	\
211 	)
212 
213 static void lru_move_tail(struct lruvec *lruvec, struct folio *folio)
214 {
215 	if (folio_test_unevictable(folio))
216 		return;
217 
218 	lruvec_del_folio(lruvec, folio);
219 	folio_clear_active(folio);
220 	lruvec_add_folio_tail(lruvec, folio);
221 	__count_vm_events(PGROTATED, folio_nr_pages(folio));
222 }
223 
224 /*
225  * Writeback is about to end against a folio which has been marked for
226  * immediate reclaim.  If it still appears to be reclaimable, move it
227  * to the tail of the inactive list.
228  *
229  * folio_rotate_reclaimable() must disable IRQs, to prevent nasty races.
230  */
231 void folio_rotate_reclaimable(struct folio *folio)
232 {
233 	if (folio_test_locked(folio) || folio_test_dirty(folio) ||
234 	    folio_test_unevictable(folio) || !folio_test_lru(folio))
235 		return;
236 
237 	folio_batch_add_and_move(folio, lru_move_tail);
238 }
239 
240 void lru_note_cost_unlock_irq(struct lruvec *lruvec, bool file,
241 		unsigned int nr_io, unsigned int nr_rotated)
242 		__releases(lruvec->lru_lock)
243 {
244 	unsigned long cost;
245 
246 	/*
247 	 * Reflect the relative cost of incurring IO and spending CPU
248 	 * time on rotations. This doesn't attempt to make a precise
249 	 * comparison, it just says: if reloads are about comparable
250 	 * between the LRU lists, or rotations are overwhelmingly
251 	 * different between them, adjust scan balance for CPU work.
252 	 */
253 	cost = nr_io * SWAP_CLUSTER_MAX + nr_rotated;
254 	if (!cost) {
255 		spin_unlock_irq(&lruvec->lru_lock);
256 		return;
257 	}
258 
259 	for (;;) {
260 		unsigned long lrusize;
261 
262 		/* Record cost event */
263 		if (file)
264 			lruvec->file_cost += cost;
265 		else
266 			lruvec->anon_cost += cost;
267 
268 		/*
269 		 * Decay previous events
270 		 *
271 		 * Because workloads change over time (and to avoid
272 		 * overflow) we keep these statistics as a floating
273 		 * average, which ends up weighing recent refaults
274 		 * more than old ones.
275 		 */
276 		lrusize = lruvec_page_state(lruvec, NR_INACTIVE_ANON) +
277 			  lruvec_page_state(lruvec, NR_ACTIVE_ANON) +
278 			  lruvec_page_state(lruvec, NR_INACTIVE_FILE) +
279 			  lruvec_page_state(lruvec, NR_ACTIVE_FILE);
280 
281 		if (lruvec->file_cost + lruvec->anon_cost > lrusize / 4) {
282 			lruvec->file_cost /= 2;
283 			lruvec->anon_cost /= 2;
284 		}
285 
286 		spin_unlock_irq(&lruvec->lru_lock);
287 		lruvec = parent_lruvec(lruvec);
288 		if (!lruvec)
289 			break;
290 		spin_lock_irq(&lruvec->lru_lock);
291 	}
292 }
293 
294 void lru_note_cost_refault(struct folio *folio)
295 {
296 	struct lruvec *lruvec;
297 
298 	lruvec = folio_lruvec_lock_irq(folio);
299 	lru_note_cost_unlock_irq(lruvec, folio_is_file_lru(folio),
300 				folio_nr_pages(folio), 0);
301 }
302 
303 static void lru_activate(struct lruvec *lruvec, struct folio *folio)
304 {
305 	long nr_pages = folio_nr_pages(folio);
306 
307 	if (folio_test_active(folio) || folio_test_unevictable(folio))
308 		return;
309 
310 
311 	lruvec_del_folio(lruvec, folio);
312 	folio_set_active(folio);
313 	lruvec_add_folio(lruvec, folio);
314 	trace_mm_lru_activate(folio);
315 
316 	__count_vm_events(PGACTIVATE, nr_pages);
317 	count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE, nr_pages);
318 }
319 
320 #ifdef CONFIG_SMP
321 static void folio_activate_drain(int cpu)
322 {
323 	struct folio_batch *fbatch = &per_cpu(cpu_fbatches.lru_activate, cpu);
324 
325 	if (folio_batch_count(fbatch))
326 		folio_batch_move_lru(fbatch, lru_activate);
327 }
328 
329 void folio_activate(struct folio *folio)
330 {
331 	if (folio_test_active(folio) || folio_test_unevictable(folio) ||
332 	    !folio_test_lru(folio))
333 		return;
334 
335 	folio_batch_add_and_move(folio, lru_activate);
336 }
337 
338 #else
339 static inline void folio_activate_drain(int cpu)
340 {
341 }
342 
343 void folio_activate(struct folio *folio)
344 {
345 	struct lruvec *lruvec;
346 
347 	if (!folio_test_clear_lru(folio))
348 		return;
349 
350 	lruvec = folio_lruvec_lock_irq(folio);
351 	lru_activate(lruvec, folio);
352 	unlock_page_lruvec_irq(lruvec);
353 	folio_set_lru(folio);
354 }
355 #endif
356 
357 static void __lru_cache_activate_folio(struct folio *folio)
358 {
359 	struct folio_batch *fbatch;
360 	int i;
361 
362 	local_lock(&cpu_fbatches.lock);
363 	fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
364 
365 	/*
366 	 * Search backwards on the optimistic assumption that the folio being
367 	 * activated has just been added to this batch. Note that only
368 	 * the local batch is examined as a !LRU folio could be in the
369 	 * process of being released, reclaimed, migrated or on a remote
370 	 * batch that is currently being drained. Furthermore, marking
371 	 * a remote batch's folio active potentially hits a race where
372 	 * a folio is marked active just after it is added to the inactive
373 	 * list causing accounting errors and BUG_ON checks to trigger.
374 	 */
375 	for (i = folio_batch_count(fbatch) - 1; i >= 0; i--) {
376 		struct folio *batch_folio = fbatch->folios[i];
377 
378 		if (batch_folio == folio) {
379 			folio_set_active(folio);
380 			break;
381 		}
382 	}
383 
384 	local_unlock(&cpu_fbatches.lock);
385 }
386 
387 #ifdef CONFIG_LRU_GEN
388 
389 static void lru_gen_inc_refs(struct folio *folio)
390 {
391 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags);
392 
393 	if (folio_test_unevictable(folio))
394 		return;
395 
396 	/* see the comment on LRU_REFS_FLAGS */
397 	if (!folio_test_referenced(folio)) {
398 		set_mask_bits(&folio->flags, LRU_REFS_MASK, BIT(PG_referenced));
399 		return;
400 	}
401 
402 	do {
403 		if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) {
404 			if (!folio_test_workingset(folio))
405 				folio_set_workingset(folio);
406 			return;
407 		}
408 
409 		new_flags = old_flags + BIT(LRU_REFS_PGOFF);
410 	} while (!try_cmpxchg(&folio->flags, &old_flags, new_flags));
411 }
412 
413 static bool lru_gen_clear_refs(struct folio *folio)
414 {
415 	struct lru_gen_folio *lrugen;
416 	int gen = folio_lru_gen(folio);
417 	int type = folio_is_file_lru(folio);
418 
419 	if (gen < 0)
420 		return true;
421 
422 	set_mask_bits(&folio->flags, LRU_REFS_FLAGS | BIT(PG_workingset), 0);
423 
424 	lrugen = &folio_lruvec(folio)->lrugen;
425 	/* whether can do without shuffling under the LRU lock */
426 	return gen == lru_gen_from_seq(READ_ONCE(lrugen->min_seq[type]));
427 }
428 
429 #else /* !CONFIG_LRU_GEN */
430 
431 static void lru_gen_inc_refs(struct folio *folio)
432 {
433 }
434 
435 static bool lru_gen_clear_refs(struct folio *folio)
436 {
437 	return false;
438 }
439 
440 #endif /* CONFIG_LRU_GEN */
441 
442 /**
443  * folio_mark_accessed - Mark a folio as having seen activity.
444  * @folio: The folio to mark.
445  *
446  * This function will perform one of the following transitions:
447  *
448  * * inactive,unreferenced	->	inactive,referenced
449  * * inactive,referenced	->	active,unreferenced
450  * * active,unreferenced	->	active,referenced
451  *
452  * When a newly allocated folio is not yet visible, so safe for non-atomic ops,
453  * __folio_set_referenced() may be substituted for folio_mark_accessed().
454  */
455 void folio_mark_accessed(struct folio *folio)
456 {
457 	if (folio_test_dropbehind(folio))
458 		return;
459 	if (lru_gen_enabled()) {
460 		lru_gen_inc_refs(folio);
461 		return;
462 	}
463 
464 	if (!folio_test_referenced(folio)) {
465 		folio_set_referenced(folio);
466 	} else if (folio_test_unevictable(folio)) {
467 		/*
468 		 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
469 		 * this list is never rotated or maintained, so marking an
470 		 * unevictable page accessed has no effect.
471 		 */
472 	} else if (!folio_test_active(folio)) {
473 		/*
474 		 * If the folio is on the LRU, queue it for activation via
475 		 * cpu_fbatches.lru_activate. Otherwise, assume the folio is in a
476 		 * folio_batch, mark it active and it'll be moved to the active
477 		 * LRU on the next drain.
478 		 */
479 		if (folio_test_lru(folio))
480 			folio_activate(folio);
481 		else
482 			__lru_cache_activate_folio(folio);
483 		folio_clear_referenced(folio);
484 		workingset_activation(folio);
485 	}
486 	if (folio_test_idle(folio))
487 		folio_clear_idle(folio);
488 }
489 EXPORT_SYMBOL(folio_mark_accessed);
490 
491 /**
492  * folio_add_lru - Add a folio to an LRU list.
493  * @folio: The folio to be added to the LRU.
494  *
495  * Queue the folio for addition to the LRU. The decision on whether
496  * to add the page to the [in]active [file|anon] list is deferred until the
497  * folio_batch is drained. This gives a chance for the caller of folio_add_lru()
498  * have the folio added to the active list using folio_mark_accessed().
499  */
500 void folio_add_lru(struct folio *folio)
501 {
502 	VM_BUG_ON_FOLIO(folio_test_active(folio) &&
503 			folio_test_unevictable(folio), folio);
504 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
505 
506 	/* see the comment in lru_gen_folio_seq() */
507 	if (lru_gen_enabled() && !folio_test_unevictable(folio) &&
508 	    lru_gen_in_fault() && !(current->flags & PF_MEMALLOC))
509 		folio_set_active(folio);
510 
511 	folio_batch_add_and_move(folio, lru_add);
512 }
513 EXPORT_SYMBOL(folio_add_lru);
514 
515 /**
516  * folio_add_lru_vma() - Add a folio to the appropate LRU list for this VMA.
517  * @folio: The folio to be added to the LRU.
518  * @vma: VMA in which the folio is mapped.
519  *
520  * If the VMA is mlocked, @folio is added to the unevictable list.
521  * Otherwise, it is treated the same way as folio_add_lru().
522  */
523 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
524 {
525 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
526 
527 	if (unlikely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED))
528 		mlock_new_folio(folio);
529 	else
530 		folio_add_lru(folio);
531 }
532 
533 /*
534  * If the folio cannot be invalidated, it is moved to the
535  * inactive list to speed up its reclaim.  It is moved to the
536  * head of the list, rather than the tail, to give the flusher
537  * threads some time to write it out, as this is much more
538  * effective than the single-page writeout from reclaim.
539  *
540  * If the folio isn't mapped and dirty/writeback, the folio
541  * could be reclaimed asap using the reclaim flag.
542  *
543  * 1. active, mapped folio -> none
544  * 2. active, dirty/writeback folio -> inactive, head, reclaim
545  * 3. inactive, mapped folio -> none
546  * 4. inactive, dirty/writeback folio -> inactive, head, reclaim
547  * 5. inactive, clean -> inactive, tail
548  * 6. Others -> none
549  *
550  * In 4, it moves to the head of the inactive list so the folio is
551  * written out by flusher threads as this is much more efficient
552  * than the single-page writeout from reclaim.
553  */
554 static void lru_deactivate_file(struct lruvec *lruvec, struct folio *folio)
555 {
556 	bool active = folio_test_active(folio) || lru_gen_enabled();
557 	long nr_pages = folio_nr_pages(folio);
558 
559 	if (folio_test_unevictable(folio))
560 		return;
561 
562 	/* Some processes are using the folio */
563 	if (folio_mapped(folio))
564 		return;
565 
566 	lruvec_del_folio(lruvec, folio);
567 	folio_clear_active(folio);
568 	folio_clear_referenced(folio);
569 
570 	if (folio_test_writeback(folio) || folio_test_dirty(folio)) {
571 		/*
572 		 * Setting the reclaim flag could race with
573 		 * folio_end_writeback() and confuse readahead.  But the
574 		 * race window is _really_ small and  it's not a critical
575 		 * problem.
576 		 */
577 		lruvec_add_folio(lruvec, folio);
578 		folio_set_reclaim(folio);
579 	} else {
580 		/*
581 		 * The folio's writeback ended while it was in the batch.
582 		 * We move that folio to the tail of the inactive list.
583 		 */
584 		lruvec_add_folio_tail(lruvec, folio);
585 		__count_vm_events(PGROTATED, nr_pages);
586 	}
587 
588 	if (active) {
589 		__count_vm_events(PGDEACTIVATE, nr_pages);
590 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
591 				     nr_pages);
592 	}
593 }
594 
595 static void lru_deactivate(struct lruvec *lruvec, struct folio *folio)
596 {
597 	long nr_pages = folio_nr_pages(folio);
598 
599 	if (folio_test_unevictable(folio) || !(folio_test_active(folio) || lru_gen_enabled()))
600 		return;
601 
602 	lruvec_del_folio(lruvec, folio);
603 	folio_clear_active(folio);
604 	folio_clear_referenced(folio);
605 	lruvec_add_folio(lruvec, folio);
606 
607 	__count_vm_events(PGDEACTIVATE, nr_pages);
608 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_pages);
609 }
610 
611 static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio)
612 {
613 	long nr_pages = folio_nr_pages(folio);
614 
615 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
616 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
617 		return;
618 
619 	lruvec_del_folio(lruvec, folio);
620 	folio_clear_active(folio);
621 	if (lru_gen_enabled())
622 		lru_gen_clear_refs(folio);
623 	else
624 		folio_clear_referenced(folio);
625 	/*
626 	 * Lazyfree folios are clean anonymous folios.  They have
627 	 * the swapbacked flag cleared, to distinguish them from normal
628 	 * anonymous folios
629 	 */
630 	folio_clear_swapbacked(folio);
631 	lruvec_add_folio(lruvec, folio);
632 
633 	__count_vm_events(PGLAZYFREE, nr_pages);
634 	count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE, nr_pages);
635 }
636 
637 /*
638  * Drain pages out of the cpu's folio_batch.
639  * Either "cpu" is the current CPU, and preemption has already been
640  * disabled; or "cpu" is being hot-unplugged, and is already dead.
641  */
642 void lru_add_drain_cpu(int cpu)
643 {
644 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
645 	struct folio_batch *fbatch = &fbatches->lru_add;
646 
647 	if (folio_batch_count(fbatch))
648 		folio_batch_move_lru(fbatch, lru_add);
649 
650 	fbatch = &fbatches->lru_move_tail;
651 	/* Disabling interrupts below acts as a compiler barrier. */
652 	if (data_race(folio_batch_count(fbatch))) {
653 		unsigned long flags;
654 
655 		/* No harm done if a racing interrupt already did this */
656 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
657 		folio_batch_move_lru(fbatch, lru_move_tail);
658 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
659 	}
660 
661 	fbatch = &fbatches->lru_deactivate_file;
662 	if (folio_batch_count(fbatch))
663 		folio_batch_move_lru(fbatch, lru_deactivate_file);
664 
665 	fbatch = &fbatches->lru_deactivate;
666 	if (folio_batch_count(fbatch))
667 		folio_batch_move_lru(fbatch, lru_deactivate);
668 
669 	fbatch = &fbatches->lru_lazyfree;
670 	if (folio_batch_count(fbatch))
671 		folio_batch_move_lru(fbatch, lru_lazyfree);
672 
673 	folio_activate_drain(cpu);
674 }
675 
676 /**
677  * deactivate_file_folio() - Deactivate a file folio.
678  * @folio: Folio to deactivate.
679  *
680  * This function hints to the VM that @folio is a good reclaim candidate,
681  * for example if its invalidation fails due to the folio being dirty
682  * or under writeback.
683  *
684  * Context: Caller holds a reference on the folio.
685  */
686 void deactivate_file_folio(struct folio *folio)
687 {
688 	/* Deactivating an unevictable folio will not accelerate reclaim */
689 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
690 		return;
691 
692 	if (lru_gen_enabled() && lru_gen_clear_refs(folio))
693 		return;
694 
695 	folio_batch_add_and_move(folio, lru_deactivate_file);
696 }
697 
698 /*
699  * folio_deactivate - deactivate a folio
700  * @folio: folio to deactivate
701  *
702  * folio_deactivate() moves @folio to the inactive list if @folio was on the
703  * active list and was not unevictable. This is done to accelerate the
704  * reclaim of @folio.
705  */
706 void folio_deactivate(struct folio *folio)
707 {
708 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
709 		return;
710 
711 	if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio))
712 		return;
713 
714 	folio_batch_add_and_move(folio, lru_deactivate);
715 }
716 
717 /**
718  * folio_mark_lazyfree - make an anon folio lazyfree
719  * @folio: folio to deactivate
720  *
721  * folio_mark_lazyfree() moves @folio to the inactive file list.
722  * This is done to accelerate the reclaim of @folio.
723  */
724 void folio_mark_lazyfree(struct folio *folio)
725 {
726 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
727 	    !folio_test_lru(folio) ||
728 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
729 		return;
730 
731 	folio_batch_add_and_move(folio, lru_lazyfree);
732 }
733 
734 void lru_add_drain(void)
735 {
736 	local_lock(&cpu_fbatches.lock);
737 	lru_add_drain_cpu(smp_processor_id());
738 	local_unlock(&cpu_fbatches.lock);
739 	mlock_drain_local();
740 }
741 
742 /*
743  * It's called from per-cpu workqueue context in SMP case so
744  * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
745  * the same cpu. It shouldn't be a problem in !SMP case since
746  * the core is only one and the locks will disable preemption.
747  */
748 static void lru_add_and_bh_lrus_drain(void)
749 {
750 	local_lock(&cpu_fbatches.lock);
751 	lru_add_drain_cpu(smp_processor_id());
752 	local_unlock(&cpu_fbatches.lock);
753 	invalidate_bh_lrus_cpu();
754 	mlock_drain_local();
755 }
756 
757 void lru_add_drain_cpu_zone(struct zone *zone)
758 {
759 	local_lock(&cpu_fbatches.lock);
760 	lru_add_drain_cpu(smp_processor_id());
761 	drain_local_pages(zone);
762 	local_unlock(&cpu_fbatches.lock);
763 	mlock_drain_local();
764 }
765 
766 #ifdef CONFIG_SMP
767 
768 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
769 
770 static void lru_add_drain_per_cpu(struct work_struct *dummy)
771 {
772 	lru_add_and_bh_lrus_drain();
773 }
774 
775 static bool cpu_needs_drain(unsigned int cpu)
776 {
777 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
778 
779 	/* Check these in order of likelihood that they're not zero */
780 	return folio_batch_count(&fbatches->lru_add) ||
781 		folio_batch_count(&fbatches->lru_move_tail) ||
782 		folio_batch_count(&fbatches->lru_deactivate_file) ||
783 		folio_batch_count(&fbatches->lru_deactivate) ||
784 		folio_batch_count(&fbatches->lru_lazyfree) ||
785 		folio_batch_count(&fbatches->lru_activate) ||
786 		need_mlock_drain(cpu) ||
787 		has_bh_in_lru(cpu, NULL);
788 }
789 
790 /*
791  * Doesn't need any cpu hotplug locking because we do rely on per-cpu
792  * kworkers being shut down before our page_alloc_cpu_dead callback is
793  * executed on the offlined cpu.
794  * Calling this function with cpu hotplug locks held can actually lead
795  * to obscure indirect dependencies via WQ context.
796  */
797 static inline void __lru_add_drain_all(bool force_all_cpus)
798 {
799 	/*
800 	 * lru_drain_gen - Global pages generation number
801 	 *
802 	 * (A) Definition: global lru_drain_gen = x implies that all generations
803 	 *     0 < n <= x are already *scheduled* for draining.
804 	 *
805 	 * This is an optimization for the highly-contended use case where a
806 	 * user space workload keeps constantly generating a flow of pages for
807 	 * each CPU.
808 	 */
809 	static unsigned int lru_drain_gen;
810 	static struct cpumask has_work;
811 	static DEFINE_MUTEX(lock);
812 	unsigned cpu, this_gen;
813 
814 	/*
815 	 * Make sure nobody triggers this path before mm_percpu_wq is fully
816 	 * initialized.
817 	 */
818 	if (WARN_ON(!mm_percpu_wq))
819 		return;
820 
821 	/*
822 	 * Guarantee folio_batch counter stores visible by this CPU
823 	 * are visible to other CPUs before loading the current drain
824 	 * generation.
825 	 */
826 	smp_mb();
827 
828 	/*
829 	 * (B) Locally cache global LRU draining generation number
830 	 *
831 	 * The read barrier ensures that the counter is loaded before the mutex
832 	 * is taken. It pairs with smp_mb() inside the mutex critical section
833 	 * at (D).
834 	 */
835 	this_gen = smp_load_acquire(&lru_drain_gen);
836 
837 	mutex_lock(&lock);
838 
839 	/*
840 	 * (C) Exit the draining operation if a newer generation, from another
841 	 * lru_add_drain_all(), was already scheduled for draining. Check (A).
842 	 */
843 	if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
844 		goto done;
845 
846 	/*
847 	 * (D) Increment global generation number
848 	 *
849 	 * Pairs with smp_load_acquire() at (B), outside of the critical
850 	 * section. Use a full memory barrier to guarantee that the
851 	 * new global drain generation number is stored before loading
852 	 * folio_batch counters.
853 	 *
854 	 * This pairing must be done here, before the for_each_online_cpu loop
855 	 * below which drains the page vectors.
856 	 *
857 	 * Let x, y, and z represent some system CPU numbers, where x < y < z.
858 	 * Assume CPU #z is in the middle of the for_each_online_cpu loop
859 	 * below and has already reached CPU #y's per-cpu data. CPU #x comes
860 	 * along, adds some pages to its per-cpu vectors, then calls
861 	 * lru_add_drain_all().
862 	 *
863 	 * If the paired barrier is done at any later step, e.g. after the
864 	 * loop, CPU #x will just exit at (C) and miss flushing out all of its
865 	 * added pages.
866 	 */
867 	WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
868 	smp_mb();
869 
870 	cpumask_clear(&has_work);
871 	for_each_online_cpu(cpu) {
872 		struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
873 
874 		if (cpu_needs_drain(cpu)) {
875 			INIT_WORK(work, lru_add_drain_per_cpu);
876 			queue_work_on(cpu, mm_percpu_wq, work);
877 			__cpumask_set_cpu(cpu, &has_work);
878 		}
879 	}
880 
881 	for_each_cpu(cpu, &has_work)
882 		flush_work(&per_cpu(lru_add_drain_work, cpu));
883 
884 done:
885 	mutex_unlock(&lock);
886 }
887 
888 void lru_add_drain_all(void)
889 {
890 	__lru_add_drain_all(false);
891 }
892 #else
893 void lru_add_drain_all(void)
894 {
895 	lru_add_drain();
896 }
897 #endif /* CONFIG_SMP */
898 
899 atomic_t lru_disable_count = ATOMIC_INIT(0);
900 
901 /*
902  * lru_cache_disable() needs to be called before we start compiling
903  * a list of folios to be migrated using folio_isolate_lru().
904  * It drains folios on LRU cache and then disable on all cpus until
905  * lru_cache_enable is called.
906  *
907  * Must be paired with a call to lru_cache_enable().
908  */
909 void lru_cache_disable(void)
910 {
911 	atomic_inc(&lru_disable_count);
912 	/*
913 	 * Readers of lru_disable_count are protected by either disabling
914 	 * preemption or rcu_read_lock:
915 	 *
916 	 * preempt_disable, local_irq_disable  [bh_lru_lock()]
917 	 * rcu_read_lock		       [rt_spin_lock CONFIG_PREEMPT_RT]
918 	 * preempt_disable		       [local_lock !CONFIG_PREEMPT_RT]
919 	 *
920 	 * Since v5.1 kernel, synchronize_rcu() is guaranteed to wait on
921 	 * preempt_disable() regions of code. So any CPU which sees
922 	 * lru_disable_count = 0 will have exited the critical
923 	 * section when synchronize_rcu() returns.
924 	 */
925 	synchronize_rcu_expedited();
926 #ifdef CONFIG_SMP
927 	__lru_add_drain_all(true);
928 #else
929 	lru_add_and_bh_lrus_drain();
930 #endif
931 }
932 
933 /**
934  * folios_put_refs - Reduce the reference count on a batch of folios.
935  * @folios: The folios.
936  * @refs: The number of refs to subtract from each folio.
937  *
938  * Like folio_put(), but for a batch of folios.  This is more efficient
939  * than writing the loop yourself as it will optimise the locks which need
940  * to be taken if the folios are freed.  The folios batch is returned
941  * empty and ready to be reused for another batch; there is no need
942  * to reinitialise it.  If @refs is NULL, we subtract one from each
943  * folio refcount.
944  *
945  * Context: May be called in process or interrupt context, but not in NMI
946  * context.  May be called while holding a spinlock.
947  */
948 void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
949 {
950 	int i, j;
951 	struct lruvec *lruvec = NULL;
952 	unsigned long flags = 0;
953 
954 	for (i = 0, j = 0; i < folios->nr; i++) {
955 		struct folio *folio = folios->folios[i];
956 		unsigned int nr_refs = refs ? refs[i] : 1;
957 
958 		if (is_huge_zero_folio(folio))
959 			continue;
960 
961 		if (folio_is_zone_device(folio)) {
962 			if (lruvec) {
963 				unlock_page_lruvec_irqrestore(lruvec, flags);
964 				lruvec = NULL;
965 			}
966 			if (folio_ref_sub_and_test(folio, nr_refs))
967 				free_zone_device_folio(folio);
968 			continue;
969 		}
970 
971 		if (!folio_ref_sub_and_test(folio, nr_refs))
972 			continue;
973 
974 		/* hugetlb has its own memcg */
975 		if (folio_test_hugetlb(folio)) {
976 			if (lruvec) {
977 				unlock_page_lruvec_irqrestore(lruvec, flags);
978 				lruvec = NULL;
979 			}
980 			free_huge_folio(folio);
981 			continue;
982 		}
983 		folio_unqueue_deferred_split(folio);
984 		__page_cache_release(folio, &lruvec, &flags);
985 
986 		if (j != i)
987 			folios->folios[j] = folio;
988 		j++;
989 	}
990 	if (lruvec)
991 		unlock_page_lruvec_irqrestore(lruvec, flags);
992 	if (!j) {
993 		folio_batch_reinit(folios);
994 		return;
995 	}
996 
997 	folios->nr = j;
998 	mem_cgroup_uncharge_folios(folios);
999 	free_unref_folios(folios);
1000 }
1001 EXPORT_SYMBOL(folios_put_refs);
1002 
1003 /**
1004  * release_pages - batched put_page()
1005  * @arg: array of pages to release
1006  * @nr: number of pages
1007  *
1008  * Decrement the reference count on all the pages in @arg.  If it
1009  * fell to zero, remove the page from the LRU and free it.
1010  *
1011  * Note that the argument can be an array of pages, encoded pages,
1012  * or folio pointers. We ignore any encoded bits, and turn any of
1013  * them into just a folio that gets free'd.
1014  */
1015 void release_pages(release_pages_arg arg, int nr)
1016 {
1017 	struct folio_batch fbatch;
1018 	int refs[PAGEVEC_SIZE];
1019 	struct encoded_page **encoded = arg.encoded_pages;
1020 	int i;
1021 
1022 	folio_batch_init(&fbatch);
1023 	for (i = 0; i < nr; i++) {
1024 		/* Turn any of the argument types into a folio */
1025 		struct folio *folio = page_folio(encoded_page_ptr(encoded[i]));
1026 
1027 		/* Is our next entry actually "nr_pages" -> "nr_refs" ? */
1028 		refs[fbatch.nr] = 1;
1029 		if (unlikely(encoded_page_flags(encoded[i]) &
1030 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
1031 			refs[fbatch.nr] = encoded_nr_pages(encoded[++i]);
1032 
1033 		if (folio_batch_add(&fbatch, folio) > 0)
1034 			continue;
1035 		folios_put_refs(&fbatch, refs);
1036 	}
1037 
1038 	if (fbatch.nr)
1039 		folios_put_refs(&fbatch, refs);
1040 }
1041 EXPORT_SYMBOL(release_pages);
1042 
1043 /*
1044  * The folios which we're about to release may be in the deferred lru-addition
1045  * queues.  That would prevent them from really being freed right now.  That's
1046  * OK from a correctness point of view but is inefficient - those folios may be
1047  * cache-warm and we want to give them back to the page allocator ASAP.
1048  *
1049  * So __folio_batch_release() will drain those queues here.
1050  * folio_batch_move_lru() calls folios_put() directly to avoid
1051  * mutual recursion.
1052  */
1053 void __folio_batch_release(struct folio_batch *fbatch)
1054 {
1055 	if (!fbatch->percpu_pvec_drained) {
1056 		lru_add_drain();
1057 		fbatch->percpu_pvec_drained = true;
1058 	}
1059 	folios_put(fbatch);
1060 }
1061 EXPORT_SYMBOL(__folio_batch_release);
1062 
1063 /**
1064  * folio_batch_remove_exceptionals() - Prune non-folios from a batch.
1065  * @fbatch: The batch to prune
1066  *
1067  * find_get_entries() fills a batch with both folios and shadow/swap/DAX
1068  * entries.  This function prunes all the non-folio entries from @fbatch
1069  * without leaving holes, so that it can be passed on to folio-only batch
1070  * operations.
1071  */
1072 void folio_batch_remove_exceptionals(struct folio_batch *fbatch)
1073 {
1074 	unsigned int i, j;
1075 
1076 	for (i = 0, j = 0; i < folio_batch_count(fbatch); i++) {
1077 		struct folio *folio = fbatch->folios[i];
1078 		if (!xa_is_value(folio))
1079 			fbatch->folios[j++] = folio;
1080 	}
1081 	fbatch->nr = j;
1082 }
1083 
1084 static const struct ctl_table swap_sysctl_table[] = {
1085 	{
1086 		.procname	= "page-cluster",
1087 		.data		= &page_cluster,
1088 		.maxlen		= sizeof(int),
1089 		.mode		= 0644,
1090 		.proc_handler	= proc_dointvec_minmax,
1091 		.extra1		= SYSCTL_ZERO,
1092 		.extra2		= (void *)&page_cluster_max,
1093 	}
1094 };
1095 
1096 /*
1097  * Perform any setup for the swap system
1098  */
1099 void __init swap_setup(void)
1100 {
1101 	unsigned long megs = totalram_pages() >> (20 - PAGE_SHIFT);
1102 
1103 	/* Use a smaller cluster for small-memory machines */
1104 	if (megs < 16)
1105 		page_cluster = 2;
1106 	else
1107 		page_cluster = 3;
1108 	/*
1109 	 * Right now other parts of the system means that we
1110 	 * _really_ don't want to cluster much more
1111 	 */
1112 
1113 	register_sysctl_init("vm", swap_sysctl_table);
1114 }
1115