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