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