• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* SPDX-License-Identifier: GPL-2.0-or-later */
2 /* internal.h: mm/ internal definitions
3  *
4  * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
5  * Written by David Howells (dhowells@redhat.com)
6  */
7 #ifndef __MM_INTERNAL_H
8 #define __MM_INTERNAL_H
9 
10 #include <linux/fs.h>
11 #include <linux/mm.h>
12 #include <linux/pagemap.h>
13 #include <linux/rmap.h>
14 #include <linux/swap.h>
15 #include <linux/swapops.h>
16 #include <linux/tracepoint-defs.h>
17 
18 struct folio_batch;
19 
20 /*
21  * The set of flags that only affect watermark checking and reclaim
22  * behaviour. This is used by the MM to obey the caller constraints
23  * about IO, FS and watermark checking while ignoring placement
24  * hints such as HIGHMEM usage.
25  */
26 #define GFP_RECLAIM_MASK (__GFP_RECLAIM|__GFP_HIGH|__GFP_IO|__GFP_FS|\
27 			__GFP_NOWARN|__GFP_RETRY_MAYFAIL|__GFP_NOFAIL|\
28 			__GFP_NORETRY|__GFP_MEMALLOC|__GFP_NOMEMALLOC|\
29 			__GFP_NOLOCKDEP)
30 
31 /* The GFP flags allowed during early boot */
32 #define GFP_BOOT_MASK (__GFP_BITS_MASK & ~(__GFP_RECLAIM|__GFP_IO|__GFP_FS))
33 
34 /* Control allocation cpuset and node placement constraints */
35 #define GFP_CONSTRAINT_MASK (__GFP_HARDWALL|__GFP_THISNODE)
36 
37 /* Do not use these with a slab allocator */
38 #define GFP_SLAB_BUG_MASK (__GFP_DMA32|__GFP_HIGHMEM|~__GFP_BITS_MASK)
39 
40 /*
41  * Different from WARN_ON_ONCE(), no warning will be issued
42  * when we specify __GFP_NOWARN.
43  */
44 #define WARN_ON_ONCE_GFP(cond, gfp)	({				\
45 	static bool __section(".data.once") __warned;			\
46 	int __ret_warn_once = !!(cond);					\
47 									\
48 	if (unlikely(!(gfp & __GFP_NOWARN) && __ret_warn_once && !__warned)) { \
49 		__warned = true;					\
50 		WARN_ON(1);						\
51 	}								\
52 	unlikely(__ret_warn_once);					\
53 })
54 
55 void page_writeback_init(void);
56 
57 /*
58  * If a 16GB hugetlb folio were mapped by PTEs of all of its 4kB pages,
59  * its nr_pages_mapped would be 0x400000: choose the ENTIRELY_MAPPED bit
60  * above that range, instead of 2*(PMD_SIZE/PAGE_SIZE).  Hugetlb currently
61  * leaves nr_pages_mapped at 0, but avoid surprise if it participates later.
62  */
63 #define ENTIRELY_MAPPED		0x800000
64 #define FOLIO_PAGES_MAPPED	(ENTIRELY_MAPPED - 1)
65 
66 /*
67  * Flags passed to __show_mem() and show_free_areas() to suppress output in
68  * various contexts.
69  */
70 #define SHOW_MEM_FILTER_NODES		(0x0001u)	/* disallowed nodes */
71 
72 /*
73  * How many individual pages have an elevated _mapcount.  Excludes
74  * the folio's entire_mapcount.
75  */
folio_nr_pages_mapped(struct folio * folio)76 static inline int folio_nr_pages_mapped(struct folio *folio)
77 {
78 	return atomic_read(&folio->_nr_pages_mapped) & FOLIO_PAGES_MAPPED;
79 }
80 
81 /*
82  * Retrieve the first entry of a folio based on a provided entry within the
83  * folio. We cannot rely on folio->swap as there is no guarantee that it has
84  * been initialized. Used for calling arch_swap_restore()
85  */
folio_swap(swp_entry_t entry,struct folio * folio)86 static inline swp_entry_t folio_swap(swp_entry_t entry, struct folio *folio)
87 {
88 	swp_entry_t swap = {
89 		.val = ALIGN_DOWN(entry.val, folio_nr_pages(folio)),
90 	};
91 
92 	return swap;
93 }
94 
folio_raw_mapping(struct folio * folio)95 static inline void *folio_raw_mapping(struct folio *folio)
96 {
97 	unsigned long mapping = (unsigned long)folio->mapping;
98 
99 	return (void *)(mapping & ~PAGE_MAPPING_FLAGS);
100 }
101 
102 #ifdef CONFIG_MMU
103 
104 /* Flags for folio_pte_batch(). */
105 typedef int __bitwise fpb_t;
106 
107 /* Compare PTEs after pte_mkclean(), ignoring the dirty bit. */
108 #define FPB_IGNORE_DIRTY		((__force fpb_t)BIT(0))
109 
110 /* Compare PTEs after pte_clear_soft_dirty(), ignoring the soft-dirty bit. */
111 #define FPB_IGNORE_SOFT_DIRTY		((__force fpb_t)BIT(1))
112 
__pte_batch_clear_ignored(pte_t pte,fpb_t flags)113 static inline pte_t __pte_batch_clear_ignored(pte_t pte, fpb_t flags)
114 {
115 	if (flags & FPB_IGNORE_DIRTY)
116 		pte = pte_mkclean(pte);
117 	if (likely(flags & FPB_IGNORE_SOFT_DIRTY))
118 		pte = pte_clear_soft_dirty(pte);
119 	return pte_wrprotect(pte_mkold(pte));
120 }
121 
122 /**
123  * folio_pte_batch - detect a PTE batch for a large folio
124  * @folio: The large folio to detect a PTE batch for.
125  * @addr: The user virtual address the first page is mapped at.
126  * @start_ptep: Page table pointer for the first entry.
127  * @pte: Page table entry for the first page.
128  * @max_nr: The maximum number of table entries to consider.
129  * @flags: Flags to modify the PTE batch semantics.
130  * @any_writable: Optional pointer to indicate whether any entry except the
131  *		  first one is writable.
132  * @any_young: Optional pointer to indicate whether any entry except the
133  *		  first one is young.
134  * @any_dirty: Optional pointer to indicate whether any entry except the
135  *		  first one is dirty.
136  *
137  * Detect a PTE batch: consecutive (present) PTEs that map consecutive
138  * pages of the same large folio.
139  *
140  * All PTEs inside a PTE batch have the same PTE bits set, excluding the PFN,
141  * the accessed bit, writable bit, dirty bit (with FPB_IGNORE_DIRTY) and
142  * soft-dirty bit (with FPB_IGNORE_SOFT_DIRTY).
143  *
144  * start_ptep must map any page of the folio. max_nr must be at least one and
145  * must be limited by the caller so scanning cannot exceed a single page table.
146  *
147  * Return: the number of table entries in the batch.
148  */
folio_pte_batch(struct folio * folio,unsigned long addr,pte_t * start_ptep,pte_t pte,int max_nr,fpb_t flags,bool * any_writable,bool * any_young,bool * any_dirty)149 static inline int folio_pte_batch(struct folio *folio, unsigned long addr,
150 		pte_t *start_ptep, pte_t pte, int max_nr, fpb_t flags,
151 		bool *any_writable, bool *any_young, bool *any_dirty)
152 {
153 	unsigned long folio_end_pfn = folio_pfn(folio) + folio_nr_pages(folio);
154 	const pte_t *end_ptep = start_ptep + max_nr;
155 	pte_t expected_pte, *ptep;
156 	bool writable, young, dirty;
157 	int nr;
158 
159 	if (any_writable)
160 		*any_writable = false;
161 	if (any_young)
162 		*any_young = false;
163 	if (any_dirty)
164 		*any_dirty = false;
165 
166 	VM_WARN_ON_FOLIO(!pte_present(pte), folio);
167 	VM_WARN_ON_FOLIO(!folio_test_large(folio) || max_nr < 1, folio);
168 	VM_WARN_ON_FOLIO(page_folio(pfn_to_page(pte_pfn(pte))) != folio, folio);
169 
170 	nr = pte_batch_hint(start_ptep, pte);
171 	expected_pte = __pte_batch_clear_ignored(pte_advance_pfn(pte, nr), flags);
172 	ptep = start_ptep + nr;
173 
174 	while (ptep < end_ptep) {
175 		pte = ptep_get(ptep);
176 		if (any_writable)
177 			writable = !!pte_write(pte);
178 		if (any_young)
179 			young = !!pte_young(pte);
180 		if (any_dirty)
181 			dirty = !!pte_dirty(pte);
182 		pte = __pte_batch_clear_ignored(pte, flags);
183 
184 		if (!pte_same(pte, expected_pte))
185 			break;
186 
187 		/*
188 		 * Stop immediately once we reached the end of the folio. In
189 		 * corner cases the next PFN might fall into a different
190 		 * folio.
191 		 */
192 		if (pte_pfn(pte) >= folio_end_pfn)
193 			break;
194 
195 		if (any_writable)
196 			*any_writable |= writable;
197 		if (any_young)
198 			*any_young |= young;
199 		if (any_dirty)
200 			*any_dirty |= dirty;
201 
202 		nr = pte_batch_hint(ptep, pte);
203 		expected_pte = pte_advance_pfn(expected_pte, nr);
204 		ptep += nr;
205 	}
206 
207 	return min(ptep - start_ptep, max_nr);
208 }
209 
210 /**
211  * pte_move_swp_offset - Move the swap entry offset field of a swap pte
212  *	 forward or backward by delta
213  * @pte: The initial pte state; is_swap_pte(pte) must be true and
214  *	 non_swap_entry() must be false.
215  * @delta: The direction and the offset we are moving; forward if delta
216  *	 is positive; backward if delta is negative
217  *
218  * Moves the swap offset, while maintaining all other fields, including
219  * swap type, and any swp pte bits. The resulting pte is returned.
220  */
pte_move_swp_offset(pte_t pte,long delta)221 static inline pte_t pte_move_swp_offset(pte_t pte, long delta)
222 {
223 	swp_entry_t entry = pte_to_swp_entry(pte);
224 	pte_t new = __swp_entry_to_pte(__swp_entry(swp_type(entry),
225 						   (swp_offset(entry) + delta)));
226 
227 	if (pte_swp_soft_dirty(pte))
228 		new = pte_swp_mksoft_dirty(new);
229 	if (pte_swp_exclusive(pte))
230 		new = pte_swp_mkexclusive(new);
231 	if (pte_swp_uffd_wp(pte))
232 		new = pte_swp_mkuffd_wp(new);
233 
234 	return new;
235 }
236 
237 
238 /**
239  * pte_next_swp_offset - Increment the swap entry offset field of a swap pte.
240  * @pte: The initial pte state; is_swap_pte(pte) must be true and
241  *	 non_swap_entry() must be false.
242  *
243  * Increments the swap offset, while maintaining all other fields, including
244  * swap type, and any swp pte bits. The resulting pte is returned.
245  */
pte_next_swp_offset(pte_t pte)246 static inline pte_t pte_next_swp_offset(pte_t pte)
247 {
248 	return pte_move_swp_offset(pte, 1);
249 }
250 
251 /**
252  * swap_pte_batch - detect a PTE batch for a set of contiguous swap entries
253  * @start_ptep: Page table pointer for the first entry.
254  * @max_nr: The maximum number of table entries to consider.
255  * @pte: Page table entry for the first entry.
256  *
257  * Detect a batch of contiguous swap entries: consecutive (non-present) PTEs
258  * containing swap entries all with consecutive offsets and targeting the same
259  * swap type, all with matching swp pte bits.
260  *
261  * max_nr must be at least one and must be limited by the caller so scanning
262  * cannot exceed a single page table.
263  *
264  * Return: the number of table entries in the batch.
265  */
swap_pte_batch(pte_t * start_ptep,int max_nr,pte_t pte)266 static inline int swap_pte_batch(pte_t *start_ptep, int max_nr, pte_t pte)
267 {
268 	pte_t expected_pte = pte_next_swp_offset(pte);
269 	const pte_t *end_ptep = start_ptep + max_nr;
270 	pte_t *ptep = start_ptep + 1;
271 
272 	VM_WARN_ON(max_nr < 1);
273 	VM_WARN_ON(!is_swap_pte(pte));
274 	VM_WARN_ON(non_swap_entry(pte_to_swp_entry(pte)));
275 
276 	while (ptep < end_ptep) {
277 		pte = ptep_get(ptep);
278 
279 		if (!pte_same(pte, expected_pte))
280 			break;
281 
282 		expected_pte = pte_next_swp_offset(expected_pte);
283 		ptep++;
284 	}
285 
286 	return ptep - start_ptep;
287 }
288 #endif /* CONFIG_MMU */
289 
290 void __acct_reclaim_writeback(pg_data_t *pgdat, struct folio *folio,
291 						int nr_throttled);
acct_reclaim_writeback(struct folio * folio)292 static inline void acct_reclaim_writeback(struct folio *folio)
293 {
294 	pg_data_t *pgdat = folio_pgdat(folio);
295 	int nr_throttled = atomic_read(&pgdat->nr_writeback_throttled);
296 
297 	if (nr_throttled)
298 		__acct_reclaim_writeback(pgdat, folio, nr_throttled);
299 }
300 
wake_throttle_isolated(pg_data_t * pgdat)301 static inline void wake_throttle_isolated(pg_data_t *pgdat)
302 {
303 	wait_queue_head_t *wqh;
304 
305 	wqh = &pgdat->reclaim_wait[VMSCAN_THROTTLE_ISOLATED];
306 	if (waitqueue_active(wqh))
307 		wake_up(wqh);
308 }
309 
310 vm_fault_t vmf_anon_prepare(struct vm_fault *vmf);
311 vm_fault_t do_swap_page(struct vm_fault *vmf);
312 void folio_rotate_reclaimable(struct folio *folio);
313 bool __folio_end_writeback(struct folio *folio);
314 void deactivate_file_folio(struct folio *folio);
315 void folio_activate(struct folio *folio);
316 
317 void free_pgtables(struct mmu_gather *tlb, struct ma_state *mas,
318 		   struct vm_area_struct *start_vma, unsigned long floor,
319 		   unsigned long ceiling, bool mm_wr_locked);
320 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte);
321 
322 struct zap_details;
323 void unmap_page_range(struct mmu_gather *tlb,
324 			     struct vm_area_struct *vma,
325 			     unsigned long addr, unsigned long end,
326 			     struct zap_details *details);
327 
328 void page_cache_ra_order(struct readahead_control *, struct file_ra_state *,
329 		unsigned int order);
330 void force_page_cache_ra(struct readahead_control *, unsigned long nr);
force_page_cache_readahead(struct address_space * mapping,struct file * file,pgoff_t index,unsigned long nr_to_read)331 static inline void force_page_cache_readahead(struct address_space *mapping,
332 		struct file *file, pgoff_t index, unsigned long nr_to_read)
333 {
334 	DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, index);
335 	force_page_cache_ra(&ractl, nr_to_read);
336 }
337 
338 unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,
339 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices);
340 unsigned find_get_entries(struct address_space *mapping, pgoff_t *start,
341 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices);
342 void filemap_free_folio(struct address_space *mapping, struct folio *folio);
343 int truncate_inode_folio(struct address_space *mapping, struct folio *folio);
344 bool truncate_inode_partial_folio(struct folio *folio, loff_t start,
345 		loff_t end);
346 long invalidate_inode_page(struct page *page);
347 unsigned long mapping_try_invalidate(struct address_space *mapping,
348 		pgoff_t start, pgoff_t end, unsigned long *nr_failed);
349 
350 /**
351  * folio_evictable - Test whether a folio is evictable.
352  * @folio: The folio to test.
353  *
354  * Test whether @folio is evictable -- i.e., should be placed on
355  * active/inactive lists vs unevictable list.
356  *
357  * Reasons folio might not be evictable:
358  * 1. folio's mapping marked unevictable
359  * 2. One of the pages in the folio is part of an mlocked VMA
360  */
folio_evictable(struct folio * folio)361 static inline bool folio_evictable(struct folio *folio)
362 {
363 	bool ret;
364 
365 	/* Prevent address_space of inode and swap cache from being freed */
366 	rcu_read_lock();
367 	ret = !mapping_unevictable(folio_mapping(folio)) &&
368 			!folio_test_mlocked(folio);
369 	rcu_read_unlock();
370 	return ret;
371 }
372 
373 /*
374  * Turn a non-refcounted page (->_refcount == 0) into refcounted with
375  * a count of one.
376  */
set_page_refcounted(struct page * page)377 static inline void set_page_refcounted(struct page *page)
378 {
379 	VM_BUG_ON_PAGE(PageTail(page), page);
380 	VM_BUG_ON_PAGE(page_ref_count(page), page);
381 	set_page_count(page, 1);
382 }
383 
384 /*
385  * Return true if a folio needs ->release_folio() calling upon it.
386  */
folio_needs_release(struct folio * folio)387 static inline bool folio_needs_release(struct folio *folio)
388 {
389 	struct address_space *mapping = folio_mapping(folio);
390 
391 	return folio_has_private(folio) ||
392 		(mapping && mapping_release_always(mapping));
393 }
394 
395 extern unsigned long highest_memmap_pfn;
396 
397 /*
398  * Maximum number of reclaim retries without progress before the OOM
399  * killer is consider the only way forward.
400  */
401 #define MAX_RECLAIM_RETRIES 16
402 
403 /*
404  * in mm/vmscan.c:
405  */
406 bool isolate_lru_page(struct page *page);
407 bool folio_isolate_lru(struct folio *folio);
408 void putback_lru_page(struct page *page);
409 void folio_putback_lru(struct folio *folio);
410 extern void reclaim_throttle(pg_data_t *pgdat, enum vmscan_throttle_state reason);
411 
412 /*
413  * in mm/rmap.c:
414  */
415 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address);
416 
417 /*
418  * in mm/page_alloc.c
419  */
420 #define K(x) ((x) << (PAGE_SHIFT-10))
421 
422 extern char * const zone_names[MAX_NR_ZONES];
423 
424 /* perform sanity checks on struct pages being allocated or freed */
425 DECLARE_STATIC_KEY_MAYBE(CONFIG_DEBUG_VM, check_pages_enabled);
426 
427 extern int min_free_kbytes;
428 
429 void setup_per_zone_wmarks(void);
430 void calculate_min_free_kbytes(void);
431 int __meminit init_per_zone_wmark_min(void);
432 void page_alloc_sysctl_init(void);
433 
434 /*
435  * Structure for holding the mostly immutable allocation parameters passed
436  * between functions involved in allocations, including the alloc_pages*
437  * family of functions.
438  *
439  * nodemask, migratetype and highest_zoneidx are initialized only once in
440  * __alloc_pages() and then never change.
441  *
442  * zonelist, preferred_zone and highest_zoneidx are set first in
443  * __alloc_pages() for the fast path, and might be later changed
444  * in __alloc_pages_slowpath(). All other functions pass the whole structure
445  * by a const pointer.
446  */
447 struct alloc_context {
448 	struct zonelist *zonelist;
449 	nodemask_t *nodemask;
450 	struct zoneref *preferred_zoneref;
451 	int migratetype;
452 
453 	/*
454 	 * highest_zoneidx represents highest usable zone index of
455 	 * the allocation request. Due to the nature of the zone,
456 	 * memory on lower zone than the highest_zoneidx will be
457 	 * protected by lowmem_reserve[highest_zoneidx].
458 	 *
459 	 * highest_zoneidx is also used by reclaim/compaction to limit
460 	 * the target zone since higher zone than this index cannot be
461 	 * usable for this allocation request.
462 	 */
463 	enum zone_type highest_zoneidx;
464 	bool spread_dirty_pages;
465 };
466 
467 /*
468  * This function returns the order of a free page in the buddy system. In
469  * general, page_zone(page)->lock must be held by the caller to prevent the
470  * page from being allocated in parallel and returning garbage as the order.
471  * If a caller does not hold page_zone(page)->lock, it must guarantee that the
472  * page cannot be allocated or merged in parallel. Alternatively, it must
473  * handle invalid values gracefully, and use buddy_order_unsafe() below.
474  */
buddy_order(struct page * page)475 static inline unsigned int buddy_order(struct page *page)
476 {
477 	/* PageBuddy() must be checked by the caller */
478 	return page_private(page);
479 }
480 
481 /*
482  * Like buddy_order(), but for callers who cannot afford to hold the zone lock.
483  * PageBuddy() should be checked first by the caller to minimize race window,
484  * and invalid values must be handled gracefully.
485  *
486  * READ_ONCE is used so that if the caller assigns the result into a local
487  * variable and e.g. tests it for valid range before using, the compiler cannot
488  * decide to remove the variable and inline the page_private(page) multiple
489  * times, potentially observing different values in the tests and the actual
490  * use of the result.
491  */
492 #define buddy_order_unsafe(page)	READ_ONCE(page_private(page))
493 
494 /*
495  * This function checks whether a page is free && is the buddy
496  * we can coalesce a page and its buddy if
497  * (a) the buddy is not in a hole (check before calling!) &&
498  * (b) the buddy is in the buddy system &&
499  * (c) a page and its buddy have the same order &&
500  * (d) a page and its buddy are in the same zone.
501  *
502  * For recording whether a page is in the buddy system, we set PageBuddy.
503  * Setting, clearing, and testing PageBuddy is serialized by zone->lock.
504  *
505  * For recording page's order, we use page_private(page).
506  */
page_is_buddy(struct page * page,struct page * buddy,unsigned int order)507 static inline bool page_is_buddy(struct page *page, struct page *buddy,
508 				 unsigned int order)
509 {
510 	if (!page_is_guard(buddy) && !PageBuddy(buddy))
511 		return false;
512 
513 	if (buddy_order(buddy) != order)
514 		return false;
515 
516 	/*
517 	 * zone check is done late to avoid uselessly calculating
518 	 * zone/node ids for pages that could never merge.
519 	 */
520 	if (page_zone_id(page) != page_zone_id(buddy))
521 		return false;
522 
523 	VM_BUG_ON_PAGE(page_count(buddy) != 0, buddy);
524 
525 	return true;
526 }
527 
528 /*
529  * Locate the struct page for both the matching buddy in our
530  * pair (buddy1) and the combined O(n+1) page they form (page).
531  *
532  * 1) Any buddy B1 will have an order O twin B2 which satisfies
533  * the following equation:
534  *     B2 = B1 ^ (1 << O)
535  * For example, if the starting buddy (buddy2) is #8 its order
536  * 1 buddy is #10:
537  *     B2 = 8 ^ (1 << 1) = 8 ^ 2 = 10
538  *
539  * 2) Any buddy B will have an order O+1 parent P which
540  * satisfies the following equation:
541  *     P = B & ~(1 << O)
542  *
543  * Assumption: *_mem_map is contiguous at least up to MAX_ORDER
544  */
545 static inline unsigned long
__find_buddy_pfn(unsigned long page_pfn,unsigned int order)546 __find_buddy_pfn(unsigned long page_pfn, unsigned int order)
547 {
548 	return page_pfn ^ (1 << order);
549 }
550 
551 /*
552  * Find the buddy of @page and validate it.
553  * @page: The input page
554  * @pfn: The pfn of the page, it saves a call to page_to_pfn() when the
555  *       function is used in the performance-critical __free_one_page().
556  * @order: The order of the page
557  * @buddy_pfn: The output pointer to the buddy pfn, it also saves a call to
558  *             page_to_pfn().
559  *
560  * The found buddy can be a non PageBuddy, out of @page's zone, or its order is
561  * not the same as @page. The validation is necessary before use it.
562  *
563  * Return: the found buddy page or NULL if not found.
564  */
find_buddy_page_pfn(struct page * page,unsigned long pfn,unsigned int order,unsigned long * buddy_pfn)565 static inline struct page *find_buddy_page_pfn(struct page *page,
566 			unsigned long pfn, unsigned int order, unsigned long *buddy_pfn)
567 {
568 	unsigned long __buddy_pfn = __find_buddy_pfn(pfn, order);
569 	struct page *buddy;
570 
571 	buddy = page + (__buddy_pfn - pfn);
572 	if (buddy_pfn)
573 		*buddy_pfn = __buddy_pfn;
574 
575 	if (page_is_buddy(page, buddy, order))
576 		return buddy;
577 	return NULL;
578 }
579 
580 extern struct page *__pageblock_pfn_to_page(unsigned long start_pfn,
581 				unsigned long end_pfn, struct zone *zone);
582 
pageblock_pfn_to_page(unsigned long start_pfn,unsigned long end_pfn,struct zone * zone)583 static inline struct page *pageblock_pfn_to_page(unsigned long start_pfn,
584 				unsigned long end_pfn, struct zone *zone)
585 {
586 	if (zone->contiguous)
587 		return pfn_to_page(start_pfn);
588 
589 	return __pageblock_pfn_to_page(start_pfn, end_pfn, zone);
590 }
591 
592 void set_zone_contiguous(struct zone *zone);
593 
clear_zone_contiguous(struct zone * zone)594 static inline void clear_zone_contiguous(struct zone *zone)
595 {
596 	zone->contiguous = false;
597 }
598 
599 extern int __isolate_free_page(struct page *page, unsigned int order);
600 extern void __putback_isolated_page(struct page *page, unsigned int order,
601 				    int mt);
602 extern void memblock_free_pages(struct page *page, unsigned long pfn,
603 					unsigned int order);
604 extern void __free_pages_core(struct page *page, unsigned int order);
605 
606 /*
607  * This will have no effect, other than possibly generating a warning, if the
608  * caller passes in a non-large folio.
609  */
folio_set_order(struct folio * folio,unsigned int order)610 static inline void folio_set_order(struct folio *folio, unsigned int order)
611 {
612 	if (WARN_ON_ONCE(!order || !folio_test_large(folio)))
613 		return;
614 
615 	folio->_flags_1 = (folio->_flags_1 & ~0xffUL) | order;
616 #ifdef CONFIG_64BIT
617 	folio->_folio_nr_pages = 1U << order;
618 #endif
619 }
620 
621 void folio_undo_large_rmappable(struct folio *folio);
622 
prep_compound_head(struct page * page,unsigned int order)623 static inline void prep_compound_head(struct page *page, unsigned int order)
624 {
625 	struct folio *folio = (struct folio *)page;
626 
627 	folio_set_order(folio, order);
628 	atomic_set(&folio->_entire_mapcount, -1);
629 	atomic_set(&folio->_nr_pages_mapped, 0);
630 	atomic_set(&folio->_pincount, 0);
631 }
632 
prep_compound_tail(struct page * head,int tail_idx)633 static inline void prep_compound_tail(struct page *head, int tail_idx)
634 {
635 	struct page *p = head + tail_idx;
636 
637 	p->mapping = TAIL_MAPPING;
638 	set_compound_head(p, head);
639 	set_page_private(p, 0);
640 }
641 
642 extern void prep_compound_page(struct page *page, unsigned int order);
643 
644 extern void post_alloc_hook(struct page *page, unsigned int order,
645 					gfp_t gfp_flags);
646 extern int user_min_free_kbytes;
647 
648 extern void free_unref_page(struct page *page, unsigned int order);
649 extern void free_unref_page_list(struct list_head *list);
650 
651 extern void zone_pcp_reset(struct zone *zone);
652 extern void zone_pcp_disable(struct zone *zone);
653 extern void zone_pcp_enable(struct zone *zone);
654 extern void zone_pcp_init(struct zone *zone);
655 
656 extern void *memmap_alloc(phys_addr_t size, phys_addr_t align,
657 			  phys_addr_t min_addr,
658 			  int nid, bool exact_nid);
659 
660 void memmap_init_range(unsigned long, int, unsigned long, unsigned long,
661 		unsigned long, enum meminit_context, struct vmem_altmap *, int);
662 
663 
664 int split_free_page(struct page *free_page,
665 			unsigned int order, unsigned long split_pfn_offset);
666 
667 #if defined CONFIG_COMPACTION || defined CONFIG_CMA
668 
669 /*
670  * in mm/compaction.c
671  */
672 /*
673  * compact_control is used to track pages being migrated and the free pages
674  * they are being migrated to during memory compaction. The free_pfn starts
675  * at the end of a zone and migrate_pfn begins at the start. Movable pages
676  * are moved to the end of a zone during a compaction run and the run
677  * completes when free_pfn <= migrate_pfn
678  */
679 struct compact_control {
680 	struct list_head freepages;	/* List of free pages to migrate to */
681 	struct list_head migratepages;	/* List of pages being migrated */
682 	unsigned int nr_freepages;	/* Number of isolated free pages */
683 	unsigned int nr_migratepages;	/* Number of pages to migrate */
684 	unsigned long free_pfn;		/* isolate_freepages search base */
685 	/*
686 	 * Acts as an in/out parameter to page isolation for migration.
687 	 * isolate_migratepages uses it as a search base.
688 	 * isolate_migratepages_block will update the value to the next pfn
689 	 * after the last isolated one.
690 	 */
691 	unsigned long migrate_pfn;
692 	unsigned long fast_start_pfn;	/* a pfn to start linear scan from */
693 	struct zone *zone;
694 	unsigned long total_migrate_scanned;
695 	unsigned long total_free_scanned;
696 	unsigned short fast_search_fail;/* failures to use free list searches */
697 	short search_order;		/* order to start a fast search at */
698 	const gfp_t gfp_mask;		/* gfp mask of a direct compactor */
699 	int order;			/* order a direct compactor needs */
700 	int migratetype;		/* migratetype of direct compactor */
701 	const unsigned int alloc_flags;	/* alloc flags of a direct compactor */
702 	const int highest_zoneidx;	/* zone index of a direct compactor */
703 	enum migrate_mode mode;		/* Async or sync migration mode */
704 	bool ignore_skip_hint;		/* Scan blocks even if marked skip */
705 	bool no_set_skip_hint;		/* Don't mark blocks for skipping */
706 	bool ignore_block_suitable;	/* Scan blocks considered unsuitable */
707 	bool direct_compaction;		/* False from kcompactd or /proc/... */
708 	bool proactive_compaction;	/* kcompactd proactive compaction */
709 	bool whole_zone;		/* Whole zone should/has been scanned */
710 	bool contended;			/* Signal lock contention */
711 	bool finish_pageblock;		/* Scan the remainder of a pageblock. Used
712 					 * when there are potentially transient
713 					 * isolation or migration failures to
714 					 * ensure forward progress.
715 					 */
716 	bool alloc_contig;		/* alloc_contig_range allocation */
717 };
718 
719 /*
720  * Used in direct compaction when a page should be taken from the freelists
721  * immediately when one is created during the free path.
722  */
723 struct capture_control {
724 	struct compact_control *cc;
725 	struct page *page;
726 };
727 
728 unsigned long
729 isolate_freepages_range(struct compact_control *cc,
730 			unsigned long start_pfn, unsigned long end_pfn);
731 int
732 isolate_migratepages_range(struct compact_control *cc,
733 			   unsigned long low_pfn, unsigned long end_pfn);
734 
735 int __alloc_contig_migrate_range(struct compact_control *cc,
736 					unsigned long start, unsigned long end);
737 
738 /* Free whole pageblock and set its migration type to MIGRATE_CMA. */
739 void init_cma_reserved_pageblock(struct page *page);
740 
741 #endif /* CONFIG_COMPACTION || CONFIG_CMA */
742 
743 int find_suitable_fallback(struct free_area *area, unsigned int order,
744 			int migratetype, bool only_stealable, bool *can_steal);
745 
free_area_empty(struct free_area * area,int migratetype)746 static inline bool free_area_empty(struct free_area *area, int migratetype)
747 {
748 	return list_empty(&area->free_list[migratetype]);
749 }
750 
751 /*
752  * These three helpers classifies VMAs for virtual memory accounting.
753  */
754 
755 /*
756  * Executable code area - executable, not writable, not stack
757  */
is_exec_mapping(vm_flags_t flags)758 static inline bool is_exec_mapping(vm_flags_t flags)
759 {
760 	return (flags & (VM_EXEC | VM_WRITE | VM_STACK)) == VM_EXEC;
761 }
762 
763 /*
764  * Stack area (including shadow stacks)
765  *
766  * VM_GROWSUP / VM_GROWSDOWN VMAs are always private anonymous:
767  * do_mmap() forbids all other combinations.
768  */
is_stack_mapping(vm_flags_t flags)769 static inline bool is_stack_mapping(vm_flags_t flags)
770 {
771 	return ((flags & VM_STACK) == VM_STACK) || (flags & VM_SHADOW_STACK);
772 }
773 
774 /*
775  * Data area - private, writable, not stack
776  */
is_data_mapping(vm_flags_t flags)777 static inline bool is_data_mapping(vm_flags_t flags)
778 {
779 	return (flags & (VM_WRITE | VM_SHARED | VM_STACK)) == VM_WRITE;
780 }
781 
782 /* mm/util.c */
783 struct anon_vma *folio_anon_vma(struct folio *folio);
784 
785 #ifdef CONFIG_MMU
786 void unmap_mapping_folio(struct folio *folio);
787 extern long populate_vma_page_range(struct vm_area_struct *vma,
788 		unsigned long start, unsigned long end, int *locked);
789 extern long faultin_page_range(struct mm_struct *mm, unsigned long start,
790 		unsigned long end, bool write, int *locked);
791 extern bool mlock_future_ok(struct mm_struct *mm, unsigned long flags,
792 			       unsigned long bytes);
793 
794 /*
795  * NOTE: This function can't tell whether the folio is "fully mapped" in the
796  * range.
797  * "fully mapped" means all the pages of folio is associated with the page
798  * table of range while this function just check whether the folio range is
799  * within the range [start, end). Funcation caller nees to do page table
800  * check if it cares about the page table association.
801  *
802  * Typical usage (like mlock or madvise) is:
803  * Caller knows at least 1 page of folio is associated with page table of VMA
804  * and the range [start, end) is intersect with the VMA range. Caller wants
805  * to know whether the folio is fully associated with the range. It calls
806  * this function to check whether the folio is in the range first. Then checks
807  * the page table to know whether the folio is fully mapped to the range.
808  */
809 static inline bool
folio_within_range(struct folio * folio,struct vm_area_struct * vma,unsigned long start,unsigned long end)810 folio_within_range(struct folio *folio, struct vm_area_struct *vma,
811 		unsigned long start, unsigned long end)
812 {
813 	pgoff_t pgoff, addr;
814 	unsigned long vma_pglen = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
815 
816 	VM_WARN_ON_FOLIO(folio_test_ksm(folio), folio);
817 	if (start > end)
818 		return false;
819 
820 	if (start < vma->vm_start)
821 		start = vma->vm_start;
822 
823 	if (end > vma->vm_end)
824 		end = vma->vm_end;
825 
826 	pgoff = folio_pgoff(folio);
827 
828 	/* if folio start address is not in vma range */
829 	if (!in_range(pgoff, vma->vm_pgoff, vma_pglen))
830 		return false;
831 
832 	addr = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
833 
834 	return !(addr < start || end - addr < folio_size(folio));
835 }
836 
837 static inline bool
folio_within_vma(struct folio * folio,struct vm_area_struct * vma)838 folio_within_vma(struct folio *folio, struct vm_area_struct *vma)
839 {
840 	return folio_within_range(folio, vma, vma->vm_start, vma->vm_end);
841 }
842 
843 /*
844  * mlock_vma_folio() and munlock_vma_folio():
845  * should be called with vma's mmap_lock held for read or write,
846  * under page table lock for the pte/pmd being added or removed.
847  *
848  * mlock is usually called at the end of folio_add_*_rmap_*(), munlock at
849  * the end of folio_remove_rmap_*(); but new anon folios are managed by
850  * folio_add_lru_vma() calling mlock_new_folio().
851  */
852 void mlock_folio(struct folio *folio);
mlock_vma_folio(struct folio * folio,struct vm_area_struct * vma)853 static inline void mlock_vma_folio(struct folio *folio,
854 				struct vm_area_struct *vma)
855 {
856 	/*
857 	 * The VM_SPECIAL check here serves two purposes.
858 	 * 1) VM_IO check prevents migration from double-counting during mlock.
859 	 * 2) Although mmap_region() and mlock_fixup() take care that VM_LOCKED
860 	 *    is never left set on a VM_SPECIAL vma, there is an interval while
861 	 *    file->f_op->mmap() is using vm_insert_page(s), when VM_LOCKED may
862 	 *    still be set while VM_SPECIAL bits are added: so ignore it then.
863 	 */
864 	if (unlikely((vma->vm_flags & (VM_LOCKED|VM_SPECIAL)) == VM_LOCKED))
865 		mlock_folio(folio);
866 }
867 
868 void munlock_folio(struct folio *folio);
munlock_vma_folio(struct folio * folio,struct vm_area_struct * vma)869 static inline void munlock_vma_folio(struct folio *folio,
870 					struct vm_area_struct *vma)
871 {
872 	/*
873 	 * munlock if the function is called. Ideally, we should only
874 	 * do munlock if any page of folio is unmapped from VMA and
875 	 * cause folio not fully mapped to VMA.
876 	 *
877 	 * But it's not easy to confirm that's the situation. So we
878 	 * always munlock the folio and page reclaim will correct it
879 	 * if it's wrong.
880 	 */
881 	if (unlikely(vma->vm_flags & VM_LOCKED))
882 		munlock_folio(folio);
883 }
884 
885 void mlock_new_folio(struct folio *folio);
886 bool need_mlock_drain(int cpu);
887 void mlock_drain_local(void);
888 void mlock_drain_remote(int cpu);
889 
890 extern pmd_t maybe_pmd_mkwrite(pmd_t pmd, struct vm_area_struct *vma);
891 
892 /*
893  * Return the start of user virtual address at the specific offset within
894  * a vma.
895  */
896 static inline unsigned long
vma_pgoff_address(pgoff_t pgoff,unsigned long nr_pages,struct vm_area_struct * vma)897 vma_pgoff_address(pgoff_t pgoff, unsigned long nr_pages,
898 		  struct vm_area_struct *vma)
899 {
900 	unsigned long address;
901 
902 	if (pgoff >= vma->vm_pgoff) {
903 		address = vma->vm_start +
904 			((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
905 		/* Check for address beyond vma (or wrapped through 0?) */
906 		if (address < vma->vm_start || address >= vma->vm_end)
907 			address = -EFAULT;
908 	} else if (pgoff + nr_pages - 1 >= vma->vm_pgoff) {
909 		/* Test above avoids possibility of wrap to 0 on 32-bit */
910 		address = vma->vm_start;
911 	} else {
912 		address = -EFAULT;
913 	}
914 	return address;
915 }
916 
917 /*
918  * Return the start of user virtual address of a page within a vma.
919  * Returns -EFAULT if all of the page is outside the range of vma.
920  * If page is a compound head, the entire compound page is considered.
921  */
922 static inline unsigned long
vma_address(struct page * page,struct vm_area_struct * vma)923 vma_address(struct page *page, struct vm_area_struct *vma)
924 {
925 	VM_BUG_ON_PAGE(PageKsm(page), page);	/* KSM page->index unusable */
926 	return vma_pgoff_address(page_to_pgoff(page), compound_nr(page), vma);
927 }
928 
929 /*
930  * Then at what user virtual address will none of the range be found in vma?
931  * Assumes that vma_address() already returned a good starting address.
932  */
vma_address_end(struct page_vma_mapped_walk * pvmw)933 static inline unsigned long vma_address_end(struct page_vma_mapped_walk *pvmw)
934 {
935 	struct vm_area_struct *vma = pvmw->vma;
936 	pgoff_t pgoff;
937 	unsigned long address;
938 
939 	/* Common case, plus ->pgoff is invalid for KSM */
940 	if (pvmw->nr_pages == 1)
941 		return pvmw->address + PAGE_SIZE;
942 
943 	pgoff = pvmw->pgoff + pvmw->nr_pages;
944 	address = vma->vm_start + ((pgoff - vma->vm_pgoff) << PAGE_SHIFT);
945 	/* Check for address beyond vma (or wrapped through 0?) */
946 	if (address < vma->vm_start || address > vma->vm_end)
947 		address = vma->vm_end;
948 	return address;
949 }
950 
maybe_unlock_mmap_for_io(struct vm_fault * vmf,struct file * fpin)951 static inline struct file *maybe_unlock_mmap_for_io(struct vm_fault *vmf,
952 						    struct file *fpin)
953 {
954 	int flags = vmf->flags;
955 
956 	if (fpin)
957 		return fpin;
958 
959 	/*
960 	 * FAULT_FLAG_RETRY_NOWAIT means we don't want to wait on page locks or
961 	 * anything, so we only pin the file and drop the mmap_lock if only
962 	 * FAULT_FLAG_ALLOW_RETRY is set, while this is the first attempt.
963 	 */
964 	if (fault_flag_allow_retry_first(flags) &&
965 	    !(flags & FAULT_FLAG_RETRY_NOWAIT)) {
966 		fpin = get_file(vmf->vma->vm_file);
967 		release_fault_lock(vmf);
968 	}
969 	return fpin;
970 }
971 #else /* !CONFIG_MMU */
unmap_mapping_folio(struct folio * folio)972 static inline void unmap_mapping_folio(struct folio *folio) { }
mlock_new_folio(struct folio * folio)973 static inline void mlock_new_folio(struct folio *folio) { }
need_mlock_drain(int cpu)974 static inline bool need_mlock_drain(int cpu) { return false; }
mlock_drain_local(void)975 static inline void mlock_drain_local(void) { }
mlock_drain_remote(int cpu)976 static inline void mlock_drain_remote(int cpu) { }
vunmap_range_noflush(unsigned long start,unsigned long end)977 static inline void vunmap_range_noflush(unsigned long start, unsigned long end)
978 {
979 }
980 #endif /* !CONFIG_MMU */
981 
982 /* Memory initialisation debug and verification */
983 #ifdef CONFIG_DEFERRED_STRUCT_PAGE_INIT
984 DECLARE_STATIC_KEY_TRUE(deferred_pages);
985 
986 bool __init deferred_grow_zone(struct zone *zone, unsigned int order);
987 #endif /* CONFIG_DEFERRED_STRUCT_PAGE_INIT */
988 
989 enum mminit_level {
990 	MMINIT_WARNING,
991 	MMINIT_VERIFY,
992 	MMINIT_TRACE
993 };
994 
995 #ifdef CONFIG_DEBUG_MEMORY_INIT
996 
997 extern int mminit_loglevel;
998 
999 #define mminit_dprintk(level, prefix, fmt, arg...) \
1000 do { \
1001 	if (level < mminit_loglevel) { \
1002 		if (level <= MMINIT_WARNING) \
1003 			pr_warn("mminit::" prefix " " fmt, ##arg);	\
1004 		else \
1005 			printk(KERN_DEBUG "mminit::" prefix " " fmt, ##arg); \
1006 	} \
1007 } while (0)
1008 
1009 extern void mminit_verify_pageflags_layout(void);
1010 extern void mminit_verify_zonelist(void);
1011 #else
1012 
mminit_dprintk(enum mminit_level level,const char * prefix,const char * fmt,...)1013 static inline void mminit_dprintk(enum mminit_level level,
1014 				const char *prefix, const char *fmt, ...)
1015 {
1016 }
1017 
mminit_verify_pageflags_layout(void)1018 static inline void mminit_verify_pageflags_layout(void)
1019 {
1020 }
1021 
mminit_verify_zonelist(void)1022 static inline void mminit_verify_zonelist(void)
1023 {
1024 }
1025 #endif /* CONFIG_DEBUG_MEMORY_INIT */
1026 
1027 #define NODE_RECLAIM_NOSCAN	-2
1028 #define NODE_RECLAIM_FULL	-1
1029 #define NODE_RECLAIM_SOME	0
1030 #define NODE_RECLAIM_SUCCESS	1
1031 
1032 #ifdef CONFIG_NUMA
1033 extern int node_reclaim(struct pglist_data *, gfp_t, unsigned int);
1034 extern int find_next_best_node(int node, nodemask_t *used_node_mask);
1035 #else
node_reclaim(struct pglist_data * pgdat,gfp_t mask,unsigned int order)1036 static inline int node_reclaim(struct pglist_data *pgdat, gfp_t mask,
1037 				unsigned int order)
1038 {
1039 	return NODE_RECLAIM_NOSCAN;
1040 }
find_next_best_node(int node,nodemask_t * used_node_mask)1041 static inline int find_next_best_node(int node, nodemask_t *used_node_mask)
1042 {
1043 	return NUMA_NO_NODE;
1044 }
1045 #endif
1046 
1047 /*
1048  * mm/memory-failure.c
1049  */
1050 extern int hwpoison_filter(struct page *p);
1051 
1052 extern u32 hwpoison_filter_dev_major;
1053 extern u32 hwpoison_filter_dev_minor;
1054 extern u64 hwpoison_filter_flags_mask;
1055 extern u64 hwpoison_filter_flags_value;
1056 extern u64 hwpoison_filter_memcg;
1057 extern u32 hwpoison_filter_enable;
1058 
1059 extern unsigned long  __must_check vm_mmap_pgoff(struct file *, unsigned long,
1060         unsigned long, unsigned long,
1061         unsigned long, unsigned long);
1062 
1063 extern void set_pageblock_order(void);
1064 unsigned long reclaim_pages(struct list_head *folio_list, bool ignore_references);
1065 unsigned int reclaim_clean_pages_from_list(struct zone *zone,
1066 					    struct list_head *folio_list);
1067 /* The ALLOC_WMARK bits are used as an index to zone->watermark */
1068 #define ALLOC_WMARK_MIN		WMARK_MIN
1069 #define ALLOC_WMARK_LOW		WMARK_LOW
1070 #define ALLOC_WMARK_HIGH	WMARK_HIGH
1071 #define ALLOC_NO_WATERMARKS	0x04 /* don't check watermarks at all */
1072 
1073 /* Mask to get the watermark bits */
1074 #define ALLOC_WMARK_MASK	(ALLOC_NO_WATERMARKS-1)
1075 
1076 /*
1077  * Only MMU archs have async oom victim reclaim - aka oom_reaper so we
1078  * cannot assume a reduced access to memory reserves is sufficient for
1079  * !MMU
1080  */
1081 #ifdef CONFIG_MMU
1082 #define ALLOC_OOM		0x08
1083 #else
1084 #define ALLOC_OOM		ALLOC_NO_WATERMARKS
1085 #endif
1086 
1087 #define ALLOC_NON_BLOCK		 0x10 /* Caller cannot block. Allow access
1088 				       * to 25% of the min watermark or
1089 				       * 62.5% if __GFP_HIGH is set.
1090 				       */
1091 #define ALLOC_MIN_RESERVE	 0x20 /* __GFP_HIGH set. Allow access to 50%
1092 				       * of the min watermark.
1093 				       */
1094 #define ALLOC_CPUSET		 0x40 /* check for correct cpuset */
1095 #define ALLOC_CMA		 0x80 /* allow allocations from CMA areas */
1096 #ifdef CONFIG_ZONE_DMA32
1097 #define ALLOC_NOFRAGMENT	0x100 /* avoid mixing pageblock types */
1098 #else
1099 #define ALLOC_NOFRAGMENT	  0x0
1100 #endif
1101 #define ALLOC_HIGHATOMIC	0x200 /* Allows access to MIGRATE_HIGHATOMIC */
1102 #define ALLOC_KSWAPD		0x800 /* allow waking of kswapd, __GFP_KSWAPD_RECLAIM set */
1103 
1104 /* Flags that allow allocations below the min watermark. */
1105 #define ALLOC_RESERVES (ALLOC_NON_BLOCK|ALLOC_MIN_RESERVE|ALLOC_HIGHATOMIC|ALLOC_OOM)
1106 
1107 enum ttu_flags;
1108 struct tlbflush_unmap_batch;
1109 
1110 
1111 /*
1112  * only for MM internal work items which do not depend on
1113  * any allocations or locks which might depend on allocations
1114  */
1115 extern struct workqueue_struct *mm_percpu_wq;
1116 
1117 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1118 void try_to_unmap_flush(void);
1119 void try_to_unmap_flush_dirty(void);
1120 void flush_tlb_batched_pending(struct mm_struct *mm);
1121 #else
try_to_unmap_flush(void)1122 static inline void try_to_unmap_flush(void)
1123 {
1124 }
try_to_unmap_flush_dirty(void)1125 static inline void try_to_unmap_flush_dirty(void)
1126 {
1127 }
flush_tlb_batched_pending(struct mm_struct * mm)1128 static inline void flush_tlb_batched_pending(struct mm_struct *mm)
1129 {
1130 }
1131 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
1132 
1133 extern const struct trace_print_flags pageflag_names[];
1134 extern const struct trace_print_flags pagetype_names[];
1135 extern const struct trace_print_flags vmaflag_names[];
1136 extern const struct trace_print_flags gfpflag_names[];
1137 
is_migrate_highatomic(enum migratetype migratetype)1138 static inline bool is_migrate_highatomic(enum migratetype migratetype)
1139 {
1140 	return migratetype == MIGRATE_HIGHATOMIC;
1141 }
1142 
is_migrate_highatomic_page(struct page * page)1143 static inline bool is_migrate_highatomic_page(struct page *page)
1144 {
1145 	return get_pageblock_migratetype(page) == MIGRATE_HIGHATOMIC;
1146 }
1147 
1148 void setup_zone_pageset(struct zone *zone);
1149 
1150 struct migration_target_control {
1151 	int nid;		/* preferred node id */
1152 	nodemask_t *nmask;
1153 	gfp_t gfp_mask;
1154 };
1155 
1156 /*
1157  * mm/filemap.c
1158  */
1159 size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
1160 			      struct folio *folio, loff_t fpos, size_t size);
1161 
1162 /*
1163  * mm/vmalloc.c
1164  */
1165 #ifdef CONFIG_MMU
1166 void __init vmalloc_init(void);
1167 int __must_check vmap_pages_range_noflush(unsigned long addr, unsigned long end,
1168                 pgprot_t prot, struct page **pages, unsigned int page_shift);
1169 #else
vmalloc_init(void)1170 static inline void vmalloc_init(void)
1171 {
1172 }
1173 
1174 static inline
vmap_pages_range_noflush(unsigned long addr,unsigned long end,pgprot_t prot,struct page ** pages,unsigned int page_shift)1175 int __must_check vmap_pages_range_noflush(unsigned long addr, unsigned long end,
1176                 pgprot_t prot, struct page **pages, unsigned int page_shift)
1177 {
1178 	return -EINVAL;
1179 }
1180 #endif
1181 
1182 int __must_check __vmap_pages_range_noflush(unsigned long addr,
1183 			       unsigned long end, pgprot_t prot,
1184 			       struct page **pages, unsigned int page_shift);
1185 
1186 void vunmap_range_noflush(unsigned long start, unsigned long end);
1187 
1188 void __vunmap_range_noflush(unsigned long start, unsigned long end);
1189 
1190 int numa_migrate_prep(struct folio *folio, struct vm_area_struct *vma,
1191 		      unsigned long addr, int page_nid, int *flags);
1192 
1193 void free_zone_device_page(struct page *page);
1194 int migrate_device_coherent_page(struct page *page);
1195 
1196 /*
1197  * mm/gup.c
1198  */
1199 int __must_check try_grab_folio(struct folio *folio, int refs,
1200 				unsigned int flags);
1201 
1202 /*
1203  * mm/huge_memory.c
1204  */
1205 struct page *follow_trans_huge_pmd(struct vm_area_struct *vma,
1206 				   unsigned long addr, pmd_t *pmd,
1207 				   unsigned int flags);
1208 
1209 enum {
1210 	/* mark page accessed */
1211 	FOLL_TOUCH = 1 << 16,
1212 	/* a retry, previous pass started an IO */
1213 	FOLL_TRIED = 1 << 17,
1214 	/* we are working on non-current tsk/mm */
1215 	FOLL_REMOTE = 1 << 18,
1216 	/* pages must be released via unpin_user_page */
1217 	FOLL_PIN = 1 << 19,
1218 	/* gup_fast: prevent fall-back to slow gup */
1219 	FOLL_FAST_ONLY = 1 << 20,
1220 	/* allow unlocking the mmap lock */
1221 	FOLL_UNLOCKABLE = 1 << 21,
1222 	/* VMA lookup+checks compatible with MADV_POPULATE_(READ|WRITE) */
1223 	FOLL_MADV_POPULATE = 1 << 22,
1224 };
1225 
1226 #define INTERNAL_GUP_FLAGS (FOLL_TOUCH | FOLL_TRIED | FOLL_REMOTE | FOLL_PIN | \
1227 			    FOLL_FAST_ONLY | FOLL_UNLOCKABLE | \
1228 			    FOLL_MADV_POPULATE)
1229 
1230 /*
1231  * Indicates for which pages that are write-protected in the page table,
1232  * whether GUP has to trigger unsharing via FAULT_FLAG_UNSHARE such that the
1233  * GUP pin will remain consistent with the pages mapped into the page tables
1234  * of the MM.
1235  *
1236  * Temporary unmapping of PageAnonExclusive() pages or clearing of
1237  * PageAnonExclusive() has to protect against concurrent GUP:
1238  * * Ordinary GUP: Using the PT lock
1239  * * GUP-fast and fork(): mm->write_protect_seq
1240  * * GUP-fast and KSM or temporary unmapping (swap, migration): see
1241  *    folio_try_share_anon_rmap_*()
1242  *
1243  * Must be called with the (sub)page that's actually referenced via the
1244  * page table entry, which might not necessarily be the head page for a
1245  * PTE-mapped THP.
1246  *
1247  * If the vma is NULL, we're coming from the GUP-fast path and might have
1248  * to fallback to the slow path just to lookup the vma.
1249  */
gup_must_unshare(struct vm_area_struct * vma,unsigned int flags,struct page * page)1250 static inline bool gup_must_unshare(struct vm_area_struct *vma,
1251 				    unsigned int flags, struct page *page)
1252 {
1253 	/*
1254 	 * FOLL_WRITE is implicitly handled correctly as the page table entry
1255 	 * has to be writable -- and if it references (part of) an anonymous
1256 	 * folio, that part is required to be marked exclusive.
1257 	 */
1258 	if ((flags & (FOLL_WRITE | FOLL_PIN)) != FOLL_PIN)
1259 		return false;
1260 	/*
1261 	 * Note: PageAnon(page) is stable until the page is actually getting
1262 	 * freed.
1263 	 */
1264 	if (!PageAnon(page)) {
1265 		/*
1266 		 * We only care about R/O long-term pining: R/O short-term
1267 		 * pinning does not have the semantics to observe successive
1268 		 * changes through the process page tables.
1269 		 */
1270 		if (!(flags & FOLL_LONGTERM))
1271 			return false;
1272 
1273 		/* We really need the vma ... */
1274 		if (!vma)
1275 			return true;
1276 
1277 		/*
1278 		 * ... because we only care about writable private ("COW")
1279 		 * mappings where we have to break COW early.
1280 		 */
1281 		return is_cow_mapping(vma->vm_flags);
1282 	}
1283 
1284 	/* Paired with a memory barrier in folio_try_share_anon_rmap_*(). */
1285 	if (IS_ENABLED(CONFIG_HAVE_FAST_GUP))
1286 		smp_rmb();
1287 
1288 	/*
1289 	 * During GUP-fast we might not get called on the head page for a
1290 	 * hugetlb page that is mapped using cont-PTE, because GUP-fast does
1291 	 * not work with the abstracted hugetlb PTEs that always point at the
1292 	 * head page. For hugetlb, PageAnonExclusive only applies on the head
1293 	 * page (as it cannot be partially COW-shared), so lookup the head page.
1294 	 */
1295 	if (unlikely(!PageHead(page) && PageHuge(page)))
1296 		page = compound_head(page);
1297 
1298 	/*
1299 	 * Note that PageKsm() pages cannot be exclusive, and consequently,
1300 	 * cannot get pinned.
1301 	 */
1302 	return !PageAnonExclusive(page);
1303 }
1304 
1305 extern bool mirrored_kernelcore;
1306 extern bool memblock_has_mirror(void);
1307 
vma_soft_dirty_enabled(struct vm_area_struct * vma)1308 static inline bool vma_soft_dirty_enabled(struct vm_area_struct *vma)
1309 {
1310 	/*
1311 	 * NOTE: we must check this before VM_SOFTDIRTY on soft-dirty
1312 	 * enablements, because when without soft-dirty being compiled in,
1313 	 * VM_SOFTDIRTY is defined as 0x0, then !(vm_flags & VM_SOFTDIRTY)
1314 	 * will be constantly true.
1315 	 */
1316 	if (!IS_ENABLED(CONFIG_MEM_SOFT_DIRTY))
1317 		return false;
1318 
1319 	/*
1320 	 * Soft-dirty is kind of special: its tracking is enabled when the
1321 	 * vma flags not set.
1322 	 */
1323 	return !(vma->vm_flags & VM_SOFTDIRTY);
1324 }
1325 
pmd_needs_soft_dirty_wp(struct vm_area_struct * vma,pmd_t pmd)1326 static inline bool pmd_needs_soft_dirty_wp(struct vm_area_struct *vma, pmd_t pmd)
1327 {
1328 	return vma_soft_dirty_enabled(vma) && !pmd_soft_dirty(pmd);
1329 }
1330 
pte_needs_soft_dirty_wp(struct vm_area_struct * vma,pte_t pte)1331 static inline bool pte_needs_soft_dirty_wp(struct vm_area_struct *vma, pte_t pte)
1332 {
1333 	return vma_soft_dirty_enabled(vma) && !pte_soft_dirty(pte);
1334 }
1335 
vma_iter_config(struct vma_iterator * vmi,unsigned long index,unsigned long last)1336 static inline void vma_iter_config(struct vma_iterator *vmi,
1337 		unsigned long index, unsigned long last)
1338 {
1339 	MAS_BUG_ON(&vmi->mas, vmi->mas.node != MAS_START &&
1340 		   (vmi->mas.index > index || vmi->mas.last < index));
1341 	__mas_set_range(&vmi->mas, index, last - 1);
1342 }
1343 
1344 /*
1345  * VMA Iterator functions shared between nommu and mmap
1346  */
vma_iter_prealloc(struct vma_iterator * vmi,struct vm_area_struct * vma)1347 static inline int vma_iter_prealloc(struct vma_iterator *vmi,
1348 		struct vm_area_struct *vma)
1349 {
1350 	return mas_preallocate(&vmi->mas, vma, GFP_KERNEL);
1351 }
1352 
vma_iter_clear(struct vma_iterator * vmi)1353 static inline void vma_iter_clear(struct vma_iterator *vmi)
1354 {
1355 	mas_store_prealloc(&vmi->mas, NULL);
1356 }
1357 
vma_iter_load(struct vma_iterator * vmi)1358 static inline struct vm_area_struct *vma_iter_load(struct vma_iterator *vmi)
1359 {
1360 	return mas_walk(&vmi->mas);
1361 }
1362 
1363 /* Store a VMA with preallocated memory */
vma_iter_store(struct vma_iterator * vmi,struct vm_area_struct * vma)1364 static inline void vma_iter_store(struct vma_iterator *vmi,
1365 				  struct vm_area_struct *vma)
1366 {
1367 
1368 #if defined(CONFIG_DEBUG_VM_MAPLE_TREE)
1369 	if (MAS_WARN_ON(&vmi->mas, vmi->mas.node != MAS_START &&
1370 			vmi->mas.index > vma->vm_start)) {
1371 		pr_warn("%lx > %lx\n store vma %lx-%lx\n into slot %lx-%lx\n",
1372 			vmi->mas.index, vma->vm_start, vma->vm_start,
1373 			vma->vm_end, vmi->mas.index, vmi->mas.last);
1374 	}
1375 	if (MAS_WARN_ON(&vmi->mas, vmi->mas.node != MAS_START &&
1376 			vmi->mas.last <  vma->vm_start)) {
1377 		pr_warn("%lx < %lx\nstore vma %lx-%lx\ninto slot %lx-%lx\n",
1378 		       vmi->mas.last, vma->vm_start, vma->vm_start, vma->vm_end,
1379 		       vmi->mas.index, vmi->mas.last);
1380 	}
1381 #endif
1382 
1383 	if (vmi->mas.node != MAS_START &&
1384 	    ((vmi->mas.index > vma->vm_start) || (vmi->mas.last < vma->vm_start)))
1385 		vma_iter_invalidate(vmi);
1386 
1387 	__mas_set_range(&vmi->mas, vma->vm_start, vma->vm_end - 1);
1388 	mas_store_prealloc(&vmi->mas, vma);
1389 }
1390 
vma_iter_store_gfp(struct vma_iterator * vmi,struct vm_area_struct * vma,gfp_t gfp)1391 static inline int vma_iter_store_gfp(struct vma_iterator *vmi,
1392 			struct vm_area_struct *vma, gfp_t gfp)
1393 {
1394 	if (vmi->mas.node != MAS_START &&
1395 	    ((vmi->mas.index > vma->vm_start) || (vmi->mas.last < vma->vm_start)))
1396 		vma_iter_invalidate(vmi);
1397 
1398 	__mas_set_range(&vmi->mas, vma->vm_start, vma->vm_end - 1);
1399 	mas_store_gfp(&vmi->mas, vma, gfp);
1400 	if (unlikely(mas_is_err(&vmi->mas)))
1401 		return -ENOMEM;
1402 
1403 	return 0;
1404 }
1405 
1406 /*
1407  * VMA lock generalization
1408  */
1409 struct vma_prepare {
1410 	struct vm_area_struct *vma;
1411 	struct vm_area_struct *adj_next;
1412 	struct file *file;
1413 	struct address_space *mapping;
1414 	struct anon_vma *anon_vma;
1415 	struct vm_area_struct *insert;
1416 	struct vm_area_struct *remove;
1417 	struct vm_area_struct *remove2;
1418 };
1419 
1420 #define SRC_PAGE_MAPPED		BIT(0)
1421 #define SRC_PAGE_MLOCKED	BIT(1)
1422 #define SRC_PAGE_CLEAN		BIT(2)
1423 #define SRC_PAGE_USAGE_MASK	(BIT(3) - 1)
1424 
src_page_usage(struct page * page)1425 static inline unsigned long src_page_usage(struct page *page)
1426 {
1427 	struct folio *src = page_folio(page);
1428 	int i = folio_page_idx(src, page);
1429 
1430 	if (folio_can_split(src) || !src->_dst_ul)
1431 		return 0;
1432 
1433 	return src->_dst_ul[i] & SRC_PAGE_USAGE_MASK;
1434 }
1435 
can_discard_src(struct page * page)1436 static inline bool can_discard_src(struct page *page)
1437 {
1438 	return src_page_usage(page) & SRC_PAGE_CLEAN;
1439 }
1440 
set_src_usage(struct page * page,unsigned long usage)1441 static inline void set_src_usage(struct page *page, unsigned long usage)
1442 {
1443 	struct folio *src = page_folio(page);
1444 	int i = folio_page_idx(src, page);
1445 
1446 	if (!folio_can_split(src) && src->_dst_ul)
1447 		src->_dst_ul[i] |= usage;
1448 }
1449 
folio_dst_page(struct folio * src,int i)1450 static inline struct page *folio_dst_page(struct folio *src, int i)
1451 {
1452 	if (folio_can_split(src) || !src->_dst_ul)
1453 		return folio_page(src, i);
1454 
1455 	return (void *)(src->_dst_ul[i] & ~SRC_PAGE_USAGE_MASK);
1456 }
1457 
1458 #ifdef CONFIG_64BIT
can_do_mseal(unsigned long flags)1459 static inline int can_do_mseal(unsigned long flags)
1460 {
1461 	if (flags)
1462 		return -EINVAL;
1463 
1464 	return 0;
1465 }
1466 
1467 bool can_modify_mm(struct mm_struct *mm, unsigned long start,
1468 		unsigned long end);
1469 bool can_modify_mm_madv(struct mm_struct *mm, unsigned long start,
1470 		unsigned long end, int behavior);
1471 #else
can_do_mseal(unsigned long flags)1472 static inline int can_do_mseal(unsigned long flags)
1473 {
1474 	return -EPERM;
1475 }
1476 
can_modify_mm(struct mm_struct * mm,unsigned long start,unsigned long end)1477 static inline bool can_modify_mm(struct mm_struct *mm, unsigned long start,
1478 		unsigned long end)
1479 {
1480 	return true;
1481 }
1482 
can_modify_mm_madv(struct mm_struct * mm,unsigned long start,unsigned long end,int behavior)1483 static inline bool can_modify_mm_madv(struct mm_struct *mm, unsigned long start,
1484 		unsigned long end, int behavior)
1485 {
1486 	return true;
1487 }
1488 #endif
1489 #endif	/* __MM_INTERNAL_H */
1490