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