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