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