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