GNU Linux-libre 4.4.284-gnu1
[releases.git] / arch / x86 / mm / fault.c
1 /*
2  *  Copyright (C) 1995  Linus Torvalds
3  *  Copyright (C) 2001, 2002 Andi Kleen, SuSE Labs.
4  *  Copyright (C) 2008-2009, Red Hat Inc., Ingo Molnar
5  */
6 #include <linux/sched.h>                /* test_thread_flag(), ...      */
7 #include <linux/kdebug.h>               /* oops_begin/end, ...          */
8 #include <linux/module.h>               /* search_exception_table       */
9 #include <linux/bootmem.h>              /* max_low_pfn                  */
10 #include <linux/kprobes.h>              /* NOKPROBE_SYMBOL, ...         */
11 #include <linux/mmiotrace.h>            /* kmmio_handler, ...           */
12 #include <linux/perf_event.h>           /* perf_sw_event                */
13 #include <linux/hugetlb.h>              /* hstate_index_to_shift        */
14 #include <linux/prefetch.h>             /* prefetchw                    */
15 #include <linux/context_tracking.h>     /* exception_enter(), ...       */
16 #include <linux/uaccess.h>              /* faulthandler_disabled()      */
17
18 #include <asm/traps.h>                  /* dotraplinkage, ...           */
19 #include <asm/pgalloc.h>                /* pgd_*(), ...                 */
20 #include <asm/kmemcheck.h>              /* kmemcheck_*(), ...           */
21 #include <asm/fixmap.h>                 /* VSYSCALL_ADDR                */
22 #include <asm/vsyscall.h>               /* emulate_vsyscall             */
23 #include <asm/vm86.h>                   /* struct vm86                  */
24
25 #define CREATE_TRACE_POINTS
26 #include <asm/trace/exceptions.h>
27
28 /*
29  * Page fault error code bits:
30  *
31  *   bit 0 ==    0: no page found       1: protection fault
32  *   bit 1 ==    0: read access         1: write access
33  *   bit 2 ==    0: kernel-mode access  1: user-mode access
34  *   bit 3 ==                           1: use of reserved bit detected
35  *   bit 4 ==                           1: fault was an instruction fetch
36  */
37 enum x86_pf_error_code {
38
39         PF_PROT         =               1 << 0,
40         PF_WRITE        =               1 << 1,
41         PF_USER         =               1 << 2,
42         PF_RSVD         =               1 << 3,
43         PF_INSTR        =               1 << 4,
44 };
45
46 /*
47  * Returns 0 if mmiotrace is disabled, or if the fault is not
48  * handled by mmiotrace:
49  */
50 static nokprobe_inline int
51 kmmio_fault(struct pt_regs *regs, unsigned long addr)
52 {
53         if (unlikely(is_kmmio_active()))
54                 if (kmmio_handler(regs, addr) == 1)
55                         return -1;
56         return 0;
57 }
58
59 static nokprobe_inline int kprobes_fault(struct pt_regs *regs)
60 {
61         int ret = 0;
62
63         /* kprobe_running() needs smp_processor_id() */
64         if (kprobes_built_in() && !user_mode(regs)) {
65                 preempt_disable();
66                 if (kprobe_running() && kprobe_fault_handler(regs, 14))
67                         ret = 1;
68                 preempt_enable();
69         }
70
71         return ret;
72 }
73
74 /*
75  * Prefetch quirks:
76  *
77  * 32-bit mode:
78  *
79  *   Sometimes AMD Athlon/Opteron CPUs report invalid exceptions on prefetch.
80  *   Check that here and ignore it.
81  *
82  * 64-bit mode:
83  *
84  *   Sometimes the CPU reports invalid exceptions on prefetch.
85  *   Check that here and ignore it.
86  *
87  * Opcode checker based on code by Richard Brunner.
88  */
89 static inline int
90 check_prefetch_opcode(struct pt_regs *regs, unsigned char *instr,
91                       unsigned char opcode, int *prefetch)
92 {
93         unsigned char instr_hi = opcode & 0xf0;
94         unsigned char instr_lo = opcode & 0x0f;
95
96         switch (instr_hi) {
97         case 0x20:
98         case 0x30:
99                 /*
100                  * Values 0x26,0x2E,0x36,0x3E are valid x86 prefixes.
101                  * In X86_64 long mode, the CPU will signal invalid
102                  * opcode if some of these prefixes are present so
103                  * X86_64 will never get here anyway
104                  */
105                 return ((instr_lo & 7) == 0x6);
106 #ifdef CONFIG_X86_64
107         case 0x40:
108                 /*
109                  * In AMD64 long mode 0x40..0x4F are valid REX prefixes
110                  * Need to figure out under what instruction mode the
111                  * instruction was issued. Could check the LDT for lm,
112                  * but for now it's good enough to assume that long
113                  * mode only uses well known segments or kernel.
114                  */
115                 return (!user_mode(regs) || user_64bit_mode(regs));
116 #endif
117         case 0x60:
118                 /* 0x64 thru 0x67 are valid prefixes in all modes. */
119                 return (instr_lo & 0xC) == 0x4;
120         case 0xF0:
121                 /* 0xF0, 0xF2, 0xF3 are valid prefixes in all modes. */
122                 return !instr_lo || (instr_lo>>1) == 1;
123         case 0x00:
124                 /* Prefetch instruction is 0x0F0D or 0x0F18 */
125                 if (probe_kernel_address(instr, opcode))
126                         return 0;
127
128                 *prefetch = (instr_lo == 0xF) &&
129                         (opcode == 0x0D || opcode == 0x18);
130                 return 0;
131         default:
132                 return 0;
133         }
134 }
135
136 static int
137 is_prefetch(struct pt_regs *regs, unsigned long error_code, unsigned long addr)
138 {
139         unsigned char *max_instr;
140         unsigned char *instr;
141         int prefetch = 0;
142
143         /*
144          * If it was a exec (instruction fetch) fault on NX page, then
145          * do not ignore the fault:
146          */
147         if (error_code & PF_INSTR)
148                 return 0;
149
150         instr = (void *)convert_ip_to_linear(current, regs);
151         max_instr = instr + 15;
152
153         if (user_mode(regs) && instr >= (unsigned char *)TASK_SIZE_MAX)
154                 return 0;
155
156         while (instr < max_instr) {
157                 unsigned char opcode;
158
159                 if (probe_kernel_address(instr, opcode))
160                         break;
161
162                 instr++;
163
164                 if (!check_prefetch_opcode(regs, instr, opcode, &prefetch))
165                         break;
166         }
167         return prefetch;
168 }
169
170 static void
171 force_sig_info_fault(int si_signo, int si_code, unsigned long address,
172                      struct task_struct *tsk, int fault)
173 {
174         unsigned lsb = 0;
175         siginfo_t info;
176
177         info.si_signo   = si_signo;
178         info.si_errno   = 0;
179         info.si_code    = si_code;
180         info.si_addr    = (void __user *)address;
181         if (fault & VM_FAULT_HWPOISON_LARGE)
182                 lsb = hstate_index_to_shift(VM_FAULT_GET_HINDEX(fault)); 
183         if (fault & VM_FAULT_HWPOISON)
184                 lsb = PAGE_SHIFT;
185         info.si_addr_lsb = lsb;
186
187         force_sig_info(si_signo, &info, tsk);
188 }
189
190 DEFINE_SPINLOCK(pgd_lock);
191 LIST_HEAD(pgd_list);
192
193 #ifdef CONFIG_X86_32
194 static inline pmd_t *vmalloc_sync_one(pgd_t *pgd, unsigned long address)
195 {
196         unsigned index = pgd_index(address);
197         pgd_t *pgd_k;
198         pud_t *pud, *pud_k;
199         pmd_t *pmd, *pmd_k;
200
201         pgd += index;
202         pgd_k = init_mm.pgd + index;
203
204         if (!pgd_present(*pgd_k))
205                 return NULL;
206
207         /*
208          * set_pgd(pgd, *pgd_k); here would be useless on PAE
209          * and redundant with the set_pmd() on non-PAE. As would
210          * set_pud.
211          */
212         pud = pud_offset(pgd, address);
213         pud_k = pud_offset(pgd_k, address);
214         if (!pud_present(*pud_k))
215                 return NULL;
216
217         pmd = pmd_offset(pud, address);
218         pmd_k = pmd_offset(pud_k, address);
219
220         if (pmd_present(*pmd) != pmd_present(*pmd_k))
221                 set_pmd(pmd, *pmd_k);
222
223         if (!pmd_present(*pmd_k))
224                 return NULL;
225         else
226                 BUG_ON(pmd_pfn(*pmd) != pmd_pfn(*pmd_k));
227
228         return pmd_k;
229 }
230
231 static void vmalloc_sync(void)
232 {
233         unsigned long address;
234
235         if (SHARED_KERNEL_PMD)
236                 return;
237
238         for (address = VMALLOC_START & PMD_MASK;
239              address >= TASK_SIZE && address < FIXADDR_TOP;
240              address += PMD_SIZE) {
241                 struct page *page;
242
243                 spin_lock(&pgd_lock);
244                 list_for_each_entry(page, &pgd_list, lru) {
245                         spinlock_t *pgt_lock;
246
247                         /* the pgt_lock only for Xen */
248                         pgt_lock = &pgd_page_get_mm(page)->page_table_lock;
249
250                         spin_lock(pgt_lock);
251                         vmalloc_sync_one(page_address(page), address);
252                         spin_unlock(pgt_lock);
253                 }
254                 spin_unlock(&pgd_lock);
255         }
256 }
257
258 void vmalloc_sync_mappings(void)
259 {
260         vmalloc_sync();
261 }
262
263 void vmalloc_sync_unmappings(void)
264 {
265         vmalloc_sync();
266 }
267
268 /*
269  * 32-bit:
270  *
271  *   Handle a fault on the vmalloc or module mapping area
272  */
273 static noinline int vmalloc_fault(unsigned long address)
274 {
275         unsigned long pgd_paddr;
276         pmd_t *pmd_k;
277         pte_t *pte_k;
278
279         /* Make sure we are in vmalloc area: */
280         if (!(address >= VMALLOC_START && address < VMALLOC_END))
281                 return -1;
282
283         /*
284          * Synchronize this task's top level page-table
285          * with the 'reference' page table.
286          *
287          * Do _not_ use "current" here. We might be inside
288          * an interrupt in the middle of a task switch..
289          */
290         pgd_paddr = read_cr3();
291         pmd_k = vmalloc_sync_one(__va(pgd_paddr), address);
292         if (!pmd_k)
293                 return -1;
294
295         if (pmd_large(*pmd_k))
296                 return 0;
297
298         pte_k = pte_offset_kernel(pmd_k, address);
299         if (!pte_present(*pte_k))
300                 return -1;
301
302         return 0;
303 }
304 NOKPROBE_SYMBOL(vmalloc_fault);
305
306 /*
307  * Did it hit the DOS screen memory VA from vm86 mode?
308  */
309 static inline void
310 check_v8086_mode(struct pt_regs *regs, unsigned long address,
311                  struct task_struct *tsk)
312 {
313 #ifdef CONFIG_VM86
314         unsigned long bit;
315
316         if (!v8086_mode(regs) || !tsk->thread.vm86)
317                 return;
318
319         bit = (address - 0xA0000) >> PAGE_SHIFT;
320         if (bit < 32)
321                 tsk->thread.vm86->screen_bitmap |= 1 << bit;
322 #endif
323 }
324
325 static bool low_pfn(unsigned long pfn)
326 {
327         return pfn < max_low_pfn;
328 }
329
330 static void dump_pagetable(unsigned long address)
331 {
332         pgd_t *base = __va(read_cr3());
333         pgd_t *pgd = &base[pgd_index(address)];
334         pmd_t *pmd;
335         pte_t *pte;
336
337 #ifdef CONFIG_X86_PAE
338         printk("*pdpt = %016Lx ", pgd_val(*pgd));
339         if (!low_pfn(pgd_val(*pgd) >> PAGE_SHIFT) || !pgd_present(*pgd))
340                 goto out;
341 #endif
342         pmd = pmd_offset(pud_offset(pgd, address), address);
343         printk(KERN_CONT "*pde = %0*Lx ", sizeof(*pmd) * 2, (u64)pmd_val(*pmd));
344
345         /*
346          * We must not directly access the pte in the highpte
347          * case if the page table is located in highmem.
348          * And let's rather not kmap-atomic the pte, just in case
349          * it's allocated already:
350          */
351         if (!low_pfn(pmd_pfn(*pmd)) || !pmd_present(*pmd) || pmd_large(*pmd))
352                 goto out;
353
354         pte = pte_offset_kernel(pmd, address);
355         printk("*pte = %0*Lx ", sizeof(*pte) * 2, (u64)pte_val(*pte));
356 out:
357         printk("\n");
358 }
359
360 #else /* CONFIG_X86_64: */
361
362 void vmalloc_sync_mappings(void)
363 {
364         /*
365          * 64-bit mappings might allocate new p4d/pud pages
366          * that need to be propagated to all tasks' PGDs.
367          */
368         sync_global_pgds(VMALLOC_START & PGDIR_MASK, VMALLOC_END, 0);
369 }
370
371 void vmalloc_sync_unmappings(void)
372 {
373         /*
374          * Unmappings never allocate or free p4d/pud pages.
375          * No work is required here.
376          */
377 }
378
379 /*
380  * 64-bit:
381  *
382  *   Handle a fault on the vmalloc area
383  */
384 static noinline int vmalloc_fault(unsigned long address)
385 {
386         pgd_t *pgd, *pgd_ref;
387         pud_t *pud, *pud_ref;
388         pmd_t *pmd, *pmd_ref;
389         pte_t *pte, *pte_ref;
390
391         /* Make sure we are in vmalloc area: */
392         if (!(address >= VMALLOC_START && address < VMALLOC_END))
393                 return -1;
394
395         /*
396          * Copy kernel mappings over when needed. This can also
397          * happen within a race in page table update. In the later
398          * case just flush:
399          */
400         pgd = pgd_offset(current->active_mm, address);
401         pgd_ref = pgd_offset_k(address);
402         if (pgd_none(*pgd_ref))
403                 return -1;
404
405         if (pgd_none(*pgd)) {
406                 set_pgd(pgd, *pgd_ref);
407                 arch_flush_lazy_mmu_mode();
408         } else {
409                 BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_ref));
410         }
411
412         /*
413          * Below here mismatches are bugs because these lower tables
414          * are shared:
415          */
416
417         pud = pud_offset(pgd, address);
418         pud_ref = pud_offset(pgd_ref, address);
419         if (pud_none(*pud_ref))
420                 return -1;
421
422         if (pud_none(*pud) || pud_pfn(*pud) != pud_pfn(*pud_ref))
423                 BUG();
424
425         if (pud_large(*pud))
426                 return 0;
427
428         pmd = pmd_offset(pud, address);
429         pmd_ref = pmd_offset(pud_ref, address);
430         if (pmd_none(*pmd_ref))
431                 return -1;
432
433         if (pmd_none(*pmd) || pmd_pfn(*pmd) != pmd_pfn(*pmd_ref))
434                 BUG();
435
436         if (pmd_large(*pmd))
437                 return 0;
438
439         pte_ref = pte_offset_kernel(pmd_ref, address);
440         if (!pte_present(*pte_ref))
441                 return -1;
442
443         pte = pte_offset_kernel(pmd, address);
444
445         /*
446          * Don't use pte_page here, because the mappings can point
447          * outside mem_map, and the NUMA hash lookup cannot handle
448          * that:
449          */
450         if (!pte_present(*pte) || pte_pfn(*pte) != pte_pfn(*pte_ref))
451                 BUG();
452
453         return 0;
454 }
455 NOKPROBE_SYMBOL(vmalloc_fault);
456
457 #ifdef CONFIG_CPU_SUP_AMD
458 static const char errata93_warning[] =
459 KERN_ERR 
460 "******* Your BIOS seems to not contain a fix for K8 errata #93\n"
461 "******* Working around it, but it may cause SEGVs or burn power.\n"
462 "******* Please consider a BIOS update.\n"
463 "******* Disabling USB legacy in the BIOS may also help.\n";
464 #endif
465
466 /*
467  * No vm86 mode in 64-bit mode:
468  */
469 static inline void
470 check_v8086_mode(struct pt_regs *regs, unsigned long address,
471                  struct task_struct *tsk)
472 {
473 }
474
475 static int bad_address(void *p)
476 {
477         unsigned long dummy;
478
479         return probe_kernel_address((unsigned long *)p, dummy);
480 }
481
482 static void dump_pagetable(unsigned long address)
483 {
484         pgd_t *base = __va(read_cr3() & PHYSICAL_PAGE_MASK);
485         pgd_t *pgd = base + pgd_index(address);
486         pud_t *pud;
487         pmd_t *pmd;
488         pte_t *pte;
489
490         if (bad_address(pgd))
491                 goto bad;
492
493         printk("PGD %lx ", pgd_val(*pgd));
494
495         if (!pgd_present(*pgd))
496                 goto out;
497
498         pud = pud_offset(pgd, address);
499         if (bad_address(pud))
500                 goto bad;
501
502         printk("PUD %lx ", pud_val(*pud));
503         if (!pud_present(*pud) || pud_large(*pud))
504                 goto out;
505
506         pmd = pmd_offset(pud, address);
507         if (bad_address(pmd))
508                 goto bad;
509
510         printk("PMD %lx ", pmd_val(*pmd));
511         if (!pmd_present(*pmd) || pmd_large(*pmd))
512                 goto out;
513
514         pte = pte_offset_kernel(pmd, address);
515         if (bad_address(pte))
516                 goto bad;
517
518         printk("PTE %lx", pte_val(*pte));
519 out:
520         printk("\n");
521         return;
522 bad:
523         printk("BAD\n");
524 }
525
526 #endif /* CONFIG_X86_64 */
527
528 /*
529  * Workaround for K8 erratum #93 & buggy BIOS.
530  *
531  * BIOS SMM functions are required to use a specific workaround
532  * to avoid corruption of the 64bit RIP register on C stepping K8.
533  *
534  * A lot of BIOS that didn't get tested properly miss this.
535  *
536  * The OS sees this as a page fault with the upper 32bits of RIP cleared.
537  * Try to work around it here.
538  *
539  * Note we only handle faults in kernel here.
540  * Does nothing on 32-bit.
541  */
542 static int is_errata93(struct pt_regs *regs, unsigned long address)
543 {
544 #if defined(CONFIG_X86_64) && defined(CONFIG_CPU_SUP_AMD)
545         if (boot_cpu_data.x86_vendor != X86_VENDOR_AMD
546             || boot_cpu_data.x86 != 0xf)
547                 return 0;
548
549         if (address != regs->ip)
550                 return 0;
551
552         if ((address >> 32) != 0)
553                 return 0;
554
555         address |= 0xffffffffUL << 32;
556         if ((address >= (u64)_stext && address <= (u64)_etext) ||
557             (address >= MODULES_VADDR && address <= MODULES_END)) {
558                 printk_once(errata93_warning);
559                 regs->ip = address;
560                 return 1;
561         }
562 #endif
563         return 0;
564 }
565
566 /*
567  * Work around K8 erratum #100 K8 in compat mode occasionally jumps
568  * to illegal addresses >4GB.
569  *
570  * We catch this in the page fault handler because these addresses
571  * are not reachable. Just detect this case and return.  Any code
572  * segment in LDT is compatibility mode.
573  */
574 static int is_errata100(struct pt_regs *regs, unsigned long address)
575 {
576 #ifdef CONFIG_X86_64
577         if ((regs->cs == __USER32_CS || (regs->cs & (1<<2))) && (address >> 32))
578                 return 1;
579 #endif
580         return 0;
581 }
582
583 static int is_f00f_bug(struct pt_regs *regs, unsigned long address)
584 {
585 #ifdef CONFIG_X86_F00F_BUG
586         unsigned long nr;
587
588         /*
589          * Pentium F0 0F C7 C8 bug workaround:
590          */
591         if (boot_cpu_has_bug(X86_BUG_F00F)) {
592                 nr = (address - idt_descr.address) >> 3;
593
594                 if (nr == 6) {
595                         do_invalid_op(regs, 0);
596                         return 1;
597                 }
598         }
599 #endif
600         return 0;
601 }
602
603 static const char nx_warning[] = KERN_CRIT
604 "kernel tried to execute NX-protected page - exploit attempt? (uid: %d)\n";
605 static const char smep_warning[] = KERN_CRIT
606 "unable to execute userspace code (SMEP?) (uid: %d)\n";
607
608 static void
609 show_fault_oops(struct pt_regs *regs, unsigned long error_code,
610                 unsigned long address)
611 {
612         if (!oops_may_print())
613                 return;
614
615         if (error_code & PF_INSTR) {
616                 unsigned int level;
617                 pgd_t *pgd;
618                 pte_t *pte;
619
620                 pgd = __va(read_cr3() & PHYSICAL_PAGE_MASK);
621                 pgd += pgd_index(address);
622
623                 pte = lookup_address_in_pgd(pgd, address, &level);
624
625                 if (pte && pte_present(*pte) && !pte_exec(*pte))
626                         printk(nx_warning, from_kuid(&init_user_ns, current_uid()));
627                 if (pte && pte_present(*pte) && pte_exec(*pte) &&
628                                 (pgd_flags(*pgd) & _PAGE_USER) &&
629                                 (__read_cr4() & X86_CR4_SMEP))
630                         printk(smep_warning, from_kuid(&init_user_ns, current_uid()));
631         }
632
633         printk(KERN_ALERT "BUG: unable to handle kernel ");
634         if (address < PAGE_SIZE)
635                 printk(KERN_CONT "NULL pointer dereference");
636         else
637                 printk(KERN_CONT "paging request");
638
639         printk(KERN_CONT " at %p\n", (void *) address);
640         printk(KERN_ALERT "IP:");
641         printk_address(regs->ip);
642
643         dump_pagetable(address);
644 }
645
646 static noinline void
647 pgtable_bad(struct pt_regs *regs, unsigned long error_code,
648             unsigned long address)
649 {
650         struct task_struct *tsk;
651         unsigned long flags;
652         int sig;
653
654         flags = oops_begin();
655         tsk = current;
656         sig = SIGKILL;
657
658         printk(KERN_ALERT "%s: Corrupted page table at address %lx\n",
659                tsk->comm, address);
660         dump_pagetable(address);
661
662         tsk->thread.cr2         = address;
663         tsk->thread.trap_nr     = X86_TRAP_PF;
664         tsk->thread.error_code  = error_code;
665
666         if (__die("Bad pagetable", regs, error_code))
667                 sig = 0;
668
669         oops_end(flags, regs, sig);
670 }
671
672 static noinline void
673 no_context(struct pt_regs *regs, unsigned long error_code,
674            unsigned long address, int signal, int si_code)
675 {
676         struct task_struct *tsk = current;
677         unsigned long flags;
678         int sig;
679
680         /* Are we prepared to handle this kernel fault? */
681         if (fixup_exception(regs)) {
682                 /*
683                  * Any interrupt that takes a fault gets the fixup. This makes
684                  * the below recursive fault logic only apply to a faults from
685                  * task context.
686                  */
687                 if (in_interrupt())
688                         return;
689
690                 /*
691                  * Per the above we're !in_interrupt(), aka. task context.
692                  *
693                  * In this case we need to make sure we're not recursively
694                  * faulting through the emulate_vsyscall() logic.
695                  */
696                 if (current_thread_info()->sig_on_uaccess_error && signal) {
697                         tsk->thread.trap_nr = X86_TRAP_PF;
698                         tsk->thread.error_code = error_code | PF_USER;
699                         tsk->thread.cr2 = address;
700
701                         /* XXX: hwpoison faults will set the wrong code. */
702                         force_sig_info_fault(signal, si_code, address, tsk, 0);
703                 }
704
705                 /*
706                  * Barring that, we can do the fixup and be happy.
707                  */
708                 return;
709         }
710
711         /*
712          * 32-bit:
713          *
714          *   Valid to do another page fault here, because if this fault
715          *   had been triggered by is_prefetch fixup_exception would have
716          *   handled it.
717          *
718          * 64-bit:
719          *
720          *   Hall of shame of CPU/BIOS bugs.
721          */
722         if (is_prefetch(regs, error_code, address))
723                 return;
724
725         if (is_errata93(regs, address))
726                 return;
727
728         /*
729          * Oops. The kernel tried to access some bad page. We'll have to
730          * terminate things with extreme prejudice:
731          */
732         flags = oops_begin();
733
734         show_fault_oops(regs, error_code, address);
735
736         if (task_stack_end_corrupted(tsk))
737                 printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
738
739         tsk->thread.cr2         = address;
740         tsk->thread.trap_nr     = X86_TRAP_PF;
741         tsk->thread.error_code  = error_code;
742
743         sig = SIGKILL;
744         if (__die("Oops", regs, error_code))
745                 sig = 0;
746
747         /* Executive summary in case the body of the oops scrolled away */
748         printk(KERN_DEFAULT "CR2: %016lx\n", address);
749
750         oops_end(flags, regs, sig);
751 }
752
753 /*
754  * Print out info about fatal segfaults, if the show_unhandled_signals
755  * sysctl is set:
756  */
757 static inline void
758 show_signal_msg(struct pt_regs *regs, unsigned long error_code,
759                 unsigned long address, struct task_struct *tsk)
760 {
761         if (!unhandled_signal(tsk, SIGSEGV))
762                 return;
763
764         if (!printk_ratelimit())
765                 return;
766
767         printk("%s%s[%d]: segfault at %lx ip %p sp %p error %lx",
768                 task_pid_nr(tsk) > 1 ? KERN_INFO : KERN_EMERG,
769                 tsk->comm, task_pid_nr(tsk), address,
770                 (void *)regs->ip, (void *)regs->sp, error_code);
771
772         print_vma_addr(KERN_CONT " in ", regs->ip);
773
774         printk(KERN_CONT "\n");
775 }
776
777 static void
778 __bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
779                        unsigned long address, int si_code)
780 {
781         struct task_struct *tsk = current;
782
783         /* User mode accesses just cause a SIGSEGV */
784         if (error_code & PF_USER) {
785                 /*
786                  * It's possible to have interrupts off here:
787                  */
788                 local_irq_enable();
789
790                 /*
791                  * Valid to do another page fault here because this one came
792                  * from user space:
793                  */
794                 if (is_prefetch(regs, error_code, address))
795                         return;
796
797                 if (is_errata100(regs, address))
798                         return;
799
800 #ifdef CONFIG_X86_64
801                 /*
802                  * Instruction fetch faults in the vsyscall page might need
803                  * emulation.
804                  */
805                 if (unlikely((error_code & PF_INSTR) &&
806                              ((address & ~0xfff) == VSYSCALL_ADDR))) {
807                         if (emulate_vsyscall(regs, address))
808                                 return;
809                 }
810 #endif
811                 /* Kernel addresses are always protection faults: */
812                 if (address >= TASK_SIZE)
813                         error_code |= PF_PROT;
814
815                 if (likely(show_unhandled_signals))
816                         show_signal_msg(regs, error_code, address, tsk);
817
818                 tsk->thread.cr2         = address;
819                 tsk->thread.error_code  = error_code;
820                 tsk->thread.trap_nr     = X86_TRAP_PF;
821
822                 force_sig_info_fault(SIGSEGV, si_code, address, tsk, 0);
823
824                 return;
825         }
826
827         if (is_f00f_bug(regs, address))
828                 return;
829
830         no_context(regs, error_code, address, SIGSEGV, si_code);
831 }
832
833 static noinline void
834 bad_area_nosemaphore(struct pt_regs *regs, unsigned long error_code,
835                      unsigned long address)
836 {
837         __bad_area_nosemaphore(regs, error_code, address, SEGV_MAPERR);
838 }
839
840 static void
841 __bad_area(struct pt_regs *regs, unsigned long error_code,
842            unsigned long address, int si_code)
843 {
844         struct mm_struct *mm = current->mm;
845
846         /*
847          * Something tried to access memory that isn't in our memory map..
848          * Fix it, but check if it's kernel or user first..
849          */
850         up_read(&mm->mmap_sem);
851
852         __bad_area_nosemaphore(regs, error_code, address, si_code);
853 }
854
855 static noinline void
856 bad_area(struct pt_regs *regs, unsigned long error_code, unsigned long address)
857 {
858         __bad_area(regs, error_code, address, SEGV_MAPERR);
859 }
860
861 static noinline void
862 bad_area_access_error(struct pt_regs *regs, unsigned long error_code,
863                       unsigned long address)
864 {
865         __bad_area(regs, error_code, address, SEGV_ACCERR);
866 }
867
868 static void
869 do_sigbus(struct pt_regs *regs, unsigned long error_code, unsigned long address,
870           unsigned int fault)
871 {
872         struct task_struct *tsk = current;
873         int code = BUS_ADRERR;
874
875         /* Kernel mode? Handle exceptions or die: */
876         if (!(error_code & PF_USER)) {
877                 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
878                 return;
879         }
880
881         /* User-space => ok to do another page fault: */
882         if (is_prefetch(regs, error_code, address))
883                 return;
884
885         tsk->thread.cr2         = address;
886         tsk->thread.error_code  = error_code;
887         tsk->thread.trap_nr     = X86_TRAP_PF;
888
889 #ifdef CONFIG_MEMORY_FAILURE
890         if (fault & (VM_FAULT_HWPOISON|VM_FAULT_HWPOISON_LARGE)) {
891                 printk(KERN_ERR
892         "MCE: Killing %s:%d due to hardware memory corruption fault at %lx\n",
893                         tsk->comm, tsk->pid, address);
894                 code = BUS_MCEERR_AR;
895         }
896 #endif
897         force_sig_info_fault(SIGBUS, code, address, tsk, fault);
898 }
899
900 static noinline void
901 mm_fault_error(struct pt_regs *regs, unsigned long error_code,
902                unsigned long address, unsigned int fault)
903 {
904         if (fatal_signal_pending(current) && !(error_code & PF_USER)) {
905                 no_context(regs, error_code, address, 0, 0);
906                 return;
907         }
908
909         if (fault & VM_FAULT_OOM) {
910                 /* Kernel mode? Handle exceptions or die: */
911                 if (!(error_code & PF_USER)) {
912                         no_context(regs, error_code, address,
913                                    SIGSEGV, SEGV_MAPERR);
914                         return;
915                 }
916
917                 /*
918                  * We ran out of memory, call the OOM killer, and return the
919                  * userspace (which will retry the fault, or kill us if we got
920                  * oom-killed):
921                  */
922                 pagefault_out_of_memory();
923         } else {
924                 if (fault & (VM_FAULT_SIGBUS|VM_FAULT_HWPOISON|
925                              VM_FAULT_HWPOISON_LARGE))
926                         do_sigbus(regs, error_code, address, fault);
927                 else if (fault & VM_FAULT_SIGSEGV)
928                         bad_area_nosemaphore(regs, error_code, address);
929                 else
930                         BUG();
931         }
932 }
933
934 static int spurious_fault_check(unsigned long error_code, pte_t *pte)
935 {
936         if ((error_code & PF_WRITE) && !pte_write(*pte))
937                 return 0;
938
939         if ((error_code & PF_INSTR) && !pte_exec(*pte))
940                 return 0;
941
942         return 1;
943 }
944
945 /*
946  * Handle a spurious fault caused by a stale TLB entry.
947  *
948  * This allows us to lazily refresh the TLB when increasing the
949  * permissions of a kernel page (RO -> RW or NX -> X).  Doing it
950  * eagerly is very expensive since that implies doing a full
951  * cross-processor TLB flush, even if no stale TLB entries exist
952  * on other processors.
953  *
954  * Spurious faults may only occur if the TLB contains an entry with
955  * fewer permission than the page table entry.  Non-present (P = 0)
956  * and reserved bit (R = 1) faults are never spurious.
957  *
958  * There are no security implications to leaving a stale TLB when
959  * increasing the permissions on a page.
960  *
961  * Returns non-zero if a spurious fault was handled, zero otherwise.
962  *
963  * See Intel Developer's Manual Vol 3 Section 4.10.4.3, bullet 3
964  * (Optional Invalidation).
965  */
966 static noinline int
967 spurious_fault(unsigned long error_code, unsigned long address)
968 {
969         pgd_t *pgd;
970         pud_t *pud;
971         pmd_t *pmd;
972         pte_t *pte;
973         int ret;
974
975         /*
976          * Only writes to RO or instruction fetches from NX may cause
977          * spurious faults.
978          *
979          * These could be from user or supervisor accesses but the TLB
980          * is only lazily flushed after a kernel mapping protection
981          * change, so user accesses are not expected to cause spurious
982          * faults.
983          */
984         if (error_code != (PF_WRITE | PF_PROT)
985             && error_code != (PF_INSTR | PF_PROT))
986                 return 0;
987
988         pgd = init_mm.pgd + pgd_index(address);
989         if (!pgd_present(*pgd))
990                 return 0;
991
992         pud = pud_offset(pgd, address);
993         if (!pud_present(*pud))
994                 return 0;
995
996         if (pud_large(*pud))
997                 return spurious_fault_check(error_code, (pte_t *) pud);
998
999         pmd = pmd_offset(pud, address);
1000         if (!pmd_present(*pmd))
1001                 return 0;
1002
1003         if (pmd_large(*pmd))
1004                 return spurious_fault_check(error_code, (pte_t *) pmd);
1005
1006         pte = pte_offset_kernel(pmd, address);
1007         if (!pte_present(*pte))
1008                 return 0;
1009
1010         ret = spurious_fault_check(error_code, pte);
1011         if (!ret)
1012                 return 0;
1013
1014         /*
1015          * Make sure we have permissions in PMD.
1016          * If not, then there's a bug in the page tables:
1017          */
1018         ret = spurious_fault_check(error_code, (pte_t *) pmd);
1019         WARN_ONCE(!ret, "PMD has incorrect permission bits\n");
1020
1021         return ret;
1022 }
1023 NOKPROBE_SYMBOL(spurious_fault);
1024
1025 int show_unhandled_signals = 1;
1026
1027 static inline int
1028 access_error(unsigned long error_code, struct vm_area_struct *vma)
1029 {
1030         if (error_code & PF_WRITE) {
1031                 /* write, present and write, not present: */
1032                 if (unlikely(!(vma->vm_flags & VM_WRITE)))
1033                         return 1;
1034                 return 0;
1035         }
1036
1037         /* read, present: */
1038         if (unlikely(error_code & PF_PROT))
1039                 return 1;
1040
1041         /* read, not present: */
1042         if (unlikely(!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))))
1043                 return 1;
1044
1045         return 0;
1046 }
1047
1048 static int fault_in_kernel_space(unsigned long address)
1049 {
1050         return address >= TASK_SIZE_MAX;
1051 }
1052
1053 static inline bool smap_violation(int error_code, struct pt_regs *regs)
1054 {
1055         if (!IS_ENABLED(CONFIG_X86_SMAP))
1056                 return false;
1057
1058         if (!static_cpu_has(X86_FEATURE_SMAP))
1059                 return false;
1060
1061         if (error_code & PF_USER)
1062                 return false;
1063
1064         if (!user_mode(regs) && (regs->flags & X86_EFLAGS_AC))
1065                 return false;
1066
1067         return true;
1068 }
1069
1070 /*
1071  * This routine handles page faults.  It determines the address,
1072  * and the problem, and then passes it off to one of the appropriate
1073  * routines.
1074  *
1075  * This function must have noinline because both callers
1076  * {,trace_}do_page_fault() have notrace on. Having this an actual function
1077  * guarantees there's a function trace entry.
1078  */
1079 static noinline void
1080 __do_page_fault(struct pt_regs *regs, unsigned long error_code,
1081                 unsigned long address)
1082 {
1083         struct vm_area_struct *vma;
1084         struct task_struct *tsk;
1085         struct mm_struct *mm;
1086         int fault, major = 0;
1087         unsigned int flags = FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_KILLABLE;
1088
1089         tsk = current;
1090         mm = tsk->mm;
1091
1092         /*
1093          * Detect and handle instructions that would cause a page fault for
1094          * both a tracked kernel page and a userspace page.
1095          */
1096         if (kmemcheck_active(regs))
1097                 kmemcheck_hide(regs);
1098         prefetchw(&mm->mmap_sem);
1099
1100         if (unlikely(kmmio_fault(regs, address)))
1101                 return;
1102
1103         /*
1104          * We fault-in kernel-space virtual memory on-demand. The
1105          * 'reference' page table is init_mm.pgd.
1106          *
1107          * NOTE! We MUST NOT take any locks for this case. We may
1108          * be in an interrupt or a critical region, and should
1109          * only copy the information from the master page table,
1110          * nothing more.
1111          *
1112          * This verifies that the fault happens in kernel space
1113          * (error_code & 4) == 0, and that the fault was not a
1114          * protection error (error_code & 9) == 0.
1115          */
1116         if (unlikely(fault_in_kernel_space(address))) {
1117                 if (!(error_code & (PF_RSVD | PF_USER | PF_PROT))) {
1118                         if (vmalloc_fault(address) >= 0)
1119                                 return;
1120
1121                         if (kmemcheck_fault(regs, address, error_code))
1122                                 return;
1123                 }
1124
1125                 /* Can handle a stale RO->RW TLB: */
1126                 if (spurious_fault(error_code, address))
1127                         return;
1128
1129                 /* kprobes don't want to hook the spurious faults: */
1130                 if (kprobes_fault(regs))
1131                         return;
1132                 /*
1133                  * Don't take the mm semaphore here. If we fixup a prefetch
1134                  * fault we could otherwise deadlock:
1135                  */
1136                 bad_area_nosemaphore(regs, error_code, address);
1137
1138                 return;
1139         }
1140
1141         /* kprobes don't want to hook the spurious faults: */
1142         if (unlikely(kprobes_fault(regs)))
1143                 return;
1144
1145         if (unlikely(error_code & PF_RSVD))
1146                 pgtable_bad(regs, error_code, address);
1147
1148         if (unlikely(smap_violation(error_code, regs))) {
1149                 bad_area_nosemaphore(regs, error_code, address);
1150                 return;
1151         }
1152
1153         /*
1154          * If we're in an interrupt, have no user context or are running
1155          * in a region with pagefaults disabled then we must not take the fault
1156          */
1157         if (unlikely(faulthandler_disabled() || !mm)) {
1158                 bad_area_nosemaphore(regs, error_code, address);
1159                 return;
1160         }
1161
1162         /*
1163          * It's safe to allow irq's after cr2 has been saved and the
1164          * vmalloc fault has been handled.
1165          *
1166          * User-mode registers count as a user access even for any
1167          * potential system fault or CPU buglet:
1168          */
1169         if (user_mode(regs)) {
1170                 local_irq_enable();
1171                 error_code |= PF_USER;
1172                 flags |= FAULT_FLAG_USER;
1173         } else {
1174                 if (regs->flags & X86_EFLAGS_IF)
1175                         local_irq_enable();
1176         }
1177
1178         perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, address);
1179
1180         if (error_code & PF_WRITE)
1181                 flags |= FAULT_FLAG_WRITE;
1182
1183         /*
1184          * When running in the kernel we expect faults to occur only to
1185          * addresses in user space.  All other faults represent errors in
1186          * the kernel and should generate an OOPS.  Unfortunately, in the
1187          * case of an erroneous fault occurring in a code path which already
1188          * holds mmap_sem we will deadlock attempting to validate the fault
1189          * against the address space.  Luckily the kernel only validly
1190          * references user space from well defined areas of code, which are
1191          * listed in the exceptions table.
1192          *
1193          * As the vast majority of faults will be valid we will only perform
1194          * the source reference check when there is a possibility of a
1195          * deadlock. Attempt to lock the address space, if we cannot we then
1196          * validate the source. If this is invalid we can skip the address
1197          * space check, thus avoiding the deadlock:
1198          */
1199         if (unlikely(!down_read_trylock(&mm->mmap_sem))) {
1200                 if ((error_code & PF_USER) == 0 &&
1201                     !search_exception_tables(regs->ip)) {
1202                         bad_area_nosemaphore(regs, error_code, address);
1203                         return;
1204                 }
1205 retry:
1206                 down_read(&mm->mmap_sem);
1207         } else {
1208                 /*
1209                  * The above down_read_trylock() might have succeeded in
1210                  * which case we'll have missed the might_sleep() from
1211                  * down_read():
1212                  */
1213                 might_sleep();
1214         }
1215
1216         vma = find_vma(mm, address);
1217         if (unlikely(!vma)) {
1218                 bad_area(regs, error_code, address);
1219                 return;
1220         }
1221         if (likely(vma->vm_start <= address))
1222                 goto good_area;
1223         if (unlikely(!(vma->vm_flags & VM_GROWSDOWN))) {
1224                 bad_area(regs, error_code, address);
1225                 return;
1226         }
1227         if (error_code & PF_USER) {
1228                 /*
1229                  * Accessing the stack below %sp is always a bug.
1230                  * The large cushion allows instructions like enter
1231                  * and pusha to work. ("enter $65535, $31" pushes
1232                  * 32 pointers and then decrements %sp by 65535.)
1233                  */
1234                 if (unlikely(address + 65536 + 32 * sizeof(unsigned long) < regs->sp)) {
1235                         bad_area(regs, error_code, address);
1236                         return;
1237                 }
1238         }
1239         if (unlikely(expand_stack(vma, address))) {
1240                 bad_area(regs, error_code, address);
1241                 return;
1242         }
1243
1244         /*
1245          * Ok, we have a good vm_area for this memory access, so
1246          * we can handle it..
1247          */
1248 good_area:
1249         if (unlikely(access_error(error_code, vma))) {
1250                 bad_area_access_error(regs, error_code, address);
1251                 return;
1252         }
1253
1254         /*
1255          * If for any reason at all we couldn't handle the fault,
1256          * make sure we exit gracefully rather than endlessly redo
1257          * the fault.  Since we never set FAULT_FLAG_RETRY_NOWAIT, if
1258          * we get VM_FAULT_RETRY back, the mmap_sem has been unlocked.
1259          */
1260         fault = handle_mm_fault(mm, vma, address, flags);
1261         major |= fault & VM_FAULT_MAJOR;
1262
1263         /*
1264          * If we need to retry the mmap_sem has already been released,
1265          * and if there is a fatal signal pending there is no guarantee
1266          * that we made any progress. Handle this case first.
1267          */
1268         if (unlikely(fault & VM_FAULT_RETRY)) {
1269                 /* Retry at most once */
1270                 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1271                         flags &= ~FAULT_FLAG_ALLOW_RETRY;
1272                         flags |= FAULT_FLAG_TRIED;
1273                         if (!fatal_signal_pending(tsk))
1274                                 goto retry;
1275                 }
1276
1277                 /* User mode? Just return to handle the fatal exception */
1278                 if (flags & FAULT_FLAG_USER)
1279                         return;
1280
1281                 /* Not returning to user mode? Handle exceptions or die: */
1282                 no_context(regs, error_code, address, SIGBUS, BUS_ADRERR);
1283                 return;
1284         }
1285
1286         up_read(&mm->mmap_sem);
1287         if (unlikely(fault & VM_FAULT_ERROR)) {
1288                 mm_fault_error(regs, error_code, address, fault);
1289                 return;
1290         }
1291
1292         /*
1293          * Major/minor page fault accounting. If any of the events
1294          * returned VM_FAULT_MAJOR, we account it as a major fault.
1295          */
1296         if (major) {
1297                 tsk->maj_flt++;
1298                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
1299         } else {
1300                 tsk->min_flt++;
1301                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
1302         }
1303
1304         check_v8086_mode(regs, address, tsk);
1305 }
1306 NOKPROBE_SYMBOL(__do_page_fault);
1307
1308 dotraplinkage void notrace
1309 do_page_fault(struct pt_regs *regs, unsigned long error_code)
1310 {
1311         unsigned long address = read_cr2(); /* Get the faulting address */
1312         enum ctx_state prev_state;
1313
1314         /*
1315          * We must have this function tagged with __kprobes, notrace and call
1316          * read_cr2() before calling anything else. To avoid calling any kind
1317          * of tracing machinery before we've observed the CR2 value.
1318          *
1319          * exception_{enter,exit}() contain all sorts of tracepoints.
1320          */
1321
1322         prev_state = exception_enter();
1323         __do_page_fault(regs, error_code, address);
1324         exception_exit(prev_state);
1325 }
1326 NOKPROBE_SYMBOL(do_page_fault);
1327
1328 #ifdef CONFIG_TRACING
1329 static nokprobe_inline void
1330 trace_page_fault_entries(unsigned long address, struct pt_regs *regs,
1331                          unsigned long error_code)
1332 {
1333         if (user_mode(regs))
1334                 trace_page_fault_user(address, regs, error_code);
1335         else
1336                 trace_page_fault_kernel(address, regs, error_code);
1337 }
1338
1339 dotraplinkage void notrace
1340 trace_do_page_fault(struct pt_regs *regs, unsigned long error_code)
1341 {
1342         /*
1343          * The exception_enter and tracepoint processing could
1344          * trigger another page faults (user space callchain
1345          * reading) and destroy the original cr2 value, so read
1346          * the faulting address now.
1347          */
1348         unsigned long address = read_cr2();
1349         enum ctx_state prev_state;
1350
1351         prev_state = exception_enter();
1352         trace_page_fault_entries(address, regs, error_code);
1353         __do_page_fault(regs, error_code, address);
1354         exception_exit(prev_state);
1355 }
1356 NOKPROBE_SYMBOL(trace_do_page_fault);
1357 #endif /* CONFIG_TRACING */