xref: /linux/mm/folio.c (revision 2f0f6b0773be0a1ec475097ae54848eea42adc7d)
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 void lru_note_cost_unlock_irq(struct lruvec *lruvec, bool file,
269 		unsigned int nr_io, unsigned int nr_rotated)
270 		__releases(lruvec->lru_lock)
271 		__releases(rcu)
272 {
273 	unsigned long cost;
274 
275 	/*
276 	 * Reflect the relative cost of incurring IO and spending CPU
277 	 * time on rotations. This doesn't attempt to make a precise
278 	 * comparison, it just says: if reloads are about comparable
279 	 * between the LRU lists, or rotations are overwhelmingly
280 	 * different between them, adjust scan balance for CPU work.
281 	 */
282 	cost = nr_io * SWAP_CLUSTER_MAX + nr_rotated;
283 	if (!cost) {
284 		spin_unlock_irq(&lruvec->lru_lock);
285 		rcu_read_unlock();
286 		return;
287 	}
288 
289 	for (;;) {
290 		unsigned long lrusize;
291 
292 		/* Record cost event */
293 		if (file)
294 			lruvec->file_cost += cost;
295 		else
296 			lruvec->anon_cost += cost;
297 
298 		/*
299 		 * Decay previous events
300 		 *
301 		 * Because workloads change over time (and to avoid
302 		 * overflow) we keep these statistics as a floating
303 		 * average, which ends up weighing recent refaults
304 		 * more than old ones.
305 		 */
306 		lrusize = lruvec_page_state(lruvec, NR_INACTIVE_ANON) +
307 			  lruvec_page_state(lruvec, NR_ACTIVE_ANON) +
308 			  lruvec_page_state(lruvec, NR_INACTIVE_FILE) +
309 			  lruvec_page_state(lruvec, NR_ACTIVE_FILE);
310 
311 		if (lruvec->file_cost + lruvec->anon_cost > lrusize / 4) {
312 			lruvec->file_cost /= 2;
313 			lruvec->anon_cost /= 2;
314 		}
315 
316 		spin_unlock_irq(&lruvec->lru_lock);
317 		lruvec = parent_lruvec(lruvec);
318 		if (!lruvec) {
319 			rcu_read_unlock();
320 			break;
321 		}
322 		spin_lock_irq(&lruvec->lru_lock);
323 	}
324 }
325 
326 void lru_note_cost_refault(struct folio *folio)
327 {
328 	struct lruvec *lruvec;
329 
330 	lruvec = folio_lruvec_lock_irq(folio);
331 	lru_note_cost_unlock_irq(lruvec, folio_is_file_lru(folio),
332 				folio_nr_pages(folio), 0);
333 }
334 
335 static void lru_activate(struct lruvec *lruvec, struct folio *folio)
336 {
337 	long nr_pages = folio_nr_pages(folio);
338 
339 	if (folio_test_active(folio) || folio_test_unevictable(folio))
340 		return;
341 
342 
343 	lruvec_del_folio(lruvec, folio);
344 	folio_set_active(folio);
345 	lruvec_add_folio(lruvec, folio);
346 	trace_mm_lru_activate(folio);
347 
348 	__count_vm_events(PGACTIVATE, nr_pages);
349 	count_memcg_events(lruvec_memcg(lruvec), PGACTIVATE, nr_pages);
350 }
351 
352 #ifdef CONFIG_SMP
353 static void folio_activate_drain(int cpu)
354 {
355 	struct folio_batch *fbatch = &per_cpu(cpu_fbatches.lru_activate, cpu);
356 
357 	if (folio_batch_count(fbatch))
358 		folio_batch_move_lru(fbatch, lru_activate);
359 }
360 
361 void folio_activate(struct folio *folio)
362 {
363 	if (folio_test_active(folio) || folio_test_unevictable(folio) ||
364 	    !folio_test_lru(folio))
365 		return;
366 
367 	folio_batch_add_and_move(folio, lru_activate);
368 }
369 
370 #else
371 static inline void folio_activate_drain(int cpu)
372 {
373 }
374 
375 void folio_activate(struct folio *folio)
376 {
377 	struct lruvec *lruvec;
378 
379 	if (!folio_test_clear_lru(folio))
380 		return;
381 
382 	lruvec = folio_lruvec_lock_irq(folio);
383 	lru_activate(lruvec, folio);
384 	lruvec_unlock_irq(lruvec);
385 	folio_set_lru(folio);
386 }
387 #endif
388 
389 static void __lru_cache_activate_folio(struct folio *folio)
390 {
391 	struct folio_batch *fbatch;
392 	int i;
393 
394 	local_lock(&cpu_fbatches.lock);
395 	fbatch = this_cpu_ptr(&cpu_fbatches.lru_add);
396 
397 	/*
398 	 * Search backwards on the optimistic assumption that the folio being
399 	 * activated has just been added to this batch. Note that only
400 	 * the local batch is examined as a !LRU folio could be in the
401 	 * process of being released, reclaimed, migrated or on a remote
402 	 * batch that is currently being drained. Furthermore, marking
403 	 * a remote batch's folio active potentially hits a race where
404 	 * a folio is marked active just after it is added to the inactive
405 	 * list causing accounting errors and BUG_ON checks to trigger.
406 	 */
407 	for (i = folio_batch_count(fbatch) - 1; i >= 0; i--) {
408 		struct folio *batch_folio = fbatch->folios[i];
409 
410 		if (batch_folio == folio) {
411 			folio_set_active(folio);
412 			break;
413 		}
414 	}
415 
416 	local_unlock(&cpu_fbatches.lock);
417 }
418 
419 #ifdef CONFIG_LRU_GEN
420 
421 static void lru_gen_inc_refs(struct folio *folio)
422 {
423 	unsigned long new_flags, old_flags = READ_ONCE(folio->flags.f);
424 
425 	if (folio_test_unevictable(folio))
426 		return;
427 
428 	/* see the comment on LRU_REFS_FLAGS */
429 	if (!folio_test_referenced(folio)) {
430 		set_mask_bits(&folio->flags.f, LRU_REFS_MASK, BIT(PG_referenced));
431 		return;
432 	}
433 
434 	do {
435 		if ((old_flags & LRU_REFS_MASK) == LRU_REFS_MASK) {
436 			if (!folio_test_workingset(folio))
437 				folio_set_workingset(folio);
438 			return;
439 		}
440 
441 		new_flags = old_flags + BIT(LRU_REFS_PGOFF);
442 	} while (!try_cmpxchg(&folio->flags.f, &old_flags, new_flags));
443 }
444 
445 static bool lru_gen_clear_refs(struct folio *folio)
446 {
447 	int gen = folio_lru_gen(folio);
448 	int type = folio_is_file_lru(folio);
449 	unsigned long seq;
450 
451 	if (gen < 0)
452 		return true;
453 
454 	set_mask_bits(&folio->flags.f, LRU_REFS_FLAGS | BIT(PG_workingset), 0);
455 
456 	rcu_read_lock();
457 	seq = READ_ONCE(folio_lruvec(folio)->lrugen.min_seq[type]);
458 	rcu_read_unlock();
459 	/* whether can do without shuffling under the LRU lock */
460 	return gen == lru_gen_from_seq(seq);
461 }
462 
463 #else /* !CONFIG_LRU_GEN */
464 
465 static void lru_gen_inc_refs(struct folio *folio)
466 {
467 }
468 
469 static bool lru_gen_clear_refs(struct folio *folio)
470 {
471 	return false;
472 }
473 
474 #endif /* CONFIG_LRU_GEN */
475 
476 /**
477  * folio_mark_accessed - Mark a folio as having seen activity.
478  * @folio: The folio to mark.
479  *
480  * This function will perform one of the following transitions:
481  *
482  * * inactive,unreferenced	->	inactive,referenced
483  * * inactive,referenced	->	active,unreferenced
484  * * active,unreferenced	->	active,referenced
485  *
486  * When a newly allocated folio is not yet visible, so safe for non-atomic ops,
487  * __folio_set_referenced() may be substituted for folio_mark_accessed().
488  */
489 void folio_mark_accessed(struct folio *folio)
490 {
491 	if (folio_test_dropbehind(folio))
492 		return;
493 	if (lru_gen_enabled()) {
494 		lru_gen_inc_refs(folio);
495 		return;
496 	}
497 
498 	if (!folio_test_referenced(folio)) {
499 		folio_set_referenced(folio);
500 	} else if (folio_test_unevictable(folio)) {
501 		/*
502 		 * Unevictable pages are on the "LRU_UNEVICTABLE" list. But,
503 		 * this list is never rotated or maintained, so marking an
504 		 * unevictable page accessed has no effect.
505 		 */
506 	} else if (!folio_test_active(folio)) {
507 		/*
508 		 * If the folio is on the LRU, queue it for activation via
509 		 * cpu_fbatches.lru_activate. Otherwise, assume the folio is in a
510 		 * folio_batch, mark it active and it'll be moved to the active
511 		 * LRU on the next drain.
512 		 */
513 		if (folio_test_lru(folio))
514 			folio_activate(folio);
515 		else
516 			__lru_cache_activate_folio(folio);
517 		folio_clear_referenced(folio);
518 		workingset_activation(folio);
519 	}
520 	if (folio_test_idle(folio))
521 		folio_clear_idle(folio);
522 }
523 EXPORT_SYMBOL(folio_mark_accessed);
524 
525 /**
526  * folio_add_lru - Add a folio to an LRU list.
527  * @folio: The folio to be added to the LRU.
528  *
529  * Queue the folio for addition to the LRU. The decision on whether
530  * to add the page to the [in]active [file|anon] list is deferred until the
531  * folio_batch is drained. This gives a chance for the caller of folio_add_lru()
532  * have the folio added to the active list using folio_mark_accessed().
533  */
534 void folio_add_lru(struct folio *folio)
535 {
536 	VM_BUG_ON_FOLIO(folio_test_active(folio) &&
537 			folio_test_unevictable(folio), folio);
538 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
539 
540 	/*
541 	 * For refaulted workingset folios, set PG_active so they
542 	 * can be added to active generations.
543 	 * For prefaulted file folios, folio_mark_accessed() sets
544 	 * PG_referenced so lru_gen_folio_seq() places them into
545 	 * the second oldest generation.
546 	 */
547 	if (lru_gen_enabled() && !folio_test_unevictable(folio) &&
548 	    lru_gen_in_fault() && !(current->flags & PF_MEMALLOC)) {
549 		if (folio_test_workingset(folio))
550 			folio_set_active(folio);
551 		else if (!folio_test_referenced(folio))
552 			folio_mark_accessed(folio);
553 	}
554 
555 	folio_batch_add_and_move(folio, lru_add);
556 }
557 EXPORT_SYMBOL(folio_add_lru);
558 
559 /**
560  * folio_add_lru_vma() - Add a folio to the appropriate LRU list for this VMA.
561  * @folio: The folio to be added to the LRU.
562  * @vma: VMA in which the folio is mapped.
563  *
564  * If the VMA is mlocked, @folio is added to the unevictable list.
565  * Otherwise, it is treated the same way as folio_add_lru().
566  */
567 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma)
568 {
569 	VM_BUG_ON_FOLIO(folio_test_lru(folio), folio);
570 
571 	if (unlikely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) == VM_LOCKED))
572 		mlock_new_folio(folio);
573 	else
574 		folio_add_lru(folio);
575 }
576 
577 /*
578  * If the folio cannot be invalidated, it is moved to the
579  * inactive list to speed up its reclaim.  It is moved to the
580  * head of the list, rather than the tail, to give the flusher
581  * threads some time to write it out, as this is much more
582  * effective than the single-page writeout from reclaim.
583  *
584  * If the folio isn't mapped and dirty/writeback, the folio
585  * could be reclaimed asap using the reclaim flag.
586  *
587  * 1. active, mapped folio -> none
588  * 2. active, dirty/writeback folio -> inactive, head, reclaim
589  * 3. inactive, mapped folio -> none
590  * 4. inactive, dirty/writeback folio -> inactive, head, reclaim
591  * 5. inactive, clean -> inactive, tail
592  * 6. Others -> none
593  *
594  * In 4, it moves to the head of the inactive list so the folio is
595  * written out by flusher threads as this is much more efficient
596  * than the single-page writeout from reclaim.
597  */
598 static void lru_deactivate_file(struct lruvec *lruvec, struct folio *folio)
599 {
600 	bool active = folio_test_active(folio) || lru_gen_enabled();
601 	long nr_pages = folio_nr_pages(folio);
602 
603 	if (folio_test_unevictable(folio))
604 		return;
605 
606 	/* Some processes are using the folio */
607 	if (folio_mapped(folio))
608 		return;
609 
610 	lruvec_del_folio(lruvec, folio);
611 	folio_clear_active(folio);
612 	folio_clear_referenced(folio);
613 
614 	if (folio_test_writeback(folio) || folio_test_dirty(folio)) {
615 		/*
616 		 * Setting the reclaim flag could race with
617 		 * folio_end_writeback() and confuse readahead.  But the
618 		 * race window is _really_ small and  it's not a critical
619 		 * problem.
620 		 */
621 		lruvec_add_folio(lruvec, folio);
622 		folio_set_reclaim(folio);
623 	} else {
624 		/*
625 		 * The folio's writeback ended while it was in the batch.
626 		 * We move that folio to the tail of the inactive list.
627 		 */
628 		lruvec_add_folio_tail(lruvec, folio);
629 		__count_vm_events(PGROTATED, nr_pages);
630 	}
631 
632 	if (active) {
633 		__count_vm_events(PGDEACTIVATE, nr_pages);
634 		count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE,
635 				     nr_pages);
636 	}
637 }
638 
639 static void lru_deactivate(struct lruvec *lruvec, struct folio *folio)
640 {
641 	long nr_pages = folio_nr_pages(folio);
642 
643 	if (folio_test_unevictable(folio) || !(folio_test_active(folio) || lru_gen_enabled()))
644 		return;
645 
646 	lruvec_del_folio(lruvec, folio);
647 	folio_clear_active(folio);
648 	folio_clear_referenced(folio);
649 	lruvec_add_folio(lruvec, folio);
650 
651 	__count_vm_events(PGDEACTIVATE, nr_pages);
652 	count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_pages);
653 }
654 
655 static void lru_lazyfree(struct lruvec *lruvec, struct folio *folio)
656 {
657 	long nr_pages = folio_nr_pages(folio);
658 
659 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
660 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
661 		return;
662 
663 	lruvec_del_folio(lruvec, folio);
664 	folio_clear_active(folio);
665 	if (lru_gen_enabled())
666 		lru_gen_clear_refs(folio);
667 	else
668 		folio_clear_referenced(folio);
669 	/*
670 	 * Lazyfree folios are clean anonymous folios.  They have
671 	 * the swapbacked flag cleared, to distinguish them from normal
672 	 * anonymous folios
673 	 */
674 	folio_clear_swapbacked(folio);
675 	lruvec_add_folio(lruvec, folio);
676 
677 	__count_vm_events(PGLAZYFREE, nr_pages);
678 	count_memcg_events(lruvec_memcg(lruvec), PGLAZYFREE, nr_pages);
679 }
680 
681 /*
682  * Drain pages out of the cpu's folio_batch.
683  * Either "cpu" is the current CPU, and preemption has already been
684  * disabled; or "cpu" is being hot-unplugged, and is already dead.
685  */
686 void lru_add_drain_cpu(int cpu)
687 {
688 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
689 	struct folio_batch *fbatch = &fbatches->lru_add;
690 	unsigned int nr_folios = folio_batch_count(fbatch);
691 
692 	if (nr_folios) {
693 		folio_batch_move_lru(fbatch, lru_add);
694 		trace_mm_lru_add_drain_tp(cpu, nr_folios);
695 	}
696 
697 	fbatch = &fbatches->lru_move_tail;
698 	/* Disabling interrupts below acts as a compiler barrier. */
699 	if (data_race(folio_batch_count(fbatch))) {
700 		unsigned long flags;
701 
702 		/* No harm done if a racing interrupt already did this */
703 		local_lock_irqsave(&cpu_fbatches.lock_irq, flags);
704 		folio_batch_move_lru(fbatch, lru_move_tail);
705 		local_unlock_irqrestore(&cpu_fbatches.lock_irq, flags);
706 	}
707 
708 	fbatch = &fbatches->lru_deactivate_file;
709 	if (folio_batch_count(fbatch))
710 		folio_batch_move_lru(fbatch, lru_deactivate_file);
711 
712 	fbatch = &fbatches->lru_deactivate;
713 	if (folio_batch_count(fbatch))
714 		folio_batch_move_lru(fbatch, lru_deactivate);
715 
716 	fbatch = &fbatches->lru_lazyfree;
717 	if (folio_batch_count(fbatch))
718 		folio_batch_move_lru(fbatch, lru_lazyfree);
719 
720 	folio_activate_drain(cpu);
721 }
722 
723 /**
724  * deactivate_file_folio() - Deactivate a file folio.
725  * @folio: Folio to deactivate.
726  *
727  * This function hints to the VM that @folio is a good reclaim candidate,
728  * for example if its invalidation fails due to the folio being dirty
729  * or under writeback.
730  *
731  * Context: Caller holds a reference on the folio.
732  */
733 void deactivate_file_folio(struct folio *folio)
734 {
735 	/* Deactivating an unevictable folio will not accelerate reclaim */
736 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
737 		return;
738 
739 	if (lru_gen_enabled() && lru_gen_clear_refs(folio))
740 		return;
741 
742 	folio_batch_add_and_move(folio, lru_deactivate_file);
743 }
744 
745 /*
746  * folio_deactivate - deactivate a folio
747  * @folio: folio to deactivate
748  *
749  * folio_deactivate() moves @folio to the inactive list if @folio was on the
750  * active list and was not unevictable. This is done to accelerate the
751  * reclaim of @folio.
752  */
753 void folio_deactivate(struct folio *folio)
754 {
755 	if (folio_test_unevictable(folio) || !folio_test_lru(folio))
756 		return;
757 
758 	if (lru_gen_enabled() ? lru_gen_clear_refs(folio) : !folio_test_active(folio))
759 		return;
760 
761 	folio_batch_add_and_move(folio, lru_deactivate);
762 }
763 
764 /**
765  * folio_mark_lazyfree - make an anon folio lazyfree
766  * @folio: folio to deactivate
767  *
768  * folio_mark_lazyfree() moves @folio to the inactive file list.
769  * This is done to accelerate the reclaim of @folio.
770  */
771 void folio_mark_lazyfree(struct folio *folio)
772 {
773 	if (!folio_test_anon(folio) || !folio_test_swapbacked(folio) ||
774 	    !folio_test_lru(folio) ||
775 	    folio_test_swapcache(folio) || folio_test_unevictable(folio))
776 		return;
777 
778 	folio_batch_add_and_move(folio, lru_lazyfree);
779 }
780 
781 void lru_add_drain(void)
782 {
783 	local_lock(&cpu_fbatches.lock);
784 	lru_add_drain_cpu(smp_processor_id());
785 	local_unlock(&cpu_fbatches.lock);
786 	mlock_drain_local();
787 }
788 
789 /*
790  * It's called from per-cpu workqueue context in SMP case so
791  * lru_add_drain_cpu and invalidate_bh_lrus_cpu should run on
792  * the same cpu. It shouldn't be a problem in !SMP case since
793  * the core is only one and the locks will disable preemption.
794  */
795 static void lru_add_and_bh_lrus_drain(void)
796 {
797 	local_lock(&cpu_fbatches.lock);
798 	lru_add_drain_cpu(smp_processor_id());
799 	local_unlock(&cpu_fbatches.lock);
800 	invalidate_bh_lrus_cpu();
801 	mlock_drain_local();
802 }
803 
804 void lru_add_drain_cpu_zone(struct zone *zone)
805 {
806 	local_lock(&cpu_fbatches.lock);
807 	lru_add_drain_cpu(smp_processor_id());
808 	drain_local_pages(zone);
809 	local_unlock(&cpu_fbatches.lock);
810 	mlock_drain_local();
811 }
812 
813 #ifdef CONFIG_SMP
814 
815 static DEFINE_PER_CPU(struct work_struct, lru_add_drain_work);
816 
817 static void lru_add_drain_per_cpu(struct work_struct *dummy)
818 {
819 	lru_add_and_bh_lrus_drain();
820 }
821 
822 static bool cpu_needs_drain(unsigned int cpu)
823 {
824 	struct cpu_fbatches *fbatches = &per_cpu(cpu_fbatches, cpu);
825 
826 	/* Check these in order of likelihood that they're not zero */
827 	return data_race(folio_batch_count(&fbatches->lru_add) ||
828 			 folio_batch_count(&fbatches->lru_move_tail) ||
829 			 folio_batch_count(&fbatches->lru_deactivate_file) ||
830 			 folio_batch_count(&fbatches->lru_deactivate) ||
831 			 folio_batch_count(&fbatches->lru_lazyfree) ||
832 			 folio_batch_count(&fbatches->lru_activate) ||
833 			 need_mlock_drain(cpu)) ||
834 		has_bh_in_lru(cpu, NULL);
835 }
836 
837 /*
838  * Doesn't need any cpu hotplug locking because we do rely on per-cpu
839  * kworkers being shut down before our page_alloc_cpu_dead callback is
840  * executed on the offlined cpu.
841  * Calling this function with cpu hotplug locks held can actually lead
842  * to obscure indirect dependencies via WQ context.
843  */
844 static inline void __lru_add_drain_all(bool force_all_cpus)
845 {
846 	/*
847 	 * lru_drain_gen - Global pages generation number
848 	 *
849 	 * (A) Definition: global lru_drain_gen = x implies that all generations
850 	 *     0 < n <= x are already *scheduled* for draining.
851 	 *
852 	 * This is an optimization for the highly-contended use case where a
853 	 * user space workload keeps constantly generating a flow of pages for
854 	 * each CPU.
855 	 */
856 	static unsigned int lru_drain_gen;
857 	static struct cpumask has_work;
858 	static DEFINE_MUTEX(lock);
859 	unsigned cpu, this_gen;
860 
861 	/*
862 	 * Make sure nobody triggers this path before mm_percpu_wq is fully
863 	 * initialized.
864 	 */
865 	if (WARN_ON(!mm_percpu_wq))
866 		return;
867 
868 	trace_mm_lru_add_drain_all_tp(force_all_cpus);
869 
870 	/*
871 	 * Guarantee folio_batch counter stores visible by this CPU
872 	 * are visible to other CPUs before loading the current drain
873 	 * generation.
874 	 */
875 	smp_mb();
876 
877 	/*
878 	 * (B) Locally cache global LRU draining generation number
879 	 *
880 	 * The read barrier ensures that the counter is loaded before the mutex
881 	 * is taken. It pairs with smp_mb() inside the mutex critical section
882 	 * at (D).
883 	 */
884 	this_gen = smp_load_acquire(&lru_drain_gen);
885 
886 	/* It helps everyone if we do our own local drain immediately. */
887 	lru_add_drain();
888 
889 	mutex_lock(&lock);
890 
891 	/*
892 	 * (C) Exit the draining operation if a newer generation, from another
893 	 * lru_add_drain_all(), was already scheduled for draining. Check (A).
894 	 */
895 	if (unlikely(this_gen != lru_drain_gen && !force_all_cpus))
896 		goto done;
897 
898 	/*
899 	 * (D) Increment global generation number
900 	 *
901 	 * Pairs with smp_load_acquire() at (B), outside of the critical
902 	 * section. Use a full memory barrier to guarantee that the
903 	 * new global drain generation number is stored before loading
904 	 * folio_batch counters.
905 	 *
906 	 * This pairing must be done here, before the for_each_online_cpu loop
907 	 * below which drains the page vectors.
908 	 *
909 	 * Let x, y, and z represent some system CPU numbers, where x < y < z.
910 	 * Assume CPU #z is in the middle of the for_each_online_cpu loop
911 	 * below and has already reached CPU #y's per-cpu data. CPU #x comes
912 	 * along, adds some pages to its per-cpu vectors, then calls
913 	 * lru_add_drain_all().
914 	 *
915 	 * If the paired barrier is done at any later step, e.g. after the
916 	 * loop, CPU #x will just exit at (C) and miss flushing out all of its
917 	 * added pages.
918 	 */
919 	WRITE_ONCE(lru_drain_gen, lru_drain_gen + 1);
920 	smp_mb();
921 
922 	cpumask_clear(&has_work);
923 	for_each_online_cpu(cpu) {
924 		struct work_struct *work = &per_cpu(lru_add_drain_work, cpu);
925 
926 		if (cpu_needs_drain(cpu)) {
927 			INIT_WORK(work, lru_add_drain_per_cpu);
928 			queue_work_on(cpu, mm_percpu_wq, work);
929 			__cpumask_set_cpu(cpu, &has_work);
930 		}
931 	}
932 
933 	for_each_cpu(cpu, &has_work)
934 		flush_work(&per_cpu(lru_add_drain_work, cpu));
935 
936 done:
937 	mutex_unlock(&lock);
938 }
939 
940 void lru_add_drain_all(void)
941 {
942 	__lru_add_drain_all(false);
943 }
944 #else
945 void lru_add_drain_all(void)
946 {
947 	lru_add_drain();
948 }
949 #endif /* CONFIG_SMP */
950 
951 atomic_t lru_disable_count = ATOMIC_INIT(0);
952 
953 /*
954  * lru_cache_disable() needs to be called before we start compiling
955  * a list of folios to be migrated using folio_isolate_lru().
956  * It drains folios on LRU cache and then disable on all cpus until
957  * lru_cache_enable is called.
958  *
959  * Must be paired with a call to lru_cache_enable().
960  */
961 void lru_cache_disable(void)
962 {
963 	atomic_inc(&lru_disable_count);
964 	/*
965 	 * Readers of lru_disable_count are protected by either disabling
966 	 * preemption or rcu_read_lock:
967 	 *
968 	 * preempt_disable, local_irq_disable  [bh_lru_lock()]
969 	 * rcu_read_lock		       [rt_spin_lock CONFIG_PREEMPT_RT]
970 	 * preempt_disable		       [local_lock !CONFIG_PREEMPT_RT]
971 	 *
972 	 * Since v5.1 kernel, synchronize_rcu() is guaranteed to wait on
973 	 * preempt_disable() regions of code. So any CPU which sees
974 	 * lru_disable_count = 0 will have exited the critical
975 	 * section when synchronize_rcu() returns.
976 	 */
977 	synchronize_rcu_expedited();
978 #ifdef CONFIG_SMP
979 	__lru_add_drain_all(true);
980 #else
981 	lru_add_and_bh_lrus_drain();
982 #endif
983 }
984 
985 /**
986  * folios_put_refs - Reduce the reference count on a batch of folios.
987  * @folios: The folios.
988  * @refs: The number of refs to subtract from each folio.
989  *
990  * Like folio_put(), but for a batch of folios.  This is more efficient
991  * than writing the loop yourself as it will optimise the locks which need
992  * to be taken if the folios are freed.  The folios batch is returned
993  * empty and ready to be reused for another batch; there is no need
994  * to reinitialise it.  If @refs is NULL, we subtract one from each
995  * folio refcount.
996  *
997  * Context: May be called in process or interrupt context, but not in NMI
998  * context.  May be called while holding a spinlock.
999  */
1000 void folios_put_refs(struct folio_batch *folios, unsigned int *refs)
1001 {
1002 	int i, j;
1003 	struct lruvec *lruvec = NULL;
1004 	unsigned long flags = 0;
1005 
1006 	for (i = 0, j = 0; i < folios->nr; i++) {
1007 		struct folio *folio = folios->folios[i];
1008 		unsigned int nr_refs = refs ? refs[i] : 1;
1009 
1010 		/* Folio batch entry may have been preemptively removed during drain. */
1011 		if (!folio)
1012 			continue;
1013 
1014 		if (is_huge_zero_folio(folio))
1015 			continue;
1016 
1017 		if (folio_is_zone_device(folio)) {
1018 			if (lruvec) {
1019 				lruvec_unlock_irqrestore(lruvec, flags);
1020 				lruvec = NULL;
1021 			}
1022 			if (folio_ref_sub_and_test(folio, nr_refs))
1023 				free_zone_device_folio(folio);
1024 			continue;
1025 		}
1026 
1027 		if (!folio_ref_sub_and_test(folio, nr_refs))
1028 			continue;
1029 
1030 		/* hugetlb has its own memcg */
1031 		if (folio_test_hugetlb(folio)) {
1032 			if (lruvec) {
1033 				lruvec_unlock_irqrestore(lruvec, flags);
1034 				lruvec = NULL;
1035 			}
1036 			free_huge_folio(folio);
1037 			continue;
1038 		}
1039 		folio_unqueue_deferred_split(folio);
1040 		__page_cache_release(folio, &lruvec, &flags);
1041 
1042 		if (j != i)
1043 			folios->folios[j] = folio;
1044 		j++;
1045 	}
1046 	if (lruvec)
1047 		lruvec_unlock_irqrestore(lruvec, flags);
1048 	if (!j) {
1049 		folio_batch_reinit(folios);
1050 		return;
1051 	}
1052 
1053 	folios->nr = j;
1054 	mem_cgroup_uncharge_folios(folios);
1055 	free_unref_folios(folios);
1056 }
1057 EXPORT_SYMBOL(folios_put_refs);
1058 
1059 /**
1060  * release_pages - batched put_page()
1061  * @arg: array of pages to release
1062  * @nr: number of pages
1063  *
1064  * Decrement the reference count on all the pages in @arg.  If it
1065  * fell to zero, remove the page from the LRU and free it.
1066  *
1067  * Note that the argument can be an array of pages, encoded pages,
1068  * or folio pointers. We ignore any encoded bits, and turn any of
1069  * them into just a folio that gets free'd.
1070  */
1071 void release_pages(release_pages_arg arg, int nr)
1072 {
1073 	struct folio_batch fbatch;
1074 	int refs[FOLIO_BATCH_SIZE];
1075 	struct encoded_page **encoded = arg.encoded_pages;
1076 	int i;
1077 
1078 	folio_batch_init(&fbatch);
1079 	for (i = 0; i < nr; i++) {
1080 		/* Turn any of the argument types into a folio */
1081 		struct folio *folio = page_folio(encoded_page_ptr(encoded[i]));
1082 
1083 		/* Is our next entry actually "nr_pages" -> "nr_refs" ? */
1084 		refs[fbatch.nr] = 1;
1085 		if (unlikely(encoded_page_flags(encoded[i]) &
1086 			     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
1087 			refs[fbatch.nr] = encoded_nr_pages(encoded[++i]);
1088 
1089 		if (folio_batch_add(&fbatch, folio) > 0)
1090 			continue;
1091 		folios_put_refs(&fbatch, refs);
1092 	}
1093 
1094 	if (fbatch.nr)
1095 		folios_put_refs(&fbatch, refs);
1096 }
1097 EXPORT_SYMBOL(release_pages);
1098 
1099 /*
1100  * The folios which we're about to release may be in the deferred lru-addition
1101  * queues.  That would prevent them from really being freed right now.  That's
1102  * OK from a correctness point of view but is inefficient - those folios may be
1103  * cache-warm and we want to give them back to the page allocator ASAP.
1104  *
1105  * So __folio_batch_release() will drain those queues here.
1106  * folio_batch_move_lru() calls folios_put() directly to avoid
1107  * mutual recursion.
1108  */
1109 void __folio_batch_release(struct folio_batch *fbatch)
1110 {
1111 	if (!fbatch->percpu_pvec_drained) {
1112 		lru_add_drain();
1113 		fbatch->percpu_pvec_drained = true;
1114 	}
1115 	folios_put(fbatch);
1116 }
1117 EXPORT_SYMBOL(__folio_batch_release);
1118 
1119 /**
1120  * folio_batch_remove_exceptionals() - Prune non-folios from a batch.
1121  * @fbatch: The batch to prune
1122  *
1123  * find_get_entries() fills a batch with both folios and shadow/swap/DAX
1124  * entries.  This function prunes all the non-folio entries from @fbatch
1125  * without leaving holes, so that it can be passed on to folio-only batch
1126  * operations.
1127  */
1128 void folio_batch_remove_exceptionals(struct folio_batch *fbatch)
1129 {
1130 	unsigned int i, j;
1131 
1132 	for (i = 0, j = 0; i < folio_batch_count(fbatch); i++) {
1133 		struct folio *folio = fbatch->folios[i];
1134 		if (!xa_is_value(folio))
1135 			fbatch->folios[j++] = folio;
1136 	}
1137 	fbatch->nr = j;
1138 }
1139 
1140 #ifdef CONFIG_MEMCG
1141 static void lruvec_reparent_lru(struct lruvec *child_lruvec,
1142 				struct lruvec *parent_lruvec,
1143 				enum lru_list lru, int nid)
1144 {
1145 	int zid;
1146 	struct zone *zone;
1147 
1148 	if (lru != LRU_UNEVICTABLE)
1149 		list_splice_tail_init(&child_lruvec->lists[lru], &parent_lruvec->lists[lru]);
1150 
1151 	for_each_managed_zone_pgdat(zone, NODE_DATA(nid), zid, MAX_NR_ZONES - 1) {
1152 		unsigned long size = mem_cgroup_get_zone_lru_size(child_lruvec, lru, zid);
1153 
1154 		mem_cgroup_update_lru_size(parent_lruvec, lru, zid, size);
1155 	}
1156 }
1157 
1158 void lru_reparent_memcg(struct mem_cgroup *memcg, struct mem_cgroup *parent, int nid)
1159 {
1160 	enum lru_list lru;
1161 	struct lruvec *child_lruvec, *parent_lruvec;
1162 
1163 	child_lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(nid));
1164 	parent_lruvec = mem_cgroup_lruvec(parent, NODE_DATA(nid));
1165 	parent_lruvec->anon_cost += child_lruvec->anon_cost;
1166 	parent_lruvec->file_cost += child_lruvec->file_cost;
1167 
1168 	for_each_lru(lru)
1169 		lruvec_reparent_lru(child_lruvec, parent_lruvec, lru, nid);
1170 }
1171 #endif
1172