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