Merge branch 'hwpoison' of git://git.kernel.org/pub/scm/linux/kernel/git/ak/linux...
[safe/jmp/linux-2.6] / 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/module.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
60 #include <asm/io.h>
61 #include <asm/pgalloc.h>
62 #include <asm/uaccess.h>
63 #include <asm/tlb.h>
64 #include <asm/tlbflush.h>
65 #include <asm/pgtable.h>
66
67 #include "internal.h"
68
69 #ifndef CONFIG_NEED_MULTIPLE_NODES
70 /* use the per-pgdat data instead for discontigmem - mbligh */
71 unsigned long max_mapnr;
72 struct page *mem_map;
73
74 EXPORT_SYMBOL(max_mapnr);
75 EXPORT_SYMBOL(mem_map);
76 #endif
77
78 unsigned long num_physpages;
79 /*
80  * A number of key systems in x86 including ioremap() rely on the assumption
81  * that high_memory defines the upper bound on direct map memory, then end
82  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
83  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
84  * and ZONE_HIGHMEM.
85  */
86 void * high_memory;
87
88 EXPORT_SYMBOL(num_physpages);
89 EXPORT_SYMBOL(high_memory);
90
91 /*
92  * Randomize the address space (stacks, mmaps, brk, etc.).
93  *
94  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
95  *   as ancient (libc5 based) binaries can segfault. )
96  */
97 int randomize_va_space __read_mostly =
98 #ifdef CONFIG_COMPAT_BRK
99                                         1;
100 #else
101                                         2;
102 #endif
103
104 static int __init disable_randmaps(char *s)
105 {
106         randomize_va_space = 0;
107         return 1;
108 }
109 __setup("norandmaps", disable_randmaps);
110
111 unsigned long zero_pfn __read_mostly;
112 unsigned long highest_memmap_pfn __read_mostly;
113
114 /*
115  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
116  */
117 static int __init init_zero_pfn(void)
118 {
119         zero_pfn = page_to_pfn(ZERO_PAGE(0));
120         return 0;
121 }
122 core_initcall(init_zero_pfn);
123
124 /*
125  * If a p?d_bad entry is found while walking page tables, report
126  * the error, before resetting entry to p?d_none.  Usually (but
127  * very seldom) called out from the p?d_none_or_clear_bad macros.
128  */
129
130 void pgd_clear_bad(pgd_t *pgd)
131 {
132         pgd_ERROR(*pgd);
133         pgd_clear(pgd);
134 }
135
136 void pud_clear_bad(pud_t *pud)
137 {
138         pud_ERROR(*pud);
139         pud_clear(pud);
140 }
141
142 void pmd_clear_bad(pmd_t *pmd)
143 {
144         pmd_ERROR(*pmd);
145         pmd_clear(pmd);
146 }
147
148 /*
149  * Note: this doesn't free the actual pages themselves. That
150  * has been handled earlier when unmapping all the memory regions.
151  */
152 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
153                            unsigned long addr)
154 {
155         pgtable_t token = pmd_pgtable(*pmd);
156         pmd_clear(pmd);
157         pte_free_tlb(tlb, token, addr);
158         tlb->mm->nr_ptes--;
159 }
160
161 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
162                                 unsigned long addr, unsigned long end,
163                                 unsigned long floor, unsigned long ceiling)
164 {
165         pmd_t *pmd;
166         unsigned long next;
167         unsigned long start;
168
169         start = addr;
170         pmd = pmd_offset(pud, addr);
171         do {
172                 next = pmd_addr_end(addr, end);
173                 if (pmd_none_or_clear_bad(pmd))
174                         continue;
175                 free_pte_range(tlb, pmd, addr);
176         } while (pmd++, addr = next, addr != end);
177
178         start &= PUD_MASK;
179         if (start < floor)
180                 return;
181         if (ceiling) {
182                 ceiling &= PUD_MASK;
183                 if (!ceiling)
184                         return;
185         }
186         if (end - 1 > ceiling - 1)
187                 return;
188
189         pmd = pmd_offset(pud, start);
190         pud_clear(pud);
191         pmd_free_tlb(tlb, pmd, start);
192 }
193
194 static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
195                                 unsigned long addr, unsigned long end,
196                                 unsigned long floor, unsigned long ceiling)
197 {
198         pud_t *pud;
199         unsigned long next;
200         unsigned long start;
201
202         start = addr;
203         pud = pud_offset(pgd, addr);
204         do {
205                 next = pud_addr_end(addr, end);
206                 if (pud_none_or_clear_bad(pud))
207                         continue;
208                 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
209         } while (pud++, addr = next, addr != end);
210
211         start &= PGDIR_MASK;
212         if (start < floor)
213                 return;
214         if (ceiling) {
215                 ceiling &= PGDIR_MASK;
216                 if (!ceiling)
217                         return;
218         }
219         if (end - 1 > ceiling - 1)
220                 return;
221
222         pud = pud_offset(pgd, start);
223         pgd_clear(pgd);
224         pud_free_tlb(tlb, pud, start);
225 }
226
227 /*
228  * This function frees user-level page tables of a process.
229  *
230  * Must be called with pagetable lock held.
231  */
232 void free_pgd_range(struct mmu_gather *tlb,
233                         unsigned long addr, unsigned long end,
234                         unsigned long floor, unsigned long ceiling)
235 {
236         pgd_t *pgd;
237         unsigned long next;
238         unsigned long start;
239
240         /*
241          * The next few lines have given us lots of grief...
242          *
243          * Why are we testing PMD* at this top level?  Because often
244          * there will be no work to do at all, and we'd prefer not to
245          * go all the way down to the bottom just to discover that.
246          *
247          * Why all these "- 1"s?  Because 0 represents both the bottom
248          * of the address space and the top of it (using -1 for the
249          * top wouldn't help much: the masks would do the wrong thing).
250          * The rule is that addr 0 and floor 0 refer to the bottom of
251          * the address space, but end 0 and ceiling 0 refer to the top
252          * Comparisons need to use "end - 1" and "ceiling - 1" (though
253          * that end 0 case should be mythical).
254          *
255          * Wherever addr is brought up or ceiling brought down, we must
256          * be careful to reject "the opposite 0" before it confuses the
257          * subsequent tests.  But what about where end is brought down
258          * by PMD_SIZE below? no, end can't go down to 0 there.
259          *
260          * Whereas we round start (addr) and ceiling down, by different
261          * masks at different levels, in order to test whether a table
262          * now has no other vmas using it, so can be freed, we don't
263          * bother to round floor or end up - the tests don't need that.
264          */
265
266         addr &= PMD_MASK;
267         if (addr < floor) {
268                 addr += PMD_SIZE;
269                 if (!addr)
270                         return;
271         }
272         if (ceiling) {
273                 ceiling &= PMD_MASK;
274                 if (!ceiling)
275                         return;
276         }
277         if (end - 1 > ceiling - 1)
278                 end -= PMD_SIZE;
279         if (addr > end - 1)
280                 return;
281
282         start = addr;
283         pgd = pgd_offset(tlb->mm, addr);
284         do {
285                 next = pgd_addr_end(addr, end);
286                 if (pgd_none_or_clear_bad(pgd))
287                         continue;
288                 free_pud_range(tlb, pgd, addr, next, floor, ceiling);
289         } while (pgd++, addr = next, addr != end);
290 }
291
292 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
293                 unsigned long floor, unsigned long ceiling)
294 {
295         while (vma) {
296                 struct vm_area_struct *next = vma->vm_next;
297                 unsigned long addr = vma->vm_start;
298
299                 /*
300                  * Hide vma from rmap and vmtruncate before freeing pgtables
301                  */
302                 anon_vma_unlink(vma);
303                 unlink_file_vma(vma);
304
305                 if (is_vm_hugetlb_page(vma)) {
306                         hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
307                                 floor, next? next->vm_start: ceiling);
308                 } else {
309                         /*
310                          * Optimization: gather nearby vmas into one call down
311                          */
312                         while (next && next->vm_start <= vma->vm_end + PMD_SIZE
313                                && !is_vm_hugetlb_page(next)) {
314                                 vma = next;
315                                 next = vma->vm_next;
316                                 anon_vma_unlink(vma);
317                                 unlink_file_vma(vma);
318                         }
319                         free_pgd_range(tlb, addr, vma->vm_end,
320                                 floor, next? next->vm_start: ceiling);
321                 }
322                 vma = next;
323         }
324 }
325
326 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
327 {
328         pgtable_t new = pte_alloc_one(mm, address);
329         if (!new)
330                 return -ENOMEM;
331
332         /*
333          * Ensure all pte setup (eg. pte page lock and page clearing) are
334          * visible before the pte is made visible to other CPUs by being
335          * put into page tables.
336          *
337          * The other side of the story is the pointer chasing in the page
338          * table walking code (when walking the page table without locking;
339          * ie. most of the time). Fortunately, these data accesses consist
340          * of a chain of data-dependent loads, meaning most CPUs (alpha
341          * being the notable exception) will already guarantee loads are
342          * seen in-order. See the alpha page table accessors for the
343          * smp_read_barrier_depends() barriers in page table walking code.
344          */
345         smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
346
347         spin_lock(&mm->page_table_lock);
348         if (!pmd_present(*pmd)) {       /* Has another populated it ? */
349                 mm->nr_ptes++;
350                 pmd_populate(mm, pmd, new);
351                 new = NULL;
352         }
353         spin_unlock(&mm->page_table_lock);
354         if (new)
355                 pte_free(mm, new);
356         return 0;
357 }
358
359 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
360 {
361         pte_t *new = pte_alloc_one_kernel(&init_mm, address);
362         if (!new)
363                 return -ENOMEM;
364
365         smp_wmb(); /* See comment in __pte_alloc */
366
367         spin_lock(&init_mm.page_table_lock);
368         if (!pmd_present(*pmd)) {       /* Has another populated it ? */
369                 pmd_populate_kernel(&init_mm, pmd, new);
370                 new = NULL;
371         }
372         spin_unlock(&init_mm.page_table_lock);
373         if (new)
374                 pte_free_kernel(&init_mm, new);
375         return 0;
376 }
377
378 static inline void add_mm_rss(struct mm_struct *mm, int file_rss, int anon_rss)
379 {
380         if (file_rss)
381                 add_mm_counter(mm, file_rss, file_rss);
382         if (anon_rss)
383                 add_mm_counter(mm, anon_rss, anon_rss);
384 }
385
386 /*
387  * This function is called to print an error when a bad pte
388  * is found. For example, we might have a PFN-mapped pte in
389  * a region that doesn't allow it.
390  *
391  * The calling function must still handle the error.
392  */
393 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
394                           pte_t pte, struct page *page)
395 {
396         pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
397         pud_t *pud = pud_offset(pgd, addr);
398         pmd_t *pmd = pmd_offset(pud, addr);
399         struct address_space *mapping;
400         pgoff_t index;
401         static unsigned long resume;
402         static unsigned long nr_shown;
403         static unsigned long nr_unshown;
404
405         /*
406          * Allow a burst of 60 reports, then keep quiet for that minute;
407          * or allow a steady drip of one report per second.
408          */
409         if (nr_shown == 60) {
410                 if (time_before(jiffies, resume)) {
411                         nr_unshown++;
412                         return;
413                 }
414                 if (nr_unshown) {
415                         printk(KERN_ALERT
416                                 "BUG: Bad page map: %lu messages suppressed\n",
417                                 nr_unshown);
418                         nr_unshown = 0;
419                 }
420                 nr_shown = 0;
421         }
422         if (nr_shown++ == 0)
423                 resume = jiffies + 60 * HZ;
424
425         mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
426         index = linear_page_index(vma, addr);
427
428         printk(KERN_ALERT
429                 "BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
430                 current->comm,
431                 (long long)pte_val(pte), (long long)pmd_val(*pmd));
432         if (page) {
433                 printk(KERN_ALERT
434                 "page:%p flags:%p count:%d mapcount:%d mapping:%p index:%lx\n",
435                 page, (void *)page->flags, page_count(page),
436                 page_mapcount(page), page->mapping, page->index);
437         }
438         printk(KERN_ALERT
439                 "addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
440                 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
441         /*
442          * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
443          */
444         if (vma->vm_ops)
445                 print_symbol(KERN_ALERT "vma->vm_ops->fault: %s\n",
446                                 (unsigned long)vma->vm_ops->fault);
447         if (vma->vm_file && vma->vm_file->f_op)
448                 print_symbol(KERN_ALERT "vma->vm_file->f_op->mmap: %s\n",
449                                 (unsigned long)vma->vm_file->f_op->mmap);
450         dump_stack();
451         add_taint(TAINT_BAD_PAGE);
452 }
453
454 static inline int is_cow_mapping(unsigned int flags)
455 {
456         return (flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
457 }
458
459 #ifndef is_zero_pfn
460 static inline int is_zero_pfn(unsigned long pfn)
461 {
462         return pfn == zero_pfn;
463 }
464 #endif
465
466 #ifndef my_zero_pfn
467 static inline unsigned long my_zero_pfn(unsigned long addr)
468 {
469         return zero_pfn;
470 }
471 #endif
472
473 /*
474  * vm_normal_page -- This function gets the "struct page" associated with a pte.
475  *
476  * "Special" mappings do not wish to be associated with a "struct page" (either
477  * it doesn't exist, or it exists but they don't want to touch it). In this
478  * case, NULL is returned here. "Normal" mappings do have a struct page.
479  *
480  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
481  * pte bit, in which case this function is trivial. Secondly, an architecture
482  * may not have a spare pte bit, which requires a more complicated scheme,
483  * described below.
484  *
485  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
486  * special mapping (even if there are underlying and valid "struct pages").
487  * COWed pages of a VM_PFNMAP are always normal.
488  *
489  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
490  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
491  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
492  * mapping will always honor the rule
493  *
494  *      pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
495  *
496  * And for normal mappings this is false.
497  *
498  * This restricts such mappings to be a linear translation from virtual address
499  * to pfn. To get around this restriction, we allow arbitrary mappings so long
500  * as the vma is not a COW mapping; in that case, we know that all ptes are
501  * special (because none can have been COWed).
502  *
503  *
504  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
505  *
506  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
507  * page" backing, however the difference is that _all_ pages with a struct
508  * page (that is, those where pfn_valid is true) are refcounted and considered
509  * normal pages by the VM. The disadvantage is that pages are refcounted
510  * (which can be slower and simply not an option for some PFNMAP users). The
511  * advantage is that we don't have to follow the strict linearity rule of
512  * PFNMAP mappings in order to support COWable mappings.
513  *
514  */
515 #ifdef __HAVE_ARCH_PTE_SPECIAL
516 # define HAVE_PTE_SPECIAL 1
517 #else
518 # define HAVE_PTE_SPECIAL 0
519 #endif
520 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
521                                 pte_t pte)
522 {
523         unsigned long pfn = pte_pfn(pte);
524
525         if (HAVE_PTE_SPECIAL) {
526                 if (likely(!pte_special(pte)))
527                         goto check_pfn;
528                 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
529                         return NULL;
530                 if (!is_zero_pfn(pfn))
531                         print_bad_pte(vma, addr, pte, NULL);
532                 return NULL;
533         }
534
535         /* !HAVE_PTE_SPECIAL case follows: */
536
537         if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
538                 if (vma->vm_flags & VM_MIXEDMAP) {
539                         if (!pfn_valid(pfn))
540                                 return NULL;
541                         goto out;
542                 } else {
543                         unsigned long off;
544                         off = (addr - vma->vm_start) >> PAGE_SHIFT;
545                         if (pfn == vma->vm_pgoff + off)
546                                 return NULL;
547                         if (!is_cow_mapping(vma->vm_flags))
548                                 return NULL;
549                 }
550         }
551
552         if (is_zero_pfn(pfn))
553                 return NULL;
554 check_pfn:
555         if (unlikely(pfn > highest_memmap_pfn)) {
556                 print_bad_pte(vma, addr, pte, NULL);
557                 return NULL;
558         }
559
560         /*
561          * NOTE! We still have PageReserved() pages in the page tables.
562          * eg. VDSO mappings can cause them to exist.
563          */
564 out:
565         return pfn_to_page(pfn);
566 }
567
568 /*
569  * copy one vm_area from one task to the other. Assumes the page tables
570  * already present in the new task to be cleared in the whole range
571  * covered by this vma.
572  */
573
574 static inline void
575 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
576                 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
577                 unsigned long addr, int *rss)
578 {
579         unsigned long vm_flags = vma->vm_flags;
580         pte_t pte = *src_pte;
581         struct page *page;
582
583         /* pte contains position in swap or file, so copy. */
584         if (unlikely(!pte_present(pte))) {
585                 if (!pte_file(pte)) {
586                         swp_entry_t entry = pte_to_swp_entry(pte);
587
588                         swap_duplicate(entry);
589                         /* make sure dst_mm is on swapoff's mmlist. */
590                         if (unlikely(list_empty(&dst_mm->mmlist))) {
591                                 spin_lock(&mmlist_lock);
592                                 if (list_empty(&dst_mm->mmlist))
593                                         list_add(&dst_mm->mmlist,
594                                                  &src_mm->mmlist);
595                                 spin_unlock(&mmlist_lock);
596                         }
597                         if (is_write_migration_entry(entry) &&
598                                         is_cow_mapping(vm_flags)) {
599                                 /*
600                                  * COW mappings require pages in both parent
601                                  * and child to be set to read.
602                                  */
603                                 make_migration_entry_read(&entry);
604                                 pte = swp_entry_to_pte(entry);
605                                 set_pte_at(src_mm, addr, src_pte, pte);
606                         }
607                 }
608                 goto out_set_pte;
609         }
610
611         /*
612          * If it's a COW mapping, write protect it both
613          * in the parent and the child
614          */
615         if (is_cow_mapping(vm_flags)) {
616                 ptep_set_wrprotect(src_mm, addr, src_pte);
617                 pte = pte_wrprotect(pte);
618         }
619
620         /*
621          * If it's a shared mapping, mark it clean in
622          * the child
623          */
624         if (vm_flags & VM_SHARED)
625                 pte = pte_mkclean(pte);
626         pte = pte_mkold(pte);
627
628         page = vm_normal_page(vma, addr, pte);
629         if (page) {
630                 get_page(page);
631                 page_dup_rmap(page);
632                 rss[PageAnon(page)]++;
633         }
634
635 out_set_pte:
636         set_pte_at(dst_mm, addr, dst_pte, pte);
637 }
638
639 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
640                 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
641                 unsigned long addr, unsigned long end)
642 {
643         pte_t *src_pte, *dst_pte;
644         spinlock_t *src_ptl, *dst_ptl;
645         int progress = 0;
646         int rss[2];
647
648 again:
649         rss[1] = rss[0] = 0;
650         dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
651         if (!dst_pte)
652                 return -ENOMEM;
653         src_pte = pte_offset_map_nested(src_pmd, addr);
654         src_ptl = pte_lockptr(src_mm, src_pmd);
655         spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
656         arch_enter_lazy_mmu_mode();
657
658         do {
659                 /*
660                  * We are holding two locks at this point - either of them
661                  * could generate latencies in another task on another CPU.
662                  */
663                 if (progress >= 32) {
664                         progress = 0;
665                         if (need_resched() ||
666                             spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
667                                 break;
668                 }
669                 if (pte_none(*src_pte)) {
670                         progress++;
671                         continue;
672                 }
673                 copy_one_pte(dst_mm, src_mm, dst_pte, src_pte, vma, addr, rss);
674                 progress += 8;
675         } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
676
677         arch_leave_lazy_mmu_mode();
678         spin_unlock(src_ptl);
679         pte_unmap_nested(src_pte - 1);
680         add_mm_rss(dst_mm, rss[0], rss[1]);
681         pte_unmap_unlock(dst_pte - 1, dst_ptl);
682         cond_resched();
683         if (addr != end)
684                 goto again;
685         return 0;
686 }
687
688 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
689                 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
690                 unsigned long addr, unsigned long end)
691 {
692         pmd_t *src_pmd, *dst_pmd;
693         unsigned long next;
694
695         dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
696         if (!dst_pmd)
697                 return -ENOMEM;
698         src_pmd = pmd_offset(src_pud, addr);
699         do {
700                 next = pmd_addr_end(addr, end);
701                 if (pmd_none_or_clear_bad(src_pmd))
702                         continue;
703                 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
704                                                 vma, addr, next))
705                         return -ENOMEM;
706         } while (dst_pmd++, src_pmd++, addr = next, addr != end);
707         return 0;
708 }
709
710 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
711                 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
712                 unsigned long addr, unsigned long end)
713 {
714         pud_t *src_pud, *dst_pud;
715         unsigned long next;
716
717         dst_pud = pud_alloc(dst_mm, dst_pgd, addr);
718         if (!dst_pud)
719                 return -ENOMEM;
720         src_pud = pud_offset(src_pgd, addr);
721         do {
722                 next = pud_addr_end(addr, end);
723                 if (pud_none_or_clear_bad(src_pud))
724                         continue;
725                 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
726                                                 vma, addr, next))
727                         return -ENOMEM;
728         } while (dst_pud++, src_pud++, addr = next, addr != end);
729         return 0;
730 }
731
732 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
733                 struct vm_area_struct *vma)
734 {
735         pgd_t *src_pgd, *dst_pgd;
736         unsigned long next;
737         unsigned long addr = vma->vm_start;
738         unsigned long end = vma->vm_end;
739         int ret;
740
741         /*
742          * Don't copy ptes where a page fault will fill them correctly.
743          * Fork becomes much lighter when there are big shared or private
744          * readonly mappings. The tradeoff is that copy_page_range is more
745          * efficient than faulting.
746          */
747         if (!(vma->vm_flags & (VM_HUGETLB|VM_NONLINEAR|VM_PFNMAP|VM_INSERTPAGE))) {
748                 if (!vma->anon_vma)
749                         return 0;
750         }
751
752         if (is_vm_hugetlb_page(vma))
753                 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
754
755         if (unlikely(is_pfn_mapping(vma))) {
756                 /*
757                  * We do not free on error cases below as remove_vma
758                  * gets called on error from higher level routine
759                  */
760                 ret = track_pfn_vma_copy(vma);
761                 if (ret)
762                         return ret;
763         }
764
765         /*
766          * We need to invalidate the secondary MMU mappings only when
767          * there could be a permission downgrade on the ptes of the
768          * parent mm. And a permission downgrade will only happen if
769          * is_cow_mapping() returns true.
770          */
771         if (is_cow_mapping(vma->vm_flags))
772                 mmu_notifier_invalidate_range_start(src_mm, addr, end);
773
774         ret = 0;
775         dst_pgd = pgd_offset(dst_mm, addr);
776         src_pgd = pgd_offset(src_mm, addr);
777         do {
778                 next = pgd_addr_end(addr, end);
779                 if (pgd_none_or_clear_bad(src_pgd))
780                         continue;
781                 if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd,
782                                             vma, addr, next))) {
783                         ret = -ENOMEM;
784                         break;
785                 }
786         } while (dst_pgd++, src_pgd++, addr = next, addr != end);
787
788         if (is_cow_mapping(vma->vm_flags))
789                 mmu_notifier_invalidate_range_end(src_mm,
790                                                   vma->vm_start, end);
791         return ret;
792 }
793
794 static unsigned long zap_pte_range(struct mmu_gather *tlb,
795                                 struct vm_area_struct *vma, pmd_t *pmd,
796                                 unsigned long addr, unsigned long end,
797                                 long *zap_work, struct zap_details *details)
798 {
799         struct mm_struct *mm = tlb->mm;
800         pte_t *pte;
801         spinlock_t *ptl;
802         int file_rss = 0;
803         int anon_rss = 0;
804
805         pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
806         arch_enter_lazy_mmu_mode();
807         do {
808                 pte_t ptent = *pte;
809                 if (pte_none(ptent)) {
810                         (*zap_work)--;
811                         continue;
812                 }
813
814                 (*zap_work) -= PAGE_SIZE;
815
816                 if (pte_present(ptent)) {
817                         struct page *page;
818
819                         page = vm_normal_page(vma, addr, ptent);
820                         if (unlikely(details) && page) {
821                                 /*
822                                  * unmap_shared_mapping_pages() wants to
823                                  * invalidate cache without truncating:
824                                  * unmap shared but keep private pages.
825                                  */
826                                 if (details->check_mapping &&
827                                     details->check_mapping != page->mapping)
828                                         continue;
829                                 /*
830                                  * Each page->index must be checked when
831                                  * invalidating or truncating nonlinear.
832                                  */
833                                 if (details->nonlinear_vma &&
834                                     (page->index < details->first_index ||
835                                      page->index > details->last_index))
836                                         continue;
837                         }
838                         ptent = ptep_get_and_clear_full(mm, addr, pte,
839                                                         tlb->fullmm);
840                         tlb_remove_tlb_entry(tlb, pte, addr);
841                         if (unlikely(!page))
842                                 continue;
843                         if (unlikely(details) && details->nonlinear_vma
844                             && linear_page_index(details->nonlinear_vma,
845                                                 addr) != page->index)
846                                 set_pte_at(mm, addr, pte,
847                                            pgoff_to_pte(page->index));
848                         if (PageAnon(page))
849                                 anon_rss--;
850                         else {
851                                 if (pte_dirty(ptent))
852                                         set_page_dirty(page);
853                                 if (pte_young(ptent) &&
854                                     likely(!VM_SequentialReadHint(vma)))
855                                         mark_page_accessed(page);
856                                 file_rss--;
857                         }
858                         page_remove_rmap(page);
859                         if (unlikely(page_mapcount(page) < 0))
860                                 print_bad_pte(vma, addr, ptent, page);
861                         tlb_remove_page(tlb, page);
862                         continue;
863                 }
864                 /*
865                  * If details->check_mapping, we leave swap entries;
866                  * if details->nonlinear_vma, we leave file entries.
867                  */
868                 if (unlikely(details))
869                         continue;
870                 if (pte_file(ptent)) {
871                         if (unlikely(!(vma->vm_flags & VM_NONLINEAR)))
872                                 print_bad_pte(vma, addr, ptent, NULL);
873                 } else if
874                   (unlikely(!free_swap_and_cache(pte_to_swp_entry(ptent))))
875                         print_bad_pte(vma, addr, ptent, NULL);
876                 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
877         } while (pte++, addr += PAGE_SIZE, (addr != end && *zap_work > 0));
878
879         add_mm_rss(mm, file_rss, anon_rss);
880         arch_leave_lazy_mmu_mode();
881         pte_unmap_unlock(pte - 1, ptl);
882
883         return addr;
884 }
885
886 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
887                                 struct vm_area_struct *vma, pud_t *pud,
888                                 unsigned long addr, unsigned long end,
889                                 long *zap_work, struct zap_details *details)
890 {
891         pmd_t *pmd;
892         unsigned long next;
893
894         pmd = pmd_offset(pud, addr);
895         do {
896                 next = pmd_addr_end(addr, end);
897                 if (pmd_none_or_clear_bad(pmd)) {
898                         (*zap_work)--;
899                         continue;
900                 }
901                 next = zap_pte_range(tlb, vma, pmd, addr, next,
902                                                 zap_work, details);
903         } while (pmd++, addr = next, (addr != end && *zap_work > 0));
904
905         return addr;
906 }
907
908 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
909                                 struct vm_area_struct *vma, pgd_t *pgd,
910                                 unsigned long addr, unsigned long end,
911                                 long *zap_work, struct zap_details *details)
912 {
913         pud_t *pud;
914         unsigned long next;
915
916         pud = pud_offset(pgd, addr);
917         do {
918                 next = pud_addr_end(addr, end);
919                 if (pud_none_or_clear_bad(pud)) {
920                         (*zap_work)--;
921                         continue;
922                 }
923                 next = zap_pmd_range(tlb, vma, pud, addr, next,
924                                                 zap_work, details);
925         } while (pud++, addr = next, (addr != end && *zap_work > 0));
926
927         return addr;
928 }
929
930 static unsigned long unmap_page_range(struct mmu_gather *tlb,
931                                 struct vm_area_struct *vma,
932                                 unsigned long addr, unsigned long end,
933                                 long *zap_work, struct zap_details *details)
934 {
935         pgd_t *pgd;
936         unsigned long next;
937
938         if (details && !details->check_mapping && !details->nonlinear_vma)
939                 details = NULL;
940
941         BUG_ON(addr >= end);
942         tlb_start_vma(tlb, vma);
943         pgd = pgd_offset(vma->vm_mm, addr);
944         do {
945                 next = pgd_addr_end(addr, end);
946                 if (pgd_none_or_clear_bad(pgd)) {
947                         (*zap_work)--;
948                         continue;
949                 }
950                 next = zap_pud_range(tlb, vma, pgd, addr, next,
951                                                 zap_work, details);
952         } while (pgd++, addr = next, (addr != end && *zap_work > 0));
953         tlb_end_vma(tlb, vma);
954
955         return addr;
956 }
957
958 #ifdef CONFIG_PREEMPT
959 # define ZAP_BLOCK_SIZE (8 * PAGE_SIZE)
960 #else
961 /* No preempt: go for improved straight-line efficiency */
962 # define ZAP_BLOCK_SIZE (1024 * PAGE_SIZE)
963 #endif
964
965 /**
966  * unmap_vmas - unmap a range of memory covered by a list of vma's
967  * @tlbp: address of the caller's struct mmu_gather
968  * @vma: the starting vma
969  * @start_addr: virtual address at which to start unmapping
970  * @end_addr: virtual address at which to end unmapping
971  * @nr_accounted: Place number of unmapped pages in vm-accountable vma's here
972  * @details: details of nonlinear truncation or shared cache invalidation
973  *
974  * Returns the end address of the unmapping (restart addr if interrupted).
975  *
976  * Unmap all pages in the vma list.
977  *
978  * We aim to not hold locks for too long (for scheduling latency reasons).
979  * So zap pages in ZAP_BLOCK_SIZE bytecounts.  This means we need to
980  * return the ending mmu_gather to the caller.
981  *
982  * Only addresses between `start' and `end' will be unmapped.
983  *
984  * The VMA list must be sorted in ascending virtual address order.
985  *
986  * unmap_vmas() assumes that the caller will flush the whole unmapped address
987  * range after unmap_vmas() returns.  So the only responsibility here is to
988  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
989  * drops the lock and schedules.
990  */
991 unsigned long unmap_vmas(struct mmu_gather **tlbp,
992                 struct vm_area_struct *vma, unsigned long start_addr,
993                 unsigned long end_addr, unsigned long *nr_accounted,
994                 struct zap_details *details)
995 {
996         long zap_work = ZAP_BLOCK_SIZE;
997         unsigned long tlb_start = 0;    /* For tlb_finish_mmu */
998         int tlb_start_valid = 0;
999         unsigned long start = start_addr;
1000         spinlock_t *i_mmap_lock = details? details->i_mmap_lock: NULL;
1001         int fullmm = (*tlbp)->fullmm;
1002         struct mm_struct *mm = vma->vm_mm;
1003
1004         mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1005         for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next) {
1006                 unsigned long end;
1007
1008                 start = max(vma->vm_start, start_addr);
1009                 if (start >= vma->vm_end)
1010                         continue;
1011                 end = min(vma->vm_end, end_addr);
1012                 if (end <= vma->vm_start)
1013                         continue;
1014
1015                 if (vma->vm_flags & VM_ACCOUNT)
1016                         *nr_accounted += (end - start) >> PAGE_SHIFT;
1017
1018                 if (unlikely(is_pfn_mapping(vma)))
1019                         untrack_pfn_vma(vma, 0, 0);
1020
1021                 while (start != end) {
1022                         if (!tlb_start_valid) {
1023                                 tlb_start = start;
1024                                 tlb_start_valid = 1;
1025                         }
1026
1027                         if (unlikely(is_vm_hugetlb_page(vma))) {
1028                                 /*
1029                                  * It is undesirable to test vma->vm_file as it
1030                                  * should be non-null for valid hugetlb area.
1031                                  * However, vm_file will be NULL in the error
1032                                  * cleanup path of do_mmap_pgoff. When
1033                                  * hugetlbfs ->mmap method fails,
1034                                  * do_mmap_pgoff() nullifies vma->vm_file
1035                                  * before calling this function to clean up.
1036                                  * Since no pte has actually been setup, it is
1037                                  * safe to do nothing in this case.
1038                                  */
1039                                 if (vma->vm_file) {
1040                                         unmap_hugepage_range(vma, start, end, NULL);
1041                                         zap_work -= (end - start) /
1042                                         pages_per_huge_page(hstate_vma(vma));
1043                                 }
1044
1045                                 start = end;
1046                         } else
1047                                 start = unmap_page_range(*tlbp, vma,
1048                                                 start, end, &zap_work, details);
1049
1050                         if (zap_work > 0) {
1051                                 BUG_ON(start != end);
1052                                 break;
1053                         }
1054
1055                         tlb_finish_mmu(*tlbp, tlb_start, start);
1056
1057                         if (need_resched() ||
1058                                 (i_mmap_lock && spin_needbreak(i_mmap_lock))) {
1059                                 if (i_mmap_lock) {
1060                                         *tlbp = NULL;
1061                                         goto out;
1062                                 }
1063                                 cond_resched();
1064                         }
1065
1066                         *tlbp = tlb_gather_mmu(vma->vm_mm, fullmm);
1067                         tlb_start_valid = 0;
1068                         zap_work = ZAP_BLOCK_SIZE;
1069                 }
1070         }
1071 out:
1072         mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1073         return start;   /* which is now the end (or restart) address */
1074 }
1075
1076 /**
1077  * zap_page_range - remove user pages in a given range
1078  * @vma: vm_area_struct holding the applicable pages
1079  * @address: starting address of pages to zap
1080  * @size: number of bytes to zap
1081  * @details: details of nonlinear truncation or shared cache invalidation
1082  */
1083 unsigned long zap_page_range(struct vm_area_struct *vma, unsigned long address,
1084                 unsigned long size, struct zap_details *details)
1085 {
1086         struct mm_struct *mm = vma->vm_mm;
1087         struct mmu_gather *tlb;
1088         unsigned long end = address + size;
1089         unsigned long nr_accounted = 0;
1090
1091         lru_add_drain();
1092         tlb = tlb_gather_mmu(mm, 0);
1093         update_hiwater_rss(mm);
1094         end = unmap_vmas(&tlb, vma, address, end, &nr_accounted, details);
1095         if (tlb)
1096                 tlb_finish_mmu(tlb, address, end);
1097         return end;
1098 }
1099
1100 /**
1101  * zap_vma_ptes - remove ptes mapping the vma
1102  * @vma: vm_area_struct holding ptes to be zapped
1103  * @address: starting address of pages to zap
1104  * @size: number of bytes to zap
1105  *
1106  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1107  *
1108  * The entire address range must be fully contained within the vma.
1109  *
1110  * Returns 0 if successful.
1111  */
1112 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1113                 unsigned long size)
1114 {
1115         if (address < vma->vm_start || address + size > vma->vm_end ||
1116                         !(vma->vm_flags & VM_PFNMAP))
1117                 return -1;
1118         zap_page_range(vma, address, size, NULL);
1119         return 0;
1120 }
1121 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1122
1123 /*
1124  * Do a quick page-table lookup for a single page.
1125  */
1126 struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
1127                         unsigned int flags)
1128 {
1129         pgd_t *pgd;
1130         pud_t *pud;
1131         pmd_t *pmd;
1132         pte_t *ptep, pte;
1133         spinlock_t *ptl;
1134         struct page *page;
1135         struct mm_struct *mm = vma->vm_mm;
1136
1137         page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
1138         if (!IS_ERR(page)) {
1139                 BUG_ON(flags & FOLL_GET);
1140                 goto out;
1141         }
1142
1143         page = NULL;
1144         pgd = pgd_offset(mm, address);
1145         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
1146                 goto no_page_table;
1147
1148         pud = pud_offset(pgd, address);
1149         if (pud_none(*pud))
1150                 goto no_page_table;
1151         if (pud_huge(*pud)) {
1152                 BUG_ON(flags & FOLL_GET);
1153                 page = follow_huge_pud(mm, address, pud, flags & FOLL_WRITE);
1154                 goto out;
1155         }
1156         if (unlikely(pud_bad(*pud)))
1157                 goto no_page_table;
1158
1159         pmd = pmd_offset(pud, address);
1160         if (pmd_none(*pmd))
1161                 goto no_page_table;
1162         if (pmd_huge(*pmd)) {
1163                 BUG_ON(flags & FOLL_GET);
1164                 page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE);
1165                 goto out;
1166         }
1167         if (unlikely(pmd_bad(*pmd)))
1168                 goto no_page_table;
1169
1170         ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
1171
1172         pte = *ptep;
1173         if (!pte_present(pte))
1174                 goto no_page;
1175         if ((flags & FOLL_WRITE) && !pte_write(pte))
1176                 goto unlock;
1177
1178         page = vm_normal_page(vma, address, pte);
1179         if (unlikely(!page)) {
1180                 if ((flags & FOLL_DUMP) ||
1181                     !is_zero_pfn(pte_pfn(pte)))
1182                         goto bad_page;
1183                 page = pte_page(pte);
1184         }
1185
1186         if (flags & FOLL_GET)
1187                 get_page(page);
1188         if (flags & FOLL_TOUCH) {
1189                 if ((flags & FOLL_WRITE) &&
1190                     !pte_dirty(pte) && !PageDirty(page))
1191                         set_page_dirty(page);
1192                 /*
1193                  * pte_mkyoung() would be more correct here, but atomic care
1194                  * is needed to avoid losing the dirty bit: it is easier to use
1195                  * mark_page_accessed().
1196                  */
1197                 mark_page_accessed(page);
1198         }
1199 unlock:
1200         pte_unmap_unlock(ptep, ptl);
1201 out:
1202         return page;
1203
1204 bad_page:
1205         pte_unmap_unlock(ptep, ptl);
1206         return ERR_PTR(-EFAULT);
1207
1208 no_page:
1209         pte_unmap_unlock(ptep, ptl);
1210         if (!pte_none(pte))
1211                 return page;
1212
1213 no_page_table:
1214         /*
1215          * When core dumping an enormous anonymous area that nobody
1216          * has touched so far, we don't want to allocate unnecessary pages or
1217          * page tables.  Return error instead of NULL to skip handle_mm_fault,
1218          * then get_dump_page() will return NULL to leave a hole in the dump.
1219          * But we can only make this optimization where a hole would surely
1220          * be zero-filled if handle_mm_fault() actually did handle it.
1221          */
1222         if ((flags & FOLL_DUMP) &&
1223             (!vma->vm_ops || !vma->vm_ops->fault))
1224                 return ERR_PTR(-EFAULT);
1225         return page;
1226 }
1227
1228 int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
1229                      unsigned long start, int nr_pages, unsigned int gup_flags,
1230                      struct page **pages, struct vm_area_struct **vmas)
1231 {
1232         int i;
1233         unsigned long vm_flags;
1234
1235         if (nr_pages <= 0)
1236                 return 0;
1237
1238         VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
1239
1240         /* 
1241          * Require read or write permissions.
1242          * If FOLL_FORCE is set, we only require the "MAY" flags.
1243          */
1244         vm_flags  = (gup_flags & FOLL_WRITE) ?
1245                         (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1246         vm_flags &= (gup_flags & FOLL_FORCE) ?
1247                         (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1248         i = 0;
1249
1250         do {
1251                 struct vm_area_struct *vma;
1252
1253                 vma = find_extend_vma(mm, start);
1254                 if (!vma && in_gate_area(tsk, start)) {
1255                         unsigned long pg = start & PAGE_MASK;
1256                         struct vm_area_struct *gate_vma = get_gate_vma(tsk);
1257                         pgd_t *pgd;
1258                         pud_t *pud;
1259                         pmd_t *pmd;
1260                         pte_t *pte;
1261
1262                         /* user gate pages are read-only */
1263                         if (gup_flags & FOLL_WRITE)
1264                                 return i ? : -EFAULT;
1265                         if (pg > TASK_SIZE)
1266                                 pgd = pgd_offset_k(pg);
1267                         else
1268                                 pgd = pgd_offset_gate(mm, pg);
1269                         BUG_ON(pgd_none(*pgd));
1270                         pud = pud_offset(pgd, pg);
1271                         BUG_ON(pud_none(*pud));
1272                         pmd = pmd_offset(pud, pg);
1273                         if (pmd_none(*pmd))
1274                                 return i ? : -EFAULT;
1275                         pte = pte_offset_map(pmd, pg);
1276                         if (pte_none(*pte)) {
1277                                 pte_unmap(pte);
1278                                 return i ? : -EFAULT;
1279                         }
1280                         if (pages) {
1281                                 struct page *page = vm_normal_page(gate_vma, start, *pte);
1282                                 pages[i] = page;
1283                                 if (page)
1284                                         get_page(page);
1285                         }
1286                         pte_unmap(pte);
1287                         if (vmas)
1288                                 vmas[i] = gate_vma;
1289                         i++;
1290                         start += PAGE_SIZE;
1291                         nr_pages--;
1292                         continue;
1293                 }
1294
1295                 if (!vma ||
1296                     (vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1297                     !(vm_flags & vma->vm_flags))
1298                         return i ? : -EFAULT;
1299
1300                 if (is_vm_hugetlb_page(vma)) {
1301                         i = follow_hugetlb_page(mm, vma, pages, vmas,
1302                                         &start, &nr_pages, i, gup_flags);
1303                         continue;
1304                 }
1305
1306                 do {
1307                         struct page *page;
1308                         unsigned int foll_flags = gup_flags;
1309
1310                         /*
1311                          * If we have a pending SIGKILL, don't keep faulting
1312                          * pages and potentially allocating memory.
1313                          */
1314                         if (unlikely(fatal_signal_pending(current)))
1315                                 return i ? i : -ERESTARTSYS;
1316
1317                         cond_resched();
1318                         while (!(page = follow_page(vma, start, foll_flags))) {
1319                                 int ret;
1320
1321                                 ret = handle_mm_fault(mm, vma, start,
1322                                         (foll_flags & FOLL_WRITE) ?
1323                                         FAULT_FLAG_WRITE : 0);
1324
1325                                 if (ret & VM_FAULT_ERROR) {
1326                                         if (ret & VM_FAULT_OOM)
1327                                                 return i ? i : -ENOMEM;
1328                                         if (ret &
1329                                             (VM_FAULT_HWPOISON|VM_FAULT_SIGBUS))
1330                                                 return i ? i : -EFAULT;
1331                                         BUG();
1332                                 }
1333                                 if (ret & VM_FAULT_MAJOR)
1334                                         tsk->maj_flt++;
1335                                 else
1336                                         tsk->min_flt++;
1337
1338                                 /*
1339                                  * The VM_FAULT_WRITE bit tells us that
1340                                  * do_wp_page has broken COW when necessary,
1341                                  * even if maybe_mkwrite decided not to set
1342                                  * pte_write. We can thus safely do subsequent
1343                                  * page lookups as if they were reads. But only
1344                                  * do so when looping for pte_write is futile:
1345                                  * in some cases userspace may also be wanting
1346                                  * to write to the gotten user page, which a
1347                                  * read fault here might prevent (a readonly
1348                                  * page might get reCOWed by userspace write).
1349                                  */
1350                                 if ((ret & VM_FAULT_WRITE) &&
1351                                     !(vma->vm_flags & VM_WRITE))
1352                                         foll_flags &= ~FOLL_WRITE;
1353
1354                                 cond_resched();
1355                         }
1356                         if (IS_ERR(page))
1357                                 return i ? i : PTR_ERR(page);
1358                         if (pages) {
1359                                 pages[i] = page;
1360
1361                                 flush_anon_page(vma, page, start);
1362                                 flush_dcache_page(page);
1363                         }
1364                         if (vmas)
1365                                 vmas[i] = vma;
1366                         i++;
1367                         start += PAGE_SIZE;
1368                         nr_pages--;
1369                 } while (nr_pages && start < vma->vm_end);
1370         } while (nr_pages);
1371         return i;
1372 }
1373
1374 /**
1375  * get_user_pages() - pin user pages in memory
1376  * @tsk:        task_struct of target task
1377  * @mm:         mm_struct of target mm
1378  * @start:      starting user address
1379  * @nr_pages:   number of pages from start to pin
1380  * @write:      whether pages will be written to by the caller
1381  * @force:      whether to force write access even if user mapping is
1382  *              readonly. This will result in the page being COWed even
1383  *              in MAP_SHARED mappings. You do not want this.
1384  * @pages:      array that receives pointers to the pages pinned.
1385  *              Should be at least nr_pages long. Or NULL, if caller
1386  *              only intends to ensure the pages are faulted in.
1387  * @vmas:       array of pointers to vmas corresponding to each page.
1388  *              Or NULL if the caller does not require them.
1389  *
1390  * Returns number of pages pinned. This may be fewer than the number
1391  * requested. If nr_pages is 0 or negative, returns 0. If no pages
1392  * were pinned, returns -errno. Each page returned must be released
1393  * with a put_page() call when it is finished with. vmas will only
1394  * remain valid while mmap_sem is held.
1395  *
1396  * Must be called with mmap_sem held for read or write.
1397  *
1398  * get_user_pages walks a process's page tables and takes a reference to
1399  * each struct page that each user address corresponds to at a given
1400  * instant. That is, it takes the page that would be accessed if a user
1401  * thread accesses the given user virtual address at that instant.
1402  *
1403  * This does not guarantee that the page exists in the user mappings when
1404  * get_user_pages returns, and there may even be a completely different
1405  * page there in some cases (eg. if mmapped pagecache has been invalidated
1406  * and subsequently re faulted). However it does guarantee that the page
1407  * won't be freed completely. And mostly callers simply care that the page
1408  * contains data that was valid *at some point in time*. Typically, an IO
1409  * or similar operation cannot guarantee anything stronger anyway because
1410  * locks can't be held over the syscall boundary.
1411  *
1412  * If write=0, the page must not be written to. If the page is written to,
1413  * set_page_dirty (or set_page_dirty_lock, as appropriate) must be called
1414  * after the page is finished with, and before put_page is called.
1415  *
1416  * get_user_pages is typically used for fewer-copy IO operations, to get a
1417  * handle on the memory by some means other than accesses via the user virtual
1418  * addresses. The pages may be submitted for DMA to devices or accessed via
1419  * their kernel linear mapping (via the kmap APIs). Care should be taken to
1420  * use the correct cache flushing APIs.
1421  *
1422  * See also get_user_pages_fast, for performance critical applications.
1423  */
1424 int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
1425                 unsigned long start, int nr_pages, int write, int force,
1426                 struct page **pages, struct vm_area_struct **vmas)
1427 {
1428         int flags = FOLL_TOUCH;
1429
1430         if (pages)
1431                 flags |= FOLL_GET;
1432         if (write)
1433                 flags |= FOLL_WRITE;
1434         if (force)
1435                 flags |= FOLL_FORCE;
1436
1437         return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas);
1438 }
1439 EXPORT_SYMBOL(get_user_pages);
1440
1441 /**
1442  * get_dump_page() - pin user page in memory while writing it to core dump
1443  * @addr: user address
1444  *
1445  * Returns struct page pointer of user page pinned for dump,
1446  * to be freed afterwards by page_cache_release() or put_page().
1447  *
1448  * Returns NULL on any kind of failure - a hole must then be inserted into
1449  * the corefile, to preserve alignment with its headers; and also returns
1450  * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
1451  * allowing a hole to be left in the corefile to save diskspace.
1452  *
1453  * Called without mmap_sem, but after all other threads have been killed.
1454  */
1455 #ifdef CONFIG_ELF_CORE
1456 struct page *get_dump_page(unsigned long addr)
1457 {
1458         struct vm_area_struct *vma;
1459         struct page *page;
1460
1461         if (__get_user_pages(current, current->mm, addr, 1,
1462                         FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma) < 1)
1463                 return NULL;
1464         flush_cache_page(vma, addr, page_to_pfn(page));
1465         return page;
1466 }
1467 #endif /* CONFIG_ELF_CORE */
1468
1469 pte_t *get_locked_pte(struct mm_struct *mm, unsigned long addr,
1470                         spinlock_t **ptl)
1471 {
1472         pgd_t * pgd = pgd_offset(mm, addr);
1473         pud_t * pud = pud_alloc(mm, pgd, addr);
1474         if (pud) {
1475                 pmd_t * pmd = pmd_alloc(mm, pud, addr);
1476                 if (pmd)
1477                         return pte_alloc_map_lock(mm, pmd, addr, ptl);
1478         }
1479         return NULL;
1480 }
1481
1482 /*
1483  * This is the old fallback for page remapping.
1484  *
1485  * For historical reasons, it only allows reserved pages. Only
1486  * old drivers should use this, and they needed to mark their
1487  * pages reserved for the old functions anyway.
1488  */
1489 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1490                         struct page *page, pgprot_t prot)
1491 {
1492         struct mm_struct *mm = vma->vm_mm;
1493         int retval;
1494         pte_t *pte;
1495         spinlock_t *ptl;
1496
1497         retval = -EINVAL;
1498         if (PageAnon(page))
1499                 goto out;
1500         retval = -ENOMEM;
1501         flush_dcache_page(page);
1502         pte = get_locked_pte(mm, addr, &ptl);
1503         if (!pte)
1504                 goto out;
1505         retval = -EBUSY;
1506         if (!pte_none(*pte))
1507                 goto out_unlock;
1508
1509         /* Ok, finally just insert the thing.. */
1510         get_page(page);
1511         inc_mm_counter(mm, file_rss);
1512         page_add_file_rmap(page);
1513         set_pte_at(mm, addr, pte, mk_pte(page, prot));
1514
1515         retval = 0;
1516         pte_unmap_unlock(pte, ptl);
1517         return retval;
1518 out_unlock:
1519         pte_unmap_unlock(pte, ptl);
1520 out:
1521         return retval;
1522 }
1523
1524 /**
1525  * vm_insert_page - insert single page into user vma
1526  * @vma: user vma to map to
1527  * @addr: target user address of this page
1528  * @page: source kernel page
1529  *
1530  * This allows drivers to insert individual pages they've allocated
1531  * into a user vma.
1532  *
1533  * The page has to be a nice clean _individual_ kernel allocation.
1534  * If you allocate a compound page, you need to have marked it as
1535  * such (__GFP_COMP), or manually just split the page up yourself
1536  * (see split_page()).
1537  *
1538  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1539  * took an arbitrary page protection parameter. This doesn't allow
1540  * that. Your vma protection will have to be set up correctly, which
1541  * means that if you want a shared writable mapping, you'd better
1542  * ask for a shared writable mapping!
1543  *
1544  * The page does not need to be reserved.
1545  */
1546 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1547                         struct page *page)
1548 {
1549         if (addr < vma->vm_start || addr >= vma->vm_end)
1550                 return -EFAULT;
1551         if (!page_count(page))
1552                 return -EINVAL;
1553         vma->vm_flags |= VM_INSERTPAGE;
1554         return insert_page(vma, addr, page, vma->vm_page_prot);
1555 }
1556 EXPORT_SYMBOL(vm_insert_page);
1557
1558 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1559                         unsigned long pfn, pgprot_t prot)
1560 {
1561         struct mm_struct *mm = vma->vm_mm;
1562         int retval;
1563         pte_t *pte, entry;
1564         spinlock_t *ptl;
1565
1566         retval = -ENOMEM;
1567         pte = get_locked_pte(mm, addr, &ptl);
1568         if (!pte)
1569                 goto out;
1570         retval = -EBUSY;
1571         if (!pte_none(*pte))
1572                 goto out_unlock;
1573
1574         /* Ok, finally just insert the thing.. */
1575         entry = pte_mkspecial(pfn_pte(pfn, prot));
1576         set_pte_at(mm, addr, pte, entry);
1577         update_mmu_cache(vma, addr, entry); /* XXX: why not for insert_page? */
1578
1579         retval = 0;
1580 out_unlock:
1581         pte_unmap_unlock(pte, ptl);
1582 out:
1583         return retval;
1584 }
1585
1586 /**
1587  * vm_insert_pfn - insert single pfn into user vma
1588  * @vma: user vma to map to
1589  * @addr: target user address of this page
1590  * @pfn: source kernel pfn
1591  *
1592  * Similar to vm_inert_page, this allows drivers to insert individual pages
1593  * they've allocated into a user vma. Same comments apply.
1594  *
1595  * This function should only be called from a vm_ops->fault handler, and
1596  * in that case the handler should return NULL.
1597  *
1598  * vma cannot be a COW mapping.
1599  *
1600  * As this is called only for pages that do not currently exist, we
1601  * do not need to flush old virtual caches or the TLB.
1602  */
1603 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1604                         unsigned long pfn)
1605 {
1606         int ret;
1607         pgprot_t pgprot = vma->vm_page_prot;
1608         /*
1609          * Technically, architectures with pte_special can avoid all these
1610          * restrictions (same for remap_pfn_range).  However we would like
1611          * consistency in testing and feature parity among all, so we should
1612          * try to keep these invariants in place for everybody.
1613          */
1614         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1615         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1616                                                 (VM_PFNMAP|VM_MIXEDMAP));
1617         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1618         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1619
1620         if (addr < vma->vm_start || addr >= vma->vm_end)
1621                 return -EFAULT;
1622         if (track_pfn_vma_new(vma, &pgprot, pfn, PAGE_SIZE))
1623                 return -EINVAL;
1624
1625         ret = insert_pfn(vma, addr, pfn, pgprot);
1626
1627         if (ret)
1628                 untrack_pfn_vma(vma, pfn, PAGE_SIZE);
1629
1630         return ret;
1631 }
1632 EXPORT_SYMBOL(vm_insert_pfn);
1633
1634 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1635                         unsigned long pfn)
1636 {
1637         BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1638
1639         if (addr < vma->vm_start || addr >= vma->vm_end)
1640                 return -EFAULT;
1641
1642         /*
1643          * If we don't have pte special, then we have to use the pfn_valid()
1644          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1645          * refcount the page if pfn_valid is true (hence insert_page rather
1646          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
1647          * without pte special, it would there be refcounted as a normal page.
1648          */
1649         if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) {
1650                 struct page *page;
1651
1652                 page = pfn_to_page(pfn);
1653                 return insert_page(vma, addr, page, vma->vm_page_prot);
1654         }
1655         return insert_pfn(vma, addr, pfn, vma->vm_page_prot);
1656 }
1657 EXPORT_SYMBOL(vm_insert_mixed);
1658
1659 /*
1660  * maps a range of physical memory into the requested pages. the old
1661  * mappings are removed. any references to nonexistent pages results
1662  * in null mappings (currently treated as "copy-on-access")
1663  */
1664 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1665                         unsigned long addr, unsigned long end,
1666                         unsigned long pfn, pgprot_t prot)
1667 {
1668         pte_t *pte;
1669         spinlock_t *ptl;
1670
1671         pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
1672         if (!pte)
1673                 return -ENOMEM;
1674         arch_enter_lazy_mmu_mode();
1675         do {
1676                 BUG_ON(!pte_none(*pte));
1677                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
1678                 pfn++;
1679         } while (pte++, addr += PAGE_SIZE, addr != end);
1680         arch_leave_lazy_mmu_mode();
1681         pte_unmap_unlock(pte - 1, ptl);
1682         return 0;
1683 }
1684
1685 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
1686                         unsigned long addr, unsigned long end,
1687                         unsigned long pfn, pgprot_t prot)
1688 {
1689         pmd_t *pmd;
1690         unsigned long next;
1691
1692         pfn -= addr >> PAGE_SHIFT;
1693         pmd = pmd_alloc(mm, pud, addr);
1694         if (!pmd)
1695                 return -ENOMEM;
1696         do {
1697                 next = pmd_addr_end(addr, end);
1698                 if (remap_pte_range(mm, pmd, addr, next,
1699                                 pfn + (addr >> PAGE_SHIFT), prot))
1700                         return -ENOMEM;
1701         } while (pmd++, addr = next, addr != end);
1702         return 0;
1703 }
1704
1705 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
1706                         unsigned long addr, unsigned long end,
1707                         unsigned long pfn, pgprot_t prot)
1708 {
1709         pud_t *pud;
1710         unsigned long next;
1711
1712         pfn -= addr >> PAGE_SHIFT;
1713         pud = pud_alloc(mm, pgd, addr);
1714         if (!pud)
1715                 return -ENOMEM;
1716         do {
1717                 next = pud_addr_end(addr, end);
1718                 if (remap_pmd_range(mm, pud, addr, next,
1719                                 pfn + (addr >> PAGE_SHIFT), prot))
1720                         return -ENOMEM;
1721         } while (pud++, addr = next, addr != end);
1722         return 0;
1723 }
1724
1725 /**
1726  * remap_pfn_range - remap kernel memory to userspace
1727  * @vma: user vma to map to
1728  * @addr: target user address to start at
1729  * @pfn: physical address of kernel memory
1730  * @size: size of map area
1731  * @prot: page protection flags for this mapping
1732  *
1733  *  Note: this is only safe if the mm semaphore is held when called.
1734  */
1735 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
1736                     unsigned long pfn, unsigned long size, pgprot_t prot)
1737 {
1738         pgd_t *pgd;
1739         unsigned long next;
1740         unsigned long end = addr + PAGE_ALIGN(size);
1741         struct mm_struct *mm = vma->vm_mm;
1742         int err;
1743
1744         /*
1745          * Physically remapped pages are special. Tell the
1746          * rest of the world about it:
1747          *   VM_IO tells people not to look at these pages
1748          *      (accesses can have side effects).
1749          *   VM_RESERVED is specified all over the place, because
1750          *      in 2.4 it kept swapout's vma scan off this vma; but
1751          *      in 2.6 the LRU scan won't even find its pages, so this
1752          *      flag means no more than count its pages in reserved_vm,
1753          *      and omit it from core dump, even when VM_IO turned off.
1754          *   VM_PFNMAP tells the core MM that the base pages are just
1755          *      raw PFN mappings, and do not have a "struct page" associated
1756          *      with them.
1757          *
1758          * There's a horrible special case to handle copy-on-write
1759          * behaviour that some programs depend on. We mark the "original"
1760          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
1761          */
1762         if (addr == vma->vm_start && end == vma->vm_end) {
1763                 vma->vm_pgoff = pfn;
1764                 vma->vm_flags |= VM_PFN_AT_MMAP;
1765         } else if (is_cow_mapping(vma->vm_flags))
1766                 return -EINVAL;
1767
1768         vma->vm_flags |= VM_IO | VM_RESERVED | VM_PFNMAP;
1769
1770         err = track_pfn_vma_new(vma, &prot, pfn, PAGE_ALIGN(size));
1771         if (err) {
1772                 /*
1773                  * To indicate that track_pfn related cleanup is not
1774                  * needed from higher level routine calling unmap_vmas
1775                  */
1776                 vma->vm_flags &= ~(VM_IO | VM_RESERVED | VM_PFNMAP);
1777                 vma->vm_flags &= ~VM_PFN_AT_MMAP;
1778                 return -EINVAL;
1779         }
1780
1781         BUG_ON(addr >= end);
1782         pfn -= addr >> PAGE_SHIFT;
1783         pgd = pgd_offset(mm, addr);
1784         flush_cache_range(vma, addr, end);
1785         do {
1786                 next = pgd_addr_end(addr, end);
1787                 err = remap_pud_range(mm, pgd, addr, next,
1788                                 pfn + (addr >> PAGE_SHIFT), prot);
1789                 if (err)
1790                         break;
1791         } while (pgd++, addr = next, addr != end);
1792
1793         if (err)
1794                 untrack_pfn_vma(vma, pfn, PAGE_ALIGN(size));
1795
1796         return err;
1797 }
1798 EXPORT_SYMBOL(remap_pfn_range);
1799
1800 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
1801                                      unsigned long addr, unsigned long end,
1802                                      pte_fn_t fn, void *data)
1803 {
1804         pte_t *pte;
1805         int err;
1806         pgtable_t token;
1807         spinlock_t *uninitialized_var(ptl);
1808
1809         pte = (mm == &init_mm) ?
1810                 pte_alloc_kernel(pmd, addr) :
1811                 pte_alloc_map_lock(mm, pmd, addr, &ptl);
1812         if (!pte)
1813                 return -ENOMEM;
1814
1815         BUG_ON(pmd_huge(*pmd));
1816
1817         arch_enter_lazy_mmu_mode();
1818
1819         token = pmd_pgtable(*pmd);
1820
1821         do {
1822                 err = fn(pte, token, addr, data);
1823                 if (err)
1824                         break;
1825         } while (pte++, addr += PAGE_SIZE, addr != end);
1826
1827         arch_leave_lazy_mmu_mode();
1828
1829         if (mm != &init_mm)
1830                 pte_unmap_unlock(pte-1, ptl);
1831         return err;
1832 }
1833
1834 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
1835                                      unsigned long addr, unsigned long end,
1836                                      pte_fn_t fn, void *data)
1837 {
1838         pmd_t *pmd;
1839         unsigned long next;
1840         int err;
1841
1842         BUG_ON(pud_huge(*pud));
1843
1844         pmd = pmd_alloc(mm, pud, addr);
1845         if (!pmd)
1846                 return -ENOMEM;
1847         do {
1848                 next = pmd_addr_end(addr, end);
1849                 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
1850                 if (err)
1851                         break;
1852         } while (pmd++, addr = next, addr != end);
1853         return err;
1854 }
1855
1856 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
1857                                      unsigned long addr, unsigned long end,
1858                                      pte_fn_t fn, void *data)
1859 {
1860         pud_t *pud;
1861         unsigned long next;
1862         int err;
1863
1864         pud = pud_alloc(mm, pgd, addr);
1865         if (!pud)
1866                 return -ENOMEM;
1867         do {
1868                 next = pud_addr_end(addr, end);
1869                 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
1870                 if (err)
1871                         break;
1872         } while (pud++, addr = next, addr != end);
1873         return err;
1874 }
1875
1876 /*
1877  * Scan a region of virtual memory, filling in page tables as necessary
1878  * and calling a provided function on each leaf page table.
1879  */
1880 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
1881                         unsigned long size, pte_fn_t fn, void *data)
1882 {
1883         pgd_t *pgd;
1884         unsigned long next;
1885         unsigned long start = addr, end = addr + size;
1886         int err;
1887
1888         BUG_ON(addr >= end);
1889         mmu_notifier_invalidate_range_start(mm, start, end);
1890         pgd = pgd_offset(mm, addr);
1891         do {
1892                 next = pgd_addr_end(addr, end);
1893                 err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
1894                 if (err)
1895                         break;
1896         } while (pgd++, addr = next, addr != end);
1897         mmu_notifier_invalidate_range_end(mm, start, end);
1898         return err;
1899 }
1900 EXPORT_SYMBOL_GPL(apply_to_page_range);
1901
1902 /*
1903  * handle_pte_fault chooses page fault handler according to an entry
1904  * which was read non-atomically.  Before making any commitment, on
1905  * those architectures or configurations (e.g. i386 with PAE) which
1906  * might give a mix of unmatched parts, do_swap_page and do_file_page
1907  * must check under lock before unmapping the pte and proceeding
1908  * (but do_wp_page is only called after already making such a check;
1909  * and do_anonymous_page and do_no_page can safely check later on).
1910  */
1911 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
1912                                 pte_t *page_table, pte_t orig_pte)
1913 {
1914         int same = 1;
1915 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
1916         if (sizeof(pte_t) > sizeof(unsigned long)) {
1917                 spinlock_t *ptl = pte_lockptr(mm, pmd);
1918                 spin_lock(ptl);
1919                 same = pte_same(*page_table, orig_pte);
1920                 spin_unlock(ptl);
1921         }
1922 #endif
1923         pte_unmap(page_table);
1924         return same;
1925 }
1926
1927 /*
1928  * Do pte_mkwrite, but only if the vma says VM_WRITE.  We do this when
1929  * servicing faults for write access.  In the normal case, do always want
1930  * pte_mkwrite.  But get_user_pages can cause write faults for mappings
1931  * that do not have writing enabled, when used by access_process_vm.
1932  */
1933 static inline pte_t maybe_mkwrite(pte_t pte, struct vm_area_struct *vma)
1934 {
1935         if (likely(vma->vm_flags & VM_WRITE))
1936                 pte = pte_mkwrite(pte);
1937         return pte;
1938 }
1939
1940 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
1941 {
1942         /*
1943          * If the source page was a PFN mapping, we don't have
1944          * a "struct page" for it. We do a best-effort copy by
1945          * just copying from the original user address. If that
1946          * fails, we just zero-fill it. Live with it.
1947          */
1948         if (unlikely(!src)) {
1949                 void *kaddr = kmap_atomic(dst, KM_USER0);
1950                 void __user *uaddr = (void __user *)(va & PAGE_MASK);
1951
1952                 /*
1953                  * This really shouldn't fail, because the page is there
1954                  * in the page tables. But it might just be unreadable,
1955                  * in which case we just give up and fill the result with
1956                  * zeroes.
1957                  */
1958                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
1959                         memset(kaddr, 0, PAGE_SIZE);
1960                 kunmap_atomic(kaddr, KM_USER0);
1961                 flush_dcache_page(dst);
1962         } else
1963                 copy_user_highpage(dst, src, va, vma);
1964 }
1965
1966 /*
1967  * This routine handles present pages, when users try to write
1968  * to a shared page. It is done by copying the page to a new address
1969  * and decrementing the shared-page counter for the old page.
1970  *
1971  * Note that this routine assumes that the protection checks have been
1972  * done by the caller (the low-level page fault routine in most cases).
1973  * Thus we can safely just mark it writable once we've done any necessary
1974  * COW.
1975  *
1976  * We also mark the page dirty at this point even though the page will
1977  * change only once the write actually happens. This avoids a few races,
1978  * and potentially makes it more efficient.
1979  *
1980  * We enter with non-exclusive mmap_sem (to exclude vma changes,
1981  * but allow concurrent faults), with pte both mapped and locked.
1982  * We return with mmap_sem still held, but pte unmapped and unlocked.
1983  */
1984 static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
1985                 unsigned long address, pte_t *page_table, pmd_t *pmd,
1986                 spinlock_t *ptl, pte_t orig_pte)
1987 {
1988         struct page *old_page, *new_page;
1989         pte_t entry;
1990         int reuse = 0, ret = 0;
1991         int page_mkwrite = 0;
1992         struct page *dirty_page = NULL;
1993
1994         old_page = vm_normal_page(vma, address, orig_pte);
1995         if (!old_page) {
1996                 /*
1997                  * VM_MIXEDMAP !pfn_valid() case
1998                  *
1999                  * We should not cow pages in a shared writeable mapping.
2000                  * Just mark the pages writable as we can't do any dirty
2001                  * accounting on raw pfn maps.
2002                  */
2003                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2004                                      (VM_WRITE|VM_SHARED))
2005                         goto reuse;
2006                 goto gotten;
2007         }
2008
2009         /*
2010          * Take out anonymous pages first, anonymous shared vmas are
2011          * not dirty accountable.
2012          */
2013         if (PageAnon(old_page) && !PageKsm(old_page)) {
2014                 if (!trylock_page(old_page)) {
2015                         page_cache_get(old_page);
2016                         pte_unmap_unlock(page_table, ptl);
2017                         lock_page(old_page);
2018                         page_table = pte_offset_map_lock(mm, pmd, address,
2019                                                          &ptl);
2020                         if (!pte_same(*page_table, orig_pte)) {
2021                                 unlock_page(old_page);
2022                                 page_cache_release(old_page);
2023                                 goto unlock;
2024                         }
2025                         page_cache_release(old_page);
2026                 }
2027                 reuse = reuse_swap_page(old_page);
2028                 unlock_page(old_page);
2029         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2030                                         (VM_WRITE|VM_SHARED))) {
2031                 /*
2032                  * Only catch write-faults on shared writable pages,
2033                  * read-only shared pages can get COWed by
2034                  * get_user_pages(.write=1, .force=1).
2035                  */
2036                 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2037                         struct vm_fault vmf;
2038                         int tmp;
2039
2040                         vmf.virtual_address = (void __user *)(address &
2041                                                                 PAGE_MASK);
2042                         vmf.pgoff = old_page->index;
2043                         vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2044                         vmf.page = old_page;
2045
2046                         /*
2047                          * Notify the address space that the page is about to
2048                          * become writable so that it can prohibit this or wait
2049                          * for the page to get into an appropriate state.
2050                          *
2051                          * We do this without the lock held, so that it can
2052                          * sleep if it needs to.
2053                          */
2054                         page_cache_get(old_page);
2055                         pte_unmap_unlock(page_table, ptl);
2056
2057                         tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
2058                         if (unlikely(tmp &
2059                                         (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2060                                 ret = tmp;
2061                                 goto unwritable_page;
2062                         }
2063                         if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
2064                                 lock_page(old_page);
2065                                 if (!old_page->mapping) {
2066                                         ret = 0; /* retry the fault */
2067                                         unlock_page(old_page);
2068                                         goto unwritable_page;
2069                                 }
2070                         } else
2071                                 VM_BUG_ON(!PageLocked(old_page));
2072
2073                         /*
2074                          * Since we dropped the lock we need to revalidate
2075                          * the PTE as someone else may have changed it.  If
2076                          * they did, we just return, as we can count on the
2077                          * MMU to tell us if they didn't also make it writable.
2078                          */
2079                         page_table = pte_offset_map_lock(mm, pmd, address,
2080                                                          &ptl);
2081                         if (!pte_same(*page_table, orig_pte)) {
2082                                 unlock_page(old_page);
2083                                 page_cache_release(old_page);
2084                                 goto unlock;
2085                         }
2086
2087                         page_mkwrite = 1;
2088                 }
2089                 dirty_page = old_page;
2090                 get_page(dirty_page);
2091                 reuse = 1;
2092         }
2093
2094         if (reuse) {
2095 reuse:
2096                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2097                 entry = pte_mkyoung(orig_pte);
2098                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2099                 if (ptep_set_access_flags(vma, address, page_table, entry,1))
2100                         update_mmu_cache(vma, address, entry);
2101                 ret |= VM_FAULT_WRITE;
2102                 goto unlock;
2103         }
2104
2105         /*
2106          * Ok, we need to copy. Oh, well..
2107          */
2108         page_cache_get(old_page);
2109 gotten:
2110         pte_unmap_unlock(page_table, ptl);
2111
2112         if (unlikely(anon_vma_prepare(vma)))
2113                 goto oom;
2114
2115         if (is_zero_pfn(pte_pfn(orig_pte))) {
2116                 new_page = alloc_zeroed_user_highpage_movable(vma, address);
2117                 if (!new_page)
2118                         goto oom;
2119         } else {
2120                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, address);
2121                 if (!new_page)
2122                         goto oom;
2123                 cow_user_page(new_page, old_page, address, vma);
2124         }
2125         __SetPageUptodate(new_page);
2126
2127         /*
2128          * Don't let another task, with possibly unlocked vma,
2129          * keep the mlocked page.
2130          */
2131         if ((vma->vm_flags & VM_LOCKED) && old_page) {
2132                 lock_page(old_page);    /* for LRU manipulation */
2133                 clear_page_mlock(old_page);
2134                 unlock_page(old_page);
2135         }
2136
2137         if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))
2138                 goto oom_free_new;
2139
2140         /*
2141          * Re-check the pte - we dropped the lock
2142          */
2143         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2144         if (likely(pte_same(*page_table, orig_pte))) {
2145                 if (old_page) {
2146                         if (!PageAnon(old_page)) {
2147                                 dec_mm_counter(mm, file_rss);
2148                                 inc_mm_counter(mm, anon_rss);
2149                         }
2150                 } else
2151                         inc_mm_counter(mm, anon_rss);
2152                 flush_cache_page(vma, address, pte_pfn(orig_pte));
2153                 entry = mk_pte(new_page, vma->vm_page_prot);
2154                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2155                 /*
2156                  * Clear the pte entry and flush it first, before updating the
2157                  * pte with the new entry. This will avoid a race condition
2158                  * seen in the presence of one thread doing SMC and another
2159                  * thread doing COW.
2160                  */
2161                 ptep_clear_flush(vma, address, page_table);
2162                 page_add_new_anon_rmap(new_page, vma, address);
2163                 /*
2164                  * We call the notify macro here because, when using secondary
2165                  * mmu page tables (such as kvm shadow page tables), we want the
2166                  * new page to be mapped directly into the secondary page table.
2167                  */
2168                 set_pte_at_notify(mm, address, page_table, entry);
2169                 update_mmu_cache(vma, address, entry);
2170                 if (old_page) {
2171                         /*
2172                          * Only after switching the pte to the new page may
2173                          * we remove the mapcount here. Otherwise another
2174                          * process may come and find the rmap count decremented
2175                          * before the pte is switched to the new page, and
2176                          * "reuse" the old page writing into it while our pte
2177                          * here still points into it and can be read by other
2178                          * threads.
2179                          *
2180                          * The critical issue is to order this
2181                          * page_remove_rmap with the ptp_clear_flush above.
2182                          * Those stores are ordered by (if nothing else,)
2183                          * the barrier present in the atomic_add_negative
2184                          * in page_remove_rmap.
2185                          *
2186                          * Then the TLB flush in ptep_clear_flush ensures that
2187                          * no process can access the old page before the
2188                          * decremented mapcount is visible. And the old page
2189                          * cannot be reused until after the decremented
2190                          * mapcount is visible. So transitively, TLBs to
2191                          * old page will be flushed before it can be reused.
2192                          */
2193                         page_remove_rmap(old_page);
2194                 }
2195
2196                 /* Free the old page.. */
2197                 new_page = old_page;
2198                 ret |= VM_FAULT_WRITE;
2199         } else
2200                 mem_cgroup_uncharge_page(new_page);
2201
2202         if (new_page)
2203                 page_cache_release(new_page);
2204         if (old_page)
2205                 page_cache_release(old_page);
2206 unlock:
2207         pte_unmap_unlock(page_table, ptl);
2208         if (dirty_page) {
2209                 /*
2210                  * Yes, Virginia, this is actually required to prevent a race
2211                  * with clear_page_dirty_for_io() from clearing the page dirty
2212                  * bit after it clear all dirty ptes, but before a racing
2213                  * do_wp_page installs a dirty pte.
2214                  *
2215                  * do_no_page is protected similarly.
2216                  */
2217                 if (!page_mkwrite) {
2218                         wait_on_page_locked(dirty_page);
2219                         set_page_dirty_balance(dirty_page, page_mkwrite);
2220                 }
2221                 put_page(dirty_page);
2222                 if (page_mkwrite) {
2223                         struct address_space *mapping = dirty_page->mapping;
2224
2225                         set_page_dirty(dirty_page);
2226                         unlock_page(dirty_page);
2227                         page_cache_release(dirty_page);
2228                         if (mapping)    {
2229                                 /*
2230                                  * Some device drivers do not set page.mapping
2231                                  * but still dirty their pages
2232                                  */
2233                                 balance_dirty_pages_ratelimited(mapping);
2234                         }
2235                 }
2236
2237                 /* file_update_time outside page_lock */
2238                 if (vma->vm_file)
2239                         file_update_time(vma->vm_file);
2240         }
2241         return ret;
2242 oom_free_new:
2243         page_cache_release(new_page);
2244 oom:
2245         if (old_page) {
2246                 if (page_mkwrite) {
2247                         unlock_page(old_page);
2248                         page_cache_release(old_page);
2249                 }
2250                 page_cache_release(old_page);
2251         }
2252         return VM_FAULT_OOM;
2253
2254 unwritable_page:
2255         page_cache_release(old_page);
2256         return ret;
2257 }
2258
2259 /*
2260  * Helper functions for unmap_mapping_range().
2261  *
2262  * __ Notes on dropping i_mmap_lock to reduce latency while unmapping __
2263  *
2264  * We have to restart searching the prio_tree whenever we drop the lock,
2265  * since the iterator is only valid while the lock is held, and anyway
2266  * a later vma might be split and reinserted earlier while lock dropped.
2267  *
2268  * The list of nonlinear vmas could be handled more efficiently, using
2269  * a placeholder, but handle it in the same way until a need is shown.
2270  * It is important to search the prio_tree before nonlinear list: a vma
2271  * may become nonlinear and be shifted from prio_tree to nonlinear list
2272  * while the lock is dropped; but never shifted from list to prio_tree.
2273  *
2274  * In order to make forward progress despite restarting the search,
2275  * vm_truncate_count is used to mark a vma as now dealt with, so we can
2276  * quickly skip it next time around.  Since the prio_tree search only
2277  * shows us those vmas affected by unmapping the range in question, we
2278  * can't efficiently keep all vmas in step with mapping->truncate_count:
2279  * so instead reset them all whenever it wraps back to 0 (then go to 1).
2280  * mapping->truncate_count and vma->vm_truncate_count are protected by
2281  * i_mmap_lock.
2282  *
2283  * In order to make forward progress despite repeatedly restarting some
2284  * large vma, note the restart_addr from unmap_vmas when it breaks out:
2285  * and restart from that address when we reach that vma again.  It might
2286  * have been split or merged, shrunk or extended, but never shifted: so
2287  * restart_addr remains valid so long as it remains in the vma's range.
2288  * unmap_mapping_range forces truncate_count to leap over page-aligned
2289  * values so we can save vma's restart_addr in its truncate_count field.
2290  */
2291 #define is_restart_addr(truncate_count) (!((truncate_count) & ~PAGE_MASK))
2292
2293 static void reset_vma_truncate_counts(struct address_space *mapping)
2294 {
2295         struct vm_area_struct *vma;
2296         struct prio_tree_iter iter;
2297
2298         vma_prio_tree_foreach(vma, &iter, &mapping->i_mmap, 0, ULONG_MAX)
2299                 vma->vm_truncate_count = 0;
2300         list_for_each_entry(vma, &mapping->i_mmap_nonlinear, shared.vm_set.list)
2301                 vma->vm_truncate_count = 0;
2302 }
2303
2304 static int unmap_mapping_range_vma(struct vm_area_struct *vma,
2305                 unsigned long start_addr, unsigned long end_addr,
2306                 struct zap_details *details)
2307 {
2308         unsigned long restart_addr;
2309         int need_break;
2310
2311         /*
2312          * files that support invalidating or truncating portions of the
2313          * file from under mmaped areas must have their ->fault function
2314          * return a locked page (and set VM_FAULT_LOCKED in the return).
2315          * This provides synchronisation against concurrent unmapping here.
2316          */
2317
2318 again:
2319         restart_addr = vma->vm_truncate_count;
2320         if (is_restart_addr(restart_addr) && start_addr < restart_addr) {
2321                 start_addr = restart_addr;
2322                 if (start_addr >= end_addr) {
2323                         /* Top of vma has been split off since last time */
2324                         vma->vm_truncate_count = details->truncate_count;
2325                         return 0;
2326                 }
2327         }
2328
2329         restart_addr = zap_page_range(vma, start_addr,
2330                                         end_addr - start_addr, details);
2331         need_break = need_resched() || spin_needbreak(details->i_mmap_lock);
2332
2333         if (restart_addr >= end_addr) {
2334                 /* We have now completed this vma: mark it so */
2335                 vma->vm_truncate_count = details->truncate_count;
2336                 if (!need_break)
2337                         return 0;
2338         } else {
2339                 /* Note restart_addr in vma's truncate_count field */
2340                 vma->vm_truncate_count = restart_addr;
2341                 if (!need_break)
2342                         goto again;
2343         }
2344
2345         spin_unlock(details->i_mmap_lock);
2346         cond_resched();
2347         spin_lock(details->i_mmap_lock);
2348         return -EINTR;
2349 }
2350
2351 static inline void unmap_mapping_range_tree(struct prio_tree_root *root,
2352                                             struct zap_details *details)
2353 {
2354         struct vm_area_struct *vma;
2355         struct prio_tree_iter iter;
2356         pgoff_t vba, vea, zba, zea;
2357
2358 restart:
2359         vma_prio_tree_foreach(vma, &iter, root,
2360                         details->first_index, details->last_index) {
2361                 /* Skip quickly over those we have already dealt with */
2362                 if (vma->vm_truncate_count == details->truncate_count)
2363                         continue;
2364
2365                 vba = vma->vm_pgoff;
2366                 vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1;
2367                 /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */
2368                 zba = details->first_index;
2369                 if (zba < vba)
2370                         zba = vba;
2371                 zea = details->last_index;
2372                 if (zea > vea)
2373                         zea = vea;
2374
2375                 if (unmap_mapping_range_vma(vma,
2376                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2377                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2378                                 details) < 0)
2379                         goto restart;
2380         }
2381 }
2382
2383 static inline void unmap_mapping_range_list(struct list_head *head,
2384                                             struct zap_details *details)
2385 {
2386         struct vm_area_struct *vma;
2387
2388         /*
2389          * In nonlinear VMAs there is no correspondence between virtual address
2390          * offset and file offset.  So we must perform an exhaustive search
2391          * across *all* the pages in each nonlinear VMA, not just the pages
2392          * whose virtual address lies outside the file truncation point.
2393          */
2394 restart:
2395         list_for_each_entry(vma, head, shared.vm_set.list) {
2396                 /* Skip quickly over those we have already dealt with */
2397                 if (vma->vm_truncate_count == details->truncate_count)
2398                         continue;
2399                 details->nonlinear_vma = vma;
2400                 if (unmap_mapping_range_vma(vma, vma->vm_start,
2401                                         vma->vm_end, details) < 0)
2402                         goto restart;
2403         }
2404 }
2405
2406 /**
2407  * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file.
2408  * @mapping: the address space containing mmaps to be unmapped.
2409  * @holebegin: byte in first page to unmap, relative to the start of
2410  * the underlying file.  This will be rounded down to a PAGE_SIZE
2411  * boundary.  Note that this is different from vmtruncate(), which
2412  * must keep the partial page.  In contrast, we must get rid of
2413  * partial pages.
2414  * @holelen: size of prospective hole in bytes.  This will be rounded
2415  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
2416  * end of the file.
2417  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2418  * but 0 when invalidating pagecache, don't throw away private data.
2419  */
2420 void unmap_mapping_range(struct address_space *mapping,
2421                 loff_t const holebegin, loff_t const holelen, int even_cows)
2422 {
2423         struct zap_details details;
2424         pgoff_t hba = holebegin >> PAGE_SHIFT;
2425         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2426
2427         /* Check for overflow. */
2428         if (sizeof(holelen) > sizeof(hlen)) {
2429                 long long holeend =
2430                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2431                 if (holeend & ~(long long)ULONG_MAX)
2432                         hlen = ULONG_MAX - hba + 1;
2433         }
2434
2435         details.check_mapping = even_cows? NULL: mapping;
2436         details.nonlinear_vma = NULL;
2437         details.first_index = hba;
2438         details.last_index = hba + hlen - 1;
2439         if (details.last_index < details.first_index)
2440                 details.last_index = ULONG_MAX;
2441         details.i_mmap_lock = &mapping->i_mmap_lock;
2442
2443         spin_lock(&mapping->i_mmap_lock);
2444
2445         /* Protect against endless unmapping loops */
2446         mapping->truncate_count++;
2447         if (unlikely(is_restart_addr(mapping->truncate_count))) {
2448                 if (mapping->truncate_count == 0)
2449                         reset_vma_truncate_counts(mapping);
2450                 mapping->truncate_count++;
2451         }
2452         details.truncate_count = mapping->truncate_count;
2453
2454         if (unlikely(!prio_tree_empty(&mapping->i_mmap)))
2455                 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2456         if (unlikely(!list_empty(&mapping->i_mmap_nonlinear)))
2457                 unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details);
2458         spin_unlock(&mapping->i_mmap_lock);
2459 }
2460 EXPORT_SYMBOL(unmap_mapping_range);
2461
2462 /**
2463  * vmtruncate - unmap mappings "freed" by truncate() syscall
2464  * @inode: inode of the file used
2465  * @offset: file offset to start truncating
2466  *
2467  * NOTE! We have to be ready to update the memory sharing
2468  * between the file and the memory map for a potential last
2469  * incomplete page.  Ugly, but necessary.
2470  */
2471 int vmtruncate(struct inode * inode, loff_t offset)
2472 {
2473         if (inode->i_size < offset) {
2474                 unsigned long limit;
2475
2476                 limit = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
2477                 if (limit != RLIM_INFINITY && offset > limit)
2478                         goto out_sig;
2479                 if (offset > inode->i_sb->s_maxbytes)
2480                         goto out_big;
2481                 i_size_write(inode, offset);
2482         } else {
2483                 struct address_space *mapping = inode->i_mapping;
2484
2485                 /*
2486                  * truncation of in-use swapfiles is disallowed - it would
2487                  * cause subsequent swapout to scribble on the now-freed
2488                  * blocks.
2489                  */
2490                 if (IS_SWAPFILE(inode))
2491                         return -ETXTBSY;
2492                 i_size_write(inode, offset);
2493
2494                 /*
2495                  * unmap_mapping_range is called twice, first simply for
2496                  * efficiency so that truncate_inode_pages does fewer
2497                  * single-page unmaps.  However after this first call, and
2498                  * before truncate_inode_pages finishes, it is possible for
2499                  * private pages to be COWed, which remain after
2500                  * truncate_inode_pages finishes, hence the second
2501                  * unmap_mapping_range call must be made for correctness.
2502                  */
2503                 unmap_mapping_range(mapping, offset + PAGE_SIZE - 1, 0, 1);
2504                 truncate_inode_pages(mapping, offset);
2505                 unmap_mapping_range(mapping, offset + PAGE_SIZE - 1, 0, 1);
2506         }
2507
2508         if (inode->i_op->truncate)
2509                 inode->i_op->truncate(inode);
2510         return 0;
2511
2512 out_sig:
2513         send_sig(SIGXFSZ, current, 0);
2514 out_big:
2515         return -EFBIG;
2516 }
2517 EXPORT_SYMBOL(vmtruncate);
2518
2519 int vmtruncate_range(struct inode *inode, loff_t offset, loff_t end)
2520 {
2521         struct address_space *mapping = inode->i_mapping;
2522
2523         /*
2524          * If the underlying filesystem is not going to provide
2525          * a way to truncate a range of blocks (punch a hole) -
2526          * we should return failure right now.
2527          */
2528         if (!inode->i_op->truncate_range)
2529                 return -ENOSYS;
2530
2531         mutex_lock(&inode->i_mutex);
2532         down_write(&inode->i_alloc_sem);
2533         unmap_mapping_range(mapping, offset, (end - offset), 1);
2534         truncate_inode_pages_range(mapping, offset, end);
2535         unmap_mapping_range(mapping, offset, (end - offset), 1);
2536         inode->i_op->truncate_range(inode, offset, end);
2537         up_write(&inode->i_alloc_sem);
2538         mutex_unlock(&inode->i_mutex);
2539
2540         return 0;
2541 }
2542
2543 /*
2544  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2545  * but allow concurrent faults), and pte mapped but not yet locked.
2546  * We return with mmap_sem still held, but pte unmapped and unlocked.
2547  */
2548 static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
2549                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2550                 unsigned int flags, pte_t orig_pte)
2551 {
2552         spinlock_t *ptl;
2553         struct page *page;
2554         swp_entry_t entry;
2555         pte_t pte;
2556         struct mem_cgroup *ptr = NULL;
2557         int ret = 0;
2558
2559         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
2560                 goto out;
2561
2562         entry = pte_to_swp_entry(orig_pte);
2563         if (unlikely(non_swap_entry(entry))) {
2564                 if (is_migration_entry(entry)) {
2565                         migration_entry_wait(mm, pmd, address);
2566                 } else if (is_hwpoison_entry(entry)) {
2567                         ret = VM_FAULT_HWPOISON;
2568                 } else {
2569                         print_bad_pte(vma, address, orig_pte, NULL);
2570                         ret = VM_FAULT_OOM;
2571                 }
2572                 goto out;
2573         }
2574         delayacct_set_flag(DELAYACCT_PF_SWAPIN);
2575         page = lookup_swap_cache(entry);
2576         if (!page) {
2577                 grab_swap_token(mm); /* Contend for token _before_ read-in */
2578                 page = swapin_readahead(entry,
2579                                         GFP_HIGHUSER_MOVABLE, vma, address);
2580                 if (!page) {
2581                         /*
2582                          * Back out if somebody else faulted in this pte
2583                          * while we released the pte lock.
2584                          */
2585                         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2586                         if (likely(pte_same(*page_table, orig_pte)))
2587                                 ret = VM_FAULT_OOM;
2588                         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2589                         goto unlock;
2590                 }
2591
2592                 /* Had to read the page from swap area: Major fault */
2593                 ret = VM_FAULT_MAJOR;
2594                 count_vm_event(PGMAJFAULT);
2595         } else if (PageHWPoison(page)) {
2596                 ret = VM_FAULT_HWPOISON;
2597                 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2598                 goto out;
2599         }
2600
2601         lock_page(page);
2602         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2603
2604         if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) {
2605                 ret = VM_FAULT_OOM;
2606                 goto out_page;
2607         }
2608
2609         /*
2610          * Back out if somebody else already faulted in this pte.
2611          */
2612         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2613         if (unlikely(!pte_same(*page_table, orig_pte)))
2614                 goto out_nomap;
2615
2616         if (unlikely(!PageUptodate(page))) {
2617                 ret = VM_FAULT_SIGBUS;
2618                 goto out_nomap;
2619         }
2620
2621         /*
2622          * The page isn't present yet, go ahead with the fault.
2623          *
2624          * Be careful about the sequence of operations here.
2625          * To get its accounting right, reuse_swap_page() must be called
2626          * while the page is counted on swap but not yet in mapcount i.e.
2627          * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
2628          * must be called after the swap_free(), or it will never succeed.
2629          * Because delete_from_swap_page() may be called by reuse_swap_page(),
2630          * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry
2631          * in page->private. In this case, a record in swap_cgroup  is silently
2632          * discarded at swap_free().
2633          */
2634
2635         inc_mm_counter(mm, anon_rss);
2636         pte = mk_pte(page, vma->vm_page_prot);
2637         if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {
2638                 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
2639                 flags &= ~FAULT_FLAG_WRITE;
2640         }
2641         flush_icache_page(vma, page);
2642         set_pte_at(mm, address, page_table, pte);
2643         page_add_anon_rmap(page, vma, address);
2644         /* It's better to call commit-charge after rmap is established */
2645         mem_cgroup_commit_charge_swapin(page, ptr);
2646
2647         swap_free(entry);
2648         if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
2649                 try_to_free_swap(page);
2650         unlock_page(page);
2651
2652         if (flags & FAULT_FLAG_WRITE) {
2653                 ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte);
2654                 if (ret & VM_FAULT_ERROR)
2655                         ret &= VM_FAULT_ERROR;
2656                 goto out;
2657         }
2658
2659         /* No need to invalidate - it was non-present before */
2660         update_mmu_cache(vma, address, pte);
2661 unlock:
2662         pte_unmap_unlock(page_table, ptl);
2663 out:
2664         return ret;
2665 out_nomap:
2666         mem_cgroup_cancel_charge_swapin(ptr);
2667         pte_unmap_unlock(page_table, ptl);
2668 out_page:
2669         unlock_page(page);
2670         page_cache_release(page);
2671         return ret;
2672 }
2673
2674 /*
2675  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2676  * but allow concurrent faults), and pte mapped but not yet locked.
2677  * We return with mmap_sem still held, but pte unmapped and unlocked.
2678  */
2679 static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
2680                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2681                 unsigned int flags)
2682 {
2683         struct page *page;
2684         spinlock_t *ptl;
2685         pte_t entry;
2686
2687         if (!(flags & FAULT_FLAG_WRITE)) {
2688                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(address),
2689                                                 vma->vm_page_prot));
2690                 ptl = pte_lockptr(mm, pmd);
2691                 spin_lock(ptl);
2692                 if (!pte_none(*page_table))
2693                         goto unlock;
2694                 goto setpte;
2695         }
2696
2697         /* Allocate our own private page. */
2698         pte_unmap(page_table);
2699
2700         if (unlikely(anon_vma_prepare(vma)))
2701                 goto oom;
2702         page = alloc_zeroed_user_highpage_movable(vma, address);
2703         if (!page)
2704                 goto oom;
2705         __SetPageUptodate(page);
2706
2707         if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))
2708                 goto oom_free_page;
2709
2710         entry = mk_pte(page, vma->vm_page_prot);
2711         if (vma->vm_flags & VM_WRITE)
2712                 entry = pte_mkwrite(pte_mkdirty(entry));
2713
2714         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2715         if (!pte_none(*page_table))
2716                 goto release;
2717
2718         inc_mm_counter(mm, anon_rss);
2719         page_add_new_anon_rmap(page, vma, address);
2720 setpte:
2721         set_pte_at(mm, address, page_table, entry);
2722
2723         /* No need to invalidate - it was non-present before */
2724         update_mmu_cache(vma, address, entry);
2725 unlock:
2726         pte_unmap_unlock(page_table, ptl);
2727         return 0;
2728 release:
2729         mem_cgroup_uncharge_page(page);
2730         page_cache_release(page);
2731         goto unlock;
2732 oom_free_page:
2733         page_cache_release(page);
2734 oom:
2735         return VM_FAULT_OOM;
2736 }
2737
2738 /*
2739  * __do_fault() tries to create a new page mapping. It aggressively
2740  * tries to share with existing pages, but makes a separate copy if
2741  * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid
2742  * the next page fault.
2743  *
2744  * As this is called only for pages that do not currently exist, we
2745  * do not need to flush old virtual caches or the TLB.
2746  *
2747  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2748  * but allow concurrent faults), and pte neither mapped nor locked.
2749  * We return with mmap_sem still held, but pte unmapped and unlocked.
2750  */
2751 static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
2752                 unsigned long address, pmd_t *pmd,
2753                 pgoff_t pgoff, unsigned int flags, pte_t orig_pte)
2754 {
2755         pte_t *page_table;
2756         spinlock_t *ptl;
2757         struct page *page;
2758         pte_t entry;
2759         int anon = 0;
2760         int charged = 0;
2761         struct page *dirty_page = NULL;
2762         struct vm_fault vmf;
2763         int ret;
2764         int page_mkwrite = 0;
2765
2766         vmf.virtual_address = (void __user *)(address & PAGE_MASK);
2767         vmf.pgoff = pgoff;
2768         vmf.flags = flags;
2769         vmf.page = NULL;
2770
2771         ret = vma->vm_ops->fault(vma, &vmf);
2772         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2773                 return ret;
2774
2775         if (unlikely(PageHWPoison(vmf.page))) {
2776                 if (ret & VM_FAULT_LOCKED)
2777                         unlock_page(vmf.page);
2778                 return VM_FAULT_HWPOISON;
2779         }
2780
2781         /*
2782          * For consistency in subsequent calls, make the faulted page always
2783          * locked.
2784          */
2785         if (unlikely(!(ret & VM_FAULT_LOCKED)))
2786                 lock_page(vmf.page);
2787         else
2788                 VM_BUG_ON(!PageLocked(vmf.page));
2789
2790         /*
2791          * Should we do an early C-O-W break?
2792          */
2793         page = vmf.page;
2794         if (flags & FAULT_FLAG_WRITE) {
2795                 if (!(vma->vm_flags & VM_SHARED)) {
2796                         anon = 1;
2797                         if (unlikely(anon_vma_prepare(vma))) {
2798                                 ret = VM_FAULT_OOM;
2799                                 goto out;
2800                         }
2801                         page = alloc_page_vma(GFP_HIGHUSER_MOVABLE,
2802                                                 vma, address);
2803                         if (!page) {
2804                                 ret = VM_FAULT_OOM;
2805                                 goto out;
2806                         }
2807                         if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL)) {
2808                                 ret = VM_FAULT_OOM;
2809                                 page_cache_release(page);
2810                                 goto out;
2811                         }
2812                         charged = 1;
2813                         /*
2814                          * Don't let another task, with possibly unlocked vma,
2815                          * keep the mlocked page.
2816                          */
2817                         if (vma->vm_flags & VM_LOCKED)
2818                                 clear_page_mlock(vmf.page);
2819                         copy_user_highpage(page, vmf.page, address, vma);
2820                         __SetPageUptodate(page);
2821                 } else {
2822                         /*
2823                          * If the page will be shareable, see if the backing
2824                          * address space wants to know that the page is about
2825                          * to become writable
2826                          */
2827                         if (vma->vm_ops->page_mkwrite) {
2828                                 int tmp;
2829
2830                                 unlock_page(page);
2831                                 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2832                                 tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
2833                                 if (unlikely(tmp &
2834                                           (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2835                                         ret = tmp;
2836                                         goto unwritable_page;
2837                                 }
2838                                 if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
2839                                         lock_page(page);
2840                                         if (!page->mapping) {
2841                                                 ret = 0; /* retry the fault */
2842                                                 unlock_page(page);
2843                                                 goto unwritable_page;
2844                                         }
2845                                 } else
2846                                         VM_BUG_ON(!PageLocked(page));
2847                                 page_mkwrite = 1;
2848                         }
2849                 }
2850
2851         }
2852
2853         page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2854
2855         /*
2856          * This silly early PAGE_DIRTY setting removes a race
2857          * due to the bad i386 page protection. But it's valid
2858          * for other architectures too.
2859          *
2860          * Note that if FAULT_FLAG_WRITE is set, we either now have
2861          * an exclusive copy of the page, or this is a shared mapping,
2862          * so we can make it writable and dirty to avoid having to
2863          * handle that later.
2864          */
2865         /* Only go through if we didn't race with anybody else... */
2866         if (likely(pte_same(*page_table, orig_pte))) {
2867                 flush_icache_page(vma, page);
2868                 entry = mk_pte(page, vma->vm_page_prot);
2869                 if (flags & FAULT_FLAG_WRITE)
2870                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2871                 if (anon) {
2872                         inc_mm_counter(mm, anon_rss);
2873                         page_add_new_anon_rmap(page, vma, address);
2874                 } else {
2875                         inc_mm_counter(mm, file_rss);
2876                         page_add_file_rmap(page);
2877                         if (flags & FAULT_FLAG_WRITE) {
2878                                 dirty_page = page;
2879                                 get_page(dirty_page);
2880                         }
2881                 }
2882                 set_pte_at(mm, address, page_table, entry);
2883
2884                 /* no need to invalidate: a not-present page won't be cached */
2885                 update_mmu_cache(vma, address, entry);
2886         } else {
2887                 if (charged)
2888                         mem_cgroup_uncharge_page(page);
2889                 if (anon)
2890                         page_cache_release(page);
2891                 else
2892                         anon = 1; /* no anon but release faulted_page */
2893         }
2894
2895         pte_unmap_unlock(page_table, ptl);
2896
2897 out:
2898         if (dirty_page) {
2899                 struct address_space *mapping = page->mapping;
2900
2901                 if (set_page_dirty(dirty_page))
2902                         page_mkwrite = 1;
2903                 unlock_page(dirty_page);
2904                 put_page(dirty_page);
2905                 if (page_mkwrite && mapping) {
2906                         /*
2907                          * Some device drivers do not set page.mapping but still
2908                          * dirty their pages
2909                          */
2910                         balance_dirty_pages_ratelimited(mapping);
2911                 }
2912
2913                 /* file_update_time outside page_lock */
2914                 if (vma->vm_file)
2915                         file_update_time(vma->vm_file);
2916         } else {
2917                 unlock_page(vmf.page);
2918                 if (anon)
2919                         page_cache_release(vmf.page);
2920         }
2921
2922         return ret;
2923
2924 unwritable_page:
2925         page_cache_release(page);
2926         return ret;
2927 }
2928
2929 static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
2930                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2931                 unsigned int flags, pte_t orig_pte)
2932 {
2933         pgoff_t pgoff = (((address & PAGE_MASK)
2934                         - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
2935
2936         pte_unmap(page_table);
2937         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
2938 }
2939
2940 /*
2941  * Fault of a previously existing named mapping. Repopulate the pte
2942  * from the encoded file_pte if possible. This enables swappable
2943  * nonlinear vmas.
2944  *
2945  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2946  * but allow concurrent faults), and pte mapped but not yet locked.
2947  * We return with mmap_sem still held, but pte unmapped and unlocked.
2948  */
2949 static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
2950                 unsigned long address, pte_t *page_table, pmd_t *pmd,
2951                 unsigned int flags, pte_t orig_pte)
2952 {
2953         pgoff_t pgoff;
2954
2955         flags |= FAULT_FLAG_NONLINEAR;
2956
2957         if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
2958                 return 0;
2959
2960         if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) {
2961                 /*
2962                  * Page table corrupted: show pte and kill process.
2963                  */
2964                 print_bad_pte(vma, address, orig_pte, NULL);
2965                 return VM_FAULT_OOM;
2966         }
2967
2968         pgoff = pte_to_pgoff(orig_pte);
2969         return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
2970 }
2971
2972 /*
2973  * These routines also need to handle stuff like marking pages dirty
2974  * and/or accessed for architectures that don't do it in hardware (most
2975  * RISC architectures).  The early dirtying is also good on the i386.
2976  *
2977  * There is also a hook called "update_mmu_cache()" that architectures
2978  * with external mmu caches can use to update those (ie the Sparc or
2979  * PowerPC hashed page tables that act as extended TLBs).
2980  *
2981  * We enter with non-exclusive mmap_sem (to exclude vma changes,
2982  * but allow concurrent faults), and pte mapped but not yet locked.
2983  * We return with mmap_sem still held, but pte unmapped and unlocked.
2984  */
2985 static inline int handle_pte_fault(struct mm_struct *mm,
2986                 struct vm_area_struct *vma, unsigned long address,
2987                 pte_t *pte, pmd_t *pmd, unsigned int flags)
2988 {
2989         pte_t entry;
2990         spinlock_t *ptl;
2991
2992         entry = *pte;
2993         if (!pte_present(entry)) {
2994                 if (pte_none(entry)) {
2995                         if (vma->vm_ops) {
2996                                 if (likely(vma->vm_ops->fault))
2997                                         return do_linear_fault(mm, vma, address,
2998                                                 pte, pmd, flags, entry);
2999                         }
3000                         return do_anonymous_page(mm, vma, address,
3001                                                  pte, pmd, flags);
3002                 }
3003                 if (pte_file(entry))
3004                         return do_nonlinear_fault(mm, vma, address,
3005                                         pte, pmd, flags, entry);
3006                 return do_swap_page(mm, vma, address,
3007                                         pte, pmd, flags, entry);
3008         }
3009
3010         ptl = pte_lockptr(mm, pmd);
3011         spin_lock(ptl);
3012         if (unlikely(!pte_same(*pte, entry)))
3013                 goto unlock;
3014         if (flags & FAULT_FLAG_WRITE) {
3015                 if (!pte_write(entry))
3016                         return do_wp_page(mm, vma, address,
3017                                         pte, pmd, ptl, entry);
3018                 entry = pte_mkdirty(entry);
3019         }
3020         entry = pte_mkyoung(entry);
3021         if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
3022                 update_mmu_cache(vma, address, entry);
3023         } else {
3024                 /*
3025                  * This is needed only for protection faults but the arch code
3026                  * is not yet telling us if this is a protection fault or not.
3027                  * This still avoids useless tlb flushes for .text page faults
3028                  * with threads.
3029                  */
3030                 if (flags & FAULT_FLAG_WRITE)
3031                         flush_tlb_page(vma, address);
3032         }
3033 unlock:
3034         pte_unmap_unlock(pte, ptl);
3035         return 0;
3036 }
3037
3038 /*
3039  * By the time we get here, we already hold the mm semaphore
3040  */
3041 int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3042                 unsigned long address, unsigned int flags)
3043 {
3044         pgd_t *pgd;
3045         pud_t *pud;
3046         pmd_t *pmd;
3047         pte_t *pte;
3048
3049         __set_current_state(TASK_RUNNING);
3050
3051         count_vm_event(PGFAULT);
3052
3053         if (unlikely(is_vm_hugetlb_page(vma)))
3054                 return hugetlb_fault(mm, vma, address, flags);
3055
3056         pgd = pgd_offset(mm, address);
3057         pud = pud_alloc(mm, pgd, address);
3058         if (!pud)
3059                 return VM_FAULT_OOM;
3060         pmd = pmd_alloc(mm, pud, address);
3061         if (!pmd)
3062                 return VM_FAULT_OOM;
3063         pte = pte_alloc_map(mm, pmd, address);
3064         if (!pte)
3065                 return VM_FAULT_OOM;
3066
3067         return handle_pte_fault(mm, vma, address, pte, pmd, flags);
3068 }
3069
3070 #ifndef __PAGETABLE_PUD_FOLDED
3071 /*
3072  * Allocate page upper directory.
3073  * We've already handled the fast-path in-line.
3074  */
3075 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
3076 {
3077         pud_t *new = pud_alloc_one(mm, address);
3078         if (!new)
3079                 return -ENOMEM;
3080
3081         smp_wmb(); /* See comment in __pte_alloc */
3082
3083         spin_lock(&mm->page_table_lock);
3084         if (pgd_present(*pgd))          /* Another has populated it */
3085                 pud_free(mm, new);
3086         else
3087                 pgd_populate(mm, pgd, new);
3088         spin_unlock(&mm->page_table_lock);
3089         return 0;
3090 }
3091 #endif /* __PAGETABLE_PUD_FOLDED */
3092
3093 #ifndef __PAGETABLE_PMD_FOLDED
3094 /*
3095  * Allocate page middle directory.
3096  * We've already handled the fast-path in-line.
3097  */
3098 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3099 {
3100         pmd_t *new = pmd_alloc_one(mm, address);
3101         if (!new)
3102                 return -ENOMEM;
3103
3104         smp_wmb(); /* See comment in __pte_alloc */
3105
3106         spin_lock(&mm->page_table_lock);
3107 #ifndef __ARCH_HAS_4LEVEL_HACK
3108         if (pud_present(*pud))          /* Another has populated it */
3109                 pmd_free(mm, new);
3110         else
3111                 pud_populate(mm, pud, new);
3112 #else
3113         if (pgd_present(*pud))          /* Another has populated it */
3114                 pmd_free(mm, new);
3115         else
3116                 pgd_populate(mm, pud, new);
3117 #endif /* __ARCH_HAS_4LEVEL_HACK */
3118         spin_unlock(&mm->page_table_lock);
3119         return 0;
3120 }
3121 #endif /* __PAGETABLE_PMD_FOLDED */
3122
3123 int make_pages_present(unsigned long addr, unsigned long end)
3124 {
3125         int ret, len, write;
3126         struct vm_area_struct * vma;
3127
3128         vma = find_vma(current->mm, addr);
3129         if (!vma)
3130                 return -ENOMEM;
3131         write = (vma->vm_flags & VM_WRITE) != 0;
3132         BUG_ON(addr >= end);
3133         BUG_ON(end > vma->vm_end);
3134         len = DIV_ROUND_UP(end, PAGE_SIZE) - addr/PAGE_SIZE;
3135         ret = get_user_pages(current, current->mm, addr,
3136                         len, write, 0, NULL, NULL);
3137         if (ret < 0)
3138                 return ret;
3139         return ret == len ? 0 : -EFAULT;
3140 }
3141
3142 #if !defined(__HAVE_ARCH_GATE_AREA)
3143
3144 #if defined(AT_SYSINFO_EHDR)
3145 static struct vm_area_struct gate_vma;
3146
3147 static int __init gate_vma_init(void)
3148 {
3149         gate_vma.vm_mm = NULL;
3150         gate_vma.vm_start = FIXADDR_USER_START;
3151         gate_vma.vm_end = FIXADDR_USER_END;
3152         gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC;
3153         gate_vma.vm_page_prot = __P101;
3154         /*
3155          * Make sure the vDSO gets into every core dump.
3156          * Dumping its contents makes post-mortem fully interpretable later
3157          * without matching up the same kernel and hardware config to see
3158          * what PC values meant.
3159          */
3160         gate_vma.vm_flags |= VM_ALWAYSDUMP;
3161         return 0;
3162 }
3163 __initcall(gate_vma_init);
3164 #endif
3165
3166 struct vm_area_struct *get_gate_vma(struct task_struct *tsk)
3167 {
3168 #ifdef AT_SYSINFO_EHDR
3169         return &gate_vma;
3170 #else
3171         return NULL;
3172 #endif
3173 }
3174
3175 int in_gate_area_no_task(unsigned long addr)
3176 {
3177 #ifdef AT_SYSINFO_EHDR
3178         if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END))
3179                 return 1;
3180 #endif
3181         return 0;
3182 }
3183
3184 #endif  /* __HAVE_ARCH_GATE_AREA */
3185
3186 static int follow_pte(struct mm_struct *mm, unsigned long address,
3187                 pte_t **ptepp, spinlock_t **ptlp)
3188 {
3189         pgd_t *pgd;
3190         pud_t *pud;
3191         pmd_t *pmd;
3192         pte_t *ptep;
3193
3194         pgd = pgd_offset(mm, address);
3195         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3196                 goto out;
3197
3198         pud = pud_offset(pgd, address);
3199         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3200                 goto out;
3201
3202         pmd = pmd_offset(pud, address);
3203         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
3204                 goto out;
3205
3206         /* We cannot handle huge page PFN maps. Luckily they don't exist. */
3207         if (pmd_huge(*pmd))
3208                 goto out;
3209
3210         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
3211         if (!ptep)
3212                 goto out;
3213         if (!pte_present(*ptep))
3214                 goto unlock;
3215         *ptepp = ptep;
3216         return 0;
3217 unlock:
3218         pte_unmap_unlock(ptep, *ptlp);
3219 out:
3220         return -EINVAL;
3221 }
3222
3223 /**
3224  * follow_pfn - look up PFN at a user virtual address
3225  * @vma: memory mapping
3226  * @address: user virtual address
3227  * @pfn: location to store found PFN
3228  *
3229  * Only IO mappings and raw PFN mappings are allowed.
3230  *
3231  * Returns zero and the pfn at @pfn on success, -ve otherwise.
3232  */
3233 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
3234         unsigned long *pfn)
3235 {
3236         int ret = -EINVAL;
3237         spinlock_t *ptl;
3238         pte_t *ptep;
3239
3240         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3241                 return ret;
3242
3243         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
3244         if (ret)
3245                 return ret;
3246         *pfn = pte_pfn(*ptep);
3247         pte_unmap_unlock(ptep, ptl);
3248         return 0;
3249 }
3250 EXPORT_SYMBOL(follow_pfn);
3251
3252 #ifdef CONFIG_HAVE_IOREMAP_PROT
3253 int follow_phys(struct vm_area_struct *vma,
3254                 unsigned long address, unsigned int flags,
3255                 unsigned long *prot, resource_size_t *phys)
3256 {
3257         int ret = -EINVAL;
3258         pte_t *ptep, pte;
3259         spinlock_t *ptl;
3260
3261         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3262                 goto out;
3263
3264         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
3265                 goto out;
3266         pte = *ptep;
3267
3268         if ((flags & FOLL_WRITE) && !pte_write(pte))
3269                 goto unlock;
3270
3271         *prot = pgprot_val(pte_pgprot(pte));
3272         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
3273
3274         ret = 0;
3275 unlock:
3276         pte_unmap_unlock(ptep, ptl);
3277 out:
3278         return ret;
3279 }
3280
3281 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
3282                         void *buf, int len, int write)
3283 {
3284         resource_size_t phys_addr;
3285         unsigned long prot = 0;
3286         void __iomem *maddr;
3287         int offset = addr & (PAGE_SIZE-1);
3288
3289         if (follow_phys(vma, addr, write, &prot, &phys_addr))
3290                 return -EINVAL;
3291
3292         maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot);
3293         if (write)
3294                 memcpy_toio(maddr + offset, buf, len);
3295         else
3296                 memcpy_fromio(buf, maddr + offset, len);
3297         iounmap(maddr);
3298
3299         return len;
3300 }
3301 #endif
3302
3303 /*
3304  * Access another process' address space.
3305  * Source/target buffer must be kernel space,
3306  * Do not walk the page table directly, use get_user_pages
3307  */
3308 int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write)
3309 {
3310         struct mm_struct *mm;
3311         struct vm_area_struct *vma;
3312         void *old_buf = buf;
3313
3314         mm = get_task_mm(tsk);
3315         if (!mm)
3316                 return 0;
3317
3318         down_read(&mm->mmap_sem);
3319         /* ignore errors, just check how much was successfully transferred */
3320         while (len) {
3321                 int bytes, ret, offset;
3322                 void *maddr;
3323                 struct page *page = NULL;
3324
3325                 ret = get_user_pages(tsk, mm, addr, 1,
3326                                 write, 1, &page, &vma);
3327                 if (ret <= 0) {
3328                         /*
3329                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
3330                          * we can access using slightly different code.
3331                          */
3332 #ifdef CONFIG_HAVE_IOREMAP_PROT
3333                         vma = find_vma(mm, addr);
3334                         if (!vma)
3335                                 break;
3336                         if (vma->vm_ops && vma->vm_ops->access)
3337                                 ret = vma->vm_ops->access(vma, addr, buf,
3338                                                           len, write);
3339                         if (ret <= 0)
3340 #endif
3341                                 break;
3342                         bytes = ret;
3343                 } else {
3344                         bytes = len;
3345                         offset = addr & (PAGE_SIZE-1);
3346                         if (bytes > PAGE_SIZE-offset)
3347                                 bytes = PAGE_SIZE-offset;
3348
3349                         maddr = kmap(page);
3350                         if (write) {
3351                                 copy_to_user_page(vma, page, addr,
3352                                                   maddr + offset, buf, bytes);
3353                                 set_page_dirty_lock(page);
3354                         } else {
3355                                 copy_from_user_page(vma, page, addr,
3356                                                     buf, maddr + offset, bytes);
3357                         }
3358                         kunmap(page);
3359                         page_cache_release(page);
3360                 }
3361                 len -= bytes;
3362                 buf += bytes;
3363                 addr += bytes;
3364         }
3365         up_read(&mm->mmap_sem);
3366         mmput(mm);
3367
3368         return buf - old_buf;
3369 }
3370
3371 /*
3372  * Print the name of a VMA.
3373  */
3374 void print_vma_addr(char *prefix, unsigned long ip)
3375 {
3376         struct mm_struct *mm = current->mm;
3377         struct vm_area_struct *vma;
3378
3379         /*
3380          * Do not print if we are in atomic
3381          * contexts (in exception stacks, etc.):
3382          */
3383         if (preempt_count())
3384                 return;
3385
3386         down_read(&mm->mmap_sem);
3387         vma = find_vma(mm, ip);
3388         if (vma && vma->vm_file) {
3389                 struct file *f = vma->vm_file;
3390                 char *buf = (char *)__get_free_page(GFP_KERNEL);
3391                 if (buf) {
3392                         char *p, *s;
3393
3394                         p = d_path(&f->f_path, buf, PAGE_SIZE);
3395                         if (IS_ERR(p))
3396                                 p = "?";
3397                         s = strrchr(p, '/');
3398                         if (s)
3399                                 p = s+1;
3400                         printk("%s%s[%lx+%lx]", prefix, p,
3401                                         vma->vm_start,
3402                                         vma->vm_end - vma->vm_start);
3403                         free_page((unsigned long)buf);
3404                 }
3405         }
3406         up_read(&current->mm->mmap_sem);
3407 }
3408
3409 #ifdef CONFIG_PROVE_LOCKING
3410 void might_fault(void)
3411 {
3412         /*
3413          * Some code (nfs/sunrpc) uses socket ops on kernel memory while
3414          * holding the mmap_sem, this is safe because kernel memory doesn't
3415          * get paged out, therefore we'll never actually fault, and the
3416          * below annotations will generate false positives.
3417          */
3418         if (segment_eq(get_fs(), KERNEL_DS))
3419                 return;
3420
3421         might_sleep();
3422         /*
3423          * it would be nicer only to annotate paths which are not under
3424          * pagefault_disable, however that requires a larger audit and
3425          * providing helpers like get_user_atomic.
3426          */
3427         if (!in_atomic() && current->mm)
3428                 might_lock_read(&current->mm->mmap_sem);
3429 }
3430 EXPORT_SYMBOL(might_fault);
3431 #endif