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