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