xref: /openbmc/linux/arch/x86/kernel/traps.c (revision 4be5e864)
1 /*
2  *  Copyright (C) 1991, 1992  Linus Torvalds
3  *  Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
4  *
5  *  Pentium III FXSR, SSE support
6  *	Gareth Hughes <gareth@valinux.com>, May 2000
7  */
8 
9 /*
10  * Handle hardware traps and faults.
11  */
12 
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 
15 #include <linux/context_tracking.h>
16 #include <linux/interrupt.h>
17 #include <linux/kallsyms.h>
18 #include <linux/spinlock.h>
19 #include <linux/kprobes.h>
20 #include <linux/uaccess.h>
21 #include <linux/kdebug.h>
22 #include <linux/kgdb.h>
23 #include <linux/kernel.h>
24 #include <linux/export.h>
25 #include <linux/ptrace.h>
26 #include <linux/uprobes.h>
27 #include <linux/string.h>
28 #include <linux/delay.h>
29 #include <linux/errno.h>
30 #include <linux/kexec.h>
31 #include <linux/sched.h>
32 #include <linux/sched/task_stack.h>
33 #include <linux/timer.h>
34 #include <linux/init.h>
35 #include <linux/bug.h>
36 #include <linux/nmi.h>
37 #include <linux/mm.h>
38 #include <linux/smp.h>
39 #include <linux/io.h>
40 #include <asm/stacktrace.h>
41 #include <asm/processor.h>
42 #include <asm/debugreg.h>
43 #include <linux/atomic.h>
44 #include <asm/text-patching.h>
45 #include <asm/ftrace.h>
46 #include <asm/traps.h>
47 #include <asm/desc.h>
48 #include <asm/fpu/internal.h>
49 #include <asm/cpu.h>
50 #include <asm/cpu_entry_area.h>
51 #include <asm/mce.h>
52 #include <asm/fixmap.h>
53 #include <asm/mach_traps.h>
54 #include <asm/alternative.h>
55 #include <asm/fpu/xstate.h>
56 #include <asm/vm86.h>
57 #include <asm/umip.h>
58 #include <asm/insn.h>
59 #include <asm/insn-eval.h>
60 
61 #ifdef CONFIG_X86_64
62 #include <asm/x86_init.h>
63 #include <asm/pgalloc.h>
64 #include <asm/proto.h>
65 #else
66 #include <asm/processor-flags.h>
67 #include <asm/setup.h>
68 #include <asm/proto.h>
69 #endif
70 
71 DECLARE_BITMAP(system_vectors, NR_VECTORS);
72 
73 static inline void cond_local_irq_enable(struct pt_regs *regs)
74 {
75 	if (regs->flags & X86_EFLAGS_IF)
76 		local_irq_enable();
77 }
78 
79 static inline void cond_local_irq_disable(struct pt_regs *regs)
80 {
81 	if (regs->flags & X86_EFLAGS_IF)
82 		local_irq_disable();
83 }
84 
85 /*
86  * In IST context, we explicitly disable preemption.  This serves two
87  * purposes: it makes it much less likely that we would accidentally
88  * schedule in IST context and it will force a warning if we somehow
89  * manage to schedule by accident.
90  */
91 void ist_enter(struct pt_regs *regs)
92 {
93 	if (user_mode(regs)) {
94 		RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
95 	} else {
96 		/*
97 		 * We might have interrupted pretty much anything.  In
98 		 * fact, if we're a machine check, we can even interrupt
99 		 * NMI processing.  We don't want in_nmi() to return true,
100 		 * but we need to notify RCU.
101 		 */
102 		rcu_nmi_enter();
103 	}
104 
105 	preempt_disable();
106 
107 	/* This code is a bit fragile.  Test it. */
108 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "ist_enter didn't work");
109 }
110 NOKPROBE_SYMBOL(ist_enter);
111 
112 void ist_exit(struct pt_regs *regs)
113 {
114 	preempt_enable_no_resched();
115 
116 	if (!user_mode(regs))
117 		rcu_nmi_exit();
118 }
119 
120 /**
121  * ist_begin_non_atomic() - begin a non-atomic section in an IST exception
122  * @regs:	regs passed to the IST exception handler
123  *
124  * IST exception handlers normally cannot schedule.  As a special
125  * exception, if the exception interrupted userspace code (i.e.
126  * user_mode(regs) would return true) and the exception was not
127  * a double fault, it can be safe to schedule.  ist_begin_non_atomic()
128  * begins a non-atomic section within an ist_enter()/ist_exit() region.
129  * Callers are responsible for enabling interrupts themselves inside
130  * the non-atomic section, and callers must call ist_end_non_atomic()
131  * before ist_exit().
132  */
133 void ist_begin_non_atomic(struct pt_regs *regs)
134 {
135 	BUG_ON(!user_mode(regs));
136 
137 	/*
138 	 * Sanity check: we need to be on the normal thread stack.  This
139 	 * will catch asm bugs and any attempt to use ist_preempt_enable
140 	 * from double_fault.
141 	 */
142 	BUG_ON(!on_thread_stack());
143 
144 	preempt_enable_no_resched();
145 }
146 
147 /**
148  * ist_end_non_atomic() - begin a non-atomic section in an IST exception
149  *
150  * Ends a non-atomic section started with ist_begin_non_atomic().
151  */
152 void ist_end_non_atomic(void)
153 {
154 	preempt_disable();
155 }
156 
157 int is_valid_bugaddr(unsigned long addr)
158 {
159 	unsigned short ud;
160 
161 	if (addr < TASK_SIZE_MAX)
162 		return 0;
163 
164 	if (probe_kernel_address((unsigned short *)addr, ud))
165 		return 0;
166 
167 	return ud == INSN_UD0 || ud == INSN_UD2;
168 }
169 
170 int fixup_bug(struct pt_regs *regs, int trapnr)
171 {
172 	if (trapnr != X86_TRAP_UD)
173 		return 0;
174 
175 	switch (report_bug(regs->ip, regs)) {
176 	case BUG_TRAP_TYPE_NONE:
177 	case BUG_TRAP_TYPE_BUG:
178 		break;
179 
180 	case BUG_TRAP_TYPE_WARN:
181 		regs->ip += LEN_UD2;
182 		return 1;
183 	}
184 
185 	return 0;
186 }
187 
188 static nokprobe_inline int
189 do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str,
190 		  struct pt_regs *regs,	long error_code)
191 {
192 	if (v8086_mode(regs)) {
193 		/*
194 		 * Traps 0, 1, 3, 4, and 5 should be forwarded to vm86.
195 		 * On nmi (interrupt 2), do_trap should not be called.
196 		 */
197 		if (trapnr < X86_TRAP_UD) {
198 			if (!handle_vm86_trap((struct kernel_vm86_regs *) regs,
199 						error_code, trapnr))
200 				return 0;
201 		}
202 	} else if (!user_mode(regs)) {
203 		if (fixup_exception(regs, trapnr, error_code, 0))
204 			return 0;
205 
206 		tsk->thread.error_code = error_code;
207 		tsk->thread.trap_nr = trapnr;
208 		die(str, regs, error_code);
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 do_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 	/*
264 	 * WARN*()s end up here; fix them up before we call the
265 	 * notifier chain.
266 	 */
267 	if (!user_mode(regs) && fixup_bug(regs, trapnr))
268 		return;
269 
270 	if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) !=
271 			NOTIFY_STOP) {
272 		cond_local_irq_enable(regs);
273 		do_trap(trapnr, signr, str, regs, error_code, sicode, addr);
274 	}
275 }
276 
277 #define IP ((void __user *)uprobe_get_trap_addr(regs))
278 #define DO_ERROR(trapnr, signr, sicode, addr, str, name)		   \
279 dotraplinkage void do_##name(struct pt_regs *regs, long error_code)	   \
280 {									   \
281 	do_error_trap(regs, error_code, str, trapnr, signr, sicode, addr); \
282 }
283 
284 DO_ERROR(X86_TRAP_DE,     SIGFPE,  FPE_INTDIV,   IP, "divide error",        divide_error)
285 DO_ERROR(X86_TRAP_OF,     SIGSEGV,          0, NULL, "overflow",            overflow)
286 DO_ERROR(X86_TRAP_UD,     SIGILL,  ILL_ILLOPN,   IP, "invalid opcode",      invalid_op)
287 DO_ERROR(X86_TRAP_OLD_MF, SIGFPE,           0, NULL, "coprocessor segment overrun", coprocessor_segment_overrun)
288 DO_ERROR(X86_TRAP_TS,     SIGSEGV,          0, NULL, "invalid TSS",         invalid_TSS)
289 DO_ERROR(X86_TRAP_NP,     SIGBUS,           0, NULL, "segment not present", segment_not_present)
290 DO_ERROR(X86_TRAP_SS,     SIGBUS,           0, NULL, "stack segment",       stack_segment)
291 #undef IP
292 
293 dotraplinkage void do_alignment_check(struct pt_regs *regs, long error_code)
294 {
295 	char *str = "alignment check";
296 
297 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
298 
299 	if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP)
300 		return;
301 
302 	if (!user_mode(regs))
303 		die("Split lock detected\n", regs, error_code);
304 
305 	local_irq_enable();
306 
307 	if (handle_user_split_lock(regs, error_code))
308 		return;
309 
310 	do_trap(X86_TRAP_AC, SIGBUS, "alignment check", regs,
311 		error_code, BUS_ADRALN, NULL);
312 }
313 
314 #ifdef CONFIG_VMAP_STACK
315 __visible void __noreturn handle_stack_overflow(const char *message,
316 						struct pt_regs *regs,
317 						unsigned long fault_address)
318 {
319 	printk(KERN_EMERG "BUG: stack guard page was hit at %p (stack is %p..%p)\n",
320 		 (void *)fault_address, current->stack,
321 		 (char *)current->stack + THREAD_SIZE - 1);
322 	die(message, regs, 0);
323 
324 	/* Be absolutely certain we don't return. */
325 	panic("%s", message);
326 }
327 #endif
328 
329 #if defined(CONFIG_X86_64) || defined(CONFIG_DOUBLEFAULT)
330 /*
331  * Runs on an IST stack for x86_64 and on a special task stack for x86_32.
332  *
333  * On x86_64, this is more or less a normal kernel entry.  Notwithstanding the
334  * SDM's warnings about double faults being unrecoverable, returning works as
335  * expected.  Presumably what the SDM actually means is that the CPU may get
336  * the register state wrong on entry, so returning could be a bad idea.
337  *
338  * Various CPU engineers have promised that double faults due to an IRET fault
339  * while the stack is read-only are, in fact, recoverable.
340  *
341  * On x86_32, this is entered through a task gate, and regs are synthesized
342  * from the TSS.  Returning is, in principle, okay, but changes to regs will
343  * be lost.  If, for some reason, we need to return to a context with modified
344  * regs, the shim code could be adjusted to synchronize the registers.
345  */
346 dotraplinkage void do_double_fault(struct pt_regs *regs, long error_code, unsigned long cr2)
347 {
348 	static const char str[] = "double fault";
349 	struct task_struct *tsk = current;
350 
351 #ifdef CONFIG_X86_ESPFIX64
352 	extern unsigned char native_irq_return_iret[];
353 
354 	/*
355 	 * If IRET takes a non-IST fault on the espfix64 stack, then we
356 	 * end up promoting it to a doublefault.  In that case, take
357 	 * advantage of the fact that we're not using the normal (TSS.sp0)
358 	 * stack right now.  We can write a fake #GP(0) frame at TSS.sp0
359 	 * and then modify our own IRET frame so that, when we return,
360 	 * we land directly at the #GP(0) vector with the stack already
361 	 * set up according to its expectations.
362 	 *
363 	 * The net result is that our #GP handler will think that we
364 	 * entered from usermode with the bad user context.
365 	 *
366 	 * No need for ist_enter here because we don't use RCU.
367 	 */
368 	if (((long)regs->sp >> P4D_SHIFT) == ESPFIX_PGD_ENTRY &&
369 		regs->cs == __KERNEL_CS &&
370 		regs->ip == (unsigned long)native_irq_return_iret)
371 	{
372 		struct pt_regs *gpregs = (struct pt_regs *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
373 
374 		/*
375 		 * regs->sp points to the failing IRET frame on the
376 		 * ESPFIX64 stack.  Copy it to the entry stack.  This fills
377 		 * in gpregs->ss through gpregs->ip.
378 		 *
379 		 */
380 		memmove(&gpregs->ip, (void *)regs->sp, 5*8);
381 		gpregs->orig_ax = 0;  /* Missing (lost) #GP error code */
382 
383 		/*
384 		 * Adjust our frame so that we return straight to the #GP
385 		 * vector with the expected RSP value.  This is safe because
386 		 * we won't enable interupts or schedule before we invoke
387 		 * general_protection, so nothing will clobber the stack
388 		 * frame we just set up.
389 		 *
390 		 * We will enter general_protection with kernel GSBASE,
391 		 * which is what the stub expects, given that the faulting
392 		 * RIP will be the IRET instruction.
393 		 */
394 		regs->ip = (unsigned long)general_protection;
395 		regs->sp = (unsigned long)&gpregs->orig_ax;
396 
397 		return;
398 	}
399 #endif
400 
401 	ist_enter(regs);
402 	notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV);
403 
404 	tsk->thread.error_code = error_code;
405 	tsk->thread.trap_nr = X86_TRAP_DF;
406 
407 #ifdef CONFIG_VMAP_STACK
408 	/*
409 	 * If we overflow the stack into a guard page, the CPU will fail
410 	 * to deliver #PF and will send #DF instead.  Similarly, if we
411 	 * take any non-IST exception while too close to the bottom of
412 	 * the stack, the processor will get a page fault while
413 	 * delivering the exception and will generate a double fault.
414 	 *
415 	 * According to the SDM (footnote in 6.15 under "Interrupt 14 -
416 	 * Page-Fault Exception (#PF):
417 	 *
418 	 *   Processors update CR2 whenever a page fault is detected. If a
419 	 *   second page fault occurs while an earlier page fault is being
420 	 *   delivered, the faulting linear address of the second fault will
421 	 *   overwrite the contents of CR2 (replacing the previous
422 	 *   address). These updates to CR2 occur even if the page fault
423 	 *   results in a double fault or occurs during the delivery of a
424 	 *   double fault.
425 	 *
426 	 * The logic below has a small possibility of incorrectly diagnosing
427 	 * some errors as stack overflows.  For example, if the IDT or GDT
428 	 * gets corrupted such that #GP delivery fails due to a bad descriptor
429 	 * causing #GP and we hit this condition while CR2 coincidentally
430 	 * points to the stack guard page, we'll think we overflowed the
431 	 * stack.  Given that we're going to panic one way or another
432 	 * if this happens, this isn't necessarily worth fixing.
433 	 *
434 	 * If necessary, we could improve the test by only diagnosing
435 	 * a stack overflow if the saved RSP points within 47 bytes of
436 	 * the bottom of the stack: if RSP == tsk_stack + 48 and we
437 	 * take an exception, the stack is already aligned and there
438 	 * will be enough room SS, RSP, RFLAGS, CS, RIP, and a
439 	 * possible error code, so a stack overflow would *not* double
440 	 * fault.  With any less space left, exception delivery could
441 	 * fail, and, as a practical matter, we've overflowed the
442 	 * stack even if the actual trigger for the double fault was
443 	 * something else.
444 	 */
445 	if ((unsigned long)task_stack_page(tsk) - 1 - cr2 < PAGE_SIZE)
446 		handle_stack_overflow("kernel stack overflow (double-fault)", regs, cr2);
447 #endif
448 
449 	pr_emerg("PANIC: double fault, error_code: 0x%lx\n", error_code);
450 	die("double fault", regs, error_code);
451 	panic("Machine halted.");
452 }
453 #endif
454 
455 dotraplinkage void do_bounds(struct pt_regs *regs, long error_code)
456 {
457 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
458 	if (notify_die(DIE_TRAP, "bounds", regs, error_code,
459 			X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP)
460 		return;
461 	cond_local_irq_enable(regs);
462 
463 	if (!user_mode(regs))
464 		die("bounds", regs, error_code);
465 
466 	do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, error_code, 0, NULL);
467 }
468 
469 enum kernel_gp_hint {
470 	GP_NO_HINT,
471 	GP_NON_CANONICAL,
472 	GP_CANONICAL
473 };
474 
475 /*
476  * When an uncaught #GP occurs, try to determine the memory address accessed by
477  * the instruction and return that address to the caller. Also, try to figure
478  * out whether any part of the access to that address was non-canonical.
479  */
480 static enum kernel_gp_hint get_kernel_gp_address(struct pt_regs *regs,
481 						 unsigned long *addr)
482 {
483 	u8 insn_buf[MAX_INSN_SIZE];
484 	struct insn insn;
485 
486 	if (probe_kernel_read(insn_buf, (void *)regs->ip, MAX_INSN_SIZE))
487 		return GP_NO_HINT;
488 
489 	kernel_insn_init(&insn, insn_buf, MAX_INSN_SIZE);
490 	insn_get_modrm(&insn);
491 	insn_get_sib(&insn);
492 
493 	*addr = (unsigned long)insn_get_addr_ref(&insn, regs);
494 	if (*addr == -1UL)
495 		return GP_NO_HINT;
496 
497 #ifdef CONFIG_X86_64
498 	/*
499 	 * Check that:
500 	 *  - the operand is not in the kernel half
501 	 *  - the last byte of the operand is not in the user canonical half
502 	 */
503 	if (*addr < ~__VIRTUAL_MASK &&
504 	    *addr + insn.opnd_bytes - 1 > __VIRTUAL_MASK)
505 		return GP_NON_CANONICAL;
506 #endif
507 
508 	return GP_CANONICAL;
509 }
510 
511 #define GPFSTR "general protection fault"
512 
513 dotraplinkage void do_general_protection(struct pt_regs *regs, long error_code)
514 {
515 	char desc[sizeof(GPFSTR) + 50 + 2*sizeof(unsigned long) + 1] = GPFSTR;
516 	enum kernel_gp_hint hint = GP_NO_HINT;
517 	struct task_struct *tsk;
518 	unsigned long gp_addr;
519 	int ret;
520 
521 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
522 	cond_local_irq_enable(regs);
523 
524 	if (static_cpu_has(X86_FEATURE_UMIP)) {
525 		if (user_mode(regs) && fixup_umip_exception(regs))
526 			return;
527 	}
528 
529 	if (v8086_mode(regs)) {
530 		local_irq_enable();
531 		handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code);
532 		return;
533 	}
534 
535 	tsk = current;
536 
537 	if (user_mode(regs)) {
538 		tsk->thread.error_code = error_code;
539 		tsk->thread.trap_nr = X86_TRAP_GP;
540 
541 		show_signal(tsk, SIGSEGV, "", desc, regs, error_code);
542 		force_sig(SIGSEGV);
543 
544 		return;
545 	}
546 
547 	if (fixup_exception(regs, X86_TRAP_GP, error_code, 0))
548 		return;
549 
550 	tsk->thread.error_code = error_code;
551 	tsk->thread.trap_nr = X86_TRAP_GP;
552 
553 	/*
554 	 * To be potentially processing a kprobe fault and to trust the result
555 	 * from kprobe_running(), we have to be non-preemptible.
556 	 */
557 	if (!preemptible() &&
558 	    kprobe_running() &&
559 	    kprobe_fault_handler(regs, X86_TRAP_GP))
560 		return;
561 
562 	ret = notify_die(DIE_GPF, desc, regs, error_code, X86_TRAP_GP, SIGSEGV);
563 	if (ret == NOTIFY_STOP)
564 		return;
565 
566 	if (error_code)
567 		snprintf(desc, sizeof(desc), "segment-related " GPFSTR);
568 	else
569 		hint = get_kernel_gp_address(regs, &gp_addr);
570 
571 	if (hint != GP_NO_HINT)
572 		snprintf(desc, sizeof(desc), GPFSTR ", %s 0x%lx",
573 			 (hint == GP_NON_CANONICAL) ? "probably for non-canonical address"
574 						    : "maybe for address",
575 			 gp_addr);
576 
577 	/*
578 	 * KASAN is interested only in the non-canonical case, clear it
579 	 * otherwise.
580 	 */
581 	if (hint != GP_NON_CANONICAL)
582 		gp_addr = 0;
583 
584 	die_addr(desc, regs, error_code, gp_addr);
585 
586 }
587 NOKPROBE_SYMBOL(do_general_protection);
588 
589 dotraplinkage void notrace do_int3(struct pt_regs *regs, long error_code)
590 {
591 	if (poke_int3_handler(regs))
592 		return;
593 
594 	/*
595 	 * Unlike any other non-IST entry, we can be called from a kprobe in
596 	 * non-CONTEXT_KERNEL kernel mode or even during context tracking
597 	 * state changes.  Make sure that we wake up RCU even if we're coming
598 	 * from kernel code.
599 	 *
600 	 * This means that we can't schedule even if we came from a
601 	 * preemptible kernel context.  That's okay.
602 	 */
603 	if (!user_mode(regs)) {
604 		rcu_nmi_enter();
605 		preempt_disable();
606 	}
607 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
608 
609 #ifdef CONFIG_KGDB_LOW_LEVEL_TRAP
610 	if (kgdb_ll_trap(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
611 				SIGTRAP) == NOTIFY_STOP)
612 		goto exit;
613 #endif /* CONFIG_KGDB_LOW_LEVEL_TRAP */
614 
615 #ifdef CONFIG_KPROBES
616 	if (kprobe_int3_handler(regs))
617 		goto exit;
618 #endif
619 
620 	if (notify_die(DIE_INT3, "int3", regs, error_code, X86_TRAP_BP,
621 			SIGTRAP) == NOTIFY_STOP)
622 		goto exit;
623 
624 	cond_local_irq_enable(regs);
625 	do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, error_code, 0, NULL);
626 	cond_local_irq_disable(regs);
627 
628 exit:
629 	if (!user_mode(regs)) {
630 		preempt_enable_no_resched();
631 		rcu_nmi_exit();
632 	}
633 }
634 NOKPROBE_SYMBOL(do_int3);
635 
636 #ifdef CONFIG_X86_64
637 /*
638  * Help handler running on a per-cpu (IST or entry trampoline) stack
639  * to switch to the normal thread stack if the interrupted code was in
640  * user mode. The actual stack switch is done in entry_64.S
641  */
642 asmlinkage __visible notrace struct pt_regs *sync_regs(struct pt_regs *eregs)
643 {
644 	struct pt_regs *regs = (struct pt_regs *)this_cpu_read(cpu_current_top_of_stack) - 1;
645 	if (regs != eregs)
646 		*regs = *eregs;
647 	return regs;
648 }
649 NOKPROBE_SYMBOL(sync_regs);
650 
651 struct bad_iret_stack {
652 	void *error_entry_ret;
653 	struct pt_regs regs;
654 };
655 
656 asmlinkage __visible notrace
657 struct bad_iret_stack *fixup_bad_iret(struct bad_iret_stack *s)
658 {
659 	/*
660 	 * This is called from entry_64.S early in handling a fault
661 	 * caused by a bad iret to user mode.  To handle the fault
662 	 * correctly, we want to move our stack frame to where it would
663 	 * be had we entered directly on the entry stack (rather than
664 	 * just below the IRET frame) and we want to pretend that the
665 	 * exception came from the IRET target.
666 	 */
667 	struct bad_iret_stack *new_stack =
668 		(struct bad_iret_stack *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
669 
670 	/* Copy the IRET target to the new stack. */
671 	memmove(&new_stack->regs.ip, (void *)s->regs.sp, 5*8);
672 
673 	/* Copy the remainder of the stack from the current stack. */
674 	memmove(new_stack, s, offsetof(struct bad_iret_stack, regs.ip));
675 
676 	BUG_ON(!user_mode(&new_stack->regs));
677 	return new_stack;
678 }
679 NOKPROBE_SYMBOL(fixup_bad_iret);
680 #endif
681 
682 static bool is_sysenter_singlestep(struct pt_regs *regs)
683 {
684 	/*
685 	 * We don't try for precision here.  If we're anywhere in the region of
686 	 * code that can be single-stepped in the SYSENTER entry path, then
687 	 * assume that this is a useless single-step trap due to SYSENTER
688 	 * being invoked with TF set.  (We don't know in advance exactly
689 	 * which instructions will be hit because BTF could plausibly
690 	 * be set.)
691 	 */
692 #ifdef CONFIG_X86_32
693 	return (regs->ip - (unsigned long)__begin_SYSENTER_singlestep_region) <
694 		(unsigned long)__end_SYSENTER_singlestep_region -
695 		(unsigned long)__begin_SYSENTER_singlestep_region;
696 #elif defined(CONFIG_IA32_EMULATION)
697 	return (regs->ip - (unsigned long)entry_SYSENTER_compat) <
698 		(unsigned long)__end_entry_SYSENTER_compat -
699 		(unsigned long)entry_SYSENTER_compat;
700 #else
701 	return false;
702 #endif
703 }
704 
705 /*
706  * Our handling of the processor debug registers is non-trivial.
707  * We do not clear them on entry and exit from the kernel. Therefore
708  * it is possible to get a watchpoint trap here from inside the kernel.
709  * However, the code in ./ptrace.c has ensured that the user can
710  * only set watchpoints on userspace addresses. Therefore the in-kernel
711  * watchpoint trap can only occur in code which is reading/writing
712  * from user space. Such code must not hold kernel locks (since it
713  * can equally take a page fault), therefore it is safe to call
714  * force_sig_info even though that claims and releases locks.
715  *
716  * Code in ./signal.c ensures that the debug control register
717  * is restored before we deliver any signal, and therefore that
718  * user code runs with the correct debug control register even though
719  * we clear it here.
720  *
721  * Being careful here means that we don't have to be as careful in a
722  * lot of more complicated places (task switching can be a bit lazy
723  * about restoring all the debug state, and ptrace doesn't have to
724  * find every occurrence of the TF bit that could be saved away even
725  * by user code)
726  *
727  * May run on IST stack.
728  */
729 dotraplinkage void do_debug(struct pt_regs *regs, long error_code)
730 {
731 	struct task_struct *tsk = current;
732 	int user_icebp = 0;
733 	unsigned long dr6;
734 	int si_code;
735 
736 	ist_enter(regs);
737 
738 	get_debugreg(dr6, 6);
739 	/*
740 	 * The Intel SDM says:
741 	 *
742 	 *   Certain debug exceptions may clear bits 0-3. The remaining
743 	 *   contents of the DR6 register are never cleared by the
744 	 *   processor. To avoid confusion in identifying debug
745 	 *   exceptions, debug handlers should clear the register before
746 	 *   returning to the interrupted task.
747 	 *
748 	 * Keep it simple: clear DR6 immediately.
749 	 */
750 	set_debugreg(0, 6);
751 
752 	/* Filter out all the reserved bits which are preset to 1 */
753 	dr6 &= ~DR6_RESERVED;
754 
755 	/*
756 	 * The SDM says "The processor clears the BTF flag when it
757 	 * generates a debug exception."  Clear TIF_BLOCKSTEP to keep
758 	 * TIF_BLOCKSTEP in sync with the hardware BTF flag.
759 	 */
760 	clear_tsk_thread_flag(tsk, TIF_BLOCKSTEP);
761 
762 	if (unlikely(!user_mode(regs) && (dr6 & DR_STEP) &&
763 		     is_sysenter_singlestep(regs))) {
764 		dr6 &= ~DR_STEP;
765 		if (!dr6)
766 			goto exit;
767 		/*
768 		 * else we might have gotten a single-step trap and hit a
769 		 * watchpoint at the same time, in which case we should fall
770 		 * through and handle the watchpoint.
771 		 */
772 	}
773 
774 	/*
775 	 * If dr6 has no reason to give us about the origin of this trap,
776 	 * then it's very likely the result of an icebp/int01 trap.
777 	 * User wants a sigtrap for that.
778 	 */
779 	if (!dr6 && user_mode(regs))
780 		user_icebp = 1;
781 
782 	/* Store the virtualized DR6 value */
783 	tsk->thread.debugreg6 = dr6;
784 
785 #ifdef CONFIG_KPROBES
786 	if (kprobe_debug_handler(regs))
787 		goto exit;
788 #endif
789 
790 	if (notify_die(DIE_DEBUG, "debug", regs, (long)&dr6, error_code,
791 							SIGTRAP) == NOTIFY_STOP)
792 		goto exit;
793 
794 	/*
795 	 * Let others (NMI) know that the debug stack is in use
796 	 * as we may switch to the interrupt stack.
797 	 */
798 	debug_stack_usage_inc();
799 
800 	/* It's safe to allow irq's after DR6 has been saved */
801 	cond_local_irq_enable(regs);
802 
803 	if (v8086_mode(regs)) {
804 		handle_vm86_trap((struct kernel_vm86_regs *) regs, error_code,
805 					X86_TRAP_DB);
806 		cond_local_irq_disable(regs);
807 		debug_stack_usage_dec();
808 		goto exit;
809 	}
810 
811 	if (WARN_ON_ONCE((dr6 & DR_STEP) && !user_mode(regs))) {
812 		/*
813 		 * Historical junk that used to handle SYSENTER single-stepping.
814 		 * This should be unreachable now.  If we survive for a while
815 		 * without anyone hitting this warning, we'll turn this into
816 		 * an oops.
817 		 */
818 		tsk->thread.debugreg6 &= ~DR_STEP;
819 		set_tsk_thread_flag(tsk, TIF_SINGLESTEP);
820 		regs->flags &= ~X86_EFLAGS_TF;
821 	}
822 	si_code = get_si_code(tsk->thread.debugreg6);
823 	if (tsk->thread.debugreg6 & (DR_STEP | DR_TRAP_BITS) || user_icebp)
824 		send_sigtrap(regs, error_code, si_code);
825 	cond_local_irq_disable(regs);
826 	debug_stack_usage_dec();
827 
828 exit:
829 	ist_exit(regs);
830 }
831 NOKPROBE_SYMBOL(do_debug);
832 
833 /*
834  * Note that we play around with the 'TS' bit in an attempt to get
835  * the correct behaviour even in the presence of the asynchronous
836  * IRQ13 behaviour
837  */
838 static void math_error(struct pt_regs *regs, int error_code, int trapnr)
839 {
840 	struct task_struct *task = current;
841 	struct fpu *fpu = &task->thread.fpu;
842 	int si_code;
843 	char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" :
844 						"simd exception";
845 
846 	cond_local_irq_enable(regs);
847 
848 	if (!user_mode(regs)) {
849 		if (fixup_exception(regs, trapnr, error_code, 0))
850 			return;
851 
852 		task->thread.error_code = error_code;
853 		task->thread.trap_nr = trapnr;
854 
855 		if (notify_die(DIE_TRAP, str, regs, error_code,
856 					trapnr, SIGFPE) != NOTIFY_STOP)
857 			die(str, regs, error_code);
858 		return;
859 	}
860 
861 	/*
862 	 * Save the info for the exception handler and clear the error.
863 	 */
864 	fpu__save(fpu);
865 
866 	task->thread.trap_nr	= trapnr;
867 	task->thread.error_code = error_code;
868 
869 	si_code = fpu__exception_code(fpu, trapnr);
870 	/* Retry when we get spurious exceptions: */
871 	if (!si_code)
872 		return;
873 
874 	force_sig_fault(SIGFPE, si_code,
875 			(void __user *)uprobe_get_trap_addr(regs));
876 }
877 
878 dotraplinkage void do_coprocessor_error(struct pt_regs *regs, long error_code)
879 {
880 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
881 	math_error(regs, error_code, X86_TRAP_MF);
882 }
883 
884 dotraplinkage void
885 do_simd_coprocessor_error(struct pt_regs *regs, long error_code)
886 {
887 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
888 	math_error(regs, error_code, X86_TRAP_XF);
889 }
890 
891 dotraplinkage void
892 do_spurious_interrupt_bug(struct pt_regs *regs, long error_code)
893 {
894 	/*
895 	 * This addresses a Pentium Pro Erratum:
896 	 *
897 	 * PROBLEM: If the APIC subsystem is configured in mixed mode with
898 	 * Virtual Wire mode implemented through the local APIC, an
899 	 * interrupt vector of 0Fh (Intel reserved encoding) may be
900 	 * generated by the local APIC (Int 15).  This vector may be
901 	 * generated upon receipt of a spurious interrupt (an interrupt
902 	 * which is removed before the system receives the INTA sequence)
903 	 * instead of the programmed 8259 spurious interrupt vector.
904 	 *
905 	 * IMPLICATION: The spurious interrupt vector programmed in the
906 	 * 8259 is normally handled by an operating system's spurious
907 	 * interrupt handler. However, a vector of 0Fh is unknown to some
908 	 * operating systems, which would crash if this erratum occurred.
909 	 *
910 	 * In theory this could be limited to 32bit, but the handler is not
911 	 * hurting and who knows which other CPUs suffer from this.
912 	 */
913 }
914 
915 dotraplinkage void
916 do_device_not_available(struct pt_regs *regs, long error_code)
917 {
918 	unsigned long cr0 = read_cr0();
919 
920 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
921 
922 #ifdef CONFIG_MATH_EMULATION
923 	if (!boot_cpu_has(X86_FEATURE_FPU) && (cr0 & X86_CR0_EM)) {
924 		struct math_emu_info info = { };
925 
926 		cond_local_irq_enable(regs);
927 
928 		info.regs = regs;
929 		math_emulate(&info);
930 		return;
931 	}
932 #endif
933 
934 	/* This should not happen. */
935 	if (WARN(cr0 & X86_CR0_TS, "CR0.TS was set")) {
936 		/* Try to fix it up and carry on. */
937 		write_cr0(cr0 & ~X86_CR0_TS);
938 	} else {
939 		/*
940 		 * Something terrible happened, and we're better off trying
941 		 * to kill the task than getting stuck in a never-ending
942 		 * loop of #NM faults.
943 		 */
944 		die("unexpected #NM exception", regs, error_code);
945 	}
946 }
947 NOKPROBE_SYMBOL(do_device_not_available);
948 
949 #ifdef CONFIG_X86_32
950 dotraplinkage void do_iret_error(struct pt_regs *regs, long error_code)
951 {
952 	RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
953 	local_irq_enable();
954 
955 	if (notify_die(DIE_TRAP, "iret exception", regs, error_code,
956 			X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) {
957 		do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, error_code,
958 			ILL_BADSTK, (void __user *)NULL);
959 	}
960 }
961 #endif
962 
963 void __init trap_init(void)
964 {
965 	/* Init cpu_entry_area before IST entries are set up */
966 	setup_cpu_entry_areas();
967 
968 	idt_setup_traps();
969 
970 	/*
971 	 * Set the IDT descriptor to a fixed read-only location, so that the
972 	 * "sidt" instruction will not leak the location of the kernel, and
973 	 * to defend the IDT against arbitrary memory write vulnerabilities.
974 	 * It will be reloaded in cpu_init() */
975 	cea_set_pte(CPU_ENTRY_AREA_RO_IDT_VADDR, __pa_symbol(idt_table),
976 		    PAGE_KERNEL_RO);
977 	idt_descr.address = CPU_ENTRY_AREA_RO_IDT;
978 
979 	/*
980 	 * Should be a barrier for any external CPU state:
981 	 */
982 	cpu_init();
983 
984 	idt_setup_ist_traps();
985 
986 	x86_init.irqs.trap_init();
987 
988 	idt_setup_debugidt_traps();
989 }
990