xref: /linux/mm/memory.c (revision cf42d4cccf0d01e375175393776a16dc47b9996f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/memory.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  */
7 
8 /*
9  * demand-loading started 01.12.91 - seems it is high on the list of
10  * things wanted, and it should be easy to implement. - Linus
11  */
12 
13 /*
14  * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
15  * pages started 02.12.91, seems to work. - Linus.
16  *
17  * Tested sharing by executing about 30 /bin/sh: under the old kernel it
18  * would have taken more than the 6M I have free, but it worked well as
19  * far as I could see.
20  *
21  * Also corrected some "invalidate()"s - I wasn't doing enough of them.
22  */
23 
24 /*
25  * Real VM (paging to/from disk) started 18.12.91. Much more work and
26  * thought has to go into this. Oh, well..
27  * 19.12.91  -  works, somewhat. Sometimes I get faults, don't know why.
28  *		Found it. Everything seems to work now.
29  * 20.12.91  -  Ok, making the swap-device changeable like the root.
30  */
31 
32 /*
33  * 05.04.94  -  Multi-page memory management added for v1.1.
34  *              Idea by Alex Bligh (alex@cconcepts.co.uk)
35  *
36  * 16.07.99  -  Support of BIGMEM added by Gerhard Wichert, Siemens AG
37  *		(Gerhard.Wichert@pdb.siemens.de)
38  *
39  * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
40  */
41 
42 #include <linux/kernel_stat.h>
43 #include <linux/mm.h>
44 #include <linux/mm_inline.h>
45 #include <linux/sched/mm.h>
46 #include <linux/sched/numa_balancing.h>
47 #include <linux/sched/task.h>
48 #include <linux/hugetlb.h>
49 #include <linux/mman.h>
50 #include <linux/swap.h>
51 #include <linux/highmem.h>
52 #include <linux/pagemap.h>
53 #include <linux/memremap.h>
54 #include <linux/kmsan.h>
55 #include <linux/ksm.h>
56 #include <linux/rmap.h>
57 #include <linux/export.h>
58 #include <linux/delayacct.h>
59 #include <linux/init.h>
60 #include <linux/pfn_t.h>
61 #include <linux/writeback.h>
62 #include <linux/memcontrol.h>
63 #include <linux/mmu_notifier.h>
64 #include <linux/swapops.h>
65 #include <linux/elf.h>
66 #include <linux/gfp.h>
67 #include <linux/migrate.h>
68 #include <linux/string.h>
69 #include <linux/memory-tiers.h>
70 #include <linux/debugfs.h>
71 #include <linux/userfaultfd_k.h>
72 #include <linux/dax.h>
73 #include <linux/oom.h>
74 #include <linux/numa.h>
75 #include <linux/perf_event.h>
76 #include <linux/ptrace.h>
77 #include <linux/vmalloc.h>
78 #include <linux/sched/sysctl.h>
79 
80 #include <trace/events/kmem.h>
81 
82 #include <asm/io.h>
83 #include <asm/mmu_context.h>
84 #include <asm/pgalloc.h>
85 #include <linux/uaccess.h>
86 #include <asm/tlb.h>
87 #include <asm/tlbflush.h>
88 
89 #include "pgalloc-track.h"
90 #include "internal.h"
91 #include "swap.h"
92 
93 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
94 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
95 #endif
96 
97 static vm_fault_t do_fault(struct vm_fault *vmf);
98 static vm_fault_t do_anonymous_page(struct vm_fault *vmf);
99 static bool vmf_pte_changed(struct vm_fault *vmf);
100 
101 /*
102  * Return true if the original pte was a uffd-wp pte marker (so the pte was
103  * wr-protected).
104  */
105 static __always_inline bool vmf_orig_pte_uffd_wp(struct vm_fault *vmf)
106 {
107 	if (!userfaultfd_wp(vmf->vma))
108 		return false;
109 	if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID))
110 		return false;
111 
112 	return pte_marker_uffd_wp(vmf->orig_pte);
113 }
114 
115 /*
116  * Randomize the address space (stacks, mmaps, brk, etc.).
117  *
118  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
119  *   as ancient (libc5 based) binaries can segfault. )
120  */
121 int randomize_va_space __read_mostly =
122 #ifdef CONFIG_COMPAT_BRK
123 					1;
124 #else
125 					2;
126 #endif
127 
128 #ifndef arch_wants_old_prefaulted_pte
129 static inline bool arch_wants_old_prefaulted_pte(void)
130 {
131 	/*
132 	 * Transitioning a PTE from 'old' to 'young' can be expensive on
133 	 * some architectures, even if it's performed in hardware. By
134 	 * default, "false" means prefaulted entries will be 'young'.
135 	 */
136 	return false;
137 }
138 #endif
139 
140 static int __init disable_randmaps(char *s)
141 {
142 	randomize_va_space = 0;
143 	return 1;
144 }
145 __setup("norandmaps", disable_randmaps);
146 
147 unsigned long zero_pfn __read_mostly;
148 EXPORT_SYMBOL(zero_pfn);
149 
150 unsigned long highest_memmap_pfn __read_mostly;
151 
152 /*
153  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
154  */
155 static int __init init_zero_pfn(void)
156 {
157 	zero_pfn = page_to_pfn(ZERO_PAGE(0));
158 	return 0;
159 }
160 early_initcall(init_zero_pfn);
161 
162 void mm_trace_rss_stat(struct mm_struct *mm, int member)
163 {
164 	trace_rss_stat(mm, member);
165 }
166 
167 /*
168  * Note: this doesn't free the actual pages themselves. That
169  * has been handled earlier when unmapping all the memory regions.
170  */
171 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
172 			   unsigned long addr)
173 {
174 	pgtable_t token = pmd_pgtable(*pmd);
175 	pmd_clear(pmd);
176 	pte_free_tlb(tlb, token, addr);
177 	mm_dec_nr_ptes(tlb->mm);
178 }
179 
180 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
181 				unsigned long addr, unsigned long end,
182 				unsigned long floor, unsigned long ceiling)
183 {
184 	pmd_t *pmd;
185 	unsigned long next;
186 	unsigned long start;
187 
188 	start = addr;
189 	pmd = pmd_offset(pud, addr);
190 	do {
191 		next = pmd_addr_end(addr, end);
192 		if (pmd_none_or_clear_bad(pmd))
193 			continue;
194 		free_pte_range(tlb, pmd, addr);
195 	} while (pmd++, addr = next, addr != end);
196 
197 	start &= PUD_MASK;
198 	if (start < floor)
199 		return;
200 	if (ceiling) {
201 		ceiling &= PUD_MASK;
202 		if (!ceiling)
203 			return;
204 	}
205 	if (end - 1 > ceiling - 1)
206 		return;
207 
208 	pmd = pmd_offset(pud, start);
209 	pud_clear(pud);
210 	pmd_free_tlb(tlb, pmd, start);
211 	mm_dec_nr_pmds(tlb->mm);
212 }
213 
214 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
215 				unsigned long addr, unsigned long end,
216 				unsigned long floor, unsigned long ceiling)
217 {
218 	pud_t *pud;
219 	unsigned long next;
220 	unsigned long start;
221 
222 	start = addr;
223 	pud = pud_offset(p4d, addr);
224 	do {
225 		next = pud_addr_end(addr, end);
226 		if (pud_none_or_clear_bad(pud))
227 			continue;
228 		free_pmd_range(tlb, pud, addr, next, floor, ceiling);
229 	} while (pud++, addr = next, addr != end);
230 
231 	start &= P4D_MASK;
232 	if (start < floor)
233 		return;
234 	if (ceiling) {
235 		ceiling &= P4D_MASK;
236 		if (!ceiling)
237 			return;
238 	}
239 	if (end - 1 > ceiling - 1)
240 		return;
241 
242 	pud = pud_offset(p4d, start);
243 	p4d_clear(p4d);
244 	pud_free_tlb(tlb, pud, start);
245 	mm_dec_nr_puds(tlb->mm);
246 }
247 
248 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
249 				unsigned long addr, unsigned long end,
250 				unsigned long floor, unsigned long ceiling)
251 {
252 	p4d_t *p4d;
253 	unsigned long next;
254 	unsigned long start;
255 
256 	start = addr;
257 	p4d = p4d_offset(pgd, addr);
258 	do {
259 		next = p4d_addr_end(addr, end);
260 		if (p4d_none_or_clear_bad(p4d))
261 			continue;
262 		free_pud_range(tlb, p4d, addr, next, floor, ceiling);
263 	} while (p4d++, addr = next, addr != end);
264 
265 	start &= PGDIR_MASK;
266 	if (start < floor)
267 		return;
268 	if (ceiling) {
269 		ceiling &= PGDIR_MASK;
270 		if (!ceiling)
271 			return;
272 	}
273 	if (end - 1 > ceiling - 1)
274 		return;
275 
276 	p4d = p4d_offset(pgd, start);
277 	pgd_clear(pgd);
278 	p4d_free_tlb(tlb, p4d, start);
279 }
280 
281 /*
282  * This function frees user-level page tables of a process.
283  */
284 void free_pgd_range(struct mmu_gather *tlb,
285 			unsigned long addr, unsigned long end,
286 			unsigned long floor, unsigned long ceiling)
287 {
288 	pgd_t *pgd;
289 	unsigned long next;
290 
291 	/*
292 	 * The next few lines have given us lots of grief...
293 	 *
294 	 * Why are we testing PMD* at this top level?  Because often
295 	 * there will be no work to do at all, and we'd prefer not to
296 	 * go all the way down to the bottom just to discover that.
297 	 *
298 	 * Why all these "- 1"s?  Because 0 represents both the bottom
299 	 * of the address space and the top of it (using -1 for the
300 	 * top wouldn't help much: the masks would do the wrong thing).
301 	 * The rule is that addr 0 and floor 0 refer to the bottom of
302 	 * the address space, but end 0 and ceiling 0 refer to the top
303 	 * Comparisons need to use "end - 1" and "ceiling - 1" (though
304 	 * that end 0 case should be mythical).
305 	 *
306 	 * Wherever addr is brought up or ceiling brought down, we must
307 	 * be careful to reject "the opposite 0" before it confuses the
308 	 * subsequent tests.  But what about where end is brought down
309 	 * by PMD_SIZE below? no, end can't go down to 0 there.
310 	 *
311 	 * Whereas we round start (addr) and ceiling down, by different
312 	 * masks at different levels, in order to test whether a table
313 	 * now has no other vmas using it, so can be freed, we don't
314 	 * bother to round floor or end up - the tests don't need that.
315 	 */
316 
317 	addr &= PMD_MASK;
318 	if (addr < floor) {
319 		addr += PMD_SIZE;
320 		if (!addr)
321 			return;
322 	}
323 	if (ceiling) {
324 		ceiling &= PMD_MASK;
325 		if (!ceiling)
326 			return;
327 	}
328 	if (end - 1 > ceiling - 1)
329 		end -= PMD_SIZE;
330 	if (addr > end - 1)
331 		return;
332 	/*
333 	 * We add page table cache pages with PAGE_SIZE,
334 	 * (see pte_free_tlb()), flush the tlb if we need
335 	 */
336 	tlb_change_page_size(tlb, PAGE_SIZE);
337 	pgd = pgd_offset(tlb->mm, addr);
338 	do {
339 		next = pgd_addr_end(addr, end);
340 		if (pgd_none_or_clear_bad(pgd))
341 			continue;
342 		free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
343 	} while (pgd++, addr = next, addr != end);
344 }
345 
346 void free_pgtables(struct mmu_gather *tlb, struct ma_state *mas,
347 		   struct vm_area_struct *vma, unsigned long floor,
348 		   unsigned long ceiling, bool mm_wr_locked)
349 {
350 	struct unlink_vma_file_batch vb;
351 
352 	do {
353 		unsigned long addr = vma->vm_start;
354 		struct vm_area_struct *next;
355 
356 		/*
357 		 * Note: USER_PGTABLES_CEILING may be passed as ceiling and may
358 		 * be 0.  This will underflow and is okay.
359 		 */
360 		next = mas_find(mas, ceiling - 1);
361 		if (unlikely(xa_is_zero(next)))
362 			next = NULL;
363 
364 		/*
365 		 * Hide vma from rmap and truncate_pagecache before freeing
366 		 * pgtables
367 		 */
368 		if (mm_wr_locked)
369 			vma_start_write(vma);
370 		unlink_anon_vmas(vma);
371 
372 		if (is_vm_hugetlb_page(vma)) {
373 			unlink_file_vma(vma);
374 			hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
375 				floor, next ? next->vm_start : ceiling);
376 		} else {
377 			unlink_file_vma_batch_init(&vb);
378 			unlink_file_vma_batch_add(&vb, vma);
379 
380 			/*
381 			 * Optimization: gather nearby vmas into one call down
382 			 */
383 			while (next && next->vm_start <= vma->vm_end + PMD_SIZE
384 			       && !is_vm_hugetlb_page(next)) {
385 				vma = next;
386 				next = mas_find(mas, ceiling - 1);
387 				if (unlikely(xa_is_zero(next)))
388 					next = NULL;
389 				if (mm_wr_locked)
390 					vma_start_write(vma);
391 				unlink_anon_vmas(vma);
392 				unlink_file_vma_batch_add(&vb, vma);
393 			}
394 			unlink_file_vma_batch_final(&vb);
395 			free_pgd_range(tlb, addr, vma->vm_end,
396 				floor, next ? next->vm_start : ceiling);
397 		}
398 		vma = next;
399 	} while (vma);
400 }
401 
402 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte)
403 {
404 	spinlock_t *ptl = pmd_lock(mm, pmd);
405 
406 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
407 		mm_inc_nr_ptes(mm);
408 		/*
409 		 * Ensure all pte setup (eg. pte page lock and page clearing) are
410 		 * visible before the pte is made visible to other CPUs by being
411 		 * put into page tables.
412 		 *
413 		 * The other side of the story is the pointer chasing in the page
414 		 * table walking code (when walking the page table without locking;
415 		 * ie. most of the time). Fortunately, these data accesses consist
416 		 * of a chain of data-dependent loads, meaning most CPUs (alpha
417 		 * being the notable exception) will already guarantee loads are
418 		 * seen in-order. See the alpha page table accessors for the
419 		 * smp_rmb() barriers in page table walking code.
420 		 */
421 		smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
422 		pmd_populate(mm, pmd, *pte);
423 		*pte = NULL;
424 	}
425 	spin_unlock(ptl);
426 }
427 
428 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
429 {
430 	pgtable_t new = pte_alloc_one(mm);
431 	if (!new)
432 		return -ENOMEM;
433 
434 	pmd_install(mm, pmd, &new);
435 	if (new)
436 		pte_free(mm, new);
437 	return 0;
438 }
439 
440 int __pte_alloc_kernel(pmd_t *pmd)
441 {
442 	pte_t *new = pte_alloc_one_kernel(&init_mm);
443 	if (!new)
444 		return -ENOMEM;
445 
446 	spin_lock(&init_mm.page_table_lock);
447 	if (likely(pmd_none(*pmd))) {	/* Has another populated it ? */
448 		smp_wmb(); /* See comment in pmd_install() */
449 		pmd_populate_kernel(&init_mm, pmd, new);
450 		new = NULL;
451 	}
452 	spin_unlock(&init_mm.page_table_lock);
453 	if (new)
454 		pte_free_kernel(&init_mm, new);
455 	return 0;
456 }
457 
458 static inline void init_rss_vec(int *rss)
459 {
460 	memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
461 }
462 
463 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
464 {
465 	int i;
466 
467 	for (i = 0; i < NR_MM_COUNTERS; i++)
468 		if (rss[i])
469 			add_mm_counter(mm, i, rss[i]);
470 }
471 
472 /*
473  * This function is called to print an error when a bad pte
474  * is found. For example, we might have a PFN-mapped pte in
475  * a region that doesn't allow it.
476  *
477  * The calling function must still handle the error.
478  */
479 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
480 			  pte_t pte, struct page *page)
481 {
482 	pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
483 	p4d_t *p4d = p4d_offset(pgd, addr);
484 	pud_t *pud = pud_offset(p4d, addr);
485 	pmd_t *pmd = pmd_offset(pud, addr);
486 	struct address_space *mapping;
487 	pgoff_t index;
488 	static unsigned long resume;
489 	static unsigned long nr_shown;
490 	static unsigned long nr_unshown;
491 
492 	/*
493 	 * Allow a burst of 60 reports, then keep quiet for that minute;
494 	 * or allow a steady drip of one report per second.
495 	 */
496 	if (nr_shown == 60) {
497 		if (time_before(jiffies, resume)) {
498 			nr_unshown++;
499 			return;
500 		}
501 		if (nr_unshown) {
502 			pr_alert("BUG: Bad page map: %lu messages suppressed\n",
503 				 nr_unshown);
504 			nr_unshown = 0;
505 		}
506 		nr_shown = 0;
507 	}
508 	if (nr_shown++ == 0)
509 		resume = jiffies + 60 * HZ;
510 
511 	mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
512 	index = linear_page_index(vma, addr);
513 
514 	pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
515 		 current->comm,
516 		 (long long)pte_val(pte), (long long)pmd_val(*pmd));
517 	if (page)
518 		dump_page(page, "bad pte");
519 	pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
520 		 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
521 	pr_alert("file:%pD fault:%ps mmap:%ps read_folio:%ps\n",
522 		 vma->vm_file,
523 		 vma->vm_ops ? vma->vm_ops->fault : NULL,
524 		 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
525 		 mapping ? mapping->a_ops->read_folio : NULL);
526 	dump_stack();
527 	add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
528 }
529 
530 /*
531  * vm_normal_page -- This function gets the "struct page" associated with a pte.
532  *
533  * "Special" mappings do not wish to be associated with a "struct page" (either
534  * it doesn't exist, or it exists but they don't want to touch it). In this
535  * case, NULL is returned here. "Normal" mappings do have a struct page.
536  *
537  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
538  * pte bit, in which case this function is trivial. Secondly, an architecture
539  * may not have a spare pte bit, which requires a more complicated scheme,
540  * described below.
541  *
542  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
543  * special mapping (even if there are underlying and valid "struct pages").
544  * COWed pages of a VM_PFNMAP are always normal.
545  *
546  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
547  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
548  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
549  * mapping will always honor the rule
550  *
551  *	pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
552  *
553  * And for normal mappings this is false.
554  *
555  * This restricts such mappings to be a linear translation from virtual address
556  * to pfn. To get around this restriction, we allow arbitrary mappings so long
557  * as the vma is not a COW mapping; in that case, we know that all ptes are
558  * special (because none can have been COWed).
559  *
560  *
561  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
562  *
563  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
564  * page" backing, however the difference is that _all_ pages with a struct
565  * page (that is, those where pfn_valid is true) are refcounted and considered
566  * normal pages by the VM. The only exception are zeropages, which are
567  * *never* refcounted.
568  *
569  * The disadvantage is that pages are refcounted (which can be slower and
570  * simply not an option for some PFNMAP users). The advantage is that we
571  * don't have to follow the strict linearity rule of PFNMAP mappings in
572  * order to support COWable mappings.
573  *
574  */
575 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
576 			    pte_t pte)
577 {
578 	unsigned long pfn = pte_pfn(pte);
579 
580 	if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
581 		if (likely(!pte_special(pte)))
582 			goto check_pfn;
583 		if (vma->vm_ops && vma->vm_ops->find_special_page)
584 			return vma->vm_ops->find_special_page(vma, addr);
585 		if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
586 			return NULL;
587 		if (is_zero_pfn(pfn))
588 			return NULL;
589 		if (pte_devmap(pte))
590 		/*
591 		 * NOTE: New users of ZONE_DEVICE will not set pte_devmap()
592 		 * and will have refcounts incremented on their struct pages
593 		 * when they are inserted into PTEs, thus they are safe to
594 		 * return here. Legacy ZONE_DEVICE pages that set pte_devmap()
595 		 * do not have refcounts. Example of legacy ZONE_DEVICE is
596 		 * MEMORY_DEVICE_FS_DAX type in pmem or virtio_fs drivers.
597 		 */
598 			return NULL;
599 
600 		print_bad_pte(vma, addr, pte, NULL);
601 		return NULL;
602 	}
603 
604 	/* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
605 
606 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
607 		if (vma->vm_flags & VM_MIXEDMAP) {
608 			if (!pfn_valid(pfn))
609 				return NULL;
610 			if (is_zero_pfn(pfn))
611 				return NULL;
612 			goto out;
613 		} else {
614 			unsigned long off;
615 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
616 			if (pfn == vma->vm_pgoff + off)
617 				return NULL;
618 			if (!is_cow_mapping(vma->vm_flags))
619 				return NULL;
620 		}
621 	}
622 
623 	if (is_zero_pfn(pfn))
624 		return NULL;
625 
626 check_pfn:
627 	if (unlikely(pfn > highest_memmap_pfn)) {
628 		print_bad_pte(vma, addr, pte, NULL);
629 		return NULL;
630 	}
631 
632 	/*
633 	 * NOTE! We still have PageReserved() pages in the page tables.
634 	 * eg. VDSO mappings can cause them to exist.
635 	 */
636 out:
637 	VM_WARN_ON_ONCE(is_zero_pfn(pfn));
638 	return pfn_to_page(pfn);
639 }
640 
641 struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr,
642 			    pte_t pte)
643 {
644 	struct page *page = vm_normal_page(vma, addr, pte);
645 
646 	if (page)
647 		return page_folio(page);
648 	return NULL;
649 }
650 
651 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
652 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
653 				pmd_t pmd)
654 {
655 	unsigned long pfn = pmd_pfn(pmd);
656 
657 	/* Currently it's only used for huge pfnmaps */
658 	if (unlikely(pmd_special(pmd)))
659 		return NULL;
660 
661 	if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
662 		if (vma->vm_flags & VM_MIXEDMAP) {
663 			if (!pfn_valid(pfn))
664 				return NULL;
665 			goto out;
666 		} else {
667 			unsigned long off;
668 			off = (addr - vma->vm_start) >> PAGE_SHIFT;
669 			if (pfn == vma->vm_pgoff + off)
670 				return NULL;
671 			if (!is_cow_mapping(vma->vm_flags))
672 				return NULL;
673 		}
674 	}
675 
676 	if (pmd_devmap(pmd))
677 		return NULL;
678 	if (is_huge_zero_pmd(pmd))
679 		return NULL;
680 	if (unlikely(pfn > highest_memmap_pfn))
681 		return NULL;
682 
683 	/*
684 	 * NOTE! We still have PageReserved() pages in the page tables.
685 	 * eg. VDSO mappings can cause them to exist.
686 	 */
687 out:
688 	return pfn_to_page(pfn);
689 }
690 
691 struct folio *vm_normal_folio_pmd(struct vm_area_struct *vma,
692 				  unsigned long addr, pmd_t pmd)
693 {
694 	struct page *page = vm_normal_page_pmd(vma, addr, pmd);
695 
696 	if (page)
697 		return page_folio(page);
698 	return NULL;
699 }
700 #endif
701 
702 /**
703  * restore_exclusive_pte - Restore a device-exclusive entry
704  * @vma: VMA covering @address
705  * @folio: the mapped folio
706  * @page: the mapped folio page
707  * @address: the virtual address
708  * @ptep: pte pointer into the locked page table mapping the folio page
709  * @orig_pte: pte value at @ptep
710  *
711  * Restore a device-exclusive non-swap entry to an ordinary present pte.
712  *
713  * The folio and the page table must be locked, and MMU notifiers must have
714  * been called to invalidate any (exclusive) device mappings.
715  *
716  * Locking the folio makes sure that anybody who just converted the pte to
717  * a device-exclusive entry can map it into the device to make forward
718  * progress without others converting it back until the folio was unlocked.
719  *
720  * If the folio lock ever becomes an issue, we can stop relying on the folio
721  * lock; it might make some scenarios with heavy thrashing less likely to
722  * make forward progress, but these scenarios might not be valid use cases.
723  *
724  * Note that the folio lock does not protect against all cases of concurrent
725  * page table modifications (e.g., MADV_DONTNEED, mprotect), so device drivers
726  * must use MMU notifiers to sync against any concurrent changes.
727  */
728 static void restore_exclusive_pte(struct vm_area_struct *vma,
729 		struct folio *folio, struct page *page, unsigned long address,
730 		pte_t *ptep, pte_t orig_pte)
731 {
732 	pte_t pte;
733 
734 	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
735 
736 	pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
737 	if (pte_swp_soft_dirty(orig_pte))
738 		pte = pte_mksoft_dirty(pte);
739 
740 	if (pte_swp_uffd_wp(orig_pte))
741 		pte = pte_mkuffd_wp(pte);
742 
743 	if ((vma->vm_flags & VM_WRITE) &&
744 	    can_change_pte_writable(vma, address, pte)) {
745 		if (folio_test_dirty(folio))
746 			pte = pte_mkdirty(pte);
747 		pte = pte_mkwrite(pte, vma);
748 	}
749 	set_pte_at(vma->vm_mm, address, ptep, pte);
750 
751 	/*
752 	 * No need to invalidate - it was non-present before. However
753 	 * secondary CPUs may have mappings that need invalidating.
754 	 */
755 	update_mmu_cache(vma, address, ptep);
756 }
757 
758 /*
759  * Tries to restore an exclusive pte if the page lock can be acquired without
760  * sleeping.
761  */
762 static int try_restore_exclusive_pte(struct vm_area_struct *vma,
763 		unsigned long addr, pte_t *ptep, pte_t orig_pte)
764 {
765 	struct page *page = pfn_swap_entry_to_page(pte_to_swp_entry(orig_pte));
766 	struct folio *folio = page_folio(page);
767 
768 	if (folio_trylock(folio)) {
769 		restore_exclusive_pte(vma, folio, page, addr, ptep, orig_pte);
770 		folio_unlock(folio);
771 		return 0;
772 	}
773 
774 	return -EBUSY;
775 }
776 
777 /*
778  * copy one vm_area from one task to the other. Assumes the page tables
779  * already present in the new task to be cleared in the whole range
780  * covered by this vma.
781  */
782 
783 static unsigned long
784 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
785 		pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
786 		struct vm_area_struct *src_vma, unsigned long addr, int *rss)
787 {
788 	unsigned long vm_flags = dst_vma->vm_flags;
789 	pte_t orig_pte = ptep_get(src_pte);
790 	pte_t pte = orig_pte;
791 	struct folio *folio;
792 	struct page *page;
793 	swp_entry_t entry = pte_to_swp_entry(orig_pte);
794 
795 	if (likely(!non_swap_entry(entry))) {
796 		if (swap_duplicate(entry) < 0)
797 			return -EIO;
798 
799 		/* make sure dst_mm is on swapoff's mmlist. */
800 		if (unlikely(list_empty(&dst_mm->mmlist))) {
801 			spin_lock(&mmlist_lock);
802 			if (list_empty(&dst_mm->mmlist))
803 				list_add(&dst_mm->mmlist,
804 						&src_mm->mmlist);
805 			spin_unlock(&mmlist_lock);
806 		}
807 		/* Mark the swap entry as shared. */
808 		if (pte_swp_exclusive(orig_pte)) {
809 			pte = pte_swp_clear_exclusive(orig_pte);
810 			set_pte_at(src_mm, addr, src_pte, pte);
811 		}
812 		rss[MM_SWAPENTS]++;
813 	} else if (is_migration_entry(entry)) {
814 		folio = pfn_swap_entry_folio(entry);
815 
816 		rss[mm_counter(folio)]++;
817 
818 		if (!is_readable_migration_entry(entry) &&
819 				is_cow_mapping(vm_flags)) {
820 			/*
821 			 * COW mappings require pages in both parent and child
822 			 * to be set to read. A previously exclusive entry is
823 			 * now shared.
824 			 */
825 			entry = make_readable_migration_entry(
826 							swp_offset(entry));
827 			pte = swp_entry_to_pte(entry);
828 			if (pte_swp_soft_dirty(orig_pte))
829 				pte = pte_swp_mksoft_dirty(pte);
830 			if (pte_swp_uffd_wp(orig_pte))
831 				pte = pte_swp_mkuffd_wp(pte);
832 			set_pte_at(src_mm, addr, src_pte, pte);
833 		}
834 	} else if (is_device_private_entry(entry)) {
835 		page = pfn_swap_entry_to_page(entry);
836 		folio = page_folio(page);
837 
838 		/*
839 		 * Update rss count even for unaddressable pages, as
840 		 * they should treated just like normal pages in this
841 		 * respect.
842 		 *
843 		 * We will likely want to have some new rss counters
844 		 * for unaddressable pages, at some point. But for now
845 		 * keep things as they are.
846 		 */
847 		folio_get(folio);
848 		rss[mm_counter(folio)]++;
849 		/* Cannot fail as these pages cannot get pinned. */
850 		folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma);
851 
852 		/*
853 		 * We do not preserve soft-dirty information, because so
854 		 * far, checkpoint/restore is the only feature that
855 		 * requires that. And checkpoint/restore does not work
856 		 * when a device driver is involved (you cannot easily
857 		 * save and restore device driver state).
858 		 */
859 		if (is_writable_device_private_entry(entry) &&
860 		    is_cow_mapping(vm_flags)) {
861 			entry = make_readable_device_private_entry(
862 							swp_offset(entry));
863 			pte = swp_entry_to_pte(entry);
864 			if (pte_swp_uffd_wp(orig_pte))
865 				pte = pte_swp_mkuffd_wp(pte);
866 			set_pte_at(src_mm, addr, src_pte, pte);
867 		}
868 	} else if (is_device_exclusive_entry(entry)) {
869 		/*
870 		 * Make device exclusive entries present by restoring the
871 		 * original entry then copying as for a present pte. Device
872 		 * exclusive entries currently only support private writable
873 		 * (ie. COW) mappings.
874 		 */
875 		VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags));
876 		if (try_restore_exclusive_pte(src_vma, addr, src_pte, orig_pte))
877 			return -EBUSY;
878 		return -ENOENT;
879 	} else if (is_pte_marker_entry(entry)) {
880 		pte_marker marker = copy_pte_marker(entry, dst_vma);
881 
882 		if (marker)
883 			set_pte_at(dst_mm, addr, dst_pte,
884 				   make_pte_marker(marker));
885 		return 0;
886 	}
887 	if (!userfaultfd_wp(dst_vma))
888 		pte = pte_swp_clear_uffd_wp(pte);
889 	set_pte_at(dst_mm, addr, dst_pte, pte);
890 	return 0;
891 }
892 
893 /*
894  * Copy a present and normal page.
895  *
896  * NOTE! The usual case is that this isn't required;
897  * instead, the caller can just increase the page refcount
898  * and re-use the pte the traditional way.
899  *
900  * And if we need a pre-allocated page but don't yet have
901  * one, return a negative error to let the preallocation
902  * code know so that it can do so outside the page table
903  * lock.
904  */
905 static inline int
906 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
907 		  pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
908 		  struct folio **prealloc, struct page *page)
909 {
910 	struct folio *new_folio;
911 	pte_t pte;
912 
913 	new_folio = *prealloc;
914 	if (!new_folio)
915 		return -EAGAIN;
916 
917 	/*
918 	 * We have a prealloc page, all good!  Take it
919 	 * over and copy the page & arm it.
920 	 */
921 
922 	if (copy_mc_user_highpage(&new_folio->page, page, addr, src_vma))
923 		return -EHWPOISON;
924 
925 	*prealloc = NULL;
926 	__folio_mark_uptodate(new_folio);
927 	folio_add_new_anon_rmap(new_folio, dst_vma, addr, RMAP_EXCLUSIVE);
928 	folio_add_lru_vma(new_folio, dst_vma);
929 	rss[MM_ANONPAGES]++;
930 
931 	/* All done, just insert the new page copy in the child */
932 	pte = folio_mk_pte(new_folio, dst_vma->vm_page_prot);
933 	pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
934 	if (userfaultfd_pte_wp(dst_vma, ptep_get(src_pte)))
935 		/* Uffd-wp needs to be delivered to dest pte as well */
936 		pte = pte_mkuffd_wp(pte);
937 	set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
938 	return 0;
939 }
940 
941 static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma,
942 		struct vm_area_struct *src_vma, pte_t *dst_pte, pte_t *src_pte,
943 		pte_t pte, unsigned long addr, int nr)
944 {
945 	struct mm_struct *src_mm = src_vma->vm_mm;
946 
947 	/* If it's a COW mapping, write protect it both processes. */
948 	if (is_cow_mapping(src_vma->vm_flags) && pte_write(pte)) {
949 		wrprotect_ptes(src_mm, addr, src_pte, nr);
950 		pte = pte_wrprotect(pte);
951 	}
952 
953 	/* If it's a shared mapping, mark it clean in the child. */
954 	if (src_vma->vm_flags & VM_SHARED)
955 		pte = pte_mkclean(pte);
956 	pte = pte_mkold(pte);
957 
958 	if (!userfaultfd_wp(dst_vma))
959 		pte = pte_clear_uffd_wp(pte);
960 
961 	set_ptes(dst_vma->vm_mm, addr, dst_pte, pte, nr);
962 }
963 
964 /*
965  * Copy one present PTE, trying to batch-process subsequent PTEs that map
966  * consecutive pages of the same folio by copying them as well.
967  *
968  * Returns -EAGAIN if one preallocated page is required to copy the next PTE.
969  * Otherwise, returns the number of copied PTEs (at least 1).
970  */
971 static inline int
972 copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
973 		 pte_t *dst_pte, pte_t *src_pte, pte_t pte, unsigned long addr,
974 		 int max_nr, int *rss, struct folio **prealloc)
975 {
976 	struct page *page;
977 	struct folio *folio;
978 	bool any_writable;
979 	fpb_t flags = 0;
980 	int err, nr;
981 
982 	page = vm_normal_page(src_vma, addr, pte);
983 	if (unlikely(!page))
984 		goto copy_pte;
985 
986 	folio = page_folio(page);
987 
988 	/*
989 	 * If we likely have to copy, just don't bother with batching. Make
990 	 * sure that the common "small folio" case is as fast as possible
991 	 * by keeping the batching logic separate.
992 	 */
993 	if (unlikely(!*prealloc && folio_test_large(folio) && max_nr != 1)) {
994 		if (src_vma->vm_flags & VM_SHARED)
995 			flags |= FPB_IGNORE_DIRTY;
996 		if (!vma_soft_dirty_enabled(src_vma))
997 			flags |= FPB_IGNORE_SOFT_DIRTY;
998 
999 		nr = folio_pte_batch(folio, addr, src_pte, pte, max_nr, flags,
1000 				     &any_writable, NULL, NULL);
1001 		folio_ref_add(folio, nr);
1002 		if (folio_test_anon(folio)) {
1003 			if (unlikely(folio_try_dup_anon_rmap_ptes(folio, page,
1004 								  nr, dst_vma, src_vma))) {
1005 				folio_ref_sub(folio, nr);
1006 				return -EAGAIN;
1007 			}
1008 			rss[MM_ANONPAGES] += nr;
1009 			VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
1010 		} else {
1011 			folio_dup_file_rmap_ptes(folio, page, nr, dst_vma);
1012 			rss[mm_counter_file(folio)] += nr;
1013 		}
1014 		if (any_writable)
1015 			pte = pte_mkwrite(pte, src_vma);
1016 		__copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte,
1017 				    addr, nr);
1018 		return nr;
1019 	}
1020 
1021 	folio_get(folio);
1022 	if (folio_test_anon(folio)) {
1023 		/*
1024 		 * If this page may have been pinned by the parent process,
1025 		 * copy the page immediately for the child so that we'll always
1026 		 * guarantee the pinned page won't be randomly replaced in the
1027 		 * future.
1028 		 */
1029 		if (unlikely(folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma))) {
1030 			/* Page may be pinned, we have to copy. */
1031 			folio_put(folio);
1032 			err = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
1033 						addr, rss, prealloc, page);
1034 			return err ? err : 1;
1035 		}
1036 		rss[MM_ANONPAGES]++;
1037 		VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
1038 	} else {
1039 		folio_dup_file_rmap_pte(folio, page, dst_vma);
1040 		rss[mm_counter_file(folio)]++;
1041 	}
1042 
1043 copy_pte:
1044 	__copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte, addr, 1);
1045 	return 1;
1046 }
1047 
1048 static inline struct folio *folio_prealloc(struct mm_struct *src_mm,
1049 		struct vm_area_struct *vma, unsigned long addr, bool need_zero)
1050 {
1051 	struct folio *new_folio;
1052 
1053 	if (need_zero)
1054 		new_folio = vma_alloc_zeroed_movable_folio(vma, addr);
1055 	else
1056 		new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, addr);
1057 
1058 	if (!new_folio)
1059 		return NULL;
1060 
1061 	if (mem_cgroup_charge(new_folio, src_mm, GFP_KERNEL)) {
1062 		folio_put(new_folio);
1063 		return NULL;
1064 	}
1065 	folio_throttle_swaprate(new_folio, GFP_KERNEL);
1066 
1067 	return new_folio;
1068 }
1069 
1070 static int
1071 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1072 	       pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1073 	       unsigned long end)
1074 {
1075 	struct mm_struct *dst_mm = dst_vma->vm_mm;
1076 	struct mm_struct *src_mm = src_vma->vm_mm;
1077 	pte_t *orig_src_pte, *orig_dst_pte;
1078 	pte_t *src_pte, *dst_pte;
1079 	pmd_t dummy_pmdval;
1080 	pte_t ptent;
1081 	spinlock_t *src_ptl, *dst_ptl;
1082 	int progress, max_nr, ret = 0;
1083 	int rss[NR_MM_COUNTERS];
1084 	swp_entry_t entry = (swp_entry_t){0};
1085 	struct folio *prealloc = NULL;
1086 	int nr;
1087 
1088 again:
1089 	progress = 0;
1090 	init_rss_vec(rss);
1091 
1092 	/*
1093 	 * copy_pmd_range()'s prior pmd_none_or_clear_bad(src_pmd), and the
1094 	 * error handling here, assume that exclusive mmap_lock on dst and src
1095 	 * protects anon from unexpected THP transitions; with shmem and file
1096 	 * protected by mmap_lock-less collapse skipping areas with anon_vma
1097 	 * (whereas vma_needs_copy() skips areas without anon_vma).  A rework
1098 	 * can remove such assumptions later, but this is good enough for now.
1099 	 */
1100 	dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1101 	if (!dst_pte) {
1102 		ret = -ENOMEM;
1103 		goto out;
1104 	}
1105 
1106 	/*
1107 	 * We already hold the exclusive mmap_lock, the copy_pte_range() and
1108 	 * retract_page_tables() are using vma->anon_vma to be exclusive, so
1109 	 * the PTE page is stable, and there is no need to get pmdval and do
1110 	 * pmd_same() check.
1111 	 */
1112 	src_pte = pte_offset_map_rw_nolock(src_mm, src_pmd, addr, &dummy_pmdval,
1113 					   &src_ptl);
1114 	if (!src_pte) {
1115 		pte_unmap_unlock(dst_pte, dst_ptl);
1116 		/* ret == 0 */
1117 		goto out;
1118 	}
1119 	spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1120 	orig_src_pte = src_pte;
1121 	orig_dst_pte = dst_pte;
1122 	arch_enter_lazy_mmu_mode();
1123 
1124 	do {
1125 		nr = 1;
1126 
1127 		/*
1128 		 * We are holding two locks at this point - either of them
1129 		 * could generate latencies in another task on another CPU.
1130 		 */
1131 		if (progress >= 32) {
1132 			progress = 0;
1133 			if (need_resched() ||
1134 			    spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1135 				break;
1136 		}
1137 		ptent = ptep_get(src_pte);
1138 		if (pte_none(ptent)) {
1139 			progress++;
1140 			continue;
1141 		}
1142 		if (unlikely(!pte_present(ptent))) {
1143 			ret = copy_nonpresent_pte(dst_mm, src_mm,
1144 						  dst_pte, src_pte,
1145 						  dst_vma, src_vma,
1146 						  addr, rss);
1147 			if (ret == -EIO) {
1148 				entry = pte_to_swp_entry(ptep_get(src_pte));
1149 				break;
1150 			} else if (ret == -EBUSY) {
1151 				break;
1152 			} else if (!ret) {
1153 				progress += 8;
1154 				continue;
1155 			}
1156 			ptent = ptep_get(src_pte);
1157 			VM_WARN_ON_ONCE(!pte_present(ptent));
1158 
1159 			/*
1160 			 * Device exclusive entry restored, continue by copying
1161 			 * the now present pte.
1162 			 */
1163 			WARN_ON_ONCE(ret != -ENOENT);
1164 		}
1165 		/* copy_present_ptes() will clear `*prealloc' if consumed */
1166 		max_nr = (end - addr) / PAGE_SIZE;
1167 		ret = copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte,
1168 					ptent, addr, max_nr, rss, &prealloc);
1169 		/*
1170 		 * If we need a pre-allocated page for this pte, drop the
1171 		 * locks, allocate, and try again.
1172 		 * If copy failed due to hwpoison in source page, break out.
1173 		 */
1174 		if (unlikely(ret == -EAGAIN || ret == -EHWPOISON))
1175 			break;
1176 		if (unlikely(prealloc)) {
1177 			/*
1178 			 * pre-alloc page cannot be reused by next time so as
1179 			 * to strictly follow mempolicy (e.g., alloc_page_vma()
1180 			 * will allocate page according to address).  This
1181 			 * could only happen if one pinned pte changed.
1182 			 */
1183 			folio_put(prealloc);
1184 			prealloc = NULL;
1185 		}
1186 		nr = ret;
1187 		progress += 8 * nr;
1188 	} while (dst_pte += nr, src_pte += nr, addr += PAGE_SIZE * nr,
1189 		 addr != end);
1190 
1191 	arch_leave_lazy_mmu_mode();
1192 	pte_unmap_unlock(orig_src_pte, src_ptl);
1193 	add_mm_rss_vec(dst_mm, rss);
1194 	pte_unmap_unlock(orig_dst_pte, dst_ptl);
1195 	cond_resched();
1196 
1197 	if (ret == -EIO) {
1198 		VM_WARN_ON_ONCE(!entry.val);
1199 		if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1200 			ret = -ENOMEM;
1201 			goto out;
1202 		}
1203 		entry.val = 0;
1204 	} else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) {
1205 		goto out;
1206 	} else if (ret ==  -EAGAIN) {
1207 		prealloc = folio_prealloc(src_mm, src_vma, addr, false);
1208 		if (!prealloc)
1209 			return -ENOMEM;
1210 	} else if (ret < 0) {
1211 		VM_WARN_ON_ONCE(1);
1212 	}
1213 
1214 	/* We've captured and resolved the error. Reset, try again. */
1215 	ret = 0;
1216 
1217 	if (addr != end)
1218 		goto again;
1219 out:
1220 	if (unlikely(prealloc))
1221 		folio_put(prealloc);
1222 	return ret;
1223 }
1224 
1225 static inline int
1226 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1227 	       pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1228 	       unsigned long end)
1229 {
1230 	struct mm_struct *dst_mm = dst_vma->vm_mm;
1231 	struct mm_struct *src_mm = src_vma->vm_mm;
1232 	pmd_t *src_pmd, *dst_pmd;
1233 	unsigned long next;
1234 
1235 	dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1236 	if (!dst_pmd)
1237 		return -ENOMEM;
1238 	src_pmd = pmd_offset(src_pud, addr);
1239 	do {
1240 		next = pmd_addr_end(addr, end);
1241 		if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1242 			|| pmd_devmap(*src_pmd)) {
1243 			int err;
1244 			VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1245 			err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
1246 					    addr, dst_vma, src_vma);
1247 			if (err == -ENOMEM)
1248 				return -ENOMEM;
1249 			if (!err)
1250 				continue;
1251 			/* fall through */
1252 		}
1253 		if (pmd_none_or_clear_bad(src_pmd))
1254 			continue;
1255 		if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1256 				   addr, next))
1257 			return -ENOMEM;
1258 	} while (dst_pmd++, src_pmd++, addr = next, addr != end);
1259 	return 0;
1260 }
1261 
1262 static inline int
1263 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1264 	       p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1265 	       unsigned long end)
1266 {
1267 	struct mm_struct *dst_mm = dst_vma->vm_mm;
1268 	struct mm_struct *src_mm = src_vma->vm_mm;
1269 	pud_t *src_pud, *dst_pud;
1270 	unsigned long next;
1271 
1272 	dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1273 	if (!dst_pud)
1274 		return -ENOMEM;
1275 	src_pud = pud_offset(src_p4d, addr);
1276 	do {
1277 		next = pud_addr_end(addr, end);
1278 		if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1279 			int err;
1280 
1281 			VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1282 			err = copy_huge_pud(dst_mm, src_mm,
1283 					    dst_pud, src_pud, addr, src_vma);
1284 			if (err == -ENOMEM)
1285 				return -ENOMEM;
1286 			if (!err)
1287 				continue;
1288 			/* fall through */
1289 		}
1290 		if (pud_none_or_clear_bad(src_pud))
1291 			continue;
1292 		if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1293 				   addr, next))
1294 			return -ENOMEM;
1295 	} while (dst_pud++, src_pud++, addr = next, addr != end);
1296 	return 0;
1297 }
1298 
1299 static inline int
1300 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1301 	       pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1302 	       unsigned long end)
1303 {
1304 	struct mm_struct *dst_mm = dst_vma->vm_mm;
1305 	p4d_t *src_p4d, *dst_p4d;
1306 	unsigned long next;
1307 
1308 	dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1309 	if (!dst_p4d)
1310 		return -ENOMEM;
1311 	src_p4d = p4d_offset(src_pgd, addr);
1312 	do {
1313 		next = p4d_addr_end(addr, end);
1314 		if (p4d_none_or_clear_bad(src_p4d))
1315 			continue;
1316 		if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1317 				   addr, next))
1318 			return -ENOMEM;
1319 	} while (dst_p4d++, src_p4d++, addr = next, addr != end);
1320 	return 0;
1321 }
1322 
1323 /*
1324  * Return true if the vma needs to copy the pgtable during this fork().  Return
1325  * false when we can speed up fork() by allowing lazy page faults later until
1326  * when the child accesses the memory range.
1327  */
1328 static bool
1329 vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1330 {
1331 	/*
1332 	 * Always copy pgtables when dst_vma has uffd-wp enabled even if it's
1333 	 * file-backed (e.g. shmem). Because when uffd-wp is enabled, pgtable
1334 	 * contains uffd-wp protection information, that's something we can't
1335 	 * retrieve from page cache, and skip copying will lose those info.
1336 	 */
1337 	if (userfaultfd_wp(dst_vma))
1338 		return true;
1339 
1340 	if (src_vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
1341 		return true;
1342 
1343 	if (src_vma->anon_vma)
1344 		return true;
1345 
1346 	/*
1347 	 * Don't copy ptes where a page fault will fill them correctly.  Fork
1348 	 * becomes much lighter when there are big shared or private readonly
1349 	 * mappings. The tradeoff is that copy_page_range is more efficient
1350 	 * than faulting.
1351 	 */
1352 	return false;
1353 }
1354 
1355 int
1356 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1357 {
1358 	pgd_t *src_pgd, *dst_pgd;
1359 	unsigned long addr = src_vma->vm_start;
1360 	unsigned long end = src_vma->vm_end;
1361 	struct mm_struct *dst_mm = dst_vma->vm_mm;
1362 	struct mm_struct *src_mm = src_vma->vm_mm;
1363 	struct mmu_notifier_range range;
1364 	unsigned long next, pfn = 0;
1365 	bool is_cow;
1366 	int ret;
1367 
1368 	if (!vma_needs_copy(dst_vma, src_vma))
1369 		return 0;
1370 
1371 	if (is_vm_hugetlb_page(src_vma))
1372 		return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma);
1373 
1374 	if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1375 		ret = track_pfn_copy(dst_vma, src_vma, &pfn);
1376 		if (ret)
1377 			return ret;
1378 	}
1379 
1380 	/*
1381 	 * We need to invalidate the secondary MMU mappings only when
1382 	 * there could be a permission downgrade on the ptes of the
1383 	 * parent mm. And a permission downgrade will only happen if
1384 	 * is_cow_mapping() returns true.
1385 	 */
1386 	is_cow = is_cow_mapping(src_vma->vm_flags);
1387 
1388 	if (is_cow) {
1389 		mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1390 					0, src_mm, addr, end);
1391 		mmu_notifier_invalidate_range_start(&range);
1392 		/*
1393 		 * Disabling preemption is not needed for the write side, as
1394 		 * the read side doesn't spin, but goes to the mmap_lock.
1395 		 *
1396 		 * Use the raw variant of the seqcount_t write API to avoid
1397 		 * lockdep complaining about preemptibility.
1398 		 */
1399 		vma_assert_write_locked(src_vma);
1400 		raw_write_seqcount_begin(&src_mm->write_protect_seq);
1401 	}
1402 
1403 	ret = 0;
1404 	dst_pgd = pgd_offset(dst_mm, addr);
1405 	src_pgd = pgd_offset(src_mm, addr);
1406 	do {
1407 		next = pgd_addr_end(addr, end);
1408 		if (pgd_none_or_clear_bad(src_pgd))
1409 			continue;
1410 		if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1411 					    addr, next))) {
1412 			ret = -ENOMEM;
1413 			break;
1414 		}
1415 	} while (dst_pgd++, src_pgd++, addr = next, addr != end);
1416 
1417 	if (is_cow) {
1418 		raw_write_seqcount_end(&src_mm->write_protect_seq);
1419 		mmu_notifier_invalidate_range_end(&range);
1420 	}
1421 	if (ret && unlikely(src_vma->vm_flags & VM_PFNMAP))
1422 		untrack_pfn_copy(dst_vma, pfn);
1423 	return ret;
1424 }
1425 
1426 /* Whether we should zap all COWed (private) pages too */
1427 static inline bool should_zap_cows(struct zap_details *details)
1428 {
1429 	/* By default, zap all pages */
1430 	if (!details || details->reclaim_pt)
1431 		return true;
1432 
1433 	/* Or, we zap COWed pages only if the caller wants to */
1434 	return details->even_cows;
1435 }
1436 
1437 /* Decides whether we should zap this folio with the folio pointer specified */
1438 static inline bool should_zap_folio(struct zap_details *details,
1439 				    struct folio *folio)
1440 {
1441 	/* If we can make a decision without *folio.. */
1442 	if (should_zap_cows(details))
1443 		return true;
1444 
1445 	/* Otherwise we should only zap non-anon folios */
1446 	return !folio_test_anon(folio);
1447 }
1448 
1449 static inline bool zap_drop_markers(struct zap_details *details)
1450 {
1451 	if (!details)
1452 		return false;
1453 
1454 	return details->zap_flags & ZAP_FLAG_DROP_MARKER;
1455 }
1456 
1457 /*
1458  * This function makes sure that we'll replace the none pte with an uffd-wp
1459  * swap special pte marker when necessary. Must be with the pgtable lock held.
1460  *
1461  * Returns true if uffd-wp ptes was installed, false otherwise.
1462  */
1463 static inline bool
1464 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
1465 			      unsigned long addr, pte_t *pte, int nr,
1466 			      struct zap_details *details, pte_t pteval)
1467 {
1468 	bool was_installed = false;
1469 
1470 #ifdef CONFIG_PTE_MARKER_UFFD_WP
1471 	/* Zap on anonymous always means dropping everything */
1472 	if (vma_is_anonymous(vma))
1473 		return false;
1474 
1475 	if (zap_drop_markers(details))
1476 		return false;
1477 
1478 	for (;;) {
1479 		/* the PFN in the PTE is irrelevant. */
1480 		if (pte_install_uffd_wp_if_needed(vma, addr, pte, pteval))
1481 			was_installed = true;
1482 		if (--nr == 0)
1483 			break;
1484 		pte++;
1485 		addr += PAGE_SIZE;
1486 	}
1487 #endif
1488 	return was_installed;
1489 }
1490 
1491 static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb,
1492 		struct vm_area_struct *vma, struct folio *folio,
1493 		struct page *page, pte_t *pte, pte_t ptent, unsigned int nr,
1494 		unsigned long addr, struct zap_details *details, int *rss,
1495 		bool *force_flush, bool *force_break, bool *any_skipped)
1496 {
1497 	struct mm_struct *mm = tlb->mm;
1498 	bool delay_rmap = false;
1499 
1500 	if (!folio_test_anon(folio)) {
1501 		ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
1502 		if (pte_dirty(ptent)) {
1503 			folio_mark_dirty(folio);
1504 			if (tlb_delay_rmap(tlb)) {
1505 				delay_rmap = true;
1506 				*force_flush = true;
1507 			}
1508 		}
1509 		if (pte_young(ptent) && likely(vma_has_recency(vma)))
1510 			folio_mark_accessed(folio);
1511 		rss[mm_counter(folio)] -= nr;
1512 	} else {
1513 		/* We don't need up-to-date accessed/dirty bits. */
1514 		clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
1515 		rss[MM_ANONPAGES] -= nr;
1516 	}
1517 	/* Checking a single PTE in a batch is sufficient. */
1518 	arch_check_zapped_pte(vma, ptent);
1519 	tlb_remove_tlb_entries(tlb, pte, nr, addr);
1520 	if (unlikely(userfaultfd_pte_wp(vma, ptent)))
1521 		*any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte,
1522 							     nr, details, ptent);
1523 
1524 	if (!delay_rmap) {
1525 		folio_remove_rmap_ptes(folio, page, nr, vma);
1526 
1527 		if (unlikely(folio_mapcount(folio) < 0))
1528 			print_bad_pte(vma, addr, ptent, page);
1529 	}
1530 	if (unlikely(__tlb_remove_folio_pages(tlb, page, nr, delay_rmap))) {
1531 		*force_flush = true;
1532 		*force_break = true;
1533 	}
1534 }
1535 
1536 /*
1537  * Zap or skip at least one present PTE, trying to batch-process subsequent
1538  * PTEs that map consecutive pages of the same folio.
1539  *
1540  * Returns the number of processed (skipped or zapped) PTEs (at least 1).
1541  */
1542 static inline int zap_present_ptes(struct mmu_gather *tlb,
1543 		struct vm_area_struct *vma, pte_t *pte, pte_t ptent,
1544 		unsigned int max_nr, unsigned long addr,
1545 		struct zap_details *details, int *rss, bool *force_flush,
1546 		bool *force_break, bool *any_skipped)
1547 {
1548 	const fpb_t fpb_flags = FPB_IGNORE_DIRTY | FPB_IGNORE_SOFT_DIRTY;
1549 	struct mm_struct *mm = tlb->mm;
1550 	struct folio *folio;
1551 	struct page *page;
1552 	int nr;
1553 
1554 	page = vm_normal_page(vma, addr, ptent);
1555 	if (!page) {
1556 		/* We don't need up-to-date accessed/dirty bits. */
1557 		ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
1558 		arch_check_zapped_pte(vma, ptent);
1559 		tlb_remove_tlb_entry(tlb, pte, addr);
1560 		if (userfaultfd_pte_wp(vma, ptent))
1561 			*any_skipped = zap_install_uffd_wp_if_needed(vma, addr,
1562 						pte, 1, details, ptent);
1563 		ksm_might_unmap_zero_page(mm, ptent);
1564 		return 1;
1565 	}
1566 
1567 	folio = page_folio(page);
1568 	if (unlikely(!should_zap_folio(details, folio))) {
1569 		*any_skipped = true;
1570 		return 1;
1571 	}
1572 
1573 	/*
1574 	 * Make sure that the common "small folio" case is as fast as possible
1575 	 * by keeping the batching logic separate.
1576 	 */
1577 	if (unlikely(folio_test_large(folio) && max_nr != 1)) {
1578 		nr = folio_pte_batch(folio, addr, pte, ptent, max_nr, fpb_flags,
1579 				     NULL, NULL, NULL);
1580 
1581 		zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, nr,
1582 				       addr, details, rss, force_flush,
1583 				       force_break, any_skipped);
1584 		return nr;
1585 	}
1586 	zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, 1, addr,
1587 			       details, rss, force_flush, force_break, any_skipped);
1588 	return 1;
1589 }
1590 
1591 static inline int zap_nonpresent_ptes(struct mmu_gather *tlb,
1592 		struct vm_area_struct *vma, pte_t *pte, pte_t ptent,
1593 		unsigned int max_nr, unsigned long addr,
1594 		struct zap_details *details, int *rss, bool *any_skipped)
1595 {
1596 	swp_entry_t entry;
1597 	int nr = 1;
1598 
1599 	*any_skipped = true;
1600 	entry = pte_to_swp_entry(ptent);
1601 	if (is_device_private_entry(entry) ||
1602 		is_device_exclusive_entry(entry)) {
1603 		struct page *page = pfn_swap_entry_to_page(entry);
1604 		struct folio *folio = page_folio(page);
1605 
1606 		if (unlikely(!should_zap_folio(details, folio)))
1607 			return 1;
1608 		/*
1609 		 * Both device private/exclusive mappings should only
1610 		 * work with anonymous page so far, so we don't need to
1611 		 * consider uffd-wp bit when zap. For more information,
1612 		 * see zap_install_uffd_wp_if_needed().
1613 		 */
1614 		WARN_ON_ONCE(!vma_is_anonymous(vma));
1615 		rss[mm_counter(folio)]--;
1616 		folio_remove_rmap_pte(folio, page, vma);
1617 		folio_put(folio);
1618 	} else if (!non_swap_entry(entry)) {
1619 		/* Genuine swap entries, hence a private anon pages */
1620 		if (!should_zap_cows(details))
1621 			return 1;
1622 
1623 		nr = swap_pte_batch(pte, max_nr, ptent);
1624 		rss[MM_SWAPENTS] -= nr;
1625 		free_swap_and_cache_nr(entry, nr);
1626 	} else if (is_migration_entry(entry)) {
1627 		struct folio *folio = pfn_swap_entry_folio(entry);
1628 
1629 		if (!should_zap_folio(details, folio))
1630 			return 1;
1631 		rss[mm_counter(folio)]--;
1632 	} else if (pte_marker_entry_uffd_wp(entry)) {
1633 		/*
1634 		 * For anon: always drop the marker; for file: only
1635 		 * drop the marker if explicitly requested.
1636 		 */
1637 		if (!vma_is_anonymous(vma) && !zap_drop_markers(details))
1638 			return 1;
1639 	} else if (is_guard_swp_entry(entry)) {
1640 		/*
1641 		 * Ordinary zapping should not remove guard PTE
1642 		 * markers. Only do so if we should remove PTE markers
1643 		 * in general.
1644 		 */
1645 		if (!zap_drop_markers(details))
1646 			return 1;
1647 	} else if (is_hwpoison_entry(entry) || is_poisoned_swp_entry(entry)) {
1648 		if (!should_zap_cows(details))
1649 			return 1;
1650 	} else {
1651 		/* We should have covered all the swap entry types */
1652 		pr_alert("unrecognized swap entry 0x%lx\n", entry.val);
1653 		WARN_ON_ONCE(1);
1654 	}
1655 	clear_not_present_full_ptes(vma->vm_mm, addr, pte, nr, tlb->fullmm);
1656 	*any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte, nr, details, ptent);
1657 
1658 	return nr;
1659 }
1660 
1661 static inline int do_zap_pte_range(struct mmu_gather *tlb,
1662 				   struct vm_area_struct *vma, pte_t *pte,
1663 				   unsigned long addr, unsigned long end,
1664 				   struct zap_details *details, int *rss,
1665 				   bool *force_flush, bool *force_break,
1666 				   bool *any_skipped)
1667 {
1668 	pte_t ptent = ptep_get(pte);
1669 	int max_nr = (end - addr) / PAGE_SIZE;
1670 	int nr = 0;
1671 
1672 	/* Skip all consecutive none ptes */
1673 	if (pte_none(ptent)) {
1674 		for (nr = 1; nr < max_nr; nr++) {
1675 			ptent = ptep_get(pte + nr);
1676 			if (!pte_none(ptent))
1677 				break;
1678 		}
1679 		max_nr -= nr;
1680 		if (!max_nr)
1681 			return nr;
1682 		pte += nr;
1683 		addr += nr * PAGE_SIZE;
1684 	}
1685 
1686 	if (pte_present(ptent))
1687 		nr += zap_present_ptes(tlb, vma, pte, ptent, max_nr, addr,
1688 				       details, rss, force_flush, force_break,
1689 				       any_skipped);
1690 	else
1691 		nr += zap_nonpresent_ptes(tlb, vma, pte, ptent, max_nr, addr,
1692 					  details, rss, any_skipped);
1693 
1694 	return nr;
1695 }
1696 
1697 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1698 				struct vm_area_struct *vma, pmd_t *pmd,
1699 				unsigned long addr, unsigned long end,
1700 				struct zap_details *details)
1701 {
1702 	bool force_flush = false, force_break = false;
1703 	struct mm_struct *mm = tlb->mm;
1704 	int rss[NR_MM_COUNTERS];
1705 	spinlock_t *ptl;
1706 	pte_t *start_pte;
1707 	pte_t *pte;
1708 	pmd_t pmdval;
1709 	unsigned long start = addr;
1710 	bool can_reclaim_pt = reclaim_pt_is_enabled(start, end, details);
1711 	bool direct_reclaim = true;
1712 	int nr;
1713 
1714 retry:
1715 	tlb_change_page_size(tlb, PAGE_SIZE);
1716 	init_rss_vec(rss);
1717 	start_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1718 	if (!pte)
1719 		return addr;
1720 
1721 	flush_tlb_batched_pending(mm);
1722 	arch_enter_lazy_mmu_mode();
1723 	do {
1724 		bool any_skipped = false;
1725 
1726 		if (need_resched()) {
1727 			direct_reclaim = false;
1728 			break;
1729 		}
1730 
1731 		nr = do_zap_pte_range(tlb, vma, pte, addr, end, details, rss,
1732 				      &force_flush, &force_break, &any_skipped);
1733 		if (any_skipped)
1734 			can_reclaim_pt = false;
1735 		if (unlikely(force_break)) {
1736 			addr += nr * PAGE_SIZE;
1737 			direct_reclaim = false;
1738 			break;
1739 		}
1740 	} while (pte += nr, addr += PAGE_SIZE * nr, addr != end);
1741 
1742 	/*
1743 	 * Fast path: try to hold the pmd lock and unmap the PTE page.
1744 	 *
1745 	 * If the pte lock was released midway (retry case), or if the attempt
1746 	 * to hold the pmd lock failed, then we need to recheck all pte entries
1747 	 * to ensure they are still none, thereby preventing the pte entries
1748 	 * from being repopulated by another thread.
1749 	 */
1750 	if (can_reclaim_pt && direct_reclaim && addr == end)
1751 		direct_reclaim = try_get_and_clear_pmd(mm, pmd, &pmdval);
1752 
1753 	add_mm_rss_vec(mm, rss);
1754 	arch_leave_lazy_mmu_mode();
1755 
1756 	/* Do the actual TLB flush before dropping ptl */
1757 	if (force_flush) {
1758 		tlb_flush_mmu_tlbonly(tlb);
1759 		tlb_flush_rmaps(tlb, vma);
1760 	}
1761 	pte_unmap_unlock(start_pte, ptl);
1762 
1763 	/*
1764 	 * If we forced a TLB flush (either due to running out of
1765 	 * batch buffers or because we needed to flush dirty TLB
1766 	 * entries before releasing the ptl), free the batched
1767 	 * memory too. Come back again if we didn't do everything.
1768 	 */
1769 	if (force_flush)
1770 		tlb_flush_mmu(tlb);
1771 
1772 	if (addr != end) {
1773 		cond_resched();
1774 		force_flush = false;
1775 		force_break = false;
1776 		goto retry;
1777 	}
1778 
1779 	if (can_reclaim_pt) {
1780 		if (direct_reclaim)
1781 			free_pte(mm, start, tlb, pmdval);
1782 		else
1783 			try_to_free_pte(mm, pmd, start, tlb);
1784 	}
1785 
1786 	return addr;
1787 }
1788 
1789 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1790 				struct vm_area_struct *vma, pud_t *pud,
1791 				unsigned long addr, unsigned long end,
1792 				struct zap_details *details)
1793 {
1794 	pmd_t *pmd;
1795 	unsigned long next;
1796 
1797 	pmd = pmd_offset(pud, addr);
1798 	do {
1799 		next = pmd_addr_end(addr, end);
1800 		if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1801 			if (next - addr != HPAGE_PMD_SIZE)
1802 				__split_huge_pmd(vma, pmd, addr, false, NULL);
1803 			else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
1804 				addr = next;
1805 				continue;
1806 			}
1807 			/* fall through */
1808 		} else if (details && details->single_folio &&
1809 			   folio_test_pmd_mappable(details->single_folio) &&
1810 			   next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1811 			spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1812 			/*
1813 			 * Take and drop THP pmd lock so that we cannot return
1814 			 * prematurely, while zap_huge_pmd() has cleared *pmd,
1815 			 * but not yet decremented compound_mapcount().
1816 			 */
1817 			spin_unlock(ptl);
1818 		}
1819 		if (pmd_none(*pmd)) {
1820 			addr = next;
1821 			continue;
1822 		}
1823 		addr = zap_pte_range(tlb, vma, pmd, addr, next, details);
1824 		if (addr != next)
1825 			pmd--;
1826 	} while (pmd++, cond_resched(), addr != end);
1827 
1828 	return addr;
1829 }
1830 
1831 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1832 				struct vm_area_struct *vma, p4d_t *p4d,
1833 				unsigned long addr, unsigned long end,
1834 				struct zap_details *details)
1835 {
1836 	pud_t *pud;
1837 	unsigned long next;
1838 
1839 	pud = pud_offset(p4d, addr);
1840 	do {
1841 		next = pud_addr_end(addr, end);
1842 		if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1843 			if (next - addr != HPAGE_PUD_SIZE) {
1844 				mmap_assert_locked(tlb->mm);
1845 				split_huge_pud(vma, pud, addr);
1846 			} else if (zap_huge_pud(tlb, vma, pud, addr))
1847 				goto next;
1848 			/* fall through */
1849 		}
1850 		if (pud_none_or_clear_bad(pud))
1851 			continue;
1852 		next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1853 next:
1854 		cond_resched();
1855 	} while (pud++, addr = next, addr != end);
1856 
1857 	return addr;
1858 }
1859 
1860 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1861 				struct vm_area_struct *vma, pgd_t *pgd,
1862 				unsigned long addr, unsigned long end,
1863 				struct zap_details *details)
1864 {
1865 	p4d_t *p4d;
1866 	unsigned long next;
1867 
1868 	p4d = p4d_offset(pgd, addr);
1869 	do {
1870 		next = p4d_addr_end(addr, end);
1871 		if (p4d_none_or_clear_bad(p4d))
1872 			continue;
1873 		next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1874 	} while (p4d++, addr = next, addr != end);
1875 
1876 	return addr;
1877 }
1878 
1879 void unmap_page_range(struct mmu_gather *tlb,
1880 			     struct vm_area_struct *vma,
1881 			     unsigned long addr, unsigned long end,
1882 			     struct zap_details *details)
1883 {
1884 	pgd_t *pgd;
1885 	unsigned long next;
1886 
1887 	BUG_ON(addr >= end);
1888 	tlb_start_vma(tlb, vma);
1889 	pgd = pgd_offset(vma->vm_mm, addr);
1890 	do {
1891 		next = pgd_addr_end(addr, end);
1892 		if (pgd_none_or_clear_bad(pgd))
1893 			continue;
1894 		next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1895 	} while (pgd++, addr = next, addr != end);
1896 	tlb_end_vma(tlb, vma);
1897 }
1898 
1899 
1900 static void unmap_single_vma(struct mmu_gather *tlb,
1901 		struct vm_area_struct *vma, unsigned long start_addr,
1902 		unsigned long end_addr,
1903 		struct zap_details *details, bool mm_wr_locked)
1904 {
1905 	unsigned long start = max(vma->vm_start, start_addr);
1906 	unsigned long end;
1907 
1908 	if (start >= vma->vm_end)
1909 		return;
1910 	end = min(vma->vm_end, end_addr);
1911 	if (end <= vma->vm_start)
1912 		return;
1913 
1914 	if (vma->vm_file)
1915 		uprobe_munmap(vma, start, end);
1916 
1917 	if (unlikely(vma->vm_flags & VM_PFNMAP))
1918 		untrack_pfn(vma, 0, 0, mm_wr_locked);
1919 
1920 	if (start != end) {
1921 		if (unlikely(is_vm_hugetlb_page(vma))) {
1922 			/*
1923 			 * It is undesirable to test vma->vm_file as it
1924 			 * should be non-null for valid hugetlb area.
1925 			 * However, vm_file will be NULL in the error
1926 			 * cleanup path of mmap_region. When
1927 			 * hugetlbfs ->mmap method fails,
1928 			 * mmap_region() nullifies vma->vm_file
1929 			 * before calling this function to clean up.
1930 			 * Since no pte has actually been setup, it is
1931 			 * safe to do nothing in this case.
1932 			 */
1933 			if (vma->vm_file) {
1934 				zap_flags_t zap_flags = details ?
1935 				    details->zap_flags : 0;
1936 				__unmap_hugepage_range(tlb, vma, start, end,
1937 							     NULL, zap_flags);
1938 			}
1939 		} else
1940 			unmap_page_range(tlb, vma, start, end, details);
1941 	}
1942 }
1943 
1944 /**
1945  * unmap_vmas - unmap a range of memory covered by a list of vma's
1946  * @tlb: address of the caller's struct mmu_gather
1947  * @mas: the maple state
1948  * @vma: the starting vma
1949  * @start_addr: virtual address at which to start unmapping
1950  * @end_addr: virtual address at which to end unmapping
1951  * @tree_end: The maximum index to check
1952  * @mm_wr_locked: lock flag
1953  *
1954  * Unmap all pages in the vma list.
1955  *
1956  * Only addresses between `start' and `end' will be unmapped.
1957  *
1958  * The VMA list must be sorted in ascending virtual address order.
1959  *
1960  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1961  * range after unmap_vmas() returns.  So the only responsibility here is to
1962  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1963  * drops the lock and schedules.
1964  */
1965 void unmap_vmas(struct mmu_gather *tlb, struct ma_state *mas,
1966 		struct vm_area_struct *vma, unsigned long start_addr,
1967 		unsigned long end_addr, unsigned long tree_end,
1968 		bool mm_wr_locked)
1969 {
1970 	struct mmu_notifier_range range;
1971 	struct zap_details details = {
1972 		.zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP,
1973 		/* Careful - we need to zap private pages too! */
1974 		.even_cows = true,
1975 	};
1976 
1977 	mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma->vm_mm,
1978 				start_addr, end_addr);
1979 	mmu_notifier_invalidate_range_start(&range);
1980 	do {
1981 		unsigned long start = start_addr;
1982 		unsigned long end = end_addr;
1983 		hugetlb_zap_begin(vma, &start, &end);
1984 		unmap_single_vma(tlb, vma, start, end, &details,
1985 				 mm_wr_locked);
1986 		hugetlb_zap_end(vma, &details);
1987 		vma = mas_find(mas, tree_end - 1);
1988 	} while (vma && likely(!xa_is_zero(vma)));
1989 	mmu_notifier_invalidate_range_end(&range);
1990 }
1991 
1992 /**
1993  * zap_page_range_single - remove user pages in a given range
1994  * @vma: vm_area_struct holding the applicable pages
1995  * @address: starting address of pages to zap
1996  * @size: number of bytes to zap
1997  * @details: details of shared cache invalidation
1998  *
1999  * The range must fit into one VMA.
2000  */
2001 void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
2002 		unsigned long size, struct zap_details *details)
2003 {
2004 	const unsigned long end = address + size;
2005 	struct mmu_notifier_range range;
2006 	struct mmu_gather tlb;
2007 
2008 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2009 				address, end);
2010 	hugetlb_zap_begin(vma, &range.start, &range.end);
2011 	tlb_gather_mmu(&tlb, vma->vm_mm);
2012 	update_hiwater_rss(vma->vm_mm);
2013 	mmu_notifier_invalidate_range_start(&range);
2014 	/*
2015 	 * unmap 'address-end' not 'range.start-range.end' as range
2016 	 * could have been expanded for hugetlb pmd sharing.
2017 	 */
2018 	unmap_single_vma(&tlb, vma, address, end, details, false);
2019 	mmu_notifier_invalidate_range_end(&range);
2020 	tlb_finish_mmu(&tlb);
2021 	hugetlb_zap_end(vma, details);
2022 }
2023 
2024 /**
2025  * zap_vma_ptes - remove ptes mapping the vma
2026  * @vma: vm_area_struct holding ptes to be zapped
2027  * @address: starting address of pages to zap
2028  * @size: number of bytes to zap
2029  *
2030  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
2031  *
2032  * The entire address range must be fully contained within the vma.
2033  *
2034  */
2035 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
2036 		unsigned long size)
2037 {
2038 	if (!range_in_vma(vma, address, address + size) ||
2039 	    		!(vma->vm_flags & VM_PFNMAP))
2040 		return;
2041 
2042 	zap_page_range_single(vma, address, size, NULL);
2043 }
2044 EXPORT_SYMBOL_GPL(zap_vma_ptes);
2045 
2046 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
2047 {
2048 	pgd_t *pgd;
2049 	p4d_t *p4d;
2050 	pud_t *pud;
2051 	pmd_t *pmd;
2052 
2053 	pgd = pgd_offset(mm, addr);
2054 	p4d = p4d_alloc(mm, pgd, addr);
2055 	if (!p4d)
2056 		return NULL;
2057 	pud = pud_alloc(mm, p4d, addr);
2058 	if (!pud)
2059 		return NULL;
2060 	pmd = pmd_alloc(mm, pud, addr);
2061 	if (!pmd)
2062 		return NULL;
2063 
2064 	VM_BUG_ON(pmd_trans_huge(*pmd));
2065 	return pmd;
2066 }
2067 
2068 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
2069 			spinlock_t **ptl)
2070 {
2071 	pmd_t *pmd = walk_to_pmd(mm, addr);
2072 
2073 	if (!pmd)
2074 		return NULL;
2075 	return pte_alloc_map_lock(mm, pmd, addr, ptl);
2076 }
2077 
2078 static bool vm_mixed_zeropage_allowed(struct vm_area_struct *vma)
2079 {
2080 	VM_WARN_ON_ONCE(vma->vm_flags & VM_PFNMAP);
2081 	/*
2082 	 * Whoever wants to forbid the zeropage after some zeropages
2083 	 * might already have been mapped has to scan the page tables and
2084 	 * bail out on any zeropages. Zeropages in COW mappings can
2085 	 * be unshared using FAULT_FLAG_UNSHARE faults.
2086 	 */
2087 	if (mm_forbids_zeropage(vma->vm_mm))
2088 		return false;
2089 	/* zeropages in COW mappings are common and unproblematic. */
2090 	if (is_cow_mapping(vma->vm_flags))
2091 		return true;
2092 	/* Mappings that do not allow for writable PTEs are unproblematic. */
2093 	if (!(vma->vm_flags & (VM_WRITE | VM_MAYWRITE)))
2094 		return true;
2095 	/*
2096 	 * Why not allow any VMA that has vm_ops->pfn_mkwrite? GUP could
2097 	 * find the shared zeropage and longterm-pin it, which would
2098 	 * be problematic as soon as the zeropage gets replaced by a different
2099 	 * page due to vma->vm_ops->pfn_mkwrite, because what's mapped would
2100 	 * now differ to what GUP looked up. FSDAX is incompatible to
2101 	 * FOLL_LONGTERM and VM_IO is incompatible to GUP completely (see
2102 	 * check_vma_flags).
2103 	 */
2104 	return vma->vm_ops && vma->vm_ops->pfn_mkwrite &&
2105 	       (vma_is_fsdax(vma) || vma->vm_flags & VM_IO);
2106 }
2107 
2108 static int validate_page_before_insert(struct vm_area_struct *vma,
2109 				       struct page *page)
2110 {
2111 	struct folio *folio = page_folio(page);
2112 
2113 	if (!folio_ref_count(folio))
2114 		return -EINVAL;
2115 	if (unlikely(is_zero_folio(folio))) {
2116 		if (!vm_mixed_zeropage_allowed(vma))
2117 			return -EINVAL;
2118 		return 0;
2119 	}
2120 	if (folio_test_anon(folio) || folio_test_slab(folio) ||
2121 	    page_has_type(page))
2122 		return -EINVAL;
2123 	flush_dcache_folio(folio);
2124 	return 0;
2125 }
2126 
2127 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
2128 				unsigned long addr, struct page *page,
2129 				pgprot_t prot, bool mkwrite)
2130 {
2131 	struct folio *folio = page_folio(page);
2132 	pte_t pteval = ptep_get(pte);
2133 
2134 	if (!pte_none(pteval)) {
2135 		if (!mkwrite)
2136 			return -EBUSY;
2137 
2138 		/* see insert_pfn(). */
2139 		if (pte_pfn(pteval) != page_to_pfn(page)) {
2140 			WARN_ON_ONCE(!is_zero_pfn(pte_pfn(pteval)));
2141 			return -EFAULT;
2142 		}
2143 		pteval = maybe_mkwrite(pteval, vma);
2144 		pteval = pte_mkyoung(pteval);
2145 		if (ptep_set_access_flags(vma, addr, pte, pteval, 1))
2146 			update_mmu_cache(vma, addr, pte);
2147 		return 0;
2148 	}
2149 
2150 	/* Ok, finally just insert the thing.. */
2151 	pteval = mk_pte(page, prot);
2152 	if (unlikely(is_zero_folio(folio))) {
2153 		pteval = pte_mkspecial(pteval);
2154 	} else {
2155 		folio_get(folio);
2156 		pteval = mk_pte(page, prot);
2157 		if (mkwrite) {
2158 			pteval = pte_mkyoung(pteval);
2159 			pteval = maybe_mkwrite(pte_mkdirty(pteval), vma);
2160 		}
2161 		inc_mm_counter(vma->vm_mm, mm_counter_file(folio));
2162 		folio_add_file_rmap_pte(folio, page, vma);
2163 	}
2164 	set_pte_at(vma->vm_mm, addr, pte, pteval);
2165 	return 0;
2166 }
2167 
2168 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
2169 			struct page *page, pgprot_t prot, bool mkwrite)
2170 {
2171 	int retval;
2172 	pte_t *pte;
2173 	spinlock_t *ptl;
2174 
2175 	retval = validate_page_before_insert(vma, page);
2176 	if (retval)
2177 		goto out;
2178 	retval = -ENOMEM;
2179 	pte = get_locked_pte(vma->vm_mm, addr, &ptl);
2180 	if (!pte)
2181 		goto out;
2182 	retval = insert_page_into_pte_locked(vma, pte, addr, page, prot,
2183 					mkwrite);
2184 	pte_unmap_unlock(pte, ptl);
2185 out:
2186 	return retval;
2187 }
2188 
2189 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
2190 			unsigned long addr, struct page *page, pgprot_t prot)
2191 {
2192 	int err;
2193 
2194 	err = validate_page_before_insert(vma, page);
2195 	if (err)
2196 		return err;
2197 	return insert_page_into_pte_locked(vma, pte, addr, page, prot, false);
2198 }
2199 
2200 /* insert_pages() amortizes the cost of spinlock operations
2201  * when inserting pages in a loop.
2202  */
2203 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
2204 			struct page **pages, unsigned long *num, pgprot_t prot)
2205 {
2206 	pmd_t *pmd = NULL;
2207 	pte_t *start_pte, *pte;
2208 	spinlock_t *pte_lock;
2209 	struct mm_struct *const mm = vma->vm_mm;
2210 	unsigned long curr_page_idx = 0;
2211 	unsigned long remaining_pages_total = *num;
2212 	unsigned long pages_to_write_in_pmd;
2213 	int ret;
2214 more:
2215 	ret = -EFAULT;
2216 	pmd = walk_to_pmd(mm, addr);
2217 	if (!pmd)
2218 		goto out;
2219 
2220 	pages_to_write_in_pmd = min_t(unsigned long,
2221 		remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
2222 
2223 	/* Allocate the PTE if necessary; takes PMD lock once only. */
2224 	ret = -ENOMEM;
2225 	if (pte_alloc(mm, pmd))
2226 		goto out;
2227 
2228 	while (pages_to_write_in_pmd) {
2229 		int pte_idx = 0;
2230 		const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
2231 
2232 		start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
2233 		if (!start_pte) {
2234 			ret = -EFAULT;
2235 			goto out;
2236 		}
2237 		for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
2238 			int err = insert_page_in_batch_locked(vma, pte,
2239 				addr, pages[curr_page_idx], prot);
2240 			if (unlikely(err)) {
2241 				pte_unmap_unlock(start_pte, pte_lock);
2242 				ret = err;
2243 				remaining_pages_total -= pte_idx;
2244 				goto out;
2245 			}
2246 			addr += PAGE_SIZE;
2247 			++curr_page_idx;
2248 		}
2249 		pte_unmap_unlock(start_pte, pte_lock);
2250 		pages_to_write_in_pmd -= batch_size;
2251 		remaining_pages_total -= batch_size;
2252 	}
2253 	if (remaining_pages_total)
2254 		goto more;
2255 	ret = 0;
2256 out:
2257 	*num = remaining_pages_total;
2258 	return ret;
2259 }
2260 
2261 /**
2262  * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
2263  * @vma: user vma to map to
2264  * @addr: target start user address of these pages
2265  * @pages: source kernel pages
2266  * @num: in: number of pages to map. out: number of pages that were *not*
2267  * mapped. (0 means all pages were successfully mapped).
2268  *
2269  * Preferred over vm_insert_page() when inserting multiple pages.
2270  *
2271  * In case of error, we may have mapped a subset of the provided
2272  * pages. It is the caller's responsibility to account for this case.
2273  *
2274  * The same restrictions apply as in vm_insert_page().
2275  */
2276 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
2277 			struct page **pages, unsigned long *num)
2278 {
2279 	const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
2280 
2281 	if (addr < vma->vm_start || end_addr >= vma->vm_end)
2282 		return -EFAULT;
2283 	if (!(vma->vm_flags & VM_MIXEDMAP)) {
2284 		BUG_ON(mmap_read_trylock(vma->vm_mm));
2285 		BUG_ON(vma->vm_flags & VM_PFNMAP);
2286 		vm_flags_set(vma, VM_MIXEDMAP);
2287 	}
2288 	/* Defer page refcount checking till we're about to map that page. */
2289 	return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
2290 }
2291 EXPORT_SYMBOL(vm_insert_pages);
2292 
2293 /**
2294  * vm_insert_page - insert single page into user vma
2295  * @vma: user vma to map to
2296  * @addr: target user address of this page
2297  * @page: source kernel page
2298  *
2299  * This allows drivers to insert individual pages they've allocated
2300  * into a user vma. The zeropage is supported in some VMAs,
2301  * see vm_mixed_zeropage_allowed().
2302  *
2303  * The page has to be a nice clean _individual_ kernel allocation.
2304  * If you allocate a compound page, you need to have marked it as
2305  * such (__GFP_COMP), or manually just split the page up yourself
2306  * (see split_page()).
2307  *
2308  * NOTE! Traditionally this was done with "remap_pfn_range()" which
2309  * took an arbitrary page protection parameter. This doesn't allow
2310  * that. Your vma protection will have to be set up correctly, which
2311  * means that if you want a shared writable mapping, you'd better
2312  * ask for a shared writable mapping!
2313  *
2314  * The page does not need to be reserved.
2315  *
2316  * Usually this function is called from f_op->mmap() handler
2317  * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
2318  * Caller must set VM_MIXEDMAP on vma if it wants to call this
2319  * function from other places, for example from page-fault handler.
2320  *
2321  * Return: %0 on success, negative error code otherwise.
2322  */
2323 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2324 			struct page *page)
2325 {
2326 	if (addr < vma->vm_start || addr >= vma->vm_end)
2327 		return -EFAULT;
2328 	if (!(vma->vm_flags & VM_MIXEDMAP)) {
2329 		BUG_ON(mmap_read_trylock(vma->vm_mm));
2330 		BUG_ON(vma->vm_flags & VM_PFNMAP);
2331 		vm_flags_set(vma, VM_MIXEDMAP);
2332 	}
2333 	return insert_page(vma, addr, page, vma->vm_page_prot, false);
2334 }
2335 EXPORT_SYMBOL(vm_insert_page);
2336 
2337 /*
2338  * __vm_map_pages - maps range of kernel pages into user vma
2339  * @vma: user vma to map to
2340  * @pages: pointer to array of source kernel pages
2341  * @num: number of pages in page array
2342  * @offset: user's requested vm_pgoff
2343  *
2344  * This allows drivers to map range of kernel pages into a user vma.
2345  * The zeropage is supported in some VMAs, see
2346  * vm_mixed_zeropage_allowed().
2347  *
2348  * Return: 0 on success and error code otherwise.
2349  */
2350 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2351 				unsigned long num, unsigned long offset)
2352 {
2353 	unsigned long count = vma_pages(vma);
2354 	unsigned long uaddr = vma->vm_start;
2355 	int ret, i;
2356 
2357 	/* Fail if the user requested offset is beyond the end of the object */
2358 	if (offset >= num)
2359 		return -ENXIO;
2360 
2361 	/* Fail if the user requested size exceeds available object size */
2362 	if (count > num - offset)
2363 		return -ENXIO;
2364 
2365 	for (i = 0; i < count; i++) {
2366 		ret = vm_insert_page(vma, uaddr, pages[offset + i]);
2367 		if (ret < 0)
2368 			return ret;
2369 		uaddr += PAGE_SIZE;
2370 	}
2371 
2372 	return 0;
2373 }
2374 
2375 /**
2376  * vm_map_pages - maps range of kernel pages starts with non zero offset
2377  * @vma: user vma to map to
2378  * @pages: pointer to array of source kernel pages
2379  * @num: number of pages in page array
2380  *
2381  * Maps an object consisting of @num pages, catering for the user's
2382  * requested vm_pgoff
2383  *
2384  * If we fail to insert any page into the vma, the function will return
2385  * immediately leaving any previously inserted pages present.  Callers
2386  * from the mmap handler may immediately return the error as their caller
2387  * will destroy the vma, removing any successfully inserted pages. Other
2388  * callers should make their own arrangements for calling unmap_region().
2389  *
2390  * Context: Process context. Called by mmap handlers.
2391  * Return: 0 on success and error code otherwise.
2392  */
2393 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2394 				unsigned long num)
2395 {
2396 	return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
2397 }
2398 EXPORT_SYMBOL(vm_map_pages);
2399 
2400 /**
2401  * vm_map_pages_zero - map range of kernel pages starts with zero offset
2402  * @vma: user vma to map to
2403  * @pages: pointer to array of source kernel pages
2404  * @num: number of pages in page array
2405  *
2406  * Similar to vm_map_pages(), except that it explicitly sets the offset
2407  * to 0. This function is intended for the drivers that did not consider
2408  * vm_pgoff.
2409  *
2410  * Context: Process context. Called by mmap handlers.
2411  * Return: 0 on success and error code otherwise.
2412  */
2413 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
2414 				unsigned long num)
2415 {
2416 	return __vm_map_pages(vma, pages, num, 0);
2417 }
2418 EXPORT_SYMBOL(vm_map_pages_zero);
2419 
2420 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2421 			pfn_t pfn, pgprot_t prot, bool mkwrite)
2422 {
2423 	struct mm_struct *mm = vma->vm_mm;
2424 	pte_t *pte, entry;
2425 	spinlock_t *ptl;
2426 
2427 	pte = get_locked_pte(mm, addr, &ptl);
2428 	if (!pte)
2429 		return VM_FAULT_OOM;
2430 	entry = ptep_get(pte);
2431 	if (!pte_none(entry)) {
2432 		if (mkwrite) {
2433 			/*
2434 			 * For read faults on private mappings the PFN passed
2435 			 * in may not match the PFN we have mapped if the
2436 			 * mapped PFN is a writeable COW page.  In the mkwrite
2437 			 * case we are creating a writable PTE for a shared
2438 			 * mapping and we expect the PFNs to match. If they
2439 			 * don't match, we are likely racing with block
2440 			 * allocation and mapping invalidation so just skip the
2441 			 * update.
2442 			 */
2443 			if (pte_pfn(entry) != pfn_t_to_pfn(pfn)) {
2444 				WARN_ON_ONCE(!is_zero_pfn(pte_pfn(entry)));
2445 				goto out_unlock;
2446 			}
2447 			entry = pte_mkyoung(entry);
2448 			entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2449 			if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2450 				update_mmu_cache(vma, addr, pte);
2451 		}
2452 		goto out_unlock;
2453 	}
2454 
2455 	/* Ok, finally just insert the thing.. */
2456 	if (pfn_t_devmap(pfn))
2457 		entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2458 	else
2459 		entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2460 
2461 	if (mkwrite) {
2462 		entry = pte_mkyoung(entry);
2463 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2464 	}
2465 
2466 	set_pte_at(mm, addr, pte, entry);
2467 	update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2468 
2469 out_unlock:
2470 	pte_unmap_unlock(pte, ptl);
2471 	return VM_FAULT_NOPAGE;
2472 }
2473 
2474 /**
2475  * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2476  * @vma: user vma to map to
2477  * @addr: target user address of this page
2478  * @pfn: source kernel pfn
2479  * @pgprot: pgprot flags for the inserted page
2480  *
2481  * This is exactly like vmf_insert_pfn(), except that it allows drivers
2482  * to override pgprot on a per-page basis.
2483  *
2484  * This only makes sense for IO mappings, and it makes no sense for
2485  * COW mappings.  In general, using multiple vmas is preferable;
2486  * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2487  * impractical.
2488  *
2489  * pgprot typically only differs from @vma->vm_page_prot when drivers set
2490  * caching- and encryption bits different than those of @vma->vm_page_prot,
2491  * because the caching- or encryption mode may not be known at mmap() time.
2492  *
2493  * This is ok as long as @vma->vm_page_prot is not used by the core vm
2494  * to set caching and encryption bits for those vmas (except for COW pages).
2495  * This is ensured by core vm only modifying these page table entries using
2496  * functions that don't touch caching- or encryption bits, using pte_modify()
2497  * if needed. (See for example mprotect()).
2498  *
2499  * Also when new page-table entries are created, this is only done using the
2500  * fault() callback, and never using the value of vma->vm_page_prot,
2501  * except for page-table entries that point to anonymous pages as the result
2502  * of COW.
2503  *
2504  * Context: Process context.  May allocate using %GFP_KERNEL.
2505  * Return: vm_fault_t value.
2506  */
2507 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2508 			unsigned long pfn, pgprot_t pgprot)
2509 {
2510 	/*
2511 	 * Technically, architectures with pte_special can avoid all these
2512 	 * restrictions (same for remap_pfn_range).  However we would like
2513 	 * consistency in testing and feature parity among all, so we should
2514 	 * try to keep these invariants in place for everybody.
2515 	 */
2516 	BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2517 	BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2518 						(VM_PFNMAP|VM_MIXEDMAP));
2519 	BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2520 	BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2521 
2522 	if (addr < vma->vm_start || addr >= vma->vm_end)
2523 		return VM_FAULT_SIGBUS;
2524 
2525 	if (!pfn_modify_allowed(pfn, pgprot))
2526 		return VM_FAULT_SIGBUS;
2527 
2528 	track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2529 
2530 	return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2531 			false);
2532 }
2533 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2534 
2535 /**
2536  * vmf_insert_pfn - insert single pfn into user vma
2537  * @vma: user vma to map to
2538  * @addr: target user address of this page
2539  * @pfn: source kernel pfn
2540  *
2541  * Similar to vm_insert_page, this allows drivers to insert individual pages
2542  * they've allocated into a user vma. Same comments apply.
2543  *
2544  * This function should only be called from a vm_ops->fault handler, and
2545  * in that case the handler should return the result of this function.
2546  *
2547  * vma cannot be a COW mapping.
2548  *
2549  * As this is called only for pages that do not currently exist, we
2550  * do not need to flush old virtual caches or the TLB.
2551  *
2552  * Context: Process context.  May allocate using %GFP_KERNEL.
2553  * Return: vm_fault_t value.
2554  */
2555 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2556 			unsigned long pfn)
2557 {
2558 	return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2559 }
2560 EXPORT_SYMBOL(vmf_insert_pfn);
2561 
2562 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn, bool mkwrite)
2563 {
2564 	if (unlikely(is_zero_pfn(pfn_t_to_pfn(pfn))) &&
2565 	    (mkwrite || !vm_mixed_zeropage_allowed(vma)))
2566 		return false;
2567 	/* these checks mirror the abort conditions in vm_normal_page */
2568 	if (vma->vm_flags & VM_MIXEDMAP)
2569 		return true;
2570 	if (pfn_t_devmap(pfn))
2571 		return true;
2572 	if (pfn_t_special(pfn))
2573 		return true;
2574 	if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2575 		return true;
2576 	return false;
2577 }
2578 
2579 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2580 		unsigned long addr, pfn_t pfn, bool mkwrite)
2581 {
2582 	pgprot_t pgprot = vma->vm_page_prot;
2583 	int err;
2584 
2585 	if (!vm_mixed_ok(vma, pfn, mkwrite))
2586 		return VM_FAULT_SIGBUS;
2587 
2588 	if (addr < vma->vm_start || addr >= vma->vm_end)
2589 		return VM_FAULT_SIGBUS;
2590 
2591 	track_pfn_insert(vma, &pgprot, pfn);
2592 
2593 	if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2594 		return VM_FAULT_SIGBUS;
2595 
2596 	/*
2597 	 * If we don't have pte special, then we have to use the pfn_valid()
2598 	 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2599 	 * refcount the page if pfn_valid is true (hence insert_page rather
2600 	 * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
2601 	 * without pte special, it would there be refcounted as a normal page.
2602 	 */
2603 	if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2604 	    !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2605 		struct page *page;
2606 
2607 		/*
2608 		 * At this point we are committed to insert_page()
2609 		 * regardless of whether the caller specified flags that
2610 		 * result in pfn_t_has_page() == false.
2611 		 */
2612 		page = pfn_to_page(pfn_t_to_pfn(pfn));
2613 		err = insert_page(vma, addr, page, pgprot, mkwrite);
2614 	} else {
2615 		return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2616 	}
2617 
2618 	if (err == -ENOMEM)
2619 		return VM_FAULT_OOM;
2620 	if (err < 0 && err != -EBUSY)
2621 		return VM_FAULT_SIGBUS;
2622 
2623 	return VM_FAULT_NOPAGE;
2624 }
2625 
2626 vm_fault_t vmf_insert_page_mkwrite(struct vm_fault *vmf, struct page *page,
2627 			bool write)
2628 {
2629 	pgprot_t pgprot = vmf->vma->vm_page_prot;
2630 	unsigned long addr = vmf->address;
2631 	int err;
2632 
2633 	if (addr < vmf->vma->vm_start || addr >= vmf->vma->vm_end)
2634 		return VM_FAULT_SIGBUS;
2635 
2636 	err = insert_page(vmf->vma, addr, page, pgprot, write);
2637 	if (err == -ENOMEM)
2638 		return VM_FAULT_OOM;
2639 	if (err < 0 && err != -EBUSY)
2640 		return VM_FAULT_SIGBUS;
2641 
2642 	return VM_FAULT_NOPAGE;
2643 }
2644 EXPORT_SYMBOL_GPL(vmf_insert_page_mkwrite);
2645 
2646 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2647 		pfn_t pfn)
2648 {
2649 	return __vm_insert_mixed(vma, addr, pfn, false);
2650 }
2651 EXPORT_SYMBOL(vmf_insert_mixed);
2652 
2653 /*
2654  *  If the insertion of PTE failed because someone else already added a
2655  *  different entry in the mean time, we treat that as success as we assume
2656  *  the same entry was actually inserted.
2657  */
2658 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2659 		unsigned long addr, pfn_t pfn)
2660 {
2661 	return __vm_insert_mixed(vma, addr, pfn, true);
2662 }
2663 
2664 /*
2665  * maps a range of physical memory into the requested pages. the old
2666  * mappings are removed. any references to nonexistent pages results
2667  * in null mappings (currently treated as "copy-on-access")
2668  */
2669 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2670 			unsigned long addr, unsigned long end,
2671 			unsigned long pfn, pgprot_t prot)
2672 {
2673 	pte_t *pte, *mapped_pte;
2674 	spinlock_t *ptl;
2675 	int err = 0;
2676 
2677 	mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2678 	if (!pte)
2679 		return -ENOMEM;
2680 	arch_enter_lazy_mmu_mode();
2681 	do {
2682 		BUG_ON(!pte_none(ptep_get(pte)));
2683 		if (!pfn_modify_allowed(pfn, prot)) {
2684 			err = -EACCES;
2685 			break;
2686 		}
2687 		set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2688 		pfn++;
2689 	} while (pte++, addr += PAGE_SIZE, addr != end);
2690 	arch_leave_lazy_mmu_mode();
2691 	pte_unmap_unlock(mapped_pte, ptl);
2692 	return err;
2693 }
2694 
2695 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2696 			unsigned long addr, unsigned long end,
2697 			unsigned long pfn, pgprot_t prot)
2698 {
2699 	pmd_t *pmd;
2700 	unsigned long next;
2701 	int err;
2702 
2703 	pfn -= addr >> PAGE_SHIFT;
2704 	pmd = pmd_alloc(mm, pud, addr);
2705 	if (!pmd)
2706 		return -ENOMEM;
2707 	VM_BUG_ON(pmd_trans_huge(*pmd));
2708 	do {
2709 		next = pmd_addr_end(addr, end);
2710 		err = remap_pte_range(mm, pmd, addr, next,
2711 				pfn + (addr >> PAGE_SHIFT), prot);
2712 		if (err)
2713 			return err;
2714 	} while (pmd++, addr = next, addr != end);
2715 	return 0;
2716 }
2717 
2718 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2719 			unsigned long addr, unsigned long end,
2720 			unsigned long pfn, pgprot_t prot)
2721 {
2722 	pud_t *pud;
2723 	unsigned long next;
2724 	int err;
2725 
2726 	pfn -= addr >> PAGE_SHIFT;
2727 	pud = pud_alloc(mm, p4d, addr);
2728 	if (!pud)
2729 		return -ENOMEM;
2730 	do {
2731 		next = pud_addr_end(addr, end);
2732 		err = remap_pmd_range(mm, pud, addr, next,
2733 				pfn + (addr >> PAGE_SHIFT), prot);
2734 		if (err)
2735 			return err;
2736 	} while (pud++, addr = next, addr != end);
2737 	return 0;
2738 }
2739 
2740 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2741 			unsigned long addr, unsigned long end,
2742 			unsigned long pfn, pgprot_t prot)
2743 {
2744 	p4d_t *p4d;
2745 	unsigned long next;
2746 	int err;
2747 
2748 	pfn -= addr >> PAGE_SHIFT;
2749 	p4d = p4d_alloc(mm, pgd, addr);
2750 	if (!p4d)
2751 		return -ENOMEM;
2752 	do {
2753 		next = p4d_addr_end(addr, end);
2754 		err = remap_pud_range(mm, p4d, addr, next,
2755 				pfn + (addr >> PAGE_SHIFT), prot);
2756 		if (err)
2757 			return err;
2758 	} while (p4d++, addr = next, addr != end);
2759 	return 0;
2760 }
2761 
2762 static int remap_pfn_range_internal(struct vm_area_struct *vma, unsigned long addr,
2763 		unsigned long pfn, unsigned long size, pgprot_t prot)
2764 {
2765 	pgd_t *pgd;
2766 	unsigned long next;
2767 	unsigned long end = addr + PAGE_ALIGN(size);
2768 	struct mm_struct *mm = vma->vm_mm;
2769 	int err;
2770 
2771 	if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2772 		return -EINVAL;
2773 
2774 	/*
2775 	 * Physically remapped pages are special. Tell the
2776 	 * rest of the world about it:
2777 	 *   VM_IO tells people not to look at these pages
2778 	 *	(accesses can have side effects).
2779 	 *   VM_PFNMAP tells the core MM that the base pages are just
2780 	 *	raw PFN mappings, and do not have a "struct page" associated
2781 	 *	with them.
2782 	 *   VM_DONTEXPAND
2783 	 *      Disable vma merging and expanding with mremap().
2784 	 *   VM_DONTDUMP
2785 	 *      Omit vma from core dump, even when VM_IO turned off.
2786 	 *
2787 	 * There's a horrible special case to handle copy-on-write
2788 	 * behaviour that some programs depend on. We mark the "original"
2789 	 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2790 	 * See vm_normal_page() for details.
2791 	 */
2792 	if (is_cow_mapping(vma->vm_flags)) {
2793 		if (addr != vma->vm_start || end != vma->vm_end)
2794 			return -EINVAL;
2795 		vma->vm_pgoff = pfn;
2796 	}
2797 
2798 	vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
2799 
2800 	BUG_ON(addr >= end);
2801 	pfn -= addr >> PAGE_SHIFT;
2802 	pgd = pgd_offset(mm, addr);
2803 	flush_cache_range(vma, addr, end);
2804 	do {
2805 		next = pgd_addr_end(addr, end);
2806 		err = remap_p4d_range(mm, pgd, addr, next,
2807 				pfn + (addr >> PAGE_SHIFT), prot);
2808 		if (err)
2809 			return err;
2810 	} while (pgd++, addr = next, addr != end);
2811 
2812 	return 0;
2813 }
2814 
2815 /*
2816  * Variant of remap_pfn_range that does not call track_pfn_remap.  The caller
2817  * must have pre-validated the caching bits of the pgprot_t.
2818  */
2819 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2820 		unsigned long pfn, unsigned long size, pgprot_t prot)
2821 {
2822 	int error = remap_pfn_range_internal(vma, addr, pfn, size, prot);
2823 
2824 	if (!error)
2825 		return 0;
2826 
2827 	/*
2828 	 * A partial pfn range mapping is dangerous: it does not
2829 	 * maintain page reference counts, and callers may free
2830 	 * pages due to the error. So zap it early.
2831 	 */
2832 	zap_page_range_single(vma, addr, size, NULL);
2833 	return error;
2834 }
2835 
2836 /**
2837  * remap_pfn_range - remap kernel memory to userspace
2838  * @vma: user vma to map to
2839  * @addr: target page aligned user address to start at
2840  * @pfn: page frame number of kernel physical memory address
2841  * @size: size of mapping area
2842  * @prot: page protection flags for this mapping
2843  *
2844  * Note: this is only safe if the mm semaphore is held when called.
2845  *
2846  * Return: %0 on success, negative error code otherwise.
2847  */
2848 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2849 		    unsigned long pfn, unsigned long size, pgprot_t prot)
2850 {
2851 	int err;
2852 
2853 	err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2854 	if (err)
2855 		return -EINVAL;
2856 
2857 	err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2858 	if (err)
2859 		untrack_pfn(vma, pfn, PAGE_ALIGN(size), true);
2860 	return err;
2861 }
2862 EXPORT_SYMBOL(remap_pfn_range);
2863 
2864 /**
2865  * vm_iomap_memory - remap memory to userspace
2866  * @vma: user vma to map to
2867  * @start: start of the physical memory to be mapped
2868  * @len: size of area
2869  *
2870  * This is a simplified io_remap_pfn_range() for common driver use. The
2871  * driver just needs to give us the physical memory range to be mapped,
2872  * we'll figure out the rest from the vma information.
2873  *
2874  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2875  * whatever write-combining details or similar.
2876  *
2877  * Return: %0 on success, negative error code otherwise.
2878  */
2879 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2880 {
2881 	unsigned long vm_len, pfn, pages;
2882 
2883 	/* Check that the physical memory area passed in looks valid */
2884 	if (start + len < start)
2885 		return -EINVAL;
2886 	/*
2887 	 * You *really* shouldn't map things that aren't page-aligned,
2888 	 * but we've historically allowed it because IO memory might
2889 	 * just have smaller alignment.
2890 	 */
2891 	len += start & ~PAGE_MASK;
2892 	pfn = start >> PAGE_SHIFT;
2893 	pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2894 	if (pfn + pages < pfn)
2895 		return -EINVAL;
2896 
2897 	/* We start the mapping 'vm_pgoff' pages into the area */
2898 	if (vma->vm_pgoff > pages)
2899 		return -EINVAL;
2900 	pfn += vma->vm_pgoff;
2901 	pages -= vma->vm_pgoff;
2902 
2903 	/* Can we fit all of the mapping? */
2904 	vm_len = vma->vm_end - vma->vm_start;
2905 	if (vm_len >> PAGE_SHIFT > pages)
2906 		return -EINVAL;
2907 
2908 	/* Ok, let it rip */
2909 	return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2910 }
2911 EXPORT_SYMBOL(vm_iomap_memory);
2912 
2913 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2914 				     unsigned long addr, unsigned long end,
2915 				     pte_fn_t fn, void *data, bool create,
2916 				     pgtbl_mod_mask *mask)
2917 {
2918 	pte_t *pte, *mapped_pte;
2919 	int err = 0;
2920 	spinlock_t *ptl;
2921 
2922 	if (create) {
2923 		mapped_pte = pte = (mm == &init_mm) ?
2924 			pte_alloc_kernel_track(pmd, addr, mask) :
2925 			pte_alloc_map_lock(mm, pmd, addr, &ptl);
2926 		if (!pte)
2927 			return -ENOMEM;
2928 	} else {
2929 		mapped_pte = pte = (mm == &init_mm) ?
2930 			pte_offset_kernel(pmd, addr) :
2931 			pte_offset_map_lock(mm, pmd, addr, &ptl);
2932 		if (!pte)
2933 			return -EINVAL;
2934 	}
2935 
2936 	arch_enter_lazy_mmu_mode();
2937 
2938 	if (fn) {
2939 		do {
2940 			if (create || !pte_none(ptep_get(pte))) {
2941 				err = fn(pte, addr, data);
2942 				if (err)
2943 					break;
2944 			}
2945 		} while (pte++, addr += PAGE_SIZE, addr != end);
2946 	}
2947 	*mask |= PGTBL_PTE_MODIFIED;
2948 
2949 	arch_leave_lazy_mmu_mode();
2950 
2951 	if (mm != &init_mm)
2952 		pte_unmap_unlock(mapped_pte, ptl);
2953 	return err;
2954 }
2955 
2956 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2957 				     unsigned long addr, unsigned long end,
2958 				     pte_fn_t fn, void *data, bool create,
2959 				     pgtbl_mod_mask *mask)
2960 {
2961 	pmd_t *pmd;
2962 	unsigned long next;
2963 	int err = 0;
2964 
2965 	BUG_ON(pud_leaf(*pud));
2966 
2967 	if (create) {
2968 		pmd = pmd_alloc_track(mm, pud, addr, mask);
2969 		if (!pmd)
2970 			return -ENOMEM;
2971 	} else {
2972 		pmd = pmd_offset(pud, addr);
2973 	}
2974 	do {
2975 		next = pmd_addr_end(addr, end);
2976 		if (pmd_none(*pmd) && !create)
2977 			continue;
2978 		if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2979 			return -EINVAL;
2980 		if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2981 			if (!create)
2982 				continue;
2983 			pmd_clear_bad(pmd);
2984 		}
2985 		err = apply_to_pte_range(mm, pmd, addr, next,
2986 					 fn, data, create, mask);
2987 		if (err)
2988 			break;
2989 	} while (pmd++, addr = next, addr != end);
2990 
2991 	return err;
2992 }
2993 
2994 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2995 				     unsigned long addr, unsigned long end,
2996 				     pte_fn_t fn, void *data, bool create,
2997 				     pgtbl_mod_mask *mask)
2998 {
2999 	pud_t *pud;
3000 	unsigned long next;
3001 	int err = 0;
3002 
3003 	if (create) {
3004 		pud = pud_alloc_track(mm, p4d, addr, mask);
3005 		if (!pud)
3006 			return -ENOMEM;
3007 	} else {
3008 		pud = pud_offset(p4d, addr);
3009 	}
3010 	do {
3011 		next = pud_addr_end(addr, end);
3012 		if (pud_none(*pud) && !create)
3013 			continue;
3014 		if (WARN_ON_ONCE(pud_leaf(*pud)))
3015 			return -EINVAL;
3016 		if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
3017 			if (!create)
3018 				continue;
3019 			pud_clear_bad(pud);
3020 		}
3021 		err = apply_to_pmd_range(mm, pud, addr, next,
3022 					 fn, data, create, mask);
3023 		if (err)
3024 			break;
3025 	} while (pud++, addr = next, addr != end);
3026 
3027 	return err;
3028 }
3029 
3030 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
3031 				     unsigned long addr, unsigned long end,
3032 				     pte_fn_t fn, void *data, bool create,
3033 				     pgtbl_mod_mask *mask)
3034 {
3035 	p4d_t *p4d;
3036 	unsigned long next;
3037 	int err = 0;
3038 
3039 	if (create) {
3040 		p4d = p4d_alloc_track(mm, pgd, addr, mask);
3041 		if (!p4d)
3042 			return -ENOMEM;
3043 	} else {
3044 		p4d = p4d_offset(pgd, addr);
3045 	}
3046 	do {
3047 		next = p4d_addr_end(addr, end);
3048 		if (p4d_none(*p4d) && !create)
3049 			continue;
3050 		if (WARN_ON_ONCE(p4d_leaf(*p4d)))
3051 			return -EINVAL;
3052 		if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
3053 			if (!create)
3054 				continue;
3055 			p4d_clear_bad(p4d);
3056 		}
3057 		err = apply_to_pud_range(mm, p4d, addr, next,
3058 					 fn, data, create, mask);
3059 		if (err)
3060 			break;
3061 	} while (p4d++, addr = next, addr != end);
3062 
3063 	return err;
3064 }
3065 
3066 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
3067 				 unsigned long size, pte_fn_t fn,
3068 				 void *data, bool create)
3069 {
3070 	pgd_t *pgd;
3071 	unsigned long start = addr, next;
3072 	unsigned long end = addr + size;
3073 	pgtbl_mod_mask mask = 0;
3074 	int err = 0;
3075 
3076 	if (WARN_ON(addr >= end))
3077 		return -EINVAL;
3078 
3079 	pgd = pgd_offset(mm, addr);
3080 	do {
3081 		next = pgd_addr_end(addr, end);
3082 		if (pgd_none(*pgd) && !create)
3083 			continue;
3084 		if (WARN_ON_ONCE(pgd_leaf(*pgd))) {
3085 			err = -EINVAL;
3086 			break;
3087 		}
3088 		if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
3089 			if (!create)
3090 				continue;
3091 			pgd_clear_bad(pgd);
3092 		}
3093 		err = apply_to_p4d_range(mm, pgd, addr, next,
3094 					 fn, data, create, &mask);
3095 		if (err)
3096 			break;
3097 	} while (pgd++, addr = next, addr != end);
3098 
3099 	if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
3100 		arch_sync_kernel_mappings(start, start + size);
3101 
3102 	return err;
3103 }
3104 
3105 /*
3106  * Scan a region of virtual memory, filling in page tables as necessary
3107  * and calling a provided function on each leaf page table.
3108  */
3109 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
3110 			unsigned long size, pte_fn_t fn, void *data)
3111 {
3112 	return __apply_to_page_range(mm, addr, size, fn, data, true);
3113 }
3114 EXPORT_SYMBOL_GPL(apply_to_page_range);
3115 
3116 /*
3117  * Scan a region of virtual memory, calling a provided function on
3118  * each leaf page table where it exists.
3119  *
3120  * Unlike apply_to_page_range, this does _not_ fill in page tables
3121  * where they are absent.
3122  */
3123 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
3124 				 unsigned long size, pte_fn_t fn, void *data)
3125 {
3126 	return __apply_to_page_range(mm, addr, size, fn, data, false);
3127 }
3128 
3129 /*
3130  * handle_pte_fault chooses page fault handler according to an entry which was
3131  * read non-atomically.  Before making any commitment, on those architectures
3132  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
3133  * parts, do_swap_page must check under lock before unmapping the pte and
3134  * proceeding (but do_wp_page is only called after already making such a check;
3135  * and do_anonymous_page can safely check later on).
3136  */
3137 static inline int pte_unmap_same(struct vm_fault *vmf)
3138 {
3139 	int same = 1;
3140 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
3141 	if (sizeof(pte_t) > sizeof(unsigned long)) {
3142 		spin_lock(vmf->ptl);
3143 		same = pte_same(ptep_get(vmf->pte), vmf->orig_pte);
3144 		spin_unlock(vmf->ptl);
3145 	}
3146 #endif
3147 	pte_unmap(vmf->pte);
3148 	vmf->pte = NULL;
3149 	return same;
3150 }
3151 
3152 /*
3153  * Return:
3154  *	0:		copied succeeded
3155  *	-EHWPOISON:	copy failed due to hwpoison in source page
3156  *	-EAGAIN:	copied failed (some other reason)
3157  */
3158 static inline int __wp_page_copy_user(struct page *dst, struct page *src,
3159 				      struct vm_fault *vmf)
3160 {
3161 	int ret;
3162 	void *kaddr;
3163 	void __user *uaddr;
3164 	struct vm_area_struct *vma = vmf->vma;
3165 	struct mm_struct *mm = vma->vm_mm;
3166 	unsigned long addr = vmf->address;
3167 
3168 	if (likely(src)) {
3169 		if (copy_mc_user_highpage(dst, src, addr, vma))
3170 			return -EHWPOISON;
3171 		return 0;
3172 	}
3173 
3174 	/*
3175 	 * If the source page was a PFN mapping, we don't have
3176 	 * a "struct page" for it. We do a best-effort copy by
3177 	 * just copying from the original user address. If that
3178 	 * fails, we just zero-fill it. Live with it.
3179 	 */
3180 	kaddr = kmap_local_page(dst);
3181 	pagefault_disable();
3182 	uaddr = (void __user *)(addr & PAGE_MASK);
3183 
3184 	/*
3185 	 * On architectures with software "accessed" bits, we would
3186 	 * take a double page fault, so mark it accessed here.
3187 	 */
3188 	vmf->pte = NULL;
3189 	if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) {
3190 		pte_t entry;
3191 
3192 		vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
3193 		if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3194 			/*
3195 			 * Other thread has already handled the fault
3196 			 * and update local tlb only
3197 			 */
3198 			if (vmf->pte)
3199 				update_mmu_tlb(vma, addr, vmf->pte);
3200 			ret = -EAGAIN;
3201 			goto pte_unlock;
3202 		}
3203 
3204 		entry = pte_mkyoung(vmf->orig_pte);
3205 		if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
3206 			update_mmu_cache_range(vmf, vma, addr, vmf->pte, 1);
3207 	}
3208 
3209 	/*
3210 	 * This really shouldn't fail, because the page is there
3211 	 * in the page tables. But it might just be unreadable,
3212 	 * in which case we just give up and fill the result with
3213 	 * zeroes.
3214 	 */
3215 	if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
3216 		if (vmf->pte)
3217 			goto warn;
3218 
3219 		/* Re-validate under PTL if the page is still mapped */
3220 		vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
3221 		if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3222 			/* The PTE changed under us, update local tlb */
3223 			if (vmf->pte)
3224 				update_mmu_tlb(vma, addr, vmf->pte);
3225 			ret = -EAGAIN;
3226 			goto pte_unlock;
3227 		}
3228 
3229 		/*
3230 		 * The same page can be mapped back since last copy attempt.
3231 		 * Try to copy again under PTL.
3232 		 */
3233 		if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
3234 			/*
3235 			 * Give a warn in case there can be some obscure
3236 			 * use-case
3237 			 */
3238 warn:
3239 			WARN_ON_ONCE(1);
3240 			clear_page(kaddr);
3241 		}
3242 	}
3243 
3244 	ret = 0;
3245 
3246 pte_unlock:
3247 	if (vmf->pte)
3248 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3249 	pagefault_enable();
3250 	kunmap_local(kaddr);
3251 	flush_dcache_page(dst);
3252 
3253 	return ret;
3254 }
3255 
3256 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
3257 {
3258 	struct file *vm_file = vma->vm_file;
3259 
3260 	if (vm_file)
3261 		return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
3262 
3263 	/*
3264 	 * Special mappings (e.g. VDSO) do not have any file so fake
3265 	 * a default GFP_KERNEL for them.
3266 	 */
3267 	return GFP_KERNEL;
3268 }
3269 
3270 /*
3271  * Notify the address space that the page is about to become writable so that
3272  * it can prohibit this or wait for the page to get into an appropriate state.
3273  *
3274  * We do this without the lock held, so that it can sleep if it needs to.
3275  */
3276 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf, struct folio *folio)
3277 {
3278 	vm_fault_t ret;
3279 	unsigned int old_flags = vmf->flags;
3280 
3281 	vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
3282 
3283 	if (vmf->vma->vm_file &&
3284 	    IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
3285 		return VM_FAULT_SIGBUS;
3286 
3287 	ret = vmf->vma->vm_ops->page_mkwrite(vmf);
3288 	/* Restore original flags so that caller is not surprised */
3289 	vmf->flags = old_flags;
3290 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
3291 		return ret;
3292 	if (unlikely(!(ret & VM_FAULT_LOCKED))) {
3293 		folio_lock(folio);
3294 		if (!folio->mapping) {
3295 			folio_unlock(folio);
3296 			return 0; /* retry */
3297 		}
3298 		ret |= VM_FAULT_LOCKED;
3299 	} else
3300 		VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3301 	return ret;
3302 }
3303 
3304 /*
3305  * Handle dirtying of a page in shared file mapping on a write fault.
3306  *
3307  * The function expects the page to be locked and unlocks it.
3308  */
3309 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
3310 {
3311 	struct vm_area_struct *vma = vmf->vma;
3312 	struct address_space *mapping;
3313 	struct folio *folio = page_folio(vmf->page);
3314 	bool dirtied;
3315 	bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
3316 
3317 	dirtied = folio_mark_dirty(folio);
3318 	VM_BUG_ON_FOLIO(folio_test_anon(folio), folio);
3319 	/*
3320 	 * Take a local copy of the address_space - folio.mapping may be zeroed
3321 	 * by truncate after folio_unlock().   The address_space itself remains
3322 	 * pinned by vma->vm_file's reference.  We rely on folio_unlock()'s
3323 	 * release semantics to prevent the compiler from undoing this copying.
3324 	 */
3325 	mapping = folio_raw_mapping(folio);
3326 	folio_unlock(folio);
3327 
3328 	if (!page_mkwrite)
3329 		file_update_time(vma->vm_file);
3330 
3331 	/*
3332 	 * Throttle page dirtying rate down to writeback speed.
3333 	 *
3334 	 * mapping may be NULL here because some device drivers do not
3335 	 * set page.mapping but still dirty their pages
3336 	 *
3337 	 * Drop the mmap_lock before waiting on IO, if we can. The file
3338 	 * is pinning the mapping, as per above.
3339 	 */
3340 	if ((dirtied || page_mkwrite) && mapping) {
3341 		struct file *fpin;
3342 
3343 		fpin = maybe_unlock_mmap_for_io(vmf, NULL);
3344 		balance_dirty_pages_ratelimited(mapping);
3345 		if (fpin) {
3346 			fput(fpin);
3347 			return VM_FAULT_COMPLETED;
3348 		}
3349 	}
3350 
3351 	return 0;
3352 }
3353 
3354 /*
3355  * Handle write page faults for pages that can be reused in the current vma
3356  *
3357  * This can happen either due to the mapping being with the VM_SHARED flag,
3358  * or due to us being the last reference standing to the page. In either
3359  * case, all we need to do here is to mark the page as writable and update
3360  * any related book-keeping.
3361  */
3362 static inline void wp_page_reuse(struct vm_fault *vmf, struct folio *folio)
3363 	__releases(vmf->ptl)
3364 {
3365 	struct vm_area_struct *vma = vmf->vma;
3366 	pte_t entry;
3367 
3368 	VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
3369 	VM_WARN_ON(is_zero_pfn(pte_pfn(vmf->orig_pte)));
3370 
3371 	if (folio) {
3372 		VM_BUG_ON(folio_test_anon(folio) &&
3373 			  !PageAnonExclusive(vmf->page));
3374 		/*
3375 		 * Clear the folio's cpupid information as the existing
3376 		 * information potentially belongs to a now completely
3377 		 * unrelated process.
3378 		 */
3379 		folio_xchg_last_cpupid(folio, (1 << LAST_CPUPID_SHIFT) - 1);
3380 	}
3381 
3382 	flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3383 	entry = pte_mkyoung(vmf->orig_pte);
3384 	entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3385 	if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
3386 		update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
3387 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3388 	count_vm_event(PGREUSE);
3389 }
3390 
3391 /*
3392  * We could add a bitflag somewhere, but for now, we know that all
3393  * vm_ops that have a ->map_pages have been audited and don't need
3394  * the mmap_lock to be held.
3395  */
3396 static inline vm_fault_t vmf_can_call_fault(const struct vm_fault *vmf)
3397 {
3398 	struct vm_area_struct *vma = vmf->vma;
3399 
3400 	if (vma->vm_ops->map_pages || !(vmf->flags & FAULT_FLAG_VMA_LOCK))
3401 		return 0;
3402 	vma_end_read(vma);
3403 	return VM_FAULT_RETRY;
3404 }
3405 
3406 /**
3407  * __vmf_anon_prepare - Prepare to handle an anonymous fault.
3408  * @vmf: The vm_fault descriptor passed from the fault handler.
3409  *
3410  * When preparing to insert an anonymous page into a VMA from a
3411  * fault handler, call this function rather than anon_vma_prepare().
3412  * If this vma does not already have an associated anon_vma and we are
3413  * only protected by the per-VMA lock, the caller must retry with the
3414  * mmap_lock held.  __anon_vma_prepare() will look at adjacent VMAs to
3415  * determine if this VMA can share its anon_vma, and that's not safe to
3416  * do with only the per-VMA lock held for this VMA.
3417  *
3418  * Return: 0 if fault handling can proceed.  Any other value should be
3419  * returned to the caller.
3420  */
3421 vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)
3422 {
3423 	struct vm_area_struct *vma = vmf->vma;
3424 	vm_fault_t ret = 0;
3425 
3426 	if (likely(vma->anon_vma))
3427 		return 0;
3428 	if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
3429 		if (!mmap_read_trylock(vma->vm_mm))
3430 			return VM_FAULT_RETRY;
3431 	}
3432 	if (__anon_vma_prepare(vma))
3433 		ret = VM_FAULT_OOM;
3434 	if (vmf->flags & FAULT_FLAG_VMA_LOCK)
3435 		mmap_read_unlock(vma->vm_mm);
3436 	return ret;
3437 }
3438 
3439 /*
3440  * Handle the case of a page which we actually need to copy to a new page,
3441  * either due to COW or unsharing.
3442  *
3443  * Called with mmap_lock locked and the old page referenced, but
3444  * without the ptl held.
3445  *
3446  * High level logic flow:
3447  *
3448  * - Allocate a page, copy the content of the old page to the new one.
3449  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
3450  * - Take the PTL. If the pte changed, bail out and release the allocated page
3451  * - If the pte is still the way we remember it, update the page table and all
3452  *   relevant references. This includes dropping the reference the page-table
3453  *   held to the old page, as well as updating the rmap.
3454  * - In any case, unlock the PTL and drop the reference we took to the old page.
3455  */
3456 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
3457 {
3458 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3459 	struct vm_area_struct *vma = vmf->vma;
3460 	struct mm_struct *mm = vma->vm_mm;
3461 	struct folio *old_folio = NULL;
3462 	struct folio *new_folio = NULL;
3463 	pte_t entry;
3464 	int page_copied = 0;
3465 	struct mmu_notifier_range range;
3466 	vm_fault_t ret;
3467 	bool pfn_is_zero;
3468 
3469 	delayacct_wpcopy_start();
3470 
3471 	if (vmf->page)
3472 		old_folio = page_folio(vmf->page);
3473 	ret = vmf_anon_prepare(vmf);
3474 	if (unlikely(ret))
3475 		goto out;
3476 
3477 	pfn_is_zero = is_zero_pfn(pte_pfn(vmf->orig_pte));
3478 	new_folio = folio_prealloc(mm, vma, vmf->address, pfn_is_zero);
3479 	if (!new_folio)
3480 		goto oom;
3481 
3482 	if (!pfn_is_zero) {
3483 		int err;
3484 
3485 		err = __wp_page_copy_user(&new_folio->page, vmf->page, vmf);
3486 		if (err) {
3487 			/*
3488 			 * COW failed, if the fault was solved by other,
3489 			 * it's fine. If not, userspace would re-fault on
3490 			 * the same address and we will handle the fault
3491 			 * from the second attempt.
3492 			 * The -EHWPOISON case will not be retried.
3493 			 */
3494 			folio_put(new_folio);
3495 			if (old_folio)
3496 				folio_put(old_folio);
3497 
3498 			delayacct_wpcopy_end();
3499 			return err == -EHWPOISON ? VM_FAULT_HWPOISON : 0;
3500 		}
3501 		kmsan_copy_page_meta(&new_folio->page, vmf->page);
3502 	}
3503 
3504 	__folio_mark_uptodate(new_folio);
3505 
3506 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
3507 				vmf->address & PAGE_MASK,
3508 				(vmf->address & PAGE_MASK) + PAGE_SIZE);
3509 	mmu_notifier_invalidate_range_start(&range);
3510 
3511 	/*
3512 	 * Re-check the pte - we dropped the lock
3513 	 */
3514 	vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
3515 	if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3516 		if (old_folio) {
3517 			if (!folio_test_anon(old_folio)) {
3518 				dec_mm_counter(mm, mm_counter_file(old_folio));
3519 				inc_mm_counter(mm, MM_ANONPAGES);
3520 			}
3521 		} else {
3522 			ksm_might_unmap_zero_page(mm, vmf->orig_pte);
3523 			inc_mm_counter(mm, MM_ANONPAGES);
3524 		}
3525 		flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3526 		entry = folio_mk_pte(new_folio, vma->vm_page_prot);
3527 		entry = pte_sw_mkyoung(entry);
3528 		if (unlikely(unshare)) {
3529 			if (pte_soft_dirty(vmf->orig_pte))
3530 				entry = pte_mksoft_dirty(entry);
3531 			if (pte_uffd_wp(vmf->orig_pte))
3532 				entry = pte_mkuffd_wp(entry);
3533 		} else {
3534 			entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3535 		}
3536 
3537 		/*
3538 		 * Clear the pte entry and flush it first, before updating the
3539 		 * pte with the new entry, to keep TLBs on different CPUs in
3540 		 * sync. This code used to set the new PTE then flush TLBs, but
3541 		 * that left a window where the new PTE could be loaded into
3542 		 * some TLBs while the old PTE remains in others.
3543 		 */
3544 		ptep_clear_flush(vma, vmf->address, vmf->pte);
3545 		folio_add_new_anon_rmap(new_folio, vma, vmf->address, RMAP_EXCLUSIVE);
3546 		folio_add_lru_vma(new_folio, vma);
3547 		BUG_ON(unshare && pte_write(entry));
3548 		set_pte_at(mm, vmf->address, vmf->pte, entry);
3549 		update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
3550 		if (old_folio) {
3551 			/*
3552 			 * Only after switching the pte to the new page may
3553 			 * we remove the mapcount here. Otherwise another
3554 			 * process may come and find the rmap count decremented
3555 			 * before the pte is switched to the new page, and
3556 			 * "reuse" the old page writing into it while our pte
3557 			 * here still points into it and can be read by other
3558 			 * threads.
3559 			 *
3560 			 * The critical issue is to order this
3561 			 * folio_remove_rmap_pte() with the ptp_clear_flush
3562 			 * above. Those stores are ordered by (if nothing else,)
3563 			 * the barrier present in the atomic_add_negative
3564 			 * in folio_remove_rmap_pte();
3565 			 *
3566 			 * Then the TLB flush in ptep_clear_flush ensures that
3567 			 * no process can access the old page before the
3568 			 * decremented mapcount is visible. And the old page
3569 			 * cannot be reused until after the decremented
3570 			 * mapcount is visible. So transitively, TLBs to
3571 			 * old page will be flushed before it can be reused.
3572 			 */
3573 			folio_remove_rmap_pte(old_folio, vmf->page, vma);
3574 		}
3575 
3576 		/* Free the old page.. */
3577 		new_folio = old_folio;
3578 		page_copied = 1;
3579 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3580 	} else if (vmf->pte) {
3581 		update_mmu_tlb(vma, vmf->address, vmf->pte);
3582 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3583 	}
3584 
3585 	mmu_notifier_invalidate_range_end(&range);
3586 
3587 	if (new_folio)
3588 		folio_put(new_folio);
3589 	if (old_folio) {
3590 		if (page_copied)
3591 			free_swap_cache(old_folio);
3592 		folio_put(old_folio);
3593 	}
3594 
3595 	delayacct_wpcopy_end();
3596 	return 0;
3597 oom:
3598 	ret = VM_FAULT_OOM;
3599 out:
3600 	if (old_folio)
3601 		folio_put(old_folio);
3602 
3603 	delayacct_wpcopy_end();
3604 	return ret;
3605 }
3606 
3607 /**
3608  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3609  *			  writeable once the page is prepared
3610  *
3611  * @vmf: structure describing the fault
3612  * @folio: the folio of vmf->page
3613  *
3614  * This function handles all that is needed to finish a write page fault in a
3615  * shared mapping due to PTE being read-only once the mapped page is prepared.
3616  * It handles locking of PTE and modifying it.
3617  *
3618  * The function expects the page to be locked or other protection against
3619  * concurrent faults / writeback (such as DAX radix tree locks).
3620  *
3621  * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3622  * we acquired PTE lock.
3623  */
3624 static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio)
3625 {
3626 	WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3627 	vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3628 				       &vmf->ptl);
3629 	if (!vmf->pte)
3630 		return VM_FAULT_NOPAGE;
3631 	/*
3632 	 * We might have raced with another page fault while we released the
3633 	 * pte_offset_map_lock.
3634 	 */
3635 	if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) {
3636 		update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3637 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3638 		return VM_FAULT_NOPAGE;
3639 	}
3640 	wp_page_reuse(vmf, folio);
3641 	return 0;
3642 }
3643 
3644 /*
3645  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3646  * mapping
3647  */
3648 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3649 {
3650 	struct vm_area_struct *vma = vmf->vma;
3651 
3652 	if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3653 		vm_fault_t ret;
3654 
3655 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3656 		ret = vmf_can_call_fault(vmf);
3657 		if (ret)
3658 			return ret;
3659 
3660 		vmf->flags |= FAULT_FLAG_MKWRITE;
3661 		ret = vma->vm_ops->pfn_mkwrite(vmf);
3662 		if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3663 			return ret;
3664 		return finish_mkwrite_fault(vmf, NULL);
3665 	}
3666 	wp_page_reuse(vmf, NULL);
3667 	return 0;
3668 }
3669 
3670 static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio)
3671 	__releases(vmf->ptl)
3672 {
3673 	struct vm_area_struct *vma = vmf->vma;
3674 	vm_fault_t ret = 0;
3675 
3676 	folio_get(folio);
3677 
3678 	if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3679 		vm_fault_t tmp;
3680 
3681 		pte_unmap_unlock(vmf->pte, vmf->ptl);
3682 		tmp = vmf_can_call_fault(vmf);
3683 		if (tmp) {
3684 			folio_put(folio);
3685 			return tmp;
3686 		}
3687 
3688 		tmp = do_page_mkwrite(vmf, folio);
3689 		if (unlikely(!tmp || (tmp &
3690 				      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3691 			folio_put(folio);
3692 			return tmp;
3693 		}
3694 		tmp = finish_mkwrite_fault(vmf, folio);
3695 		if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3696 			folio_unlock(folio);
3697 			folio_put(folio);
3698 			return tmp;
3699 		}
3700 	} else {
3701 		wp_page_reuse(vmf, folio);
3702 		folio_lock(folio);
3703 	}
3704 	ret |= fault_dirty_shared_page(vmf);
3705 	folio_put(folio);
3706 
3707 	return ret;
3708 }
3709 
3710 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3711 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
3712 		struct vm_area_struct *vma)
3713 {
3714 	bool exclusive = false;
3715 
3716 	/* Let's just free up a large folio if only a single page is mapped. */
3717 	if (folio_large_mapcount(folio) <= 1)
3718 		return false;
3719 
3720 	/*
3721 	 * The assumption for anonymous folios is that each page can only get
3722 	 * mapped once into each MM. The only exception are KSM folios, which
3723 	 * are always small.
3724 	 *
3725 	 * Each taken mapcount must be paired with exactly one taken reference,
3726 	 * whereby the refcount must be incremented before the mapcount when
3727 	 * mapping a page, and the refcount must be decremented after the
3728 	 * mapcount when unmapping a page.
3729 	 *
3730 	 * If all folio references are from mappings, and all mappings are in
3731 	 * the page tables of this MM, then this folio is exclusive to this MM.
3732 	 */
3733 	if (folio_test_large_maybe_mapped_shared(folio))
3734 		return false;
3735 
3736 	VM_WARN_ON_ONCE(folio_test_ksm(folio));
3737 
3738 	if (unlikely(folio_test_swapcache(folio))) {
3739 		/*
3740 		 * Note: freeing up the swapcache will fail if some PTEs are
3741 		 * still swap entries.
3742 		 */
3743 		if (!folio_trylock(folio))
3744 			return false;
3745 		folio_free_swap(folio);
3746 		folio_unlock(folio);
3747 	}
3748 
3749 	if (folio_large_mapcount(folio) != folio_ref_count(folio))
3750 		return false;
3751 
3752 	/* Stabilize the mapcount vs. refcount and recheck. */
3753 	folio_lock_large_mapcount(folio);
3754 	VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_ref_count(folio), folio);
3755 
3756 	if (folio_test_large_maybe_mapped_shared(folio))
3757 		goto unlock;
3758 	if (folio_large_mapcount(folio) != folio_ref_count(folio))
3759 		goto unlock;
3760 
3761 	VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_nr_pages(folio), folio);
3762 	VM_WARN_ON_ONCE_FOLIO(folio_entire_mapcount(folio), folio);
3763 	VM_WARN_ON_ONCE(folio_mm_id(folio, 0) != vma->vm_mm->mm_id &&
3764 			folio_mm_id(folio, 1) != vma->vm_mm->mm_id);
3765 
3766 	/*
3767 	 * Do we need the folio lock? Likely not. If there would have been
3768 	 * references from page migration/swapout, we would have detected
3769 	 * an additional folio reference and never ended up here.
3770 	 */
3771 	exclusive = true;
3772 unlock:
3773 	folio_unlock_large_mapcount(folio);
3774 	return exclusive;
3775 }
3776 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
3777 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
3778 		struct vm_area_struct *vma)
3779 {
3780 	BUILD_BUG();
3781 }
3782 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3783 
3784 static bool wp_can_reuse_anon_folio(struct folio *folio,
3785 				    struct vm_area_struct *vma)
3786 {
3787 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && folio_test_large(folio))
3788 		return __wp_can_reuse_large_anon_folio(folio, vma);
3789 
3790 	/*
3791 	 * We have to verify under folio lock: these early checks are
3792 	 * just an optimization to avoid locking the folio and freeing
3793 	 * the swapcache if there is little hope that we can reuse.
3794 	 *
3795 	 * KSM doesn't necessarily raise the folio refcount.
3796 	 */
3797 	if (folio_test_ksm(folio) || folio_ref_count(folio) > 3)
3798 		return false;
3799 	if (!folio_test_lru(folio))
3800 		/*
3801 		 * We cannot easily detect+handle references from
3802 		 * remote LRU caches or references to LRU folios.
3803 		 */
3804 		lru_add_drain();
3805 	if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio))
3806 		return false;
3807 	if (!folio_trylock(folio))
3808 		return false;
3809 	if (folio_test_swapcache(folio))
3810 		folio_free_swap(folio);
3811 	if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
3812 		folio_unlock(folio);
3813 		return false;
3814 	}
3815 	/*
3816 	 * Ok, we've got the only folio reference from our mapping
3817 	 * and the folio is locked, it's dark out, and we're wearing
3818 	 * sunglasses. Hit it.
3819 	 */
3820 	folio_move_anon_rmap(folio, vma);
3821 	folio_unlock(folio);
3822 	return true;
3823 }
3824 
3825 /*
3826  * This routine handles present pages, when
3827  * * users try to write to a shared page (FAULT_FLAG_WRITE)
3828  * * GUP wants to take a R/O pin on a possibly shared anonymous page
3829  *   (FAULT_FLAG_UNSHARE)
3830  *
3831  * It is done by copying the page to a new address and decrementing the
3832  * shared-page counter for the old page.
3833  *
3834  * Note that this routine assumes that the protection checks have been
3835  * done by the caller (the low-level page fault routine in most cases).
3836  * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
3837  * done any necessary COW.
3838  *
3839  * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
3840  * though the page will change only once the write actually happens. This
3841  * avoids a few races, and potentially makes it more efficient.
3842  *
3843  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3844  * but allow concurrent faults), with pte both mapped and locked.
3845  * We return with mmap_lock still held, but pte unmapped and unlocked.
3846  */
3847 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3848 	__releases(vmf->ptl)
3849 {
3850 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3851 	struct vm_area_struct *vma = vmf->vma;
3852 	struct folio *folio = NULL;
3853 	pte_t pte;
3854 
3855 	if (likely(!unshare)) {
3856 		if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) {
3857 			if (!userfaultfd_wp_async(vma)) {
3858 				pte_unmap_unlock(vmf->pte, vmf->ptl);
3859 				return handle_userfault(vmf, VM_UFFD_WP);
3860 			}
3861 
3862 			/*
3863 			 * Nothing needed (cache flush, TLB invalidations,
3864 			 * etc.) because we're only removing the uffd-wp bit,
3865 			 * which is completely invisible to the user.
3866 			 */
3867 			pte = pte_clear_uffd_wp(ptep_get(vmf->pte));
3868 
3869 			set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3870 			/*
3871 			 * Update this to be prepared for following up CoW
3872 			 * handling
3873 			 */
3874 			vmf->orig_pte = pte;
3875 		}
3876 
3877 		/*
3878 		 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3879 		 * is flushed in this case before copying.
3880 		 */
3881 		if (unlikely(userfaultfd_wp(vmf->vma) &&
3882 			     mm_tlb_flush_pending(vmf->vma->vm_mm)))
3883 			flush_tlb_page(vmf->vma, vmf->address);
3884 	}
3885 
3886 	vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3887 
3888 	if (vmf->page)
3889 		folio = page_folio(vmf->page);
3890 
3891 	/*
3892 	 * Shared mapping: we are guaranteed to have VM_WRITE and
3893 	 * FAULT_FLAG_WRITE set at this point.
3894 	 */
3895 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
3896 		/*
3897 		 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3898 		 * VM_PFNMAP VMA. FS DAX also wants ops->pfn_mkwrite called.
3899 		 *
3900 		 * We should not cow pages in a shared writeable mapping.
3901 		 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3902 		 */
3903 		if (!vmf->page || is_fsdax_page(vmf->page)) {
3904 			vmf->page = NULL;
3905 			return wp_pfn_shared(vmf);
3906 		}
3907 		return wp_page_shared(vmf, folio);
3908 	}
3909 
3910 	/*
3911 	 * Private mapping: create an exclusive anonymous page copy if reuse
3912 	 * is impossible. We might miss VM_WRITE for FOLL_FORCE handling.
3913 	 *
3914 	 * If we encounter a page that is marked exclusive, we must reuse
3915 	 * the page without further checks.
3916 	 */
3917 	if (folio && folio_test_anon(folio) &&
3918 	    (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) {
3919 		if (!PageAnonExclusive(vmf->page))
3920 			SetPageAnonExclusive(vmf->page);
3921 		if (unlikely(unshare)) {
3922 			pte_unmap_unlock(vmf->pte, vmf->ptl);
3923 			return 0;
3924 		}
3925 		wp_page_reuse(vmf, folio);
3926 		return 0;
3927 	}
3928 	/*
3929 	 * Ok, we need to copy. Oh, well..
3930 	 */
3931 	if (folio)
3932 		folio_get(folio);
3933 
3934 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3935 #ifdef CONFIG_KSM
3936 	if (folio && folio_test_ksm(folio))
3937 		count_vm_event(COW_KSM);
3938 #endif
3939 	return wp_page_copy(vmf);
3940 }
3941 
3942 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3943 		unsigned long start_addr, unsigned long end_addr,
3944 		struct zap_details *details)
3945 {
3946 	zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3947 }
3948 
3949 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3950 					    pgoff_t first_index,
3951 					    pgoff_t last_index,
3952 					    struct zap_details *details)
3953 {
3954 	struct vm_area_struct *vma;
3955 	pgoff_t vba, vea, zba, zea;
3956 
3957 	vma_interval_tree_foreach(vma, root, first_index, last_index) {
3958 		vba = vma->vm_pgoff;
3959 		vea = vba + vma_pages(vma) - 1;
3960 		zba = max(first_index, vba);
3961 		zea = min(last_index, vea);
3962 
3963 		unmap_mapping_range_vma(vma,
3964 			((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3965 			((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3966 				details);
3967 	}
3968 }
3969 
3970 /**
3971  * unmap_mapping_folio() - Unmap single folio from processes.
3972  * @folio: The locked folio to be unmapped.
3973  *
3974  * Unmap this folio from any userspace process which still has it mmaped.
3975  * Typically, for efficiency, the range of nearby pages has already been
3976  * unmapped by unmap_mapping_pages() or unmap_mapping_range().  But once
3977  * truncation or invalidation holds the lock on a folio, it may find that
3978  * the page has been remapped again: and then uses unmap_mapping_folio()
3979  * to unmap it finally.
3980  */
3981 void unmap_mapping_folio(struct folio *folio)
3982 {
3983 	struct address_space *mapping = folio->mapping;
3984 	struct zap_details details = { };
3985 	pgoff_t	first_index;
3986 	pgoff_t	last_index;
3987 
3988 	VM_BUG_ON(!folio_test_locked(folio));
3989 
3990 	first_index = folio->index;
3991 	last_index = folio_next_index(folio) - 1;
3992 
3993 	details.even_cows = false;
3994 	details.single_folio = folio;
3995 	details.zap_flags = ZAP_FLAG_DROP_MARKER;
3996 
3997 	i_mmap_lock_read(mapping);
3998 	if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3999 		unmap_mapping_range_tree(&mapping->i_mmap, first_index,
4000 					 last_index, &details);
4001 	i_mmap_unlock_read(mapping);
4002 }
4003 
4004 /**
4005  * unmap_mapping_pages() - Unmap pages from processes.
4006  * @mapping: The address space containing pages to be unmapped.
4007  * @start: Index of first page to be unmapped.
4008  * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
4009  * @even_cows: Whether to unmap even private COWed pages.
4010  *
4011  * Unmap the pages in this address space from any userspace process which
4012  * has them mmaped.  Generally, you want to remove COWed pages as well when
4013  * a file is being truncated, but not when invalidating pages from the page
4014  * cache.
4015  */
4016 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
4017 		pgoff_t nr, bool even_cows)
4018 {
4019 	struct zap_details details = { };
4020 	pgoff_t	first_index = start;
4021 	pgoff_t	last_index = start + nr - 1;
4022 
4023 	details.even_cows = even_cows;
4024 	if (last_index < first_index)
4025 		last_index = ULONG_MAX;
4026 
4027 	i_mmap_lock_read(mapping);
4028 	if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
4029 		unmap_mapping_range_tree(&mapping->i_mmap, first_index,
4030 					 last_index, &details);
4031 	i_mmap_unlock_read(mapping);
4032 }
4033 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
4034 
4035 /**
4036  * unmap_mapping_range - unmap the portion of all mmaps in the specified
4037  * address_space corresponding to the specified byte range in the underlying
4038  * file.
4039  *
4040  * @mapping: the address space containing mmaps to be unmapped.
4041  * @holebegin: byte in first page to unmap, relative to the start of
4042  * the underlying file.  This will be rounded down to a PAGE_SIZE
4043  * boundary.  Note that this is different from truncate_pagecache(), which
4044  * must keep the partial page.  In contrast, we must get rid of
4045  * partial pages.
4046  * @holelen: size of prospective hole in bytes.  This will be rounded
4047  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
4048  * end of the file.
4049  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
4050  * but 0 when invalidating pagecache, don't throw away private data.
4051  */
4052 void unmap_mapping_range(struct address_space *mapping,
4053 		loff_t const holebegin, loff_t const holelen, int even_cows)
4054 {
4055 	pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT;
4056 	pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT;
4057 
4058 	/* Check for overflow. */
4059 	if (sizeof(holelen) > sizeof(hlen)) {
4060 		long long holeend =
4061 			(holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
4062 		if (holeend & ~(long long)ULONG_MAX)
4063 			hlen = ULONG_MAX - hba + 1;
4064 	}
4065 
4066 	unmap_mapping_pages(mapping, hba, hlen, even_cows);
4067 }
4068 EXPORT_SYMBOL(unmap_mapping_range);
4069 
4070 /*
4071  * Restore a potential device exclusive pte to a working pte entry
4072  */
4073 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
4074 {
4075 	struct folio *folio = page_folio(vmf->page);
4076 	struct vm_area_struct *vma = vmf->vma;
4077 	struct mmu_notifier_range range;
4078 	vm_fault_t ret;
4079 
4080 	/*
4081 	 * We need a reference to lock the folio because we don't hold
4082 	 * the PTL so a racing thread can remove the device-exclusive
4083 	 * entry and unmap it. If the folio is free the entry must
4084 	 * have been removed already. If it happens to have already
4085 	 * been re-allocated after being freed all we do is lock and
4086 	 * unlock it.
4087 	 */
4088 	if (!folio_try_get(folio))
4089 		return 0;
4090 
4091 	ret = folio_lock_or_retry(folio, vmf);
4092 	if (ret) {
4093 		folio_put(folio);
4094 		return ret;
4095 	}
4096 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_CLEAR, 0,
4097 				vma->vm_mm, vmf->address & PAGE_MASK,
4098 				(vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
4099 	mmu_notifier_invalidate_range_start(&range);
4100 
4101 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4102 				&vmf->ptl);
4103 	if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4104 		restore_exclusive_pte(vma, folio, vmf->page, vmf->address,
4105 				      vmf->pte, vmf->orig_pte);
4106 
4107 	if (vmf->pte)
4108 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4109 	folio_unlock(folio);
4110 	folio_put(folio);
4111 
4112 	mmu_notifier_invalidate_range_end(&range);
4113 	return 0;
4114 }
4115 
4116 static inline bool should_try_to_free_swap(struct folio *folio,
4117 					   struct vm_area_struct *vma,
4118 					   unsigned int fault_flags)
4119 {
4120 	if (!folio_test_swapcache(folio))
4121 		return false;
4122 	if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
4123 	    folio_test_mlocked(folio))
4124 		return true;
4125 	/*
4126 	 * If we want to map a page that's in the swapcache writable, we
4127 	 * have to detect via the refcount if we're really the exclusive
4128 	 * user. Try freeing the swapcache to get rid of the swapcache
4129 	 * reference only in case it's likely that we'll be the exlusive user.
4130 	 */
4131 	return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) &&
4132 		folio_ref_count(folio) == (1 + folio_nr_pages(folio));
4133 }
4134 
4135 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
4136 {
4137 	vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4138 				       vmf->address, &vmf->ptl);
4139 	if (!vmf->pte)
4140 		return 0;
4141 	/*
4142 	 * Be careful so that we will only recover a special uffd-wp pte into a
4143 	 * none pte.  Otherwise it means the pte could have changed, so retry.
4144 	 *
4145 	 * This should also cover the case where e.g. the pte changed
4146 	 * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED.
4147 	 * So is_pte_marker() check is not enough to safely drop the pte.
4148 	 */
4149 	if (pte_same(vmf->orig_pte, ptep_get(vmf->pte)))
4150 		pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
4151 	pte_unmap_unlock(vmf->pte, vmf->ptl);
4152 	return 0;
4153 }
4154 
4155 static vm_fault_t do_pte_missing(struct vm_fault *vmf)
4156 {
4157 	if (vma_is_anonymous(vmf->vma))
4158 		return do_anonymous_page(vmf);
4159 	else
4160 		return do_fault(vmf);
4161 }
4162 
4163 /*
4164  * This is actually a page-missing access, but with uffd-wp special pte
4165  * installed.  It means this pte was wr-protected before being unmapped.
4166  */
4167 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
4168 {
4169 	/*
4170 	 * Just in case there're leftover special ptes even after the region
4171 	 * got unregistered - we can simply clear them.
4172 	 */
4173 	if (unlikely(!userfaultfd_wp(vmf->vma)))
4174 		return pte_marker_clear(vmf);
4175 
4176 	return do_pte_missing(vmf);
4177 }
4178 
4179 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
4180 {
4181 	swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
4182 	unsigned long marker = pte_marker_get(entry);
4183 
4184 	/*
4185 	 * PTE markers should never be empty.  If anything weird happened,
4186 	 * the best thing to do is to kill the process along with its mm.
4187 	 */
4188 	if (WARN_ON_ONCE(!marker))
4189 		return VM_FAULT_SIGBUS;
4190 
4191 	/* Higher priority than uffd-wp when data corrupted */
4192 	if (marker & PTE_MARKER_POISONED)
4193 		return VM_FAULT_HWPOISON;
4194 
4195 	/* Hitting a guard page is always a fatal condition. */
4196 	if (marker & PTE_MARKER_GUARD)
4197 		return VM_FAULT_SIGSEGV;
4198 
4199 	if (pte_marker_entry_uffd_wp(entry))
4200 		return pte_marker_handle_uffd_wp(vmf);
4201 
4202 	/* This is an unknown pte marker */
4203 	return VM_FAULT_SIGBUS;
4204 }
4205 
4206 static struct folio *__alloc_swap_folio(struct vm_fault *vmf)
4207 {
4208 	struct vm_area_struct *vma = vmf->vma;
4209 	struct folio *folio;
4210 	swp_entry_t entry;
4211 
4212 	folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, vmf->address);
4213 	if (!folio)
4214 		return NULL;
4215 
4216 	entry = pte_to_swp_entry(vmf->orig_pte);
4217 	if (mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
4218 					   GFP_KERNEL, entry)) {
4219 		folio_put(folio);
4220 		return NULL;
4221 	}
4222 
4223 	return folio;
4224 }
4225 
4226 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4227 static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
4228 {
4229 	struct swap_info_struct *si = swp_swap_info(entry);
4230 	pgoff_t offset = swp_offset(entry);
4231 	int i;
4232 
4233 	/*
4234 	 * While allocating a large folio and doing swap_read_folio, which is
4235 	 * the case the being faulted pte doesn't have swapcache. We need to
4236 	 * ensure all PTEs have no cache as well, otherwise, we might go to
4237 	 * swap devices while the content is in swapcache.
4238 	 */
4239 	for (i = 0; i < max_nr; i++) {
4240 		if ((si->swap_map[offset + i] & SWAP_HAS_CACHE))
4241 			return i;
4242 	}
4243 
4244 	return i;
4245 }
4246 
4247 /*
4248  * Check if the PTEs within a range are contiguous swap entries
4249  * and have consistent swapcache, zeromap.
4250  */
4251 static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)
4252 {
4253 	unsigned long addr;
4254 	swp_entry_t entry;
4255 	int idx;
4256 	pte_t pte;
4257 
4258 	addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
4259 	idx = (vmf->address - addr) / PAGE_SIZE;
4260 	pte = ptep_get(ptep);
4261 
4262 	if (!pte_same(pte, pte_move_swp_offset(vmf->orig_pte, -idx)))
4263 		return false;
4264 	entry = pte_to_swp_entry(pte);
4265 	if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages)
4266 		return false;
4267 
4268 	/*
4269 	 * swap_read_folio() can't handle the case a large folio is hybridly
4270 	 * from different backends. And they are likely corner cases. Similar
4271 	 * things might be added once zswap support large folios.
4272 	 */
4273 	if (unlikely(swap_zeromap_batch(entry, nr_pages, NULL) != nr_pages))
4274 		return false;
4275 	if (unlikely(non_swapcache_batch(entry, nr_pages) != nr_pages))
4276 		return false;
4277 
4278 	return true;
4279 }
4280 
4281 static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,
4282 						     unsigned long addr,
4283 						     unsigned long orders)
4284 {
4285 	int order, nr;
4286 
4287 	order = highest_order(orders);
4288 
4289 	/*
4290 	 * To swap in a THP with nr pages, we require that its first swap_offset
4291 	 * is aligned with that number, as it was when the THP was swapped out.
4292 	 * This helps filter out most invalid entries.
4293 	 */
4294 	while (orders) {
4295 		nr = 1 << order;
4296 		if ((addr >> PAGE_SHIFT) % nr == swp_offset % nr)
4297 			break;
4298 		order = next_order(&orders, order);
4299 	}
4300 
4301 	return orders;
4302 }
4303 
4304 static struct folio *alloc_swap_folio(struct vm_fault *vmf)
4305 {
4306 	struct vm_area_struct *vma = vmf->vma;
4307 	unsigned long orders;
4308 	struct folio *folio;
4309 	unsigned long addr;
4310 	swp_entry_t entry;
4311 	spinlock_t *ptl;
4312 	pte_t *pte;
4313 	gfp_t gfp;
4314 	int order;
4315 
4316 	/*
4317 	 * If uffd is active for the vma we need per-page fault fidelity to
4318 	 * maintain the uffd semantics.
4319 	 */
4320 	if (unlikely(userfaultfd_armed(vma)))
4321 		goto fallback;
4322 
4323 	/*
4324 	 * A large swapped out folio could be partially or fully in zswap. We
4325 	 * lack handling for such cases, so fallback to swapping in order-0
4326 	 * folio.
4327 	 */
4328 	if (!zswap_never_enabled())
4329 		goto fallback;
4330 
4331 	entry = pte_to_swp_entry(vmf->orig_pte);
4332 	/*
4333 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
4334 	 * and suitable for swapping THP.
4335 	 */
4336 	orders = thp_vma_allowable_orders(vma, vma->vm_flags,
4337 			TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
4338 	orders = thp_vma_suitable_orders(vma, vmf->address, orders);
4339 	orders = thp_swap_suitable_orders(swp_offset(entry),
4340 					  vmf->address, orders);
4341 
4342 	if (!orders)
4343 		goto fallback;
4344 
4345 	pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4346 				  vmf->address & PMD_MASK, &ptl);
4347 	if (unlikely(!pte))
4348 		goto fallback;
4349 
4350 	/*
4351 	 * For do_swap_page, find the highest order where the aligned range is
4352 	 * completely swap entries with contiguous swap offsets.
4353 	 */
4354 	order = highest_order(orders);
4355 	while (orders) {
4356 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4357 		if (can_swapin_thp(vmf, pte + pte_index(addr), 1 << order))
4358 			break;
4359 		order = next_order(&orders, order);
4360 	}
4361 
4362 	pte_unmap_unlock(pte, ptl);
4363 
4364 	/* Try allocating the highest of the remaining orders. */
4365 	gfp = vma_thp_gfp_mask(vma);
4366 	while (orders) {
4367 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4368 		folio = vma_alloc_folio(gfp, order, vma, addr);
4369 		if (folio) {
4370 			if (!mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
4371 							    gfp, entry))
4372 				return folio;
4373 			count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK_CHARGE);
4374 			folio_put(folio);
4375 		}
4376 		count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK);
4377 		order = next_order(&orders, order);
4378 	}
4379 
4380 fallback:
4381 	return __alloc_swap_folio(vmf);
4382 }
4383 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
4384 static struct folio *alloc_swap_folio(struct vm_fault *vmf)
4385 {
4386 	return __alloc_swap_folio(vmf);
4387 }
4388 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4389 
4390 static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);
4391 
4392 /*
4393  * We enter with non-exclusive mmap_lock (to exclude vma changes,
4394  * but allow concurrent faults), and pte mapped but not yet locked.
4395  * We return with pte unmapped and unlocked.
4396  *
4397  * We return with the mmap_lock locked or unlocked in the same cases
4398  * as does filemap_fault().
4399  */
4400 vm_fault_t do_swap_page(struct vm_fault *vmf)
4401 {
4402 	struct vm_area_struct *vma = vmf->vma;
4403 	struct folio *swapcache, *folio = NULL;
4404 	DECLARE_WAITQUEUE(wait, current);
4405 	struct page *page;
4406 	struct swap_info_struct *si = NULL;
4407 	rmap_t rmap_flags = RMAP_NONE;
4408 	bool need_clear_cache = false;
4409 	bool exclusive = false;
4410 	swp_entry_t entry;
4411 	pte_t pte;
4412 	vm_fault_t ret = 0;
4413 	void *shadow = NULL;
4414 	int nr_pages;
4415 	unsigned long page_idx;
4416 	unsigned long address;
4417 	pte_t *ptep;
4418 
4419 	if (!pte_unmap_same(vmf))
4420 		goto out;
4421 
4422 	entry = pte_to_swp_entry(vmf->orig_pte);
4423 	if (unlikely(non_swap_entry(entry))) {
4424 		if (is_migration_entry(entry)) {
4425 			migration_entry_wait(vma->vm_mm, vmf->pmd,
4426 					     vmf->address);
4427 		} else if (is_device_exclusive_entry(entry)) {
4428 			vmf->page = pfn_swap_entry_to_page(entry);
4429 			ret = remove_device_exclusive_entry(vmf);
4430 		} else if (is_device_private_entry(entry)) {
4431 			if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
4432 				/*
4433 				 * migrate_to_ram is not yet ready to operate
4434 				 * under VMA lock.
4435 				 */
4436 				vma_end_read(vma);
4437 				ret = VM_FAULT_RETRY;
4438 				goto out;
4439 			}
4440 
4441 			vmf->page = pfn_swap_entry_to_page(entry);
4442 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4443 					vmf->address, &vmf->ptl);
4444 			if (unlikely(!vmf->pte ||
4445 				     !pte_same(ptep_get(vmf->pte),
4446 							vmf->orig_pte)))
4447 				goto unlock;
4448 
4449 			/*
4450 			 * Get a page reference while we know the page can't be
4451 			 * freed.
4452 			 */
4453 			if (trylock_page(vmf->page)) {
4454 				struct dev_pagemap *pgmap;
4455 
4456 				get_page(vmf->page);
4457 				pte_unmap_unlock(vmf->pte, vmf->ptl);
4458 				pgmap = page_pgmap(vmf->page);
4459 				ret = pgmap->ops->migrate_to_ram(vmf);
4460 				unlock_page(vmf->page);
4461 				put_page(vmf->page);
4462 			} else {
4463 				pte_unmap_unlock(vmf->pte, vmf->ptl);
4464 			}
4465 		} else if (is_hwpoison_entry(entry)) {
4466 			ret = VM_FAULT_HWPOISON;
4467 		} else if (is_pte_marker_entry(entry)) {
4468 			ret = handle_pte_marker(vmf);
4469 		} else {
4470 			print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
4471 			ret = VM_FAULT_SIGBUS;
4472 		}
4473 		goto out;
4474 	}
4475 
4476 	/* Prevent swapoff from happening to us. */
4477 	si = get_swap_device(entry);
4478 	if (unlikely(!si))
4479 		goto out;
4480 
4481 	folio = swap_cache_get_folio(entry, vma, vmf->address);
4482 	if (folio)
4483 		page = folio_file_page(folio, swp_offset(entry));
4484 	swapcache = folio;
4485 
4486 	if (!folio) {
4487 		if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
4488 		    __swap_count(entry) == 1) {
4489 			/* skip swapcache */
4490 			folio = alloc_swap_folio(vmf);
4491 			if (folio) {
4492 				__folio_set_locked(folio);
4493 				__folio_set_swapbacked(folio);
4494 
4495 				nr_pages = folio_nr_pages(folio);
4496 				if (folio_test_large(folio))
4497 					entry.val = ALIGN_DOWN(entry.val, nr_pages);
4498 				/*
4499 				 * Prevent parallel swapin from proceeding with
4500 				 * the cache flag. Otherwise, another thread
4501 				 * may finish swapin first, free the entry, and
4502 				 * swapout reusing the same entry. It's
4503 				 * undetectable as pte_same() returns true due
4504 				 * to entry reuse.
4505 				 */
4506 				if (swapcache_prepare(entry, nr_pages)) {
4507 					/*
4508 					 * Relax a bit to prevent rapid
4509 					 * repeated page faults.
4510 					 */
4511 					add_wait_queue(&swapcache_wq, &wait);
4512 					schedule_timeout_uninterruptible(1);
4513 					remove_wait_queue(&swapcache_wq, &wait);
4514 					goto out_page;
4515 				}
4516 				need_clear_cache = true;
4517 
4518 				memcg1_swapin(entry, nr_pages);
4519 
4520 				shadow = get_shadow_from_swap_cache(entry);
4521 				if (shadow)
4522 					workingset_refault(folio, shadow);
4523 
4524 				folio_add_lru(folio);
4525 
4526 				/* To provide entry to swap_read_folio() */
4527 				folio->swap = entry;
4528 				swap_read_folio(folio, NULL);
4529 				folio->private = NULL;
4530 			}
4531 		} else {
4532 			folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
4533 						vmf);
4534 			swapcache = folio;
4535 		}
4536 
4537 		if (!folio) {
4538 			/*
4539 			 * Back out if somebody else faulted in this pte
4540 			 * while we released the pte lock.
4541 			 */
4542 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4543 					vmf->address, &vmf->ptl);
4544 			if (likely(vmf->pte &&
4545 				   pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4546 				ret = VM_FAULT_OOM;
4547 			goto unlock;
4548 		}
4549 
4550 		/* Had to read the page from swap area: Major fault */
4551 		ret = VM_FAULT_MAJOR;
4552 		count_vm_event(PGMAJFAULT);
4553 		count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
4554 		page = folio_file_page(folio, swp_offset(entry));
4555 	} else if (PageHWPoison(page)) {
4556 		/*
4557 		 * hwpoisoned dirty swapcache pages are kept for killing
4558 		 * owner processes (which may be unknown at hwpoison time)
4559 		 */
4560 		ret = VM_FAULT_HWPOISON;
4561 		goto out_release;
4562 	}
4563 
4564 	ret |= folio_lock_or_retry(folio, vmf);
4565 	if (ret & VM_FAULT_RETRY)
4566 		goto out_release;
4567 
4568 	if (swapcache) {
4569 		/*
4570 		 * Make sure folio_free_swap() or swapoff did not release the
4571 		 * swapcache from under us.  The page pin, and pte_same test
4572 		 * below, are not enough to exclude that.  Even if it is still
4573 		 * swapcache, we need to check that the page's swap has not
4574 		 * changed.
4575 		 */
4576 		if (unlikely(!folio_test_swapcache(folio) ||
4577 			     page_swap_entry(page).val != entry.val))
4578 			goto out_page;
4579 
4580 		/*
4581 		 * KSM sometimes has to copy on read faults, for example, if
4582 		 * page->index of !PageKSM() pages would be nonlinear inside the
4583 		 * anon VMA -- PageKSM() is lost on actual swapout.
4584 		 */
4585 		folio = ksm_might_need_to_copy(folio, vma, vmf->address);
4586 		if (unlikely(!folio)) {
4587 			ret = VM_FAULT_OOM;
4588 			folio = swapcache;
4589 			goto out_page;
4590 		} else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
4591 			ret = VM_FAULT_HWPOISON;
4592 			folio = swapcache;
4593 			goto out_page;
4594 		}
4595 		if (folio != swapcache)
4596 			page = folio_page(folio, 0);
4597 
4598 		/*
4599 		 * If we want to map a page that's in the swapcache writable, we
4600 		 * have to detect via the refcount if we're really the exclusive
4601 		 * owner. Try removing the extra reference from the local LRU
4602 		 * caches if required.
4603 		 */
4604 		if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache &&
4605 		    !folio_test_ksm(folio) && !folio_test_lru(folio))
4606 			lru_add_drain();
4607 	}
4608 
4609 	folio_throttle_swaprate(folio, GFP_KERNEL);
4610 
4611 	/*
4612 	 * Back out if somebody else already faulted in this pte.
4613 	 */
4614 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4615 			&vmf->ptl);
4616 	if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4617 		goto out_nomap;
4618 
4619 	if (unlikely(!folio_test_uptodate(folio))) {
4620 		ret = VM_FAULT_SIGBUS;
4621 		goto out_nomap;
4622 	}
4623 
4624 	/* allocated large folios for SWP_SYNCHRONOUS_IO */
4625 	if (folio_test_large(folio) && !folio_test_swapcache(folio)) {
4626 		unsigned long nr = folio_nr_pages(folio);
4627 		unsigned long folio_start = ALIGN_DOWN(vmf->address, nr * PAGE_SIZE);
4628 		unsigned long idx = (vmf->address - folio_start) / PAGE_SIZE;
4629 		pte_t *folio_ptep = vmf->pte - idx;
4630 		pte_t folio_pte = ptep_get(folio_ptep);
4631 
4632 		if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
4633 		    swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
4634 			goto out_nomap;
4635 
4636 		page_idx = idx;
4637 		address = folio_start;
4638 		ptep = folio_ptep;
4639 		goto check_folio;
4640 	}
4641 
4642 	nr_pages = 1;
4643 	page_idx = 0;
4644 	address = vmf->address;
4645 	ptep = vmf->pte;
4646 	if (folio_test_large(folio) && folio_test_swapcache(folio)) {
4647 		int nr = folio_nr_pages(folio);
4648 		unsigned long idx = folio_page_idx(folio, page);
4649 		unsigned long folio_start = address - idx * PAGE_SIZE;
4650 		unsigned long folio_end = folio_start + nr * PAGE_SIZE;
4651 		pte_t *folio_ptep;
4652 		pte_t folio_pte;
4653 
4654 		if (unlikely(folio_start < max(address & PMD_MASK, vma->vm_start)))
4655 			goto check_folio;
4656 		if (unlikely(folio_end > pmd_addr_end(address, vma->vm_end)))
4657 			goto check_folio;
4658 
4659 		folio_ptep = vmf->pte - idx;
4660 		folio_pte = ptep_get(folio_ptep);
4661 		if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
4662 		    swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
4663 			goto check_folio;
4664 
4665 		page_idx = idx;
4666 		address = folio_start;
4667 		ptep = folio_ptep;
4668 		nr_pages = nr;
4669 		entry = folio->swap;
4670 		page = &folio->page;
4671 	}
4672 
4673 check_folio:
4674 	/*
4675 	 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
4676 	 * must never point at an anonymous page in the swapcache that is
4677 	 * PG_anon_exclusive. Sanity check that this holds and especially, that
4678 	 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
4679 	 * check after taking the PT lock and making sure that nobody
4680 	 * concurrently faulted in this page and set PG_anon_exclusive.
4681 	 */
4682 	BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
4683 	BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
4684 
4685 	/*
4686 	 * Check under PT lock (to protect against concurrent fork() sharing
4687 	 * the swap entry concurrently) for certainly exclusive pages.
4688 	 */
4689 	if (!folio_test_ksm(folio)) {
4690 		exclusive = pte_swp_exclusive(vmf->orig_pte);
4691 		if (folio != swapcache) {
4692 			/*
4693 			 * We have a fresh page that is not exposed to the
4694 			 * swapcache -> certainly exclusive.
4695 			 */
4696 			exclusive = true;
4697 		} else if (exclusive && folio_test_writeback(folio) &&
4698 			  data_race(si->flags & SWP_STABLE_WRITES)) {
4699 			/*
4700 			 * This is tricky: not all swap backends support
4701 			 * concurrent page modifications while under writeback.
4702 			 *
4703 			 * So if we stumble over such a page in the swapcache
4704 			 * we must not set the page exclusive, otherwise we can
4705 			 * map it writable without further checks and modify it
4706 			 * while still under writeback.
4707 			 *
4708 			 * For these problematic swap backends, simply drop the
4709 			 * exclusive marker: this is perfectly fine as we start
4710 			 * writeback only if we fully unmapped the page and
4711 			 * there are no unexpected references on the page after
4712 			 * unmapping succeeded. After fully unmapped, no
4713 			 * further GUP references (FOLL_GET and FOLL_PIN) can
4714 			 * appear, so dropping the exclusive marker and mapping
4715 			 * it only R/O is fine.
4716 			 */
4717 			exclusive = false;
4718 		}
4719 	}
4720 
4721 	/*
4722 	 * Some architectures may have to restore extra metadata to the page
4723 	 * when reading from swap. This metadata may be indexed by swap entry
4724 	 * so this must be called before swap_free().
4725 	 */
4726 	arch_swap_restore(folio_swap(entry, folio), folio);
4727 
4728 	/*
4729 	 * Remove the swap entry and conditionally try to free up the swapcache.
4730 	 * We're already holding a reference on the page but haven't mapped it
4731 	 * yet.
4732 	 */
4733 	swap_free_nr(entry, nr_pages);
4734 	if (should_try_to_free_swap(folio, vma, vmf->flags))
4735 		folio_free_swap(folio);
4736 
4737 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
4738 	add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages);
4739 	pte = mk_pte(page, vma->vm_page_prot);
4740 	if (pte_swp_soft_dirty(vmf->orig_pte))
4741 		pte = pte_mksoft_dirty(pte);
4742 	if (pte_swp_uffd_wp(vmf->orig_pte))
4743 		pte = pte_mkuffd_wp(pte);
4744 
4745 	/*
4746 	 * Same logic as in do_wp_page(); however, optimize for pages that are
4747 	 * certainly not shared either because we just allocated them without
4748 	 * exposing them to the swapcache or because the swap entry indicates
4749 	 * exclusivity.
4750 	 */
4751 	if (!folio_test_ksm(folio) &&
4752 	    (exclusive || folio_ref_count(folio) == 1)) {
4753 		if ((vma->vm_flags & VM_WRITE) && !userfaultfd_pte_wp(vma, pte) &&
4754 		    !pte_needs_soft_dirty_wp(vma, pte)) {
4755 			pte = pte_mkwrite(pte, vma);
4756 			if (vmf->flags & FAULT_FLAG_WRITE) {
4757 				pte = pte_mkdirty(pte);
4758 				vmf->flags &= ~FAULT_FLAG_WRITE;
4759 			}
4760 		}
4761 		rmap_flags |= RMAP_EXCLUSIVE;
4762 	}
4763 	folio_ref_add(folio, nr_pages - 1);
4764 	flush_icache_pages(vma, page, nr_pages);
4765 	vmf->orig_pte = pte_advance_pfn(pte, page_idx);
4766 
4767 	/* ksm created a completely new copy */
4768 	if (unlikely(folio != swapcache && swapcache)) {
4769 		folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
4770 		folio_add_lru_vma(folio, vma);
4771 	} else if (!folio_test_anon(folio)) {
4772 		/*
4773 		 * We currently only expect small !anon folios which are either
4774 		 * fully exclusive or fully shared, or new allocated large
4775 		 * folios which are fully exclusive. If we ever get large
4776 		 * folios within swapcache here, we have to be careful.
4777 		 */
4778 		VM_WARN_ON_ONCE(folio_test_large(folio) && folio_test_swapcache(folio));
4779 		VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
4780 		folio_add_new_anon_rmap(folio, vma, address, rmap_flags);
4781 	} else {
4782 		folio_add_anon_rmap_ptes(folio, page, nr_pages, vma, address,
4783 					rmap_flags);
4784 	}
4785 
4786 	VM_BUG_ON(!folio_test_anon(folio) ||
4787 			(pte_write(pte) && !PageAnonExclusive(page)));
4788 	set_ptes(vma->vm_mm, address, ptep, pte, nr_pages);
4789 	arch_do_swap_page_nr(vma->vm_mm, vma, address,
4790 			pte, pte, nr_pages);
4791 
4792 	folio_unlock(folio);
4793 	if (folio != swapcache && swapcache) {
4794 		/*
4795 		 * Hold the lock to avoid the swap entry to be reused
4796 		 * until we take the PT lock for the pte_same() check
4797 		 * (to avoid false positives from pte_same). For
4798 		 * further safety release the lock after the swap_free
4799 		 * so that the swap count won't change under a
4800 		 * parallel locked swapcache.
4801 		 */
4802 		folio_unlock(swapcache);
4803 		folio_put(swapcache);
4804 	}
4805 
4806 	if (vmf->flags & FAULT_FLAG_WRITE) {
4807 		ret |= do_wp_page(vmf);
4808 		if (ret & VM_FAULT_ERROR)
4809 			ret &= VM_FAULT_ERROR;
4810 		goto out;
4811 	}
4812 
4813 	/* No need to invalidate - it was non-present before */
4814 	update_mmu_cache_range(vmf, vma, address, ptep, nr_pages);
4815 unlock:
4816 	if (vmf->pte)
4817 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4818 out:
4819 	/* Clear the swap cache pin for direct swapin after PTL unlock */
4820 	if (need_clear_cache) {
4821 		swapcache_clear(si, entry, nr_pages);
4822 		if (waitqueue_active(&swapcache_wq))
4823 			wake_up(&swapcache_wq);
4824 	}
4825 	if (si)
4826 		put_swap_device(si);
4827 	return ret;
4828 out_nomap:
4829 	if (vmf->pte)
4830 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4831 out_page:
4832 	folio_unlock(folio);
4833 out_release:
4834 	folio_put(folio);
4835 	if (folio != swapcache && swapcache) {
4836 		folio_unlock(swapcache);
4837 		folio_put(swapcache);
4838 	}
4839 	if (need_clear_cache) {
4840 		swapcache_clear(si, entry, nr_pages);
4841 		if (waitqueue_active(&swapcache_wq))
4842 			wake_up(&swapcache_wq);
4843 	}
4844 	if (si)
4845 		put_swap_device(si);
4846 	return ret;
4847 }
4848 
4849 static bool pte_range_none(pte_t *pte, int nr_pages)
4850 {
4851 	int i;
4852 
4853 	for (i = 0; i < nr_pages; i++) {
4854 		if (!pte_none(ptep_get_lockless(pte + i)))
4855 			return false;
4856 	}
4857 
4858 	return true;
4859 }
4860 
4861 static struct folio *alloc_anon_folio(struct vm_fault *vmf)
4862 {
4863 	struct vm_area_struct *vma = vmf->vma;
4864 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4865 	unsigned long orders;
4866 	struct folio *folio;
4867 	unsigned long addr;
4868 	pte_t *pte;
4869 	gfp_t gfp;
4870 	int order;
4871 
4872 	/*
4873 	 * If uffd is active for the vma we need per-page fault fidelity to
4874 	 * maintain the uffd semantics.
4875 	 */
4876 	if (unlikely(userfaultfd_armed(vma)))
4877 		goto fallback;
4878 
4879 	/*
4880 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
4881 	 * for this vma. Then filter out the orders that can't be allocated over
4882 	 * the faulting address and still be fully contained in the vma.
4883 	 */
4884 	orders = thp_vma_allowable_orders(vma, vma->vm_flags,
4885 			TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
4886 	orders = thp_vma_suitable_orders(vma, vmf->address, orders);
4887 
4888 	if (!orders)
4889 		goto fallback;
4890 
4891 	pte = pte_offset_map(vmf->pmd, vmf->address & PMD_MASK);
4892 	if (!pte)
4893 		return ERR_PTR(-EAGAIN);
4894 
4895 	/*
4896 	 * Find the highest order where the aligned range is completely
4897 	 * pte_none(). Note that all remaining orders will be completely
4898 	 * pte_none().
4899 	 */
4900 	order = highest_order(orders);
4901 	while (orders) {
4902 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4903 		if (pte_range_none(pte + pte_index(addr), 1 << order))
4904 			break;
4905 		order = next_order(&orders, order);
4906 	}
4907 
4908 	pte_unmap(pte);
4909 
4910 	if (!orders)
4911 		goto fallback;
4912 
4913 	/* Try allocating the highest of the remaining orders. */
4914 	gfp = vma_thp_gfp_mask(vma);
4915 	while (orders) {
4916 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4917 		folio = vma_alloc_folio(gfp, order, vma, addr);
4918 		if (folio) {
4919 			if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
4920 				count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
4921 				folio_put(folio);
4922 				goto next;
4923 			}
4924 			folio_throttle_swaprate(folio, gfp);
4925 			/*
4926 			 * When a folio is not zeroed during allocation
4927 			 * (__GFP_ZERO not used) or user folios require special
4928 			 * handling, folio_zero_user() is used to make sure
4929 			 * that the page corresponding to the faulting address
4930 			 * will be hot in the cache after zeroing.
4931 			 */
4932 			if (user_alloc_needs_zeroing())
4933 				folio_zero_user(folio, vmf->address);
4934 			return folio;
4935 		}
4936 next:
4937 		count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
4938 		order = next_order(&orders, order);
4939 	}
4940 
4941 fallback:
4942 #endif
4943 	return folio_prealloc(vma->vm_mm, vma, vmf->address, true);
4944 }
4945 
4946 /*
4947  * We enter with non-exclusive mmap_lock (to exclude vma changes,
4948  * but allow concurrent faults), and pte mapped but not yet locked.
4949  * We return with mmap_lock still held, but pte unmapped and unlocked.
4950  */
4951 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
4952 {
4953 	struct vm_area_struct *vma = vmf->vma;
4954 	unsigned long addr = vmf->address;
4955 	struct folio *folio;
4956 	vm_fault_t ret = 0;
4957 	int nr_pages = 1;
4958 	pte_t entry;
4959 
4960 	/* File mapping without ->vm_ops ? */
4961 	if (vma->vm_flags & VM_SHARED)
4962 		return VM_FAULT_SIGBUS;
4963 
4964 	/*
4965 	 * Use pte_alloc() instead of pte_alloc_map(), so that OOM can
4966 	 * be distinguished from a transient failure of pte_offset_map().
4967 	 */
4968 	if (pte_alloc(vma->vm_mm, vmf->pmd))
4969 		return VM_FAULT_OOM;
4970 
4971 	/* Use the zero-page for reads */
4972 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
4973 			!mm_forbids_zeropage(vma->vm_mm)) {
4974 		entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
4975 						vma->vm_page_prot));
4976 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4977 				vmf->address, &vmf->ptl);
4978 		if (!vmf->pte)
4979 			goto unlock;
4980 		if (vmf_pte_changed(vmf)) {
4981 			update_mmu_tlb(vma, vmf->address, vmf->pte);
4982 			goto unlock;
4983 		}
4984 		ret = check_stable_address_space(vma->vm_mm);
4985 		if (ret)
4986 			goto unlock;
4987 		/* Deliver the page fault to userland, check inside PT lock */
4988 		if (userfaultfd_missing(vma)) {
4989 			pte_unmap_unlock(vmf->pte, vmf->ptl);
4990 			return handle_userfault(vmf, VM_UFFD_MISSING);
4991 		}
4992 		goto setpte;
4993 	}
4994 
4995 	/* Allocate our own private page. */
4996 	ret = vmf_anon_prepare(vmf);
4997 	if (ret)
4998 		return ret;
4999 	/* Returns NULL on OOM or ERR_PTR(-EAGAIN) if we must retry the fault */
5000 	folio = alloc_anon_folio(vmf);
5001 	if (IS_ERR(folio))
5002 		return 0;
5003 	if (!folio)
5004 		goto oom;
5005 
5006 	nr_pages = folio_nr_pages(folio);
5007 	addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
5008 
5009 	/*
5010 	 * The memory barrier inside __folio_mark_uptodate makes sure that
5011 	 * preceding stores to the page contents become visible before
5012 	 * the set_pte_at() write.
5013 	 */
5014 	__folio_mark_uptodate(folio);
5015 
5016 	entry = folio_mk_pte(folio, vma->vm_page_prot);
5017 	entry = pte_sw_mkyoung(entry);
5018 	if (vma->vm_flags & VM_WRITE)
5019 		entry = pte_mkwrite(pte_mkdirty(entry), vma);
5020 
5021 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
5022 	if (!vmf->pte)
5023 		goto release;
5024 	if (nr_pages == 1 && vmf_pte_changed(vmf)) {
5025 		update_mmu_tlb(vma, addr, vmf->pte);
5026 		goto release;
5027 	} else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5028 		update_mmu_tlb_range(vma, addr, vmf->pte, nr_pages);
5029 		goto release;
5030 	}
5031 
5032 	ret = check_stable_address_space(vma->vm_mm);
5033 	if (ret)
5034 		goto release;
5035 
5036 	/* Deliver the page fault to userland, check inside PT lock */
5037 	if (userfaultfd_missing(vma)) {
5038 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5039 		folio_put(folio);
5040 		return handle_userfault(vmf, VM_UFFD_MISSING);
5041 	}
5042 
5043 	folio_ref_add(folio, nr_pages - 1);
5044 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
5045 	count_mthp_stat(folio_order(folio), MTHP_STAT_ANON_FAULT_ALLOC);
5046 	folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5047 	folio_add_lru_vma(folio, vma);
5048 setpte:
5049 	if (vmf_orig_pte_uffd_wp(vmf))
5050 		entry = pte_mkuffd_wp(entry);
5051 	set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr_pages);
5052 
5053 	/* No need to invalidate - it was non-present before */
5054 	update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr_pages);
5055 unlock:
5056 	if (vmf->pte)
5057 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5058 	return ret;
5059 release:
5060 	folio_put(folio);
5061 	goto unlock;
5062 oom:
5063 	return VM_FAULT_OOM;
5064 }
5065 
5066 /*
5067  * The mmap_lock must have been held on entry, and may have been
5068  * released depending on flags and vma->vm_ops->fault() return value.
5069  * See filemap_fault() and __lock_page_retry().
5070  */
5071 static vm_fault_t __do_fault(struct vm_fault *vmf)
5072 {
5073 	struct vm_area_struct *vma = vmf->vma;
5074 	struct folio *folio;
5075 	vm_fault_t ret;
5076 
5077 	/*
5078 	 * Preallocate pte before we take page_lock because this might lead to
5079 	 * deadlocks for memcg reclaim which waits for pages under writeback:
5080 	 *				lock_page(A)
5081 	 *				SetPageWriteback(A)
5082 	 *				unlock_page(A)
5083 	 * lock_page(B)
5084 	 *				lock_page(B)
5085 	 * pte_alloc_one
5086 	 *   shrink_folio_list
5087 	 *     wait_on_page_writeback(A)
5088 	 *				SetPageWriteback(B)
5089 	 *				unlock_page(B)
5090 	 *				# flush A, B to clear the writeback
5091 	 */
5092 	if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
5093 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5094 		if (!vmf->prealloc_pte)
5095 			return VM_FAULT_OOM;
5096 	}
5097 
5098 	ret = vma->vm_ops->fault(vmf);
5099 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
5100 			    VM_FAULT_DONE_COW)))
5101 		return ret;
5102 
5103 	folio = page_folio(vmf->page);
5104 	if (unlikely(PageHWPoison(vmf->page))) {
5105 		vm_fault_t poisonret = VM_FAULT_HWPOISON;
5106 		if (ret & VM_FAULT_LOCKED) {
5107 			if (page_mapped(vmf->page))
5108 				unmap_mapping_folio(folio);
5109 			/* Retry if a clean folio was removed from the cache. */
5110 			if (mapping_evict_folio(folio->mapping, folio))
5111 				poisonret = VM_FAULT_NOPAGE;
5112 			folio_unlock(folio);
5113 		}
5114 		folio_put(folio);
5115 		vmf->page = NULL;
5116 		return poisonret;
5117 	}
5118 
5119 	if (unlikely(!(ret & VM_FAULT_LOCKED)))
5120 		folio_lock(folio);
5121 	else
5122 		VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page);
5123 
5124 	return ret;
5125 }
5126 
5127 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5128 static void deposit_prealloc_pte(struct vm_fault *vmf)
5129 {
5130 	struct vm_area_struct *vma = vmf->vma;
5131 
5132 	pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
5133 	/*
5134 	 * We are going to consume the prealloc table,
5135 	 * count that as nr_ptes.
5136 	 */
5137 	mm_inc_nr_ptes(vma->vm_mm);
5138 	vmf->prealloc_pte = NULL;
5139 }
5140 
5141 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
5142 {
5143 	struct folio *folio = page_folio(page);
5144 	struct vm_area_struct *vma = vmf->vma;
5145 	bool write = vmf->flags & FAULT_FLAG_WRITE;
5146 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
5147 	pmd_t entry;
5148 	vm_fault_t ret = VM_FAULT_FALLBACK;
5149 
5150 	/*
5151 	 * It is too late to allocate a small folio, we already have a large
5152 	 * folio in the pagecache: especially s390 KVM cannot tolerate any
5153 	 * PMD mappings, but PTE-mapped THP are fine. So let's simply refuse any
5154 	 * PMD mappings if THPs are disabled.
5155 	 */
5156 	if (thp_disabled_by_hw() || vma_thp_disabled(vma, vma->vm_flags))
5157 		return ret;
5158 
5159 	if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
5160 		return ret;
5161 
5162 	if (folio_order(folio) != HPAGE_PMD_ORDER)
5163 		return ret;
5164 	page = &folio->page;
5165 
5166 	/*
5167 	 * Just backoff if any subpage of a THP is corrupted otherwise
5168 	 * the corrupted page may mapped by PMD silently to escape the
5169 	 * check.  This kind of THP just can be PTE mapped.  Access to
5170 	 * the corrupted subpage should trigger SIGBUS as expected.
5171 	 */
5172 	if (unlikely(folio_test_has_hwpoisoned(folio)))
5173 		return ret;
5174 
5175 	/*
5176 	 * Archs like ppc64 need additional space to store information
5177 	 * related to pte entry. Use the preallocated table for that.
5178 	 */
5179 	if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
5180 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5181 		if (!vmf->prealloc_pte)
5182 			return VM_FAULT_OOM;
5183 	}
5184 
5185 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
5186 	if (unlikely(!pmd_none(*vmf->pmd)))
5187 		goto out;
5188 
5189 	flush_icache_pages(vma, page, HPAGE_PMD_NR);
5190 
5191 	entry = folio_mk_pmd(folio, vma->vm_page_prot);
5192 	if (write)
5193 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
5194 
5195 	add_mm_counter(vma->vm_mm, mm_counter_file(folio), HPAGE_PMD_NR);
5196 	folio_add_file_rmap_pmd(folio, page, vma);
5197 
5198 	/*
5199 	 * deposit and withdraw with pmd lock held
5200 	 */
5201 	if (arch_needs_pgtable_deposit())
5202 		deposit_prealloc_pte(vmf);
5203 
5204 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
5205 
5206 	update_mmu_cache_pmd(vma, haddr, vmf->pmd);
5207 
5208 	/* fault is handled */
5209 	ret = 0;
5210 	count_vm_event(THP_FILE_MAPPED);
5211 out:
5212 	spin_unlock(vmf->ptl);
5213 	return ret;
5214 }
5215 #else
5216 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
5217 {
5218 	return VM_FAULT_FALLBACK;
5219 }
5220 #endif
5221 
5222 /**
5223  * set_pte_range - Set a range of PTEs to point to pages in a folio.
5224  * @vmf: Fault decription.
5225  * @folio: The folio that contains @page.
5226  * @page: The first page to create a PTE for.
5227  * @nr: The number of PTEs to create.
5228  * @addr: The first address to create a PTE for.
5229  */
5230 void set_pte_range(struct vm_fault *vmf, struct folio *folio,
5231 		struct page *page, unsigned int nr, unsigned long addr)
5232 {
5233 	struct vm_area_struct *vma = vmf->vma;
5234 	bool write = vmf->flags & FAULT_FLAG_WRITE;
5235 	bool prefault = !in_range(vmf->address, addr, nr * PAGE_SIZE);
5236 	pte_t entry;
5237 
5238 	flush_icache_pages(vma, page, nr);
5239 	entry = mk_pte(page, vma->vm_page_prot);
5240 
5241 	if (prefault && arch_wants_old_prefaulted_pte())
5242 		entry = pte_mkold(entry);
5243 	else
5244 		entry = pte_sw_mkyoung(entry);
5245 
5246 	if (write)
5247 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
5248 	else if (pte_write(entry) && folio_test_dirty(folio))
5249 		entry = pte_mkdirty(entry);
5250 	if (unlikely(vmf_orig_pte_uffd_wp(vmf)))
5251 		entry = pte_mkuffd_wp(entry);
5252 	/* copy-on-write page */
5253 	if (write && !(vma->vm_flags & VM_SHARED)) {
5254 		VM_BUG_ON_FOLIO(nr != 1, folio);
5255 		folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5256 		folio_add_lru_vma(folio, vma);
5257 	} else {
5258 		folio_add_file_rmap_ptes(folio, page, nr, vma);
5259 	}
5260 	set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr);
5261 
5262 	/* no need to invalidate: a not-present page won't be cached */
5263 	update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr);
5264 }
5265 
5266 static bool vmf_pte_changed(struct vm_fault *vmf)
5267 {
5268 	if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
5269 		return !pte_same(ptep_get(vmf->pte), vmf->orig_pte);
5270 
5271 	return !pte_none(ptep_get(vmf->pte));
5272 }
5273 
5274 /**
5275  * finish_fault - finish page fault once we have prepared the page to fault
5276  *
5277  * @vmf: structure describing the fault
5278  *
5279  * This function handles all that is needed to finish a page fault once the
5280  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
5281  * given page, adds reverse page mapping, handles memcg charges and LRU
5282  * addition.
5283  *
5284  * The function expects the page to be locked and on success it consumes a
5285  * reference of a page being mapped (for the PTE which maps it).
5286  *
5287  * Return: %0 on success, %VM_FAULT_ code in case of error.
5288  */
5289 vm_fault_t finish_fault(struct vm_fault *vmf)
5290 {
5291 	struct vm_area_struct *vma = vmf->vma;
5292 	struct page *page;
5293 	struct folio *folio;
5294 	vm_fault_t ret;
5295 	bool is_cow = (vmf->flags & FAULT_FLAG_WRITE) &&
5296 		      !(vma->vm_flags & VM_SHARED);
5297 	int type, nr_pages;
5298 	unsigned long addr;
5299 	bool needs_fallback = false;
5300 
5301 fallback:
5302 	addr = vmf->address;
5303 
5304 	/* Did we COW the page? */
5305 	if (is_cow)
5306 		page = vmf->cow_page;
5307 	else
5308 		page = vmf->page;
5309 
5310 	/*
5311 	 * check even for read faults because we might have lost our CoWed
5312 	 * page
5313 	 */
5314 	if (!(vma->vm_flags & VM_SHARED)) {
5315 		ret = check_stable_address_space(vma->vm_mm);
5316 		if (ret)
5317 			return ret;
5318 	}
5319 
5320 	if (pmd_none(*vmf->pmd)) {
5321 		if (PageTransCompound(page)) {
5322 			ret = do_set_pmd(vmf, page);
5323 			if (ret != VM_FAULT_FALLBACK)
5324 				return ret;
5325 		}
5326 
5327 		if (vmf->prealloc_pte)
5328 			pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
5329 		else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
5330 			return VM_FAULT_OOM;
5331 	}
5332 
5333 	folio = page_folio(page);
5334 	nr_pages = folio_nr_pages(folio);
5335 
5336 	/*
5337 	 * Using per-page fault to maintain the uffd semantics, and same
5338 	 * approach also applies to non-anonymous-shmem faults to avoid
5339 	 * inflating the RSS of the process.
5340 	 */
5341 	if (!vma_is_anon_shmem(vma) || unlikely(userfaultfd_armed(vma)) ||
5342 	    unlikely(needs_fallback)) {
5343 		nr_pages = 1;
5344 	} else if (nr_pages > 1) {
5345 		pgoff_t idx = folio_page_idx(folio, page);
5346 		/* The page offset of vmf->address within the VMA. */
5347 		pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
5348 		/* The index of the entry in the pagetable for fault page. */
5349 		pgoff_t pte_off = pte_index(vmf->address);
5350 
5351 		/*
5352 		 * Fallback to per-page fault in case the folio size in page
5353 		 * cache beyond the VMA limits and PMD pagetable limits.
5354 		 */
5355 		if (unlikely(vma_off < idx ||
5356 			    vma_off + (nr_pages - idx) > vma_pages(vma) ||
5357 			    pte_off < idx ||
5358 			    pte_off + (nr_pages - idx)  > PTRS_PER_PTE)) {
5359 			nr_pages = 1;
5360 		} else {
5361 			/* Now we can set mappings for the whole large folio. */
5362 			addr = vmf->address - idx * PAGE_SIZE;
5363 			page = &folio->page;
5364 		}
5365 	}
5366 
5367 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5368 				       addr, &vmf->ptl);
5369 	if (!vmf->pte)
5370 		return VM_FAULT_NOPAGE;
5371 
5372 	/* Re-check under ptl */
5373 	if (nr_pages == 1 && unlikely(vmf_pte_changed(vmf))) {
5374 		update_mmu_tlb(vma, addr, vmf->pte);
5375 		ret = VM_FAULT_NOPAGE;
5376 		goto unlock;
5377 	} else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5378 		needs_fallback = true;
5379 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5380 		goto fallback;
5381 	}
5382 
5383 	folio_ref_add(folio, nr_pages - 1);
5384 	set_pte_range(vmf, folio, page, nr_pages, addr);
5385 	type = is_cow ? MM_ANONPAGES : mm_counter_file(folio);
5386 	add_mm_counter(vma->vm_mm, type, nr_pages);
5387 	ret = 0;
5388 
5389 unlock:
5390 	pte_unmap_unlock(vmf->pte, vmf->ptl);
5391 	return ret;
5392 }
5393 
5394 static unsigned long fault_around_pages __read_mostly =
5395 	65536 >> PAGE_SHIFT;
5396 
5397 #ifdef CONFIG_DEBUG_FS
5398 static int fault_around_bytes_get(void *data, u64 *val)
5399 {
5400 	*val = fault_around_pages << PAGE_SHIFT;
5401 	return 0;
5402 }
5403 
5404 /*
5405  * fault_around_bytes must be rounded down to the nearest page order as it's
5406  * what do_fault_around() expects to see.
5407  */
5408 static int fault_around_bytes_set(void *data, u64 val)
5409 {
5410 	if (val / PAGE_SIZE > PTRS_PER_PTE)
5411 		return -EINVAL;
5412 
5413 	/*
5414 	 * The minimum value is 1 page, however this results in no fault-around
5415 	 * at all. See should_fault_around().
5416 	 */
5417 	val = max(val, PAGE_SIZE);
5418 	fault_around_pages = rounddown_pow_of_two(val) >> PAGE_SHIFT;
5419 
5420 	return 0;
5421 }
5422 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
5423 		fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
5424 
5425 static int __init fault_around_debugfs(void)
5426 {
5427 	debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
5428 				   &fault_around_bytes_fops);
5429 	return 0;
5430 }
5431 late_initcall(fault_around_debugfs);
5432 #endif
5433 
5434 /*
5435  * do_fault_around() tries to map few pages around the fault address. The hope
5436  * is that the pages will be needed soon and this will lower the number of
5437  * faults to handle.
5438  *
5439  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
5440  * not ready to be mapped: not up-to-date, locked, etc.
5441  *
5442  * This function doesn't cross VMA or page table boundaries, in order to call
5443  * map_pages() and acquire a PTE lock only once.
5444  *
5445  * fault_around_pages defines how many pages we'll try to map.
5446  * do_fault_around() expects it to be set to a power of two less than or equal
5447  * to PTRS_PER_PTE.
5448  *
5449  * The virtual address of the area that we map is naturally aligned to
5450  * fault_around_pages * PAGE_SIZE rounded down to the machine page size
5451  * (and therefore to page order).  This way it's easier to guarantee
5452  * that we don't cross page table boundaries.
5453  */
5454 static vm_fault_t do_fault_around(struct vm_fault *vmf)
5455 {
5456 	pgoff_t nr_pages = READ_ONCE(fault_around_pages);
5457 	pgoff_t pte_off = pte_index(vmf->address);
5458 	/* The page offset of vmf->address within the VMA. */
5459 	pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
5460 	pgoff_t from_pte, to_pte;
5461 	vm_fault_t ret;
5462 
5463 	/* The PTE offset of the start address, clamped to the VMA. */
5464 	from_pte = max(ALIGN_DOWN(pte_off, nr_pages),
5465 		       pte_off - min(pte_off, vma_off));
5466 
5467 	/* The PTE offset of the end address, clamped to the VMA and PTE. */
5468 	to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE,
5469 		      pte_off + vma_pages(vmf->vma) - vma_off) - 1;
5470 
5471 	if (pmd_none(*vmf->pmd)) {
5472 		vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
5473 		if (!vmf->prealloc_pte)
5474 			return VM_FAULT_OOM;
5475 	}
5476 
5477 	rcu_read_lock();
5478 	ret = vmf->vma->vm_ops->map_pages(vmf,
5479 			vmf->pgoff + from_pte - pte_off,
5480 			vmf->pgoff + to_pte - pte_off);
5481 	rcu_read_unlock();
5482 
5483 	return ret;
5484 }
5485 
5486 /* Return true if we should do read fault-around, false otherwise */
5487 static inline bool should_fault_around(struct vm_fault *vmf)
5488 {
5489 	/* No ->map_pages?  No way to fault around... */
5490 	if (!vmf->vma->vm_ops->map_pages)
5491 		return false;
5492 
5493 	if (uffd_disable_fault_around(vmf->vma))
5494 		return false;
5495 
5496 	/* A single page implies no faulting 'around' at all. */
5497 	return fault_around_pages > 1;
5498 }
5499 
5500 static vm_fault_t do_read_fault(struct vm_fault *vmf)
5501 {
5502 	vm_fault_t ret = 0;
5503 	struct folio *folio;
5504 
5505 	/*
5506 	 * Let's call ->map_pages() first and use ->fault() as fallback
5507 	 * if page by the offset is not ready to be mapped (cold cache or
5508 	 * something).
5509 	 */
5510 	if (should_fault_around(vmf)) {
5511 		ret = do_fault_around(vmf);
5512 		if (ret)
5513 			return ret;
5514 	}
5515 
5516 	ret = vmf_can_call_fault(vmf);
5517 	if (ret)
5518 		return ret;
5519 
5520 	ret = __do_fault(vmf);
5521 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5522 		return ret;
5523 
5524 	ret |= finish_fault(vmf);
5525 	folio = page_folio(vmf->page);
5526 	folio_unlock(folio);
5527 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5528 		folio_put(folio);
5529 	return ret;
5530 }
5531 
5532 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
5533 {
5534 	struct vm_area_struct *vma = vmf->vma;
5535 	struct folio *folio;
5536 	vm_fault_t ret;
5537 
5538 	ret = vmf_can_call_fault(vmf);
5539 	if (!ret)
5540 		ret = vmf_anon_prepare(vmf);
5541 	if (ret)
5542 		return ret;
5543 
5544 	folio = folio_prealloc(vma->vm_mm, vma, vmf->address, false);
5545 	if (!folio)
5546 		return VM_FAULT_OOM;
5547 
5548 	vmf->cow_page = &folio->page;
5549 
5550 	ret = __do_fault(vmf);
5551 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5552 		goto uncharge_out;
5553 	if (ret & VM_FAULT_DONE_COW)
5554 		return ret;
5555 
5556 	if (copy_mc_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma)) {
5557 		ret = VM_FAULT_HWPOISON;
5558 		goto unlock;
5559 	}
5560 	__folio_mark_uptodate(folio);
5561 
5562 	ret |= finish_fault(vmf);
5563 unlock:
5564 	unlock_page(vmf->page);
5565 	put_page(vmf->page);
5566 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5567 		goto uncharge_out;
5568 	return ret;
5569 uncharge_out:
5570 	folio_put(folio);
5571 	return ret;
5572 }
5573 
5574 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
5575 {
5576 	struct vm_area_struct *vma = vmf->vma;
5577 	vm_fault_t ret, tmp;
5578 	struct folio *folio;
5579 
5580 	ret = vmf_can_call_fault(vmf);
5581 	if (ret)
5582 		return ret;
5583 
5584 	ret = __do_fault(vmf);
5585 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5586 		return ret;
5587 
5588 	folio = page_folio(vmf->page);
5589 
5590 	/*
5591 	 * Check if the backing address space wants to know that the page is
5592 	 * about to become writable
5593 	 */
5594 	if (vma->vm_ops->page_mkwrite) {
5595 		folio_unlock(folio);
5596 		tmp = do_page_mkwrite(vmf, folio);
5597 		if (unlikely(!tmp ||
5598 				(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
5599 			folio_put(folio);
5600 			return tmp;
5601 		}
5602 	}
5603 
5604 	ret |= finish_fault(vmf);
5605 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
5606 					VM_FAULT_RETRY))) {
5607 		folio_unlock(folio);
5608 		folio_put(folio);
5609 		return ret;
5610 	}
5611 
5612 	ret |= fault_dirty_shared_page(vmf);
5613 	return ret;
5614 }
5615 
5616 /*
5617  * We enter with non-exclusive mmap_lock (to exclude vma changes,
5618  * but allow concurrent faults).
5619  * The mmap_lock may have been released depending on flags and our
5620  * return value.  See filemap_fault() and __folio_lock_or_retry().
5621  * If mmap_lock is released, vma may become invalid (for example
5622  * by other thread calling munmap()).
5623  */
5624 static vm_fault_t do_fault(struct vm_fault *vmf)
5625 {
5626 	struct vm_area_struct *vma = vmf->vma;
5627 	struct mm_struct *vm_mm = vma->vm_mm;
5628 	vm_fault_t ret;
5629 
5630 	/*
5631 	 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
5632 	 */
5633 	if (!vma->vm_ops->fault) {
5634 		vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
5635 					       vmf->address, &vmf->ptl);
5636 		if (unlikely(!vmf->pte))
5637 			ret = VM_FAULT_SIGBUS;
5638 		else {
5639 			/*
5640 			 * Make sure this is not a temporary clearing of pte
5641 			 * by holding ptl and checking again. A R/M/W update
5642 			 * of pte involves: take ptl, clearing the pte so that
5643 			 * we don't have concurrent modification by hardware
5644 			 * followed by an update.
5645 			 */
5646 			if (unlikely(pte_none(ptep_get(vmf->pte))))
5647 				ret = VM_FAULT_SIGBUS;
5648 			else
5649 				ret = VM_FAULT_NOPAGE;
5650 
5651 			pte_unmap_unlock(vmf->pte, vmf->ptl);
5652 		}
5653 	} else if (!(vmf->flags & FAULT_FLAG_WRITE))
5654 		ret = do_read_fault(vmf);
5655 	else if (!(vma->vm_flags & VM_SHARED))
5656 		ret = do_cow_fault(vmf);
5657 	else
5658 		ret = do_shared_fault(vmf);
5659 
5660 	/* preallocated pagetable is unused: free it */
5661 	if (vmf->prealloc_pte) {
5662 		pte_free(vm_mm, vmf->prealloc_pte);
5663 		vmf->prealloc_pte = NULL;
5664 	}
5665 	return ret;
5666 }
5667 
5668 int numa_migrate_check(struct folio *folio, struct vm_fault *vmf,
5669 		      unsigned long addr, int *flags,
5670 		      bool writable, int *last_cpupid)
5671 {
5672 	struct vm_area_struct *vma = vmf->vma;
5673 
5674 	/*
5675 	 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
5676 	 * much anyway since they can be in shared cache state. This misses
5677 	 * the case where a mapping is writable but the process never writes
5678 	 * to it but pte_write gets cleared during protection updates and
5679 	 * pte_dirty has unpredictable behaviour between PTE scan updates,
5680 	 * background writeback, dirty balancing and application behaviour.
5681 	 */
5682 	if (!writable)
5683 		*flags |= TNF_NO_GROUP;
5684 
5685 	/*
5686 	 * Flag if the folio is shared between multiple address spaces. This
5687 	 * is later used when determining whether to group tasks together
5688 	 */
5689 	if (folio_maybe_mapped_shared(folio) && (vma->vm_flags & VM_SHARED))
5690 		*flags |= TNF_SHARED;
5691 	/*
5692 	 * For memory tiering mode, cpupid of slow memory page is used
5693 	 * to record page access time.  So use default value.
5694 	 */
5695 	if (folio_use_access_time(folio))
5696 		*last_cpupid = (-1 & LAST_CPUPID_MASK);
5697 	else
5698 		*last_cpupid = folio_last_cpupid(folio);
5699 
5700 	/* Record the current PID acceesing VMA */
5701 	vma_set_access_pid_bit(vma);
5702 
5703 	count_vm_numa_event(NUMA_HINT_FAULTS);
5704 #ifdef CONFIG_NUMA_BALANCING
5705 	count_memcg_folio_events(folio, NUMA_HINT_FAULTS, 1);
5706 #endif
5707 	if (folio_nid(folio) == numa_node_id()) {
5708 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
5709 		*flags |= TNF_FAULT_LOCAL;
5710 	}
5711 
5712 	return mpol_misplaced(folio, vmf, addr);
5713 }
5714 
5715 static void numa_rebuild_single_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
5716 					unsigned long fault_addr, pte_t *fault_pte,
5717 					bool writable)
5718 {
5719 	pte_t pte, old_pte;
5720 
5721 	old_pte = ptep_modify_prot_start(vma, fault_addr, fault_pte);
5722 	pte = pte_modify(old_pte, vma->vm_page_prot);
5723 	pte = pte_mkyoung(pte);
5724 	if (writable)
5725 		pte = pte_mkwrite(pte, vma);
5726 	ptep_modify_prot_commit(vma, fault_addr, fault_pte, old_pte, pte);
5727 	update_mmu_cache_range(vmf, vma, fault_addr, fault_pte, 1);
5728 }
5729 
5730 static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
5731 				       struct folio *folio, pte_t fault_pte,
5732 				       bool ignore_writable, bool pte_write_upgrade)
5733 {
5734 	int nr = pte_pfn(fault_pte) - folio_pfn(folio);
5735 	unsigned long start, end, addr = vmf->address;
5736 	unsigned long addr_start = addr - (nr << PAGE_SHIFT);
5737 	unsigned long pt_start = ALIGN_DOWN(addr, PMD_SIZE);
5738 	pte_t *start_ptep;
5739 
5740 	/* Stay within the VMA and within the page table. */
5741 	start = max3(addr_start, pt_start, vma->vm_start);
5742 	end = min3(addr_start + folio_size(folio), pt_start + PMD_SIZE,
5743 		   vma->vm_end);
5744 	start_ptep = vmf->pte - ((addr - start) >> PAGE_SHIFT);
5745 
5746 	/* Restore all PTEs' mapping of the large folio */
5747 	for (addr = start; addr != end; start_ptep++, addr += PAGE_SIZE) {
5748 		pte_t ptent = ptep_get(start_ptep);
5749 		bool writable = false;
5750 
5751 		if (!pte_present(ptent) || !pte_protnone(ptent))
5752 			continue;
5753 
5754 		if (pfn_folio(pte_pfn(ptent)) != folio)
5755 			continue;
5756 
5757 		if (!ignore_writable) {
5758 			ptent = pte_modify(ptent, vma->vm_page_prot);
5759 			writable = pte_write(ptent);
5760 			if (!writable && pte_write_upgrade &&
5761 			    can_change_pte_writable(vma, addr, ptent))
5762 				writable = true;
5763 		}
5764 
5765 		numa_rebuild_single_mapping(vmf, vma, addr, start_ptep, writable);
5766 	}
5767 }
5768 
5769 static vm_fault_t do_numa_page(struct vm_fault *vmf)
5770 {
5771 	struct vm_area_struct *vma = vmf->vma;
5772 	struct folio *folio = NULL;
5773 	int nid = NUMA_NO_NODE;
5774 	bool writable = false, ignore_writable = false;
5775 	bool pte_write_upgrade = vma_wants_manual_pte_write_upgrade(vma);
5776 	int last_cpupid;
5777 	int target_nid;
5778 	pte_t pte, old_pte;
5779 	int flags = 0, nr_pages;
5780 
5781 	/*
5782 	 * The pte cannot be used safely until we verify, while holding the page
5783 	 * table lock, that its contents have not changed during fault handling.
5784 	 */
5785 	spin_lock(vmf->ptl);
5786 	/* Read the live PTE from the page tables: */
5787 	old_pte = ptep_get(vmf->pte);
5788 
5789 	if (unlikely(!pte_same(old_pte, vmf->orig_pte))) {
5790 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5791 		return 0;
5792 	}
5793 
5794 	pte = pte_modify(old_pte, vma->vm_page_prot);
5795 
5796 	/*
5797 	 * Detect now whether the PTE could be writable; this information
5798 	 * is only valid while holding the PT lock.
5799 	 */
5800 	writable = pte_write(pte);
5801 	if (!writable && pte_write_upgrade &&
5802 	    can_change_pte_writable(vma, vmf->address, pte))
5803 		writable = true;
5804 
5805 	folio = vm_normal_folio(vma, vmf->address, pte);
5806 	if (!folio || folio_is_zone_device(folio))
5807 		goto out_map;
5808 
5809 	nid = folio_nid(folio);
5810 	nr_pages = folio_nr_pages(folio);
5811 
5812 	target_nid = numa_migrate_check(folio, vmf, vmf->address, &flags,
5813 					writable, &last_cpupid);
5814 	if (target_nid == NUMA_NO_NODE)
5815 		goto out_map;
5816 	if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) {
5817 		flags |= TNF_MIGRATE_FAIL;
5818 		goto out_map;
5819 	}
5820 	/* The folio is isolated and isolation code holds a folio reference. */
5821 	pte_unmap_unlock(vmf->pte, vmf->ptl);
5822 	writable = false;
5823 	ignore_writable = true;
5824 
5825 	/* Migrate to the requested node */
5826 	if (!migrate_misplaced_folio(folio, target_nid)) {
5827 		nid = target_nid;
5828 		flags |= TNF_MIGRATED;
5829 		task_numa_fault(last_cpupid, nid, nr_pages, flags);
5830 		return 0;
5831 	}
5832 
5833 	flags |= TNF_MIGRATE_FAIL;
5834 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5835 				       vmf->address, &vmf->ptl);
5836 	if (unlikely(!vmf->pte))
5837 		return 0;
5838 	if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
5839 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5840 		return 0;
5841 	}
5842 out_map:
5843 	/*
5844 	 * Make it present again, depending on how arch implements
5845 	 * non-accessible ptes, some can allow access by kernel mode.
5846 	 */
5847 	if (folio && folio_test_large(folio))
5848 		numa_rebuild_large_mapping(vmf, vma, folio, pte, ignore_writable,
5849 					   pte_write_upgrade);
5850 	else
5851 		numa_rebuild_single_mapping(vmf, vma, vmf->address, vmf->pte,
5852 					    writable);
5853 	pte_unmap_unlock(vmf->pte, vmf->ptl);
5854 
5855 	if (nid != NUMA_NO_NODE)
5856 		task_numa_fault(last_cpupid, nid, nr_pages, flags);
5857 	return 0;
5858 }
5859 
5860 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
5861 {
5862 	struct vm_area_struct *vma = vmf->vma;
5863 	if (vma_is_anonymous(vma))
5864 		return do_huge_pmd_anonymous_page(vmf);
5865 	if (vma->vm_ops->huge_fault)
5866 		return vma->vm_ops->huge_fault(vmf, PMD_ORDER);
5867 	return VM_FAULT_FALLBACK;
5868 }
5869 
5870 /* `inline' is required to avoid gcc 4.1.2 build error */
5871 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
5872 {
5873 	struct vm_area_struct *vma = vmf->vma;
5874 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
5875 	vm_fault_t ret;
5876 
5877 	if (vma_is_anonymous(vma)) {
5878 		if (likely(!unshare) &&
5879 		    userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) {
5880 			if (userfaultfd_wp_async(vmf->vma))
5881 				goto split;
5882 			return handle_userfault(vmf, VM_UFFD_WP);
5883 		}
5884 		return do_huge_pmd_wp_page(vmf);
5885 	}
5886 
5887 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
5888 		if (vma->vm_ops->huge_fault) {
5889 			ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER);
5890 			if (!(ret & VM_FAULT_FALLBACK))
5891 				return ret;
5892 		}
5893 	}
5894 
5895 split:
5896 	/* COW or write-notify handled on pte level: split pmd. */
5897 	__split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
5898 
5899 	return VM_FAULT_FALLBACK;
5900 }
5901 
5902 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
5903 {
5904 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&			\
5905 	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
5906 	struct vm_area_struct *vma = vmf->vma;
5907 	/* No support for anonymous transparent PUD pages yet */
5908 	if (vma_is_anonymous(vma))
5909 		return VM_FAULT_FALLBACK;
5910 	if (vma->vm_ops->huge_fault)
5911 		return vma->vm_ops->huge_fault(vmf, PUD_ORDER);
5912 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5913 	return VM_FAULT_FALLBACK;
5914 }
5915 
5916 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
5917 {
5918 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&			\
5919 	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
5920 	struct vm_area_struct *vma = vmf->vma;
5921 	vm_fault_t ret;
5922 
5923 	/* No support for anonymous transparent PUD pages yet */
5924 	if (vma_is_anonymous(vma))
5925 		goto split;
5926 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
5927 		if (vma->vm_ops->huge_fault) {
5928 			ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER);
5929 			if (!(ret & VM_FAULT_FALLBACK))
5930 				return ret;
5931 		}
5932 	}
5933 split:
5934 	/* COW or write-notify not handled on PUD level: split pud.*/
5935 	__split_huge_pud(vma, vmf->pud, vmf->address);
5936 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
5937 	return VM_FAULT_FALLBACK;
5938 }
5939 
5940 /*
5941  * These routines also need to handle stuff like marking pages dirty
5942  * and/or accessed for architectures that don't do it in hardware (most
5943  * RISC architectures).  The early dirtying is also good on the i386.
5944  *
5945  * There is also a hook called "update_mmu_cache()" that architectures
5946  * with external mmu caches can use to update those (ie the Sparc or
5947  * PowerPC hashed page tables that act as extended TLBs).
5948  *
5949  * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
5950  * concurrent faults).
5951  *
5952  * The mmap_lock may have been released depending on flags and our return value.
5953  * See filemap_fault() and __folio_lock_or_retry().
5954  */
5955 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
5956 {
5957 	pte_t entry;
5958 
5959 	if (unlikely(pmd_none(*vmf->pmd))) {
5960 		/*
5961 		 * Leave __pte_alloc() until later: because vm_ops->fault may
5962 		 * want to allocate huge page, and if we expose page table
5963 		 * for an instant, it will be difficult to retract from
5964 		 * concurrent faults and from rmap lookups.
5965 		 */
5966 		vmf->pte = NULL;
5967 		vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
5968 	} else {
5969 		pmd_t dummy_pmdval;
5970 
5971 		/*
5972 		 * A regular pmd is established and it can't morph into a huge
5973 		 * pmd by anon khugepaged, since that takes mmap_lock in write
5974 		 * mode; but shmem or file collapse to THP could still morph
5975 		 * it into a huge pmd: just retry later if so.
5976 		 *
5977 		 * Use the maywrite version to indicate that vmf->pte may be
5978 		 * modified, but since we will use pte_same() to detect the
5979 		 * change of the !pte_none() entry, there is no need to recheck
5980 		 * the pmdval. Here we chooes to pass a dummy variable instead
5981 		 * of NULL, which helps new user think about why this place is
5982 		 * special.
5983 		 */
5984 		vmf->pte = pte_offset_map_rw_nolock(vmf->vma->vm_mm, vmf->pmd,
5985 						    vmf->address, &dummy_pmdval,
5986 						    &vmf->ptl);
5987 		if (unlikely(!vmf->pte))
5988 			return 0;
5989 		vmf->orig_pte = ptep_get_lockless(vmf->pte);
5990 		vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
5991 
5992 		if (pte_none(vmf->orig_pte)) {
5993 			pte_unmap(vmf->pte);
5994 			vmf->pte = NULL;
5995 		}
5996 	}
5997 
5998 	if (!vmf->pte)
5999 		return do_pte_missing(vmf);
6000 
6001 	if (!pte_present(vmf->orig_pte))
6002 		return do_swap_page(vmf);
6003 
6004 	if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
6005 		return do_numa_page(vmf);
6006 
6007 	spin_lock(vmf->ptl);
6008 	entry = vmf->orig_pte;
6009 	if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) {
6010 		update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
6011 		goto unlock;
6012 	}
6013 	if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6014 		if (!pte_write(entry))
6015 			return do_wp_page(vmf);
6016 		else if (likely(vmf->flags & FAULT_FLAG_WRITE))
6017 			entry = pte_mkdirty(entry);
6018 	}
6019 	entry = pte_mkyoung(entry);
6020 	if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
6021 				vmf->flags & FAULT_FLAG_WRITE)) {
6022 		update_mmu_cache_range(vmf, vmf->vma, vmf->address,
6023 				vmf->pte, 1);
6024 	} else {
6025 		/* Skip spurious TLB flush for retried page fault */
6026 		if (vmf->flags & FAULT_FLAG_TRIED)
6027 			goto unlock;
6028 		/*
6029 		 * This is needed only for protection faults but the arch code
6030 		 * is not yet telling us if this is a protection fault or not.
6031 		 * This still avoids useless tlb flushes for .text page faults
6032 		 * with threads.
6033 		 */
6034 		if (vmf->flags & FAULT_FLAG_WRITE)
6035 			flush_tlb_fix_spurious_fault(vmf->vma, vmf->address,
6036 						     vmf->pte);
6037 	}
6038 unlock:
6039 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6040 	return 0;
6041 }
6042 
6043 /*
6044  * On entry, we hold either the VMA lock or the mmap_lock
6045  * (FAULT_FLAG_VMA_LOCK tells you which).  If VM_FAULT_RETRY is set in
6046  * the result, the mmap_lock is not held on exit.  See filemap_fault()
6047  * and __folio_lock_or_retry().
6048  */
6049 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
6050 		unsigned long address, unsigned int flags)
6051 {
6052 	struct vm_fault vmf = {
6053 		.vma = vma,
6054 		.address = address & PAGE_MASK,
6055 		.real_address = address,
6056 		.flags = flags,
6057 		.pgoff = linear_page_index(vma, address),
6058 		.gfp_mask = __get_fault_gfp_mask(vma),
6059 	};
6060 	struct mm_struct *mm = vma->vm_mm;
6061 	unsigned long vm_flags = vma->vm_flags;
6062 	pgd_t *pgd;
6063 	p4d_t *p4d;
6064 	vm_fault_t ret;
6065 
6066 	pgd = pgd_offset(mm, address);
6067 	p4d = p4d_alloc(mm, pgd, address);
6068 	if (!p4d)
6069 		return VM_FAULT_OOM;
6070 
6071 	vmf.pud = pud_alloc(mm, p4d, address);
6072 	if (!vmf.pud)
6073 		return VM_FAULT_OOM;
6074 retry_pud:
6075 	if (pud_none(*vmf.pud) &&
6076 	    thp_vma_allowable_order(vma, vm_flags,
6077 				TVA_IN_PF | TVA_ENFORCE_SYSFS, PUD_ORDER)) {
6078 		ret = create_huge_pud(&vmf);
6079 		if (!(ret & VM_FAULT_FALLBACK))
6080 			return ret;
6081 	} else {
6082 		pud_t orig_pud = *vmf.pud;
6083 
6084 		barrier();
6085 		if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
6086 
6087 			/*
6088 			 * TODO once we support anonymous PUDs: NUMA case and
6089 			 * FAULT_FLAG_UNSHARE handling.
6090 			 */
6091 			if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
6092 				ret = wp_huge_pud(&vmf, orig_pud);
6093 				if (!(ret & VM_FAULT_FALLBACK))
6094 					return ret;
6095 			} else {
6096 				huge_pud_set_accessed(&vmf, orig_pud);
6097 				return 0;
6098 			}
6099 		}
6100 	}
6101 
6102 	vmf.pmd = pmd_alloc(mm, vmf.pud, address);
6103 	if (!vmf.pmd)
6104 		return VM_FAULT_OOM;
6105 
6106 	/* Huge pud page fault raced with pmd_alloc? */
6107 	if (pud_trans_unstable(vmf.pud))
6108 		goto retry_pud;
6109 
6110 	if (pmd_none(*vmf.pmd) &&
6111 	    thp_vma_allowable_order(vma, vm_flags,
6112 				TVA_IN_PF | TVA_ENFORCE_SYSFS, PMD_ORDER)) {
6113 		ret = create_huge_pmd(&vmf);
6114 		if (!(ret & VM_FAULT_FALLBACK))
6115 			return ret;
6116 	} else {
6117 		vmf.orig_pmd = pmdp_get_lockless(vmf.pmd);
6118 
6119 		if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
6120 			VM_BUG_ON(thp_migration_supported() &&
6121 					  !is_pmd_migration_entry(vmf.orig_pmd));
6122 			if (is_pmd_migration_entry(vmf.orig_pmd))
6123 				pmd_migration_entry_wait(mm, vmf.pmd);
6124 			return 0;
6125 		}
6126 		if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
6127 			if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
6128 				return do_huge_pmd_numa_page(&vmf);
6129 
6130 			if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6131 			    !pmd_write(vmf.orig_pmd)) {
6132 				ret = wp_huge_pmd(&vmf);
6133 				if (!(ret & VM_FAULT_FALLBACK))
6134 					return ret;
6135 			} else {
6136 				huge_pmd_set_accessed(&vmf);
6137 				return 0;
6138 			}
6139 		}
6140 	}
6141 
6142 	return handle_pte_fault(&vmf);
6143 }
6144 
6145 /**
6146  * mm_account_fault - Do page fault accounting
6147  * @mm: mm from which memcg should be extracted. It can be NULL.
6148  * @regs: the pt_regs struct pointer.  When set to NULL, will skip accounting
6149  *        of perf event counters, but we'll still do the per-task accounting to
6150  *        the task who triggered this page fault.
6151  * @address: the faulted address.
6152  * @flags: the fault flags.
6153  * @ret: the fault retcode.
6154  *
6155  * This will take care of most of the page fault accounting.  Meanwhile, it
6156  * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
6157  * updates.  However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
6158  * still be in per-arch page fault handlers at the entry of page fault.
6159  */
6160 static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs,
6161 				    unsigned long address, unsigned int flags,
6162 				    vm_fault_t ret)
6163 {
6164 	bool major;
6165 
6166 	/* Incomplete faults will be accounted upon completion. */
6167 	if (ret & VM_FAULT_RETRY)
6168 		return;
6169 
6170 	/*
6171 	 * To preserve the behavior of older kernels, PGFAULT counters record
6172 	 * both successful and failed faults, as opposed to perf counters,
6173 	 * which ignore failed cases.
6174 	 */
6175 	count_vm_event(PGFAULT);
6176 	count_memcg_event_mm(mm, PGFAULT);
6177 
6178 	/*
6179 	 * Do not account for unsuccessful faults (e.g. when the address wasn't
6180 	 * valid).  That includes arch_vma_access_permitted() failing before
6181 	 * reaching here. So this is not a "this many hardware page faults"
6182 	 * counter.  We should use the hw profiling for that.
6183 	 */
6184 	if (ret & VM_FAULT_ERROR)
6185 		return;
6186 
6187 	/*
6188 	 * We define the fault as a major fault when the final successful fault
6189 	 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
6190 	 * handle it immediately previously).
6191 	 */
6192 	major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
6193 
6194 	if (major)
6195 		current->maj_flt++;
6196 	else
6197 		current->min_flt++;
6198 
6199 	/*
6200 	 * If the fault is done for GUP, regs will be NULL.  We only do the
6201 	 * accounting for the per thread fault counters who triggered the
6202 	 * fault, and we skip the perf event updates.
6203 	 */
6204 	if (!regs)
6205 		return;
6206 
6207 	if (major)
6208 		perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
6209 	else
6210 		perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
6211 }
6212 
6213 #ifdef CONFIG_LRU_GEN
6214 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6215 {
6216 	/* the LRU algorithm only applies to accesses with recency */
6217 	current->in_lru_fault = vma_has_recency(vma);
6218 }
6219 
6220 static void lru_gen_exit_fault(void)
6221 {
6222 	current->in_lru_fault = false;
6223 }
6224 #else
6225 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6226 {
6227 }
6228 
6229 static void lru_gen_exit_fault(void)
6230 {
6231 }
6232 #endif /* CONFIG_LRU_GEN */
6233 
6234 static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma,
6235 				       unsigned int *flags)
6236 {
6237 	if (unlikely(*flags & FAULT_FLAG_UNSHARE)) {
6238 		if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE))
6239 			return VM_FAULT_SIGSEGV;
6240 		/*
6241 		 * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's
6242 		 * just treat it like an ordinary read-fault otherwise.
6243 		 */
6244 		if (!is_cow_mapping(vma->vm_flags))
6245 			*flags &= ~FAULT_FLAG_UNSHARE;
6246 	} else if (*flags & FAULT_FLAG_WRITE) {
6247 		/* Write faults on read-only mappings are impossible ... */
6248 		if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE)))
6249 			return VM_FAULT_SIGSEGV;
6250 		/* ... and FOLL_FORCE only applies to COW mappings. */
6251 		if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) &&
6252 				 !is_cow_mapping(vma->vm_flags)))
6253 			return VM_FAULT_SIGSEGV;
6254 	}
6255 #ifdef CONFIG_PER_VMA_LOCK
6256 	/*
6257 	 * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of
6258 	 * the assumption that lock is dropped on VM_FAULT_RETRY.
6259 	 */
6260 	if (WARN_ON_ONCE((*flags &
6261 			(FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) ==
6262 			(FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))
6263 		return VM_FAULT_SIGSEGV;
6264 #endif
6265 
6266 	return 0;
6267 }
6268 
6269 /*
6270  * By the time we get here, we already hold either the VMA lock or the
6271  * mmap_lock (FAULT_FLAG_VMA_LOCK tells you which).
6272  *
6273  * The mmap_lock may have been released depending on flags and our
6274  * return value.  See filemap_fault() and __folio_lock_or_retry().
6275  */
6276 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
6277 			   unsigned int flags, struct pt_regs *regs)
6278 {
6279 	/* If the fault handler drops the mmap_lock, vma may be freed */
6280 	struct mm_struct *mm = vma->vm_mm;
6281 	vm_fault_t ret;
6282 	bool is_droppable;
6283 
6284 	__set_current_state(TASK_RUNNING);
6285 
6286 	ret = sanitize_fault_flags(vma, &flags);
6287 	if (ret)
6288 		goto out;
6289 
6290 	if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
6291 					    flags & FAULT_FLAG_INSTRUCTION,
6292 					    flags & FAULT_FLAG_REMOTE)) {
6293 		ret = VM_FAULT_SIGSEGV;
6294 		goto out;
6295 	}
6296 
6297 	is_droppable = !!(vma->vm_flags & VM_DROPPABLE);
6298 
6299 	/*
6300 	 * Enable the memcg OOM handling for faults triggered in user
6301 	 * space.  Kernel faults are handled more gracefully.
6302 	 */
6303 	if (flags & FAULT_FLAG_USER)
6304 		mem_cgroup_enter_user_fault();
6305 
6306 	lru_gen_enter_fault(vma);
6307 
6308 	if (unlikely(is_vm_hugetlb_page(vma)))
6309 		ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
6310 	else
6311 		ret = __handle_mm_fault(vma, address, flags);
6312 
6313 	/*
6314 	 * Warning: It is no longer safe to dereference vma-> after this point,
6315 	 * because mmap_lock might have been dropped by __handle_mm_fault(), so
6316 	 * vma might be destroyed from underneath us.
6317 	 */
6318 
6319 	lru_gen_exit_fault();
6320 
6321 	/* If the mapping is droppable, then errors due to OOM aren't fatal. */
6322 	if (is_droppable)
6323 		ret &= ~VM_FAULT_OOM;
6324 
6325 	if (flags & FAULT_FLAG_USER) {
6326 		mem_cgroup_exit_user_fault();
6327 		/*
6328 		 * The task may have entered a memcg OOM situation but
6329 		 * if the allocation error was handled gracefully (no
6330 		 * VM_FAULT_OOM), there is no need to kill anything.
6331 		 * Just clean up the OOM state peacefully.
6332 		 */
6333 		if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
6334 			mem_cgroup_oom_synchronize(false);
6335 	}
6336 out:
6337 	mm_account_fault(mm, regs, address, flags, ret);
6338 
6339 	return ret;
6340 }
6341 EXPORT_SYMBOL_GPL(handle_mm_fault);
6342 
6343 #ifdef CONFIG_LOCK_MM_AND_FIND_VMA
6344 #include <linux/extable.h>
6345 
6346 static inline bool get_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
6347 {
6348 	if (likely(mmap_read_trylock(mm)))
6349 		return true;
6350 
6351 	if (regs && !user_mode(regs)) {
6352 		unsigned long ip = exception_ip(regs);
6353 		if (!search_exception_tables(ip))
6354 			return false;
6355 	}
6356 
6357 	return !mmap_read_lock_killable(mm);
6358 }
6359 
6360 static inline bool mmap_upgrade_trylock(struct mm_struct *mm)
6361 {
6362 	/*
6363 	 * We don't have this operation yet.
6364 	 *
6365 	 * It should be easy enough to do: it's basically a
6366 	 *    atomic_long_try_cmpxchg_acquire()
6367 	 * from RWSEM_READER_BIAS -> RWSEM_WRITER_LOCKED, but
6368 	 * it also needs the proper lockdep magic etc.
6369 	 */
6370 	return false;
6371 }
6372 
6373 static inline bool upgrade_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
6374 {
6375 	mmap_read_unlock(mm);
6376 	if (regs && !user_mode(regs)) {
6377 		unsigned long ip = exception_ip(regs);
6378 		if (!search_exception_tables(ip))
6379 			return false;
6380 	}
6381 	return !mmap_write_lock_killable(mm);
6382 }
6383 
6384 /*
6385  * Helper for page fault handling.
6386  *
6387  * This is kind of equivalent to "mmap_read_lock()" followed
6388  * by "find_extend_vma()", except it's a lot more careful about
6389  * the locking (and will drop the lock on failure).
6390  *
6391  * For example, if we have a kernel bug that causes a page
6392  * fault, we don't want to just use mmap_read_lock() to get
6393  * the mm lock, because that would deadlock if the bug were
6394  * to happen while we're holding the mm lock for writing.
6395  *
6396  * So this checks the exception tables on kernel faults in
6397  * order to only do this all for instructions that are actually
6398  * expected to fault.
6399  *
6400  * We can also actually take the mm lock for writing if we
6401  * need to extend the vma, which helps the VM layer a lot.
6402  */
6403 struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm,
6404 			unsigned long addr, struct pt_regs *regs)
6405 {
6406 	struct vm_area_struct *vma;
6407 
6408 	if (!get_mmap_lock_carefully(mm, regs))
6409 		return NULL;
6410 
6411 	vma = find_vma(mm, addr);
6412 	if (likely(vma && (vma->vm_start <= addr)))
6413 		return vma;
6414 
6415 	/*
6416 	 * Well, dang. We might still be successful, but only
6417 	 * if we can extend a vma to do so.
6418 	 */
6419 	if (!vma || !(vma->vm_flags & VM_GROWSDOWN)) {
6420 		mmap_read_unlock(mm);
6421 		return NULL;
6422 	}
6423 
6424 	/*
6425 	 * We can try to upgrade the mmap lock atomically,
6426 	 * in which case we can continue to use the vma
6427 	 * we already looked up.
6428 	 *
6429 	 * Otherwise we'll have to drop the mmap lock and
6430 	 * re-take it, and also look up the vma again,
6431 	 * re-checking it.
6432 	 */
6433 	if (!mmap_upgrade_trylock(mm)) {
6434 		if (!upgrade_mmap_lock_carefully(mm, regs))
6435 			return NULL;
6436 
6437 		vma = find_vma(mm, addr);
6438 		if (!vma)
6439 			goto fail;
6440 		if (vma->vm_start <= addr)
6441 			goto success;
6442 		if (!(vma->vm_flags & VM_GROWSDOWN))
6443 			goto fail;
6444 	}
6445 
6446 	if (expand_stack_locked(vma, addr))
6447 		goto fail;
6448 
6449 success:
6450 	mmap_write_downgrade(mm);
6451 	return vma;
6452 
6453 fail:
6454 	mmap_write_unlock(mm);
6455 	return NULL;
6456 }
6457 #endif
6458 
6459 #ifdef CONFIG_PER_VMA_LOCK
6460 static inline bool __vma_enter_locked(struct vm_area_struct *vma, bool detaching)
6461 {
6462 	unsigned int tgt_refcnt = VMA_LOCK_OFFSET;
6463 
6464 	/* Additional refcnt if the vma is attached. */
6465 	if (!detaching)
6466 		tgt_refcnt++;
6467 
6468 	/*
6469 	 * If vma is detached then only vma_mark_attached() can raise the
6470 	 * vm_refcnt. mmap_write_lock prevents racing with vma_mark_attached().
6471 	 */
6472 	if (!refcount_add_not_zero(VMA_LOCK_OFFSET, &vma->vm_refcnt))
6473 		return false;
6474 
6475 	rwsem_acquire(&vma->vmlock_dep_map, 0, 0, _RET_IP_);
6476 	rcuwait_wait_event(&vma->vm_mm->vma_writer_wait,
6477 		   refcount_read(&vma->vm_refcnt) == tgt_refcnt,
6478 		   TASK_UNINTERRUPTIBLE);
6479 	lock_acquired(&vma->vmlock_dep_map, _RET_IP_);
6480 
6481 	return true;
6482 }
6483 
6484 static inline void __vma_exit_locked(struct vm_area_struct *vma, bool *detached)
6485 {
6486 	*detached = refcount_sub_and_test(VMA_LOCK_OFFSET, &vma->vm_refcnt);
6487 	rwsem_release(&vma->vmlock_dep_map, _RET_IP_);
6488 }
6489 
6490 void __vma_start_write(struct vm_area_struct *vma, unsigned int mm_lock_seq)
6491 {
6492 	bool locked;
6493 
6494 	/*
6495 	 * __vma_enter_locked() returns false immediately if the vma is not
6496 	 * attached, otherwise it waits until refcnt is indicating that vma
6497 	 * is attached with no readers.
6498 	 */
6499 	locked = __vma_enter_locked(vma, false);
6500 
6501 	/*
6502 	 * We should use WRITE_ONCE() here because we can have concurrent reads
6503 	 * from the early lockless pessimistic check in vma_start_read().
6504 	 * We don't really care about the correctness of that early check, but
6505 	 * we should use WRITE_ONCE() for cleanliness and to keep KCSAN happy.
6506 	 */
6507 	WRITE_ONCE(vma->vm_lock_seq, mm_lock_seq);
6508 
6509 	if (locked) {
6510 		bool detached;
6511 
6512 		__vma_exit_locked(vma, &detached);
6513 		WARN_ON_ONCE(detached); /* vma should remain attached */
6514 	}
6515 }
6516 EXPORT_SYMBOL_GPL(__vma_start_write);
6517 
6518 void vma_mark_detached(struct vm_area_struct *vma)
6519 {
6520 	vma_assert_write_locked(vma);
6521 	vma_assert_attached(vma);
6522 
6523 	/*
6524 	 * We are the only writer, so no need to use vma_refcount_put().
6525 	 * The condition below is unlikely because the vma has been already
6526 	 * write-locked and readers can increment vm_refcnt only temporarily
6527 	 * before they check vm_lock_seq, realize the vma is locked and drop
6528 	 * back the vm_refcnt. That is a narrow window for observing a raised
6529 	 * vm_refcnt.
6530 	 */
6531 	if (unlikely(!refcount_dec_and_test(&vma->vm_refcnt))) {
6532 		/* Wait until vma is detached with no readers. */
6533 		if (__vma_enter_locked(vma, true)) {
6534 			bool detached;
6535 
6536 			__vma_exit_locked(vma, &detached);
6537 			WARN_ON_ONCE(!detached);
6538 		}
6539 	}
6540 }
6541 
6542 /*
6543  * Lookup and lock a VMA under RCU protection. Returned VMA is guaranteed to be
6544  * stable and not isolated. If the VMA is not found or is being modified the
6545  * function returns NULL.
6546  */
6547 struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,
6548 					  unsigned long address)
6549 {
6550 	MA_STATE(mas, &mm->mm_mt, address, address);
6551 	struct vm_area_struct *vma;
6552 
6553 	rcu_read_lock();
6554 retry:
6555 	vma = mas_walk(&mas);
6556 	if (!vma)
6557 		goto inval;
6558 
6559 	vma = vma_start_read(mm, vma);
6560 	if (IS_ERR_OR_NULL(vma)) {
6561 		/* Check if the VMA got isolated after we found it */
6562 		if (PTR_ERR(vma) == -EAGAIN) {
6563 			count_vm_vma_lock_event(VMA_LOCK_MISS);
6564 			/* The area was replaced with another one */
6565 			goto retry;
6566 		}
6567 
6568 		/* Failed to lock the VMA */
6569 		goto inval;
6570 	}
6571 	/*
6572 	 * At this point, we have a stable reference to a VMA: The VMA is
6573 	 * locked and we know it hasn't already been isolated.
6574 	 * From here on, we can access the VMA without worrying about which
6575 	 * fields are accessible for RCU readers.
6576 	 */
6577 
6578 	/* Check if the vma we locked is the right one. */
6579 	if (unlikely(vma->vm_mm != mm ||
6580 		     address < vma->vm_start || address >= vma->vm_end))
6581 		goto inval_end_read;
6582 
6583 	rcu_read_unlock();
6584 	return vma;
6585 
6586 inval_end_read:
6587 	vma_end_read(vma);
6588 inval:
6589 	rcu_read_unlock();
6590 	count_vm_vma_lock_event(VMA_LOCK_ABORT);
6591 	return NULL;
6592 }
6593 #endif /* CONFIG_PER_VMA_LOCK */
6594 
6595 #ifndef __PAGETABLE_P4D_FOLDED
6596 /*
6597  * Allocate p4d page table.
6598  * We've already handled the fast-path in-line.
6599  */
6600 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
6601 {
6602 	p4d_t *new = p4d_alloc_one(mm, address);
6603 	if (!new)
6604 		return -ENOMEM;
6605 
6606 	spin_lock(&mm->page_table_lock);
6607 	if (pgd_present(*pgd)) {	/* Another has populated it */
6608 		p4d_free(mm, new);
6609 	} else {
6610 		smp_wmb(); /* See comment in pmd_install() */
6611 		pgd_populate(mm, pgd, new);
6612 	}
6613 	spin_unlock(&mm->page_table_lock);
6614 	return 0;
6615 }
6616 #endif /* __PAGETABLE_P4D_FOLDED */
6617 
6618 #ifndef __PAGETABLE_PUD_FOLDED
6619 /*
6620  * Allocate page upper directory.
6621  * We've already handled the fast-path in-line.
6622  */
6623 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
6624 {
6625 	pud_t *new = pud_alloc_one(mm, address);
6626 	if (!new)
6627 		return -ENOMEM;
6628 
6629 	spin_lock(&mm->page_table_lock);
6630 	if (!p4d_present(*p4d)) {
6631 		mm_inc_nr_puds(mm);
6632 		smp_wmb(); /* See comment in pmd_install() */
6633 		p4d_populate(mm, p4d, new);
6634 	} else	/* Another has populated it */
6635 		pud_free(mm, new);
6636 	spin_unlock(&mm->page_table_lock);
6637 	return 0;
6638 }
6639 #endif /* __PAGETABLE_PUD_FOLDED */
6640 
6641 #ifndef __PAGETABLE_PMD_FOLDED
6642 /*
6643  * Allocate page middle directory.
6644  * We've already handled the fast-path in-line.
6645  */
6646 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
6647 {
6648 	spinlock_t *ptl;
6649 	pmd_t *new = pmd_alloc_one(mm, address);
6650 	if (!new)
6651 		return -ENOMEM;
6652 
6653 	ptl = pud_lock(mm, pud);
6654 	if (!pud_present(*pud)) {
6655 		mm_inc_nr_pmds(mm);
6656 		smp_wmb(); /* See comment in pmd_install() */
6657 		pud_populate(mm, pud, new);
6658 	} else {	/* Another has populated it */
6659 		pmd_free(mm, new);
6660 	}
6661 	spin_unlock(ptl);
6662 	return 0;
6663 }
6664 #endif /* __PAGETABLE_PMD_FOLDED */
6665 
6666 static inline void pfnmap_args_setup(struct follow_pfnmap_args *args,
6667 				     spinlock_t *lock, pte_t *ptep,
6668 				     pgprot_t pgprot, unsigned long pfn_base,
6669 				     unsigned long addr_mask, bool writable,
6670 				     bool special)
6671 {
6672 	args->lock = lock;
6673 	args->ptep = ptep;
6674 	args->pfn = pfn_base + ((args->address & ~addr_mask) >> PAGE_SHIFT);
6675 	args->addr_mask = addr_mask;
6676 	args->pgprot = pgprot;
6677 	args->writable = writable;
6678 	args->special = special;
6679 }
6680 
6681 static inline void pfnmap_lockdep_assert(struct vm_area_struct *vma)
6682 {
6683 #ifdef CONFIG_LOCKDEP
6684 	struct file *file = vma->vm_file;
6685 	struct address_space *mapping = file ? file->f_mapping : NULL;
6686 
6687 	if (mapping)
6688 		lockdep_assert(lockdep_is_held(&mapping->i_mmap_rwsem) ||
6689 			       lockdep_is_held(&vma->vm_mm->mmap_lock));
6690 	else
6691 		lockdep_assert(lockdep_is_held(&vma->vm_mm->mmap_lock));
6692 #endif
6693 }
6694 
6695 /**
6696  * follow_pfnmap_start() - Look up a pfn mapping at a user virtual address
6697  * @args: Pointer to struct @follow_pfnmap_args
6698  *
6699  * The caller needs to setup args->vma and args->address to point to the
6700  * virtual address as the target of such lookup.  On a successful return,
6701  * the results will be put into other output fields.
6702  *
6703  * After the caller finished using the fields, the caller must invoke
6704  * another follow_pfnmap_end() to proper releases the locks and resources
6705  * of such look up request.
6706  *
6707  * During the start() and end() calls, the results in @args will be valid
6708  * as proper locks will be held.  After the end() is called, all the fields
6709  * in @follow_pfnmap_args will be invalid to be further accessed.  Further
6710  * use of such information after end() may require proper synchronizations
6711  * by the caller with page table updates, otherwise it can create a
6712  * security bug.
6713  *
6714  * If the PTE maps a refcounted page, callers are responsible to protect
6715  * against invalidation with MMU notifiers; otherwise access to the PFN at
6716  * a later point in time can trigger use-after-free.
6717  *
6718  * Only IO mappings and raw PFN mappings are allowed.  The mmap semaphore
6719  * should be taken for read, and the mmap semaphore cannot be released
6720  * before the end() is invoked.
6721  *
6722  * This function must not be used to modify PTE content.
6723  *
6724  * Return: zero on success, negative otherwise.
6725  */
6726 int follow_pfnmap_start(struct follow_pfnmap_args *args)
6727 {
6728 	struct vm_area_struct *vma = args->vma;
6729 	unsigned long address = args->address;
6730 	struct mm_struct *mm = vma->vm_mm;
6731 	spinlock_t *lock;
6732 	pgd_t *pgdp;
6733 	p4d_t *p4dp, p4d;
6734 	pud_t *pudp, pud;
6735 	pmd_t *pmdp, pmd;
6736 	pte_t *ptep, pte;
6737 
6738 	pfnmap_lockdep_assert(vma);
6739 
6740 	if (unlikely(address < vma->vm_start || address >= vma->vm_end))
6741 		goto out;
6742 
6743 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
6744 		goto out;
6745 retry:
6746 	pgdp = pgd_offset(mm, address);
6747 	if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp)))
6748 		goto out;
6749 
6750 	p4dp = p4d_offset(pgdp, address);
6751 	p4d = READ_ONCE(*p4dp);
6752 	if (p4d_none(p4d) || unlikely(p4d_bad(p4d)))
6753 		goto out;
6754 
6755 	pudp = pud_offset(p4dp, address);
6756 	pud = READ_ONCE(*pudp);
6757 	if (pud_none(pud))
6758 		goto out;
6759 	if (pud_leaf(pud)) {
6760 		lock = pud_lock(mm, pudp);
6761 		if (!unlikely(pud_leaf(pud))) {
6762 			spin_unlock(lock);
6763 			goto retry;
6764 		}
6765 		pfnmap_args_setup(args, lock, NULL, pud_pgprot(pud),
6766 				  pud_pfn(pud), PUD_MASK, pud_write(pud),
6767 				  pud_special(pud));
6768 		return 0;
6769 	}
6770 
6771 	pmdp = pmd_offset(pudp, address);
6772 	pmd = pmdp_get_lockless(pmdp);
6773 	if (pmd_leaf(pmd)) {
6774 		lock = pmd_lock(mm, pmdp);
6775 		if (!unlikely(pmd_leaf(pmd))) {
6776 			spin_unlock(lock);
6777 			goto retry;
6778 		}
6779 		pfnmap_args_setup(args, lock, NULL, pmd_pgprot(pmd),
6780 				  pmd_pfn(pmd), PMD_MASK, pmd_write(pmd),
6781 				  pmd_special(pmd));
6782 		return 0;
6783 	}
6784 
6785 	ptep = pte_offset_map_lock(mm, pmdp, address, &lock);
6786 	if (!ptep)
6787 		goto out;
6788 	pte = ptep_get(ptep);
6789 	if (!pte_present(pte))
6790 		goto unlock;
6791 	pfnmap_args_setup(args, lock, ptep, pte_pgprot(pte),
6792 			  pte_pfn(pte), PAGE_MASK, pte_write(pte),
6793 			  pte_special(pte));
6794 	return 0;
6795 unlock:
6796 	pte_unmap_unlock(ptep, lock);
6797 out:
6798 	return -EINVAL;
6799 }
6800 EXPORT_SYMBOL_GPL(follow_pfnmap_start);
6801 
6802 /**
6803  * follow_pfnmap_end(): End a follow_pfnmap_start() process
6804  * @args: Pointer to struct @follow_pfnmap_args
6805  *
6806  * Must be used in pair of follow_pfnmap_start().  See the start() function
6807  * above for more information.
6808  */
6809 void follow_pfnmap_end(struct follow_pfnmap_args *args)
6810 {
6811 	if (args->lock)
6812 		spin_unlock(args->lock);
6813 	if (args->ptep)
6814 		pte_unmap(args->ptep);
6815 }
6816 EXPORT_SYMBOL_GPL(follow_pfnmap_end);
6817 
6818 #ifdef CONFIG_HAVE_IOREMAP_PROT
6819 /**
6820  * generic_access_phys - generic implementation for iomem mmap access
6821  * @vma: the vma to access
6822  * @addr: userspace address, not relative offset within @vma
6823  * @buf: buffer to read/write
6824  * @len: length of transfer
6825  * @write: set to FOLL_WRITE when writing, otherwise reading
6826  *
6827  * This is a generic implementation for &vm_operations_struct.access for an
6828  * iomem mapping. This callback is used by access_process_vm() when the @vma is
6829  * not page based.
6830  */
6831 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
6832 			void *buf, int len, int write)
6833 {
6834 	resource_size_t phys_addr;
6835 	pgprot_t prot = __pgprot(0);
6836 	void __iomem *maddr;
6837 	int offset = offset_in_page(addr);
6838 	int ret = -EINVAL;
6839 	bool writable;
6840 	struct follow_pfnmap_args args = { .vma = vma, .address = addr };
6841 
6842 retry:
6843 	if (follow_pfnmap_start(&args))
6844 		return -EINVAL;
6845 	prot = args.pgprot;
6846 	phys_addr = (resource_size_t)args.pfn << PAGE_SHIFT;
6847 	writable = args.writable;
6848 	follow_pfnmap_end(&args);
6849 
6850 	if ((write & FOLL_WRITE) && !writable)
6851 		return -EINVAL;
6852 
6853 	maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
6854 	if (!maddr)
6855 		return -ENOMEM;
6856 
6857 	if (follow_pfnmap_start(&args))
6858 		goto out_unmap;
6859 
6860 	if ((pgprot_val(prot) != pgprot_val(args.pgprot)) ||
6861 	    (phys_addr != (args.pfn << PAGE_SHIFT)) ||
6862 	    (writable != args.writable)) {
6863 		follow_pfnmap_end(&args);
6864 		iounmap(maddr);
6865 		goto retry;
6866 	}
6867 
6868 	if (write)
6869 		memcpy_toio(maddr + offset, buf, len);
6870 	else
6871 		memcpy_fromio(buf, maddr + offset, len);
6872 	ret = len;
6873 	follow_pfnmap_end(&args);
6874 out_unmap:
6875 	iounmap(maddr);
6876 
6877 	return ret;
6878 }
6879 EXPORT_SYMBOL_GPL(generic_access_phys);
6880 #endif
6881 
6882 /*
6883  * Access another process' address space as given in mm.
6884  */
6885 static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
6886 			      void *buf, int len, unsigned int gup_flags)
6887 {
6888 	void *old_buf = buf;
6889 	int write = gup_flags & FOLL_WRITE;
6890 
6891 	if (mmap_read_lock_killable(mm))
6892 		return 0;
6893 
6894 	/* Untag the address before looking up the VMA */
6895 	addr = untagged_addr_remote(mm, addr);
6896 
6897 	/* Avoid triggering the temporary warning in __get_user_pages */
6898 	if (!vma_lookup(mm, addr) && !expand_stack(mm, addr))
6899 		return 0;
6900 
6901 	/* ignore errors, just check how much was successfully transferred */
6902 	while (len) {
6903 		int bytes, offset;
6904 		void *maddr;
6905 		struct vm_area_struct *vma = NULL;
6906 		struct page *page = get_user_page_vma_remote(mm, addr,
6907 							     gup_flags, &vma);
6908 
6909 		if (IS_ERR(page)) {
6910 			/* We might need to expand the stack to access it */
6911 			vma = vma_lookup(mm, addr);
6912 			if (!vma) {
6913 				vma = expand_stack(mm, addr);
6914 
6915 				/* mmap_lock was dropped on failure */
6916 				if (!vma)
6917 					return buf - old_buf;
6918 
6919 				/* Try again if stack expansion worked */
6920 				continue;
6921 			}
6922 
6923 			/*
6924 			 * Check if this is a VM_IO | VM_PFNMAP VMA, which
6925 			 * we can access using slightly different code.
6926 			 */
6927 			bytes = 0;
6928 #ifdef CONFIG_HAVE_IOREMAP_PROT
6929 			if (vma->vm_ops && vma->vm_ops->access)
6930 				bytes = vma->vm_ops->access(vma, addr, buf,
6931 							    len, write);
6932 #endif
6933 			if (bytes <= 0)
6934 				break;
6935 		} else {
6936 			bytes = len;
6937 			offset = addr & (PAGE_SIZE-1);
6938 			if (bytes > PAGE_SIZE-offset)
6939 				bytes = PAGE_SIZE-offset;
6940 
6941 			maddr = kmap_local_page(page);
6942 			if (write) {
6943 				copy_to_user_page(vma, page, addr,
6944 						  maddr + offset, buf, bytes);
6945 				set_page_dirty_lock(page);
6946 			} else {
6947 				copy_from_user_page(vma, page, addr,
6948 						    buf, maddr + offset, bytes);
6949 			}
6950 			unmap_and_put_page(page, maddr);
6951 		}
6952 		len -= bytes;
6953 		buf += bytes;
6954 		addr += bytes;
6955 	}
6956 	mmap_read_unlock(mm);
6957 
6958 	return buf - old_buf;
6959 }
6960 
6961 /**
6962  * access_remote_vm - access another process' address space
6963  * @mm:		the mm_struct of the target address space
6964  * @addr:	start address to access
6965  * @buf:	source or destination buffer
6966  * @len:	number of bytes to transfer
6967  * @gup_flags:	flags modifying lookup behaviour
6968  *
6969  * The caller must hold a reference on @mm.
6970  *
6971  * Return: number of bytes copied from source to destination.
6972  */
6973 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
6974 		void *buf, int len, unsigned int gup_flags)
6975 {
6976 	return __access_remote_vm(mm, addr, buf, len, gup_flags);
6977 }
6978 
6979 /*
6980  * Access another process' address space.
6981  * Source/target buffer must be kernel space,
6982  * Do not walk the page table directly, use get_user_pages
6983  */
6984 int access_process_vm(struct task_struct *tsk, unsigned long addr,
6985 		void *buf, int len, unsigned int gup_flags)
6986 {
6987 	struct mm_struct *mm;
6988 	int ret;
6989 
6990 	mm = get_task_mm(tsk);
6991 	if (!mm)
6992 		return 0;
6993 
6994 	ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
6995 
6996 	mmput(mm);
6997 
6998 	return ret;
6999 }
7000 EXPORT_SYMBOL_GPL(access_process_vm);
7001 
7002 #ifdef CONFIG_BPF_SYSCALL
7003 /*
7004  * Copy a string from another process's address space as given in mm.
7005  * If there is any error return -EFAULT.
7006  */
7007 static int __copy_remote_vm_str(struct mm_struct *mm, unsigned long addr,
7008 				void *buf, int len, unsigned int gup_flags)
7009 {
7010 	void *old_buf = buf;
7011 	int err = 0;
7012 
7013 	*(char *)buf = '\0';
7014 
7015 	if (mmap_read_lock_killable(mm))
7016 		return -EFAULT;
7017 
7018 	addr = untagged_addr_remote(mm, addr);
7019 
7020 	/* Avoid triggering the temporary warning in __get_user_pages */
7021 	if (!vma_lookup(mm, addr)) {
7022 		err = -EFAULT;
7023 		goto out;
7024 	}
7025 
7026 	while (len) {
7027 		int bytes, offset, retval;
7028 		void *maddr;
7029 		struct page *page;
7030 		struct vm_area_struct *vma = NULL;
7031 
7032 		page = get_user_page_vma_remote(mm, addr, gup_flags, &vma);
7033 		if (IS_ERR(page)) {
7034 			/*
7035 			 * Treat as a total failure for now until we decide how
7036 			 * to handle the CONFIG_HAVE_IOREMAP_PROT case and
7037 			 * stack expansion.
7038 			 */
7039 			*(char *)buf = '\0';
7040 			err = -EFAULT;
7041 			goto out;
7042 		}
7043 
7044 		bytes = len;
7045 		offset = addr & (PAGE_SIZE - 1);
7046 		if (bytes > PAGE_SIZE - offset)
7047 			bytes = PAGE_SIZE - offset;
7048 
7049 		maddr = kmap_local_page(page);
7050 		retval = strscpy(buf, maddr + offset, bytes);
7051 		if (retval >= 0) {
7052 			/* Found the end of the string */
7053 			buf += retval;
7054 			unmap_and_put_page(page, maddr);
7055 			break;
7056 		}
7057 
7058 		buf += bytes - 1;
7059 		/*
7060 		 * Because strscpy always NUL terminates we need to
7061 		 * copy the last byte in the page if we are going to
7062 		 * load more pages
7063 		 */
7064 		if (bytes != len) {
7065 			addr += bytes - 1;
7066 			copy_from_user_page(vma, page, addr, buf, maddr + (PAGE_SIZE - 1), 1);
7067 			buf += 1;
7068 			addr += 1;
7069 		}
7070 		len -= bytes;
7071 
7072 		unmap_and_put_page(page, maddr);
7073 	}
7074 
7075 out:
7076 	mmap_read_unlock(mm);
7077 	if (err)
7078 		return err;
7079 	return buf - old_buf;
7080 }
7081 
7082 /**
7083  * copy_remote_vm_str - copy a string from another process's address space.
7084  * @tsk:	the task of the target address space
7085  * @addr:	start address to read from
7086  * @buf:	destination buffer
7087  * @len:	number of bytes to copy
7088  * @gup_flags:	flags modifying lookup behaviour
7089  *
7090  * The caller must hold a reference on @mm.
7091  *
7092  * Return: number of bytes copied from @addr (source) to @buf (destination);
7093  * not including the trailing NUL. Always guaranteed to leave NUL-terminated
7094  * buffer. On any error, return -EFAULT.
7095  */
7096 int copy_remote_vm_str(struct task_struct *tsk, unsigned long addr,
7097 		       void *buf, int len, unsigned int gup_flags)
7098 {
7099 	struct mm_struct *mm;
7100 	int ret;
7101 
7102 	if (unlikely(len == 0))
7103 		return 0;
7104 
7105 	mm = get_task_mm(tsk);
7106 	if (!mm) {
7107 		*(char *)buf = '\0';
7108 		return -EFAULT;
7109 	}
7110 
7111 	ret = __copy_remote_vm_str(mm, addr, buf, len, gup_flags);
7112 
7113 	mmput(mm);
7114 
7115 	return ret;
7116 }
7117 EXPORT_SYMBOL_GPL(copy_remote_vm_str);
7118 #endif /* CONFIG_BPF_SYSCALL */
7119 
7120 /*
7121  * Print the name of a VMA.
7122  */
7123 void print_vma_addr(char *prefix, unsigned long ip)
7124 {
7125 	struct mm_struct *mm = current->mm;
7126 	struct vm_area_struct *vma;
7127 
7128 	/*
7129 	 * we might be running from an atomic context so we cannot sleep
7130 	 */
7131 	if (!mmap_read_trylock(mm))
7132 		return;
7133 
7134 	vma = vma_lookup(mm, ip);
7135 	if (vma && vma->vm_file) {
7136 		struct file *f = vma->vm_file;
7137 		ip -= vma->vm_start;
7138 		ip += vma->vm_pgoff << PAGE_SHIFT;
7139 		printk("%s%pD[%lx,%lx+%lx]", prefix, f, ip,
7140 				vma->vm_start,
7141 				vma->vm_end - vma->vm_start);
7142 	}
7143 	mmap_read_unlock(mm);
7144 }
7145 
7146 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
7147 void __might_fault(const char *file, int line)
7148 {
7149 	if (pagefault_disabled())
7150 		return;
7151 	__might_sleep(file, line);
7152 	if (current->mm)
7153 		might_lock_read(&current->mm->mmap_lock);
7154 }
7155 EXPORT_SYMBOL(__might_fault);
7156 #endif
7157 
7158 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
7159 /*
7160  * Process all subpages of the specified huge page with the specified
7161  * operation.  The target subpage will be processed last to keep its
7162  * cache lines hot.
7163  */
7164 static inline int process_huge_page(
7165 	unsigned long addr_hint, unsigned int nr_pages,
7166 	int (*process_subpage)(unsigned long addr, int idx, void *arg),
7167 	void *arg)
7168 {
7169 	int i, n, base, l, ret;
7170 	unsigned long addr = addr_hint &
7171 		~(((unsigned long)nr_pages << PAGE_SHIFT) - 1);
7172 
7173 	/* Process target subpage last to keep its cache lines hot */
7174 	might_sleep();
7175 	n = (addr_hint - addr) / PAGE_SIZE;
7176 	if (2 * n <= nr_pages) {
7177 		/* If target subpage in first half of huge page */
7178 		base = 0;
7179 		l = n;
7180 		/* Process subpages at the end of huge page */
7181 		for (i = nr_pages - 1; i >= 2 * n; i--) {
7182 			cond_resched();
7183 			ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7184 			if (ret)
7185 				return ret;
7186 		}
7187 	} else {
7188 		/* If target subpage in second half of huge page */
7189 		base = nr_pages - 2 * (nr_pages - n);
7190 		l = nr_pages - n;
7191 		/* Process subpages at the begin of huge page */
7192 		for (i = 0; i < base; i++) {
7193 			cond_resched();
7194 			ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7195 			if (ret)
7196 				return ret;
7197 		}
7198 	}
7199 	/*
7200 	 * Process remaining subpages in left-right-left-right pattern
7201 	 * towards the target subpage
7202 	 */
7203 	for (i = 0; i < l; i++) {
7204 		int left_idx = base + i;
7205 		int right_idx = base + 2 * l - 1 - i;
7206 
7207 		cond_resched();
7208 		ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
7209 		if (ret)
7210 			return ret;
7211 		cond_resched();
7212 		ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
7213 		if (ret)
7214 			return ret;
7215 	}
7216 	return 0;
7217 }
7218 
7219 static void clear_gigantic_page(struct folio *folio, unsigned long addr_hint,
7220 				unsigned int nr_pages)
7221 {
7222 	unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(folio));
7223 	int i;
7224 
7225 	might_sleep();
7226 	for (i = 0; i < nr_pages; i++) {
7227 		cond_resched();
7228 		clear_user_highpage(folio_page(folio, i), addr + i * PAGE_SIZE);
7229 	}
7230 }
7231 
7232 static int clear_subpage(unsigned long addr, int idx, void *arg)
7233 {
7234 	struct folio *folio = arg;
7235 
7236 	clear_user_highpage(folio_page(folio, idx), addr);
7237 	return 0;
7238 }
7239 
7240 /**
7241  * folio_zero_user - Zero a folio which will be mapped to userspace.
7242  * @folio: The folio to zero.
7243  * @addr_hint: The address will be accessed or the base address if uncelar.
7244  */
7245 void folio_zero_user(struct folio *folio, unsigned long addr_hint)
7246 {
7247 	unsigned int nr_pages = folio_nr_pages(folio);
7248 
7249 	if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
7250 		clear_gigantic_page(folio, addr_hint, nr_pages);
7251 	else
7252 		process_huge_page(addr_hint, nr_pages, clear_subpage, folio);
7253 }
7254 
7255 static int copy_user_gigantic_page(struct folio *dst, struct folio *src,
7256 				   unsigned long addr_hint,
7257 				   struct vm_area_struct *vma,
7258 				   unsigned int nr_pages)
7259 {
7260 	unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(dst));
7261 	struct page *dst_page;
7262 	struct page *src_page;
7263 	int i;
7264 
7265 	for (i = 0; i < nr_pages; i++) {
7266 		dst_page = folio_page(dst, i);
7267 		src_page = folio_page(src, i);
7268 
7269 		cond_resched();
7270 		if (copy_mc_user_highpage(dst_page, src_page,
7271 					  addr + i*PAGE_SIZE, vma))
7272 			return -EHWPOISON;
7273 	}
7274 	return 0;
7275 }
7276 
7277 struct copy_subpage_arg {
7278 	struct folio *dst;
7279 	struct folio *src;
7280 	struct vm_area_struct *vma;
7281 };
7282 
7283 static int copy_subpage(unsigned long addr, int idx, void *arg)
7284 {
7285 	struct copy_subpage_arg *copy_arg = arg;
7286 	struct page *dst = folio_page(copy_arg->dst, idx);
7287 	struct page *src = folio_page(copy_arg->src, idx);
7288 
7289 	if (copy_mc_user_highpage(dst, src, addr, copy_arg->vma))
7290 		return -EHWPOISON;
7291 	return 0;
7292 }
7293 
7294 int copy_user_large_folio(struct folio *dst, struct folio *src,
7295 			  unsigned long addr_hint, struct vm_area_struct *vma)
7296 {
7297 	unsigned int nr_pages = folio_nr_pages(dst);
7298 	struct copy_subpage_arg arg = {
7299 		.dst = dst,
7300 		.src = src,
7301 		.vma = vma,
7302 	};
7303 
7304 	if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
7305 		return copy_user_gigantic_page(dst, src, addr_hint, vma, nr_pages);
7306 
7307 	return process_huge_page(addr_hint, nr_pages, copy_subpage, &arg);
7308 }
7309 
7310 long copy_folio_from_user(struct folio *dst_folio,
7311 			   const void __user *usr_src,
7312 			   bool allow_pagefault)
7313 {
7314 	void *kaddr;
7315 	unsigned long i, rc = 0;
7316 	unsigned int nr_pages = folio_nr_pages(dst_folio);
7317 	unsigned long ret_val = nr_pages * PAGE_SIZE;
7318 	struct page *subpage;
7319 
7320 	for (i = 0; i < nr_pages; i++) {
7321 		subpage = folio_page(dst_folio, i);
7322 		kaddr = kmap_local_page(subpage);
7323 		if (!allow_pagefault)
7324 			pagefault_disable();
7325 		rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE);
7326 		if (!allow_pagefault)
7327 			pagefault_enable();
7328 		kunmap_local(kaddr);
7329 
7330 		ret_val -= (PAGE_SIZE - rc);
7331 		if (rc)
7332 			break;
7333 
7334 		flush_dcache_page(subpage);
7335 
7336 		cond_resched();
7337 	}
7338 	return ret_val;
7339 }
7340 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
7341 
7342 #if defined(CONFIG_SPLIT_PTE_PTLOCKS) && ALLOC_SPLIT_PTLOCKS
7343 
7344 static struct kmem_cache *page_ptl_cachep;
7345 
7346 void __init ptlock_cache_init(void)
7347 {
7348 	page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
7349 			SLAB_PANIC, NULL);
7350 }
7351 
7352 bool ptlock_alloc(struct ptdesc *ptdesc)
7353 {
7354 	spinlock_t *ptl;
7355 
7356 	ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
7357 	if (!ptl)
7358 		return false;
7359 	ptdesc->ptl = ptl;
7360 	return true;
7361 }
7362 
7363 void ptlock_free(struct ptdesc *ptdesc)
7364 {
7365 	if (ptdesc->ptl)
7366 		kmem_cache_free(page_ptl_cachep, ptdesc->ptl);
7367 }
7368 #endif
7369 
7370 void vma_pgtable_walk_begin(struct vm_area_struct *vma)
7371 {
7372 	if (is_vm_hugetlb_page(vma))
7373 		hugetlb_vma_lock_read(vma);
7374 }
7375 
7376 void vma_pgtable_walk_end(struct vm_area_struct *vma)
7377 {
7378 	if (is_vm_hugetlb_page(vma))
7379 		hugetlb_vma_unlock_read(vma);
7380 }
7381