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