1 /*
2 * Copyright (C) 1991, 1992 Linus Torvalds
3 * Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
4 *
5 * Pentium III FXSR, SSE support
6 * Gareth Hughes <gareth@valinux.com>, May 2000
7 */
8
9 /*
10 * Handle hardware traps and faults.
11 */
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/context_tracking.h>
16 #include <linux/interrupt.h>
17 #include <linux/kallsyms.h>
18 #include <linux/kmsan.h>
19 #include <linux/spinlock.h>
20 #include <linux/kprobes.h>
21 #include <linux/uaccess.h>
22 #include <linux/kdebug.h>
23 #include <linux/kgdb.h>
24 #include <linux/kernel.h>
25 #include <linux/export.h>
26 #include <linux/ptrace.h>
27 #include <linux/uprobes.h>
28 #include <linux/string.h>
29 #include <linux/delay.h>
30 #include <linux/errno.h>
31 #include <linux/kexec.h>
32 #include <linux/sched.h>
33 #include <linux/sched/task_stack.h>
34 #include <linux/timer.h>
35 #include <linux/init.h>
36 #include <linux/bug.h>
37 #include <linux/nmi.h>
38 #include <linux/mm.h>
39 #include <linux/smp.h>
40 #include <linux/cpu.h>
41 #include <linux/io.h>
42 #include <linux/hardirq.h>
43 #include <linux/atomic.h>
44 #include <linux/iommu.h>
45 #include <linux/ubsan.h>
46
47 #include <asm/stacktrace.h>
48 #include <asm/processor.h>
49 #include <asm/debugreg.h>
50 #include <asm/realmode.h>
51 #include <asm/text-patching.h>
52 #include <asm/ftrace.h>
53 #include <asm/traps.h>
54 #include <asm/desc.h>
55 #include <asm/fred.h>
56 #include <asm/fpu/api.h>
57 #include <asm/cpu.h>
58 #include <asm/cpu_entry_area.h>
59 #include <asm/mce.h>
60 #include <asm/fixmap.h>
61 #include <asm/mach_traps.h>
62 #include <asm/alternative.h>
63 #include <asm/fpu/xstate.h>
64 #include <asm/vm86.h>
65 #include <asm/umip.h>
66 #include <asm/insn.h>
67 #include <asm/insn-eval.h>
68 #include <asm/vdso.h>
69 #include <asm/tdx.h>
70 #include <asm/cfi.h>
71
72 #ifdef CONFIG_X86_64
73 #include <asm/x86_init.h>
74 #else
75 #include <asm/processor-flags.h>
76 #include <asm/setup.h>
77 #endif
78
79 #include <asm/proto.h>
80
81 DECLARE_BITMAP(system_vectors, NR_VECTORS);
82
is_valid_bugaddr(unsigned long addr)83 __always_inline int is_valid_bugaddr(unsigned long addr)
84 {
85 if (addr < TASK_SIZE_MAX)
86 return 0;
87
88 /*
89 * We got #UD, if the text isn't readable we'd have gotten
90 * a different exception.
91 */
92 return *(unsigned short *)addr == INSN_UD2;
93 }
94
95 /*
96 * Check for UD1 or UD2, accounting for Address Size Override Prefixes.
97 * If it's a UD1, further decode to determine its use:
98 *
99 * FineIBT: ea (bad)
100 * FineIBT: f0 75 f9 lock jne . - 6
101 * UBSan{0}: 67 0f b9 00 ud1 (%eax),%eax
102 * UBSan{10}: 67 0f b9 40 10 ud1 0x10(%eax),%eax
103 * static_call: 0f b9 cc ud1 %esp,%ecx
104 *
105 * Notably UBSAN uses EAX, static_call uses ECX.
106 */
decode_bug(unsigned long addr,s32 * imm,int * len)107 __always_inline int decode_bug(unsigned long addr, s32 *imm, int *len)
108 {
109 unsigned long start = addr;
110 bool lock = false;
111 u8 v;
112
113 if (addr < TASK_SIZE_MAX)
114 return BUG_NONE;
115
116 v = *(u8 *)(addr++);
117 if (v == INSN_ASOP)
118 v = *(u8 *)(addr++);
119
120 if (v == INSN_LOCK) {
121 lock = true;
122 v = *(u8 *)(addr++);
123 }
124
125 switch (v) {
126 case 0x70 ... 0x7f: /* Jcc.d8 */
127 addr += 1; /* d8 */
128 *len = addr - start;
129 WARN_ON_ONCE(!lock);
130 return BUG_LOCK;
131
132 case 0xea:
133 *len = addr - start;
134 return BUG_EA;
135
136 case OPCODE_ESCAPE:
137 break;
138
139 default:
140 return BUG_NONE;
141 }
142
143 v = *(u8 *)(addr++);
144 if (v == SECOND_BYTE_OPCODE_UD2) {
145 *len = addr - start;
146 return BUG_UD2;
147 }
148
149 if (v != SECOND_BYTE_OPCODE_UD1)
150 return BUG_NONE;
151
152 *imm = 0;
153 v = *(u8 *)(addr++); /* ModRM */
154
155 if (X86_MODRM_MOD(v) != 3 && X86_MODRM_RM(v) == 4)
156 addr++; /* SIB */
157
158 /* Decode immediate, if present */
159 switch (X86_MODRM_MOD(v)) {
160 case 0: if (X86_MODRM_RM(v) == 5)
161 addr += 4; /* RIP + disp32 */
162 break;
163
164 case 1: *imm = *(s8 *)addr;
165 addr += 1;
166 break;
167
168 case 2: *imm = *(s32 *)addr;
169 addr += 4;
170 break;
171
172 case 3: break;
173 }
174
175 /* record instruction length */
176 *len = addr - start;
177
178 if (X86_MODRM_REG(v) == 0) /* EAX */
179 return BUG_UD1_UBSAN;
180
181 return BUG_UD1;
182 }
183
184
185 static nokprobe_inline int
do_trap_no_signal(struct task_struct * tsk,int trapnr,const char * str,struct pt_regs * regs,long error_code)186 do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str,
187 struct pt_regs *regs, long error_code)
188 {
189 if (v8086_mode(regs)) {
190 /*
191 * Traps 0, 1, 3, 4, and 5 should be forwarded to vm86.
192 * On nmi (interrupt 2), do_trap should not be called.
193 */
194 if (trapnr < X86_TRAP_UD) {
195 if (!handle_vm86_trap((struct kernel_vm86_regs *) regs,
196 error_code, trapnr))
197 return 0;
198 }
199 } else if (!user_mode(regs)) {
200 if (fixup_exception(regs, trapnr, error_code, 0))
201 return 0;
202
203 tsk->thread.error_code = error_code;
204 tsk->thread.trap_nr = trapnr;
205 die(str, regs, error_code);
206 } else {
207 if (fixup_vdso_exception(regs, trapnr, error_code, 0))
208 return 0;
209 }
210
211 /*
212 * We want error_code and trap_nr set for userspace faults and
213 * kernelspace faults which result in die(), but not
214 * kernelspace faults which are fixed up. die() gives the
215 * process no chance to handle the signal and notice the
216 * kernel fault information, so that won't result in polluting
217 * the information about previously queued, but not yet
218 * delivered, faults. See also exc_general_protection below.
219 */
220 tsk->thread.error_code = error_code;
221 tsk->thread.trap_nr = trapnr;
222
223 return -1;
224 }
225
show_signal(struct task_struct * tsk,int signr,const char * type,const char * desc,struct pt_regs * regs,long error_code)226 static void show_signal(struct task_struct *tsk, int signr,
227 const char *type, const char *desc,
228 struct pt_regs *regs, long error_code)
229 {
230 if (show_unhandled_signals && unhandled_signal(tsk, signr) &&
231 printk_ratelimit()) {
232 pr_info("%s[%d] %s%s ip:%lx sp:%lx error:%lx",
233 tsk->comm, task_pid_nr(tsk), type, desc,
234 regs->ip, regs->sp, error_code);
235 print_vma_addr(KERN_CONT " in ", regs->ip);
236 pr_cont("\n");
237 }
238 }
239
240 static void
do_trap(int trapnr,int signr,char * str,struct pt_regs * regs,long error_code,int sicode,void __user * addr)241 do_trap(int trapnr, int signr, char *str, struct pt_regs *regs,
242 long error_code, int sicode, void __user *addr)
243 {
244 struct task_struct *tsk = current;
245
246 if (!do_trap_no_signal(tsk, trapnr, str, regs, error_code))
247 return;
248
249 show_signal(tsk, signr, "trap ", str, regs, error_code);
250
251 if (!sicode)
252 force_sig(signr);
253 else
254 force_sig_fault(signr, sicode, addr);
255 }
256 NOKPROBE_SYMBOL(do_trap);
257
do_error_trap(struct pt_regs * regs,long error_code,char * str,unsigned long trapnr,int signr,int sicode,void __user * addr)258 static void do_error_trap(struct pt_regs *regs, long error_code, char *str,
259 unsigned long trapnr, int signr, int sicode, void __user *addr)
260 {
261 RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
262
263 if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) !=
264 NOTIFY_STOP) {
265 cond_local_irq_enable(regs);
266 do_trap(trapnr, signr, str, regs, error_code, sicode, addr);
267 cond_local_irq_disable(regs);
268 }
269 }
270
271 /*
272 * Posix requires to provide the address of the faulting instruction for
273 * SIGILL (#UD) and SIGFPE (#DE) in the si_addr member of siginfo_t.
274 *
275 * This address is usually regs->ip, but when an uprobe moved the code out
276 * of line then regs->ip points to the XOL code which would confuse
277 * anything which analyzes the fault address vs. the unmodified binary. If
278 * a trap happened in XOL code then uprobe maps regs->ip back to the
279 * original instruction address.
280 */
error_get_trap_addr(struct pt_regs * regs)281 static __always_inline void __user *error_get_trap_addr(struct pt_regs *regs)
282 {
283 return (void __user *)uprobe_get_trap_addr(regs);
284 }
285
DEFINE_IDTENTRY(exc_divide_error)286 DEFINE_IDTENTRY(exc_divide_error)
287 {
288 do_error_trap(regs, 0, "divide error", X86_TRAP_DE, SIGFPE,
289 FPE_INTDIV, error_get_trap_addr(regs));
290 }
291
DEFINE_IDTENTRY(exc_overflow)292 DEFINE_IDTENTRY(exc_overflow)
293 {
294 do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0, NULL);
295 }
296
297 #ifdef CONFIG_X86_F00F_BUG
handle_invalid_op(struct pt_regs * regs)298 void handle_invalid_op(struct pt_regs *regs)
299 #else
300 static inline void handle_invalid_op(struct pt_regs *regs)
301 #endif
302 {
303 do_error_trap(regs, 0, "invalid opcode", X86_TRAP_UD, SIGILL,
304 ILL_ILLOPN, error_get_trap_addr(regs));
305 }
306
handle_bug(struct pt_regs * regs)307 static noinstr bool handle_bug(struct pt_regs *regs)
308 {
309 unsigned long addr = regs->ip;
310 bool handled = false;
311 int ud_type, ud_len;
312 s32 ud_imm;
313
314 ud_type = decode_bug(addr, &ud_imm, &ud_len);
315 if (ud_type == BUG_NONE)
316 return handled;
317
318 /*
319 * All lies, just get the WARN/BUG out.
320 */
321 instrumentation_begin();
322 /*
323 * Normally @regs are unpoisoned by irqentry_enter(), but handle_bug()
324 * is a rare case that uses @regs without passing them to
325 * irqentry_enter().
326 */
327 kmsan_unpoison_entry_regs(regs);
328 /*
329 * Since we're emulating a CALL with exceptions, restore the interrupt
330 * state to what it was at the exception site.
331 */
332 if (regs->flags & X86_EFLAGS_IF)
333 raw_local_irq_enable();
334
335 switch (ud_type) {
336 case BUG_UD2:
337 if (report_bug(regs->ip, regs) == BUG_TRAP_TYPE_WARN) {
338 handled = true;
339 break;
340 }
341 fallthrough;
342
343 case BUG_EA:
344 case BUG_LOCK:
345 if (handle_cfi_failure(regs) == BUG_TRAP_TYPE_WARN) {
346 handled = true;
347 break;
348 }
349 break;
350
351 case BUG_UD1_UBSAN:
352 if (IS_ENABLED(CONFIG_UBSAN_TRAP)) {
353 pr_crit("%s at %pS\n",
354 report_ubsan_failure(regs, ud_imm),
355 (void *)regs->ip);
356 }
357 break;
358
359 default:
360 break;
361 }
362
363 /*
364 * When continuing, and regs->ip hasn't changed, move it to the next
365 * instruction. When not continuing execution, restore the instruction
366 * pointer.
367 */
368 if (handled) {
369 if (regs->ip == addr)
370 regs->ip += ud_len;
371 } else {
372 regs->ip = addr;
373 }
374
375 if (regs->flags & X86_EFLAGS_IF)
376 raw_local_irq_disable();
377 instrumentation_end();
378
379 return handled;
380 }
381
DEFINE_IDTENTRY_RAW(exc_invalid_op)382 DEFINE_IDTENTRY_RAW(exc_invalid_op)
383 {
384 irqentry_state_t state;
385
386 /*
387 * We use UD2 as a short encoding for 'CALL __WARN', as such
388 * handle it before exception entry to avoid recursive WARN
389 * in case exception entry is the one triggering WARNs.
390 */
391 if (!user_mode(regs) && handle_bug(regs))
392 return;
393
394 state = irqentry_enter(regs);
395 instrumentation_begin();
396 handle_invalid_op(regs);
397 instrumentation_end();
398 irqentry_exit(regs, state);
399 }
400
DEFINE_IDTENTRY(exc_coproc_segment_overrun)401 DEFINE_IDTENTRY(exc_coproc_segment_overrun)
402 {
403 do_error_trap(regs, 0, "coprocessor segment overrun",
404 X86_TRAP_OLD_MF, SIGFPE, 0, NULL);
405 }
406
DEFINE_IDTENTRY_ERRORCODE(exc_invalid_tss)407 DEFINE_IDTENTRY_ERRORCODE(exc_invalid_tss)
408 {
409 do_error_trap(regs, error_code, "invalid TSS", X86_TRAP_TS, SIGSEGV,
410 0, NULL);
411 }
412
DEFINE_IDTENTRY_ERRORCODE(exc_segment_not_present)413 DEFINE_IDTENTRY_ERRORCODE(exc_segment_not_present)
414 {
415 do_error_trap(regs, error_code, "segment not present", X86_TRAP_NP,
416 SIGBUS, 0, NULL);
417 }
418
DEFINE_IDTENTRY_ERRORCODE(exc_stack_segment)419 DEFINE_IDTENTRY_ERRORCODE(exc_stack_segment)
420 {
421 do_error_trap(regs, error_code, "stack segment", X86_TRAP_SS, SIGBUS,
422 0, NULL);
423 }
424
DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check)425 DEFINE_IDTENTRY_ERRORCODE(exc_alignment_check)
426 {
427 char *str = "alignment check";
428
429 if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP)
430 return;
431
432 if (!user_mode(regs))
433 die("Split lock detected\n", regs, error_code);
434
435 local_irq_enable();
436
437 if (handle_user_split_lock(regs, error_code))
438 goto out;
439
440 do_trap(X86_TRAP_AC, SIGBUS, "alignment check", regs,
441 error_code, BUS_ADRALN, NULL);
442
443 out:
444 local_irq_disable();
445 }
446
447 #ifdef CONFIG_VMAP_STACK
handle_stack_overflow(struct pt_regs * regs,unsigned long fault_address,struct stack_info * info)448 __visible void __noreturn handle_stack_overflow(struct pt_regs *regs,
449 unsigned long fault_address,
450 struct stack_info *info)
451 {
452 const char *name = stack_type_name(info->type);
453
454 printk(KERN_EMERG "BUG: %s stack guard page was hit at %p (stack is %p..%p)\n",
455 name, (void *)fault_address, info->begin, info->end);
456
457 die("stack guard page", regs, 0);
458
459 /* Be absolutely certain we don't return. */
460 panic("%s stack guard hit", name);
461 }
462 #endif
463
464 /*
465 * Prevent the compiler and/or objtool from marking the !CONFIG_X86_ESPFIX64
466 * version of exc_double_fault() as noreturn. Otherwise the noreturn mismatch
467 * between configs triggers objtool warnings.
468 *
469 * This is a temporary hack until we have compiler or plugin support for
470 * annotating noreturns.
471 */
472 #ifdef CONFIG_X86_ESPFIX64
473 #define always_true() true
474 #else
475 bool always_true(void);
always_true(void)476 bool __weak always_true(void) { return true; }
477 #endif
478
479 /*
480 * Runs on an IST stack for x86_64 and on a special task stack for x86_32.
481 *
482 * On x86_64, this is more or less a normal kernel entry. Notwithstanding the
483 * SDM's warnings about double faults being unrecoverable, returning works as
484 * expected. Presumably what the SDM actually means is that the CPU may get
485 * the register state wrong on entry, so returning could be a bad idea.
486 *
487 * Various CPU engineers have promised that double faults due to an IRET fault
488 * while the stack is read-only are, in fact, recoverable.
489 *
490 * On x86_32, this is entered through a task gate, and regs are synthesized
491 * from the TSS. Returning is, in principle, okay, but changes to regs will
492 * be lost. If, for some reason, we need to return to a context with modified
493 * regs, the shim code could be adjusted to synchronize the registers.
494 *
495 * The 32bit #DF shim provides CR2 already as an argument. On 64bit it needs
496 * to be read before doing anything else.
497 */
DEFINE_IDTENTRY_DF(exc_double_fault)498 DEFINE_IDTENTRY_DF(exc_double_fault)
499 {
500 static const char str[] = "double fault";
501 struct task_struct *tsk = current;
502
503 #ifdef CONFIG_VMAP_STACK
504 unsigned long address = read_cr2();
505 struct stack_info info;
506 #endif
507
508 #ifdef CONFIG_X86_ESPFIX64
509 extern unsigned char native_irq_return_iret[];
510
511 /*
512 * If IRET takes a non-IST fault on the espfix64 stack, then we
513 * end up promoting it to a doublefault. In that case, take
514 * advantage of the fact that we're not using the normal (TSS.sp0)
515 * stack right now. We can write a fake #GP(0) frame at TSS.sp0
516 * and then modify our own IRET frame so that, when we return,
517 * we land directly at the #GP(0) vector with the stack already
518 * set up according to its expectations.
519 *
520 * The net result is that our #GP handler will think that we
521 * entered from usermode with the bad user context.
522 *
523 * No need for nmi_enter() here because we don't use RCU.
524 */
525 if (((long)regs->sp >> P4D_SHIFT) == ESPFIX_PGD_ENTRY &&
526 regs->cs == __KERNEL_CS &&
527 regs->ip == (unsigned long)native_irq_return_iret)
528 {
529 struct pt_regs *gpregs = (struct pt_regs *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
530 unsigned long *p = (unsigned long *)regs->sp;
531
532 /*
533 * regs->sp points to the failing IRET frame on the
534 * ESPFIX64 stack. Copy it to the entry stack. This fills
535 * in gpregs->ss through gpregs->ip.
536 *
537 */
538 gpregs->ip = p[0];
539 gpregs->cs = p[1];
540 gpregs->flags = p[2];
541 gpregs->sp = p[3];
542 gpregs->ss = p[4];
543 gpregs->orig_ax = 0; /* Missing (lost) #GP error code */
544
545 /*
546 * Adjust our frame so that we return straight to the #GP
547 * vector with the expected RSP value. This is safe because
548 * we won't enable interrupts or schedule before we invoke
549 * general_protection, so nothing will clobber the stack
550 * frame we just set up.
551 *
552 * We will enter general_protection with kernel GSBASE,
553 * which is what the stub expects, given that the faulting
554 * RIP will be the IRET instruction.
555 */
556 regs->ip = (unsigned long)asm_exc_general_protection;
557 regs->sp = (unsigned long)&gpregs->orig_ax;
558
559 return;
560 }
561 #endif
562
563 irqentry_nmi_enter(regs);
564 instrumentation_begin();
565 notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV);
566
567 tsk->thread.error_code = error_code;
568 tsk->thread.trap_nr = X86_TRAP_DF;
569
570 #ifdef CONFIG_VMAP_STACK
571 /*
572 * If we overflow the stack into a guard page, the CPU will fail
573 * to deliver #PF and will send #DF instead. Similarly, if we
574 * take any non-IST exception while too close to the bottom of
575 * the stack, the processor will get a page fault while
576 * delivering the exception and will generate a double fault.
577 *
578 * According to the SDM (footnote in 6.15 under "Interrupt 14 -
579 * Page-Fault Exception (#PF):
580 *
581 * Processors update CR2 whenever a page fault is detected. If a
582 * second page fault occurs while an earlier page fault is being
583 * delivered, the faulting linear address of the second fault will
584 * overwrite the contents of CR2 (replacing the previous
585 * address). These updates to CR2 occur even if the page fault
586 * results in a double fault or occurs during the delivery of a
587 * double fault.
588 *
589 * The logic below has a small possibility of incorrectly diagnosing
590 * some errors as stack overflows. For example, if the IDT or GDT
591 * gets corrupted such that #GP delivery fails due to a bad descriptor
592 * causing #GP and we hit this condition while CR2 coincidentally
593 * points to the stack guard page, we'll think we overflowed the
594 * stack. Given that we're going to panic one way or another
595 * if this happens, this isn't necessarily worth fixing.
596 *
597 * If necessary, we could improve the test by only diagnosing
598 * a stack overflow if the saved RSP points within 47 bytes of
599 * the bottom of the stack: if RSP == tsk_stack + 48 and we
600 * take an exception, the stack is already aligned and there
601 * will be enough room SS, RSP, RFLAGS, CS, RIP, and a
602 * possible error code, so a stack overflow would *not* double
603 * fault. With any less space left, exception delivery could
604 * fail, and, as a practical matter, we've overflowed the
605 * stack even if the actual trigger for the double fault was
606 * something else.
607 */
608 if (get_stack_guard_info((void *)address, &info))
609 handle_stack_overflow(regs, address, &info);
610 #endif
611
612 pr_emerg("PANIC: double fault, error_code: 0x%lx\n", error_code);
613 die("double fault", regs, error_code);
614 if (always_true())
615 panic("Machine halted.");
616 instrumentation_end();
617 }
618
DEFINE_IDTENTRY(exc_bounds)619 DEFINE_IDTENTRY(exc_bounds)
620 {
621 if (notify_die(DIE_TRAP, "bounds", regs, 0,
622 X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP)
623 return;
624 cond_local_irq_enable(regs);
625
626 if (!user_mode(regs))
627 die("bounds", regs, 0);
628
629 do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, 0, 0, NULL);
630
631 cond_local_irq_disable(regs);
632 }
633
634 enum kernel_gp_hint {
635 GP_NO_HINT,
636 GP_NON_CANONICAL,
637 GP_CANONICAL
638 };
639
640 /*
641 * When an uncaught #GP occurs, try to determine the memory address accessed by
642 * the instruction and return that address to the caller. Also, try to figure
643 * out whether any part of the access to that address was non-canonical.
644 */
get_kernel_gp_address(struct pt_regs * regs,unsigned long * addr)645 static enum kernel_gp_hint get_kernel_gp_address(struct pt_regs *regs,
646 unsigned long *addr)
647 {
648 u8 insn_buf[MAX_INSN_SIZE];
649 struct insn insn;
650 int ret;
651
652 if (copy_from_kernel_nofault(insn_buf, (void *)regs->ip,
653 MAX_INSN_SIZE))
654 return GP_NO_HINT;
655
656 ret = insn_decode_kernel(&insn, insn_buf);
657 if (ret < 0)
658 return GP_NO_HINT;
659
660 *addr = (unsigned long)insn_get_addr_ref(&insn, regs);
661 if (*addr == -1UL)
662 return GP_NO_HINT;
663
664 #ifdef CONFIG_X86_64
665 /*
666 * Check that:
667 * - the operand is not in the kernel half
668 * - the last byte of the operand is not in the user canonical half
669 */
670 if (*addr < ~__VIRTUAL_MASK &&
671 *addr + insn.opnd_bytes - 1 > __VIRTUAL_MASK)
672 return GP_NON_CANONICAL;
673 #endif
674
675 return GP_CANONICAL;
676 }
677
678 #define GPFSTR "general protection fault"
679
fixup_iopl_exception(struct pt_regs * regs)680 static bool fixup_iopl_exception(struct pt_regs *regs)
681 {
682 struct thread_struct *t = ¤t->thread;
683 unsigned char byte;
684 unsigned long ip;
685
686 if (!IS_ENABLED(CONFIG_X86_IOPL_IOPERM) || t->iopl_emul != 3)
687 return false;
688
689 if (insn_get_effective_ip(regs, &ip))
690 return false;
691
692 if (get_user(byte, (const char __user *)ip))
693 return false;
694
695 if (byte != 0xfa && byte != 0xfb)
696 return false;
697
698 if (!t->iopl_warn && printk_ratelimit()) {
699 pr_err("%s[%d] attempts to use CLI/STI, pretending it's a NOP, ip:%lx",
700 current->comm, task_pid_nr(current), ip);
701 print_vma_addr(KERN_CONT " in ", ip);
702 pr_cont("\n");
703 t->iopl_warn = 1;
704 }
705
706 regs->ip += 1;
707 return true;
708 }
709
710 /*
711 * The unprivileged ENQCMD instruction generates #GPs if the
712 * IA32_PASID MSR has not been populated. If possible, populate
713 * the MSR from a PASID previously allocated to the mm.
714 */
try_fixup_enqcmd_gp(void)715 static bool try_fixup_enqcmd_gp(void)
716 {
717 #ifdef CONFIG_ARCH_HAS_CPU_PASID
718 u32 pasid;
719
720 /*
721 * MSR_IA32_PASID is managed using XSAVE. Directly
722 * writing to the MSR is only possible when fpregs
723 * are valid and the fpstate is not. This is
724 * guaranteed when handling a userspace exception
725 * in *before* interrupts are re-enabled.
726 */
727 lockdep_assert_irqs_disabled();
728
729 /*
730 * Hardware without ENQCMD will not generate
731 * #GPs that can be fixed up here.
732 */
733 if (!cpu_feature_enabled(X86_FEATURE_ENQCMD))
734 return false;
735
736 /*
737 * If the mm has not been allocated a
738 * PASID, the #GP can not be fixed up.
739 */
740 if (!mm_valid_pasid(current->mm))
741 return false;
742
743 pasid = mm_get_enqcmd_pasid(current->mm);
744
745 /*
746 * Did this thread already have its PASID activated?
747 * If so, the #GP must be from something else.
748 */
749 if (current->pasid_activated)
750 return false;
751
752 wrmsrl(MSR_IA32_PASID, pasid | MSR_IA32_PASID_VALID);
753 current->pasid_activated = 1;
754
755 return true;
756 #else
757 return false;
758 #endif
759 }
760
gp_try_fixup_and_notify(struct pt_regs * regs,int trapnr,unsigned long error_code,const char * str,unsigned long address)761 static bool gp_try_fixup_and_notify(struct pt_regs *regs, int trapnr,
762 unsigned long error_code, const char *str,
763 unsigned long address)
764 {
765 if (fixup_exception(regs, trapnr, error_code, address))
766 return true;
767
768 current->thread.error_code = error_code;
769 current->thread.trap_nr = trapnr;
770
771 /*
772 * To be potentially processing a kprobe fault and to trust the result
773 * from kprobe_running(), we have to be non-preemptible.
774 */
775 if (!preemptible() && kprobe_running() &&
776 kprobe_fault_handler(regs, trapnr))
777 return true;
778
779 return notify_die(DIE_GPF, str, regs, error_code, trapnr, SIGSEGV) == NOTIFY_STOP;
780 }
781
gp_user_force_sig_segv(struct pt_regs * regs,int trapnr,unsigned long error_code,const char * str)782 static void gp_user_force_sig_segv(struct pt_regs *regs, int trapnr,
783 unsigned long error_code, const char *str)
784 {
785 current->thread.error_code = error_code;
786 current->thread.trap_nr = trapnr;
787 show_signal(current, SIGSEGV, "", str, regs, error_code);
788 force_sig(SIGSEGV);
789 }
790
DEFINE_IDTENTRY_ERRORCODE(exc_general_protection)791 DEFINE_IDTENTRY_ERRORCODE(exc_general_protection)
792 {
793 char desc[sizeof(GPFSTR) + 50 + 2*sizeof(unsigned long) + 1] = GPFSTR;
794 enum kernel_gp_hint hint = GP_NO_HINT;
795 unsigned long gp_addr;
796
797 if (user_mode(regs) && try_fixup_enqcmd_gp())
798 return;
799
800 cond_local_irq_enable(regs);
801
802 if (static_cpu_has(X86_FEATURE_UMIP)) {
803 if (user_mode(regs) && fixup_umip_exception(regs))
804 goto exit;
805 }
806
807 if (v8086_mode(regs)) {
808 local_irq_enable();
809 handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code);
810 local_irq_disable();
811 return;
812 }
813
814 if (user_mode(regs)) {
815 if (fixup_iopl_exception(regs))
816 goto exit;
817
818 if (fixup_vdso_exception(regs, X86_TRAP_GP, error_code, 0))
819 goto exit;
820
821 gp_user_force_sig_segv(regs, X86_TRAP_GP, error_code, desc);
822 goto exit;
823 }
824
825 if (gp_try_fixup_and_notify(regs, X86_TRAP_GP, error_code, desc, 0))
826 goto exit;
827
828 if (error_code)
829 snprintf(desc, sizeof(desc), "segment-related " GPFSTR);
830 else
831 hint = get_kernel_gp_address(regs, &gp_addr);
832
833 if (hint != GP_NO_HINT)
834 snprintf(desc, sizeof(desc), GPFSTR ", %s 0x%lx",
835 (hint == GP_NON_CANONICAL) ? "probably for non-canonical address"
836 : "maybe for address",
837 gp_addr);
838
839 /*
840 * KASAN is interested only in the non-canonical case, clear it
841 * otherwise.
842 */
843 if (hint != GP_NON_CANONICAL)
844 gp_addr = 0;
845
846 die_addr(desc, regs, error_code, gp_addr);
847
848 exit:
849 cond_local_irq_disable(regs);
850 }
851
do_int3(struct pt_regs * regs)852 static bool do_int3(struct pt_regs *regs)
853 {
854 int res;
855
856 #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
857 if (kgdb_ll_trap(DIE_INT3, "int3", regs, 0, X86_TRAP_BP,
858 SIGTRAP) == NOTIFY_STOP)
859 return true;
860 #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
861
862 #ifdef CONFIG_KPROBES
863 if (kprobe_int3_handler(regs))
864 return true;
865 #endif
866 res = notify_die(DIE_INT3, "int3", regs, 0, X86_TRAP_BP, SIGTRAP);
867
868 return res == NOTIFY_STOP;
869 }
870 NOKPROBE_SYMBOL(do_int3);
871
do_int3_user(struct pt_regs * regs)872 static void do_int3_user(struct pt_regs *regs)
873 {
874 if (do_int3(regs))
875 return;
876
877 cond_local_irq_enable(regs);
878 do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, 0, 0, NULL);
879 cond_local_irq_disable(regs);
880 }
881
DEFINE_IDTENTRY_RAW(exc_int3)882 DEFINE_IDTENTRY_RAW(exc_int3)
883 {
884 /*
885 * poke_int3_handler() is completely self contained code; it does (and
886 * must) *NOT* call out to anything, lest it hits upon yet another
887 * INT3.
888 */
889 if (poke_int3_handler(regs))
890 return;
891
892 /*
893 * irqentry_enter_from_user_mode() uses static_branch_{,un}likely()
894 * and therefore can trigger INT3, hence poke_int3_handler() must
895 * be done before. If the entry came from kernel mode, then use
896 * nmi_enter() because the INT3 could have been hit in any context
897 * including NMI.
898 */
899 if (user_mode(regs)) {
900 irqentry_enter_from_user_mode(regs);
901 instrumentation_begin();
902 do_int3_user(regs);
903 instrumentation_end();
904 irqentry_exit_to_user_mode(regs);
905 } else {
906 irqentry_state_t irq_state = irqentry_nmi_enter(regs);
907
908 instrumentation_begin();
909 if (!do_int3(regs))
910 die("int3", regs, 0);
911 instrumentation_end();
912 irqentry_nmi_exit(regs, irq_state);
913 }
914 }
915
916 #ifdef CONFIG_X86_64
917 /*
918 * Help handler running on a per-cpu (IST or entry trampoline) stack
919 * to switch to the normal thread stack if the interrupted code was in
920 * user mode. The actual stack switch is done in entry_64.S
921 */
sync_regs(struct pt_regs * eregs)922 asmlinkage __visible noinstr struct pt_regs *sync_regs(struct pt_regs *eregs)
923 {
924 struct pt_regs *regs = (struct pt_regs *)current_top_of_stack() - 1;
925 if (regs != eregs)
926 *regs = *eregs;
927 return regs;
928 }
929
930 #ifdef CONFIG_AMD_MEM_ENCRYPT
vc_switch_off_ist(struct pt_regs * regs)931 asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *regs)
932 {
933 unsigned long sp, *stack;
934 struct stack_info info;
935 struct pt_regs *regs_ret;
936
937 /*
938 * In the SYSCALL entry path the RSP value comes from user-space - don't
939 * trust it and switch to the current kernel stack
940 */
941 if (ip_within_syscall_gap(regs)) {
942 sp = current_top_of_stack();
943 goto sync;
944 }
945
946 /*
947 * From here on the RSP value is trusted. Now check whether entry
948 * happened from a safe stack. Not safe are the entry or unknown stacks,
949 * use the fall-back stack instead in this case.
950 */
951 sp = regs->sp;
952 stack = (unsigned long *)sp;
953
954 if (!get_stack_info_noinstr(stack, current, &info) || info.type == STACK_TYPE_ENTRY ||
955 info.type > STACK_TYPE_EXCEPTION_LAST)
956 sp = __this_cpu_ist_top_va(VC2);
957
958 sync:
959 /*
960 * Found a safe stack - switch to it as if the entry didn't happen via
961 * IST stack. The code below only copies pt_regs, the real switch happens
962 * in assembly code.
963 */
964 sp = ALIGN_DOWN(sp, 8) - sizeof(*regs_ret);
965
966 regs_ret = (struct pt_regs *)sp;
967 *regs_ret = *regs;
968
969 return regs_ret;
970 }
971 #endif
972
fixup_bad_iret(struct pt_regs * bad_regs)973 asmlinkage __visible noinstr struct pt_regs *fixup_bad_iret(struct pt_regs *bad_regs)
974 {
975 struct pt_regs tmp, *new_stack;
976
977 /*
978 * This is called from entry_64.S early in handling a fault
979 * caused by a bad iret to user mode. To handle the fault
980 * correctly, we want to move our stack frame to where it would
981 * be had we entered directly on the entry stack (rather than
982 * just below the IRET frame) and we want to pretend that the
983 * exception came from the IRET target.
984 */
985 new_stack = (struct pt_regs *)__this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
986
987 /* Copy the IRET target to the temporary storage. */
988 __memcpy(&tmp.ip, (void *)bad_regs->sp, 5*8);
989
990 /* Copy the remainder of the stack from the current stack. */
991 __memcpy(&tmp, bad_regs, offsetof(struct pt_regs, ip));
992
993 /* Update the entry stack */
994 __memcpy(new_stack, &tmp, sizeof(tmp));
995
996 BUG_ON(!user_mode(new_stack));
997 return new_stack;
998 }
999 #endif
1000
is_sysenter_singlestep(struct pt_regs * regs)1001 static bool is_sysenter_singlestep(struct pt_regs *regs)
1002 {
1003 /*
1004 * We don't try for precision here. If we're anywhere in the region of
1005 * code that can be single-stepped in the SYSENTER entry path, then
1006 * assume that this is a useless single-step trap due to SYSENTER
1007 * being invoked with TF set. (We don't know in advance exactly
1008 * which instructions will be hit because BTF could plausibly
1009 * be set.)
1010 */
1011 #ifdef CONFIG_X86_32
1012 return (regs->ip - (unsigned long)__begin_SYSENTER_singlestep_region) <
1013 (unsigned long)__end_SYSENTER_singlestep_region -
1014 (unsigned long)__begin_SYSENTER_singlestep_region;
1015 #elif defined(CONFIG_IA32_EMULATION)
1016 return (regs->ip - (unsigned long)entry_SYSENTER_compat) <
1017 (unsigned long)__end_entry_SYSENTER_compat -
1018 (unsigned long)entry_SYSENTER_compat;
1019 #else
1020 return false;
1021 #endif
1022 }
1023
debug_read_clear_dr6(void)1024 static __always_inline unsigned long debug_read_clear_dr6(void)
1025 {
1026 unsigned long dr6;
1027
1028 /*
1029 * The Intel SDM says:
1030 *
1031 * Certain debug exceptions may clear bits 0-3. The remaining
1032 * contents of the DR6 register are never cleared by the
1033 * processor. To avoid confusion in identifying debug
1034 * exceptions, debug handlers should clear the register before
1035 * returning to the interrupted task.
1036 *
1037 * Keep it simple: clear DR6 immediately.
1038 */
1039 get_debugreg(dr6, 6);
1040 set_debugreg(DR6_RESERVED, 6);
1041 dr6 ^= DR6_RESERVED; /* Flip to positive polarity */
1042
1043 return dr6;
1044 }
1045
1046 /*
1047 * Our handling of the processor debug registers is non-trivial.
1048 * We do not clear them on entry and exit from the kernel. Therefore
1049 * it is possible to get a watchpoint trap here from inside the kernel.
1050 * However, the code in ./ptrace.c has ensured that the user can
1051 * only set watchpoints on userspace addresses. Therefore the in-kernel
1052 * watchpoint trap can only occur in code which is reading/writing
1053 * from user space. Such code must not hold kernel locks (since it
1054 * can equally take a page fault), therefore it is safe to call
1055 * force_sig_info even though that claims and releases locks.
1056 *
1057 * Code in ./signal.c ensures that the debug control register
1058 * is restored before we deliver any signal, and therefore that
1059 * user code runs with the correct debug control register even though
1060 * we clear it here.
1061 *
1062 * Being careful here means that we don't have to be as careful in a
1063 * lot of more complicated places (task switching can be a bit lazy
1064 * about restoring all the debug state, and ptrace doesn't have to
1065 * find every occurrence of the TF bit that could be saved away even
1066 * by user code)
1067 *
1068 * May run on IST stack.
1069 */
1070
notify_debug(struct pt_regs * regs,unsigned long * dr6)1071 static bool notify_debug(struct pt_regs *regs, unsigned long *dr6)
1072 {
1073 /*
1074 * Notifiers will clear bits in @dr6 to indicate the event has been
1075 * consumed - hw_breakpoint_handler(), single_stop_cont().
1076 *
1077 * Notifiers will set bits in @virtual_dr6 to indicate the desire
1078 * for signals - ptrace_triggered(), kgdb_hw_overflow_handler().
1079 */
1080 if (notify_die(DIE_DEBUG, "debug", regs, (long)dr6, 0, SIGTRAP) == NOTIFY_STOP)
1081 return true;
1082
1083 return false;
1084 }
1085
exc_debug_kernel(struct pt_regs * regs,unsigned long dr6)1086 static noinstr void exc_debug_kernel(struct pt_regs *regs, unsigned long dr6)
1087 {
1088 /*
1089 * Disable breakpoints during exception handling; recursive exceptions
1090 * are exceedingly 'fun'.
1091 *
1092 * Since this function is NOKPROBE, and that also applies to
1093 * HW_BREAKPOINT_X, we can't hit a breakpoint before this (XXX except a
1094 * HW_BREAKPOINT_W on our stack)
1095 *
1096 * Entry text is excluded for HW_BP_X and cpu_entry_area, which
1097 * includes the entry stack is excluded for everything.
1098 *
1099 * For FRED, nested #DB should just work fine. But when a watchpoint or
1100 * breakpoint is set in the code path which is executed by #DB handler,
1101 * it results in an endless recursion and stack overflow. Thus we stay
1102 * with the IDT approach, i.e., save DR7 and disable #DB.
1103 */
1104 unsigned long dr7 = local_db_save();
1105 irqentry_state_t irq_state = irqentry_nmi_enter(regs);
1106 instrumentation_begin();
1107
1108 /*
1109 * If something gets miswired and we end up here for a user mode
1110 * #DB, we will malfunction.
1111 */
1112 WARN_ON_ONCE(user_mode(regs));
1113
1114 if (test_thread_flag(TIF_BLOCKSTEP)) {
1115 /*
1116 * The SDM says "The processor clears the BTF flag when it
1117 * generates a debug exception." but PTRACE_BLOCKSTEP requested
1118 * it for userspace, but we just took a kernel #DB, so re-set
1119 * BTF.
1120 */
1121 unsigned long debugctl;
1122
1123 rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1124 debugctl |= DEBUGCTLMSR_BTF;
1125 wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1126 }
1127
1128 /*
1129 * Catch SYSENTER with TF set and clear DR_STEP. If this hit a
1130 * watchpoint at the same time then that will still be handled.
1131 */
1132 if (!cpu_feature_enabled(X86_FEATURE_FRED) &&
1133 (dr6 & DR_STEP) && is_sysenter_singlestep(regs))
1134 dr6 &= ~DR_STEP;
1135
1136 /*
1137 * The kernel doesn't use INT1
1138 */
1139 if (!dr6)
1140 goto out;
1141
1142 if (notify_debug(regs, &dr6))
1143 goto out;
1144
1145 /*
1146 * The kernel doesn't use TF single-step outside of:
1147 *
1148 * - Kprobes, consumed through kprobe_debug_handler()
1149 * - KGDB, consumed through notify_debug()
1150 *
1151 * So if we get here with DR_STEP set, something is wonky.
1152 *
1153 * A known way to trigger this is through QEMU's GDB stub,
1154 * which leaks #DB into the guest and causes IST recursion.
1155 */
1156 if (WARN_ON_ONCE(dr6 & DR_STEP))
1157 regs->flags &= ~X86_EFLAGS_TF;
1158 out:
1159 instrumentation_end();
1160 irqentry_nmi_exit(regs, irq_state);
1161
1162 local_db_restore(dr7);
1163 }
1164
exc_debug_user(struct pt_regs * regs,unsigned long dr6)1165 static noinstr void exc_debug_user(struct pt_regs *regs, unsigned long dr6)
1166 {
1167 bool icebp;
1168
1169 /*
1170 * If something gets miswired and we end up here for a kernel mode
1171 * #DB, we will malfunction.
1172 */
1173 WARN_ON_ONCE(!user_mode(regs));
1174
1175 /*
1176 * NB: We can't easily clear DR7 here because
1177 * irqentry_exit_to_usermode() can invoke ptrace, schedule, access
1178 * user memory, etc. This means that a recursive #DB is possible. If
1179 * this happens, that #DB will hit exc_debug_kernel() and clear DR7.
1180 * Since we're not on the IST stack right now, everything will be
1181 * fine.
1182 */
1183
1184 irqentry_enter_from_user_mode(regs);
1185 instrumentation_begin();
1186
1187 /*
1188 * Start the virtual/ptrace DR6 value with just the DR_STEP mask
1189 * of the real DR6. ptrace_triggered() will set the DR_TRAPn bits.
1190 *
1191 * Userspace expects DR_STEP to be visible in ptrace_get_debugreg(6)
1192 * even if it is not the result of PTRACE_SINGLESTEP.
1193 */
1194 current->thread.virtual_dr6 = (dr6 & DR_STEP);
1195
1196 /*
1197 * The SDM says "The processor clears the BTF flag when it
1198 * generates a debug exception." Clear TIF_BLOCKSTEP to keep
1199 * TIF_BLOCKSTEP in sync with the hardware BTF flag.
1200 */
1201 clear_thread_flag(TIF_BLOCKSTEP);
1202
1203 /*
1204 * If dr6 has no reason to give us about the origin of this trap,
1205 * then it's very likely the result of an icebp/int01 trap.
1206 * User wants a sigtrap for that.
1207 */
1208 icebp = !dr6;
1209
1210 if (notify_debug(regs, &dr6))
1211 goto out;
1212
1213 /* It's safe to allow irq's after DR6 has been saved */
1214 local_irq_enable();
1215
1216 if (v8086_mode(regs)) {
1217 handle_vm86_trap((struct kernel_vm86_regs *)regs, 0, X86_TRAP_DB);
1218 goto out_irq;
1219 }
1220
1221 /* #DB for bus lock can only be triggered from userspace. */
1222 if (dr6 & DR_BUS_LOCK)
1223 handle_bus_lock(regs);
1224
1225 /* Add the virtual_dr6 bits for signals. */
1226 dr6 |= current->thread.virtual_dr6;
1227 if (dr6 & (DR_STEP | DR_TRAP_BITS) || icebp)
1228 send_sigtrap(regs, 0, get_si_code(dr6));
1229
1230 out_irq:
1231 local_irq_disable();
1232 out:
1233 instrumentation_end();
1234 irqentry_exit_to_user_mode(regs);
1235 }
1236
1237 #ifdef CONFIG_X86_64
1238 /* IST stack entry */
DEFINE_IDTENTRY_DEBUG(exc_debug)1239 DEFINE_IDTENTRY_DEBUG(exc_debug)
1240 {
1241 exc_debug_kernel(regs, debug_read_clear_dr6());
1242 }
1243
1244 /* User entry, runs on regular task stack */
DEFINE_IDTENTRY_DEBUG_USER(exc_debug)1245 DEFINE_IDTENTRY_DEBUG_USER(exc_debug)
1246 {
1247 exc_debug_user(regs, debug_read_clear_dr6());
1248 }
1249
1250 #ifdef CONFIG_X86_FRED
1251 /*
1252 * When occurred on different ring level, i.e., from user or kernel
1253 * context, #DB needs to be handled on different stack: User #DB on
1254 * current task stack, while kernel #DB on a dedicated stack.
1255 *
1256 * This is exactly how FRED event delivery invokes an exception
1257 * handler: ring 3 event on level 0 stack, i.e., current task stack;
1258 * ring 0 event on the #DB dedicated stack specified in the
1259 * IA32_FRED_STKLVLS MSR. So unlike IDT, the FRED debug exception
1260 * entry stub doesn't do stack switch.
1261 */
DEFINE_FREDENTRY_DEBUG(exc_debug)1262 DEFINE_FREDENTRY_DEBUG(exc_debug)
1263 {
1264 /*
1265 * FRED #DB stores DR6 on the stack in the format which
1266 * debug_read_clear_dr6() returns for the IDT entry points.
1267 */
1268 unsigned long dr6 = fred_event_data(regs);
1269
1270 if (user_mode(regs))
1271 exc_debug_user(regs, dr6);
1272 else
1273 exc_debug_kernel(regs, dr6);
1274 }
1275 #endif /* CONFIG_X86_FRED */
1276
1277 #else
1278 /* 32 bit does not have separate entry points. */
DEFINE_IDTENTRY_RAW(exc_debug)1279 DEFINE_IDTENTRY_RAW(exc_debug)
1280 {
1281 unsigned long dr6 = debug_read_clear_dr6();
1282
1283 if (user_mode(regs))
1284 exc_debug_user(regs, dr6);
1285 else
1286 exc_debug_kernel(regs, dr6);
1287 }
1288 #endif
1289
1290 /*
1291 * Note that we play around with the 'TS' bit in an attempt to get
1292 * the correct behaviour even in the presence of the asynchronous
1293 * IRQ13 behaviour
1294 */
math_error(struct pt_regs * regs,int trapnr)1295 static void math_error(struct pt_regs *regs, int trapnr)
1296 {
1297 struct task_struct *task = current;
1298 struct fpu *fpu = &task->thread.fpu;
1299 int si_code;
1300 char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" :
1301 "simd exception";
1302
1303 cond_local_irq_enable(regs);
1304
1305 if (!user_mode(regs)) {
1306 if (fixup_exception(regs, trapnr, 0, 0))
1307 goto exit;
1308
1309 task->thread.error_code = 0;
1310 task->thread.trap_nr = trapnr;
1311
1312 if (notify_die(DIE_TRAP, str, regs, 0, trapnr,
1313 SIGFPE) != NOTIFY_STOP)
1314 die(str, regs, 0);
1315 goto exit;
1316 }
1317
1318 /*
1319 * Synchronize the FPU register state to the memory register state
1320 * if necessary. This allows the exception handler to inspect it.
1321 */
1322 fpu_sync_fpstate(fpu);
1323
1324 task->thread.trap_nr = trapnr;
1325 task->thread.error_code = 0;
1326
1327 si_code = fpu__exception_code(fpu, trapnr);
1328 /* Retry when we get spurious exceptions: */
1329 if (!si_code)
1330 goto exit;
1331
1332 if (fixup_vdso_exception(regs, trapnr, 0, 0))
1333 goto exit;
1334
1335 force_sig_fault(SIGFPE, si_code,
1336 (void __user *)uprobe_get_trap_addr(regs));
1337 exit:
1338 cond_local_irq_disable(regs);
1339 }
1340
DEFINE_IDTENTRY(exc_coprocessor_error)1341 DEFINE_IDTENTRY(exc_coprocessor_error)
1342 {
1343 math_error(regs, X86_TRAP_MF);
1344 }
1345
DEFINE_IDTENTRY(exc_simd_coprocessor_error)1346 DEFINE_IDTENTRY(exc_simd_coprocessor_error)
1347 {
1348 if (IS_ENABLED(CONFIG_X86_INVD_BUG)) {
1349 /* AMD 486 bug: INVD in CPL 0 raises #XF instead of #GP */
1350 if (!static_cpu_has(X86_FEATURE_XMM)) {
1351 __exc_general_protection(regs, 0);
1352 return;
1353 }
1354 }
1355 math_error(regs, X86_TRAP_XF);
1356 }
1357
DEFINE_IDTENTRY(exc_spurious_interrupt_bug)1358 DEFINE_IDTENTRY(exc_spurious_interrupt_bug)
1359 {
1360 /*
1361 * This addresses a Pentium Pro Erratum:
1362 *
1363 * PROBLEM: If the APIC subsystem is configured in mixed mode with
1364 * Virtual Wire mode implemented through the local APIC, an
1365 * interrupt vector of 0Fh (Intel reserved encoding) may be
1366 * generated by the local APIC (Int 15). This vector may be
1367 * generated upon receipt of a spurious interrupt (an interrupt
1368 * which is removed before the system receives the INTA sequence)
1369 * instead of the programmed 8259 spurious interrupt vector.
1370 *
1371 * IMPLICATION: The spurious interrupt vector programmed in the
1372 * 8259 is normally handled by an operating system's spurious
1373 * interrupt handler. However, a vector of 0Fh is unknown to some
1374 * operating systems, which would crash if this erratum occurred.
1375 *
1376 * In theory this could be limited to 32bit, but the handler is not
1377 * hurting and who knows which other CPUs suffer from this.
1378 */
1379 }
1380
handle_xfd_event(struct pt_regs * regs)1381 static bool handle_xfd_event(struct pt_regs *regs)
1382 {
1383 u64 xfd_err;
1384 int err;
1385
1386 if (!IS_ENABLED(CONFIG_X86_64) || !cpu_feature_enabled(X86_FEATURE_XFD))
1387 return false;
1388
1389 rdmsrl(MSR_IA32_XFD_ERR, xfd_err);
1390 if (!xfd_err)
1391 return false;
1392
1393 wrmsrl(MSR_IA32_XFD_ERR, 0);
1394
1395 /* Die if that happens in kernel space */
1396 if (WARN_ON(!user_mode(regs)))
1397 return false;
1398
1399 local_irq_enable();
1400
1401 err = xfd_enable_feature(xfd_err);
1402
1403 switch (err) {
1404 case -EPERM:
1405 force_sig_fault(SIGILL, ILL_ILLOPC, error_get_trap_addr(regs));
1406 break;
1407 case -EFAULT:
1408 force_sig(SIGSEGV);
1409 break;
1410 }
1411
1412 local_irq_disable();
1413 return true;
1414 }
1415
DEFINE_IDTENTRY(exc_device_not_available)1416 DEFINE_IDTENTRY(exc_device_not_available)
1417 {
1418 unsigned long cr0 = read_cr0();
1419
1420 if (handle_xfd_event(regs))
1421 return;
1422
1423 #ifdef CONFIG_MATH_EMULATION
1424 if (!boot_cpu_has(X86_FEATURE_FPU) && (cr0 & X86_CR0_EM)) {
1425 struct math_emu_info info = { };
1426
1427 cond_local_irq_enable(regs);
1428
1429 info.regs = regs;
1430 math_emulate(&info);
1431
1432 cond_local_irq_disable(regs);
1433 return;
1434 }
1435 #endif
1436
1437 /* This should not happen. */
1438 if (WARN(cr0 & X86_CR0_TS, "CR0.TS was set")) {
1439 /* Try to fix it up and carry on. */
1440 write_cr0(cr0 & ~X86_CR0_TS);
1441 } else {
1442 /*
1443 * Something terrible happened, and we're better off trying
1444 * to kill the task than getting stuck in a never-ending
1445 * loop of #NM faults.
1446 */
1447 die("unexpected #NM exception", regs, 0);
1448 }
1449 }
1450
1451 #ifdef CONFIG_INTEL_TDX_GUEST
1452
1453 #define VE_FAULT_STR "VE fault"
1454
ve_raise_fault(struct pt_regs * regs,long error_code,unsigned long address)1455 static void ve_raise_fault(struct pt_regs *regs, long error_code,
1456 unsigned long address)
1457 {
1458 if (user_mode(regs)) {
1459 gp_user_force_sig_segv(regs, X86_TRAP_VE, error_code, VE_FAULT_STR);
1460 return;
1461 }
1462
1463 if (gp_try_fixup_and_notify(regs, X86_TRAP_VE, error_code,
1464 VE_FAULT_STR, address)) {
1465 return;
1466 }
1467
1468 die_addr(VE_FAULT_STR, regs, error_code, address);
1469 }
1470
1471 /*
1472 * Virtualization Exceptions (#VE) are delivered to TDX guests due to
1473 * specific guest actions which may happen in either user space or the
1474 * kernel:
1475 *
1476 * * Specific instructions (WBINVD, for example)
1477 * * Specific MSR accesses
1478 * * Specific CPUID leaf accesses
1479 * * Access to specific guest physical addresses
1480 *
1481 * In the settings that Linux will run in, virtualization exceptions are
1482 * never generated on accesses to normal, TD-private memory that has been
1483 * accepted (by BIOS or with tdx_enc_status_changed()).
1484 *
1485 * Syscall entry code has a critical window where the kernel stack is not
1486 * yet set up. Any exception in this window leads to hard to debug issues
1487 * and can be exploited for privilege escalation. Exceptions in the NMI
1488 * entry code also cause issues. Returning from the exception handler with
1489 * IRET will re-enable NMIs and nested NMI will corrupt the NMI stack.
1490 *
1491 * For these reasons, the kernel avoids #VEs during the syscall gap and
1492 * the NMI entry code. Entry code paths do not access TD-shared memory,
1493 * MMIO regions, use #VE triggering MSRs, instructions, or CPUID leaves
1494 * that might generate #VE. VMM can remove memory from TD at any point,
1495 * but access to unaccepted (or missing) private memory leads to VM
1496 * termination, not to #VE.
1497 *
1498 * Similarly to page faults and breakpoints, #VEs are allowed in NMI
1499 * handlers once the kernel is ready to deal with nested NMIs.
1500 *
1501 * During #VE delivery, all interrupts, including NMIs, are blocked until
1502 * TDGETVEINFO is called. It prevents #VE nesting until the kernel reads
1503 * the VE info.
1504 *
1505 * If a guest kernel action which would normally cause a #VE occurs in
1506 * the interrupt-disabled region before TDGETVEINFO, a #DF (fault
1507 * exception) is delivered to the guest which will result in an oops.
1508 *
1509 * The entry code has been audited carefully for following these expectations.
1510 * Changes in the entry code have to be audited for correctness vs. this
1511 * aspect. Similarly to #PF, #VE in these places will expose kernel to
1512 * privilege escalation or may lead to random crashes.
1513 */
DEFINE_IDTENTRY(exc_virtualization_exception)1514 DEFINE_IDTENTRY(exc_virtualization_exception)
1515 {
1516 struct ve_info ve;
1517
1518 /*
1519 * NMIs/Machine-checks/Interrupts will be in a disabled state
1520 * till TDGETVEINFO TDCALL is executed. This ensures that VE
1521 * info cannot be overwritten by a nested #VE.
1522 */
1523 tdx_get_ve_info(&ve);
1524
1525 cond_local_irq_enable(regs);
1526
1527 /*
1528 * If tdx_handle_virt_exception() could not process
1529 * it successfully, treat it as #GP(0) and handle it.
1530 */
1531 if (!tdx_handle_virt_exception(regs, &ve))
1532 ve_raise_fault(regs, 0, ve.gla);
1533
1534 cond_local_irq_disable(regs);
1535 }
1536
1537 #endif
1538
1539 #ifdef CONFIG_X86_32
DEFINE_IDTENTRY_SW(iret_error)1540 DEFINE_IDTENTRY_SW(iret_error)
1541 {
1542 local_irq_enable();
1543 if (notify_die(DIE_TRAP, "iret exception", regs, 0,
1544 X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) {
1545 do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, 0,
1546 ILL_BADSTK, (void __user *)NULL);
1547 }
1548 local_irq_disable();
1549 }
1550 #endif
1551
trap_init(void)1552 void __init trap_init(void)
1553 {
1554 /* Init cpu_entry_area before IST entries are set up */
1555 setup_cpu_entry_areas();
1556
1557 /* Init GHCB memory pages when running as an SEV-ES guest */
1558 sev_es_init_vc_handling();
1559
1560 /* Initialize TSS before setting up traps so ISTs work */
1561 cpu_init_exception_handling(true);
1562
1563 /* Setup traps as cpu_init() might #GP */
1564 if (!cpu_feature_enabled(X86_FEATURE_FRED))
1565 idt_setup_traps();
1566
1567 cpu_init();
1568 }
1569