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