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