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