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