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