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