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