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