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