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