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