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