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