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