Merge tag 'v3.10.72' into linux-linaro-lsk
[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                                                 return i ? i : -EFAULT;
1851                                         BUG();
1852                                 }
1853
1854                                 if (tsk) {
1855                                         if (ret & VM_FAULT_MAJOR)
1856                                                 tsk->maj_flt++;
1857                                         else
1858                                                 tsk->min_flt++;
1859                                 }
1860
1861                                 if (ret & VM_FAULT_RETRY) {
1862                                         if (nonblocking)
1863                                                 *nonblocking = 0;
1864                                         return i;
1865                                 }
1866
1867                                 /*
1868                                  * The VM_FAULT_WRITE bit tells us that
1869                                  * do_wp_page has broken COW when necessary,
1870                                  * even if maybe_mkwrite decided not to set
1871                                  * pte_write. We can thus safely do subsequent
1872                                  * page lookups as if they were reads. But only
1873                                  * do so when looping for pte_write is futile:
1874                                  * in some cases userspace may also be wanting
1875                                  * to write to the gotten user page, which a
1876                                  * read fault here might prevent (a readonly
1877                                  * page might get reCOWed by userspace write).
1878                                  */
1879                                 if ((ret & VM_FAULT_WRITE) &&
1880                                     !(vma->vm_flags & VM_WRITE))
1881                                         foll_flags &= ~FOLL_WRITE;
1882
1883                                 cond_resched();
1884                         }
1885                         if (IS_ERR(page))
1886                                 return i ? i : PTR_ERR(page);
1887                         if (pages) {
1888                                 pages[i] = page;
1889
1890                                 flush_anon_page(vma, page, start);
1891                                 flush_dcache_page(page);
1892                                 page_mask = 0;
1893                         }
1894 next_page:
1895                         if (vmas) {
1896                                 vmas[i] = vma;
1897                                 page_mask = 0;
1898                         }
1899                         page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
1900                         if (page_increm > nr_pages)
1901                                 page_increm = nr_pages;
1902                         i += page_increm;
1903                         start += page_increm * PAGE_SIZE;
1904                         nr_pages -= page_increm;
1905                 } while (nr_pages && start < vma->vm_end);
1906         } while (nr_pages);
1907         return i;
1908 }
1909 EXPORT_SYMBOL(__get_user_pages);
1910
1911 /*
1912  * fixup_user_fault() - manually resolve a user page fault
1913  * @tsk:        the task_struct to use for page fault accounting, or
1914  *              NULL if faults are not to be recorded.
1915  * @mm:         mm_struct of target mm
1916  * @address:    user address
1917  * @fault_flags:flags to pass down to handle_mm_fault()
1918  *
1919  * This is meant to be called in the specific scenario where for locking reasons
1920  * we try to access user memory in atomic context (within a pagefault_disable()
1921  * section), this returns -EFAULT, and we want to resolve the user fault before
1922  * trying again.
1923  *
1924  * Typically this is meant to be used by the futex code.
1925  *
1926  * The main difference with get_user_pages() is that this function will
1927  * unconditionally call handle_mm_fault() which will in turn perform all the
1928  * necessary SW fixup of the dirty and young bits in the PTE, while
1929  * handle_mm_fault() only guarantees to update these in the struct page.
1930  *
1931  * This is important for some architectures where those bits also gate the
1932  * access permission to the page because they are maintained in software.  On
1933  * such architectures, gup() will not be enough to make a subsequent access
1934  * succeed.
1935  *
1936  * This should be called with the mm_sem held for read.
1937  */
1938 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
1939                      unsigned long address, unsigned int fault_flags)
1940 {
1941         struct vm_area_struct *vma;
1942         vm_flags_t vm_flags;
1943         int ret;
1944
1945         vma = find_extend_vma(mm, address);
1946         if (!vma || address < vma->vm_start)
1947                 return -EFAULT;
1948
1949         vm_flags = (fault_flags & FAULT_FLAG_WRITE) ? VM_WRITE : VM_READ;
1950         if (!(vm_flags & vma->vm_flags))
1951                 return -EFAULT;
1952
1953         ret = handle_mm_fault(mm, vma, address, fault_flags);
1954         if (ret & VM_FAULT_ERROR) {
1955                 if (ret & VM_FAULT_OOM)
1956                         return -ENOMEM;
1957                 if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
1958                         return -EHWPOISON;
1959                 if (ret & VM_FAULT_SIGBUS)
1960                         return -EFAULT;
1961                 BUG();
1962         }
1963         if (tsk) {
1964                 if (ret & VM_FAULT_MAJOR)
1965                         tsk->maj_flt++;
1966                 else
1967                         tsk->min_flt++;
1968         }
1969         return 0;
1970 }
1971
1972 /*
1973  * get_user_pages() - pin user pages in memory
1974  * @tsk:        the task_struct to use for page fault accounting, or
1975  *              NULL if faults are not to be recorded.
1976  * @mm:         mm_struct of target mm
1977  * @start:      starting user address
1978  * @nr_pages:   number of pages from start to pin
1979  * @write:      whether pages will be written to by the caller
1980  * @force:      whether to force write access even if user mapping is
1981  *              readonly. This will result in the page being COWed even
1982  *              in MAP_SHARED mappings. You do not want this.
1983  * @pages:      array that receives pointers to the pages pinned.
1984  *              Should be at least nr_pages long. Or NULL, if caller
1985  *              only intends to ensure the pages are faulted in.
1986  * @vmas:       array of pointers to vmas corresponding to each page.
1987  *              Or NULL if the caller does not require them.
1988  *
1989  * Returns number of pages pinned. This may be fewer than the number
1990  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1991  * were pinned, returns -errno. Each page returned must be released
1992  * with a put_page() call when it is finished with. vmas will only
1993  * remain valid while mmap_sem is held.
1994  *
1995  * Must be called with mmap_sem held for read or write.
1996  *
1997  * get_user_pages walks a process's page tables and takes a reference to
1998  * each struct page that each user address corresponds to at a given
1999  * instant. That is, it takes the page that would be accessed if a user
2000  * thread accesses the given user virtual address at that instant.
2001  *
2002  * This does not guarantee that the page exists in the user mappings when
2003  * get_user_pages returns, and there may even be a completely different
2004  * page there in some cases (eg. if mmapped pagecache has been invalidated
2005  * and subsequently re faulted). However it does guarantee that the page
2006  * won't be freed completely. And mostly callers simply care that the page
2007  * contains data that was valid *at some point in time*. Typically, an IO
2008  * or similar operation cannot guarantee anything stronger anyway because
2009  * locks can't be held over the syscall boundary.
2010  *
2011  * If write=0, the page must not be written to. If the page is written to,
2012  * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called
2013  * after the page is finished with, and before put_page is called.
2014  *
2015  * get_user_pages is typically used for fewer-copy IO operations, to get a
2016  * handle on the memory by some means other than accesses via the user virtual
2017  * addresses. The pages may be submitted for DMA to devices or accessed via
2018  * their kernel linear mapping (via the kmap APIs). Care should be taken to
2019  * use the correct cache flushing APIs.
2020  *
2021  * See also get_user_pages_fast, for performance critical applications.
2022  */
2023 long get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
2024                 unsigned long start, unsigned long nr_pages, int write,
2025                 int force, struct page **pages, struct vm_area_struct **vmas)
2026 {
2027         int flags = FOLL_TOUCH;
2028
2029         if (pages)
2030                 flags |= FOLL_GET;
2031         if (write)
2032                 flags |= FOLL_WRITE;
2033         if (force)
2034                 flags |= FOLL_FORCE;
2035
2036         return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas,
2037                                 NULL);
2038 }
2039 EXPORT_SYMBOL(get_user_pages);
2040
2041 /**
2042  * get_dump_page() - pin user page in memory while writing it to core dump
2043  * @addr: user address
2044  *
2045  * Returns struct page pointer of user page pinned for dump,
2046  * to be freed afterwards by page_cache_release() or put_page().
2047  *
2048  * Returns NULL on any kind of failure - a hole must then be inserted into
2049  * the corefile, to preserve alignment with its headers; and also returns
2050  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
2051  * allowing a hole to be left in the corefile to save diskspace.
2052  *
2053  * Called without mmap_sem, but after all other threads have been killed.
2054  */
2055 #ifdef CONFIG_ELF_CORE
2056 struct page *get_dump_page(unsigned long addr)
2057 {
2058         struct vm_area_struct *vma;
2059         struct page *page;
2060
2061         if (__get_user_pages(current, current->mm, addr, 1,
2062                              FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
2063                              NULL) < 1)
2064                 return NULL;
2065         flush_cache_page(vma, addr, page_to_pfn(page));
2066         return page;
2067 }
2068 #endif /* CONFIG_ELF_CORE */
2069
2070 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
2071                         spinlock_t **ptl)
2072 {
2073         pgd_t * pgd = pgd_offset(mm, addr);
2074         pud_t * pud = pud_alloc(mm, pgd, addr);
2075         if (pud) {
2076                 pmd_t * pmd = pmd_alloc(mm, pud, addr);
2077                 if (pmd) {
2078                         VM_BUG_ON(pmd_trans_huge(*pmd));
2079                         return pte_alloc_map_lock(mm, pmd, addr, ptl);
2080                 }
2081         }
2082         return NULL;
2083 }
2084
2085 /*
2086  * This is the old fallback for page remapping.
2087  *
2088  * For historical reasons, it only allows reserved pages. Only
2089  * old drivers should use this, and they needed to mark their
2090  * pages reserved for the old functions anyway.
2091  */
2092 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
2093                         struct page *page, pgprot_t prot)
2094 {
2095         struct mm_struct *mm = vma->vm_mm;
2096         int retval;
2097         pte_t *pte;
2098         spinlock_t *ptl;
2099
2100         retval = -EINVAL;
2101         if (PageAnon(page))
2102                 goto out;
2103         retval = -ENOMEM;
2104         flush_dcache_page(page);
2105         pte = get_locked_pte(mm, addr, &ptl);
2106         if (!pte)
2107                 goto out;
2108         retval = -EBUSY;
2109         if (!pte_none(*pte))
2110                 goto out_unlock;
2111
2112         /* Ok, finally just insert the thing.. */
2113         get_page(page);
2114         inc_mm_counter_fast(mm, MM_FILEPAGES);
2115         page_add_file_rmap(page);
2116         set_pte_at(mm, addr, pte, mk_pte(page, prot));
2117
2118         retval = 0;
2119         pte_unmap_unlock(pte, ptl);
2120         return retval;
2121 out_unlock:
2122         pte_unmap_unlock(pte, ptl);
2123 out:
2124         return retval;
2125 }
2126
2127 /**
2128  * vm_insert_page - insert single page into user vma
2129  * @vma: user vma to map to
2130  * @addr: target user address of this page
2131  * @page: source kernel page
2132  *
2133  * This allows drivers to insert individual pages they've allocated
2134  * into a user vma.
2135  *
2136  * The page has to be a nice clean _individual_ kernel allocation.
2137  * If you allocate a compound page, you need to have marked it as
2138  * such (__GFP_COMP), or manually just split the page up yourself
2139  * (see split_page()).
2140  *
2141  * NOTE! Traditionally this was done with "remap_pfn_range()" which
2142  * took an arbitrary page protection parameter. This doesn't allow
2143  * that. Your vma protection will have to be set up correctly, which
2144  * means that if you want a shared writable mapping, you'd better
2145  * ask for a shared writable mapping!
2146  *
2147  * The page does not need to be reserved.
2148  *
2149  * Usually this function is called from f_op->mmap() handler
2150  * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
2151  * Caller must set VM_MIXEDMAP on vma if it wants to call this
2152  * function from other places, for example from page-fault handler.
2153  */
2154 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2155                         struct page *page)
2156 {
2157         if (addr < vma->vm_start || addr >= vma->vm_end)
2158                 return -EFAULT;
2159         if (!page_count(page))
2160                 return -EINVAL;
2161         if (!(vma->vm_flags & VM_MIXEDMAP)) {
2162                 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
2163                 BUG_ON(vma->vm_flags & VM_PFNMAP);
2164                 vma->vm_flags |= VM_MIXEDMAP;
2165         }
2166         return insert_page(vma, addr, page, vma->vm_page_prot);
2167 }
2168 EXPORT_SYMBOL(vm_insert_page);
2169
2170 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2171                         unsigned long pfn, pgprot_t prot)
2172 {
2173         struct mm_struct *mm = vma->vm_mm;
2174         int retval;
2175         pte_t *pte, entry;
2176         spinlock_t *ptl;
2177
2178         retval = -ENOMEM;
2179         pte = get_locked_pte(mm, addr, &ptl);
2180         if (!pte)
2181                 goto out;
2182         retval = -EBUSY;
2183         if (!pte_none(*pte))
2184                 goto out_unlock;
2185
2186         /* Ok, finally just insert the thing.. */
2187         entry = pte_mkspecial(pfn_pte(pfn, prot));
2188         set_pte_at(mm, addr, pte, entry);
2189         update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2190
2191         retval = 0;
2192 out_unlock:
2193         pte_unmap_unlock(pte, ptl);
2194 out:
2195         return retval;
2196 }
2197
2198 /**
2199  * vm_insert_pfn - insert single pfn into user vma
2200  * @vma: user vma to map to
2201  * @addr: target user address of this page
2202  * @pfn: source kernel pfn
2203  *
2204  * Similar to vm_insert_page, this allows drivers to insert individual pages
2205  * they've allocated into a user vma. Same comments apply.
2206  *
2207  * This function should only be called from a vm_ops->fault handler, and
2208  * in that case the handler should return NULL.
2209  *
2210  * vma cannot be a COW mapping.
2211  *
2212  * As this is called only for pages that do not currently exist, we
2213  * do not need to flush old virtual caches or the TLB.
2214  */
2215 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2216                         unsigned long pfn)
2217 {
2218         int ret;
2219         pgprot_t pgprot = vma->vm_page_prot;
2220         /*
2221          * Technically, architectures with pte_special can avoid all these
2222          * restrictions (same for remap_pfn_range).  However we would like
2223          * consistency in testing and feature parity among all, so we should
2224          * try to keep these invariants in place for everybody.
2225          */
2226         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2227         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2228                                                 (VM_PFNMAP|VM_MIXEDMAP));
2229         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2230         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2231
2232         if (addr < vma->vm_start || addr >= vma->vm_end)
2233                 return -EFAULT;
2234         if (track_pfn_insert(vma, &pgprot, pfn))
2235                 return -EINVAL;
2236
2237         ret = insert_pfn(vma, addr, pfn, pgprot);
2238
2239         return ret;
2240 }
2241 EXPORT_SYMBOL(vm_insert_pfn);
2242
2243 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2244                         unsigned long pfn)
2245 {
2246         BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
2247
2248         if (addr < vma->vm_start || addr >= vma->vm_end)
2249                 return -EFAULT;
2250
2251         /*
2252          * If we don't have pte special, then we have to use the pfn_valid()
2253          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2254          * refcount the page if pfn_valid is true (hence insert_page rather
2255          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
2256          * without pte special, it would there be refcounted as a normal page.
2257          */
2258         if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) {
2259                 struct page *page;
2260
2261                 page = pfn_to_page(pfn);
2262                 return insert_page(vma, addr, page, vma->vm_page_prot);
2263         }
2264         return insert_pfn(vma, addr, pfn, vma->vm_page_prot);
2265 }
2266 EXPORT_SYMBOL(vm_insert_mixed);
2267
2268 /*
2269  * maps a range of physical memory into the requested pages. the old
2270  * mappings are removed. any references to nonexistent pages results
2271  * in null mappings (currently treated as "copy-on-access")
2272  */
2273 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2274                         unsigned long addr, unsigned long end,
2275                         unsigned long pfn, pgprot_t prot)
2276 {
2277         pte_t *pte;
2278         spinlock_t *ptl;
2279
2280         pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2281         if (!pte)
2282                 return -ENOMEM;
2283         arch_enter_lazy_mmu_mode();
2284         do {
2285                 BUG_ON(!pte_none(*pte));
2286                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2287                 pfn++;
2288         } while (pte++, addr += PAGE_SIZE, addr != end);
2289         arch_leave_lazy_mmu_mode();
2290         pte_unmap_unlock(pte - 1, ptl);
2291         return 0;
2292 }
2293
2294 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2295                         unsigned long addr, unsigned long end,
2296                         unsigned long pfn, pgprot_t prot)
2297 {
2298         pmd_t *pmd;
2299         unsigned long next;
2300
2301         pfn -= addr >> PAGE_SHIFT;
2302         pmd = pmd_alloc(mm, pud, addr);
2303         if (!pmd)
2304                 return -ENOMEM;
2305         VM_BUG_ON(pmd_trans_huge(*pmd));
2306         do {
2307                 next = pmd_addr_end(addr, end);
2308                 if (remap_pte_range(mm, pmd, addr, next,
2309                                 pfn + (addr >> PAGE_SHIFT), prot))
2310                         return -ENOMEM;
2311         } while (pmd++, addr = next, addr != end);
2312         return 0;
2313 }
2314
2315 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
2316                         unsigned long addr, unsigned long end,
2317                         unsigned long pfn, pgprot_t prot)
2318 {
2319         pud_t *pud;
2320         unsigned long next;
2321
2322         pfn -= addr >> PAGE_SHIFT;
2323         pud = pud_alloc(mm, pgd, addr);
2324         if (!pud)
2325                 return -ENOMEM;
2326         do {
2327                 next = pud_addr_end(addr, end);
2328                 if (remap_pmd_range(mm, pud, addr, next,
2329                                 pfn + (addr >> PAGE_SHIFT), prot))
2330                         return -ENOMEM;
2331         } while (pud++, addr = next, addr != end);
2332         return 0;
2333 }
2334
2335 /**
2336  * remap_pfn_range - remap kernel memory to userspace
2337  * @vma: user vma to map to
2338  * @addr: target user address to start at
2339  * @pfn: physical address of kernel memory
2340  * @size: size of map area
2341  * @prot: page protection flags for this mapping
2342  *
2343  *  Note: this is only safe if the mm semaphore is held when called.
2344  */
2345 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2346                     unsigned long pfn, unsigned long size, pgprot_t prot)
2347 {
2348         pgd_t *pgd;
2349         unsigned long next;
2350         unsigned long end = addr + PAGE_ALIGN(size);
2351         struct mm_struct *mm = vma->vm_mm;
2352         int err;
2353
2354         /*
2355          * Physically remapped pages are special. Tell the
2356          * rest of the world about it:
2357          *   VM_IO tells people not to look at these pages
2358          *      (accesses can have side effects).
2359          *   VM_PFNMAP tells the core MM that the base pages are just
2360          *      raw PFN mappings, and do not have a "struct page" associated
2361          *      with them.
2362          *   VM_DONTEXPAND
2363          *      Disable vma merging and expanding with mremap().
2364          *   VM_DONTDUMP
2365          *      Omit vma from core dump, even when VM_IO turned off.
2366          *
2367          * There's a horrible special case to handle copy-on-write
2368          * behaviour that some programs depend on. We mark the "original"
2369          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2370          * See vm_normal_page() for details.
2371          */
2372         if (is_cow_mapping(vma->vm_flags)) {
2373                 if (addr != vma->vm_start || end != vma->vm_end)
2374                         return -EINVAL;
2375                 vma->vm_pgoff = pfn;
2376         }
2377
2378         err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2379         if (err)
2380                 return -EINVAL;
2381
2382         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2383
2384         BUG_ON(addr >= end);
2385         pfn -= addr >> PAGE_SHIFT;
2386         pgd = pgd_offset(mm, addr);
2387         flush_cache_range(vma, addr, end);
2388         do {
2389                 next = pgd_addr_end(addr, end);
2390                 err = remap_pud_range(mm, pgd, addr, next,
2391                                 pfn + (addr >> PAGE_SHIFT), prot);
2392                 if (err)
2393                         break;
2394         } while (pgd++, addr = next, addr != end);
2395
2396         if (err)
2397                 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2398
2399         return err;
2400 }
2401 EXPORT_SYMBOL(remap_pfn_range);
2402
2403 /**
2404  * vm_iomap_memory - remap memory to userspace
2405  * @vma: user vma to map to
2406  * @start: start of area
2407  * @len: size of area
2408  *
2409  * This is a simplified io_remap_pfn_range() for common driver use. The
2410  * driver just needs to give us the physical memory range to be mapped,
2411  * we'll figure out the rest from the vma information.
2412  *
2413  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2414  * whatever write-combining details or similar.
2415  */
2416 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2417 {
2418         unsigned long vm_len, pfn, pages;
2419
2420         /* Check that the physical memory area passed in looks valid */
2421         if (start + len < start)
2422                 return -EINVAL;
2423         /*
2424          * You *really* shouldn't map things that aren't page-aligned,
2425          * but we've historically allowed it because IO memory might
2426          * just have smaller alignment.
2427          */
2428         len += start & ~PAGE_MASK;
2429         pfn = start >> PAGE_SHIFT;
2430         pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2431         if (pfn + pages < pfn)
2432                 return -EINVAL;
2433
2434         /* We start the mapping 'vm_pgoff' pages into the area */
2435         if (vma->vm_pgoff > pages)
2436                 return -EINVAL;
2437         pfn += vma->vm_pgoff;
2438         pages -= vma->vm_pgoff;
2439
2440         /* Can we fit all of the mapping? */
2441         vm_len = vma->vm_end - vma->vm_start;
2442         if (vm_len >> PAGE_SHIFT > pages)
2443                 return -EINVAL;
2444
2445         /* Ok, let it rip */
2446         return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2447 }
2448 EXPORT_SYMBOL(vm_iomap_memory);
2449
2450 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2451                                      unsigned long addr, unsigned long end,
2452                                      pte_fn_t fn, void *data)
2453 {
2454         pte_t *pte;
2455         int err;
2456         pgtable_t token;
2457         spinlock_t *uninitialized_var(ptl);
2458
2459         pte = (mm == &init_mm) ?
2460                 pte_alloc_kernel(pmd, addr) :
2461                 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2462         if (!pte)
2463                 return -ENOMEM;
2464
2465         BUG_ON(pmd_huge(*pmd));
2466
2467         arch_enter_lazy_mmu_mode();
2468
2469         token = pmd_pgtable(*pmd);
2470
2471         do {
2472                 err = fn(pte++, token, addr, data);
2473                 if (err)
2474                         break;
2475         } while (addr += PAGE_SIZE, addr != end);
2476
2477         arch_leave_lazy_mmu_mode();
2478
2479         if (mm != &init_mm)
2480                 pte_unmap_unlock(pte-1, ptl);
2481         return err;
2482 }
2483
2484 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2485                                      unsigned long addr, unsigned long end,
2486                                      pte_fn_t fn, void *data)
2487 {
2488         pmd_t *pmd;
2489         unsigned long next;
2490         int err;
2491
2492         BUG_ON(pud_huge(*pud));
2493
2494         pmd = pmd_alloc(mm, pud, addr);
2495         if (!pmd)
2496                 return -ENOMEM;
2497         do {
2498                 next = pmd_addr_end(addr, end);
2499                 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2500                 if (err)
2501                         break;
2502         } while (pmd++, addr = next, addr != end);
2503         return err;
2504 }
2505
2506 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
2507                                      unsigned long addr, unsigned long end,
2508                                      pte_fn_t fn, void *data)
2509 {
2510         pud_t *pud;
2511         unsigned long next;
2512         int err;
2513
2514         pud = pud_alloc(mm, pgd, addr);
2515         if (!pud)
2516                 return -ENOMEM;
2517         do {
2518                 next = pud_addr_end(addr, end);
2519                 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2520                 if (err)
2521                         break;
2522         } while (pud++, addr = next, addr != end);
2523         return err;
2524 }
2525
2526 /*
2527  * Scan a region of virtual memory, filling in page tables as necessary
2528  * and calling a provided function on each leaf page table.
2529  */
2530 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2531                         unsigned long size, pte_fn_t fn, void *data)
2532 {
2533         pgd_t *pgd;
2534         unsigned long next;
2535         unsigned long end = addr + size;
2536         int err;
2537
2538         BUG_ON(addr >= end);
2539         pgd = pgd_offset(mm, addr);
2540         do {
2541                 next = pgd_addr_end(addr, end);
2542                 err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
2543                 if (err)
2544                         break;
2545         } while (pgd++, addr = next, addr != end);
2546
2547         return err;
2548 }
2549 EXPORT_SYMBOL_GPL(apply_to_page_range);
2550
2551 /*
2552  * handle_pte_fault chooses page fault handler according to an entry
2553  * which was read non-atomically.  Before making any commitment, on
2554  * those architectures or configurations (e.g. i386 with PAE) which
2555  * might give a mix of unmatched parts, do_swap_page and do_nonlinear_fault
2556  * must check under lock before unmapping the pte and proceeding
2557  * (but do_wp_page is only called after already making such a check;
2558  * and do_anonymous_page can safely check later on).
2559  */
2560 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2561                                 pte_t *page_table, pte_t orig_pte)
2562 {
2563         int same = 1;
2564 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2565         if (sizeof(pte_t) > sizeof(unsigned long)) {
2566                 spinlock_t *ptl = pte_lockptr(mm, pmd);
2567                 spin_lock(ptl);
2568                 same = pte_same(*page_table, orig_pte);
2569                 spin_unlock(ptl);
2570         }
2571 #endif
2572         pte_unmap(page_table);
2573         return same;
2574 }
2575
2576 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
2577 {
2578         /*
2579          * If the source page was a PFN mapping, we don't have
2580          * a "struct page" for it. We do a best-effort copy by
2581          * just copying from the original user address. If that
2582          * fails, we just zero-fill it. Live with it.
2583          */
2584         if (unlikely(!src)) {
2585                 void *kaddr = kmap_atomic(dst);
2586                 void __user *uaddr = (void __user *)(va & PAGE_MASK);
2587
2588                 /*
2589                  * This really shouldn't fail, because the page is there
2590                  * in the page tables. But it might just be unreadable,
2591                  * in which case we just give up and fill the result with
2592                  * zeroes.
2593                  */
2594                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2595                         clear_page(kaddr);
2596                 kunmap_atomic(kaddr);
2597                 flush_dcache_page(dst);
2598         } else
2599                 copy_user_highpage(dst, src, va, vma);
2600 }
2601
2602 /*
2603  * This routine handles present pages, when users try to write
2604  * to a shared page. It is done by copying the page to a new address
2605  * and decrementing the shared-page counter for the old page.
2606  *
2607  * Note that this routine assumes that the protection checks have been
2608  * done by the caller (the low-level page fault routine in most cases).
2609  * Thus we can safely just mark it writable once we've done any necessary
2610  * COW.
2611  *
2612  * We also mark the page dirty at this point even though the page will
2613  * change only once the write actually happens. This avoids a few races,
2614  * and potentially makes it more efficient.
2615  *
2616  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2617  * but allow concurrent faults), with pte both mapped and locked.
2618  * We return with mmap_sem still held, but pte unmapped and unlocked.
2619  */
2620 static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
2621                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2622                 spinlock_t *ptl, pte_t orig_pte)
2623         __releases(ptl)
2624 {
2625         struct page *old_page, *new_page = NULL;
2626         pte_t entry;
2627         int ret = 0;
2628         int page_mkwrite = 0;
2629         struct page *dirty_page = NULL;
2630         unsigned long mmun_start = 0;   /* For mmu_notifiers */
2631         unsigned long mmun_end = 0;     /* For mmu_notifiers */
2632
2633         old_page = vm_normal_page(vma, address, orig_pte);
2634         if (!old_page) {
2635                 /*
2636                  * VM_MIXEDMAP !pfn_valid() case
2637                  *
2638                  * We should not cow pages in a shared writeable mapping.
2639                  * Just mark the pages writable as we can't do any dirty
2640                  * accounting on raw pfn maps.
2641                  */
2642                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2643                                      (VM_WRITE|VM_SHARED))
2644                         goto reuse;
2645                 goto gotten;
2646         }
2647
2648         /*
2649          * Take out anonymous pages first, anonymous shared vmas are
2650          * not dirty accountable.
2651          */
2652         if (PageAnon(old_page) && !PageKsm(old_page)) {
2653                 if (!trylock_page(old_page)) {
2654                         page_cache_get(old_page);
2655                         pte_unmap_unlock(page_table, ptl);
2656                         lock_page(old_page);
2657                         page_table = pte_offset_map_lock(mm, pmd, address,
2658                                                          &ptl);
2659                         if (!pte_same(*page_table, orig_pte)) {
2660                                 unlock_page(old_page);
2661                                 goto unlock;
2662                         }
2663                         page_cache_release(old_page);
2664                 }
2665                 if (reuse_swap_page(old_page)) {
2666                         /*
2667                          * The page is all ours.  Move it to our anon_vma so
2668                          * the rmap code will not search our parent or siblings.
2669                          * Protected against the rmap code by the page lock.
2670                          */
2671                         page_move_anon_rmap(old_page, vma, address);
2672                         unlock_page(old_page);
2673                         goto reuse;
2674                 }
2675                 unlock_page(old_page);
2676         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2677                                         (VM_WRITE|VM_SHARED))) {
2678                 /*
2679                  * Only catch write-faults on shared writable pages,
2680                  * read-only shared pages can get COWed by
2681                  * get_user_pages(.write=1, .force=1).
2682                  */
2683                 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2684                         struct vm_fault vmf;
2685                         int tmp;
2686
2687                         vmf.virtual_address = (void __user *)(address &
2688                                                                 PAGE_MASK);
2689                         vmf.pgoff = old_page->index;
2690                         vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2691                         vmf.page = old_page;
2692
2693                         /*
2694                          * Notify the address space that the page is about to
2695                          * become writable so that it can prohibit this or wait
2696                          * for the page to get into an appropriate state.
2697                          *
2698                          * We do this without the lock held, so that it can
2699                          * sleep if it needs to.
2700                          */
2701                         page_cache_get(old_page);
2702                         pte_unmap_unlock(page_table, ptl);
2703
2704                         tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
2705                         if (unlikely(tmp &
2706                                         (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2707                                 ret = tmp;
2708                                 goto unwritable_page;
2709                         }
2710                         if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
2711                                 lock_page(old_page);
2712                                 if (!old_page->mapping) {
2713                                         ret = 0; /* retry the fault */
2714                                         unlock_page(old_page);
2715                                         goto unwritable_page;
2716                                 }
2717                         } else
2718                                 VM_BUG_ON(!PageLocked(old_page));
2719
2720                         /*
2721                          * Since we dropped the lock we need to revalidate
2722                          * the PTE as someone else may have changed it.  If
2723                          * they did, we just return, as we can count on the
2724                          * MMU to tell us if they didn't also make it writable.
2725                          */
2726                         page_table = pte_offset_map_lock(mm, pmd, address,
2727                                                          &ptl);
2728                         if (!pte_same(*page_table, orig_pte)) {
2729                                 unlock_page(old_page);
2730                                 goto unlock;
2731                         }
2732
2733                         page_mkwrite = 1;
2734                 }
2735                 dirty_page = old_page;
2736                 get_page(dirty_page);
2737
2738 reuse:
2739                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2740                 entry = pte_mkyoung(orig_pte);
2741                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2742                 if (ptep_set_access_flags(vma, address, page_table, entry,1))
2743                         update_mmu_cache(vma, address, page_table);
2744                 pte_unmap_unlock(page_table, ptl);
2745                 ret |= VM_FAULT_WRITE;
2746
2747                 if (!dirty_page)
2748                         return ret;
2749
2750                 /*
2751                  * Yes, Virginia, this is actually required to prevent a race
2752                  * with clear_page_dirty_for_io() from clearing the page dirty
2753                  * bit after it clear all dirty ptes, but before a racing
2754                  * do_wp_page installs a dirty pte.
2755                  *
2756                  * __do_fault is protected similarly.
2757                  */
2758                 if (!page_mkwrite) {
2759                         wait_on_page_locked(dirty_page);
2760                         set_page_dirty_balance(dirty_page, page_mkwrite);
2761                         /* file_update_time outside page_lock */
2762                         if (vma->vm_file)
2763                                 file_update_time(vma->vm_file);
2764                 }
2765                 put_page(dirty_page);
2766                 if (page_mkwrite) {
2767                         struct address_space *mapping = dirty_page->mapping;
2768
2769                         set_page_dirty(dirty_page);
2770                         unlock_page(dirty_page);
2771                         page_cache_release(dirty_page);
2772                         if (mapping)    {
2773                                 /*
2774                                  * Some device drivers do not set page.mapping
2775                                  * but still dirty their pages
2776                                  */
2777                                 balance_dirty_pages_ratelimited(mapping);
2778                         }
2779                 }
2780
2781                 return ret;
2782         }
2783
2784         /*
2785          * Ok, we need to copy. Oh, well..
2786          */
2787         page_cache_get(old_page);
2788 gotten:
2789         pte_unmap_unlock(page_table, ptl);
2790
2791         if (unlikely(anon_vma_prepare(vma)))
2792                 goto oom;
2793
2794         if (is_zero_pfn(pte_pfn(orig_pte))) {
2795                 new_page = alloc_zeroed_user_highpage_movable(vma, address);
2796                 if (!new_page)
2797                         goto oom;
2798         } else {
2799                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2800                 if (!new_page)
2801                         goto oom;
2802                 cow_user_page(new_page, old_page, address, vma);
2803         }
2804         __SetPageUptodate(new_page);
2805
2806         if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))
2807                 goto oom_free_new;
2808
2809         mmun_start  = address & PAGE_MASK;
2810         mmun_end    = mmun_start + PAGE_SIZE;
2811         mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2812
2813         /*
2814          * Re-check the pte - we dropped the lock
2815          */
2816         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2817         if (likely(pte_same(*page_table, orig_pte))) {
2818                 if (old_page) {
2819                         if (!PageAnon(old_page)) {
2820                                 dec_mm_counter_fast(mm, MM_FILEPAGES);
2821                                 inc_mm_counter_fast(mm, MM_ANONPAGES);
2822                         }
2823                 } else
2824                         inc_mm_counter_fast(mm, MM_ANONPAGES);
2825                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2826                 entry = mk_pte(new_page, vma->vm_page_prot);
2827                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2828                 /*
2829                  * Clear the pte entry and flush it first, before updating the
2830                  * pte with the new entry. This will avoid a race condition
2831                  * seen in the presence of one thread doing SMC and another
2832                  * thread doing COW.
2833                  */
2834                 ptep_clear_flush(vma, address, page_table);
2835                 page_add_new_anon_rmap(new_page, vma, address);
2836                 /*
2837                  * We call the notify macro here because, when using secondary
2838                  * mmu page tables (such as kvm shadow page tables), we want the
2839                  * new page to be mapped directly into the secondary page table.
2840                  */
2841                 set_pte_at_notify(mm, address, page_table, entry);
2842                 update_mmu_cache(vma, address, page_table);
2843                 if (old_page) {
2844                         /*
2845                          * Only after switching the pte to the new page may
2846                          * we remove the mapcount here. Otherwise another
2847                          * process may come and find the rmap count decremented
2848                          * before the pte is switched to the new page, and
2849                          * "reuse" the old page writing into it while our pte
2850                          * here still points into it and can be read by other
2851                          * threads.
2852                          *
2853                          * The critical issue is to order this
2854                          * page_remove_rmap with the ptp_clear_flush above.
2855                          * Those stores are ordered by (if nothing else,)
2856                          * the barrier present in the atomic_add_negative
2857                          * in page_remove_rmap.
2858                          *
2859                          * Then the TLB flush in ptep_clear_flush ensures that
2860                          * no process can access the old page before the
2861                          * decremented mapcount is visible. And the old page
2862                          * cannot be reused until after the decremented
2863                          * mapcount is visible. So transitively, TLBs to
2864                          * old page will be flushed before it can be reused.
2865                          */
2866                         page_remove_rmap(old_page);
2867                 }
2868
2869                 /* Free the old page.. */
2870                 new_page = old_page;
2871                 ret |= VM_FAULT_WRITE;
2872         } else
2873                 mem_cgroup_uncharge_page(new_page);
2874
2875         if (new_page)
2876                 page_cache_release(new_page);
2877 unlock:
2878         pte_unmap_unlock(page_table, ptl);
2879         if (mmun_end > mmun_start)
2880                 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2881         if (old_page) {
2882                 /*
2883                  * Don't let another task, with possibly unlocked vma,
2884                  * keep the mlocked page.
2885                  */
2886                 if ((ret & VM_FAULT_WRITE) && (vma->vm_flags & VM_LOCKED)) {
2887                         lock_page(old_page);    /* LRU manipulation */
2888                         munlock_vma_page(old_page);
2889                         unlock_page(old_page);
2890                 }
2891                 page_cache_release(old_page);
2892         }
2893         return ret;
2894 oom_free_new:
2895         page_cache_release(new_page);
2896 oom:
2897         if (old_page)
2898                 page_cache_release(old_page);
2899         return VM_FAULT_OOM;
2900
2901 unwritable_page:
2902         page_cache_release(old_page);
2903         return ret;
2904 }
2905
2906 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2907                 unsigned long start_addr, unsigned long end_addr,
2908                 struct zap_details *details)
2909 {
2910         zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2911 }
2912
2913 static inline void unmap_mapping_range_tree(struct rb_root *root,
2914                                             struct zap_details *details)
2915 {
2916         struct vm_area_struct *vma;
2917         pgoff_t vba, vea, zba, zea;
2918
2919         vma_interval_tree_foreach(vma, root,
2920                         details->first_index, details->last_index) {
2921
2922                 vba = vma->vm_pgoff;
2923                 vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1;
2924                 /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */
2925                 zba = details->first_index;
2926                 if (zba < vba)
2927                         zba = vba;
2928                 zea = details->last_index;
2929                 if (zea > vea)
2930                         zea = vea;
2931
2932                 unmap_mapping_range_vma(vma,
2933                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2934                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2935                                 details);
2936         }
2937 }
2938
2939 static inline void unmap_mapping_range_list(struct list_head *head,
2940                                             struct zap_details *details)
2941 {
2942         struct vm_area_struct *vma;
2943
2944         /*
2945          * In nonlinear VMAs there is no correspondence between virtual address
2946          * offset and file offset.  So we must perform an exhaustive search
2947          * across *all* the pages in each nonlinear VMA, not just the pages
2948          * whose virtual address lies outside the file truncation point.
2949          */
2950         list_for_each_entry(vma, head, shared.nonlinear) {
2951                 details->nonlinear_vma = vma;
2952                 unmap_mapping_range_vma(vma, vma->vm_start, vma->vm_end, details);
2953         }
2954 }
2955
2956 /**
2957  * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file.
2958  * @mapping: the address space containing mmaps to be unmapped.
2959  * @holebegin: byte in first page to unmap, relative to the start of
2960  * the underlying file.  This will be rounded down to a PAGE_SIZE
2961  * boundary.  Note that this is different from truncate_pagecache(), which
2962  * must keep the partial page.  In contrast, we must get rid of
2963  * partial pages.
2964  * @holelen: size of prospective hole in bytes.  This will be rounded
2965  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
2966  * end of the file.
2967  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2968  * but 0 when invalidating pagecache, don't throw away private data.
2969  */
2970 void unmap_mapping_range(struct address_space *mapping,
2971                 loff_t const holebegin, loff_t const holelen, int even_cows)
2972 {
2973         struct zap_details details;
2974         pgoff_t hba = holebegin >> PAGE_SHIFT;
2975         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2976
2977         /* Check for overflow. */
2978         if (sizeof(holelen) > sizeof(hlen)) {
2979                 long long holeend =
2980                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2981                 if (holeend & ~(long long)ULONG_MAX)
2982                         hlen = ULONG_MAX - hba + 1;
2983         }
2984
2985         details.check_mapping = even_cows? NULL: mapping;
2986         details.nonlinear_vma = NULL;
2987         details.first_index = hba;
2988         details.last_index = hba + hlen - 1;
2989         if (details.last_index < details.first_index)
2990                 details.last_index = ULONG_MAX;
2991
2992
2993         mutex_lock(&mapping->i_mmap_mutex);
2994         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
2995                 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2996         if (unlikely(!list_empty(&mapping->i_mmap_nonlinear)))
2997                 unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details);
2998         mutex_unlock(&mapping->i_mmap_mutex);
2999 }
3000 EXPORT_SYMBOL(unmap_mapping_range);
3001
3002 /*
3003  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3004  * but allow concurrent faults), and pte mapped but not yet locked.
3005  * We return with mmap_sem still held, but pte unmapped and unlocked.
3006  */
3007 static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
3008                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3009                 unsigned int flags, pte_t orig_pte)
3010 {
3011         spinlock_t *ptl;
3012         struct page *page, *swapcache;
3013         swp_entry_t entry;
3014         pte_t pte;
3015         int locked;
3016         struct mem_cgroup *ptr;
3017         int exclusive = 0;
3018         int ret = 0;
3019
3020         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3021                 goto out;
3022
3023         entry = pte_to_swp_entry(orig_pte);
3024         if (unlikely(non_swap_entry(entry))) {
3025                 if (is_migration_entry(entry)) {
3026                         migration_entry_wait(mm, pmd, address);
3027                 } else if (is_hwpoison_entry(entry)) {
3028                         ret = VM_FAULT_HWPOISON;
3029                 } else {
3030                         print_bad_pte(vma, address, orig_pte, NULL);
3031                         ret = VM_FAULT_SIGBUS;
3032                 }
3033                 goto out;
3034         }
3035         delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3036         page = lookup_swap_cache(entry);
3037         if (!page) {
3038                 page = swapin_readahead(entry,
3039                                         GFP_HIGHUSER_MOVABLE, vma, address);
3040                 if (!page) {
3041                         /*
3042                          * Back out if somebody else faulted in this pte
3043                          * while we released the pte lock.
3044                          */
3045                         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3046                         if (likely(pte_same(*page_table, orig_pte)))
3047                                 ret = VM_FAULT_OOM;
3048                         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3049                         goto unlock;
3050                 }
3051
3052                 /* Had to read the page from swap area: Major fault */
3053                 ret = VM_FAULT_MAJOR;
3054                 count_vm_event(PGMAJFAULT);
3055                 mem_cgroup_count_vm_event(mm, PGMAJFAULT);
3056         } else if (PageHWPoison(page)) {
3057                 /*
3058                  * hwpoisoned dirty swapcache pages are kept for killing
3059                  * owner processes (which may be unknown at hwpoison time)
3060                  */
3061                 ret = VM_FAULT_HWPOISON;
3062                 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3063                 swapcache = page;
3064                 goto out_release;
3065         }
3066
3067         swapcache = page;
3068         locked = lock_page_or_retry(page, mm, flags);
3069
3070         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3071         if (!locked) {
3072                 ret |= VM_FAULT_RETRY;
3073                 goto out_release;
3074         }
3075
3076         /*
3077          * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3078          * release the swapcache from under us.  The page pin, and pte_same
3079          * test below, are not enough to exclude that.  Even if it is still
3080          * swapcache, we need to check that the page's swap has not changed.
3081          */
3082         if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3083                 goto out_page;
3084
3085         page = ksm_might_need_to_copy(page, vma, address);
3086         if (unlikely(!page)) {
3087                 ret = VM_FAULT_OOM;
3088                 page = swapcache;
3089                 goto out_page;
3090         }
3091
3092         if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) {
3093                 ret = VM_FAULT_OOM;
3094                 goto out_page;
3095         }
3096
3097         /*
3098          * Back out if somebody else already faulted in this pte.
3099          */
3100         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3101         if (unlikely(!pte_same(*page_table, orig_pte)))
3102                 goto out_nomap;
3103
3104         if (unlikely(!PageUptodate(page))) {
3105                 ret = VM_FAULT_SIGBUS;
3106                 goto out_nomap;
3107         }
3108
3109         /*
3110          * The page isn't present yet, go ahead with the fault.
3111          *
3112          * Be careful about the sequence of operations here.
3113          * To get its accounting right, reuse_swap_page() must be called
3114          * while the page is counted on swap but not yet in mapcount i.e.
3115          * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3116          * must be called after the swap_free(), or it will never succeed.
3117          * Because delete_from_swap_page() may be called by reuse_swap_page(),
3118          * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry
3119          * in page->private. In this case, a record in swap_cgroup  is silently
3120          * discarded at swap_free().
3121          */
3122
3123         inc_mm_counter_fast(mm, MM_ANONPAGES);
3124         dec_mm_counter_fast(mm, MM_SWAPENTS);
3125         pte = mk_pte(page, vma->vm_page_prot);
3126         if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {
3127                 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3128                 flags &= ~FAULT_FLAG_WRITE;
3129                 ret |= VM_FAULT_WRITE;
3130                 exclusive = 1;
3131         }
3132         flush_icache_page(vma, page);
3133         set_pte_at(mm, address, page_table, pte);
3134         if (page == swapcache)
3135                 do_page_add_anon_rmap(page, vma, address, exclusive);
3136         else /* ksm created a completely new copy */
3137                 page_add_new_anon_rmap(page, vma, address);
3138         /* It's better to call commit-charge after rmap is established */
3139         mem_cgroup_commit_charge_swapin(page, ptr);
3140
3141         swap_free(entry);
3142         if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3143                 try_to_free_swap(page);
3144         unlock_page(page);
3145         if (page != swapcache) {
3146                 /*
3147                  * Hold the lock to avoid the swap entry to be reused
3148                  * until we take the PT lock for the pte_same() check
3149                  * (to avoid false positives from pte_same). For
3150                  * further safety release the lock after the swap_free
3151                  * so that the swap count won't change under a
3152                  * parallel locked swapcache.
3153                  */
3154                 unlock_page(swapcache);
3155                 page_cache_release(swapcache);
3156         }
3157
3158         if (flags & FAULT_FLAG_WRITE) {
3159                 ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte);
3160                 if (ret & VM_FAULT_ERROR)
3161                         ret &= VM_FAULT_ERROR;
3162                 goto out;
3163         }
3164
3165         /* No need to invalidate - it was non-present before */
3166         update_mmu_cache(vma, address, page_table);
3167 unlock:
3168         pte_unmap_unlock(page_table, ptl);
3169 out:
3170         return ret;
3171 out_nomap:
3172         mem_cgroup_cancel_charge_swapin(ptr);
3173         pte_unmap_unlock(page_table, ptl);
3174 out_page:
3175         unlock_page(page);
3176 out_release:
3177         page_cache_release(page);
3178         if (page != swapcache) {
3179                 unlock_page(swapcache);
3180                 page_cache_release(swapcache);
3181         }
3182         return ret;
3183 }
3184
3185 /*
3186  * This is like a special single-page "expand_{down|up}wards()",
3187  * except we must first make sure that 'address{-|+}PAGE_SIZE'
3188  * doesn't hit another vma.
3189  */
3190 static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address)
3191 {
3192         address &= PAGE_MASK;
3193         if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) {
3194                 struct vm_area_struct *prev = vma->vm_prev;
3195
3196                 /*
3197                  * Is there a mapping abutting this one below?
3198                  *
3199                  * That's only ok if it's the same stack mapping
3200                  * that has gotten split..
3201                  */
3202                 if (prev && prev->vm_end == address)
3203                         return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM;
3204
3205                 return expand_downwards(vma, address - PAGE_SIZE);
3206         }
3207         if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) {
3208                 struct vm_area_struct *next = vma->vm_next;
3209
3210                 /* As VM_GROWSDOWN but s/below/above/ */
3211                 if (next && next->vm_start == address + PAGE_SIZE)
3212                         return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM;
3213
3214                 return expand_upwards(vma, address + PAGE_SIZE);
3215         }
3216         return 0;
3217 }
3218
3219 /*
3220  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3221  * but allow concurrent faults), and pte mapped but not yet locked.
3222  * We return with mmap_sem still held, but pte unmapped and unlocked.
3223  */
3224 static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
3225                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3226                 unsigned int flags)
3227 {
3228         struct page *page;
3229         spinlock_t *ptl;
3230         pte_t entry;
3231
3232         pte_unmap(page_table);
3233
3234         /* Check if we need to add a guard page to the stack */
3235         if (check_stack_guard_page(vma, address) < 0)
3236                 return VM_FAULT_SIGBUS;
3237
3238         /* Use the zero-page for reads */
3239         if (!(flags & FAULT_FLAG_WRITE)) {
3240                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(address),
3241                                                 vma->vm_page_prot));
3242                 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3243                 if (!pte_none(*page_table))
3244                         goto unlock;
3245                 goto setpte;
3246         }
3247
3248         /* Allocate our own private page. */
3249         if (unlikely(anon_vma_prepare(vma)))
3250                 goto oom;
3251         page = alloc_zeroed_user_highpage_movable(vma, address);
3252         if (!page)
3253                 goto oom;
3254         /*
3255          * The memory barrier inside __SetPageUptodate makes sure that
3256          * preceeding stores to the page contents become visible before
3257          * the set_pte_at() write.
3258          */
3259         __SetPageUptodate(page);
3260
3261         if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))
3262                 goto oom_free_page;
3263
3264         entry = mk_pte(page, vma->vm_page_prot);
3265         if (vma->vm_flags & VM_WRITE)
3266                 entry = pte_mkwrite(pte_mkdirty(entry));
3267
3268         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3269         if (!pte_none(*page_table))
3270                 goto release;
3271
3272         inc_mm_counter_fast(mm, MM_ANONPAGES);
3273         page_add_new_anon_rmap(page, vma, address);
3274 setpte:
3275         set_pte_at(mm, address, page_table, entry);
3276
3277         /* No need to invalidate - it was non-present before */
3278         update_mmu_cache(vma, address, page_table);
3279 unlock:
3280         pte_unmap_unlock(page_table, ptl);
3281         return 0;
3282 release:
3283         mem_cgroup_uncharge_page(page);
3284         page_cache_release(page);
3285         goto unlock;
3286 oom_free_page:
3287         page_cache_release(page);
3288 oom:
3289         return VM_FAULT_OOM;
3290 }
3291
3292 /*
3293  * __do_fault() tries to create a new page mapping. It aggressively
3294  * tries to share with existing pages, but makes a separate copy if
3295  * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid
3296  * the next page fault.
3297  *
3298  * As this is called only for pages that do not currently exist, we
3299  * do not need to flush old virtual caches or the TLB.
3300  *
3301  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3302  * but allow concurrent faults), and pte neither mapped nor locked.
3303  * We return with mmap_sem still held, but pte unmapped and unlocked.
3304  */
3305 static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3306                 unsigned long address, pmd_t *pmd,
3307                 pgoff_t pgoff, unsigned int flags, pte_t orig_pte)
3308 {
3309         pte_t *page_table;
3310         spinlock_t *ptl;
3311         struct page *page;
3312         struct page *cow_page;
3313         pte_t entry;
3314         int anon = 0;
3315         struct page *dirty_page = NULL;
3316         struct vm_fault vmf;
3317         int ret;
3318         int page_mkwrite = 0;
3319
3320         /*
3321          * If we do COW later, allocate page befor taking lock_page()
3322          * on the file cache page. This will reduce lock holding time.
3323          */
3324         if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
3325
3326                 if (unlikely(anon_vma_prepare(vma)))
3327                         return VM_FAULT_OOM;
3328
3329                 cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
3330                 if (!cow_page)
3331                         return VM_FAULT_OOM;
3332
3333                 if (mem_cgroup_newpage_charge(cow_page, mm, GFP_KERNEL)) {
3334                         page_cache_release(cow_page);
3335                         return VM_FAULT_OOM;
3336                 }
3337         } else
3338                 cow_page = NULL;
3339
3340         vmf.virtual_address = (void __user *)(address & PAGE_MASK);
3341         vmf.pgoff = pgoff;
3342         vmf.flags = flags;
3343         vmf.page = NULL;
3344
3345         ret = vma->vm_ops->fault(vma, &vmf);
3346         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3347                             VM_FAULT_RETRY)))
3348                 goto uncharge_out;
3349
3350         if (unlikely(PageHWPoison(vmf.page))) {
3351                 if (ret & VM_FAULT_LOCKED)
3352                         unlock_page(vmf.page);
3353                 ret = VM_FAULT_HWPOISON;
3354                 goto uncharge_out;
3355         }
3356
3357         /*
3358          * For consistency in subsequent calls, make the faulted page always
3359          * locked.
3360          */
3361         if (unlikely(!(ret & VM_FAULT_LOCKED)))
3362                 lock_page(vmf.page);
3363         else
3364                 VM_BUG_ON(!PageLocked(vmf.page));
3365
3366         /*
3367          * Should we do an early C-O-W break?
3368          */
3369         page = vmf.page;
3370         if (flags & FAULT_FLAG_WRITE) {
3371                 if (!(vma->vm_flags & VM_SHARED)) {
3372                         page = cow_page;
3373                         anon = 1;
3374                         copy_user_highpage(page, vmf.page, address, vma);
3375                         __SetPageUptodate(page);
3376                 } else {
3377                         /*
3378                          * If the page will be shareable, see if the backing
3379                          * address space wants to know that the page is about
3380                          * to become writable
3381                          */
3382                         if (vma->vm_ops->page_mkwrite) {
3383                                 int tmp;
3384
3385                                 unlock_page(page);
3386                                 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
3387                                 tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
3388                                 if (unlikely(tmp &
3389                                           (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3390                                         ret = tmp;
3391                                         goto unwritable_page;
3392                                 }
3393                                 if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
3394                                         lock_page(page);
3395                                         if (!page->mapping) {
3396                                                 ret = 0; /* retry the fault */
3397                                                 unlock_page(page);
3398                                                 goto unwritable_page;
3399                                         }
3400                                 } else
3401                                         VM_BUG_ON(!PageLocked(page));
3402                                 page_mkwrite = 1;
3403                         }
3404                 }
3405
3406         }
3407
3408         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3409
3410         /*
3411          * This silly early PAGE_DIRTY setting removes a race
3412          * due to the bad i386 page protection. But it's valid
3413          * for other architectures too.
3414          *
3415          * Note that if FAULT_FLAG_WRITE is set, we either now have
3416          * an exclusive copy of the page, or this is a shared mapping,
3417          * so we can make it writable and dirty to avoid having to
3418          * handle that later.
3419          */
3420         /* Only go through if we didn't race with anybody else... */
3421         if (likely(pte_same(*page_table, orig_pte))) {
3422                 flush_icache_page(vma, page);
3423                 entry = mk_pte(page, vma->vm_page_prot);
3424                 if (flags & FAULT_FLAG_WRITE)
3425                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3426                 if (anon) {
3427                         inc_mm_counter_fast(mm, MM_ANONPAGES);
3428                         page_add_new_anon_rmap(page, vma, address);
3429                 } else {
3430                         inc_mm_counter_fast(mm, MM_FILEPAGES);
3431                         page_add_file_rmap(page);
3432                         if (flags & FAULT_FLAG_WRITE) {
3433                                 dirty_page = page;
3434                                 get_page(dirty_page);
3435                         }
3436                 }
3437                 set_pte_at(mm, address, page_table, entry);
3438
3439                 /* no need to invalidate: a not-present page won't be cached */
3440                 update_mmu_cache(vma, address, page_table);
3441         } else {
3442                 if (cow_page)
3443                         mem_cgroup_uncharge_page(cow_page);
3444                 if (anon)
3445                         page_cache_release(page);
3446                 else
3447                         anon = 1; /* no anon but release faulted_page */
3448         }
3449
3450         pte_unmap_unlock(page_table, ptl);
3451
3452         if (dirty_page) {
3453                 struct address_space *mapping = page->mapping;
3454                 int dirtied = 0;
3455
3456                 if (set_page_dirty(dirty_page))
3457                         dirtied = 1;
3458                 unlock_page(dirty_page);
3459                 put_page(dirty_page);
3460                 if ((dirtied || page_mkwrite) && mapping) {
3461                         /*
3462                          * Some device drivers do not set page.mapping but still
3463                          * dirty their pages
3464                          */
3465                         balance_dirty_pages_ratelimited(mapping);
3466                 }
3467
3468                 /* file_update_time outside page_lock */
3469                 if (vma->vm_file && !page_mkwrite)
3470                         file_update_time(vma->vm_file);
3471         } else {
3472                 unlock_page(vmf.page);
3473                 if (anon)
3474                         page_cache_release(vmf.page);
3475         }
3476
3477         return ret;
3478
3479 unwritable_page:
3480         page_cache_release(page);
3481         return ret;
3482 uncharge_out:
3483         /* fs's fault handler get error */
3484         if (cow_page) {
3485                 mem_cgroup_uncharge_page(cow_page);
3486                 page_cache_release(cow_page);
3487         }
3488         return ret;
3489 }
3490
3491 static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3492                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3493                 unsigned int flags, pte_t orig_pte)
3494 {
3495         pgoff_t pgoff = (((address & PAGE_MASK)
3496                         - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
3497
3498         pte_unmap(page_table);
3499         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3500 }
3501
3502 /*
3503  * Fault of a previously existing named mapping. Repopulate the pte
3504  * from the encoded file_pte if possible. This enables swappable
3505  * nonlinear vmas.
3506  *
3507  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3508  * but allow concurrent faults), and pte mapped but not yet locked.
3509  * We return with mmap_sem still held, but pte unmapped and unlocked.
3510  */
3511 static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3512                 unsigned long address, pte_t *page_table, pmd_t *pmd,
3513                 unsigned int flags, pte_t orig_pte)
3514 {
3515         pgoff_t pgoff;
3516
3517         flags |= FAULT_FLAG_NONLINEAR;
3518
3519         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3520                 return 0;
3521
3522         if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) {
3523                 /*
3524                  * Page table corrupted: show pte and kill process.
3525                  */
3526                 print_bad_pte(vma, address, orig_pte, NULL);
3527                 return VM_FAULT_SIGBUS;
3528         }
3529
3530         pgoff = pte_to_pgoff(orig_pte);
3531         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3532 }
3533
3534 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3535                                 unsigned long addr, int page_nid)
3536 {
3537         get_page(page);
3538
3539         count_vm_numa_event(NUMA_HINT_FAULTS);
3540         if (page_nid == numa_node_id())
3541                 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3542
3543         return mpol_misplaced(page, vma, addr);
3544 }
3545
3546 int do_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3547                    unsigned long addr, pte_t pte, pte_t *ptep, pmd_t *pmd)
3548 {
3549         struct page *page = NULL;
3550         spinlock_t *ptl;
3551         int page_nid = -1;
3552         int target_nid;
3553         bool migrated = false;
3554
3555         /*
3556         * The "pte" at this point cannot be used safely without
3557         * validation through pte_unmap_same(). It's of NUMA type but
3558         * the pfn may be screwed if the read is non atomic.
3559         *
3560         * ptep_modify_prot_start is not called as this is clearing
3561         * the _PAGE_NUMA bit and it is not really expected that there
3562         * would be concurrent hardware modifications to the PTE.
3563         */
3564         ptl = pte_lockptr(mm, pmd);
3565         spin_lock(ptl);
3566         if (unlikely(!pte_same(*ptep, pte))) {
3567                 pte_unmap_unlock(ptep, ptl);
3568                 goto out;
3569         }
3570
3571         pte = pte_mknonnuma(pte);
3572         set_pte_at(mm, addr, ptep, pte);
3573         update_mmu_cache(vma, addr, ptep);
3574
3575         page = vm_normal_page(vma, addr, pte);
3576         if (!page) {
3577                 pte_unmap_unlock(ptep, ptl);
3578                 return 0;
3579         }
3580
3581         page_nid = page_to_nid(page);
3582         target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3583         pte_unmap_unlock(ptep, ptl);
3584         if (target_nid == -1) {
3585                 put_page(page);
3586                 goto out;
3587         }
3588
3589         /* Migrate to the requested node */
3590         migrated = migrate_misplaced_page(page, target_nid);
3591         if (migrated)
3592                 page_nid = target_nid;
3593
3594 out:
3595         if (page_nid != -1)
3596                 task_numa_fault(page_nid, 1, migrated);
3597         return 0;
3598 }
3599
3600 /* NUMA hinting page fault entry point for regular pmds */
3601 #ifdef CONFIG_NUMA_BALANCING
3602 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3603                      unsigned long addr, pmd_t *pmdp)
3604 {
3605         pmd_t pmd;
3606         pte_t *pte, *orig_pte;
3607         unsigned long _addr = addr & PMD_MASK;
3608         unsigned long offset;
3609         spinlock_t *ptl;
3610         bool numa = false;
3611
3612         spin_lock(&mm->page_table_lock);
3613         pmd = *pmdp;
3614         if (pmd_numa(pmd)) {
3615                 set_pmd_at(mm, _addr, pmdp, pmd_mknonnuma(pmd));
3616                 numa = true;
3617         }
3618         spin_unlock(&mm->page_table_lock);
3619
3620         if (!numa)
3621                 return 0;
3622
3623         /* we're in a page fault so some vma must be in the range */
3624         BUG_ON(!vma);
3625         BUG_ON(vma->vm_start >= _addr + PMD_SIZE);
3626         offset = max(_addr, vma->vm_start) & ~PMD_MASK;
3627         VM_BUG_ON(offset >= PMD_SIZE);
3628         orig_pte = pte = pte_offset_map_lock(mm, pmdp, _addr, &ptl);
3629         pte += offset >> PAGE_SHIFT;
3630         for (addr = _addr + offset; addr < _addr + PMD_SIZE; pte++, addr += PAGE_SIZE) {
3631                 pte_t pteval = *pte;
3632                 struct page *page;
3633                 int page_nid = -1;
3634                 int target_nid;
3635                 bool migrated = false;
3636
3637                 if (!pte_present(pteval))
3638                         continue;
3639                 if (!pte_numa(pteval))
3640                         continue;
3641                 if (addr >= vma->vm_end) {
3642                         vma = find_vma(mm, addr);
3643                         /* there's a pte present so there must be a vma */
3644                         BUG_ON(!vma);
3645                         BUG_ON(addr < vma->vm_start);
3646                 }
3647                 if (pte_numa(pteval)) {
3648                         pteval = pte_mknonnuma(pteval);
3649                         set_pte_at(mm, addr, pte, pteval);
3650                 }
3651                 page = vm_normal_page(vma, addr, pteval);
3652                 if (unlikely(!page))
3653                         continue;
3654                 /* only check non-shared pages */
3655                 if (unlikely(page_mapcount(page) != 1))
3656                         continue;
3657
3658                 page_nid = page_to_nid(page);
3659                 target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3660                 pte_unmap_unlock(pte, ptl);
3661                 if (target_nid != -1) {
3662                         migrated = migrate_misplaced_page(page, target_nid);
3663                         if (migrated)
3664                                 page_nid = target_nid;
3665                 } else {
3666                         put_page(page);
3667                 }
3668
3669                 if (page_nid != -1)
3670                         task_numa_fault(page_nid, 1, migrated);
3671
3672                 pte = pte_offset_map_lock(mm, pmdp, addr, &ptl);
3673         }
3674         pte_unmap_unlock(orig_pte, ptl);
3675
3676         return 0;
3677 }
3678 #else
3679 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3680                      unsigned long addr, pmd_t *pmdp)
3681 {
3682         BUG();
3683         return 0;
3684 }
3685 #endif /* CONFIG_NUMA_BALANCING */
3686
3687 /*
3688  * These routines also need to handle stuff like marking pages dirty
3689  * and/or accessed for architectures that don't do it in hardware (most
3690  * RISC architectures).  The early dirtying is also good on the i386.
3691  *
3692  * There is also a hook called "update_mmu_cache()" that architectures
3693  * with external mmu caches can use to update those (ie the Sparc or
3694  * PowerPC hashed page tables that act as extended TLBs).
3695  *
3696  * We enter with non-exclusive mmap_sem (to exclude vma changes,
3697  * but allow concurrent faults), and pte mapped but not yet locked.
3698  * We return with mmap_sem still held, but pte unmapped and unlocked.
3699  */
3700 int handle_pte_fault(struct mm_struct *mm,
3701                      struct vm_area_struct *vma, unsigned long address,
3702                      pte_t *pte, pmd_t *pmd, unsigned int flags)
3703 {
3704         pte_t entry;
3705         spinlock_t *ptl;
3706
3707         entry = *pte;
3708         if (!pte_present(entry)) {
3709                 if (pte_none(entry)) {
3710                         if (vma->vm_ops) {
3711                                 if (likely(vma->vm_ops->fault))
3712                                         return do_linear_fault(mm, vma, address,
3713                                                 pte, pmd, flags, entry);
3714                         }
3715                         return do_anonymous_page(mm, vma, address,
3716                                                  pte, pmd, flags);
3717                 }
3718                 if (pte_file(entry))
3719                         return do_nonlinear_fault(mm, vma, address,
3720                                         pte, pmd, flags, entry);
3721                 return do_swap_page(mm, vma, address,
3722                                         pte, pmd, flags, entry);
3723         }
3724
3725         if (pte_numa(entry))
3726                 return do_numa_page(mm, vma, address, entry, pte, pmd);
3727
3728         ptl = pte_lockptr(mm, pmd);
3729         spin_lock(ptl);
3730         if (unlikely(!pte_same(*pte, entry)))
3731                 goto unlock;
3732         if (flags & FAULT_FLAG_WRITE) {
3733                 if (!pte_write(entry))
3734                         return do_wp_page(mm, vma, address,
3735                                         pte, pmd, ptl, entry);
3736                 entry = pte_mkdirty(entry);
3737         }
3738         entry = pte_mkyoung(entry);
3739         if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
3740                 update_mmu_cache(vma, address, pte);
3741         } else {
3742                 /*
3743                  * This is needed only for protection faults but the arch code
3744                  * is not yet telling us if this is a protection fault or not.
3745                  * This still avoids useless tlb flushes for .text page faults
3746                  * with threads.
3747                  */
3748                 if (flags & FAULT_FLAG_WRITE)
3749                         flush_tlb_fix_spurious_fault(vma, address);
3750         }
3751 unlock:
3752         pte_unmap_unlock(pte, ptl);
3753         return 0;
3754 }
3755
3756 /*
3757  * By the time we get here, we already hold the mm semaphore
3758  */
3759 static int __handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3760                              unsigned long address, unsigned int flags)
3761 {
3762         pgd_t *pgd;
3763         pud_t *pud;
3764         pmd_t *pmd;
3765         pte_t *pte;
3766
3767         if (unlikely(is_vm_hugetlb_page(vma)))
3768                 return hugetlb_fault(mm, vma, address, flags);
3769
3770 retry:
3771         pgd = pgd_offset(mm, address);
3772         pud = pud_alloc(mm, pgd, address);
3773         if (!pud)
3774                 return VM_FAULT_OOM;
3775         pmd = pmd_alloc(mm, pud, address);
3776         if (!pmd)
3777                 return VM_FAULT_OOM;
3778         if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) {
3779                 if (!vma->vm_ops)
3780                         return do_huge_pmd_anonymous_page(mm, vma, address,
3781                                                           pmd, flags);
3782         } else {
3783                 pmd_t orig_pmd = *pmd;
3784                 int ret;
3785
3786                 barrier();
3787                 if (pmd_trans_huge(orig_pmd)) {
3788                         unsigned int dirty = flags & FAULT_FLAG_WRITE;
3789
3790                         /*
3791                          * If the pmd is splitting, return and retry the
3792                          * the fault.  Alternative: wait until the split
3793                          * is done, and goto retry.
3794                          */
3795                         if (pmd_trans_splitting(orig_pmd))
3796                                 return 0;
3797
3798                         if (pmd_numa(orig_pmd))
3799                                 return do_huge_pmd_numa_page(mm, vma, address,
3800                                                              orig_pmd, pmd);
3801
3802                         if (dirty && !pmd_write(orig_pmd)) {
3803                                 ret = do_huge_pmd_wp_page(mm, vma, address, pmd,
3804                                                           orig_pmd);
3805                                 /*
3806                                  * If COW results in an oom, the huge pmd will
3807                                  * have been split, so retry the fault on the
3808                                  * pte for a smaller charge.
3809                                  */
3810                                 if (unlikely(ret & VM_FAULT_OOM))
3811                                         goto retry;
3812                                 return ret;
3813                         } else {
3814                                 huge_pmd_set_accessed(mm, vma, address, pmd,
3815                                                       orig_pmd, dirty);
3816                         }
3817
3818                         return 0;
3819                 }
3820         }
3821
3822         if (pmd_numa(*pmd))
3823                 return do_pmd_numa_page(mm, vma, address, pmd);
3824
3825         /*
3826          * Use __pte_alloc instead of pte_alloc_map, because we can't
3827          * run pte_offset_map on the pmd, if an huge pmd could
3828          * materialize from under us from a different thread.
3829          */
3830         if (unlikely(pmd_none(*pmd)) &&
3831             unlikely(__pte_alloc(mm, vma, pmd, address)))
3832                 return VM_FAULT_OOM;
3833         /* if an huge pmd materialized from under us just retry later */
3834         if (unlikely(pmd_trans_huge(*pmd)))
3835                 return 0;
3836         /*
3837          * A regular pmd is established and it can't morph into a huge pmd
3838          * from under us anymore at this point because we hold the mmap_sem
3839          * read mode and khugepaged takes it in write mode. So now it's
3840          * safe to run pte_offset_map().
3841          */
3842         pte = pte_offset_map(pmd, address);
3843
3844         return handle_pte_fault(mm, vma, address, pte, pmd, flags);
3845 }
3846
3847 int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3848                     unsigned long address, unsigned int flags)
3849 {
3850         int ret;
3851
3852         __set_current_state(TASK_RUNNING);
3853
3854         count_vm_event(PGFAULT);
3855         mem_cgroup_count_vm_event(mm, PGFAULT);
3856
3857         /* do counter updates before entering really critical section. */
3858         check_sync_rss_stat(current);
3859
3860         /*
3861          * Enable the memcg OOM handling for faults triggered in user
3862          * space.  Kernel faults are handled more gracefully.
3863          */
3864         if (flags & FAULT_FLAG_USER)
3865                 mem_cgroup_oom_enable();
3866
3867         ret = __handle_mm_fault(mm, vma, address, flags);
3868
3869         if (flags & FAULT_FLAG_USER) {
3870                 mem_cgroup_oom_disable();
3871                 /*
3872                  * The task may have entered a memcg OOM situation but
3873                  * if the allocation error was handled gracefully (no
3874                  * VM_FAULT_OOM), there is no need to kill anything.
3875                  * Just clean up the OOM state peacefully.
3876                  */
3877                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
3878                         mem_cgroup_oom_synchronize(false);
3879         }
3880
3881         return ret;
3882 }
3883
3884 #ifndef __PAGETABLE_PUD_FOLDED
3885 /*
3886  * Allocate page upper directory.
3887  * We've already handled the fast-path in-line.
3888  */
3889 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
3890 {
3891         pud_t *new = pud_alloc_one(mm, address);
3892         if (!new)
3893                 return -ENOMEM;
3894
3895         smp_wmb(); /* See comment in __pte_alloc */
3896
3897         spin_lock(&mm->page_table_lock);
3898         if (pgd_present(*pgd))          /* Another has populated it */
3899                 pud_free(mm, new);
3900         else
3901                 pgd_populate(mm, pgd, new);
3902         spin_unlock(&mm->page_table_lock);
3903         return 0;
3904 }
3905 #endif /* __PAGETABLE_PUD_FOLDED */
3906
3907 #ifndef __PAGETABLE_PMD_FOLDED
3908 /*
3909  * Allocate page middle directory.
3910  * We've already handled the fast-path in-line.
3911  */
3912 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3913 {
3914         pmd_t *new = pmd_alloc_one(mm, address);
3915         if (!new)
3916                 return -ENOMEM;
3917
3918         smp_wmb(); /* See comment in __pte_alloc */
3919
3920         spin_lock(&mm->page_table_lock);
3921 #ifndef __ARCH_HAS_4LEVEL_HACK
3922         if (pud_present(*pud))          /* Another has populated it */
3923                 pmd_free(mm, new);
3924         else
3925                 pud_populate(mm, pud, new);
3926 #else
3927         if (pgd_present(*pud))          /* Another has populated it */
3928                 pmd_free(mm, new);
3929         else
3930                 pgd_populate(mm, pud, new);
3931 #endif /* __ARCH_HAS_4LEVEL_HACK */
3932         spin_unlock(&mm->page_table_lock);
3933         return 0;
3934 }
3935 #endif /* __PAGETABLE_PMD_FOLDED */
3936
3937 #if !defined(__HAVE_ARCH_GATE_AREA)
3938
3939 #if defined(AT_SYSINFO_EHDR)
3940 static struct vm_area_struct gate_vma;
3941
3942 static int __init gate_vma_init(void)
3943 {
3944         gate_vma.vm_mm = NULL;
3945         gate_vma.vm_start = FIXADDR_USER_START;
3946         gate_vma.vm_end = FIXADDR_USER_END;
3947         gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC;
3948         gate_vma.vm_page_prot = __P101;
3949
3950         return 0;
3951 }
3952 __initcall(gate_vma_init);
3953 #endif
3954
3955 struct vm_area_struct *get_gate_vma(struct mm_struct *mm)
3956 {
3957 #ifdef AT_SYSINFO_EHDR
3958         return &gate_vma;
3959 #else
3960         return NULL;
3961 #endif
3962 }
3963
3964 int in_gate_area_no_mm(unsigned long addr)
3965 {
3966 #ifdef AT_SYSINFO_EHDR
3967         if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END))
3968                 return 1;
3969 #endif
3970         return 0;
3971 }
3972
3973 #endif  /* __HAVE_ARCH_GATE_AREA */
3974
3975 static int __follow_pte(struct mm_struct *mm, unsigned long address,
3976                 pte_t **ptepp, spinlock_t **ptlp)
3977 {
3978         pgd_t *pgd;
3979         pud_t *pud;
3980         pmd_t *pmd;
3981         pte_t *ptep;
3982
3983         pgd = pgd_offset(mm, address);
3984         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3985                 goto out;
3986
3987         pud = pud_offset(pgd, address);
3988         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3989                 goto out;
3990
3991         pmd = pmd_offset(pud, address);
3992         VM_BUG_ON(pmd_trans_huge(*pmd));
3993         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
3994                 goto out;
3995
3996         /* We cannot handle huge page PFN maps. Luckily they don't exist. */
3997         if (pmd_huge(*pmd))
3998                 goto out;
3999
4000         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4001         if (!ptep)
4002                 goto out;
4003         if (!pte_present(*ptep))
4004                 goto unlock;
4005         *ptepp = ptep;
4006         return 0;
4007 unlock:
4008         pte_unmap_unlock(ptep, *ptlp);
4009 out:
4010         return -EINVAL;
4011 }
4012
4013 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4014                              pte_t **ptepp, spinlock_t **ptlp)
4015 {
4016         int res;
4017
4018         /* (void) is needed to make gcc happy */
4019         (void) __cond_lock(*ptlp,
4020                            !(res = __follow_pte(mm, address, ptepp, ptlp)));
4021         return res;
4022 }
4023
4024 /**
4025  * follow_pfn - look up PFN at a user virtual address
4026  * @vma: memory mapping
4027  * @address: user virtual address
4028  * @pfn: location to store found PFN
4029  *
4030  * Only IO mappings and raw PFN mappings are allowed.
4031  *
4032  * Returns zero and the pfn at @pfn on success, -ve otherwise.
4033  */
4034 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4035         unsigned long *pfn)
4036 {
4037         int ret = -EINVAL;
4038         spinlock_t *ptl;
4039         pte_t *ptep;
4040
4041         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4042                 return ret;
4043
4044         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4045         if (ret)
4046                 return ret;
4047         *pfn = pte_pfn(*ptep);
4048         pte_unmap_unlock(ptep, ptl);
4049         return 0;
4050 }
4051 EXPORT_SYMBOL(follow_pfn);
4052
4053 #ifdef CONFIG_HAVE_IOREMAP_PROT
4054 int follow_phys(struct vm_area_struct *vma,
4055                 unsigned long address, unsigned int flags,
4056                 unsigned long *prot, resource_size_t *phys)
4057 {
4058         int ret = -EINVAL;
4059         pte_t *ptep, pte;
4060         spinlock_t *ptl;
4061
4062         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4063                 goto out;
4064
4065         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4066                 goto out;
4067         pte = *ptep;
4068
4069         if ((flags & FOLL_WRITE) && !pte_write(pte))
4070                 goto unlock;
4071
4072         *prot = pgprot_val(pte_pgprot(pte));
4073         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4074
4075         ret = 0;
4076 unlock:
4077         pte_unmap_unlock(ptep, ptl);
4078 out:
4079         return ret;
4080 }
4081
4082 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4083                         void *buf, int len, int write)
4084 {
4085         resource_size_t phys_addr;
4086         unsigned long prot = 0;
4087         void __iomem *maddr;
4088         int offset = addr & (PAGE_SIZE-1);
4089
4090         if (follow_phys(vma, addr, write, &prot, &phys_addr))
4091                 return -EINVAL;
4092
4093         maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4094         if (write)
4095                 memcpy_toio(maddr + offset, buf, len);
4096         else
4097                 memcpy_fromio(buf, maddr + offset, len);
4098         iounmap(maddr);
4099
4100         return len;
4101 }
4102 EXPORT_SYMBOL_GPL(generic_access_phys);
4103 #endif
4104
4105 /*
4106  * Access another process' address space as given in mm.  If non-NULL, use the
4107  * given task for page fault accounting.
4108  */
4109 static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4110                 unsigned long addr, void *buf, int len, int write)
4111 {
4112         struct vm_area_struct *vma;
4113         void *old_buf = buf;
4114
4115         down_read(&mm->mmap_sem);
4116         /* ignore errors, just check how much was successfully transferred */
4117         while (len) {
4118                 int bytes, ret, offset;
4119                 void *maddr;
4120                 struct page *page = NULL;
4121
4122                 ret = get_user_pages(tsk, mm, addr, 1,
4123                                 write, 1, &page, &vma);
4124                 if (ret <= 0) {
4125                         /*
4126                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
4127                          * we can access using slightly different code.
4128                          */
4129 #ifdef CONFIG_HAVE_IOREMAP_PROT
4130                         vma = find_vma(mm, addr);
4131                         if (!vma || vma->vm_start > addr)
4132                                 break;
4133                         if (vma->vm_ops && vma->vm_ops->access)
4134                                 ret = vma->vm_ops->access(vma, addr, buf,
4135                                                           len, write);
4136                         if (ret <= 0)
4137 #endif
4138                                 break;
4139                         bytes = ret;
4140                 } else {
4141                         bytes = len;
4142                         offset = addr & (PAGE_SIZE-1);
4143                         if (bytes > PAGE_SIZE-offset)
4144                                 bytes = PAGE_SIZE-offset;
4145
4146                         maddr = kmap(page);
4147                         if (write) {
4148                                 copy_to_user_page(vma, page, addr,
4149                                                   maddr + offset, buf, bytes);
4150                                 set_page_dirty_lock(page);
4151                         } else {
4152                                 copy_from_user_page(vma, page, addr,
4153                                                     buf, maddr + offset, bytes);
4154                         }
4155                         kunmap(page);
4156                         page_cache_release(page);
4157                 }
4158                 len -= bytes;
4159                 buf += bytes;
4160                 addr += bytes;
4161         }
4162         up_read(&mm->mmap_sem);
4163
4164         return buf - old_buf;
4165 }
4166
4167 /**
4168  * access_remote_vm - access another process' address space
4169  * @mm:         the mm_struct of the target address space
4170  * @addr:       start address to access
4171  * @buf:        source or destination buffer
4172  * @len:        number of bytes to transfer
4173  * @write:      whether the access is a write
4174  *
4175  * The caller must hold a reference on @mm.
4176  */
4177 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4178                 void *buf, int len, int write)
4179 {
4180         return __access_remote_vm(NULL, mm, addr, buf, len, write);
4181 }
4182
4183 /*
4184  * Access another process' address space.
4185  * Source/target buffer must be kernel space,
4186  * Do not walk the page table directly, use get_user_pages
4187  */
4188 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4189                 void *buf, int len, int write)
4190 {
4191         struct mm_struct *mm;
4192         int ret;
4193
4194         mm = get_task_mm(tsk);
4195         if (!mm)
4196                 return 0;
4197
4198         ret = __access_remote_vm(tsk, mm, addr, buf, len, write);
4199         mmput(mm);
4200
4201         return ret;
4202 }
4203
4204 /*
4205  * Print the name of a VMA.
4206  */
4207 void print_vma_addr(char *prefix, unsigned long ip)
4208 {
4209         struct mm_struct *mm = current->mm;
4210         struct vm_area_struct *vma;
4211
4212         /*
4213          * Do not print if we are in atomic
4214          * contexts (in exception stacks, etc.):
4215          */
4216         if (preempt_count())
4217                 return;
4218
4219         down_read(&mm->mmap_sem);
4220         vma = find_vma(mm, ip);
4221         if (vma && vma->vm_file) {
4222                 struct file *f = vma->vm_file;
4223                 char *buf = (char *)__get_free_page(GFP_KERNEL);
4224                 if (buf) {
4225                         char *p;
4226
4227                         p = d_path(&f->f_path, buf, PAGE_SIZE);
4228                         if (IS_ERR(p))
4229                                 p = "?";
4230                         printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4231                                         vma->vm_start,
4232                                         vma->vm_end - vma->vm_start);
4233                         free_page((unsigned long)buf);
4234                 }
4235         }
4236         up_read(&mm->mmap_sem);
4237 }
4238
4239 #ifdef CONFIG_PROVE_LOCKING
4240 void might_fault(void)
4241 {
4242         /*
4243          * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4244          * holding the mmap_sem, this is safe because kernel memory doesn't
4245          * get paged out, therefore we'll never actually fault, and the
4246          * below annotations will generate false positives.
4247          */
4248         if (segment_eq(get_fs(), KERNEL_DS))
4249                 return;
4250
4251         might_sleep();
4252         /*
4253          * it would be nicer only to annotate paths which are not under
4254          * pagefault_disable, however that requires a larger audit and
4255          * providing helpers like get_user_atomic.
4256          */
4257         if (!in_atomic() && current->mm)
4258                 might_lock_read(&current->mm->mmap_sem);
4259 }
4260 EXPORT_SYMBOL(might_fault);
4261 #endif
4262
4263 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4264 static void clear_gigantic_page(struct page *page,
4265                                 unsigned long addr,
4266                                 unsigned int pages_per_huge_page)
4267 {
4268         int i;
4269         struct page *p = page;
4270
4271         might_sleep();
4272         for (i = 0; i < pages_per_huge_page;
4273              i++, p = mem_map_next(p, page, i)) {
4274                 cond_resched();
4275                 clear_user_highpage(p, addr + i * PAGE_SIZE);
4276         }
4277 }
4278 void clear_huge_page(struct page *page,
4279                      unsigned long addr, unsigned int pages_per_huge_page)
4280 {
4281         int i;
4282
4283         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4284                 clear_gigantic_page(page, addr, pages_per_huge_page);
4285                 return;
4286         }
4287
4288         might_sleep();
4289         for (i = 0; i < pages_per_huge_page; i++) {
4290                 cond_resched();
4291                 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4292         }
4293 }
4294
4295 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4296                                     unsigned long addr,
4297                                     struct vm_area_struct *vma,
4298                                     unsigned int pages_per_huge_page)
4299 {
4300         int i;
4301         struct page *dst_base = dst;
4302         struct page *src_base = src;
4303
4304         for (i = 0; i < pages_per_huge_page; ) {
4305                 cond_resched();
4306                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4307
4308                 i++;
4309                 dst = mem_map_next(dst, dst_base, i);
4310                 src = mem_map_next(src, src_base, i);
4311         }
4312 }
4313
4314 void copy_user_huge_page(struct page *dst, struct page *src,
4315                          unsigned long addr, struct vm_area_struct *vma,
4316                          unsigned int pages_per_huge_page)
4317 {
4318         int i;
4319
4320         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4321                 copy_user_gigantic_page(dst, src, addr, vma,
4322                                         pages_per_huge_page);
4323                 return;
4324         }
4325
4326         might_sleep();
4327         for (i = 0; i < pages_per_huge_page; i++) {
4328                 cond_resched();
4329                 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4330         }
4331 }
4332 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */