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