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