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