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