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