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