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