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