xref: /linux/mm/folio.c (revision 1b78070aaef63512688aebfbc82365ef9d6660f1)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/folio.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  */
7 
8 /*
9  * Folio LRU helpers: add/remove folios from LRU lists, batching,
10  * activation/deactivation, and page cache release paths.
11  */
12 
13 #include <linux/mm.h>
14 #include <linux/sched.h>
15 #include <linux/kernel_stat.h>
16 #include <linux/swap.h>
17 #include <linux/mman.h>
18 #include <linux/pagemap.h>
19 #include <linux/folio_batch.h>
20 #include <linux/init.h>
21 #include <linux/export.h>
22 #include <linux/mm_inline.h>
23 #include <linux/percpu_counter.h>
24 #include <linux/memremap.h>
25 #include <linux/percpu.h>
26 #include <linux/cpu.h>
27 #include <linux/notifier.h>
28 #include <linux/backing-dev.h>
29 #include <linux/memcontrol.h>
30 #include <linux/gfp.h>
31 #include <linux/uio.h>
32 #include <linux/hugetlb.h>
33 #include <linux/page_idle.h>
34 #include <linux/local_lock.h>
35 #include <linux/buffer_head.h>
36 
37 #include "internal.h"
38 #include "page_alloc.h"
39 
40 #define CREATE_TRACE_POINTS
41 #include <trace/events/pagemap.h>
42 
43 struct cpu_fbatches {
44 	/*
45 	 * The following folio batches are grouped together because they are protected
46 	 * by disabling preemption (and interrupts remain enabled).
47 	 */
48 	local_lock_t lock;
49 	struct folio_batch lru_add;
50 	struct folio_batch lru_deactivate_file;
51 	struct folio_batch lru_deactivate;
52 	struct folio_batch lru_lazyfree;
53 #ifdef CONFIG_SMP
54 	struct folio_batch lru_activate;
55 #endif
56 	/* Protecting the following batches which require disabling interrupts */
57 	local_lock_t lock_irq;
58 	struct folio_batch lru_move_tail;
59 };
60 
61 static DEFINE_PER_CPU(struct cpu_fbatches, cpu_fbatches) = {
62 	.lock = INIT_LOCAL_LOCK(lock),
63 	.lock_irq = INIT_LOCAL_LOCK(lock_irq),
64 };
65 
66 static void __page_cache_release(struct folio *folio, struct lruvec **lruvecp,
67 		unsigned long *flagsp)
68 {
69 	if (folio_test_lru(folio)) {
70 		folio_lruvec_relock_irqsave(folio, lruvecp, flagsp);
71 		lruvec_del_folio(*lruvecp, folio);
72 		__folio_clear_lru_flags(folio);
73 	}
74 }
75 
76 /*
77  * This path almost never happens for VM activity - pages are normally freed
78  * in batches.  But it gets used by networking - and for compound pages.
79  */
80 static void page_cache_release(struct folio *folio)
81 {
82 	struct lruvec *lruvec = NULL;
83 	unsigned long flags;
84 
85 	__page_cache_release(folio, &lruvec, &flags);
86 	if (lruvec)
87 		lruvec_unlock_irqrestore(lruvec, flags);
88 }
89 
90 void __folio_put(struct folio *folio)
91 {
92 	if (unlikely(folio_is_zone_device(folio))) {
93 		free_zone_device_folio(folio);
94 		return;
95 	}
96 
97 	if (folio_test_hugetlb(folio)) {
98 		free_huge_folio(folio);
99 		return;
100 	}
101 
102 	page_cache_release(folio);
103 	folio_unqueue_deferred_split(folio);
104 	mem_cgroup_uncharge(folio);
105 	free_frozen_pages(&folio->page, folio_order(folio));
106 }
107 EXPORT_SYMBOL(__folio_put);
108 
109 typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio);
110 
111 static void lru_add(struct lruvec *lruvec, struct folio *folio)
112 {
113 	int was_unevictable = folio_test_clear_unevictable(folio);
114 	long nr_pages = folio_nr_pages(folio);
115 
116 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
117 
118 	/*
119 	 * Is an smp_mb__after_atomic() still required here, before
120 	 * folio_evictable() tests the mlocked flag, to rule out the possibility
121 	 * of stranding an evictable folio on an unevictable LRU?  I think
122 	 * not, because __munlock_folio() only clears the mlocked flag
123 	 * while the LRU lock is held.
124 	 *
125 	 * (That is not true of __page_cache_release(), and not necessarily
126 	 * true of folios_put(): but those only clear the mlocked flag after
127 	 * folio_put_testzero() has excluded any other users of the folio.)
128 	 */
129 	if (folio_evictable(folio)) {
130 		if (was_unevictable)
131 			__count_vm_events(UNEVICTABLE_PGRESCUED, nr_pages);
132 	} else {
133 		folio_clear_active(folio);
134 		folio_set_unevictable(folio);
135 		/*
136 		 * folio->mlock_count = !!folio_test_mlocked(folio)?
137 		 * But that leaves __mlock_folio() in doubt whether another
138 		 * actor has already counted the mlock or not.  Err on the
139 		 * safe side, underestimate, let page reclaim fix it, rather
140 		 * than leaving a page on the unevictable LRU indefinitely.
141 		 */
142 		folio->mlock_count = 0;
143 		if (!was_unevictable)
144 			__count_vm_events(UNEVICTABLE_PGCULLED, nr_pages);
145 	}
146 
147 	lruvec_add_folio(lruvec, folio);
148 	trace_mm_lru_insertion(folio);
149 }
150 
151 static void folio_batch_move_lru(struct folio_batch *fbatch, move_fn_t move_fn)
152 {
153 	int i;
154 	struct lruvec *lruvec = NULL;
155 	unsigned long flags = 0;
156 	struct folio_batch free_fbatch;
157 	bool is_lru_add = (move_fn == lru_add);
158 
159 	/*
160 	 * If we're adding to the LRU, preemptively filter dead folios. Use
161 	 * this dedicated folio batch for temp storage and deferred cleanup.
162 	 */
163 	if (is_lru_add)
164 		folio_batch_init(&free_fbatch);
165 
166 	for (i = 0; i < folio_batch_count(fbatch); i++) {
167 		struct folio *folio = fbatch->folios[i];
168 
169 		/* block memcg migration while the folio moves between lru */
170 		if (!is_lru_add && !folio_test_clear_lru(folio))
171 			continue;
172 
173 		/*
174 		 * Filter dead folios by moving them from the add batch to the temp
175 		 * batch for freeing after this loop.
176 		 *
177 		 * We're bypassing normal cleanup. Clear flags that are not
178 		 * applicable to dead folios.
179 		 *
180 		 * Since the folio may be part of a huge page, unqueue from
181 		 * deferred split list to avoid a dangling list entry.
182 		 */
183 		if (is_lru_add && folio_ref_freeze(folio, 1)) {
184 			__folio_clear_active(folio);
185 			__folio_clear_unevictable(folio);
186 			folio_unqueue_deferred_split(folio);
187 			fbatch->folios[i] = NULL;
188 			folio_batch_add(&free_fbatch, folio);
189 			continue;
190 		}
191 
192 		folio_lruvec_relock_irqsave(folio, &lruvec, &flags);
193 		move_fn(lruvec, folio);
194 
195 		folio_set_lru(folio);
196 	}
197 
198 	if (lruvec)
199 		lruvec_unlock_irqrestore(lruvec, flags);
200 
201 	/* Cleanup filtered dead folios. */
202 	if (is_lru_add) {
203 		mem_cgroup_uncharge_folios(&free_fbatch);
204 		free_unref_folios(&free_fbatch);
205 	}
206 
207 	folios_put(fbatch);
208 }
209 
210 static void __folio_batch_add_and_move(struct folio_batch __percpu *fbatch,
211 		struct folio *folio, move_fn_t move_fn, bool disable_irq)
212 {
213 	unsigned long flags;
214 
215 	folio_get(folio);
216 
217 	if (disable_irq)
218 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
219 	else
220 		local_lock(&cpu_fbatches.lock);
221 
222 	if (!folio_batch_add(this_cpu_ptr(fbatch), folio) ||
223 			!folio_may_be_lru_cached(folio) || lru_cache_disabled())
224 		folio_batch_move_lru(this_cpu_ptr(fbatch), move_fn);
225 
226 	if (disable_irq)
227 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
228 	else
229 		local_unlock(&cpu_fbatches.lock);
230 }
231 
232 #define folio_batch_add_and_move(folio, op)		\
233 	__folio_batch_add_and_move(			\
234 		&cpu_fbatches.op,			\
235 		folio,					\
236 		op,					\
237 		offsetof(struct cpu_fbatches, op) >=	\
238 		offsetof(struct cpu_fbatches, lock_irq)	\
239 	)
240 
241 static void lru_move_tail(struct lruvec *lruvec, struct folio *folio)
242 {
243 	if (folio_test_unevictable(folio))
244 		return;
245 
246 	lruvec_del_folio(lruvec, folio);
247 	folio_clear_active(folio);
248 	lruvec_add_folio_tail(lruvec, folio);
249 	__count_vm_events(PGROTATED, folio_nr_pages(folio));
250 }
251 
252 /*
253  * Writeback is about to end against a folio which has been marked for
254  * immediate reclaim.  If it still appears to be reclaimable, move it
255  * to the tail of the inactive list.
256  *
257  * folio_rotate_reclaimable() must disable IRQs, to prevent nasty races.
258  */
259 void folio_rotate_reclaimable(struct folio *folio)
260 {
261 	if (folio_test_locked(folio) || folio_test_dirty(folio) ||
262 	    folio_test_unevictable(folio) || !folio_test_lru(folio))
263 		return;
264 
265 	folio_batch_add_and_move(folio, lru_move_tail);
266 }
267 
268 static void lru_activate(struct lruvec *lruvec, struct folio *folio)
269 {
270 	long nr_pages = folio_nr_pages(folio);
271 
272 	if (folio_test_active(folio) || folio_test_unevictable(folio))
273 		return;
274 
275 
276 	lruvec_del_folio(lruvec, folio);
277 	folio_set_active(folio);
278 	lruvec_add_folio(lruvec, folio);
279 	trace_mm_lru_activate(folio);
280 
281 	__count_vm_events(PGACTIVATE, nr_pages);
282 	count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE, nr_pages);
283 }
284 
285 #ifdef CONFIG_SMP
286 static void folio_activate_drain(int cpu)
287 {
288 	struct folio_batch *fbatch = &per_cpu(cpu_fbatches.lru_activate, cpu);
289 
290 	if (folio_batch_count(fbatch))
291 		folio_batch_move_lru(fbatch, lru_activate);
292 }
293 
294 void folio_activate(struct folio *folio)
295 {
296 	if (folio_test_active(folio) || folio_test_unevictable(folio) ||
297 	    !folio_test_lru(folio))
298 		return;
299 
300 	folio_batch_add_and_move(folio, lru_activate);
301 }
302 
303 #else
304 static inline void folio_activate_drain(int cpu)
305 {
306 }
307 
308 void folio_activate(struct folio *folio)
309 {
310 	struct lruvec *lruvec;
311 
312 	if (!folio_test_clear_lru(folio))
313 		return;
314 
315 	lruvec = folio_lruvec_lock_irq(folio);
316 	lru_activate(lruvec, folio);
317 	lruvec_unlock_irq(lruvec);
318 	folio_set_lru(folio);
319 }
320 #endif
321 
322 static void __lru_cache_activate_folio(struct folio *folio)
323 {
324 	struct folio_batch *fbatch;
325 	int i;
326 
327 	local_lock(&cpu_fbatches.lock);
328 	fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
329 
330 	/*
331 	 * Search backwards on the optimistic assumption that the folio being
332 	 * activated has just been added to this batch. Note that only
333 	 * the local batch is examined as a !LRU folio could be in the
334 	 * process of being released, reclaimed, migrated or on a remote
335 	 * batch that is currently being drained. Furthermore, marking
336 	 * a remote batch's folio active potentially hits a race where
337 	 * a folio is marked active just after it is added to the inactive
338 	 * list causing accounting errors and BUG_ON checks to trigger.
339 	 */
340 	for (i = folio_batch_count(fbatch) - 1; i >= 0; i--) {
341 		struct folio *batch_folio = fbatch->folios[i];
342 
343 		if (batch_folio == folio) {
344 			folio_set_active(folio);
345 			break;
346 		}
347 	}
348 
349 	local_unlock(&cpu_fbatches.lock);
350 }
351 
352 #ifdef CONFIG_LRU_GEN
353 
354 static void lru_gen_inc_refs(struct folio *folio)
355 {
356 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f);
357 
358 	if (folio_test_unevictable(folio))
359 		return;
360 
361 	/* see the comment on LRU_REFS_FLAGS */
362 	if (!folio_test_referenced(folio)) {
363 		set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced));
364 		return;
365 	}
366 
367 	do {
368 		if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) {
369 			if (!folio_test_workingset(folio))
370 				folio_set_workingset(folio);
371 			return;
372 		}
373 
374 		new_flags = old_flags + BIT(LRU_REFS_PGOFF);
375 	} while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags));
376 }
377 
378 static bool lru_gen_clear_refs(struct folio *folio)
379 {
380 	int gen = folio_lru_gen(folio);
381 	int type = folio_is_file_lru(folio);
382 	unsigned long seq;
383 
384 	if (gen < 0)
385 		return true;
386 
387 	set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0);
388 
389 	rcu_read_lock();
390 	seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]);
391 	rcu_read_unlock();
392 	/* whether can do without shuffling under the LRU lock */
393 	return gen == lru_gen_from_seq(seq);
394 }
395 
396 #else /* !CONFIG_LRU_GEN */
397 
398 static void lru_gen_inc_refs(struct folio *folio)
399 {
400 }
401 
402 static bool lru_gen_clear_refs(struct folio *folio)
403 {
404 	return false;
405 }
406 
407 #endif /* CONFIG_LRU_GEN */
408 
409 /**
410  * folio_mark_accessed - Mark a folio as having seen activity.
411  * @folio: The folio to mark.
412  *
413  * This function will perform one of the following transitions:
414  *
415  * * inactive,unreferenced	->	inactive,referenced
416  * * inactive,referenced	->	active,unreferenced
417  * * active,unreferenced	->	active,referenced
418  *
419  * When a newly allocated folio is not yet visible, so safe for non-atomic ops,
420  * __folio_set_referenced() may be substituted for folio_mark_accessed().
421  */
422 void folio_mark_accessed(struct folio *folio)
423 {
424 	if (folio_test_dropbehind(folio))
425 		return;
426 	if (lru_gen_enabled()) {
427 		lru_gen_inc_refs(folio);
428 		return;
429 	}
430 
431 	if (!folio_test_referenced(folio)) {
432 		folio_set_referenced(folio);
433 	} else if (folio_test_unevictable(folio)) {
434 		/*
435 		 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
436 		 * this list is never rotated or maintained, so marking an
437 		 * unevictable page accessed has no effect.
438 		 */
439 	} else if (!folio_test_active(folio)) {
440 		/*
441 		 * If the folio is on the LRU, queue it for activation via
442 		 * cpu_fbatches.lru_activate. Otherwise, assume the folio is in a
443 		 * folio_batch, mark it active and it'll be moved to the active
444 		 * LRU on the next drain.
445 		 */
446 		if (folio_test_lru(folio))
447 			folio_activate(folio);
448 		else
449 			__lru_cache_activate_folio(folio);
450 		folio_clear_referenced(folio);
451 		workingset_activation(folio);
452 	}
453 	if (folio_test_idle(folio))
454 		folio_clear_idle(folio);
455 }
456 EXPORT_SYMBOL(folio_mark_accessed);
457 
458 /**
459  * folio_add_lru - Add a folio to an LRU list.
460  * @folio: The folio to be added to the LRU.
461  *
462  * Queue the folio for addition to the LRU. The decision on whether
463  * to add the page to the [in]active [file|anon] list is deferred until the
464  * folio_batch is drained. This gives a chance for the caller of folio_add_lru()
465  * have the folio added to the active list using folio_mark_accessed().
466  */
467 void folio_add_lru(struct folio *folio)
468 {
469 	VM_BUG_ON_FOLIO(folio_test_active(folio) &&
470 			folio_test_unevictable(folio), folio);
471 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
472 
473 	/*
474 	 * For refaulted workingset folios, set PG_active so they
475 	 * can be added to active generations.
476 	 * For prefaulted file folios, folio_mark_accessed() sets
477 	 * PG_referenced so lru_gen_folio_seq() places them into
478 	 * the second oldest generation.
479 	 */
480 	if (lru_gen_enabled() && !folio_test_unevictable(folio) &&
481 	    lru_gen_in_fault() && !(current->flags & PF_MEMALLOC)) {
482 		if (folio_test_workingset(folio))
483 			folio_set_active(folio);
484 		else if (!folio_test_referenced(folio))
485 			folio_mark_accessed(folio);
486 	}
487 
488 	folio_batch_add_and_move(folio, lru_add);
489 }
490 EXPORT_SYMBOL(folio_add_lru);
491 
492 /**
493  * folio_add_lru_vma() - Add a folio to the appropriate LRU list for this VMA.
494  * @folio: The folio to be added to the LRU.
495  * @vma: VMA in which the folio is mapped.
496  *
497  * If the VMA is mlocked, @folio is added to the unevictable list.
498  * Otherwise, it is treated the same way as folio_add_lru().
499  */
500 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
501 {
502 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
503 
504 	if (unlikely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED))
505 		mlock_new_folio(folio);
506 	else
507 		folio_add_lru(folio);
508 }
509 
510 /*
511  * If the folio cannot be invalidated, it is moved to the
512  * inactive list to speed up its reclaim.  It is moved to the
513  * head of the list, rather than the tail, to give the flusher
514  * threads some time to write it out, as this is much more
515  * effective than the single-page writeout from reclaim.
516  *
517  * If the folio isn't mapped and dirty/writeback, the folio
518  * could be reclaimed asap using the reclaim flag.
519  *
520  * 1. active, mapped folio -> none
521  * 2. active, dirty/writeback folio -> inactive, head, reclaim
522  * 3. inactive, mapped folio -> none
523  * 4. inactive, dirty/writeback folio -> inactive, head, reclaim
524  * 5. inactive, clean -> inactive, tail
525  * 6. Others -> none
526  *
527  * In 4, it moves to the head of the inactive list so the folio is
528  * written out by flusher threads as this is much more efficient
529  * than the single-page writeout from reclaim.
530  */
531 static void lru_deactivate_file(struct lruvec *lruvec, struct folio *folio)
532 {
533 	bool active = folio_test_active(folio) || lru_gen_enabled();
534 	long nr_pages = folio_nr_pages(folio);
535 
536 	if (folio_test_unevictable(folio))
537 		return;
538 
539 	/* Some processes are using the folio */
540 	if (folio_mapped(folio))
541 		return;
542 
543 	lruvec_del_folio(lruvec, folio);
544 	folio_clear_active(folio);
545 	folio_clear_referenced(folio);
546 
547 	if (folio_test_writeback(folio) || folio_test_dirty(folio)) {
548 		/*
549 		 * Setting the reclaim flag could race with
550 		 * folio_end_writeback() and confuse readahead.  But the
551 		 * race window is _really_ small and  it's not a critical
552 		 * problem.
553 		 */
554 		lruvec_add_folio(lruvec, folio);
555 		folio_set_reclaim(folio);
556 	} else {
557 		/*
558 		 * The folio's writeback ended while it was in the batch.
559 		 * We move that folio to the tail of the inactive list.
560 		 */
561 		lruvec_add_folio_tail(lruvec, folio);
562 		__count_vm_events(PGROTATED, nr_pages);
563 	}
564 
565 	if (active) {
566 		__count_vm_events(PGDEACTIVATE, nr_pages);
567 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
568 				     nr_pages);
569 	}
570 }
571 
572 static void lru_deactivate(struct lruvec *lruvec, struct folio *folio)
573 {
574 	long nr_pages = folio_nr_pages(folio);
575 
576 	if (folio_test_unevictable(folio) || !(folio_test_active(folio) || lru_gen_enabled()))
577 		return;
578 
579 	lruvec_del_folio(lruvec, folio);
580 	folio_clear_active(folio);
581 	folio_clear_referenced(folio);
582 	lruvec_add_folio(lruvec, folio);
583 
584 	__count_vm_events(PGDEACTIVATE, nr_pages);
585 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_pages);
586 }
587 
588 static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio)
589 {
590 	long nr_pages = folio_nr_pages(folio);
591 
592 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
593 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
594 		return;
595 
596 	lruvec_del_folio(lruvec, folio);
597 	folio_clear_active(folio);
598 	if (lru_gen_enabled())
599 		lru_gen_clear_refs(folio);
600 	else
601 		folio_clear_referenced(folio);
602 	/*
603 	 * Lazyfree folios are clean anonymous folios.  They have
604 	 * the swapbacked flag cleared, to distinguish them from normal
605 	 * anonymous folios
606 	 */
607 	folio_clear_swapbacked(folio);
608 	lruvec_add_folio(lruvec, folio);
609 
610 	__count_vm_events(PGLAZYFREE, nr_pages);
611 	count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE, nr_pages);
612 }
613 
614 /*
615  * Drain pages out of the cpu's folio_batch.
616  * Either "cpu" is the current CPU, and preemption has already been
617  * disabled; or "cpu" is being hot-unplugged, and is already dead.
618  */
619 void lru_add_drain_cpu(int cpu)
620 {
621 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
622 	struct folio_batch *fbatch = &fbatches->lru_add;
623 	unsigned int nr_folios = folio_batch_count(fbatch);
624 
625 	if (nr_folios) {
626 		folio_batch_move_lru(fbatch, lru_add);
627 		trace_mm_lru_add_drain_tp(cpu, nr_folios);
628 	}
629 
630 	fbatch = &fbatches->lru_move_tail;
631 	/* Disabling interrupts below acts as a compiler barrier. */
632 	if (data_race(folio_batch_count(fbatch))) {
633 		unsigned long flags;
634 
635 		/* No harm done if a racing interrupt already did this */
636 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
637 		folio_batch_move_lru(fbatch, lru_move_tail);
638 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
639 	}
640 
641 	fbatch = &fbatches->lru_deactivate_file;
642 	if (folio_batch_count(fbatch))
643 		folio_batch_move_lru(fbatch, lru_deactivate_file);
644 
645 	fbatch = &fbatches->lru_deactivate;
646 	if (folio_batch_count(fbatch))
647 		folio_batch_move_lru(fbatch, lru_deactivate);
648 
649 	fbatch = &fbatches->lru_lazyfree;
650 	if (folio_batch_count(fbatch))
651 		folio_batch_move_lru(fbatch, lru_lazyfree);
652 
653 	folio_activate_drain(cpu);
654 }
655 
656 /**
657  * deactivate_file_folio() - Deactivate a file folio.
658  * @folio: Folio to deactivate.
659  *
660  * This function hints to the VM that @folio is a good reclaim candidate,
661  * for example if its invalidation fails due to the folio being dirty
662  * or under writeback.
663  *
664  * Context: Caller holds a reference on the folio.
665  */
666 void deactivate_file_folio(struct folio *folio)
667 {
668 	/* Deactivating an unevictable folio will not accelerate reclaim */
669 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
670 		return;
671 
672 	if (lru_gen_enabled() && lru_gen_clear_refs(folio))
673 		return;
674 
675 	folio_batch_add_and_move(folio, lru_deactivate_file);
676 }
677 
678 /*
679  * folio_deactivate - deactivate a folio
680  * @folio: folio to deactivate
681  *
682  * folio_deactivate() moves @folio to the inactive list if @folio was on the
683  * active list and was not unevictable. This is done to accelerate the
684  * reclaim of @folio.
685  */
686 void folio_deactivate(struct folio *folio)
687 {
688 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
689 		return;
690 
691 	if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio))
692 		return;
693 
694 	folio_batch_add_and_move(folio, lru_deactivate);
695 }
696 
697 /**
698  * folio_mark_lazyfree - make an anon folio lazyfree
699  * @folio: folio to deactivate
700  *
701  * folio_mark_lazyfree() moves @folio to the inactive file list.
702  * This is done to accelerate the reclaim of @folio.
703  */
704 void folio_mark_lazyfree(struct folio *folio)
705 {
706 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
707 	    !folio_test_lru(folio) ||
708 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
709 		return;
710 
711 	folio_batch_add_and_move(folio, lru_lazyfree);
712 }
713 
714 void lru_add_drain(void)
715 {
716 	local_lock(&cpu_fbatches.lock);
717 	lru_add_drain_cpu(smp_processor_id());
718 	local_unlock(&cpu_fbatches.lock);
719 	mlock_drain_local();
720 }
721 
722 /*
723  * It's called from per-cpu workqueue context in SMP case so
724  * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
725  * the same cpu. It shouldn't be a problem in !SMP case since
726  * the core is only one and the locks will disable preemption.
727  */
728 static void lru_add_and_bh_lrus_drain(void)
729 {
730 	local_lock(&cpu_fbatches.lock);
731 	lru_add_drain_cpu(smp_processor_id());
732 	local_unlock(&cpu_fbatches.lock);
733 	invalidate_bh_lrus_cpu();
734 	mlock_drain_local();
735 }
736 
737 void lru_add_drain_cpu_zone(struct zone *zone)
738 {
739 	local_lock(&cpu_fbatches.lock);
740 	lru_add_drain_cpu(smp_processor_id());
741 	drain_local_pages(zone);
742 	local_unlock(&cpu_fbatches.lock);
743 	mlock_drain_local();
744 }
745 
746 #ifdef CONFIG_SMP
747 
748 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
749 
750 static void lru_add_drain_per_cpu(struct work_struct *dummy)
751 {
752 	lru_add_and_bh_lrus_drain();
753 }
754 
755 static bool cpu_needs_drain(unsigned int cpu)
756 {
757 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
758 
759 	/* Check these in order of likelihood that they're not zero */
760 	return data_race(folio_batch_count(&fbatches->lru_add) ||
761 			 folio_batch_count(&fbatches->lru_move_tail) ||
762 			 folio_batch_count(&fbatches->lru_deactivate_file) ||
763 			 folio_batch_count(&fbatches->lru_deactivate) ||
764 			 folio_batch_count(&fbatches->lru_lazyfree) ||
765 			 folio_batch_count(&fbatches->lru_activate) ||
766 			 need_mlock_drain(cpu)) ||
767 		has_bh_in_lru(cpu, NULL);
768 }
769 
770 /*
771  * Doesn't need any cpu hotplug locking because we do rely on per-cpu
772  * kworkers being shut down before our page_alloc_cpu_dead callback is
773  * executed on the offlined cpu.
774  * Calling this function with cpu hotplug locks held can actually lead
775  * to obscure indirect dependencies via WQ context.
776  */
777 static inline void __lru_add_drain_all(bool force_all_cpus)
778 {
779 	/*
780 	 * lru_drain_gen - Global pages generation number
781 	 *
782 	 * (A) Definition: global lru_drain_gen = x implies that all generations
783 	 *     0 < n <= x are already *scheduled* for draining.
784 	 *
785 	 * This is an optimization for the highly-contended use case where a
786 	 * user space workload keeps constantly generating a flow of pages for
787 	 * each CPU.
788 	 */
789 	static unsigned int lru_drain_gen;
790 	static struct cpumask has_work;
791 	static DEFINE_MUTEX(lock);
792 	unsigned cpu, this_gen;
793 
794 	/*
795 	 * Make sure nobody triggers this path before mm_percpu_wq is fully
796 	 * initialized.
797 	 */
798 	if (WARN_ON(!mm_percpu_wq))
799 		return;
800 
801 	trace_mm_lru_add_drain_all_tp(force_all_cpus);
802 
803 	/*
804 	 * Guarantee folio_batch counter stores visible by this CPU
805 	 * are visible to other CPUs before loading the current drain
806 	 * generation.
807 	 */
808 	smp_mb();
809 
810 	/*
811 	 * (B) Locally cache global LRU draining generation number
812 	 *
813 	 * The read barrier ensures that the counter is loaded before the mutex
814 	 * is taken. It pairs with smp_mb() inside the mutex critical section
815 	 * at (D).
816 	 */
817 	this_gen = smp_load_acquire(&lru_drain_gen);
818 
819 	/* It helps everyone if we do our own local drain immediately. */
820 	lru_add_drain();
821 
822 	mutex_lock(&lock);
823 
824 	/*
825 	 * (C) Exit the draining operation if a newer generation, from another
826 	 * lru_add_drain_all(), was already scheduled for draining. Check (A).
827 	 */
828 	if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
829 		goto done;
830 
831 	/*
832 	 * (D) Increment global generation number
833 	 *
834 	 * Pairs with smp_load_acquire() at (B), outside of the critical
835 	 * section. Use a full memory barrier to guarantee that the
836 	 * new global drain generation number is stored before loading
837 	 * folio_batch counters.
838 	 *
839 	 * This pairing must be done here, before the for_each_online_cpu loop
840 	 * below which drains the page vectors.
841 	 *
842 	 * Let x, y, and z represent some system CPU numbers, where x < y < z.
843 	 * Assume CPU #z is in the middle of the for_each_online_cpu loop
844 	 * below and has already reached CPU #y's per-cpu data. CPU #x comes
845 	 * along, adds some pages to its per-cpu vectors, then calls
846 	 * lru_add_drain_all().
847 	 *
848 	 * If the paired barrier is done at any later step, e.g. after the
849 	 * loop, CPU #x will just exit at (C) and miss flushing out all of its
850 	 * added pages.
851 	 */
852 	WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
853 	smp_mb();
854 
855 	cpumask_clear(&has_work);
856 	for_each_online_cpu(cpu) {
857 		struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
858 
859 		if (cpu_needs_drain(cpu)) {
860 			INIT_WORK(work, lru_add_drain_per_cpu);
861 			queue_work_on(cpu, mm_percpu_wq, work);
862 			__cpumask_set_cpu(cpu, &has_work);
863 		}
864 	}
865 
866 	for_each_cpu(cpu, &has_work)
867 		flush_work(&per_cpu(lru_add_drain_work, cpu));
868 
869 done:
870 	mutex_unlock(&lock);
871 }
872 
873 void lru_add_drain_all(void)
874 {
875 	__lru_add_drain_all(false);
876 }
877 #else
878 void lru_add_drain_all(void)
879 {
880 	lru_add_drain();
881 }
882 #endif /* CONFIG_SMP */
883 
884 /**
885  * lru_cache_drain_for_folio() - drain LRU caches if the caches might hold
886  *				 folio references
887  * @folio: The folio.
888  * @extra_refs: Extra folio references held by the caller.
889  * @drained: Drain status for batch folio processing.
890  *
891  * Drain LRU caches if the caches might hold folio references. Start
892  * with a local LRU cache drain, to then drain LRU caches on all CPUs if
893  * local draining was insufficient.
894  *
895  * This function detects LRU cache references by comparing the folio refcount
896  * with the sum of the expected folio refcount + extra references held by the
897  * caller. Note that we cannot rely on PG_lru to reliably detect all LRU
898  * cache references, and there are rare scenarios (concurrent folio (un)mapping)
899  * where this function might miss detecting LRU cache references.
900  *
901  * If @drained is not NULL, the function will avoid re-draining LRU caches
902  * when processing multiple folios in a row. In that case, the variable
903  * @drained points at must be initialized to LRU_CACHE_NOT_DRAINED before
904  * the first invocation by the caller.
905  */
906 void lru_cache_drain_for_folio(const struct folio *folio,
907 		unsigned int extra_refs, enum lru_cache_drained *drained)
908 {
909 	if (!folio_may_be_lru_cached(folio))
910 		return;
911 
912 	if (!drained || *drained == LRU_CACHE_NOT_DRAINED) {
913 		if (folio_ref_count(folio) ==
914 		    folio_expected_ref_count(folio) + extra_refs)
915 			return;
916 		lru_add_drain();
917 		if (drained)
918 			*drained = LRU_CACHE_DRAINED;
919 	}
920 	if (!drained || *drained == LRU_CACHE_DRAINED) {
921 		if (folio_ref_count(folio) ==
922 		    folio_expected_ref_count(folio) + extra_refs)
923 			return;
924 		lru_add_drain_all();
925 		if (drained)
926 			*drained = LRU_CACHE_DRAINED_ALL;
927 	}
928 }
929 
930 atomic_t lru_disable_count = ATOMIC_INIT(0);
931 
932 /*
933  * lru_cache_disable() needs to be called before we start compiling
934  * a list of folios to be migrated using folio_isolate_lru().
935  * It drains folios on LRU cache and then disable on all cpus until
936  * lru_cache_enable is called.
937  *
938  * Must be paired with a call to lru_cache_enable().
939  */
940 void lru_cache_disable(void)
941 {
942 	atomic_inc(&lru_disable_count);
943 	/*
944 	 * Readers of lru_disable_count are protected by either disabling
945 	 * preemption or rcu_read_lock:
946 	 *
947 	 * preempt_disable, local_irq_disable  [bh_lru_lock()]
948 	 * rcu_read_lock		       [rt_spin_lock CONFIG_PREEMPT_RT]
949 	 * preempt_disable		       [local_lock !CONFIG_PREEMPT_RT]
950 	 *
951 	 * Since v5.1 kernel, synchronize_rcu() is guaranteed to wait on
952 	 * preempt_disable() regions of code. So any CPU which sees
953 	 * lru_disable_count = 0 will have exited the critical
954 	 * section when synchronize_rcu() returns.
955 	 */
956 	synchronize_rcu_expedited();
957 #ifdef CONFIG_SMP
958 	__lru_add_drain_all(true);
959 #else
960 	lru_add_and_bh_lrus_drain();
961 #endif
962 }
963 
964 /**
965  * folios_put_refs - Reduce the reference count on a batch of folios.
966  * @folios: The folios.
967  * @refs: The number of refs to subtract from each folio.
968  *
969  * Like folio_put(), but for a batch of folios.  This is more efficient
970  * than writing the loop yourself as it will optimise the locks which need
971  * to be taken if the folios are freed.  The folios batch is returned
972  * empty and ready to be reused for another batch; there is no need
973  * to reinitialise it.  If @refs is NULL, we subtract one from each
974  * folio refcount.
975  *
976  * Context: May be called in process or interrupt context, but not in NMI
977  * context.  May be called while holding a spinlock.
978  */
979 void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
980 {
981 	int i, j;
982 	struct lruvec *lruvec = NULL;
983 	unsigned long flags = 0;
984 
985 	for (i = 0, j = 0; i < folios->nr; i++) {
986 		struct folio *folio = folios->folios[i];
987 		unsigned int nr_refs = refs ? refs[i] : 1;
988 
989 		/* Folio batch entry may have been preemptively removed during drain. */
990 		if (!folio)
991 			continue;
992 
993 		if (is_huge_zero_folio(folio))
994 			continue;
995 
996 		if (folio_is_zone_device(folio)) {
997 			if (lruvec) {
998 				lruvec_unlock_irqrestore(lruvec, flags);
999 				lruvec = NULL;
1000 			}
1001 			if (folio_ref_sub_and_test(folio, nr_refs))
1002 				free_zone_device_folio(folio);
1003 			continue;
1004 		}
1005 
1006 		if (!folio_ref_sub_and_test(folio, nr_refs))
1007 			continue;
1008 
1009 		/* hugetlb has its own memcg */
1010 		if (folio_test_hugetlb(folio)) {
1011 			if (lruvec) {
1012 				lruvec_unlock_irqrestore(lruvec, flags);
1013 				lruvec = NULL;
1014 			}
1015 			free_huge_folio(folio);
1016 			continue;
1017 		}
1018 		folio_unqueue_deferred_split(folio);
1019 		__page_cache_release(folio, &lruvec, &flags);
1020 
1021 		if (j != i)
1022 			folios->folios[j] = folio;
1023 		j++;
1024 	}
1025 	if (lruvec)
1026 		lruvec_unlock_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[FOLIO_BATCH_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 #ifdef CONFIG_MEMCG
1120 static void lruvec_reparent_lru(struct lruvec *child_lruvec,
1121 				struct lruvec *parent_lruvec,
1122 				enum lru_list lru, int nid)
1123 {
1124 	int zid;
1125 	struct zone *zone;
1126 
1127 	if (lru != LRU_UNEVICTABLE)
1128 		list_splice_tail_init(&child_lruvec->lists[lru], &parent_lruvec->lists[lru]);
1129 
1130 	for_each_managed_zone_pgdat(zone, NODE_DATA(nid), zid, MAX_NR_ZONES - 1) {
1131 		unsigned long size = mem_cgroup_get_zone_lru_size(child_lruvec, lru, zid);
1132 
1133 		if (!size)
1134 			continue;
1135 
1136 		/*
1137 		 * The folios are accounted to the parent from now on, so the
1138 		 * size has to be moved, not just copied. Leaving it behind
1139 		 * makes the dying child describe folios it no longer owns.
1140 		 */
1141 		mem_cgroup_update_lru_size(parent_lruvec, lru, zid, size);
1142 		mem_cgroup_update_lru_size(child_lruvec, lru, zid, -(long)size);
1143 	}
1144 }
1145 
1146 void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid)
1147 {
1148 	enum lru_list lru;
1149 	struct lruvec *child_lruvec, *parent_lruvec;
1150 
1151 	child_lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
1152 	parent_lruvec = mem_cgroup_lruvec(parent, NODE_DATA(nid));
1153 
1154 	for_each_lru(lru)
1155 		lruvec_reparent_lru(child_lruvec, parent_lruvec, lru, nid);
1156 }
1157 #endif
1158