xref: /linux/mm/internal.h (revision d68ce4e71248e1ff5af9654b407541d9260b3ba5)
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /* internal.h: mm/ internal definitions
3  *
4  * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  */
7 #ifndef __MM_INTERNAL_H
8 #define __MM_INTERNAL_H
9 
10 #include <linux/file.h>
11 #include <linux/fs.h>
12 #include <linux/khugepaged.h>
13 #include <linux/mm.h>
14 #include <linux/mm_inline.h>
15 #include <linux/mmu_notifier.h>
16 #include <linux/pagemap.h>
17 #include <linux/pagewalk.h>
18 #include <linux/rmap.h>
19 #include <linux/swap.h>
20 #include <linux/leafops.h>
21 #include <linux/tracepoint-defs.h>
22 
23 /* Internal core VMA manipulation functions. */
24 #include "vma.h"
25 
26 struct folio_batch;
27 
28 int __copy_remote_mm_str(struct mm_struct *mm, unsigned long addr,
29 		void *buf, int len, unsigned int gup_flags);
30 
31 /* mm/workingset.c */
32 bool workingset_test_recent(void *shadow, bool file, bool *workingset,
33 			    bool flush);
34 void workingset_age_nonresident(struct lruvec *lruvec, unsigned long nr_pages);
35 void *workingset_eviction(struct folio *folio,
36 			  struct mem_cgroup *target_memcg);
37 void workingset_refault(struct folio *folio, void *shadow);
38 void workingset_activation(struct folio *folio);
39 
40 /* mm/folio.c */
41 void folio_add_lru_vma(struct folio *folio, struct vm_area_struct *vma);
42 
43 static inline bool folio_may_be_lru_cached(const struct folio *folio)
44 {
45 	/*
46 	 * Holding PMD-sized folios in per-CPU LRU cache unbalances accounting.
47 	 * Holding small numbers of low-order mTHP folios in per-CPU LRU cache
48 	 * will be sensible, but nobody has implemented and tested that yet.
49 	 */
50 	return !folio_test_large(folio);
51 }
52 
53 static inline void lru_cache_enable(void)
54 {
55 	atomic_dec(&lru_disable_count);
56 }
57 
58 void lru_cache_disable(void);
59 void lru_add_drain(void);
60 void lru_add_drain_cpu(int cpu);
61 void lru_add_drain_cpu_zone(struct zone *zone);
62 void folio_deactivate(struct folio *folio);
63 void folio_mark_lazyfree(struct folio *folio);
64 
65 /* mm/vmscan.c */
66 unsigned long zone_reclaimable_pages(struct zone *zone);
67 unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
68 				gfp_t gfp_mask, const nodemask_t *mask);
69 unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
70 			      int zone_idx);
71 
72 #define MEMCG_RECLAIM_MAY_SWAP (1 << 1)
73 #define MEMCG_RECLAIM_PROACTIVE (1 << 2)
74 enum {
75 	MIN_SWAPPINESS = 0,
76 	MAX_SWAPPINESS = 200,
77 
78 	/* Just reclaim from anon folios in proactive memory reclaim */
79 	SWAPPINESS_ANON_ONLY = MAX_SWAPPINESS + 1,
80 };
81 
82 unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
83 					   unsigned long nr_pages,
84 					   gfp_t gfp_mask,
85 					   unsigned int reclaim_options,
86 					   int *swappiness);
87 
88 #ifdef CONFIG_NUMA
89 extern int sysctl_min_unmapped_ratio;
90 extern int sysctl_min_slab_ratio;
91 #endif
92 
93 /*
94  * Maintains state across a page table move. The operation assumes both source
95  * and destination VMAs already exist and are specified by the user.
96  *
97  * Partial moves are permitted, but the old and new ranges must both reside
98  * within a VMA.
99  *
100  * mmap lock must be held in write and VMA write locks must be held on any VMA
101  * that is visible.
102  *
103  * Use the PAGETABLE_MOVE() macro to initialise this struct.
104  *
105  * The old_addr and new_addr fields are updated as the page table move is
106  * executed.
107  *
108  * NOTE: The page table move is affected by reading from [old_addr, old_end),
109  * and old_addr may be updated for better page table alignment, so len_in
110  * represents the length of the range being copied as specified by the user.
111  */
112 struct pagetable_move_control {
113 	struct vm_area_struct *old; /* Source VMA. */
114 	struct vm_area_struct *new; /* Destination VMA. */
115 	unsigned long old_addr; /* Address from which the move begins. */
116 	unsigned long old_end; /* Exclusive address at which old range ends. */
117 	unsigned long new_addr; /* Address to move page tables to. */
118 	unsigned long len_in; /* Bytes to remap specified by user. */
119 
120 	bool need_rmap_locks; /* Do rmap locks need to be taken? */
121 	bool for_stack; /* Is this an early temp stack being moved? */
122 };
123 
124 #define PAGETABLE_MOVE(name, old_, new_, old_addr_, new_addr_, len_)	\
125 	struct pagetable_move_control name = {				\
126 		.old = old_,						\
127 		.new = new_,						\
128 		.old_addr = old_addr_,					\
129 		.old_end = (old_addr_) + (len_),			\
130 		.new_addr = new_addr_,					\
131 		.len_in = len_,						\
132 	}
133 
134 /*
135  * The set of flags that only affect watermark checking and reclaim
136  * behaviour. This is used by the MM to obey the caller constraints
137  * about IO, FS and watermark checking while ignoring placement
138  * hints such as HIGHMEM usage.
139  */
140 #define GFP_RECLAIM_MASK (__GFP_RECLAIM|__GFP_HIGH|__GFP_IO|__GFP_FS|\
141 			__GFP_NOWARN|__GFP_RETRY_MAYFAIL|__GFP_NOFAIL|\
142 			__GFP_NORETRY|__GFP_MEMALLOC|__GFP_NOMEMALLOC|\
143 			__GFP_NOLOCKDEP)
144 
145 /* The GFP flags allowed during early boot */
146 #define GFP_BOOT_MASK (__GFP_BITS_MASK & ~(__GFP_RECLAIM|__GFP_IO|__GFP_FS))
147 
148 /* Control allocation cpuset and node placement constraints */
149 #define GFP_CONSTRAINT_MASK (__GFP_HARDWALL|__GFP_THISNODE)
150 
151 /* Do not use these with a slab allocator */
152 #define GFP_SLAB_BUG_MASK (__GFP_DMA32|__GFP_HIGHMEM|~__GFP_BITS_MASK)
153 
154 /*
155  * Different from WARN_ON_ONCE(), no warning will be issued
156  * when we specify __GFP_NOWARN.
157  */
158 #define WARN_ON_ONCE_GFP(cond, gfp)	({				\
159 	static bool __section(".data..once") __warned;			\
160 	int __ret_warn_once = !!(cond);					\
161 									\
162 	if (unlikely(!(gfp & __GFP_NOWARN) && __ret_warn_once && !__warned)) { \
163 		__warned = true;					\
164 		WARN_ON(1);						\
165 	}								\
166 	unlikely(__ret_warn_once);					\
167 })
168 
169 void page_writeback_init(void);
170 
171 /*
172  * If a 16GB hugetlb folio were mapped by PTEs of all of its 4kB pages,
173  * its nr_pages_mapped would be 0x400000: choose the ENTIRELY_MAPPED bit
174  * above that range, instead of 2*(PMD_SIZE/PAGE_SIZE).  Hugetlb currently
175  * leaves nr_pages_mapped at 0, but avoid surprise if it participates later.
176  */
177 #define ENTIRELY_MAPPED		0x800000
178 #define FOLIO_PAGES_MAPPED	(ENTIRELY_MAPPED - 1)
179 
180 /*
181  * Flags passed to __show_mem() and show_free_areas() to suppress output in
182  * various contexts.
183  */
184 #define SHOW_MEM_FILTER_NODES		(0x0001u)	/* disallowed nodes */
185 
186 /*
187  * How many individual pages have an elevated _mapcount.  Excludes
188  * the folio's entire_mapcount.
189  *
190  * Don't use this function outside of debugging code.
191  */
192 static inline int folio_nr_pages_mapped(const struct folio *folio)
193 {
194 	if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT))
195 		return -1;
196 	return atomic_read(&folio->_nr_pages_mapped) & FOLIO_PAGES_MAPPED;
197 }
198 
199 /*
200  * Retrieve the first entry of a folio based on a provided entry within the
201  * folio. We cannot rely on folio->swap as there is no guarantee that it has
202  * been initialized. Used for calling arch_swap_restore()
203  */
204 static inline swp_entry_t folio_swap(swp_entry_t entry,
205 		const struct folio *folio)
206 {
207 	swp_entry_t swap = {
208 		.val = ALIGN_DOWN(entry.val, folio_nr_pages(folio)),
209 	};
210 
211 	return swap;
212 }
213 
214 static inline void *folio_raw_mapping(const struct folio *folio)
215 {
216 	unsigned long mapping = (unsigned long)folio->mapping;
217 
218 	return (void *)(mapping & ~FOLIO_MAPPING_FLAGS);
219 }
220 
221 /*
222  * If the VMA has a close hook then close it, and since closing it might leave
223  * it in an inconsistent state which makes the use of any hooks suspect, clear
224  * them down by installing dummy empty hooks.
225  */
226 static inline void vma_close(struct vm_area_struct *vma)
227 {
228 	if (vma->vm_ops && vma->vm_ops->close) {
229 		vma->vm_ops->close(vma);
230 
231 		/*
232 		 * The mapping is in an inconsistent state, and no further hooks
233 		 * may be invoked upon it.
234 		 */
235 		vma->vm_ops = &vma_dummy_vm_ops;
236 	}
237 }
238 
239 /*
240  * This is a file-backed mapping, and is about to be memory mapped - invoke its
241  * mmap hook and safely handle error conditions. On error, VMA hooks will be
242  * mutated.
243  *
244  * @file: File which backs the mapping.
245  * @vma:  VMA which we are mapping.
246  *
247  * Returns: 0 if success, error otherwise.
248  */
249 static inline int mmap_file(struct file *file, struct vm_area_struct *vma)
250 {
251 	const unsigned long orig_start = vma->vm_start;
252 	const unsigned long orig_end = vma->vm_end;
253 	const vma_flags_t orig_flags = vma->flags;
254 	int err;
255 
256 	err = vfs_mmap(file, vma);
257 	/*
258 	 * Either we tried to call the file hook for mmap() and an error arose
259 	 * or a driver set vma->vm_ops = NULL intending there to be no VMA
260 	 * operations.
261 	 *
262 	 * In the former case the VMA is in an inconsistent state and we mustn't
263 	 * invoke any further hooks on it, in the latter case the hook actually
264 	 * wanted no further hooks to be invoked, so fix both by setting dummy
265 	 * VMA ops.
266 	 */
267 	if (unlikely(err || !vma->vm_ops))
268 		vma->vm_ops = &vma_dummy_vm_ops;
269 	if (unlikely(err))
270 		return err;
271 
272 	err = mmap_hook_validate(orig_start, orig_end, &orig_flags, vma);
273 	if (unlikely(err)) {
274 		vma->vm_start = orig_start;
275 		vma->vm_end = orig_end;
276 	}
277 
278 	return err;
279 }
280 
281 /* unmap_vmas is in mm/memory.c */
282 void unmap_vmas(struct mmu_gather *tlb, struct unmap_desc *unmap);
283 
284 #ifdef CONFIG_MMU
285 
286 bool cond_install_uffd_wp_ptes(struct vm_area_struct *vma,
287 		unsigned long addr, pte_t *ptep, pte_t pte,
288 		unsigned long nr_ptes);
289 
290 static inline void get_anon_vma(struct anon_vma *anon_vma)
291 {
292 	atomic_inc(&anon_vma->refcount);
293 }
294 
295 void __put_anon_vma(struct anon_vma *anon_vma);
296 
297 static inline void put_anon_vma(struct anon_vma *anon_vma)
298 {
299 	if (atomic_dec_and_test(&anon_vma->refcount))
300 		__put_anon_vma(anon_vma);
301 }
302 
303 static inline void anon_vma_lock_write(struct anon_vma *anon_vma)
304 {
305 	down_write(&anon_vma->root->rwsem);
306 }
307 
308 static inline void anon_vma_unlock_write(struct anon_vma *anon_vma)
309 {
310 	up_write(&anon_vma->root->rwsem);
311 }
312 
313 static inline void anon_vma_lock_read(struct anon_vma *anon_vma)
314 {
315 	down_read(&anon_vma->root->rwsem);
316 }
317 
318 static inline int anon_vma_trylock_read(struct anon_vma *anon_vma)
319 {
320 	return down_read_trylock(&anon_vma->root->rwsem);
321 }
322 
323 static inline void anon_vma_unlock_read(struct anon_vma *anon_vma)
324 {
325 	up_read(&anon_vma->root->rwsem);
326 }
327 
328 struct anon_vma *folio_get_anon_vma(const struct folio *folio);
329 
330 /* Operations which modify VMAs. */
331 enum vma_operation {
332 	VMA_OP_SPLIT,
333 	VMA_OP_MERGE_UNFAULTED,
334 	VMA_OP_REMAP,
335 	VMA_OP_FORK,
336 };
337 
338 int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src,
339 	enum vma_operation operation);
340 int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma);
341 int  __anon_vma_prepare(struct vm_area_struct *vma);
342 void unlink_anon_vmas(struct vm_area_struct *vma);
343 
344 static inline int anon_vma_prepare(struct vm_area_struct *vma)
345 {
346 	if (likely(vma_has_anon_rmap(vma)))
347 		return 0;
348 
349 	return __anon_vma_prepare(vma);
350 }
351 
352 /* Flags for folio_pte_batch(). */
353 typedef int __bitwise fpb_t;
354 
355 /* Compare PTEs respecting the dirty bit. */
356 #define FPB_RESPECT_DIRTY		((__force fpb_t)BIT(0))
357 
358 /* Compare PTEs respecting the soft-dirty bit. */
359 #define FPB_RESPECT_SOFT_DIRTY		((__force fpb_t)BIT(1))
360 
361 /* Compare PTEs respecting the writable bit. */
362 #define FPB_RESPECT_WRITE		((__force fpb_t)BIT(2))
363 
364 /*
365  * Merge PTE write bits: if any PTE in the batch is writable, modify the
366  * PTE at @ptentp to be writable.
367  */
368 #define FPB_MERGE_WRITE			((__force fpb_t)BIT(3))
369 
370 /*
371  * Merge PTE young and dirty bits: if any PTE in the batch is young or dirty,
372  * modify the PTE at @ptentp to be young or dirty, respectively.
373  */
374 #define FPB_MERGE_YOUNG_DIRTY		((__force fpb_t)BIT(4))
375 
376 static inline pte_t __pte_batch_clear_ignored(pte_t pte, fpb_t flags)
377 {
378 	if (!(flags & FPB_RESPECT_DIRTY))
379 		pte = pte_mkclean(pte);
380 	if (likely(!(flags & FPB_RESPECT_SOFT_DIRTY)))
381 		pte = pte_clear_soft_dirty(pte);
382 	if (likely(!(flags & FPB_RESPECT_WRITE)))
383 		pte = pte_wrprotect(pte);
384 	return pte_mkold(pte);
385 }
386 
387 /**
388  * folio_pte_batch_flags - detect a PTE batch for a large folio
389  * @folio: The large folio to detect a PTE batch for.
390  * @vma: The VMA. Only relevant with FPB_MERGE_WRITE, otherwise can be NULL.
391  * @ptep: Page table pointer for the first entry.
392  * @ptentp: Pointer to a COPY of the first page table entry whose flags this
393  *	    function updates based on @flags if appropriate.
394  * @max_nr: The maximum number of table entries to consider.
395  * @flags: Flags to modify the PTE batch semantics.
396  *
397  * Detect a PTE batch: consecutive (present) PTEs that map consecutive
398  * pages of the same large folio in a single VMA and a single page table.
399  *
400  * All PTEs inside a PTE batch have the same PTE bits set, excluding the PFN,
401  * the accessed bit, writable bit, dirty bit (unless FPB_RESPECT_DIRTY is set)
402  * and soft-dirty bit (unless FPB_RESPECT_SOFT_DIRTY is set).
403  *
404  * @ptep must map any page of the folio. max_nr must be at least one and
405  * must be limited by the caller so scanning cannot exceed a single VMA and
406  * a single page table.
407  *
408  * Depending on the FPB_MERGE_* flags, the pte stored at @ptentp will
409  * be updated: it's crucial that a pointer to a COPY of the first
410  * page table entry, obtained through ptep_get(), is provided as @ptentp.
411  *
412  * This function will be inlined to optimize based on the input parameters;
413  * consider using folio_pte_batch() instead if applicable.
414  *
415  * Return: the number of table entries in the batch.
416  */
417 static inline unsigned int folio_pte_batch_flags(struct folio *folio,
418 		struct vm_area_struct *vma, pte_t *ptep, pte_t *ptentp,
419 		unsigned int max_nr, fpb_t flags)
420 {
421 	bool any_writable = false, any_young = false, any_dirty = false;
422 	pte_t expected_pte, pte = *ptentp;
423 	unsigned int nr, cur_nr;
424 
425 	VM_WARN_ON_FOLIO(!pte_present(pte), folio);
426 	VM_WARN_ON_FOLIO(!folio_test_large(folio) || max_nr < 1, folio);
427 	VM_WARN_ON_FOLIO(page_folio(pfn_to_page(pte_pfn(pte))) != folio, folio);
428 	/*
429 	 * Ensure this is a pointer to a copy not a pointer into a page table.
430 	 * If this is a stack value, it won't be a valid virtual address, but
431 	 * that's fine because it also cannot be pointing into the page table.
432 	 */
433 	VM_WARN_ON(virt_addr_valid(ptentp) && PageTable(virt_to_page(ptentp)));
434 
435 	/* Limit max_nr to the actual remaining PFNs in the folio we could batch. */
436 	max_nr = min_t(unsigned long, max_nr,
437 		       folio_pfn(folio) + folio_nr_pages(folio) - pte_pfn(pte));
438 
439 	nr = pte_batch_hint(ptep, pte);
440 	expected_pte = __pte_batch_clear_ignored(pte_advance_pfn(pte, nr), flags);
441 	ptep = ptep + nr;
442 
443 	while (nr < max_nr) {
444 		pte = ptep_get(ptep);
445 
446 		if (!pte_same(__pte_batch_clear_ignored(pte, flags), expected_pte))
447 			break;
448 
449 		if (flags & FPB_MERGE_WRITE)
450 			any_writable |= pte_write(pte);
451 		if (flags & FPB_MERGE_YOUNG_DIRTY) {
452 			any_young |= pte_young(pte);
453 			any_dirty |= pte_dirty(pte);
454 		}
455 
456 		cur_nr = pte_batch_hint(ptep, pte);
457 		expected_pte = pte_advance_pfn(expected_pte, cur_nr);
458 		ptep += cur_nr;
459 		nr += cur_nr;
460 	}
461 
462 	if (any_writable)
463 		*ptentp = pte_mkwrite(*ptentp, vma);
464 	if (any_young)
465 		*ptentp = pte_mkyoung(*ptentp);
466 	if (any_dirty)
467 		*ptentp = pte_mkdirty(*ptentp);
468 
469 	return min(nr, max_nr);
470 }
471 
472 unsigned int folio_pte_batch(struct folio *folio, pte_t *ptep, pte_t pte,
473 		unsigned int max_nr);
474 
475 /**
476  * pte_move_swp_offset - Move the swap entry offset field of a swap pte
477  *	 forward or backward by delta
478  * @pte: The initial pte state; must be a swap entry
479  * @delta: The direction and the offset we are moving; forward if delta
480  *	 is positive; backward if delta is negative
481  *
482  * Moves the swap offset, while maintaining all other fields, including
483  * swap type, and any swp pte bits. The resulting pte is returned.
484  */
485 static inline pte_t pte_move_swp_offset(pte_t pte, long delta)
486 {
487 	const softleaf_t entry = softleaf_from_pte(pte);
488 	pte_t new = __swp_entry_to_pte(__swp_entry(swp_type(entry),
489 						   (swp_offset(entry) + delta)));
490 
491 	if (pte_swp_soft_dirty(pte))
492 		new = pte_swp_mksoft_dirty(new);
493 	if (pte_swp_exclusive(pte))
494 		new = pte_swp_mkexclusive(new);
495 	if (pte_swp_uffd(pte))
496 		new = pte_swp_mkuffd(new);
497 
498 	return new;
499 }
500 
501 
502 /**
503  * pte_next_swp_offset - Increment the swap entry offset field of a swap pte.
504  * @pte: The initial pte state; must be a swap entry.
505  *
506  * Increments the swap offset, while maintaining all other fields, including
507  * swap type, and any swp pte bits. The resulting pte is returned.
508  */
509 static inline pte_t pte_next_swp_offset(pte_t pte)
510 {
511 	return pte_move_swp_offset(pte, 1);
512 }
513 
514 /**
515  * swap_pte_batch - detect a PTE batch for a set of contiguous swap entries
516  * @start_ptep: Page table pointer for the first entry.
517  * @max_nr: The maximum number of table entries to consider.
518  * @pte: Page table entry for the first entry.
519  *
520  * Detect a batch of contiguous swap entries: consecutive (non-present) PTEs
521  * containing swap entries all with consecutive offsets and targeting the same
522  * swap type, all with matching swp pte bits.
523  *
524  * max_nr must be at least one and must be limited by the caller so scanning
525  * cannot exceed a single page table.
526  *
527  * Return: the number of table entries in the batch.
528  */
529 static inline int swap_pte_batch(pte_t *start_ptep, int max_nr, pte_t pte)
530 {
531 	pte_t expected_pte = pte_next_swp_offset(pte);
532 	const pte_t *end_ptep = start_ptep + max_nr;
533 	pte_t *ptep = start_ptep + 1;
534 
535 	VM_WARN_ON(max_nr < 1);
536 	VM_WARN_ON(!softleaf_is_swap(softleaf_from_pte(pte)));
537 
538 	while (ptep < end_ptep) {
539 		pte = ptep_get(ptep);
540 
541 		if (!pte_same(pte, expected_pte))
542 			break;
543 		expected_pte = pte_next_swp_offset(expected_pte);
544 		ptep++;
545 	}
546 
547 	return ptep - start_ptep;
548 }
549 #endif /* CONFIG_MMU */
550 
551 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
552 						int nr_throttled);
553 static inline void acct_reclaim_writeback(struct folio *folio)
554 {
555 	pg_data_t *pgdat = folio_pgdat(folio);
556 	int nr_throttled = atomic_read(&pgdat->nr_writeback_throttled);
557 
558 	if (nr_throttled)
559 		__acct_reclaim_writeback(pgdat, folio, nr_throttled);
560 }
561 
562 static inline void wake_throttle_isolated(pg_data_t *pgdat)
563 {
564 	wait_queue_head_t *wqh;
565 
566 	wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_ISOLATED];
567 	if (waitqueue_active(wqh))
568 		wake_up(wqh);
569 }
570 
571 vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf);
572 static inline vm_fault_t vmf_anon_prepare(struct vm_fault *vmf)
573 {
574 	vm_fault_t ret = __vmf_anon_prepare(vmf);
575 
576 	if (unlikely(ret & VM_FAULT_RETRY))
577 		vma_end_read(vmf->vma);
578 	return ret;
579 }
580 
581 vm_fault_t do_swap_page(struct vm_fault *vmf);
582 void folio_rotate_reclaimable(struct folio *folio);
583 bool __folio_end_writeback(struct folio *folio);
584 void deactivate_file_folio(struct folio *folio);
585 void folio_activate(struct folio *folio);
586 
587 void free_pgtables(struct mmu_gather *tlb, struct unmap_desc *desc);
588 
589 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte);
590 
591 /**
592  * sync_with_folio_pmd_zap - sync with concurrent zapping of folios
593  * @mm: The mm_struct.
594  * @pmdp: Pointer to the pmd that was found to be pmd_none().
595  *
596  * When we find a pmd_none() while unmapping a folio without holding the PTL,
597  * zap_huge_pmd() may have cleared the PMD but not yet updated the folio
598  * mapcount, and zap_empty_pte_table() clears the PMD only after the rmaps
599  * for the table have been removed, but nothing orders the pmd_none() read
600  * against later mapcount reads. Skipping the PMD without synchronization
601  * could make folio unmapping code assume that unmapping failed.
602  *
603  * Wait for concurrent zapping to complete by grabbing the PTL.
604  */
605 static inline void sync_with_folio_pmd_zap(struct mm_struct *mm, pmd_t *pmdp)
606 {
607 	spinlock_t *ptl = pmd_lock(mm, pmdp);
608 
609 	spin_unlock(ptl);
610 }
611 
612 struct zap_details;
613 void zap_vma_range_batched(struct mmu_gather *tlb,
614 		struct vm_area_struct *vma, unsigned long addr,
615 		unsigned long size, struct zap_details *details);
616 int zap_vma_for_reaping(struct vm_area_struct *vma);
617 int folio_unmap_invalidate(struct address_space *mapping, struct folio *folio,
618 			   gfp_t gfp);
619 
620 void page_cache_ra_order(struct readahead_control *, struct file_ra_state *);
621 void force_page_cache_ra(struct readahead_control *, unsigned long nr);
622 static inline void force_page_cache_readahead(struct address_space *mapping,
623 		struct file *file, pgoff_t index, unsigned long nr_to_read)
624 {
625 	DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, index);
626 	force_page_cache_ra(&ractl, nr_to_read);
627 }
628 
629 /*
630  * Take two page table locks at the same level in address order such that
631  * we cannot deadlock.
632  */
633 static inline void double_pt_lock(spinlock_t *ptl1, spinlock_t *ptl2)
634 	__acquires(ptl1)
635 	__acquires(ptl2)
636 {
637 	if (ptl1 > ptl2)
638 		swap(ptl1, ptl2);
639 	spin_lock(ptl1);
640 	if (ptl1 != ptl2)
641 		spin_lock_nested(ptl2, SINGLE_DEPTH_NESTING);
642 	else
643 		__acquire(ptl2);
644 }
645 
646 static inline void double_pt_unlock(spinlock_t *ptl1, spinlock_t *ptl2)
647 	__releases(ptl1)
648 	__releases(ptl2)
649 {
650 	spin_unlock(ptl1);
651 	if (ptl1 != ptl2)
652 		spin_unlock(ptl2);
653 	else
654 		__release(ptl2);
655 }
656 
657 unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,
658 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices);
659 unsigned find_get_entries(struct address_space *mapping, pgoff_t *start,
660 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices);
661 int truncate_inode_folio(struct address_space *mapping, struct folio *folio);
662 bool truncate_inode_partial_folio(struct folio *folio, loff_t lstart,
663 		loff_t lend, pgoff_t *pstart, pgoff_t *pend);
664 long mapping_evict_folio(struct address_space *mapping, struct folio *folio);
665 unsigned long mapping_try_invalidate(struct address_space *mapping,
666 		pgoff_t start, pgoff_t end, unsigned long *nr_failed);
667 
668 /**
669  * folio_evictable - Test whether a folio is evictable.
670  * @folio: The folio to test.
671  *
672  * Test whether @folio is evictable -- i.e., should be placed on
673  * active/inactive lists vs unevictable list.
674  *
675  * Reasons folio might not be evictable:
676  * 1. folio's mapping marked unevictable
677  * 2. One of the pages in the folio is part of an mlocked VMA
678  */
679 static inline bool folio_evictable(struct folio *folio)
680 {
681 	bool ret;
682 
683 	/* Prevent address_space of inode and swap cache from being freed */
684 	rcu_read_lock();
685 	ret = !mapping_unevictable(folio_mapping(folio)) &&
686 			!folio_test_mlocked(folio);
687 	rcu_read_unlock();
688 	return ret;
689 }
690 
691 /*
692  * Turn a non-refcounted page (->_refcount == 0) into refcounted with
693  * a count of one.
694  */
695 static inline void set_page_refcounted(struct page *page)
696 {
697 	VM_BUG_ON_PAGE(PageTail(page), page);
698 	VM_BUG_ON_PAGE(page_ref_count(page), page);
699 	set_page_count(page, 1);
700 }
701 
702 static inline void set_pages_refcounted(struct page *page, unsigned long nr_pages)
703 {
704 	unsigned long pfn = page_to_pfn(page);
705 
706 	for (; nr_pages--; pfn++)
707 		set_page_refcounted(pfn_to_page(pfn));
708 }
709 
710 /*
711  * Return true if a folio needs ->release_folio() calling upon it.
712  */
713 static inline bool folio_needs_release(struct folio *folio)
714 {
715 	struct address_space *mapping = folio_mapping(folio);
716 
717 	return folio_has_private(folio) ||
718 		(mapping && mapping_release_always(mapping));
719 }
720 
721 extern unsigned long highest_memmap_pfn;
722 
723 /*
724  * Maximum number of reclaim retries without progress before the OOM
725  * killer is consider the only way forward.
726  */
727 #define MAX_RECLAIM_RETRIES 16
728 
729 /*
730  * in mm/vmscan.c:
731  */
732 bool folio_isolate_lru(struct folio *folio);
733 void folio_putback_lru(struct folio *folio);
734 extern void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason);
735 int user_proactive_reclaim(char *buf,
736 			   struct mem_cgroup *memcg, pg_data_t *pgdat);
737 
738 /*
739  * in mm/rmap.c:
740  */
741 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address);
742 
743 /*
744  * in mm/khugepaged.c
745  */
746 void set_recommended_min_free_kbytes(void);
747 
748 /*
749  * in mm/page_alloc.c
750  */
751 #define K(x) ((x) << (PAGE_SHIFT-10))
752 
753 extern char * const zone_names[MAX_NR_ZONES];
754 
755 extern int min_free_kbytes;
756 extern int defrag_mode;
757 
758 void setup_per_zone_wmarks(void);
759 void calculate_min_free_kbytes(void);
760 int __meminit init_per_zone_wmark_min(void);
761 
762 extern int __isolate_free_page(struct page *page, unsigned int order);
763 extern void __putback_isolated_page(struct page *page, unsigned int order,
764 				    int mt);
765 
766 /*
767  * This will have no effect, other than possibly generating a warning, if the
768  * caller passes in a non-large folio.
769  */
770 static inline void folio_set_order(struct folio *folio, unsigned int order)
771 {
772 	if (WARN_ON_ONCE(!order || !folio_test_large(folio)))
773 		return;
774 	VM_WARN_ON_ONCE(order > MAX_FOLIO_ORDER);
775 
776 	folio->_flags_1 = (folio->_flags_1 & ~0xffUL) | order;
777 #ifdef NR_PAGES_IN_LARGE_FOLIO
778 	folio->_nr_pages = 1U << order;
779 #endif
780 }
781 
782 bool __folio_unqueue_deferred_split(struct folio *folio);
783 static inline bool folio_unqueue_deferred_split(struct folio *folio)
784 {
785 	if (folio_order(folio) <= 1 || !folio_test_large_rmappable(folio))
786 		return false;
787 
788 	/*
789 	 * At this point, there is no one trying to add the folio to
790 	 * deferred_list. If folio is not in deferred_list, it's safe
791 	 * to check without acquiring the list_lru lock.
792 	 */
793 	if (data_race(list_empty(&folio->_deferred_list)))
794 		return false;
795 
796 	return __folio_unqueue_deferred_split(folio);
797 }
798 
799 static inline struct folio *page_rmappable_folio(struct page *page)
800 {
801 	struct folio *folio = (struct folio *)page;
802 
803 	if (folio && folio_test_large(folio))
804 		folio_set_large_rmappable(folio);
805 	return folio;
806 }
807 
808 static inline void prep_compound_head(struct page *page, unsigned int order)
809 {
810 	struct folio *folio = (struct folio *)page;
811 
812 	folio_set_order(folio, order);
813 	atomic_set(&folio->_large_mapcount, -1);
814 	if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
815 		atomic_set(&folio->_nr_pages_mapped, 0);
816 	if (IS_ENABLED(CONFIG_MM_ID)) {
817 		folio->_mm_ids = 0;
818 		folio->_mm_id_mapcount[0] = -1;
819 		folio->_mm_id_mapcount[1] = -1;
820 	}
821 	if (IS_ENABLED(CONFIG_64BIT) || order > 1) {
822 		atomic_set(&folio->_pincount, 0);
823 		atomic_set(&folio->_entire_mapcount, -1);
824 	}
825 	if (order > 1)
826 		INIT_LIST_HEAD(&folio->_deferred_list);
827 }
828 
829 static inline void prep_compound_tail(struct page *tail,
830 		const struct page *head, unsigned int order)
831 {
832 	tail->mapping = TAIL_MAPPING;
833 	set_compound_head(tail, head, order);
834 	VM_WARN_ON_ONCE(tail->private);
835 }
836 
837 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
838 
839 /*
840  * in mm/compaction.c
841  */
842 /*
843  * compact_control is used to track pages being migrated and the free pages
844  * they are being migrated to during memory compaction. The free_pfn starts
845  * at the end of a zone and migrate_pfn begins at the start. Movable pages
846  * are moved to the end of a zone during a compaction run and the run
847  * completes when free_pfn <= migrate_pfn
848  */
849 struct compact_control {
850 	struct list_head freepages[NR_PAGE_ORDERS];	/* List of free pages to migrate to */
851 	struct list_head migratepages;	/* List of pages being migrated */
852 	unsigned int nr_freepages;	/* Number of isolated free pages */
853 	unsigned int nr_migratepages;	/* Number of pages to migrate */
854 	unsigned long free_pfn;		/* isolate_freepages search base */
855 	/*
856 	 * Acts as an in/out parameter to page isolation for migration.
857 	 * isolate_migratepages uses it as a search base.
858 	 * isolate_migratepages_block will update the value to the next pfn
859 	 * after the last isolated one.
860 	 */
861 	unsigned long migrate_pfn;
862 	unsigned long fast_start_pfn;	/* a pfn to start linear scan from */
863 	struct zone *zone;
864 	unsigned long total_migrate_scanned;
865 	unsigned long total_free_scanned;
866 	unsigned short fast_search_fail;/* failures to use free list searches */
867 	short search_order;		/* order to start a fast search at */
868 	const gfp_t gfp_mask;		/* gfp mask of a direct compactor */
869 	int order;			/* order a direct compactor needs */
870 	int migratetype;		/* migratetype of direct compactor */
871 	const unsigned int alloc_flags;	/* alloc flags of a direct compactor */
872 	const int highest_zoneidx;	/* zone index of a direct compactor */
873 	enum migrate_mode mode;		/* Async or sync migration mode */
874 	bool ignore_skip_hint;		/* Scan blocks even if marked skip */
875 	bool no_set_skip_hint;		/* Don't mark blocks for skipping */
876 	bool ignore_block_suitable;	/* Scan blocks considered unsuitable */
877 	bool direct_compaction;		/* False from kcompactd or /proc/... */
878 	bool proactive_compaction;	/* kcompactd proactive compaction */
879 	bool whole_zone;		/* Whole zone should/has been scanned */
880 	bool contended;			/* Signal lock contention */
881 	bool finish_pageblock;		/* Scan the remainder of a pageblock. Used
882 					 * when there are potentially transient
883 					 * isolation or migration failures to
884 					 * ensure forward progress.
885 					 */
886 	bool alloc_contig;		/* alloc_contig_range allocation */
887 };
888 
889 /*
890  * Used in direct compaction when a page should be taken from the freelists
891  * immediately when one is created during the free path.
892  */
893 struct capture_control {
894 	struct zone *zone;
895 	int migratetype;
896 	/*
897 	 * Allocation request order. May differ from the compaction
898 	 * order: defrag_mode promotes sub-block allocations to
899 	 * pageblock-order compaction; capture still matches at the
900 	 * original allocation order so prep_new_page() is consistent.
901 	 */
902 	int order;
903 	struct page *page;
904 };
905 
906 unsigned long
907 isolate_freepages_range(struct compact_control *cc,
908 			unsigned long start_pfn, unsigned long end_pfn);
909 int
910 isolate_migratepages_range(struct compact_control *cc,
911 			   unsigned long low_pfn, unsigned long end_pfn);
912 
913 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
914 
915 struct cma;
916 
917 #ifdef CONFIG_CMA
918 bool cma_validate_zones(struct cma *cma);
919 void *cma_reserve_early(struct cma *cma, unsigned long size);
920 #else
921 static inline bool cma_validate_zones(struct cma *cma)
922 {
923 	return false;
924 }
925 static inline void *cma_reserve_early(struct cma *cma, unsigned long size)
926 {
927 	return NULL;
928 }
929 #endif
930 
931 /* mm/util.c */
932 struct anon_vma *folio_anon_vma(const struct folio *folio);
933 
934 #ifdef CONFIG_MMU
935 void unmap_mapping_folio(struct folio *folio);
936 extern long populate_vma_page_range(struct vm_area_struct *vma,
937 		unsigned long start, unsigned long end, int *locked);
938 extern long faultin_page_range(struct mm_struct *mm, unsigned long start,
939 		unsigned long end, bool write, int *locked);
940 bool mlock_future_ok(const struct mm_struct *mm, bool is_vma_locked,
941 		unsigned long bytes);
942 
943 /*
944  * NOTE: This function can't tell whether the folio is "fully mapped" in the
945  * range.
946  * "fully mapped" means all the pages of folio is associated with the page
947  * table of range while this function just check whether the folio range is
948  * within the range [start, end). Function caller needs to do page table
949  * check if it cares about the page table association.
950  *
951  * Typical usage (like mlock or madvise) is:
952  * Caller knows at least 1 page of folio is associated with page table of VMA
953  * and the range [start, end) is intersect with the VMA range. Caller wants
954  * to know whether the folio is fully associated with the range. It calls
955  * this function to check whether the folio is in the range first. Then checks
956  * the page table to know whether the folio is fully mapped to the range.
957  */
958 static inline bool
959 folio_within_range(struct folio *folio, struct vm_area_struct *vma,
960 		unsigned long start, unsigned long end)
961 {
962 	const unsigned long vma_pglen = vma_pages(vma);
963 	pgoff_t pgoff_folio, pgoff_vma_start;
964 	unsigned long addr;
965 
966 	VM_WARN_ON_FOLIO(folio_test_ksm(folio), folio);
967 	if (start > end)
968 		return false;
969 
970 	pgoff_folio = folio_pgoff(folio);
971 	pgoff_vma_start = folio_test_anon(folio) ?
972 		vma_start_anon_pgoff(vma) : vma_start_pgoff(vma);
973 
974 	if (start < vma->vm_start)
975 		start = vma->vm_start;
976 
977 	if (end > vma->vm_end)
978 		end = vma->vm_end;
979 
980 	/* if folio start address is not in vma range */
981 	if (!in_range(pgoff_folio, pgoff_vma_start, vma_pglen))
982 		return false;
983 
984 	addr = vma->vm_start + ((pgoff_folio - pgoff_vma_start) << PAGE_SHIFT);
985 
986 	return !(addr < start || end - addr < folio_size(folio));
987 }
988 
989 static inline bool
990 folio_within_vma(struct folio *folio, struct vm_area_struct *vma)
991 {
992 	return folio_within_range(folio, vma, vma->vm_start, vma->vm_end);
993 }
994 
995 /*
996  * mlock_vma_folio() and munlock_vma_folio():
997  * should be called with vma's mmap_lock held for read or write,
998  * under page table lock for the pte/pmd being added or removed.
999  *
1000  * mlock is usually called at the end of folio_add_*_rmap_*(), munlock at
1001  * the end of folio_remove_rmap_*(); but new anon folios are managed by
1002  * folio_add_lru_vma() calling mlock_new_folio().
1003  */
1004 void mlock_folio(struct folio *folio);
1005 static inline void mlock_vma_folio(struct folio *folio,
1006 				struct vm_area_struct *vma)
1007 {
1008 	if (vma_test(vma, VMA_LOCKED_BIT))
1009 		mlock_folio(folio);
1010 }
1011 
1012 void munlock_folio(struct folio *folio);
1013 static inline void munlock_vma_folio(struct folio *folio,
1014 					struct vm_area_struct *vma)
1015 {
1016 	/*
1017 	 * munlock if the function is called. Ideally, we should only
1018 	 * do munlock if any page of folio is unmapped from VMA and
1019 	 * cause folio not fully mapped to VMA.
1020 	 *
1021 	 * But it's not easy to confirm that's the situation. So we
1022 	 * always munlock the folio and page reclaim will correct it
1023 	 * if it's wrong.
1024 	 */
1025 	/*
1026 	 * VMA_LOCKONFAULT_BIT alone marks an mlock walk in progress, see
1027 	 * mlock_vma_pages_range(). An unmap racing with the walk must still
1028 	 * munlock folios the walk has already counted.
1029 	 */
1030 	if (unlikely(vma_test_any_mask(vma, VMA_LOCKED_MASK)))
1031 		munlock_folio(folio);
1032 }
1033 
1034 void mlock_new_folio(struct folio *folio);
1035 bool need_mlock_drain(int cpu);
1036 void mlock_drain_local(void);
1037 void mlock_drain_remote(int cpu);
1038 
1039 extern pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma);
1040 
1041 static inline unsigned long __vma_address(const struct vm_area_struct *vma,
1042 		pgoff_t pgoff, pgoff_t pgoff_start, unsigned long nr_pages)
1043 {
1044 	unsigned long address;
1045 
1046 	if (pgoff >= pgoff_start) {
1047 		address = vma->vm_start +
1048 			((pgoff - pgoff_start) << PAGE_SHIFT);
1049 		/* Check for address beyond vma (or wrapped through 0?) */
1050 		if (address < vma->vm_start || address >= vma->vm_end)
1051 			address = -EFAULT;
1052 	} else if (pgoff + nr_pages - 1 >= pgoff_start) {
1053 		/* Test above avoids possibility of wrap to 0 on 32-bit */
1054 		address = vma->vm_start;
1055 	} else {
1056 		address = -EFAULT;
1057 	}
1058 	return address;
1059 }
1060 
1061 /**
1062  * vma_filebacked_address - Find the virtual address a file-backed page range is
1063  * mapped at.
1064  * @vma: The vma which maps this object.
1065  * @pgoff: The page offset within its object.
1066  * @nr_pages: The number of pages to consider.
1067  *
1068  * Returns: If any page in this range is mapped by this VMA, return the first
1069  * address where any of these pages appear.  Otherwise, return -EFAULT.
1070  */
1071 static inline unsigned long vma_filebacked_address(const struct vm_area_struct *vma,
1072 		pgoff_t pgoff, unsigned long nr_pages)
1073 {
1074 	VM_WARN_ON_ONCE(vma_is_anonymous(vma));
1075 
1076 	return __vma_address(vma, pgoff, vma_start_pgoff(vma), nr_pages);
1077 }
1078 
1079 /**
1080  * vma_anon_address - Find the virtual address an anonymous page range is mapped
1081  * at.
1082  * @vma: The vma which maps this object.
1083  * @pgoff_anon: The anonymous page index belonging to the folio.
1084  * @nr_pages: The number of pages to consider.
1085  *
1086  * This is only valid for anonymous or MAP_PRIVATE-mapped file-backed VMAs.
1087  *
1088  * Returns: If any page in this range is mapped by this VMA, return the first
1089  * address where any of these pages appear. Otherwise, return -EFAULT.
1090  */
1091 static inline unsigned long vma_anon_address(const struct vm_area_struct *vma,
1092 		pgoff_t pgoff_anon, unsigned long nr_pages)
1093 {
1094 	VM_WARN_ON_ONCE(!vma_is_cow_mapping(vma));
1095 
1096 	return __vma_address(vma, pgoff_anon, vma_start_anon_pgoff(vma), nr_pages);
1097 }
1098 
1099 /*
1100  * At what user virtual address will none of the range be found in vma?
1101  * Assumes that vma_address() already returned a good starting address.
1102  */
1103 static inline unsigned long vma_address_end(struct page_vma_mapped_walk *pvmw)
1104 {
1105 	const pgoff_t pgoff_end = pvmw->pgoff + pvmw->nr_pages;
1106 	const struct vm_area_struct *vma = pvmw->vma;
1107 	pgoff_t pgoff_vma_start;
1108 	unsigned long address;
1109 
1110 	/* Common case, plus ->pgoff is invalid for KSM */
1111 	if (pvmw->nr_pages == 1)
1112 		return pvmw->address + PAGE_SIZE;
1113 
1114 	if (pvmw->pgoff_is_anon)
1115 		pgoff_vma_start = vma_start_anon_pgoff(vma);
1116 	else
1117 		pgoff_vma_start = vma_start_pgoff(vma);
1118 
1119 	address = vma->vm_start +
1120 		((pgoff_end - pgoff_vma_start) << PAGE_SHIFT);
1121 	/* Check for address beyond vma (or wrapped through 0?) */
1122 	if (address < vma->vm_start || address > vma->vm_end)
1123 		address = vma->vm_end;
1124 	return address;
1125 }
1126 
1127 static inline struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
1128 						    struct file *fpin)
1129 {
1130 	int flags = vmf->flags;
1131 
1132 	if (fpin)
1133 		return fpin;
1134 
1135 	/*
1136 	 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
1137 	 * anything, so we only pin the file and drop the mmap_lock if only
1138 	 * FAULT_FLAG_ALLOW_RETRY is set, while this is the first attempt.
1139 	 */
1140 	if (fault_flag_allow_retry_first(flags) &&
1141 	    !(flags & FAULT_FLAG_RETRY_NOWAIT)) {
1142 		fpin = get_file(vmf->vma->vm_file);
1143 		release_fault_lock(vmf);
1144 	}
1145 	return fpin;
1146 }
1147 
1148 static inline bool vma_supports_mlock(const struct vm_area_struct *vma)
1149 {
1150 	if (!vma_is_mm_backed(vma))
1151 		return false;
1152 	/* Core mm may discard droppable memory at any time. */
1153 	if (vma_test_single_mask(vma, VMA_DROPPABLE))
1154 		return false;
1155 	if (vma_is_dax(vma) || vma_is_hugetlb(vma))
1156 		return false;
1157 	return vma != get_gate_vma(current->mm);
1158 }
1159 
1160 #else /* !CONFIG_MMU */
1161 static inline void unmap_mapping_folio(struct folio *folio) { }
1162 static inline void mlock_new_folio(struct folio *folio) { }
1163 static inline bool need_mlock_drain(int cpu) { return false; }
1164 static inline void mlock_drain_local(void) { }
1165 static inline void mlock_drain_remote(int cpu) { }
1166 #endif /* !CONFIG_MMU */
1167 
1168 #ifdef CONFIG_NUMA
1169 extern int node_reclaim_mode;
1170 
1171 extern unsigned long node_reclaim(struct pglist_data *pgdat,
1172 				  gfp_t gfp_mask, unsigned int order);
1173 int find_next_best_node_in(int node, nodemask_t *used_node_mask,
1174 		const nodemask_t *candidates);
1175 #else
1176 #define node_reclaim_mode 0
1177 
1178 static inline unsigned long node_reclaim(struct pglist_data *pgdat,
1179 					 gfp_t mask, unsigned int order)
1180 {
1181 	return 0;
1182 }
1183 static inline int find_next_best_node_in(int node, nodemask_t *used_node_mask,
1184 		const nodemask_t *candidates)
1185 {
1186 	return NUMA_NO_NODE;
1187 }
1188 #endif
1189 
1190 static inline bool node_reclaim_enabled(void)
1191 {
1192 	/* Is any node_reclaim_mode bit set? */
1193 	return node_reclaim_mode & (RECLAIM_ZONE|RECLAIM_WRITE|RECLAIM_UNMAP);
1194 }
1195 
1196 /*
1197  * mm/memory-failure.c
1198  */
1199 #ifdef CONFIG_MEMORY_FAILURE
1200 int unmap_poisoned_folio(struct folio *folio, unsigned long pfn, bool must_kill);
1201 void shake_folio(struct folio *folio);
1202 typedef int hwpoison_filter_func_t(struct page *p);
1203 void hwpoison_filter_register(hwpoison_filter_func_t *filter);
1204 void hwpoison_filter_unregister(void);
1205 
1206 #define MAGIC_HWPOISON	0x48575053U	/* HWPS */
1207 void SetPageHWPoisonTakenOff(struct page *page);
1208 void ClearPageHWPoisonTakenOff(struct page *page);
1209 bool take_page_off_buddy(struct page *page);
1210 bool put_page_back_buddy(struct page *page);
1211 struct task_struct *task_early_kill(struct task_struct *tsk, int force_early);
1212 void add_to_kill_ksm(struct task_struct *tsk, const struct page *p,
1213 		     struct vm_area_struct *vma, struct list_head *to_kill,
1214 		     unsigned long ksm_addr);
1215 unsigned long page_mapped_in_vma(const struct page *page,
1216 		struct vm_area_struct *vma);
1217 
1218 #else
1219 static inline int unmap_poisoned_folio(struct folio *folio, unsigned long pfn, bool must_kill)
1220 {
1221 	return -EBUSY;
1222 }
1223 #endif
1224 
1225 extern unsigned long  __must_check vm_mmap_pgoff(struct file *, unsigned long,
1226         unsigned long, unsigned long,
1227         unsigned long, unsigned long);
1228 
1229 unsigned long reclaim_pages(struct list_head *folio_list);
1230 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1231 					    struct list_head *folio_list);
1232 
1233 enum ttu_flags;
1234 struct tlbflush_unmap_batch;
1235 
1236 
1237 /*
1238  * only for MM internal work items which do not depend on
1239  * any allocations or locks which might depend on allocations
1240  */
1241 extern struct workqueue_struct *mm_percpu_wq;
1242 
1243 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1244 void try_to_unmap_flush(void);
1245 void try_to_unmap_flush_dirty(void);
1246 void flush_tlb_batched_pending(struct mm_struct *mm);
1247 #else
1248 static inline void try_to_unmap_flush(void)
1249 {
1250 }
1251 static inline void try_to_unmap_flush_dirty(void)
1252 {
1253 }
1254 static inline void flush_tlb_batched_pending(struct mm_struct *mm)
1255 {
1256 }
1257 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
1258 
1259 extern const struct trace_print_flags pageflag_names[];
1260 extern const struct trace_print_flags vmaflag_names[];
1261 extern const struct trace_print_flags gfpflag_names[];
1262 
1263 void setup_zone_pageset(struct zone *zone);
1264 
1265 struct migration_target_control {
1266 	int nid;		/* preferred node id */
1267 	nodemask_t *nmask;
1268 	gfp_t gfp_mask;
1269 	enum migrate_reason reason;
1270 };
1271 
1272 /*
1273  * mm/filemap.c
1274  */
1275 size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
1276 			      struct folio *folio, loff_t fpos, size_t size);
1277 
1278 static inline bool vma_is_single_threaded_private(struct vm_area_struct *vma)
1279 {
1280 	if (vma->vm_flags & VM_SHARED)
1281 		return false;
1282 
1283 	return atomic_read(&vma->vm_mm->mm_users) == 1;
1284 }
1285 
1286 #ifdef CONFIG_NUMA_BALANCING
1287 bool folio_can_map_prot_numa(struct folio *folio, struct vm_area_struct *vma,
1288 		bool is_private_single_threaded);
1289 
1290 #else
1291 static inline bool folio_can_map_prot_numa(struct folio *folio,
1292 		struct vm_area_struct *vma, bool is_private_single_threaded)
1293 {
1294 	return false;
1295 }
1296 #endif
1297 
1298 int numa_migrate_check(struct folio *folio, struct vm_fault *vmf,
1299 		      unsigned long addr, int *flags, bool writable,
1300 		      int *last_cpupid);
1301 
1302 void free_zone_device_folio(struct folio *folio);
1303 int migrate_device_coherent_folio(struct folio *folio);
1304 
1305 /*
1306  * mm/gup.c
1307  */
1308 int __must_check try_grab_folio(struct folio *folio, int refs,
1309 				unsigned int flags);
1310 
1311 /*
1312  * mm/huge_memory.c
1313  */
1314 void touch_pud(struct vm_area_struct *vma, unsigned long addr,
1315 	       pud_t *pud, bool write);
1316 bool touch_pmd(struct vm_area_struct *vma, unsigned long addr,
1317 	       pmd_t *pmd, bool write);
1318 
1319 /*
1320  * Parses a string with mem suffixes into its order. Useful to parse kernel
1321  * parameters.
1322  */
1323 static inline int get_order_from_str(const char *size_str,
1324 				     unsigned long valid_orders)
1325 {
1326 	unsigned long size;
1327 	char *endptr;
1328 	int order;
1329 
1330 	size = memparse(size_str, &endptr);
1331 
1332 	if (!is_power_of_2(size))
1333 		return -EINVAL;
1334 	order = get_order(size);
1335 	if (BIT(order) & ~valid_orders)
1336 		return -EINVAL;
1337 
1338 	return order;
1339 }
1340 
1341 enum {
1342 	/* mark page accessed */
1343 	FOLL_TOUCH = 1 << 16,
1344 	/* a retry, previous pass started an IO */
1345 	FOLL_TRIED = 1 << 17,
1346 	/* we are working on non-current tsk/mm */
1347 	FOLL_REMOTE = 1 << 18,
1348 	/* pages must be released via unpin_user_page */
1349 	FOLL_PIN = 1 << 19,
1350 	/* gup_fast: prevent fall-back to slow gup */
1351 	FOLL_FAST_ONLY = 1 << 20,
1352 	/* allow unlocking the mmap lock */
1353 	FOLL_UNLOCKABLE = 1 << 21,
1354 	/* VMA lookup+checks compatible with MADV_POPULATE_(READ|WRITE) */
1355 	FOLL_MADV_POPULATE = 1 << 22,
1356 };
1357 
1358 #define INTERNAL_GUP_FLAGS (FOLL_TOUCH | FOLL_TRIED | FOLL_REMOTE | FOLL_PIN | \
1359 			    FOLL_FAST_ONLY | FOLL_UNLOCKABLE | \
1360 			    FOLL_MADV_POPULATE)
1361 
1362 /*
1363  * Indicates for which pages that are write-protected in the page table,
1364  * whether GUP has to trigger unsharing via FAULT_FLAG_UNSHARE such that the
1365  * GUP pin will remain consistent with the pages mapped into the page tables
1366  * of the MM.
1367  *
1368  * Temporary unmapping of PageAnonExclusive() pages or clearing of
1369  * PageAnonExclusive() has to protect against concurrent GUP:
1370  * * Ordinary GUP: Using the PT lock
1371  * * GUP-fast and fork(): mm->write_protect_seq
1372  * * GUP-fast and KSM or temporary unmapping (swap, migration): see
1373  *    folio_try_share_anon_rmap_*()
1374  *
1375  * Must be called with the (sub)page that's actually referenced via the
1376  * page table entry, which might not necessarily be the head page for a
1377  * PTE-mapped THP.
1378  *
1379  * If the vma is NULL, we're coming from the GUP-fast path and might have
1380  * to fallback to the slow path just to lookup the vma.
1381  */
1382 static inline bool gup_must_unshare(struct vm_area_struct *vma,
1383 				    unsigned int flags, struct page *page)
1384 {
1385 	/*
1386 	 * FOLL_WRITE is implicitly handled correctly as the page table entry
1387 	 * has to be writable -- and if it references (part of) an anonymous
1388 	 * folio, that part is required to be marked exclusive.
1389 	 */
1390 	if ((flags & (FOLL_WRITE | FOLL_PIN)) != FOLL_PIN)
1391 		return false;
1392 	/*
1393 	 * Note: PageAnon(page) is stable until the page is actually getting
1394 	 * freed.
1395 	 */
1396 	if (!PageAnon(page)) {
1397 		/*
1398 		 * We only care about R/O long-term pining: R/O short-term
1399 		 * pinning does not have the semantics to observe successive
1400 		 * changes through the process page tables.
1401 		 */
1402 		if (!(flags & FOLL_LONGTERM))
1403 			return false;
1404 
1405 		/* We really need the vma ... */
1406 		if (!vma)
1407 			return true;
1408 
1409 		/*
1410 		 * ... because we only care about writable private ("COW")
1411 		 * mappings where we have to break COW early.
1412 		 */
1413 		return vma_is_cow_mapping(vma);
1414 	}
1415 
1416 	/* Paired with a memory barrier in folio_try_share_anon_rmap_*(). */
1417 	if (IS_ENABLED(CONFIG_HAVE_GUP_FAST))
1418 		smp_rmb();
1419 
1420 	/*
1421 	 * Note that KSM pages cannot be exclusive, and consequently,
1422 	 * cannot get pinned.
1423 	 */
1424 	return !PageAnonExclusive(page);
1425 }
1426 
1427 
1428 static inline bool vma_soft_dirty_enabled(struct vm_area_struct *vma)
1429 {
1430 	/*
1431 	 * NOTE: we must check this before VM_SOFTDIRTY on soft-dirty
1432 	 * enablements, because when without soft-dirty being compiled in,
1433 	 * VM_SOFTDIRTY is defined as 0x0, then !(vm_flags & VM_SOFTDIRTY)
1434 	 * will be constantly true.
1435 	 */
1436 	if (!pgtable_supports_soft_dirty())
1437 		return false;
1438 
1439 	/*
1440 	 * Soft-dirty is kind of special: its tracking is enabled when the
1441 	 * vma flags not set.
1442 	 */
1443 	return !(vma->vm_flags & VM_SOFTDIRTY);
1444 }
1445 
1446 static inline bool pmd_needs_soft_dirty_wp(struct vm_area_struct *vma, pmd_t pmd)
1447 {
1448 	return vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd);
1449 }
1450 
1451 static inline bool pte_needs_soft_dirty_wp(struct vm_area_struct *vma, pte_t pte)
1452 {
1453 	return vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte);
1454 }
1455 
1456 /* shrinker related functions */
1457 unsigned long shrink_slab(gfp_t gfp_mask, int nid, struct mem_cgroup *memcg,
1458 			  int priority);
1459 
1460 int shmem_add_to_page_cache(struct folio *folio,
1461 			    struct address_space *mapping,
1462 			    pgoff_t index, void *expected, gfp_t gfp);
1463 int shmem_inode_acct_blocks(struct inode *inode, long pages);
1464 bool shmem_recalc_inode(struct inode *inode, long alloced, long swapped);
1465 
1466 #ifdef CONFIG_SHRINKER_DEBUG
1467 static inline __printf(2, 0) int shrinker_debugfs_name_alloc(
1468 			struct shrinker *shrinker, const char *fmt, va_list ap)
1469 {
1470 	shrinker->name = kvasprintf_const(GFP_KERNEL, fmt, ap);
1471 
1472 	return shrinker->name ? 0 : -ENOMEM;
1473 }
1474 
1475 static inline void shrinker_debugfs_name_free(struct shrinker *shrinker)
1476 {
1477 	kfree_const(shrinker->name);
1478 	shrinker->name = NULL;
1479 }
1480 
1481 extern int shrinker_debugfs_add(struct shrinker *shrinker);
1482 extern struct dentry *shrinker_debugfs_detach(struct shrinker *shrinker,
1483 					      int *debugfs_id);
1484 extern void shrinker_debugfs_remove(struct dentry *debugfs_entry,
1485 				    int debugfs_id);
1486 #else /* CONFIG_SHRINKER_DEBUG */
1487 static inline int shrinker_debugfs_add(struct shrinker *shrinker)
1488 {
1489 	return 0;
1490 }
1491 static inline int shrinker_debugfs_name_alloc(struct shrinker *shrinker,
1492 					      const char *fmt, va_list ap)
1493 {
1494 	return 0;
1495 }
1496 static inline void shrinker_debugfs_name_free(struct shrinker *shrinker)
1497 {
1498 }
1499 static inline struct dentry *shrinker_debugfs_detach(struct shrinker *shrinker,
1500 						     int *debugfs_id)
1501 {
1502 	*debugfs_id = -1;
1503 	return NULL;
1504 }
1505 static inline void shrinker_debugfs_remove(struct dentry *debugfs_entry,
1506 					   int debugfs_id)
1507 {
1508 }
1509 #endif /* CONFIG_SHRINKER_DEBUG */
1510 
1511 /* Only track the nodes of mappings with shadow entries */
1512 void workingset_update_node(struct xa_node *node);
1513 extern struct list_lru shadow_nodes;
1514 #define mapping_set_update(xas, mapping) do {			\
1515 	if (!dax_mapping(mapping) && !shmem_mapping(mapping)) {	\
1516 		xas_set_update(xas, workingset_update_node);	\
1517 		xas_set_lru(xas, &shadow_nodes);		\
1518 	}							\
1519 } while (0)
1520 
1521 /* mremap.c */
1522 unsigned long move_page_tables(struct pagetable_move_control *pmc);
1523 
1524 #ifdef CONFIG_UNACCEPTED_MEMORY
1525 void accept_page(struct page *page);
1526 #else /* CONFIG_UNACCEPTED_MEMORY */
1527 static inline void accept_page(struct page *page)
1528 {
1529 }
1530 #endif /* CONFIG_UNACCEPTED_MEMORY */
1531 
1532 /* pagewalk.c */
1533 int walk_page_range_mm_unsafe(struct mm_struct *mm, unsigned long start,
1534 		unsigned long end, const struct mm_walk_ops *ops,
1535 		void *private);
1536 int walk_page_range_vma_unsafe(struct vm_area_struct *vma, unsigned long start,
1537 		unsigned long end, const struct mm_walk_ops *ops,
1538 		void *private);
1539 int walk_page_range_debug(struct mm_struct *mm, unsigned long start,
1540 			  unsigned long end, const struct mm_walk_ops *ops,
1541 			  pgd_t *pgd, void *private);
1542 
1543 void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm);
1544 int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm);
1545 
1546 int remap_pfn_range_prepare(struct vm_area_desc *desc);
1547 int remap_pfn_range_complete(struct vm_area_struct *vma,
1548 			     struct mmap_action *action);
1549 int simple_ioremap_prepare(struct vm_area_desc *desc);
1550 int map_kernel_pages_prepare(struct vm_area_desc *desc);
1551 int map_kernel_pages_complete(struct vm_area_struct *vma,
1552 			      struct mmap_action *action);
1553 int map_discontig_kernel_pages_prepare(struct vm_area_desc *desc);
1554 int map_discontig_kernel_pages_complete(struct vm_area_struct *vma,
1555 					struct mmap_action *action);
1556 
1557 static inline int io_remap_pfn_range_prepare(struct vm_area_desc *desc)
1558 {
1559 	struct mmap_action *action = &desc->action;
1560 	const unsigned long orig_pfn = action->remap.start_pfn;
1561 	const pgprot_t orig_pgprot = action->remap.pgprot;
1562 	const unsigned long size = action->remap.size;
1563 	const unsigned long pfn = io_remap_pfn_range_pfn(orig_pfn, size);
1564 	int err;
1565 
1566 	action->remap.start_pfn = pfn;
1567 	action->remap.pgprot = pgprot_decrypted(orig_pgprot);
1568 	err = remap_pfn_range_prepare(desc);
1569 	if (err)
1570 		return err;
1571 
1572 	/* Remap does the actual work. */
1573 	action->type = MMAP_REMAP_PFN;
1574 	return 0;
1575 }
1576 
1577 /*
1578  * When we succeed an mmap action or just before we unmap a VMA on error, we
1579  * need to ensure any rmap lock held is released. On unmap it's required to
1580  * avoid a deadlock.
1581  */
1582 static inline void maybe_rmap_unlock_action(struct vm_area_struct *vma,
1583 		struct mmap_action *action)
1584 {
1585 	struct file *file;
1586 
1587 	if (!action->hide_from_rmap_until_complete)
1588 		return;
1589 
1590 	VM_WARN_ON_ONCE(vma_is_anonymous(vma));
1591 	file = vma->vm_file;
1592 	i_mmap_unlock_write(file->f_mapping);
1593 	action->hide_from_rmap_until_complete = false;
1594 }
1595 
1596 #ifdef CONFIG_MMU_NOTIFIER
1597 static inline bool clear_flush_young_ptes_notify(struct vm_area_struct *vma,
1598 		unsigned long addr, pte_t *ptep, unsigned int nr)
1599 {
1600 	bool young;
1601 
1602 	young = clear_flush_young_ptes(vma, addr, ptep, nr);
1603 	young |= mmu_notifier_clear_flush_young(vma->vm_mm, addr,
1604 						addr + nr * PAGE_SIZE);
1605 	return young;
1606 }
1607 
1608 static inline bool pmdp_clear_flush_young_notify(struct vm_area_struct *vma,
1609 		unsigned long addr, pmd_t *pmdp)
1610 {
1611 	bool young;
1612 
1613 	young = pmdp_clear_flush_young(vma, addr, pmdp);
1614 	young |= mmu_notifier_clear_flush_young(vma->vm_mm, addr, addr + PMD_SIZE);
1615 	return young;
1616 }
1617 
1618 static inline bool test_and_clear_young_ptes_notify(struct vm_area_struct *vma,
1619 		unsigned long addr, pte_t *ptep, unsigned int nr)
1620 {
1621 	bool young;
1622 
1623 	young = test_and_clear_young_ptes(vma, addr, ptep, nr);
1624 	young |= mmu_notifier_clear_young(vma->vm_mm, addr, addr + nr * PAGE_SIZE);
1625 	return young;
1626 }
1627 
1628 static inline bool pmdp_test_and_clear_young_notify(struct vm_area_struct *vma,
1629 		unsigned long addr, pmd_t *pmdp)
1630 {
1631 	bool young;
1632 
1633 	young = pmdp_test_and_clear_young(vma, addr, pmdp);
1634 	young |= mmu_notifier_clear_young(vma->vm_mm, addr, addr + PMD_SIZE);
1635 	return young;
1636 }
1637 
1638 #else /* CONFIG_MMU_NOTIFIER */
1639 
1640 #define clear_flush_young_ptes_notify	clear_flush_young_ptes
1641 #define pmdp_clear_flush_young_notify	pmdp_clear_flush_young
1642 #define test_and_clear_young_ptes_notify	test_and_clear_young_ptes
1643 #define pmdp_test_and_clear_young_notify	pmdp_test_and_clear_young
1644 
1645 #endif /* CONFIG_MMU_NOTIFIER */
1646 
1647 extern int sysctl_max_map_count;
1648 static inline int get_sysctl_max_map_count(void)
1649 {
1650 	return READ_ONCE(sysctl_max_map_count);
1651 }
1652 
1653 bool may_expand_vm(struct mm_struct *mm, const vma_flags_t *vma_flags,
1654 		   unsigned long npages);
1655 
1656 static inline void mm_prepare_for_swap_entries(struct mm_struct *mm)
1657 {
1658 	if (list_empty(&mm->mmlist)) {
1659 		spin_lock(&mmlist_lock);
1660 		if (list_empty(&mm->mmlist))
1661 			list_add(&mm->mmlist, &init_mm.mmlist);
1662 		spin_unlock(&mmlist_lock);
1663 	}
1664 }
1665 
1666 static inline bool can_spin_trylock(void)
1667 {
1668 	/*
1669 	 * In PREEMPT_RT spin_trylock() will call raw_spin_lock() which is
1670 	 * unsafe in NMI. If spin_trylock() is called from hard IRQ the current
1671 	 * task may be waiting for one rt_spin_lock, but rt_spin_trylock() will
1672 	 * mark the task as the owner of another rt_spin_lock which will
1673 	 * confuse PI logic, so return immediately if called from hard IRQ or
1674 	 * NMI.
1675 	 *
1676 	 * Note, irqs_disabled() case is ok. spin_trylock() can be called
1677 	 * from raw_spin_lock_irqsave region.
1678 	 */
1679 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && (in_nmi() || in_hardirq()))
1680 		return false;
1681 
1682 	/* On UP, spin_trylock() always succeeds even when it is locked */
1683 	if (!IS_ENABLED(CONFIG_SMP) && in_nmi())
1684 		return false;
1685 
1686 	return true;
1687 }
1688 
1689 /* char-mem.c */
1690 bool file_is_dev_zero(const struct file *file);
1691 
1692 #endif	/* __MM_INTERNAL_H */
1693