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