Merge branch 'x86-mm-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
[linux-2.6-block.git] / arch / x86 / mm / fault.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright (C) 1995  Linus Torvalds
4  *  Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.
5  *  Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar
6  */
7 #include <linux/sched.h>                /* test_thread_flag(), ...      */
8 #include <linux/sched/task_stack.h>     /* task_stack_*(), ...          */
9 #include <linux/kdebug.h>               /* oops_begin/end, ...          */
10 #include <linux/extable.h>              /* search_exception_tables      */
11 #include <linux/bootmem.h>              /* max_low_pfn                  */
12 #include <linux/kprobes.h>              /* NOKPROBE_SYMBOL, ...         */
13 #include <linux/mmiotrace.h>            /* kmmio_handler, ...           */
14 #include <linux/perf_event.h>           /* perf_sw_event                */
15 #include <linux/hugetlb.h>              /* hstate_index_to_shift        */
16 #include <linux/prefetch.h>             /* prefetchw                    */
17 #include <linux/context_tracking.h>     /* exception_enter(), ...       */
18 #include <linux/uaccess.h>              /* faulthandler_disabled()      */
19 #include <linux/efi.h>                  /* efi_recover_from_page_fault()*/
20 #include <linux/mm_types.h>
21
22 #include <asm/cpufeature.h>             /* boot_cpu_has, ...            */
23 #include <asm/traps.h>                  /* dotraplinkage, ...           */
24 #include <asm/pgalloc.h>                /* pgd_*(), ...                 */
25 #include <asm/fixmap.h>                 /* VSYSCALL_ADDR                */
26 #include <asm/vsyscall.h>               /* emulate_vsyscall             */
27 #include <asm/vm86.h>                   /* struct vm86                  */
28 #include <asm/mmu_context.h>            /* vma_pkey()                   */
29 #include <asm/efi.h>                    /* efi_recover_from_page_fault()*/
30
31 #define CREATE_TRACE_POINTS
32 #include <asm/trace/exceptions.h>
33
34 /*
35  * Returns 0 if mmiotrace is disabled, or if the fault is not
36  * handled by mmiotrace:
37  */
38 static nokprobe_inline int
39 kmmio_fault(struct pt_regs *regs, unsigned long addr)
40 {
41         if (unlikely(is_kmmio_active()))
42                 if (kmmio_handler(regs, addr) == 1)
43                         return -1;
44         return 0;
45 }
46
47 static nokprobe_inline int kprobes_fault(struct pt_regs *regs)
48 {
49         if (!kprobes_built_in())
50                 return 0;
51         if (user_mode(regs))
52                 return 0;
53         /*
54          * To be potentially processing a kprobe fault and to be allowed to call
55          * kprobe_running(), we have to be non-preemptible.
56          */
57         if (preemptible())
58                 return 0;
59         if (!kprobe_running())
60                 return 0;
61         return kprobe_fault_handler(regs, X86_TRAP_PF);
62 }
63
64 /*
65  * Prefetch quirks:
66  *
67  * 32-bit mode:
68  *
69  *   Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
70  *   Check that here and ignore it.
71  *
72  * 64-bit mode:
73  *
74  *   Sometimes the CPU reports invalid exceptions on prefetch.
75  *   Check that here and ignore it.
76  *
77  * Opcode checker based on code by Richard Brunner.
78  */
79 static inline int
80 check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
81                       unsigned char opcode, int *prefetch)
82 {
83         unsigned char instr_hi = opcode & 0xf0;
84         unsigned char instr_lo = opcode & 0x0f;
85
86         switch (instr_hi) {
87         case 0x20:
88         case 0x30:
89                 /*
90                  * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
91                  * In X86_64 long mode, the CPU will signal invalid
92                  * opcode if some of these prefixes are present so
93                  * X86_64 will never get here anyway
94                  */
95                 return ((instr_lo & 7) == 0x6);
96 #ifdef CONFIG_X86_64
97         case 0x40:
98                 /*
99                  * In AMD64 long mode 0x40..0x4F are valid REX prefixes
100                  * Need to figure out under what instruction mode the
101                  * instruction was issued. Could check the LDT for lm,
102                  * but for now it's good enough to assume that long
103                  * mode only uses well known segments or kernel.
104                  */
105                 return (!user_mode(regs) || user_64bit_mode(regs));
106 #endif
107         case 0x60:
108                 /* 0x64 thru 0x67 are valid prefixes in all modes. */
109                 return (instr_lo & 0xC) == 0x4;
110         case 0xF0:
111                 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
112                 return !instr_lo || (instr_lo>>1) == 1;
113         case 0x00:
114                 /* Prefetch instruction is 0x0F0D or 0x0F18 */
115                 if (probe_kernel_address(instr, opcode))
116                         return 0;
117
118                 *prefetch = (instr_lo == 0xF) &&
119                         (opcode == 0x0D || opcode == 0x18);
120                 return 0;
121         default:
122                 return 0;
123         }
124 }
125
126 static int
127 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
128 {
129         unsigned char *max_instr;
130         unsigned char *instr;
131         int prefetch = 0;
132
133         /*
134          * If it was a exec (instruction fetch) fault on NX page, then
135          * do not ignore the fault:
136          */
137         if (error_code & X86_PF_INSTR)
138                 return 0;
139
140         instr = (void *)convert_ip_to_linear(current, regs);
141         max_instr = instr + 15;
142
143         if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE_MAX)
144                 return 0;
145
146         while (instr < max_instr) {
147                 unsigned char opcode;
148
149                 if (probe_kernel_address(instr, opcode))
150                         break;
151
152                 instr++;
153
154                 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
155                         break;
156         }
157         return prefetch;
158 }
159
160 /*
161  * A protection key fault means that the PKRU value did not allow
162  * access to some PTE.  Userspace can figure out what PKRU was
163  * from the XSAVE state, and this function fills out a field in
164  * siginfo so userspace can discover which protection key was set
165  * on the PTE.
166  *
167  * If we get here, we know that the hardware signaled a X86_PF_PK
168  * fault and that there was a VMA once we got in the fault
169  * handler.  It does *not* guarantee that the VMA we find here
170  * was the one that we faulted on.
171  *
172  * 1. T1   : mprotect_key(foo, PAGE_SIZE, pkey=4);
173  * 2. T1   : set PKRU to deny access to pkey=4, touches page
174  * 3. T1   : faults...
175  * 4.    T2: mprotect_key(foo, PAGE_SIZE, pkey=5);
176  * 5. T1   : enters fault handler, takes mmap_sem, etc...
177  * 6. T1   : reaches here, sees vma_pkey(vma)=5, when we really
178  *           faulted on a pte with its pkey=4.
179  */
180 static void fill_sig_info_pkey(int si_signo, int si_code, siginfo_t *info,
181                 u32 *pkey)
182 {
183         /* This is effectively an #ifdef */
184         if (!boot_cpu_has(X86_FEATURE_OSPKE))
185                 return;
186
187         /* Fault not from Protection Keys: nothing to do */
188         if ((si_code != SEGV_PKUERR) || (si_signo != SIGSEGV))
189                 return;
190         /*
191          * force_sig_info_fault() is called from a number of
192          * contexts, some of which have a VMA and some of which
193          * do not.  The X86_PF_PK handing happens after we have a
194          * valid VMA, so we should never reach this without a
195          * valid VMA.
196          */
197         if (!pkey) {
198                 WARN_ONCE(1, "PKU fault with no VMA passed in");
199                 info->si_pkey = 0;
200                 return;
201         }
202         /*
203          * si_pkey should be thought of as a strong hint, but not
204          * absolutely guranteed to be 100% accurate because of
205          * the race explained above.
206          */
207         info->si_pkey = *pkey;
208 }
209
210 static void
211 force_sig_info_fault(int si_signo, int si_code, unsigned long address,
212                      struct task_struct *tsk, u32 *pkey, int fault)
213 {
214         unsigned lsb = 0;
215         siginfo_t info;
216
217         clear_siginfo(&info);
218         info.si_signo   = si_signo;
219         info.si_errno   = 0;
220         info.si_code    = si_code;
221         info.si_addr    = (void __user *)address;
222         if (fault & VM_FAULT_HWPOISON_LARGE)
223                 lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault)); 
224         if (fault & VM_FAULT_HWPOISON)
225                 lsb = PAGE_SHIFT;
226         info.si_addr_lsb = lsb;
227
228         fill_sig_info_pkey(si_signo, si_code, &info, pkey);
229
230         force_sig_info(si_signo, &info, tsk);
231 }
232
233 DEFINE_SPINLOCK(pgd_lock);
234 LIST_HEAD(pgd_list);
235
236 #ifdef CONFIG_X86_32
237 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
238 {
239         unsigned index = pgd_index(address);
240         pgd_t *pgd_k;
241         p4d_t *p4d, *p4d_k;
242         pud_t *pud, *pud_k;
243         pmd_t *pmd, *pmd_k;
244
245         pgd += index;
246         pgd_k = init_mm.pgd + index;
247
248         if (!pgd_present(*pgd_k))
249                 return NULL;
250
251         /*
252          * set_pgd(pgd, *pgd_k); here would be useless on PAE
253          * and redundant with the set_pmd() on non-PAE. As would
254          * set_p4d/set_pud.
255          */
256         p4d = p4d_offset(pgd, address);
257         p4d_k = p4d_offset(pgd_k, address);
258         if (!p4d_present(*p4d_k))
259                 return NULL;
260
261         pud = pud_offset(p4d, address);
262         pud_k = pud_offset(p4d_k, address);
263         if (!pud_present(*pud_k))
264                 return NULL;
265
266         pmd = pmd_offset(pud, address);
267         pmd_k = pmd_offset(pud_k, address);
268         if (!pmd_present(*pmd_k))
269                 return NULL;
270
271         if (!pmd_present(*pmd))
272                 set_pmd(pmd, *pmd_k);
273         else
274                 BUG_ON(pmd_page(*pmd) != pmd_page(*pmd_k));
275
276         return pmd_k;
277 }
278
279 void vmalloc_sync_all(void)
280 {
281         unsigned long address;
282
283         if (SHARED_KERNEL_PMD)
284                 return;
285
286         for (address = VMALLOC_START & PMD_MASK;
287              address >= TASK_SIZE_MAX && address < FIXADDR_TOP;
288              address += PMD_SIZE) {
289                 struct page *page;
290
291                 spin_lock(&pgd_lock);
292                 list_for_each_entry(page, &pgd_list, lru) {
293                         spinlock_t *pgt_lock;
294                         pmd_t *ret;
295
296                         /* the pgt_lock only for Xen */
297                         pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
298
299                         spin_lock(pgt_lock);
300                         ret = vmalloc_sync_one(page_address(page), address);
301                         spin_unlock(pgt_lock);
302
303                         if (!ret)
304                                 break;
305                 }
306                 spin_unlock(&pgd_lock);
307         }
308 }
309
310 /*
311  * 32-bit:
312  *
313  *   Handle a fault on the vmalloc or module mapping area
314  */
315 static noinline int vmalloc_fault(unsigned long address)
316 {
317         unsigned long pgd_paddr;
318         pmd_t *pmd_k;
319         pte_t *pte_k;
320
321         /* Make sure we are in vmalloc area: */
322         if (!(address >= VMALLOC_START && address < VMALLOC_END))
323                 return -1;
324
325         /*
326          * Synchronize this task's top level page-table
327          * with the 'reference' page table.
328          *
329          * Do _not_ use "current" here. We might be inside
330          * an interrupt in the middle of a task switch..
331          */
332         pgd_paddr = read_cr3_pa();
333         pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
334         if (!pmd_k)
335                 return -1;
336
337         if (pmd_large(*pmd_k))
338                 return 0;
339
340         pte_k = pte_offset_kernel(pmd_k, address);
341         if (!pte_present(*pte_k))
342                 return -1;
343
344         return 0;
345 }
346 NOKPROBE_SYMBOL(vmalloc_fault);
347
348 /*
349  * Did it hit the DOS screen memory VA from vm86 mode?
350  */
351 static inline void
352 check_v8086_mode(struct pt_regs *regs, unsigned long address,
353                  struct task_struct *tsk)
354 {
355 #ifdef CONFIG_VM86
356         unsigned long bit;
357
358         if (!v8086_mode(regs) || !tsk->thread.vm86)
359                 return;
360
361         bit = (address - 0xA0000) >> PAGE_SHIFT;
362         if (bit < 32)
363                 tsk->thread.vm86->screen_bitmap |= 1 << bit;
364 #endif
365 }
366
367 static bool low_pfn(unsigned long pfn)
368 {
369         return pfn < max_low_pfn;
370 }
371
372 static void dump_pagetable(unsigned long address)
373 {
374         pgd_t *base = __va(read_cr3_pa());
375         pgd_t *pgd = &base[pgd_index(address)];
376         p4d_t *p4d;
377         pud_t *pud;
378         pmd_t *pmd;
379         pte_t *pte;
380
381 #ifdef CONFIG_X86_PAE
382         pr_info("*pdpt = %016Lx ", pgd_val(*pgd));
383         if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
384                 goto out;
385 #define pr_pde pr_cont
386 #else
387 #define pr_pde pr_info
388 #endif
389         p4d = p4d_offset(pgd, address);
390         pud = pud_offset(p4d, address);
391         pmd = pmd_offset(pud, address);
392         pr_pde("*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
393 #undef pr_pde
394
395         /*
396          * We must not directly access the pte in the highpte
397          * case if the page table is located in highmem.
398          * And let's rather not kmap-atomic the pte, just in case
399          * it's allocated already:
400          */
401         if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
402                 goto out;
403
404         pte = pte_offset_kernel(pmd, address);
405         pr_cont("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
406 out:
407         pr_cont("\n");
408 }
409
410 #else /* CONFIG_X86_64: */
411
412 void vmalloc_sync_all(void)
413 {
414         sync_global_pgds(VMALLOC_START & PGDIR_MASK, VMALLOC_END);
415 }
416
417 /*
418  * 64-bit:
419  *
420  *   Handle a fault on the vmalloc area
421  */
422 static noinline int vmalloc_fault(unsigned long address)
423 {
424         pgd_t *pgd, *pgd_k;
425         p4d_t *p4d, *p4d_k;
426         pud_t *pud;
427         pmd_t *pmd;
428         pte_t *pte;
429
430         /* Make sure we are in vmalloc area: */
431         if (!(address >= VMALLOC_START && address < VMALLOC_END))
432                 return -1;
433
434         WARN_ON_ONCE(in_nmi());
435
436         /*
437          * Copy kernel mappings over when needed. This can also
438          * happen within a race in page table update. In the later
439          * case just flush:
440          */
441         pgd = (pgd_t *)__va(read_cr3_pa()) + pgd_index(address);
442         pgd_k = pgd_offset_k(address);
443         if (pgd_none(*pgd_k))
444                 return -1;
445
446         if (pgtable_l5_enabled()) {
447                 if (pgd_none(*pgd)) {
448                         set_pgd(pgd, *pgd_k);
449                         arch_flush_lazy_mmu_mode();
450                 } else {
451                         BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_k));
452                 }
453         }
454
455         /* With 4-level paging, copying happens on the p4d level. */
456         p4d = p4d_offset(pgd, address);
457         p4d_k = p4d_offset(pgd_k, address);
458         if (p4d_none(*p4d_k))
459                 return -1;
460
461         if (p4d_none(*p4d) && !pgtable_l5_enabled()) {
462                 set_p4d(p4d, *p4d_k);
463                 arch_flush_lazy_mmu_mode();
464         } else {
465                 BUG_ON(p4d_pfn(*p4d) != p4d_pfn(*p4d_k));
466         }
467
468         BUILD_BUG_ON(CONFIG_PGTABLE_LEVELS < 4);
469
470         pud = pud_offset(p4d, address);
471         if (pud_none(*pud))
472                 return -1;
473
474         if (pud_large(*pud))
475                 return 0;
476
477         pmd = pmd_offset(pud, address);
478         if (pmd_none(*pmd))
479                 return -1;
480
481         if (pmd_large(*pmd))
482                 return 0;
483
484         pte = pte_offset_kernel(pmd, address);
485         if (!pte_present(*pte))
486                 return -1;
487
488         return 0;
489 }
490 NOKPROBE_SYMBOL(vmalloc_fault);
491
492 #ifdef CONFIG_CPU_SUP_AMD
493 static const char errata93_warning[] =
494 KERN_ERR 
495 "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
496 "******* Working around it, but it may cause SEGVs or burn power.\n"
497 "******* Please consider a BIOS update.\n"
498 "******* Disabling USB legacy in the BIOS may also help.\n";
499 #endif
500
501 /*
502  * No vm86 mode in 64-bit mode:
503  */
504 static inline void
505 check_v8086_mode(struct pt_regs *regs, unsigned long address,
506                  struct task_struct *tsk)
507 {
508 }
509
510 static int bad_address(void *p)
511 {
512         unsigned long dummy;
513
514         return probe_kernel_address((unsigned long *)p, dummy);
515 }
516
517 static void dump_pagetable(unsigned long address)
518 {
519         pgd_t *base = __va(read_cr3_pa());
520         pgd_t *pgd = base + pgd_index(address);
521         p4d_t *p4d;
522         pud_t *pud;
523         pmd_t *pmd;
524         pte_t *pte;
525
526         if (bad_address(pgd))
527                 goto bad;
528
529         pr_info("PGD %lx ", pgd_val(*pgd));
530
531         if (!pgd_present(*pgd))
532                 goto out;
533
534         p4d = p4d_offset(pgd, address);
535         if (bad_address(p4d))
536                 goto bad;
537
538         pr_cont("P4D %lx ", p4d_val(*p4d));
539         if (!p4d_present(*p4d) || p4d_large(*p4d))
540                 goto out;
541
542         pud = pud_offset(p4d, address);
543         if (bad_address(pud))
544                 goto bad;
545
546         pr_cont("PUD %lx ", pud_val(*pud));
547         if (!pud_present(*pud) || pud_large(*pud))
548                 goto out;
549
550         pmd = pmd_offset(pud, address);
551         if (bad_address(pmd))
552                 goto bad;
553
554         pr_cont("PMD %lx ", pmd_val(*pmd));
555         if (!pmd_present(*pmd) || pmd_large(*pmd))
556                 goto out;
557
558         pte = pte_offset_kernel(pmd, address);
559         if (bad_address(pte))
560                 goto bad;
561
562         pr_cont("PTE %lx", pte_val(*pte));
563 out:
564         pr_cont("\n");
565         return;
566 bad:
567         pr_info("BAD\n");
568 }
569
570 #endif /* CONFIG_X86_64 */
571
572 /*
573  * Workaround for K8 erratum #93 & buggy BIOS.
574  *
575  * BIOS SMM functions are required to use a specific workaround
576  * to avoid corruption of the 64bit RIP register on C stepping K8.
577  *
578  * A lot of BIOS that didn't get tested properly miss this.
579  *
580  * The OS sees this as a page fault with the upper 32bits of RIP cleared.
581  * Try to work around it here.
582  *
583  * Note we only handle faults in kernel here.
584  * Does nothing on 32-bit.
585  */
586 static int is_errata93(struct pt_regs *regs, unsigned long address)
587 {
588 #if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
589         if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
590             || boot_cpu_data.x86 != 0xf)
591                 return 0;
592
593         if (address != regs->ip)
594                 return 0;
595
596         if ((address >> 32) != 0)
597                 return 0;
598
599         address |= 0xffffffffUL << 32;
600         if ((address >= (u64)_stext && address <= (u64)_etext) ||
601             (address >= MODULES_VADDR && address <= MODULES_END)) {
602                 printk_once(errata93_warning);
603                 regs->ip = address;
604                 return 1;
605         }
606 #endif
607         return 0;
608 }
609
610 /*
611  * Work around K8 erratum #100 K8 in compat mode occasionally jumps
612  * to illegal addresses >4GB.
613  *
614  * We catch this in the page fault handler because these addresses
615  * are not reachable. Just detect this case and return.  Any code
616  * segment in LDT is compatibility mode.
617  */
618 static int is_errata100(struct pt_regs *regs, unsigned long address)
619 {
620 #ifdef CONFIG_X86_64
621         if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
622                 return 1;
623 #endif
624         return 0;
625 }
626
627 static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
628 {
629 #ifdef CONFIG_X86_F00F_BUG
630         unsigned long nr;
631
632         /*
633          * Pentium F0 0F C7 C8 bug workaround:
634          */
635         if (boot_cpu_has_bug(X86_BUG_F00F)) {
636                 nr = (address - idt_descr.address) >> 3;
637
638                 if (nr == 6) {
639                         do_invalid_op(regs, 0);
640                         return 1;
641                 }
642         }
643 #endif
644         return 0;
645 }
646
647 static void
648 show_fault_oops(struct pt_regs *regs, unsigned long error_code,
649                 unsigned long address)
650 {
651         if (!oops_may_print())
652                 return;
653
654         if (error_code & X86_PF_INSTR) {
655                 unsigned int level;
656                 pgd_t *pgd;
657                 pte_t *pte;
658
659                 pgd = __va(read_cr3_pa());
660                 pgd += pgd_index(address);
661
662                 pte = lookup_address_in_pgd(pgd, address, &level);
663
664                 if (pte && pte_present(*pte) && !pte_exec(*pte))
665                         pr_crit("kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n",
666                                 from_kuid(&init_user_ns, current_uid()));
667                 if (pte && pte_present(*pte) && pte_exec(*pte) &&
668                                 (pgd_flags(*pgd) & _PAGE_USER) &&
669                                 (__read_cr4() & X86_CR4_SMEP))
670                         pr_crit("unable to execute userspace code (SMEP?) (uid: %d)\n",
671                                 from_kuid(&init_user_ns, current_uid()));
672         }
673
674         pr_alert("BUG: unable to handle kernel %s at %px\n",
675                  address < PAGE_SIZE ? "NULL pointer dereference" : "paging request",
676                  (void *)address);
677
678         dump_pagetable(address);
679 }
680
681 static noinline void
682 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
683             unsigned long address)
684 {
685         struct task_struct *tsk;
686         unsigned long flags;
687         int sig;
688
689         flags = oops_begin();
690         tsk = current;
691         sig = SIGKILL;
692
693         printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
694                tsk->comm, address);
695         dump_pagetable(address);
696
697         tsk->thread.cr2         = address;
698         tsk->thread.trap_nr     = X86_TRAP_PF;
699         tsk->thread.error_code  = error_code;
700
701         if (__die("Bad pagetable", regs, error_code))
702                 sig = 0;
703
704         oops_end(flags, regs, sig);
705 }
706
707 static noinline void
708 no_context(struct pt_regs *regs, unsigned long error_code,
709            unsigned long address, int signal, int si_code)
710 {
711         struct task_struct *tsk = current;
712         unsigned long flags;
713         int sig;
714
715         /* Are we prepared to handle this kernel fault? */
716         if (fixup_exception(regs, X86_TRAP_PF, error_code, address)) {
717                 /*
718                  * Any interrupt that takes a fault gets the fixup. This makes
719                  * the below recursive fault logic only apply to a faults from
720                  * task context.
721                  */
722                 if (in_interrupt())
723                         return;
724
725                 /*
726                  * Per the above we're !in_interrupt(), aka. task context.
727                  *
728                  * In this case we need to make sure we're not recursively
729                  * faulting through the emulate_vsyscall() logic.
730                  */
731                 if (current->thread.sig_on_uaccess_err && signal) {
732                         tsk->thread.trap_nr = X86_TRAP_PF;
733                         tsk->thread.error_code = error_code | X86_PF_USER;
734                         tsk->thread.cr2 = address;
735
736                         /* XXX: hwpoison faults will set the wrong code. */
737                         force_sig_info_fault(signal, si_code, address,
738                                              tsk, NULL, 0);
739                 }
740
741                 /*
742                  * Barring that, we can do the fixup and be happy.
743                  */
744                 return;
745         }
746
747 #ifdef CONFIG_VMAP_STACK
748         /*
749          * Stack overflow?  During boot, we can fault near the initial
750          * stack in the direct map, but that's not an overflow -- check
751          * that we're in vmalloc space to avoid this.
752          */
753         if (is_vmalloc_addr((void *)address) &&
754             (((unsigned long)tsk->stack - 1 - address < PAGE_SIZE) ||
755              address - ((unsigned long)tsk->stack + THREAD_SIZE) < PAGE_SIZE)) {
756                 unsigned long stack = this_cpu_read(orig_ist.ist[DOUBLEFAULT_STACK]) - sizeof(void *);
757                 /*
758                  * We're likely to be running with very little stack space
759                  * left.  It's plausible that we'd hit this condition but
760                  * double-fault even before we get this far, in which case
761                  * we're fine: the double-fault handler will deal with it.
762                  *
763                  * We don't want to make it all the way into the oops code
764                  * and then double-fault, though, because we're likely to
765                  * break the console driver and lose most of the stack dump.
766                  */
767                 asm volatile ("movq %[stack], %%rsp\n\t"
768                               "call handle_stack_overflow\n\t"
769                               "1: jmp 1b"
770                               : ASM_CALL_CONSTRAINT
771                               : "D" ("kernel stack overflow (page fault)"),
772                                 "S" (regs), "d" (address),
773                                 [stack] "rm" (stack));
774                 unreachable();
775         }
776 #endif
777
778         /*
779          * 32-bit:
780          *
781          *   Valid to do another page fault here, because if this fault
782          *   had been triggered by is_prefetch fixup_exception would have
783          *   handled it.
784          *
785          * 64-bit:
786          *
787          *   Hall of shame of CPU/BIOS bugs.
788          */
789         if (is_prefetch(regs, error_code, address))
790                 return;
791
792         if (is_errata93(regs, address))
793                 return;
794
795         /*
796          * Buggy firmware could access regions which might page fault, try to
797          * recover from such faults.
798          */
799         if (IS_ENABLED(CONFIG_EFI))
800                 efi_recover_from_page_fault(address);
801
802         /*
803          * Oops. The kernel tried to access some bad page. We'll have to
804          * terminate things with extreme prejudice:
805          */
806         flags = oops_begin();
807
808         show_fault_oops(regs, error_code, address);
809
810         if (task_stack_end_corrupted(tsk))
811                 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
812
813         tsk->thread.cr2         = address;
814         tsk->thread.trap_nr     = X86_TRAP_PF;
815         tsk->thread.error_code  = error_code;
816
817         sig = SIGKILL;
818         if (__die("Oops", regs, error_code))
819                 sig = 0;
820
821         /* Executive summary in case the body of the oops scrolled away */
822         printk(KERN_DEFAULT "CR2: %016lx\n", address);
823
824         oops_end(flags, regs, sig);
825 }
826
827 /*
828  * Print out info about fatal segfaults, if the show_unhandled_signals
829  * sysctl is set:
830  */
831 static inline void
832 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
833                 unsigned long address, struct task_struct *tsk)
834 {
835         const char *loglvl = task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG;
836
837         if (!unhandled_signal(tsk, SIGSEGV))
838                 return;
839
840         if (!printk_ratelimit())
841                 return;
842
843         printk("%s%s[%d]: segfault at %lx ip %px sp %px error %lx",
844                 loglvl, tsk->comm, task_pid_nr(tsk), address,
845                 (void *)regs->ip, (void *)regs->sp, error_code);
846
847         print_vma_addr(KERN_CONT " in ", regs->ip);
848
849         printk(KERN_CONT "\n");
850
851         show_opcodes(regs, loglvl);
852 }
853
854 /*
855  * The (legacy) vsyscall page is the long page in the kernel portion
856  * of the address space that has user-accessible permissions.
857  */
858 static bool is_vsyscall_vaddr(unsigned long vaddr)
859 {
860         return unlikely((vaddr & PAGE_MASK) == VSYSCALL_ADDR);
861 }
862
863 static void
864 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
865                        unsigned long address, u32 *pkey, int si_code)
866 {
867         struct task_struct *tsk = current;
868
869         /* User mode accesses just cause a SIGSEGV */
870         if (error_code & X86_PF_USER) {
871                 /*
872                  * It's possible to have interrupts off here:
873                  */
874                 local_irq_enable();
875
876                 /*
877                  * Valid to do another page fault here because this one came
878                  * from user space:
879                  */
880                 if (is_prefetch(regs, error_code, address))
881                         return;
882
883                 if (is_errata100(regs, address))
884                         return;
885
886                 /*
887                  * To avoid leaking information about the kernel page table
888                  * layout, pretend that user-mode accesses to kernel addresses
889                  * are always protection faults.
890                  */
891                 if (address >= TASK_SIZE_MAX)
892                         error_code |= X86_PF_PROT;
893
894                 if (likely(show_unhandled_signals))
895                         show_signal_msg(regs, error_code, address, tsk);
896
897                 tsk->thread.cr2         = address;
898                 tsk->thread.error_code  = error_code;
899                 tsk->thread.trap_nr     = X86_TRAP_PF;
900
901                 force_sig_info_fault(SIGSEGV, si_code, address, tsk, pkey, 0);
902
903                 return;
904         }
905
906         if (is_f00f_bug(regs, address))
907                 return;
908
909         no_context(regs, error_code, address, SIGSEGV, si_code);
910 }
911
912 static noinline void
913 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
914                      unsigned long address, u32 *pkey)
915 {
916         __bad_area_nosemaphore(regs, error_code, address, pkey, SEGV_MAPERR);
917 }
918
919 static void
920 __bad_area(struct pt_regs *regs, unsigned long error_code,
921            unsigned long address,  struct vm_area_struct *vma, int si_code)
922 {
923         struct mm_struct *mm = current->mm;
924         u32 pkey;
925
926         if (vma)
927                 pkey = vma_pkey(vma);
928
929         /*
930          * Something tried to access memory that isn't in our memory map..
931          * Fix it, but check if it's kernel or user first..
932          */
933         up_read(&mm->mmap_sem);
934
935         __bad_area_nosemaphore(regs, error_code, address,
936                                (vma) ? &pkey : NULL, si_code);
937 }
938
939 static noinline void
940 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
941 {
942         __bad_area(regs, error_code, address, NULL, SEGV_MAPERR);
943 }
944
945 static inline bool bad_area_access_from_pkeys(unsigned long error_code,
946                 struct vm_area_struct *vma)
947 {
948         /* This code is always called on the current mm */
949         bool foreign = false;
950
951         if (!boot_cpu_has(X86_FEATURE_OSPKE))
952                 return false;
953         if (error_code & X86_PF_PK)
954                 return true;
955         /* this checks permission keys on the VMA: */
956         if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
957                                        (error_code & X86_PF_INSTR), foreign))
958                 return true;
959         return false;
960 }
961
962 static noinline void
963 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
964                       unsigned long address, struct vm_area_struct *vma)
965 {
966         /*
967          * This OSPKE check is not strictly necessary at runtime.
968          * But, doing it this way allows compiler optimizations
969          * if pkeys are compiled out.
970          */
971         if (bad_area_access_from_pkeys(error_code, vma))
972                 __bad_area(regs, error_code, address, vma, SEGV_PKUERR);
973         else
974                 __bad_area(regs, error_code, address, vma, SEGV_ACCERR);
975 }
976
977 static void
978 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
979           u32 *pkey, unsigned int fault)
980 {
981         struct task_struct *tsk = current;
982         int code = BUS_ADRERR;
983
984         /* Kernel mode? Handle exceptions or die: */
985         if (!(error_code & X86_PF_USER)) {
986                 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
987                 return;
988         }
989
990         /* User-space => ok to do another page fault: */
991         if (is_prefetch(regs, error_code, address))
992                 return;
993
994         tsk->thread.cr2         = address;
995         tsk->thread.error_code  = error_code;
996         tsk->thread.trap_nr     = X86_TRAP_PF;
997
998 #ifdef CONFIG_MEMORY_FAILURE
999         if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
1000                 printk(KERN_ERR
1001         "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
1002                         tsk->comm, tsk->pid, address);
1003                 code = BUS_MCEERR_AR;
1004         }
1005 #endif
1006         force_sig_info_fault(SIGBUS, code, address, tsk, pkey, fault);
1007 }
1008
1009 static noinline void
1010 mm_fault_error(struct pt_regs *regs, unsigned long error_code,
1011                unsigned long address, u32 *pkey, vm_fault_t fault)
1012 {
1013         if (fatal_signal_pending(current) && !(error_code & X86_PF_USER)) {
1014                 no_context(regs, error_code, address, 0, 0);
1015                 return;
1016         }
1017
1018         if (fault & VM_FAULT_OOM) {
1019                 /* Kernel mode? Handle exceptions or die: */
1020                 if (!(error_code & X86_PF_USER)) {
1021                         no_context(regs, error_code, address,
1022                                    SIGSEGV, SEGV_MAPERR);
1023                         return;
1024                 }
1025
1026                 /*
1027                  * We ran out of memory, call the OOM killer, and return the
1028                  * userspace (which will retry the fault, or kill us if we got
1029                  * oom-killed):
1030                  */
1031                 pagefault_out_of_memory();
1032         } else {
1033                 if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
1034                              VM_FAULT_HWPOISON_LARGE))
1035                         do_sigbus(regs, error_code, address, pkey, fault);
1036                 else if (fault & VM_FAULT_SIGSEGV)
1037                         bad_area_nosemaphore(regs, error_code, address, pkey);
1038                 else
1039                         BUG();
1040         }
1041 }
1042
1043 static int spurious_kernel_fault_check(unsigned long error_code, pte_t *pte)
1044 {
1045         if ((error_code & X86_PF_WRITE) && !pte_write(*pte))
1046                 return 0;
1047
1048         if ((error_code & X86_PF_INSTR) && !pte_exec(*pte))
1049                 return 0;
1050
1051         return 1;
1052 }
1053
1054 /*
1055  * Handle a spurious fault caused by a stale TLB entry.
1056  *
1057  * This allows us to lazily refresh the TLB when increasing the
1058  * permissions of a kernel page (RO -> RW or NX -> X).  Doing it
1059  * eagerly is very expensive since that implies doing a full
1060  * cross-processor TLB flush, even if no stale TLB entries exist
1061  * on other processors.
1062  *
1063  * Spurious faults may only occur if the TLB contains an entry with
1064  * fewer permission than the page table entry.  Non-present (P = 0)
1065  * and reserved bit (R = 1) faults are never spurious.
1066  *
1067  * There are no security implications to leaving a stale TLB when
1068  * increasing the permissions on a page.
1069  *
1070  * Returns non-zero if a spurious fault was handled, zero otherwise.
1071  *
1072  * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
1073  * (Optional Invalidation).
1074  */
1075 static noinline int
1076 spurious_kernel_fault(unsigned long error_code, unsigned long address)
1077 {
1078         pgd_t *pgd;
1079         p4d_t *p4d;
1080         pud_t *pud;
1081         pmd_t *pmd;
1082         pte_t *pte;
1083         int ret;
1084
1085         /*
1086          * Only writes to RO or instruction fetches from NX may cause
1087          * spurious faults.
1088          *
1089          * These could be from user or supervisor accesses but the TLB
1090          * is only lazily flushed after a kernel mapping protection
1091          * change, so user accesses are not expected to cause spurious
1092          * faults.
1093          */
1094         if (error_code != (X86_PF_WRITE | X86_PF_PROT) &&
1095             error_code != (X86_PF_INSTR | X86_PF_PROT))
1096                 return 0;
1097
1098         pgd = init_mm.pgd + pgd_index(address);
1099         if (!pgd_present(*pgd))
1100                 return 0;
1101
1102         p4d = p4d_offset(pgd, address);
1103         if (!p4d_present(*p4d))
1104                 return 0;
1105
1106         if (p4d_large(*p4d))
1107                 return spurious_kernel_fault_check(error_code, (pte_t *) p4d);
1108
1109         pud = pud_offset(p4d, address);
1110         if (!pud_present(*pud))
1111                 return 0;
1112
1113         if (pud_large(*pud))
1114                 return spurious_kernel_fault_check(error_code, (pte_t *) pud);
1115
1116         pmd = pmd_offset(pud, address);
1117         if (!pmd_present(*pmd))
1118                 return 0;
1119
1120         if (pmd_large(*pmd))
1121                 return spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1122
1123         pte = pte_offset_kernel(pmd, address);
1124         if (!pte_present(*pte))
1125                 return 0;
1126
1127         ret = spurious_kernel_fault_check(error_code, pte);
1128         if (!ret)
1129                 return 0;
1130
1131         /*
1132          * Make sure we have permissions in PMD.
1133          * If not, then there's a bug in the page tables:
1134          */
1135         ret = spurious_kernel_fault_check(error_code, (pte_t *) pmd);
1136         WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1137
1138         return ret;
1139 }
1140 NOKPROBE_SYMBOL(spurious_kernel_fault);
1141
1142 int show_unhandled_signals = 1;
1143
1144 static inline int
1145 access_error(unsigned long error_code, struct vm_area_struct *vma)
1146 {
1147         /* This is only called for the current mm, so: */
1148         bool foreign = false;
1149
1150         /*
1151          * Read or write was blocked by protection keys.  This is
1152          * always an unconditional error and can never result in
1153          * a follow-up action to resolve the fault, like a COW.
1154          */
1155         if (error_code & X86_PF_PK)
1156                 return 1;
1157
1158         /*
1159          * Make sure to check the VMA so that we do not perform
1160          * faults just to hit a X86_PF_PK as soon as we fill in a
1161          * page.
1162          */
1163         if (!arch_vma_access_permitted(vma, (error_code & X86_PF_WRITE),
1164                                        (error_code & X86_PF_INSTR), foreign))
1165                 return 1;
1166
1167         if (error_code & X86_PF_WRITE) {
1168                 /* write, present and write, not present: */
1169                 if (unlikely(!(vma->vm_flags & VM_WRITE)))
1170                         return 1;
1171                 return 0;
1172         }
1173
1174         /* read, present: */
1175         if (unlikely(error_code & X86_PF_PROT))
1176                 return 1;
1177
1178         /* read, not present: */
1179         if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))))
1180                 return 1;
1181
1182         return 0;
1183 }
1184
1185 static int fault_in_kernel_space(unsigned long address)
1186 {
1187         /*
1188          * On 64-bit systems, the vsyscall page is at an address above
1189          * TASK_SIZE_MAX, but is not considered part of the kernel
1190          * address space.
1191          */
1192         if (IS_ENABLED(CONFIG_X86_64) && is_vsyscall_vaddr(address))
1193                 return false;
1194
1195         return address >= TASK_SIZE_MAX;
1196 }
1197
1198 static inline bool smap_violation(int error_code, struct pt_regs *regs)
1199 {
1200         if (!IS_ENABLED(CONFIG_X86_SMAP))
1201                 return false;
1202
1203         if (!static_cpu_has(X86_FEATURE_SMAP))
1204                 return false;
1205
1206         if (error_code & X86_PF_USER)
1207                 return false;
1208
1209         if (!user_mode(regs) && (regs->flags & X86_EFLAGS_AC))
1210                 return false;
1211
1212         return true;
1213 }
1214
1215 /*
1216  * Called for all faults where 'address' is part of the kernel address
1217  * space.  Might get called for faults that originate from *code* that
1218  * ran in userspace or the kernel.
1219  */
1220 static void
1221 do_kern_addr_fault(struct pt_regs *regs, unsigned long hw_error_code,
1222                    unsigned long address)
1223 {
1224         /*
1225          * Protection keys exceptions only happen on user pages.  We
1226          * have no user pages in the kernel portion of the address
1227          * space, so do not expect them here.
1228          */
1229         WARN_ON_ONCE(hw_error_code & X86_PF_PK);
1230
1231         /*
1232          * We can fault-in kernel-space virtual memory on-demand. The
1233          * 'reference' page table is init_mm.pgd.
1234          *
1235          * NOTE! We MUST NOT take any locks for this case. We may
1236          * be in an interrupt or a critical region, and should
1237          * only copy the information from the master page table,
1238          * nothing more.
1239          *
1240          * Before doing this on-demand faulting, ensure that the
1241          * fault is not any of the following:
1242          * 1. A fault on a PTE with a reserved bit set.
1243          * 2. A fault caused by a user-mode access.  (Do not demand-
1244          *    fault kernel memory due to user-mode accesses).
1245          * 3. A fault caused by a page-level protection violation.
1246          *    (A demand fault would be on a non-present page which
1247          *     would have X86_PF_PROT==0).
1248          */
1249         if (!(hw_error_code & (X86_PF_RSVD | X86_PF_USER | X86_PF_PROT))) {
1250                 if (vmalloc_fault(address) >= 0)
1251                         return;
1252         }
1253
1254         /* Was the fault spurious, caused by lazy TLB invalidation? */
1255         if (spurious_kernel_fault(hw_error_code, address))
1256                 return;
1257
1258         /* kprobes don't want to hook the spurious faults: */
1259         if (kprobes_fault(regs))
1260                 return;
1261
1262         /*
1263          * Note, despite being a "bad area", there are quite a few
1264          * acceptable reasons to get here, such as erratum fixups
1265          * and handling kernel code that can fault, like get_user().
1266          *
1267          * Don't take the mm semaphore here. If we fixup a prefetch
1268          * fault we could otherwise deadlock:
1269          */
1270         bad_area_nosemaphore(regs, hw_error_code, address, NULL);
1271 }
1272 NOKPROBE_SYMBOL(do_kern_addr_fault);
1273
1274 /* Handle faults in the user portion of the address space */
1275 static inline
1276 void do_user_addr_fault(struct pt_regs *regs,
1277                         unsigned long hw_error_code,
1278                         unsigned long address)
1279 {
1280         unsigned long sw_error_code;
1281         struct vm_area_struct *vma;
1282         struct task_struct *tsk;
1283         struct mm_struct *mm;
1284         vm_fault_t fault, major = 0;
1285         unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1286         u32 pkey;
1287
1288         tsk = current;
1289         mm = tsk->mm;
1290
1291         /* kprobes don't want to hook the spurious faults: */
1292         if (unlikely(kprobes_fault(regs)))
1293                 return;
1294
1295         /*
1296          * Reserved bits are never expected to be set on
1297          * entries in the user portion of the page tables.
1298          */
1299         if (unlikely(hw_error_code & X86_PF_RSVD))
1300                 pgtable_bad(regs, hw_error_code, address);
1301
1302         /*
1303          * Check for invalid kernel (supervisor) access to user
1304          * pages in the user address space.
1305          */
1306         if (unlikely(smap_violation(hw_error_code, regs))) {
1307                 bad_area_nosemaphore(regs, hw_error_code, address, NULL);
1308                 return;
1309         }
1310
1311         /*
1312          * If we're in an interrupt, have no user context or are running
1313          * in a region with pagefaults disabled then we must not take the fault
1314          */
1315         if (unlikely(faulthandler_disabled() || !mm)) {
1316                 bad_area_nosemaphore(regs, hw_error_code, address, NULL);
1317                 return;
1318         }
1319
1320         /*
1321          * hw_error_code is literally the "page fault error code" passed to
1322          * the kernel directly from the hardware.  But, we will shortly be
1323          * modifying it in software, so give it a new name.
1324          */
1325         sw_error_code = hw_error_code;
1326
1327         /*
1328          * It's safe to allow irq's after cr2 has been saved and the
1329          * vmalloc fault has been handled.
1330          *
1331          * User-mode registers count as a user access even for any
1332          * potential system fault or CPU buglet:
1333          */
1334         if (user_mode(regs)) {
1335                 local_irq_enable();
1336                 /*
1337                  * Up to this point, X86_PF_USER set in hw_error_code
1338                  * indicated a user-mode access.  But, after this,
1339                  * X86_PF_USER in sw_error_code will indicate either
1340                  * that, *or* an implicit kernel(supervisor)-mode access
1341                  * which originated from user mode.
1342                  */
1343                 if (!(hw_error_code & X86_PF_USER)) {
1344                         /*
1345                          * The CPU was in user mode, but the CPU says
1346                          * the fault was not a user-mode access.
1347                          * Must be an implicit kernel-mode access,
1348                          * which we do not expect to happen in the
1349                          * user address space.
1350                          */
1351                         pr_warn_once("kernel-mode error from user-mode: %lx\n",
1352                                         hw_error_code);
1353
1354                         sw_error_code |= X86_PF_USER;
1355                 }
1356                 flags |= FAULT_FLAG_USER;
1357         } else {
1358                 if (regs->flags & X86_EFLAGS_IF)
1359                         local_irq_enable();
1360         }
1361
1362         perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1363
1364         if (sw_error_code & X86_PF_WRITE)
1365                 flags |= FAULT_FLAG_WRITE;
1366         if (sw_error_code & X86_PF_INSTR)
1367                 flags |= FAULT_FLAG_INSTRUCTION;
1368
1369 #ifdef CONFIG_X86_64
1370         /*
1371          * Instruction fetch faults in the vsyscall page might need
1372          * emulation.  The vsyscall page is at a high address
1373          * (>PAGE_OFFSET), but is considered to be part of the user
1374          * address space.
1375          *
1376          * The vsyscall page does not have a "real" VMA, so do this
1377          * emulation before we go searching for VMAs.
1378          */
1379         if ((sw_error_code & X86_PF_INSTR) && is_vsyscall_vaddr(address)) {
1380                 if (emulate_vsyscall(regs, address))
1381                         return;
1382         }
1383 #endif
1384
1385         /*
1386          * Kernel-mode access to the user address space should only occur
1387          * on well-defined single instructions listed in the exception
1388          * tables.  But, an erroneous kernel fault occurring outside one of
1389          * those areas which also holds mmap_sem might deadlock attempting
1390          * to validate the fault against the address space.
1391          *
1392          * Only do the expensive exception table search when we might be at
1393          * risk of a deadlock.  This happens if we
1394          * 1. Failed to acquire mmap_sem, and
1395          * 2. The access did not originate in userspace.  Note: either the
1396          *    hardware or earlier page fault code may set X86_PF_USER
1397          *    in sw_error_code.
1398          */
1399         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
1400                 if (!(sw_error_code & X86_PF_USER) &&
1401                     !search_exception_tables(regs->ip)) {
1402                         /*
1403                          * Fault from code in kernel from
1404                          * which we do not expect faults.
1405                          */
1406                         bad_area_nosemaphore(regs, sw_error_code, address, NULL);
1407                         return;
1408                 }
1409 retry:
1410                 down_read(&mm->mmap_sem);
1411         } else {
1412                 /*
1413                  * The above down_read_trylock() might have succeeded in
1414                  * which case we'll have missed the might_sleep() from
1415                  * down_read():
1416                  */
1417                 might_sleep();
1418         }
1419
1420         vma = find_vma(mm, address);
1421         if (unlikely(!vma)) {
1422                 bad_area(regs, sw_error_code, address);
1423                 return;
1424         }
1425         if (likely(vma->vm_start <= address))
1426                 goto good_area;
1427         if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1428                 bad_area(regs, sw_error_code, address);
1429                 return;
1430         }
1431         if (sw_error_code & X86_PF_USER) {
1432                 /*
1433                  * Accessing the stack below %sp is always a bug.
1434                  * The large cushion allows instructions like enter
1435                  * and pusha to work. ("enter $65535, $31" pushes
1436                  * 32 pointers and then decrements %sp by 65535.)
1437                  */
1438                 if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
1439                         bad_area(regs, sw_error_code, address);
1440                         return;
1441                 }
1442         }
1443         if (unlikely(expand_stack(vma, address))) {
1444                 bad_area(regs, sw_error_code, address);
1445                 return;
1446         }
1447
1448         /*
1449          * Ok, we have a good vm_area for this memory access, so
1450          * we can handle it..
1451          */
1452 good_area:
1453         if (unlikely(access_error(sw_error_code, vma))) {
1454                 bad_area_access_error(regs, sw_error_code, address, vma);
1455                 return;
1456         }
1457
1458         /*
1459          * If for any reason at all we couldn't handle the fault,
1460          * make sure we exit gracefully rather than endlessly redo
1461          * the fault.  Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1462          * we get VM_FAULT_RETRY back, the mmap_sem has been unlocked.
1463          *
1464          * Note that handle_userfault() may also release and reacquire mmap_sem
1465          * (and not return with VM_FAULT_RETRY), when returning to userland to
1466          * repeat the page fault later with a VM_FAULT_NOPAGE retval
1467          * (potentially after handling any pending signal during the return to
1468          * userland). The return to userland is identified whenever
1469          * FAULT_FLAG_USER|FAULT_FLAG_KILLABLE are both set in flags.
1470          * Thus we have to be careful about not touching vma after handling the
1471          * fault, so we read the pkey beforehand.
1472          */
1473         pkey = vma_pkey(vma);
1474         fault = handle_mm_fault(vma, address, flags);
1475         major |= fault & VM_FAULT_MAJOR;
1476
1477         /*
1478          * If we need to retry the mmap_sem has already been released,
1479          * and if there is a fatal signal pending there is no guarantee
1480          * that we made any progress. Handle this case first.
1481          */
1482         if (unlikely(fault & VM_FAULT_RETRY)) {
1483                 /* Retry at most once */
1484                 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1485                         flags &= ~FAULT_FLAG_ALLOW_RETRY;
1486                         flags |= FAULT_FLAG_TRIED;
1487                         if (!fatal_signal_pending(tsk))
1488                                 goto retry;
1489                 }
1490
1491                 /* User mode? Just return to handle the fatal exception */
1492                 if (flags & FAULT_FLAG_USER)
1493                         return;
1494
1495                 /* Not returning to user mode? Handle exceptions or die: */
1496                 no_context(regs, sw_error_code, address, SIGBUS, BUS_ADRERR);
1497                 return;
1498         }
1499
1500         up_read(&mm->mmap_sem);
1501         if (unlikely(fault & VM_FAULT_ERROR)) {
1502                 mm_fault_error(regs, sw_error_code, address, &pkey, fault);
1503                 return;
1504         }
1505
1506         /*
1507          * Major/minor page fault accounting. If any of the events
1508          * returned VM_FAULT_MAJOR, we account it as a major fault.
1509          */
1510         if (major) {
1511                 tsk->maj_flt++;
1512                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
1513         } else {
1514                 tsk->min_flt++;
1515                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
1516         }
1517
1518         check_v8086_mode(regs, address, tsk);
1519 }
1520 NOKPROBE_SYMBOL(do_user_addr_fault);
1521
1522 /*
1523  * This routine handles page faults.  It determines the address,
1524  * and the problem, and then passes it off to one of the appropriate
1525  * routines.
1526  */
1527 static noinline void
1528 __do_page_fault(struct pt_regs *regs, unsigned long hw_error_code,
1529                 unsigned long address)
1530 {
1531         prefetchw(&current->mm->mmap_sem);
1532
1533         if (unlikely(kmmio_fault(regs, address)))
1534                 return;
1535
1536         /* Was the fault on kernel-controlled part of the address space? */
1537         if (unlikely(fault_in_kernel_space(address)))
1538                 do_kern_addr_fault(regs, hw_error_code, address);
1539         else
1540                 do_user_addr_fault(regs, hw_error_code, address);
1541 }
1542 NOKPROBE_SYMBOL(__do_page_fault);
1543
1544 static nokprobe_inline void
1545 trace_page_fault_entries(unsigned long address, struct pt_regs *regs,
1546                          unsigned long error_code)
1547 {
1548         if (user_mode(regs))
1549                 trace_page_fault_user(address, regs, error_code);
1550         else
1551                 trace_page_fault_kernel(address, regs, error_code);
1552 }
1553
1554 /*
1555  * We must have this function blacklisted from kprobes, tagged with notrace
1556  * and call read_cr2() before calling anything else. To avoid calling any
1557  * kind of tracing machinery before we've observed the CR2 value.
1558  *
1559  * exception_{enter,exit}() contains all sorts of tracepoints.
1560  */
1561 dotraplinkage void notrace
1562 do_page_fault(struct pt_regs *regs, unsigned long error_code)
1563 {
1564         unsigned long address = read_cr2(); /* Get the faulting address */
1565         enum ctx_state prev_state;
1566
1567         prev_state = exception_enter();
1568         if (trace_pagefault_enabled())
1569                 trace_page_fault_entries(address, regs, error_code);
1570
1571         __do_page_fault(regs, error_code, address);
1572         exception_exit(prev_state);
1573 }
1574 NOKPROBE_SYMBOL(do_page_fault);