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