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