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