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