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