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