Merge tag 'v3.10.86' into linux-linaro-lsk-v3.10
[firefly-linux-kernel-4.4.55.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
63 #include <asm/io.h>
64 #include <asm/pgalloc.h>
65 #include <asm/uaccess.h>
66 #include <asm/tlb.h>
67 #include <asm/tlbflush.h>
68 #include <asm/pgtable.h>
69
70 #include "internal.h"
71
72 #ifdef LAST_NID_NOT_IN_PAGE_FLAGS
73 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_nid.
74 #endif
75
76 #ifndef CONFIG_NEED_MULTIPLE_NODES
77 /* use the per-pgdat data instead for discontigmem - mbligh */
78 unsigned long max_mapnr;
79 struct page *mem_map;
80
81 EXPORT_SYMBOL(max_mapnr);
82 EXPORT_SYMBOL(mem_map);
83 #endif
84
85 unsigned long num_physpages;
86 /*
87  * A number of key systems in x86 including ioremap() rely on the assumption
88  * that high_memory defines the upper bound on direct map memory, then end
89  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
90  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
91  * and ZONE_HIGHMEM.
92  */
93 void * high_memory;
94
95 EXPORT_SYMBOL(num_physpages);
96 EXPORT_SYMBOL(high_memory);
97
98 /*
99  * Randomize the address space (stacks, mmaps, brk, etc.).
100  *
101  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
102  *   as ancient (libc5 based) binaries can segfault. )
103  */
104 int randomize_va_space __read_mostly =
105 #ifdef CONFIG_COMPAT_BRK
106                                         1;
107 #else
108                                         2;
109 #endif
110
111 static int __init disable_randmaps(char *s)
112 {
113         randomize_va_space = 0;
114         return 1;
115 }
116 __setup("norandmaps", disable_randmaps);
117
118 unsigned long zero_pfn __read_mostly;
119 unsigned long highest_memmap_pfn __read_mostly;
120
121 EXPORT_SYMBOL(zero_pfn);
122
123 /*
124  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
125  */
126 static int __init init_zero_pfn(void)
127 {
128         zero_pfn = page_to_pfn(ZERO_PAGE(0));
129         return 0;
130 }
131 core_initcall(init_zero_pfn);
132
133
134 #if defined(SPLIT_RSS_COUNTING)
135
136 void sync_mm_rss(struct mm_struct *mm)
137 {
138         int i;
139
140         for (i = 0; i < NR_MM_COUNTERS; i++) {
141                 if (current->rss_stat.count[i]) {
142                         add_mm_counter(mm, i, current->rss_stat.count[i]);
143                         current->rss_stat.count[i] = 0;
144                 }
145         }
146         current->rss_stat.events = 0;
147 }
148
149 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
150 {
151         struct task_struct *task = current;
152
153         if (likely(task->mm == mm))
154                 task->rss_stat.count[member] += val;
155         else
156                 add_mm_counter(mm, member, val);
157 }
158 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
159 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
160
161 /* sync counter once per 64 page faults */
162 #define TASK_RSS_EVENTS_THRESH  (64)
163 static void check_sync_rss_stat(struct task_struct *task)
164 {
165         if (unlikely(task != current))
166                 return;
167         if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
168                 sync_mm_rss(task->mm);
169 }
170 #else /* SPLIT_RSS_COUNTING */
171
172 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
173 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
174
175 static void check_sync_rss_stat(struct task_struct *task)
176 {
177 }
178
179 #endif /* SPLIT_RSS_COUNTING */
180
181 #ifdef HAVE_GENERIC_MMU_GATHER
182
183 static int tlb_next_batch(struct mmu_gather *tlb)
184 {
185         struct mmu_gather_batch *batch;
186
187         batch = tlb->active;
188         if (batch->next) {
189                 tlb->active = batch->next;
190                 return 1;
191         }
192
193         if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
194                 return 0;
195
196         batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
197         if (!batch)
198                 return 0;
199
200         tlb->batch_count++;
201         batch->next = NULL;
202         batch->nr   = 0;
203         batch->max  = MAX_GATHER_BATCH;
204
205         tlb->active->next = batch;
206         tlb->active = batch;
207
208         return 1;
209 }
210
211 /* tlb_gather_mmu
212  *      Called to initialize an (on-stack) mmu_gather structure for page-table
213  *      tear-down from @mm. The @fullmm argument is used when @mm is without
214  *      users and we're going to destroy the full address space (exit/execve).
215  */
216 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end)
217 {
218         tlb->mm = mm;
219
220         /* Is it from 0 to ~0? */
221         tlb->fullmm     = !(start | (end+1));
222         tlb->need_flush_all = 0;
223         tlb->start      = start;
224         tlb->end        = end;
225         tlb->need_flush = 0;
226         tlb->local.next = NULL;
227         tlb->local.nr   = 0;
228         tlb->local.max  = ARRAY_SIZE(tlb->__pages);
229         tlb->active     = &tlb->local;
230         tlb->batch_count = 0;
231
232 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
233         tlb->batch = NULL;
234 #endif
235 }
236
237 void tlb_flush_mmu(struct mmu_gather *tlb)
238 {
239         struct mmu_gather_batch *batch;
240
241         if (!tlb->need_flush)
242                 return;
243         tlb->need_flush = 0;
244         tlb_flush(tlb);
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(src_mm, mmun_start,
1073                                                     mmun_end);
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(src_mm, mmun_start, mmun_end);
1091         return ret;
1092 }
1093
1094 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1095                                 struct vm_area_struct *vma, pmd_t *pmd,
1096                                 unsigned long addr, unsigned long end,
1097                                 struct zap_details *details)
1098 {
1099         struct mm_struct *mm = tlb->mm;
1100         int force_flush = 0;
1101         int rss[NR_MM_COUNTERS];
1102         spinlock_t *ptl;
1103         pte_t *start_pte;
1104         pte_t *pte;
1105
1106 again:
1107         init_rss_vec(rss);
1108         start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1109         pte = start_pte;
1110         arch_enter_lazy_mmu_mode();
1111         do {
1112                 pte_t ptent = *pte;
1113                 if (pte_none(ptent)) {
1114                         continue;
1115                 }
1116
1117                 if (pte_present(ptent)) {
1118                         struct page *page;
1119
1120                         page = vm_normal_page(vma, addr, ptent);
1121                         if (unlikely(details) && page) {
1122                                 /*
1123                                  * unmap_shared_mapping_pages() wants to
1124                                  * invalidate cache without truncating:
1125                                  * unmap shared but keep private pages.
1126                                  */
1127                                 if (details->check_mapping &&
1128                                     details->check_mapping != page->mapping)
1129                                         continue;
1130                                 /*
1131                                  * Each page->index must be checked when
1132                                  * invalidating or truncating nonlinear.
1133                                  */
1134                                 if (details->nonlinear_vma &&
1135                                     (page->index < details->first_index ||
1136                                      page->index > details->last_index))
1137                                         continue;
1138                         }
1139                         ptent = ptep_get_and_clear_full(mm, addr, pte,
1140                                                         tlb->fullmm);
1141                         tlb_remove_tlb_entry(tlb, pte, addr);
1142                         if (unlikely(!page))
1143                                 continue;
1144                         if (unlikely(details) && details->nonlinear_vma
1145                             && linear_page_index(details->nonlinear_vma,
1146                                                 addr) != page->index)
1147                                 set_pte_at(mm, addr, pte,
1148                                            pgoff_to_pte(page->index));
1149                         if (PageAnon(page))
1150                                 rss[MM_ANONPAGES]--;
1151                         else {
1152                                 if (pte_dirty(ptent))
1153                                         set_page_dirty(page);
1154                                 if (pte_young(ptent) &&
1155                                     likely(!VM_SequentialReadHint(vma)))
1156                                         mark_page_accessed(page);
1157                                 rss[MM_FILEPAGES]--;
1158                         }
1159                         page_remove_rmap(page);
1160                         if (unlikely(page_mapcount(page) < 0))
1161                                 print_bad_pte(vma, addr, ptent, page);
1162                         force_flush = !__tlb_remove_page(tlb, page);
1163                         if (force_flush)
1164                                 break;
1165                         continue;
1166                 }
1167                 /*
1168                  * If details->check_mapping, we leave swap entries;
1169                  * if details->nonlinear_vma, we leave file entries.
1170                  */
1171                 if (unlikely(details))
1172                         continue;
1173                 if (pte_file(ptent)) {
1174                         if (unlikely(!(vma->vm_flags & VM_NONLINEAR)))
1175                                 print_bad_pte(vma, addr, ptent, NULL);
1176                 } else {
1177                         swp_entry_t entry = pte_to_swp_entry(ptent);
1178
1179                         if (!non_swap_entry(entry))
1180                                 rss[MM_SWAPENTS]--;
1181                         else if (is_migration_entry(entry)) {
1182                                 struct page *page;
1183
1184                                 page = migration_entry_to_page(entry);
1185
1186                                 if (PageAnon(page))
1187                                         rss[MM_ANONPAGES]--;
1188                                 else
1189                                         rss[MM_FILEPAGES]--;
1190                         }
1191                         if (unlikely(!free_swap_and_cache(entry)))
1192                                 print_bad_pte(vma, addr, ptent, NULL);
1193                 }
1194                 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1195         } while (pte++, addr += PAGE_SIZE, addr != end);
1196
1197         add_mm_rss_vec(mm, rss);
1198         arch_leave_lazy_mmu_mode();
1199         pte_unmap_unlock(start_pte, ptl);
1200
1201         /*
1202          * mmu_gather ran out of room to batch pages, we break out of
1203          * the PTE lock to avoid doing the potential expensive TLB invalidate
1204          * and page-free while holding it.
1205          */
1206         if (force_flush) {
1207                 unsigned long old_end;
1208
1209                 force_flush = 0;
1210
1211                 /*
1212                  * Flush the TLB just for the previous segment,
1213                  * then update the range to be the remaining
1214                  * TLB range.
1215                  */
1216                 old_end = tlb->end;
1217                 tlb->end = addr;
1218
1219                 tlb_flush_mmu(tlb);
1220
1221                 tlb->start = addr;
1222                 tlb->end = old_end;
1223
1224                 if (addr != end)
1225                         goto again;
1226         }
1227
1228         return addr;
1229 }
1230
1231 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1232                                 struct vm_area_struct *vma, pud_t *pud,
1233                                 unsigned long addr, unsigned long end,
1234                                 struct zap_details *details)
1235 {
1236         pmd_t *pmd;
1237         unsigned long next;
1238
1239         pmd = pmd_offset(pud, addr);
1240         do {
1241                 next = pmd_addr_end(addr, end);
1242                 if (pmd_trans_huge(*pmd)) {
1243                         if (next - addr != HPAGE_PMD_SIZE) {
1244 #ifdef CONFIG_DEBUG_VM
1245                                 if (!rwsem_is_locked(&tlb->mm->mmap_sem)) {
1246                                         pr_err("%s: mmap_sem is unlocked! addr=0x%lx end=0x%lx vma->vm_start=0x%lx vma->vm_end=0x%lx\n",
1247                                                 __func__, addr, end,
1248                                                 vma->vm_start,
1249                                                 vma->vm_end);
1250                                         BUG();
1251                                 }
1252 #endif
1253                                 split_huge_page_pmd(vma, addr, pmd);
1254                         } else if (zap_huge_pmd(tlb, vma, pmd, addr))
1255                                 goto next;
1256                         /* fall through */
1257                 }
1258                 /*
1259                  * Here there can be other concurrent MADV_DONTNEED or
1260                  * trans huge page faults running, and if the pmd is
1261                  * none or trans huge it can change under us. This is
1262                  * because MADV_DONTNEED holds the mmap_sem in read
1263                  * mode.
1264                  */
1265                 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1266                         goto next;
1267                 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1268 next:
1269                 cond_resched();
1270         } while (pmd++, addr = next, addr != end);
1271
1272         return addr;
1273 }
1274
1275 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1276                                 struct vm_area_struct *vma, pgd_t *pgd,
1277                                 unsigned long addr, unsigned long end,
1278                                 struct zap_details *details)
1279 {
1280         pud_t *pud;
1281         unsigned long next;
1282
1283         pud = pud_offset(pgd, addr);
1284         do {
1285                 next = pud_addr_end(addr, end);
1286                 if (pud_none_or_clear_bad(pud))
1287                         continue;
1288                 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1289         } while (pud++, addr = next, addr != end);
1290
1291         return addr;
1292 }
1293
1294 static void unmap_page_range(struct mmu_gather *tlb,
1295                              struct vm_area_struct *vma,
1296                              unsigned long addr, unsigned long end,
1297                              struct zap_details *details)
1298 {
1299         pgd_t *pgd;
1300         unsigned long next;
1301
1302         if (details && !details->check_mapping && !details->nonlinear_vma)
1303                 details = NULL;
1304
1305         BUG_ON(addr >= end);
1306         mem_cgroup_uncharge_start();
1307         tlb_start_vma(tlb, vma);
1308         pgd = pgd_offset(vma->vm_mm, addr);
1309         do {
1310                 next = pgd_addr_end(addr, end);
1311                 if (pgd_none_or_clear_bad(pgd))
1312                         continue;
1313                 next = zap_pud_range(tlb, vma, pgd, addr, next, details);
1314         } while (pgd++, addr = next, addr != end);
1315         tlb_end_vma(tlb, vma);
1316         mem_cgroup_uncharge_end();
1317 }
1318
1319
1320 static void unmap_single_vma(struct mmu_gather *tlb,
1321                 struct vm_area_struct *vma, unsigned long start_addr,
1322                 unsigned long end_addr,
1323                 struct zap_details *details)
1324 {
1325         unsigned long start = max(vma->vm_start, start_addr);
1326         unsigned long end;
1327
1328         if (start >= vma->vm_end)
1329                 return;
1330         end = min(vma->vm_end, end_addr);
1331         if (end <= vma->vm_start)
1332                 return;
1333
1334         if (vma->vm_file)
1335                 uprobe_munmap(vma, start, end);
1336
1337         if (unlikely(vma->vm_flags & VM_PFNMAP))
1338                 untrack_pfn(vma, 0, 0);
1339
1340         if (start != end) {
1341                 if (unlikely(is_vm_hugetlb_page(vma))) {
1342                         /*
1343                          * It is undesirable to test vma->vm_file as it
1344                          * should be non-null for valid hugetlb area.
1345                          * However, vm_file will be NULL in the error
1346                          * cleanup path of do_mmap_pgoff. When
1347                          * hugetlbfs ->mmap method fails,
1348                          * do_mmap_pgoff() nullifies vma->vm_file
1349                          * before calling this function to clean up.
1350                          * Since no pte has actually been setup, it is
1351                          * safe to do nothing in this case.
1352                          */
1353                         if (vma->vm_file) {
1354                                 mutex_lock(&vma->vm_file->f_mapping->i_mmap_mutex);
1355                                 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1356                                 mutex_unlock(&vma->vm_file->f_mapping->i_mmap_mutex);
1357                         }
1358                 } else
1359                         unmap_page_range(tlb, vma, start, end, details);
1360         }
1361 }
1362
1363 /**
1364  * unmap_vmas - unmap a range of memory covered by a list of vma's
1365  * @tlb: address of the caller's struct mmu_gather
1366  * @vma: the starting vma
1367  * @start_addr: virtual address at which to start unmapping
1368  * @end_addr: virtual address at which to end unmapping
1369  *
1370  * Unmap all pages in the vma list.
1371  *
1372  * Only addresses between `start' and `end' will be unmapped.
1373  *
1374  * The VMA list must be sorted in ascending virtual address order.
1375  *
1376  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1377  * range after unmap_vmas() returns.  So the only responsibility here is to
1378  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1379  * drops the lock and schedules.
1380  */
1381 void unmap_vmas(struct mmu_gather *tlb,
1382                 struct vm_area_struct *vma, unsigned long start_addr,
1383                 unsigned long end_addr)
1384 {
1385         struct mm_struct *mm = vma->vm_mm;
1386
1387         mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1388         for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1389                 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1390         mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1391 }
1392
1393 /**
1394  * zap_page_range - remove user pages in a given range
1395  * @vma: vm_area_struct holding the applicable pages
1396  * @start: starting address of pages to zap
1397  * @size: number of bytes to zap
1398  * @details: details of nonlinear truncation or shared cache invalidation
1399  *
1400  * Caller must protect the VMA list
1401  */
1402 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1403                 unsigned long size, struct zap_details *details)
1404 {
1405         struct mm_struct *mm = vma->vm_mm;
1406         struct mmu_gather tlb;
1407         unsigned long end = start + size;
1408
1409         lru_add_drain();
1410         tlb_gather_mmu(&tlb, mm, start, end);
1411         update_hiwater_rss(mm);
1412         mmu_notifier_invalidate_range_start(mm, start, end);
1413         for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
1414                 unmap_single_vma(&tlb, vma, start, end, details);
1415         mmu_notifier_invalidate_range_end(mm, start, end);
1416         tlb_finish_mmu(&tlb, start, end);
1417 }
1418
1419 /**
1420  * zap_page_range_single - remove user pages in a given range
1421  * @vma: vm_area_struct holding the applicable pages
1422  * @address: starting address of pages to zap
1423  * @size: number of bytes to zap
1424  * @details: details of nonlinear truncation or shared cache invalidation
1425  *
1426  * The range must fit into one VMA.
1427  */
1428 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1429                 unsigned long size, struct zap_details *details)
1430 {
1431         struct mm_struct *mm = vma->vm_mm;
1432         struct mmu_gather tlb;
1433         unsigned long end = address + size;
1434
1435         lru_add_drain();
1436         tlb_gather_mmu(&tlb, mm, address, end);
1437         update_hiwater_rss(mm);
1438         mmu_notifier_invalidate_range_start(mm, address, end);
1439         unmap_single_vma(&tlb, vma, address, end, details);
1440         mmu_notifier_invalidate_range_end(mm, address, end);
1441         tlb_finish_mmu(&tlb, address, end);
1442 }
1443
1444 /**
1445  * zap_vma_ptes - remove ptes mapping the vma
1446  * @vma: vm_area_struct holding ptes to be zapped
1447  * @address: starting address of pages to zap
1448  * @size: number of bytes to zap
1449  *
1450  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1451  *
1452  * The entire address range must be fully contained within the vma.
1453  *
1454  * Returns 0 if successful.
1455  */
1456 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1457                 unsigned long size)
1458 {
1459         if (address < vma->vm_start || address + size > vma->vm_end ||
1460                         !(vma->vm_flags & VM_PFNMAP))
1461                 return -1;
1462         zap_page_range_single(vma, address, size, NULL);
1463         return 0;
1464 }
1465 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1466
1467 /**
1468  * follow_page_mask - look up a page descriptor from a user-virtual address
1469  * @vma: vm_area_struct mapping @address
1470  * @address: virtual address to look up
1471  * @flags: flags modifying lookup behaviour
1472  * @page_mask: on output, *page_mask is set according to the size of the page
1473  *
1474  * @flags can have FOLL_ flags set, defined in <linux/mm.h>
1475  *
1476  * Returns the mapped (struct page *), %NULL if no mapping exists, or
1477  * an error pointer if there is a mapping to something not represented
1478  * by a page descriptor (see also vm_normal_page()).
1479  */
1480 struct page *follow_page_mask(struct vm_area_struct *vma,
1481                               unsigned long address, unsigned int flags,
1482                               unsigned int *page_mask)
1483 {
1484         pgd_t *pgd;
1485         pud_t *pud;
1486         pmd_t *pmd;
1487         pte_t *ptep, pte;
1488         spinlock_t *ptl;
1489         struct page *page;
1490         struct mm_struct *mm = vma->vm_mm;
1491
1492         *page_mask = 0;
1493
1494         page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
1495         if (!IS_ERR(page)) {
1496                 BUG_ON(flags & FOLL_GET);
1497                 goto out;
1498         }
1499
1500         page = NULL;
1501         pgd = pgd_offset(mm, address);
1502         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
1503                 goto no_page_table;
1504
1505         pud = pud_offset(pgd, address);
1506         if (pud_none(*pud))
1507                 goto no_page_table;
1508         if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
1509                 BUG_ON(flags & FOLL_GET);
1510                 page = follow_huge_pud(mm, address, pud, flags & FOLL_WRITE);
1511                 goto out;
1512         }
1513         if (unlikely(pud_bad(*pud)))
1514                 goto no_page_table;
1515
1516         pmd = pmd_offset(pud, address);
1517         if (pmd_none(*pmd))
1518                 goto no_page_table;
1519         if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) {
1520                 BUG_ON(flags & FOLL_GET);
1521                 page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE);
1522                 goto out;
1523         }
1524         if ((flags & FOLL_NUMA) && pmd_numa(*pmd))
1525                 goto no_page_table;
1526         if (pmd_trans_huge(*pmd)) {
1527                 if (flags & FOLL_SPLIT) {
1528                         split_huge_page_pmd(vma, address, pmd);
1529                         goto split_fallthrough;
1530                 }
1531                 spin_lock(&mm->page_table_lock);
1532                 if (likely(pmd_trans_huge(*pmd))) {
1533                         if (unlikely(pmd_trans_splitting(*pmd))) {
1534                                 spin_unlock(&mm->page_table_lock);
1535                                 wait_split_huge_page(vma->anon_vma, pmd);
1536                         } else {
1537                                 page = follow_trans_huge_pmd(vma, address,
1538                                                              pmd, flags);
1539                                 spin_unlock(&mm->page_table_lock);
1540                                 *page_mask = HPAGE_PMD_NR - 1;
1541                                 goto out;
1542                         }
1543                 } else
1544                         spin_unlock(&mm->page_table_lock);
1545                 /* fall through */
1546         }
1547 split_fallthrough:
1548         if (unlikely(pmd_bad(*pmd)))
1549                 goto no_page_table;
1550
1551         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
1552
1553         pte = *ptep;
1554         if (!pte_present(pte)) {
1555                 swp_entry_t entry;
1556                 /*
1557                  * KSM's break_ksm() relies upon recognizing a ksm page
1558                  * even while it is being migrated, so for that case we
1559                  * need migration_entry_wait().
1560                  */
1561                 if (likely(!(flags & FOLL_MIGRATION)))
1562                         goto no_page;
1563                 if (pte_none(pte) || pte_file(pte))
1564                         goto no_page;
1565                 entry = pte_to_swp_entry(pte);
1566                 if (!is_migration_entry(entry))
1567                         goto no_page;
1568                 pte_unmap_unlock(ptep, ptl);
1569                 migration_entry_wait(mm, pmd, address);
1570                 goto split_fallthrough;
1571         }
1572         if ((flags & FOLL_NUMA) && pte_numa(pte))
1573                 goto no_page;
1574         if ((flags & FOLL_WRITE) && !pte_write(pte))
1575                 goto unlock;
1576
1577         page = vm_normal_page(vma, address, pte);
1578         if (unlikely(!page)) {
1579                 if ((flags & FOLL_DUMP) ||
1580                     !is_zero_pfn(pte_pfn(pte)))
1581                         goto bad_page;
1582                 page = pte_page(pte);
1583         }
1584
1585         if (flags & FOLL_GET)
1586                 get_page_foll(page);
1587         if (flags & FOLL_TOUCH) {
1588                 if ((flags & FOLL_WRITE) &&
1589                     !pte_dirty(pte) && !PageDirty(page))
1590                         set_page_dirty(page);
1591                 /*
1592                  * pte_mkyoung() would be more correct here, but atomic care
1593                  * is needed to avoid losing the dirty bit: it is easier to use
1594                  * mark_page_accessed().
1595                  */
1596                 mark_page_accessed(page);
1597         }
1598         if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1599                 /*
1600                  * The preliminary mapping check is mainly to avoid the
1601                  * pointless overhead of lock_page on the ZERO_PAGE
1602                  * which might bounce very badly if there is contention.
1603                  *
1604                  * If the page is already locked, we don't need to
1605                  * handle it now - vmscan will handle it later if and
1606                  * when it attempts to reclaim the page.
1607                  */
1608                 if (page->mapping && trylock_page(page)) {
1609                         lru_add_drain();  /* push cached pages to LRU */
1610                         /*
1611                          * Because we lock page here, and migration is
1612                          * blocked by the pte's page reference, and we
1613                          * know the page is still mapped, we don't even
1614                          * need to check for file-cache page truncation.
1615                          */
1616                         mlock_vma_page(page);
1617                         unlock_page(page);
1618                 }
1619         }
1620 unlock:
1621         pte_unmap_unlock(ptep, ptl);
1622 out:
1623         return page;
1624
1625 bad_page:
1626         pte_unmap_unlock(ptep, ptl);
1627         return ERR_PTR(-EFAULT);
1628
1629 no_page:
1630         pte_unmap_unlock(ptep, ptl);
1631         if (!pte_none(pte))
1632                 return page;
1633
1634 no_page_table:
1635         /*
1636          * When core dumping an enormous anonymous area that nobody
1637          * has touched so far, we don't want to allocate unnecessary pages or
1638          * page tables.  Return error instead of NULL to skip handle_mm_fault,
1639          * then get_dump_page() will return NULL to leave a hole in the dump.
1640          * But we can only make this optimization where a hole would surely
1641          * be zero-filled if handle_mm_fault() actually did handle it.
1642          */
1643         if ((flags & FOLL_DUMP) &&
1644             (!vma->vm_ops || !vma->vm_ops->fault))
1645                 return ERR_PTR(-EFAULT);
1646         return page;
1647 }
1648
1649 static inline int stack_guard_page(struct vm_area_struct *vma, unsigned long addr)
1650 {
1651         return stack_guard_page_start(vma, addr) ||
1652                stack_guard_page_end(vma, addr+PAGE_SIZE);
1653 }
1654
1655 /**
1656  * __get_user_pages() - pin user pages in memory
1657  * @tsk:        task_struct of target task
1658  * @mm:         mm_struct of target mm
1659  * @start:      starting user address
1660  * @nr_pages:   number of pages from start to pin
1661  * @gup_flags:  flags modifying pin behaviour
1662  * @pages:      array that receives pointers to the pages pinned.
1663  *              Should be at least nr_pages long. Or NULL, if caller
1664  *              only intends to ensure the pages are faulted in.
1665  * @vmas:       array of pointers to vmas corresponding to each page.
1666  *              Or NULL if the caller does not require them.
1667  * @nonblocking: whether waiting for disk IO or mmap_sem contention
1668  *
1669  * Returns number of pages pinned. This may be fewer than the number
1670  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1671  * were pinned, returns -errno. Each page returned must be released
1672  * with a put_page() call when it is finished with. vmas will only
1673  * remain valid while mmap_sem is held.
1674  *
1675  * Must be called with mmap_sem held for read or write.
1676  *
1677  * __get_user_pages walks a process's page tables and takes a reference to
1678  * each struct page that each user address corresponds to at a given
1679  * instant. That is, it takes the page that would be accessed if a user
1680  * thread accesses the given user virtual address at that instant.
1681  *
1682  * This does not guarantee that the page exists in the user mappings when
1683  * __get_user_pages returns, and there may even be a completely different
1684  * page there in some cases (eg. if mmapped pagecache has been invalidated
1685  * and subsequently re faulted). However it does guarantee that the page
1686  * won't be freed completely. And mostly callers simply care that the page
1687  * contains data that was valid *at some point in time*. Typically, an IO
1688  * or similar operation cannot guarantee anything stronger anyway because
1689  * locks can't be held over the syscall boundary.
1690  *
1691  * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1692  * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1693  * appropriate) must be called after the page is finished with, and
1694  * before put_page is called.
1695  *
1696  * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
1697  * or mmap_sem contention, and if waiting is needed to pin all pages,
1698  * *@nonblocking will be set to 0.
1699  *
1700  * In most cases, get_user_pages or get_user_pages_fast should be used
1701  * instead of __get_user_pages. __get_user_pages should be used only if
1702  * you need some special @gup_flags.
1703  */
1704 long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
1705                 unsigned long start, unsigned long nr_pages,
1706                 unsigned int gup_flags, struct page **pages,
1707                 struct vm_area_struct **vmas, int *nonblocking)
1708 {
1709         long i;
1710         unsigned long vm_flags;
1711         unsigned int page_mask;
1712
1713         if (!nr_pages)
1714                 return 0;
1715
1716         VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
1717
1718         /* 
1719          * Require read or write permissions.
1720          * If FOLL_FORCE is set, we only require the "MAY" flags.
1721          */
1722         vm_flags  = (gup_flags & FOLL_WRITE) ?
1723                         (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1724         vm_flags &= (gup_flags & FOLL_FORCE) ?
1725                         (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1726
1727         /*
1728          * If FOLL_FORCE and FOLL_NUMA are both set, handle_mm_fault
1729          * would be called on PROT_NONE ranges. We must never invoke
1730          * handle_mm_fault on PROT_NONE ranges or the NUMA hinting
1731          * page faults would unprotect the PROT_NONE ranges if
1732          * _PAGE_NUMA and _PAGE_PROTNONE are sharing the same pte/pmd
1733          * bitflag. So to avoid that, don't set FOLL_NUMA if
1734          * FOLL_FORCE is set.
1735          */
1736         if (!(gup_flags & FOLL_FORCE))
1737                 gup_flags |= FOLL_NUMA;
1738
1739         i = 0;
1740
1741         do {
1742                 struct vm_area_struct *vma;
1743
1744                 vma = find_extend_vma(mm, start);
1745                 if (!vma && in_gate_area(mm, start)) {
1746                         unsigned long pg = start & PAGE_MASK;
1747                         pgd_t *pgd;
1748                         pud_t *pud;
1749                         pmd_t *pmd;
1750                         pte_t *pte;
1751
1752                         /* user gate pages are read-only */
1753                         if (gup_flags & FOLL_WRITE)
1754                                 return i ? : -EFAULT;
1755                         if (pg > TASK_SIZE)
1756                                 pgd = pgd_offset_k(pg);
1757                         else
1758                                 pgd = pgd_offset_gate(mm, pg);
1759                         BUG_ON(pgd_none(*pgd));
1760                         pud = pud_offset(pgd, pg);
1761                         BUG_ON(pud_none(*pud));
1762                         pmd = pmd_offset(pud, pg);
1763                         if (pmd_none(*pmd))
1764                                 return i ? : -EFAULT;
1765                         VM_BUG_ON(pmd_trans_huge(*pmd));
1766                         pte = pte_offset_map(pmd, pg);
1767                         if (pte_none(*pte)) {
1768                                 pte_unmap(pte);
1769                                 return i ? : -EFAULT;
1770                         }
1771                         vma = get_gate_vma(mm);
1772                         if (pages) {
1773                                 struct page *page;
1774
1775                                 page = vm_normal_page(vma, start, *pte);
1776                                 if (!page) {
1777                                         if (!(gup_flags & FOLL_DUMP) &&
1778                                              is_zero_pfn(pte_pfn(*pte)))
1779                                                 page = pte_page(*pte);
1780                                         else {
1781                                                 pte_unmap(pte);
1782                                                 return i ? : -EFAULT;
1783                                         }
1784                                 }
1785                                 pages[i] = page;
1786                                 get_page(page);
1787                         }
1788                         pte_unmap(pte);
1789                         page_mask = 0;
1790                         goto next_page;
1791                 }
1792
1793                 if (!vma ||
1794                     (vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1795                     !(vm_flags & vma->vm_flags))
1796                         return i ? : -EFAULT;
1797
1798                 if (is_vm_hugetlb_page(vma)) {
1799                         i = follow_hugetlb_page(mm, vma, pages, vmas,
1800                                         &start, &nr_pages, i, gup_flags);
1801                         continue;
1802                 }
1803
1804                 do {
1805                         struct page *page;
1806                         unsigned int foll_flags = gup_flags;
1807                         unsigned int page_increm;
1808
1809                         /*
1810                          * If we have a pending SIGKILL, don't keep faulting
1811                          * pages and potentially allocating memory.
1812                          */
1813                         if (unlikely(fatal_signal_pending(current)))
1814                                 return i ? i : -ERESTARTSYS;
1815
1816                         cond_resched();
1817                         while (!(page = follow_page_mask(vma, start,
1818                                                 foll_flags, &page_mask))) {
1819                                 int ret;
1820                                 unsigned int fault_flags = 0;
1821
1822                                 /* For mlock, just skip the stack guard page. */
1823                                 if (foll_flags & FOLL_MLOCK) {
1824                                         if (stack_guard_page(vma, start))
1825                                                 goto next_page;
1826                                 }
1827                                 if (foll_flags & FOLL_WRITE)
1828                                         fault_flags |= FAULT_FLAG_WRITE;
1829                                 if (nonblocking)
1830                                         fault_flags |= FAULT_FLAG_ALLOW_RETRY;
1831                                 if (foll_flags & FOLL_NOWAIT)
1832                                         fault_flags |= (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT);
1833
1834                                 ret = handle_mm_fault(mm, vma, start,
1835                                                         fault_flags);
1836
1837                                 if (ret & VM_FAULT_ERROR) {
1838                                         if (ret & VM_FAULT_OOM)
1839                                                 return i ? i : -ENOMEM;
1840                                         if (ret & (VM_FAULT_HWPOISON |
1841                                                    VM_FAULT_HWPOISON_LARGE)) {
1842                                                 if (i)
1843                                                         return i;
1844                                                 else if (gup_flags & FOLL_HWPOISON)
1845                                                         return -EHWPOISON;
1846                                                 else
1847                                                         return -EFAULT;
1848                                         }
1849                                         if (ret & (VM_FAULT_SIGBUS |
1850                                                    VM_FAULT_SIGSEGV))
1851                                                 return i ? i : -EFAULT;
1852                                         BUG();
1853                                 }
1854
1855                                 if (tsk) {
1856                                         if (ret & VM_FAULT_MAJOR)
1857                                                 tsk->maj_flt++;
1858                                         else
1859                                                 tsk->min_flt++;
1860                                 }
1861
1862                                 if (ret & VM_FAULT_RETRY) {
1863                                         if (nonblocking)
1864                                                 *nonblocking = 0;
1865                                         return i;
1866                                 }
1867
1868                                 /*
1869                                  * The VM_FAULT_WRITE bit tells us that
1870                                  * do_wp_page has broken COW when necessary,
1871                                  * even if maybe_mkwrite decided not to set
1872                                  * pte_write. We can thus safely do subsequent
1873                                  * page lookups as if they were reads. But only
1874                                  * do so when looping for pte_write is futile:
1875                                  * in some cases userspace may also be wanting
1876                                  * to write to the gotten user page, which a
1877                                  * read fault here might prevent (a readonly
1878                                  * page might get reCOWed by userspace write).
1879                                  */
1880                                 if ((ret & VM_FAULT_WRITE) &&
1881                                     !(vma->vm_flags & VM_WRITE))
1882                                         foll_flags &= ~FOLL_WRITE;
1883
1884                                 cond_resched();
1885                         }
1886                         if (IS_ERR(page))
1887                                 return i ? i : PTR_ERR(page);
1888                         if (pages) {
1889                                 pages[i] = page;
1890
1891                                 flush_anon_page(vma, page, start);
1892                                 flush_dcache_page(page);
1893                                 page_mask = 0;
1894                         }
1895 next_page:
1896                         if (vmas) {
1897                                 vmas[i] = vma;
1898                                 page_mask = 0;
1899                         }
1900                         page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
1901                         if (page_increm > nr_pages)
1902                                 page_increm = nr_pages;
1903                         i += page_increm;
1904                         start += page_increm * PAGE_SIZE;
1905                         nr_pages -= page_increm;
1906                 } while (nr_pages && start < vma->vm_end);
1907         } while (nr_pages);
1908         return i;
1909 }
1910 EXPORT_SYMBOL(__get_user_pages);
1911
1912 /*
1913  * fixup_user_fault() - manually resolve a user page fault
1914  * @tsk:        the task_struct to use for page fault accounting, or
1915  *              NULL if faults are not to be recorded.
1916  * @mm:         mm_struct of target mm
1917  * @address:    user address
1918  * @fault_flags:flags to pass down to handle_mm_fault()
1919  *
1920  * This is meant to be called in the specific scenario where for locking reasons
1921  * we try to access user memory in atomic context (within a pagefault_disable()
1922  * section), this returns -EFAULT, and we want to resolve the user fault before
1923  * trying again.
1924  *
1925  * Typically this is meant to be used by the futex code.
1926  *
1927  * The main difference with get_user_pages() is that this function will
1928  * unconditionally call handle_mm_fault() which will in turn perform all the
1929  * necessary SW fixup of the dirty and young bits in the PTE, while
1930  * handle_mm_fault() only guarantees to update these in the struct page.
1931  *
1932  * This is important for some architectures where those bits also gate the
1933  * access permission to the page because they are maintained in software.  On
1934  * such architectures, gup() will not be enough to make a subsequent access
1935  * succeed.
1936  *
1937  * This should be called with the mm_sem held for read.
1938  */
1939 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
1940                      unsigned long address, unsigned int fault_flags)
1941 {
1942         struct vm_area_struct *vma;
1943         vm_flags_t vm_flags;
1944         int ret;
1945
1946         vma = find_extend_vma(mm, address);
1947         if (!vma || address < vma->vm_start)
1948                 return -EFAULT;
1949
1950         vm_flags = (fault_flags & FAULT_FLAG_WRITE) ? VM_WRITE : VM_READ;
1951         if (!(vm_flags & vma->vm_flags))
1952                 return -EFAULT;
1953
1954         ret = handle_mm_fault(mm, vma, address, fault_flags);
1955         if (ret & VM_FAULT_ERROR) {
1956                 if (ret & VM_FAULT_OOM)
1957                         return -ENOMEM;
1958                 if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
1959                         return -EHWPOISON;
1960                 if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
1961                         return -EFAULT;
1962                 BUG();
1963         }
1964         if (tsk) {
1965                 if (ret & VM_FAULT_MAJOR)
1966                         tsk->maj_flt++;
1967                 else
1968                         tsk->min_flt++;
1969         }
1970         return 0;
1971 }
1972
1973 /*
1974  * get_user_pages() - pin user pages in memory
1975  * @tsk:        the task_struct to use for page fault accounting, or
1976  *              NULL if faults are not to be recorded.
1977  * @mm:         mm_struct of target mm
1978  * @start:      starting user address
1979  * @nr_pages:   number of pages from start to pin
1980  * @write:      whether pages will be written to by the caller
1981  * @force:      whether to force write access even if user mapping is
1982  *              readonly. This will result in the page being COWed even
1983  *              in MAP_SHARED mappings. You do not want this.
1984  * @pages:      array that receives pointers to the pages pinned.
1985  *              Should be at least nr_pages long. Or NULL, if caller
1986  *              only intends to ensure the pages are faulted in.
1987  * @vmas:       array of pointers to vmas corresponding to each page.
1988  *              Or NULL if the caller does not require them.
1989  *
1990  * Returns number of pages pinned. This may be fewer than the number
1991  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1992  * were pinned, returns -errno. Each page returned must be released
1993  * with a put_page() call when it is finished with. vmas will only
1994  * remain valid while mmap_sem is held.
1995  *
1996  * Must be called with mmap_sem held for read or write.
1997  *
1998  * get_user_pages walks a process's page tables and takes a reference to
1999  * each struct page that each user address corresponds to at a given
2000  * instant. That is, it takes the page that would be accessed if a user
2001  * thread accesses the given user virtual address at that instant.
2002  *
2003  * This does not guarantee that the page exists in the user mappings when
2004  * get_user_pages returns, and there may even be a completely different
2005  * page there in some cases (eg. if mmapped pagecache has been invalidated
2006  * and subsequently re faulted). However it does guarantee that the page
2007  * won't be freed completely. And mostly callers simply care that the page
2008  * contains data that was valid *at some point in time*. Typically, an IO
2009  * or similar operation cannot guarantee anything stronger anyway because
2010  * locks can't be held over the syscall boundary.
2011  *
2012  * If write=0, the page must not be written to. If the page is written to,
2013  * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called
2014  * after the page is finished with, and before put_page is called.
2015  *
2016  * get_user_pages is typically used for fewer-copy IO operations, to get a
2017  * handle on the memory by some means other than accesses via the user virtual
2018  * addresses. The pages may be submitted for DMA to devices or accessed via
2019  * their kernel linear mapping (via the kmap APIs). Care should be taken to
2020  * use the correct cache flushing APIs.
2021  *
2022  * See also get_user_pages_fast, for performance critical applications.
2023  */
2024 long get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
2025                 unsigned long start, unsigned long nr_pages, int write,
2026                 int force, struct page **pages, struct vm_area_struct **vmas)
2027 {
2028         int flags = FOLL_TOUCH;
2029
2030         if (pages)
2031                 flags |= FOLL_GET;
2032         if (write)
2033                 flags |= FOLL_WRITE;
2034         if (force)
2035                 flags |= FOLL_FORCE;
2036
2037         return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas,
2038                                 NULL);
2039 }
2040 EXPORT_SYMBOL(get_user_pages);
2041
2042 /**
2043  * get_dump_page() - pin user page in memory while writing it to core dump
2044  * @addr: user address
2045  *
2046  * Returns struct page pointer of user page pinned for dump,
2047  * to be freed afterwards by page_cache_release() or put_page().
2048  *
2049  * Returns NULL on any kind of failure - a hole must then be inserted into
2050  * the corefile, to preserve alignment with its headers; and also returns
2051  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
2052  * allowing a hole to be left in the corefile to save diskspace.
2053  *
2054  * Called without mmap_sem, but after all other threads have been killed.
2055  */
2056 #ifdef CONFIG_ELF_CORE
2057 struct page *get_dump_page(unsigned long addr)
2058 {
2059         struct vm_area_struct *vma;
2060         struct page *page;
2061
2062         if (__get_user_pages(current, current->mm, addr, 1,
2063                              FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
2064                              NULL) < 1)
2065                 return NULL;
2066         flush_cache_page(vma, addr, page_to_pfn(page));
2067         return page;
2068 }
2069 #endif /* CONFIG_ELF_CORE */
2070
2071 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
2072                         spinlock_t **ptl)
2073 {
2074         pgd_t * pgd = pgd_offset(mm, addr);
2075         pud_t * pud = pud_alloc(mm, pgd, addr);
2076         if (pud) {
2077                 pmd_t * pmd = pmd_alloc(mm, pud, addr);
2078                 if (pmd) {
2079                         VM_BUG_ON(pmd_trans_huge(*pmd));
2080                         return pte_alloc_map_lock(mm, pmd, addr, ptl);
2081                 }
2082         }
2083         return NULL;
2084 }
2085
2086 /*
2087  * This is the old fallback for page remapping.
2088  *
2089  * For historical reasons, it only allows reserved pages. Only
2090  * old drivers should use this, and they needed to mark their
2091  * pages reserved for the old functions anyway.
2092  */
2093 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
2094                         struct page *page, pgprot_t prot)
2095 {
2096         struct mm_struct *mm = vma->vm_mm;
2097         int retval;
2098         pte_t *pte;
2099         spinlock_t *ptl;
2100
2101         retval = -EINVAL;
2102         if (PageAnon(page))
2103                 goto out;
2104         retval = -ENOMEM;
2105         flush_dcache_page(page);
2106         pte = get_locked_pte(mm, addr, &ptl);
2107         if (!pte)
2108                 goto out;
2109         retval = -EBUSY;
2110         if (!pte_none(*pte))
2111                 goto out_unlock;
2112
2113         /* Ok, finally just insert the thing.. */
2114         get_page(page);
2115         inc_mm_counter_fast(mm, MM_FILEPAGES);
2116         page_add_file_rmap(page);
2117         set_pte_at(mm, addr, pte, mk_pte(page, prot));
2118
2119         retval = 0;
2120         pte_unmap_unlock(pte, ptl);
2121         return retval;
2122 out_unlock:
2123         pte_unmap_unlock(pte, ptl);
2124 out:
2125         return retval;
2126 }
2127
2128 /**
2129  * vm_insert_page - insert single page into user vma
2130  * @vma: user vma to map to
2131  * @addr: target user address of this page
2132  * @page: source kernel page
2133  *
2134  * This allows drivers to insert individual pages they've allocated
2135  * into a user vma.
2136  *
2137  * The page has to be a nice clean _individual_ kernel allocation.
2138  * If you allocate a compound page, you need to have marked it as
2139  * such (__GFP_COMP), or manually just split the page up yourself
2140  * (see split_page()).
2141  *
2142  * NOTE! Traditionally this was done with "remap_pfn_range()" which
2143  * took an arbitrary page protection parameter. This doesn't allow
2144  * that. Your vma protection will have to be set up correctly, which
2145  * means that if you want a shared writable mapping, you'd better
2146  * ask for a shared writable mapping!
2147  *
2148  * The page does not need to be reserved.
2149  *
2150  * Usually this function is called from f_op->mmap() handler
2151  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
2152  * Caller must set VM_MIXEDMAP on vma if it wants to call this
2153  * function from other places, for example from page-fault handler.
2154  */
2155 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2156                         struct page *page)
2157 {
2158         if (addr < vma->vm_start || addr >= vma->vm_end)
2159                 return -EFAULT;
2160         if (!page_count(page))
2161                 return -EINVAL;
2162         if (!(vma->vm_flags & VM_MIXEDMAP)) {
2163                 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
2164                 BUG_ON(vma->vm_flags & VM_PFNMAP);
2165                 vma->vm_flags |= VM_MIXEDMAP;
2166         }
2167         return insert_page(vma, addr, page, vma->vm_page_prot);
2168 }
2169 EXPORT_SYMBOL(vm_insert_page);
2170
2171 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2172                         unsigned long pfn, pgprot_t prot)
2173 {
2174         struct mm_struct *mm = vma->vm_mm;
2175         int retval;
2176         pte_t *pte, entry;
2177         spinlock_t *ptl;
2178
2179         retval = -ENOMEM;
2180         pte = get_locked_pte(mm, addr, &ptl);
2181         if (!pte)
2182                 goto out;
2183         retval = -EBUSY;
2184         if (!pte_none(*pte))
2185                 goto out_unlock;
2186
2187         /* Ok, finally just insert the thing.. */
2188         entry = pte_mkspecial(pfn_pte(pfn, prot));
2189         set_pte_at(mm, addr, pte, entry);
2190         update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2191
2192         retval = 0;
2193 out_unlock:
2194         pte_unmap_unlock(pte, ptl);
2195 out:
2196         return retval;
2197 }
2198
2199 /**
2200  * vm_insert_pfn - insert single pfn into user vma
2201  * @vma: user vma to map to
2202  * @addr: target user address of this page
2203  * @pfn: source kernel pfn
2204  *
2205  * Similar to vm_insert_page, this allows drivers to insert individual pages
2206  * they've allocated into a user vma. Same comments apply.
2207  *
2208  * This function should only be called from a vm_ops->fault handler, and
2209  * in that case the handler should return NULL.
2210  *
2211  * vma cannot be a COW mapping.
2212  *
2213  * As this is called only for pages that do not currently exist, we
2214  * do not need to flush old virtual caches or the TLB.
2215  */
2216 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2217                         unsigned long pfn)
2218 {
2219         int ret;
2220         pgprot_t pgprot = vma->vm_page_prot;
2221         /*
2222          * Technically, architectures with pte_special can avoid all these
2223          * restrictions (same for remap_pfn_range).  However we would like
2224          * consistency in testing and feature parity among all, so we should
2225          * try to keep these invariants in place for everybody.
2226          */
2227         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2228         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2229                                                 (VM_PFNMAP|VM_MIXEDMAP));
2230         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2231         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2232
2233         if (addr < vma->vm_start || addr >= vma->vm_end)
2234                 return -EFAULT;
2235         if (track_pfn_insert(vma, &pgprot, pfn))
2236                 return -EINVAL;
2237
2238         ret = insert_pfn(vma, addr, pfn, pgprot);
2239
2240         return ret;
2241 }
2242 EXPORT_SYMBOL(vm_insert_pfn);
2243
2244 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2245                         unsigned long pfn)
2246 {
2247         BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
2248
2249         if (addr < vma->vm_start || addr >= vma->vm_end)
2250                 return -EFAULT;
2251
2252         /*
2253          * If we don't have pte special, then we have to use the pfn_valid()
2254          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2255          * refcount the page if pfn_valid is true (hence insert_page rather
2256          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
2257          * without pte special, it would there be refcounted as a normal page.
2258          */
2259         if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) {
2260                 struct page *page;
2261
2262                 page = pfn_to_page(pfn);
2263                 return insert_page(vma, addr, page, vma->vm_page_prot);
2264         }
2265         return insert_pfn(vma, addr, pfn, vma->vm_page_prot);
2266 }
2267 EXPORT_SYMBOL(vm_insert_mixed);
2268
2269 /*
2270  * maps a range of physical memory into the requested pages. the old
2271  * mappings are removed. any references to nonexistent pages results
2272  * in null mappings (currently treated as "copy-on-access")
2273  */
2274 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2275                         unsigned long addr, unsigned long end,
2276                         unsigned long pfn, pgprot_t prot)
2277 {
2278         pte_t *pte;
2279         spinlock_t *ptl;
2280
2281         pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2282         if (!pte)
2283                 return -ENOMEM;
2284         arch_enter_lazy_mmu_mode();
2285         do {
2286                 BUG_ON(!pte_none(*pte));
2287                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2288                 pfn++;
2289         } while (pte++, addr += PAGE_SIZE, addr != end);
2290         arch_leave_lazy_mmu_mode();
2291         pte_unmap_unlock(pte - 1, ptl);
2292         return 0;
2293 }
2294
2295 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2296                         unsigned long addr, unsigned long end,
2297                         unsigned long pfn, pgprot_t prot)
2298 {
2299         pmd_t *pmd;
2300         unsigned long next;
2301
2302         pfn -= addr >> PAGE_SHIFT;
2303         pmd = pmd_alloc(mm, pud, addr);
2304         if (!pmd)
2305                 return -ENOMEM;
2306         VM_BUG_ON(pmd_trans_huge(*pmd));
2307         do {
2308                 next = pmd_addr_end(addr, end);
2309                 if (remap_pte_range(mm, pmd, addr, next,
2310                                 pfn + (addr >> PAGE_SHIFT), prot))
2311                         return -ENOMEM;
2312         } while (pmd++, addr = next, addr != end);
2313         return 0;
2314 }
2315
2316 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
2317                         unsigned long addr, unsigned long end,
2318                         unsigned long pfn, pgprot_t prot)
2319 {
2320         pud_t *pud;
2321         unsigned long next;
2322
2323         pfn -= addr >> PAGE_SHIFT;
2324         pud = pud_alloc(mm, pgd, addr);
2325         if (!pud)
2326                 return -ENOMEM;
2327         do {
2328                 next = pud_addr_end(addr, end);
2329                 if (remap_pmd_range(mm, pud, addr, next,
2330                                 pfn + (addr >> PAGE_SHIFT), prot))
2331                         return -ENOMEM;
2332         } while (pud++, addr = next, addr != end);
2333         return 0;
2334 }
2335
2336 /**
2337  * remap_pfn_range - remap kernel memory to userspace
2338  * @vma: user vma to map to
2339  * @addr: target user address to start at
2340  * @pfn: physical address of kernel memory
2341  * @size: size of map area
2342  * @prot: page protection flags for this mapping
2343  *
2344  *  Note: this is only safe if the mm semaphore is held when called.
2345  */
2346 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2347                     unsigned long pfn, unsigned long size, pgprot_t prot)
2348 {
2349         pgd_t *pgd;
2350         unsigned long next;
2351         unsigned long end = addr + PAGE_ALIGN(size);
2352         struct mm_struct *mm = vma->vm_mm;
2353         int err;
2354
2355         /*
2356          * Physically remapped pages are special. Tell the
2357          * rest of the world about it:
2358          *   VM_IO tells people not to look at these pages
2359          *      (accesses can have side effects).
2360          *   VM_PFNMAP tells the core MM that the base pages are just
2361          *      raw PFN mappings, and do not have a "struct page" associated
2362          *      with them.
2363          *   VM_DONTEXPAND
2364          *      Disable vma merging and expanding with mremap().
2365          *   VM_DONTDUMP
2366          *      Omit vma from core dump, even when VM_IO turned off.
2367          *
2368          * There's a horrible special case to handle copy-on-write
2369          * behaviour that some programs depend on. We mark the "original"
2370          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2371          * See vm_normal_page() for details.
2372          */
2373         if (is_cow_mapping(vma->vm_flags)) {
2374                 if (addr != vma->vm_start || end != vma->vm_end)
2375                         return -EINVAL;
2376                 vma->vm_pgoff = pfn;
2377         }
2378
2379         err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2380         if (err)
2381                 return -EINVAL;
2382
2383         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2384
2385         BUG_ON(addr >= end);
2386         pfn -= addr >> PAGE_SHIFT;
2387         pgd = pgd_offset(mm, addr);
2388         flush_cache_range(vma, addr, end);
2389         do {
2390                 next = pgd_addr_end(addr, end);
2391                 err = remap_pud_range(mm, pgd, addr, next,
2392                                 pfn + (addr >> PAGE_SHIFT), prot);
2393                 if (err)
2394                         break;
2395         } while (pgd++, addr = next, addr != end);
2396
2397         if (err)
2398                 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2399
2400         return err;
2401 }
2402 EXPORT_SYMBOL(remap_pfn_range);
2403
2404 /**
2405  * vm_iomap_memory - remap memory to userspace
2406  * @vma: user vma to map to
2407  * @start: start of area
2408  * @len: size of area
2409  *
2410  * This is a simplified io_remap_pfn_range() for common driver use. The
2411  * driver just needs to give us the physical memory range to be mapped,
2412  * we'll figure out the rest from the vma information.
2413  *
2414  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2415  * whatever write-combining details or similar.
2416  */
2417 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2418 {
2419         unsigned long vm_len, pfn, pages;
2420
2421         /* Check that the physical memory area passed in looks valid */
2422         if (start + len < start)
2423                 return -EINVAL;
2424         /*
2425          * You *really* shouldn't map things that aren't page-aligned,
2426          * but we've historically allowed it because IO memory might
2427          * just have smaller alignment.
2428          */
2429         len += start & ~PAGE_MASK;
2430         pfn = start >> PAGE_SHIFT;
2431         pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2432         if (pfn + pages < pfn)
2433                 return -EINVAL;
2434
2435         /* We start the mapping 'vm_pgoff' pages into the area */
2436         if (vma->vm_pgoff > pages)
2437                 return -EINVAL;
2438         pfn += vma->vm_pgoff;
2439         pages -= vma->vm_pgoff;
2440
2441         /* Can we fit all of the mapping? */
2442         vm_len = vma->vm_end - vma->vm_start;
2443         if (vm_len >> PAGE_SHIFT > pages)
2444                 return -EINVAL;
2445
2446         /* Ok, let it rip */
2447         return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2448 }
2449 EXPORT_SYMBOL(vm_iomap_memory);
2450
2451 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2452                                      unsigned long addr, unsigned long end,
2453                                      pte_fn_t fn, void *data)
2454 {
2455         pte_t *pte;
2456         int err;
2457         pgtable_t token;
2458         spinlock_t *uninitialized_var(ptl);
2459
2460         pte = (mm == &init_mm) ?
2461                 pte_alloc_kernel(pmd, addr) :
2462                 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2463         if (!pte)
2464                 return -ENOMEM;
2465
2466         BUG_ON(pmd_huge(*pmd));
2467
2468         arch_enter_lazy_mmu_mode();
2469
2470         token = pmd_pgtable(*pmd);
2471
2472         do {
2473                 err = fn(pte++, token, addr, data);
2474                 if (err)
2475                         break;
2476         } while (addr += PAGE_SIZE, addr != end);
2477
2478         arch_leave_lazy_mmu_mode();
2479
2480         if (mm != &init_mm)
2481                 pte_unmap_unlock(pte-1, ptl);
2482         return err;
2483 }
2484
2485 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2486                                      unsigned long addr, unsigned long end,
2487                                      pte_fn_t fn, void *data)
2488 {
2489         pmd_t *pmd;
2490         unsigned long next;
2491         int err;
2492
2493         BUG_ON(pud_huge(*pud));
2494
2495         pmd = pmd_alloc(mm, pud, addr);
2496         if (!pmd)
2497                 return -ENOMEM;
2498         do {
2499                 next = pmd_addr_end(addr, end);
2500                 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2501                 if (err)
2502                         break;
2503         } while (pmd++, addr = next, addr != end);
2504         return err;
2505 }
2506
2507 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
2508                                      unsigned long addr, unsigned long end,
2509                                      pte_fn_t fn, void *data)
2510 {
2511         pud_t *pud;
2512         unsigned long next;
2513         int err;
2514
2515         pud = pud_alloc(mm, pgd, addr);
2516         if (!pud)
2517                 return -ENOMEM;
2518         do {
2519                 next = pud_addr_end(addr, end);
2520                 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2521                 if (err)
2522                         break;
2523         } while (pud++, addr = next, addr != end);
2524         return err;
2525 }
2526
2527 /*
2528  * Scan a region of virtual memory, filling in page tables as necessary
2529  * and calling a provided function on each leaf page table.
2530  */
2531 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2532                         unsigned long size, pte_fn_t fn, void *data)
2533 {
2534         pgd_t *pgd;
2535         unsigned long next;
2536         unsigned long end = addr + size;
2537         int err;
2538
2539         BUG_ON(addr >= end);
2540         pgd = pgd_offset(mm, addr);
2541         do {
2542                 next = pgd_addr_end(addr, end);
2543                 err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
2544                 if (err)
2545                         break;
2546         } while (pgd++, addr = next, addr != end);
2547
2548         return err;
2549 }
2550 EXPORT_SYMBOL_GPL(apply_to_page_range);
2551
2552 /*
2553  * handle_pte_fault chooses page fault handler according to an entry
2554  * which was read non-atomically.  Before making any commitment, on
2555  * those architectures or configurations (e.g. i386 with PAE) which
2556  * might give a mix of unmatched parts, do_swap_page and do_nonlinear_fault
2557  * must check under lock before unmapping the pte and proceeding
2558  * (but do_wp_page is only called after already making such a check;
2559  * and do_anonymous_page can safely check later on).
2560  */
2561 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2562                                 pte_t *page_table, pte_t orig_pte)
2563 {
2564         int same = 1;
2565 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2566         if (sizeof(pte_t) > sizeof(unsigned long)) {
2567                 spinlock_t *ptl = pte_lockptr(mm, pmd);
2568                 spin_lock(ptl);
2569                 same = pte_same(*page_table, orig_pte);
2570                 spin_unlock(ptl);
2571         }
2572 #endif
2573         pte_unmap(page_table);
2574         return same;
2575 }
2576
2577 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
2578 {
2579         /*
2580          * If the source page was a PFN mapping, we don't have
2581          * a "struct page" for it. We do a best-effort copy by
2582          * just copying from the original user address. If that
2583          * fails, we just zero-fill it. Live with it.
2584          */
2585         if (unlikely(!src)) {
2586                 void *kaddr = kmap_atomic(dst);
2587                 void __user *uaddr = (void __user *)(va & PAGE_MASK);
2588
2589                 /*
2590                  * This really shouldn't fail, because the page is there
2591                  * in the page tables. But it might just be unreadable,
2592                  * in which case we just give up and fill the result with
2593                  * zeroes.
2594                  */
2595                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2596                         clear_page(kaddr);
2597                 kunmap_atomic(kaddr);
2598                 flush_dcache_page(dst);
2599         } else
2600                 copy_user_highpage(dst, src, va, vma);
2601 }
2602
2603 /*
2604  * This routine handles present pages, when users try to write
2605  * to a shared page. It is done by copying the page to a new address
2606  * and decrementing the shared-page counter for the old page.
2607  *
2608  * Note that this routine assumes that the protection checks have been
2609  * done by the caller (the low-level page fault routine in most cases).
2610  * Thus we can safely just mark it writable once we've done any necessary
2611  * COW.
2612  *
2613  * We also mark the page dirty at this point even though the page will
2614  * change only once the write actually happens. This avoids a few races,
2615  * and potentially makes it more efficient.
2616  *
2617  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2618  * but allow concurrent faults), with pte both mapped and locked.
2619  * We return with mmap_sem still held, but pte unmapped and unlocked.
2620  */
2621 static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
2622                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2623                 spinlock_t *ptl, pte_t orig_pte)
2624         __releases(ptl)
2625 {
2626         struct page *old_page, *new_page = NULL;
2627         pte_t entry;
2628         int ret = 0;
2629         int page_mkwrite = 0;
2630         struct page *dirty_page = NULL;
2631         unsigned long mmun_start = 0;   /* For mmu_notifiers */
2632         unsigned long mmun_end = 0;     /* For mmu_notifiers */
2633
2634         old_page = vm_normal_page(vma, address, orig_pte);
2635         if (!old_page) {
2636                 /*
2637                  * VM_MIXEDMAP !pfn_valid() case
2638                  *
2639                  * We should not cow pages in a shared writeable mapping.
2640                  * Just mark the pages writable as we can't do any dirty
2641                  * accounting on raw pfn maps.
2642                  */
2643                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2644                                      (VM_WRITE|VM_SHARED))
2645                         goto reuse;
2646                 goto gotten;
2647         }
2648
2649         /*
2650          * Take out anonymous pages first, anonymous shared vmas are
2651          * not dirty accountable.
2652          */
2653         if (PageAnon(old_page) && !PageKsm(old_page)) {
2654                 if (!trylock_page(old_page)) {
2655                         page_cache_get(old_page);
2656                         pte_unmap_unlock(page_table, ptl);
2657                         lock_page(old_page);
2658                         page_table = pte_offset_map_lock(mm, pmd, address,
2659                                                          &ptl);
2660                         if (!pte_same(*page_table, orig_pte)) {
2661                                 unlock_page(old_page);
2662                                 goto unlock;
2663                         }
2664                         page_cache_release(old_page);
2665                 }
2666                 if (reuse_swap_page(old_page)) {
2667                         /*
2668                          * The page is all ours.  Move it to our anon_vma so
2669                          * the rmap code will not search our parent or siblings.
2670                          * Protected against the rmap code by the page lock.
2671                          */
2672                         page_move_anon_rmap(old_page, vma, address);
2673                         unlock_page(old_page);
2674                         goto reuse;
2675                 }
2676                 unlock_page(old_page);
2677         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2678                                         (VM_WRITE|VM_SHARED))) {
2679                 /*
2680                  * Only catch write-faults on shared writable pages,
2681                  * read-only shared pages can get COWed by
2682                  * get_user_pages(.write=1, .force=1).
2683                  */
2684                 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2685                         struct vm_fault vmf;
2686                         int tmp;
2687
2688                         vmf.virtual_address = (void __user *)(address &
2689                                                                 PAGE_MASK);
2690                         vmf.pgoff = old_page->index;
2691                         vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2692                         vmf.page = old_page;
2693
2694                         /*
2695                          * Notify the address space that the page is about to
2696                          * become writable so that it can prohibit this or wait
2697                          * for the page to get into an appropriate state.
2698                          *
2699                          * We do this without the lock held, so that it can
2700                          * sleep if it needs to.
2701                          */
2702                         page_cache_get(old_page);
2703                         pte_unmap_unlock(page_table, ptl);
2704
2705                         tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
2706                         if (unlikely(tmp &
2707                                         (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2708                                 ret = tmp;
2709                                 goto unwritable_page;
2710                         }
2711                         if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
2712                                 lock_page(old_page);
2713                                 if (!old_page->mapping) {
2714                                         ret = 0; /* retry the fault */
2715                                         unlock_page(old_page);
2716                                         goto unwritable_page;
2717                                 }
2718                         } else
2719                                 VM_BUG_ON(!PageLocked(old_page));
2720
2721                         /*
2722                          * Since we dropped the lock we need to revalidate
2723                          * the PTE as someone else may have changed it.  If
2724                          * they did, we just return, as we can count on the
2725                          * MMU to tell us if they didn't also make it writable.
2726                          */
2727                         page_table = pte_offset_map_lock(mm, pmd, address,
2728                                                          &ptl);
2729                         if (!pte_same(*page_table, orig_pte)) {
2730                                 unlock_page(old_page);
2731                                 goto unlock;
2732                         }
2733
2734                         page_mkwrite = 1;
2735                 }
2736                 dirty_page = old_page;
2737                 get_page(dirty_page);
2738
2739 reuse:
2740                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2741                 entry = pte_mkyoung(orig_pte);
2742                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2743                 if (ptep_set_access_flags(vma, address, page_table, entry,1))
2744                         update_mmu_cache(vma, address, page_table);
2745                 pte_unmap_unlock(page_table, ptl);
2746                 ret |= VM_FAULT_WRITE;
2747
2748                 if (!dirty_page)
2749                         return ret;
2750
2751                 /*
2752                  * Yes, Virginia, this is actually required to prevent a race
2753                  * with clear_page_dirty_for_io() from clearing the page dirty
2754                  * bit after it clear all dirty ptes, but before a racing
2755                  * do_wp_page installs a dirty pte.
2756                  *
2757                  * __do_fault is protected similarly.
2758                  */
2759                 if (!page_mkwrite) {
2760                         wait_on_page_locked(dirty_page);
2761                         set_page_dirty_balance(dirty_page, page_mkwrite);
2762                         /* file_update_time outside page_lock */
2763                         if (vma->vm_file)
2764                                 file_update_time(vma->vm_file);
2765                 }
2766                 put_page(dirty_page);
2767                 if (page_mkwrite) {
2768                         struct address_space *mapping = dirty_page->mapping;
2769
2770                         set_page_dirty(dirty_page);
2771                         unlock_page(dirty_page);
2772                         page_cache_release(dirty_page);
2773                         if (mapping)    {
2774                                 /*
2775                                  * Some device drivers do not set page.mapping
2776                                  * but still dirty their pages
2777                                  */
2778                                 balance_dirty_pages_ratelimited(mapping);
2779                         }
2780                 }
2781
2782                 return ret;
2783         }
2784
2785         /*
2786          * Ok, we need to copy. Oh, well..
2787          */
2788         page_cache_get(old_page);
2789 gotten:
2790         pte_unmap_unlock(page_table, ptl);
2791
2792         if (unlikely(anon_vma_prepare(vma)))
2793                 goto oom;
2794
2795         if (is_zero_pfn(pte_pfn(orig_pte))) {
2796                 new_page = alloc_zeroed_user_highpage_movable(vma, address);
2797                 if (!new_page)
2798                         goto oom;
2799         } else {
2800                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2801                 if (!new_page)
2802                         goto oom;
2803                 cow_user_page(new_page, old_page, address, vma);
2804         }
2805         __SetPageUptodate(new_page);
2806
2807         if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))
2808                 goto oom_free_new;
2809
2810         mmun_start  = address & PAGE_MASK;
2811         mmun_end    = mmun_start + PAGE_SIZE;
2812         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2813
2814         /*
2815          * Re-check the pte - we dropped the lock
2816          */
2817         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2818         if (likely(pte_same(*page_table, orig_pte))) {
2819                 if (old_page) {
2820                         if (!PageAnon(old_page)) {
2821                                 dec_mm_counter_fast(mm, MM_FILEPAGES);
2822                                 inc_mm_counter_fast(mm, MM_ANONPAGES);
2823                         }
2824                 } else
2825                         inc_mm_counter_fast(mm, MM_ANONPAGES);
2826                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2827                 entry = mk_pte(new_page, vma->vm_page_prot);
2828                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2829                 /*
2830                  * Clear the pte entry and flush it first, before updating the
2831                  * pte with the new entry. This will avoid a race condition
2832                  * seen in the presence of one thread doing SMC and another
2833                  * thread doing COW.
2834                  */
2835                 ptep_clear_flush(vma, address, page_table);
2836                 page_add_new_anon_rmap(new_page, vma, address);
2837                 /*
2838                  * We call the notify macro here because, when using secondary
2839                  * mmu page tables (such as kvm shadow page tables), we want the
2840                  * new page to be mapped directly into the secondary page table.
2841                  */
2842                 set_pte_at_notify(mm, address, page_table, entry);
2843                 update_mmu_cache(vma, address, page_table);
2844                 if (old_page) {
2845                         /*
2846                          * Only after switching the pte to the new page may
2847                          * we remove the mapcount here. Otherwise another
2848                          * process may come and find the rmap count decremented
2849                          * before the pte is switched to the new page, and
2850                          * "reuse" the old page writing into it while our pte
2851                          * here still points into it and can be read by other
2852                          * threads.
2853                          *
2854                          * The critical issue is to order this
2855                          * page_remove_rmap with the ptp_clear_flush above.
2856                          * Those stores are ordered by (if nothing else,)
2857                          * the barrier present in the atomic_add_negative
2858                          * in page_remove_rmap.
2859                          *
2860                          * Then the TLB flush in ptep_clear_flush ensures that
2861                          * no process can access the old page before the
2862                          * decremented mapcount is visible. And the old page
2863                          * cannot be reused until after the decremented
2864                          * mapcount is visible. So transitively, TLBs to
2865                          * old page will be flushed before it can be reused.
2866                          */
2867                         page_remove_rmap(old_page);
2868                 }
2869
2870                 /* Free the old page.. */
2871                 new_page = old_page;
2872                 ret |= VM_FAULT_WRITE;
2873         } else
2874                 mem_cgroup_uncharge_page(new_page);
2875
2876         if (new_page)
2877                 page_cache_release(new_page);
2878 unlock:
2879         pte_unmap_unlock(page_table, ptl);
2880         if (mmun_end > mmun_start)
2881                 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2882         if (old_page) {
2883                 /*
2884                  * Don't let another task, with possibly unlocked vma,
2885                  * keep the mlocked page.
2886                  */
2887                 if ((ret & VM_FAULT_WRITE) && (vma->vm_flags & VM_LOCKED)) {
2888                         lock_page(old_page);    /* LRU manipulation */
2889                         munlock_vma_page(old_page);
2890                         unlock_page(old_page);
2891                 }
2892                 page_cache_release(old_page);
2893         }
2894         return ret;
2895 oom_free_new:
2896         page_cache_release(new_page);
2897 oom:
2898         if (old_page)
2899                 page_cache_release(old_page);
2900         return VM_FAULT_OOM;
2901
2902 unwritable_page:
2903         page_cache_release(old_page);
2904         return ret;
2905 }
2906
2907 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2908                 unsigned long start_addr, unsigned long end_addr,
2909                 struct zap_details *details)
2910 {
2911         zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2912 }
2913
2914 static inline void unmap_mapping_range_tree(struct rb_root *root,
2915                                             struct zap_details *details)
2916 {
2917         struct vm_area_struct *vma;
2918         pgoff_t vba, vea, zba, zea;
2919
2920         vma_interval_tree_foreach(vma, root,
2921                         details->first_index, details->last_index) {
2922
2923                 vba = vma->vm_pgoff;
2924                 vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1;
2925                 /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */
2926                 zba = details->first_index;
2927                 if (zba < vba)
2928                         zba = vba;
2929                 zea = details->last_index;
2930                 if (zea > vea)
2931                         zea = vea;
2932
2933                 unmap_mapping_range_vma(vma,
2934                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2935                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2936                                 details);
2937         }
2938 }
2939
2940 static inline void unmap_mapping_range_list(struct list_head *head,
2941                                             struct zap_details *details)
2942 {
2943         struct vm_area_struct *vma;
2944
2945         /*
2946          * In nonlinear VMAs there is no correspondence between virtual address
2947          * offset and file offset.  So we must perform an exhaustive search
2948          * across *all* the pages in each nonlinear VMA, not just the pages
2949          * whose virtual address lies outside the file truncation point.
2950          */
2951         list_for_each_entry(vma, head, shared.nonlinear) {
2952                 details->nonlinear_vma = vma;
2953                 unmap_mapping_range_vma(vma, vma->vm_start, vma->vm_end, details);
2954         }
2955 }
2956
2957 /**
2958  * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file.
2959  * @mapping: the address space containing mmaps to be unmapped.
2960  * @holebegin: byte in first page to unmap, relative to the start of
2961  * the underlying file.  This will be rounded down to a PAGE_SIZE
2962  * boundary.  Note that this is different from truncate_pagecache(), which
2963  * must keep the partial page.  In contrast, we must get rid of
2964  * partial pages.
2965  * @holelen: size of prospective hole in bytes.  This will be rounded
2966  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
2967  * end of the file.
2968  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2969  * but 0 when invalidating pagecache, don't throw away private data.
2970  */
2971 void unmap_mapping_range(struct address_space *mapping,
2972                 loff_t const holebegin, loff_t const holelen, int even_cows)
2973 {
2974         struct zap_details details;
2975         pgoff_t hba = holebegin >> PAGE_SHIFT;
2976         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2977
2978         /* Check for overflow. */
2979         if (sizeof(holelen) > sizeof(hlen)) {
2980                 long long holeend =
2981                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2982                 if (holeend & ~(long long)ULONG_MAX)
2983                         hlen = ULONG_MAX - hba + 1;
2984         }
2985
2986         details.check_mapping = even_cows? NULL: mapping;
2987         details.nonlinear_vma = NULL;
2988         details.first_index = hba;
2989         details.last_index = hba + hlen - 1;
2990         if (details.last_index < details.first_index)
2991                 details.last_index = ULONG_MAX;
2992
2993
2994         mutex_lock(&mapping->i_mmap_mutex);
2995         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
2996                 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2997         if (unlikely(!list_empty(&mapping->i_mmap_nonlinear)))
2998                 unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details);
2999         mutex_unlock(&mapping->i_mmap_mutex);
3000 }
3001 EXPORT_SYMBOL(unmap_mapping_range);
3002
3003 /*
3004  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3005  * but allow concurrent faults), and pte mapped but not yet locked.
3006  * We return with mmap_sem still held, but pte unmapped and unlocked.
3007  */
3008 static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
3009                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3010                 unsigned int flags, pte_t orig_pte)
3011 {
3012         spinlock_t *ptl;
3013         struct page *page, *swapcache;
3014         swp_entry_t entry;
3015         pte_t pte;
3016         int locked;
3017         struct mem_cgroup *ptr;
3018         int exclusive = 0;
3019         int ret = 0;
3020
3021         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3022                 goto out;
3023
3024         entry = pte_to_swp_entry(orig_pte);
3025         if (unlikely(non_swap_entry(entry))) {
3026                 if (is_migration_entry(entry)) {
3027                         migration_entry_wait(mm, pmd, address);
3028                 } else if (is_hwpoison_entry(entry)) {
3029                         ret = VM_FAULT_HWPOISON;
3030                 } else {
3031                         print_bad_pte(vma, address, orig_pte, NULL);
3032                         ret = VM_FAULT_SIGBUS;
3033                 }
3034                 goto out;
3035         }
3036         delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3037         page = lookup_swap_cache(entry);
3038         if (!page) {
3039                 page = swapin_readahead(entry,
3040                                         GFP_HIGHUSER_MOVABLE, vma, address);
3041                 if (!page) {
3042                         /*
3043                          * Back out if somebody else faulted in this pte
3044                          * while we released the pte lock.
3045                          */
3046                         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3047                         if (likely(pte_same(*page_table, orig_pte)))
3048                                 ret = VM_FAULT_OOM;
3049                         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3050                         goto unlock;
3051                 }
3052
3053                 /* Had to read the page from swap area: Major fault */
3054                 ret = VM_FAULT_MAJOR;
3055                 count_vm_event(PGMAJFAULT);
3056                 mem_cgroup_count_vm_event(mm, PGMAJFAULT);
3057         } else if (PageHWPoison(page)) {
3058                 /*
3059                  * hwpoisoned dirty swapcache pages are kept for killing
3060                  * owner processes (which may be unknown at hwpoison time)
3061                  */
3062                 ret = VM_FAULT_HWPOISON;
3063                 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3064                 swapcache = page;
3065                 goto out_release;
3066         }
3067
3068         swapcache = page;
3069         locked = lock_page_or_retry(page, mm, flags);
3070
3071         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3072         if (!locked) {
3073                 ret |= VM_FAULT_RETRY;
3074                 goto out_release;
3075         }
3076
3077         /*
3078          * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3079          * release the swapcache from under us.  The page pin, and pte_same
3080          * test below, are not enough to exclude that.  Even if it is still
3081          * swapcache, we need to check that the page's swap has not changed.
3082          */
3083         if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3084                 goto out_page;
3085
3086         page = ksm_might_need_to_copy(page, vma, address);
3087         if (unlikely(!page)) {
3088                 ret = VM_FAULT_OOM;
3089                 page = swapcache;
3090                 goto out_page;
3091         }
3092
3093         if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) {
3094                 ret = VM_FAULT_OOM;
3095                 goto out_page;
3096         }
3097
3098         /*
3099          * Back out if somebody else already faulted in this pte.
3100          */
3101         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3102         if (unlikely(!pte_same(*page_table, orig_pte)))
3103                 goto out_nomap;
3104
3105         if (unlikely(!PageUptodate(page))) {
3106                 ret = VM_FAULT_SIGBUS;
3107                 goto out_nomap;
3108         }
3109
3110         /*
3111          * The page isn't present yet, go ahead with the fault.
3112          *
3113          * Be careful about the sequence of operations here.
3114          * To get its accounting right, reuse_swap_page() must be called
3115          * while the page is counted on swap but not yet in mapcount i.e.
3116          * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3117          * must be called after the swap_free(), or it will never succeed.
3118          * Because delete_from_swap_page() may be called by reuse_swap_page(),
3119          * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry
3120          * in page->private. In this case, a record in swap_cgroup  is silently
3121          * discarded at swap_free().
3122          */
3123
3124         inc_mm_counter_fast(mm, MM_ANONPAGES);
3125         dec_mm_counter_fast(mm, MM_SWAPENTS);
3126         pte = mk_pte(page, vma->vm_page_prot);
3127         if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {
3128                 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3129                 flags &= ~FAULT_FLAG_WRITE;
3130                 ret |= VM_FAULT_WRITE;
3131                 exclusive = 1;
3132         }
3133         flush_icache_page(vma, page);
3134         set_pte_at(mm, address, page_table, pte);
3135         if (page == swapcache)
3136                 do_page_add_anon_rmap(page, vma, address, exclusive);
3137         else /* ksm created a completely new copy */
3138                 page_add_new_anon_rmap(page, vma, address);
3139         /* It's better to call commit-charge after rmap is established */
3140         mem_cgroup_commit_charge_swapin(page, ptr);
3141
3142         swap_free(entry);
3143         if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3144                 try_to_free_swap(page);
3145         unlock_page(page);
3146         if (page != swapcache) {
3147                 /*
3148                  * Hold the lock to avoid the swap entry to be reused
3149                  * until we take the PT lock for the pte_same() check
3150                  * (to avoid false positives from pte_same). For
3151                  * further safety release the lock after the swap_free
3152                  * so that the swap count won't change under a
3153                  * parallel locked swapcache.
3154                  */
3155                 unlock_page(swapcache);
3156                 page_cache_release(swapcache);
3157         }
3158
3159         if (flags & FAULT_FLAG_WRITE) {
3160                 ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte);
3161                 if (ret & VM_FAULT_ERROR)
3162                         ret &= VM_FAULT_ERROR;
3163                 goto out;
3164         }
3165
3166         /* No need to invalidate - it was non-present before */
3167         update_mmu_cache(vma, address, page_table);
3168 unlock:
3169         pte_unmap_unlock(page_table, ptl);
3170 out:
3171         return ret;
3172 out_nomap:
3173         mem_cgroup_cancel_charge_swapin(ptr);
3174         pte_unmap_unlock(page_table, ptl);
3175 out_page:
3176         unlock_page(page);
3177 out_release:
3178         page_cache_release(page);
3179         if (page != swapcache) {
3180                 unlock_page(swapcache);
3181                 page_cache_release(swapcache);
3182         }
3183         return ret;
3184 }
3185
3186 /*
3187  * This is like a special single-page "expand_{down|up}wards()",
3188  * except we must first make sure that 'address{-|+}PAGE_SIZE'
3189  * doesn't hit another vma.
3190  */
3191 static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address)
3192 {
3193         address &= PAGE_MASK;
3194         if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) {
3195                 struct vm_area_struct *prev = vma->vm_prev;
3196
3197                 /*
3198                  * Is there a mapping abutting this one below?
3199                  *
3200                  * That's only ok if it's the same stack mapping
3201                  * that has gotten split..
3202                  */
3203                 if (prev && prev->vm_end == address)
3204                         return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM;
3205
3206                 return expand_downwards(vma, address - PAGE_SIZE);
3207         }
3208         if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) {
3209                 struct vm_area_struct *next = vma->vm_next;
3210
3211                 /* As VM_GROWSDOWN but s/below/above/ */
3212                 if (next && next->vm_start == address + PAGE_SIZE)
3213                         return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM;
3214
3215                 return expand_upwards(vma, address + PAGE_SIZE);
3216         }
3217         return 0;
3218 }
3219
3220 /*
3221  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3222  * but allow concurrent faults), and pte mapped but not yet locked.
3223  * We return with mmap_sem still held, but pte unmapped and unlocked.
3224  */
3225 static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
3226                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3227                 unsigned int flags)
3228 {
3229         struct page *page;
3230         spinlock_t *ptl;
3231         pte_t entry;
3232
3233         pte_unmap(page_table);
3234
3235         /* File mapping without ->vm_ops ? */
3236         if (vma->vm_flags & VM_SHARED)
3237                 return VM_FAULT_SIGBUS;
3238
3239         /* Check if we need to add a guard page to the stack */
3240         if (check_stack_guard_page(vma, address) < 0)
3241                 return VM_FAULT_SIGSEGV;
3242
3243         /* Use the zero-page for reads */
3244         if (!(flags & FAULT_FLAG_WRITE)) {
3245                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(address),
3246                                                 vma->vm_page_prot));
3247                 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3248                 if (!pte_none(*page_table))
3249                         goto unlock;
3250                 goto setpte;
3251         }
3252
3253         /* Allocate our own private page. */
3254         if (unlikely(anon_vma_prepare(vma)))
3255                 goto oom;
3256         page = alloc_zeroed_user_highpage_movable(vma, address);
3257         if (!page)
3258                 goto oom;
3259         /*
3260          * The memory barrier inside __SetPageUptodate makes sure that
3261          * preceeding stores to the page contents become visible before
3262          * the set_pte_at() write.
3263          */
3264         __SetPageUptodate(page);
3265
3266         if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))
3267                 goto oom_free_page;
3268
3269         entry = mk_pte(page, vma->vm_page_prot);
3270         if (vma->vm_flags & VM_WRITE)
3271                 entry = pte_mkwrite(pte_mkdirty(entry));
3272
3273         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3274         if (!pte_none(*page_table))
3275                 goto release;
3276
3277         inc_mm_counter_fast(mm, MM_ANONPAGES);
3278         page_add_new_anon_rmap(page, vma, address);
3279 setpte:
3280         set_pte_at(mm, address, page_table, entry);
3281
3282         /* No need to invalidate - it was non-present before */
3283         update_mmu_cache(vma, address, page_table);
3284 unlock:
3285         pte_unmap_unlock(page_table, ptl);
3286         return 0;
3287 release:
3288         mem_cgroup_uncharge_page(page);
3289         page_cache_release(page);
3290         goto unlock;
3291 oom_free_page:
3292         page_cache_release(page);
3293 oom:
3294         return VM_FAULT_OOM;
3295 }
3296
3297 /*
3298  * __do_fault() tries to create a new page mapping. It aggressively
3299  * tries to share with existing pages, but makes a separate copy if
3300  * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid
3301  * the next page fault.
3302  *
3303  * As this is called only for pages that do not currently exist, we
3304  * do not need to flush old virtual caches or the TLB.
3305  *
3306  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3307  * but allow concurrent faults), and pte neither mapped nor locked.
3308  * We return with mmap_sem still held, but pte unmapped and unlocked.
3309  */
3310 static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3311                 unsigned long address, pmd_t *pmd,
3312                 pgoff_t pgoff, unsigned int flags, pte_t orig_pte)
3313 {
3314         pte_t *page_table;
3315         spinlock_t *ptl;
3316         struct page *page;
3317         struct page *cow_page;
3318         pte_t entry;
3319         int anon = 0;
3320         struct page *dirty_page = NULL;
3321         struct vm_fault vmf;
3322         int ret;
3323         int page_mkwrite = 0;
3324
3325         /*
3326          * If we do COW later, allocate page befor taking lock_page()
3327          * on the file cache page. This will reduce lock holding time.
3328          */
3329         if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
3330
3331                 if (unlikely(anon_vma_prepare(vma)))
3332                         return VM_FAULT_OOM;
3333
3334                 cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
3335                 if (!cow_page)
3336                         return VM_FAULT_OOM;
3337
3338                 if (mem_cgroup_newpage_charge(cow_page, mm, GFP_KERNEL)) {
3339                         page_cache_release(cow_page);
3340                         return VM_FAULT_OOM;
3341                 }
3342         } else
3343                 cow_page = NULL;
3344
3345         vmf.virtual_address = (void __user *)(address & PAGE_MASK);
3346         vmf.pgoff = pgoff;
3347         vmf.flags = flags;
3348         vmf.page = NULL;
3349
3350         ret = vma->vm_ops->fault(vma, &vmf);
3351         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3352                             VM_FAULT_RETRY)))
3353                 goto uncharge_out;
3354
3355         if (unlikely(PageHWPoison(vmf.page))) {
3356                 if (ret & VM_FAULT_LOCKED)
3357                         unlock_page(vmf.page);
3358                 ret = VM_FAULT_HWPOISON;
3359                 goto uncharge_out;
3360         }
3361
3362         /*
3363          * For consistency in subsequent calls, make the faulted page always
3364          * locked.
3365          */
3366         if (unlikely(!(ret & VM_FAULT_LOCKED)))
3367                 lock_page(vmf.page);
3368         else
3369                 VM_BUG_ON(!PageLocked(vmf.page));
3370
3371         /*
3372          * Should we do an early C-O-W break?
3373          */
3374         page = vmf.page;
3375         if (flags & FAULT_FLAG_WRITE) {
3376                 if (!(vma->vm_flags & VM_SHARED)) {
3377                         page = cow_page;
3378                         anon = 1;
3379                         copy_user_highpage(page, vmf.page, address, vma);
3380                         __SetPageUptodate(page);
3381                 } else {
3382                         /*
3383                          * If the page will be shareable, see if the backing
3384                          * address space wants to know that the page is about
3385                          * to become writable
3386                          */
3387                         if (vma->vm_ops->page_mkwrite) {
3388                                 int tmp;
3389
3390                                 unlock_page(page);
3391                                 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
3392                                 tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
3393                                 if (unlikely(tmp &
3394                                           (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3395                                         ret = tmp;
3396                                         goto unwritable_page;
3397                                 }
3398                                 if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
3399                                         lock_page(page);
3400                                         if (!page->mapping) {
3401                                                 ret = 0; /* retry the fault */
3402                                                 unlock_page(page);
3403                                                 goto unwritable_page;
3404                                         }
3405                                 } else
3406                                         VM_BUG_ON(!PageLocked(page));
3407                                 page_mkwrite = 1;
3408                         }
3409                 }
3410
3411         }
3412
3413         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3414
3415         /*
3416          * This silly early PAGE_DIRTY setting removes a race
3417          * due to the bad i386 page protection. But it's valid
3418          * for other architectures too.
3419          *
3420          * Note that if FAULT_FLAG_WRITE is set, we either now have
3421          * an exclusive copy of the page, or this is a shared mapping,
3422          * so we can make it writable and dirty to avoid having to
3423          * handle that later.
3424          */
3425         /* Only go through if we didn't race with anybody else... */
3426         if (likely(pte_same(*page_table, orig_pte))) {
3427                 flush_icache_page(vma, page);
3428                 entry = mk_pte(page, vma->vm_page_prot);
3429                 if (flags & FAULT_FLAG_WRITE)
3430                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3431                 if (anon) {
3432                         inc_mm_counter_fast(mm, MM_ANONPAGES);
3433                         page_add_new_anon_rmap(page, vma, address);
3434                 } else {
3435                         inc_mm_counter_fast(mm, MM_FILEPAGES);
3436                         page_add_file_rmap(page);
3437                         if (flags & FAULT_FLAG_WRITE) {
3438                                 dirty_page = page;
3439                                 get_page(dirty_page);
3440                         }
3441                 }
3442                 set_pte_at(mm, address, page_table, entry);
3443
3444                 /* no need to invalidate: a not-present page won't be cached */
3445                 update_mmu_cache(vma, address, page_table);
3446         } else {
3447                 if (cow_page)
3448                         mem_cgroup_uncharge_page(cow_page);
3449                 if (anon)
3450                         page_cache_release(page);
3451                 else
3452                         anon = 1; /* no anon but release faulted_page */
3453         }
3454
3455         pte_unmap_unlock(page_table, ptl);
3456
3457         if (dirty_page) {
3458                 struct address_space *mapping = page->mapping;
3459                 int dirtied = 0;
3460
3461                 if (set_page_dirty(dirty_page))
3462                         dirtied = 1;
3463                 unlock_page(dirty_page);
3464                 put_page(dirty_page);
3465                 if ((dirtied || page_mkwrite) && mapping) {
3466                         /*
3467                          * Some device drivers do not set page.mapping but still
3468                          * dirty their pages
3469                          */
3470                         balance_dirty_pages_ratelimited(mapping);
3471                 }
3472
3473                 /* file_update_time outside page_lock */
3474                 if (vma->vm_file && !page_mkwrite)
3475                         file_update_time(vma->vm_file);
3476         } else {
3477                 unlock_page(vmf.page);
3478                 if (anon)
3479                         page_cache_release(vmf.page);
3480         }
3481
3482         return ret;
3483
3484 unwritable_page:
3485         page_cache_release(page);
3486         return ret;
3487 uncharge_out:
3488         /* fs's fault handler get error */
3489         if (cow_page) {
3490                 mem_cgroup_uncharge_page(cow_page);
3491                 page_cache_release(cow_page);
3492         }
3493         return ret;
3494 }
3495
3496 static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3497                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3498                 unsigned int flags, pte_t orig_pte)
3499 {
3500         pgoff_t pgoff = (((address & PAGE_MASK)
3501                         - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
3502
3503         pte_unmap(page_table);
3504         /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
3505         if (!vma->vm_ops->fault)
3506                 return VM_FAULT_SIGBUS;
3507         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3508 }
3509
3510 /*
3511  * Fault of a previously existing named mapping. Repopulate the pte
3512  * from the encoded file_pte if possible. This enables swappable
3513  * nonlinear vmas.
3514  *
3515  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3516  * but allow concurrent faults), and pte mapped but not yet locked.
3517  * We return with mmap_sem still held, but pte unmapped and unlocked.
3518  */
3519 static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3520                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3521                 unsigned int flags, pte_t orig_pte)
3522 {
3523         pgoff_t pgoff;
3524
3525         flags |= FAULT_FLAG_NONLINEAR;
3526
3527         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3528                 return 0;
3529
3530         if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) {
3531                 /*
3532                  * Page table corrupted: show pte and kill process.
3533                  */
3534                 print_bad_pte(vma, address, orig_pte, NULL);
3535                 return VM_FAULT_SIGBUS;
3536         }
3537
3538         pgoff = pte_to_pgoff(orig_pte);
3539         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3540 }
3541
3542 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3543                                 unsigned long addr, int page_nid)
3544 {
3545         get_page(page);
3546
3547         count_vm_numa_event(NUMA_HINT_FAULTS);
3548         if (page_nid == numa_node_id())
3549                 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3550
3551         return mpol_misplaced(page, vma, addr);
3552 }
3553
3554 int do_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3555                    unsigned long addr, pte_t pte, pte_t *ptep, pmd_t *pmd)
3556 {
3557         struct page *page = NULL;
3558         spinlock_t *ptl;
3559         int page_nid = -1;
3560         int target_nid;
3561         bool migrated = false;
3562
3563         /*
3564         * The "pte" at this point cannot be used safely without
3565         * validation through pte_unmap_same(). It's of NUMA type but
3566         * the pfn may be screwed if the read is non atomic.
3567         *
3568         * ptep_modify_prot_start is not called as this is clearing
3569         * the _PAGE_NUMA bit and it is not really expected that there
3570         * would be concurrent hardware modifications to the PTE.
3571         */
3572         ptl = pte_lockptr(mm, pmd);
3573         spin_lock(ptl);
3574         if (unlikely(!pte_same(*ptep, pte))) {
3575                 pte_unmap_unlock(ptep, ptl);
3576                 goto out;
3577         }
3578
3579         pte = pte_mknonnuma(pte);
3580         set_pte_at(mm, addr, ptep, pte);
3581         update_mmu_cache(vma, addr, ptep);
3582
3583         page = vm_normal_page(vma, addr, pte);
3584         if (!page) {
3585                 pte_unmap_unlock(ptep, ptl);
3586                 return 0;
3587         }
3588
3589         page_nid = page_to_nid(page);
3590         target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3591         pte_unmap_unlock(ptep, ptl);
3592         if (target_nid == -1) {
3593                 put_page(page);
3594                 goto out;
3595         }
3596
3597         /* Migrate to the requested node */
3598         migrated = migrate_misplaced_page(page, target_nid);
3599         if (migrated)
3600                 page_nid = target_nid;
3601
3602 out:
3603         if (page_nid != -1)
3604                 task_numa_fault(page_nid, 1, migrated);
3605         return 0;
3606 }
3607
3608 /* NUMA hinting page fault entry point for regular pmds */
3609 #ifdef CONFIG_NUMA_BALANCING
3610 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3611                      unsigned long addr, pmd_t *pmdp)
3612 {
3613         pmd_t pmd;
3614         pte_t *pte, *orig_pte;
3615         unsigned long _addr = addr & PMD_MASK;
3616         unsigned long offset;
3617         spinlock_t *ptl;
3618         bool numa = false;
3619
3620         spin_lock(&mm->page_table_lock);
3621         pmd = *pmdp;
3622         if (pmd_numa(pmd)) {
3623                 set_pmd_at(mm, _addr, pmdp, pmd_mknonnuma(pmd));
3624                 numa = true;
3625         }
3626         spin_unlock(&mm->page_table_lock);
3627
3628         if (!numa)
3629                 return 0;
3630
3631         /* we're in a page fault so some vma must be in the range */
3632         BUG_ON(!vma);
3633         BUG_ON(vma->vm_start >= _addr + PMD_SIZE);
3634         offset = max(_addr, vma->vm_start) & ~PMD_MASK;
3635         VM_BUG_ON(offset >= PMD_SIZE);
3636         orig_pte = pte = pte_offset_map_lock(mm, pmdp, _addr, &ptl);
3637         pte += offset >> PAGE_SHIFT;
3638         for (addr = _addr + offset; addr < _addr + PMD_SIZE; pte++, addr += PAGE_SIZE) {
3639                 pte_t pteval = *pte;
3640                 struct page *page;
3641                 int page_nid = -1;
3642                 int target_nid;
3643                 bool migrated = false;
3644
3645                 if (!pte_present(pteval))
3646                         continue;
3647                 if (!pte_numa(pteval))
3648                         continue;
3649                 if (addr >= vma->vm_end) {
3650                         vma = find_vma(mm, addr);
3651                         /* there's a pte present so there must be a vma */
3652                         BUG_ON(!vma);
3653                         BUG_ON(addr < vma->vm_start);
3654                 }
3655                 if (pte_numa(pteval)) {
3656                         pteval = pte_mknonnuma(pteval);
3657                         set_pte_at(mm, addr, pte, pteval);
3658                 }
3659                 page = vm_normal_page(vma, addr, pteval);
3660                 if (unlikely(!page))
3661                         continue;
3662                 /* only check non-shared pages */
3663                 if (unlikely(page_mapcount(page) != 1))
3664                         continue;
3665
3666                 page_nid = page_to_nid(page);
3667                 target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3668                 pte_unmap_unlock(pte, ptl);
3669                 if (target_nid != -1) {
3670                         migrated = migrate_misplaced_page(page, target_nid);
3671                         if (migrated)
3672                                 page_nid = target_nid;
3673                 } else {
3674                         put_page(page);
3675                 }
3676
3677                 if (page_nid != -1)
3678                         task_numa_fault(page_nid, 1, migrated);
3679
3680                 pte = pte_offset_map_lock(mm, pmdp, addr, &ptl);
3681         }
3682         pte_unmap_unlock(orig_pte, ptl);
3683
3684         return 0;
3685 }
3686 #else
3687 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3688                      unsigned long addr, pmd_t *pmdp)
3689 {
3690         BUG();
3691         return 0;
3692 }
3693 #endif /* CONFIG_NUMA_BALANCING */
3694
3695 /*
3696  * These routines also need to handle stuff like marking pages dirty
3697  * and/or accessed for architectures that don't do it in hardware (most
3698  * RISC architectures).  The early dirtying is also good on the i386.
3699  *
3700  * There is also a hook called "update_mmu_cache()" that architectures
3701  * with external mmu caches can use to update those (ie the Sparc or
3702  * PowerPC hashed page tables that act as extended TLBs).
3703  *
3704  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3705  * but allow concurrent faults), and pte mapped but not yet locked.
3706  * We return with mmap_sem still held, but pte unmapped and unlocked.
3707  */
3708 int handle_pte_fault(struct mm_struct *mm,
3709                      struct vm_area_struct *vma, unsigned long address,
3710                      pte_t *pte, pmd_t *pmd, unsigned int flags)
3711 {
3712         pte_t entry;
3713         spinlock_t *ptl;
3714
3715         entry = *pte;
3716         if (!pte_present(entry)) {
3717                 if (pte_none(entry)) {
3718                         if (vma->vm_ops)
3719                                 return do_linear_fault(mm, vma, address,
3720                                                 pte, pmd, flags, entry);
3721                         return do_anonymous_page(mm, vma, address,
3722                                                  pte, pmd, flags);
3723                 }
3724                 if (pte_file(entry))
3725                         return do_nonlinear_fault(mm, vma, address,
3726                                         pte, pmd, flags, entry);
3727                 return do_swap_page(mm, vma, address,
3728                                         pte, pmd, flags, entry);
3729         }
3730
3731         if (pte_numa(entry))
3732                 return do_numa_page(mm, vma, address, entry, pte, pmd);
3733
3734         ptl = pte_lockptr(mm, pmd);
3735         spin_lock(ptl);
3736         if (unlikely(!pte_same(*pte, entry)))
3737                 goto unlock;
3738         if (flags & FAULT_FLAG_WRITE) {
3739                 if (!pte_write(entry))
3740                         return do_wp_page(mm, vma, address,
3741                                         pte, pmd, ptl, entry);
3742                 entry = pte_mkdirty(entry);
3743         }
3744         entry = pte_mkyoung(entry);
3745         if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
3746                 update_mmu_cache(vma, address, pte);
3747         } else {
3748                 /*
3749                  * This is needed only for protection faults but the arch code
3750                  * is not yet telling us if this is a protection fault or not.
3751                  * This still avoids useless tlb flushes for .text page faults
3752                  * with threads.
3753                  */
3754                 if (flags & FAULT_FLAG_WRITE)
3755                         flush_tlb_fix_spurious_fault(vma, address);
3756         }
3757 unlock:
3758         pte_unmap_unlock(pte, ptl);
3759         return 0;
3760 }
3761
3762 /*
3763  * By the time we get here, we already hold the mm semaphore
3764  */
3765 static int __handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3766                              unsigned long address, unsigned int flags)
3767 {
3768         pgd_t *pgd;
3769         pud_t *pud;
3770         pmd_t *pmd;
3771         pte_t *pte;
3772
3773         if (unlikely(is_vm_hugetlb_page(vma)))
3774                 return hugetlb_fault(mm, vma, address, flags);
3775
3776 retry:
3777         pgd = pgd_offset(mm, address);
3778         pud = pud_alloc(mm, pgd, address);
3779         if (!pud)
3780                 return VM_FAULT_OOM;
3781         pmd = pmd_alloc(mm, pud, address);
3782         if (!pmd)
3783                 return VM_FAULT_OOM;
3784         if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) {
3785                 if (!vma->vm_ops)
3786                         return do_huge_pmd_anonymous_page(mm, vma, address,
3787                                                           pmd, flags);
3788         } else {
3789                 pmd_t orig_pmd = *pmd;
3790                 int ret;
3791
3792                 barrier();
3793                 if (pmd_trans_huge(orig_pmd)) {
3794                         unsigned int dirty = flags & FAULT_FLAG_WRITE;
3795
3796                         /*
3797                          * If the pmd is splitting, return and retry the
3798                          * the fault.  Alternative: wait until the split
3799                          * is done, and goto retry.
3800                          */
3801                         if (pmd_trans_splitting(orig_pmd))
3802                                 return 0;
3803
3804                         if (pmd_numa(orig_pmd))
3805                                 return do_huge_pmd_numa_page(mm, vma, address,
3806                                                              orig_pmd, pmd);
3807
3808                         if (dirty && !pmd_write(orig_pmd)) {
3809                                 ret = do_huge_pmd_wp_page(mm, vma, address, pmd,
3810                                                           orig_pmd);
3811                                 /*
3812                                  * If COW results in an oom, the huge pmd will
3813                                  * have been split, so retry the fault on the
3814                                  * pte for a smaller charge.
3815                                  */
3816                                 if (unlikely(ret & VM_FAULT_OOM))
3817                                         goto retry;
3818                                 return ret;
3819                         } else {
3820                                 huge_pmd_set_accessed(mm, vma, address, pmd,
3821                                                       orig_pmd, dirty);
3822                         }
3823
3824                         return 0;
3825                 }
3826         }
3827
3828         if (pmd_numa(*pmd))
3829                 return do_pmd_numa_page(mm, vma, address, pmd);
3830
3831         /*
3832          * Use __pte_alloc instead of pte_alloc_map, because we can't
3833          * run pte_offset_map on the pmd, if an huge pmd could
3834          * materialize from under us from a different thread.
3835          */
3836         if (unlikely(pmd_none(*pmd)) &&
3837             unlikely(__pte_alloc(mm, vma, pmd, address)))
3838                 return VM_FAULT_OOM;
3839         /* if an huge pmd materialized from under us just retry later */
3840         if (unlikely(pmd_trans_huge(*pmd)))
3841                 return 0;
3842         /*
3843          * A regular pmd is established and it can't morph into a huge pmd
3844          * from under us anymore at this point because we hold the mmap_sem
3845          * read mode and khugepaged takes it in write mode. So now it's
3846          * safe to run pte_offset_map().
3847          */
3848         pte = pte_offset_map(pmd, address);
3849
3850         return handle_pte_fault(mm, vma, address, pte, pmd, flags);
3851 }
3852
3853 int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3854                     unsigned long address, unsigned int flags)
3855 {
3856         int ret;
3857
3858         __set_current_state(TASK_RUNNING);
3859
3860         count_vm_event(PGFAULT);
3861         mem_cgroup_count_vm_event(mm, PGFAULT);
3862
3863         /* do counter updates before entering really critical section. */
3864         check_sync_rss_stat(current);
3865
3866         /*
3867          * Enable the memcg OOM handling for faults triggered in user
3868          * space.  Kernel faults are handled more gracefully.
3869          */
3870         if (flags & FAULT_FLAG_USER)
3871                 mem_cgroup_oom_enable();
3872
3873         ret = __handle_mm_fault(mm, vma, address, flags);
3874
3875         if (flags & FAULT_FLAG_USER) {
3876                 mem_cgroup_oom_disable();
3877                 /*
3878                  * The task may have entered a memcg OOM situation but
3879                  * if the allocation error was handled gracefully (no
3880                  * VM_FAULT_OOM), there is no need to kill anything.
3881                  * Just clean up the OOM state peacefully.
3882                  */
3883                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
3884                         mem_cgroup_oom_synchronize(false);
3885         }
3886
3887         return ret;
3888 }
3889
3890 #ifndef __PAGETABLE_PUD_FOLDED
3891 /*
3892  * Allocate page upper directory.
3893  * We've already handled the fast-path in-line.
3894  */
3895 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
3896 {
3897         pud_t *new = pud_alloc_one(mm, address);
3898         if (!new)
3899                 return -ENOMEM;
3900
3901         smp_wmb(); /* See comment in __pte_alloc */
3902
3903         spin_lock(&mm->page_table_lock);
3904         if (pgd_present(*pgd))          /* Another has populated it */
3905                 pud_free(mm, new);
3906         else
3907                 pgd_populate(mm, pgd, new);
3908         spin_unlock(&mm->page_table_lock);
3909         return 0;
3910 }
3911 #endif /* __PAGETABLE_PUD_FOLDED */
3912
3913 #ifndef __PAGETABLE_PMD_FOLDED
3914 /*
3915  * Allocate page middle directory.
3916  * We've already handled the fast-path in-line.
3917  */
3918 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3919 {
3920         pmd_t *new = pmd_alloc_one(mm, address);
3921         if (!new)
3922                 return -ENOMEM;
3923
3924         smp_wmb(); /* See comment in __pte_alloc */
3925
3926         spin_lock(&mm->page_table_lock);
3927 #ifndef __ARCH_HAS_4LEVEL_HACK
3928         if (pud_present(*pud))          /* Another has populated it */
3929                 pmd_free(mm, new);
3930         else
3931                 pud_populate(mm, pud, new);
3932 #else
3933         if (pgd_present(*pud))          /* Another has populated it */
3934                 pmd_free(mm, new);
3935         else
3936                 pgd_populate(mm, pud, new);
3937 #endif /* __ARCH_HAS_4LEVEL_HACK */
3938         spin_unlock(&mm->page_table_lock);
3939         return 0;
3940 }
3941 #endif /* __PAGETABLE_PMD_FOLDED */
3942
3943 #if !defined(__HAVE_ARCH_GATE_AREA)
3944
3945 #if defined(AT_SYSINFO_EHDR)
3946 static struct vm_area_struct gate_vma;
3947
3948 static int __init gate_vma_init(void)
3949 {
3950         gate_vma.vm_mm = NULL;
3951         gate_vma.vm_start = FIXADDR_USER_START;
3952         gate_vma.vm_end = FIXADDR_USER_END;
3953         gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC;
3954         gate_vma.vm_page_prot = __P101;
3955
3956         return 0;
3957 }
3958 __initcall(gate_vma_init);
3959 #endif
3960
3961 struct vm_area_struct *get_gate_vma(struct mm_struct *mm)
3962 {
3963 #ifdef AT_SYSINFO_EHDR
3964         return &gate_vma;
3965 #else
3966         return NULL;
3967 #endif
3968 }
3969
3970 int in_gate_area_no_mm(unsigned long addr)
3971 {
3972 #ifdef AT_SYSINFO_EHDR
3973         if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END))
3974                 return 1;
3975 #endif
3976         return 0;
3977 }
3978
3979 #endif  /* __HAVE_ARCH_GATE_AREA */
3980
3981 static int __follow_pte(struct mm_struct *mm, unsigned long address,
3982                 pte_t **ptepp, spinlock_t **ptlp)
3983 {
3984         pgd_t *pgd;
3985         pud_t *pud;
3986         pmd_t *pmd;
3987         pte_t *ptep;
3988
3989         pgd = pgd_offset(mm, address);
3990         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3991                 goto out;
3992
3993         pud = pud_offset(pgd, address);
3994         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3995                 goto out;
3996
3997         pmd = pmd_offset(pud, address);
3998         VM_BUG_ON(pmd_trans_huge(*pmd));
3999         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4000                 goto out;
4001
4002         /* We cannot handle huge page PFN maps. Luckily they don't exist. */
4003         if (pmd_huge(*pmd))
4004                 goto out;
4005
4006         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4007         if (!ptep)
4008                 goto out;
4009         if (!pte_present(*ptep))
4010                 goto unlock;
4011         *ptepp = ptep;
4012         return 0;
4013 unlock:
4014         pte_unmap_unlock(ptep, *ptlp);
4015 out:
4016         return -EINVAL;
4017 }
4018
4019 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4020                              pte_t **ptepp, spinlock_t **ptlp)
4021 {
4022         int res;
4023
4024         /* (void) is needed to make gcc happy */
4025         (void) __cond_lock(*ptlp,
4026                            !(res = __follow_pte(mm, address, ptepp, ptlp)));
4027         return res;
4028 }
4029
4030 /**
4031  * follow_pfn - look up PFN at a user virtual address
4032  * @vma: memory mapping
4033  * @address: user virtual address
4034  * @pfn: location to store found PFN
4035  *
4036  * Only IO mappings and raw PFN mappings are allowed.
4037  *
4038  * Returns zero and the pfn at @pfn on success, -ve otherwise.
4039  */
4040 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4041         unsigned long *pfn)
4042 {
4043         int ret = -EINVAL;
4044         spinlock_t *ptl;
4045         pte_t *ptep;
4046
4047         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4048                 return ret;
4049
4050         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4051         if (ret)
4052                 return ret;
4053         *pfn = pte_pfn(*ptep);
4054         pte_unmap_unlock(ptep, ptl);
4055         return 0;
4056 }
4057 EXPORT_SYMBOL(follow_pfn);
4058
4059 #ifdef CONFIG_HAVE_IOREMAP_PROT
4060 int follow_phys(struct vm_area_struct *vma,
4061                 unsigned long address, unsigned int flags,
4062                 unsigned long *prot, resource_size_t *phys)
4063 {
4064         int ret = -EINVAL;
4065         pte_t *ptep, pte;
4066         spinlock_t *ptl;
4067
4068         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4069                 goto out;
4070
4071         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4072                 goto out;
4073         pte = *ptep;
4074
4075         if ((flags & FOLL_WRITE) && !pte_write(pte))
4076                 goto unlock;
4077
4078         *prot = pgprot_val(pte_pgprot(pte));
4079         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4080
4081         ret = 0;
4082 unlock:
4083         pte_unmap_unlock(ptep, ptl);
4084 out:
4085         return ret;
4086 }
4087
4088 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4089                         void *buf, int len, int write)
4090 {
4091         resource_size_t phys_addr;
4092         unsigned long prot = 0;
4093         void __iomem *maddr;
4094         int offset = addr & (PAGE_SIZE-1);
4095
4096         if (follow_phys(vma, addr, write, &prot, &phys_addr))
4097                 return -EINVAL;
4098
4099         maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4100         if (write)
4101                 memcpy_toio(maddr + offset, buf, len);
4102         else
4103                 memcpy_fromio(buf, maddr + offset, len);
4104         iounmap(maddr);
4105
4106         return len;
4107 }
4108 EXPORT_SYMBOL_GPL(generic_access_phys);
4109 #endif
4110
4111 /*
4112  * Access another process' address space as given in mm.  If non-NULL, use the
4113  * given task for page fault accounting.
4114  */
4115 static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4116                 unsigned long addr, void *buf, int len, int write)
4117 {
4118         struct vm_area_struct *vma;
4119         void *old_buf = buf;
4120
4121         down_read(&mm->mmap_sem);
4122         /* ignore errors, just check how much was successfully transferred */
4123         while (len) {
4124                 int bytes, ret, offset;
4125                 void *maddr;
4126                 struct page *page = NULL;
4127
4128                 ret = get_user_pages(tsk, mm, addr, 1,
4129                                 write, 1, &page, &vma);
4130                 if (ret <= 0) {
4131                         /*
4132                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
4133                          * we can access using slightly different code.
4134                          */
4135 #ifdef CONFIG_HAVE_IOREMAP_PROT
4136                         vma = find_vma(mm, addr);
4137                         if (!vma || vma->vm_start > addr)
4138                                 break;
4139                         if (vma->vm_ops && vma->vm_ops->access)
4140                                 ret = vma->vm_ops->access(vma, addr, buf,
4141                                                           len, write);
4142                         if (ret <= 0)
4143 #endif
4144                                 break;
4145                         bytes = ret;
4146                 } else {
4147                         bytes = len;
4148                         offset = addr & (PAGE_SIZE-1);
4149                         if (bytes > PAGE_SIZE-offset)
4150                                 bytes = PAGE_SIZE-offset;
4151
4152                         maddr = kmap(page);
4153                         if (write) {
4154                                 copy_to_user_page(vma, page, addr,
4155                                                   maddr + offset, buf, bytes);
4156                                 set_page_dirty_lock(page);
4157                         } else {
4158                                 copy_from_user_page(vma, page, addr,
4159                                                     buf, maddr + offset, bytes);
4160                         }
4161                         kunmap(page);
4162                         page_cache_release(page);
4163                 }
4164                 len -= bytes;
4165                 buf += bytes;
4166                 addr += bytes;
4167         }
4168         up_read(&mm->mmap_sem);
4169
4170         return buf - old_buf;
4171 }
4172
4173 /**
4174  * access_remote_vm - access another process' address space
4175  * @mm:         the mm_struct of the target address space
4176  * @addr:       start address to access
4177  * @buf:        source or destination buffer
4178  * @len:        number of bytes to transfer
4179  * @write:      whether the access is a write
4180  *
4181  * The caller must hold a reference on @mm.
4182  */
4183 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4184                 void *buf, int len, int write)
4185 {
4186         return __access_remote_vm(NULL, mm, addr, buf, len, write);
4187 }
4188
4189 /*
4190  * Access another process' address space.
4191  * Source/target buffer must be kernel space,
4192  * Do not walk the page table directly, use get_user_pages
4193  */
4194 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4195                 void *buf, int len, int write)
4196 {
4197         struct mm_struct *mm;
4198         int ret;
4199
4200         mm = get_task_mm(tsk);
4201         if (!mm)
4202                 return 0;
4203
4204         ret = __access_remote_vm(tsk, mm, addr, buf, len, write);
4205         mmput(mm);
4206
4207         return ret;
4208 }
4209
4210 /*
4211  * Print the name of a VMA.
4212  */
4213 void print_vma_addr(char *prefix, unsigned long ip)
4214 {
4215         struct mm_struct *mm = current->mm;
4216         struct vm_area_struct *vma;
4217
4218         /*
4219          * Do not print if we are in atomic
4220          * contexts (in exception stacks, etc.):
4221          */
4222         if (preempt_count())
4223                 return;
4224
4225         down_read(&mm->mmap_sem);
4226         vma = find_vma(mm, ip);
4227         if (vma && vma->vm_file) {
4228                 struct file *f = vma->vm_file;
4229                 char *buf = (char *)__get_free_page(GFP_KERNEL);
4230                 if (buf) {
4231                         char *p;
4232
4233                         p = d_path(&f->f_path, buf, PAGE_SIZE);
4234                         if (IS_ERR(p))
4235                                 p = "?";
4236                         printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4237                                         vma->vm_start,
4238                                         vma->vm_end - vma->vm_start);
4239                         free_page((unsigned long)buf);
4240                 }
4241         }
4242         up_read(&mm->mmap_sem);
4243 }
4244
4245 #ifdef CONFIG_PROVE_LOCKING
4246 void might_fault(void)
4247 {
4248         /*
4249          * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4250          * holding the mmap_sem, this is safe because kernel memory doesn't
4251          * get paged out, therefore we'll never actually fault, and the
4252          * below annotations will generate false positives.
4253          */
4254         if (segment_eq(get_fs(), KERNEL_DS))
4255                 return;
4256
4257         might_sleep();
4258         /*
4259          * it would be nicer only to annotate paths which are not under
4260          * pagefault_disable, however that requires a larger audit and
4261          * providing helpers like get_user_atomic.
4262          */
4263         if (!in_atomic() && current->mm)
4264                 might_lock_read(&current->mm->mmap_sem);
4265 }
4266 EXPORT_SYMBOL(might_fault);
4267 #endif
4268
4269 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4270 static void clear_gigantic_page(struct page *page,
4271                                 unsigned long addr,
4272                                 unsigned int pages_per_huge_page)
4273 {
4274         int i;
4275         struct page *p = page;
4276
4277         might_sleep();
4278         for (i = 0; i < pages_per_huge_page;
4279              i++, p = mem_map_next(p, page, i)) {
4280                 cond_resched();
4281                 clear_user_highpage(p, addr + i * PAGE_SIZE);
4282         }
4283 }
4284 void clear_huge_page(struct page *page,
4285                      unsigned long addr, unsigned int pages_per_huge_page)
4286 {
4287         int i;
4288
4289         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4290                 clear_gigantic_page(page, addr, pages_per_huge_page);
4291                 return;
4292         }
4293
4294         might_sleep();
4295         for (i = 0; i < pages_per_huge_page; i++) {
4296                 cond_resched();
4297                 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4298         }
4299 }
4300
4301 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4302                                     unsigned long addr,
4303                                     struct vm_area_struct *vma,
4304                                     unsigned int pages_per_huge_page)
4305 {
4306         int i;
4307         struct page *dst_base = dst;
4308         struct page *src_base = src;
4309
4310         for (i = 0; i < pages_per_huge_page; ) {
4311                 cond_resched();
4312                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4313
4314                 i++;
4315                 dst = mem_map_next(dst, dst_base, i);
4316                 src = mem_map_next(src, src_base, i);
4317         }
4318 }
4319
4320 void copy_user_huge_page(struct page *dst, struct page *src,
4321                          unsigned long addr, struct vm_area_struct *vma,
4322                          unsigned int pages_per_huge_page)
4323 {
4324         int i;
4325
4326         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4327                 copy_user_gigantic_page(dst, src, addr, vma,
4328                                         pages_per_huge_page);
4329                 return;
4330         }
4331
4332         might_sleep();
4333         for (i = 0; i < pages_per_huge_page; i++) {
4334                 cond_resched();
4335                 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4336         }
4337 }
4338 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */