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 struct swap_info_struct *si = NULL;
3391 bool need_clear_cache = false;
3392 swp_entry_t entry;
3393 pte_t pte;
3394 int locked;
3395 int exclusive = 0;
3396 vm_fault_t ret = 0;
3397 void *shadow = NULL;
3398
3399 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3400 goto out;
3401
3402 entry = pte_to_swp_entry(vmf->orig_pte);
3403 if (unlikely(non_swap_entry(entry))) {
3404 if (is_migration_entry(entry)) {
3405 migration_entry_wait(vma->vm_mm, vmf->pmd,
3406 vmf->address);
3407 } else if (is_device_private_entry(entry)) {
3408 vmf->page = device_private_entry_to_page(entry);
3409 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3410 vmf->address, &vmf->ptl);
3411 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3412 spin_unlock(vmf->ptl);
3413 goto out;
3414 }
3415
3416 /*
3417 * Get a page reference while we know the page can't be
3418 * freed.
3419 */
3420 get_page(vmf->page);
3421 pte_unmap_unlock(vmf->pte, vmf->ptl);
3422 vmf->page->pgmap->ops->migrate_to_ram(vmf);
3423 put_page(vmf->page);
3424 } else if (is_hwpoison_entry(entry)) {
3425 ret = VM_FAULT_HWPOISON;
3426 } else {
3427 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3428 ret = VM_FAULT_SIGBUS;
3429 }
3430 goto out;
3431 }
3432
3433 /* Prevent swapoff from happening to us. */
3434 si = get_swap_device(entry);
3435 if (unlikely(!si))
3436 goto out;
3437
3438 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3439 page = lookup_swap_cache(entry, vma, vmf->address);
3440 swapcache = page;
3441
3442 if (!page) {
3443 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3444 __swap_count(entry) == 1) {
3445 /*
3446 * Prevent parallel swapin from proceeding with
3447 * the cache flag. Otherwise, another thread may
3448 * finish swapin first, free the entry, and swapout
3449 * reusing the same entry. It's undetectable as
3450 * pte_same() returns true due to entry reuse.
3451 */
3452 if (swapcache_prepare(entry)) {
3453 /* Relax a bit to prevent rapid repeated page faults */
3454 schedule_timeout_uninterruptible(1);
3455 goto out;
3456 }
3457 need_clear_cache = true;
3458
3459 /* skip swapcache */
3460 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3461 vmf->address);
3462 if (page) {
3463 int err;
3464
3465 __SetPageLocked(page);
3466 __SetPageSwapBacked(page);
3467 set_page_private(page, entry.val);
3468
3469 /* Tell memcg to use swap ownership records */
3470 SetPageSwapCache(page);
3471 err = mem_cgroup_charge(page, vma->vm_mm,
3472 GFP_KERNEL);
3473 ClearPageSwapCache(page);
3474 if (err) {
3475 ret = VM_FAULT_OOM;
3476 goto out_page;
3477 }
3478
3479 shadow = get_shadow_from_swap_cache(entry);
3480 if (shadow)
3481 workingset_refault(page, shadow);
3482
3483 lru_cache_add(page);
3484 swap_readpage(page, true);
3485 }
3486 } else {
3487 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3488 vmf);
3489 swapcache = page;
3490 }
3491
3492 if (!page) {
3493 /*
3494 * Back out if somebody else faulted in this pte
3495 * while we released the pte lock.
3496 */
3497 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3498 vmf->address, &vmf->ptl);
3499 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3500 ret = VM_FAULT_OOM;
3501 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3502 goto unlock;
3503 }
3504
3505 /* Had to read the page from swap area: Major fault */
3506 ret = VM_FAULT_MAJOR;
3507 count_vm_event(PGMAJFAULT);
3508 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3509 } else if (PageHWPoison(page)) {
3510 /*
3511 * hwpoisoned dirty swapcache pages are kept for killing
3512 * owner processes (which may be unknown at hwpoison time)
3513 */
3514 ret = VM_FAULT_HWPOISON;
3515 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3516 goto out_release;
3517 }
3518
3519 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3520
3521 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3522 if (!locked) {
3523 ret |= VM_FAULT_RETRY;
3524 goto out_release;
3525 }
3526
3527 /*
3528 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3529 * release the swapcache from under us. The page pin, and pte_same
3530 * test below, are not enough to exclude that. Even if it is still
3531 * swapcache, we need to check that the page's swap has not changed.
3532 */
3533 if (unlikely((!PageSwapCache(page) ||
3534 page_private(page) != entry.val)) && swapcache)
3535 goto out_page;
3536
3537 page = ksm_might_need_to_copy(page, vma, vmf->address);
3538 if (unlikely(!page)) {
3539 ret = VM_FAULT_OOM;
3540 page = swapcache;
3541 goto out_page;
3542 }
3543
3544 cgroup_throttle_swaprate(page, GFP_KERNEL);
3545
3546 /*
3547 * Back out if somebody else already faulted in this pte.
3548 */
3549 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3550 &vmf->ptl);
3551 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3552 goto out_nomap;
3553
3554 if (unlikely(!PageUptodate(page))) {
3555 ret = VM_FAULT_SIGBUS;
3556 goto out_nomap;
3557 }
3558
3559 /*
3560 * The page isn't present yet, go ahead with the fault.
3561 *
3562 * Be careful about the sequence of operations here.
3563 * To get its accounting right, reuse_swap_page() must be called
3564 * while the page is counted on swap but not yet in mapcount i.e.
3565 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3566 * must be called after the swap_free(), or it will never succeed.
3567 */
3568 if (unlikely(xpm_integrity_validate_hook(vmf->vma, vmf->flags,
3569 vmf->address, page))){
3570 ret = VM_FAULT_SIGSEGV;
3571 goto out_nomap;
3572 }
3573
3574 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3575 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3576 pte = mk_pte(page, vma->vm_page_prot);
3577 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3578 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3579 vmf->flags &= ~FAULT_FLAG_WRITE;
3580 ret |= VM_FAULT_WRITE;
3581 exclusive = RMAP_EXCLUSIVE;
3582 }
3583 flush_icache_page(vma, page);
3584 if (pte_swp_soft_dirty(vmf->orig_pte))
3585 pte = pte_mksoft_dirty(pte);
3586 if (pte_swp_uffd_wp(vmf->orig_pte)) {
3587 pte = pte_mkuffd_wp(pte);
3588 pte = pte_wrprotect(pte);
3589 }
3590 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3591 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3592 vmf->orig_pte = pte;
3593
3594 /* ksm created a completely new copy */
3595 if (unlikely(page != swapcache && swapcache)) {
3596 page_add_new_anon_rmap(page, vma, vmf->address, false);
3597 lru_cache_add_inactive_or_unevictable(page, vma);
3598 } else {
3599 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3600 }
3601
3602 swap_free(entry);
3603 if (mem_cgroup_swap_full(page) ||
3604 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3605 try_to_free_swap(page);
3606 unlock_page(page);
3607 if (page != swapcache && swapcache) {
3608 /*
3609 * Hold the lock to avoid the swap entry to be reused
3610 * until we take the PT lock for the pte_same() check
3611 * (to avoid false positives from pte_same). For
3612 * further safety release the lock after the swap_free
3613 * so that the swap count won't change under a
3614 * parallel locked swapcache.
3615 */
3616 unlock_page(swapcache);
3617 put_page(swapcache);
3618 }
3619
3620 if (vmf->flags & FAULT_FLAG_WRITE) {
3621 ret |= do_wp_page(vmf);
3622 if (ret & VM_FAULT_ERROR)
3623 ret &= VM_FAULT_ERROR;
3624 goto out;
3625 }
3626
3627 /* No need to invalidate - it was non-present before */
3628 update_mmu_cache(vma, vmf->address, vmf->pte);
3629 unlock:
3630 pte_unmap_unlock(vmf->pte, vmf->ptl);
3631 out:
3632 /* Clear the swap cache pin for direct swapin after PTL unlock */
3633 if (need_clear_cache)
3634 swapcache_clear(si, entry);
3635 if (si)
3636 put_swap_device(si);
3637 return ret;
3638 out_nomap:
3639 pte_unmap_unlock(vmf->pte, vmf->ptl);
3640 out_page:
3641 unlock_page(page);
3642 out_release:
3643 put_page(page);
3644 if (page != swapcache && swapcache) {
3645 unlock_page(swapcache);
3646 put_page(swapcache);
3647 }
3648 if (need_clear_cache)
3649 swapcache_clear(si, entry);
3650 if (si)
3651 put_swap_device(si);
3652 return ret;
3653 }
3654
3655 /*
3656 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3657 * but allow concurrent faults), and pte mapped but not yet locked.
3658 * We return with mmap_lock still held, but pte unmapped and unlocked.
3659 */
do_anonymous_page(struct vm_fault * vmf)3660 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3661 {
3662 struct vm_area_struct *vma = vmf->vma;
3663 struct page *page;
3664 vm_fault_t ret = 0;
3665 pte_t entry;
3666
3667 /* File mapping without ->vm_ops ? */
3668 if (vma->vm_flags & VM_SHARED)
3669 return VM_FAULT_SIGBUS;
3670
3671 /*
3672 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3673 * pte_offset_map() on pmds where a huge pmd might be created
3674 * from a different thread.
3675 *
3676 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3677 * parallel threads are excluded by other means.
3678 *
3679 * Here we only have mmap_read_lock(mm).
3680 */
3681 if (pte_alloc(vma->vm_mm, vmf->pmd))
3682 return VM_FAULT_OOM;
3683
3684 /* See the comment in pte_alloc_one_map() */
3685 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3686 return 0;
3687
3688 /* use extra page table for userexpte */
3689 if (vma->vm_flags & VM_USEREXPTE) {
3690 if (do_uxpte_page_fault(vmf, &entry))
3691 goto oom;
3692
3693 if(xpm_integrity_check_hook(vma, vmf->flags, vmf->address,
3694 pte_page(entry)))
3695 return VM_FAULT_SIGSEGV;
3696 else
3697 goto got_page;
3698 }
3699
3700 /* Use the zero-page for reads */
3701 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3702 !mm_forbids_zeropage(vma->vm_mm)) {
3703 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3704 vma->vm_page_prot));
3705 got_page:
3706 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3707 vmf->address, &vmf->ptl);
3708 if (!pte_none(*vmf->pte)) {
3709 update_mmu_tlb(vma, vmf->address, vmf->pte);
3710 goto unlock;
3711 }
3712 ret = check_stable_address_space(vma->vm_mm);
3713 if (ret)
3714 goto unlock;
3715 /* Deliver the page fault to userland, check inside PT lock */
3716 if (userfaultfd_missing(vma)) {
3717 pte_unmap_unlock(vmf->pte, vmf->ptl);
3718 return handle_userfault(vmf, VM_UFFD_MISSING);
3719 }
3720 goto setpte;
3721 }
3722
3723 /* Allocate our own private page. */
3724 if (unlikely(anon_vma_prepare(vma)))
3725 goto oom;
3726 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3727 if (!page)
3728 goto oom;
3729
3730 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
3731 goto oom_free_page;
3732 cgroup_throttle_swaprate(page, GFP_KERNEL);
3733
3734 /*
3735 * The memory barrier inside __SetPageUptodate makes sure that
3736 * preceding stores to the page contents become visible before
3737 * the set_pte_at() write.
3738 */
3739 __SetPageUptodate(page);
3740
3741 entry = mk_pte(page, vma->vm_page_prot);
3742 entry = pte_sw_mkyoung(entry);
3743 if (vma->vm_flags & VM_WRITE)
3744 entry = pte_mkwrite(pte_mkdirty(entry));
3745
3746 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3747 &vmf->ptl);
3748 if (!pte_none(*vmf->pte)) {
3749 update_mmu_cache(vma, vmf->address, vmf->pte);
3750 goto release;
3751 }
3752
3753 ret = check_stable_address_space(vma->vm_mm);
3754 if (ret)
3755 goto release;
3756
3757 /* Deliver the page fault to userland, check inside PT lock */
3758 if (userfaultfd_missing(vma)) {
3759 pte_unmap_unlock(vmf->pte, vmf->ptl);
3760 put_page(page);
3761 return handle_userfault(vmf, VM_UFFD_MISSING);
3762 }
3763
3764 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3765 page_add_new_anon_rmap(page, vma, vmf->address, false);
3766 if (vma->vm_flags & VM_PURGEABLE)
3767 SetPagePurgeable(page);
3768
3769 lru_cache_add_inactive_or_unevictable(page, vma);
3770 setpte:
3771 if (vma->vm_flags & VM_PURGEABLE)
3772 uxpte_set_present(vma, vmf->address);
3773
3774 if(!pte_special(entry)){
3775 xpm_integrity_update_hook(vma, vmf->flags, page);
3776 }
3777
3778 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3779
3780 /* No need to invalidate - it was non-present before */
3781 update_mmu_cache(vma, vmf->address, vmf->pte);
3782 unlock:
3783 pte_unmap_unlock(vmf->pte, vmf->ptl);
3784 return ret;
3785 release:
3786 put_page(page);
3787 goto unlock;
3788 oom_free_page:
3789 put_page(page);
3790 oom:
3791 return VM_FAULT_OOM;
3792 }
3793
3794 /*
3795 * The mmap_lock must have been held on entry, and may have been
3796 * released depending on flags and vma->vm_ops->fault() return value.
3797 * See filemap_fault() and __lock_page_retry().
3798 */
__do_fault(struct vm_fault * vmf)3799 static vm_fault_t __do_fault(struct vm_fault *vmf)
3800 {
3801 struct vm_area_struct *vma = vmf->vma;
3802 vm_fault_t ret;
3803
3804 /*
3805 * Preallocate pte before we take page_lock because this might lead to
3806 * deadlocks for memcg reclaim which waits for pages under writeback:
3807 * lock_page(A)
3808 * SetPageWriteback(A)
3809 * unlock_page(A)
3810 * lock_page(B)
3811 * lock_page(B)
3812 * pte_alloc_one
3813 * shrink_page_list
3814 * wait_on_page_writeback(A)
3815 * SetPageWriteback(B)
3816 * unlock_page(B)
3817 * # flush A, B to clear the writeback
3818 */
3819 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3820 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3821 if (!vmf->prealloc_pte)
3822 return VM_FAULT_OOM;
3823 smp_wmb(); /* See comment in __pte_alloc() */
3824 }
3825
3826 ret = vma->vm_ops->fault(vmf);
3827 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3828 VM_FAULT_DONE_COW)))
3829 return ret;
3830
3831 if (unlikely(PageHWPoison(vmf->page))) {
3832 struct page *page = vmf->page;
3833 vm_fault_t poisonret = VM_FAULT_HWPOISON;
3834 if (ret & VM_FAULT_LOCKED) {
3835 if (page_mapped(page))
3836 unmap_mapping_pages(page_mapping(page),
3837 page->index, 1, false);
3838 /* Retry if a clean page was removed from the cache. */
3839 if (invalidate_inode_page(page))
3840 poisonret = VM_FAULT_NOPAGE;
3841 unlock_page(page);
3842 }
3843 put_page(page);
3844 vmf->page = NULL;
3845 return poisonret;
3846 }
3847
3848 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3849 lock_page(vmf->page);
3850 else
3851 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3852
3853 return ret;
3854 }
3855
3856 /*
3857 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3858 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3859 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3860 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3861 */
pmd_devmap_trans_unstable(pmd_t * pmd)3862 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3863 {
3864 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3865 }
3866
pte_alloc_one_map(struct vm_fault * vmf)3867 static vm_fault_t pte_alloc_one_map(struct vm_fault *vmf)
3868 {
3869 struct vm_area_struct *vma = vmf->vma;
3870
3871 if (!pmd_none(*vmf->pmd))
3872 goto map_pte;
3873 if (vmf->prealloc_pte) {
3874 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3875 if (unlikely(!pmd_none(*vmf->pmd))) {
3876 spin_unlock(vmf->ptl);
3877 goto map_pte;
3878 }
3879
3880 mm_inc_nr_ptes(vma->vm_mm);
3881 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3882 spin_unlock(vmf->ptl);
3883 vmf->prealloc_pte = NULL;
3884 } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) {
3885 return VM_FAULT_OOM;
3886 }
3887 map_pte:
3888 /*
3889 * If a huge pmd materialized under us just retry later. Use
3890 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3891 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3892 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3893 * running immediately after a huge pmd fault in a different thread of
3894 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3895 * All we have to ensure is that it is a regular pmd that we can walk
3896 * with pte_offset_map() and we can do that through an atomic read in
3897 * C, which is what pmd_trans_unstable() provides.
3898 */
3899 if (pmd_devmap_trans_unstable(vmf->pmd))
3900 return VM_FAULT_NOPAGE;
3901
3902 /*
3903 * At this point we know that our vmf->pmd points to a page of ptes
3904 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3905 * for the duration of the fault. If a racing MADV_DONTNEED runs and
3906 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3907 * be valid and we will re-check to make sure the vmf->pte isn't
3908 * pte_none() under vmf->ptl protection when we return to
3909 * alloc_set_pte().
3910 */
3911 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3912 &vmf->ptl);
3913 return 0;
3914 }
3915
3916 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
deposit_prealloc_pte(struct vm_fault * vmf)3917 static void deposit_prealloc_pte(struct vm_fault *vmf)
3918 {
3919 struct vm_area_struct *vma = vmf->vma;
3920
3921 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3922 /*
3923 * We are going to consume the prealloc table,
3924 * count that as nr_ptes.
3925 */
3926 mm_inc_nr_ptes(vma->vm_mm);
3927 vmf->prealloc_pte = NULL;
3928 }
3929
do_set_pmd(struct vm_fault * vmf,struct page * page)3930 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3931 {
3932 struct vm_area_struct *vma = vmf->vma;
3933 bool write = vmf->flags & FAULT_FLAG_WRITE;
3934 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3935 pmd_t entry;
3936 int i;
3937 vm_fault_t ret = VM_FAULT_FALLBACK;
3938
3939 if (!transhuge_vma_suitable(vma, haddr))
3940 return ret;
3941
3942 page = compound_head(page);
3943 if (compound_order(page) != HPAGE_PMD_ORDER)
3944 return ret;
3945
3946 /*
3947 * Archs like ppc64 need additonal space to store information
3948 * related to pte entry. Use the preallocated table for that.
3949 */
3950 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3951 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3952 if (!vmf->prealloc_pte)
3953 return VM_FAULT_OOM;
3954 smp_wmb(); /* See comment in __pte_alloc() */
3955 }
3956
3957 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3958 if (unlikely(!pmd_none(*vmf->pmd)))
3959 goto out;
3960
3961 for (i = 0; i < HPAGE_PMD_NR; i++)
3962 flush_icache_page(vma, page + i);
3963
3964 entry = mk_huge_pmd(page, vma->vm_page_prot);
3965 if (write)
3966 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3967
3968 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3969 page_add_file_rmap(page, true);
3970 /*
3971 * deposit and withdraw with pmd lock held
3972 */
3973 if (arch_needs_pgtable_deposit())
3974 deposit_prealloc_pte(vmf);
3975
3976 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3977
3978 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3979
3980 /* fault is handled */
3981 ret = 0;
3982 count_vm_event(THP_FILE_MAPPED);
3983 out:
3984 spin_unlock(vmf->ptl);
3985 return ret;
3986 }
3987 #else
do_set_pmd(struct vm_fault * vmf,struct page * page)3988 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3989 {
3990 BUILD_BUG();
3991 return 0;
3992 }
3993 #endif
3994
3995 /**
3996 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3997 * mapping. If needed, the function allocates page table or use pre-allocated.
3998 *
3999 * @vmf: fault environment
4000 * @page: page to map
4001 *
4002 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
4003 * return.
4004 *
4005 * Target users are page handler itself and implementations of
4006 * vm_ops->map_pages.
4007 *
4008 * Return: %0 on success, %VM_FAULT_ code in case of error.
4009 */
alloc_set_pte(struct vm_fault * vmf,struct page * page)4010 vm_fault_t alloc_set_pte(struct vm_fault *vmf, struct page *page)
4011 {
4012 struct vm_area_struct *vma = vmf->vma;
4013 bool write = vmf->flags & FAULT_FLAG_WRITE;
4014 pte_t entry;
4015 vm_fault_t ret;
4016
4017 if (pmd_none(*vmf->pmd) && PageTransCompound(page)) {
4018 ret = do_set_pmd(vmf, page);
4019 if (ret != VM_FAULT_FALLBACK)
4020 return ret;
4021 }
4022
4023 if (!vmf->pte) {
4024 ret = pte_alloc_one_map(vmf);
4025 if (ret)
4026 return ret;
4027 }
4028
4029 /* Re-check under ptl */
4030 if (unlikely(!pte_none(*vmf->pte))) {
4031 update_mmu_tlb(vma, vmf->address, vmf->pte);
4032 return VM_FAULT_NOPAGE;
4033 }
4034
4035 /* check the confliction of xpm integrity flags*/
4036 if (unlikely(xpm_integrity_validate_hook(vmf->vma, vmf->flags,
4037 vmf->address, page)))
4038 return VM_FAULT_SIGSEGV;
4039
4040 flush_icache_page(vma, page);
4041 entry = mk_pte(page, vma->vm_page_prot);
4042 entry = pte_sw_mkyoung(entry);
4043 if (write)
4044 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
4045 /* copy-on-write page */
4046 if (write && !(vma->vm_flags & VM_SHARED)) {
4047 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4048 page_add_new_anon_rmap(page, vma, vmf->address, false);
4049 lru_cache_add_inactive_or_unevictable(page, vma);
4050 } else {
4051 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
4052 page_add_file_rmap(page, false);
4053 }
4054 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
4055
4056 /* no need to invalidate: a not-present page won't be cached */
4057 update_mmu_cache(vma, vmf->address, vmf->pte);
4058
4059 return 0;
4060 }
4061
4062
4063 /**
4064 * finish_fault - finish page fault once we have prepared the page to fault
4065 *
4066 * @vmf: structure describing the fault
4067 *
4068 * This function handles all that is needed to finish a page fault once the
4069 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4070 * given page, adds reverse page mapping, handles memcg charges and LRU
4071 * addition.
4072 *
4073 * The function expects the page to be locked and on success it consumes a
4074 * reference of a page being mapped (for the PTE which maps it).
4075 *
4076 * Return: %0 on success, %VM_FAULT_ code in case of error.
4077 */
finish_fault(struct vm_fault * vmf)4078 vm_fault_t finish_fault(struct vm_fault *vmf)
4079 {
4080 struct page *page;
4081 vm_fault_t ret = 0;
4082
4083 /* Did we COW the page? */
4084 if ((vmf->flags & FAULT_FLAG_WRITE) &&
4085 !(vmf->vma->vm_flags & VM_SHARED))
4086 page = vmf->cow_page;
4087 else
4088 page = vmf->page;
4089
4090 /*
4091 * check even for read faults because we might have lost our CoWed
4092 * page
4093 */
4094 if (!(vmf->vma->vm_flags & VM_SHARED))
4095 ret = check_stable_address_space(vmf->vma->vm_mm);
4096 if (!ret)
4097 ret = alloc_set_pte(vmf, page);
4098 if (vmf->pte)
4099 pte_unmap_unlock(vmf->pte, vmf->ptl);
4100 return ret;
4101 }
4102
4103 static unsigned long fault_around_bytes __read_mostly =
4104 rounddown_pow_of_two(65536);
4105
4106 #ifdef CONFIG_DEBUG_FS
fault_around_bytes_get(void * data,u64 * val)4107 static int fault_around_bytes_get(void *data, u64 *val)
4108 {
4109 *val = fault_around_bytes;
4110 return 0;
4111 }
4112
4113 /*
4114 * fault_around_bytes must be rounded down to the nearest page order as it's
4115 * what do_fault_around() expects to see.
4116 */
fault_around_bytes_set(void * data,u64 val)4117 static int fault_around_bytes_set(void *data, u64 val)
4118 {
4119 if (val / PAGE_SIZE > PTRS_PER_PTE)
4120 return -EINVAL;
4121 if (val > PAGE_SIZE)
4122 fault_around_bytes = rounddown_pow_of_two(val);
4123 else
4124 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4125 return 0;
4126 }
4127 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4128 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4129
fault_around_debugfs(void)4130 static int __init fault_around_debugfs(void)
4131 {
4132 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4133 &fault_around_bytes_fops);
4134 return 0;
4135 }
4136 late_initcall(fault_around_debugfs);
4137 #endif
4138
4139 /*
4140 * do_fault_around() tries to map few pages around the fault address. The hope
4141 * is that the pages will be needed soon and this will lower the number of
4142 * faults to handle.
4143 *
4144 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4145 * not ready to be mapped: not up-to-date, locked, etc.
4146 *
4147 * This function is called with the page table lock taken. In the split ptlock
4148 * case the page table lock only protects only those entries which belong to
4149 * the page table corresponding to the fault address.
4150 *
4151 * This function doesn't cross the VMA boundaries, in order to call map_pages()
4152 * only once.
4153 *
4154 * fault_around_bytes defines how many bytes we'll try to map.
4155 * do_fault_around() expects it to be set to a power of two less than or equal
4156 * to PTRS_PER_PTE.
4157 *
4158 * The virtual address of the area that we map is naturally aligned to
4159 * fault_around_bytes rounded down to the machine page size
4160 * (and therefore to page order). This way it's easier to guarantee
4161 * that we don't cross page table boundaries.
4162 */
do_fault_around(struct vm_fault * vmf)4163 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4164 {
4165 unsigned long address = vmf->address, nr_pages, mask;
4166 pgoff_t start_pgoff = vmf->pgoff;
4167 pgoff_t end_pgoff;
4168 int off;
4169 vm_fault_t ret = 0;
4170
4171 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4172 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4173
4174 vmf->address = max(address & mask, vmf->vma->vm_start);
4175 off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4176 start_pgoff -= off;
4177
4178 /*
4179 * end_pgoff is either the end of the page table, the end of
4180 * the vma or nr_pages from start_pgoff, depending what is nearest.
4181 */
4182 end_pgoff = start_pgoff -
4183 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4184 PTRS_PER_PTE - 1;
4185 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4186 start_pgoff + nr_pages - 1);
4187
4188 if (pmd_none(*vmf->pmd)) {
4189 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4190 if (!vmf->prealloc_pte)
4191 goto out;
4192 smp_wmb(); /* See comment in __pte_alloc() */
4193 }
4194
4195 vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4196
4197 /* Huge page is mapped? Page fault is solved */
4198 if (pmd_trans_huge(*vmf->pmd)) {
4199 ret = VM_FAULT_NOPAGE;
4200 goto out;
4201 }
4202
4203 /* ->map_pages() haven't done anything useful. Cold page cache? */
4204 if (!vmf->pte)
4205 goto out;
4206
4207 /* check if the page fault is solved */
4208 vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
4209 if (!pte_none(*vmf->pte))
4210 ret = VM_FAULT_NOPAGE;
4211 pte_unmap_unlock(vmf->pte, vmf->ptl);
4212 out:
4213 vmf->address = address;
4214 vmf->pte = NULL;
4215 return ret;
4216 }
4217
do_read_fault(struct vm_fault * vmf)4218 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4219 {
4220 struct vm_area_struct *vma = vmf->vma;
4221 vm_fault_t ret = 0;
4222
4223 /*
4224 * Let's call ->map_pages() first and use ->fault() as fallback
4225 * if page by the offset is not ready to be mapped (cold cache or
4226 * something).
4227 */
4228 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
4229 ret = do_fault_around(vmf);
4230 if (ret)
4231 return ret;
4232 }
4233
4234 ret = __do_fault(vmf);
4235 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4236 return ret;
4237
4238 ret |= finish_fault(vmf);
4239 unlock_page(vmf->page);
4240 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4241 put_page(vmf->page);
4242 return ret;
4243 }
4244
do_cow_fault(struct vm_fault * vmf)4245 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4246 {
4247 struct vm_area_struct *vma = vmf->vma;
4248 vm_fault_t ret;
4249
4250 if (unlikely(anon_vma_prepare(vma)))
4251 return VM_FAULT_OOM;
4252
4253 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4254 if (!vmf->cow_page)
4255 return VM_FAULT_OOM;
4256
4257 if (mem_cgroup_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL)) {
4258 put_page(vmf->cow_page);
4259 return VM_FAULT_OOM;
4260 }
4261 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4262
4263 ret = __do_fault(vmf);
4264 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4265 goto uncharge_out;
4266 if (ret & VM_FAULT_DONE_COW)
4267 return ret;
4268
4269 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4270 __SetPageUptodate(vmf->cow_page);
4271
4272 ret |= finish_fault(vmf);
4273 unlock_page(vmf->page);
4274 put_page(vmf->page);
4275 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4276 goto uncharge_out;
4277 return ret;
4278 uncharge_out:
4279 put_page(vmf->cow_page);
4280 return ret;
4281 }
4282
do_shared_fault(struct vm_fault * vmf)4283 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4284 {
4285 struct vm_area_struct *vma = vmf->vma;
4286 vm_fault_t ret, tmp;
4287
4288 ret = __do_fault(vmf);
4289 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4290 return ret;
4291
4292 /*
4293 * Check if the backing address space wants to know that the page is
4294 * about to become writable
4295 */
4296 if (vma->vm_ops->page_mkwrite) {
4297 unlock_page(vmf->page);
4298 tmp = do_page_mkwrite(vmf);
4299 if (unlikely(!tmp ||
4300 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4301 put_page(vmf->page);
4302 return tmp;
4303 }
4304 }
4305
4306 ret |= finish_fault(vmf);
4307 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4308 VM_FAULT_RETRY))) {
4309 unlock_page(vmf->page);
4310 put_page(vmf->page);
4311 return ret;
4312 }
4313
4314 ret |= fault_dirty_shared_page(vmf);
4315 return ret;
4316 }
4317
4318 /*
4319 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4320 * but allow concurrent faults).
4321 * The mmap_lock may have been released depending on flags and our
4322 * return value. See filemap_fault() and __lock_page_or_retry().
4323 * If mmap_lock is released, vma may become invalid (for example
4324 * by other thread calling munmap()).
4325 */
do_fault(struct vm_fault * vmf)4326 static vm_fault_t do_fault(struct vm_fault *vmf)
4327 {
4328 struct vm_area_struct *vma = vmf->vma;
4329 struct mm_struct *vm_mm = vma->vm_mm;
4330 vm_fault_t ret;
4331
4332 /*
4333 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4334 */
4335 if (!vma->vm_ops->fault) {
4336 /*
4337 * If we find a migration pmd entry or a none pmd entry, which
4338 * should never happen, return SIGBUS
4339 */
4340 if (unlikely(!pmd_present(*vmf->pmd)))
4341 ret = VM_FAULT_SIGBUS;
4342 else {
4343 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4344 vmf->pmd,
4345 vmf->address,
4346 &vmf->ptl);
4347 /*
4348 * Make sure this is not a temporary clearing of pte
4349 * by holding ptl and checking again. A R/M/W update
4350 * of pte involves: take ptl, clearing the pte so that
4351 * we don't have concurrent modification by hardware
4352 * followed by an update.
4353 */
4354 if (unlikely(pte_none(*vmf->pte)))
4355 ret = VM_FAULT_SIGBUS;
4356 else
4357 ret = VM_FAULT_NOPAGE;
4358
4359 pte_unmap_unlock(vmf->pte, vmf->ptl);
4360 }
4361 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4362 ret = do_read_fault(vmf);
4363 else if (!(vma->vm_flags & VM_SHARED))
4364 ret = do_cow_fault(vmf);
4365 else
4366 ret = do_shared_fault(vmf);
4367
4368 /* preallocated pagetable is unused: free it */
4369 if (vmf->prealloc_pte) {
4370 pte_free(vm_mm, vmf->prealloc_pte);
4371 vmf->prealloc_pte = NULL;
4372 }
4373 return ret;
4374 }
4375
numa_migrate_prep(struct page * page,struct vm_area_struct * vma,unsigned long addr,int page_nid,int * flags)4376 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4377 unsigned long addr, int page_nid,
4378 int *flags)
4379 {
4380 get_page(page);
4381
4382 count_vm_numa_event(NUMA_HINT_FAULTS);
4383 if (page_nid == numa_node_id()) {
4384 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4385 *flags |= TNF_FAULT_LOCAL;
4386 }
4387
4388 return mpol_misplaced(page, vma, addr);
4389 }
4390
do_numa_page(struct vm_fault * vmf)4391 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4392 {
4393 struct vm_area_struct *vma = vmf->vma;
4394 struct page *page = NULL;
4395 int page_nid = NUMA_NO_NODE;
4396 int last_cpupid;
4397 int target_nid;
4398 bool migrated = false;
4399 pte_t pte, old_pte;
4400 bool was_writable = pte_savedwrite(vmf->orig_pte);
4401 int flags = 0;
4402
4403 /*
4404 * The "pte" at this point cannot be used safely without
4405 * validation through pte_unmap_same(). It's of NUMA type but
4406 * the pfn may be screwed if the read is non atomic.
4407 */
4408 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4409 spin_lock(vmf->ptl);
4410 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4411 pte_unmap_unlock(vmf->pte, vmf->ptl);
4412 goto out;
4413 }
4414
4415 /*
4416 * Make it present again, Depending on how arch implementes non
4417 * accessible ptes, some can allow access by kernel mode.
4418 */
4419 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4420 pte = pte_modify(old_pte, vma->vm_page_prot);
4421 pte = pte_mkyoung(pte);
4422 if (was_writable)
4423 pte = pte_mkwrite(pte);
4424 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4425 update_mmu_cache(vma, vmf->address, vmf->pte);
4426
4427 page = vm_normal_page(vma, vmf->address, pte);
4428 if (!page) {
4429 pte_unmap_unlock(vmf->pte, vmf->ptl);
4430 return 0;
4431 }
4432
4433 /* TODO: handle PTE-mapped THP */
4434 if (PageCompound(page)) {
4435 pte_unmap_unlock(vmf->pte, vmf->ptl);
4436 return 0;
4437 }
4438
4439 /*
4440 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4441 * much anyway since they can be in shared cache state. This misses
4442 * the case where a mapping is writable but the process never writes
4443 * to it but pte_write gets cleared during protection updates and
4444 * pte_dirty has unpredictable behaviour between PTE scan updates,
4445 * background writeback, dirty balancing and application behaviour.
4446 */
4447 if (!pte_write(pte))
4448 flags |= TNF_NO_GROUP;
4449
4450 /*
4451 * Flag if the page is shared between multiple address spaces. This
4452 * is later used when determining whether to group tasks together
4453 */
4454 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4455 flags |= TNF_SHARED;
4456
4457 last_cpupid = page_cpupid_last(page);
4458 page_nid = page_to_nid(page);
4459 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4460 &flags);
4461 pte_unmap_unlock(vmf->pte, vmf->ptl);
4462 if (target_nid == NUMA_NO_NODE) {
4463 put_page(page);
4464 goto out;
4465 }
4466
4467 /* Migrate to the requested node */
4468 migrated = migrate_misplaced_page(page, vma, target_nid);
4469 if (migrated) {
4470 page_nid = target_nid;
4471 flags |= TNF_MIGRATED;
4472 } else
4473 flags |= TNF_MIGRATE_FAIL;
4474
4475 out:
4476 if (page_nid != NUMA_NO_NODE)
4477 task_numa_fault(last_cpupid, page_nid, 1, flags);
4478 return 0;
4479 }
4480
create_huge_pmd(struct vm_fault * vmf)4481 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4482 {
4483 if (vma_is_anonymous(vmf->vma))
4484 return do_huge_pmd_anonymous_page(vmf);
4485 if (vmf->vma->vm_ops->huge_fault)
4486 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4487 return VM_FAULT_FALLBACK;
4488 }
4489
4490 /* `inline' is required to avoid gcc 4.1.2 build error */
wp_huge_pmd(struct vm_fault * vmf,pmd_t orig_pmd)4491 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
4492 {
4493 if (vma_is_anonymous(vmf->vma)) {
4494 if (userfaultfd_huge_pmd_wp(vmf->vma, orig_pmd))
4495 return handle_userfault(vmf, VM_UFFD_WP);
4496 return do_huge_pmd_wp_page(vmf, orig_pmd);
4497 }
4498 if (vmf->vma->vm_ops->huge_fault) {
4499 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4500
4501 if (!(ret & VM_FAULT_FALLBACK))
4502 return ret;
4503 }
4504
4505 /* COW or write-notify handled on pte level: split pmd. */
4506 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4507
4508 return VM_FAULT_FALLBACK;
4509 }
4510
create_huge_pud(struct vm_fault * vmf)4511 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4512 {
4513 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4514 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4515 /* No support for anonymous transparent PUD pages yet */
4516 if (vma_is_anonymous(vmf->vma))
4517 return VM_FAULT_FALLBACK;
4518 if (vmf->vma->vm_ops->huge_fault)
4519 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4520 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4521 return VM_FAULT_FALLBACK;
4522 }
4523
wp_huge_pud(struct vm_fault * vmf,pud_t orig_pud)4524 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4525 {
4526 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4527 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4528 /* No support for anonymous transparent PUD pages yet */
4529 if (vma_is_anonymous(vmf->vma))
4530 goto split;
4531 if (vmf->vma->vm_ops->huge_fault) {
4532 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4533
4534 if (!(ret & VM_FAULT_FALLBACK))
4535 return ret;
4536 }
4537 split:
4538 /* COW or write-notify not handled on PUD level: split pud.*/
4539 __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4540 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
4541 return VM_FAULT_FALLBACK;
4542 }
4543
4544 /*
4545 * These routines also need to handle stuff like marking pages dirty
4546 * and/or accessed for architectures that don't do it in hardware (most
4547 * RISC architectures). The early dirtying is also good on the i386.
4548 *
4549 * There is also a hook called "update_mmu_cache()" that architectures
4550 * with external mmu caches can use to update those (ie the Sparc or
4551 * PowerPC hashed page tables that act as extended TLBs).
4552 *
4553 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4554 * concurrent faults).
4555 *
4556 * The mmap_lock may have been released depending on flags and our return value.
4557 * See filemap_fault() and __lock_page_or_retry().
4558 */
handle_pte_fault(struct vm_fault * vmf)4559 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4560 {
4561 pte_t entry;
4562
4563 if (unlikely(pmd_none(*vmf->pmd))) {
4564 /*
4565 * Leave __pte_alloc() until later: because vm_ops->fault may
4566 * want to allocate huge page, and if we expose page table
4567 * for an instant, it will be difficult to retract from
4568 * concurrent faults and from rmap lookups.
4569 */
4570 vmf->pte = NULL;
4571 } else {
4572 /* See comment in pte_alloc_one_map() */
4573 if (pmd_devmap_trans_unstable(vmf->pmd))
4574 return 0;
4575 /*
4576 * A regular pmd is established and it can't morph into a huge
4577 * pmd from under us anymore at this point because we hold the
4578 * mmap_lock read mode and khugepaged takes it in write mode.
4579 * So now it's safe to run pte_offset_map().
4580 */
4581 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4582 vmf->orig_pte = *vmf->pte;
4583
4584 /*
4585 * some architectures can have larger ptes than wordsize,
4586 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4587 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4588 * accesses. The code below just needs a consistent view
4589 * for the ifs and we later double check anyway with the
4590 * ptl lock held. So here a barrier will do.
4591 */
4592 barrier();
4593 if (pte_none(vmf->orig_pte)) {
4594 pte_unmap(vmf->pte);
4595 vmf->pte = NULL;
4596 }
4597 }
4598
4599 if (!vmf->pte) {
4600 if (vma_is_anonymous(vmf->vma))
4601 return do_anonymous_page(vmf);
4602 else
4603 return do_fault(vmf);
4604 }
4605
4606 if (!pte_present(vmf->orig_pte))
4607 return do_swap_page(vmf);
4608
4609 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4610 return do_numa_page(vmf);
4611
4612 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4613 spin_lock(vmf->ptl);
4614 entry = vmf->orig_pte;
4615 if (unlikely(!pte_same(*vmf->pte, entry))) {
4616 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4617 goto unlock;
4618 }
4619 if (vmf->flags & FAULT_FLAG_WRITE) {
4620 if (!pte_write(entry))
4621 return do_wp_page(vmf);
4622 entry = pte_mkdirty(entry);
4623 }
4624 entry = pte_mkyoung(entry);
4625 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4626 vmf->flags & FAULT_FLAG_WRITE)) {
4627 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4628 } else {
4629 /* Skip spurious TLB flush for retried page fault */
4630 if (vmf->flags & FAULT_FLAG_TRIED)
4631 goto unlock;
4632 /*
4633 * This is needed only for protection faults but the arch code
4634 * is not yet telling us if this is a protection fault or not.
4635 * This still avoids useless tlb flushes for .text page faults
4636 * with threads.
4637 */
4638 if (vmf->flags & FAULT_FLAG_WRITE)
4639 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4640 }
4641 unlock:
4642 pte_unmap_unlock(vmf->pte, vmf->ptl);
4643 return 0;
4644 }
4645
4646 /*
4647 * By the time we get here, we already hold the mm semaphore
4648 *
4649 * The mmap_lock may have been released depending on flags and our
4650 * return value. See filemap_fault() and __lock_page_or_retry().
4651 */
__handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags)4652 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4653 unsigned long address, unsigned int flags)
4654 {
4655 struct vm_fault vmf = {
4656 .vma = vma,
4657 .address = address & PAGE_MASK,
4658 .flags = flags,
4659 .pgoff = linear_page_index(vma, address),
4660 .gfp_mask = __get_fault_gfp_mask(vma),
4661 };
4662 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4663 struct mm_struct *mm = vma->vm_mm;
4664 pgd_t *pgd;
4665 p4d_t *p4d;
4666 vm_fault_t ret;
4667
4668 pgd = pgd_offset(mm, address);
4669 p4d = p4d_alloc(mm, pgd, address);
4670 if (!p4d)
4671 return VM_FAULT_OOM;
4672
4673 vmf.pud = pud_alloc(mm, p4d, address);
4674 if (!vmf.pud)
4675 return VM_FAULT_OOM;
4676 retry_pud:
4677 if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4678 ret = create_huge_pud(&vmf);
4679 if (!(ret & VM_FAULT_FALLBACK))
4680 return ret;
4681 } else {
4682 pud_t orig_pud = *vmf.pud;
4683
4684 barrier();
4685 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4686
4687 /* NUMA case for anonymous PUDs would go here */
4688
4689 if (dirty && !pud_write(orig_pud)) {
4690 ret = wp_huge_pud(&vmf, orig_pud);
4691 if (!(ret & VM_FAULT_FALLBACK))
4692 return ret;
4693 } else {
4694 huge_pud_set_accessed(&vmf, orig_pud);
4695 return 0;
4696 }
4697 }
4698 }
4699
4700 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4701 if (!vmf.pmd)
4702 return VM_FAULT_OOM;
4703
4704 /* Huge pud page fault raced with pmd_alloc? */
4705 if (pud_trans_unstable(vmf.pud))
4706 goto retry_pud;
4707
4708 if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4709 ret = create_huge_pmd(&vmf);
4710 if (!(ret & VM_FAULT_FALLBACK))
4711 return ret;
4712 } else {
4713 pmd_t orig_pmd = *vmf.pmd;
4714
4715 barrier();
4716 if (unlikely(is_swap_pmd(orig_pmd))) {
4717 VM_BUG_ON(thp_migration_supported() &&
4718 !is_pmd_migration_entry(orig_pmd));
4719 if (is_pmd_migration_entry(orig_pmd))
4720 pmd_migration_entry_wait(mm, vmf.pmd);
4721 return 0;
4722 }
4723 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4724 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4725 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4726
4727 if (dirty && !pmd_write(orig_pmd)) {
4728 ret = wp_huge_pmd(&vmf, orig_pmd);
4729 if (!(ret & VM_FAULT_FALLBACK))
4730 return ret;
4731 } else {
4732 huge_pmd_set_accessed(&vmf, orig_pmd);
4733 return 0;
4734 }
4735 }
4736 }
4737
4738 return handle_pte_fault(&vmf);
4739 }
4740
4741 /**
4742 * mm_account_fault - Do page fault accountings
4743 *
4744 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
4745 * of perf event counters, but we'll still do the per-task accounting to
4746 * the task who triggered this page fault.
4747 * @address: the faulted address.
4748 * @flags: the fault flags.
4749 * @ret: the fault retcode.
4750 *
4751 * This will take care of most of the page fault accountings. Meanwhile, it
4752 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
4753 * updates. However note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
4754 * still be in per-arch page fault handlers at the entry of page fault.
4755 */
mm_account_fault(struct pt_regs * regs,unsigned long address,unsigned int flags,vm_fault_t ret)4756 static inline void mm_account_fault(struct pt_regs *regs,
4757 unsigned long address, unsigned int flags,
4758 vm_fault_t ret)
4759 {
4760 bool major;
4761
4762 /*
4763 * We don't do accounting for some specific faults:
4764 *
4765 * - Unsuccessful faults (e.g. when the address wasn't valid). That
4766 * includes arch_vma_access_permitted() failing before reaching here.
4767 * So this is not a "this many hardware page faults" counter. We
4768 * should use the hw profiling for that.
4769 *
4770 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted
4771 * once they're completed.
4772 */
4773 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
4774 return;
4775
4776 /*
4777 * We define the fault as a major fault when the final successful fault
4778 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
4779 * handle it immediately previously).
4780 */
4781 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
4782
4783 if (major)
4784 current->maj_flt++;
4785 else
4786 current->min_flt++;
4787
4788 /*
4789 * If the fault is done for GUP, regs will be NULL. We only do the
4790 * accounting for the per thread fault counters who triggered the
4791 * fault, and we skip the perf event updates.
4792 */
4793 if (!regs)
4794 return;
4795
4796 if (major)
4797 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
4798 else
4799 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
4800 }
4801
4802 /*
4803 * By the time we get here, we already hold the mm semaphore
4804 *
4805 * The mmap_lock may have been released depending on flags and our
4806 * return value. See filemap_fault() and __lock_page_or_retry().
4807 */
handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags,struct pt_regs * regs)4808 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4809 unsigned int flags, struct pt_regs *regs)
4810 {
4811 vm_fault_t ret;
4812
4813 __set_current_state(TASK_RUNNING);
4814
4815 count_vm_event(PGFAULT);
4816 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4817
4818 /* do counter updates before entering really critical section. */
4819 check_sync_rss_stat(current);
4820
4821 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4822 flags & FAULT_FLAG_INSTRUCTION,
4823 flags & FAULT_FLAG_REMOTE))
4824 return VM_FAULT_SIGSEGV;
4825
4826 /*
4827 * Enable the memcg OOM handling for faults triggered in user
4828 * space. Kernel faults are handled more gracefully.
4829 */
4830 if (flags & FAULT_FLAG_USER)
4831 mem_cgroup_enter_user_fault();
4832
4833 if (unlikely(is_vm_hugetlb_page(vma)))
4834 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4835 else
4836 ret = __handle_mm_fault(vma, address, flags);
4837
4838 if (flags & FAULT_FLAG_USER) {
4839 mem_cgroup_exit_user_fault();
4840 /*
4841 * The task may have entered a memcg OOM situation but
4842 * if the allocation error was handled gracefully (no
4843 * VM_FAULT_OOM), there is no need to kill anything.
4844 * Just clean up the OOM state peacefully.
4845 */
4846 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4847 mem_cgroup_oom_synchronize(false);
4848 }
4849
4850 mm_account_fault(regs, address, flags, ret);
4851
4852 return ret;
4853 }
4854 EXPORT_SYMBOL_GPL(handle_mm_fault);
4855
4856 #ifndef __PAGETABLE_P4D_FOLDED
4857 /*
4858 * Allocate p4d page table.
4859 * We've already handled the fast-path in-line.
4860 */
__p4d_alloc(struct mm_struct * mm,pgd_t * pgd,unsigned long address)4861 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4862 {
4863 p4d_t *new = p4d_alloc_one(mm, address);
4864 if (!new)
4865 return -ENOMEM;
4866
4867 smp_wmb(); /* See comment in __pte_alloc */
4868
4869 spin_lock(&mm->page_table_lock);
4870 if (pgd_present(*pgd)) /* Another has populated it */
4871 p4d_free(mm, new);
4872 else
4873 pgd_populate(mm, pgd, new);
4874 spin_unlock(&mm->page_table_lock);
4875 return 0;
4876 }
4877 #endif /* __PAGETABLE_P4D_FOLDED */
4878
4879 #ifndef __PAGETABLE_PUD_FOLDED
4880 /*
4881 * Allocate page upper directory.
4882 * We've already handled the fast-path in-line.
4883 */
__pud_alloc(struct mm_struct * mm,p4d_t * p4d,unsigned long address)4884 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4885 {
4886 pud_t *new = pud_alloc_one(mm, address);
4887 if (!new)
4888 return -ENOMEM;
4889
4890 smp_wmb(); /* See comment in __pte_alloc */
4891
4892 spin_lock(&mm->page_table_lock);
4893 if (!p4d_present(*p4d)) {
4894 mm_inc_nr_puds(mm);
4895 p4d_populate(mm, p4d, new);
4896 } else /* Another has populated it */
4897 pud_free(mm, new);
4898 spin_unlock(&mm->page_table_lock);
4899 return 0;
4900 }
4901 #endif /* __PAGETABLE_PUD_FOLDED */
4902
4903 #ifndef __PAGETABLE_PMD_FOLDED
4904 /*
4905 * Allocate page middle directory.
4906 * We've already handled the fast-path in-line.
4907 */
__pmd_alloc(struct mm_struct * mm,pud_t * pud,unsigned long address)4908 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4909 {
4910 spinlock_t *ptl;
4911 pmd_t *new = pmd_alloc_one(mm, address);
4912 if (!new)
4913 return -ENOMEM;
4914
4915 smp_wmb(); /* See comment in __pte_alloc */
4916
4917 ptl = pud_lock(mm, pud);
4918 if (!pud_present(*pud)) {
4919 mm_inc_nr_pmds(mm);
4920 pud_populate(mm, pud, new);
4921 } else /* Another has populated it */
4922 pmd_free(mm, new);
4923 spin_unlock(ptl);
4924 return 0;
4925 }
4926 #endif /* __PAGETABLE_PMD_FOLDED */
4927
follow_invalidate_pte(struct mm_struct * mm,unsigned long address,struct mmu_notifier_range * range,pte_t ** ptepp,pmd_t ** pmdpp,spinlock_t ** ptlp)4928 int follow_invalidate_pte(struct mm_struct *mm, unsigned long address,
4929 struct mmu_notifier_range *range, pte_t **ptepp,
4930 pmd_t **pmdpp, spinlock_t **ptlp)
4931 {
4932 pgd_t *pgd;
4933 p4d_t *p4d;
4934 pud_t *pud;
4935 pmd_t *pmd;
4936 pte_t *ptep;
4937
4938 pgd = pgd_offset(mm, address);
4939 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4940 goto out;
4941
4942 p4d = p4d_offset(pgd, address);
4943 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4944 goto out;
4945
4946 pud = pud_offset(p4d, address);
4947 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4948 goto out;
4949
4950 pmd = pmd_offset(pud, address);
4951 VM_BUG_ON(pmd_trans_huge(*pmd));
4952
4953 if (pmd_huge(*pmd)) {
4954 if (!pmdpp)
4955 goto out;
4956
4957 if (range) {
4958 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0,
4959 NULL, mm, address & PMD_MASK,
4960 (address & PMD_MASK) + PMD_SIZE);
4961 mmu_notifier_invalidate_range_start(range);
4962 }
4963 *ptlp = pmd_lock(mm, pmd);
4964 if (pmd_huge(*pmd)) {
4965 *pmdpp = pmd;
4966 return 0;
4967 }
4968 spin_unlock(*ptlp);
4969 if (range)
4970 mmu_notifier_invalidate_range_end(range);
4971 }
4972
4973 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4974 goto out;
4975
4976 if (range) {
4977 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
4978 address & PAGE_MASK,
4979 (address & PAGE_MASK) + PAGE_SIZE);
4980 mmu_notifier_invalidate_range_start(range);
4981 }
4982 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4983 if (!pte_present(*ptep))
4984 goto unlock;
4985 *ptepp = ptep;
4986 return 0;
4987 unlock:
4988 pte_unmap_unlock(ptep, *ptlp);
4989 if (range)
4990 mmu_notifier_invalidate_range_end(range);
4991 out:
4992 return -EINVAL;
4993 }
4994
4995 /**
4996 * follow_pte - look up PTE at a user virtual address
4997 * @mm: the mm_struct of the target address space
4998 * @address: user virtual address
4999 * @ptepp: location to store found PTE
5000 * @ptlp: location to store the lock for the PTE
5001 *
5002 * On a successful return, the pointer to the PTE is stored in @ptepp;
5003 * the corresponding lock is taken and its location is stored in @ptlp.
5004 * The contents of the PTE are only stable until @ptlp is released;
5005 * any further use, if any, must be protected against invalidation
5006 * with MMU notifiers.
5007 *
5008 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
5009 * should be taken for read.
5010 *
5011 * KVM uses this function. While it is arguably less bad than ``follow_pfn``,
5012 * it is not a good general-purpose API.
5013 *
5014 * Return: zero on success, -ve otherwise.
5015 */
follow_pte(struct mm_struct * mm,unsigned long address,pte_t ** ptepp,spinlock_t ** ptlp)5016 int follow_pte(struct mm_struct *mm, unsigned long address,
5017 pte_t **ptepp, spinlock_t **ptlp)
5018 {
5019 return follow_invalidate_pte(mm, address, NULL, ptepp, NULL, ptlp);
5020 }
5021 EXPORT_SYMBOL_GPL(follow_pte);
5022
5023 /**
5024 * follow_pfn - look up PFN at a user virtual address
5025 * @vma: memory mapping
5026 * @address: user virtual address
5027 * @pfn: location to store found PFN
5028 *
5029 * Only IO mappings and raw PFN mappings are allowed.
5030 *
5031 * This function does not allow the caller to read the permissions
5032 * of the PTE. Do not use it.
5033 *
5034 * Return: zero and the pfn at @pfn on success, -ve otherwise.
5035 */
follow_pfn(struct vm_area_struct * vma,unsigned long address,unsigned long * pfn)5036 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5037 unsigned long *pfn)
5038 {
5039 int ret = -EINVAL;
5040 spinlock_t *ptl;
5041 pte_t *ptep;
5042
5043 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5044 return ret;
5045
5046 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5047 if (ret)
5048 return ret;
5049 *pfn = pte_pfn(*ptep);
5050 pte_unmap_unlock(ptep, ptl);
5051 return 0;
5052 }
5053 EXPORT_SYMBOL(follow_pfn);
5054
5055 #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)5056 int follow_phys(struct vm_area_struct *vma,
5057 unsigned long address, unsigned int flags,
5058 unsigned long *prot, resource_size_t *phys)
5059 {
5060 int ret = -EINVAL;
5061 pte_t *ptep, pte;
5062 spinlock_t *ptl;
5063
5064 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5065 goto out;
5066
5067 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5068 goto out;
5069 pte = *ptep;
5070
5071 if ((flags & FOLL_WRITE) && !pte_write(pte))
5072 goto unlock;
5073
5074 *prot = pgprot_val(pte_pgprot(pte));
5075 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5076
5077 ret = 0;
5078 unlock:
5079 pte_unmap_unlock(ptep, ptl);
5080 out:
5081 return ret;
5082 }
5083
generic_access_phys(struct vm_area_struct * vma,unsigned long addr,void * buf,int len,int write)5084 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5085 void *buf, int len, int write)
5086 {
5087 resource_size_t phys_addr;
5088 unsigned long prot = 0;
5089 void __iomem *maddr;
5090 int offset = addr & (PAGE_SIZE-1);
5091
5092 if (follow_phys(vma, addr, write, &prot, &phys_addr))
5093 return -EINVAL;
5094
5095 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5096 if (!maddr)
5097 return -ENOMEM;
5098
5099 if (write)
5100 memcpy_toio(maddr + offset, buf, len);
5101 else
5102 memcpy_fromio(buf, maddr + offset, len);
5103 iounmap(maddr);
5104
5105 return len;
5106 }
5107 EXPORT_SYMBOL_GPL(generic_access_phys);
5108 #endif
5109
5110 /*
5111 * Access another process' address space as given in mm. If non-NULL, use the
5112 * given task for page fault accounting.
5113 */
__access_remote_vm(struct task_struct * tsk,struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)5114 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
5115 unsigned long addr, void *buf, int len, unsigned int gup_flags)
5116 {
5117 struct vm_area_struct *vma;
5118 void *old_buf = buf;
5119 int write = gup_flags & FOLL_WRITE;
5120
5121 if (mmap_read_lock_killable(mm))
5122 return 0;
5123
5124 /* ignore errors, just check how much was successfully transferred */
5125 while (len) {
5126 int bytes, ret, offset;
5127 void *maddr;
5128 struct page *page = NULL;
5129
5130 ret = get_user_pages_remote(mm, addr, 1,
5131 gup_flags, &page, &vma, NULL);
5132 if (ret <= 0) {
5133 #ifndef CONFIG_HAVE_IOREMAP_PROT
5134 break;
5135 #else
5136 /*
5137 * Check if this is a VM_IO | VM_PFNMAP VMA, which
5138 * we can access using slightly different code.
5139 */
5140 vma = find_vma(mm, addr);
5141 if (!vma || vma->vm_start > addr)
5142 break;
5143 if (vma->vm_ops && vma->vm_ops->access)
5144 ret = vma->vm_ops->access(vma, addr, buf,
5145 len, write);
5146 if (ret <= 0)
5147 break;
5148 bytes = ret;
5149 #endif
5150 } else {
5151 bytes = len;
5152 offset = addr & (PAGE_SIZE-1);
5153 if (bytes > PAGE_SIZE-offset)
5154 bytes = PAGE_SIZE-offset;
5155
5156 maddr = kmap(page);
5157 if (write) {
5158 copy_to_user_page(vma, page, addr,
5159 maddr + offset, buf, bytes);
5160 set_page_dirty_lock(page);
5161 } else {
5162 copy_from_user_page(vma, page, addr,
5163 buf, maddr + offset, bytes);
5164 }
5165 kunmap(page);
5166 put_page(page);
5167 }
5168 len -= bytes;
5169 buf += bytes;
5170 addr += bytes;
5171 }
5172 mmap_read_unlock(mm);
5173
5174 return buf - old_buf;
5175 }
5176
5177 /**
5178 * access_remote_vm - access another process' address space
5179 * @mm: the mm_struct of the target address space
5180 * @addr: start address to access
5181 * @buf: source or destination buffer
5182 * @len: number of bytes to transfer
5183 * @gup_flags: flags modifying lookup behaviour
5184 *
5185 * The caller must hold a reference on @mm.
5186 *
5187 * Return: number of bytes copied from source to destination.
5188 */
access_remote_vm(struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)5189 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5190 void *buf, int len, unsigned int gup_flags)
5191 {
5192 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
5193 }
5194
5195 /*
5196 * Access another process' address space.
5197 * Source/target buffer must be kernel space,
5198 * Do not walk the page table directly, use get_user_pages
5199 */
access_process_vm(struct task_struct * tsk,unsigned long addr,void * buf,int len,unsigned int gup_flags)5200 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5201 void *buf, int len, unsigned int gup_flags)
5202 {
5203 struct mm_struct *mm;
5204 int ret;
5205
5206 mm = get_task_mm(tsk);
5207 if (!mm)
5208 return 0;
5209
5210 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
5211
5212 mmput(mm);
5213
5214 return ret;
5215 }
5216 EXPORT_SYMBOL_GPL(access_process_vm);
5217
5218 /*
5219 * Print the name of a VMA.
5220 */
print_vma_addr(char * prefix,unsigned long ip)5221 void print_vma_addr(char *prefix, unsigned long ip)
5222 {
5223 struct mm_struct *mm = current->mm;
5224 struct vm_area_struct *vma;
5225
5226 /*
5227 * we might be running from an atomic context so we cannot sleep
5228 */
5229 if (!mmap_read_trylock(mm))
5230 return;
5231
5232 vma = find_vma(mm, ip);
5233 if (vma && vma->vm_file) {
5234 struct file *f = vma->vm_file;
5235 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5236 if (buf) {
5237 char *p;
5238
5239 p = file_path(f, buf, PAGE_SIZE);
5240 if (IS_ERR(p))
5241 p = "?";
5242 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5243 vma->vm_start,
5244 vma->vm_end - vma->vm_start);
5245 free_page((unsigned long)buf);
5246 }
5247 }
5248 mmap_read_unlock(mm);
5249 }
5250
5251 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
__might_fault(const char * file,int line)5252 void __might_fault(const char *file, int line)
5253 {
5254 /*
5255 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
5256 * holding the mmap_lock, this is safe because kernel memory doesn't
5257 * get paged out, therefore we'll never actually fault, and the
5258 * below annotations will generate false positives.
5259 */
5260 if (uaccess_kernel())
5261 return;
5262 if (pagefault_disabled())
5263 return;
5264 __might_sleep(file, line, 0);
5265 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5266 if (current->mm)
5267 might_lock_read(¤t->mm->mmap_lock);
5268 #endif
5269 }
5270 EXPORT_SYMBOL(__might_fault);
5271 #endif
5272
5273 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5274 /*
5275 * Process all subpages of the specified huge page with the specified
5276 * operation. The target subpage will be processed last to keep its
5277 * cache lines hot.
5278 */
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)5279 static inline void process_huge_page(
5280 unsigned long addr_hint, unsigned int pages_per_huge_page,
5281 void (*process_subpage)(unsigned long addr, int idx, void *arg),
5282 void *arg)
5283 {
5284 int i, n, base, l;
5285 unsigned long addr = addr_hint &
5286 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5287
5288 /* Process target subpage last to keep its cache lines hot */
5289 might_sleep();
5290 n = (addr_hint - addr) / PAGE_SIZE;
5291 if (2 * n <= pages_per_huge_page) {
5292 /* If target subpage in first half of huge page */
5293 base = 0;
5294 l = n;
5295 /* Process subpages at the end of huge page */
5296 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5297 cond_resched();
5298 process_subpage(addr + i * PAGE_SIZE, i, arg);
5299 }
5300 } else {
5301 /* If target subpage in second half of huge page */
5302 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5303 l = pages_per_huge_page - n;
5304 /* Process subpages at the begin of huge page */
5305 for (i = 0; i < base; i++) {
5306 cond_resched();
5307 process_subpage(addr + i * PAGE_SIZE, i, arg);
5308 }
5309 }
5310 /*
5311 * Process remaining subpages in left-right-left-right pattern
5312 * towards the target subpage
5313 */
5314 for (i = 0; i < l; i++) {
5315 int left_idx = base + i;
5316 int right_idx = base + 2 * l - 1 - i;
5317
5318 cond_resched();
5319 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5320 cond_resched();
5321 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5322 }
5323 }
5324
clear_gigantic_page(struct page * page,unsigned long addr,unsigned int pages_per_huge_page)5325 static void clear_gigantic_page(struct page *page,
5326 unsigned long addr,
5327 unsigned int pages_per_huge_page)
5328 {
5329 int i;
5330 struct page *p = page;
5331
5332 might_sleep();
5333 for (i = 0; i < pages_per_huge_page;
5334 i++, p = mem_map_next(p, page, i)) {
5335 cond_resched();
5336 clear_user_highpage(p, addr + i * PAGE_SIZE);
5337 }
5338 }
5339
clear_subpage(unsigned long addr,int idx,void * arg)5340 static void clear_subpage(unsigned long addr, int idx, void *arg)
5341 {
5342 struct page *page = arg;
5343
5344 clear_user_highpage(page + idx, addr);
5345 }
5346
clear_huge_page(struct page * page,unsigned long addr_hint,unsigned int pages_per_huge_page)5347 void clear_huge_page(struct page *page,
5348 unsigned long addr_hint, unsigned int pages_per_huge_page)
5349 {
5350 unsigned long addr = addr_hint &
5351 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5352
5353 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5354 clear_gigantic_page(page, addr, pages_per_huge_page);
5355 return;
5356 }
5357
5358 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5359 }
5360
copy_user_gigantic_page(struct page * dst,struct page * src,unsigned long addr,struct vm_area_struct * vma,unsigned int pages_per_huge_page)5361 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5362 unsigned long addr,
5363 struct vm_area_struct *vma,
5364 unsigned int pages_per_huge_page)
5365 {
5366 int i;
5367 struct page *dst_base = dst;
5368 struct page *src_base = src;
5369
5370 for (i = 0; i < pages_per_huge_page; ) {
5371 cond_resched();
5372 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5373
5374 i++;
5375 dst = mem_map_next(dst, dst_base, i);
5376 src = mem_map_next(src, src_base, i);
5377 }
5378 }
5379
5380 struct copy_subpage_arg {
5381 struct page *dst;
5382 struct page *src;
5383 struct vm_area_struct *vma;
5384 };
5385
copy_subpage(unsigned long addr,int idx,void * arg)5386 static void copy_subpage(unsigned long addr, int idx, void *arg)
5387 {
5388 struct copy_subpage_arg *copy_arg = arg;
5389
5390 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5391 addr, copy_arg->vma);
5392 }
5393
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)5394 void copy_user_huge_page(struct page *dst, struct page *src,
5395 unsigned long addr_hint, struct vm_area_struct *vma,
5396 unsigned int pages_per_huge_page)
5397 {
5398 unsigned long addr = addr_hint &
5399 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5400 struct copy_subpage_arg arg = {
5401 .dst = dst,
5402 .src = src,
5403 .vma = vma,
5404 };
5405
5406 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5407 copy_user_gigantic_page(dst, src, addr, vma,
5408 pages_per_huge_page);
5409 return;
5410 }
5411
5412 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5413 }
5414
copy_huge_page_from_user(struct page * dst_page,const void __user * usr_src,unsigned int pages_per_huge_page,bool allow_pagefault)5415 long copy_huge_page_from_user(struct page *dst_page,
5416 const void __user *usr_src,
5417 unsigned int pages_per_huge_page,
5418 bool allow_pagefault)
5419 {
5420 void *src = (void *)usr_src;
5421 void *page_kaddr;
5422 unsigned long i, rc = 0;
5423 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5424 struct page *subpage = dst_page;
5425
5426 for (i = 0; i < pages_per_huge_page;
5427 i++, subpage = mem_map_next(subpage, dst_page, i)) {
5428 if (allow_pagefault)
5429 page_kaddr = kmap(subpage);
5430 else
5431 page_kaddr = kmap_atomic(subpage);
5432 rc = copy_from_user(page_kaddr,
5433 (const void __user *)(src + i * PAGE_SIZE),
5434 PAGE_SIZE);
5435 if (allow_pagefault)
5436 kunmap(subpage);
5437 else
5438 kunmap_atomic(page_kaddr);
5439
5440 ret_val -= (PAGE_SIZE - rc);
5441 if (rc)
5442 break;
5443
5444 flush_dcache_page(subpage);
5445
5446 cond_resched();
5447 }
5448 return ret_val;
5449 }
5450 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5451
5452 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5453
5454 static struct kmem_cache *page_ptl_cachep;
5455
ptlock_cache_init(void)5456 void __init ptlock_cache_init(void)
5457 {
5458 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5459 SLAB_PANIC, NULL);
5460 }
5461
ptlock_alloc(struct page * page)5462 bool ptlock_alloc(struct page *page)
5463 {
5464 spinlock_t *ptl;
5465
5466 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5467 if (!ptl)
5468 return false;
5469 page->ptl = ptl;
5470 return true;
5471 }
5472
ptlock_free(struct page * page)5473 void ptlock_free(struct page *page)
5474 {
5475 kmem_cache_free(page_ptl_cachep, page->ptl);
5476 }
5477 #endif
5478