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