xref: /linux/include/linux/mm.h (revision 49bda4826843be0ef97a162009a29ea3a63f3935)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MM_H
3 #define _LINUX_MM_H
4 
5 #include <linux/args.h>
6 #include <linux/errno.h>
7 #include <linux/mmdebug.h>
8 #include <linux/gfp.h>
9 #include <linux/pgalloc_tag.h>
10 #include <linux/bug.h>
11 #include <linux/list.h>
12 #include <linux/mmzone.h>
13 #include <linux/rbtree.h>
14 #include <linux/atomic.h>
15 #include <linux/debug_locks.h>
16 #include <linux/compiler.h>
17 #include <linux/mm_types.h>
18 #include <linux/mmap_lock.h>
19 #include <linux/range.h>
20 #include <linux/pfn.h>
21 #include <linux/percpu-refcount.h>
22 #include <linux/bit_spinlock.h>
23 #include <linux/shrinker.h>
24 #include <linux/resource.h>
25 #include <linux/page_ext.h>
26 #include <linux/err.h>
27 #include <linux/page-flags.h>
28 #include <linux/page_ref.h>
29 #include <linux/overflow.h>
30 #include <linux/sched.h>
31 #include <linux/pgtable.h>
32 #include <linux/kasan.h>
33 #include <linux/memremap.h>
34 #include <linux/slab.h>
35 #include <linux/cacheinfo.h>
36 #include <linux/rcuwait.h>
37 #include <linux/bitmap.h>
38 #include <linux/bitops.h>
39 #include <linux/iommu-debug-pagealloc.h>
40 #include <linux/kcsan-checks.h>
41 
42 struct mempolicy;
43 struct anon_vma;
44 struct anon_vma_chain;
45 struct user_struct;
46 struct pt_regs;
47 struct folio_batch;
48 
49 void arch_mm_preinit(void);
50 void mm_core_init_early(void);
51 void mm_core_init(void);
52 void init_mm_internals(void);
53 
54 extern atomic_long_t _totalram_pages;
totalram_pages(void)55 static inline unsigned long totalram_pages(void)
56 {
57 	return (unsigned long)atomic_long_read(&_totalram_pages);
58 }
59 
totalram_pages_inc(void)60 static inline void totalram_pages_inc(void)
61 {
62 	atomic_long_inc(&_totalram_pages);
63 }
64 
totalram_pages_dec(void)65 static inline void totalram_pages_dec(void)
66 {
67 	atomic_long_dec(&_totalram_pages);
68 }
69 
totalram_pages_add(long count)70 static inline void totalram_pages_add(long count)
71 {
72 	atomic_long_add(count, &_totalram_pages);
73 }
74 
75 extern void * high_memory;
76 
77 /*
78  * Convert between pages and MB
79  * 20 is the shift for 1MB (2^20 = 1MB)
80  * PAGE_SHIFT is the shift for page size (e.g., 12 for 4KB pages)
81  * So (20 - PAGE_SHIFT) converts between pages and MB
82  */
83 #define PAGES_TO_MB(pages) ((pages) >> (20 - PAGE_SHIFT))
84 #define MB_TO_PAGES(mb)    ((mb) << (20 - PAGE_SHIFT))
85 
86 #ifdef CONFIG_SYSCTL
87 extern int sysctl_legacy_va_layout;
88 #else
89 #define sysctl_legacy_va_layout 0
90 #endif
91 
92 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_BITS
93 extern const int mmap_rnd_bits_min;
94 extern int mmap_rnd_bits_max __ro_after_init;
95 extern int mmap_rnd_bits __read_mostly;
96 #endif
97 #ifdef CONFIG_HAVE_ARCH_MMAP_RND_COMPAT_BITS
98 extern const int mmap_rnd_compat_bits_min;
99 extern const int mmap_rnd_compat_bits_max;
100 extern int mmap_rnd_compat_bits __read_mostly;
101 #endif
102 
103 #ifndef DIRECT_MAP_PHYSMEM_END
104 # ifdef MAX_PHYSMEM_BITS
105 # define DIRECT_MAP_PHYSMEM_END	((1ULL << MAX_PHYSMEM_BITS) - 1)
106 # else
107 # define DIRECT_MAP_PHYSMEM_END	(((phys_addr_t)-1)&~(1ULL<<63))
108 # endif
109 #endif
110 
111 #define INVALID_PHYS_ADDR (~(phys_addr_t)0)
112 
113 #include <asm/page.h>
114 #include <asm/processor.h>
115 
116 #ifndef __pa_symbol
117 #define __pa_symbol(x)  __pa(RELOC_HIDE((unsigned long)(x), 0))
118 #endif
119 
120 #ifndef page_to_virt
121 #define page_to_virt(x)	__va(PFN_PHYS(page_to_pfn(x)))
122 #endif
123 
124 #ifndef lm_alias
125 #define lm_alias(x)	__va(__pa_symbol(x))
126 #endif
127 
128 /*
129  * To prevent common memory management code establishing
130  * a zero page mapping on a read fault.
131  * This macro should be defined within <asm/pgtable.h>.
132  * s390 does this to prevent multiplexing of hardware bits
133  * related to the physical page in case of virtualization.
134  */
135 #ifndef mm_forbids_zeropage
136 #define mm_forbids_zeropage(X)	(0)
137 #endif
138 
139 /*
140  * On some architectures it is expensive to call memset() for small sizes.
141  * If an architecture decides to implement their own version of
142  * mm_zero_struct_page they should wrap the defines below in a #ifndef and
143  * define their own version of this macro in <asm/pgtable.h>
144  */
145 #if BITS_PER_LONG == 64
146 /* This function must be updated when the size of struct page grows above 96
147  * or reduces below 56. The idea that compiler optimizes out switch()
148  * statement, and only leaves move/store instructions. Also the compiler can
149  * combine write statements if they are both assignments and can be reordered,
150  * this can result in several of the writes here being dropped.
151  */
152 #define	mm_zero_struct_page(pp) __mm_zero_struct_page(pp)
__mm_zero_struct_page(struct page * page)153 static inline void __mm_zero_struct_page(struct page *page)
154 {
155 	unsigned long *_pp = (void *)page;
156 
157 	 /* Check that struct page is either 56, 64, 72, 80, 88 or 96 bytes */
158 	BUILD_BUG_ON(sizeof(struct page) & 7);
159 	BUILD_BUG_ON(sizeof(struct page) < 56);
160 	BUILD_BUG_ON(sizeof(struct page) > 96);
161 
162 	switch (sizeof(struct page)) {
163 	case 96:
164 		_pp[11] = 0;
165 		fallthrough;
166 	case 88:
167 		_pp[10] = 0;
168 		fallthrough;
169 	case 80:
170 		_pp[9] = 0;
171 		fallthrough;
172 	case 72:
173 		_pp[8] = 0;
174 		fallthrough;
175 	case 64:
176 		_pp[7] = 0;
177 		fallthrough;
178 	case 56:
179 		_pp[6] = 0;
180 		_pp[5] = 0;
181 		_pp[4] = 0;
182 		_pp[3] = 0;
183 		_pp[2] = 0;
184 		_pp[1] = 0;
185 		_pp[0] = 0;
186 	}
187 }
188 #else
189 #define mm_zero_struct_page(pp)  ((void)memset((pp), 0, sizeof(struct page)))
190 #endif
191 
192 /*
193  * Default maximum number of active map areas, this limits the number of vmas
194  * per mm struct. Users can overwrite this number by sysctl but there is a
195  * problem.
196  *
197  * When a program's coredump is generated as ELF format, a section is created
198  * per a vma. In ELF, the number of sections is represented in unsigned short.
199  * This means the number of sections should be smaller than 65535 at coredump.
200  * Because the kernel adds some informative sections to a image of program at
201  * generating coredump, we need some margin. The number of extra sections is
202  * 1-3 now and depends on arch. We use "5" as safe margin, here.
203  *
204  * ELF extended numbering allows more than 65535 sections, so 16-bit bound is
205  * not a hard limit any more. Although some userspace tools can be surprised by
206  * that.
207  */
208 #define MAPCOUNT_ELF_CORE_MARGIN	(5)
209 #define DEFAULT_MAX_MAP_COUNT	(USHRT_MAX - MAPCOUNT_ELF_CORE_MARGIN)
210 
211 extern unsigned long sysctl_user_reserve_kbytes;
212 extern unsigned long sysctl_admin_reserve_kbytes;
213 
214 #if defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP)
215 bool page_range_contiguous(const struct page *page, unsigned long nr_pages);
216 #else
page_range_contiguous(const struct page * page,unsigned long nr_pages)217 static inline bool page_range_contiguous(const struct page *page,
218 		unsigned long nr_pages)
219 {
220 	return true;
221 }
222 #endif
223 
224 /* to align the pointer to the (next) page boundary */
225 #define PAGE_ALIGN(addr) ALIGN(addr, PAGE_SIZE)
226 
227 /* to align the pointer to the (prev) page boundary */
228 #define PAGE_ALIGN_DOWN(addr) ALIGN_DOWN(addr, PAGE_SIZE)
229 
230 /* test whether an address (unsigned long or pointer) is aligned to PAGE_SIZE */
231 #define PAGE_ALIGNED(addr)	IS_ALIGNED((unsigned long)(addr), PAGE_SIZE)
232 
233 /**
234  * folio_page_idx - Return the number of a page in a folio.
235  * @folio: The folio.
236  * @page: The folio page.
237  *
238  * This function expects that the page is actually part of the folio.
239  * The returned number is relative to the start of the folio.
240  */
folio_page_idx(const struct folio * folio,const struct page * page)241 static inline unsigned long folio_page_idx(const struct folio *folio,
242 		const struct page *page)
243 {
244 	return page - &folio->page;
245 }
246 
lru_to_folio(struct list_head * head)247 static inline struct folio *lru_to_folio(struct list_head *head)
248 {
249 	return list_entry((head)->prev, struct folio, lru);
250 }
251 
252 void setup_initial_init_mm(void *start_code, void *end_code,
253 			   void *end_data, void *brk);
254 
255 /*
256  * Linux kernel virtual memory manager primitives.
257  * The idea being to have a "virtual" mm in the same way
258  * we have a virtual fs - giving a cleaner interface to the
259  * mm details, and allowing different kinds of memory mappings
260  * (from shared memory to executable loading to arbitrary
261  * mmap() functions).
262  */
263 
264 struct vm_area_struct *vm_area_alloc(struct mm_struct *);
265 struct vm_area_struct *vm_area_dup(struct vm_area_struct *);
266 void vm_area_free(struct vm_area_struct *);
267 
268 #ifndef CONFIG_MMU
269 extern struct rb_root nommu_region_tree;
270 extern struct rw_semaphore nommu_region_sem;
271 
272 extern unsigned int kobjsize(const void *objp);
273 #endif
274 
275 /*
276  * vm_flags in vm_area_struct, see mm_types.h.
277  * When changing, update also include/trace/events/mmflags.h
278  */
279 
280 #define VM_NONE		0x00000000
281 
282 /**
283  * typedef vma_flag_t - specifies an individual VMA flag by bit number.
284  *
285  * This value is made type safe by sparse to avoid passing invalid flag values
286  * around.
287  */
288 typedef int __bitwise vma_flag_t;
289 
290 #define DECLARE_VMA_BIT(name, bitnum) \
291 	VMA_ ## name ## _BIT = ((__force vma_flag_t)bitnum)
292 #define DECLARE_VMA_BIT_ALIAS(name, aliased) \
293 	VMA_ ## name ## _BIT = (VMA_ ## aliased ## _BIT)
294 enum {
295 	DECLARE_VMA_BIT(READ, 0),
296 	DECLARE_VMA_BIT(WRITE, 1),
297 	DECLARE_VMA_BIT(EXEC, 2),
298 	DECLARE_VMA_BIT(SHARED, 3),
299 	/* mprotect() hardcodes VM_MAYREAD >> 4 == VM_READ, and so for r/w/x bits. */
300 	DECLARE_VMA_BIT(MAYREAD, 4),	/* limits for mprotect() etc. */
301 	DECLARE_VMA_BIT(MAYWRITE, 5),
302 	DECLARE_VMA_BIT(MAYEXEC, 6),
303 	DECLARE_VMA_BIT(MAYSHARE, 7),
304 	DECLARE_VMA_BIT(GROWSDOWN, 8),	/* general info on the segment */
305 #ifdef CONFIG_MMU
306 	DECLARE_VMA_BIT(UFFD_MISSING, 9),/* missing pages tracking */
307 #else
308 	/* nommu: R/O MAP_PRIVATE mapping that might overlay a file mapping */
309 	DECLARE_VMA_BIT(MAYOVERLAY, 9),
310 #endif /* CONFIG_MMU */
311 	/* Page-ranges managed without "struct page", just pure PFN */
312 	DECLARE_VMA_BIT(PFNMAP, 10),
313 	DECLARE_VMA_BIT(MAYBE_GUARD, 11),
314 	DECLARE_VMA_BIT(UFFD_WP, 12),	/* wrprotect pages tracking */
315 	DECLARE_VMA_BIT(LOCKED, 13),
316 	DECLARE_VMA_BIT(IO, 14),	/* Memory mapped I/O or similar */
317 	DECLARE_VMA_BIT(SEQ_READ, 15),	/* App will access data sequentially */
318 	DECLARE_VMA_BIT(RAND_READ, 16),	/* App will not benefit from clustered reads */
319 	DECLARE_VMA_BIT(DONTCOPY, 17),	/* Do not copy this vma on fork */
320 	DECLARE_VMA_BIT(DONTEXPAND, 18),/* Cannot expand with mremap() */
321 	DECLARE_VMA_BIT(LOCKONFAULT, 19),/* Lock pages covered when faulted in */
322 	DECLARE_VMA_BIT(ACCOUNT, 20),	/* Is a VM accounted object */
323 	DECLARE_VMA_BIT(NORESERVE, 21),	/* should the VM suppress accounting */
324 	DECLARE_VMA_BIT(HUGETLB, 22),	/* Huge TLB Page VM */
325 	DECLARE_VMA_BIT(SYNC, 23),	/* Synchronous page faults */
326 	DECLARE_VMA_BIT(ARCH_1, 24),	/* Architecture-specific flag */
327 	DECLARE_VMA_BIT(WIPEONFORK, 25),/* Wipe VMA contents in child. */
328 	DECLARE_VMA_BIT(DONTDUMP, 26),	/* Do not include in the core dump */
329 	DECLARE_VMA_BIT(SOFTDIRTY, 27),	/* NOT soft dirty clean area */
330 	DECLARE_VMA_BIT(MIXEDMAP, 28),	/* Can contain struct page and pure PFN pages */
331 	DECLARE_VMA_BIT(HUGEPAGE, 29),	/* MADV_HUGEPAGE marked this vma */
332 	DECLARE_VMA_BIT(NOHUGEPAGE, 30),/* MADV_NOHUGEPAGE marked this vma */
333 	DECLARE_VMA_BIT(MERGEABLE, 31),	/* KSM may merge identical pages */
334 	/* These bits are reused, we define specific uses below. */
335 	DECLARE_VMA_BIT(HIGH_ARCH_0, 32),
336 	DECLARE_VMA_BIT(HIGH_ARCH_1, 33),
337 	DECLARE_VMA_BIT(HIGH_ARCH_2, 34),
338 	DECLARE_VMA_BIT(HIGH_ARCH_3, 35),
339 	DECLARE_VMA_BIT(HIGH_ARCH_4, 36),
340 	DECLARE_VMA_BIT(HIGH_ARCH_5, 37),
341 	DECLARE_VMA_BIT(HIGH_ARCH_6, 38),
342 	/*
343 	 * This flag is used to connect VFIO to arch specific KVM code. It
344 	 * indicates that the memory under this VMA is safe for use with any
345 	 * non-cachable memory type inside KVM. Some VFIO devices, on some
346 	 * platforms, are thought to be unsafe and can cause machine crashes
347 	 * if KVM does not lock down the memory type.
348 	 */
349 	DECLARE_VMA_BIT(ALLOW_ANY_UNCACHED, 39),
350 #if defined(CONFIG_PPC32)
351 	DECLARE_VMA_BIT_ALIAS(DROPPABLE, ARCH_1),
352 #elif defined(CONFIG_64BIT)
353 	DECLARE_VMA_BIT(DROPPABLE, 40),
354 #endif
355 	DECLARE_VMA_BIT(UFFD_MINOR, 41),
356 	DECLARE_VMA_BIT(SEALED, 42),
357 	DECLARE_VMA_BIT(UFFD_RWP, 43),
358 	/* Flags that reuse flags above. */
359 	DECLARE_VMA_BIT_ALIAS(PKEY_BIT0, HIGH_ARCH_0),
360 	DECLARE_VMA_BIT_ALIAS(PKEY_BIT1, HIGH_ARCH_1),
361 	DECLARE_VMA_BIT_ALIAS(PKEY_BIT2, HIGH_ARCH_2),
362 	DECLARE_VMA_BIT_ALIAS(PKEY_BIT3, HIGH_ARCH_3),
363 	DECLARE_VMA_BIT_ALIAS(PKEY_BIT4, HIGH_ARCH_4),
364 #if defined(CONFIG_X86_USER_SHADOW_STACK) || defined(CONFIG_RISCV_USER_CFI)
365 	/*
366 	 * VM_SHADOW_STACK should not be set with VM_SHARED because of lack of
367 	 * support core mm.
368 	 *
369 	 * These VMAs will get a single end guard page. This helps userspace
370 	 * protect itself from attacks. A single page is enough for current
371 	 * shadow stack archs (x86). See the comments near alloc_shstk() in
372 	 * arch/x86/kernel/shstk.c for more details on the guard size.
373 	 */
374 	DECLARE_VMA_BIT_ALIAS(SHADOW_STACK, HIGH_ARCH_5),
375 #elif defined(CONFIG_ARM64_GCS)
376 	/*
377 	 * arm64's Guarded Control Stack implements similar functionality and
378 	 * has similar constraints to shadow stacks.
379 	 */
380 	DECLARE_VMA_BIT_ALIAS(SHADOW_STACK, HIGH_ARCH_6),
381 #endif
382 	DECLARE_VMA_BIT_ALIAS(SAO, ARCH_1),		/* Strong Access Ordering (powerpc) */
383 	DECLARE_VMA_BIT_ALIAS(GROWSUP, ARCH_1),		/* parisc */
384 	DECLARE_VMA_BIT_ALIAS(SPARC_ADI, ARCH_1),	/* sparc64 */
385 	DECLARE_VMA_BIT_ALIAS(ARM64_BTI, ARCH_1),	/* arm64 */
386 	DECLARE_VMA_BIT_ALIAS(ARCH_CLEAR, ARCH_1),	/* sparc64, arm64 */
387 	DECLARE_VMA_BIT_ALIAS(MAPPED_COPY, ARCH_1),	/* !CONFIG_MMU */
388 	DECLARE_VMA_BIT_ALIAS(MTE, HIGH_ARCH_4),	/* arm64 */
389 	DECLARE_VMA_BIT_ALIAS(MTE_ALLOWED, HIGH_ARCH_5),/* arm64 */
390 #ifdef CONFIG_STACK_GROWSUP
391 	DECLARE_VMA_BIT_ALIAS(STACK, GROWSUP),
392 	DECLARE_VMA_BIT_ALIAS(STACK_EARLY, GROWSDOWN),
393 #else
394 	DECLARE_VMA_BIT_ALIAS(STACK, GROWSDOWN),
395 #endif
396 };
397 #undef DECLARE_VMA_BIT
398 #undef DECLARE_VMA_BIT_ALIAS
399 
400 #define INIT_VM_FLAG(name) BIT((__force int) VMA_ ## name ## _BIT)
401 #define VM_READ		INIT_VM_FLAG(READ)
402 #define VM_WRITE	INIT_VM_FLAG(WRITE)
403 #define VM_EXEC		INIT_VM_FLAG(EXEC)
404 #define VM_SHARED	INIT_VM_FLAG(SHARED)
405 #define VM_MAYREAD	INIT_VM_FLAG(MAYREAD)
406 #define VM_MAYWRITE	INIT_VM_FLAG(MAYWRITE)
407 #define VM_MAYEXEC	INIT_VM_FLAG(MAYEXEC)
408 #define VM_MAYSHARE	INIT_VM_FLAG(MAYSHARE)
409 #define VM_GROWSDOWN	INIT_VM_FLAG(GROWSDOWN)
410 #ifdef CONFIG_MMU
411 #define VM_UFFD_MISSING	INIT_VM_FLAG(UFFD_MISSING)
412 #else
413 #define VM_UFFD_MISSING	VM_NONE
414 #define VM_MAYOVERLAY	INIT_VM_FLAG(MAYOVERLAY)
415 #endif
416 #define VM_PFNMAP	INIT_VM_FLAG(PFNMAP)
417 #define VM_MAYBE_GUARD	INIT_VM_FLAG(MAYBE_GUARD)
418 #define VM_UFFD_WP	INIT_VM_FLAG(UFFD_WP)
419 #define VM_LOCKED	INIT_VM_FLAG(LOCKED)
420 #define VM_IO		INIT_VM_FLAG(IO)
421 #define VM_SEQ_READ	INIT_VM_FLAG(SEQ_READ)
422 #define VM_RAND_READ	INIT_VM_FLAG(RAND_READ)
423 #define VM_DONTCOPY	INIT_VM_FLAG(DONTCOPY)
424 #define VM_DONTEXPAND	INIT_VM_FLAG(DONTEXPAND)
425 #define VM_LOCKONFAULT	INIT_VM_FLAG(LOCKONFAULT)
426 #define VM_ACCOUNT	INIT_VM_FLAG(ACCOUNT)
427 #define VM_NORESERVE	INIT_VM_FLAG(NORESERVE)
428 #define VM_HUGETLB	INIT_VM_FLAG(HUGETLB)
429 #define VM_SYNC		INIT_VM_FLAG(SYNC)
430 #define VM_ARCH_1	INIT_VM_FLAG(ARCH_1)
431 #define VM_WIPEONFORK	INIT_VM_FLAG(WIPEONFORK)
432 #define VM_DONTDUMP	INIT_VM_FLAG(DONTDUMP)
433 #ifdef CONFIG_MEM_SOFT_DIRTY
434 #define VM_SOFTDIRTY	INIT_VM_FLAG(SOFTDIRTY)
435 #else
436 #define VM_SOFTDIRTY	VM_NONE
437 #endif
438 #define VM_MIXEDMAP	INIT_VM_FLAG(MIXEDMAP)
439 #define VM_HUGEPAGE	INIT_VM_FLAG(HUGEPAGE)
440 #define VM_NOHUGEPAGE	INIT_VM_FLAG(NOHUGEPAGE)
441 #define VM_MERGEABLE	INIT_VM_FLAG(MERGEABLE)
442 #define VM_STACK	INIT_VM_FLAG(STACK)
443 #ifdef CONFIG_STACK_GROWSUP
444 #define VM_STACK_EARLY	INIT_VM_FLAG(STACK_EARLY)
445 #define VMA_STACK_EARLY mk_vma_flags(VMA_STACK_EARLY_BIT)
446 #else
447 #define VM_STACK_EARLY	VM_NONE
448 #define VMA_STACK_EARLY EMPTY_VMA_FLAGS
449 #endif
450 #ifdef CONFIG_ARCH_HAS_PKEYS
451 #define VM_PKEY_SHIFT ((__force int)VMA_HIGH_ARCH_0_BIT)
452 /* Despite the naming, these are FLAGS not bits. */
453 #define VM_PKEY_BIT0 INIT_VM_FLAG(PKEY_BIT0)
454 #define VM_PKEY_BIT1 INIT_VM_FLAG(PKEY_BIT1)
455 #define VM_PKEY_BIT2 INIT_VM_FLAG(PKEY_BIT2)
456 #if CONFIG_ARCH_PKEY_BITS > 3
457 #define VM_PKEY_BIT3 INIT_VM_FLAG(PKEY_BIT3)
458 #else
459 #define VM_PKEY_BIT3  VM_NONE
460 #endif /* CONFIG_ARCH_PKEY_BITS > 3 */
461 #if CONFIG_ARCH_PKEY_BITS > 4
462 #define VM_PKEY_BIT4 INIT_VM_FLAG(PKEY_BIT4)
463 #else
464 #define VM_PKEY_BIT4  VM_NONE
465 #endif /* CONFIG_ARCH_PKEY_BITS > 4 */
466 #endif /* CONFIG_ARCH_HAS_PKEYS */
467 #if defined(CONFIG_X86_USER_SHADOW_STACK) || defined(CONFIG_ARM64_GCS) || \
468 	defined(CONFIG_RISCV_USER_CFI)
469 #define VM_SHADOW_STACK	INIT_VM_FLAG(SHADOW_STACK)
470 #define VMA_SHADOW_STACK mk_vma_flags(VMA_SHADOW_STACK_BIT)
471 #define VMA_STARTGAP_FLAGS mk_vma_flags(VMA_GROWSDOWN_BIT, VMA_SHADOW_STACK_BIT)
472 #else
473 #define VM_SHADOW_STACK	VM_NONE
474 #define VMA_SHADOW_STACK EMPTY_VMA_FLAGS
475 #define VMA_STARTGAP_FLAGS mk_vma_flags(VMA_GROWSDOWN_BIT)
476 #endif
477 #if defined(CONFIG_PPC64)
478 #define VM_SAO		INIT_VM_FLAG(SAO)
479 #elif defined(CONFIG_PARISC)
480 #define VM_GROWSUP	INIT_VM_FLAG(GROWSUP)
481 #define VMA_GROWSUP	mk_vma_flags(VMA_GROWSUP_BIT)
482 #elif defined(CONFIG_SPARC64)
483 #define VM_SPARC_ADI	INIT_VM_FLAG(SPARC_ADI)
484 #define VM_ARCH_CLEAR	INIT_VM_FLAG(ARCH_CLEAR)
485 #elif defined(CONFIG_ARM64)
486 #define VM_ARM64_BTI	INIT_VM_FLAG(ARM64_BTI)
487 #define VM_ARCH_CLEAR	INIT_VM_FLAG(ARCH_CLEAR)
488 #elif !defined(CONFIG_MMU)
489 #define VM_MAPPED_COPY	INIT_VM_FLAG(MAPPED_COPY)
490 #endif
491 #ifndef VM_GROWSUP
492 #define VM_GROWSUP	VM_NONE
493 #define VMA_GROWSUP	EMPTY_VMA_FLAGS
494 #endif
495 #ifdef CONFIG_ARM64_MTE
496 #define VM_MTE		INIT_VM_FLAG(MTE)
497 #define VM_MTE_ALLOWED	INIT_VM_FLAG(MTE_ALLOWED)
498 #else
499 #define VM_MTE		VM_NONE
500 #define VM_MTE_ALLOWED	VM_NONE
501 #endif
502 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
503 #define VM_UFFD_MINOR	INIT_VM_FLAG(UFFD_MINOR)
504 #else
505 #define VM_UFFD_MINOR	VM_NONE
506 #endif
507 #ifdef CONFIG_USERFAULTFD_RWP
508 #define VM_UFFD_RWP		INIT_VM_FLAG(UFFD_RWP)
509 #else
510 #define VM_UFFD_RWP		VM_NONE
511 #endif
512 
513 /*
514  * vma_flags_t masks for the userfaultfd VMA flags. The two high-bit modes are
515  * gated on the same configs as their VM_* flags above -- both of which imply
516  * 64BIT -- so an out-of-range bit is never fed to mk_vma_flags() on a build
517  * whose bitmap cannot hold it.
518  */
519 #define VMA_UFFD_MISSING	mk_vma_flags(VMA_UFFD_MISSING_BIT)
520 #define VMA_UFFD_WP		mk_vma_flags(VMA_UFFD_WP_BIT)
521 #ifdef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
522 #define VMA_UFFD_MINOR		mk_vma_flags(VMA_UFFD_MINOR_BIT)
523 #else
524 #define VMA_UFFD_MINOR		EMPTY_VMA_FLAGS
525 #endif
526 #ifdef CONFIG_USERFAULTFD_RWP
527 #define VMA_UFFD_RWP		mk_vma_flags(VMA_UFFD_RWP_BIT)
528 #else
529 #define VMA_UFFD_RWP		EMPTY_VMA_FLAGS
530 #endif
531 
532 #ifdef CONFIG_64BIT
533 #define VM_ALLOW_ANY_UNCACHED	INIT_VM_FLAG(ALLOW_ANY_UNCACHED)
534 #define VM_SEALED		INIT_VM_FLAG(SEALED)
535 #else
536 #define VM_ALLOW_ANY_UNCACHED	VM_NONE
537 #define VM_SEALED		VM_NONE
538 #endif
539 #if defined(CONFIG_64BIT) || defined(CONFIG_PPC32)
540 #define VM_DROPPABLE		INIT_VM_FLAG(DROPPABLE)
541 #define VMA_DROPPABLE		mk_vma_flags(VMA_DROPPABLE_BIT)
542 #else
543 #define VM_DROPPABLE		VM_NONE
544 #define VMA_DROPPABLE		EMPTY_VMA_FLAGS
545 #endif
546 
547 /* Bits set in the VMA until the stack is in its final location */
548 #define VM_STACK_INCOMPLETE_SETUP (VM_RAND_READ | VM_SEQ_READ | VM_STACK_EARLY)
549 #define VMA_STACK_INCOMPLETE_SETUP append_vma_flags(		\
550 	VMA_STACK_EARLY, VMA_RAND_READ_BIT, VMA_SEQ_READ_BIT)
551 
552 #define TASK_EXEC_BIT ((current->personality & READ_IMPLIES_EXEC) ? \
553 		       VMA_EXEC_BIT : VMA_READ_BIT)
554 
555 /* Common data flag combinations */
556 #define VMA_DATA_FLAGS_TSK_EXEC	mk_vma_flags(VMA_READ_BIT, VMA_WRITE_BIT, \
557 		TASK_EXEC_BIT, VMA_MAYREAD_BIT, VMA_MAYWRITE_BIT,	  \
558 		VMA_MAYEXEC_BIT)
559 #define VMA_DATA_FLAGS_NON_EXEC	mk_vma_flags(VMA_READ_BIT, VMA_WRITE_BIT, \
560 		VMA_MAYREAD_BIT, VMA_MAYWRITE_BIT, VMA_MAYEXEC_BIT)
561 #define VMA_DATA_FLAGS_EXEC	mk_vma_flags(VMA_READ_BIT, VMA_WRITE_BIT, \
562 		VMA_EXEC_BIT, VMA_MAYREAD_BIT, VMA_MAYWRITE_BIT,	  \
563 		VMA_MAYEXEC_BIT)
564 
565 #ifndef VMA_DATA_DEFAULT_FLAGS		/* arch can override this */
566 #define VMA_DATA_DEFAULT_FLAGS  VMA_DATA_FLAGS_EXEC
567 #endif
568 
569 #ifndef VMA_STACK_DEFAULT_FLAGS		/* arch can override this */
570 #define VMA_STACK_DEFAULT_FLAGS VMA_DATA_DEFAULT_FLAGS
571 #endif
572 
573 #define VMA_STACK_FLAGS	append_vma_flags(VMA_STACK_DEFAULT_FLAGS,	\
574 		VMA_STACK_BIT, VMA_ACCOUNT_BIT)
575 
576 /* Temporary until VMA flags conversion complete. */
577 #define VM_STACK_FLAGS vma_flags_to_legacy(VMA_STACK_FLAGS)
578 
579 #ifdef CONFIG_MSEAL_SYSTEM_MAPPINGS
580 #define VM_SEALED_SYSMAP	VM_SEALED
581 #else
582 #define VM_SEALED_SYSMAP	VM_NONE
583 #endif
584 
585 /* VMA basic access permission flags */
586 #define VM_ACCESS_FLAGS (VM_READ | VM_WRITE | VM_EXEC)
587 #define VMA_ACCESS_FLAGS mk_vma_flags(VMA_READ_BIT, VMA_WRITE_BIT, VMA_EXEC_BIT)
588 
589 /*
590  * Special vmas that are non-mergable, non-mlock()able.
591  */
592 
593 #define VMA_SPECIAL_FLAGS mk_vma_flags(VMA_IO_BIT, VMA_DONTEXPAND_BIT, \
594 				       VMA_PFNMAP_BIT, VMA_MIXEDMAP_BIT)
595 #define VM_SPECIAL vma_flags_to_legacy(VMA_SPECIAL_FLAGS)
596 
597 /*
598  * Physically remapped pages are special. Tell the
599  * rest of the world about it:
600  *   IO tells people not to look at these pages
601  *	(accesses can have side effects).
602  *   PFNMAP tells the core MM that the base pages are just
603  *	raw PFN mappings, and do not have a "struct page" associated
604  *	with them.
605  *   DONTEXPAND
606  *      Disable vma merging and expanding with mremap().
607  *   DONTDUMP
608  *      Omit vma from core dump, even when VM_IO turned off.
609  */
610 #define VMA_REMAP_FLAGS mk_vma_flags(VMA_IO_BIT, VMA_PFNMAP_BIT,	\
611 				     VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT)
612 
613 /* This mask prevents VMA from being scanned with khugepaged */
614 #define VM_NO_KHUGEPAGED (VM_SPECIAL | VM_HUGETLB)
615 
616 /* This mask defines which mm->def_flags a process can inherit its parent */
617 #define VM_INIT_DEF_MASK	VM_NOHUGEPAGE
618 
619 /* This mask represents all the VMA flag bits used by mlock */
620 #define VM_LOCKED_MASK	(VM_LOCKED | VM_LOCKONFAULT)
621 
622 #define VMA_LOCKED_MASK	mk_vma_flags(VMA_LOCKED_BIT, VMA_LOCKONFAULT_BIT)
623 
624 /* These flags can be updated atomically via VMA/mmap read lock. */
625 #define VM_ATOMIC_SET_ALLOWED VM_MAYBE_GUARD
626 
627 /* Arch-specific flags to clear when updating VM flags on protection change */
628 #ifndef VM_ARCH_CLEAR
629 #define VM_ARCH_CLEAR	VM_NONE
630 #endif
631 #define VM_FLAGS_CLEAR	(ARCH_VM_PKEY_FLAGS | VM_ARCH_CLEAR)
632 
633 /*
634  * Flags which should be 'sticky' on merge - that is, flags which, when one VMA
635  * possesses it but the other does not, the merged VMA should nonetheless have
636  * applied to it:
637  *
638  *   VMA_SOFTDIRTY_BIT - if a VMA is marked soft-dirty, that is has not had its
639  *                       references cleared via /proc/$pid/clear_refs, any
640  *                       merged VMA should be considered soft-dirty also as it
641  *                       operates at a VMA granularity.
642  *
643  * VMA_MAYBE_GUARD_BIT - If a VMA may have guard regions in place it implies
644  *                       that mapped page tables may contain metadata not
645  *                       described by the VMA and thus any merged VMA may also
646  *                       contain this metadata, and thus we must make this flag
647  *                       sticky.
648  */
649 #ifdef CONFIG_MEM_SOFT_DIRTY
650 #define VMA_STICKY_FLAGS mk_vma_flags(VMA_SOFTDIRTY_BIT, VMA_MAYBE_GUARD_BIT)
651 #else
652 #define VMA_STICKY_FLAGS mk_vma_flags(VMA_MAYBE_GUARD_BIT)
653 #endif
654 
655 /*
656  * VMA flags we ignore for the purposes of merge, i.e. one VMA possessing one
657  * of these flags and the other not does not preclude a merge.
658  *
659  *    VMA_STICKY_FLAGS - When merging VMAs, VMA flags must match, unless they
660  *                       are 'sticky'. If any sticky flags exist in either VMA,
661  *                       we simply set all of them on the merged VMA.
662  */
663 #define VMA_IGNORE_MERGE_FLAGS VMA_STICKY_FLAGS
664 
665 /*
666  * Flags which should result in page tables being copied on fork. These are
667  * flags which indicate that the VMA maps page tables which cannot be
668  * reconsistuted upon page fault, so necessitate page table copying upon fork.
669  *
670  * Note that these flags should be compared with the DESTINATION VMA not the
671  * source: VM_UFFD_WP and VM_UFFD_RWP may be cleared on the destination
672  * (dup_userfaultfd() -> userfaultfd_reset_ctx() when the parent context did
673  * not negotiate UFFD_FEATURE_EVENT_FORK), while all other flags propagate.
674  *
675  * VM_PFNMAP / VM_MIXEDMAP - These contain kernel-mapped data which cannot be
676  *                           reasonably reconstructed on page fault.
677  *
678  *              VM_UFFD_WP - Encodes metadata about an installed uffd
679  *              VM_UFFD_RWP  write- or read-write-protect handler, which
680  *                           cannot be reconstructed on page fault.
681  *
682  *                           We always copy pgtables when dst_vma has the
683  *                           uffd PTE bit in use even if it's file-backed
684  *                           (e.g. shmem). Because when the uffd bit is
685  *                           in use, the pgtable contains the protection
686  *                           information, that's something we can't
687  *                           retrieve from page cache, and skip copying
688  *                           will lose those info.
689  *
690  *          VM_MAYBE_GUARD - Could contain page guard region markers which
691  *                           by design are a property of the page tables
692  *                           only and thus cannot be reconstructed on page
693  *                           fault.
694  */
695 #define VM_COPY_ON_FORK (VM_PFNMAP | VM_MIXEDMAP | VM_UFFD_WP | VM_UFFD_RWP | \
696 			 VM_MAYBE_GUARD)
697 
698 /*
699  * mapping from the currently active vm_flags protection bits (the
700  * low four bits) to a page protection mask..
701  */
702 
703 /*
704  * The default fault flags that should be used by most of the
705  * arch-specific page fault handlers.
706  */
707 #define FAULT_FLAG_DEFAULT  (FAULT_FLAG_ALLOW_RETRY | \
708 			     FAULT_FLAG_KILLABLE | \
709 			     FAULT_FLAG_INTERRUPTIBLE)
710 
711 /**
712  * fault_flag_allow_retry_first - check ALLOW_RETRY the first time
713  * @flags: Fault flags.
714  *
715  * This is mostly used for places where we want to try to avoid taking
716  * the mmap_lock for too long a time when waiting for another condition
717  * to change, in which case we can try to be polite to release the
718  * mmap_lock in the first round to avoid potential starvation of other
719  * processes that would also want the mmap_lock.
720  *
721  * Return: true if the page fault allows retry and this is the first
722  * attempt of the fault handling; false otherwise.
723  */
fault_flag_allow_retry_first(enum fault_flag flags)724 static inline bool fault_flag_allow_retry_first(enum fault_flag flags)
725 {
726 	return (flags & FAULT_FLAG_ALLOW_RETRY) &&
727 	    (!(flags & FAULT_FLAG_TRIED));
728 }
729 
730 #define FAULT_FLAG_TRACE \
731 	{ FAULT_FLAG_WRITE,		"WRITE" }, \
732 	{ FAULT_FLAG_MKWRITE,		"MKWRITE" }, \
733 	{ FAULT_FLAG_ALLOW_RETRY,	"ALLOW_RETRY" }, \
734 	{ FAULT_FLAG_RETRY_NOWAIT,	"RETRY_NOWAIT" }, \
735 	{ FAULT_FLAG_KILLABLE,		"KILLABLE" }, \
736 	{ FAULT_FLAG_TRIED,		"TRIED" }, \
737 	{ FAULT_FLAG_USER,		"USER" }, \
738 	{ FAULT_FLAG_REMOTE,		"REMOTE" }, \
739 	{ FAULT_FLAG_INSTRUCTION,	"INSTRUCTION" }, \
740 	{ FAULT_FLAG_INTERRUPTIBLE,	"INTERRUPTIBLE" }, \
741 	{ FAULT_FLAG_VMA_LOCK,		"VMA_LOCK" }
742 
743 /*
744  * vm_fault is filled by the pagefault handler and passed to the vma's
745  * ->fault function. The vma's ->fault is responsible for returning a bitmask
746  * of VM_FAULT_xxx flags that give details about how the fault was handled.
747  *
748  * MM layer fills up gfp_mask for page allocations but fault handler might
749  * alter it if its implementation requires a different allocation context.
750  *
751  * pgoff should be used in favour of virtual_address, if possible.
752  */
753 struct vm_fault {
754 	const struct {
755 		struct vm_area_struct *vma;	/* Target VMA */
756 		gfp_t gfp_mask;			/* gfp mask to be used for allocations */
757 		pgoff_t pgoff;			/* Logical page offset based on vma */
758 		unsigned long address;		/* Faulting virtual address - masked */
759 		unsigned long real_address;	/* Faulting virtual address - unmasked */
760 	};
761 	enum fault_flag flags;		/* FAULT_FLAG_xxx flags
762 					 * XXX: should really be 'const' */
763 	pmd_t *pmd;			/* Pointer to pmd entry matching
764 					 * the 'address' */
765 	pud_t *pud;			/* Pointer to pud entry matching
766 					 * the 'address'
767 					 */
768 	union {
769 		pte_t orig_pte;		/* Value of PTE at the time of fault */
770 		pmd_t orig_pmd;		/* Value of PMD at the time of fault,
771 					 * used by PMD fault only.
772 					 */
773 	};
774 
775 	struct page *cow_page;		/* Page handler may use for COW fault */
776 	struct page *page;		/* ->fault handlers should return a
777 					 * page here, unless VM_FAULT_NOPAGE
778 					 * is set (which is also implied by
779 					 * VM_FAULT_ERROR).
780 					 */
781 	/* These three entries are valid only while holding ptl lock */
782 	pte_t *pte;			/* Pointer to pte entry matching
783 					 * the 'address'. NULL if the page
784 					 * table hasn't been allocated.
785 					 */
786 	spinlock_t *ptl;		/* Page table lock.
787 					 * Protects pte page table if 'pte'
788 					 * is not NULL, otherwise pmd.
789 					 */
790 	pgtable_t prealloc_pte;		/* Pre-allocated pte page table.
791 					 * vm_ops->map_pages() sets up a page
792 					 * table from atomic context.
793 					 * do_fault_around() pre-allocates
794 					 * page table to avoid allocation from
795 					 * atomic context.
796 					 */
797 };
798 
799 struct vm_uffd_ops;
800 
801 /*
802  * These are the virtual MM functions - opening of an area, closing and
803  * unmapping it (needed to keep files on disk up-to-date etc), pointer
804  * to the functions called when a no-page or a wp-page exception occurs.
805  */
806 struct vm_operations_struct {
807 	/**
808 	 * @open: Called when a VMA is remapped, split or forked. Not called
809 	 * upon first mapping a VMA.
810 	 * Context: User context.  May sleep.  Caller holds mmap_lock.
811 	 */
812 	void (*open)(struct vm_area_struct *vma);
813 	/**
814 	 * @close: Called when the VMA is being removed from the MM.
815 	 * Context: User context.  May sleep.  Caller holds mmap_lock.
816 	 */
817 	void (*close)(struct vm_area_struct *vma);
818 	/**
819 	 * @mapped: Called when the VMA is first mapped in the MM. Not called if
820 	 * the new VMA is merged with an adjacent VMA.
821 	 *
822 	 * The @vm_private_data field is an output field allowing the user to
823 	 * modify vma->vm_private_data as necessary.
824 	 *
825 	 * ONLY valid if set from f_op->mmap_prepare. Will result in an error if
826 	 * set from f_op->mmap.
827 	 *
828 	 * Returns %0 on success, or an error otherwise. On error, the VMA will
829 	 * be unmapped.
830 	 *
831 	 * Context: User context.  May sleep.  Caller holds mmap_lock.
832 	 */
833 	int (*mapped)(unsigned long start, unsigned long end, pgoff_t pgoff,
834 		      const struct file *file, void **vm_private_data);
835 	/* Called any time before splitting to check if it's allowed */
836 	int (*may_split)(struct vm_area_struct *vma, unsigned long addr);
837 	int (*mremap)(struct vm_area_struct *vma);
838 	/*
839 	 * Called by mprotect() to make driver-specific permission
840 	 * checks before mprotect() is finalised.   The VMA must not
841 	 * be modified.  Returns 0 if mprotect() can proceed.
842 	 */
843 	int (*mprotect)(struct vm_area_struct *vma, unsigned long start,
844 			unsigned long end, unsigned long newflags);
845 	vm_fault_t (*fault)(struct vm_fault *vmf);
846 	vm_fault_t (*huge_fault)(struct vm_fault *vmf, unsigned int order);
847 	vm_fault_t (*map_pages)(struct vm_fault *vmf,
848 			pgoff_t start_pgoff, pgoff_t end_pgoff);
849 	unsigned long (*pagesize)(struct vm_area_struct *vma);
850 
851 	/* notification that a previously read-only page is about to become
852 	 * writable, if an error is returned it will cause a SIGBUS */
853 	vm_fault_t (*page_mkwrite)(struct vm_fault *vmf);
854 
855 	/* same as page_mkwrite when using VM_PFNMAP|VM_MIXEDMAP */
856 	vm_fault_t (*pfn_mkwrite)(struct vm_fault *vmf);
857 
858 	/* called by access_process_vm when get_user_pages() fails, typically
859 	 * for use by special VMAs. See also generic_access_phys() for a generic
860 	 * implementation useful for any iomem mapping.
861 	 */
862 	int (*access)(struct vm_area_struct *vma, unsigned long addr,
863 		      void *buf, int len, int write);
864 
865 	/* Called by the /proc/PID/maps code to ask the vma whether it
866 	 * has a special name.  Returning non-NULL will also cause this
867 	 * vma to be dumped unconditionally. */
868 	const char *(*name)(struct vm_area_struct *vma);
869 
870 #ifdef CONFIG_NUMA
871 	/*
872 	 * set_policy() op must add a reference to any non-NULL @new mempolicy
873 	 * to hold the policy upon return.  Caller should pass NULL @new to
874 	 * remove a policy and fall back to surrounding context--i.e. do not
875 	 * install a MPOL_DEFAULT policy, nor the task or system default
876 	 * mempolicy.
877 	 */
878 	int (*set_policy)(struct vm_area_struct *vma, struct mempolicy *new);
879 
880 	/*
881 	 * get_policy() op must add reference [mpol_get()] to any policy at
882 	 * (vma,addr) marked as MPOL_SHARED.  The shared policy infrastructure
883 	 * in mm/mempolicy.c will do this automatically.
884 	 * get_policy() must NOT add a ref if the policy at (vma,addr) is not
885 	 * marked as MPOL_SHARED. vma policies are protected by the mmap_lock.
886 	 * If no [shared/vma] mempolicy exists at the addr, get_policy() op
887 	 * must return NULL--i.e., do not "fallback" to task or system default
888 	 * policy.
889 	 */
890 	struct mempolicy *(*get_policy)(struct vm_area_struct *vma,
891 					unsigned long addr, pgoff_t *ilx);
892 #endif
893 #ifdef CONFIG_FIND_NORMAL_PAGE
894 	/*
895 	 * Called by vm_normal_page() for special PTEs in @vma at @addr. This
896 	 * allows for returning a "normal" page from vm_normal_page() even
897 	 * though the PTE indicates that the "struct page" either does not exist
898 	 * or should not be touched: "special".
899 	 *
900 	 * Do not add new users: this really only works when a "normal" page
901 	 * was mapped, but then the PTE got changed to something weird (+
902 	 * marked special) that would not make pte_pfn() identify the originally
903 	 * inserted page.
904 	 */
905 	struct page *(*find_normal_page)(struct vm_area_struct *vma,
906 					 unsigned long addr);
907 #endif /* CONFIG_FIND_NORMAL_PAGE */
908 #ifdef CONFIG_USERFAULTFD
909 	const struct vm_uffd_ops *uffd_ops;
910 #endif
911 };
912 
913 #ifdef CONFIG_NUMA_BALANCING
vma_numab_state_init(struct vm_area_struct * vma)914 static inline void vma_numab_state_init(struct vm_area_struct *vma)
915 {
916 	vma->numab_state = NULL;
917 }
vma_numab_state_free(struct vm_area_struct * vma)918 static inline void vma_numab_state_free(struct vm_area_struct *vma)
919 {
920 	kfree(vma->numab_state);
921 }
922 #else
vma_numab_state_init(struct vm_area_struct * vma)923 static inline void vma_numab_state_init(struct vm_area_struct *vma) {}
vma_numab_state_free(struct vm_area_struct * vma)924 static inline void vma_numab_state_free(struct vm_area_struct *vma) {}
925 #endif /* CONFIG_NUMA_BALANCING */
926 
927 /*
928  * These must be here rather than mmap_lock.h as dependent on vm_fault type,
929  * declared in this header.
930  */
931 #ifdef CONFIG_PER_VMA_LOCK
release_fault_lock(struct vm_fault * vmf)932 static inline void release_fault_lock(struct vm_fault *vmf)
933 {
934 	if (vmf->flags & FAULT_FLAG_VMA_LOCK)
935 		vma_end_read(vmf->vma);
936 	else
937 		mmap_read_unlock(vmf->vma->vm_mm);
938 }
939 
assert_fault_locked(const struct vm_fault * vmf)940 static inline void assert_fault_locked(const struct vm_fault *vmf)
941 {
942 	if (vmf->flags & FAULT_FLAG_VMA_LOCK)
943 		vma_assert_locked(vmf->vma);
944 	else
945 		mmap_assert_locked(vmf->vma->vm_mm);
946 }
947 #else
release_fault_lock(struct vm_fault * vmf)948 static inline void release_fault_lock(struct vm_fault *vmf)
949 {
950 	mmap_read_unlock(vmf->vma->vm_mm);
951 }
952 
assert_fault_locked(const struct vm_fault * vmf)953 static inline void assert_fault_locked(const struct vm_fault *vmf)
954 {
955 	mmap_assert_locked(vmf->vma->vm_mm);
956 }
957 #endif /* CONFIG_PER_VMA_LOCK */
958 
mm_flags_test(int flag,const struct mm_struct * mm)959 static inline bool mm_flags_test(int flag, const struct mm_struct *mm)
960 {
961 	return test_bit(flag, ACCESS_PRIVATE(&mm->flags, __mm_flags));
962 }
963 
mm_flags_test_and_set(int flag,struct mm_struct * mm)964 static inline bool mm_flags_test_and_set(int flag, struct mm_struct *mm)
965 {
966 	return test_and_set_bit(flag, ACCESS_PRIVATE(&mm->flags, __mm_flags));
967 }
968 
mm_flags_test_and_clear(int flag,struct mm_struct * mm)969 static inline bool mm_flags_test_and_clear(int flag, struct mm_struct *mm)
970 {
971 	return test_and_clear_bit(flag, ACCESS_PRIVATE(&mm->flags, __mm_flags));
972 }
973 
mm_flags_set(int flag,struct mm_struct * mm)974 static inline void mm_flags_set(int flag, struct mm_struct *mm)
975 {
976 	set_bit(flag, ACCESS_PRIVATE(&mm->flags, __mm_flags));
977 }
978 
mm_flags_clear(int flag,struct mm_struct * mm)979 static inline void mm_flags_clear(int flag, struct mm_struct *mm)
980 {
981 	clear_bit(flag, ACCESS_PRIVATE(&mm->flags, __mm_flags));
982 }
983 
mm_flags_clear_all(struct mm_struct * mm)984 static inline void mm_flags_clear_all(struct mm_struct *mm)
985 {
986 	bitmap_zero(ACCESS_PRIVATE(&mm->flags, __mm_flags), NUM_MM_FLAG_BITS);
987 }
988 
989 extern const struct vm_operations_struct vma_dummy_vm_ops;
990 
vma_init(struct vm_area_struct * vma,struct mm_struct * mm)991 static inline void vma_init(struct vm_area_struct *vma, struct mm_struct *mm)
992 {
993 	memset(vma, 0, sizeof(*vma));
994 	vma->vm_mm = mm;
995 	vma->vm_ops = &vma_dummy_vm_ops;
996 	INIT_LIST_HEAD(&vma->anon_vma_chain);
997 	vma_lock_init(vma, false);
998 }
999 
1000 /* Use when VMA is not part of the VMA tree and needs no locking */
vm_flags_init(struct vm_area_struct * vma,vm_flags_t flags)1001 static inline void vm_flags_init(struct vm_area_struct *vma,
1002 				 vm_flags_t flags)
1003 {
1004 	VM_WARN_ON_ONCE(!pgtable_supports_soft_dirty() && (flags & VM_SOFTDIRTY));
1005 	vma_flags_clear_all(&vma->flags);
1006 	vma_flags_overwrite_word(&vma->flags, flags);
1007 }
1008 
1009 /*
1010  * Use when VMA is part of the VMA tree and modifications need coordination
1011  * Note: vm_flags_reset and vm_flags_reset_once do not lock the vma and
1012  * it should be locked explicitly beforehand.
1013  */
vm_flags_reset(struct vm_area_struct * vma,vm_flags_t flags)1014 static inline void vm_flags_reset(struct vm_area_struct *vma,
1015 				  vm_flags_t flags)
1016 {
1017 	VM_WARN_ON_ONCE(!pgtable_supports_soft_dirty() && (flags & VM_SOFTDIRTY));
1018 	vma_assert_write_locked(vma);
1019 	vm_flags_init(vma, flags);
1020 }
1021 
vma_flags_reset_once(struct vm_area_struct * vma,vma_flags_t * flags)1022 static inline void vma_flags_reset_once(struct vm_area_struct *vma,
1023 					vma_flags_t *flags)
1024 {
1025 	const unsigned long word = flags->__vma_flags[0];
1026 
1027 	/* It is assumed only the first system word must be written once. */
1028 	vma_flags_overwrite_word_once(&vma->flags, word);
1029 	/* The remainder can be copied normally. */
1030 	if (NUM_VMA_FLAG_BITS > BITS_PER_LONG) {
1031 		unsigned long *dst = &vma->flags.__vma_flags[1];
1032 		const unsigned long *src = &flags->__vma_flags[1];
1033 
1034 		bitmap_copy(dst, src, NUM_VMA_FLAG_BITS - BITS_PER_LONG);
1035 	}
1036 }
1037 
vm_flags_set(struct vm_area_struct * vma,vm_flags_t flags)1038 static inline void vm_flags_set(struct vm_area_struct *vma,
1039 				vm_flags_t flags)
1040 {
1041 	vma_start_write(vma);
1042 	vma_flags_set_word(&vma->flags, flags);
1043 }
1044 
vm_flags_clear(struct vm_area_struct * vma,vm_flags_t flags)1045 static inline void vm_flags_clear(struct vm_area_struct *vma,
1046 				  vm_flags_t flags)
1047 {
1048 	VM_WARN_ON_ONCE(!pgtable_supports_soft_dirty() && (flags & VM_SOFTDIRTY));
1049 	vma_start_write(vma);
1050 	vma_flags_clear_word(&vma->flags, flags);
1051 }
1052 
1053 /*
1054  * Use only if VMA is not part of the VMA tree or has no other users and
1055  * therefore needs no locking.
1056  */
__vm_flags_mod(struct vm_area_struct * vma,vm_flags_t set,vm_flags_t clear)1057 static inline void __vm_flags_mod(struct vm_area_struct *vma,
1058 				  vm_flags_t set, vm_flags_t clear)
1059 {
1060 	vm_flags_init(vma, (vma->vm_flags | set) & ~clear);
1061 }
1062 
1063 /*
1064  * Use only when the order of set/clear operations is unimportant, otherwise
1065  * use vm_flags_{set|clear} explicitly.
1066  */
vm_flags_mod(struct vm_area_struct * vma,vm_flags_t set,vm_flags_t clear)1067 static inline void vm_flags_mod(struct vm_area_struct *vma,
1068 				vm_flags_t set, vm_flags_t clear)
1069 {
1070 	vma_start_write(vma);
1071 	__vm_flags_mod(vma, set, clear);
1072 }
1073 
__vma_atomic_valid_flag(struct vm_area_struct * vma,vma_flag_t bit)1074 static __always_inline bool __vma_atomic_valid_flag(struct vm_area_struct *vma,
1075 		vma_flag_t bit)
1076 {
1077 	const vm_flags_t mask = BIT((__force int)bit);
1078 
1079 	/* Only specific flags are permitted */
1080 	if (WARN_ON_ONCE(!(mask & VM_ATOMIC_SET_ALLOWED)))
1081 		return false;
1082 
1083 	return true;
1084 }
1085 
1086 /*
1087  * Set VMA flag atomically. Requires only VMA/mmap read lock. Only specific
1088  * valid flags are allowed to do this.
1089  */
vma_set_atomic_flag(struct vm_area_struct * vma,vma_flag_t bit)1090 static __always_inline void vma_set_atomic_flag(struct vm_area_struct *vma,
1091 		vma_flag_t bit)
1092 {
1093 	unsigned long *bitmap = vma->flags.__vma_flags;
1094 
1095 	vma_assert_stabilised(vma);
1096 	if (__vma_atomic_valid_flag(vma, bit))
1097 		set_bit((__force int)bit, bitmap);
1098 }
1099 
1100 /*
1101  * Test for VMA flag atomically. Requires no locks. Only specific valid flags
1102  * are allowed to do this.
1103  *
1104  * This is necessarily racey, so callers must ensure that serialisation is
1105  * achieved through some other means, or that races are permissible.
1106  */
vma_test_atomic_flag(struct vm_area_struct * vma,vma_flag_t bit)1107 static __always_inline bool vma_test_atomic_flag(struct vm_area_struct *vma,
1108 		vma_flag_t bit)
1109 {
1110 	if (__vma_atomic_valid_flag(vma, bit))
1111 		return test_bit((__force int)bit, &vma->vm_flags);
1112 
1113 	return false;
1114 }
1115 
1116 /* Set an individual VMA flag in flags, non-atomically. */
vma_flags_set_flag(vma_flags_t * flags,vma_flag_t bit)1117 static __always_inline void vma_flags_set_flag(vma_flags_t *flags,
1118 		vma_flag_t bit)
1119 {
1120 	unsigned long *bitmap = flags->__vma_flags;
1121 
1122 	__set_bit((__force int)bit, bitmap);
1123 }
1124 
__mk_vma_flags(vma_flags_t flags,size_t count,const vma_flag_t * bits)1125 static __always_inline vma_flags_t __mk_vma_flags(vma_flags_t flags,
1126 		size_t count, const vma_flag_t *bits)
1127 {
1128 	int i;
1129 
1130 	for (i = 0; i < count; i++)
1131 		vma_flags_set_flag(&flags, bits[i]);
1132 	return flags;
1133 }
1134 
1135 /*
1136  * Helper macro which bitwise-or combines the specified input flags into a
1137  * vma_flags_t bitmap value. E.g.:
1138  *
1139  * vma_flags_t flags = mk_vma_flags(VMA_IO_BIT, VMA_PFNMAP_BIT,
1140  *              VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT);
1141  *
1142  * The compiler cleverly optimises away all of the work and this ends up being
1143  * equivalent to aggregating the values manually.
1144  */
1145 #define mk_vma_flags(...) __mk_vma_flags(EMPTY_VMA_FLAGS,			\
1146 		COUNT_ARGS(__VA_ARGS__), (const vma_flag_t []){__VA_ARGS__})
1147 
1148 /*
1149  * Helper macro which acts like mk_vma_flags, only appending to a copy of the
1150  * specified flags rather than establishing new flags. E.g.:
1151  *
1152  * vma_flags_t flags = append_vma_flags(VMA_STACK_DEFAULT_FLAGS, VMA_STACK_BIT,
1153  *              VMA_ACCOUNT_BIT);
1154  */
1155 #define append_vma_flags(flags, ...) __mk_vma_flags(flags,			\
1156 		COUNT_ARGS(__VA_ARGS__), (const vma_flag_t []){__VA_ARGS__})
1157 
1158 /* Calculates the number of set bits in the specified VMA flags. */
vma_flags_count(const vma_flags_t * flags)1159 static __always_inline int vma_flags_count(const vma_flags_t *flags)
1160 {
1161 	const unsigned long *bitmap = flags->__vma_flags;
1162 
1163 	return bitmap_weight(bitmap, NUM_VMA_FLAG_BITS);
1164 }
1165 
1166 /*
1167  * Test whether a specific VMA flag is set, e.g.:
1168  *
1169  * if (vma_flags_test(flags, VMA_READ_BIT)) { ... }
1170  */
vma_flags_test(const vma_flags_t * flags,vma_flag_t bit)1171 static __always_inline bool vma_flags_test(const vma_flags_t *flags,
1172 		vma_flag_t bit)
1173 {
1174 	const unsigned long *bitmap = flags->__vma_flags;
1175 
1176 	return test_bit((__force int)bit, bitmap);
1177 }
1178 
1179 /*
1180  * Obtain a set of VMA flags which contain the overlapping flags contained
1181  * within flags and to_and.
1182  */
vma_flags_and_mask(const vma_flags_t * flags,vma_flags_t to_and)1183 static __always_inline vma_flags_t vma_flags_and_mask(const vma_flags_t *flags,
1184 						      vma_flags_t to_and)
1185 {
1186 	vma_flags_t dst;
1187 	unsigned long *bitmap_dst = dst.__vma_flags;
1188 	const unsigned long *bitmap = flags->__vma_flags;
1189 	const unsigned long *bitmap_to_and = to_and.__vma_flags;
1190 
1191 	bitmap_and(bitmap_dst, bitmap, bitmap_to_and, NUM_VMA_FLAG_BITS);
1192 	return dst;
1193 }
1194 
1195 /*
1196  * Obtain a set of VMA flags which contains the specified overlapping flags,
1197  * e.g.:
1198  *
1199  * vma_flags_t read_flags = vma_flags_and(&flags, VMA_READ_BIT,
1200  *                                        VMA_MAY_READ_BIT);
1201  */
1202 #define vma_flags_and(flags, ...)				\
1203 	vma_flags_and_mask(flags, mk_vma_flags(__VA_ARGS__))
1204 
1205 /*  Test each of to_test flags in flags, non-atomically. */
vma_flags_test_any_mask(const vma_flags_t * flags,vma_flags_t to_test)1206 static __always_inline bool vma_flags_test_any_mask(const vma_flags_t *flags,
1207 		vma_flags_t to_test)
1208 {
1209 	const unsigned long *bitmap = flags->__vma_flags;
1210 	const unsigned long *bitmap_to_test = to_test.__vma_flags;
1211 
1212 	return bitmap_intersects(bitmap_to_test, bitmap, NUM_VMA_FLAG_BITS);
1213 }
1214 
1215 /*
1216  * Test whether any specified VMA flag is set, e.g.:
1217  *
1218  * if (vma_flags_test_any(flags, VMA_READ_BIT, VMA_MAYREAD_BIT)) { ... }
1219  */
1220 #define vma_flags_test_any(flags, ...) \
1221 	vma_flags_test_any_mask(flags, mk_vma_flags(__VA_ARGS__))
1222 
1223 /* Test that ALL of the to_test flags are set, non-atomically. */
vma_flags_test_all_mask(const vma_flags_t * flags,vma_flags_t to_test)1224 static __always_inline bool vma_flags_test_all_mask(const vma_flags_t *flags,
1225 		vma_flags_t to_test)
1226 {
1227 	const unsigned long *bitmap = flags->__vma_flags;
1228 	const unsigned long *bitmap_to_test = to_test.__vma_flags;
1229 
1230 	return bitmap_subset(bitmap_to_test, bitmap, NUM_VMA_FLAG_BITS);
1231 }
1232 
1233 /*
1234  * Test whether ALL specified VMA flags are set, e.g.:
1235  *
1236  * if (vma_flags_test_all(flags, VMA_READ_BIT, VMA_MAYREAD_BIT)) { ... }
1237  */
1238 #define vma_flags_test_all(flags, ...) \
1239 	vma_flags_test_all_mask(flags, mk_vma_flags(__VA_ARGS__))
1240 
1241 /*
1242  * Helper to test that a flag mask of type vma_flags_t has a SINGLE flag set
1243  * (returning false if flagmask has no flags set).
1244  *
1245  * This is defined to make the semantics clearer when testing an optionally
1246  * defined VMA flags mask, e.g.:
1247  *
1248  * if (vma_flags_test_single_mask(&flags, VMA_DROPPABLE)) { ... }
1249  *
1250  * When VMA_DROPPABLE is defined if available, or set to EMPTY_VMA_FLAGS
1251  * otherwise.
1252  */
vma_flags_test_single_mask(const vma_flags_t * flags,vma_flags_t flagmask)1253 static __always_inline bool vma_flags_test_single_mask(const vma_flags_t *flags,
1254 		vma_flags_t flagmask)
1255 {
1256 	VM_WARN_ON_ONCE(vma_flags_count(&flagmask) > 1);
1257 
1258 	return vma_flags_test_any_mask(flags, flagmask);
1259 }
1260 
1261 /* Set each of the to_set flags in flags, non-atomically. */
vma_flags_set_mask(vma_flags_t * flags,vma_flags_t to_set)1262 static __always_inline void vma_flags_set_mask(vma_flags_t *flags,
1263 		vma_flags_t to_set)
1264 {
1265 	unsigned long *bitmap = flags->__vma_flags;
1266 	const unsigned long *bitmap_to_set = to_set.__vma_flags;
1267 
1268 	bitmap_or(bitmap, bitmap, bitmap_to_set, NUM_VMA_FLAG_BITS);
1269 }
1270 
1271 /*
1272  * Set all specified VMA flags, e.g.:
1273  *
1274  * vma_flags_set(&flags, VMA_READ_BIT, VMA_WRITE_BIT, VMA_EXEC_BIT);
1275  */
1276 #define vma_flags_set(flags, ...) \
1277 	vma_flags_set_mask(flags, mk_vma_flags(__VA_ARGS__))
1278 
__mk_vma_flags_from_masks(size_t count,const vma_flags_t * masks)1279 static __always_inline vma_flags_t __mk_vma_flags_from_masks(size_t count,
1280 		const vma_flags_t *masks)
1281 {
1282 	vma_flags_t flags = EMPTY_VMA_FLAGS;
1283 	size_t i;
1284 
1285 	for (i = 0; i < count; i++)
1286 		vma_flags_set_mask(&flags, masks[i]);
1287 	return flags;
1288 }
1289 
1290 /*
1291  * Combine pre-computed vma_flags_t masks into one value, e.g.:
1292  *
1293  * vma_flags_t flags = mk_vma_flags_from_masks(VMA_UFFD_WP, VMA_UFFD_MINOR);
1294  *
1295  * Unlike mk_vma_flags(), which takes bit numbers, this takes whole masks --
1296  * each of which may be EMPTY_VMA_FLAGS when its feature is unavailable -- so a
1297  * bit that does not exist on the current build is never materialised.
1298  */
1299 #define mk_vma_flags_from_masks(...)					\
1300 	__mk_vma_flags_from_masks(COUNT_ARGS(__VA_ARGS__),		\
1301 		(const vma_flags_t []){__VA_ARGS__})
1302 
1303 /* Clear all of the to-clear flags in flags, non-atomically. */
vma_flags_clear_mask(vma_flags_t * flags,vma_flags_t to_clear)1304 static __always_inline void vma_flags_clear_mask(vma_flags_t *flags,
1305 		vma_flags_t to_clear)
1306 {
1307 	unsigned long *bitmap = flags->__vma_flags;
1308 	const unsigned long *bitmap_to_clear = to_clear.__vma_flags;
1309 
1310 	bitmap_andnot(bitmap, bitmap, bitmap_to_clear, NUM_VMA_FLAG_BITS);
1311 }
1312 
1313 /*
1314  * Clear all specified individual flags, e.g.:
1315  *
1316  * vma_flags_clear(&flags, VMA_READ_BIT, VMA_WRITE_BIT, VMA_EXEC_BIT);
1317  */
1318 #define vma_flags_clear(flags, ...) \
1319 	vma_flags_clear_mask(flags, mk_vma_flags(__VA_ARGS__))
1320 
1321 /*
1322  * Obtain a VMA flags value containing those flags that are present in flags or
1323  * flags_other but not in both.
1324  */
vma_flags_diff_pair(const vma_flags_t * flags,const vma_flags_t * flags_other)1325 static __always_inline vma_flags_t vma_flags_diff_pair(const vma_flags_t *flags,
1326 		const vma_flags_t *flags_other)
1327 {
1328 	vma_flags_t dst;
1329 	const unsigned long *bitmap_other = flags_other->__vma_flags;
1330 	const unsigned long *bitmap = flags->__vma_flags;
1331 	unsigned long *bitmap_dst = dst.__vma_flags;
1332 
1333 	bitmap_xor(bitmap_dst, bitmap, bitmap_other, NUM_VMA_FLAG_BITS);
1334 	return dst;
1335 }
1336 
1337 /* Determine if flags and flags_other have precisely the same flags set. */
vma_flags_same_pair(const vma_flags_t * flags,const vma_flags_t * flags_other)1338 static __always_inline bool vma_flags_same_pair(const vma_flags_t *flags,
1339 						const vma_flags_t *flags_other)
1340 {
1341 	const unsigned long *bitmap = flags->__vma_flags;
1342 	const unsigned long *bitmap_other = flags_other->__vma_flags;
1343 
1344 	return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS);
1345 }
1346 
1347 /* Determine if flags and flags_other have precisely the same flags set.  */
vma_flags_same_mask(const vma_flags_t * flags,vma_flags_t flags_other)1348 static __always_inline bool vma_flags_same_mask(const vma_flags_t *flags,
1349 						vma_flags_t flags_other)
1350 {
1351 	const unsigned long *bitmap = flags->__vma_flags;
1352 	const unsigned long *bitmap_other = flags_other.__vma_flags;
1353 
1354 	return bitmap_equal(bitmap, bitmap_other, NUM_VMA_FLAG_BITS);
1355 }
1356 
1357 /*
1358  * Helper macro to determine if only the specific flags are set, e.g.:
1359  *
1360  * if (vma_flags_same(&flags, VMA_WRITE_BIT) { ... }
1361  */
1362 #define vma_flags_same(flags, ...) \
1363 	vma_flags_same_mask(flags, mk_vma_flags(__VA_ARGS__))
1364 
1365 /*
1366  * Test whether a specific flag in the VMA is set, e.g.:
1367  *
1368  * if (vma_test(vma, VMA_READ_BIT)) { ... }
1369  */
vma_test(const struct vm_area_struct * vma,vma_flag_t bit)1370 static __always_inline bool vma_test(const struct vm_area_struct *vma,
1371 		vma_flag_t bit)
1372 {
1373 	return vma_flags_test(&vma->flags, bit);
1374 }
1375 
1376 /* Helper to test any VMA flags in a VMA . */
vma_test_any_mask(const struct vm_area_struct * vma,vma_flags_t flags)1377 static __always_inline bool vma_test_any_mask(const struct vm_area_struct *vma,
1378 		vma_flags_t flags)
1379 {
1380 	return vma_flags_test_any_mask(&vma->flags, flags);
1381 }
1382 
1383 /*
1384  * Helper macro for testing whether any VMA flags are set in a VMA,
1385  * e.g.:
1386  *
1387  * if (vma_test_any(vma, VMA_IO_BIT, VMA_PFNMAP_BIT,
1388  *		VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT)) { ... }
1389  */
1390 #define vma_test_any(vma, ...) \
1391 	vma_test_any_mask(vma, mk_vma_flags(__VA_ARGS__))
1392 
1393 /*
1394  * Helper to test that ALL specified flags are set in a VMA.
1395  *
1396  * Note: appropriate locks must be held, this function does not acquire them for
1397  * you.
1398  */
vma_test_all_mask(const struct vm_area_struct * vma,vma_flags_t flags)1399 static __always_inline bool vma_test_all_mask(const struct vm_area_struct *vma,
1400 		vma_flags_t flags)
1401 {
1402 	return vma_flags_test_all_mask(&vma->flags, flags);
1403 }
1404 
1405 /*
1406  * Helper macro for checking that ALL specified flags are set in a VMA, e.g.:
1407  *
1408  * if (vma_test_all(vma, VMA_READ_BIT, VMA_MAYREAD_BIT) { ... }
1409  */
1410 #define vma_test_all(vma, ...) \
1411 	vma_test_all_mask(vma, mk_vma_flags(__VA_ARGS__))
1412 
1413 /*
1414  * Helper to test that a flag mask of type vma_flags_t has a SINGLE flag set
1415  * (returning false if flagmask has no flags set).
1416  *
1417  * This is useful when a flag needs to be either defined or not depending upon
1418  * kernel configuration, e.g.:
1419  *
1420  * if (vma_test_single_mask(vma, VMA_DROPPABLE)) { ... }
1421  *
1422  * When VMA_DROPPABLE is defined if available, or set to EMPTY_VMA_FLAGS
1423  * otherwise.
1424  */
1425 static __always_inline bool
vma_test_single_mask(const struct vm_area_struct * vma,vma_flags_t flagmask)1426 vma_test_single_mask(const struct vm_area_struct *vma, vma_flags_t flagmask)
1427 {
1428 	return vma_flags_test_single_mask(&vma->flags, flagmask);
1429 }
1430 
1431 /*
1432  * Helper to set all VMA flags in a VMA.
1433  *
1434  * Note: appropriate locks must be held, this function does not acquire them for
1435  * you.
1436  */
vma_set_flags_mask(struct vm_area_struct * vma,vma_flags_t flags)1437 static __always_inline void vma_set_flags_mask(struct vm_area_struct *vma,
1438 		vma_flags_t flags)
1439 {
1440 	vma_flags_set_mask(&vma->flags, flags);
1441 }
1442 
1443 /*
1444  * Helper macro for specifying VMA flags in a VMA, e.g.:
1445  *
1446  * vma_set_flags(vma, VMA_IO_BIT, VMA_PFNMAP_BIT, VMA_DONTEXPAND_BIT,
1447  * 		VMA_DONTDUMP_BIT);
1448  *
1449  * Note: appropriate locks must be held, this function does not acquire them for
1450  * you.
1451  */
1452 #define vma_set_flags(vma, ...) \
1453 	vma_set_flags_mask(vma, mk_vma_flags(__VA_ARGS__))
1454 
1455 /* Helper to clear all VMA flags in a VMA. */
vma_clear_flags_mask(struct vm_area_struct * vma,vma_flags_t flags)1456 static __always_inline void vma_clear_flags_mask(struct vm_area_struct *vma,
1457 		vma_flags_t flags)
1458 {
1459 	vma_flags_clear_mask(&vma->flags, flags);
1460 }
1461 
1462 /*
1463  * Helper macro for clearing VMA flags, e.g.:
1464  *
1465  * vma_clear_flags(vma, VMA_IO_BIT, VMA_PFNMAP_BIT, VMA_DONTEXPAND_BIT,
1466  * 		VMA_DONTDUMP_BIT);
1467  */
1468 #define vma_clear_flags(vma, ...) \
1469 	vma_clear_flags_mask(vma, mk_vma_flags(__VA_ARGS__))
1470 
1471 /*
1472  * Test whether a specific VMA flag is set in a VMA descriptor, e.g.:
1473  *
1474  * if (vma_desc_test(desc, VMA_READ_BIT)) { ... }
1475  */
vma_desc_test(const struct vm_area_desc * desc,vma_flag_t bit)1476 static __always_inline bool vma_desc_test(const struct vm_area_desc *desc,
1477 		vma_flag_t bit)
1478 {
1479 	return vma_flags_test(&desc->vma_flags, bit);
1480 }
1481 
1482 /* Helper to test any VMA flags in a VMA descriptor. */
vma_desc_test_any_mask(const struct vm_area_desc * desc,vma_flags_t flags)1483 static __always_inline bool vma_desc_test_any_mask(const struct vm_area_desc *desc,
1484 		vma_flags_t flags)
1485 {
1486 	return vma_flags_test_any_mask(&desc->vma_flags, flags);
1487 }
1488 
1489 /*
1490  * Helper macro for testing whether any VMA flags are set in a VMA descriptor,
1491  * e.g.:
1492  *
1493  * if (vma_desc_test_any(desc, VMA_IO_BIT, VMA_PFNMAP_BIT,
1494  *		VMA_DONTEXPAND_BIT, VMA_DONTDUMP_BIT)) { ... }
1495  */
1496 #define vma_desc_test_any(desc, ...) \
1497 	vma_desc_test_any_mask(desc, mk_vma_flags(__VA_ARGS__))
1498 
1499 /* Helper to test all VMA flags in a VMA descriptor. */
vma_desc_test_all_mask(const struct vm_area_desc * desc,vma_flags_t flags)1500 static __always_inline bool vma_desc_test_all_mask(const struct vm_area_desc *desc,
1501 		vma_flags_t flags)
1502 {
1503 	return vma_flags_test_all_mask(&desc->vma_flags, flags);
1504 }
1505 
1506 /*
1507  * Helper macro for testing whether ALL VMA flags are set in a VMA descriptor,
1508  * e.g.:
1509  *
1510  * if (vma_desc_test_all(desc, VMA_READ_BIT, VMA_MAYREAD_BIT)) { ... }
1511  */
1512 #define vma_desc_test_all(desc, ...) \
1513 	vma_desc_test_all_mask(desc, mk_vma_flags(__VA_ARGS__))
1514 
1515 /* Helper to set all VMA flags in a VMA descriptor. */
vma_desc_set_flags_mask(struct vm_area_desc * desc,vma_flags_t flags)1516 static __always_inline void vma_desc_set_flags_mask(struct vm_area_desc *desc,
1517 		vma_flags_t flags)
1518 {
1519 	vma_flags_set_mask(&desc->vma_flags, flags);
1520 }
1521 
1522 /*
1523  * Helper macro for specifying VMA flags for an input pointer to a struct
1524  * vm_area_desc object describing a proposed VMA, e.g.:
1525  *
1526  * vma_desc_set_flags(desc, VMA_IO_BIT, VMA_PFNMAP_BIT, VMA_DONTEXPAND_BIT,
1527  * 		VMA_DONTDUMP_BIT);
1528  */
1529 #define vma_desc_set_flags(desc, ...) \
1530 	vma_desc_set_flags_mask(desc, mk_vma_flags(__VA_ARGS__))
1531 
1532 /* Helper to clear all VMA flags in a VMA descriptor. */
vma_desc_clear_flags_mask(struct vm_area_desc * desc,vma_flags_t flags)1533 static __always_inline void vma_desc_clear_flags_mask(struct vm_area_desc *desc,
1534 		vma_flags_t flags)
1535 {
1536 	vma_flags_clear_mask(&desc->vma_flags, flags);
1537 }
1538 
1539 /*
1540  * Helper macro for clearing VMA flags for an input pointer to a struct
1541  * vm_area_desc object describing a proposed VMA, e.g.:
1542  *
1543  * vma_desc_clear_flags(desc, VMA_IO_BIT, VMA_PFNMAP_BIT, VMA_DONTEXPAND_BIT,
1544  * 		VMA_DONTDUMP_BIT);
1545  */
1546 #define vma_desc_clear_flags(desc, ...) \
1547 	vma_desc_clear_flags_mask(desc, mk_vma_flags(__VA_ARGS__))
1548 
vma_set_anonymous(struct vm_area_struct * vma)1549 static inline void vma_set_anonymous(struct vm_area_struct *vma)
1550 {
1551 	vma->vm_ops = NULL;
1552 }
1553 
vma_desc_set_anonymous(struct vm_area_desc * desc)1554 static inline void vma_desc_set_anonymous(struct vm_area_desc *desc)
1555 {
1556 	desc->vm_ops = NULL;
1557 }
1558 
vma_is_anonymous(const struct vm_area_struct * vma)1559 static inline bool vma_is_anonymous(const struct vm_area_struct *vma)
1560 {
1561 	return !vma->vm_ops;
1562 }
1563 
1564 /*
1565  * Indicate if the VMA is a heap for the given task; for
1566  * /proc/PID/maps that is the heap of the main task.
1567  */
vma_is_initial_heap(const struct vm_area_struct * vma)1568 static inline bool vma_is_initial_heap(const struct vm_area_struct *vma)
1569 {
1570 	return vma->vm_start < vma->vm_mm->brk &&
1571 		vma->vm_end > vma->vm_mm->start_brk;
1572 }
1573 
1574 /*
1575  * Indicate if the VMA is a stack for the given task; for
1576  * /proc/PID/maps that is the stack of the main task.
1577  */
vma_is_initial_stack(const struct vm_area_struct * vma)1578 static inline bool vma_is_initial_stack(const struct vm_area_struct *vma)
1579 {
1580 	/*
1581 	 * We make no effort to guess what a given thread considers to be
1582 	 * its "stack".  It's not even well-defined for programs written
1583 	 * languages like Go.
1584 	 */
1585 	return vma->vm_start <= vma->vm_mm->start_stack &&
1586 		vma->vm_end >= vma->vm_mm->start_stack;
1587 }
1588 
vma_flags_can_grow(const vma_flags_t * flags)1589 static inline bool vma_flags_can_grow(const vma_flags_t *flags)
1590 {
1591 	if (vma_flags_test_single_mask(flags, VMA_GROWSUP))
1592 		return true;
1593 	if (vma_flags_test(flags, VMA_GROWSDOWN_BIT))
1594 		return true;
1595 
1596 	return false;
1597 }
1598 
vma_can_grow(const struct vm_area_struct * vma)1599 static inline bool vma_can_grow(const struct vm_area_struct *vma)
1600 {
1601 	return vma_flags_can_grow(&vma->flags);
1602 }
1603 
vma_is_temporary_stack(const struct vm_area_struct * vma)1604 static inline bool vma_is_temporary_stack(const struct vm_area_struct *vma)
1605 {
1606 	if (!vma_can_grow(vma))
1607 		return false;
1608 
1609 	if ((vma->vm_flags & VM_STACK_INCOMPLETE_SETUP) ==
1610 						VM_STACK_INCOMPLETE_SETUP)
1611 		return true;
1612 
1613 	return false;
1614 }
1615 
vma_is_foreign(const struct vm_area_struct * vma)1616 static inline bool vma_is_foreign(const struct vm_area_struct *vma)
1617 {
1618 	if (!current->mm)
1619 		return true;
1620 
1621 	if (current->mm != vma->vm_mm)
1622 		return true;
1623 
1624 	return false;
1625 }
1626 
vma_is_accessible(const struct vm_area_struct * vma)1627 static inline bool vma_is_accessible(const struct vm_area_struct *vma)
1628 {
1629 	return vma->vm_flags & VM_ACCESS_FLAGS;
1630 }
1631 
is_shared_maywrite(const vma_flags_t * flags)1632 static inline bool is_shared_maywrite(const vma_flags_t *flags)
1633 {
1634 	return vma_flags_test_all(flags, VMA_SHARED_BIT, VMA_MAYWRITE_BIT);
1635 }
1636 
vma_is_shared_maywrite(const struct vm_area_struct * vma)1637 static inline bool vma_is_shared_maywrite(const struct vm_area_struct *vma)
1638 {
1639 	return is_shared_maywrite(&vma->flags);
1640 }
1641 
1642 /**
1643  * vma_kernel_pagesize - Default page size granularity for this VMA.
1644  * @vma: The user mapping.
1645  *
1646  * The kernel page size specifies in which granularity VMA modifications
1647  * can be performed. Folios in this VMA will be aligned to, and at least
1648  * the size of the number of bytes returned by this function.
1649  *
1650  * The default kernel page size is not affected by Transparent Huge Pages
1651  * being in effect.
1652  *
1653  * Return: The default page size granularity for this VMA.
1654  */
vma_kernel_pagesize(struct vm_area_struct * vma)1655 static inline unsigned long vma_kernel_pagesize(struct vm_area_struct *vma)
1656 {
1657 	if (unlikely(vma->vm_ops && vma->vm_ops->pagesize))
1658 		return vma->vm_ops->pagesize(vma);
1659 	return PAGE_SIZE;
1660 }
1661 
1662 unsigned long vma_mmu_pagesize(struct vm_area_struct *vma);
1663 
1664 static inline
vma_find(struct vma_iterator * vmi,unsigned long max)1665 struct vm_area_struct *vma_find(struct vma_iterator *vmi, unsigned long max)
1666 {
1667 	return mas_find(&vmi->mas, max - 1);
1668 }
1669 
vma_next(struct vma_iterator * vmi)1670 static inline struct vm_area_struct *vma_next(struct vma_iterator *vmi)
1671 {
1672 	/*
1673 	 * Uses mas_find() to get the first VMA when the iterator starts.
1674 	 * Calling mas_next() could skip the first entry.
1675 	 */
1676 	return mas_find(&vmi->mas, ULONG_MAX);
1677 }
1678 
1679 static inline
vma_iter_next_range(struct vma_iterator * vmi)1680 struct vm_area_struct *vma_iter_next_range(struct vma_iterator *vmi)
1681 {
1682 	return mas_next_range(&vmi->mas, ULONG_MAX);
1683 }
1684 
1685 
vma_prev(struct vma_iterator * vmi)1686 static inline struct vm_area_struct *vma_prev(struct vma_iterator *vmi)
1687 {
1688 	return mas_prev(&vmi->mas, 0);
1689 }
1690 
vma_iter_clear_gfp(struct vma_iterator * vmi,unsigned long start,unsigned long end,gfp_t gfp)1691 static inline int vma_iter_clear_gfp(struct vma_iterator *vmi,
1692 			unsigned long start, unsigned long end, gfp_t gfp)
1693 {
1694 	__mas_set_range(&vmi->mas, start, end - 1);
1695 	mas_store_gfp(&vmi->mas, NULL, gfp);
1696 	if (unlikely(mas_is_err(&vmi->mas)))
1697 		return -ENOMEM;
1698 
1699 	return 0;
1700 }
1701 
1702 /* Free any unused preallocations */
vma_iter_free(struct vma_iterator * vmi)1703 static inline void vma_iter_free(struct vma_iterator *vmi)
1704 {
1705 	mas_destroy(&vmi->mas);
1706 }
1707 
vma_iter_bulk_store(struct vma_iterator * vmi,struct vm_area_struct * vma)1708 static inline int vma_iter_bulk_store(struct vma_iterator *vmi,
1709 				      struct vm_area_struct *vma)
1710 {
1711 	vmi->mas.index = vma->vm_start;
1712 	vmi->mas.last = vma->vm_end - 1;
1713 	mas_store(&vmi->mas, vma);
1714 	if (unlikely(mas_is_err(&vmi->mas)))
1715 		return -ENOMEM;
1716 
1717 	vma_mark_attached(vma);
1718 	return 0;
1719 }
1720 
vma_iter_invalidate(struct vma_iterator * vmi)1721 static inline void vma_iter_invalidate(struct vma_iterator *vmi)
1722 {
1723 	mas_pause(&vmi->mas);
1724 }
1725 
vma_iter_set(struct vma_iterator * vmi,unsigned long addr)1726 static inline void vma_iter_set(struct vma_iterator *vmi, unsigned long addr)
1727 {
1728 	mas_set(&vmi->mas, addr);
1729 }
1730 
1731 #define for_each_vma(__vmi, __vma)					\
1732 	while (((__vma) = vma_next(&(__vmi))) != NULL)
1733 
1734 /* The MM code likes to work with exclusive end addresses */
1735 #define for_each_vma_range(__vmi, __vma, __end)				\
1736 	while (((__vma) = vma_find(&(__vmi), (__end))) != NULL)
1737 
1738 #ifdef CONFIG_SHMEM
1739 /*
1740  * The vma_is_shmem is not inline because it is used only by slow
1741  * paths in userfault.
1742  */
1743 bool vma_is_shmem(const struct vm_area_struct *vma);
1744 bool vma_is_anon_shmem(const struct vm_area_struct *vma);
1745 #else
vma_is_shmem(const struct vm_area_struct * vma)1746 static inline bool vma_is_shmem(const struct vm_area_struct *vma) { return false; }
vma_is_anon_shmem(const struct vm_area_struct * vma)1747 static inline bool vma_is_anon_shmem(const struct vm_area_struct *vma) { return false; }
1748 #endif
1749 
1750 int vma_is_stack_for_current(const struct vm_area_struct *vma);
1751 
1752 /* flush_tlb_range() takes a vma, not a mm, and can care about flags */
1753 #define TLB_FLUSH_VMA(mm,flags) { .vm_mm = (mm), .vm_flags = (flags) }
1754 
1755 struct mmu_gather;
1756 struct inode;
1757 
1758 extern void prep_compound_page(struct page *page, unsigned int order);
1759 
folio_large_order(const struct folio * folio)1760 static inline unsigned int folio_large_order(const struct folio *folio)
1761 {
1762 	return folio->_flags_1 & 0xff;
1763 }
1764 
1765 #ifdef NR_PAGES_IN_LARGE_FOLIO
folio_large_nr_pages(const struct folio * folio)1766 static inline unsigned long folio_large_nr_pages(const struct folio *folio)
1767 {
1768 	return folio->_nr_pages;
1769 }
1770 #else
folio_large_nr_pages(const struct folio * folio)1771 static inline unsigned long folio_large_nr_pages(const struct folio *folio)
1772 {
1773 	return 1L << folio_large_order(folio);
1774 }
1775 #endif
1776 
1777 /*
1778  * compound_order() can be called without holding a reference, which means
1779  * that niceties like page_folio() don't work.  These callers should be
1780  * prepared to handle wild return values.  For example, PG_head may be
1781  * set before the order is initialised, or this may be a tail page.
1782  * See compaction.c for some good examples.
1783  */
compound_order(const struct page * page)1784 static inline unsigned int compound_order(const struct page *page)
1785 {
1786 	const struct folio *folio = (struct folio *)page;
1787 
1788 	if (!test_bit(PG_head, &folio->flags.f))
1789 		return 0;
1790 	return folio_large_order(folio);
1791 }
1792 
1793 /**
1794  * folio_order - The allocation order of a folio.
1795  * @folio: The folio.
1796  *
1797  * A folio is composed of 2^order pages.  See get_order() for the definition
1798  * of order.
1799  *
1800  * Return: The order of the folio.
1801  */
folio_order(const struct folio * folio)1802 static inline unsigned int folio_order(const struct folio *folio)
1803 {
1804 	if (!folio_test_large(folio))
1805 		return 0;
1806 	return folio_large_order(folio);
1807 }
1808 
1809 /**
1810  * folio_reset_order - Reset the folio order and derived _nr_pages
1811  * @folio: The folio.
1812  *
1813  * Reset the order and derived _nr_pages to 0. Must only be used in the
1814  * process of splitting large folios.
1815  */
folio_reset_order(struct folio * folio)1816 static inline void folio_reset_order(struct folio *folio)
1817 {
1818 	if (WARN_ON_ONCE(!folio_test_large(folio)))
1819 		return;
1820 	folio->_flags_1 &= ~0xffUL;
1821 #ifdef NR_PAGES_IN_LARGE_FOLIO
1822 	folio->_nr_pages = 0;
1823 #endif
1824 }
1825 
1826 #include <linux/huge_mm.h>
1827 
1828 /*
1829  * Methods to modify the page usage count.
1830  *
1831  * What counts for a page usage:
1832  * - cache mapping   (page->mapping)
1833  * - private data    (page->private)
1834  * - page mapped in a task's page tables, each mapping
1835  *   is counted separately
1836  *
1837  * Also, many kernel routines increase the page count before a critical
1838  * routine so they can be sure the page doesn't go away from under them.
1839  */
1840 
1841 /*
1842  * Drop a ref, return true if the refcount fell to zero (the page has no users)
1843  */
put_page_testzero(struct page * page)1844 static inline int put_page_testzero(struct page *page)
1845 {
1846 	VM_BUG_ON_PAGE(page_ref_count(page) == 0, page);
1847 	return page_ref_dec_and_test(page);
1848 }
1849 
folio_put_testzero(struct folio * folio)1850 static inline int folio_put_testzero(struct folio *folio)
1851 {
1852 	return put_page_testzero(&folio->page);
1853 }
1854 
1855 /*
1856  * Try to grab a ref unless the page has a refcount of zero, return false if
1857  * that is the case.
1858  * This can be called when MMU is off so it must not access
1859  * any of the virtual mappings.
1860  */
get_page_unless_zero(struct page * page)1861 static inline bool get_page_unless_zero(struct page *page)
1862 {
1863 	return page_ref_add_unless_zero(page, 1);
1864 }
1865 
folio_get_nontail_page(struct page * page)1866 static inline struct folio *folio_get_nontail_page(struct page *page)
1867 {
1868 	if (unlikely(!get_page_unless_zero(page)))
1869 		return NULL;
1870 	return (struct folio *)page;
1871 }
1872 
1873 extern int page_is_ram(unsigned long pfn);
1874 
1875 enum {
1876 	REGION_INTERSECTS,
1877 	REGION_DISJOINT,
1878 	REGION_MIXED,
1879 };
1880 
1881 int region_intersects(resource_size_t offset, size_t size, unsigned long flags,
1882 		      unsigned long desc);
1883 
1884 /* Support for virtually mapped pages */
1885 struct page *vmalloc_to_page(const void *addr);
1886 unsigned long vmalloc_to_pfn(const void *addr);
1887 
1888 /*
1889  * Determine if an address is within the vmalloc range
1890  *
1891  * On nommu, vmalloc/vfree wrap through kmalloc/kfree directly, so there
1892  * is no special casing required.
1893  */
1894 #ifdef CONFIG_MMU
1895 extern bool is_vmalloc_addr(const void *x);
1896 extern int is_vmalloc_or_module_addr(const void *x);
1897 #else
is_vmalloc_addr(const void * x)1898 static inline bool is_vmalloc_addr(const void *x)
1899 {
1900 	return false;
1901 }
is_vmalloc_or_module_addr(const void * x)1902 static inline int is_vmalloc_or_module_addr(const void *x)
1903 {
1904 	return 0;
1905 }
1906 #endif
1907 
1908 /*
1909  * How many times the entire folio is mapped as a single unit (eg by a
1910  * PMD or PUD entry).  This is probably not what you want, except for
1911  * debugging purposes or implementation of other core folio_*() primitives.
1912  */
folio_entire_mapcount(const struct folio * folio)1913 static inline int folio_entire_mapcount(const struct folio *folio)
1914 {
1915 	VM_BUG_ON_FOLIO(!folio_test_large(folio), folio);
1916 	if (!IS_ENABLED(CONFIG_64BIT) && unlikely(folio_large_order(folio) == 1))
1917 		return 0;
1918 	return atomic_read(&folio->_entire_mapcount) + 1;
1919 }
1920 
folio_large_mapcount(const struct folio * folio)1921 static inline int folio_large_mapcount(const struct folio *folio)
1922 {
1923 	VM_WARN_ON_FOLIO(!folio_test_large(folio), folio);
1924 	return atomic_read(&folio->_large_mapcount) + 1;
1925 }
1926 
1927 /**
1928  * folio_mapcount() - Number of mappings of this folio.
1929  * @folio: The folio.
1930  *
1931  * The folio mapcount corresponds to the number of present user page table
1932  * entries that reference any part of a folio. Each such present user page
1933  * table entry must be paired with exactly on folio reference.
1934  *
1935  * For ordindary folios, each user page table entry (PTE/PMD/PUD/...) counts
1936  * exactly once.
1937  *
1938  * For hugetlb folios, each abstracted "hugetlb" user page table entry that
1939  * references the entire folio counts exactly once, even when such special
1940  * page table entries are comprised of multiple ordinary page table entries.
1941  *
1942  * Will report 0 for pages which cannot be mapped into userspace, such as
1943  * slab, page tables and similar.
1944  *
1945  * Return: The number of times this folio is mapped.
1946  */
folio_mapcount(const struct folio * folio)1947 static inline int folio_mapcount(const struct folio *folio)
1948 {
1949 	int mapcount;
1950 
1951 	if (likely(!folio_test_large(folio))) {
1952 		mapcount = atomic_read(&folio->_mapcount) + 1;
1953 		if (page_mapcount_is_type(mapcount))
1954 			mapcount = 0;
1955 		return mapcount;
1956 	}
1957 	return folio_large_mapcount(folio);
1958 }
1959 
1960 /**
1961  * folio_mapped - Is this folio mapped into userspace?
1962  * @folio: The folio.
1963  *
1964  * Return: True if any page in this folio is referenced by user page tables.
1965  */
folio_mapped(const struct folio * folio)1966 static inline bool folio_mapped(const struct folio *folio)
1967 {
1968 	return folio_mapcount(folio) >= 1;
1969 }
1970 
virt_to_head_page(const void * x)1971 static inline struct page *virt_to_head_page(const void *x)
1972 {
1973 	struct page *page = virt_to_page(x);
1974 
1975 	return compound_head(page);
1976 }
1977 
virt_to_folio(const void * x)1978 static inline struct folio *virt_to_folio(const void *x)
1979 {
1980 	struct page *page = virt_to_page(x);
1981 
1982 	return page_folio(page);
1983 }
1984 
1985 void __folio_put(struct folio *folio);
1986 
1987 void split_page(struct page *page, unsigned int order);
1988 void folio_copy(struct folio *dst, struct folio *src);
1989 int folio_mc_copy(struct folio *dst, struct folio *src);
1990 
1991 unsigned long nr_free_buffer_pages(void);
1992 
1993 /* Returns the number of bytes in this potentially compound page. */
page_size(const struct page * page)1994 static inline unsigned long page_size(const struct page *page)
1995 {
1996 	return PAGE_SIZE << compound_order(page);
1997 }
1998 
1999 /* Returns the number of bits needed for the number of bytes in a page */
page_shift(struct page * page)2000 static inline unsigned int page_shift(struct page *page)
2001 {
2002 	return PAGE_SHIFT + compound_order(page);
2003 }
2004 
2005 /**
2006  * thp_order - Order of a transparent huge page.
2007  * @page: Head page of a transparent huge page.
2008  */
thp_order(struct page * page)2009 static inline unsigned int thp_order(struct page *page)
2010 {
2011 	VM_BUG_ON_PGFLAGS(PageTail(page), page);
2012 	return compound_order(page);
2013 }
2014 
2015 /**
2016  * thp_size - Size of a transparent huge page.
2017  * @page: Head page of a transparent huge page.
2018  *
2019  * Return: Number of bytes in this page.
2020  */
thp_size(struct page * page)2021 static inline unsigned long thp_size(struct page *page)
2022 {
2023 	return PAGE_SIZE << thp_order(page);
2024 }
2025 
2026 #ifdef CONFIG_MMU
2027 /*
2028  * Do pte_mkwrite, but only if the vma says VM_WRITE.  We do this when
2029  * servicing faults for write access.  In the normal case, do always want
2030  * pte_mkwrite.  But get_user_pages can cause write faults for mappings
2031  * that do not have writing enabled, when used by access_process_vm.
2032  */
maybe_mkwrite(pte_t pte,struct vm_area_struct * vma)2033 static inline pte_t maybe_mkwrite(pte_t pte, struct vm_area_struct *vma)
2034 {
2035 	if (likely(vma->vm_flags & VM_WRITE))
2036 		pte = pte_mkwrite(pte, vma);
2037 	return pte;
2038 }
2039 
2040 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *page);
2041 void set_pte_range(struct vm_fault *vmf, struct folio *folio,
2042 		struct page *page, unsigned int nr, unsigned long addr);
2043 
2044 vm_fault_t finish_fault(struct vm_fault *vmf);
2045 #endif
2046 
2047 /*
2048  * Multiple processes may "see" the same page. E.g. for untouched
2049  * mappings of /dev/null, all processes see the same page full of
2050  * zeroes, and text pages of executables and shared libraries have
2051  * only one copy in memory, at most, normally.
2052  *
2053  * For the non-reserved pages, page_count(page) denotes a reference count.
2054  *   page_count() == 0 means the page is free. page->lru is then used for
2055  *   freelist management in the buddy allocator.
2056  *   page_count() > 0  means the page has been allocated.
2057  *
2058  * Pages are allocated by the slab allocator in order to provide memory
2059  * to kmalloc and kmem_cache_alloc. In this case, the management of the
2060  * page, and the fields in 'struct page' are the responsibility of mm/slab.c
2061  * unless a particular usage is carefully commented. (the responsibility of
2062  * freeing the kmalloc memory is the caller's, of course).
2063  *
2064  * A page may be used by anyone else who does a __get_free_page().
2065  * In this case, page_count still tracks the references, and should only
2066  * be used through the normal accessor functions. The top bits of page->flags
2067  * and page->virtual store page management information, but all other fields
2068  * are unused and could be used privately, carefully. The management of this
2069  * page is the responsibility of the one who allocated it, and those who have
2070  * subsequently been given references to it.
2071  *
2072  * The other pages (we may call them "pagecache pages") are completely
2073  * managed by the Linux memory manager: I/O, buffers, swapping etc.
2074  * The following discussion applies only to them.
2075  *
2076  * A pagecache page contains an opaque `private' member, which belongs to the
2077  * page's address_space. Usually, this is the address of a circular list of
2078  * the page's disk buffers. PG_private must be set to tell the VM to call
2079  * into the filesystem to release these pages.
2080  *
2081  * A folio may belong to an inode's memory mapping. In this case,
2082  * folio->mapping points to the inode, and folio->index is the file
2083  * offset of the folio, in units of PAGE_SIZE.
2084  *
2085  * If pagecache pages are not associated with an inode, they are said to be
2086  * anonymous pages. These may become associated with the swapcache, and in that
2087  * case PG_swapcache is set, and page->private is an offset into the swapcache.
2088  *
2089  * In either case (swapcache or inode backed), the pagecache itself holds one
2090  * reference to the page. Setting PG_private should also increment the
2091  * refcount. The each user mapping also has a reference to the page.
2092  *
2093  * The pagecache pages are stored in a per-mapping radix tree, which is
2094  * rooted at mapping->i_pages, and indexed by offset.
2095  * Where 2.4 and early 2.6 kernels kept dirty/clean pages in per-address_space
2096  * lists, we instead now tag pages as dirty/writeback in the radix tree.
2097  *
2098  * All pagecache pages may be subject to I/O:
2099  * - inode pages may need to be read from disk,
2100  * - inode pages which have been modified and are MAP_SHARED may need
2101  *   to be written back to the inode on disk,
2102  * - anonymous pages (including MAP_PRIVATE file mappings) which have been
2103  *   modified may need to be swapped out to swap space and (later) to be read
2104  *   back into memory.
2105  */
2106 
2107 /* 127: arbitrary random number, small enough to assemble well */
2108 #define folio_ref_zero_or_close_to_overflow(folio) \
2109 	((unsigned int) folio_ref_count(folio) + 127u <= 127u)
2110 
2111 /**
2112  * folio_get - Increment the reference count on a folio.
2113  * @folio: The folio.
2114  *
2115  * Context: May be called in any context, as long as you know that
2116  * you have a refcount on the folio.  If you do not already have one,
2117  * folio_try_get() may be the right interface for you to use.
2118  */
folio_get(struct folio * folio)2119 static inline void folio_get(struct folio *folio)
2120 {
2121 	VM_BUG_ON_FOLIO(folio_ref_zero_or_close_to_overflow(folio), folio);
2122 	folio_ref_inc(folio);
2123 }
2124 
get_page(struct page * page)2125 static inline void get_page(struct page *page)
2126 {
2127 	struct folio *folio = page_folio(page);
2128 	if (WARN_ON_ONCE(folio_test_slab(folio)))
2129 		return;
2130 	if (WARN_ON_ONCE(folio_test_large_kmalloc(folio)))
2131 		return;
2132 	folio_get(folio);
2133 }
2134 
try_get_page(struct page * page)2135 static inline __must_check bool try_get_page(struct page *page)
2136 {
2137 	page = compound_head(page);
2138 	if (WARN_ON_ONCE(page_ref_count(page) <= 0))
2139 		return false;
2140 	page_ref_inc(page);
2141 	return true;
2142 }
2143 
2144 /**
2145  * folio_put - Decrement the reference count on a folio.
2146  * @folio: The folio.
2147  *
2148  * If the folio's reference count reaches zero, the memory will be
2149  * released back to the page allocator and may be used by another
2150  * allocation immediately.  Do not access the memory or the struct folio
2151  * after calling folio_put() unless you can be sure that it wasn't the
2152  * last reference.
2153  *
2154  * Context: May be called in process or interrupt context, but not in NMI
2155  * context.  May be called while holding a spinlock.
2156  */
folio_put(struct folio * folio)2157 static inline void folio_put(struct folio *folio)
2158 {
2159 	if (folio_put_testzero(folio))
2160 		__folio_put(folio);
2161 }
2162 
2163 /**
2164  * folio_put_refs - Reduce the reference count on a folio.
2165  * @folio: The folio.
2166  * @refs: The amount to subtract from the folio's reference count.
2167  *
2168  * If the folio's reference count reaches zero, the memory will be
2169  * released back to the page allocator and may be used by another
2170  * allocation immediately.  Do not access the memory or the struct folio
2171  * after calling folio_put_refs() unless you can be sure that these weren't
2172  * the last references.
2173  *
2174  * Context: May be called in process or interrupt context, but not in NMI
2175  * context.  May be called while holding a spinlock.
2176  */
folio_put_refs(struct folio * folio,int refs)2177 static inline void folio_put_refs(struct folio *folio, int refs)
2178 {
2179 	if (folio_ref_sub_and_test(folio, refs))
2180 		__folio_put(folio);
2181 }
2182 
2183 void folios_put_refs(struct folio_batch *folios, unsigned int *refs);
2184 
2185 /*
2186  * union release_pages_arg - an array of pages or folios
2187  *
2188  * release_pages() releases a simple array of multiple pages, and
2189  * accepts various different forms of said page array: either
2190  * a regular old boring array of pages, an array of folios, or
2191  * an array of encoded page pointers.
2192  *
2193  * The transparent union syntax for this kind of "any of these
2194  * argument types" is all kinds of ugly, so look away.
2195  */
2196 typedef union {
2197 	struct page **pages;
2198 	struct folio **folios;
2199 	struct encoded_page **encoded_pages;
2200 } release_pages_arg __attribute__ ((__transparent_union__));
2201 
2202 void release_pages(release_pages_arg, int nr);
2203 
2204 /**
2205  * folios_put - Decrement the reference count on an array of folios.
2206  * @folios: The folios.
2207  *
2208  * Like folio_put(), but for a batch of folios.  This is more efficient
2209  * than writing the loop yourself as it will optimise the locks which need
2210  * to be taken if the folios are freed.  The folios batch is returned
2211  * empty and ready to be reused for another batch; there is no need to
2212  * reinitialise it.
2213  *
2214  * Context: May be called in process or interrupt context, but not in NMI
2215  * context.  May be called while holding a spinlock.
2216  */
folios_put(struct folio_batch * folios)2217 static inline void folios_put(struct folio_batch *folios)
2218 {
2219 	folios_put_refs(folios, NULL);
2220 }
2221 
put_page(struct page * page)2222 static inline void put_page(struct page *page)
2223 {
2224 	struct folio *folio = page_folio(page);
2225 
2226 	if (folio_test_slab(folio) || folio_test_large_kmalloc(folio))
2227 		return;
2228 
2229 	folio_put(folio);
2230 }
2231 
2232 /*
2233  * GUP_PIN_COUNTING_BIAS, and the associated functions that use it, overload
2234  * the page's refcount so that two separate items are tracked: the original page
2235  * reference count, and also a new count of how many pin_user_pages() calls were
2236  * made against the page. ("gup-pinned" is another term for the latter).
2237  *
2238  * With this scheme, pin_user_pages() becomes special: such pages are marked as
2239  * distinct from normal pages. As such, the unpin_user_page() call (and its
2240  * variants) must be used in order to release gup-pinned pages.
2241  *
2242  * Choice of value:
2243  *
2244  * By making GUP_PIN_COUNTING_BIAS a power of two, debugging of page reference
2245  * counts with respect to pin_user_pages() and unpin_user_page() becomes
2246  * simpler, due to the fact that adding an even power of two to the page
2247  * refcount has the effect of using only the upper N bits, for the code that
2248  * counts up using the bias value. This means that the lower bits are left for
2249  * the exclusive use of the original code that increments and decrements by one
2250  * (or at least, by much smaller values than the bias value).
2251  *
2252  * Of course, once the lower bits overflow into the upper bits (and this is
2253  * OK, because subtraction recovers the original values), then visual inspection
2254  * no longer suffices to directly view the separate counts. However, for normal
2255  * applications that don't have huge page reference counts, this won't be an
2256  * issue.
2257  *
2258  * Locking: the lockless algorithm described in folio_try_get_rcu()
2259  * provides safe operation for get_user_pages(), folio_mkclean() and
2260  * other calls that race to set up page table entries.
2261  */
2262 #define GUP_PIN_COUNTING_BIAS (1U << 10)
2263 
2264 void unpin_user_page(struct page *page);
2265 void unpin_folio(struct folio *folio);
2266 void unpin_user_pages_dirty_lock(struct page **pages, unsigned long npages,
2267 				 bool make_dirty);
2268 void unpin_user_page_range_dirty_lock(struct page *page, unsigned long npages,
2269 				      bool make_dirty);
2270 void unpin_user_pages(struct page **pages, unsigned long npages);
2271 void unpin_user_folio(struct folio *folio, unsigned long npages);
2272 void unpin_folios(struct folio **folios, unsigned long nfolios);
2273 
2274 /**
2275  * vma_flags_is_cow_mapping() - Do these VMA flags imply a CoW mapping?
2276  * @flags: The VMA flags to check.
2277  *
2278  * Mappings which could be CoW'd (subject to Copy-On-Write faults) are
2279  * described as CoW mappings.
2280  *
2281  * All mappings backed by anonymous folios (all anonymous mappings and most
2282  * MAP_PRIVATE-file backed ranges) are CoW mappings.
2283  *
2284  * All other mappings (including all MAP_SHARED mappings) are non-CoW.
2285  *
2286  * The criteria are !VMA_SHARED_BIT, VMA_MAYWRITE_BIT.
2287  *
2288  * VMA_MAYWRITE_BIT is checked instead of VMA_WRITE_BIT to account for both
2289  * future mprotect() calls which can render a read-only mapping writable, and
2290  * GUP with FOLL_FORCE (e.g. ptrace) which can CoW a read-only mapping.
2291  *
2292  * - No anonymous mapping can ever clear VMA_MAYWRITE_BIT.
2293  *
2294  * - Writes to anonymous mappings do not immediately result in CoW faults but
2295  *   may do so after the process is forked or if a read is followed by a
2296  *   write.
2297  *
2298  * - Writes to MAP_PRIVATE file-backed mappings result in CoW faults and may
2299  *   do so again after fork.
2300  *
2301  * - MAP_SHARED mappings of a file opened read-only are transformed into
2302  *   VMA_MAYSHARE_BIT, !VMA_SHARED_BIT, !VMA_MAYWRITE_BIT mappings, so remain
2303  *   non-CoW.
2304  *
2305  * - Drivers may clear VMA_MAYWRITE_BIT but do so at mmap() time and cannot
2306  *   mark themselves anonymous. Having cleared this flag it is not valid for
2307  *   them to leave the VMA_WRITE_BIT flag set.
2308  *
2309  * As a consequence, the anonymous reverse mapping only tracks CoW mappings.
2310  *
2311  * Returns: true if the flags indicate a CoW mapping, otherwise false.
2312  */
vma_flags_is_cow_mapping(const vma_flags_t * flags)2313 static inline bool vma_flags_is_cow_mapping(const vma_flags_t *flags)
2314 {
2315 	return vma_flags_test(flags, VMA_MAYWRITE_BIT) &&
2316 		!vma_flags_test(flags, VMA_SHARED_BIT);
2317 }
2318 
2319 /**
2320  * vma_is_cow_mapping() - Is this VMA a CoW mapping?
2321  * @vma: The VMA to check.
2322  *
2323  * See vma_flags_is_cow_mapping() for details.
2324  *
2325  * Returns: true if the VMA is a CoW mapping, otherwise false.
2326  */
vma_is_cow_mapping(const struct vm_area_struct * vma)2327 static inline bool vma_is_cow_mapping(const struct vm_area_struct *vma)
2328 {
2329 	return vma_flags_is_cow_mapping(&vma->flags);
2330 }
2331 
2332 /**
2333  * vma_desc_is_cow_mapping() - Is this VMA descriptor a CoW mapping?
2334  * @desc: The VMA descriptor to check.
2335  *
2336  * See vma_flags_is_cow_mapping() for details.
2337  *
2338  * Returns: true if the VMA descriptor describes a CoW mapping, otherwise
2339  * false.
2340  */
vma_desc_is_cow_mapping(struct vm_area_desc * desc)2341 static inline bool vma_desc_is_cow_mapping(struct vm_area_desc *desc)
2342 {
2343 	return vma_flags_is_cow_mapping(&desc->vma_flags);
2344 }
2345 
2346 #ifndef CONFIG_MMU
is_nommu_shared_mapping(vm_flags_t flags)2347 static inline bool is_nommu_shared_mapping(vm_flags_t flags)
2348 {
2349 	/*
2350 	 * NOMMU shared mappings are ordinary MAP_SHARED mappings and selected
2351 	 * R/O MAP_PRIVATE file mappings that are an effective R/O overlay of
2352 	 * a file mapping. R/O MAP_PRIVATE mappings might still modify
2353 	 * underlying memory if ptrace is active, so this is only possible if
2354 	 * ptrace does not apply. Note that there is no mprotect() to upgrade
2355 	 * write permissions later.
2356 	 */
2357 	return flags & (VM_MAYSHARE | VM_MAYOVERLAY);
2358 }
2359 
is_nommu_shared_vma_flags(const vma_flags_t * flags)2360 static inline bool is_nommu_shared_vma_flags(const vma_flags_t *flags)
2361 {
2362 	return vma_flags_test_any(flags, VMA_MAYSHARE_BIT, VMA_MAYOVERLAY_BIT);
2363 }
2364 #endif
2365 
2366 #if defined(CONFIG_SPARSEMEM) && !defined(CONFIG_SPARSEMEM_VMEMMAP)
2367 #define SECTION_IN_PAGE_FLAGS
2368 #endif
2369 
2370 /*
2371  * The identification function is mainly used by the buddy allocator for
2372  * determining if two pages could be buddies. We are not really identifying
2373  * the zone since we could be using the section number id if we do not have
2374  * node id available in page flags.
2375  * We only guarantee that it will return the same value for two combinable
2376  * pages in a zone.
2377  */
page_zone_id(struct page * page)2378 static inline int page_zone_id(struct page *page)
2379 {
2380 	return (page->flags.f >> ZONEID_PGSHIFT) & ZONEID_MASK;
2381 }
2382 
2383 #ifdef NODE_NOT_IN_PAGE_FLAGS
2384 int memdesc_nid(const memdesc_flags_t *mdf);
2385 #else
2386 #ifdef CONFIG_NUMA
memdesc_nid(const memdesc_flags_t * mdf)2387 static inline int memdesc_nid(const memdesc_flags_t *mdf)
2388 {
2389 	ASSERT_EXCLUSIVE_BITS(mdf->f, NODES_MASK << NODES_PGSHIFT);
2390 	return (mdf->f >> NODES_PGSHIFT) & NODES_MASK;
2391 }
2392 #else
memdesc_nid(const memdesc_flags_t * mdf)2393 static inline int memdesc_nid(const memdesc_flags_t *mdf)
2394 {
2395 	return 0;
2396 }
2397 #endif
2398 #endif
2399 
page_to_nid(const struct page * page)2400 static inline int page_to_nid(const struct page *page)
2401 {
2402 	return memdesc_nid(&(PF_POISONED_CHECK(page)->flags));
2403 }
2404 
folio_nid(const struct folio * folio)2405 static inline int folio_nid(const struct folio *folio)
2406 {
2407 	return memdesc_nid(&folio->flags);
2408 }
2409 
2410 #ifdef CONFIG_NUMA_BALANCING
2411 /* page access time bits needs to hold at least 4 seconds */
2412 #define PAGE_ACCESS_TIME_MIN_BITS	12
2413 #if LAST_CPUPID_SHIFT < PAGE_ACCESS_TIME_MIN_BITS
2414 #define PAGE_ACCESS_TIME_BUCKETS				\
2415 	(PAGE_ACCESS_TIME_MIN_BITS - LAST_CPUPID_SHIFT)
2416 #else
2417 #define PAGE_ACCESS_TIME_BUCKETS	0
2418 #endif
2419 
2420 #define PAGE_ACCESS_TIME_MASK				\
2421 	(LAST_CPUPID_MASK << PAGE_ACCESS_TIME_BUCKETS)
2422 
cpu_pid_to_cpupid(int cpu,int pid)2423 static inline int cpu_pid_to_cpupid(int cpu, int pid)
2424 {
2425 	return ((cpu & LAST__CPU_MASK) << LAST__PID_SHIFT) | (pid & LAST__PID_MASK);
2426 }
2427 
cpupid_to_pid(int cpupid)2428 static inline int cpupid_to_pid(int cpupid)
2429 {
2430 	return cpupid & LAST__PID_MASK;
2431 }
2432 
cpupid_to_cpu(int cpupid)2433 static inline int cpupid_to_cpu(int cpupid)
2434 {
2435 	return (cpupid >> LAST__PID_SHIFT) & LAST__CPU_MASK;
2436 }
2437 
cpupid_to_nid(int cpupid)2438 static inline int cpupid_to_nid(int cpupid)
2439 {
2440 	return cpu_to_node(cpupid_to_cpu(cpupid));
2441 }
2442 
cpupid_pid_unset(int cpupid)2443 static inline bool cpupid_pid_unset(int cpupid)
2444 {
2445 	return cpupid_to_pid(cpupid) == (-1 & LAST__PID_MASK);
2446 }
2447 
cpupid_cpu_unset(int cpupid)2448 static inline bool cpupid_cpu_unset(int cpupid)
2449 {
2450 	return cpupid_to_cpu(cpupid) == (-1 & LAST__CPU_MASK);
2451 }
2452 
__cpupid_match_pid(pid_t task_pid,int cpupid)2453 static inline bool __cpupid_match_pid(pid_t task_pid, int cpupid)
2454 {
2455 	return (task_pid & LAST__PID_MASK) == cpupid_to_pid(cpupid);
2456 }
2457 
2458 #define cpupid_match_pid(task, cpupid) __cpupid_match_pid(task->pid, cpupid)
2459 #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
folio_xchg_last_cpupid(struct folio * folio,int cpupid)2460 static inline int folio_xchg_last_cpupid(struct folio *folio, int cpupid)
2461 {
2462 	return xchg(&folio->_last_cpupid, cpupid & LAST_CPUPID_MASK);
2463 }
2464 
folio_last_cpupid(struct folio * folio)2465 static inline int folio_last_cpupid(struct folio *folio)
2466 {
2467 	return folio->_last_cpupid;
2468 }
page_cpupid_reset_last(struct page * page)2469 static inline void page_cpupid_reset_last(struct page *page)
2470 {
2471 	page->_last_cpupid = -1 & LAST_CPUPID_MASK;
2472 }
2473 #else
folio_last_cpupid(struct folio * folio)2474 static inline int folio_last_cpupid(struct folio *folio)
2475 {
2476 	return (folio->flags.f >> LAST_CPUPID_PGSHIFT) & LAST_CPUPID_MASK;
2477 }
2478 
2479 int folio_xchg_last_cpupid(struct folio *folio, int cpupid);
2480 
page_cpupid_reset_last(struct page * page)2481 static inline void page_cpupid_reset_last(struct page *page)
2482 {
2483 	page->flags.f |= LAST_CPUPID_MASK << LAST_CPUPID_PGSHIFT;
2484 }
2485 #endif /* LAST_CPUPID_NOT_IN_PAGE_FLAGS */
2486 
folio_xchg_access_time(struct folio * folio,int time)2487 static inline int folio_xchg_access_time(struct folio *folio, int time)
2488 {
2489 	int last_time;
2490 
2491 	last_time = folio_xchg_last_cpupid(folio,
2492 					   time >> PAGE_ACCESS_TIME_BUCKETS);
2493 	return last_time << PAGE_ACCESS_TIME_BUCKETS;
2494 }
2495 
vma_set_access_pid_bit(struct vm_area_struct * vma)2496 static inline void vma_set_access_pid_bit(struct vm_area_struct *vma)
2497 {
2498 	unsigned int pid_bit;
2499 
2500 	pid_bit = hash_32(current->pid, ilog2(BITS_PER_LONG));
2501 	if (vma->numab_state && !test_bit(pid_bit, &vma->numab_state->pids_active[1])) {
2502 		__set_bit(pid_bit, &vma->numab_state->pids_active[1]);
2503 	}
2504 }
2505 
2506 bool folio_use_access_time(struct folio *folio);
2507 #else /* !CONFIG_NUMA_BALANCING */
folio_xchg_last_cpupid(struct folio * folio,int cpupid)2508 static inline int folio_xchg_last_cpupid(struct folio *folio, int cpupid)
2509 {
2510 	return folio_nid(folio); /* XXX */
2511 }
2512 
folio_xchg_access_time(struct folio * folio,int time)2513 static inline int folio_xchg_access_time(struct folio *folio, int time)
2514 {
2515 	return 0;
2516 }
2517 
folio_last_cpupid(struct folio * folio)2518 static inline int folio_last_cpupid(struct folio *folio)
2519 {
2520 	return folio_nid(folio); /* XXX */
2521 }
2522 
cpupid_to_nid(int cpupid)2523 static inline int cpupid_to_nid(int cpupid)
2524 {
2525 	return -1;
2526 }
2527 
cpupid_to_pid(int cpupid)2528 static inline int cpupid_to_pid(int cpupid)
2529 {
2530 	return -1;
2531 }
2532 
cpupid_to_cpu(int cpupid)2533 static inline int cpupid_to_cpu(int cpupid)
2534 {
2535 	return -1;
2536 }
2537 
cpu_pid_to_cpupid(int nid,int pid)2538 static inline int cpu_pid_to_cpupid(int nid, int pid)
2539 {
2540 	return -1;
2541 }
2542 
cpupid_pid_unset(int cpupid)2543 static inline bool cpupid_pid_unset(int cpupid)
2544 {
2545 	return true;
2546 }
2547 
page_cpupid_reset_last(struct page * page)2548 static inline void page_cpupid_reset_last(struct page *page)
2549 {
2550 }
2551 
cpupid_match_pid(struct task_struct * task,int cpupid)2552 static inline bool cpupid_match_pid(struct task_struct *task, int cpupid)
2553 {
2554 	return false;
2555 }
2556 
vma_set_access_pid_bit(struct vm_area_struct * vma)2557 static inline void vma_set_access_pid_bit(struct vm_area_struct *vma)
2558 {
2559 }
folio_use_access_time(struct folio * folio)2560 static inline bool folio_use_access_time(struct folio *folio)
2561 {
2562 	return false;
2563 }
2564 #endif /* CONFIG_NUMA_BALANCING */
2565 
2566 #if defined(CONFIG_KASAN_SW_TAGS) || defined(CONFIG_KASAN_HW_TAGS)
2567 
2568 /*
2569  * KASAN per-page tags are stored xor'ed with 0xff. This allows to avoid
2570  * setting tags for all pages to native kernel tag value 0xff, as the default
2571  * value 0x00 maps to 0xff.
2572  */
2573 
page_kasan_tag(const struct page * page)2574 static inline u8 page_kasan_tag(const struct page *page)
2575 {
2576 	u8 tag = KASAN_TAG_KERNEL;
2577 
2578 	if (kasan_enabled()) {
2579 		tag = (page->flags.f >> KASAN_TAG_PGSHIFT) & KASAN_TAG_MASK;
2580 		tag ^= 0xff;
2581 	}
2582 
2583 	return tag;
2584 }
2585 
page_kasan_tag_set(struct page * page,u8 tag)2586 static inline void page_kasan_tag_set(struct page *page, u8 tag)
2587 {
2588 	unsigned long old_flags, flags;
2589 
2590 	if (!kasan_enabled())
2591 		return;
2592 
2593 	tag ^= 0xff;
2594 	old_flags = READ_ONCE(page->flags.f);
2595 	do {
2596 		flags = old_flags;
2597 		flags &= ~(KASAN_TAG_MASK << KASAN_TAG_PGSHIFT);
2598 		flags |= (tag & KASAN_TAG_MASK) << KASAN_TAG_PGSHIFT;
2599 	} while (unlikely(!try_cmpxchg(&page->flags.f, &old_flags, flags)));
2600 }
2601 
page_kasan_tag_reset(struct page * page)2602 static inline void page_kasan_tag_reset(struct page *page)
2603 {
2604 	if (kasan_enabled())
2605 		page_kasan_tag_set(page, KASAN_TAG_KERNEL);
2606 }
2607 
2608 #else /* CONFIG_KASAN_SW_TAGS || CONFIG_KASAN_HW_TAGS */
2609 
page_kasan_tag(const struct page * page)2610 static inline u8 page_kasan_tag(const struct page *page)
2611 {
2612 	return 0xff;
2613 }
2614 
page_kasan_tag_set(struct page * page,u8 tag)2615 static inline void page_kasan_tag_set(struct page *page, u8 tag) { }
page_kasan_tag_reset(struct page * page)2616 static inline void page_kasan_tag_reset(struct page *page) { }
2617 
2618 #endif /* CONFIG_KASAN_SW_TAGS || CONFIG_KASAN_HW_TAGS */
2619 
page_zone(const struct page * page)2620 static inline struct zone *page_zone(const struct page *page)
2621 {
2622 	return &NODE_DATA(page_to_nid(page))->node_zones[page_zonenum(page)];
2623 }
2624 
page_pgdat(const struct page * page)2625 static inline pg_data_t *page_pgdat(const struct page *page)
2626 {
2627 	return NODE_DATA(page_to_nid(page));
2628 }
2629 
folio_pgdat(const struct folio * folio)2630 static inline pg_data_t *folio_pgdat(const struct folio *folio)
2631 {
2632 	return NODE_DATA(folio_nid(folio));
2633 }
2634 
folio_zone(const struct folio * folio)2635 static inline struct zone *folio_zone(const struct folio *folio)
2636 {
2637 	return &folio_pgdat(folio)->node_zones[folio_zonenum(folio)];
2638 }
2639 
2640 #ifdef SECTION_IN_PAGE_FLAGS
set_page_section(struct page * page,unsigned long section)2641 static inline void set_page_section(struct page *page, unsigned long section)
2642 {
2643 	page->flags.f &= ~(SECTIONS_MASK << SECTIONS_PGSHIFT);
2644 	page->flags.f |= (section & SECTIONS_MASK) << SECTIONS_PGSHIFT;
2645 }
2646 
memdesc_section(const memdesc_flags_t * mdf)2647 static inline unsigned long memdesc_section(const memdesc_flags_t *mdf)
2648 {
2649 	ASSERT_EXCLUSIVE_BITS(mdf->f, SECTIONS_MASK << SECTIONS_PGSHIFT);
2650 	return (mdf->f >> SECTIONS_PGSHIFT) & SECTIONS_MASK;
2651 }
2652 #else /* !SECTION_IN_PAGE_FLAGS */
memdesc_section(const memdesc_flags_t * mdf)2653 static inline unsigned long memdesc_section(const memdesc_flags_t *mdf)
2654 {
2655 	return 0;
2656 }
2657 #endif /* SECTION_IN_PAGE_FLAGS */
2658 
2659 /**
2660  * folio_pfn - Return the Page Frame Number of a folio.
2661  * @folio: The folio.
2662  *
2663  * A folio may contain multiple pages.  The pages have consecutive
2664  * Page Frame Numbers.
2665  *
2666  * Return: The Page Frame Number of the first page in the folio.
2667  */
folio_pfn(const struct folio * folio)2668 static inline unsigned long folio_pfn(const struct folio *folio)
2669 {
2670 	return page_to_pfn(&folio->page);
2671 }
2672 
pfn_folio(unsigned long pfn)2673 static inline struct folio *pfn_folio(unsigned long pfn)
2674 {
2675 	return page_folio(pfn_to_page(pfn));
2676 }
2677 
2678 #ifdef CONFIG_MMU
mk_pte(const struct page * page,pgprot_t pgprot)2679 static inline pte_t mk_pte(const struct page *page, pgprot_t pgprot)
2680 {
2681 	return pfn_pte(page_to_pfn(page), pgprot);
2682 }
2683 
2684 /**
2685  * folio_mk_pte - Create a PTE for this folio
2686  * @folio: The folio to create a PTE for
2687  * @pgprot: The page protection bits to use
2688  *
2689  * Create a page table entry for the first page of this folio.
2690  * This is suitable for passing to set_ptes().
2691  *
2692  * Return: A page table entry suitable for mapping this folio.
2693  */
folio_mk_pte(const struct folio * folio,pgprot_t pgprot)2694 static inline pte_t folio_mk_pte(const struct folio *folio, pgprot_t pgprot)
2695 {
2696 	return pfn_pte(folio_pfn(folio), pgprot);
2697 }
2698 
2699 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
2700 /**
2701  * folio_mk_pmd - Create a PMD for this folio
2702  * @folio: The folio to create a PMD for
2703  * @pgprot: The page protection bits to use
2704  *
2705  * Create a page table entry for the first page of this folio.
2706  * This is suitable for passing to set_pmd_at().
2707  *
2708  * Return: A page table entry suitable for mapping this folio.
2709  */
folio_mk_pmd(const struct folio * folio,pgprot_t pgprot)2710 static inline pmd_t folio_mk_pmd(const struct folio *folio, pgprot_t pgprot)
2711 {
2712 	return pmd_mkhuge(pfn_pmd(folio_pfn(folio), pgprot));
2713 }
2714 
2715 #ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD
2716 /**
2717  * folio_mk_pud - Create a PUD for this folio
2718  * @folio: The folio to create a PUD for
2719  * @pgprot: The page protection bits to use
2720  *
2721  * Create a page table entry for the first page of this folio.
2722  * This is suitable for passing to set_pud_at().
2723  *
2724  * Return: A page table entry suitable for mapping this folio.
2725  */
folio_mk_pud(const struct folio * folio,pgprot_t pgprot)2726 static inline pud_t folio_mk_pud(const struct folio *folio, pgprot_t pgprot)
2727 {
2728 	return pud_mkhuge(pfn_pud(folio_pfn(folio), pgprot));
2729 }
2730 #endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
2731 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
2732 #endif /* CONFIG_MMU */
2733 
folio_has_pincount(const struct folio * folio)2734 static inline bool folio_has_pincount(const struct folio *folio)
2735 {
2736 	if (IS_ENABLED(CONFIG_64BIT))
2737 		return folio_test_large(folio);
2738 	return folio_order(folio) > 1;
2739 }
2740 
2741 /**
2742  * folio_maybe_dma_pinned - Report if a folio may be pinned for DMA.
2743  * @folio: The folio.
2744  *
2745  * This function checks if a folio has been pinned via a call to
2746  * a function in the pin_user_pages() family.
2747  *
2748  * For small folios, the return value is partially fuzzy: false is not fuzzy,
2749  * because it means "definitely not pinned for DMA", but true means "probably
2750  * pinned for DMA, but possibly a false positive due to having at least
2751  * GUP_PIN_COUNTING_BIAS worth of normal folio references".
2752  *
2753  * False positives are OK, because: a) it's unlikely for a folio to
2754  * get that many refcounts, and b) all the callers of this routine are
2755  * expected to be able to deal gracefully with a false positive.
2756  *
2757  * For most large folios, the result will be exactly correct. That's because
2758  * we have more tracking data available: the _pincount field is used
2759  * instead of the GUP_PIN_COUNTING_BIAS scheme.
2760  *
2761  * For more information, please see Documentation/core-api/pin_user_pages.rst.
2762  *
2763  * Return: True, if it is likely that the folio has been "dma-pinned".
2764  * False, if the folio is definitely not dma-pinned.
2765  */
folio_maybe_dma_pinned(struct folio * folio)2766 static inline bool folio_maybe_dma_pinned(struct folio *folio)
2767 {
2768 	if (folio_has_pincount(folio))
2769 		return atomic_read(&folio->_pincount) > 0;
2770 
2771 	/*
2772 	 * folio_ref_count() is signed. If that refcount overflows, then
2773 	 * folio_ref_count() returns a negative value, and callers will avoid
2774 	 * further incrementing the refcount.
2775 	 *
2776 	 * Here, for that overflow case, use the sign bit to count a little
2777 	 * bit higher via unsigned math, and thus still get an accurate result.
2778 	 */
2779 	return ((unsigned int)folio_ref_count(folio)) >=
2780 		GUP_PIN_COUNTING_BIAS;
2781 }
2782 
2783 /*
2784  * This should most likely only be called during fork() to see whether we
2785  * should break the cow immediately for an anon page on the src mm.
2786  *
2787  * The caller has to hold the PT lock and the vma->vm_mm->->write_protect_seq.
2788  */
folio_needs_cow_for_dma(struct vm_area_struct * vma,struct folio * folio)2789 static inline bool folio_needs_cow_for_dma(struct vm_area_struct *vma,
2790 					  struct folio *folio)
2791 {
2792 	VM_BUG_ON(!(raw_read_seqcount(&vma->vm_mm->write_protect_seq) & 1));
2793 
2794 	if (!mm_flags_test(MMF_HAS_PINNED, vma->vm_mm))
2795 		return false;
2796 
2797 	return folio_maybe_dma_pinned(folio);
2798 }
2799 
2800 /**
2801  * is_zero_page - Query if a page is a zero page
2802  * @page: The page to query
2803  *
2804  * This returns true if @page is one of the permanent zero pages.
2805  */
is_zero_page(const struct page * page)2806 static inline bool is_zero_page(const struct page *page)
2807 {
2808 	return is_zero_pfn(page_to_pfn(page));
2809 }
2810 
2811 /**
2812  * is_zero_folio - Query if a folio is a zero page
2813  * @folio: The folio to query
2814  *
2815  * This returns true if @folio is one of the permanent zero pages.
2816  */
is_zero_folio(const struct folio * folio)2817 static inline bool is_zero_folio(const struct folio *folio)
2818 {
2819 	return is_zero_page(&folio->page);
2820 }
2821 
2822 /* MIGRATE_CMA and ZONE_MOVABLE do not allow pin folios */
2823 #ifdef CONFIG_MIGRATION
folio_is_longterm_pinnable(struct folio * folio)2824 static inline bool folio_is_longterm_pinnable(struct folio *folio)
2825 {
2826 #ifdef CONFIG_CMA
2827 	int mt = folio_migratetype(folio);
2828 
2829 	if (mt == MIGRATE_CMA || mt == MIGRATE_ISOLATE)
2830 		return false;
2831 #endif
2832 	/* The zero page can be "pinned" but gets special handling. */
2833 	if (is_zero_folio(folio))
2834 		return true;
2835 
2836 	/* Coherent device memory must always allow eviction. */
2837 	if (folio_is_device_coherent(folio))
2838 		return false;
2839 
2840 	/*
2841 	 * Filesystems can only tolerate transient delays to truncate and
2842 	 * hole-punch operations
2843 	 */
2844 	if (folio_is_fsdax(folio))
2845 		return false;
2846 
2847 	/* Otherwise, non-movable zone folios can be pinned. */
2848 	return !folio_is_zone_movable(folio);
2849 
2850 }
2851 #else
folio_is_longterm_pinnable(struct folio * folio)2852 static inline bool folio_is_longterm_pinnable(struct folio *folio)
2853 {
2854 	return true;
2855 }
2856 #endif
2857 
set_page_zone(struct page * page,enum zone_type zone)2858 static inline void set_page_zone(struct page *page, enum zone_type zone)
2859 {
2860 	page->flags.f &= ~(ZONES_MASK << ZONES_PGSHIFT);
2861 	page->flags.f |= (zone & ZONES_MASK) << ZONES_PGSHIFT;
2862 }
2863 
set_page_node(struct page * page,unsigned long node)2864 static inline void set_page_node(struct page *page, unsigned long node)
2865 {
2866 	page->flags.f &= ~(NODES_MASK << NODES_PGSHIFT);
2867 	page->flags.f |= (node & NODES_MASK) << NODES_PGSHIFT;
2868 }
2869 
set_page_links(struct page * page,enum zone_type zone,unsigned long node,unsigned long pfn)2870 static inline void set_page_links(struct page *page, enum zone_type zone,
2871 	unsigned long node, unsigned long pfn)
2872 {
2873 	set_page_zone(page, zone);
2874 	set_page_node(page, node);
2875 #ifdef SECTION_IN_PAGE_FLAGS
2876 	set_page_section(page, pfn_to_section_nr(pfn));
2877 #endif
2878 }
2879 
2880 /**
2881  * folio_nr_pages - The number of pages in the folio.
2882  * @folio: The folio.
2883  *
2884  * Return: A positive power of two.
2885  */
folio_nr_pages(const struct folio * folio)2886 static inline unsigned long folio_nr_pages(const struct folio *folio)
2887 {
2888 	if (!folio_test_large(folio))
2889 		return 1;
2890 	return folio_large_nr_pages(folio);
2891 }
2892 
2893 /*
2894  * compound_nr() returns the number of pages in this potentially compound
2895  * page.  compound_nr() can be called on a tail page, and is defined to
2896  * return 1 in that case.
2897  */
compound_nr(const struct page * page)2898 static inline unsigned long compound_nr(const struct page *page)
2899 {
2900 	const struct folio *folio = (struct folio *)page;
2901 
2902 	if (!test_bit(PG_head, &folio->flags.f))
2903 		return 1;
2904 	return folio_large_nr_pages(folio);
2905 }
2906 
2907 /**
2908  * folio_next - Move to the next physical folio.
2909  * @folio: The folio we're currently operating on.
2910  *
2911  * If you have physically contiguous memory which may span more than
2912  * one folio (eg a &struct bio_vec), use this function to move from one
2913  * folio to the next.  Do not use it if the memory is only virtually
2914  * contiguous as the folios are almost certainly not adjacent to each
2915  * other.  This is the folio equivalent to writing ``page++``.
2916  *
2917  * Context: We assume that the folios are refcounted and/or locked at a
2918  * higher level and do not adjust the reference counts.
2919  * Return: The next struct folio.
2920  */
folio_next(struct folio * folio)2921 static inline struct folio *folio_next(struct folio *folio)
2922 {
2923 	return (struct folio *)folio_page(folio, folio_nr_pages(folio));
2924 }
2925 
2926 /**
2927  * folio_shift - The size of the memory described by this folio.
2928  * @folio: The folio.
2929  *
2930  * A folio represents a number of bytes which is a power-of-two in size.
2931  * This function tells you which power-of-two the folio is.  See also
2932  * folio_size() and folio_order().
2933  *
2934  * Context: The caller should have a reference on the folio to prevent
2935  * it from being split.  It is not necessary for the folio to be locked.
2936  * Return: The base-2 logarithm of the size of this folio.
2937  */
folio_shift(const struct folio * folio)2938 static inline unsigned int folio_shift(const struct folio *folio)
2939 {
2940 	return PAGE_SHIFT + folio_order(folio);
2941 }
2942 
2943 /**
2944  * folio_size - The number of bytes in a folio.
2945  * @folio: The folio.
2946  *
2947  * Context: The caller should have a reference on the folio to prevent
2948  * it from being split.  It is not necessary for the folio to be locked.
2949  * Return: The number of bytes in this folio.
2950  */
folio_size(const struct folio * folio)2951 static inline size_t folio_size(const struct folio *folio)
2952 {
2953 	return PAGE_SIZE << folio_order(folio);
2954 }
2955 
2956 /**
2957  * folio_maybe_mapped_shared - Whether the folio is mapped into the page
2958  *			       tables of more than one MM
2959  * @folio: The folio.
2960  *
2961  * This function checks if the folio maybe currently mapped into more than one
2962  * MM ("maybe mapped shared"), or if the folio is certainly mapped into a single
2963  * MM ("mapped exclusively").
2964  *
2965  * For KSM folios, this function also returns "mapped shared" when a folio is
2966  * mapped multiple times into the same MM, because the individual page mappings
2967  * are independent.
2968  *
2969  * For small anonymous folios and anonymous hugetlb folios, the return
2970  * value will be exactly correct: non-KSM folios can only be mapped at most once
2971  * into an MM, and they cannot be partially mapped. KSM folios are
2972  * considered shared even if mapped multiple times into the same MM.
2973  *
2974  * For other folios, the result can be fuzzy:
2975  *    #. For partially-mappable large folios (THP), the return value can wrongly
2976  *       indicate "mapped shared" (false positive) if a folio was mapped by
2977  *       more than two MMs at one point in time.
2978  *    #. For pagecache folios (including hugetlb), the return value can wrongly
2979  *       indicate "mapped shared" (false positive) when two VMAs in the same MM
2980  *       cover the same file range.
2981  *
2982  * Further, this function only considers current page table mappings that
2983  * are tracked using the folio mapcount(s).
2984  *
2985  * This function does not consider:
2986  *    #. If the folio might get mapped in the (near) future (e.g., swapcache,
2987  *       pagecache, temporary unmapping for migration).
2988  *    #. If the folio is mapped differently (VM_PFNMAP).
2989  *    #. If hugetlb page table sharing applies. Callers might want to check
2990  *       hugetlb_pmd_shared().
2991  *
2992  * Return: Whether the folio is estimated to be mapped into more than one MM.
2993  */
folio_maybe_mapped_shared(struct folio * folio)2994 static inline bool folio_maybe_mapped_shared(struct folio *folio)
2995 {
2996 	int mapcount = folio_mapcount(folio);
2997 
2998 	/* Only partially-mappable folios require more care. */
2999 	if (!folio_test_large(folio) || unlikely(folio_test_hugetlb(folio)))
3000 		return mapcount > 1;
3001 
3002 	/*
3003 	 * vm_insert_page() without CONFIG_TRANSPARENT_HUGEPAGE ...
3004 	 * simply assume "mapped shared", nobody should really care
3005 	 * about this for arbitrary kernel allocations.
3006 	 */
3007 	if (!IS_ENABLED(CONFIG_MM_ID))
3008 		return true;
3009 
3010 	/*
3011 	 * A single mapping implies "mapped exclusively", even if the
3012 	 * folio flag says something different: it's easier to handle this
3013 	 * case here instead of on the RMAP hot path.
3014 	 */
3015 	if (mapcount <= 1)
3016 		return false;
3017 	return test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids);
3018 }
3019 
3020 /**
3021  * folio_expected_ref_count - calculate the expected folio refcount
3022  * @folio: the folio
3023  *
3024  * Calculate the expected folio refcount, taking references from the pagecache,
3025  * swapcache, PG_private and page table mappings into account. Useful in
3026  * combination with folio_ref_count() to detect unexpected references (e.g.,
3027  * GUP or other temporary references).
3028  *
3029  * Does currently not consider references from the LRU cache. If the folio
3030  * was isolated from the LRU (which is the case during migration or split),
3031  * the LRU cache does not apply.
3032  *
3033  * Calling this function on an unmapped folio -- !folio_mapped() -- that is
3034  * locked will return a stable result.
3035  *
3036  * Calling this function on a mapped folio will not result in a stable result,
3037  * because nothing stops additional page table mappings from coming (e.g.,
3038  * fork()) or going (e.g., munmap()).
3039  *
3040  * Calling this function without the folio lock will also not result in a
3041  * stable result: for example, the folio might get dropped from the swapcache
3042  * concurrently.
3043  *
3044  * However, even when called without the folio lock or on a mapped folio,
3045  * this function can be used to detect unexpected references early (for example,
3046  * if it makes sense to even lock the folio and unmap it).
3047  *
3048  * The caller must add any reference (e.g., from folio_try_get()) it might be
3049  * holding itself to the result.
3050  *
3051  * Returns: the expected folio refcount.
3052  */
folio_expected_ref_count(const struct folio * folio)3053 static inline int folio_expected_ref_count(const struct folio *folio)
3054 {
3055 	const int order = folio_order(folio);
3056 	int ref_count = 0;
3057 
3058 	if (WARN_ON_ONCE(page_has_type(&folio->page) && !folio_test_hugetlb(folio)))
3059 		return 0;
3060 
3061 	/* One reference per page from the swapcache. */
3062 	ref_count += folio_test_swapcache(folio) << order;
3063 
3064 	if (!folio_test_anon(folio)) {
3065 		/* One reference per page from the pagecache. */
3066 		ref_count += !!folio->mapping << order;
3067 		/* One reference from PG_private. */
3068 		ref_count += folio_test_private(folio);
3069 	}
3070 
3071 	/* One reference per page table mapping. */
3072 	return ref_count + folio_mapcount(folio);
3073 }
3074 
3075 #ifndef HAVE_ARCH_MAKE_FOLIO_ACCESSIBLE
arch_make_folio_accessible(struct folio * folio)3076 static inline int arch_make_folio_accessible(struct folio *folio)
3077 {
3078 	return 0;
3079 }
3080 #endif
3081 
3082 /*
3083  * Some inline functions in vmstat.h depend on page_zone()
3084  */
3085 #include <linux/vmstat.h>
3086 
3087 #if defined(CONFIG_HIGHMEM) && !defined(WANT_PAGE_VIRTUAL)
3088 #define HASHED_PAGE_VIRTUAL
3089 #endif
3090 
3091 #if defined(WANT_PAGE_VIRTUAL)
page_address(const struct page * page)3092 static inline void *page_address(const struct page *page)
3093 {
3094 	return page->virtual;
3095 }
set_page_address(struct page * page,void * address)3096 static inline void set_page_address(struct page *page, void *address)
3097 {
3098 	page->virtual = address;
3099 }
3100 #define page_address_init()  do { } while(0)
3101 #endif
3102 
3103 #if defined(HASHED_PAGE_VIRTUAL)
3104 void *page_address(const struct page *page);
3105 void set_page_address(struct page *page, void *virtual);
3106 void page_address_init(void);
3107 #endif
3108 
lowmem_page_address(const struct page * page)3109 static __always_inline void *lowmem_page_address(const struct page *page)
3110 {
3111 	return page_to_virt(page);
3112 }
3113 
3114 #if !defined(HASHED_PAGE_VIRTUAL) && !defined(WANT_PAGE_VIRTUAL)
3115 #define page_address(page) lowmem_page_address(page)
3116 #define set_page_address(page, address)  do { } while(0)
3117 #define page_address_init()  do { } while(0)
3118 #endif
3119 
folio_address(const struct folio * folio)3120 static inline void *folio_address(const struct folio *folio)
3121 {
3122 	return page_address(&folio->page);
3123 }
3124 
3125 /*
3126  * Return true only if the page has been allocated with
3127  * ALLOC_NO_WATERMARKS and the low watermark was not
3128  * met implying that the system is under some pressure.
3129  */
page_is_pfmemalloc(const struct page * page)3130 static inline bool page_is_pfmemalloc(const struct page *page)
3131 {
3132 	/*
3133 	 * lru.next has bit 1 set if the page is allocated from the
3134 	 * pfmemalloc reserves.  Callers may simply overwrite it if
3135 	 * they do not need to preserve that information.
3136 	 */
3137 	return (uintptr_t)page->lru.next & BIT(1);
3138 }
3139 
3140 /*
3141  * Return true only if the folio has been allocated with
3142  * ALLOC_NO_WATERMARKS and the low watermark was not
3143  * met implying that the system is under some pressure.
3144  */
folio_is_pfmemalloc(const struct folio * folio)3145 static inline bool folio_is_pfmemalloc(const struct folio *folio)
3146 {
3147 	/*
3148 	 * lru.next has bit 1 set if the page is allocated from the
3149 	 * pfmemalloc reserves.  Callers may simply overwrite it if
3150 	 * they do not need to preserve that information.
3151 	 */
3152 	return (uintptr_t)folio->lru.next & BIT(1);
3153 }
3154 
3155 /*
3156  * Only to be called by the page allocator on a freshly allocated
3157  * page.
3158  */
set_page_pfmemalloc(struct page * page)3159 static inline void set_page_pfmemalloc(struct page *page)
3160 {
3161 	page->lru.next = (void *)BIT(1);
3162 }
3163 
clear_page_pfmemalloc(struct page * page)3164 static inline void clear_page_pfmemalloc(struct page *page)
3165 {
3166 	page->lru.next = NULL;
3167 }
3168 
3169 /*
3170  * Can be called by the pagefault handler when it gets a VM_FAULT_OOM.
3171  */
3172 extern void pagefault_out_of_memory(void);
3173 
3174 #define offset_in_page(p)	((unsigned long)(p) & ~PAGE_MASK)
3175 #define offset_in_folio(folio, p) ((unsigned long)(p) & (folio_size(folio) - 1))
3176 
3177 /*
3178  * Parameter block passed down to zap_pte_range in exceptional cases.
3179  */
3180 struct zap_details {
3181 	struct folio *single_folio;	/* Locked folio to be unmapped */
3182 	bool skip_cows;			/* Do not zap COWed private pages */
3183 	bool reclaim_pt;		/* Need reclaim page tables? */
3184 	bool reaping;			/* Reaping, do not block. */
3185 	zap_flags_t zap_flags;		/* Extra flags for zapping */
3186 };
3187 
3188 /*
3189  * Whether to drop the pte markers, for example, the uffd-wp information for
3190  * file-backed memory.  This should only be specified when we will completely
3191  * drop the page in the mm, either by truncation or unmapping of the vma.  By
3192  * default, the flag is not set.
3193  */
3194 #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
3195 /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
3196 #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
3197 
3198 #ifdef CONFIG_MMU
3199 extern bool can_do_mlock(void);
3200 #else
can_do_mlock(void)3201 static inline bool can_do_mlock(void) { return false; }
3202 #endif
3203 extern int user_shm_lock(size_t, struct ucounts *);
3204 extern void user_shm_unlock(size_t, struct ucounts *);
3205 
3206 struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr,
3207 			     pte_t pte);
3208 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
3209 			     pte_t pte);
3210 struct folio *vm_normal_folio_pmd(struct vm_area_struct *vma,
3211 				  unsigned long addr, pmd_t pmd);
3212 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
3213 				pmd_t pmd);
3214 struct page *vm_normal_page_pud(struct vm_area_struct *vma, unsigned long addr,
3215 		pud_t pud);
3216 
3217 void zap_special_vma_range(struct vm_area_struct *vma, unsigned long address,
3218 		  unsigned long size);
3219 void zap_vma_range(struct vm_area_struct *vma, unsigned long address,
3220 			   unsigned long size);
3221 /**
3222  * zap_vma - zap all page table entries in a vma
3223  * @vma: The vma to zap.
3224  */
zap_vma(struct vm_area_struct * vma)3225 static inline void zap_vma(struct vm_area_struct *vma)
3226 {
3227 	zap_vma_range(vma, vma->vm_start, vma->vm_end - vma->vm_start);
3228 }
3229 struct mmu_notifier_range;
3230 
3231 void free_pgd_range(struct mmu_gather *tlb, unsigned long addr,
3232 		unsigned long end, unsigned long floor, unsigned long ceiling);
3233 int
3234 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma);
3235 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
3236 			void *buf, int len, int write);
3237 
3238 struct follow_pfnmap_args {
3239 	/**
3240 	 * Inputs:
3241 	 * @vma: Pointer to @vm_area_struct struct
3242 	 * @address: the virtual address to walk
3243 	 */
3244 	struct vm_area_struct *vma;
3245 	unsigned long address;
3246 	/**
3247 	 * Internals:
3248 	 *
3249 	 * The caller shouldn't touch any of these.
3250 	 */
3251 	spinlock_t *lock;
3252 	pte_t *ptep;
3253 	/**
3254 	 * Outputs:
3255 	 *
3256 	 * @pfn: the PFN of the address
3257 	 * @addr_mask: address mask covering pfn
3258 	 * @pgprot: the pgprot_t of the mapping
3259 	 * @writable: whether the mapping is writable
3260 	 * @special: whether the mapping is a special mapping (real PFN maps)
3261 	 */
3262 	unsigned long pfn;
3263 	unsigned long addr_mask;
3264 	pgprot_t pgprot;
3265 	bool writable;
3266 	bool special;
3267 };
3268 int follow_pfnmap_start(struct follow_pfnmap_args *args);
3269 void follow_pfnmap_end(struct follow_pfnmap_args *args);
3270 
3271 extern void truncate_pagecache(struct inode *inode, loff_t new);
3272 extern void truncate_setsize(struct inode *inode, loff_t newsize);
3273 void pagecache_isize_extended(struct inode *inode, loff_t from, loff_t to);
3274 void truncate_pagecache_range(struct inode *inode, loff_t offset, loff_t end);
3275 int generic_error_remove_folio(struct address_space *mapping,
3276 		struct folio *folio);
3277 
3278 struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm,
3279 		unsigned long address, struct pt_regs *regs);
3280 
3281 #ifdef CONFIG_MMU
3282 extern vm_fault_t handle_mm_fault(struct vm_area_struct *vma,
3283 				  unsigned long address, unsigned int flags,
3284 				  struct pt_regs *regs);
3285 extern int fixup_user_fault(struct mm_struct *mm,
3286 			    unsigned long address, unsigned int fault_flags,
3287 			    bool *unlocked);
3288 void unmap_mapping_pages(struct address_space *mapping,
3289 		pgoff_t start, pgoff_t nr, bool even_cows);
3290 void unmap_mapping_range(struct address_space *mapping,
3291 		loff_t const holebegin, loff_t const holelen, int even_cows);
3292 #else
handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags,struct pt_regs * regs)3293 static inline vm_fault_t handle_mm_fault(struct vm_area_struct *vma,
3294 					 unsigned long address, unsigned int flags,
3295 					 struct pt_regs *regs)
3296 {
3297 	/* should never happen if there's no MMU */
3298 	BUG();
3299 	return VM_FAULT_SIGBUS;
3300 }
fixup_user_fault(struct mm_struct * mm,unsigned long address,unsigned int fault_flags,bool * unlocked)3301 static inline int fixup_user_fault(struct mm_struct *mm, unsigned long address,
3302 		unsigned int fault_flags, bool *unlocked)
3303 {
3304 	/* should never happen if there's no MMU */
3305 	BUG();
3306 	return -EFAULT;
3307 }
unmap_mapping_pages(struct address_space * mapping,pgoff_t start,pgoff_t nr,bool even_cows)3308 static inline void unmap_mapping_pages(struct address_space *mapping,
3309 		pgoff_t start, pgoff_t nr, bool even_cows) { }
unmap_mapping_range(struct address_space * mapping,loff_t const holebegin,loff_t const holelen,int even_cows)3310 static inline void unmap_mapping_range(struct address_space *mapping,
3311 		loff_t const holebegin, loff_t const holelen, int even_cows) { }
3312 #endif
3313 
unmap_shared_mapping_range(struct address_space * mapping,loff_t const holebegin,loff_t const holelen)3314 static inline void unmap_shared_mapping_range(struct address_space *mapping,
3315 		loff_t const holebegin, loff_t const holelen)
3316 {
3317 	unmap_mapping_range(mapping, holebegin, holelen, 0);
3318 }
3319 
3320 static inline struct vm_area_struct *vma_lookup(struct mm_struct *mm,
3321 						unsigned long addr);
3322 
3323 extern int access_process_vm(struct task_struct *tsk, unsigned long addr,
3324 		void *buf, int len, unsigned int gup_flags);
3325 extern int access_remote_vm(struct mm_struct *mm, unsigned long addr,
3326 		void *buf, int len, unsigned int gup_flags);
3327 
3328 #ifdef CONFIG_BPF_SYSCALL
3329 extern int copy_remote_vm_str(struct task_struct *tsk, unsigned long addr,
3330 			      void *buf, int len, unsigned int gup_flags);
3331 #endif
3332 
3333 long get_user_pages_remote(struct mm_struct *mm,
3334 			   unsigned long start, unsigned long nr_pages,
3335 			   unsigned int gup_flags, struct page **pages,
3336 			   int *locked);
3337 long pin_user_pages_remote(struct mm_struct *mm,
3338 			   unsigned long start, unsigned long nr_pages,
3339 			   unsigned int gup_flags, struct page **pages,
3340 			   int *locked);
3341 
3342 /*
3343  * Retrieves a single page alongside its VMA. Does not support FOLL_NOWAIT.
3344  */
get_user_page_vma_remote(struct mm_struct * mm,unsigned long addr,int gup_flags,struct vm_area_struct ** vmap)3345 static inline struct page *get_user_page_vma_remote(struct mm_struct *mm,
3346 						    unsigned long addr,
3347 						    int gup_flags,
3348 						    struct vm_area_struct **vmap)
3349 {
3350 	struct page *page;
3351 	struct vm_area_struct *vma;
3352 	int got;
3353 
3354 	if (WARN_ON_ONCE(unlikely(gup_flags & FOLL_NOWAIT)))
3355 		return ERR_PTR(-EINVAL);
3356 
3357 	got = get_user_pages_remote(mm, addr, 1, gup_flags, &page, NULL);
3358 
3359 	if (got < 0)
3360 		return ERR_PTR(got);
3361 
3362 	vma = vma_lookup(mm, addr);
3363 	if (WARN_ON_ONCE(!vma)) {
3364 		put_page(page);
3365 		return ERR_PTR(-EINVAL);
3366 	}
3367 
3368 	*vmap = vma;
3369 	return page;
3370 }
3371 
3372 long get_user_pages(unsigned long start, unsigned long nr_pages,
3373 		    unsigned int gup_flags, struct page **pages);
3374 long pin_user_pages(unsigned long start, unsigned long nr_pages,
3375 		    unsigned int gup_flags, struct page **pages);
3376 long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3377 		    struct page **pages, unsigned int gup_flags);
3378 long pin_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
3379 		    struct page **pages, unsigned int gup_flags);
3380 long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
3381 		      struct folio **folios, unsigned int max_folios,
3382 		      pgoff_t *offset);
3383 int folio_add_pins(struct folio *folio, unsigned int pins);
3384 
3385 int get_user_pages_fast(unsigned long start, int nr_pages,
3386 			unsigned int gup_flags, struct page **pages);
3387 int pin_user_pages_fast(unsigned long start, int nr_pages,
3388 			unsigned int gup_flags, struct page **pages);
3389 void folio_add_pin(struct folio *folio);
3390 
3391 int account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc);
3392 int __account_locked_vm(struct mm_struct *mm, unsigned long pages, bool inc,
3393 			const struct task_struct *task, bool bypass_rlim);
3394 
3395 struct kvec;
3396 struct page *get_dump_page(unsigned long addr, int *locked);
3397 
3398 bool folio_mark_dirty(struct folio *folio);
3399 bool folio_mark_dirty_lock(struct folio *folio);
3400 bool set_page_dirty(struct page *page);
3401 int set_page_dirty_lock(struct page *page);
3402 
3403 int get_cmdline(struct task_struct *task, char *buffer, int buflen);
3404 
3405 /*
3406  * Flags used by change_protection().  For now we make it a bitmap so
3407  * that we can pass in multiple flags just like parameters.  However
3408  * for now all the callers are only use one of the flags at the same
3409  * time.
3410  */
3411 /*
3412  * Whether we should manually check if we can map individual PTEs writable,
3413  * because something (e.g., COW, uffd-wp) blocks that from happening for all
3414  * PTEs automatically in a writable mapping.
3415  */
3416 #define  MM_CP_TRY_CHANGE_WRITABLE	   (1UL << 0)
3417 /* Whether this protection change is for NUMA hints */
3418 #define  MM_CP_PROT_NUMA                   (1UL << 1)
3419 /* Whether this change is for write protecting */
3420 #define  MM_CP_UFFD_WP                     (1UL << 2) /* do wp */
3421 #define  MM_CP_UFFD_WP_RESOLVE             (1UL << 3) /* Resolve wp */
3422 #define  MM_CP_UFFD_WP_ALL                 (MM_CP_UFFD_WP | \
3423 					    MM_CP_UFFD_WP_RESOLVE)
3424 /* Whether this change is for uffd RWP */
3425 #define  MM_CP_UFFD_RWP                    (1UL << 4) /* do rwp */
3426 #define  MM_CP_UFFD_RWP_RESOLVE            (1UL << 5) /* resolve rwp */
3427 #define  MM_CP_UFFD_RWP_ALL                (MM_CP_UFFD_RWP | \
3428 					    MM_CP_UFFD_RWP_RESOLVE)
3429 
3430 bool can_change_pte_writable(struct vm_area_struct *vma, unsigned long addr,
3431 			     pte_t pte);
3432 extern long change_protection(struct mmu_gather *tlb,
3433 			      struct vm_area_struct *vma, unsigned long start,
3434 			      unsigned long end, unsigned long cp_flags);
3435 extern int mprotect_fixup(struct vma_iterator *vmi, struct mmu_gather *tlb,
3436 	  struct vm_area_struct *vma, struct vm_area_struct **pprev,
3437 	  unsigned long start, unsigned long end, vm_flags_t newflags);
3438 
3439 /*
3440  * doesn't attempt to fault and will return short.
3441  */
3442 int get_user_pages_fast_only(unsigned long start, int nr_pages,
3443 			     unsigned int gup_flags, struct page **pages);
3444 
get_user_page_fast_only(unsigned long addr,unsigned int gup_flags,struct page ** pagep)3445 static inline bool get_user_page_fast_only(unsigned long addr,
3446 			unsigned int gup_flags, struct page **pagep)
3447 {
3448 	return get_user_pages_fast_only(addr, 1, gup_flags, pagep) == 1;
3449 }
3450 /*
3451  * per-process(per-mm_struct) statistics.
3452  */
get_mm_counter(struct mm_struct * mm,int member)3453 static inline unsigned long get_mm_counter(struct mm_struct *mm, int member)
3454 {
3455 	return percpu_counter_read_positive(&mm->rss_stat[member]);
3456 }
3457 
get_mm_counter_sum(struct mm_struct * mm,int member)3458 static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)
3459 {
3460 	return percpu_counter_sum_positive(&mm->rss_stat[member]);
3461 }
3462 
3463 void mm_trace_rss_stat(struct mm_struct *mm, int member);
3464 
add_mm_counter(struct mm_struct * mm,int member,long value)3465 static inline void add_mm_counter(struct mm_struct *mm, int member, long value)
3466 {
3467 	percpu_counter_add(&mm->rss_stat[member], value);
3468 
3469 	mm_trace_rss_stat(mm, member);
3470 }
3471 
inc_mm_counter(struct mm_struct * mm,int member)3472 static inline void inc_mm_counter(struct mm_struct *mm, int member)
3473 {
3474 	percpu_counter_inc(&mm->rss_stat[member]);
3475 
3476 	mm_trace_rss_stat(mm, member);
3477 }
3478 
dec_mm_counter(struct mm_struct * mm,int member)3479 static inline void dec_mm_counter(struct mm_struct *mm, int member)
3480 {
3481 	percpu_counter_dec(&mm->rss_stat[member]);
3482 
3483 	mm_trace_rss_stat(mm, member);
3484 }
3485 
3486 /* Optimized variant when folio is already known not to be anon */
mm_counter_file(struct folio * folio)3487 static inline int mm_counter_file(struct folio *folio)
3488 {
3489 	if (folio_test_swapbacked(folio))
3490 		return MM_SHMEMPAGES;
3491 	return MM_FILEPAGES;
3492 }
3493 
mm_counter(struct folio * folio)3494 static inline int mm_counter(struct folio *folio)
3495 {
3496 	if (folio_test_anon(folio))
3497 		return MM_ANONPAGES;
3498 	return mm_counter_file(folio);
3499 }
3500 
get_mm_rss(struct mm_struct * mm)3501 static inline unsigned long get_mm_rss(struct mm_struct *mm)
3502 {
3503 	return get_mm_counter(mm, MM_FILEPAGES) +
3504 		get_mm_counter(mm, MM_ANONPAGES) +
3505 		get_mm_counter(mm, MM_SHMEMPAGES);
3506 }
3507 
get_mm_rss_sum(struct mm_struct * mm)3508 static inline unsigned long get_mm_rss_sum(struct mm_struct *mm)
3509 {
3510 	return get_mm_counter_sum(mm, MM_FILEPAGES) +
3511 		get_mm_counter_sum(mm, MM_ANONPAGES) +
3512 		get_mm_counter_sum(mm, MM_SHMEMPAGES);
3513 }
3514 
get_mm_hiwater_rss(struct mm_struct * mm)3515 static inline unsigned long get_mm_hiwater_rss(struct mm_struct *mm)
3516 {
3517 	return max(mm->hiwater_rss, get_mm_rss(mm));
3518 }
3519 
get_mm_hiwater_vm(struct mm_struct * mm)3520 static inline unsigned long get_mm_hiwater_vm(struct mm_struct *mm)
3521 {
3522 	return max(mm->hiwater_vm, mm->total_vm);
3523 }
3524 
update_hiwater_rss(struct mm_struct * mm)3525 static inline void update_hiwater_rss(struct mm_struct *mm)
3526 {
3527 	unsigned long _rss = get_mm_rss(mm);
3528 
3529 	if (data_race(mm->hiwater_rss) < _rss)
3530 		data_race(mm->hiwater_rss = _rss);
3531 }
3532 
update_hiwater_vm(struct mm_struct * mm)3533 static inline void update_hiwater_vm(struct mm_struct *mm)
3534 {
3535 	if (mm->hiwater_vm < mm->total_vm)
3536 		mm->hiwater_vm = mm->total_vm;
3537 }
3538 
reset_mm_hiwater_rss(struct mm_struct * mm)3539 static inline void reset_mm_hiwater_rss(struct mm_struct *mm)
3540 {
3541 	mm->hiwater_rss = get_mm_rss(mm);
3542 }
3543 
setmax_mm_hiwater_rss(unsigned long * maxrss,struct mm_struct * mm)3544 static inline void setmax_mm_hiwater_rss(unsigned long *maxrss,
3545 					 struct mm_struct *mm)
3546 {
3547 	unsigned long hiwater_rss = get_mm_hiwater_rss(mm);
3548 
3549 	if (*maxrss < hiwater_rss)
3550 		*maxrss = hiwater_rss;
3551 }
3552 
3553 #ifndef CONFIG_ARCH_HAS_PTE_SPECIAL
pte_special(pte_t pte)3554 static inline int pte_special(pte_t pte)
3555 {
3556 	return 0;
3557 }
3558 
pte_mkspecial(pte_t pte)3559 static inline pte_t pte_mkspecial(pte_t pte)
3560 {
3561 	return pte;
3562 }
3563 #endif
3564 
3565 #ifndef CONFIG_ARCH_SUPPORTS_PMD_PFNMAP
pmd_special(pmd_t pmd)3566 static inline bool pmd_special(pmd_t pmd)
3567 {
3568 	return false;
3569 }
3570 
pmd_mkspecial(pmd_t pmd)3571 static inline pmd_t pmd_mkspecial(pmd_t pmd)
3572 {
3573 	return pmd;
3574 }
3575 #endif	/* CONFIG_ARCH_SUPPORTS_PMD_PFNMAP */
3576 
3577 #ifndef CONFIG_ARCH_SUPPORTS_PUD_PFNMAP
pud_special(pud_t pud)3578 static inline bool pud_special(pud_t pud)
3579 {
3580 	return false;
3581 }
3582 
pud_mkspecial(pud_t pud)3583 static inline pud_t pud_mkspecial(pud_t pud)
3584 {
3585 	return pud;
3586 }
3587 #endif	/* CONFIG_ARCH_SUPPORTS_PUD_PFNMAP */
3588 
3589 extern pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr,
3590 			     spinlock_t **ptl);
3591 
3592 #ifdef __PAGETABLE_P4D_FOLDED
__p4d_alloc(struct mm_struct * mm,pgd_t * pgd,unsigned long address)3593 static inline int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd,
3594 						unsigned long address)
3595 {
3596 	return 0;
3597 }
3598 #else
3599 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address);
3600 #endif
3601 
3602 #if defined(__PAGETABLE_PUD_FOLDED) || !defined(CONFIG_MMU)
__pud_alloc(struct mm_struct * mm,p4d_t * p4d,unsigned long address)3603 static inline int __pud_alloc(struct mm_struct *mm, p4d_t *p4d,
3604 						unsigned long address)
3605 {
3606 	return 0;
3607 }
mm_inc_nr_puds(struct mm_struct * mm)3608 static inline void mm_inc_nr_puds(struct mm_struct *mm) {}
mm_dec_nr_puds(struct mm_struct * mm)3609 static inline void mm_dec_nr_puds(struct mm_struct *mm) {}
3610 
3611 #else
3612 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address);
3613 
mm_inc_nr_puds(struct mm_struct * mm)3614 static inline void mm_inc_nr_puds(struct mm_struct *mm)
3615 {
3616 	if (mm_pud_folded(mm))
3617 		return;
3618 	atomic_long_add(PTRS_PER_PUD * sizeof(pud_t), &mm->pgtables_bytes);
3619 }
3620 
mm_dec_nr_puds(struct mm_struct * mm)3621 static inline void mm_dec_nr_puds(struct mm_struct *mm)
3622 {
3623 	if (mm_pud_folded(mm))
3624 		return;
3625 	atomic_long_sub(PTRS_PER_PUD * sizeof(pud_t), &mm->pgtables_bytes);
3626 }
3627 #endif
3628 
3629 #if defined(__PAGETABLE_PMD_FOLDED) || !defined(CONFIG_MMU)
__pmd_alloc(struct mm_struct * mm,pud_t * pud,unsigned long address)3630 static inline int __pmd_alloc(struct mm_struct *mm, pud_t *pud,
3631 						unsigned long address)
3632 {
3633 	return 0;
3634 }
3635 
mm_inc_nr_pmds(struct mm_struct * mm)3636 static inline void mm_inc_nr_pmds(struct mm_struct *mm) {}
mm_dec_nr_pmds(struct mm_struct * mm)3637 static inline void mm_dec_nr_pmds(struct mm_struct *mm) {}
3638 
3639 #else
3640 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address);
3641 
mm_inc_nr_pmds(struct mm_struct * mm)3642 static inline void mm_inc_nr_pmds(struct mm_struct *mm)
3643 {
3644 	if (mm_pmd_folded(mm))
3645 		return;
3646 	atomic_long_add(PTRS_PER_PMD * sizeof(pmd_t), &mm->pgtables_bytes);
3647 }
3648 
mm_dec_nr_pmds(struct mm_struct * mm)3649 static inline void mm_dec_nr_pmds(struct mm_struct *mm)
3650 {
3651 	if (mm_pmd_folded(mm))
3652 		return;
3653 	atomic_long_sub(PTRS_PER_PMD * sizeof(pmd_t), &mm->pgtables_bytes);
3654 }
3655 #endif
3656 
3657 #ifdef CONFIG_MMU
mm_pgtables_bytes_init(struct mm_struct * mm)3658 static inline void mm_pgtables_bytes_init(struct mm_struct *mm)
3659 {
3660 	atomic_long_set(&mm->pgtables_bytes, 0);
3661 }
3662 
mm_pgtables_bytes(const struct mm_struct * mm)3663 static inline unsigned long mm_pgtables_bytes(const struct mm_struct *mm)
3664 {
3665 	return atomic_long_read(&mm->pgtables_bytes);
3666 }
3667 
mm_inc_nr_ptes(struct mm_struct * mm)3668 static inline void mm_inc_nr_ptes(struct mm_struct *mm)
3669 {
3670 	atomic_long_add(PTRS_PER_PTE * sizeof(pte_t), &mm->pgtables_bytes);
3671 }
3672 
mm_dec_nr_ptes(struct mm_struct * mm)3673 static inline void mm_dec_nr_ptes(struct mm_struct *mm)
3674 {
3675 	atomic_long_sub(PTRS_PER_PTE * sizeof(pte_t), &mm->pgtables_bytes);
3676 }
3677 #else
3678 
mm_pgtables_bytes_init(struct mm_struct * mm)3679 static inline void mm_pgtables_bytes_init(struct mm_struct *mm) {}
mm_pgtables_bytes(const struct mm_struct * mm)3680 static inline unsigned long mm_pgtables_bytes(const struct mm_struct *mm)
3681 {
3682 	return 0;
3683 }
3684 
mm_inc_nr_ptes(struct mm_struct * mm)3685 static inline void mm_inc_nr_ptes(struct mm_struct *mm) {}
mm_dec_nr_ptes(struct mm_struct * mm)3686 static inline void mm_dec_nr_ptes(struct mm_struct *mm) {}
3687 #endif
3688 
3689 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd);
3690 int __pte_alloc_kernel(pmd_t *pmd);
3691 
3692 #if defined(CONFIG_MMU)
3693 
p4d_alloc(struct mm_struct * mm,pgd_t * pgd,unsigned long address)3694 static inline p4d_t *p4d_alloc(struct mm_struct *mm, pgd_t *pgd,
3695 		unsigned long address)
3696 {
3697 	return (unlikely(pgd_none(*pgd)) && __p4d_alloc(mm, pgd, address)) ?
3698 		NULL : p4d_offset(pgd, address);
3699 }
3700 
pud_alloc(struct mm_struct * mm,p4d_t * p4d,unsigned long address)3701 static inline pud_t *pud_alloc(struct mm_struct *mm, p4d_t *p4d,
3702 		unsigned long address)
3703 {
3704 	return (unlikely(p4d_none(*p4d)) && __pud_alloc(mm, p4d, address)) ?
3705 		NULL : pud_offset(p4d, address);
3706 }
3707 
pmd_alloc(struct mm_struct * mm,pud_t * pud,unsigned long address)3708 static inline pmd_t *pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3709 {
3710 	return (unlikely(pud_none(*pud)) && __pmd_alloc(mm, pud, address))?
3711 		NULL: pmd_offset(pud, address);
3712 }
3713 #endif /* CONFIG_MMU */
3714 
3715 enum pt_flags {
3716 	PT_kernel = PG_referenced,
3717 	PT_reserved = PG_reserved,
3718 	/* High bits are used for zone/node/section */
3719 };
3720 
virt_to_ptdesc(const void * x)3721 static inline struct ptdesc *virt_to_ptdesc(const void *x)
3722 {
3723 	return page_ptdesc(virt_to_page(x));
3724 }
3725 
3726 /**
3727  * ptdesc_address - Virtual address of page table.
3728  * @pt: Page table descriptor.
3729  *
3730  * Return: The first byte of the page table described by @pt.
3731  */
ptdesc_address(const struct ptdesc * pt)3732 static inline void *ptdesc_address(const struct ptdesc *pt)
3733 {
3734 	return folio_address(ptdesc_folio(pt));
3735 }
3736 
pagetable_is_reserved(struct ptdesc * pt)3737 static inline bool pagetable_is_reserved(struct ptdesc *pt)
3738 {
3739 	return test_bit(PT_reserved, &pt->pt_flags.f);
3740 }
3741 
3742 /**
3743  * ptdesc_set_kernel - Mark a ptdesc used to map the kernel
3744  * @ptdesc: The ptdesc to be marked
3745  *
3746  * Kernel page tables often need special handling. Set a flag so that
3747  * the handling code knows this ptdesc will not be used for userspace.
3748  */
ptdesc_set_kernel(struct ptdesc * ptdesc)3749 static inline void ptdesc_set_kernel(struct ptdesc *ptdesc)
3750 {
3751 	set_bit(PT_kernel, &ptdesc->pt_flags.f);
3752 }
3753 
3754 /**
3755  * ptdesc_clear_kernel - Mark a ptdesc as no longer used to map the kernel
3756  * @ptdesc: The ptdesc to be unmarked
3757  *
3758  * Use when the ptdesc is no longer used to map the kernel and no longer
3759  * needs special handling.
3760  */
ptdesc_clear_kernel(struct ptdesc * ptdesc)3761 static inline void ptdesc_clear_kernel(struct ptdesc *ptdesc)
3762 {
3763 	/*
3764 	 * Note: the 'PG_referenced' bit does not strictly need to be
3765 	 * cleared before freeing the page. But this is nice for
3766 	 * symmetry.
3767 	 */
3768 	clear_bit(PT_kernel, &ptdesc->pt_flags.f);
3769 }
3770 
3771 /**
3772  * ptdesc_test_kernel - Check if a ptdesc is used to map the kernel
3773  * @ptdesc: The ptdesc being tested
3774  *
3775  * Call to tell if the ptdesc used to map the kernel.
3776  */
ptdesc_test_kernel(const struct ptdesc * ptdesc)3777 static inline bool ptdesc_test_kernel(const struct ptdesc *ptdesc)
3778 {
3779 	return test_bit(PT_kernel, &ptdesc->pt_flags.f);
3780 }
3781 
3782 /**
3783  * pagetable_alloc - Allocate pagetables
3784  * @gfp:    GFP flags
3785  * @order:  desired pagetable order
3786  *
3787  * pagetable_alloc allocates memory for page tables as well as a page table
3788  * descriptor to describe that memory.
3789  *
3790  * Return: The ptdesc describing the allocated page tables.
3791  */
pagetable_alloc_noprof(gfp_t gfp,unsigned int order)3792 static inline struct ptdesc *pagetable_alloc_noprof(gfp_t gfp, unsigned int order)
3793 {
3794 	struct page *page = alloc_pages_noprof(gfp | __GFP_COMP, order);
3795 
3796 	return page_ptdesc(page);
3797 }
3798 #define pagetable_alloc(...)	alloc_hooks(pagetable_alloc_noprof(__VA_ARGS__))
3799 
__pagetable_free(struct ptdesc * pt)3800 static inline void __pagetable_free(struct ptdesc *pt)
3801 {
3802 	struct page *page = ptdesc_page(pt);
3803 
3804 	__free_pages(page, compound_order(page));
3805 }
3806 
3807 #ifdef CONFIG_ASYNC_KERNEL_PGTABLE_FREE
3808 void pagetable_free_kernel(struct ptdesc *pt);
3809 #else
pagetable_free_kernel(struct ptdesc * pt)3810 static inline void pagetable_free_kernel(struct ptdesc *pt)
3811 {
3812 	__pagetable_free(pt);
3813 }
3814 #endif
3815 /**
3816  * pagetable_free - Free pagetables
3817  * @pt:	The page table descriptor
3818  *
3819  * pagetable_free frees the memory of all page tables described by a page
3820  * table descriptor and the memory for the descriptor itself.
3821  */
pagetable_free(struct ptdesc * pt)3822 static inline void pagetable_free(struct ptdesc *pt)
3823 {
3824 	if (ptdesc_test_kernel(pt)) {
3825 		ptdesc_clear_kernel(pt);
3826 		pagetable_free_kernel(pt);
3827 	} else {
3828 		__pagetable_free(pt);
3829 	}
3830 }
3831 
3832 #if defined(CONFIG_SPLIT_PTE_PTLOCKS)
3833 #if ALLOC_SPLIT_PTLOCKS
3834 void __init ptlock_cache_init(void);
3835 bool ptlock_alloc(struct ptdesc *ptdesc);
3836 void ptlock_free(struct ptdesc *ptdesc);
3837 
ptlock_ptr(struct ptdesc * ptdesc)3838 static inline spinlock_t *ptlock_ptr(struct ptdesc *ptdesc)
3839 {
3840 	return ptdesc->ptl;
3841 }
3842 #else /* ALLOC_SPLIT_PTLOCKS */
ptlock_cache_init(void)3843 static inline void ptlock_cache_init(void)
3844 {
3845 }
3846 
ptlock_alloc(struct ptdesc * ptdesc)3847 static inline bool ptlock_alloc(struct ptdesc *ptdesc)
3848 {
3849 	return true;
3850 }
3851 
ptlock_free(struct ptdesc * ptdesc)3852 static inline void ptlock_free(struct ptdesc *ptdesc)
3853 {
3854 }
3855 
ptlock_ptr(struct ptdesc * ptdesc)3856 static inline spinlock_t *ptlock_ptr(struct ptdesc *ptdesc)
3857 {
3858 	return &ptdesc->ptl;
3859 }
3860 #endif /* ALLOC_SPLIT_PTLOCKS */
3861 
pte_lockptr(struct mm_struct * mm,pmd_t * pmd)3862 static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmd)
3863 {
3864 	return ptlock_ptr(page_ptdesc(pmd_page(*pmd)));
3865 }
3866 
ptep_lockptr(struct mm_struct * mm,pte_t * pte)3867 static inline spinlock_t *ptep_lockptr(struct mm_struct *mm, pte_t *pte)
3868 {
3869 	BUILD_BUG_ON(IS_ENABLED(CONFIG_HIGHPTE));
3870 	BUILD_BUG_ON(MAX_PTRS_PER_PTE * sizeof(pte_t) > PAGE_SIZE);
3871 	return ptlock_ptr(virt_to_ptdesc(pte));
3872 }
3873 
ptlock_init(struct ptdesc * ptdesc)3874 static inline bool ptlock_init(struct ptdesc *ptdesc)
3875 {
3876 	/*
3877 	 * prep_new_page() initialize page->private (and therefore page->ptl)
3878 	 * with 0. Make sure nobody took it in use in between.
3879 	 *
3880 	 * It can happen if arch try to use slab for page table allocation:
3881 	 * slab code uses page->slab_cache, which share storage with page->ptl.
3882 	 */
3883 	VM_BUG_ON_PAGE(*(unsigned long *)&ptdesc->ptl, ptdesc_page(ptdesc));
3884 	if (!ptlock_alloc(ptdesc))
3885 		return false;
3886 	spin_lock_init(ptlock_ptr(ptdesc));
3887 	return true;
3888 }
3889 
3890 #else	/* !defined(CONFIG_SPLIT_PTE_PTLOCKS) */
3891 /*
3892  * We use mm->page_table_lock to guard all pagetable pages of the mm.
3893  */
pte_lockptr(struct mm_struct * mm,pmd_t * pmd)3894 static inline spinlock_t *pte_lockptr(struct mm_struct *mm, pmd_t *pmd)
3895 {
3896 	return &mm->page_table_lock;
3897 }
ptep_lockptr(struct mm_struct * mm,pte_t * pte)3898 static inline spinlock_t *ptep_lockptr(struct mm_struct *mm, pte_t *pte)
3899 {
3900 	return &mm->page_table_lock;
3901 }
ptlock_cache_init(void)3902 static inline void ptlock_cache_init(void) {}
ptlock_init(struct ptdesc * ptdesc)3903 static inline bool ptlock_init(struct ptdesc *ptdesc) { return true; }
ptlock_free(struct ptdesc * ptdesc)3904 static inline void ptlock_free(struct ptdesc *ptdesc) {}
3905 #endif /* defined(CONFIG_SPLIT_PTE_PTLOCKS) */
3906 
__pagetable_ctor(struct ptdesc * ptdesc)3907 static inline void __pagetable_ctor(struct ptdesc *ptdesc)
3908 {
3909 	struct folio *folio = ptdesc_folio(ptdesc);
3910 
3911 	__folio_set_pgtable(folio);
3912 	lruvec_stat_add_folio(folio, NR_PAGETABLE);
3913 }
3914 
pagetable_dtor(struct ptdesc * ptdesc)3915 static inline void pagetable_dtor(struct ptdesc *ptdesc)
3916 {
3917 	struct folio *folio = ptdesc_folio(ptdesc);
3918 
3919 	ptlock_free(ptdesc);
3920 	__folio_clear_pgtable(folio);
3921 	lruvec_stat_sub_folio(folio, NR_PAGETABLE);
3922 }
3923 
pagetable_dtor_free(struct ptdesc * ptdesc)3924 static inline void pagetable_dtor_free(struct ptdesc *ptdesc)
3925 {
3926 	pagetable_dtor(ptdesc);
3927 	pagetable_free(ptdesc);
3928 }
3929 
pagetable_pte_ctor(struct mm_struct * mm,struct ptdesc * ptdesc)3930 static inline bool pagetable_pte_ctor(struct mm_struct *mm,
3931 				      struct ptdesc *ptdesc)
3932 {
3933 	if (mm != &init_mm && !ptlock_init(ptdesc))
3934 		return false;
3935 	__pagetable_ctor(ptdesc);
3936 	return true;
3937 }
3938 
3939 pte_t *__pte_offset_map(pmd_t *pmd, unsigned long addr, pmd_t *pmdvalp);
3940 
pte_offset_map(pmd_t * pmd,unsigned long addr)3941 static inline pte_t *pte_offset_map(pmd_t *pmd, unsigned long addr)
3942 {
3943 	return __pte_offset_map(pmd, addr, NULL);
3944 }
3945 
3946 pte_t *pte_offset_map_lock(struct mm_struct *mm, pmd_t *pmd,
3947 			   unsigned long addr, spinlock_t **ptlp);
3948 
3949 pte_t *pte_offset_map_ro_nolock(struct mm_struct *mm, pmd_t *pmd,
3950 				unsigned long addr, spinlock_t **ptlp);
3951 pte_t *pte_offset_map_rw_nolock(struct mm_struct *mm, pmd_t *pmd,
3952 				unsigned long addr, pmd_t *pmdvalp,
3953 				spinlock_t **ptlp);
3954 
3955 #define pte_unmap_unlock(pte, ptl)	do {		\
3956 	spin_unlock(ptl);				\
3957 	pte_unmap(pte);					\
3958 } while (0)
3959 
3960 #define pte_alloc(mm, pmd) (unlikely(pmd_none(*(pmd))) && __pte_alloc(mm, pmd))
3961 
3962 #define pte_alloc_map(mm, pmd, address)			\
3963 	(pte_alloc(mm, pmd) ? NULL : pte_offset_map(pmd, address))
3964 
3965 #define pte_alloc_map_lock(mm, pmd, address, ptlp)	\
3966 	(pte_alloc(mm, pmd) ?			\
3967 		 NULL : pte_offset_map_lock(mm, pmd, address, ptlp))
3968 
3969 #define pte_alloc_kernel(pmd, address)			\
3970 	((unlikely(pmd_none(*(pmd))) && __pte_alloc_kernel(pmd))? \
3971 		NULL: pte_offset_kernel(pmd, address))
3972 
3973 #if defined(CONFIG_SPLIT_PMD_PTLOCKS)
3974 
pmd_pgtable_page(pmd_t * pmd)3975 static inline struct page *pmd_pgtable_page(pmd_t *pmd)
3976 {
3977 	unsigned long mask = ~(PTRS_PER_PMD * sizeof(pmd_t) - 1);
3978 	return virt_to_page((void *)((unsigned long) pmd & mask));
3979 }
3980 
pmd_ptdesc(pmd_t * pmd)3981 static inline struct ptdesc *pmd_ptdesc(pmd_t *pmd)
3982 {
3983 	return page_ptdesc(pmd_pgtable_page(pmd));
3984 }
3985 
pmd_lockptr(struct mm_struct * mm,pmd_t * pmd)3986 static inline spinlock_t *pmd_lockptr(struct mm_struct *mm, pmd_t *pmd)
3987 {
3988 	return ptlock_ptr(pmd_ptdesc(pmd));
3989 }
3990 
pmd_ptlock_init(struct ptdesc * ptdesc)3991 static inline bool pmd_ptlock_init(struct ptdesc *ptdesc)
3992 {
3993 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3994 	ptdesc->pmd_huge_pte = NULL;
3995 #endif
3996 	return ptlock_init(ptdesc);
3997 }
3998 
3999 #define pmd_huge_pte(mm, pmd) (pmd_ptdesc(pmd)->pmd_huge_pte)
4000 
4001 #else
4002 
pmd_lockptr(struct mm_struct * mm,pmd_t * pmd)4003 static inline spinlock_t *pmd_lockptr(struct mm_struct *mm, pmd_t *pmd)
4004 {
4005 	return &mm->page_table_lock;
4006 }
4007 
pmd_ptlock_init(struct ptdesc * ptdesc)4008 static inline bool pmd_ptlock_init(struct ptdesc *ptdesc) { return true; }
4009 
4010 #define pmd_huge_pte(mm, pmd) ((mm)->pmd_huge_pte)
4011 
4012 #endif
4013 
pmd_lock(struct mm_struct * mm,pmd_t * pmd)4014 static inline spinlock_t *pmd_lock(struct mm_struct *mm, pmd_t *pmd)
4015 {
4016 	spinlock_t *ptl = pmd_lockptr(mm, pmd);
4017 	spin_lock(ptl);
4018 	return ptl;
4019 }
4020 
pagetable_pmd_ctor(struct mm_struct * mm,struct ptdesc * ptdesc)4021 static inline bool pagetable_pmd_ctor(struct mm_struct *mm,
4022 				      struct ptdesc *ptdesc)
4023 {
4024 	if (mm != &init_mm && !pmd_ptlock_init(ptdesc))
4025 		return false;
4026 	ptdesc_pmd_pts_init(ptdesc);
4027 	__pagetable_ctor(ptdesc);
4028 	return true;
4029 }
4030 
4031 /*
4032  * No scalability reason to split PUD locks yet, but follow the same pattern
4033  * as the PMD locks to make it easier if we decide to.  The VM should not be
4034  * considered ready to switch to split PUD locks yet; there may be places
4035  * which need to be converted from page_table_lock.
4036  */
pud_lockptr(struct mm_struct * mm,pud_t * pud)4037 static inline spinlock_t *pud_lockptr(struct mm_struct *mm, pud_t *pud)
4038 {
4039 	return &mm->page_table_lock;
4040 }
4041 
pud_lock(struct mm_struct * mm,pud_t * pud)4042 static inline spinlock_t *pud_lock(struct mm_struct *mm, pud_t *pud)
4043 {
4044 	spinlock_t *ptl = pud_lockptr(mm, pud);
4045 
4046 	spin_lock(ptl);
4047 	return ptl;
4048 }
4049 
pagetable_pud_ctor(struct ptdesc * ptdesc)4050 static inline void pagetable_pud_ctor(struct ptdesc *ptdesc)
4051 {
4052 	__pagetable_ctor(ptdesc);
4053 }
4054 
pagetable_p4d_ctor(struct ptdesc * ptdesc)4055 static inline void pagetable_p4d_ctor(struct ptdesc *ptdesc)
4056 {
4057 	__pagetable_ctor(ptdesc);
4058 }
4059 
pagetable_pgd_ctor(struct ptdesc * ptdesc)4060 static inline void pagetable_pgd_ctor(struct ptdesc *ptdesc)
4061 {
4062 	__pagetable_ctor(ptdesc);
4063 }
4064 
4065 extern void __init pagecache_init(void);
4066 extern void free_initmem(void);
4067 
4068 /*
4069  * Free reserved pages within range [PAGE_ALIGN(start), end & PAGE_MASK)
4070  * into the buddy system. The freed pages will be poisoned with pattern
4071  * "poison" if it's within range [0, UCHAR_MAX].
4072  * Return pages freed into the buddy system.
4073  */
4074 extern unsigned long free_reserved_area(void *start, void *end,
4075 					int poison, const char *s);
4076 
4077 extern void adjust_managed_page_count(struct page *page, long count);
4078 
4079 void free_reserved_pages(struct page *page, unsigned int order);
4080 
free_reserved_page(struct page * page)4081 static inline void free_reserved_page(struct page *page)
4082 {
4083 	free_reserved_pages(page, 0);
4084 }
4085 
mark_page_reserved(struct page * page)4086 static inline void mark_page_reserved(struct page *page)
4087 {
4088 	SetPageReserved(page);
4089 	adjust_managed_page_count(page, -1);
4090 }
4091 
free_reserved_ptdesc(struct ptdesc * pt)4092 static inline void free_reserved_ptdesc(struct ptdesc *pt)
4093 {
4094 	free_reserved_page(ptdesc_page(pt));
4095 }
4096 
4097 /*
4098  * Default method to free all the __init memory into the buddy system.
4099  * The freed pages will be poisoned with pattern "poison" if it's within
4100  * range [0, UCHAR_MAX].
4101  * Return pages freed into the buddy system.
4102  */
free_initmem_default(int poison)4103 static inline unsigned long free_initmem_default(int poison)
4104 {
4105 	extern char __init_begin[], __init_end[];
4106 
4107 	return free_reserved_area(&__init_begin, &__init_end,
4108 				  poison, "unused kernel image (initmem)");
4109 }
4110 
get_num_physpages(void)4111 static inline unsigned long get_num_physpages(void)
4112 {
4113 	int nid;
4114 	unsigned long phys_pages = 0;
4115 
4116 	for_each_online_node(nid)
4117 		phys_pages += node_present_pages(nid);
4118 
4119 	return phys_pages;
4120 }
4121 
4122 /*
4123  * FIXME: Using memblock node mappings, an architecture may initialise its
4124  * zones, allocate the backing mem_map and account for memory holes in an
4125  * architecture independent manner.
4126  *
4127  * An architecture is expected to register range of page frames backed by
4128  * physical memory with memblock_add[_node]() before calling
4129  * free_area_init() passing in the PFN each zone ends at. At a basic
4130  * usage, an architecture is expected to do something like
4131  *
4132  * unsigned long max_zone_pfns[MAX_NR_ZONES] = {max_dma, max_normal_pfn,
4133  * 							 max_highmem_pfn};
4134  * for_each_valid_physical_page_range()
4135  *	memblock_add_node(base, size, nid, MEMBLOCK_NONE)
4136  * free_area_init(max_zone_pfns);
4137  */
4138 void arch_zone_limits_init(unsigned long *max_zone_pfn);
4139 unsigned long node_map_pfn_alignment(void);
4140 extern unsigned long absent_pages_in_range(unsigned long start_pfn,
4141 						unsigned long end_pfn);
4142 extern void get_pfn_range_for_nid(unsigned int nid,
4143 			unsigned long *start_pfn, unsigned long *end_pfn);
4144 
4145 #ifndef CONFIG_NUMA
early_pfn_to_nid(unsigned long pfn)4146 static inline int early_pfn_to_nid(unsigned long pfn)
4147 {
4148 	return 0;
4149 }
4150 #else
4151 /* please see mm/page_alloc.c */
4152 extern int __meminit early_pfn_to_nid(unsigned long pfn);
4153 #endif
4154 
4155 extern void mem_init(void);
4156 extern void __init mmap_init(void);
4157 
4158 extern void __show_mem(unsigned int flags, const nodemask_t *nodemask, int max_zone_idx);
show_mem(void)4159 static inline void show_mem(void)
4160 {
4161 	__show_mem(0, NULL, MAX_NR_ZONES - 1);
4162 }
4163 extern long si_mem_available(void);
4164 extern void si_meminfo(struct sysinfo * val);
4165 extern void si_meminfo_node(struct sysinfo *val, int nid);
4166 
4167 extern __printf(3, 4)
4168 void warn_alloc(gfp_t gfp_mask, const nodemask_t *nodemask, const char *fmt, ...);
4169 
4170 extern void setup_per_cpu_pageset(void);
4171 
4172 /* nommu.c */
4173 extern atomic_long_t mmap_pages_allocated;
4174 extern int nommu_shrink_inode_mappings(struct inode *, size_t, size_t);
4175 
4176 /* interval_tree.c */
4177 void mapping_rmap_tree_insert(struct vm_area_struct *vma,
4178 			      struct address_space *mapping);
4179 void mapping_rmap_tree_insert_after(struct vm_area_struct *vma,
4180 				    struct vm_area_struct *prev,
4181 				    struct address_space *mapping);
4182 void mapping_rmap_tree_remove(struct vm_area_struct *vma,
4183 			      struct address_space *mapping);
4184 struct vm_area_struct *
4185 mapping_rmap_tree_iter_first(struct address_space *mapping,
4186 			     pgoff_t pgoff_start, pgoff_t pgoff_last);
4187 struct vm_area_struct *
4188 mapping_rmap_tree_iter_next(struct vm_area_struct *vma,
4189 			    pgoff_t pgoff_start, pgoff_t pgoff_last);
4190 
4191 #define mapping_rmap_tree_foreach(vma, mapping, pgoff_start, pgoff_last) \
4192 	for (vma = mapping_rmap_tree_iter_first(mapping, pgoff_start,	 \
4193 						pgoff_last);		 \
4194 	     vma; vma = mapping_rmap_tree_iter_next(vma, pgoff_start,	 \
4195 						    pgoff_last))
4196 
4197 void anon_rmap_tree_insert(struct anon_vma_chain *avc,
4198 			   struct anon_vma *anon_vma);
4199 void anon_rmap_tree_remove(struct anon_vma_chain *avc,
4200 			   struct anon_vma *anon_vma);
4201 struct anon_vma_chain *
4202 anon_rmap_tree_iter_first(struct anon_vma *anon_vma,
4203 			  pgoff_t pgoff_start, pgoff_t pgoff_last);
4204 struct anon_vma_chain *
4205 anon_rmap_tree_iter_next(struct anon_vma_chain *avc,
4206 			 pgoff_t pgoff_start, pgoff_t pgoff_last);
4207 #ifdef CONFIG_DEBUG_VM_RB
4208 void anon_rmap_tree_verify(struct anon_vma_chain *avc);
4209 #endif
4210 
4211 #define anon_rmap_tree_foreach(avc, anon_vma, pgoff_start, pgoff_last)		 \
4212 	for (avc = anon_rmap_tree_iter_first(anon_vma, pgoff_start, pgoff_last); \
4213 	     avc; avc = anon_rmap_tree_iter_next(avc, pgoff_start, pgoff_last))
4214 
4215 /* mmap.c */
4216 extern int __vm_enough_memory(const struct mm_struct *mm, long pages, int cap_sys_admin);
4217 extern void exit_mmap(struct mm_struct *);
4218 bool mmap_read_lock_maybe_expand(struct mm_struct *mm, struct vm_area_struct *vma,
4219 				 unsigned long addr, bool write);
4220 
check_data_rlimit(unsigned long rlim,unsigned long new,unsigned long start,unsigned long end_data,unsigned long start_data)4221 static inline int check_data_rlimit(unsigned long rlim,
4222 				    unsigned long new,
4223 				    unsigned long start,
4224 				    unsigned long end_data,
4225 				    unsigned long start_data)
4226 {
4227 	if (rlim < RLIM_INFINITY) {
4228 		if (((new - start) + (end_data - start_data)) > rlim)
4229 			return -ENOSPC;
4230 	}
4231 
4232 	return 0;
4233 }
4234 
4235 extern int mm_take_all_locks(struct mm_struct *mm);
4236 extern void mm_drop_all_locks(struct mm_struct *mm);
4237 
4238 extern int set_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file);
4239 extern int replace_mm_exe_file(struct mm_struct *mm, struct file *new_exe_file);
4240 extern struct file *get_mm_exe_file(struct mm_struct *mm);
4241 extern struct file *get_task_exe_file(struct task_struct *task);
4242 
4243 extern void vm_stat_account(struct mm_struct *, vm_flags_t, long npages);
4244 
4245 extern bool vma_is_special_mapping(const struct vm_area_struct *vma,
4246 				   const struct vm_special_mapping *sm);
4247 struct vm_area_struct *_install_special_mapping(struct mm_struct *mm,
4248 				   unsigned long addr, unsigned long len,
4249 				   vm_flags_t vm_flags,
4250 				   const struct vm_special_mapping *spec);
4251 
4252 unsigned long randomize_stack_top(unsigned long stack_top);
4253 unsigned long randomize_page(unsigned long start, unsigned long range);
4254 
4255 unsigned long
4256 __get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
4257 		    unsigned long pgoff, unsigned long flags,
4258 		    vma_flags_t vma_flags);
4259 
4260 static inline unsigned long
get_unmapped_area(struct file * file,unsigned long addr,unsigned long len,unsigned long pgoff,unsigned long flags)4261 get_unmapped_area(struct file *file, unsigned long addr, unsigned long len,
4262 		  unsigned long pgoff, unsigned long flags)
4263 {
4264 	return __get_unmapped_area(file, addr, len, pgoff, flags,
4265 				   EMPTY_VMA_FLAGS);
4266 }
4267 
4268 unsigned long do_mmap(struct file *file, unsigned long addr,
4269 	unsigned long len, unsigned long prot, unsigned long flags,
4270 	vma_flags_t vma_flags, unsigned long pgoff, unsigned long *populate,
4271 	struct list_head *uf);
4272 extern int do_vmi_munmap(struct vma_iterator *vmi, struct mm_struct *mm,
4273 			 unsigned long start, size_t len, struct list_head *uf,
4274 			 bool unlock);
4275 int do_vmi_align_munmap(struct vma_iterator *vmi, struct vm_area_struct *vma,
4276 		    struct mm_struct *mm, unsigned long start,
4277 		    unsigned long end, struct list_head *uf, bool unlock);
4278 extern int do_munmap(struct mm_struct *, unsigned long, size_t,
4279 		     struct list_head *uf);
4280 extern int do_madvise(struct mm_struct *mm, unsigned long start, size_t len_in, int behavior);
4281 
4282 #ifdef CONFIG_MMU
4283 extern int __mm_populate(unsigned long addr, unsigned long len,
4284 			 int ignore_errors);
mm_populate(unsigned long addr,unsigned long len)4285 static inline void mm_populate(unsigned long addr, unsigned long len)
4286 {
4287 	/* Ignore errors */
4288 	(void) __mm_populate(addr, len, 1);
4289 }
4290 #else
mm_populate(unsigned long addr,unsigned long len)4291 static inline void mm_populate(unsigned long addr, unsigned long len) {}
4292 #endif
4293 
4294 /* This takes the mm semaphore itself */
4295 int __must_check vm_brk_flags(unsigned long addr, unsigned long request, bool is_exec);
4296 int vm_munmap(unsigned long start, size_t len);
4297 unsigned long __must_check vm_mmap(struct file *file, unsigned long addr,
4298 		unsigned long len, unsigned long prot,
4299 		unsigned long flag, unsigned long offset);
4300 unsigned long __must_check vm_mmap_shadow_stack(unsigned long addr,
4301 		unsigned long len, unsigned long flags);
4302 
4303 struct vm_unmapped_area_info {
4304 #define VM_UNMAPPED_AREA_TOPDOWN 1
4305 	unsigned long flags;
4306 	unsigned long length;
4307 	unsigned long low_limit;
4308 	unsigned long high_limit;
4309 	unsigned long align_mask;
4310 	unsigned long align_offset;
4311 	unsigned long start_gap;
4312 };
4313 
4314 extern unsigned long vm_unmapped_area(struct vm_unmapped_area_info *info);
4315 
4316 /* truncate.c */
4317 void truncate_inode_pages(struct address_space *mapping, loff_t lstart);
4318 void truncate_inode_pages_range(struct address_space *mapping, loff_t lstart,
4319 		uoff_t lend);
4320 void truncate_inode_pages_final(struct address_space *mapping);
4321 
4322 /* generic vm_area_ops exported for stackable file systems */
4323 extern vm_fault_t filemap_fault(struct vm_fault *vmf);
4324 extern vm_fault_t filemap_map_pages(struct vm_fault *vmf,
4325 		pgoff_t start_pgoff, pgoff_t end_pgoff);
4326 extern vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf);
4327 
4328 extern unsigned long stack_guard_gap;
4329 /* Generic expand stack which grows the stack according to GROWS{UP,DOWN} */
4330 int expand_stack_locked(struct vm_area_struct *vma, unsigned long address);
4331 struct vm_area_struct *expand_stack(struct mm_struct * mm, unsigned long addr);
4332 
4333 /* Look up the first VMA which satisfies  addr < vm_end,  NULL if none. */
4334 extern struct vm_area_struct * find_vma(struct mm_struct * mm, unsigned long addr);
4335 extern struct vm_area_struct * find_vma_prev(struct mm_struct * mm, unsigned long addr,
4336 					     struct vm_area_struct **pprev);
4337 
4338 /*
4339  * Look up the first VMA which intersects the interval [start_addr, end_addr)
4340  * NULL if none.  Assume start_addr < end_addr.
4341  */
4342 struct vm_area_struct *find_vma_intersection(struct mm_struct *mm,
4343 			unsigned long start_addr, unsigned long end_addr);
4344 
4345 /**
4346  * vma_lookup() - Find a VMA at a specific address
4347  * @mm: The process address space.
4348  * @addr: The user address.
4349  *
4350  * Return: The vm_area_struct at the given address, %NULL otherwise.
4351  */
4352 static inline
vma_lookup(struct mm_struct * mm,unsigned long addr)4353 struct vm_area_struct *vma_lookup(struct mm_struct *mm, unsigned long addr)
4354 {
4355 	return mtree_load(&mm->mm_mt, addr);
4356 }
4357 
stack_guard_start_gap(const struct vm_area_struct * vma)4358 static inline unsigned long stack_guard_start_gap(const struct vm_area_struct *vma)
4359 {
4360 	if (vma->vm_flags & VM_GROWSDOWN)
4361 		return stack_guard_gap;
4362 
4363 	/* See reasoning around the VM_SHADOW_STACK definition */
4364 	if (vma->vm_flags & VM_SHADOW_STACK)
4365 		return PAGE_SIZE;
4366 
4367 	return 0;
4368 }
4369 
vm_start_gap(const struct vm_area_struct * vma)4370 static inline unsigned long vm_start_gap(const struct vm_area_struct *vma)
4371 {
4372 	unsigned long gap = stack_guard_start_gap(vma);
4373 	unsigned long vm_start = vma->vm_start;
4374 
4375 	vm_start -= gap;
4376 	if (vm_start > vma->vm_start)
4377 		vm_start = 0;
4378 	return vm_start;
4379 }
4380 
vm_end_gap(const struct vm_area_struct * vma)4381 static inline unsigned long vm_end_gap(const struct vm_area_struct *vma)
4382 {
4383 	unsigned long vm_end = vma->vm_end;
4384 
4385 	if (vma->vm_flags & VM_GROWSUP) {
4386 		vm_end += stack_guard_gap;
4387 		if (vm_end < vma->vm_end)
4388 			vm_end = -PAGE_SIZE;
4389 	}
4390 	return vm_end;
4391 }
4392 
vma_pages(const struct vm_area_struct * vma)4393 static inline unsigned long vma_pages(const struct vm_area_struct *vma)
4394 {
4395 	return (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
4396 }
4397 
4398 /**
4399  * vma_start_pgoff() - Get the page offset of the start of @vma
4400  * @vma: The VMA whose page offset is required.
4401  *
4402  * If the VMA is file-backed, this is the page offset into the file.
4403  *
4404  * If @vma is anonymous, this is the virtual page offset of the start of the
4405  * VMA - if unfaulted, then vma->vm_start >> PAGE_SHIFT, if faulted then the
4406  * virtual page offset at the time of first fault.
4407  *
4408  * If @vma is a MAP_PRIVATE file-backed mapping, then this returns the
4409  * page offset within the file.
4410  *
4411  * Edge cases: nommu does not abide by these, MAP_PRIVATE-/dev/zero satisfies
4412  * vma_is_anonymous() but has file-backed page offset, and MAP_PRIVATE-pfnmap
4413  * regions have their page offset set to the first PFN in the range.
4414  *
4415  * Returns: The page offset of the start of @vma.
4416  */
vma_start_pgoff(const struct vm_area_struct * vma)4417 static inline pgoff_t vma_start_pgoff(const struct vm_area_struct *vma)
4418 {
4419 	return vma->vm_pgoff;
4420 }
4421 
4422 /**
4423  * vma_end_pgoff() - Get the page offset of the exclusive end of @vma
4424  * @vma: The VMA whose end page offset is required.
4425  *
4426  * This returns the exclusive end page offset of @vma, which is useful for
4427  * expressing page offset ranges.
4428  *
4429  * See the description of vma_start_pgoff() for a description of VMA page
4430  * offsets.
4431  *
4432  * Returns: The exclusive end page offset of @vma.
4433  */
vma_end_pgoff(const struct vm_area_struct * vma)4434 static inline pgoff_t vma_end_pgoff(const struct vm_area_struct *vma)
4435 {
4436 	return vma_start_pgoff(vma) + vma_pages(vma);
4437 }
4438 
4439 /**
4440  * vma_last_pgoff() - Get the page offset of the last page in @vma
4441  * @vma: The VMA whose last page offset is required.
4442  *
4443  * This returns the last page offset contained within @vma.
4444  *
4445  * See the description of vma_start_pgoff() for a description of VMA page
4446  * offsets.
4447  *
4448  * Returns: The last page offset of @vma.
4449  */
vma_last_pgoff(const struct vm_area_struct * vma)4450 static inline pgoff_t vma_last_pgoff(const struct vm_area_struct *vma)
4451 {
4452 	return vma_end_pgoff(vma) - 1;
4453 }
4454 
4455 /**
4456  * vma_start_anon_pgoff() - Get the anonymous page offset of the start of @vma
4457  * @vma: The VMA whose anonymous page offset is required.
4458  *
4459  * If unfaulted, then this is vma->vm_start >> PAGE_SHIFT, if faulted then the
4460  * anonymous page offset at the time of first fault.
4461  *
4462  * If the VMA is anonymous, this returns the same value as vma_start_pgoff().
4463  *
4464  * This value is used for tracking MAP_PRIVATE file-backed mappings by their
4465  * anonymous page offset.
4466  *
4467  * Returns: The anonymous page offset of the start of @vma.
4468  */
vma_start_anon_pgoff(const struct vm_area_struct * vma)4469 static inline pgoff_t vma_start_anon_pgoff(const struct vm_area_struct *vma)
4470 {
4471 	pgoff_t pgoff = 0;
4472 
4473 #ifdef CONFIG_64BIT
4474 	pgoff += vma->__vm_anon_pgoff_hi;
4475 	pgoff <<= 32;
4476 #endif
4477 	pgoff += vma->__vm_anon_pgoff_lo;
4478 	return pgoff;
4479 }
4480 
4481 /**
4482  * vma_end_anon_pgoff() - Get the anonymous page offset of the exclusive end of
4483  * @vma.
4484  * @vma: The VMA whose end anonymous page offset is required.
4485  *
4486  * This returns the anonymous exclusive end page offset of @vma, which is useful
4487  * for expressing page offset ranges.
4488  *
4489  * See the description of vma_start_anon_pgoff() for a description of VMA
4490  * anonymous page offsets.
4491  *
4492  * Returns: The exclusive end anonymous page offset of @vma.
4493  */
vma_end_anon_pgoff(const struct vm_area_struct * vma)4494 static inline pgoff_t vma_end_anon_pgoff(const struct vm_area_struct *vma)
4495 {
4496 	return vma_start_anon_pgoff(vma) + vma_pages(vma);
4497 }
4498 
4499 /**
4500  * vma_last_anon_pgoff() - Get the anonymous page offset of the last page in
4501  * @vma.
4502  * @vma: The VMA whose last anonymous page offset is required.
4503  *
4504  * See the description of vma_start_anon_pgoff() for a description of VMA
4505  * anonymous page offsets.
4506  *
4507  * Returns: The last anonymous page offset of @vma.
4508  */
vma_last_anon_pgoff(const struct vm_area_struct * vma)4509 static inline pgoff_t vma_last_anon_pgoff(const struct vm_area_struct *vma)
4510 {
4511 	return vma_end_anon_pgoff(vma) - 1;
4512 }
4513 
vma_desc_size(const struct vm_area_desc * desc)4514 static inline unsigned long vma_desc_size(const struct vm_area_desc *desc)
4515 {
4516 	return desc->end - desc->start;
4517 }
4518 
vma_desc_pages(const struct vm_area_desc * desc)4519 static inline unsigned long vma_desc_pages(const struct vm_area_desc *desc)
4520 {
4521 	return vma_desc_size(desc) >> PAGE_SHIFT;
4522 }
4523 
4524 /**
4525  * mmap_action_remap - helper for mmap_prepare hook to specify that a pure PFN
4526  * remap is required.
4527  * @desc: The VMA descriptor for the VMA requiring remap.
4528  * @start: The virtual address to start the remap from, must be within the VMA.
4529  * @start_pfn: The first PFN in the range to remap.
4530  * @size: The size of the range to remap, in bytes, at most spanning to the end
4531  * of the VMA.
4532  */
mmap_action_remap(struct vm_area_desc * desc,unsigned long start,unsigned long start_pfn,unsigned long size)4533 static inline void mmap_action_remap(struct vm_area_desc *desc,
4534 				     unsigned long start,
4535 				     unsigned long start_pfn,
4536 				     unsigned long size)
4537 {
4538 	struct mmap_action *action = &desc->action;
4539 
4540 	/* [start, start + size) must be within the VMA. */
4541 	WARN_ON_ONCE(start < desc->start || start >= desc->end);
4542 	WARN_ON_ONCE(start + size > desc->end);
4543 
4544 	action->type = MMAP_REMAP_PFN;
4545 	action->remap.start = start;
4546 	action->remap.start_pfn = start_pfn;
4547 	action->remap.size = size;
4548 	action->remap.pgprot = desc->page_prot;
4549 }
4550 
4551 /**
4552  * mmap_action_remap_full - helper for mmap_prepare hook to specify that the
4553  * entirety of a VMA should be PFN remapped.
4554  * @desc: The VMA descriptor for the VMA requiring remap.
4555  * @start_pfn: The first PFN in the range to remap.
4556  */
mmap_action_remap_full(struct vm_area_desc * desc,unsigned long start_pfn)4557 static inline void mmap_action_remap_full(struct vm_area_desc *desc,
4558 					  unsigned long start_pfn)
4559 {
4560 	mmap_action_remap(desc, desc->start, start_pfn, vma_desc_size(desc));
4561 }
4562 
4563 /**
4564  * mmap_action_ioremap - helper for mmap_prepare hook to specify that a pure PFN
4565  * I/O remap is required.
4566  * @desc: The VMA descriptor for the VMA requiring remap.
4567  * @start: The virtual address to start the remap from, must be within the VMA.
4568  * @start_pfn: The first PFN in the range to remap.
4569  * @size: The size of the range to remap, in bytes, at most spanning to the end
4570  * of the VMA.
4571  */
mmap_action_ioremap(struct vm_area_desc * desc,unsigned long start,unsigned long start_pfn,unsigned long size)4572 static inline void mmap_action_ioremap(struct vm_area_desc *desc,
4573 				       unsigned long start,
4574 				       unsigned long start_pfn,
4575 				       unsigned long size)
4576 {
4577 	mmap_action_remap(desc, start, start_pfn, size);
4578 	desc->action.type = MMAP_IO_REMAP_PFN;
4579 }
4580 
4581 /**
4582  * mmap_action_ioremap_full - helper for mmap_prepare hook to specify that the
4583  * entirety of a VMA should be PFN I/O remapped.
4584  * @desc: The VMA descriptor for the VMA requiring remap.
4585  * @start_pfn: The first PFN in the range to remap.
4586  */
mmap_action_ioremap_full(struct vm_area_desc * desc,unsigned long start_pfn)4587 static inline void mmap_action_ioremap_full(struct vm_area_desc *desc,
4588 					    unsigned long start_pfn)
4589 {
4590 	mmap_action_ioremap(desc, desc->start, start_pfn, vma_desc_size(desc));
4591 }
4592 
4593 /**
4594  * mmap_action_simple_ioremap - helper for mmap_prepare hook to specify that the
4595  * physical range in [start_phys_addr, start_phys_addr + size) should be I/O
4596  * remapped.
4597  * @desc: The VMA descriptor for the VMA requiring remap.
4598  * @start_phys_addr: Start of the physical memory to be mapped.
4599  * @size: Size of the area to map.
4600  *
4601  * NOTE: Some drivers might want to tweak desc->page_prot for purposes of
4602  * write-combine or similar.
4603  */
mmap_action_simple_ioremap(struct vm_area_desc * desc,phys_addr_t start_phys_addr,unsigned long size)4604 static inline void mmap_action_simple_ioremap(struct vm_area_desc *desc,
4605 					      phys_addr_t start_phys_addr,
4606 					      unsigned long size)
4607 {
4608 	struct mmap_action *action = &desc->action;
4609 
4610 	action->simple_ioremap.start_phys_addr = start_phys_addr;
4611 	action->simple_ioremap.size = size;
4612 	action->type = MMAP_SIMPLE_IO_REMAP;
4613 }
4614 
4615 /**
4616  * mmap_action_map_kernel_pages - helper for mmap_prepare hook to specify that
4617  * @num kernel pages contained in the @pages array should be mapped to userland
4618  * starting at virtual address @start.
4619  * @desc: The VMA descriptor for the VMA requiring kernel pags to be mapped.
4620  * @start: The virtual address from which to map them.
4621  * @pages: An array of struct page pointers describing the memory to map.
4622  * @nr_pages: The number of entries in the @pages aray.
4623  */
mmap_action_map_kernel_pages(struct vm_area_desc * desc,unsigned long start,struct page ** pages,unsigned long nr_pages)4624 static inline void mmap_action_map_kernel_pages(struct vm_area_desc *desc,
4625 		unsigned long start, struct page **pages,
4626 		unsigned long nr_pages)
4627 {
4628 	struct mmap_action *action = &desc->action;
4629 
4630 	action->type = MMAP_MAP_KERNEL_PAGES;
4631 	action->map_kernel.start = start;
4632 	action->map_kernel.pages = pages;
4633 	action->map_kernel.nr_pages = nr_pages;
4634 	action->map_kernel.pgoff = desc->pgoff;
4635 }
4636 
4637 /**
4638  * mmap_action_map_kernel_pages_full - helper for mmap_prepare hook to specify that
4639  * kernel pages contained in the @pages array should be mapped to userland
4640  * from @desc->start to @desc->end.
4641  * @desc: The VMA descriptor for the VMA requiring kernel pags to be mapped.
4642  * @pages: An array of struct page pointers describing the memory to map.
4643  *
4644  * The caller must ensure that @pages contains sufficient entries to cover the
4645  * entire range described by @desc.
4646  */
mmap_action_map_kernel_pages_full(struct vm_area_desc * desc,struct page ** pages)4647 static inline void mmap_action_map_kernel_pages_full(struct vm_area_desc *desc,
4648 		struct page **pages)
4649 {
4650 	mmap_action_map_kernel_pages(desc, desc->start, pages,
4651 				     vma_desc_pages(desc));
4652 }
4653 
4654 int mmap_action_prepare(struct vm_area_desc *desc);
4655 int mmap_action_complete(struct vm_area_struct *vma,
4656 			 struct mmap_action *action, bool is_compat);
4657 
4658 /* Look up the first VMA which exactly match the interval vm_start ... vm_end */
find_exact_vma(struct mm_struct * mm,unsigned long vm_start,unsigned long vm_end)4659 static inline struct vm_area_struct *find_exact_vma(struct mm_struct *mm,
4660 				unsigned long vm_start, unsigned long vm_end)
4661 {
4662 	struct vm_area_struct *vma = vma_lookup(mm, vm_start);
4663 
4664 	if (vma && (vma->vm_start != vm_start || vma->vm_end != vm_end))
4665 		vma = NULL;
4666 
4667 	return vma;
4668 }
4669 
4670 /**
4671  * range_is_subset - Is the specified inner range a subset of the outer range?
4672  * @outer_start: The start of the outer range.
4673  * @outer_end: The exclusive end of the outer range.
4674  * @inner_start: The start of the inner range.
4675  * @inner_end: The exclusive end of the inner range.
4676  *
4677  * Returns: %true if [inner_start, inner_end) is a subset of [outer_start,
4678  * outer_end), otherwise %false.
4679  */
range_is_subset(unsigned long outer_start,unsigned long outer_end,unsigned long inner_start,unsigned long inner_end)4680 static inline bool range_is_subset(unsigned long outer_start,
4681 				   unsigned long outer_end,
4682 				   unsigned long inner_start,
4683 				   unsigned long inner_end)
4684 {
4685 	return outer_start <= inner_start && inner_end <= outer_end;
4686 }
4687 
4688 /**
4689  * range_in_vma - is the specified [@start, @end) range a subset of the VMA?
4690  * @vma: The VMA against which we want to check [@start, @end).
4691  * @start: The start of the range we wish to check.
4692  * @end: The exclusive end of the range we wish to check.
4693  *
4694  * Returns: %true if [@start, @end) is a subset of [@vma->vm_start,
4695  * @vma->vm_end), %false otherwise.
4696  */
range_in_vma(const struct vm_area_struct * vma,unsigned long start,unsigned long end)4697 static inline bool range_in_vma(const struct vm_area_struct *vma,
4698 				unsigned long start, unsigned long end)
4699 {
4700 	if (!vma)
4701 		return false;
4702 
4703 	return range_is_subset(vma->vm_start, vma->vm_end, start, end);
4704 }
4705 
4706 /**
4707  * range_in_vma_desc - is the specified [@start, @end) range a subset of the VMA
4708  * described by @desc, a VMA descriptor?
4709  * @desc: The VMA descriptor against which we want to check [@start, @end).
4710  * @start: The start of the range we wish to check.
4711  * @end: The exclusive end of the range we wish to check.
4712  *
4713  * Returns: %true if [@start, @end) is a subset of [@desc->start, @desc->end),
4714  * %false otherwise.
4715  */
range_in_vma_desc(const struct vm_area_desc * desc,unsigned long start,unsigned long end)4716 static inline bool range_in_vma_desc(const struct vm_area_desc *desc,
4717 				     unsigned long start, unsigned long end)
4718 {
4719 	if (!desc)
4720 		return false;
4721 
4722 	return range_is_subset(desc->start, desc->end, start, end);
4723 }
4724 
4725 #ifdef CONFIG_MMU
4726 pgprot_t vm_get_page_prot(vm_flags_t vm_flags);
4727 
vma_flags_to_page_prot(vma_flags_t vma_flags)4728 static inline pgprot_t vma_flags_to_page_prot(vma_flags_t vma_flags)
4729 {
4730 	const vm_flags_t vm_flags = vma_flags_to_legacy(vma_flags);
4731 
4732 	return vm_get_page_prot(vm_flags);
4733 }
4734 
vma_get_page_prot(const struct vm_area_struct * vma)4735 static inline pgprot_t vma_get_page_prot(const struct vm_area_struct *vma)
4736 {
4737 	return vma_flags_to_page_prot(vma->flags);
4738 }
4739 
4740 void vma_set_page_prot(struct vm_area_struct *vma);
4741 #else
vm_get_page_prot(vm_flags_t vm_flags)4742 static inline pgprot_t vm_get_page_prot(vm_flags_t vm_flags)
4743 {
4744 	return __pgprot(0);
4745 }
vma_flags_to_page_prot(vma_flags_t vma_flags)4746 static inline pgprot_t vma_flags_to_page_prot(vma_flags_t vma_flags)
4747 {
4748 	return __pgprot(0);
4749 }
vma_get_page_prot(const struct vm_area_struct * vma)4750 static inline pgprot_t vma_get_page_prot(const struct vm_area_struct *vma)
4751 {
4752 	return __pgprot(0);
4753 }
vma_set_page_prot(struct vm_area_struct * vma)4754 static inline void vma_set_page_prot(struct vm_area_struct *vma)
4755 {
4756 	vma->vm_page_prot = vma_get_page_prot(vma);
4757 }
4758 #endif
4759 
4760 void vma_set_file(struct vm_area_struct *vma, struct file *file);
4761 
4762 #ifdef CONFIG_NUMA_BALANCING
4763 unsigned long change_prot_numa(struct vm_area_struct *vma,
4764 			unsigned long start, unsigned long end);
4765 #endif
4766 
4767 struct vm_area_struct *find_extend_vma_locked(struct mm_struct *,
4768 		unsigned long addr);
4769 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
4770 		    unsigned long pfn, unsigned long size, pgprot_t pgprot);
4771 
4772 int vm_insert_page(struct vm_area_struct *, unsigned long addr, struct page *);
4773 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
4774 			struct page **pages, unsigned long *num);
4775 int map_kernel_pages_prepare(struct vm_area_desc *desc);
4776 int map_kernel_pages_complete(struct vm_area_struct *vma,
4777 			      struct mmap_action *action);
4778 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
4779 				unsigned long num);
4780 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
4781 				unsigned long num);
4782 vm_fault_t vmf_insert_page_mkwrite(struct vm_fault *vmf, struct page *page,
4783 			bool write);
4784 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
4785 			unsigned long pfn);
4786 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
4787 			unsigned long pfn, pgprot_t pgprot);
4788 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
4789 			unsigned long pfn);
4790 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
4791 		unsigned long addr, unsigned long pfn);
4792 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len);
4793 
vmf_insert_page(struct vm_area_struct * vma,unsigned long addr,struct page * page)4794 static inline vm_fault_t vmf_insert_page(struct vm_area_struct *vma,
4795 				unsigned long addr, struct page *page)
4796 {
4797 	int err = vm_insert_page(vma, addr, page);
4798 
4799 	if (err == -ENOMEM)
4800 		return VM_FAULT_OOM;
4801 	if (err < 0 && err != -EBUSY)
4802 		return VM_FAULT_SIGBUS;
4803 
4804 	return VM_FAULT_NOPAGE;
4805 }
4806 
4807 #ifndef io_remap_pfn_range_pfn
io_remap_pfn_range_pfn(unsigned long pfn,unsigned long size)4808 static inline unsigned long io_remap_pfn_range_pfn(unsigned long pfn,
4809 		unsigned long size)
4810 {
4811 	return pfn;
4812 }
4813 #endif
4814 
io_remap_pfn_range(struct vm_area_struct * vma,unsigned long addr,unsigned long orig_pfn,unsigned long size,pgprot_t orig_prot)4815 static inline int io_remap_pfn_range(struct vm_area_struct *vma,
4816 				     unsigned long addr, unsigned long orig_pfn,
4817 				     unsigned long size, pgprot_t orig_prot)
4818 {
4819 	const unsigned long pfn = io_remap_pfn_range_pfn(orig_pfn, size);
4820 	const pgprot_t prot = pgprot_decrypted(orig_prot);
4821 
4822 	return remap_pfn_range(vma, addr, pfn, size, prot);
4823 }
4824 
vmf_error(int err)4825 static inline vm_fault_t vmf_error(int err)
4826 {
4827 	if (err == -ENOMEM)
4828 		return VM_FAULT_OOM;
4829 	else if (err == -EHWPOISON)
4830 		return VM_FAULT_HWPOISON;
4831 	return VM_FAULT_SIGBUS;
4832 }
4833 
4834 /*
4835  * Convert errno to return value for ->page_mkwrite() calls.
4836  *
4837  * This should eventually be merged with vmf_error() above, but will need a
4838  * careful audit of all vmf_error() callers.
4839  */
vmf_fs_error(int err)4840 static inline vm_fault_t vmf_fs_error(int err)
4841 {
4842 	if (err == 0)
4843 		return VM_FAULT_LOCKED;
4844 	if (err == -EFAULT || err == -EAGAIN)
4845 		return VM_FAULT_NOPAGE;
4846 	if (err == -ENOMEM)
4847 		return VM_FAULT_OOM;
4848 	/* -ENOSPC, -EDQUOT, -EIO ... */
4849 	return VM_FAULT_SIGBUS;
4850 }
4851 
vm_fault_to_errno(vm_fault_t vm_fault,int foll_flags)4852 static inline int vm_fault_to_errno(vm_fault_t vm_fault, int foll_flags)
4853 {
4854 	if (vm_fault & VM_FAULT_OOM)
4855 		return -ENOMEM;
4856 	if (vm_fault & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
4857 		return (foll_flags & FOLL_HWPOISON) ? -EHWPOISON : -EFAULT;
4858 	if (vm_fault & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
4859 		return -EFAULT;
4860 	return 0;
4861 }
4862 
4863 /*
4864  * Indicates whether GUP can follow a PROT_NONE mapped page, or whether
4865  * a (NUMA hinting or userfaultfd RWP) fault is required.
4866  */
gup_can_follow_protnone(const struct vm_area_struct * vma,unsigned int flags)4867 static inline bool gup_can_follow_protnone(const struct vm_area_struct *vma,
4868 					   unsigned int flags)
4869 {
4870 	/*
4871 	 * VM_UFFD_RWP uses protnone as an access-tracking marker, not for
4872 	 * NUMA hinting. GUP must always take a fault so the access is
4873 	 * delivered to userfaultfd, regardless of FOLL_HONOR_NUMA_FAULT.
4874 	 *
4875 	 * Only do so while the VMA is accessible. If it has been made
4876 	 * inaccessible (e.g. mprotect(PROT_NONE)), fall through to the guard
4877 	 * below: forcing a fault there would loop, as handle_mm_fault() makes
4878 	 * no progress on protnone in an inaccessible VMA, and the access is
4879 	 * denied regardless of RWP anyway.
4880 	 */
4881 	if (vma_test_single_mask(vma, VMA_UFFD_RWP) && vma_is_accessible(vma))
4882 		return false;
4883 
4884 	/*
4885 	 * If callers don't want to honor NUMA hinting faults, no need to
4886 	 * determine if we would actually have to trigger a NUMA hinting fault.
4887 	 */
4888 	if (!(flags & FOLL_HONOR_NUMA_FAULT))
4889 		return true;
4890 
4891 	/*
4892 	 * NUMA hinting faults don't apply in inaccessible (PROT_NONE) VMAs.
4893 	 *
4894 	 * Requiring a fault here even for inaccessible VMAs would mean that
4895 	 * FOLL_FORCE cannot make any progress, because handle_mm_fault()
4896 	 * refuses to process NUMA hinting faults in inaccessible VMAs.
4897 	 */
4898 	return !vma_is_accessible(vma);
4899 }
4900 
4901 typedef int (*pte_fn_t)(pte_t *pte, unsigned long addr, void *data);
4902 extern int apply_to_page_range(struct mm_struct *mm, unsigned long address,
4903 			       unsigned long size, pte_fn_t fn, void *data);
4904 extern int apply_to_existing_page_range(struct mm_struct *mm,
4905 				   unsigned long address, unsigned long size,
4906 				   pte_fn_t fn, void *data);
4907 
4908 #ifdef CONFIG_PAGE_POISONING
4909 extern void __kernel_poison_pages(struct page *page, int numpages);
4910 extern void __kernel_unpoison_pages(struct page *page, int numpages);
4911 extern bool _page_poisoning_enabled_early;
4912 DECLARE_STATIC_KEY_FALSE(_page_poisoning_enabled);
page_poisoning_enabled(void)4913 static inline bool page_poisoning_enabled(void)
4914 {
4915 	return _page_poisoning_enabled_early;
4916 }
4917 /*
4918  * For use in fast paths after init_mem_debugging() has run, or when a
4919  * false negative result is not harmful when called too early.
4920  */
page_poisoning_enabled_static(void)4921 static inline bool page_poisoning_enabled_static(void)
4922 {
4923 	return static_branch_unlikely(&_page_poisoning_enabled);
4924 }
kernel_poison_pages(struct page * page,int numpages)4925 static inline void kernel_poison_pages(struct page *page, int numpages)
4926 {
4927 	if (page_poisoning_enabled_static())
4928 		__kernel_poison_pages(page, numpages);
4929 }
kernel_unpoison_pages(struct page * page,int numpages)4930 static inline void kernel_unpoison_pages(struct page *page, int numpages)
4931 {
4932 	if (page_poisoning_enabled_static())
4933 		__kernel_unpoison_pages(page, numpages);
4934 }
4935 #else
page_poisoning_enabled(void)4936 static inline bool page_poisoning_enabled(void) { return false; }
page_poisoning_enabled_static(void)4937 static inline bool page_poisoning_enabled_static(void) { return false; }
__kernel_poison_pages(struct page * page,int nunmpages)4938 static inline void __kernel_poison_pages(struct page *page, int nunmpages) { }
kernel_poison_pages(struct page * page,int numpages)4939 static inline void kernel_poison_pages(struct page *page, int numpages) { }
kernel_unpoison_pages(struct page * page,int numpages)4940 static inline void kernel_unpoison_pages(struct page *page, int numpages) { }
4941 #endif
4942 
4943 DECLARE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_ALLOC_DEFAULT_ON, init_on_alloc);
want_init_on_alloc(gfp_t flags)4944 static inline bool want_init_on_alloc(gfp_t flags)
4945 {
4946 	if (static_branch_maybe(CONFIG_INIT_ON_ALLOC_DEFAULT_ON,
4947 				&init_on_alloc))
4948 		return true;
4949 	return flags & __GFP_ZERO;
4950 }
4951 
4952 DECLARE_STATIC_KEY_MAYBE(CONFIG_INIT_ON_FREE_DEFAULT_ON, init_on_free);
want_init_on_free(void)4953 static inline bool want_init_on_free(void)
4954 {
4955 	return static_branch_maybe(CONFIG_INIT_ON_FREE_DEFAULT_ON,
4956 				   &init_on_free);
4957 }
4958 
4959 extern bool _debug_pagealloc_enabled_early;
4960 DECLARE_STATIC_KEY_FALSE(_debug_pagealloc_enabled);
4961 
debug_pagealloc_enabled(void)4962 static inline bool debug_pagealloc_enabled(void)
4963 {
4964 	return IS_ENABLED(CONFIG_DEBUG_PAGEALLOC) &&
4965 		_debug_pagealloc_enabled_early;
4966 }
4967 
4968 /*
4969  * For use in fast paths after mem_debugging_and_hardening_init() has run,
4970  * or when a false negative result is not harmful when called too early.
4971  */
debug_pagealloc_enabled_static(void)4972 static inline bool debug_pagealloc_enabled_static(void)
4973 {
4974 	if (!IS_ENABLED(CONFIG_DEBUG_PAGEALLOC))
4975 		return false;
4976 
4977 	return static_branch_unlikely(&_debug_pagealloc_enabled);
4978 }
4979 
4980 /*
4981  * To support DEBUG_PAGEALLOC architecture must ensure that
4982  * __kernel_map_pages() never fails
4983  */
4984 extern void __kernel_map_pages(struct page *page, int numpages, int enable);
4985 #ifdef CONFIG_DEBUG_PAGEALLOC
debug_pagealloc_map_pages(struct page * page,int numpages)4986 static inline void debug_pagealloc_map_pages(struct page *page, int numpages)
4987 {
4988 	iommu_debug_check_unmapped(page, numpages);
4989 
4990 	if (debug_pagealloc_enabled_static())
4991 		__kernel_map_pages(page, numpages, 1);
4992 }
4993 
debug_pagealloc_unmap_pages(struct page * page,int numpages)4994 static inline void debug_pagealloc_unmap_pages(struct page *page, int numpages)
4995 {
4996 	iommu_debug_check_unmapped(page, numpages);
4997 
4998 	if (debug_pagealloc_enabled_static())
4999 		__kernel_map_pages(page, numpages, 0);
5000 }
5001 
5002 extern unsigned int _debug_guardpage_minorder;
5003 DECLARE_STATIC_KEY_FALSE(_debug_guardpage_enabled);
5004 
debug_guardpage_minorder(void)5005 static inline unsigned int debug_guardpage_minorder(void)
5006 {
5007 	return _debug_guardpage_minorder;
5008 }
5009 
debug_guardpage_enabled(void)5010 static inline bool debug_guardpage_enabled(void)
5011 {
5012 	return static_branch_unlikely(&_debug_guardpage_enabled);
5013 }
5014 
page_is_guard(const struct page * page)5015 static inline bool page_is_guard(const struct page *page)
5016 {
5017 	if (!debug_guardpage_enabled())
5018 		return false;
5019 
5020 	return PageGuard(page);
5021 }
5022 
5023 bool __set_page_guard(struct zone *zone, struct page *page, unsigned int order);
set_page_guard(struct zone * zone,struct page * page,unsigned int order)5024 static inline bool set_page_guard(struct zone *zone, struct page *page,
5025 				  unsigned int order)
5026 {
5027 	if (!debug_guardpage_enabled())
5028 		return false;
5029 	return __set_page_guard(zone, page, order);
5030 }
5031 
5032 void __clear_page_guard(struct zone *zone, struct page *page, unsigned int order);
clear_page_guard(struct zone * zone,struct page * page,unsigned int order)5033 static inline void clear_page_guard(struct zone *zone, struct page *page,
5034 				    unsigned int order)
5035 {
5036 	if (!debug_guardpage_enabled())
5037 		return;
5038 	__clear_page_guard(zone, page, order);
5039 }
5040 
5041 #else	/* CONFIG_DEBUG_PAGEALLOC */
debug_pagealloc_map_pages(struct page * page,int numpages)5042 static inline void debug_pagealloc_map_pages(struct page *page, int numpages) {}
debug_pagealloc_unmap_pages(struct page * page,int numpages)5043 static inline void debug_pagealloc_unmap_pages(struct page *page, int numpages) {}
debug_guardpage_minorder(void)5044 static inline unsigned int debug_guardpage_minorder(void) { return 0; }
debug_guardpage_enabled(void)5045 static inline bool debug_guardpage_enabled(void) { return false; }
page_is_guard(const struct page * page)5046 static inline bool page_is_guard(const struct page *page) { return false; }
set_page_guard(struct zone * zone,struct page * page,unsigned int order)5047 static inline bool set_page_guard(struct zone *zone, struct page *page,
5048 			unsigned int order) { return false; }
clear_page_guard(struct zone * zone,struct page * page,unsigned int order)5049 static inline void clear_page_guard(struct zone *zone, struct page *page,
5050 				unsigned int order) {}
5051 #endif	/* CONFIG_DEBUG_PAGEALLOC */
5052 
5053 #ifndef clear_pages
5054 /**
5055  * clear_pages() - clear a page range for kernel-internal use.
5056  * @addr: start address
5057  * @npages: number of pages
5058  *
5059  * Use clear_user_pages() instead when clearing a page range to be
5060  * mapped to user space.
5061  *
5062  * Does absolutely no exception handling.
5063  *
5064  * Note that even though the clearing operation is preemptible, clear_pages()
5065  * does not (and on architectures where it reduces to a few long-running
5066  * instructions, might not be able to) call cond_resched() to check if
5067  * rescheduling is required.
5068  *
5069  * When running under preemptible models this is not a problem. Under
5070  * cooperatively scheduled models, however, the caller is expected to
5071  * limit @npages to no more than PROCESS_PAGES_NON_PREEMPT_BATCH.
5072  */
clear_pages(void * addr,unsigned int npages)5073 static inline void clear_pages(void *addr, unsigned int npages)
5074 {
5075 	do {
5076 		clear_page(addr);
5077 		addr += PAGE_SIZE;
5078 	} while (--npages);
5079 }
5080 #endif
5081 
5082 #ifndef PROCESS_PAGES_NON_PREEMPT_BATCH
5083 #ifdef clear_pages
5084 /*
5085  * The architecture defines clear_pages(), and we assume that it is
5086  * generally "fast". So choose a batch size large enough to allow the processor
5087  * headroom for optimizing the operation and yet small enough that we see
5088  * reasonable preemption latency for when this optimization is not possible
5089  * (ex. slow microarchitectures, memory bandwidth saturation.)
5090  *
5091  * With a value of 32MB and assuming a memory bandwidth of ~10GBps, this should
5092  * result in worst case preemption latency of around 3ms when clearing pages.
5093  *
5094  * (See comment above clear_pages() for why preemption latency is a concern
5095  * here.)
5096  */
5097 #define PROCESS_PAGES_NON_PREEMPT_BATCH		(SZ_32M >> PAGE_SHIFT)
5098 #else /* !clear_pages */
5099 /*
5100  * The architecture does not provide a clear_pages() implementation. Assume
5101  * that clear_page() -- which clear_pages() will fallback to -- is relatively
5102  * slow and choose a small value for PROCESS_PAGES_NON_PREEMPT_BATCH.
5103  */
5104 #define PROCESS_PAGES_NON_PREEMPT_BATCH		1
5105 #endif
5106 #endif
5107 
5108 #ifdef __HAVE_ARCH_GATE_AREA
5109 extern struct vm_area_struct *get_gate_vma(struct mm_struct *mm);
5110 extern int in_gate_area_no_mm(unsigned long addr);
5111 extern int in_gate_area(struct mm_struct *mm, unsigned long addr);
5112 #else
get_gate_vma(struct mm_struct * mm)5113 static inline struct vm_area_struct *get_gate_vma(struct mm_struct *mm)
5114 {
5115 	return NULL;
5116 }
in_gate_area_no_mm(unsigned long addr)5117 static inline int in_gate_area_no_mm(unsigned long addr) { return 0; }
in_gate_area(struct mm_struct * mm,unsigned long addr)5118 static inline int in_gate_area(struct mm_struct *mm, unsigned long addr)
5119 {
5120 	return 0;
5121 }
5122 #endif	/* __HAVE_ARCH_GATE_AREA */
5123 
5124 bool process_shares_mm(const struct task_struct *p, const struct mm_struct *mm);
5125 
5126 void drop_slab(void);
5127 
5128 #ifndef CONFIG_MMU
5129 #define randomize_va_space 0
5130 #else
5131 extern int randomize_va_space;
5132 #endif
5133 
5134 const char * arch_vma_name(struct vm_area_struct *vma);
5135 #ifdef CONFIG_MMU
5136 void print_vma_addr(char *prefix, unsigned long rip);
5137 #else
print_vma_addr(char * prefix,unsigned long rip)5138 static inline void print_vma_addr(char *prefix, unsigned long rip)
5139 {
5140 }
5141 #endif
5142 
5143 unsigned long section_map_size(void);
5144 struct page * __populate_section_memmap(unsigned long pfn,
5145 		unsigned long nr_pages, int nid, struct vmem_altmap *altmap,
5146 		struct dev_pagemap *pgmap);
5147 void *vmemmap_alloc_block(unsigned long size, int node);
5148 struct vmem_altmap;
5149 void *vmemmap_alloc_block_buf(unsigned long size, int node,
5150 			      struct vmem_altmap *altmap);
5151 void vmemmap_verify(pte_t *, int, unsigned long, unsigned long);
5152 void vmemmap_set_pmd(pmd_t *pmd, void *p, int node,
5153 		     unsigned long addr, unsigned long next);
5154 int vmemmap_check_pmd(pmd_t *pmd, int node,
5155 		      unsigned long addr, unsigned long next);
5156 int vmemmap_populate_basepages(unsigned long start, unsigned long end,
5157 			       int node, struct vmem_altmap *altmap);
5158 int vmemmap_populate_hugepages(unsigned long start, unsigned long end,
5159 			       int node, struct vmem_altmap *altmap);
5160 int vmemmap_populate(unsigned long start, unsigned long end, int node,
5161 		struct vmem_altmap *altmap);
5162 int vmemmap_populate_hvo(unsigned long start, unsigned long end,
5163 			 unsigned int order, struct zone *zone,
5164 			 unsigned long headsize);
5165 void vmemmap_wrprotect_hvo(unsigned long start, unsigned long end, int node,
5166 			  unsigned long headsize);
5167 void vmemmap_populate_print_last(void);
5168 #ifdef CONFIG_MEMORY_HOTPLUG
5169 void vmemmap_free(unsigned long start, unsigned long end,
5170 		struct vmem_altmap *altmap);
5171 #endif
5172 
5173 #ifdef CONFIG_SPARSEMEM_VMEMMAP
vmem_altmap_offset(const struct vmem_altmap * altmap)5174 static inline unsigned long vmem_altmap_offset(const struct vmem_altmap *altmap)
5175 {
5176 	/* number of pfns from base where pfn_to_page() is valid */
5177 	if (altmap)
5178 		return altmap->reserve + altmap->free;
5179 	return 0;
5180 }
5181 
vmem_altmap_free(struct vmem_altmap * altmap,unsigned long nr_pfns)5182 static inline void vmem_altmap_free(struct vmem_altmap *altmap,
5183 				    unsigned long nr_pfns)
5184 {
5185 	altmap->alloc -= nr_pfns;
5186 }
5187 #else
vmem_altmap_offset(const struct vmem_altmap * altmap)5188 static inline unsigned long vmem_altmap_offset(const struct vmem_altmap *altmap)
5189 {
5190 	return 0;
5191 }
5192 
vmem_altmap_free(struct vmem_altmap * altmap,unsigned long nr_pfns)5193 static inline void vmem_altmap_free(struct vmem_altmap *altmap,
5194 				    unsigned long nr_pfns)
5195 {
5196 }
5197 #endif
5198 
5199 #define VMEMMAP_RESERVE_NR	2
5200 #ifdef CONFIG_ARCH_WANT_OPTIMIZE_DAX_VMEMMAP
__vmemmap_can_optimize(struct vmem_altmap * altmap,struct dev_pagemap * pgmap)5201 static inline bool __vmemmap_can_optimize(struct vmem_altmap *altmap,
5202 					  struct dev_pagemap *pgmap)
5203 {
5204 	unsigned long nr_pages;
5205 	unsigned long nr_vmemmap_pages;
5206 
5207 	if (!pgmap || !is_power_of_2(sizeof(struct page)))
5208 		return false;
5209 
5210 	nr_pages = pgmap_vmemmap_nr(pgmap);
5211 	nr_vmemmap_pages = ((nr_pages * sizeof(struct page)) >> PAGE_SHIFT);
5212 	/*
5213 	 * For vmemmap optimization with DAX we need minimum 2 vmemmap
5214 	 * pages. See layout diagram in Documentation/mm/vmemmap_dedup.rst
5215 	 */
5216 	return !altmap && (nr_vmemmap_pages > VMEMMAP_RESERVE_NR);
5217 }
5218 /*
5219  * If we don't have an architecture override, use the generic rule
5220  */
5221 #ifndef vmemmap_can_optimize
5222 #define vmemmap_can_optimize __vmemmap_can_optimize
5223 #endif
5224 
5225 #else
vmemmap_can_optimize(struct vmem_altmap * altmap,struct dev_pagemap * pgmap)5226 static inline bool vmemmap_can_optimize(struct vmem_altmap *altmap,
5227 					   struct dev_pagemap *pgmap)
5228 {
5229 	return false;
5230 }
5231 #endif
5232 
5233 enum mf_flags {
5234 	MF_COUNT_INCREASED = 1 << 0,
5235 	MF_ACTION_REQUIRED = 1 << 1,
5236 	MF_MUST_KILL = 1 << 2,
5237 	MF_SOFT_OFFLINE = 1 << 3,
5238 	MF_UNPOISON = 1 << 4,
5239 	MF_SW_SIMULATED = 1 << 5,
5240 	MF_NO_RETRY = 1 << 6,
5241 	MF_MEM_PRE_REMOVE = 1 << 7,
5242 };
5243 int mf_dax_kill_procs(struct address_space *mapping, pgoff_t index,
5244 		      unsigned long count, int mf_flags);
5245 extern int memory_failure(unsigned long pfn, int flags);
5246 extern int unpoison_memory(unsigned long pfn);
5247 extern atomic_long_t num_poisoned_pages __read_mostly;
5248 extern int soft_offline_page(unsigned long pfn, int flags);
5249 #ifdef CONFIG_MEMORY_FAILURE
5250 /*
5251  * Sysfs entries for memory failure handling statistics.
5252  */
5253 extern const struct attribute_group memory_failure_attr_group;
5254 extern void memory_failure_queue(unsigned long pfn, int flags);
5255 void num_poisoned_pages_inc(unsigned long pfn);
5256 void num_poisoned_pages_sub(unsigned long pfn, long i);
5257 #else
memory_failure_queue(unsigned long pfn,int flags)5258 static inline void memory_failure_queue(unsigned long pfn, int flags)
5259 {
5260 }
5261 
num_poisoned_pages_inc(unsigned long pfn)5262 static inline void num_poisoned_pages_inc(unsigned long pfn)
5263 {
5264 }
5265 
num_poisoned_pages_sub(unsigned long pfn,long i)5266 static inline void num_poisoned_pages_sub(unsigned long pfn, long i)
5267 {
5268 }
5269 #endif
5270 
5271 #if defined(CONFIG_MEMORY_FAILURE) && defined(CONFIG_MEMORY_HOTPLUG)
5272 extern void memblk_nr_poison_inc(unsigned long pfn);
5273 extern void memblk_nr_poison_sub(unsigned long pfn, long i);
5274 #else
memblk_nr_poison_inc(unsigned long pfn)5275 static inline void memblk_nr_poison_inc(unsigned long pfn)
5276 {
5277 }
5278 
memblk_nr_poison_sub(unsigned long pfn,long i)5279 static inline void memblk_nr_poison_sub(unsigned long pfn, long i)
5280 {
5281 }
5282 #endif
5283 
5284 #ifndef arch_memory_failure
arch_memory_failure(unsigned long pfn,int flags)5285 static inline int arch_memory_failure(unsigned long pfn, int flags)
5286 {
5287 	return -ENXIO;
5288 }
5289 #endif
5290 
5291 #ifndef arch_is_platform_page
arch_is_platform_page(u64 paddr)5292 static inline bool arch_is_platform_page(u64 paddr)
5293 {
5294 	return false;
5295 }
5296 #endif
5297 
5298 /*
5299  * Error handlers for various types of pages.
5300  */
5301 enum mf_result {
5302 	MF_IGNORED,	/* Error: cannot be handled */
5303 	MF_FAILED,	/* Error: handling failed */
5304 	MF_DELAYED,	/* Will be handled later */
5305 	MF_RECOVERED,	/* Successfully recovered */
5306 };
5307 
5308 enum mf_action_page_type {
5309 	MF_MSG_KERNEL,
5310 	MF_MSG_KERNEL_HIGH_ORDER,
5311 	MF_MSG_DIFFERENT_COMPOUND,
5312 	MF_MSG_HUGE,
5313 	MF_MSG_FREE_HUGE,
5314 	MF_MSG_GET_HWPOISON,
5315 	MF_MSG_UNMAP_FAILED,
5316 	MF_MSG_DIRTY_SWAPCACHE,
5317 	MF_MSG_CLEAN_SWAPCACHE,
5318 	MF_MSG_DIRTY_MLOCKED_LRU,
5319 	MF_MSG_CLEAN_MLOCKED_LRU,
5320 	MF_MSG_DIRTY_UNEVICTABLE_LRU,
5321 	MF_MSG_CLEAN_UNEVICTABLE_LRU,
5322 	MF_MSG_DIRTY_LRU,
5323 	MF_MSG_CLEAN_LRU,
5324 	MF_MSG_TRUNCATED_LRU,
5325 	MF_MSG_BUDDY,
5326 	MF_MSG_DAX,
5327 	MF_MSG_UNSPLIT_THP,
5328 	MF_MSG_ALREADY_POISONED,
5329 	MF_MSG_PFN_MAP,
5330 	MF_MSG_UNKNOWN,
5331 };
5332 
5333 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5334 void folio_zero_user(struct folio *folio, unsigned long addr_hint);
5335 int copy_user_large_folio(struct folio *dst, struct folio *src,
5336 			  unsigned long addr_hint,
5337 			  struct vm_area_struct *vma);
5338 long copy_folio_from_user(struct folio *dst_folio,
5339 			   const void __user *usr_src,
5340 			   bool allow_pagefault);
5341 
5342 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5343 
5344 #if MAX_NUMNODES > 1
5345 void __init setup_nr_node_ids(void);
5346 #else
setup_nr_node_ids(void)5347 static inline void setup_nr_node_ids(void) {}
5348 #endif
5349 
5350 extern int memcmp_pages(struct page *page1, struct page *page2);
5351 
pages_identical(struct page * page1,struct page * page2)5352 static inline int pages_identical(struct page *page1, struct page *page2)
5353 {
5354 	return !memcmp_pages(page1, page2);
5355 }
5356 
5357 #ifdef CONFIG_MAPPING_DIRTY_HELPERS
5358 unsigned long clean_record_shared_mapping_range(struct address_space *mapping,
5359 						pgoff_t first_index, pgoff_t nr,
5360 						pgoff_t bitmap_pgoff,
5361 						unsigned long *bitmap,
5362 						pgoff_t *start,
5363 						pgoff_t *end);
5364 
5365 unsigned long wp_shared_mapping_range(struct address_space *mapping,
5366 				      pgoff_t first_index, pgoff_t nr);
5367 #endif
5368 
5369 #ifdef CONFIG_ANON_VMA_NAME
5370 int set_anon_vma_name(unsigned long addr, unsigned long size,
5371 		      const char __user *uname);
5372 #else
5373 static inline
set_anon_vma_name(unsigned long addr,unsigned long size,const char __user * uname)5374 int set_anon_vma_name(unsigned long addr, unsigned long size,
5375 		      const char __user *uname)
5376 {
5377 	return -EINVAL;
5378 }
5379 #endif
5380 
5381 #ifdef CONFIG_UNACCEPTED_MEMORY
5382 
5383 bool range_contains_unaccepted_memory(phys_addr_t start, unsigned long size);
5384 void accept_memory(phys_addr_t start, unsigned long size);
5385 
5386 #else
5387 
range_contains_unaccepted_memory(phys_addr_t start,unsigned long size)5388 static inline bool range_contains_unaccepted_memory(phys_addr_t start,
5389 						    unsigned long size)
5390 {
5391 	return false;
5392 }
5393 
accept_memory(phys_addr_t start,unsigned long size)5394 static inline void accept_memory(phys_addr_t start, unsigned long size)
5395 {
5396 }
5397 
5398 #endif
5399 
pfn_is_unaccepted_memory(unsigned long pfn)5400 static inline bool pfn_is_unaccepted_memory(unsigned long pfn)
5401 {
5402 	return range_contains_unaccepted_memory(pfn << PAGE_SHIFT, PAGE_SIZE);
5403 }
5404 
5405 void vma_pgtable_walk_begin(struct vm_area_struct *vma);
5406 void vma_pgtable_walk_end(struct vm_area_struct *vma);
5407 
5408 int reserve_mem_find_by_name(const char *name, phys_addr_t *start, phys_addr_t *size);
5409 int reserve_mem_release_by_name(const char *name);
5410 
5411 #ifdef CONFIG_64BIT
5412 void mseal_mmap_page_zero(void);
5413 #else
mseal_mmap_page_zero(void)5414 static inline void mseal_mmap_page_zero(void) {}
5415 #endif
5416 
5417 /*
5418  * user_alloc_needs_zeroing checks if a user folio from page allocator needs to
5419  * be zeroed or not.
5420  */
user_alloc_needs_zeroing(void)5421 static inline bool user_alloc_needs_zeroing(void)
5422 {
5423 	/*
5424 	 * for user folios, arch with cache aliasing requires cache flush and
5425 	 * arc changes folio->flags to make icache coherent with dcache, so
5426 	 * always return false to make caller use
5427 	 * clear_user_page()/clear_user_highpage().
5428 	 */
5429 	return cpu_dcache_is_aliasing() || cpu_icache_is_aliasing() ||
5430 	       !static_branch_maybe(CONFIG_INIT_ON_ALLOC_DEFAULT_ON,
5431 				   &init_on_alloc);
5432 }
5433 
5434 int arch_get_shadow_stack_status(struct task_struct *t, unsigned long __user *status);
5435 int arch_set_shadow_stack_status(struct task_struct *t, unsigned long status);
5436 int arch_lock_shadow_stack_status(struct task_struct *t, unsigned long status);
5437 
5438 /*
5439  * DMA mapping IDs for page_pool
5440  *
5441  * When DMA-mapping a page, page_pool allocates an ID (from an xarray) and
5442  * stashes it in the upper bits of page->pp_magic. We always want to be able to
5443  * unambiguously identify page pool pages (using page_pool_page_is_pp()). Non-PP
5444  * pages can have arbitrary kernel pointers stored in the same field as pp_magic
5445  * (since it overlaps with page->lru.next), so we must ensure that we cannot
5446  * mistake a valid kernel pointer with any of the values we write into this
5447  * field.
5448  *
5449  * On architectures that set POISON_POINTER_DELTA, this is already ensured,
5450  * since this value becomes part of PP_SIGNATURE; meaning we can just use the
5451  * space between the PP_SIGNATURE value (without POISON_POINTER_DELTA), and the
5452  * lowest bits of POISON_POINTER_DELTA. On arches where POISON_POINTER_DELTA is
5453  * 0, we use the lowest bit of PAGE_OFFSET as the boundary if that value is
5454  * known at compile-time.
5455  *
5456  * If the value of PAGE_OFFSET is not known at compile time, or if it is too
5457  * small to leave at least 8 bits available above PP_SIGNATURE, we define the
5458  * number of bits to be 0, which turns off the DMA index tracking altogether
5459  * (see page_pool_register_dma_index()).
5460  */
5461 #define PP_DMA_INDEX_SHIFT (1 + __fls(PP_SIGNATURE - POISON_POINTER_DELTA))
5462 #if POISON_POINTER_DELTA > 0
5463 /* PP_SIGNATURE includes POISON_POINTER_DELTA, so limit the size of the DMA
5464  * index to not overlap with that if set
5465  */
5466 #define PP_DMA_INDEX_BITS MIN(32, __ffs(POISON_POINTER_DELTA) - PP_DMA_INDEX_SHIFT)
5467 #else
5468 /* Use the lowest bit of PAGE_OFFSET if there's at least 8 bits available; see above */
5469 #define PP_DMA_INDEX_MIN_OFFSET (1 << (PP_DMA_INDEX_SHIFT + 8))
5470 #define PP_DMA_INDEX_BITS ((__builtin_constant_p(PAGE_OFFSET) && \
5471 			    PAGE_OFFSET >= PP_DMA_INDEX_MIN_OFFSET && \
5472 			    !(PAGE_OFFSET & (PP_DMA_INDEX_MIN_OFFSET - 1))) ? \
5473 			      MIN(32, __ffs(PAGE_OFFSET) - PP_DMA_INDEX_SHIFT) : 0)
5474 
5475 #endif
5476 
5477 #define PP_DMA_INDEX_MASK GENMASK(PP_DMA_INDEX_BITS + PP_DMA_INDEX_SHIFT - 1, \
5478 				  PP_DMA_INDEX_SHIFT)
5479 
5480 /* Mask used for checking in page_pool_page_is_pp() below. page->pp_magic is
5481  * OR'ed with PP_SIGNATURE after the allocation in order to preserve bit 0 for
5482  * the head page of compound page and bit 1 for pfmemalloc page, as well as the
5483  * bits used for the DMA index. page_is_pfmemalloc() is checked in
5484  * __page_pool_put_page() to avoid recycling the pfmemalloc page.
5485  */
5486 #define PP_MAGIC_MASK ~(PP_DMA_INDEX_MASK | 0x3UL)
5487 
5488 #ifdef CONFIG_PAGE_POOL
page_pool_page_is_pp(const struct page * page)5489 static inline bool page_pool_page_is_pp(const struct page *page)
5490 {
5491 	return (page->pp_magic & PP_MAGIC_MASK) == PP_SIGNATURE;
5492 }
5493 #else
page_pool_page_is_pp(const struct page * page)5494 static inline bool page_pool_page_is_pp(const struct page *page)
5495 {
5496 	return false;
5497 }
5498 #endif
5499 
5500 #define PAGE_SNAPSHOT_FAITHFUL (1 << 0)
5501 #define PAGE_SNAPSHOT_PG_BUDDY (1 << 1)
5502 #define PAGE_SNAPSHOT_PG_IDLE  (1 << 2)
5503 
5504 struct page_snapshot {
5505 	struct folio folio_snapshot;
5506 	struct page page_snapshot;
5507 	unsigned long pfn;
5508 	unsigned long idx;
5509 	unsigned long flags;
5510 };
5511 
snapshot_page_is_faithful(const struct page_snapshot * ps)5512 static inline bool snapshot_page_is_faithful(const struct page_snapshot *ps)
5513 {
5514 	return ps->flags & PAGE_SNAPSHOT_FAITHFUL;
5515 }
5516 
5517 void snapshot_page(struct page_snapshot *ps, const struct page *page);
5518 
5519 void map_anon_folio_pte_nopf(struct folio *folio, pte_t *pte,
5520 		struct vm_area_struct *vma, unsigned long addr,
5521 		bool uffd_wp);
5522 
5523 #endif /* _LINUX_MM_H */
5524