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