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