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