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