GNU Linux-libre 4.14.262-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 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1310                                 struct vm_area_struct *vma, pmd_t *pmd,
1311                                 unsigned long addr, unsigned long end,
1312                                 struct zap_details *details)
1313 {
1314         struct mm_struct *mm = tlb->mm;
1315         int force_flush = 0;
1316         int rss[NR_MM_COUNTERS];
1317         spinlock_t *ptl;
1318         pte_t *start_pte;
1319         pte_t *pte;
1320         swp_entry_t entry;
1321
1322         tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1323 again:
1324         init_rss_vec(rss);
1325         start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1326         pte = start_pte;
1327         flush_tlb_batched_pending(mm);
1328         arch_enter_lazy_mmu_mode();
1329         do {
1330                 pte_t ptent = *pte;
1331                 if (pte_none(ptent))
1332                         continue;
1333
1334                 if (pte_present(ptent)) {
1335                         struct page *page;
1336
1337                         page = _vm_normal_page(vma, addr, ptent, true);
1338                         if (unlikely(details) && page) {
1339                                 /*
1340                                  * unmap_shared_mapping_pages() wants to
1341                                  * invalidate cache without truncating:
1342                                  * unmap shared but keep private pages.
1343                                  */
1344                                 if (details->check_mapping &&
1345                                     details->check_mapping != page_rmapping(page))
1346                                         continue;
1347                         }
1348                         ptent = ptep_get_and_clear_full(mm, addr, pte,
1349                                                         tlb->fullmm);
1350                         tlb_remove_tlb_entry(tlb, pte, addr);
1351                         if (unlikely(!page))
1352                                 continue;
1353
1354                         if (!PageAnon(page)) {
1355                                 if (pte_dirty(ptent)) {
1356                                         force_flush = 1;
1357                                         set_page_dirty(page);
1358                                 }
1359                                 if (pte_young(ptent) &&
1360                                     likely(!(vma->vm_flags & VM_SEQ_READ)))
1361                                         mark_page_accessed(page);
1362                         }
1363                         rss[mm_counter(page)]--;
1364                         page_remove_rmap(page, false);
1365                         if (unlikely(page_mapcount(page) < 0))
1366                                 print_bad_pte(vma, addr, ptent, page);
1367                         if (unlikely(__tlb_remove_page(tlb, page))) {
1368                                 force_flush = 1;
1369                                 addr += PAGE_SIZE;
1370                                 break;
1371                         }
1372                         continue;
1373                 }
1374
1375                 entry = pte_to_swp_entry(ptent);
1376                 if (non_swap_entry(entry) && is_device_private_entry(entry)) {
1377                         struct page *page = device_private_entry_to_page(entry);
1378
1379                         if (unlikely(details && details->check_mapping)) {
1380                                 /*
1381                                  * unmap_shared_mapping_pages() wants to
1382                                  * invalidate cache without truncating:
1383                                  * unmap shared but keep private pages.
1384                                  */
1385                                 if (details->check_mapping !=
1386                                     page_rmapping(page))
1387                                         continue;
1388                         }
1389
1390                         pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1391                         rss[mm_counter(page)]--;
1392                         page_remove_rmap(page, false);
1393                         put_page(page);
1394                         continue;
1395                 }
1396
1397                 /* If details->check_mapping, we leave swap entries. */
1398                 if (unlikely(details))
1399                         continue;
1400
1401                 entry = pte_to_swp_entry(ptent);
1402                 if (!non_swap_entry(entry))
1403                         rss[MM_SWAPENTS]--;
1404                 else if (is_migration_entry(entry)) {
1405                         struct page *page;
1406
1407                         page = migration_entry_to_page(entry);
1408                         rss[mm_counter(page)]--;
1409                 }
1410                 if (unlikely(!free_swap_and_cache(entry)))
1411                         print_bad_pte(vma, addr, ptent, NULL);
1412                 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1413         } while (pte++, addr += PAGE_SIZE, addr != end);
1414
1415         add_mm_rss_vec(mm, rss);
1416         arch_leave_lazy_mmu_mode();
1417
1418         /* Do the actual TLB flush before dropping ptl */
1419         if (force_flush)
1420                 tlb_flush_mmu_tlbonly(tlb);
1421         pte_unmap_unlock(start_pte, ptl);
1422
1423         /*
1424          * If we forced a TLB flush (either due to running out of
1425          * batch buffers or because we needed to flush dirty TLB
1426          * entries before releasing the ptl), free the batched
1427          * memory too. Restart if we didn't do everything.
1428          */
1429         if (force_flush) {
1430                 force_flush = 0;
1431                 tlb_flush_mmu_free(tlb);
1432                 if (addr != end)
1433                         goto again;
1434         }
1435
1436         return addr;
1437 }
1438
1439 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1440                                 struct vm_area_struct *vma, pud_t *pud,
1441                                 unsigned long addr, unsigned long end,
1442                                 struct zap_details *details)
1443 {
1444         pmd_t *pmd;
1445         unsigned long next;
1446
1447         pmd = pmd_offset(pud, addr);
1448         do {
1449                 next = pmd_addr_end(addr, end);
1450                 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1451                         if (next - addr != HPAGE_PMD_SIZE)
1452                                 __split_huge_pmd(vma, pmd, addr, false, NULL);
1453                         else if (zap_huge_pmd(tlb, vma, pmd, addr))
1454                                 goto next;
1455                         /* fall through */
1456                 }
1457                 /*
1458                  * Here there can be other concurrent MADV_DONTNEED or
1459                  * trans huge page faults running, and if the pmd is
1460                  * none or trans huge it can change under us. This is
1461                  * because MADV_DONTNEED holds the mmap_sem in read
1462                  * mode.
1463                  */
1464                 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1465                         goto next;
1466                 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1467 next:
1468                 cond_resched();
1469         } while (pmd++, addr = next, addr != end);
1470
1471         return addr;
1472 }
1473
1474 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1475                                 struct vm_area_struct *vma, p4d_t *p4d,
1476                                 unsigned long addr, unsigned long end,
1477                                 struct zap_details *details)
1478 {
1479         pud_t *pud;
1480         unsigned long next;
1481
1482         pud = pud_offset(p4d, addr);
1483         do {
1484                 next = pud_addr_end(addr, end);
1485                 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1486                         if (next - addr != HPAGE_PUD_SIZE) {
1487                                 VM_BUG_ON_VMA(!rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1488                                 split_huge_pud(vma, pud, addr);
1489                         } else if (zap_huge_pud(tlb, vma, pud, addr))
1490                                 goto next;
1491                         /* fall through */
1492                 }
1493                 if (pud_none_or_clear_bad(pud))
1494                         continue;
1495                 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1496 next:
1497                 cond_resched();
1498         } while (pud++, addr = next, addr != end);
1499
1500         return addr;
1501 }
1502
1503 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1504                                 struct vm_area_struct *vma, pgd_t *pgd,
1505                                 unsigned long addr, unsigned long end,
1506                                 struct zap_details *details)
1507 {
1508         p4d_t *p4d;
1509         unsigned long next;
1510
1511         p4d = p4d_offset(pgd, addr);
1512         do {
1513                 next = p4d_addr_end(addr, end);
1514                 if (p4d_none_or_clear_bad(p4d))
1515                         continue;
1516                 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1517         } while (p4d++, addr = next, addr != end);
1518
1519         return addr;
1520 }
1521
1522 void unmap_page_range(struct mmu_gather *tlb,
1523                              struct vm_area_struct *vma,
1524                              unsigned long addr, unsigned long end,
1525                              struct zap_details *details)
1526 {
1527         pgd_t *pgd;
1528         unsigned long next;
1529
1530         BUG_ON(addr >= end);
1531         tlb_start_vma(tlb, vma);
1532         pgd = pgd_offset(vma->vm_mm, addr);
1533         do {
1534                 next = pgd_addr_end(addr, end);
1535                 if (pgd_none_or_clear_bad(pgd))
1536                         continue;
1537                 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1538         } while (pgd++, addr = next, addr != end);
1539         tlb_end_vma(tlb, vma);
1540 }
1541
1542
1543 static void unmap_single_vma(struct mmu_gather *tlb,
1544                 struct vm_area_struct *vma, unsigned long start_addr,
1545                 unsigned long end_addr,
1546                 struct zap_details *details)
1547 {
1548         unsigned long start = max(vma->vm_start, start_addr);
1549         unsigned long end;
1550
1551         if (start >= vma->vm_end)
1552                 return;
1553         end = min(vma->vm_end, end_addr);
1554         if (end <= vma->vm_start)
1555                 return;
1556
1557         if (vma->vm_file)
1558                 uprobe_munmap(vma, start, end);
1559
1560         if (unlikely(vma->vm_flags & VM_PFNMAP))
1561                 untrack_pfn(vma, 0, 0);
1562
1563         if (start != end) {
1564                 if (unlikely(is_vm_hugetlb_page(vma))) {
1565                         /*
1566                          * It is undesirable to test vma->vm_file as it
1567                          * should be non-null for valid hugetlb area.
1568                          * However, vm_file will be NULL in the error
1569                          * cleanup path of mmap_region. When
1570                          * hugetlbfs ->mmap method fails,
1571                          * mmap_region() nullifies vma->vm_file
1572                          * before calling this function to clean up.
1573                          * Since no pte has actually been setup, it is
1574                          * safe to do nothing in this case.
1575                          */
1576                         if (vma->vm_file) {
1577                                 i_mmap_lock_write(vma->vm_file->f_mapping);
1578                                 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1579                                 i_mmap_unlock_write(vma->vm_file->f_mapping);
1580                         }
1581                 } else
1582                         unmap_page_range(tlb, vma, start, end, details);
1583         }
1584 }
1585
1586 /**
1587  * unmap_vmas - unmap a range of memory covered by a list of vma's
1588  * @tlb: address of the caller's struct mmu_gather
1589  * @vma: the starting vma
1590  * @start_addr: virtual address at which to start unmapping
1591  * @end_addr: virtual address at which to end unmapping
1592  *
1593  * Unmap all pages in the vma list.
1594  *
1595  * Only addresses between `start' and `end' will be unmapped.
1596  *
1597  * The VMA list must be sorted in ascending virtual address order.
1598  *
1599  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1600  * range after unmap_vmas() returns.  So the only responsibility here is to
1601  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1602  * drops the lock and schedules.
1603  */
1604 void unmap_vmas(struct mmu_gather *tlb,
1605                 struct vm_area_struct *vma, unsigned long start_addr,
1606                 unsigned long end_addr)
1607 {
1608         struct mm_struct *mm = vma->vm_mm;
1609
1610         mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1611         for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1612                 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1613         mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1614 }
1615
1616 /**
1617  * zap_page_range - remove user pages in a given range
1618  * @vma: vm_area_struct holding the applicable pages
1619  * @start: starting address of pages to zap
1620  * @size: number of bytes to zap
1621  *
1622  * Caller must protect the VMA list
1623  */
1624 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1625                 unsigned long size)
1626 {
1627         struct mm_struct *mm = vma->vm_mm;
1628         struct mmu_gather tlb;
1629         unsigned long end = start + size;
1630
1631         lru_add_drain();
1632         tlb_gather_mmu(&tlb, mm, start, end);
1633         update_hiwater_rss(mm);
1634         mmu_notifier_invalidate_range_start(mm, start, end);
1635         for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
1636                 unmap_single_vma(&tlb, vma, start, end, NULL);
1637
1638                 /*
1639                  * zap_page_range does not specify whether mmap_sem should be
1640                  * held for read or write. That allows parallel zap_page_range
1641                  * operations to unmap a PTE and defer a flush meaning that
1642                  * this call observes pte_none and fails to flush the TLB.
1643                  * Rather than adding a complex API, ensure that no stale
1644                  * TLB entries exist when this call returns.
1645                  */
1646                 flush_tlb_range(vma, start, end);
1647         }
1648
1649         mmu_notifier_invalidate_range_end(mm, start, end);
1650         tlb_finish_mmu(&tlb, start, end);
1651 }
1652
1653 /**
1654  * zap_page_range_single - remove user pages in a given range
1655  * @vma: vm_area_struct holding the applicable pages
1656  * @address: starting address of pages to zap
1657  * @size: number of bytes to zap
1658  * @details: details of shared cache invalidation
1659  *
1660  * The range must fit into one VMA.
1661  */
1662 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1663                 unsigned long size, struct zap_details *details)
1664 {
1665         struct mm_struct *mm = vma->vm_mm;
1666         struct mmu_gather tlb;
1667         unsigned long end = address + size;
1668
1669         lru_add_drain();
1670         tlb_gather_mmu(&tlb, mm, address, end);
1671         update_hiwater_rss(mm);
1672         mmu_notifier_invalidate_range_start(mm, address, end);
1673         unmap_single_vma(&tlb, vma, address, end, details);
1674         mmu_notifier_invalidate_range_end(mm, address, end);
1675         tlb_finish_mmu(&tlb, address, end);
1676 }
1677
1678 /**
1679  * zap_vma_ptes - remove ptes mapping the vma
1680  * @vma: vm_area_struct holding ptes to be zapped
1681  * @address: starting address of pages to zap
1682  * @size: number of bytes to zap
1683  *
1684  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1685  *
1686  * The entire address range must be fully contained within the vma.
1687  *
1688  * Returns 0 if successful.
1689  */
1690 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1691                 unsigned long size)
1692 {
1693         if (address < vma->vm_start || address + size > vma->vm_end ||
1694                         !(vma->vm_flags & VM_PFNMAP))
1695                 return -1;
1696         zap_page_range_single(vma, address, size, NULL);
1697         return 0;
1698 }
1699 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1700
1701 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1702                         spinlock_t **ptl)
1703 {
1704         pgd_t *pgd;
1705         p4d_t *p4d;
1706         pud_t *pud;
1707         pmd_t *pmd;
1708
1709         pgd = pgd_offset(mm, addr);
1710         p4d = p4d_alloc(mm, pgd, addr);
1711         if (!p4d)
1712                 return NULL;
1713         pud = pud_alloc(mm, p4d, addr);
1714         if (!pud)
1715                 return NULL;
1716         pmd = pmd_alloc(mm, pud, addr);
1717         if (!pmd)
1718                 return NULL;
1719
1720         VM_BUG_ON(pmd_trans_huge(*pmd));
1721         return pte_alloc_map_lock(mm, pmd, addr, ptl);
1722 }
1723
1724 /*
1725  * This is the old fallback for page remapping.
1726  *
1727  * For historical reasons, it only allows reserved pages. Only
1728  * old drivers should use this, and they needed to mark their
1729  * pages reserved for the old functions anyway.
1730  */
1731 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1732                         struct page *page, pgprot_t prot)
1733 {
1734         struct mm_struct *mm = vma->vm_mm;
1735         int retval;
1736         pte_t *pte;
1737         spinlock_t *ptl;
1738
1739         retval = -EINVAL;
1740         if (PageAnon(page))
1741                 goto out;
1742         retval = -ENOMEM;
1743         flush_dcache_page(page);
1744         pte = get_locked_pte(mm, addr, &ptl);
1745         if (!pte)
1746                 goto out;
1747         retval = -EBUSY;
1748         if (!pte_none(*pte))
1749                 goto out_unlock;
1750
1751         /* Ok, finally just insert the thing.. */
1752         get_page(page);
1753         inc_mm_counter_fast(mm, mm_counter_file(page));
1754         page_add_file_rmap(page, false);
1755         set_pte_at(mm, addr, pte, mk_pte(page, prot));
1756
1757         retval = 0;
1758         pte_unmap_unlock(pte, ptl);
1759         return retval;
1760 out_unlock:
1761         pte_unmap_unlock(pte, ptl);
1762 out:
1763         return retval;
1764 }
1765
1766 /**
1767  * vm_insert_page - insert single page into user vma
1768  * @vma: user vma to map to
1769  * @addr: target user address of this page
1770  * @page: source kernel page
1771  *
1772  * This allows drivers to insert individual pages they've allocated
1773  * into a user vma.
1774  *
1775  * The page has to be a nice clean _individual_ kernel allocation.
1776  * If you allocate a compound page, you need to have marked it as
1777  * such (__GFP_COMP), or manually just split the page up yourself
1778  * (see split_page()).
1779  *
1780  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1781  * took an arbitrary page protection parameter. This doesn't allow
1782  * that. Your vma protection will have to be set up correctly, which
1783  * means that if you want a shared writable mapping, you'd better
1784  * ask for a shared writable mapping!
1785  *
1786  * The page does not need to be reserved.
1787  *
1788  * Usually this function is called from f_op->mmap() handler
1789  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1790  * Caller must set VM_MIXEDMAP on vma if it wants to call this
1791  * function from other places, for example from page-fault handler.
1792  */
1793 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1794                         struct page *page)
1795 {
1796         if (addr < vma->vm_start || addr >= vma->vm_end)
1797                 return -EFAULT;
1798         if (!page_count(page))
1799                 return -EINVAL;
1800         if (!(vma->vm_flags & VM_MIXEDMAP)) {
1801                 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1802                 BUG_ON(vma->vm_flags & VM_PFNMAP);
1803                 vma->vm_flags |= VM_MIXEDMAP;
1804         }
1805         return insert_page(vma, addr, page, vma->vm_page_prot);
1806 }
1807 EXPORT_SYMBOL(vm_insert_page);
1808
1809 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1810                         pfn_t pfn, pgprot_t prot, bool mkwrite)
1811 {
1812         struct mm_struct *mm = vma->vm_mm;
1813         int retval;
1814         pte_t *pte, entry;
1815         spinlock_t *ptl;
1816
1817         retval = -ENOMEM;
1818         pte = get_locked_pte(mm, addr, &ptl);
1819         if (!pte)
1820                 goto out;
1821         retval = -EBUSY;
1822         if (!pte_none(*pte)) {
1823                 if (mkwrite) {
1824                         /*
1825                          * For read faults on private mappings the PFN passed
1826                          * in may not match the PFN we have mapped if the
1827                          * mapped PFN is a writeable COW page.  In the mkwrite
1828                          * case we are creating a writable PTE for a shared
1829                          * mapping and we expect the PFNs to match. If they
1830                          * don't match, we are likely racing with block
1831                          * allocation and mapping invalidation so just skip the
1832                          * update.
1833                          */
1834                         if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1835                                 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1836                                 goto out_unlock;
1837                         }
1838                         entry = pte_mkyoung(*pte);
1839                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1840                         if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1841                                 update_mmu_cache(vma, addr, pte);
1842                 }
1843                 goto out_unlock;
1844         }
1845
1846         /* Ok, finally just insert the thing.. */
1847         if (pfn_t_devmap(pfn))
1848                 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1849         else
1850                 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1851
1852         if (mkwrite) {
1853                 entry = pte_mkyoung(entry);
1854                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1855         }
1856
1857         set_pte_at(mm, addr, pte, entry);
1858         update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1859
1860         retval = 0;
1861 out_unlock:
1862         pte_unmap_unlock(pte, ptl);
1863 out:
1864         return retval;
1865 }
1866
1867 /**
1868  * vm_insert_pfn - insert single pfn into user vma
1869  * @vma: user vma to map to
1870  * @addr: target user address of this page
1871  * @pfn: source kernel pfn
1872  *
1873  * Similar to vm_insert_page, this allows drivers to insert individual pages
1874  * they've allocated into a user vma. Same comments apply.
1875  *
1876  * This function should only be called from a vm_ops->fault handler, and
1877  * in that case the handler should return NULL.
1878  *
1879  * vma cannot be a COW mapping.
1880  *
1881  * As this is called only for pages that do not currently exist, we
1882  * do not need to flush old virtual caches or the TLB.
1883  */
1884 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1885                         unsigned long pfn)
1886 {
1887         return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1888 }
1889 EXPORT_SYMBOL(vm_insert_pfn);
1890
1891 /**
1892  * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1893  * @vma: user vma to map to
1894  * @addr: target user address of this page
1895  * @pfn: source kernel pfn
1896  * @pgprot: pgprot flags for the inserted page
1897  *
1898  * This is exactly like vm_insert_pfn, except that it allows drivers to
1899  * to override pgprot on a per-page basis.
1900  *
1901  * This only makes sense for IO mappings, and it makes no sense for
1902  * cow mappings.  In general, using multiple vmas is preferable;
1903  * vm_insert_pfn_prot should only be used if using multiple VMAs is
1904  * impractical.
1905  */
1906 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1907                         unsigned long pfn, pgprot_t pgprot)
1908 {
1909         int ret;
1910         /*
1911          * Technically, architectures with pte_special can avoid all these
1912          * restrictions (same for remap_pfn_range).  However we would like
1913          * consistency in testing and feature parity among all, so we should
1914          * try to keep these invariants in place for everybody.
1915          */
1916         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1917         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1918                                                 (VM_PFNMAP|VM_MIXEDMAP));
1919         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1920         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1921
1922         if (addr < vma->vm_start || addr >= vma->vm_end)
1923                 return -EFAULT;
1924
1925         if (!pfn_modify_allowed(pfn, pgprot))
1926                 return -EACCES;
1927
1928         track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
1929
1930         ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1931                         false);
1932
1933         return ret;
1934 }
1935 EXPORT_SYMBOL(vm_insert_pfn_prot);
1936
1937 static int __vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1938                         pfn_t pfn, bool mkwrite)
1939 {
1940         pgprot_t pgprot = vma->vm_page_prot;
1941
1942         BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1943
1944         if (addr < vma->vm_start || addr >= vma->vm_end)
1945                 return -EFAULT;
1946
1947         track_pfn_insert(vma, &pgprot, pfn);
1948
1949         if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
1950                 return -EACCES;
1951
1952         /*
1953          * If we don't have pte special, then we have to use the pfn_valid()
1954          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1955          * refcount the page if pfn_valid is true (hence insert_page rather
1956          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
1957          * without pte special, it would there be refcounted as a normal page.
1958          */
1959         if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1960                 struct page *page;
1961
1962                 /*
1963                  * At this point we are committed to insert_page()
1964                  * regardless of whether the caller specified flags that
1965                  * result in pfn_t_has_page() == false.
1966                  */
1967                 page = pfn_to_page(pfn_t_to_pfn(pfn));
1968                 return insert_page(vma, addr, page, pgprot);
1969         }
1970         return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
1971 }
1972
1973 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1974                         pfn_t pfn)
1975 {
1976         return __vm_insert_mixed(vma, addr, pfn, false);
1977
1978 }
1979 EXPORT_SYMBOL(vm_insert_mixed);
1980
1981 int vm_insert_mixed_mkwrite(struct vm_area_struct *vma, unsigned long addr,
1982                         pfn_t pfn)
1983 {
1984         return __vm_insert_mixed(vma, addr, pfn, true);
1985 }
1986 EXPORT_SYMBOL(vm_insert_mixed_mkwrite);
1987
1988 /*
1989  * maps a range of physical memory into the requested pages. the old
1990  * mappings are removed. any references to nonexistent pages results
1991  * in null mappings (currently treated as "copy-on-access")
1992  */
1993 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1994                         unsigned long addr, unsigned long end,
1995                         unsigned long pfn, pgprot_t prot)
1996 {
1997         pte_t *pte, *mapped_pte;
1998         spinlock_t *ptl;
1999         int err = 0;
2000
2001         mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2002         if (!pte)
2003                 return -ENOMEM;
2004         arch_enter_lazy_mmu_mode();
2005         do {
2006                 BUG_ON(!pte_none(*pte));
2007                 if (!pfn_modify_allowed(pfn, prot)) {
2008                         err = -EACCES;
2009                         break;
2010                 }
2011                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2012                 pfn++;
2013         } while (pte++, addr += PAGE_SIZE, addr != end);
2014         arch_leave_lazy_mmu_mode();
2015         pte_unmap_unlock(mapped_pte, ptl);
2016         return err;
2017 }
2018
2019 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2020                         unsigned long addr, unsigned long end,
2021                         unsigned long pfn, pgprot_t prot)
2022 {
2023         pmd_t *pmd;
2024         unsigned long next;
2025         int err;
2026
2027         pfn -= addr >> PAGE_SHIFT;
2028         pmd = pmd_alloc(mm, pud, addr);
2029         if (!pmd)
2030                 return -ENOMEM;
2031         VM_BUG_ON(pmd_trans_huge(*pmd));
2032         do {
2033                 next = pmd_addr_end(addr, end);
2034                 err = remap_pte_range(mm, pmd, addr, next,
2035                                 pfn + (addr >> PAGE_SHIFT), prot);
2036                 if (err)
2037                         return err;
2038         } while (pmd++, addr = next, addr != end);
2039         return 0;
2040 }
2041
2042 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2043                         unsigned long addr, unsigned long end,
2044                         unsigned long pfn, pgprot_t prot)
2045 {
2046         pud_t *pud;
2047         unsigned long next;
2048         int err;
2049
2050         pfn -= addr >> PAGE_SHIFT;
2051         pud = pud_alloc(mm, p4d, addr);
2052         if (!pud)
2053                 return -ENOMEM;
2054         do {
2055                 next = pud_addr_end(addr, end);
2056                 err = remap_pmd_range(mm, pud, addr, next,
2057                                 pfn + (addr >> PAGE_SHIFT), prot);
2058                 if (err)
2059                         return err;
2060         } while (pud++, addr = next, addr != end);
2061         return 0;
2062 }
2063
2064 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2065                         unsigned long addr, unsigned long end,
2066                         unsigned long pfn, pgprot_t prot)
2067 {
2068         p4d_t *p4d;
2069         unsigned long next;
2070         int err;
2071
2072         pfn -= addr >> PAGE_SHIFT;
2073         p4d = p4d_alloc(mm, pgd, addr);
2074         if (!p4d)
2075                 return -ENOMEM;
2076         do {
2077                 next = p4d_addr_end(addr, end);
2078                 err = remap_pud_range(mm, p4d, addr, next,
2079                                 pfn + (addr >> PAGE_SHIFT), prot);
2080                 if (err)
2081                         return err;
2082         } while (p4d++, addr = next, addr != end);
2083         return 0;
2084 }
2085
2086 /**
2087  * remap_pfn_range - remap kernel memory to userspace
2088  * @vma: user vma to map to
2089  * @addr: target user address to start at
2090  * @pfn: physical address of kernel memory
2091  * @size: size of map area
2092  * @prot: page protection flags for this mapping
2093  *
2094  *  Note: this is only safe if the mm semaphore is held when called.
2095  */
2096 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2097                     unsigned long pfn, unsigned long size, pgprot_t prot)
2098 {
2099         pgd_t *pgd;
2100         unsigned long next;
2101         unsigned long end = addr + PAGE_ALIGN(size);
2102         struct mm_struct *mm = vma->vm_mm;
2103         unsigned long remap_pfn = pfn;
2104         int err;
2105
2106         /*
2107          * Physically remapped pages are special. Tell the
2108          * rest of the world about it:
2109          *   VM_IO tells people not to look at these pages
2110          *      (accesses can have side effects).
2111          *   VM_PFNMAP tells the core MM that the base pages are just
2112          *      raw PFN mappings, and do not have a "struct page" associated
2113          *      with them.
2114          *   VM_DONTEXPAND
2115          *      Disable vma merging and expanding with mremap().
2116          *   VM_DONTDUMP
2117          *      Omit vma from core dump, even when VM_IO turned off.
2118          *
2119          * There's a horrible special case to handle copy-on-write
2120          * behaviour that some programs depend on. We mark the "original"
2121          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2122          * See vm_normal_page() for details.
2123          */
2124         if (is_cow_mapping(vma->vm_flags)) {
2125                 if (addr != vma->vm_start || end != vma->vm_end)
2126                         return -EINVAL;
2127                 vma->vm_pgoff = pfn;
2128         }
2129
2130         err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2131         if (err)
2132                 return -EINVAL;
2133
2134         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2135
2136         BUG_ON(addr >= end);
2137         pfn -= addr >> PAGE_SHIFT;
2138         pgd = pgd_offset(mm, addr);
2139         flush_cache_range(vma, addr, end);
2140         do {
2141                 next = pgd_addr_end(addr, end);
2142                 err = remap_p4d_range(mm, pgd, addr, next,
2143                                 pfn + (addr >> PAGE_SHIFT), prot);
2144                 if (err)
2145                         break;
2146         } while (pgd++, addr = next, addr != end);
2147
2148         if (err)
2149                 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2150
2151         return err;
2152 }
2153 EXPORT_SYMBOL(remap_pfn_range);
2154
2155 /**
2156  * vm_iomap_memory - remap memory to userspace
2157  * @vma: user vma to map to
2158  * @start: start of area
2159  * @len: size of area
2160  *
2161  * This is a simplified io_remap_pfn_range() for common driver use. The
2162  * driver just needs to give us the physical memory range to be mapped,
2163  * we'll figure out the rest from the vma information.
2164  *
2165  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2166  * whatever write-combining details or similar.
2167  */
2168 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2169 {
2170         unsigned long vm_len, pfn, pages;
2171
2172         /* Check that the physical memory area passed in looks valid */
2173         if (start + len < start)
2174                 return -EINVAL;
2175         /*
2176          * You *really* shouldn't map things that aren't page-aligned,
2177          * but we've historically allowed it because IO memory might
2178          * just have smaller alignment.
2179          */
2180         len += start & ~PAGE_MASK;
2181         pfn = start >> PAGE_SHIFT;
2182         pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2183         if (pfn + pages < pfn)
2184                 return -EINVAL;
2185
2186         /* We start the mapping 'vm_pgoff' pages into the area */
2187         if (vma->vm_pgoff > pages)
2188                 return -EINVAL;
2189         pfn += vma->vm_pgoff;
2190         pages -= vma->vm_pgoff;
2191
2192         /* Can we fit all of the mapping? */
2193         vm_len = vma->vm_end - vma->vm_start;
2194         if (vm_len >> PAGE_SHIFT > pages)
2195                 return -EINVAL;
2196
2197         /* Ok, let it rip */
2198         return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2199 }
2200 EXPORT_SYMBOL(vm_iomap_memory);
2201
2202 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2203                                      unsigned long addr, unsigned long end,
2204                                      pte_fn_t fn, void *data)
2205 {
2206         pte_t *pte;
2207         int err;
2208         pgtable_t token;
2209         spinlock_t *uninitialized_var(ptl);
2210
2211         pte = (mm == &init_mm) ?
2212                 pte_alloc_kernel(pmd, addr) :
2213                 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2214         if (!pte)
2215                 return -ENOMEM;
2216
2217         BUG_ON(pmd_huge(*pmd));
2218
2219         arch_enter_lazy_mmu_mode();
2220
2221         token = pmd_pgtable(*pmd);
2222
2223         do {
2224                 err = fn(pte++, token, addr, data);
2225                 if (err)
2226                         break;
2227         } while (addr += PAGE_SIZE, addr != end);
2228
2229         arch_leave_lazy_mmu_mode();
2230
2231         if (mm != &init_mm)
2232                 pte_unmap_unlock(pte-1, ptl);
2233         return err;
2234 }
2235
2236 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2237                                      unsigned long addr, unsigned long end,
2238                                      pte_fn_t fn, void *data)
2239 {
2240         pmd_t *pmd;
2241         unsigned long next;
2242         int err;
2243
2244         BUG_ON(pud_huge(*pud));
2245
2246         pmd = pmd_alloc(mm, pud, addr);
2247         if (!pmd)
2248                 return -ENOMEM;
2249         do {
2250                 next = pmd_addr_end(addr, end);
2251                 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2252                 if (err)
2253                         break;
2254         } while (pmd++, addr = next, addr != end);
2255         return err;
2256 }
2257
2258 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2259                                      unsigned long addr, unsigned long end,
2260                                      pte_fn_t fn, void *data)
2261 {
2262         pud_t *pud;
2263         unsigned long next;
2264         int err;
2265
2266         pud = pud_alloc(mm, p4d, addr);
2267         if (!pud)
2268                 return -ENOMEM;
2269         do {
2270                 next = pud_addr_end(addr, end);
2271                 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2272                 if (err)
2273                         break;
2274         } while (pud++, addr = next, addr != end);
2275         return err;
2276 }
2277
2278 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2279                                      unsigned long addr, unsigned long end,
2280                                      pte_fn_t fn, void *data)
2281 {
2282         p4d_t *p4d;
2283         unsigned long next;
2284         int err;
2285
2286         p4d = p4d_alloc(mm, pgd, addr);
2287         if (!p4d)
2288                 return -ENOMEM;
2289         do {
2290                 next = p4d_addr_end(addr, end);
2291                 err = apply_to_pud_range(mm, p4d, addr, next, fn, data);
2292                 if (err)
2293                         break;
2294         } while (p4d++, addr = next, addr != end);
2295         return err;
2296 }
2297
2298 /*
2299  * Scan a region of virtual memory, filling in page tables as necessary
2300  * and calling a provided function on each leaf page table.
2301  */
2302 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2303                         unsigned long size, pte_fn_t fn, void *data)
2304 {
2305         pgd_t *pgd;
2306         unsigned long next;
2307         unsigned long end = addr + size;
2308         int err;
2309
2310         if (WARN_ON(addr >= end))
2311                 return -EINVAL;
2312
2313         pgd = pgd_offset(mm, addr);
2314         do {
2315                 next = pgd_addr_end(addr, end);
2316                 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data);
2317                 if (err)
2318                         break;
2319         } while (pgd++, addr = next, addr != end);
2320
2321         return err;
2322 }
2323 EXPORT_SYMBOL_GPL(apply_to_page_range);
2324
2325 /*
2326  * handle_pte_fault chooses page fault handler according to an entry which was
2327  * read non-atomically.  Before making any commitment, on those architectures
2328  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2329  * parts, do_swap_page must check under lock before unmapping the pte and
2330  * proceeding (but do_wp_page is only called after already making such a check;
2331  * and do_anonymous_page can safely check later on).
2332  */
2333 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2334                                 pte_t *page_table, pte_t orig_pte)
2335 {
2336         int same = 1;
2337 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2338         if (sizeof(pte_t) > sizeof(unsigned long)) {
2339                 spinlock_t *ptl = pte_lockptr(mm, pmd);
2340                 spin_lock(ptl);
2341                 same = pte_same(*page_table, orig_pte);
2342                 spin_unlock(ptl);
2343         }
2344 #endif
2345         pte_unmap(page_table);
2346         return same;
2347 }
2348
2349 static inline bool cow_user_page(struct page *dst, struct page *src,
2350                                  struct vm_fault *vmf)
2351 {
2352         bool ret;
2353         void *kaddr;
2354         void __user *uaddr;
2355         bool locked = false;
2356         struct vm_area_struct *vma = vmf->vma;
2357         struct mm_struct *mm = vma->vm_mm;
2358         unsigned long addr = vmf->address;
2359
2360         debug_dma_assert_idle(src);
2361
2362         if (likely(src)) {
2363                 copy_user_highpage(dst, src, addr, vma);
2364                 return true;
2365         }
2366
2367         /*
2368          * If the source page was a PFN mapping, we don't have
2369          * a "struct page" for it. We do a best-effort copy by
2370          * just copying from the original user address. If that
2371          * fails, we just zero-fill it. Live with it.
2372          */
2373         kaddr = kmap_atomic(dst);
2374         uaddr = (void __user *)(addr & PAGE_MASK);
2375
2376         /*
2377          * On architectures with software "accessed" bits, we would
2378          * take a double page fault, so mark it accessed here.
2379          */
2380         if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2381                 pte_t entry;
2382
2383                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2384                 locked = true;
2385                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2386                         /*
2387                          * Other thread has already handled the fault
2388                          * and we don't need to do anything. If it's
2389                          * not the case, the fault will be triggered
2390                          * again on the same address.
2391                          */
2392                         ret = false;
2393                         goto pte_unlock;
2394                 }
2395
2396                 entry = pte_mkyoung(vmf->orig_pte);
2397                 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2398                         update_mmu_cache(vma, addr, vmf->pte);
2399         }
2400
2401         /*
2402          * This really shouldn't fail, because the page is there
2403          * in the page tables. But it might just be unreadable,
2404          * in which case we just give up and fill the result with
2405          * zeroes.
2406          */
2407         if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2408                 if (locked)
2409                         goto warn;
2410
2411                 /* Re-validate under PTL if the page is still mapped */
2412                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2413                 locked = true;
2414                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2415                         /* The PTE changed under us. Retry page fault. */
2416                         ret = false;
2417                         goto pte_unlock;
2418                 }
2419
2420                 /*
2421                  * The same page can be mapped back since last copy attampt.
2422                  * Try to copy again under PTL.
2423                  */
2424                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2425                         /*
2426                          * Give a warn in case there can be some obscure
2427                          * use-case
2428                          */
2429 warn:
2430                         WARN_ON_ONCE(1);
2431                         clear_page(kaddr);
2432                 }
2433         }
2434
2435         ret = true;
2436
2437 pte_unlock:
2438         if (locked)
2439                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2440         kunmap_atomic(kaddr);
2441         flush_dcache_page(dst);
2442
2443         return ret;
2444 }
2445
2446 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2447 {
2448         struct file *vm_file = vma->vm_file;
2449
2450         if (vm_file)
2451                 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2452
2453         /*
2454          * Special mappings (e.g. VDSO) do not have any file so fake
2455          * a default GFP_KERNEL for them.
2456          */
2457         return GFP_KERNEL;
2458 }
2459
2460 /*
2461  * Notify the address space that the page is about to become writable so that
2462  * it can prohibit this or wait for the page to get into an appropriate state.
2463  *
2464  * We do this without the lock held, so that it can sleep if it needs to.
2465  */
2466 static int do_page_mkwrite(struct vm_fault *vmf)
2467 {
2468         int ret;
2469         struct page *page = vmf->page;
2470         unsigned int old_flags = vmf->flags;
2471
2472         vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2473
2474         ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2475         /* Restore original flags so that caller is not surprised */
2476         vmf->flags = old_flags;
2477         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2478                 return ret;
2479         if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2480                 lock_page(page);
2481                 if (!page->mapping) {
2482                         unlock_page(page);
2483                         return 0; /* retry */
2484                 }
2485                 ret |= VM_FAULT_LOCKED;
2486         } else
2487                 VM_BUG_ON_PAGE(!PageLocked(page), page);
2488         return ret;
2489 }
2490
2491 /*
2492  * Handle dirtying of a page in shared file mapping on a write fault.
2493  *
2494  * The function expects the page to be locked and unlocks it.
2495  */
2496 static void fault_dirty_shared_page(struct vm_area_struct *vma,
2497                                     struct page *page)
2498 {
2499         struct address_space *mapping;
2500         bool dirtied;
2501         bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2502
2503         dirtied = set_page_dirty(page);
2504         VM_BUG_ON_PAGE(PageAnon(page), page);
2505         /*
2506          * Take a local copy of the address_space - page.mapping may be zeroed
2507          * by truncate after unlock_page().   The address_space itself remains
2508          * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
2509          * release semantics to prevent the compiler from undoing this copying.
2510          */
2511         mapping = page_rmapping(page);
2512         unlock_page(page);
2513
2514         if ((dirtied || page_mkwrite) && mapping) {
2515                 /*
2516                  * Some device drivers do not set page.mapping
2517                  * but still dirty their pages
2518                  */
2519                 balance_dirty_pages_ratelimited(mapping);
2520         }
2521
2522         if (!page_mkwrite)
2523                 file_update_time(vma->vm_file);
2524 }
2525
2526 /*
2527  * Handle write page faults for pages that can be reused in the current vma
2528  *
2529  * This can happen either due to the mapping being with the VM_SHARED flag,
2530  * or due to us being the last reference standing to the page. In either
2531  * case, all we need to do here is to mark the page as writable and update
2532  * any related book-keeping.
2533  */
2534 static inline void wp_page_reuse(struct vm_fault *vmf)
2535         __releases(vmf->ptl)
2536 {
2537         struct vm_area_struct *vma = vmf->vma;
2538         struct page *page = vmf->page;
2539         pte_t entry;
2540         /*
2541          * Clear the pages cpupid information as the existing
2542          * information potentially belongs to a now completely
2543          * unrelated process.
2544          */
2545         if (page)
2546                 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2547
2548         flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2549         entry = pte_mkyoung(vmf->orig_pte);
2550         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2551         if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2552                 update_mmu_cache(vma, vmf->address, vmf->pte);
2553         pte_unmap_unlock(vmf->pte, vmf->ptl);
2554 }
2555
2556 /*
2557  * Handle the case of a page which we actually need to copy to a new page.
2558  *
2559  * Called with mmap_sem locked and the old page referenced, but
2560  * without the ptl held.
2561  *
2562  * High level logic flow:
2563  *
2564  * - Allocate a page, copy the content of the old page to the new one.
2565  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2566  * - Take the PTL. If the pte changed, bail out and release the allocated page
2567  * - If the pte is still the way we remember it, update the page table and all
2568  *   relevant references. This includes dropping the reference the page-table
2569  *   held to the old page, as well as updating the rmap.
2570  * - In any case, unlock the PTL and drop the reference we took to the old page.
2571  */
2572 static int wp_page_copy(struct vm_fault *vmf)
2573 {
2574         struct vm_area_struct *vma = vmf->vma;
2575         struct mm_struct *mm = vma->vm_mm;
2576         struct page *old_page = vmf->page;
2577         struct page *new_page = NULL;
2578         pte_t entry;
2579         int page_copied = 0;
2580         const unsigned long mmun_start = vmf->address & PAGE_MASK;
2581         const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2582         struct mem_cgroup *memcg;
2583
2584         if (unlikely(anon_vma_prepare(vma)))
2585                 goto oom;
2586
2587         if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2588                 new_page = alloc_zeroed_user_highpage_movable(vma,
2589                                                               vmf->address);
2590                 if (!new_page)
2591                         goto oom;
2592         } else {
2593                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2594                                 vmf->address);
2595                 if (!new_page)
2596                         goto oom;
2597
2598                 if (!cow_user_page(new_page, old_page, vmf)) {
2599                         /*
2600                          * COW failed, if the fault was solved by other,
2601                          * it's fine. If not, userspace would re-fault on
2602                          * the same address and we will handle the fault
2603                          * from the second attempt.
2604                          */
2605                         put_page(new_page);
2606                         if (old_page)
2607                                 put_page(old_page);
2608                         return 0;
2609                 }
2610         }
2611
2612         if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
2613                 goto oom_free_new;
2614
2615         __SetPageUptodate(new_page);
2616
2617         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2618
2619         /*
2620          * Re-check the pte - we dropped the lock
2621          */
2622         vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2623         if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2624                 if (old_page) {
2625                         if (!PageAnon(old_page)) {
2626                                 dec_mm_counter_fast(mm,
2627                                                 mm_counter_file(old_page));
2628                                 inc_mm_counter_fast(mm, MM_ANONPAGES);
2629                         }
2630                 } else {
2631                         inc_mm_counter_fast(mm, MM_ANONPAGES);
2632                 }
2633                 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2634                 entry = mk_pte(new_page, vma->vm_page_prot);
2635                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2636                 /*
2637                  * Clear the pte entry and flush it first, before updating the
2638                  * pte with the new entry. This will avoid a race condition
2639                  * seen in the presence of one thread doing SMC and another
2640                  * thread doing COW.
2641                  */
2642                 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2643                 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2644                 mem_cgroup_commit_charge(new_page, memcg, false, false);
2645                 lru_cache_add_active_or_unevictable(new_page, vma);
2646                 /*
2647                  * We call the notify macro here because, when using secondary
2648                  * mmu page tables (such as kvm shadow page tables), we want the
2649                  * new page to be mapped directly into the secondary page table.
2650                  */
2651                 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2652                 update_mmu_cache(vma, vmf->address, vmf->pte);
2653                 if (old_page) {
2654                         /*
2655                          * Only after switching the pte to the new page may
2656                          * we remove the mapcount here. Otherwise another
2657                          * process may come and find the rmap count decremented
2658                          * before the pte is switched to the new page, and
2659                          * "reuse" the old page writing into it while our pte
2660                          * here still points into it and can be read by other
2661                          * threads.
2662                          *
2663                          * The critical issue is to order this
2664                          * page_remove_rmap with the ptp_clear_flush above.
2665                          * Those stores are ordered by (if nothing else,)
2666                          * the barrier present in the atomic_add_negative
2667                          * in page_remove_rmap.
2668                          *
2669                          * Then the TLB flush in ptep_clear_flush ensures that
2670                          * no process can access the old page before the
2671                          * decremented mapcount is visible. And the old page
2672                          * cannot be reused until after the decremented
2673                          * mapcount is visible. So transitively, TLBs to
2674                          * old page will be flushed before it can be reused.
2675                          */
2676                         page_remove_rmap(old_page, false);
2677                 }
2678
2679                 /* Free the old page.. */
2680                 new_page = old_page;
2681                 page_copied = 1;
2682         } else {
2683                 mem_cgroup_cancel_charge(new_page, memcg, false);
2684         }
2685
2686         if (new_page)
2687                 put_page(new_page);
2688
2689         pte_unmap_unlock(vmf->pte, vmf->ptl);
2690         mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2691         if (old_page) {
2692                 /*
2693                  * Don't let another task, with possibly unlocked vma,
2694                  * keep the mlocked page.
2695                  */
2696                 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2697                         lock_page(old_page);    /* LRU manipulation */
2698                         if (PageMlocked(old_page))
2699                                 munlock_vma_page(old_page);
2700                         unlock_page(old_page);
2701                 }
2702                 put_page(old_page);
2703         }
2704         return page_copied ? VM_FAULT_WRITE : 0;
2705 oom_free_new:
2706         put_page(new_page);
2707 oom:
2708         if (old_page)
2709                 put_page(old_page);
2710         return VM_FAULT_OOM;
2711 }
2712
2713 /**
2714  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
2715  *                        writeable once the page is prepared
2716  *
2717  * @vmf: structure describing the fault
2718  *
2719  * This function handles all that is needed to finish a write page fault in a
2720  * shared mapping due to PTE being read-only once the mapped page is prepared.
2721  * It handles locking of PTE and modifying it. The function returns
2722  * VM_FAULT_WRITE on success, 0 when PTE got changed before we acquired PTE
2723  * lock.
2724  *
2725  * The function expects the page to be locked or other protection against
2726  * concurrent faults / writeback (such as DAX radix tree locks).
2727  */
2728 int finish_mkwrite_fault(struct vm_fault *vmf)
2729 {
2730         WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
2731         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
2732                                        &vmf->ptl);
2733         /*
2734          * We might have raced with another page fault while we released the
2735          * pte_offset_map_lock.
2736          */
2737         if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2738                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2739                 return VM_FAULT_NOPAGE;
2740         }
2741         wp_page_reuse(vmf);
2742         return 0;
2743 }
2744
2745 /*
2746  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2747  * mapping
2748  */
2749 static int wp_pfn_shared(struct vm_fault *vmf)
2750 {
2751         struct vm_area_struct *vma = vmf->vma;
2752
2753         if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2754                 int ret;
2755
2756                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2757                 vmf->flags |= FAULT_FLAG_MKWRITE;
2758                 ret = vma->vm_ops->pfn_mkwrite(vmf);
2759                 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2760                         return ret;
2761                 return finish_mkwrite_fault(vmf);
2762         }
2763         wp_page_reuse(vmf);
2764         return VM_FAULT_WRITE;
2765 }
2766
2767 static int wp_page_shared(struct vm_fault *vmf)
2768         __releases(vmf->ptl)
2769 {
2770         struct vm_area_struct *vma = vmf->vma;
2771
2772         get_page(vmf->page);
2773
2774         if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2775                 int tmp;
2776
2777                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2778                 tmp = do_page_mkwrite(vmf);
2779                 if (unlikely(!tmp || (tmp &
2780                                       (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2781                         put_page(vmf->page);
2782                         return tmp;
2783                 }
2784                 tmp = finish_mkwrite_fault(vmf);
2785                 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2786                         unlock_page(vmf->page);
2787                         put_page(vmf->page);
2788                         return tmp;
2789                 }
2790         } else {
2791                 wp_page_reuse(vmf);
2792                 lock_page(vmf->page);
2793         }
2794         fault_dirty_shared_page(vma, vmf->page);
2795         put_page(vmf->page);
2796
2797         return VM_FAULT_WRITE;
2798 }
2799
2800 /*
2801  * This routine handles present pages, when users try to write
2802  * to a shared page. It is done by copying the page to a new address
2803  * and decrementing the shared-page counter for the old page.
2804  *
2805  * Note that this routine assumes that the protection checks have been
2806  * done by the caller (the low-level page fault routine in most cases).
2807  * Thus we can safely just mark it writable once we've done any necessary
2808  * COW.
2809  *
2810  * We also mark the page dirty at this point even though the page will
2811  * change only once the write actually happens. This avoids a few races,
2812  * and potentially makes it more efficient.
2813  *
2814  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2815  * but allow concurrent faults), with pte both mapped and locked.
2816  * We return with mmap_sem still held, but pte unmapped and unlocked.
2817  */
2818 static int do_wp_page(struct vm_fault *vmf)
2819         __releases(vmf->ptl)
2820 {
2821         struct vm_area_struct *vma = vmf->vma;
2822
2823         vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2824         if (!vmf->page) {
2825                 /*
2826                  * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2827                  * VM_PFNMAP VMA.
2828                  *
2829                  * We should not cow pages in a shared writeable mapping.
2830                  * Just mark the pages writable and/or call ops->pfn_mkwrite.
2831                  */
2832                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2833                                      (VM_WRITE|VM_SHARED))
2834                         return wp_pfn_shared(vmf);
2835
2836                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2837                 return wp_page_copy(vmf);
2838         }
2839
2840         /*
2841          * Take out anonymous pages first, anonymous shared vmas are
2842          * not dirty accountable.
2843          */
2844         if (PageAnon(vmf->page) && !PageKsm(vmf->page)) {
2845                 int total_map_swapcount;
2846                 if (!trylock_page(vmf->page)) {
2847                         get_page(vmf->page);
2848                         pte_unmap_unlock(vmf->pte, vmf->ptl);
2849                         lock_page(vmf->page);
2850                         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
2851                                         vmf->address, &vmf->ptl);
2852                         if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2853                                 unlock_page(vmf->page);
2854                                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2855                                 put_page(vmf->page);
2856                                 return 0;
2857                         }
2858                         put_page(vmf->page);
2859                 }
2860                 if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2861                         if (total_map_swapcount == 1) {
2862                                 /*
2863                                  * The page is all ours. Move it to
2864                                  * our anon_vma so the rmap code will
2865                                  * not search our parent or siblings.
2866                                  * Protected against the rmap code by
2867                                  * the page lock.
2868                                  */
2869                                 page_move_anon_rmap(vmf->page, vma);
2870                         }
2871                         unlock_page(vmf->page);
2872                         wp_page_reuse(vmf);
2873                         return VM_FAULT_WRITE;
2874                 }
2875                 unlock_page(vmf->page);
2876         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2877                                         (VM_WRITE|VM_SHARED))) {
2878                 return wp_page_shared(vmf);
2879         }
2880
2881         /*
2882          * Ok, we need to copy. Oh, well..
2883          */
2884         get_page(vmf->page);
2885
2886         pte_unmap_unlock(vmf->pte, vmf->ptl);
2887         return wp_page_copy(vmf);
2888 }
2889
2890 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2891                 unsigned long start_addr, unsigned long end_addr,
2892                 struct zap_details *details)
2893 {
2894         zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2895 }
2896
2897 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
2898                                             struct zap_details *details)
2899 {
2900         struct vm_area_struct *vma;
2901         pgoff_t vba, vea, zba, zea;
2902
2903         vma_interval_tree_foreach(vma, root,
2904                         details->first_index, details->last_index) {
2905
2906                 vba = vma->vm_pgoff;
2907                 vea = vba + vma_pages(vma) - 1;
2908                 zba = details->first_index;
2909                 if (zba < vba)
2910                         zba = vba;
2911                 zea = details->last_index;
2912                 if (zea > vea)
2913                         zea = vea;
2914
2915                 unmap_mapping_range_vma(vma,
2916                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2917                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2918                                 details);
2919         }
2920 }
2921
2922 /**
2923  * unmap_mapping_range - unmap the portion of all mmaps in the specified
2924  * address_space corresponding to the specified page range in the underlying
2925  * file.
2926  *
2927  * @mapping: the address space containing mmaps to be unmapped.
2928  * @holebegin: byte in first page to unmap, relative to the start of
2929  * the underlying file.  This will be rounded down to a PAGE_SIZE
2930  * boundary.  Note that this is different from truncate_pagecache(), which
2931  * must keep the partial page.  In contrast, we must get rid of
2932  * partial pages.
2933  * @holelen: size of prospective hole in bytes.  This will be rounded
2934  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
2935  * end of the file.
2936  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2937  * but 0 when invalidating pagecache, don't throw away private data.
2938  */
2939 void unmap_mapping_range(struct address_space *mapping,
2940                 loff_t const holebegin, loff_t const holelen, int even_cows)
2941 {
2942         struct zap_details details = { };
2943         pgoff_t hba = holebegin >> PAGE_SHIFT;
2944         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2945
2946         /* Check for overflow. */
2947         if (sizeof(holelen) > sizeof(hlen)) {
2948                 long long holeend =
2949                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2950                 if (holeend & ~(long long)ULONG_MAX)
2951                         hlen = ULONG_MAX - hba + 1;
2952         }
2953
2954         details.check_mapping = even_cows ? NULL : mapping;
2955         details.first_index = hba;
2956         details.last_index = hba + hlen - 1;
2957         if (details.last_index < details.first_index)
2958                 details.last_index = ULONG_MAX;
2959
2960         i_mmap_lock_write(mapping);
2961         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2962                 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2963         i_mmap_unlock_write(mapping);
2964 }
2965 EXPORT_SYMBOL(unmap_mapping_range);
2966
2967 /*
2968  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2969  * but allow concurrent faults), and pte mapped but not yet locked.
2970  * We return with pte unmapped and unlocked.
2971  *
2972  * We return with the mmap_sem locked or unlocked in the same cases
2973  * as does filemap_fault().
2974  */
2975 int do_swap_page(struct vm_fault *vmf)
2976 {
2977         struct vm_area_struct *vma = vmf->vma;
2978         struct page *page = NULL, *swapcache;
2979         struct mem_cgroup *memcg;
2980         struct vma_swap_readahead swap_ra;
2981         swp_entry_t entry;
2982         pte_t pte;
2983         int locked;
2984         int exclusive = 0;
2985         int ret = 0;
2986         bool vma_readahead = swap_use_vma_readahead();
2987
2988         if (vma_readahead)
2989                 page = swap_readahead_detect(vmf, &swap_ra);
2990         if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte)) {
2991                 if (page)
2992                         put_page(page);
2993                 goto out;
2994         }
2995
2996         entry = pte_to_swp_entry(vmf->orig_pte);
2997         if (unlikely(non_swap_entry(entry))) {
2998                 if (is_migration_entry(entry)) {
2999                         migration_entry_wait(vma->vm_mm, vmf->pmd,
3000                                              vmf->address);
3001                 } else if (is_device_private_entry(entry)) {
3002                         /*
3003                          * For un-addressable device memory we call the pgmap
3004                          * fault handler callback. The callback must migrate
3005                          * the page back to some CPU accessible page.
3006                          */
3007                         ret = device_private_entry_fault(vma, vmf->address, entry,
3008                                                  vmf->flags, vmf->pmd);
3009                 } else if (is_hwpoison_entry(entry)) {
3010                         ret = VM_FAULT_HWPOISON;
3011                 } else {
3012                         print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3013                         ret = VM_FAULT_SIGBUS;
3014                 }
3015                 goto out;
3016         }
3017         delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3018         if (!page)
3019                 page = lookup_swap_cache(entry, vma_readahead ? vma : NULL,
3020                                          vmf->address);
3021         if (!page) {
3022                 if (vma_readahead)
3023                         page = do_swap_page_readahead(entry,
3024                                 GFP_HIGHUSER_MOVABLE, vmf, &swap_ra);
3025                 else
3026                         page = swapin_readahead(entry,
3027                                 GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3028                 if (!page) {
3029                         /*
3030                          * Back out if somebody else faulted in this pte
3031                          * while we released the pte lock.
3032                          */
3033                         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3034                                         vmf->address, &vmf->ptl);
3035                         if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3036                                 ret = VM_FAULT_OOM;
3037                         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3038                         goto unlock;
3039                 }
3040
3041                 /* Had to read the page from swap area: Major fault */
3042                 ret = VM_FAULT_MAJOR;
3043                 count_vm_event(PGMAJFAULT);
3044                 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3045         } else if (PageHWPoison(page)) {
3046                 /*
3047                  * hwpoisoned dirty swapcache pages are kept for killing
3048                  * owner processes (which may be unknown at hwpoison time)
3049                  */
3050                 ret = VM_FAULT_HWPOISON;
3051                 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3052                 swapcache = page;
3053                 goto out_release;
3054         }
3055
3056         swapcache = page;
3057         locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3058
3059         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3060         if (!locked) {
3061                 ret |= VM_FAULT_RETRY;
3062                 goto out_release;
3063         }
3064
3065         /*
3066          * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3067          * release the swapcache from under us.  The page pin, and pte_same
3068          * test below, are not enough to exclude that.  Even if it is still
3069          * swapcache, we need to check that the page's swap has not changed.
3070          */
3071         if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3072                 goto out_page;
3073
3074         page = ksm_might_need_to_copy(page, vma, vmf->address);
3075         if (unlikely(!page)) {
3076                 ret = VM_FAULT_OOM;
3077                 page = swapcache;
3078                 goto out_page;
3079         }
3080
3081         if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
3082                                 &memcg, false)) {
3083                 ret = VM_FAULT_OOM;
3084                 goto out_page;
3085         }
3086
3087         /*
3088          * Back out if somebody else already faulted in this pte.
3089          */
3090         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3091                         &vmf->ptl);
3092         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3093                 goto out_nomap;
3094
3095         if (unlikely(!PageUptodate(page))) {
3096                 ret = VM_FAULT_SIGBUS;
3097                 goto out_nomap;
3098         }
3099
3100         /*
3101          * The page isn't present yet, go ahead with the fault.
3102          *
3103          * Be careful about the sequence of operations here.
3104          * To get its accounting right, reuse_swap_page() must be called
3105          * while the page is counted on swap but not yet in mapcount i.e.
3106          * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3107          * must be called after the swap_free(), or it will never succeed.
3108          */
3109
3110         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3111         dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3112         pte = mk_pte(page, vma->vm_page_prot);
3113         if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3114                 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3115                 vmf->flags &= ~FAULT_FLAG_WRITE;
3116                 ret |= VM_FAULT_WRITE;
3117                 exclusive = RMAP_EXCLUSIVE;
3118         }
3119         flush_icache_page(vma, page);
3120         if (pte_swp_soft_dirty(vmf->orig_pte))
3121                 pte = pte_mksoft_dirty(pte);
3122         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3123         vmf->orig_pte = pte;
3124         if (page == swapcache) {
3125                 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3126                 mem_cgroup_commit_charge(page, memcg, true, false);
3127                 activate_page(page);
3128         } else { /* ksm created a completely new copy */
3129                 page_add_new_anon_rmap(page, vma, vmf->address, false);
3130                 mem_cgroup_commit_charge(page, memcg, false, false);
3131                 lru_cache_add_active_or_unevictable(page, vma);
3132         }
3133
3134         swap_free(entry);
3135         if (mem_cgroup_swap_full(page) ||
3136             (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3137                 try_to_free_swap(page);
3138         unlock_page(page);
3139         if (page != swapcache) {
3140                 /*
3141                  * Hold the lock to avoid the swap entry to be reused
3142                  * until we take the PT lock for the pte_same() check
3143                  * (to avoid false positives from pte_same). For
3144                  * further safety release the lock after the swap_free
3145                  * so that the swap count won't change under a
3146                  * parallel locked swapcache.
3147                  */
3148                 unlock_page(swapcache);
3149                 put_page(swapcache);
3150         }
3151
3152         if (vmf->flags & FAULT_FLAG_WRITE) {
3153                 ret |= do_wp_page(vmf);
3154                 if (ret & VM_FAULT_ERROR)
3155                         ret &= VM_FAULT_ERROR;
3156                 goto out;
3157         }
3158
3159         /* No need to invalidate - it was non-present before */
3160         update_mmu_cache(vma, vmf->address, vmf->pte);
3161 unlock:
3162         pte_unmap_unlock(vmf->pte, vmf->ptl);
3163 out:
3164         return ret;
3165 out_nomap:
3166         mem_cgroup_cancel_charge(page, memcg, false);
3167         pte_unmap_unlock(vmf->pte, vmf->ptl);
3168 out_page:
3169         unlock_page(page);
3170 out_release:
3171         put_page(page);
3172         if (page != swapcache) {
3173                 unlock_page(swapcache);
3174                 put_page(swapcache);
3175         }
3176         return ret;
3177 }
3178
3179 /*
3180  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3181  * but allow concurrent faults), and pte mapped but not yet locked.
3182  * We return with mmap_sem still held, but pte unmapped and unlocked.
3183  */
3184 static int do_anonymous_page(struct vm_fault *vmf)
3185 {
3186         struct vm_area_struct *vma = vmf->vma;
3187         struct mem_cgroup *memcg;
3188         struct page *page;
3189         int ret = 0;
3190         pte_t entry;
3191
3192         /* File mapping without ->vm_ops ? */
3193         if (vma->vm_flags & VM_SHARED)
3194                 return VM_FAULT_SIGBUS;
3195
3196         /*
3197          * Use pte_alloc() instead of pte_alloc_map().  We can't run
3198          * pte_offset_map() on pmds where a huge pmd might be created
3199          * from a different thread.
3200          *
3201          * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
3202          * parallel threads are excluded by other means.
3203          *
3204          * Here we only have down_read(mmap_sem).
3205          */
3206         if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
3207                 return VM_FAULT_OOM;
3208
3209         /* See the comment in pte_alloc_one_map() */
3210         if (unlikely(pmd_trans_unstable(vmf->pmd)))
3211                 return 0;
3212
3213         /* Use the zero-page for reads */
3214         if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3215                         !mm_forbids_zeropage(vma->vm_mm)) {
3216                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3217                                                 vma->vm_page_prot));
3218                 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3219                                 vmf->address, &vmf->ptl);
3220                 if (!pte_none(*vmf->pte))
3221                         goto unlock;
3222                 ret = check_stable_address_space(vma->vm_mm);
3223                 if (ret)
3224                         goto unlock;
3225                 /* Deliver the page fault to userland, check inside PT lock */
3226                 if (userfaultfd_missing(vma)) {
3227                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3228                         return handle_userfault(vmf, VM_UFFD_MISSING);
3229                 }
3230                 goto setpte;
3231         }
3232
3233         /* Allocate our own private page. */
3234         if (unlikely(anon_vma_prepare(vma)))
3235                 goto oom;
3236         page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3237         if (!page)
3238                 goto oom;
3239
3240         if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
3241                 goto oom_free_page;
3242
3243         /*
3244          * The memory barrier inside __SetPageUptodate makes sure that
3245          * preceeding stores to the page contents become visible before
3246          * the set_pte_at() write.
3247          */
3248         __SetPageUptodate(page);
3249
3250         entry = mk_pte(page, vma->vm_page_prot);
3251         if (vma->vm_flags & VM_WRITE)
3252                 entry = pte_mkwrite(pte_mkdirty(entry));
3253
3254         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3255                         &vmf->ptl);
3256         if (!pte_none(*vmf->pte))
3257                 goto release;
3258
3259         ret = check_stable_address_space(vma->vm_mm);
3260         if (ret)
3261                 goto release;
3262
3263         /* Deliver the page fault to userland, check inside PT lock */
3264         if (userfaultfd_missing(vma)) {
3265                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3266                 mem_cgroup_cancel_charge(page, memcg, false);
3267                 put_page(page);
3268                 return handle_userfault(vmf, VM_UFFD_MISSING);
3269         }
3270
3271         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3272         page_add_new_anon_rmap(page, vma, vmf->address, false);
3273         mem_cgroup_commit_charge(page, memcg, false, false);
3274         lru_cache_add_active_or_unevictable(page, vma);
3275 setpte:
3276         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3277
3278         /* No need to invalidate - it was non-present before */
3279         update_mmu_cache(vma, vmf->address, vmf->pte);
3280 unlock:
3281         pte_unmap_unlock(vmf->pte, vmf->ptl);
3282         return ret;
3283 release:
3284         mem_cgroup_cancel_charge(page, memcg, false);
3285         put_page(page);
3286         goto unlock;
3287 oom_free_page:
3288         put_page(page);
3289 oom:
3290         return VM_FAULT_OOM;
3291 }
3292
3293 /*
3294  * The mmap_sem must have been held on entry, and may have been
3295  * released depending on flags and vma->vm_ops->fault() return value.
3296  * See filemap_fault() and __lock_page_retry().
3297  */
3298 static int __do_fault(struct vm_fault *vmf)
3299 {
3300         struct vm_area_struct *vma = vmf->vma;
3301         int ret;
3302
3303         /*
3304          * Preallocate pte before we take page_lock because this might lead to
3305          * deadlocks for memcg reclaim which waits for pages under writeback:
3306          *                              lock_page(A)
3307          *                              SetPageWriteback(A)
3308          *                              unlock_page(A)
3309          * lock_page(B)
3310          *                              lock_page(B)
3311          * pte_alloc_pne
3312          *   shrink_page_list
3313          *     wait_on_page_writeback(A)
3314          *                              SetPageWriteback(B)
3315          *                              unlock_page(B)
3316          *                              # flush A, B to clear the writeback
3317          */
3318         if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3319                 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3320                                                   vmf->address);
3321                 if (!vmf->prealloc_pte)
3322                         return VM_FAULT_OOM;
3323                 smp_wmb(); /* See comment in __pte_alloc() */
3324         }
3325
3326         ret = vma->vm_ops->fault(vmf);
3327         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3328                             VM_FAULT_DONE_COW)))
3329                 return ret;
3330
3331         if (unlikely(PageHWPoison(vmf->page))) {
3332                 if (ret & VM_FAULT_LOCKED)
3333                         unlock_page(vmf->page);
3334                 put_page(vmf->page);
3335                 vmf->page = NULL;
3336                 return VM_FAULT_HWPOISON;
3337         }
3338
3339         if (unlikely(!(ret & VM_FAULT_LOCKED)))
3340                 lock_page(vmf->page);
3341         else
3342                 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3343
3344         return ret;
3345 }
3346
3347 /*
3348  * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3349  * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3350  * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3351  * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3352  */
3353 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3354 {
3355         return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3356 }
3357
3358 static int pte_alloc_one_map(struct vm_fault *vmf)
3359 {
3360         struct vm_area_struct *vma = vmf->vma;
3361
3362         if (!pmd_none(*vmf->pmd))
3363                 goto map_pte;
3364         if (vmf->prealloc_pte) {
3365                 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3366                 if (unlikely(!pmd_none(*vmf->pmd))) {
3367                         spin_unlock(vmf->ptl);
3368                         goto map_pte;
3369                 }
3370
3371                 atomic_long_inc(&vma->vm_mm->nr_ptes);
3372                 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3373                 spin_unlock(vmf->ptl);
3374                 vmf->prealloc_pte = NULL;
3375         } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
3376                 return VM_FAULT_OOM;
3377         }
3378 map_pte:
3379         /*
3380          * If a huge pmd materialized under us just retry later.  Use
3381          * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3382          * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3383          * under us and then back to pmd_none, as a result of MADV_DONTNEED
3384          * running immediately after a huge pmd fault in a different thread of
3385          * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3386          * All we have to ensure is that it is a regular pmd that we can walk
3387          * with pte_offset_map() and we can do that through an atomic read in
3388          * C, which is what pmd_trans_unstable() provides.
3389          */
3390         if (pmd_devmap_trans_unstable(vmf->pmd))
3391                 return VM_FAULT_NOPAGE;
3392
3393         /*
3394          * At this point we know that our vmf->pmd points to a page of ptes
3395          * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3396          * for the duration of the fault.  If a racing MADV_DONTNEED runs and
3397          * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3398          * be valid and we will re-check to make sure the vmf->pte isn't
3399          * pte_none() under vmf->ptl protection when we return to
3400          * alloc_set_pte().
3401          */
3402         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3403                         &vmf->ptl);
3404         return 0;
3405 }
3406
3407 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3408
3409 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
3410 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
3411                 unsigned long haddr)
3412 {
3413         if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
3414                         (vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
3415                 return false;
3416         if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
3417                 return false;
3418         return true;
3419 }
3420
3421 static void deposit_prealloc_pte(struct vm_fault *vmf)
3422 {
3423         struct vm_area_struct *vma = vmf->vma;
3424
3425         pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3426         /*
3427          * We are going to consume the prealloc table,
3428          * count that as nr_ptes.
3429          */
3430         atomic_long_inc(&vma->vm_mm->nr_ptes);
3431         vmf->prealloc_pte = NULL;
3432 }
3433
3434 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3435 {
3436         struct vm_area_struct *vma = vmf->vma;
3437         bool write = vmf->flags & FAULT_FLAG_WRITE;
3438         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3439         pmd_t entry;
3440         int i, ret;
3441
3442         if (!transhuge_vma_suitable(vma, haddr))
3443                 return VM_FAULT_FALLBACK;
3444
3445         ret = VM_FAULT_FALLBACK;
3446         page = compound_head(page);
3447
3448         /*
3449          * Archs like ppc64 need additonal space to store information
3450          * related to pte entry. Use the preallocated table for that.
3451          */
3452         if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3453                 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
3454                 if (!vmf->prealloc_pte)
3455                         return VM_FAULT_OOM;
3456                 smp_wmb(); /* See comment in __pte_alloc() */
3457         }
3458
3459         vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3460         if (unlikely(!pmd_none(*vmf->pmd)))
3461                 goto out;
3462
3463         for (i = 0; i < HPAGE_PMD_NR; i++)
3464                 flush_icache_page(vma, page + i);
3465
3466         entry = mk_huge_pmd(page, vma->vm_page_prot);
3467         if (write)
3468                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3469
3470         add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
3471         page_add_file_rmap(page, true);
3472         /*
3473          * deposit and withdraw with pmd lock held
3474          */
3475         if (arch_needs_pgtable_deposit())
3476                 deposit_prealloc_pte(vmf);
3477
3478         set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3479
3480         update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3481
3482         /* fault is handled */
3483         ret = 0;
3484         count_vm_event(THP_FILE_MAPPED);
3485 out:
3486         spin_unlock(vmf->ptl);
3487         return ret;
3488 }
3489 #else
3490 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3491 {
3492         BUILD_BUG();
3493         return 0;
3494 }
3495 #endif
3496
3497 /**
3498  * alloc_set_pte - setup new PTE entry for given page and add reverse page
3499  * mapping. If needed, the fucntion allocates page table or use pre-allocated.
3500  *
3501  * @vmf: fault environment
3502  * @memcg: memcg to charge page (only for private mappings)
3503  * @page: page to map
3504  *
3505  * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3506  * return.
3507  *
3508  * Target users are page handler itself and implementations of
3509  * vm_ops->map_pages.
3510  */
3511 int alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
3512                 struct page *page)
3513 {
3514         struct vm_area_struct *vma = vmf->vma;
3515         bool write = vmf->flags & FAULT_FLAG_WRITE;
3516         pte_t entry;
3517         int ret;
3518
3519         if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3520                         IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
3521                 /* THP on COW? */
3522                 VM_BUG_ON_PAGE(memcg, page);
3523
3524                 ret = do_set_pmd(vmf, page);
3525                 if (ret != VM_FAULT_FALLBACK)
3526                         return ret;
3527         }
3528
3529         if (!vmf->pte) {
3530                 ret = pte_alloc_one_map(vmf);
3531                 if (ret)
3532                         return ret;
3533         }
3534
3535         /* Re-check under ptl */
3536         if (unlikely(!pte_none(*vmf->pte)))
3537                 return VM_FAULT_NOPAGE;
3538
3539         flush_icache_page(vma, page);
3540         entry = mk_pte(page, vma->vm_page_prot);
3541         if (write)
3542                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3543         /* copy-on-write page */
3544         if (write && !(vma->vm_flags & VM_SHARED)) {
3545                 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3546                 page_add_new_anon_rmap(page, vma, vmf->address, false);
3547                 mem_cgroup_commit_charge(page, memcg, false, false);
3548                 lru_cache_add_active_or_unevictable(page, vma);
3549         } else {
3550                 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3551                 page_add_file_rmap(page, false);
3552         }
3553         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3554
3555         /* no need to invalidate: a not-present page won't be cached */
3556         update_mmu_cache(vma, vmf->address, vmf->pte);
3557
3558         return 0;
3559 }
3560
3561
3562 /**
3563  * finish_fault - finish page fault once we have prepared the page to fault
3564  *
3565  * @vmf: structure describing the fault
3566  *
3567  * This function handles all that is needed to finish a page fault once the
3568  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3569  * given page, adds reverse page mapping, handles memcg charges and LRU
3570  * addition. The function returns 0 on success, VM_FAULT_ code in case of
3571  * error.
3572  *
3573  * The function expects the page to be locked and on success it consumes a
3574  * reference of a page being mapped (for the PTE which maps it).
3575  */
3576 int finish_fault(struct vm_fault *vmf)
3577 {
3578         struct page *page;
3579         int ret = 0;
3580
3581         /* Did we COW the page? */
3582         if ((vmf->flags & FAULT_FLAG_WRITE) &&
3583             !(vmf->vma->vm_flags & VM_SHARED))
3584                 page = vmf->cow_page;
3585         else
3586                 page = vmf->page;
3587
3588         /*
3589          * check even for read faults because we might have lost our CoWed
3590          * page
3591          */
3592         if (!(vmf->vma->vm_flags & VM_SHARED))
3593                 ret = check_stable_address_space(vmf->vma->vm_mm);
3594         if (!ret)
3595                 ret = alloc_set_pte(vmf, vmf->memcg, page);
3596         if (vmf->pte)
3597                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3598         return ret;
3599 }
3600
3601 static unsigned long fault_around_bytes __read_mostly =
3602         rounddown_pow_of_two(65536);
3603
3604 #ifdef CONFIG_DEBUG_FS
3605 static int fault_around_bytes_get(void *data, u64 *val)
3606 {
3607         *val = fault_around_bytes;
3608         return 0;
3609 }
3610
3611 /*
3612  * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3613  * rounded down to nearest page order. It's what do_fault_around() expects to
3614  * see.
3615  */
3616 static int fault_around_bytes_set(void *data, u64 val)
3617 {
3618         if (val / PAGE_SIZE > PTRS_PER_PTE)
3619                 return -EINVAL;
3620         if (val > PAGE_SIZE)
3621                 fault_around_bytes = rounddown_pow_of_two(val);
3622         else
3623                 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3624         return 0;
3625 }
3626 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3627                 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3628
3629 static int __init fault_around_debugfs(void)
3630 {
3631         void *ret;
3632
3633         ret = debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3634                         &fault_around_bytes_fops);
3635         if (!ret)
3636                 pr_warn("Failed to create fault_around_bytes in debugfs");
3637         return 0;
3638 }
3639 late_initcall(fault_around_debugfs);
3640 #endif
3641
3642 /*
3643  * do_fault_around() tries to map few pages around the fault address. The hope
3644  * is that the pages will be needed soon and this will lower the number of
3645  * faults to handle.
3646  *
3647  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3648  * not ready to be mapped: not up-to-date, locked, etc.
3649  *
3650  * This function is called with the page table lock taken. In the split ptlock
3651  * case the page table lock only protects only those entries which belong to
3652  * the page table corresponding to the fault address.
3653  *
3654  * This function doesn't cross the VMA boundaries, in order to call map_pages()
3655  * only once.
3656  *
3657  * fault_around_pages() defines how many pages we'll try to map.
3658  * do_fault_around() expects it to return a power of two less than or equal to
3659  * PTRS_PER_PTE.
3660  *
3661  * The virtual address of the area that we map is naturally aligned to the
3662  * fault_around_pages() value (and therefore to page order).  This way it's
3663  * easier to guarantee that we don't cross page table boundaries.
3664  */
3665 static int do_fault_around(struct vm_fault *vmf)
3666 {
3667         unsigned long address = vmf->address, nr_pages, mask;
3668         pgoff_t start_pgoff = vmf->pgoff;
3669         pgoff_t end_pgoff;
3670         int off, ret = 0;
3671
3672         nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3673         mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3674
3675         vmf->address = max(address & mask, vmf->vma->vm_start);
3676         off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3677         start_pgoff -= off;
3678
3679         /*
3680          *  end_pgoff is either end of page table or end of vma
3681          *  or fault_around_pages() from start_pgoff, depending what is nearest.
3682          */
3683         end_pgoff = start_pgoff -
3684                 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3685                 PTRS_PER_PTE - 1;
3686         end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3687                         start_pgoff + nr_pages - 1);
3688
3689         if (pmd_none(*vmf->pmd)) {
3690                 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3691                                                   vmf->address);
3692                 if (!vmf->prealloc_pte)
3693                         goto out;
3694                 smp_wmb(); /* See comment in __pte_alloc() */
3695         }
3696
3697         vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
3698
3699         /* Huge page is mapped? Page fault is solved */
3700         if (pmd_trans_huge(*vmf->pmd)) {
3701                 ret = VM_FAULT_NOPAGE;
3702                 goto out;
3703         }
3704
3705         /* ->map_pages() haven't done anything useful. Cold page cache? */
3706         if (!vmf->pte)
3707                 goto out;
3708
3709         /* check if the page fault is solved */
3710         vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3711         if (!pte_none(*vmf->pte))
3712                 ret = VM_FAULT_NOPAGE;
3713         pte_unmap_unlock(vmf->pte, vmf->ptl);
3714 out:
3715         vmf->address = address;
3716         vmf->pte = NULL;
3717         return ret;
3718 }
3719
3720 static int do_read_fault(struct vm_fault *vmf)
3721 {
3722         struct vm_area_struct *vma = vmf->vma;
3723         int ret = 0;
3724
3725         /*
3726          * Let's call ->map_pages() first and use ->fault() as fallback
3727          * if page by the offset is not ready to be mapped (cold cache or
3728          * something).
3729          */
3730         if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3731                 ret = do_fault_around(vmf);
3732                 if (ret)
3733                         return ret;
3734         }
3735
3736         ret = __do_fault(vmf);
3737         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3738                 return ret;
3739
3740         ret |= finish_fault(vmf);
3741         unlock_page(vmf->page);
3742         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3743                 put_page(vmf->page);
3744         return ret;
3745 }
3746
3747 static int do_cow_fault(struct vm_fault *vmf)
3748 {
3749         struct vm_area_struct *vma = vmf->vma;
3750         int ret;
3751
3752         if (unlikely(anon_vma_prepare(vma)))
3753                 return VM_FAULT_OOM;
3754
3755         vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3756         if (!vmf->cow_page)
3757                 return VM_FAULT_OOM;
3758
3759         if (mem_cgroup_try_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
3760                                 &vmf->memcg, false)) {
3761                 put_page(vmf->cow_page);
3762                 return VM_FAULT_OOM;
3763         }
3764
3765         ret = __do_fault(vmf);
3766         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3767                 goto uncharge_out;
3768         if (ret & VM_FAULT_DONE_COW)
3769                 return ret;
3770
3771         copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3772         __SetPageUptodate(vmf->cow_page);
3773
3774         ret |= finish_fault(vmf);
3775         unlock_page(vmf->page);
3776         put_page(vmf->page);
3777         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3778                 goto uncharge_out;
3779         return ret;
3780 uncharge_out:
3781         mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3782         put_page(vmf->cow_page);
3783         return ret;
3784 }
3785
3786 static int do_shared_fault(struct vm_fault *vmf)
3787 {
3788         struct vm_area_struct *vma = vmf->vma;
3789         int ret, tmp;
3790
3791         ret = __do_fault(vmf);
3792         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3793                 return ret;
3794
3795         /*
3796          * Check if the backing address space wants to know that the page is
3797          * about to become writable
3798          */
3799         if (vma->vm_ops->page_mkwrite) {
3800                 unlock_page(vmf->page);
3801                 tmp = do_page_mkwrite(vmf);
3802                 if (unlikely(!tmp ||
3803                                 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3804                         put_page(vmf->page);
3805                         return tmp;
3806                 }
3807         }
3808
3809         ret |= finish_fault(vmf);
3810         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3811                                         VM_FAULT_RETRY))) {
3812                 unlock_page(vmf->page);
3813                 put_page(vmf->page);
3814                 return ret;
3815         }
3816
3817         fault_dirty_shared_page(vma, vmf->page);
3818         return ret;
3819 }
3820
3821 /*
3822  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3823  * but allow concurrent faults).
3824  * The mmap_sem may have been released depending on flags and our
3825  * return value.  See filemap_fault() and __lock_page_or_retry().
3826  */
3827 static int do_fault(struct vm_fault *vmf)
3828 {
3829         struct vm_area_struct *vma = vmf->vma;
3830         int ret;
3831
3832         /*
3833          * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
3834          */
3835         if (!vma->vm_ops->fault) {
3836                 /*
3837                  * If we find a migration pmd entry or a none pmd entry, which
3838                  * should never happen, return SIGBUS
3839                  */
3840                 if (unlikely(!pmd_present(*vmf->pmd)))
3841                         ret = VM_FAULT_SIGBUS;
3842                 else {
3843                         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
3844                                                        vmf->pmd,
3845                                                        vmf->address,
3846                                                        &vmf->ptl);
3847                         /*
3848                          * Make sure this is not a temporary clearing of pte
3849                          * by holding ptl and checking again. A R/M/W update
3850                          * of pte involves: take ptl, clearing the pte so that
3851                          * we don't have concurrent modification by hardware
3852                          * followed by an update.
3853                          */
3854                         if (unlikely(pte_none(*vmf->pte)))
3855                                 ret = VM_FAULT_SIGBUS;
3856                         else
3857                                 ret = VM_FAULT_NOPAGE;
3858
3859                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3860                 }
3861         } else if (!(vmf->flags & FAULT_FLAG_WRITE))
3862                 ret = do_read_fault(vmf);
3863         else if (!(vma->vm_flags & VM_SHARED))
3864                 ret = do_cow_fault(vmf);
3865         else
3866                 ret = do_shared_fault(vmf);
3867
3868         /* preallocated pagetable is unused: free it */
3869         if (vmf->prealloc_pte) {
3870                 pte_free(vma->vm_mm, vmf->prealloc_pte);
3871                 vmf->prealloc_pte = NULL;
3872         }
3873         return ret;
3874 }
3875
3876 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3877                                 unsigned long addr, int page_nid,
3878                                 int *flags)
3879 {
3880         get_page(page);
3881
3882         count_vm_numa_event(NUMA_HINT_FAULTS);
3883         if (page_nid == numa_node_id()) {
3884                 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3885                 *flags |= TNF_FAULT_LOCAL;
3886         }
3887
3888         return mpol_misplaced(page, vma, addr);
3889 }
3890
3891 static int do_numa_page(struct vm_fault *vmf)
3892 {
3893         struct vm_area_struct *vma = vmf->vma;
3894         struct page *page = NULL;
3895         int page_nid = -1;
3896         int last_cpupid;
3897         int target_nid;
3898         bool migrated = false;
3899         pte_t pte;
3900         bool was_writable = pte_savedwrite(vmf->orig_pte);
3901         int flags = 0;
3902
3903         /*
3904          * The "pte" at this point cannot be used safely without
3905          * validation through pte_unmap_same(). It's of NUMA type but
3906          * the pfn may be screwed if the read is non atomic.
3907          */
3908         vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
3909         spin_lock(vmf->ptl);
3910         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3911                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3912                 goto out;
3913         }
3914
3915         /*
3916          * Make it present again, Depending on how arch implementes non
3917          * accessible ptes, some can allow access by kernel mode.
3918          */
3919         pte = ptep_modify_prot_start(vma->vm_mm, vmf->address, vmf->pte);
3920         pte = pte_modify(pte, vma->vm_page_prot);
3921         pte = pte_mkyoung(pte);
3922         if (was_writable)
3923                 pte = pte_mkwrite(pte);
3924         ptep_modify_prot_commit(vma->vm_mm, vmf->address, vmf->pte, pte);
3925         update_mmu_cache(vma, vmf->address, vmf->pte);
3926
3927         page = vm_normal_page(vma, vmf->address, pte);
3928         if (!page) {
3929                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3930                 return 0;
3931         }
3932
3933         /* TODO: handle PTE-mapped THP */
3934         if (PageCompound(page)) {
3935                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3936                 return 0;
3937         }
3938
3939         /*
3940          * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3941          * much anyway since they can be in shared cache state. This misses
3942          * the case where a mapping is writable but the process never writes
3943          * to it but pte_write gets cleared during protection updates and
3944          * pte_dirty has unpredictable behaviour between PTE scan updates,
3945          * background writeback, dirty balancing and application behaviour.
3946          */
3947         if (!pte_write(pte))
3948                 flags |= TNF_NO_GROUP;
3949
3950         /*
3951          * Flag if the page is shared between multiple address spaces. This
3952          * is later used when determining whether to group tasks together
3953          */
3954         if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3955                 flags |= TNF_SHARED;
3956
3957         last_cpupid = page_cpupid_last(page);
3958         page_nid = page_to_nid(page);
3959         target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3960                         &flags);
3961         pte_unmap_unlock(vmf->pte, vmf->ptl);
3962         if (target_nid == -1) {
3963                 put_page(page);
3964                 goto out;
3965         }
3966
3967         /* Migrate to the requested node */
3968         migrated = migrate_misplaced_page(page, vma, target_nid);
3969         if (migrated) {
3970                 page_nid = target_nid;
3971                 flags |= TNF_MIGRATED;
3972         } else
3973                 flags |= TNF_MIGRATE_FAIL;
3974
3975 out:
3976         if (page_nid != -1)
3977                 task_numa_fault(last_cpupid, page_nid, 1, flags);
3978         return 0;
3979 }
3980
3981 static inline int create_huge_pmd(struct vm_fault *vmf)
3982 {
3983         if (vma_is_anonymous(vmf->vma))
3984                 return do_huge_pmd_anonymous_page(vmf);
3985         if (vmf->vma->vm_ops->huge_fault)
3986                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3987         return VM_FAULT_FALLBACK;
3988 }
3989
3990 static int wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
3991 {
3992         if (vma_is_anonymous(vmf->vma))
3993                 return do_huge_pmd_wp_page(vmf, orig_pmd);
3994         if (vmf->vma->vm_ops->huge_fault)
3995                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3996
3997         /* COW handled on pte level: split pmd */
3998         VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
3999         __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4000
4001         return VM_FAULT_FALLBACK;
4002 }
4003
4004 static inline bool vma_is_accessible(struct vm_area_struct *vma)
4005 {
4006         return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
4007 }
4008
4009 static int create_huge_pud(struct vm_fault *vmf)
4010 {
4011 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4012         /* No support for anonymous transparent PUD pages yet */
4013         if (vma_is_anonymous(vmf->vma))
4014                 return VM_FAULT_FALLBACK;
4015         if (vmf->vma->vm_ops->huge_fault)
4016                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4017 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4018         return VM_FAULT_FALLBACK;
4019 }
4020
4021 static int wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4022 {
4023 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4024         /* No support for anonymous transparent PUD pages yet */
4025         if (vma_is_anonymous(vmf->vma))
4026                 return VM_FAULT_FALLBACK;
4027         if (vmf->vma->vm_ops->huge_fault)
4028                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4029 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4030         return VM_FAULT_FALLBACK;
4031 }
4032
4033 /*
4034  * These routines also need to handle stuff like marking pages dirty
4035  * and/or accessed for architectures that don't do it in hardware (most
4036  * RISC architectures).  The early dirtying is also good on the i386.
4037  *
4038  * There is also a hook called "update_mmu_cache()" that architectures
4039  * with external mmu caches can use to update those (ie the Sparc or
4040  * PowerPC hashed page tables that act as extended TLBs).
4041  *
4042  * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
4043  * concurrent faults).
4044  *
4045  * The mmap_sem may have been released depending on flags and our return value.
4046  * See filemap_fault() and __lock_page_or_retry().
4047  */
4048 static int handle_pte_fault(struct vm_fault *vmf)
4049 {
4050         pte_t entry;
4051
4052         if (unlikely(pmd_none(*vmf->pmd))) {
4053                 /*
4054                  * Leave __pte_alloc() until later: because vm_ops->fault may
4055                  * want to allocate huge page, and if we expose page table
4056                  * for an instant, it will be difficult to retract from
4057                  * concurrent faults and from rmap lookups.
4058                  */
4059                 vmf->pte = NULL;
4060         } else {
4061                 /* See comment in pte_alloc_one_map() */
4062                 if (pmd_devmap_trans_unstable(vmf->pmd))
4063                         return 0;
4064                 /*
4065                  * A regular pmd is established and it can't morph into a huge
4066                  * pmd from under us anymore at this point because we hold the
4067                  * mmap_sem read mode and khugepaged takes it in write mode.
4068                  * So now it's safe to run pte_offset_map().
4069                  */
4070                 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4071                 vmf->orig_pte = *vmf->pte;
4072
4073                 /*
4074                  * some architectures can have larger ptes than wordsize,
4075                  * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4076                  * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
4077                  * atomic accesses.  The code below just needs a consistent
4078                  * view for the ifs and we later double check anyway with the
4079                  * ptl lock held. So here a barrier will do.
4080                  */
4081                 barrier();
4082                 if (pte_none(vmf->orig_pte)) {
4083                         pte_unmap(vmf->pte);
4084                         vmf->pte = NULL;
4085                 }
4086         }
4087
4088         if (!vmf->pte) {
4089                 if (vma_is_anonymous(vmf->vma))
4090                         return do_anonymous_page(vmf);
4091                 else
4092                         return do_fault(vmf);
4093         }
4094
4095         if (!pte_present(vmf->orig_pte))
4096                 return do_swap_page(vmf);
4097
4098         if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4099                 return do_numa_page(vmf);
4100
4101         vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4102         spin_lock(vmf->ptl);
4103         entry = vmf->orig_pte;
4104         if (unlikely(!pte_same(*vmf->pte, entry)))
4105                 goto unlock;
4106         if (vmf->flags & FAULT_FLAG_WRITE) {
4107                 if (!pte_write(entry))
4108                         return do_wp_page(vmf);
4109                 entry = pte_mkdirty(entry);
4110         }
4111         entry = pte_mkyoung(entry);
4112         if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4113                                 vmf->flags & FAULT_FLAG_WRITE)) {
4114                 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4115         } else {
4116                 /*
4117                  * This is needed only for protection faults but the arch code
4118                  * is not yet telling us if this is a protection fault or not.
4119                  * This still avoids useless tlb flushes for .text page faults
4120                  * with threads.
4121                  */
4122                 if (vmf->flags & FAULT_FLAG_WRITE)
4123                         flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4124         }
4125 unlock:
4126         pte_unmap_unlock(vmf->pte, vmf->ptl);
4127         return 0;
4128 }
4129
4130 /*
4131  * By the time we get here, we already hold the mm semaphore
4132  *
4133  * The mmap_sem may have been released depending on flags and our
4134  * return value.  See filemap_fault() and __lock_page_or_retry().
4135  */
4136 static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4137                 unsigned int flags)
4138 {
4139         struct vm_fault vmf = {
4140                 .vma = vma,
4141                 .address = address & PAGE_MASK,
4142                 .flags = flags,
4143                 .pgoff = linear_page_index(vma, address),
4144                 .gfp_mask = __get_fault_gfp_mask(vma),
4145         };
4146         unsigned int dirty = flags & FAULT_FLAG_WRITE;
4147         struct mm_struct *mm = vma->vm_mm;
4148         pgd_t *pgd;
4149         p4d_t *p4d;
4150         int ret;
4151
4152         pgd = pgd_offset(mm, address);
4153         p4d = p4d_alloc(mm, pgd, address);
4154         if (!p4d)
4155                 return VM_FAULT_OOM;
4156
4157         vmf.pud = pud_alloc(mm, p4d, address);
4158         if (!vmf.pud)
4159                 return VM_FAULT_OOM;
4160         if (pud_none(*vmf.pud) && transparent_hugepage_enabled(vma)) {
4161                 ret = create_huge_pud(&vmf);
4162                 if (!(ret & VM_FAULT_FALLBACK))
4163                         return ret;
4164         } else {
4165                 pud_t orig_pud = *vmf.pud;
4166
4167                 barrier();
4168                 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4169
4170                         /* NUMA case for anonymous PUDs would go here */
4171
4172                         if (dirty && !pud_write(orig_pud)) {
4173                                 ret = wp_huge_pud(&vmf, orig_pud);
4174                                 if (!(ret & VM_FAULT_FALLBACK))
4175                                         return ret;
4176                         } else {
4177                                 huge_pud_set_accessed(&vmf, orig_pud);
4178                                 return 0;
4179                         }
4180                 }
4181         }
4182
4183         vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4184         if (!vmf.pmd)
4185                 return VM_FAULT_OOM;
4186         if (pmd_none(*vmf.pmd) && transparent_hugepage_enabled(vma)) {
4187                 ret = create_huge_pmd(&vmf);
4188                 if (!(ret & VM_FAULT_FALLBACK))
4189                         return ret;
4190         } else {
4191                 pmd_t orig_pmd = *vmf.pmd;
4192
4193                 barrier();
4194                 if (unlikely(is_swap_pmd(orig_pmd))) {
4195                         VM_BUG_ON(thp_migration_supported() &&
4196                                           !is_pmd_migration_entry(orig_pmd));
4197                         if (is_pmd_migration_entry(orig_pmd))
4198                                 pmd_migration_entry_wait(mm, vmf.pmd);
4199                         return 0;
4200                 }
4201                 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4202                         if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4203                                 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4204
4205                         if (dirty && !pmd_write(orig_pmd)) {
4206                                 ret = wp_huge_pmd(&vmf, orig_pmd);
4207                                 if (!(ret & VM_FAULT_FALLBACK))
4208                                         return ret;
4209                         } else {
4210                                 huge_pmd_set_accessed(&vmf, orig_pmd);
4211                                 return 0;
4212                         }
4213                 }
4214         }
4215
4216         return handle_pte_fault(&vmf);
4217 }
4218
4219 /*
4220  * By the time we get here, we already hold the mm semaphore
4221  *
4222  * The mmap_sem may have been released depending on flags and our
4223  * return value.  See filemap_fault() and __lock_page_or_retry().
4224  */
4225 int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4226                 unsigned int flags)
4227 {
4228         int ret;
4229
4230         __set_current_state(TASK_RUNNING);
4231
4232         count_vm_event(PGFAULT);
4233         count_memcg_event_mm(vma->vm_mm, PGFAULT);
4234
4235         /* do counter updates before entering really critical section. */
4236         check_sync_rss_stat(current);
4237
4238         if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4239                                             flags & FAULT_FLAG_INSTRUCTION,
4240                                             flags & FAULT_FLAG_REMOTE))
4241                 return VM_FAULT_SIGSEGV;
4242
4243         /*
4244          * Enable the memcg OOM handling for faults triggered in user
4245          * space.  Kernel faults are handled more gracefully.
4246          */
4247         if (flags & FAULT_FLAG_USER)
4248                 mem_cgroup_oom_enable();
4249
4250         if (unlikely(is_vm_hugetlb_page(vma)))
4251                 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4252         else
4253                 ret = __handle_mm_fault(vma, address, flags);
4254
4255         if (flags & FAULT_FLAG_USER) {
4256                 mem_cgroup_oom_disable();
4257                 /*
4258                  * The task may have entered a memcg OOM situation but
4259                  * if the allocation error was handled gracefully (no
4260                  * VM_FAULT_OOM), there is no need to kill anything.
4261                  * Just clean up the OOM state peacefully.
4262                  */
4263                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4264                         mem_cgroup_oom_synchronize(false);
4265         }
4266
4267         return ret;
4268 }
4269 EXPORT_SYMBOL_GPL(handle_mm_fault);
4270
4271 #ifndef __PAGETABLE_P4D_FOLDED
4272 /*
4273  * Allocate p4d page table.
4274  * We've already handled the fast-path in-line.
4275  */
4276 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4277 {
4278         p4d_t *new = p4d_alloc_one(mm, address);
4279         if (!new)
4280                 return -ENOMEM;
4281
4282         smp_wmb(); /* See comment in __pte_alloc */
4283
4284         spin_lock(&mm->page_table_lock);
4285         if (pgd_present(*pgd))          /* Another has populated it */
4286                 p4d_free(mm, new);
4287         else
4288                 pgd_populate(mm, pgd, new);
4289         spin_unlock(&mm->page_table_lock);
4290         return 0;
4291 }
4292 #endif /* __PAGETABLE_P4D_FOLDED */
4293
4294 #ifndef __PAGETABLE_PUD_FOLDED
4295 /*
4296  * Allocate page upper directory.
4297  * We've already handled the fast-path in-line.
4298  */
4299 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4300 {
4301         pud_t *new = pud_alloc_one(mm, address);
4302         if (!new)
4303                 return -ENOMEM;
4304
4305         smp_wmb(); /* See comment in __pte_alloc */
4306
4307         spin_lock(&mm->page_table_lock);
4308 #ifndef __ARCH_HAS_5LEVEL_HACK
4309         if (p4d_present(*p4d))          /* Another has populated it */
4310                 pud_free(mm, new);
4311         else
4312                 p4d_populate(mm, p4d, new);
4313 #else
4314         if (pgd_present(*p4d))          /* Another has populated it */
4315                 pud_free(mm, new);
4316         else
4317                 pgd_populate(mm, p4d, new);
4318 #endif /* __ARCH_HAS_5LEVEL_HACK */
4319         spin_unlock(&mm->page_table_lock);
4320         return 0;
4321 }
4322 #endif /* __PAGETABLE_PUD_FOLDED */
4323
4324 #ifndef __PAGETABLE_PMD_FOLDED
4325 /*
4326  * Allocate page middle directory.
4327  * We've already handled the fast-path in-line.
4328  */
4329 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4330 {
4331         spinlock_t *ptl;
4332         pmd_t *new = pmd_alloc_one(mm, address);
4333         if (!new)
4334                 return -ENOMEM;
4335
4336         smp_wmb(); /* See comment in __pte_alloc */
4337
4338         ptl = pud_lock(mm, pud);
4339 #ifndef __ARCH_HAS_4LEVEL_HACK
4340         if (!pud_present(*pud)) {
4341                 mm_inc_nr_pmds(mm);
4342                 pud_populate(mm, pud, new);
4343         } else  /* Another has populated it */
4344                 pmd_free(mm, new);
4345 #else
4346         if (!pgd_present(*pud)) {
4347                 mm_inc_nr_pmds(mm);
4348                 pgd_populate(mm, pud, new);
4349         } else /* Another has populated it */
4350                 pmd_free(mm, new);
4351 #endif /* __ARCH_HAS_4LEVEL_HACK */
4352         spin_unlock(ptl);
4353         return 0;
4354 }
4355 #endif /* __PAGETABLE_PMD_FOLDED */
4356
4357 static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4358                             unsigned long *start, unsigned long *end,
4359                             pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4360 {
4361         pgd_t *pgd;
4362         p4d_t *p4d;
4363         pud_t *pud;
4364         pmd_t *pmd;
4365         pte_t *ptep;
4366
4367         pgd = pgd_offset(mm, address);
4368         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4369                 goto out;
4370
4371         p4d = p4d_offset(pgd, address);
4372         if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4373                 goto out;
4374
4375         pud = pud_offset(p4d, address);
4376         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4377                 goto out;
4378
4379         pmd = pmd_offset(pud, address);
4380         VM_BUG_ON(pmd_trans_huge(*pmd));
4381
4382         if (pmd_huge(*pmd)) {
4383                 if (!pmdpp)
4384                         goto out;
4385
4386                 if (start && end) {
4387                         *start = address & PMD_MASK;
4388                         *end = *start + PMD_SIZE;
4389                         mmu_notifier_invalidate_range_start(mm, *start, *end);
4390                 }
4391                 *ptlp = pmd_lock(mm, pmd);
4392                 if (pmd_huge(*pmd)) {
4393                         *pmdpp = pmd;
4394                         return 0;
4395                 }
4396                 spin_unlock(*ptlp);
4397                 if (start && end)
4398                         mmu_notifier_invalidate_range_end(mm, *start, *end);
4399         }
4400
4401         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4402                 goto out;
4403
4404         if (start && end) {
4405                 *start = address & PAGE_MASK;
4406                 *end = *start + PAGE_SIZE;
4407                 mmu_notifier_invalidate_range_start(mm, *start, *end);
4408         }
4409         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4410         if (!pte_present(*ptep))
4411                 goto unlock;
4412         *ptepp = ptep;
4413         return 0;
4414 unlock:
4415         pte_unmap_unlock(ptep, *ptlp);
4416         if (start && end)
4417                 mmu_notifier_invalidate_range_end(mm, *start, *end);
4418 out:
4419         return -EINVAL;
4420 }
4421
4422 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4423                              pte_t **ptepp, spinlock_t **ptlp)
4424 {
4425         int res;
4426
4427         /* (void) is needed to make gcc happy */
4428         (void) __cond_lock(*ptlp,
4429                            !(res = __follow_pte_pmd(mm, address, NULL, NULL,
4430                                                     ptepp, NULL, ptlp)));
4431         return res;
4432 }
4433
4434 int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4435                              unsigned long *start, unsigned long *end,
4436                              pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4437 {
4438         int res;
4439
4440         /* (void) is needed to make gcc happy */
4441         (void) __cond_lock(*ptlp,
4442                            !(res = __follow_pte_pmd(mm, address, start, end,
4443                                                     ptepp, pmdpp, ptlp)));
4444         return res;
4445 }
4446 EXPORT_SYMBOL(follow_pte_pmd);
4447
4448 /**
4449  * follow_pfn - look up PFN at a user virtual address
4450  * @vma: memory mapping
4451  * @address: user virtual address
4452  * @pfn: location to store found PFN
4453  *
4454  * Only IO mappings and raw PFN mappings are allowed.
4455  *
4456  * Returns zero and the pfn at @pfn on success, -ve otherwise.
4457  */
4458 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4459         unsigned long *pfn)
4460 {
4461         int ret = -EINVAL;
4462         spinlock_t *ptl;
4463         pte_t *ptep;
4464
4465         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4466                 return ret;
4467
4468         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4469         if (ret)
4470                 return ret;
4471         *pfn = pte_pfn(*ptep);
4472         pte_unmap_unlock(ptep, ptl);
4473         return 0;
4474 }
4475 EXPORT_SYMBOL(follow_pfn);
4476
4477 #ifdef CONFIG_HAVE_IOREMAP_PROT
4478 int follow_phys(struct vm_area_struct *vma,
4479                 unsigned long address, unsigned int flags,
4480                 unsigned long *prot, resource_size_t *phys)
4481 {
4482         int ret = -EINVAL;
4483         pte_t *ptep, pte;
4484         spinlock_t *ptl;
4485
4486         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4487                 goto out;
4488
4489         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4490                 goto out;
4491         pte = *ptep;
4492
4493         if ((flags & FOLL_WRITE) && !pte_write(pte))
4494                 goto unlock;
4495
4496         *prot = pgprot_val(pte_pgprot(pte));
4497         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4498
4499         ret = 0;
4500 unlock:
4501         pte_unmap_unlock(ptep, ptl);
4502 out:
4503         return ret;
4504 }
4505
4506 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4507                         void *buf, int len, int write)
4508 {
4509         resource_size_t phys_addr;
4510         unsigned long prot = 0;
4511         void __iomem *maddr;
4512         int offset = addr & (PAGE_SIZE-1);
4513
4514         if (follow_phys(vma, addr, write, &prot, &phys_addr))
4515                 return -EINVAL;
4516
4517         maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4518         if (!maddr)
4519                 return -ENOMEM;
4520
4521         if (write)
4522                 memcpy_toio(maddr + offset, buf, len);
4523         else
4524                 memcpy_fromio(buf, maddr + offset, len);
4525         iounmap(maddr);
4526
4527         return len;
4528 }
4529 EXPORT_SYMBOL_GPL(generic_access_phys);
4530 #endif
4531
4532 /*
4533  * Access another process' address space as given in mm.  If non-NULL, use the
4534  * given task for page fault accounting.
4535  */
4536 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4537                 unsigned long addr, void *buf, int len, unsigned int gup_flags)
4538 {
4539         struct vm_area_struct *vma;
4540         void *old_buf = buf;
4541         int write = gup_flags & FOLL_WRITE;
4542
4543         down_read(&mm->mmap_sem);
4544         /* ignore errors, just check how much was successfully transferred */
4545         while (len) {
4546                 int bytes, ret, offset;
4547                 void *maddr;
4548                 struct page *page = NULL;
4549
4550                 ret = get_user_pages_remote(tsk, mm, addr, 1,
4551                                 gup_flags, &page, &vma, NULL);
4552                 if (ret <= 0) {
4553 #ifndef CONFIG_HAVE_IOREMAP_PROT
4554                         break;
4555 #else
4556                         /*
4557                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
4558                          * we can access using slightly different code.
4559                          */
4560                         vma = find_vma(mm, addr);
4561                         if (!vma || vma->vm_start > addr)
4562                                 break;
4563                         if (vma->vm_ops && vma->vm_ops->access)
4564                                 ret = vma->vm_ops->access(vma, addr, buf,
4565                                                           len, write);
4566                         if (ret <= 0)
4567                                 break;
4568                         bytes = ret;
4569 #endif
4570                 } else {
4571                         bytes = len;
4572                         offset = addr & (PAGE_SIZE-1);
4573                         if (bytes > PAGE_SIZE-offset)
4574                                 bytes = PAGE_SIZE-offset;
4575
4576                         maddr = kmap(page);
4577                         if (write) {
4578                                 copy_to_user_page(vma, page, addr,
4579                                                   maddr + offset, buf, bytes);
4580                                 set_page_dirty_lock(page);
4581                         } else {
4582                                 copy_from_user_page(vma, page, addr,
4583                                                     buf, maddr + offset, bytes);
4584                         }
4585                         kunmap(page);
4586                         put_page(page);
4587                 }
4588                 len -= bytes;
4589                 buf += bytes;
4590                 addr += bytes;
4591         }
4592         up_read(&mm->mmap_sem);
4593
4594         return buf - old_buf;
4595 }
4596
4597 /**
4598  * access_remote_vm - access another process' address space
4599  * @mm:         the mm_struct of the target address space
4600  * @addr:       start address to access
4601  * @buf:        source or destination buffer
4602  * @len:        number of bytes to transfer
4603  * @gup_flags:  flags modifying lookup behaviour
4604  *
4605  * The caller must hold a reference on @mm.
4606  */
4607 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4608                 void *buf, int len, unsigned int gup_flags)
4609 {
4610         return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
4611 }
4612
4613 /*
4614  * Access another process' address space.
4615  * Source/target buffer must be kernel space,
4616  * Do not walk the page table directly, use get_user_pages
4617  */
4618 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4619                 void *buf, int len, unsigned int gup_flags)
4620 {
4621         struct mm_struct *mm;
4622         int ret;
4623
4624         mm = get_task_mm(tsk);
4625         if (!mm)
4626                 return 0;
4627
4628         ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4629
4630         mmput(mm);
4631
4632         return ret;
4633 }
4634 EXPORT_SYMBOL_GPL(access_process_vm);
4635
4636 /*
4637  * Print the name of a VMA.
4638  */
4639 void print_vma_addr(char *prefix, unsigned long ip)
4640 {
4641         struct mm_struct *mm = current->mm;
4642         struct vm_area_struct *vma;
4643
4644         /*
4645          * Do not print if we are in atomic
4646          * contexts (in exception stacks, etc.):
4647          */
4648         if (preempt_count())
4649                 return;
4650
4651         down_read(&mm->mmap_sem);
4652         vma = find_vma(mm, ip);
4653         if (vma && vma->vm_file) {
4654                 struct file *f = vma->vm_file;
4655                 char *buf = (char *)__get_free_page(GFP_KERNEL);
4656                 if (buf) {
4657                         char *p;
4658
4659                         p = file_path(f, buf, PAGE_SIZE);
4660                         if (IS_ERR(p))
4661                                 p = "?";
4662                         printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4663                                         vma->vm_start,
4664                                         vma->vm_end - vma->vm_start);
4665                         free_page((unsigned long)buf);
4666                 }
4667         }
4668         up_read(&mm->mmap_sem);
4669 }
4670
4671 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4672 void __might_fault(const char *file, int line)
4673 {
4674         /*
4675          * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4676          * holding the mmap_sem, this is safe because kernel memory doesn't
4677          * get paged out, therefore we'll never actually fault, and the
4678          * below annotations will generate false positives.
4679          */
4680         if (uaccess_kernel())
4681                 return;
4682         if (pagefault_disabled())
4683                 return;
4684         __might_sleep(file, line, 0);
4685 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4686         if (current->mm)
4687                 might_lock_read(&current->mm->mmap_sem);
4688 #endif
4689 }
4690 EXPORT_SYMBOL(__might_fault);
4691 #endif
4692
4693 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4694 static void clear_gigantic_page(struct page *page,
4695                                 unsigned long addr,
4696                                 unsigned int pages_per_huge_page)
4697 {
4698         int i;
4699         struct page *p = page;
4700
4701         might_sleep();
4702         for (i = 0; i < pages_per_huge_page;
4703              i++, p = mem_map_next(p, page, i)) {
4704                 cond_resched();
4705                 clear_user_highpage(p, addr + i * PAGE_SIZE);
4706         }
4707 }
4708 void clear_huge_page(struct page *page,
4709                      unsigned long addr_hint, unsigned int pages_per_huge_page)
4710 {
4711         int i, n, base, l;
4712         unsigned long addr = addr_hint &
4713                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4714
4715         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4716                 clear_gigantic_page(page, addr, pages_per_huge_page);
4717                 return;
4718         }
4719
4720         /* Clear sub-page to access last to keep its cache lines hot */
4721         might_sleep();
4722         n = (addr_hint - addr) / PAGE_SIZE;
4723         if (2 * n <= pages_per_huge_page) {
4724                 /* If sub-page to access in first half of huge page */
4725                 base = 0;
4726                 l = n;
4727                 /* Clear sub-pages at the end of huge page */
4728                 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
4729                         cond_resched();
4730                         clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4731                 }
4732         } else {
4733                 /* If sub-page to access in second half of huge page */
4734                 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4735                 l = pages_per_huge_page - n;
4736                 /* Clear sub-pages at the begin of huge page */
4737                 for (i = 0; i < base; i++) {
4738                         cond_resched();
4739                         clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4740                 }
4741         }
4742         /*
4743          * Clear remaining sub-pages in left-right-left-right pattern
4744          * towards the sub-page to access
4745          */
4746         for (i = 0; i < l; i++) {
4747                 int left_idx = base + i;
4748                 int right_idx = base + 2 * l - 1 - i;
4749
4750                 cond_resched();
4751                 clear_user_highpage(page + left_idx,
4752                                     addr + left_idx * PAGE_SIZE);
4753                 cond_resched();
4754                 clear_user_highpage(page + right_idx,
4755                                     addr + right_idx * PAGE_SIZE);
4756         }
4757 }
4758
4759 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4760                                     unsigned long addr,
4761                                     struct vm_area_struct *vma,
4762                                     unsigned int pages_per_huge_page)
4763 {
4764         int i;
4765         struct page *dst_base = dst;
4766         struct page *src_base = src;
4767
4768         for (i = 0; i < pages_per_huge_page; ) {
4769                 cond_resched();
4770                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4771
4772                 i++;
4773                 dst = mem_map_next(dst, dst_base, i);
4774                 src = mem_map_next(src, src_base, i);
4775         }
4776 }
4777
4778 void copy_user_huge_page(struct page *dst, struct page *src,
4779                          unsigned long addr, struct vm_area_struct *vma,
4780                          unsigned int pages_per_huge_page)
4781 {
4782         int i;
4783
4784         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4785                 copy_user_gigantic_page(dst, src, addr, vma,
4786                                         pages_per_huge_page);
4787                 return;
4788         }
4789
4790         might_sleep();
4791         for (i = 0; i < pages_per_huge_page; i++) {
4792                 cond_resched();
4793                 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4794         }
4795 }
4796
4797 long copy_huge_page_from_user(struct page *dst_page,
4798                                 const void __user *usr_src,
4799                                 unsigned int pages_per_huge_page,
4800                                 bool allow_pagefault)
4801 {
4802         void *src = (void *)usr_src;
4803         void *page_kaddr;
4804         unsigned long i, rc = 0;
4805         unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4806         struct page *subpage = dst_page;
4807
4808         for (i = 0; i < pages_per_huge_page;
4809              i++, subpage = mem_map_next(subpage, dst_page, i)) {
4810                 if (allow_pagefault)
4811                         page_kaddr = kmap(subpage);
4812                 else
4813                         page_kaddr = kmap_atomic(subpage);
4814                 rc = copy_from_user(page_kaddr,
4815                                 (const void __user *)(src + i * PAGE_SIZE),
4816                                 PAGE_SIZE);
4817                 if (allow_pagefault)
4818                         kunmap(subpage);
4819                 else
4820                         kunmap_atomic(page_kaddr);
4821
4822                 ret_val -= (PAGE_SIZE - rc);
4823                 if (rc)
4824                         break;
4825
4826                 cond_resched();
4827         }
4828         return ret_val;
4829 }
4830 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4831
4832 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4833
4834 static struct kmem_cache *page_ptl_cachep;
4835
4836 void __init ptlock_cache_init(void)
4837 {
4838         page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4839                         SLAB_PANIC, NULL);
4840 }
4841
4842 bool ptlock_alloc(struct page *page)
4843 {
4844         spinlock_t *ptl;
4845
4846         ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4847         if (!ptl)
4848                 return false;
4849         page->ptl = ptl;
4850         return true;
4851 }
4852
4853 void ptlock_free(struct page *page)
4854 {
4855         kmem_cache_free(page_ptl_cachep, page->ptl);
4856 }
4857 #endif