xref: /linux/include/linux/mm_types.h (revision 334fbe734e687404f346eba7d5d96ed2b44d35ab)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_MM_TYPES_H
3 #define _LINUX_MM_TYPES_H
4 
5 #include <linux/mm_types_task.h>
6 
7 #include <linux/auxvec.h>
8 #include <linux/kref.h>
9 #include <linux/list.h>
10 #include <linux/spinlock.h>
11 #include <linux/rbtree.h>
12 #include <linux/maple_tree.h>
13 #include <linux/rwsem.h>
14 #include <linux/completion.h>
15 #include <linux/cpumask.h>
16 #include <linux/uprobes.h>
17 #include <linux/rcupdate.h>
18 #include <linux/page-flags-layout.h>
19 #include <linux/workqueue.h>
20 #include <linux/seqlock.h>
21 #include <linux/percpu_counter.h>
22 #include <linux/types.h>
23 #include <linux/rseq_types.h>
24 #include <linux/bitmap.h>
25 
26 #include <asm/mmu.h>
27 
28 #ifndef AT_VECTOR_SIZE_ARCH
29 #define AT_VECTOR_SIZE_ARCH 0
30 #endif
31 #define AT_VECTOR_SIZE (2*(AT_VECTOR_SIZE_ARCH + AT_VECTOR_SIZE_BASE + 1))
32 
33 
34 struct address_space;
35 struct futex_private_hash;
36 struct mem_cgroup;
37 
38 typedef struct {
39 	unsigned long f;
40 } memdesc_flags_t;
41 
42 /*
43  * Each physical page in the system has a struct page associated with
44  * it to keep track of whatever it is we are using the page for at the
45  * moment. Note that we have no way to track which tasks are using
46  * a page, though if it is a pagecache page, rmap structures can tell us
47  * who is mapping it.
48  *
49  * If you allocate the page using alloc_pages(), you can use some of the
50  * space in struct page for your own purposes.  The five words in the main
51  * union are available, except for bit 0 of the first word which must be
52  * kept clear.  Many users use this word to store a pointer to an object
53  * which is guaranteed to be aligned.  If you use the same storage as
54  * page->mapping, you must restore it to NULL before freeing the page.
55  *
56  * The mapcount field must not be used for own purposes.
57  *
58  * If you want to use the refcount field, it must be used in such a way
59  * that other CPUs temporarily incrementing and then decrementing the
60  * refcount does not cause problems.  On receiving the page from
61  * alloc_pages(), the refcount will be positive.
62  *
63  * If you allocate pages of order > 0, you can use some of the fields
64  * in each subpage, but you may need to restore some of their values
65  * afterwards.
66  *
67  * SLUB uses cmpxchg_double() to atomically update its freelist and counters.
68  * That requires that freelist & counters in struct slab be adjacent and
69  * double-word aligned. Because struct slab currently just reinterprets the
70  * bits of struct page, we align all struct pages to double-word boundaries,
71  * and ensure that 'freelist' is aligned within struct slab.
72  */
73 #ifdef CONFIG_HAVE_ALIGNED_STRUCT_PAGE
74 #define _struct_page_alignment	__aligned(2 * sizeof(unsigned long))
75 #else
76 #define _struct_page_alignment	__aligned(sizeof(unsigned long))
77 #endif
78 
79 struct page {
80 	memdesc_flags_t flags;		/* Atomic flags, some possibly
81 					 * updated asynchronously */
82 	/*
83 	 * Five words (20/40 bytes) are available in this union.
84 	 * WARNING: bit 0 of the first word is used for PageTail(). That
85 	 * means the other users of this union MUST NOT use the bit to
86 	 * avoid collision and false-positive PageTail().
87 	 */
88 	union {
89 		struct {	/* Page cache and anonymous pages */
90 			/**
91 			 * @lru: Pageout list, eg. active_list protected by
92 			 * lruvec->lru_lock.  Sometimes used as a generic list
93 			 * by the page owner.
94 			 */
95 			union {
96 				struct list_head lru;
97 
98 				/* Or, free page */
99 				struct list_head buddy_list;
100 				struct list_head pcp_list;
101 				struct llist_node pcp_llist;
102 			};
103 			struct address_space *mapping;
104 			union {
105 				pgoff_t __folio_index;		/* Our offset within mapping. */
106 				unsigned long share;	/* share count for fsdax */
107 			};
108 			/**
109 			 * @private: Mapping-private opaque data.
110 			 * Usually used for buffer_heads if PagePrivate.
111 			 * Used for swp_entry_t if swapcache flag set.
112 			 * Indicates order in the buddy system if PageBuddy
113 			 * or on pcp_llist.
114 			 */
115 			unsigned long private;
116 		};
117 		struct {	/* page_pool used by netstack */
118 			/**
119 			 * @pp_magic: magic value to avoid recycling non
120 			 * page_pool allocated pages.
121 			 */
122 			unsigned long pp_magic;
123 			struct page_pool *pp;
124 			unsigned long _pp_mapping_pad;
125 			unsigned long dma_addr;
126 			atomic_long_t pp_ref_count;
127 		};
128 		struct {	/* Tail pages of compound page */
129 			unsigned long compound_info;	/* Bit zero is set */
130 		};
131 		struct {	/* ZONE_DEVICE pages */
132 			/*
133 			 * The first word is used for compound_info or folio
134 			 * pgmap
135 			 */
136 			void *_unused_pgmap_compound_info;
137 			void *zone_device_data;
138 			/*
139 			 * ZONE_DEVICE private pages are counted as being
140 			 * mapped so the next 3 words hold the mapping, index,
141 			 * and private fields from the source anonymous or
142 			 * page cache page while the page is migrated to device
143 			 * private memory.
144 			 * ZONE_DEVICE MEMORY_DEVICE_FS_DAX pages also
145 			 * use the mapping, index, and private fields when
146 			 * pmem backed DAX files are mapped.
147 			 */
148 		};
149 
150 		/** @rcu_head: You can use this to free a page by RCU. */
151 		struct rcu_head rcu_head;
152 	};
153 
154 	union {		/* This union is 4 bytes in size. */
155 		/*
156 		 * For head pages of typed folios, the value stored here
157 		 * allows for determining what this page is used for. The
158 		 * tail pages of typed folios will not store a type
159 		 * (page_type == _mapcount == -1).
160 		 *
161 		 * See page-flags.h for a list of page types which are currently
162 		 * stored here.
163 		 *
164 		 * Owners of typed folios may reuse the lower 16 bit of the
165 		 * head page page_type field after setting the page type,
166 		 * but must reset these 16 bit to -1 before clearing the
167 		 * page type.
168 		 */
169 		unsigned int page_type;
170 
171 		/*
172 		 * For pages that are part of non-typed folios for which mappings
173 		 * are tracked via the RMAP, encodes the number of times this page
174 		 * is directly referenced by a page table.
175 		 *
176 		 * Note that the mapcount is always initialized to -1, so that
177 		 * transitions both from it and to it can be tracked, using
178 		 * atomic_inc_and_test() and atomic_add_negative(-1).
179 		 */
180 		atomic_t _mapcount;
181 	};
182 
183 	/* Usage count. *DO NOT USE DIRECTLY*. See page_ref.h */
184 	atomic_t _refcount;
185 
186 #ifdef CONFIG_MEMCG
187 	unsigned long memcg_data;
188 #elif defined(CONFIG_SLAB_OBJ_EXT)
189 	unsigned long _unused_slab_obj_exts;
190 #endif
191 
192 	/*
193 	 * On machines where all RAM is mapped into kernel address space,
194 	 * we can simply calculate the virtual address. On machines with
195 	 * highmem some memory is mapped into kernel virtual memory
196 	 * dynamically, so we need a place to store that address.
197 	 * Note that this field could be 16 bits on x86 ... ;)
198 	 *
199 	 * Architectures with slow multiplication can define
200 	 * WANT_PAGE_VIRTUAL in asm/page.h
201 	 */
202 #if defined(WANT_PAGE_VIRTUAL)
203 	void *virtual;			/* Kernel virtual address (NULL if
204 					   not kmapped, ie. highmem) */
205 #endif /* WANT_PAGE_VIRTUAL */
206 
207 #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
208 	int _last_cpupid;
209 #endif
210 
211 #ifdef CONFIG_KMSAN
212 	/*
213 	 * KMSAN metadata for this page:
214 	 *  - shadow page: every bit indicates whether the corresponding
215 	 *    bit of the original page is initialized (0) or not (1);
216 	 *  - origin page: every 4 bytes contain an id of the stack trace
217 	 *    where the uninitialized value was created.
218 	 */
219 	struct page *kmsan_shadow;
220 	struct page *kmsan_origin;
221 #endif
222 } _struct_page_alignment;
223 
224 /*
225  * struct encoded_page - a nonexistent type marking this pointer
226  *
227  * An 'encoded_page' pointer is a pointer to a regular 'struct page', but
228  * with the low bits of the pointer indicating extra context-dependent
229  * information. Only used in mmu_gather handling, and this acts as a type
230  * system check on that use.
231  *
232  * We only really have two guaranteed bits in general, although you could
233  * play with 'struct page' alignment (see CONFIG_HAVE_ALIGNED_STRUCT_PAGE)
234  * for more.
235  *
236  * Use the supplied helper functions to endcode/decode the pointer and bits.
237  */
238 struct encoded_page;
239 
240 #define ENCODED_PAGE_BITS			3ul
241 
242 /* Perform rmap removal after we have flushed the TLB. */
243 #define ENCODED_PAGE_BIT_DELAY_RMAP		1ul
244 
245 /*
246  * The next item in an encoded_page array is the "nr_pages" argument, specifying
247  * the number of consecutive pages starting from this page, that all belong to
248  * the same folio. For example, "nr_pages" corresponds to the number of folio
249  * references that must be dropped. If this bit is not set, "nr_pages" is
250  * implicitly 1.
251  */
252 #define ENCODED_PAGE_BIT_NR_PAGES_NEXT		2ul
253 
encode_page(struct page * page,unsigned long flags)254 static __always_inline struct encoded_page *encode_page(struct page *page, unsigned long flags)
255 {
256 	BUILD_BUG_ON(flags > ENCODED_PAGE_BITS);
257 	return (struct encoded_page *)(flags | (unsigned long)page);
258 }
259 
encoded_page_flags(struct encoded_page * page)260 static inline unsigned long encoded_page_flags(struct encoded_page *page)
261 {
262 	return ENCODED_PAGE_BITS & (unsigned long)page;
263 }
264 
encoded_page_ptr(struct encoded_page * page)265 static inline struct page *encoded_page_ptr(struct encoded_page *page)
266 {
267 	return (struct page *)(~ENCODED_PAGE_BITS & (unsigned long)page);
268 }
269 
encode_nr_pages(unsigned long nr)270 static __always_inline struct encoded_page *encode_nr_pages(unsigned long nr)
271 {
272 	VM_WARN_ON_ONCE((nr << 2) >> 2 != nr);
273 	return (struct encoded_page *)(nr << 2);
274 }
275 
encoded_nr_pages(struct encoded_page * page)276 static __always_inline unsigned long encoded_nr_pages(struct encoded_page *page)
277 {
278 	return ((unsigned long)page) >> 2;
279 }
280 
281 /*
282  * A swap entry has to fit into a "unsigned long", as the entry is hidden
283  * in the "index" field of the swapper address space.
284  */
285 typedef struct {
286 	unsigned long val;
287 } swp_entry_t;
288 
289 /**
290  * typedef softleaf_t - Describes a page table software leaf entry, abstracted
291  * from its architecture-specific encoding.
292  *
293  * Page table leaf entries are those which do not reference any descendent page
294  * tables but rather either reference a data page, are an empty (or 'none'
295  * entry), or contain a non-present entry.
296  *
297  * If referencing another page table or a data page then the page table entry is
298  * pertinent to hardware - that is it tells the hardware how to decode the page
299  * table entry.
300  *
301  * Otherwise it is a software-defined leaf page table entry, which this type
302  * describes. See leafops.h and specifically @softleaf_type for a list of all
303  * possible kinds of software leaf entry.
304  *
305  * A softleaf_t entry is abstracted from the hardware page table entry, so is
306  * not architecture-specific.
307  *
308  * NOTE: While we transition from the confusing swp_entry_t type used for this
309  *       purpose, we simply alias this type. This will be removed once the
310  *       transition is complete.
311  */
312 typedef swp_entry_t softleaf_t;
313 
314 #if defined(CONFIG_MEMCG) || defined(CONFIG_SLAB_OBJ_EXT)
315 /* We have some extra room after the refcount in tail pages. */
316 #define NR_PAGES_IN_LARGE_FOLIO
317 #endif
318 
319 /*
320  * On 32bit, we can cut the required metadata in half, because:
321  * (a) PID_MAX_LIMIT implicitly limits the number of MMs we could ever have,
322  *     so we can limit MM IDs to 15 bit (32767).
323  * (b) We don't expect folios where even a single complete PTE mapping by
324  *     one MM would exceed 15 bits (order-15).
325  */
326 #ifdef CONFIG_64BIT
327 typedef int mm_id_mapcount_t;
328 #define MM_ID_MAPCOUNT_MAX		INT_MAX
329 typedef unsigned int mm_id_t;
330 #else /* !CONFIG_64BIT */
331 typedef short mm_id_mapcount_t;
332 #define MM_ID_MAPCOUNT_MAX		SHRT_MAX
333 typedef unsigned short mm_id_t;
334 #endif /* CONFIG_64BIT */
335 
336 /* We implicitly use the dummy ID for init-mm etc. where we never rmap pages. */
337 #define MM_ID_DUMMY			0
338 #define MM_ID_MIN			(MM_ID_DUMMY + 1)
339 
340 /*
341  * We leave the highest bit of each MM id unused, so we can store a flag
342  * in the highest bit of each folio->_mm_id[].
343  */
344 #define MM_ID_BITS			((sizeof(mm_id_t) * BITS_PER_BYTE) - 1)
345 #define MM_ID_MASK			((1U << MM_ID_BITS) - 1)
346 #define MM_ID_MAX			MM_ID_MASK
347 
348 /*
349  * In order to use bit_spin_lock(), which requires an unsigned long, we
350  * operate on folio->_mm_ids when working on flags.
351  */
352 #define FOLIO_MM_IDS_LOCK_BITNUM	MM_ID_BITS
353 #define FOLIO_MM_IDS_LOCK_BIT		BIT(FOLIO_MM_IDS_LOCK_BITNUM)
354 #define FOLIO_MM_IDS_SHARED_BITNUM	(2 * MM_ID_BITS + 1)
355 #define FOLIO_MM_IDS_SHARED_BIT		BIT(FOLIO_MM_IDS_SHARED_BITNUM)
356 
357 /**
358  * struct folio - Represents a contiguous set of bytes.
359  * @flags: Identical to the page flags.
360  * @lru: Least Recently Used list; tracks how recently this folio was used.
361  * @mlock_count: Number of times this folio has been pinned by mlock().
362  * @mapping: The file this page belongs to, or refers to the anon_vma for
363  *    anonymous memory.
364  * @index: Offset within the file, in units of pages.  For anonymous memory,
365  *    this is the index from the beginning of the mmap.
366  * @share: number of DAX mappings that reference this folio. See
367  *    dax_associate_entry.
368  * @private: Filesystem per-folio data (see folio_attach_private()).
369  * @swap: Used for swp_entry_t if folio_test_swapcache().
370  * @_mapcount: Do not access this member directly.  Use folio_mapcount() to
371  *    find out how many times this folio is mapped by userspace.
372  * @_refcount: Do not access this member directly.  Use folio_ref_count()
373  *    to find how many references there are to this folio.
374  * @memcg_data: Memory Control Group data.
375  * @pgmap: Metadata for ZONE_DEVICE mappings
376  * @virtual: Virtual address in the kernel direct map.
377  * @_last_cpupid: IDs of last CPU and last process that accessed the folio.
378  * @_entire_mapcount: Do not use directly, call folio_entire_mapcount().
379  * @_large_mapcount: Do not use directly, call folio_mapcount().
380  * @_nr_pages_mapped: Do not use outside of rmap and debug code.
381  * @_pincount: Do not use directly, call folio_maybe_dma_pinned().
382  * @_nr_pages: Do not use directly, call folio_nr_pages().
383  * @_mm_id: Do not use outside of rmap code.
384  * @_mm_ids: Do not use outside of rmap code.
385  * @_mm_id_mapcount: Do not use outside of rmap code.
386  * @_hugetlb_subpool: Do not use directly, use accessor in hugetlb.h.
387  * @_hugetlb_cgroup: Do not use directly, use accessor in hugetlb_cgroup.h.
388  * @_hugetlb_cgroup_rsvd: Do not use directly, use accessor in hugetlb_cgroup.h.
389  * @_hugetlb_hwpoison: Do not use directly, call raw_hwp_list_head().
390  * @_deferred_list: Folios to be split under memory pressure.
391  * @_unused_slab_obj_exts: Placeholder to match obj_exts in struct slab.
392  *
393  * A folio is a physically, virtually and logically contiguous set
394  * of bytes.  It is a power-of-two in size, and it is aligned to that
395  * same power-of-two.  It is at least as large as %PAGE_SIZE.  If it is
396  * in the page cache, it is at a file offset which is a multiple of that
397  * power-of-two.  It may be mapped into userspace at an address which is
398  * at an arbitrary page offset, but its kernel virtual address is aligned
399  * to its size.
400  */
401 struct folio {
402 	/* private: don't document the anon union */
403 	union {
404 		struct {
405 	/* public: */
406 			memdesc_flags_t flags;
407 			union {
408 				struct list_head lru;
409 	/* private: avoid cluttering the output */
410 				/* For the Unevictable "LRU list" slot */
411 				struct {
412 					/* Avoid compound_info */
413 					void *__filler;
414 	/* public: */
415 					unsigned int mlock_count;
416 	/* private: */
417 				};
418 	/* public: */
419 				struct dev_pagemap *pgmap;
420 			};
421 			struct address_space *mapping;
422 			union {
423 				pgoff_t index;
424 				unsigned long share;
425 			};
426 			union {
427 				void *private;
428 				swp_entry_t swap;
429 			};
430 			atomic_t _mapcount;
431 			atomic_t _refcount;
432 #ifdef CONFIG_MEMCG
433 			unsigned long memcg_data;
434 #elif defined(CONFIG_SLAB_OBJ_EXT)
435 			unsigned long _unused_slab_obj_exts;
436 #endif
437 #if defined(WANT_PAGE_VIRTUAL)
438 			void *virtual;
439 #endif
440 #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
441 			int _last_cpupid;
442 #endif
443 	/* private: the union with struct page is transitional */
444 		};
445 		struct page page;
446 	};
447 	union {
448 		struct {
449 			unsigned long _flags_1;
450 			unsigned long _head_1;
451 			union {
452 				struct {
453 	/* public: */
454 					atomic_t _large_mapcount;
455 					atomic_t _nr_pages_mapped;
456 #ifdef CONFIG_64BIT
457 					atomic_t _entire_mapcount;
458 					atomic_t _pincount;
459 #endif /* CONFIG_64BIT */
460 					mm_id_mapcount_t _mm_id_mapcount[2];
461 					union {
462 						mm_id_t _mm_id[2];
463 						unsigned long _mm_ids;
464 					};
465 	/* private: the union with struct page is transitional */
466 				};
467 				unsigned long _usable_1[4];
468 			};
469 			atomic_t _mapcount_1;
470 			atomic_t _refcount_1;
471 	/* public: */
472 #ifdef NR_PAGES_IN_LARGE_FOLIO
473 			unsigned int _nr_pages;
474 #endif /* NR_PAGES_IN_LARGE_FOLIO */
475 	/* private: the union with struct page is transitional */
476 		};
477 		struct page __page_1;
478 	};
479 	union {
480 		struct {
481 			unsigned long _flags_2;
482 			unsigned long _head_2;
483 	/* public: */
484 			struct list_head _deferred_list;
485 #ifndef CONFIG_64BIT
486 			atomic_t _entire_mapcount;
487 			atomic_t _pincount;
488 #endif /* !CONFIG_64BIT */
489 	/* private: the union with struct page is transitional */
490 		};
491 		struct page __page_2;
492 	};
493 	union {
494 		struct {
495 			unsigned long _flags_3;
496 			unsigned long _head_3;
497 	/* public: */
498 			void *_hugetlb_subpool;
499 			void *_hugetlb_cgroup;
500 			void *_hugetlb_cgroup_rsvd;
501 			void *_hugetlb_hwpoison;
502 	/* private: the union with struct page is transitional */
503 		};
504 		struct page __page_3;
505 	};
506 };
507 
508 #define FOLIO_MATCH(pg, fl)						\
509 	static_assert(offsetof(struct page, pg) == offsetof(struct folio, fl))
510 FOLIO_MATCH(flags, flags);
511 FOLIO_MATCH(lru, lru);
512 FOLIO_MATCH(mapping, mapping);
513 FOLIO_MATCH(compound_info, lru);
514 FOLIO_MATCH(__folio_index, index);
515 FOLIO_MATCH(private, private);
516 FOLIO_MATCH(_mapcount, _mapcount);
517 FOLIO_MATCH(_refcount, _refcount);
518 #ifdef CONFIG_MEMCG
519 FOLIO_MATCH(memcg_data, memcg_data);
520 #endif
521 #if defined(WANT_PAGE_VIRTUAL)
522 FOLIO_MATCH(virtual, virtual);
523 #endif
524 #ifdef LAST_CPUPID_NOT_IN_PAGE_FLAGS
525 FOLIO_MATCH(_last_cpupid, _last_cpupid);
526 #endif
527 #undef FOLIO_MATCH
528 #define FOLIO_MATCH(pg, fl)						\
529 	static_assert(offsetof(struct folio, fl) ==			\
530 			offsetof(struct page, pg) + sizeof(struct page))
531 FOLIO_MATCH(flags, _flags_1);
532 FOLIO_MATCH(compound_info, _head_1);
533 FOLIO_MATCH(_mapcount, _mapcount_1);
534 FOLIO_MATCH(_refcount, _refcount_1);
535 #undef FOLIO_MATCH
536 #define FOLIO_MATCH(pg, fl)						\
537 	static_assert(offsetof(struct folio, fl) ==			\
538 			offsetof(struct page, pg) + 2 * sizeof(struct page))
539 FOLIO_MATCH(flags, _flags_2);
540 FOLIO_MATCH(compound_info, _head_2);
541 #undef FOLIO_MATCH
542 #define FOLIO_MATCH(pg, fl)						\
543 	static_assert(offsetof(struct folio, fl) ==			\
544 			offsetof(struct page, pg) + 3 * sizeof(struct page))
545 FOLIO_MATCH(flags, _flags_3);
546 FOLIO_MATCH(compound_info, _head_3);
547 #undef FOLIO_MATCH
548 
549 /**
550  * struct ptdesc -    Memory descriptor for page tables.
551  * @pt_flags: enum pt_flags plus zone/node/section.
552  * @pt_rcu_head:      For freeing page table pages.
553  * @pt_list:          List of used page tables. Used for s390 gmap shadow pages
554  *                    (which are not linked into the user page tables) and x86
555  *                    pgds.
556  * @_pt_pad_1:        Padding that aliases with page's compound head.
557  * @pmd_huge_pte:     Protected by ptdesc->ptl, used for THPs.
558  * @__page_mapping:   Aliases with page->mapping. Unused for page tables.
559  * @pt_index:         Used for s390 gmap.
560  * @pt_mm:            Used for x86 pgds.
561  * @pt_frag_refcount: For fragmented page table tracking. Powerpc only.
562  * @pt_share_count:   Used for HugeTLB PMD page table share count.
563  * @_pt_pad_2:        Padding to ensure proper alignment.
564  * @ptl:              Lock for the page table.
565  * @__page_type:      Same as page->page_type. Unused for page tables.
566  * @__page_refcount:  Same as page refcount.
567  * @pt_memcg_data:    Memcg data. Tracked for page tables here.
568  *
569  * This struct overlays struct page for now. Do not modify without a good
570  * understanding of the issues.
571  */
572 struct ptdesc {
573 	memdesc_flags_t pt_flags;
574 
575 	union {
576 		struct rcu_head pt_rcu_head;
577 		struct list_head pt_list;
578 		struct {
579 			unsigned long _pt_pad_1;
580 			pgtable_t pmd_huge_pte;
581 		};
582 	};
583 	unsigned long __page_mapping;
584 
585 	union {
586 		pgoff_t pt_index;
587 		struct mm_struct *pt_mm;
588 		atomic_t pt_frag_refcount;
589 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
590 		atomic_t pt_share_count;
591 #endif
592 	};
593 
594 	union {
595 		unsigned long _pt_pad_2;
596 #if ALLOC_SPLIT_PTLOCKS
597 		spinlock_t *ptl;
598 #else
599 		spinlock_t ptl;
600 #endif
601 	};
602 	unsigned int __page_type;
603 	atomic_t __page_refcount;
604 #ifdef CONFIG_MEMCG
605 	unsigned long pt_memcg_data;
606 #endif
607 };
608 
609 #define TABLE_MATCH(pg, pt)						\
610 	static_assert(offsetof(struct page, pg) == offsetof(struct ptdesc, pt))
611 TABLE_MATCH(flags, pt_flags);
612 TABLE_MATCH(compound_info, pt_list);
613 TABLE_MATCH(compound_info, _pt_pad_1);
614 TABLE_MATCH(mapping, __page_mapping);
615 TABLE_MATCH(__folio_index, pt_index);
616 TABLE_MATCH(rcu_head, pt_rcu_head);
617 TABLE_MATCH(page_type, __page_type);
618 TABLE_MATCH(_refcount, __page_refcount);
619 #ifdef CONFIG_MEMCG
620 TABLE_MATCH(memcg_data, pt_memcg_data);
621 #endif
622 #undef TABLE_MATCH
623 static_assert(sizeof(struct ptdesc) <= sizeof(struct page));
624 
625 #define ptdesc_page(pt)			(_Generic((pt),			\
626 	const struct ptdesc *:		(const struct page *)(pt),	\
627 	struct ptdesc *:		(struct page *)(pt)))
628 
629 #define ptdesc_folio(pt)		(_Generic((pt),			\
630 	const struct ptdesc *:		(const struct folio *)(pt),	\
631 	struct ptdesc *:		(struct folio *)(pt)))
632 
633 #define page_ptdesc(p)			(_Generic((p),			\
634 	const struct page *:		(const struct ptdesc *)(p),	\
635 	struct page *:			(struct ptdesc *)(p)))
636 
637 #ifdef CONFIG_HUGETLB_PMD_PAGE_TABLE_SHARING
ptdesc_pmd_pts_init(struct ptdesc * ptdesc)638 static inline void ptdesc_pmd_pts_init(struct ptdesc *ptdesc)
639 {
640 	atomic_set(&ptdesc->pt_share_count, 0);
641 }
642 
ptdesc_pmd_pts_inc(struct ptdesc * ptdesc)643 static inline void ptdesc_pmd_pts_inc(struct ptdesc *ptdesc)
644 {
645 	atomic_inc(&ptdesc->pt_share_count);
646 }
647 
ptdesc_pmd_pts_dec(struct ptdesc * ptdesc)648 static inline void ptdesc_pmd_pts_dec(struct ptdesc *ptdesc)
649 {
650 	atomic_dec(&ptdesc->pt_share_count);
651 }
652 
ptdesc_pmd_pts_count(const struct ptdesc * ptdesc)653 static inline int ptdesc_pmd_pts_count(const struct ptdesc *ptdesc)
654 {
655 	return atomic_read(&ptdesc->pt_share_count);
656 }
657 
ptdesc_pmd_is_shared(struct ptdesc * ptdesc)658 static inline bool ptdesc_pmd_is_shared(struct ptdesc *ptdesc)
659 {
660 	return !!ptdesc_pmd_pts_count(ptdesc);
661 }
662 #else
ptdesc_pmd_pts_init(struct ptdesc * ptdesc)663 static inline void ptdesc_pmd_pts_init(struct ptdesc *ptdesc)
664 {
665 }
666 #endif
667 
668 /*
669  * Used for sizing the vmemmap region on some architectures
670  */
671 #define STRUCT_PAGE_MAX_SHIFT	(order_base_2(sizeof(struct page)))
672 
673 /*
674  * page_private can be used on tail pages.  However, PagePrivate is only
675  * checked by the VM on the head page.  So page_private on the tail pages
676  * should be used for data that's ancillary to the head page (eg attaching
677  * buffer heads to tail pages after attaching buffer heads to the head page)
678  */
679 #define page_private(page)		((page)->private)
680 
set_page_private(struct page * page,unsigned long private)681 static inline void set_page_private(struct page *page, unsigned long private)
682 {
683 	page->private = private;
684 }
685 
folio_get_private(const struct folio * folio)686 static inline void *folio_get_private(const struct folio *folio)
687 {
688 	return folio->private;
689 }
690 
691 typedef unsigned long vm_flags_t;
692 
693 /*
694  * freeptr_t represents a SLUB freelist pointer, which might be encoded
695  * and not dereferenceable if CONFIG_SLAB_FREELIST_HARDENED is enabled.
696  */
697 typedef struct { unsigned long v; } freeptr_t;
698 
699 /*
700  * A region containing a mapping of a non-memory backed file under NOMMU
701  * conditions.  These are held in a global tree and are pinned by the VMAs that
702  * map parts of them.
703  */
704 struct vm_region {
705 	struct rb_node	vm_rb;		/* link in global region tree */
706 	vm_flags_t	vm_flags;	/* VMA vm_flags */
707 	unsigned long	vm_start;	/* start address of region */
708 	unsigned long	vm_end;		/* region initialised to here */
709 	unsigned long	vm_top;		/* region allocated to here */
710 	unsigned long	vm_pgoff;	/* the offset in vm_file corresponding to vm_start */
711 	struct file	*vm_file;	/* the backing file or NULL */
712 
713 	int		vm_usage;	/* region usage count (access under nommu_region_sem) */
714 	bool		vm_icache_flushed : 1; /* true if the icache has been flushed for
715 						* this region */
716 };
717 
718 #ifdef CONFIG_USERFAULTFD
719 #define NULL_VM_UFFD_CTX ((struct vm_userfaultfd_ctx) { NULL, })
720 struct vm_userfaultfd_ctx {
721 	struct userfaultfd_ctx *ctx;
722 };
723 #else /* CONFIG_USERFAULTFD */
724 #define NULL_VM_UFFD_CTX ((struct vm_userfaultfd_ctx) {})
725 struct vm_userfaultfd_ctx {};
726 #endif /* CONFIG_USERFAULTFD */
727 
728 struct anon_vma_name {
729 	struct kref kref;
730 	/* The name needs to be at the end because it is dynamically sized. */
731 	char name[];
732 };
733 
734 #ifdef CONFIG_ANON_VMA_NAME
735 /*
736  * mmap_lock should be read-locked when calling anon_vma_name(). Caller should
737  * either keep holding the lock while using the returned pointer or it should
738  * raise anon_vma_name refcount before releasing the lock.
739  */
740 struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma);
741 struct anon_vma_name *anon_vma_name_alloc(const char *name);
742 void anon_vma_name_free(struct kref *kref);
743 #else /* CONFIG_ANON_VMA_NAME */
anon_vma_name(struct vm_area_struct * vma)744 static inline struct anon_vma_name *anon_vma_name(struct vm_area_struct *vma)
745 {
746 	return NULL;
747 }
748 
anon_vma_name_alloc(const char * name)749 static inline struct anon_vma_name *anon_vma_name_alloc(const char *name)
750 {
751 	return NULL;
752 }
753 #endif
754 
755 /*
756  * While __vma_enter_locked() is working to ensure are no read-locks held on a
757  * VMA (either while acquiring a VMA write lock or marking a VMA detached) we
758  * set the VM_REFCNT_EXCLUDE_READERS_FLAG in vma->vm_refcnt to indiciate to
759  * vma_start_read() that the reference count should be left alone.
760  *
761  * See the comment describing vm_refcnt in vm_area_struct for details as to
762  * which values the VMA reference count can be.
763  */
764 #define VM_REFCNT_EXCLUDE_READERS_BIT	(30)
765 #define VM_REFCNT_EXCLUDE_READERS_FLAG	(1U << VM_REFCNT_EXCLUDE_READERS_BIT)
766 #define VM_REFCNT_LIMIT			(VM_REFCNT_EXCLUDE_READERS_FLAG - 1)
767 
768 struct vma_numab_state {
769 	/*
770 	 * Initialised as time in 'jiffies' after which VMA
771 	 * should be scanned.  Delays first scan of new VMA by at
772 	 * least sysctl_numa_balancing_scan_delay:
773 	 */
774 	unsigned long next_scan;
775 
776 	/*
777 	 * Time in jiffies when pids_active[] is reset to
778 	 * detect phase change behaviour:
779 	 */
780 	unsigned long pids_active_reset;
781 
782 	/*
783 	 * Approximate tracking of PIDs that trapped a NUMA hinting
784 	 * fault. May produce false positives due to hash collisions.
785 	 *
786 	 *   [0] Previous PID tracking
787 	 *   [1] Current PID tracking
788 	 *
789 	 * Window moves after next_pid_reset has expired approximately
790 	 * every VMA_PID_RESET_PERIOD jiffies:
791 	 */
792 	unsigned long pids_active[2];
793 
794 	/* MM scan sequence ID when scan first started after VMA creation */
795 	int start_scan_seq;
796 
797 	/*
798 	 * MM scan sequence ID when the VMA was last completely scanned.
799 	 * A VMA is not eligible for scanning if prev_scan_seq == numa_scan_seq
800 	 */
801 	int prev_scan_seq;
802 };
803 
804 #ifdef __HAVE_PFNMAP_TRACKING
805 struct pfnmap_track_ctx {
806 	struct kref kref;
807 	unsigned long pfn;
808 	unsigned long size;	/* in bytes */
809 };
810 #endif
811 
812 /* What action should be taken after an .mmap_prepare call is complete? */
813 enum mmap_action_type {
814 	MMAP_NOTHING,		/* Mapping is complete, no further action. */
815 	MMAP_REMAP_PFN,		/* Remap PFN range. */
816 	MMAP_IO_REMAP_PFN,	/* I/O remap PFN range. */
817 	MMAP_SIMPLE_IO_REMAP,	/* I/O remap with guardrails. */
818 	MMAP_MAP_KERNEL_PAGES,	/* Map kernel page range from array. */
819 };
820 
821 /*
822  * Describes an action an mmap_prepare hook can instruct to be taken to complete
823  * the mapping of a VMA. Specified in vm_area_desc.
824  */
825 struct mmap_action {
826 	union {
827 		struct {
828 			unsigned long start;
829 			unsigned long start_pfn;
830 			unsigned long size;
831 			pgprot_t pgprot;
832 		} remap;
833 		struct {
834 			phys_addr_t start_phys_addr;
835 			unsigned long size;
836 		} simple_ioremap;
837 		struct {
838 			unsigned long start;
839 			struct page **pages;
840 			unsigned long nr_pages;
841 			pgoff_t pgoff;
842 		} map_kernel;
843 	};
844 	enum mmap_action_type type;
845 
846 	/*
847 	 * If specified, this hook is invoked after the selected action has been
848 	 * successfully completed. Note that the VMA write lock still held.
849 	 *
850 	 * The absolute minimum ought to be done here.
851 	 *
852 	 * Returns 0 on success, or an error code.
853 	 */
854 	int (*success_hook)(const struct vm_area_struct *vma);
855 
856 	/*
857 	 * If specified, this hook is invoked when an error occurred when
858 	 * attempting the selected action.
859 	 *
860 	 * The hook can return an error code in order to filter the error, but
861 	 * it is not valid to clear the error here.
862 	 */
863 	int (*error_hook)(int err);
864 
865 	/*
866 	 * This should be set in rare instances where the operation required
867 	 * that the rmap should not be able to access the VMA until
868 	 * completely set up.
869 	 */
870 	bool hide_from_rmap_until_complete :1;
871 };
872 
873 /*
874  * Opaque type representing current VMA (vm_area_struct) flag state. Must be
875  * accessed via vma_flags_xxx() helper functions.
876  */
877 #define NUM_VMA_FLAG_BITS BITS_PER_LONG
878 typedef struct {
879 	DECLARE_BITMAP(__vma_flags, NUM_VMA_FLAG_BITS);
880 } vma_flags_t;
881 
882 #define EMPTY_VMA_FLAGS ((vma_flags_t){ })
883 
884 /* Are no flags set in the specified VMA flags? */
vma_flags_empty(const vma_flags_t * flags)885 static __always_inline bool vma_flags_empty(const vma_flags_t *flags)
886 {
887 	const unsigned long *bitmap = flags->__vma_flags;
888 
889 	return bitmap_empty(bitmap, NUM_VMA_FLAG_BITS);
890 }
891 
892 /*
893  * Describes a VMA that is about to be mmap()'ed. Drivers may choose to
894  * manipulate mutable fields which will cause those fields to be updated in the
895  * resultant VMA.
896  *
897  * Helper functions are not required for manipulating any field.
898  */
899 struct vm_area_desc {
900 	/* Immutable state. */
901 	struct mm_struct *mm;
902 	struct file *file; /* May vary from vm_file in stacked callers. */
903 	unsigned long start;
904 	unsigned long end;
905 
906 	/* Mutable fields. Populated with initial state. */
907 	pgoff_t pgoff;
908 	struct file *vm_file;
909 	vma_flags_t vma_flags;
910 	pgprot_t page_prot;
911 
912 	/* Write-only fields. */
913 	const struct vm_operations_struct *vm_ops;
914 	void *private_data;
915 
916 	/* Take further action? */
917 	struct mmap_action action;
918 };
919 
920 /*
921  * This struct describes a virtual memory area. There is one of these
922  * per VM-area/task. A VM area is any part of the process virtual memory
923  * space that has a special rule for the page-fault handlers (ie a shared
924  * library, the executable area etc).
925  *
926  * Only explicitly marked struct members may be accessed by RCU readers before
927  * getting a stable reference.
928  *
929  * WARNING: when adding new members, please update vm_area_init_from() to copy
930  * them during vm_area_struct content duplication.
931  */
932 struct vm_area_struct {
933 	/* The first cache line has the info for VMA tree walking. */
934 
935 	union {
936 		struct {
937 			/* VMA covers [vm_start; vm_end) addresses within mm */
938 			unsigned long vm_start;
939 			unsigned long vm_end;
940 		};
941 		freeptr_t vm_freeptr; /* Pointer used by SLAB_TYPESAFE_BY_RCU */
942 	};
943 
944 	/*
945 	 * The address space we belong to.
946 	 * Unstable RCU readers are allowed to read this.
947 	 */
948 	struct mm_struct *vm_mm;
949 	pgprot_t vm_page_prot;          /* Access permissions of this VMA. */
950 
951 	/*
952 	 * Flags, see mm.h.
953 	 * To modify use vm_flags_{init|reset|set|clear|mod} functions.
954 	 * Preferably, use vma_flags_xxx() functions.
955 	 */
956 	union {
957 		/* Temporary while VMA flags are being converted. */
958 		const vm_flags_t vm_flags;
959 		vma_flags_t flags;
960 	};
961 
962 #ifdef CONFIG_PER_VMA_LOCK
963 	/*
964 	 * Can only be written (using WRITE_ONCE()) while holding both:
965 	 *  - mmap_lock (in write mode)
966 	 *  - vm_refcnt bit at VM_REFCNT_EXCLUDE_READERS_FLAG is set
967 	 * Can be read reliably while holding one of:
968 	 *  - mmap_lock (in read or write mode)
969 	 *  - vm_refcnt bit at VM_REFCNT_EXCLUDE_READERS_BIT is set or vm_refcnt > 1
970 	 * Can be read unreliably (using READ_ONCE()) for pessimistic bailout
971 	 * while holding nothing (except RCU to keep the VMA struct allocated).
972 	 *
973 	 * This sequence counter is explicitly allowed to overflow; sequence
974 	 * counter reuse can only lead to occasional unnecessary use of the
975 	 * slowpath.
976 	 */
977 	unsigned int vm_lock_seq;
978 #endif
979 	/*
980 	 * A file's MAP_PRIVATE vma can be in both i_mmap tree and anon_vma
981 	 * list, after a COW of one of the file pages.	A MAP_SHARED vma
982 	 * can only be in the i_mmap tree.  An anonymous MAP_PRIVATE, stack
983 	 * or brk vma (with NULL file) can only be in an anon_vma list.
984 	 */
985 	struct list_head anon_vma_chain; /* Serialized by mmap_lock &
986 					  * page_table_lock */
987 	struct anon_vma *anon_vma;	/* Serialized by page_table_lock */
988 
989 	/* Function pointers to deal with this struct. */
990 	const struct vm_operations_struct *vm_ops;
991 
992 	/* Information about our backing store: */
993 	unsigned long vm_pgoff;		/* Offset (within vm_file) in PAGE_SIZE
994 					   units */
995 	struct file * vm_file;		/* File we map to (can be NULL). */
996 	void * vm_private_data;		/* was vm_pte (shared mem) */
997 
998 #ifdef CONFIG_SWAP
999 	atomic_long_t swap_readahead_info;
1000 #endif
1001 #ifndef CONFIG_MMU
1002 	struct vm_region *vm_region;	/* NOMMU mapping region */
1003 #endif
1004 #ifdef CONFIG_NUMA
1005 	struct mempolicy *vm_policy;	/* NUMA policy for the VMA */
1006 #endif
1007 #ifdef CONFIG_NUMA_BALANCING
1008 	struct vma_numab_state *numab_state;	/* NUMA Balancing state */
1009 #endif
1010 #ifdef CONFIG_PER_VMA_LOCK
1011 	/*
1012 	 * Used to keep track of firstly, whether the VMA is attached, secondly,
1013 	 * if attached, how many read locks are taken, and thirdly, if the
1014 	 * VM_REFCNT_EXCLUDE_READERS_FLAG is set, whether any read locks held
1015 	 * are currently in the process of being excluded.
1016 	 *
1017 	 * This value can be equal to:
1018 	 *
1019 	 * 0 - Detached. IMPORTANT: when the refcnt is zero, readers cannot
1020 	 * increment it.
1021 	 *
1022 	 * 1 - Attached and either unlocked or write-locked. Write locks are
1023 	 * identified via __is_vma_write_locked() which checks for equality of
1024 	 * vma->vm_lock_seq and mm->mm_lock_seq.
1025 	 *
1026 	 * >1, < VM_REFCNT_EXCLUDE_READERS_FLAG - Read-locked or (unlikely)
1027 	 * write-locked with other threads having temporarily incremented the
1028 	 * reference count prior to determining it is write-locked and
1029 	 * decrementing it again.
1030 	 *
1031 	 * VM_REFCNT_EXCLUDE_READERS_FLAG - Detached, pending
1032 	 * __vma_end_exclude_readers() completion which will decrement the
1033 	 * reference count to zero. IMPORTANT - at this stage no further readers
1034 	 * can increment the reference count. It can only be reduced.
1035 	 *
1036 	 * VM_REFCNT_EXCLUDE_READERS_FLAG + 1 - A thread is either write-locking
1037 	 * an attached VMA and has yet to invoke __vma_end_exclude_readers(),
1038 	 * OR a thread is detaching a VMA and is waiting on a single spurious
1039 	 * reader in order to decrement the reference count. IMPORTANT - as
1040 	 * above, no further readers can increment the reference count.
1041 	 *
1042 	 * > VM_REFCNT_EXCLUDE_READERS_FLAG + 1 - A thread is either
1043 	 * write-locking or detaching a VMA is waiting on readers to
1044 	 * exit. IMPORTANT - as above, no further readers can increment the
1045 	 * reference count.
1046 	 *
1047 	 * NOTE: Unstable RCU readers are allowed to read this.
1048 	 */
1049 	refcount_t vm_refcnt ____cacheline_aligned_in_smp;
1050 #ifdef CONFIG_DEBUG_LOCK_ALLOC
1051 	struct lockdep_map vmlock_dep_map;
1052 #endif
1053 #endif
1054 	/*
1055 	 * For areas with an address space and backing store,
1056 	 * linkage into the address_space->i_mmap interval tree.
1057 	 *
1058 	 */
1059 	struct {
1060 		struct rb_node rb;
1061 		unsigned long rb_subtree_last;
1062 	} shared;
1063 #ifdef CONFIG_ANON_VMA_NAME
1064 	/*
1065 	 * For private and shared anonymous mappings, a pointer to a null
1066 	 * terminated string containing the name given to the vma, or NULL if
1067 	 * unnamed. Serialized by mmap_lock. Use anon_vma_name to access.
1068 	 */
1069 	struct anon_vma_name *anon_name;
1070 #endif
1071 	struct vm_userfaultfd_ctx vm_userfaultfd_ctx;
1072 #ifdef __HAVE_PFNMAP_TRACKING
1073 	struct pfnmap_track_ctx *pfnmap_track_ctx;
1074 #endif
1075 } __randomize_layout;
1076 
1077 /* Clears all bits in the VMA flags bitmap, non-atomically. */
vma_flags_clear_all(vma_flags_t * flags)1078 static __always_inline void vma_flags_clear_all(vma_flags_t *flags)
1079 {
1080 	bitmap_zero(flags->__vma_flags, NUM_VMA_FLAG_BITS);
1081 }
1082 
1083 /*
1084  * Helper function which converts a vma_flags_t value to a legacy vm_flags_t
1085  * value. This is only valid if the input flags value can be expressed in a
1086  * system word.
1087  *
1088  * Will be removed once the conversion to VMA flags is complete.
1089  */
vma_flags_to_legacy(vma_flags_t flags)1090 static __always_inline vm_flags_t vma_flags_to_legacy(vma_flags_t flags)
1091 {
1092 	return (vm_flags_t)flags.__vma_flags[0];
1093 }
1094 
1095 /*
1096  * Copy value to the first system word of VMA flags, non-atomically.
1097  *
1098  * IMPORTANT: This does not overwrite bytes past the first system word. The
1099  * caller must account for this.
1100  */
vma_flags_overwrite_word(vma_flags_t * flags,unsigned long value)1101 static __always_inline void vma_flags_overwrite_word(vma_flags_t *flags,
1102 		unsigned long value)
1103 {
1104 	unsigned long *bitmap = flags->__vma_flags;
1105 
1106 	bitmap[0] = value;
1107 }
1108 
1109 /*
1110  * Helper function which converts a legacy vm_flags_t value to a vma_flags_t
1111  * value.
1112  *
1113  * Will be removed once the conversion to VMA flags is complete.
1114  */
legacy_to_vma_flags(vm_flags_t flags)1115 static __always_inline vma_flags_t legacy_to_vma_flags(vm_flags_t flags)
1116 {
1117 	vma_flags_t ret = EMPTY_VMA_FLAGS;
1118 
1119 	vma_flags_overwrite_word(&ret, flags);
1120 	return ret;
1121 }
1122 
1123 /*
1124  * Copy value to the first system word of VMA flags ONCE, non-atomically.
1125  *
1126  * IMPORTANT: This does not overwrite bytes past the first system word. The
1127  * caller must account for this.
1128  */
vma_flags_overwrite_word_once(vma_flags_t * flags,unsigned long value)1129 static __always_inline void vma_flags_overwrite_word_once(vma_flags_t *flags,
1130 		unsigned long value)
1131 {
1132 	unsigned long *bitmap = flags->__vma_flags;
1133 
1134 	WRITE_ONCE(*bitmap, value);
1135 }
1136 
1137 /* Update the first system word of VMA flags setting bits, non-atomically. */
vma_flags_set_word(vma_flags_t * flags,unsigned long value)1138 static __always_inline void vma_flags_set_word(vma_flags_t *flags,
1139 		unsigned long value)
1140 {
1141 	unsigned long *bitmap = flags->__vma_flags;
1142 
1143 	*bitmap |= value;
1144 }
1145 
1146 /* Update the first system word of VMA flags clearing bits, non-atomically. */
vma_flags_clear_word(vma_flags_t * flags,unsigned long value)1147 static __always_inline void vma_flags_clear_word(vma_flags_t *flags,
1148 		unsigned long value)
1149 {
1150 	unsigned long *bitmap = flags->__vma_flags;
1151 
1152 	*bitmap &= ~value;
1153 }
1154 
1155 #ifdef CONFIG_NUMA
1156 #define vma_policy(vma) ((vma)->vm_policy)
1157 #else
1158 #define vma_policy(vma) NULL
1159 #endif
1160 
1161 /*
1162  * Opaque type representing current mm_struct flag state. Must be accessed via
1163  * mm_flags_xxx() helper functions.
1164  */
1165 #define NUM_MM_FLAG_BITS (64)
1166 typedef struct {
1167 	DECLARE_BITMAP(__mm_flags, NUM_MM_FLAG_BITS);
1168 } __private mm_flags_t;
1169 
1170 struct kioctx_table;
1171 struct iommu_mm_data;
1172 struct mm_struct {
1173 	struct {
1174 		/*
1175 		 * Fields which are often written to are placed in a separate
1176 		 * cache line.
1177 		 */
1178 		struct {
1179 			/**
1180 			 * @mm_count: The number of references to &struct
1181 			 * mm_struct (@mm_users count as 1).
1182 			 *
1183 			 * Use mmgrab()/mmdrop() to modify. When this drops to
1184 			 * 0, the &struct mm_struct is freed.
1185 			 */
1186 			atomic_t mm_count;
1187 		} ____cacheline_aligned_in_smp;
1188 
1189 		struct maple_tree mm_mt;
1190 
1191 		unsigned long mmap_base;	/* base of mmap area */
1192 		unsigned long mmap_legacy_base;	/* base of mmap area in bottom-up allocations */
1193 #ifdef CONFIG_HAVE_ARCH_COMPAT_MMAP_BASES
1194 		/* Base addresses for compatible mmap() */
1195 		unsigned long mmap_compat_base;
1196 		unsigned long mmap_compat_legacy_base;
1197 #endif
1198 		unsigned long task_size;	/* size of task vm space */
1199 		pgd_t * pgd;
1200 
1201 #ifdef CONFIG_MEMBARRIER
1202 		/**
1203 		 * @membarrier_state: Flags controlling membarrier behavior.
1204 		 *
1205 		 * This field is close to @pgd to hopefully fit in the same
1206 		 * cache-line, which needs to be touched by switch_mm().
1207 		 */
1208 		atomic_t membarrier_state;
1209 #endif
1210 
1211 		/**
1212 		 * @mm_users: The number of users including userspace.
1213 		 *
1214 		 * Use mmget()/mmget_not_zero()/mmput() to modify. When this
1215 		 * drops to 0 (i.e. when the task exits and there are no other
1216 		 * temporary reference holders), we also release a reference on
1217 		 * @mm_count (which may then free the &struct mm_struct if
1218 		 * @mm_count also drops to 0).
1219 		 */
1220 		atomic_t mm_users;
1221 
1222 		/* MM CID related storage */
1223 		struct mm_mm_cid mm_cid;
1224 
1225 #ifdef CONFIG_MMU
1226 		atomic_long_t pgtables_bytes;	/* size of all page tables */
1227 #endif
1228 		int map_count;			/* number of VMAs */
1229 
1230 		spinlock_t page_table_lock; /* Protects page tables and some
1231 					     * counters
1232 					     */
1233 		/*
1234 		 * Typically the current mmap_lock's offset is 56 bytes from
1235 		 * the last cacheline boundary, which is very optimal, as
1236 		 * its two hot fields 'count' and 'owner' sit in 2 different
1237 		 * cachelines, and when mmap_lock is highly contended, both
1238 		 * of the 2 fields will be accessed frequently, current layout
1239 		 * will help to reduce cache bouncing.
1240 		 *
1241 		 * So please be careful with adding new fields before
1242 		 * mmap_lock, which can easily push the 2 fields into one
1243 		 * cacheline.
1244 		 */
1245 		struct rw_semaphore mmap_lock;
1246 
1247 		struct list_head mmlist; /* List of maybe swapped mm's.	These
1248 					  * are globally strung together off
1249 					  * init_mm.mmlist, and are protected
1250 					  * by mmlist_lock
1251 					  */
1252 #ifdef CONFIG_PER_VMA_LOCK
1253 		struct rcuwait vma_writer_wait;
1254 		/*
1255 		 * This field has lock-like semantics, meaning it is sometimes
1256 		 * accessed with ACQUIRE/RELEASE semantics.
1257 		 * Roughly speaking, incrementing the sequence number is
1258 		 * equivalent to releasing locks on VMAs; reading the sequence
1259 		 * number can be part of taking a read lock on a VMA.
1260 		 * Incremented every time mmap_lock is write-locked/unlocked.
1261 		 * Initialized to 0, therefore odd values indicate mmap_lock
1262 		 * is write-locked and even values that it's released.
1263 		 *
1264 		 * Can be modified under write mmap_lock using RELEASE
1265 		 * semantics.
1266 		 * Can be read with no other protection when holding write
1267 		 * mmap_lock.
1268 		 * Can be read with ACQUIRE semantics if not holding write
1269 		 * mmap_lock.
1270 		 */
1271 		seqcount_t mm_lock_seq;
1272 #endif
1273 #ifdef CONFIG_FUTEX_PRIVATE_HASH
1274 		struct mutex			futex_hash_lock;
1275 		struct futex_private_hash	__rcu *futex_phash;
1276 		struct futex_private_hash	*futex_phash_new;
1277 		/* futex-ref */
1278 		unsigned long			futex_batches;
1279 		struct rcu_head			futex_rcu;
1280 		atomic_long_t			futex_atomic;
1281 		unsigned int			__percpu *futex_ref;
1282 #endif
1283 
1284 		unsigned long hiwater_rss; /* High-watermark of RSS usage */
1285 		unsigned long hiwater_vm;  /* High-water virtual memory usage */
1286 
1287 		unsigned long total_vm;	   /* Total pages mapped */
1288 		unsigned long locked_vm;   /* Pages that have PG_mlocked set */
1289 		atomic64_t    pinned_vm;   /* Refcount permanently increased */
1290 		unsigned long data_vm;	   /* VM_WRITE & ~VM_SHARED & ~VM_STACK */
1291 		unsigned long exec_vm;	   /* VM_EXEC & ~VM_WRITE & ~VM_STACK */
1292 		unsigned long stack_vm;	   /* VM_STACK */
1293 		union {
1294 			/* Temporary while VMA flags are being converted. */
1295 			vm_flags_t def_flags;
1296 			vma_flags_t def_vma_flags;
1297 		};
1298 
1299 		/**
1300 		 * @write_protect_seq: Locked when any thread is write
1301 		 * protecting pages mapped by this mm to enforce a later COW,
1302 		 * for instance during page table copying for fork().
1303 		 */
1304 		seqcount_t write_protect_seq;
1305 
1306 		spinlock_t arg_lock; /* protect the below fields */
1307 
1308 		unsigned long start_code, end_code, start_data, end_data;
1309 		unsigned long start_brk, brk, start_stack;
1310 		unsigned long arg_start, arg_end, env_start, env_end;
1311 
1312 		unsigned long saved_auxv[AT_VECTOR_SIZE]; /* for /proc/PID/auxv */
1313 
1314 #ifdef CONFIG_ARCH_HAS_ELF_CORE_EFLAGS
1315 		/* the ABI-related flags from the ELF header. Used for core dump */
1316 		unsigned long saved_e_flags;
1317 #endif
1318 
1319 		struct percpu_counter rss_stat[NR_MM_COUNTERS];
1320 
1321 		struct linux_binfmt *binfmt;
1322 
1323 		/* Architecture-specific MM context */
1324 		mm_context_t context;
1325 
1326 		mm_flags_t flags; /* Must use mm_flags_* hlpers to access */
1327 
1328 #ifdef CONFIG_AIO
1329 		spinlock_t			ioctx_lock;
1330 		struct kioctx_table __rcu	*ioctx_table;
1331 #endif
1332 #ifdef CONFIG_MEMCG
1333 		/*
1334 		 * "owner" points to a task that is regarded as the canonical
1335 		 * user/owner of this mm. All of the following must be true in
1336 		 * order for it to be changed:
1337 		 *
1338 		 * current == mm->owner
1339 		 * current->mm != mm
1340 		 * new_owner->mm == mm
1341 		 * new_owner->alloc_lock is held
1342 		 */
1343 		struct task_struct __rcu *owner;
1344 #endif
1345 		struct user_namespace *user_ns;
1346 
1347 		/* store ref to file /proc/<pid>/exe symlink points to */
1348 		struct file __rcu *exe_file;
1349 #ifdef CONFIG_MMU_NOTIFIER
1350 		struct mmu_notifier_subscriptions *notifier_subscriptions;
1351 #endif
1352 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && !defined(CONFIG_SPLIT_PMD_PTLOCKS)
1353 		pgtable_t pmd_huge_pte; /* protected by page_table_lock */
1354 #endif
1355 #ifdef CONFIG_NUMA_BALANCING
1356 		/*
1357 		 * numa_next_scan is the next time that PTEs will be remapped
1358 		 * PROT_NONE to trigger NUMA hinting faults; such faults gather
1359 		 * statistics and migrate pages to new nodes if necessary.
1360 		 */
1361 		unsigned long numa_next_scan;
1362 
1363 		/* Restart point for scanning and remapping PTEs. */
1364 		unsigned long numa_scan_offset;
1365 
1366 		/* numa_scan_seq prevents two threads remapping PTEs. */
1367 		int numa_scan_seq;
1368 #endif
1369 		/*
1370 		 * An operation with batched TLB flushing is going on. Anything
1371 		 * that can move process memory needs to flush the TLB when
1372 		 * moving a PROT_NONE mapped page.
1373 		 */
1374 		atomic_t tlb_flush_pending;
1375 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1376 		/* See flush_tlb_batched_pending() */
1377 		atomic_t tlb_flush_batched;
1378 #endif
1379 		struct uprobes_state uprobes_state;
1380 #ifdef CONFIG_PREEMPT_RT
1381 		struct rcu_head delayed_drop;
1382 #endif
1383 #ifdef CONFIG_HUGETLB_PAGE
1384 		atomic_long_t hugetlb_usage;
1385 #endif
1386 		struct work_struct async_put_work;
1387 
1388 #ifdef CONFIG_IOMMU_MM_DATA
1389 		struct iommu_mm_data *iommu_mm;
1390 #endif
1391 #ifdef CONFIG_KSM
1392 		/*
1393 		 * Represent how many pages of this process are involved in KSM
1394 		 * merging (not including ksm_zero_pages).
1395 		 */
1396 		unsigned long ksm_merging_pages;
1397 		/*
1398 		 * Represent how many pages are checked for ksm merging
1399 		 * including merged and not merged.
1400 		 */
1401 		unsigned long ksm_rmap_items;
1402 		/*
1403 		 * Represent how many empty pages are merged with kernel zero
1404 		 * pages when enabling KSM use_zero_pages.
1405 		 */
1406 		atomic_long_t ksm_zero_pages;
1407 #endif /* CONFIG_KSM */
1408 #ifdef CONFIG_LRU_GEN_WALKS_MMU
1409 		struct {
1410 			/* this mm_struct is on lru_gen_mm_list */
1411 			struct list_head list;
1412 			/*
1413 			 * Set when switching to this mm_struct, as a hint of
1414 			 * whether it has been used since the last time per-node
1415 			 * page table walkers cleared the corresponding bits.
1416 			 */
1417 			unsigned long bitmap;
1418 #ifdef CONFIG_MEMCG
1419 			/* points to the memcg of "owner" above */
1420 			struct mem_cgroup *memcg;
1421 #endif
1422 		} lru_gen;
1423 #endif /* CONFIG_LRU_GEN_WALKS_MMU */
1424 #ifdef CONFIG_MM_ID
1425 		mm_id_t mm_id;
1426 #endif /* CONFIG_MM_ID */
1427 	} __randomize_layout;
1428 
1429 	/*
1430 	 * The mm_cpumask needs to be at the end of mm_struct, because it
1431 	 * is dynamically sized based on nr_cpu_ids.
1432 	 */
1433 	char flexible_array[] __aligned(__alignof__(unsigned long));
1434 };
1435 
1436 /* Copy value to the first system word of mm flags, non-atomically. */
__mm_flags_overwrite_word(struct mm_struct * mm,unsigned long value)1437 static inline void __mm_flags_overwrite_word(struct mm_struct *mm, unsigned long value)
1438 {
1439 	*ACCESS_PRIVATE(&mm->flags, __mm_flags) = value;
1440 }
1441 
1442 /* Obtain a read-only view of the mm flags bitmap. */
__mm_flags_get_bitmap(const struct mm_struct * mm)1443 static inline const unsigned long *__mm_flags_get_bitmap(const struct mm_struct *mm)
1444 {
1445 	return (const unsigned long *)ACCESS_PRIVATE(&mm->flags, __mm_flags);
1446 }
1447 
1448 /* Read the first system word of mm flags, non-atomically. */
__mm_flags_get_word(const struct mm_struct * mm)1449 static inline unsigned long __mm_flags_get_word(const struct mm_struct *mm)
1450 {
1451 	return *__mm_flags_get_bitmap(mm);
1452 }
1453 
1454 /*
1455  * Update the first system word of mm flags ONLY, applying the specified mask to
1456  * it, then setting all flags specified by bits.
1457  */
__mm_flags_set_mask_bits_word(struct mm_struct * mm,unsigned long mask,unsigned long bits)1458 static inline void __mm_flags_set_mask_bits_word(struct mm_struct *mm,
1459 		unsigned long mask, unsigned long bits)
1460 {
1461 	unsigned long *bitmap = ACCESS_PRIVATE(&mm->flags, __mm_flags);
1462 
1463 	set_mask_bits(bitmap, mask, bits);
1464 }
1465 
1466 #define MM_MT_FLAGS	(MT_FLAGS_ALLOC_RANGE | MT_FLAGS_LOCK_EXTERN | \
1467 			 MT_FLAGS_USE_RCU)
1468 extern struct mm_struct init_mm;
1469 
1470 #define MM_STRUCT_FLEXIBLE_ARRAY_INIT				\
1471 {								\
1472 	[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0	\
1473 }
1474 
1475 /* Pointer magic because the dynamic array size confuses some compilers. */
mm_init_cpumask(struct mm_struct * mm)1476 static inline void mm_init_cpumask(struct mm_struct *mm)
1477 {
1478 	unsigned long cpu_bitmap = (unsigned long)mm;
1479 
1480 	cpu_bitmap += offsetof(struct mm_struct, flexible_array);
1481 	cpumask_clear((struct cpumask *)cpu_bitmap);
1482 }
1483 
1484 /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
mm_cpumask(struct mm_struct * mm)1485 static inline cpumask_t *mm_cpumask(struct mm_struct *mm)
1486 {
1487 	return (struct cpumask *)&mm->flexible_array;
1488 }
1489 
1490 #ifdef CONFIG_LRU_GEN
1491 
1492 struct lru_gen_mm_list {
1493 	/* mm_struct list for page table walkers */
1494 	struct list_head fifo;
1495 	/* protects the list above */
1496 	spinlock_t lock;
1497 };
1498 
1499 #endif /* CONFIG_LRU_GEN */
1500 
1501 #ifdef CONFIG_LRU_GEN_WALKS_MMU
1502 
1503 void lru_gen_add_mm(struct mm_struct *mm);
1504 void lru_gen_del_mm(struct mm_struct *mm);
1505 void lru_gen_migrate_mm(struct mm_struct *mm);
1506 
lru_gen_init_mm(struct mm_struct * mm)1507 static inline void lru_gen_init_mm(struct mm_struct *mm)
1508 {
1509 	INIT_LIST_HEAD(&mm->lru_gen.list);
1510 	mm->lru_gen.bitmap = 0;
1511 #ifdef CONFIG_MEMCG
1512 	mm->lru_gen.memcg = NULL;
1513 #endif
1514 }
1515 
lru_gen_use_mm(struct mm_struct * mm)1516 static inline void lru_gen_use_mm(struct mm_struct *mm)
1517 {
1518 	/*
1519 	 * When the bitmap is set, page reclaim knows this mm_struct has been
1520 	 * used since the last time it cleared the bitmap. So it might be worth
1521 	 * walking the page tables of this mm_struct to clear the accessed bit.
1522 	 */
1523 	WRITE_ONCE(mm->lru_gen.bitmap, -1);
1524 }
1525 
1526 #else /* !CONFIG_LRU_GEN_WALKS_MMU */
1527 
lru_gen_add_mm(struct mm_struct * mm)1528 static inline void lru_gen_add_mm(struct mm_struct *mm)
1529 {
1530 }
1531 
lru_gen_del_mm(struct mm_struct * mm)1532 static inline void lru_gen_del_mm(struct mm_struct *mm)
1533 {
1534 }
1535 
lru_gen_migrate_mm(struct mm_struct * mm)1536 static inline void lru_gen_migrate_mm(struct mm_struct *mm)
1537 {
1538 }
1539 
lru_gen_init_mm(struct mm_struct * mm)1540 static inline void lru_gen_init_mm(struct mm_struct *mm)
1541 {
1542 }
1543 
lru_gen_use_mm(struct mm_struct * mm)1544 static inline void lru_gen_use_mm(struct mm_struct *mm)
1545 {
1546 }
1547 
1548 #endif /* CONFIG_LRU_GEN_WALKS_MMU */
1549 
1550 struct vma_iterator {
1551 	struct ma_state mas;
1552 };
1553 
1554 #define VMA_ITERATOR(name, __mm, __addr)				\
1555 	struct vma_iterator name = {					\
1556 		.mas = {						\
1557 			.tree = &(__mm)->mm_mt,				\
1558 			.index = __addr,				\
1559 			.node = NULL,					\
1560 			.status = ma_start,				\
1561 		},							\
1562 	}
1563 
vma_iter_init(struct vma_iterator * vmi,struct mm_struct * mm,unsigned long addr)1564 static inline void vma_iter_init(struct vma_iterator *vmi,
1565 		struct mm_struct *mm, unsigned long addr)
1566 {
1567 	mas_init(&vmi->mas, &mm->mm_mt, addr);
1568 }
1569 
1570 #ifdef CONFIG_SCHED_MM_CID
1571 /*
1572  * mm_cpus_allowed: Union of all mm's threads allowed CPUs.
1573  */
mm_cpus_allowed(struct mm_struct * mm)1574 static inline cpumask_t *mm_cpus_allowed(struct mm_struct *mm)
1575 {
1576 	unsigned long bitmap = (unsigned long)mm;
1577 
1578 	bitmap += offsetof(struct mm_struct, flexible_array);
1579 	/* Skip cpu_bitmap */
1580 	bitmap += cpumask_size();
1581 	return (struct cpumask *)bitmap;
1582 }
1583 
1584 /* Accessor for struct mm_struct's cidmask. */
mm_cidmask(struct mm_struct * mm)1585 static inline unsigned long *mm_cidmask(struct mm_struct *mm)
1586 {
1587 	unsigned long cid_bitmap = (unsigned long)mm_cpus_allowed(mm);
1588 
1589 	/* Skip mm_cpus_allowed */
1590 	cid_bitmap += cpumask_size();
1591 	return (unsigned long *)cid_bitmap;
1592 }
1593 
1594 void mm_init_cid(struct mm_struct *mm, struct task_struct *p);
1595 
mm_alloc_cid_noprof(struct mm_struct * mm,struct task_struct * p)1596 static inline int mm_alloc_cid_noprof(struct mm_struct *mm, struct task_struct *p)
1597 {
1598 	mm->mm_cid.pcpu = alloc_percpu_noprof(struct mm_cid_pcpu);
1599 	if (!mm->mm_cid.pcpu)
1600 		return -ENOMEM;
1601 	mm_init_cid(mm, p);
1602 	return 0;
1603 }
1604 # define mm_alloc_cid(...)	alloc_hooks(mm_alloc_cid_noprof(__VA_ARGS__))
1605 
mm_destroy_cid(struct mm_struct * mm)1606 static inline void mm_destroy_cid(struct mm_struct *mm)
1607 {
1608 	free_percpu(mm->mm_cid.pcpu);
1609 	mm->mm_cid.pcpu = NULL;
1610 }
1611 
mm_cid_size(void)1612 static inline unsigned int mm_cid_size(void)
1613 {
1614 	/* mm_cpus_allowed(), mm_cidmask(). */
1615 	return cpumask_size() + bitmap_size(num_possible_cpus());
1616 }
1617 
1618 /* Use 2 * NR_CPUS as worse case for static allocation. */
1619 # define MM_CID_STATIC_SIZE	(2 * sizeof(cpumask_t))
1620 #else /* CONFIG_SCHED_MM_CID */
mm_init_cid(struct mm_struct * mm,struct task_struct * p)1621 static inline void mm_init_cid(struct mm_struct *mm, struct task_struct *p) { }
mm_alloc_cid(struct mm_struct * mm,struct task_struct * p)1622 static inline int mm_alloc_cid(struct mm_struct *mm, struct task_struct *p) { return 0; }
mm_destroy_cid(struct mm_struct * mm)1623 static inline void mm_destroy_cid(struct mm_struct *mm) { }
mm_cid_size(void)1624 static inline unsigned int mm_cid_size(void)
1625 {
1626 	return 0;
1627 }
1628 # define MM_CID_STATIC_SIZE	0
1629 #endif /* CONFIG_SCHED_MM_CID */
1630 
1631 struct mmu_gather;
1632 extern void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm);
1633 extern void tlb_gather_mmu_fullmm(struct mmu_gather *tlb, struct mm_struct *mm);
1634 void tlb_gather_mmu_vma(struct mmu_gather *tlb, struct vm_area_struct *vma);
1635 extern void tlb_finish_mmu(struct mmu_gather *tlb);
1636 
1637 struct vm_fault;
1638 
1639 /**
1640  * typedef vm_fault_t - Return type for page fault handlers.
1641  *
1642  * Page fault handlers return a bitmask of %VM_FAULT values.
1643  */
1644 typedef __bitwise unsigned int vm_fault_t;
1645 
1646 /**
1647  * enum vm_fault_reason - Page fault handlers return a bitmask of
1648  * these values to tell the core VM what happened when handling the
1649  * fault. Used to decide whether a process gets delivered SIGBUS or
1650  * just gets major/minor fault counters bumped up.
1651  *
1652  * @VM_FAULT_OOM:		Out Of Memory
1653  * @VM_FAULT_SIGBUS:		Bad access
1654  * @VM_FAULT_MAJOR:		Page read from storage
1655  * @VM_FAULT_HWPOISON:		Hit poisoned small page
1656  * @VM_FAULT_HWPOISON_LARGE:	Hit poisoned large page. Index encoded
1657  *				in upper bits
1658  * @VM_FAULT_SIGSEGV:		segmentation fault
1659  * @VM_FAULT_NOPAGE:		->fault installed the pte, not return page
1660  * @VM_FAULT_LOCKED:		->fault locked the returned page
1661  * @VM_FAULT_RETRY:		->fault blocked, must retry
1662  * @VM_FAULT_FALLBACK:		huge page fault failed, fall back to small
1663  * @VM_FAULT_DONE_COW:		->fault has fully handled COW
1664  * @VM_FAULT_NEEDDSYNC:		->fault did not modify page tables and needs
1665  *				fsync() to complete (for synchronous page faults
1666  *				in DAX)
1667  * @VM_FAULT_COMPLETED:		->fault completed, meanwhile mmap lock released
1668  * @VM_FAULT_HINDEX_MASK:	mask HINDEX value
1669  *
1670  */
1671 enum vm_fault_reason {
1672 	VM_FAULT_OOM            = (__force vm_fault_t)0x000001,
1673 	VM_FAULT_SIGBUS         = (__force vm_fault_t)0x000002,
1674 	VM_FAULT_MAJOR          = (__force vm_fault_t)0x000004,
1675 	VM_FAULT_HWPOISON       = (__force vm_fault_t)0x000010,
1676 	VM_FAULT_HWPOISON_LARGE = (__force vm_fault_t)0x000020,
1677 	VM_FAULT_SIGSEGV        = (__force vm_fault_t)0x000040,
1678 	VM_FAULT_NOPAGE         = (__force vm_fault_t)0x000100,
1679 	VM_FAULT_LOCKED         = (__force vm_fault_t)0x000200,
1680 	VM_FAULT_RETRY          = (__force vm_fault_t)0x000400,
1681 	VM_FAULT_FALLBACK       = (__force vm_fault_t)0x000800,
1682 	VM_FAULT_DONE_COW       = (__force vm_fault_t)0x001000,
1683 	VM_FAULT_NEEDDSYNC      = (__force vm_fault_t)0x002000,
1684 	VM_FAULT_COMPLETED      = (__force vm_fault_t)0x004000,
1685 	VM_FAULT_HINDEX_MASK    = (__force vm_fault_t)0x0f0000,
1686 };
1687 
1688 /* Encode hstate index for a hwpoisoned large page */
1689 #define VM_FAULT_SET_HINDEX(x) ((__force vm_fault_t)((x) << 16))
1690 #define VM_FAULT_GET_HINDEX(x) (((__force unsigned int)(x) >> 16) & 0xf)
1691 
1692 #define VM_FAULT_ERROR (VM_FAULT_OOM | VM_FAULT_SIGBUS |	\
1693 			VM_FAULT_SIGSEGV | VM_FAULT_HWPOISON |	\
1694 			VM_FAULT_HWPOISON_LARGE | VM_FAULT_FALLBACK)
1695 
1696 #define VM_FAULT_RESULT_TRACE \
1697 	{ VM_FAULT_OOM,                 "OOM" },	\
1698 	{ VM_FAULT_SIGBUS,              "SIGBUS" },	\
1699 	{ VM_FAULT_MAJOR,               "MAJOR" },	\
1700 	{ VM_FAULT_HWPOISON,            "HWPOISON" },	\
1701 	{ VM_FAULT_HWPOISON_LARGE,      "HWPOISON_LARGE" },	\
1702 	{ VM_FAULT_SIGSEGV,             "SIGSEGV" },	\
1703 	{ VM_FAULT_NOPAGE,              "NOPAGE" },	\
1704 	{ VM_FAULT_LOCKED,              "LOCKED" },	\
1705 	{ VM_FAULT_RETRY,               "RETRY" },	\
1706 	{ VM_FAULT_FALLBACK,            "FALLBACK" },	\
1707 	{ VM_FAULT_DONE_COW,            "DONE_COW" },	\
1708 	{ VM_FAULT_NEEDDSYNC,           "NEEDDSYNC" },	\
1709 	{ VM_FAULT_COMPLETED,           "COMPLETED" }
1710 
1711 struct vm_special_mapping {
1712 	const char *name;	/* The name, e.g. "[vdso]". */
1713 
1714 	/*
1715 	 * If .fault is not provided, this points to a
1716 	 * NULL-terminated array of pages that back the special mapping.
1717 	 *
1718 	 * This must not be NULL unless .fault is provided.
1719 	 */
1720 	struct page **pages;
1721 
1722 	/*
1723 	 * If non-NULL, then this is called to resolve page faults
1724 	 * on the special mapping.  If used, .pages is not checked.
1725 	 */
1726 	vm_fault_t (*fault)(const struct vm_special_mapping *sm,
1727 				struct vm_area_struct *vma,
1728 				struct vm_fault *vmf);
1729 
1730 	int (*mremap)(const struct vm_special_mapping *sm,
1731 		     struct vm_area_struct *new_vma);
1732 
1733 	void (*close)(const struct vm_special_mapping *sm,
1734 		      struct vm_area_struct *vma);
1735 };
1736 
1737 enum tlb_flush_reason {
1738 	TLB_FLUSH_ON_TASK_SWITCH,
1739 	TLB_REMOTE_SHOOTDOWN,
1740 	TLB_LOCAL_SHOOTDOWN,
1741 	TLB_LOCAL_MM_SHOOTDOWN,
1742 	TLB_REMOTE_SEND_IPI,
1743 	TLB_REMOTE_WRONG_CPU,
1744 };
1745 
1746 /**
1747  * enum fault_flag - Fault flag definitions.
1748  * @FAULT_FLAG_WRITE: Fault was a write fault.
1749  * @FAULT_FLAG_MKWRITE: Fault was mkwrite of existing PTE.
1750  * @FAULT_FLAG_ALLOW_RETRY: Allow to retry the fault if blocked.
1751  * @FAULT_FLAG_RETRY_NOWAIT: Don't drop mmap_lock and wait when retrying.
1752  * @FAULT_FLAG_KILLABLE: The fault task is in SIGKILL killable region.
1753  * @FAULT_FLAG_TRIED: The fault has been tried once.
1754  * @FAULT_FLAG_USER: The fault originated in userspace.
1755  * @FAULT_FLAG_REMOTE: The fault is not for current task/mm.
1756  * @FAULT_FLAG_INSTRUCTION: The fault was during an instruction fetch.
1757  * @FAULT_FLAG_INTERRUPTIBLE: The fault can be interrupted by non-fatal signals.
1758  * @FAULT_FLAG_UNSHARE: The fault is an unsharing request to break COW in a
1759  *                      COW mapping, making sure that an exclusive anon page is
1760  *                      mapped after the fault.
1761  * @FAULT_FLAG_ORIG_PTE_VALID: whether the fault has vmf->orig_pte cached.
1762  *                        We should only access orig_pte if this flag set.
1763  * @FAULT_FLAG_VMA_LOCK: The fault is handled under VMA lock.
1764  *
1765  * About @FAULT_FLAG_ALLOW_RETRY and @FAULT_FLAG_TRIED: we can specify
1766  * whether we would allow page faults to retry by specifying these two
1767  * fault flags correctly.  Currently there can be three legal combinations:
1768  *
1769  * (a) ALLOW_RETRY and !TRIED:  this means the page fault allows retry, and
1770  *                              this is the first try
1771  *
1772  * (b) ALLOW_RETRY and TRIED:   this means the page fault allows retry, and
1773  *                              we've already tried at least once
1774  *
1775  * (c) !ALLOW_RETRY and !TRIED: this means the page fault does not allow retry
1776  *
1777  * The unlisted combination (!ALLOW_RETRY && TRIED) is illegal and should never
1778  * be used.  Note that page faults can be allowed to retry for multiple times,
1779  * in which case we'll have an initial fault with flags (a) then later on
1780  * continuous faults with flags (b).  We should always try to detect pending
1781  * signals before a retry to make sure the continuous page faults can still be
1782  * interrupted if necessary.
1783  *
1784  * The combination FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE is illegal.
1785  * FAULT_FLAG_UNSHARE is ignored and treated like an ordinary read fault when
1786  * applied to mappings that are not COW mappings.
1787  */
1788 enum fault_flag {
1789 	FAULT_FLAG_WRITE =		1 << 0,
1790 	FAULT_FLAG_MKWRITE =		1 << 1,
1791 	FAULT_FLAG_ALLOW_RETRY =	1 << 2,
1792 	FAULT_FLAG_RETRY_NOWAIT = 	1 << 3,
1793 	FAULT_FLAG_KILLABLE =		1 << 4,
1794 	FAULT_FLAG_TRIED = 		1 << 5,
1795 	FAULT_FLAG_USER =		1 << 6,
1796 	FAULT_FLAG_REMOTE =		1 << 7,
1797 	FAULT_FLAG_INSTRUCTION =	1 << 8,
1798 	FAULT_FLAG_INTERRUPTIBLE =	1 << 9,
1799 	FAULT_FLAG_UNSHARE =		1 << 10,
1800 	FAULT_FLAG_ORIG_PTE_VALID =	1 << 11,
1801 	FAULT_FLAG_VMA_LOCK =		1 << 12,
1802 };
1803 
1804 typedef unsigned int __bitwise zap_flags_t;
1805 
1806 /* Flags for clear_young_dirty_ptes(). */
1807 typedef int __bitwise cydp_t;
1808 
1809 /* Clear the access bit */
1810 #define CYDP_CLEAR_YOUNG		((__force cydp_t)BIT(0))
1811 
1812 /* Clear the dirty bit */
1813 #define CYDP_CLEAR_DIRTY		((__force cydp_t)BIT(1))
1814 
1815 /*
1816  * FOLL_PIN and FOLL_LONGTERM may be used in various combinations with each
1817  * other. Here is what they mean, and how to use them:
1818  *
1819  *
1820  * FIXME: For pages which are part of a filesystem, mappings are subject to the
1821  * lifetime enforced by the filesystem and we need guarantees that longterm
1822  * users like RDMA and V4L2 only establish mappings which coordinate usage with
1823  * the filesystem.  Ideas for this coordination include revoking the longterm
1824  * pin, delaying writeback, bounce buffer page writeback, etc.  As FS DAX was
1825  * added after the problem with filesystems was found FS DAX VMAs are
1826  * specifically failed.  Filesystem pages are still subject to bugs and use of
1827  * FOLL_LONGTERM should be avoided on those pages.
1828  *
1829  * In the CMA case: long term pins in a CMA region would unnecessarily fragment
1830  * that region.  And so, CMA attempts to migrate the page before pinning, when
1831  * FOLL_LONGTERM is specified.
1832  *
1833  * FOLL_PIN indicates that a special kind of tracking (not just page->_refcount,
1834  * but an additional pin counting system) will be invoked. This is intended for
1835  * anything that gets a page reference and then touches page data (for example,
1836  * Direct IO). This lets the filesystem know that some non-file-system entity is
1837  * potentially changing the pages' data. In contrast to FOLL_GET (whose pages
1838  * are released via put_page()), FOLL_PIN pages must be released, ultimately, by
1839  * a call to unpin_user_page().
1840  *
1841  * FOLL_PIN is similar to FOLL_GET: both of these pin pages. They use different
1842  * and separate refcounting mechanisms, however, and that means that each has
1843  * its own acquire and release mechanisms:
1844  *
1845  *     FOLL_GET: get_user_pages*() to acquire, and put_page() to release.
1846  *
1847  *     FOLL_PIN: pin_user_pages*() to acquire, and unpin_user_pages to release.
1848  *
1849  * FOLL_PIN and FOLL_GET are mutually exclusive for a given function call.
1850  * (The underlying pages may experience both FOLL_GET-based and FOLL_PIN-based
1851  * calls applied to them, and that's perfectly OK. This is a constraint on the
1852  * callers, not on the pages.)
1853  *
1854  * FOLL_PIN should be set internally by the pin_user_pages*() APIs, never
1855  * directly by the caller. That's in order to help avoid mismatches when
1856  * releasing pages: get_user_pages*() pages must be released via put_page(),
1857  * while pin_user_pages*() pages must be released via unpin_user_page().
1858  *
1859  * Please see Documentation/core-api/pin_user_pages.rst for more information.
1860  */
1861 
1862 enum {
1863 	/* check pte is writable */
1864 	FOLL_WRITE = 1 << 0,
1865 	/* do get_page on page */
1866 	FOLL_GET = 1 << 1,
1867 	/* give error on hole if it would be zero */
1868 	FOLL_DUMP = 1 << 2,
1869 	/* get_user_pages read/write w/o permission */
1870 	FOLL_FORCE = 1 << 3,
1871 	/*
1872 	 * if a disk transfer is needed, start the IO and return without waiting
1873 	 * upon it
1874 	 */
1875 	FOLL_NOWAIT = 1 << 4,
1876 	/* do not fault in pages */
1877 	FOLL_NOFAULT = 1 << 5,
1878 	/* check page is hwpoisoned */
1879 	FOLL_HWPOISON = 1 << 6,
1880 	/* don't do file mappings */
1881 	FOLL_ANON = 1 << 7,
1882 	/*
1883 	 * FOLL_LONGTERM indicates that the page will be held for an indefinite
1884 	 * time period _often_ under userspace control.  This is in contrast to
1885 	 * iov_iter_get_pages(), whose usages are transient.
1886 	 */
1887 	FOLL_LONGTERM = 1 << 8,
1888 	/* split huge pmd before returning */
1889 	FOLL_SPLIT_PMD = 1 << 9,
1890 	/* allow returning PCI P2PDMA pages */
1891 	FOLL_PCI_P2PDMA = 1 << 10,
1892 	/* allow interrupts from generic signals */
1893 	FOLL_INTERRUPTIBLE = 1 << 11,
1894 	/*
1895 	 * Always honor (trigger) NUMA hinting faults.
1896 	 *
1897 	 * FOLL_WRITE implicitly honors NUMA hinting faults because a
1898 	 * PROT_NONE-mapped page is not writable (exceptions with FOLL_FORCE
1899 	 * apply). get_user_pages_fast_only() always implicitly honors NUMA
1900 	 * hinting faults.
1901 	 */
1902 	FOLL_HONOR_NUMA_FAULT = 1 << 12,
1903 
1904 	/* See also internal only FOLL flags in mm/internal.h */
1905 };
1906 
1907 /* mm flags */
1908 
1909 /*
1910  * The first two bits represent core dump modes for set-user-ID,
1911  * the modes are SUID_DUMP_* defined in linux/sched/coredump.h
1912  */
1913 #define MMF_DUMPABLE_BITS 2
1914 #define MMF_DUMPABLE_MASK (BIT(MMF_DUMPABLE_BITS) - 1)
1915 /* coredump filter bits */
1916 #define MMF_DUMP_ANON_PRIVATE	2
1917 #define MMF_DUMP_ANON_SHARED	3
1918 #define MMF_DUMP_MAPPED_PRIVATE	4
1919 #define MMF_DUMP_MAPPED_SHARED	5
1920 #define MMF_DUMP_ELF_HEADERS	6
1921 #define MMF_DUMP_HUGETLB_PRIVATE 7
1922 #define MMF_DUMP_HUGETLB_SHARED  8
1923 #define MMF_DUMP_DAX_PRIVATE	9
1924 #define MMF_DUMP_DAX_SHARED	10
1925 
1926 #define MMF_DUMP_FILTER_SHIFT	MMF_DUMPABLE_BITS
1927 #define MMF_DUMP_FILTER_BITS	9
1928 #define MMF_DUMP_FILTER_MASK \
1929 	((BIT(MMF_DUMP_FILTER_BITS) - 1) << MMF_DUMP_FILTER_SHIFT)
1930 #define MMF_DUMP_FILTER_DEFAULT \
1931 	(BIT(MMF_DUMP_ANON_PRIVATE) | BIT(MMF_DUMP_ANON_SHARED) | \
1932 	 BIT(MMF_DUMP_HUGETLB_PRIVATE) | MMF_DUMP_MASK_DEFAULT_ELF)
1933 
1934 #ifdef CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS
1935 # define MMF_DUMP_MASK_DEFAULT_ELF	BIT(MMF_DUMP_ELF_HEADERS)
1936 #else
1937 # define MMF_DUMP_MASK_DEFAULT_ELF	0
1938 #endif
1939 					/* leave room for more dump flags */
1940 #define MMF_VM_MERGEABLE	16	/* KSM may merge identical pages */
1941 #define MMF_VM_HUGEPAGE		17	/* set when mm is available for khugepaged */
1942 
1943 #define MMF_HUGE_ZERO_FOLIO	18      /* mm has ever used the global huge zero folio */
1944 
1945 #define MMF_HAS_UPROBES		19	/* has uprobes */
1946 #define MMF_RECALC_UPROBES	20	/* MMF_HAS_UPROBES can be wrong */
1947 #define MMF_OOM_SKIP		21	/* mm is of no interest for the OOM killer */
1948 #define MMF_UNSTABLE		22	/* mm is unstable for copy_from_user */
1949 #define MMF_DISABLE_THP_EXCEPT_ADVISED	23	/* no THP except when advised (e.g., VM_HUGEPAGE) */
1950 #define MMF_DISABLE_THP_COMPLETELY	24	/* no THP for all VMAs */
1951 #define MMF_DISABLE_THP_MASK	(BIT(MMF_DISABLE_THP_COMPLETELY) | \
1952 				 BIT(MMF_DISABLE_THP_EXCEPT_ADVISED))
1953 #define MMF_OOM_REAP_QUEUED	25	/* mm was queued for oom_reaper */
1954 #define MMF_MULTIPROCESS	26	/* mm is shared between processes */
1955 /*
1956  * MMF_HAS_PINNED: Whether this mm has pinned any pages.  This can be either
1957  * replaced in the future by mm.pinned_vm when it becomes stable, or grow into
1958  * a counter on its own. We're aggresive on this bit for now: even if the
1959  * pinned pages were unpinned later on, we'll still keep this bit set for the
1960  * lifecycle of this mm, just for simplicity.
1961  */
1962 #define MMF_HAS_PINNED		27	/* FOLL_PIN has run, never cleared */
1963 
1964 #define MMF_HAS_MDWE		28
1965 #define MMF_HAS_MDWE_MASK	BIT(MMF_HAS_MDWE)
1966 
1967 #define MMF_HAS_MDWE_NO_INHERIT	29
1968 
1969 #define MMF_VM_MERGE_ANY	30
1970 #define MMF_VM_MERGE_ANY_MASK	BIT(MMF_VM_MERGE_ANY)
1971 
1972 #define MMF_TOPDOWN		31	/* mm searches top down by default */
1973 #define MMF_TOPDOWN_MASK	BIT(MMF_TOPDOWN)
1974 
1975 #define MMF_INIT_LEGACY_MASK	(MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK |\
1976 				 MMF_DISABLE_THP_MASK | MMF_HAS_MDWE_MASK |\
1977 				 MMF_VM_MERGE_ANY_MASK | MMF_TOPDOWN_MASK)
1978 
1979 /* Legacy flags must fit within 32 bits. */
1980 static_assert((u64)MMF_INIT_LEGACY_MASK <= (u64)UINT_MAX);
1981 
1982 /*
1983  * Initialise legacy flags according to masks, propagating selected flags on
1984  * fork. Further flag manipulation can be performed by the caller.
1985  */
mmf_init_legacy_flags(unsigned long flags)1986 static inline unsigned long mmf_init_legacy_flags(unsigned long flags)
1987 {
1988 	if (flags & (1UL << MMF_HAS_MDWE_NO_INHERIT))
1989 		flags &= ~((1UL << MMF_HAS_MDWE) |
1990 			   (1UL << MMF_HAS_MDWE_NO_INHERIT));
1991 	return flags & MMF_INIT_LEGACY_MASK;
1992 }
1993 
1994 #endif /* _LINUX_MM_TYPES_H */
1995