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