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