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