xref: /xnu-11215.41.3/osfmk/i386/trap.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 /*
57  */
58 
59 /*
60  * Hardware trap/fault handler.
61  */
62 
63 #include <mach_kdp.h>
64 #include <mach_ldebug.h>
65 
66 #include <types.h>
67 #include <i386/eflags.h>
68 #include <i386/trap_internal.h>
69 #include <i386/pmap.h>
70 #include <i386/fpu.h>
71 #include <i386/panic_notify.h>
72 #include <i386/lapic.h>
73 
74 #include <mach/exception.h>
75 #include <mach/kern_return.h>
76 #include <mach/vm_param.h>
77 #include <mach/i386/thread_status.h>
78 
79 #include <vm/vm_kern.h>
80 #include <vm/vm_fault.h>
81 #include <vm/vm_map_xnu.h>
82 
83 #include <kern/kern_types.h>
84 #include <kern/processor.h>
85 #include <kern/thread.h>
86 #include <kern/task.h>
87 #include <kern/restartable.h>
88 #include <kern/sched.h>
89 #include <kern/sched_prim.h>
90 #include <kern/exception.h>
91 #include <kern/spl.h>
92 #include <kern/misc_protos.h>
93 #include <kern/debug.h>
94 #if CONFIG_TELEMETRY
95 #include <kern/telemetry.h>
96 #endif
97 #include <kern/zalloc_internal.h>
98 #include <sys/kdebug.h>
99 #include <kperf/kperf.h>
100 #include <prng/random.h>
101 #include <prng/entropy.h>
102 
103 #include <string.h>
104 
105 #include <i386/postcode.h>
106 #include <i386/mp_desc.h>
107 #include <i386/proc_reg.h>
108 #include <i386/machine_routines.h>
109 #if CONFIG_MCA
110 #include <i386/machine_check.h>
111 #endif
112 #include <mach/i386/syscall_sw.h>
113 
114 #include <libkern/OSDebug.h>
115 #include <i386/cpu_threads.h>
116 #include <machine/pal_routines.h>
117 #include <i386/lbr.h>
118 
119 extern void throttle_lowpri_io(int);
120 extern void kprint_state(x86_saved_state64_t *saved_state);
121 #if DEVELOPMENT || DEBUG
122 int insnstream_force_cacheline_mismatch = 0;
123 extern int panic_on_cacheline_mismatch;
124 extern char panic_on_trap_procname[];
125 extern uint32_t panic_on_trap_mask;
126 #endif
127 
128 extern int insn_copyin_count;
129 
130 /*
131  * Forward declarations
132  */
133 static void panic_trap(x86_saved_state64_t *saved_state, const char *trapreason, uint32_t pl, kern_return_t fault_result) __dead2;
134 static void set_recovery_ip(x86_saved_state64_t *saved_state, vm_offset_t ip);
135 #if DEVELOPMENT || DEBUG
136 static __attribute__((noinline)) void copy_instruction_stream(thread_t thread, uint64_t rip, int trap_code, bool inspect_cacheline);
137 #else
138 static __attribute__((noinline)) void copy_instruction_stream(thread_t thread, uint64_t rip, int trap_code);
139 #endif
140 
141 #if CONFIG_DTRACE
142 /* See <rdar://problem/4613924> */
143 perfCallback tempDTraceTrapHook = NULL; /* Pointer to DTrace fbt trap hook routine */
144 
145 extern boolean_t dtrace_tally_fault(user_addr_t);
146 extern boolean_t dtrace_handle_trap(int, x86_saved_state_t *);
147 #endif
148 
149 #ifdef MACH_BSD
150 extern char *   proc_name_address(void *p);
151 #endif /* MACH_BSD */
152 
153 extern boolean_t pmap_smep_enabled;
154 extern boolean_t pmap_smap_enabled;
155 
156 __attribute__((noreturn))
157 void
thread_syscall_return(kern_return_t ret)158 thread_syscall_return(
159 	kern_return_t ret)
160 {
161 	thread_t        thr_act = current_thread();
162 	boolean_t       is_mach;
163 	int             code;
164 
165 	pal_register_cache_state(thr_act, DIRTY);
166 
167 	if (thread_is_64bit_addr(thr_act)) {
168 		x86_saved_state64_t     *regs;
169 
170 		regs = USER_REGS64(thr_act);
171 
172 		code = (int) (regs->rax & SYSCALL_NUMBER_MASK);
173 		is_mach = (regs->rax & SYSCALL_CLASS_MASK)
174 		    == (SYSCALL_CLASS_MACH << SYSCALL_CLASS_SHIFT);
175 		if (kdebug_enable && is_mach) {
176 			/* Mach trap */
177 			KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
178 			    MACHDBG_CODE(DBG_MACH_EXCP_SC, code) | DBG_FUNC_END,
179 			    ret, 0, 0, 0, 0);
180 		}
181 		regs->rax = ret;
182 #if DEBUG
183 		if (is_mach) {
184 			DEBUG_KPRINT_SYSCALL_MACH(
185 				"thread_syscall_return: 64-bit mach ret=%u\n",
186 				ret);
187 		} else {
188 			DEBUG_KPRINT_SYSCALL_UNIX(
189 				"thread_syscall_return: 64-bit unix ret=%u\n",
190 				ret);
191 		}
192 #endif
193 	} else {
194 		x86_saved_state32_t     *regs;
195 
196 		regs = USER_REGS32(thr_act);
197 
198 		code = ((int) regs->eax);
199 		is_mach = (code < 0);
200 		if (kdebug_enable && is_mach) {
201 			/* Mach trap */
202 			KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
203 			    MACHDBG_CODE(DBG_MACH_EXCP_SC, -code) | DBG_FUNC_END,
204 			    ret, 0, 0, 0, 0);
205 		}
206 		regs->eax = ret;
207 #if DEBUG
208 		if (is_mach) {
209 			DEBUG_KPRINT_SYSCALL_MACH(
210 				"thread_syscall_return: 32-bit mach ret=%u\n",
211 				ret);
212 		} else {
213 			DEBUG_KPRINT_SYSCALL_UNIX(
214 				"thread_syscall_return: 32-bit unix ret=%u\n",
215 				ret);
216 		}
217 #endif
218 	}
219 
220 #if DEBUG || DEVELOPMENT
221 	kern_allocation_name_t
222 	prior __assert_only = thread_get_kernel_state(thr_act)->allocation_name;
223 	assertf(prior == NULL, "thread_set_allocation_name(\"%s\") not cleared", kern_allocation_get_name(prior));
224 #endif /* DEBUG || DEVELOPMENT */
225 
226 	throttle_lowpri_io(1);
227 
228 	thread_exception_return();
229 	/*NOTREACHED*/
230 }
231 
232 /*
233  * Fault recovery in copyin/copyout routines.
234  */
235 struct recovery {
236 	uintptr_t       fault_addr;
237 	uintptr_t       recover_addr;
238 };
239 
240 extern struct recovery  recover_table[];
241 extern struct recovery  recover_table_end[];
242 
243 const char *    trap_type[] = {TRAP_NAMES};
244 unsigned        TRAP_TYPES = sizeof(trap_type) / sizeof(trap_type[0]);
245 
246 extern void     PE_incoming_interrupt(int interrupt);
247 
248 #if defined(__x86_64__) && DEBUG
249 void
kprint_state(x86_saved_state64_t * saved_state)250 kprint_state(x86_saved_state64_t        *saved_state)
251 {
252 	kprintf("current_cpu_datap() 0x%lx\n", (uintptr_t)current_cpu_datap());
253 	kprintf("Current GS base MSR 0x%llx\n", rdmsr64(MSR_IA32_GS_BASE));
254 	kprintf("Kernel  GS base MSR 0x%llx\n", rdmsr64(MSR_IA32_KERNEL_GS_BASE));
255 	kprintf("state at 0x%lx:\n", (uintptr_t) saved_state);
256 
257 	kprintf("      rdi    0x%llx\n", saved_state->rdi);
258 	kprintf("      rsi    0x%llx\n", saved_state->rsi);
259 	kprintf("      rdx    0x%llx\n", saved_state->rdx);
260 	kprintf("      r10    0x%llx\n", saved_state->r10);
261 	kprintf("      r8     0x%llx\n", saved_state->r8);
262 	kprintf("      r9     0x%llx\n", saved_state->r9);
263 
264 	kprintf("      cr2    0x%llx\n", saved_state->cr2);
265 	kprintf("real  cr2    0x%lx\n", get_cr2());
266 	kprintf("      r15    0x%llx\n", saved_state->r15);
267 	kprintf("      r14    0x%llx\n", saved_state->r14);
268 	kprintf("      r13    0x%llx\n", saved_state->r13);
269 	kprintf("      r12    0x%llx\n", saved_state->r12);
270 	kprintf("      r11    0x%llx\n", saved_state->r11);
271 	kprintf("      rbp    0x%llx\n", saved_state->rbp);
272 	kprintf("      rbx    0x%llx\n", saved_state->rbx);
273 	kprintf("      rcx    0x%llx\n", saved_state->rcx);
274 	kprintf("      rax    0x%llx\n", saved_state->rax);
275 
276 	kprintf("      gs     0x%x\n", saved_state->gs);
277 	kprintf("      fs     0x%x\n", saved_state->fs);
278 
279 	kprintf("  isf.trapno 0x%x\n", saved_state->isf.trapno);
280 	kprintf("  isf._pad   0x%x\n", saved_state->isf._pad);
281 	kprintf("  isf.trapfn 0x%llx\n", saved_state->isf.trapfn);
282 	kprintf("  isf.err    0x%llx\n", saved_state->isf.err);
283 	kprintf("  isf.rip    0x%llx\n", saved_state->isf.rip);
284 	kprintf("  isf.cs     0x%llx\n", saved_state->isf.cs);
285 	kprintf("  isf.rflags 0x%llx\n", saved_state->isf.rflags);
286 	kprintf("  isf.rsp    0x%llx\n", saved_state->isf.rsp);
287 	kprintf("  isf.ss     0x%llx\n", saved_state->isf.ss);
288 }
289 #endif
290 
291 
292 /*
293  * Non-zero indicates latency assert is enabled and capped at valued
294  * absolute time units.
295  */
296 
297 uint64_t interrupt_latency_cap = 0;
298 boolean_t ilat_assert = FALSE;
299 
300 void
interrupt_latency_tracker_setup(void)301 interrupt_latency_tracker_setup(void)
302 {
303 	uint32_t ilat_cap_us;
304 	if (PE_parse_boot_argn("interrupt_latency_cap_us", &ilat_cap_us, sizeof(ilat_cap_us))) {
305 		interrupt_latency_cap = ilat_cap_us * NSEC_PER_USEC;
306 		nanoseconds_to_absolutetime(interrupt_latency_cap, &interrupt_latency_cap);
307 	} else {
308 		interrupt_latency_cap = LockTimeOut;
309 	}
310 	PE_parse_boot_argn("-interrupt_latency_assert_enable", &ilat_assert, sizeof(ilat_assert));
311 }
312 
313 void
interrupt_reset_latency_stats(void)314 interrupt_reset_latency_stats(void)
315 {
316 	uint32_t i;
317 	for (i = 0; i < real_ncpus; i++) {
318 		cpu_data_ptr[i]->cpu_max_observed_int_latency =
319 		    cpu_data_ptr[i]->cpu_max_observed_int_latency_vector = 0;
320 	}
321 }
322 
323 void
interrupt_populate_latency_stats(char * buf,unsigned bufsize)324 interrupt_populate_latency_stats(char *buf, unsigned bufsize)
325 {
326 	uint32_t i, tcpu = ~0;
327 	uint64_t cur_max = 0;
328 
329 	for (i = 0; i < real_ncpus; i++) {
330 		if (cur_max < cpu_data_ptr[i]->cpu_max_observed_int_latency) {
331 			cur_max = cpu_data_ptr[i]->cpu_max_observed_int_latency;
332 			tcpu = i;
333 		}
334 	}
335 
336 	if (tcpu < real_ncpus) {
337 		snprintf(buf, bufsize, "0x%x 0x%x 0x%llx", tcpu, cpu_data_ptr[tcpu]->cpu_max_observed_int_latency_vector, cpu_data_ptr[tcpu]->cpu_max_observed_int_latency);
338 	}
339 }
340 
341 uint32_t interrupt_timer_coalescing_enabled = 1;
342 uint64_t interrupt_coalesced_timers;
343 
344 /*
345  * Handle interrupts:
346  *  - local APIC interrupts (IPIs, timers, etc) are handled by the kernel,
347  *  - device interrupts go to the platform expert.
348  */
349 void
interrupt(x86_saved_state_t * state)350 interrupt(x86_saved_state_t *state)
351 {
352 	uint64_t        rip;
353 	uint64_t        rsp;
354 	int             interrupt_num;
355 	boolean_t       user_mode = FALSE;
356 	int             ipl;
357 	int             cnum = cpu_number();
358 	cpu_data_t      *cdp = cpu_data_ptr[cnum];
359 	int             itype = DBG_INTR_TYPE_UNKNOWN;
360 	int             handled;
361 
362 
363 	x86_saved_state64_t     *state64 = saved_state64(state);
364 	rip = state64->isf.rip;
365 	rsp = state64->isf.rsp;
366 	interrupt_num = state64->isf.trapno;
367 	if (state64->isf.cs & 0x03) {
368 		user_mode = TRUE;
369 	}
370 
371 #if DEVELOPMENT || DEBUG
372 	uint64_t frameptr = is_saved_state64(state) ? state64->rbp : saved_state32(state)->ebp;
373 	uint32_t traptrace_index = traptrace_start(interrupt_num, rip, mach_absolute_time(), frameptr);
374 #endif
375 
376 	if (cpu_data_ptr[cnum]->lcpu.package->num_idle == topoParms.nLThreadsPerPackage) {
377 		cpu_data_ptr[cnum]->cpu_hwIntpexits[interrupt_num]++;
378 	}
379 
380 	if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_INTERPROCESSOR_INTERRUPT)) {
381 		itype = DBG_INTR_TYPE_IPI;
382 	} else if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_TIMER_INTERRUPT)) {
383 		itype = DBG_INTR_TYPE_TIMER;
384 	} else {
385 		itype = DBG_INTR_TYPE_OTHER;
386 	}
387 
388 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
389 	    MACHDBG_CODE(DBG_MACH_EXCP_INTR, 0) | DBG_FUNC_START,
390 	    interrupt_num,
391 	    (user_mode ? rip : VM_KERNEL_UNSLIDE(rip)),
392 	    user_mode, itype, 0);
393 
394 	SCHED_STATS_INC(interrupt_count);
395 
396 #if CONFIG_TELEMETRY
397 	if (telemetry_needs_record) {
398 		telemetry_mark_curthread(user_mode, FALSE);
399 	}
400 #endif
401 
402 	ipl = get_preemption_level();
403 
404 	/*
405 	 * Handle local APIC interrupts
406 	 * else call platform expert for devices.
407 	 */
408 	handled = lapic_interrupt(interrupt_num, state);
409 
410 	if (!handled) {
411 		if (interrupt_num == (LAPIC_DEFAULT_INTERRUPT_BASE + LAPIC_CMCI_INTERRUPT)) {
412 			/*
413 			 * CMCI can be signalled on any logical processor, and the kexts
414 			 * that implement handling CMCI use IOKit to register handlers for
415 			 * the CMCI vector, so if we see a CMCI, do not encode a CPU
416 			 * number in bits 8:31 (since the vector is the same regardless of
417 			 * the handling CPU).
418 			 */
419 			PE_incoming_interrupt(interrupt_num);
420 		} else if (cnum <= lapic_max_interrupt_cpunum) {
421 			PE_incoming_interrupt((cnum << 8) | interrupt_num);
422 		}
423 	}
424 
425 	if (__improbable(get_preemption_level() != ipl)) {
426 		panic("Preemption level altered by interrupt vector 0x%x: initial 0x%x, final: 0x%x", interrupt_num, ipl, get_preemption_level());
427 	}
428 
429 
430 	if (__improbable(cdp->cpu_nested_istack)) {
431 		cdp->cpu_nested_istack_events++;
432 	} else {
433 		uint64_t ctime = mach_absolute_time();
434 		uint64_t int_latency = ctime - cdp->cpu_int_event_time;
435 		uint64_t esdeadline, ehdeadline;
436 		/* Attempt to process deferred timers in the context of
437 		 * this interrupt, unless interrupt time has already exceeded
438 		 * TCOAL_ILAT_THRESHOLD.
439 		 */
440 #define TCOAL_ILAT_THRESHOLD (30000ULL)
441 
442 		if ((int_latency < TCOAL_ILAT_THRESHOLD) &&
443 		    interrupt_timer_coalescing_enabled) {
444 			esdeadline = cdp->rtclock_timer.queue.earliest_soft_deadline;
445 			ehdeadline = cdp->rtclock_timer.deadline;
446 			if ((ctime >= esdeadline) && (ctime < ehdeadline)) {
447 				interrupt_coalesced_timers++;
448 				TCOAL_DEBUG(0x88880000 | DBG_FUNC_START, ctime, esdeadline, ehdeadline, interrupt_coalesced_timers, 0);
449 				rtclock_intr(state);
450 				TCOAL_DEBUG(0x88880000 | DBG_FUNC_END, ctime, esdeadline, interrupt_coalesced_timers, 0, 0);
451 			} else {
452 				TCOAL_DEBUG(0x77770000, ctime, cdp->rtclock_timer.queue.earliest_soft_deadline, cdp->rtclock_timer.deadline, interrupt_coalesced_timers, 0);
453 			}
454 		}
455 
456 		if (__improbable(ilat_assert && (int_latency > interrupt_latency_cap) && !machine_timeout_suspended())) {
457 			panic("Interrupt vector 0x%x exceeded interrupt latency threshold, 0x%llx absolute time delta, prior signals: 0x%x, current signals: 0x%x", interrupt_num, int_latency, cdp->cpu_prior_signals, cdp->cpu_signals);
458 		}
459 
460 		if (__improbable(int_latency > cdp->cpu_max_observed_int_latency)) {
461 			cdp->cpu_max_observed_int_latency = int_latency;
462 			cdp->cpu_max_observed_int_latency_vector = interrupt_num;
463 		}
464 	}
465 
466 	/*
467 	 * Having serviced the interrupt first, look at the interrupted stack depth.
468 	 */
469 	if (!user_mode) {
470 		uint64_t depth = cdp->cpu_kernel_stack
471 		    + sizeof(struct thread_kernel_state)
472 		    + sizeof(struct i386_exception_link *)
473 		    - rsp;
474 		if (__improbable(depth > kernel_stack_depth_max)) {
475 			kernel_stack_depth_max = (vm_offset_t)depth;
476 			KERNEL_DEBUG_CONSTANT(
477 				MACHDBG_CODE(DBG_MACH_SCHED, MACH_STACK_DEPTH),
478 				(long) depth, (long) VM_KERNEL_UNSLIDE(rip), 0, 0, 0);
479 		}
480 	}
481 
482 	if (cnum == master_cpu) {
483 		entropy_collect();
484 	}
485 
486 #if KPERF
487 	kperf_interrupt();
488 #endif /* KPERF */
489 
490 	KDBG_RELEASE(MACHDBG_CODE(DBG_MACH_EXCP_INTR, 0) | DBG_FUNC_END,
491 	    interrupt_num);
492 
493 	assert(ml_get_interrupts_enabled() == FALSE);
494 
495 #if DEVELOPMENT || DEBUG
496 	if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
497 		traptrace_end(traptrace_index, mach_absolute_time());
498 	}
499 #endif
500 }
501 
502 static inline void
reset_dr7(void)503 reset_dr7(void)
504 {
505 	long dr7 = 0x400; /* magic dr7 reset value; 32 bit on i386, 64 bit on x86_64 */
506 	__asm__ volatile ("mov %0,%%dr7" : : "r" (dr7));
507 }
508 #if MACH_KDP
509 unsigned kdp_has_active_watchpoints = 0;
510 #define NO_WATCHPOINTS (!kdp_has_active_watchpoints)
511 #else
512 #define NO_WATCHPOINTS 1
513 #endif
514 
515 static uint32_t bound_chk_violations_event;
516 
517 static void
xnu_soft_trap_handle_breakpoint(__unused void * tstate,uint16_t comment)518 xnu_soft_trap_handle_breakpoint(
519 	__unused void     *tstate,
520 	uint16_t          comment)
521 {
522 	if (comment == CLANG_SOFT_TRAP_BOUND_CHK) {
523 		os_atomic_inc(&bound_chk_violations_event, relaxed);
524 	}
525 }
526 
527 KERNEL_BRK_DESCRIPTOR_DEFINE(clang_desc,
528     .type                = KERNEL_BRK_TYPE_CLANG,
529     .base                = CLANG_X86_TRAP_START,
530     .max                 = CLANG_X86_TRAP_END,
531     .options             = KERNEL_BRK_UNRECOVERABLE,
532     .handle_breakpoint   = NULL);
533 
534 KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_soft_traps_desc,
535     .type                = KERNEL_BRK_TYPE_TELEMETRY,
536     .base                = XNU_SOFT_TRAP_START,
537     .max                 = XNU_SOFT_TRAP_END,
538     .options             = KERNEL_BRK_RECOVERABLE | KERNEL_BRK_CORE_ANALYTICS,
539     .handle_breakpoint   = xnu_soft_trap_handle_breakpoint);
540 
541 KERNEL_BRK_DESCRIPTOR_DEFINE(libcxx_desc,
542     .type                = KERNEL_BRK_TYPE_LIBCXX,
543     .base                = LIBCXX_TRAP_START,
544     .max                 = LIBCXX_TRAP_END,
545     .options             = KERNEL_BRK_UNRECOVERABLE,
546     .handle_breakpoint   = NULL);
547 
548 KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_hard_traps_desc,
549     .type                = KERNEL_BRK_TYPE_XNU,
550     .base                = XNU_HARD_TRAP_START,
551     .max                 = XNU_HARD_TRAP_END,
552     .options             = KERNEL_BRK_UNRECOVERABLE,
553     .handle_breakpoint   = NULL);
554 
555 static bool
handle_kernel_breakpoint(x86_saved_state64_t * state,uint16_t * out_comment)556 handle_kernel_breakpoint(x86_saved_state64_t *state, uint16_t *out_comment)
557 {
558 	uint16_t comment;
559 	const struct kernel_brk_descriptor *desc;
560 	uint8_t inst_buf[8];
561 	uint32_t prefix16 = 0x80B90F67; /* Encoding prefix for ud1 <16-bit code>(%eax), %eax */
562 	uint32_t prefix8 = 0x40B90F67; /* Encoding prefix for ud1 <8-bit code>(%eax), %eax */
563 	bool found_prefix8 = false;
564 
565 	vm_size_t sz = ml_nofault_copy(state->isf.rip, (vm_offset_t)inst_buf, sizeof(inst_buf));
566 	if (sz != sizeof(inst_buf)) {
567 		return false;
568 	}
569 
570 	if (bcmp(inst_buf, &prefix16, sizeof(prefix16)) == 0) {
571 		/* The two bytes following the prefix is our code */
572 		comment = inst_buf[5] << 8 | inst_buf[4];
573 	} else if (bcmp(inst_buf, &prefix8, sizeof(prefix8)) == 0) {
574 		/* The one byte following the prefix is our code */
575 		found_prefix8 = true;
576 		comment = inst_buf[4];
577 	} else {
578 		return false;
579 	}
580 
581 	if (out_comment) {
582 		*out_comment = comment;
583 	}
584 	desc = find_brk_descriptor_by_comment(comment);
585 
586 	if (!desc) {
587 		return false;
588 	}
589 
590 	if (desc->options & KERNEL_BRK_TELEMETRY_OPTIONS) {
591 		telemetry_kernel_brk(desc->type, desc->options, (void *)state, comment);
592 	}
593 
594 	if (desc->handle_breakpoint) {
595 		desc->handle_breakpoint(state, comment); /* May trigger panic */
596 	}
597 
598 	/* Still alive? Check if we should recover. */
599 	if (desc->options & KERNEL_BRK_RECOVERABLE) {
600 		/* ud1 can be five or eight-byte long depending on the prefix */
601 		set_recovery_ip(state, state->isf.rip + (found_prefix8 ? 5 : 8));
602 		return true;
603 	}
604 
605 	return false;
606 }
607 
608 // Find a recovery entry for an instruction address if one is present.
609 static struct recovery const*
find_recovery_entry(vm_offset_t kern_ip)610 find_recovery_entry(vm_offset_t kern_ip)
611 {
612 	for (struct recovery const* rp = recover_table; rp < recover_table_end; rp++) {
613 		if (kern_ip == rp->fault_addr) {
614 			return rp;
615 		}
616 	}
617 	return NULL;
618 }
619 
620 /*
621  * Trap from kernel mode.  Only page-fault errors are recoverable,
622  * and then only in special circumstances.  All other errors are
623  * fatal.  Return value indicates if trap was handled.
624  */
625 
626 void
kernel_trap(x86_saved_state_t * state,uintptr_t * lo_spp)627 kernel_trap(
628 	x86_saved_state_t       *state,
629 	uintptr_t *lo_spp)
630 {
631 	char                    trapreason[32];
632 	const char              *trapname = NULL;
633 	uint16_t                trapcomment = 0;
634 
635 	x86_saved_state64_t     *saved_state;
636 	int                     code;
637 	user_addr_t             vaddr;
638 	int                     type;
639 	vm_map_t                map = 0;        /* protected by T_PAGE_FAULT */
640 	kern_return_t           result = KERN_FAILURE;
641 	kern_return_t           fault_result = KERN_SUCCESS;
642 	thread_t                thread;
643 	boolean_t               intr;
644 	vm_prot_t               prot;
645 	struct recovery const   *rp = NULL;
646 	vm_offset_t             kern_ip;
647 	int                     is_user;
648 	int                     trap_pl = get_preemption_level();
649 
650 	thread = current_thread();
651 
652 	if (__improbable(is_saved_state32(state))) {
653 		panic("kernel_trap(%p) with 32-bit state", state);
654 	}
655 	saved_state = saved_state64(state);
656 
657 	/* Record cpu where state was captured */
658 	saved_state->isf.cpu = cpu_number();
659 
660 	vaddr = (user_addr_t)saved_state->cr2;
661 	type  = saved_state->isf.trapno;
662 	code  = (int)(saved_state->isf.err & 0xffff);
663 	intr  = (saved_state->isf.rflags & EFL_IF) != 0;        /* state of ints at trap */
664 	kern_ip = (vm_offset_t)saved_state->isf.rip;
665 
666 	is_user = (vaddr < VM_MAX_USER_PAGE_ADDRESS);
667 
668 #if DEVELOPMENT || DEBUG
669 	uint32_t traptrace_index = traptrace_start(type, kern_ip, mach_absolute_time(), saved_state->rbp);
670 #endif
671 
672 #if CONFIG_DTRACE
673 	/*
674 	 * Is there a DTrace hook?
675 	 */
676 	if (__improbable(tempDTraceTrapHook != NULL)) {
677 		if (tempDTraceTrapHook(type, state, lo_spp, 0) == KERN_SUCCESS) {
678 			/*
679 			 * If it succeeds, we are done...
680 			 */
681 			goto common_return;
682 		}
683 	}
684 
685 	/* Handle traps originated from probe context. */
686 	if (thread != THREAD_NULL && thread->t_dtrace_inprobe) {
687 		if (dtrace_handle_trap(type, state)) {
688 			goto common_return;
689 		}
690 	}
691 
692 #endif /* CONFIG_DTRACE */
693 
694 	/*
695 	 * we come here with interrupts off as we don't want to recurse
696 	 * on preemption below.  but we do want to re-enable interrupts
697 	 * as soon we possibly can to hold latency down
698 	 */
699 	if (__improbable(T_PREEMPT == type)) {
700 		ast_taken_kernel();
701 
702 		KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
703 		    (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
704 		    0, 0, 0, VM_KERNEL_UNSLIDE(kern_ip), 0);
705 
706 		goto common_return;
707 	}
708 
709 	user_addr_t     kd_vaddr = is_user ? vaddr : VM_KERNEL_UNSLIDE(vaddr);
710 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
711 	    (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
712 	    (unsigned)(kd_vaddr >> 32), (unsigned)kd_vaddr, is_user,
713 	    VM_KERNEL_UNSLIDE(kern_ip), 0);
714 
715 
716 	if (T_PAGE_FAULT == type) {
717 		/*
718 		 * assume we're faulting in the kernel map
719 		 */
720 		map = kernel_map;
721 
722 		if (__probable((thread != THREAD_NULL) && (thread->map != kernel_map) &&
723 		    (vaddr < VM_MAX_USER_PAGE_ADDRESS))) {
724 			/* fault occurred in userspace */
725 			map = thread->map;
726 
727 			/* Intercept a potential Supervisor Mode Execute
728 			 * Protection fault. These criteria identify
729 			 * both NX faults and SMEP faults, but both
730 			 * are fatal. We avoid checking PTEs (racy).
731 			 * (The VM could just redrive a SMEP fault, hence
732 			 * the intercept).
733 			 */
734 			if (__improbable((code == (T_PF_PROT | T_PF_EXECUTE)) &&
735 			    (pmap_smep_enabled) && (saved_state->isf.rip == vaddr))) {
736 				goto debugger_entry;
737 			}
738 
739 			/*
740 			 * Additionally check for SMAP faults...
741 			 * which are characterized by page-present and
742 			 * the AC bit unset (i.e. not from copyin/out path).
743 			 */
744 			if (__improbable(code & T_PF_PROT &&
745 			    pmap_smap_enabled &&
746 			    (saved_state->isf.rflags & EFL_AC) == 0)) {
747 				goto debugger_entry;
748 			}
749 
750 			/*
751 			 * If we're not sharing cr3 with the user
752 			 * and we faulted in copyio,
753 			 * then switch cr3 here and dismiss the fault.
754 			 */
755 			if (no_shared_cr3 &&
756 			    (thread->machine.specFlags & CopyIOActive) &&
757 			    map->pmap->pm_cr3 != get_cr3_base()) {
758 				pmap_assert(current_cpu_datap()->cpu_pmap_pcid_enabled == FALSE);
759 				set_cr3_raw(map->pmap->pm_cr3);
760 				return;
761 			}
762 			if (__improbable(vaddr < PAGE_SIZE) &&
763 			    ((thread->machine.specFlags & CopyIOActive) == 0)) {
764 				goto debugger_entry;
765 			}
766 		}
767 	}
768 
769 	(void) ml_set_interrupts_enabled(intr);
770 
771 	switch (type) {
772 	case T_NO_FPU:
773 		fpnoextflt();
774 		goto common_return;
775 
776 	case T_FPU_FAULT:
777 		fpextovrflt();
778 		goto common_return;
779 
780 	case T_FLOATING_POINT_ERROR:
781 		fpexterrflt();
782 		goto common_return;
783 
784 	case T_SSE_FLOAT_ERROR:
785 		fpSSEexterrflt();
786 		goto common_return;
787 
788 	case T_INVALID_OPCODE:
789 		if (handle_kernel_breakpoint(saved_state, &trapcomment)) {
790 			goto common_return;
791 		} else if (trapcomment != 0) {
792 			/* augment trap name with trap comment */
793 			trapname = tsnprintf(trapreason, sizeof(trapreason), "%s #%#04hx", trap_type[type], trapcomment);
794 		}
795 		fpUDflt(kern_ip);
796 		goto debugger_entry;
797 
798 	case T_DEBUG:
799 		/*
800 		 * Re-enable LBR tracing for core/panic files if necessary. i386_lbr_enable confirms LBR should be re-enabled.
801 		 */
802 		i386_lbr_enable();
803 		if ((saved_state->isf.rflags & EFL_TF) == 0 && NO_WATCHPOINTS) {
804 			/* We've somehow encountered a debug
805 			 * register match that does not belong
806 			 * to the kernel debugger.
807 			 * This isn't supposed to happen.
808 			 */
809 			reset_dr7();
810 			goto common_return;
811 		}
812 		goto debugger_entry;
813 	case T_INT3:
814 		goto debugger_entry;
815 	case T_PAGE_FAULT:
816 
817 #if CONFIG_DTRACE
818 		if (thread != THREAD_NULL && thread->t_dtrace_inprobe) { /* Executing under dtrace_probe? */
819 			if (dtrace_tally_fault(vaddr)) { /* Should a fault under dtrace be ignored? */
820 				/*
821 				 * DTrace has "anticipated" the possibility of this fault, and has
822 				 * established the suitable recovery state. Drop down now into the
823 				 * recovery handling code in "case T_GENERAL_PROTECTION:".
824 				 */
825 				goto FALL_THROUGH;
826 			}
827 		}
828 #endif /* CONFIG_DTRACE */
829 
830 		prot = VM_PROT_READ;
831 
832 		if (code & T_PF_WRITE) {
833 			prot |= VM_PROT_WRITE;
834 		}
835 		if (code & T_PF_EXECUTE) {
836 			prot |= VM_PROT_EXECUTE;
837 		}
838 
839 		/**
840 		 * vm_fault() can be called with preemption disabled (and indeed this is expected for
841 		 * certain copyio() scenarios), but can't safely be called with interrupts disabled
842 		 * once the system has gone multi-threaded.  Other than some early-boot situations
843 		 * such as startup kext loading, kernel paging operations should never be triggered
844 		 * by non-interruptible code in the first place, so a fault from such a context will
845 		 * ultimately produce a kernel page fault panic anyway.  In these cases, skip calling
846 		 * vm_fault() to avoid masking the real kernel panic with a failed VM locking assertion.
847 		 */
848 		if (__improbable(!(intr ||
849 		    startup_phase < STARTUP_SUB_EARLY_BOOT ||
850 		    current_cpu_datap()->cpu_hibernate))) {
851 			fault_result = result = KERN_FAILURE;
852 			goto FALL_THROUGH;
853 		}
854 
855 		// VM will query this property when deciding to throttle this fault, we don't want to
856 		// throttle kernel faults for copyio faults. The presence of a recovery entry is used as a
857 		// proxy for being in copyio code.
858 		rp = find_recovery_entry(kern_ip);
859 		const bool was_recover = thread->recover;
860 		thread->recover = was_recover || (rp != NULL);
861 
862 		fault_result = result = vm_fault(map,
863 		    vaddr,
864 		    prot,
865 		    FALSE, VM_KERN_MEMORY_NONE,
866 		    THREAD_UNINT, NULL, 0);
867 
868 		thread->recover = was_recover;
869 		if (result == KERN_SUCCESS) {
870 			goto common_return;
871 		}
872 		/*
873 		 * fall through
874 		 */
875 FALL_THROUGH:
876 
877 	case T_GENERAL_PROTECTION:
878 		/*
879 		 * If there is a failure recovery address
880 		 * for this fault, go there.
881 		 */
882 		if ((rp != NULL) || (rp = find_recovery_entry(kern_ip))) {
883 			set_recovery_ip(saved_state, rp->recover_addr);
884 			goto common_return;
885 		}
886 
887 		/*
888 		 * Unanticipated page-fault errors in kernel
889 		 * should not happen.
890 		 *
891 		 * fall through...
892 		 */
893 		OS_FALLTHROUGH;
894 	default:
895 		/*
896 		 * Exception 15 is reserved but some chips may generate it
897 		 * spuriously. Seen at startup on AMD Athlon-64.
898 		 */
899 		if (type == 15) {
900 			kprintf("kernel_trap() ignoring spurious trap 15\n");
901 			goto common_return;
902 		}
903 debugger_entry:
904 		/* Ensure that the i386_kernel_state at the base of the
905 		 * current thread's stack (if any) is synchronized with the
906 		 * context at the moment of the trap, to facilitate
907 		 * access through the debugger.
908 		 */
909 		sync_iss_to_iks(state);
910 #if  MACH_KDP
911 		if (kdp_i386_trap(type, saved_state, result, (vm_offset_t)vaddr)) {
912 			goto common_return;
913 		}
914 #endif
915 	}
916 	if (type == T_PAGE_FAULT) {
917 		panic_fault_address = vaddr;
918 	}
919 	pal_cli();
920 
921 	if (trapname == NULL) {
922 		trapname = type < TRAP_TYPES ? trap_type[type] : "Unknown";
923 	}
924 
925 	panic_trap(saved_state, trapname, trap_pl, fault_result);
926 	/*
927 	 * NO RETURN
928 	 */
929 
930 common_return:
931 #if DEVELOPMENT || DEBUG
932 	if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
933 		traptrace_end(traptrace_index, mach_absolute_time());
934 	}
935 #endif
936 	return;
937 }
938 
939 static void
set_recovery_ip(x86_saved_state64_t * saved_state,vm_offset_t ip)940 set_recovery_ip(x86_saved_state64_t  *saved_state, vm_offset_t ip)
941 {
942 	saved_state->isf.rip = ip;
943 }
944 
945 static void
panic_trap(x86_saved_state64_t * regs,const char * trapname,uint32_t pl,kern_return_t fault_result)946 panic_trap(x86_saved_state64_t *regs, const char *trapname, uint32_t pl, kern_return_t fault_result)
947 {
948 	pal_cr_t        cr0, cr2, cr3, cr4;
949 	boolean_t       potential_smep_fault = FALSE, potential_kernel_NX_fault = FALSE;
950 	boolean_t       potential_smap_fault = FALSE;
951 
952 	pal_get_control_registers( &cr0, &cr2, &cr3, &cr4 );
953 	assert(ml_get_interrupts_enabled() == FALSE);
954 	current_cpu_datap()->cpu_fatal_trap_state = regs;
955 	/*
956 	 * Issue an I/O port read if one has been requested - this is an
957 	 * event logic analyzers can use as a trigger point.
958 	 */
959 	panic_notify();
960 
961 	kprintf("CPU %d panic trap number 0x%x, rip 0x%016llx\n",
962 	    cpu_number(), regs->isf.trapno, regs->isf.rip);
963 	kprintf("cr0 0x%016llx cr2 0x%016llx cr3 0x%016llx cr4 0x%016llx\n",
964 	    cr0, cr2, cr3, cr4);
965 
966 	if ((regs->isf.trapno == T_PAGE_FAULT) && (regs->isf.err == (T_PF_PROT | T_PF_EXECUTE)) && (regs->isf.rip == regs->cr2)) {
967 		if (pmap_smep_enabled && (regs->isf.rip < VM_MAX_USER_PAGE_ADDRESS)) {
968 			potential_smep_fault = TRUE;
969 		} else if (regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
970 			potential_kernel_NX_fault = TRUE;
971 		}
972 	} else if (pmap_smap_enabled &&
973 	    regs->isf.trapno == T_PAGE_FAULT &&
974 	    regs->isf.err & T_PF_PROT &&
975 	    regs->cr2 < VM_MAX_USER_PAGE_ADDRESS &&
976 	    regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
977 		potential_smap_fault = TRUE;
978 	}
979 
980 #undef panic
981 	panic("Kernel trap at 0x%016llx, type %d=%s, registers:\n"
982 	    "CR0: 0x%016llx, CR2: 0x%016llx, CR3: 0x%016llx, CR4: 0x%016llx\n"
983 	    "RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
984 	    "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
985 	    "R8:  0x%016llx, R9:  0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
986 	    "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
987 	    "RFL: 0x%016llx, RIP: 0x%016llx, CS:  0x%016llx, SS:  0x%016llx\n"
988 	    "Fault CR2: 0x%016llx, Error code: 0x%016llx, Fault CPU: 0x%x%s%s%s%s, PL: %d, VF: %d\n",
989 	    regs->isf.rip, regs->isf.trapno, trapname,
990 	    cr0, cr2, cr3, cr4,
991 	    regs->rax, regs->rbx, regs->rcx, regs->rdx,
992 	    regs->isf.rsp, regs->rbp, regs->rsi, regs->rdi,
993 	    regs->r8, regs->r9, regs->r10, regs->r11,
994 	    regs->r12, regs->r13, regs->r14, regs->r15,
995 	    regs->isf.rflags, regs->isf.rip, regs->isf.cs & 0xFFFF,
996 	    regs->isf.ss & 0xFFFF, regs->cr2, regs->isf.err, regs->isf.cpu,
997 	    virtualized ? " VMM" : "",
998 	    potential_kernel_NX_fault ? " Kernel NX fault" : "",
999 	    potential_smep_fault ? " SMEP/User NX fault" : "",
1000 	    potential_smap_fault ? " SMAP fault" : "",
1001 	    pl,
1002 	    fault_result);
1003 }
1004 
1005 #if CONFIG_DTRACE
1006 extern kern_return_t dtrace_user_probe(x86_saved_state_t *);
1007 #endif
1008 
1009 #if DEBUG
1010 uint32_t fsigs[2];
1011 uint32_t fsigns, fsigcs;
1012 #endif
1013 
1014 /*
1015  *	Trap from user mode.
1016  */
1017 void
user_trap(x86_saved_state_t * saved_state)1018 user_trap(
1019 	x86_saved_state_t *saved_state)
1020 {
1021 	int                     exc;
1022 	int                     err;
1023 	mach_exception_code_t   code;
1024 	mach_exception_subcode_t subcode;
1025 	int                     type;
1026 	user_addr_t             vaddr;
1027 	vm_prot_t               prot;
1028 	thread_t                thread = current_thread();
1029 	kern_return_t           kret;
1030 	user_addr_t             rip;
1031 	unsigned long           dr6 = 0; /* 32 bit for i386, 64 bit for x86_64 */
1032 	int                     current_cpu = cpu_number();
1033 #if DEVELOPMENT || DEBUG
1034 	bool                    inspect_cacheline = false;
1035 	uint32_t                traptrace_index;
1036 #endif
1037 	assert((is_saved_state32(saved_state) && !thread_is_64bit_addr(thread)) ||
1038 	    (is_saved_state64(saved_state) && thread_is_64bit_addr(thread)));
1039 
1040 	if (is_saved_state64(saved_state)) {
1041 		x86_saved_state64_t     *regs;
1042 
1043 		regs = saved_state64(saved_state);
1044 
1045 		/* Record cpu where state was captured */
1046 		regs->isf.cpu = current_cpu;
1047 
1048 		type = regs->isf.trapno;
1049 		err  = (int)regs->isf.err & 0xffff;
1050 		vaddr = (user_addr_t)regs->cr2;
1051 		rip   = (user_addr_t)regs->isf.rip;
1052 #if DEVELOPMENT || DEBUG
1053 		traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->rbp);
1054 #endif
1055 	} else {
1056 		x86_saved_state32_t     *regs;
1057 
1058 		regs = saved_state32(saved_state);
1059 
1060 		/* Record cpu where state was captured */
1061 		regs->cpu = current_cpu;
1062 
1063 		type  = regs->trapno;
1064 		err   = regs->err & 0xffff;
1065 		vaddr = (user_addr_t)regs->cr2;
1066 		rip   = (user_addr_t)regs->eip;
1067 #if DEVELOPMENT || DEBUG
1068 		traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->ebp);
1069 #endif
1070 	}
1071 
1072 #if DEVELOPMENT || DEBUG
1073 	/*
1074 	 * Copy the cacheline of code into the thread's instruction stream save area
1075 	 * before enabling interrupts (the assumption is that we have not otherwise faulted or
1076 	 * trapped since the original cache line stores).  If the saved code is not valid,
1077 	 * we'll catch it below when we process the copyin() for unhandled faults.
1078 	 */
1079 	if (thread->machine.insn_copy_optout == false &&
1080 	    (type == T_PAGE_FAULT || type == T_INVALID_OPCODE || type == T_GENERAL_PROTECTION)) {
1081 #define CACHELINE_SIZE 64
1082 		THREAD_TO_PCB(thread)->insn_cacheline[CACHELINE_SIZE] = (uint8_t)(rip & (CACHELINE_SIZE - 1));
1083 		bcopy(&cpu_shadowp(current_cpu)->cpu_rtimes[0],
1084 		    &THREAD_TO_PCB(thread)->insn_cacheline[0],
1085 		    sizeof(THREAD_TO_PCB(thread)->insn_cacheline) - 1);
1086 		inspect_cacheline = true;
1087 	}
1088 #endif
1089 
1090 	if (type == T_DEBUG) {
1091 		if (thread->machine.ids) {
1092 			unsigned long clear = 0;
1093 			/* Stash and clear this processor's DR6 value, in the event
1094 			 * this was a debug register match
1095 			 */
1096 			__asm__ volatile ("mov %%db6, %0" : "=r" (dr6));
1097 			__asm__ volatile ("mov %0, %%db6" : : "r" (clear));
1098 		}
1099 		/* [Re]Enable LBRs *BEFORE* enabling interrupts to ensure we hit the right CPU */
1100 		i386_lbr_enable();
1101 	}
1102 
1103 	if (type == T_PAGE_FAULT) {
1104 		thread_reset_pcs_will_fault(thread);
1105 	}
1106 
1107 	pal_sti();
1108 
1109 	KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1110 	    (MACHDBG_CODE(DBG_MACH_EXCP_UTRAP_x86, type)) | DBG_FUNC_NONE,
1111 	    (unsigned)(vaddr >> 32), (unsigned)vaddr,
1112 	    (unsigned)(rip >> 32), (unsigned)rip, 0);
1113 
1114 	code = 0;
1115 	subcode = 0;
1116 	exc = 0;
1117 
1118 #if CONFIG_DTRACE
1119 	/*
1120 	 * DTrace does not consume all user traps, only INT_3's for now.
1121 	 * Avoid needlessly calling tempDTraceTrapHook here, and let the
1122 	 * INT_3 case handle them.
1123 	 */
1124 #endif
1125 
1126 	DEBUG_KPRINT_SYSCALL_MASK(1,
1127 	    "user_trap: type=0x%x(%s) err=0x%x cr2=%p rip=%p\n",
1128 	    type, trap_type[type], err, (void *)(long) vaddr, (void *)(long) rip);
1129 
1130 	switch (type) {
1131 	case T_DIVIDE_ERROR:
1132 		exc = EXC_ARITHMETIC;
1133 		code = EXC_I386_DIV;
1134 		break;
1135 
1136 	case T_DEBUG:
1137 	{
1138 		pcb_t   pcb;
1139 		/*
1140 		 * Update the PCB with this processor's DR6 value
1141 		 * in the event this was a debug register match.
1142 		 */
1143 		pcb = THREAD_TO_PCB(thread);
1144 		if (pcb->ids) {
1145 			/*
1146 			 * We can get and set the status register
1147 			 * in 32-bit mode even on a 64-bit thread
1148 			 * because the high order bits are not
1149 			 * used on x86_64
1150 			 */
1151 			if (thread_is_64bit_addr(thread)) {
1152 				x86_debug_state64_t *ids = pcb->ids;
1153 				ids->dr6 = dr6;
1154 			} else {         /* 32 bit thread */
1155 				x86_debug_state32_t *ids = pcb->ids;
1156 				ids->dr6 = (uint32_t) dr6;
1157 			}
1158 		}
1159 		exc = EXC_BREAKPOINT;
1160 		code = EXC_I386_SGL;
1161 		break;
1162 	}
1163 	case T_INT3:
1164 #if CONFIG_DTRACE
1165 		if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
1166 			return; /* If it succeeds, we are done... */
1167 		}
1168 #endif
1169 		exc = EXC_BREAKPOINT;
1170 		code = EXC_I386_BPT;
1171 		break;
1172 
1173 	case T_OVERFLOW:
1174 		exc = EXC_ARITHMETIC;
1175 		code = EXC_I386_INTO;
1176 		break;
1177 
1178 	case T_OUT_OF_BOUNDS:
1179 		exc = EXC_SOFTWARE;
1180 		code = EXC_I386_BOUND;
1181 		break;
1182 
1183 	case T_INVALID_OPCODE:
1184 		if (fpUDflt(rip) == 1) {
1185 			exc = EXC_BAD_INSTRUCTION;
1186 			code = EXC_I386_INVOP;
1187 		}
1188 		break;
1189 
1190 	case T_NO_FPU:
1191 		fpnoextflt();
1192 		break;
1193 
1194 	case T_FPU_FAULT:
1195 		fpextovrflt();
1196 		/*
1197 		 * Raise exception.
1198 		 */
1199 		exc = EXC_BAD_ACCESS;
1200 		code = VM_PROT_READ | VM_PROT_EXECUTE;
1201 		subcode = 0;
1202 		break;
1203 
1204 	case T_INVALID_TSS:     /* invalid TSS == iret with NT flag set */
1205 		exc = EXC_BAD_INSTRUCTION;
1206 		code = EXC_I386_INVTSSFLT;
1207 		subcode = err;
1208 		break;
1209 
1210 	case T_SEGMENT_NOT_PRESENT:
1211 		exc = EXC_BAD_INSTRUCTION;
1212 		code = EXC_I386_SEGNPFLT;
1213 		subcode = err;
1214 		break;
1215 
1216 	case T_STACK_FAULT:
1217 		exc = EXC_BAD_INSTRUCTION;
1218 		code = EXC_I386_STKFLT;
1219 		subcode = err;
1220 		break;
1221 
1222 	case T_GENERAL_PROTECTION:
1223 		/*
1224 		 * There's a wide range of circumstances which generate this
1225 		 * class of exception. From user-space, many involve bad
1226 		 * addresses (such as a non-canonical 64-bit address).
1227 		 * So we map this to EXC_BAD_ACCESS (and thereby SIGSEGV).
1228 		 * The trouble is cr2 doesn't contain the faulting address;
1229 		 * we'd need to decode the faulting instruction to really
1230 		 * determine this. We'll leave that to debuggers.
1231 		 * However, attempted execution of privileged instructions
1232 		 * (e.g. cli) also generate GP faults and so we map these to
1233 		 * to EXC_BAD_ACCESS (and thence SIGSEGV) also - rather than
1234 		 * EXC_BAD_INSTRUCTION which is more accurate. We just can't
1235 		 * win!
1236 		 */
1237 		exc = EXC_BAD_ACCESS;
1238 		code = EXC_I386_GPFLT;
1239 		subcode = err;
1240 		break;
1241 
1242 	case T_PAGE_FAULT:
1243 	{
1244 		prot = VM_PROT_READ;
1245 
1246 		if (err & T_PF_WRITE) {
1247 			prot |= VM_PROT_WRITE;
1248 		}
1249 		if (__improbable(err & T_PF_EXECUTE)) {
1250 			prot |= VM_PROT_EXECUTE;
1251 		}
1252 #if DEVELOPMENT || DEBUG
1253 		bool do_simd_hash = thread_fpsimd_hash_enabled();
1254 		uint32_t fsig = 0;
1255 		fsig = do_simd_hash ? thread_fpsimd_hash(thread) : 0;
1256 #if DEBUG
1257 		fsigs[0] = fsig;
1258 #endif
1259 #endif
1260 		kret = vm_fault(thread->map,
1261 		    vaddr,
1262 		    prot, FALSE, VM_KERN_MEMORY_NONE,
1263 		    THREAD_ABORTSAFE, NULL, 0);
1264 #if DEVELOPMENT || DEBUG
1265 		if (do_simd_hash && fsig) {
1266 			uint32_t fsig2 = thread_fpsimd_hash(thread);
1267 #if DEBUG
1268 			fsigcs++;
1269 			fsigs[1] = fsig2;
1270 #endif
1271 			if (fsig != fsig2) {
1272 				panic("FP/SIMD state hash mismatch across fault thread: %p 0x%x->0x%x", thread, fsig, fsig2);
1273 			}
1274 		} else {
1275 #if DEBUG
1276 			fsigns++;
1277 #endif
1278 		}
1279 #endif
1280 		if (__probable((kret == KERN_SUCCESS) || (kret == KERN_ABORTED))) {
1281 			break;
1282 		} else if (__improbable(kret == KERN_FAILURE)) {
1283 			/*
1284 			 * For a user trap, vm_fault() should never return KERN_FAILURE.
1285 			 * If it does, we're leaking preemption disables somewhere in the kernel.
1286 			 */
1287 			panic("vm_fault() KERN_FAILURE from user fault on thread %p", thread);
1288 		}
1289 
1290 		/* PAL debug hook (empty on x86) */
1291 		pal_dbg_page_fault(thread, vaddr, kret);
1292 		exc = EXC_BAD_ACCESS;
1293 		code = kret;
1294 		subcode = vaddr;
1295 	}
1296 	break;
1297 
1298 	case T_SSE_FLOAT_ERROR:
1299 		fpSSEexterrflt();
1300 		exc = EXC_ARITHMETIC;
1301 		code = EXC_I386_SSEEXTERR;
1302 		subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_MXCSR;
1303 		break;
1304 
1305 
1306 	case T_FLOATING_POINT_ERROR:
1307 		fpexterrflt();
1308 		exc = EXC_ARITHMETIC;
1309 		code = EXC_I386_EXTERR;
1310 		subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_status;
1311 		break;
1312 
1313 	case T_DTRACE_RET:
1314 #if CONFIG_DTRACE
1315 		if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
1316 			return; /* If it succeeds, we are done... */
1317 		}
1318 #endif
1319 		/*
1320 		 * If we get an INT 0x7f when we do not expect to,
1321 		 * treat it as an illegal instruction
1322 		 */
1323 		exc = EXC_BAD_INSTRUCTION;
1324 		code = EXC_I386_INVOP;
1325 		break;
1326 
1327 	default:
1328 		panic("Unexpected user trap, type %d", type);
1329 	}
1330 
1331 	if (type == T_PAGE_FAULT) {
1332 		thread_reset_pcs_done_faulting(thread);
1333 	}
1334 
1335 	if (exc != 0) {
1336 		uint16_t cs;
1337 		boolean_t intrs;
1338 
1339 		if (is_saved_state64(saved_state)) {
1340 			cs = saved_state64(saved_state)->isf.cs;
1341 		} else {
1342 			cs = saved_state32(saved_state)->cs;
1343 		}
1344 
1345 		if (last_branch_enabled_modes == LBR_ENABLED_USERMODE) {
1346 			intrs = ml_set_interrupts_enabled(FALSE);
1347 			/*
1348 			 * This is a bit racy (it's possible for this thread to migrate to another CPU, then
1349 			 * migrate back, but that seems rather rare in practice), but good enough to ensure
1350 			 * the LBRs are saved before proceeding with exception/signal dispatch.
1351 			 */
1352 			if (current_cpu == cpu_number()) {
1353 				i386_lbr_synch(thread);
1354 			}
1355 			ml_set_interrupts_enabled(intrs);
1356 		}
1357 
1358 		/*
1359 		 * Do not try to copyin from the instruction stream if the page fault was due
1360 		 * to an access to rip and was unhandled.
1361 		 * Do not deal with cases when %cs != USER[64]_CS
1362 		 * And of course there's no need to copy the instruction stream if the boot-arg
1363 		 * was set to 0.
1364 		 */
1365 		if (thread->machine.insn_copy_optout == false && insn_copyin_count > 0 &&
1366 		    (cs == USER64_CS || cs == USER_CS) && (type != T_PAGE_FAULT || vaddr != rip)) {
1367 #if DEVELOPMENT || DEBUG
1368 			copy_instruction_stream(thread, rip, type, inspect_cacheline);
1369 #else
1370 			copy_instruction_stream(thread, rip, type);
1371 #endif
1372 		}
1373 
1374 #if DEVELOPMENT || DEBUG
1375 		if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
1376 			traptrace_end(traptrace_index, mach_absolute_time());
1377 		}
1378 #endif
1379 		/*
1380 		 * Note: Codepaths that directly return from user_trap() have pending
1381 		 * ASTs processed in locore
1382 		 */
1383 		i386_exception(exc, code, subcode);
1384 		/* NOTREACHED */
1385 	} else {
1386 #if DEVELOPMENT || DEBUG
1387 		if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
1388 			traptrace_end(traptrace_index, mach_absolute_time());
1389 		}
1390 #endif
1391 	}
1392 }
1393 
1394 /*
1395  * Copyin up to x86_INSTRUCTION_STATE_MAX_INSN_BYTES bytes from the page that includes `rip`,
1396  * ensuring that we stay on the same page, clipping the start or end, as needed.
1397  * Add the clipped amount back at the start or end, depending on where it fits.
1398  * Consult the variable populated by the boot-arg `insn_capcnt'
1399  */
1400 static __attribute__((noinline)) void
copy_instruction_stream(thread_t thread,uint64_t rip,int __unused trap_code,bool inspect_cacheline)1401 copy_instruction_stream(thread_t thread, uint64_t rip, int __unused trap_code
1402 #if DEVELOPMENT || DEBUG
1403     , bool inspect_cacheline
1404 #endif
1405     )
1406 {
1407 #if x86_INSTRUCTION_STATE_MAX_INSN_BYTES > 4096
1408 #error x86_INSTRUCTION_STATE_MAX_INSN_BYTES cannot exceed a page in size.
1409 #endif
1410 	pcb_t pcb = THREAD_TO_PCB(thread);
1411 	vm_map_offset_t pagemask = ~vm_map_page_mask(current_map());
1412 	vm_map_offset_t rip_page = rip & pagemask;
1413 	vm_map_offset_t start_addr;
1414 	vm_map_offset_t insn_offset;
1415 	vm_map_offset_t end_addr = rip + (insn_copyin_count / 2);
1416 	void *stack_buffer;
1417 	int copyin_err = 0;
1418 #if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
1419 	void *procname;
1420 #endif
1421 
1422 #if DEVELOPMENT || DEBUG
1423 	assert(insn_copyin_count <= x86_INSTRUCTION_STATE_MAX_INSN_BYTES);
1424 #else
1425 	if (insn_copyin_count > x86_INSTRUCTION_STATE_MAX_INSN_BYTES ||
1426 	    insn_copyin_count < 64 /* CACHELINE_SIZE */) {
1427 		return;
1428 	}
1429 #endif
1430 
1431 #pragma clang diagnostic push
1432 #pragma clang diagnostic ignored "-Walloca"
1433 	stack_buffer = __builtin_alloca(insn_copyin_count);
1434 #pragma clang diagnostic pop
1435 
1436 	if (rip >= (insn_copyin_count / 2)) {
1437 		start_addr = rip - (insn_copyin_count / 2);
1438 	} else {
1439 		start_addr = 0;
1440 	}
1441 
1442 	if (start_addr < rip_page) {
1443 		insn_offset = (insn_copyin_count / 2) - (rip_page - start_addr);
1444 		end_addr += (rip_page - start_addr);
1445 		start_addr = rip_page;
1446 	} else if (end_addr >= (rip_page + (~pagemask + 1))) {
1447 		start_addr -= (end_addr - (rip_page + (~pagemask + 1))); /* Adjust start address backward */
1448 		/* Adjust instruction offset due to start address change */
1449 		insn_offset = (insn_copyin_count / 2) + (end_addr - (rip_page + (~pagemask + 1)));
1450 		end_addr = rip_page + (~pagemask + 1);  /* clip to the start of the next page (non-inclusive */
1451 	} else {
1452 		insn_offset = insn_copyin_count / 2;
1453 	}
1454 
1455 	disable_preemption();   /* Prevent copyin from faulting in the instruction stream */
1456 	if (
1457 #if DEVELOPMENT || DEBUG
1458 		(insnstream_force_cacheline_mismatch < 2) &&
1459 #endif
1460 		((end_addr > start_addr) && (copyin_err = copyin(start_addr, stack_buffer, end_addr - start_addr)) == 0)) {
1461 		enable_preemption();
1462 
1463 		if (pcb->insn_state == 0) {
1464 			pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
1465 		}
1466 
1467 		if (pcb->insn_state != 0) {
1468 			bcopy(stack_buffer, pcb->insn_state->insn_bytes, end_addr - start_addr);
1469 			bzero(&pcb->insn_state->insn_bytes[end_addr - start_addr],
1470 			    insn_copyin_count - (end_addr - start_addr));
1471 
1472 			pcb->insn_state->insn_stream_valid_bytes = (int)(end_addr - start_addr);
1473 			pcb->insn_state->insn_offset = (int)insn_offset;
1474 
1475 #if DEVELOPMENT || DEBUG
1476 			/* Now try to validate the cacheline we read at early-fault time matches the code
1477 			 * copied in. Before we do that, we have to make sure the buffer contains a valid
1478 			 * cacheline by looking for the 2 sentinel values written in the event the cacheline
1479 			 * could not be copied.
1480 			 */
1481 #define CACHELINE_DATA_NOT_PRESENT 0xdeadc0debeefcafeULL
1482 #define CACHELINE_MASK (CACHELINE_SIZE - 1)
1483 
1484 			if (inspect_cacheline &&
1485 			    (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
1486 			    *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
1487 				/*
1488 				 * The position of the cacheline in the instruction buffer is at offset
1489 				 * insn_offset - (rip & CACHELINE_MASK)
1490 				 */
1491 				if (__improbable((rip & CACHELINE_MASK) > insn_offset)) {
1492 					printf("thread %p code cacheline @ %p clipped wrt copied-in code (offset %d)\n",
1493 					    thread, (void *)(rip & ~CACHELINE_MASK), (int)(rip & CACHELINE_MASK));
1494 				} else if (bcmp(&pcb->insn_state->insn_bytes[insn_offset - (rip & CACHELINE_MASK)],
1495 				    &pcb->insn_cacheline[0], CACHELINE_SIZE) != 0
1496 				    || insnstream_force_cacheline_mismatch
1497 				    ) {
1498 #if x86_INSTRUCTION_STATE_CACHELINE_SIZE != CACHELINE_SIZE
1499 #error cacheline size mismatch
1500 #endif
1501 					bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
1502 					    x86_INSTRUCTION_STATE_CACHELINE_SIZE);
1503 					/* Mark the instruction stream as being out-of-synch */
1504 					pcb->insn_state->out_of_synch = 1;
1505 
1506 					printf("thread %p code cacheline @ %p mismatches with copied-in code [trap 0x%x]\n",
1507 					    thread, (void *)(rip & ~CACHELINE_MASK), trap_code);
1508 					for (int i = 0; i < 8; i++) {
1509 						printf("\t[%d] cl=0x%08llx vs. ci=0x%08llx\n", i, *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[i * 8],
1510 						    *(uint64_t *)(uintptr_t)&pcb->insn_state->insn_bytes[(i * 8) + insn_offset - (rip & CACHELINE_MASK)]);
1511 					}
1512 					if (panic_on_cacheline_mismatch) {
1513 						panic("Cacheline mismatch while processing unhandled exception.");
1514 					}
1515 				} else {
1516 					pcb->insn_state->out_of_synch = 0;
1517 				}
1518 			} else if (inspect_cacheline) {
1519 				printf("thread %p could not capture code cacheline at fault IP %p [offset %d]\n",
1520 				    (void *)thread, (void *)rip, (int)(insn_offset - (rip & CACHELINE_MASK)));
1521 				pcb->insn_state->out_of_synch = 0;
1522 			}
1523 #else
1524 			pcb->insn_state->out_of_synch = 0;
1525 #endif /* DEVELOPMENT || DEBUG */
1526 
1527 #if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
1528 			if (panic_on_trap_procname[0] != 0) {
1529 				task_t task = get_threadtask(thread);
1530 				char procnamebuf[65] = {0};
1531 
1532 				if (get_bsdtask_info(task) != NULL) {
1533 					procname = proc_name_address(get_bsdtask_info(task));
1534 					strlcpy(procnamebuf, procname, sizeof(procnamebuf));
1535 
1536 					if (strcasecmp(panic_on_trap_procname, procnamebuf) == 0 &&
1537 					    ((1U << trap_code) & panic_on_trap_mask) != 0) {
1538 						panic("Panic requested on trap type 0x%x for process `%s'", trap_code,
1539 						    panic_on_trap_procname);
1540 						/*NORETURN*/
1541 					}
1542 				}
1543 			}
1544 #endif /* MACH_BSD && (DEVELOPMENT || DEBUG) */
1545 		}
1546 	} else {
1547 		enable_preemption();
1548 
1549 		pcb->insn_state_copyin_failure_errorcode = copyin_err;
1550 #if DEVELOPMENT || DEBUG
1551 		if (inspect_cacheline && pcb->insn_state == 0) {
1552 			pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
1553 		}
1554 		if (pcb->insn_state != 0) {
1555 			pcb->insn_state->insn_stream_valid_bytes = 0;
1556 			pcb->insn_state->insn_offset = 0;
1557 
1558 			if (inspect_cacheline &&
1559 			    (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
1560 			    *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
1561 				/*
1562 				 * We can still copy the cacheline into the instruction state structure
1563 				 * if it contains valid data
1564 				 */
1565 				pcb->insn_state->out_of_synch = 1;
1566 				bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
1567 				    x86_INSTRUCTION_STATE_CACHELINE_SIZE);
1568 			}
1569 		}
1570 #endif /* DEVELOPMENT || DEBUG */
1571 	}
1572 }
1573 
1574 /*
1575  * Handle exceptions for i386.
1576  *
1577  * If we are an AT bus machine, we must turn off the AST for a
1578  * delayed floating-point exception.
1579  *
1580  * If we are providing floating-point emulation, we may have
1581  * to retrieve the real register values from the floating point
1582  * emulator.
1583  */
1584 void
i386_exception(int exc,mach_exception_code_t code,mach_exception_subcode_t subcode)1585 i386_exception(
1586 	int     exc,
1587 	mach_exception_code_t code,
1588 	mach_exception_subcode_t subcode)
1589 {
1590 	mach_exception_data_type_t   codes[EXCEPTION_CODE_MAX];
1591 
1592 	DEBUG_KPRINT_SYSCALL_MACH("i386_exception: exc=%d code=0x%llx subcode=0x%llx\n",
1593 	    exc, code, subcode);
1594 	codes[0] = code;                /* new exception interface */
1595 	codes[1] = subcode;
1596 	exception_triage(exc, codes, 2);
1597 	/*NOTREACHED*/
1598 }
1599 
1600 
1601 /* Synchronize a thread's x86_kernel_state (if any) with the given
1602  * x86_saved_state_t obtained from the trap/IPI handler; called in
1603  * kernel_trap() prior to entering the debugger, and when receiving
1604  * an "MP_KDP" IPI. Called with null saved_state if an incoming IPI
1605  * was detected from the kernel while spinning with interrupts masked.
1606  */
1607 
1608 void
sync_iss_to_iks(x86_saved_state_t * saved_state)1609 sync_iss_to_iks(x86_saved_state_t *saved_state)
1610 {
1611 	struct x86_kernel_state *iks = NULL;
1612 	vm_offset_t kstack;
1613 	boolean_t record_active_regs = FALSE;
1614 
1615 	/* The PAL may have a special way to sync registers */
1616 	if (saved_state && saved_state->flavor == THREAD_STATE_NONE) {
1617 		pal_get_kern_regs( saved_state );
1618 	}
1619 
1620 	if (current_thread() != NULL &&
1621 	    (kstack = current_thread()->kernel_stack) != 0) {
1622 		x86_saved_state64_t     *regs = saved_state64(saved_state);
1623 
1624 		iks = STACK_IKS(kstack);
1625 
1626 		/* Did we take the trap/interrupt in kernel mode? */
1627 		if (saved_state == NULL || /* NULL => polling in kernel */
1628 		    regs == USER_REGS64(current_thread())) {
1629 			record_active_regs = TRUE;
1630 		} else {
1631 			iks->k_rbx = regs->rbx;
1632 			iks->k_rsp = regs->isf.rsp;
1633 			iks->k_rbp = regs->rbp;
1634 			iks->k_r12 = regs->r12;
1635 			iks->k_r13 = regs->r13;
1636 			iks->k_r14 = regs->r14;
1637 			iks->k_r15 = regs->r15;
1638 			iks->k_rip = regs->isf.rip;
1639 		}
1640 	}
1641 
1642 	if (record_active_regs == TRUE) {
1643 		/* Show the trap handler path */
1644 		__asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
1645 		__asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
1646 		__asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
1647 		__asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
1648 		__asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
1649 		__asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
1650 		__asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
1651 		/* "Current" instruction pointer */
1652 		__asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:"
1653                                   : "=m" (iks->k_rip)
1654                                   :
1655                                   : "rax");
1656 	}
1657 }
1658 
1659 /*
1660  * This is used by the NMI interrupt handler (from mp.c) to
1661  * uncondtionally sync the trap handler context to the IKS
1662  * irrespective of whether the NMI was fielded in kernel
1663  * or user space.
1664  */
1665 void
sync_iss_to_iks_unconditionally(__unused x86_saved_state_t * saved_state)1666 sync_iss_to_iks_unconditionally(__unused x86_saved_state_t *saved_state)
1667 {
1668 	struct x86_kernel_state *iks;
1669 	vm_offset_t kstack;
1670 
1671 	if ((kstack = current_thread()->kernel_stack) != 0) {
1672 		iks = STACK_IKS(kstack);
1673 		/* Display the trap handler path */
1674 		__asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
1675 		__asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
1676 		__asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
1677 		__asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
1678 		__asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
1679 		__asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
1680 		__asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
1681 		/* "Current" instruction pointer */
1682 		__asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:" : "=m" (iks->k_rip)::"rax");
1683 	}
1684 }
1685 
1686 #if DEBUG
1687 #define TERI 1
1688 #endif
1689 
1690 #if TERI
1691 extern void     thread_exception_return_internal(void) __dead2;
1692 
1693 void
thread_exception_return(void)1694 thread_exception_return(void)
1695 {
1696 	thread_t thread = current_thread();
1697 	task_t   task   = current_task();
1698 
1699 	ml_set_interrupts_enabled(FALSE);
1700 	if (thread_is_64bit_addr(thread) != task_has_64Bit_addr(task)) {
1701 		panic("Task/thread bitness mismatch %p %p, task: %d, thread: %d",
1702 		    thread, task, thread_is_64bit_addr(thread), task_has_64Bit_addr(task));
1703 	}
1704 
1705 	if (thread_is_64bit_addr(thread)) {
1706 		if ((gdt_desc_p(USER64_CS)->access & ACC_PL_U) == 0) {
1707 			panic("64-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER64_CS));
1708 		}
1709 	} else {
1710 		if ((gdt_desc_p(USER_CS)->access & ACC_PL_U) == 0) {
1711 			panic("32-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER_CS));
1712 		}
1713 	}
1714 	assert(get_preemption_level() == 0);
1715 	thread_exception_return_internal();
1716 }
1717 #endif
1718 
1719 #if DEVELOPMENT || DEBUG
1720 static int trap_handled;
1721 
1722 static void
handle_recoverable_kernel_trap(__unused void * tstate,uint16_t comment)1723 handle_recoverable_kernel_trap(
1724 	__unused void     *tstate,
1725 	uint16_t          comment)
1726 {
1727 	assert(comment == TEST_RECOVERABLE_SOFT_TRAP);
1728 
1729 	printf("Recoverable trap handled.\n");
1730 	trap_handled = 1;
1731 }
1732 
1733 KERNEL_BRK_DESCRIPTOR_DEFINE(test_desc,
1734     .type                = KERNEL_BRK_TYPE_TEST,
1735     .base                = TEST_RECOVERABLE_SOFT_TRAP,
1736     .max                 = TEST_RECOVERABLE_SOFT_TRAP,
1737     .options             = KERNEL_BRK_RECOVERABLE,
1738     .handle_breakpoint   = handle_recoverable_kernel_trap);
1739 
1740 static int
recoverable_kernel_trap_test(__unused int64_t in,int64_t * out)1741 recoverable_kernel_trap_test(__unused int64_t in, int64_t *out)
1742 {
1743 	ml_recoverable_trap(TEST_RECOVERABLE_SOFT_TRAP);
1744 
1745 	*out = trap_handled;
1746 	return 0;
1747 }
1748 
1749 SYSCTL_TEST_REGISTER(recoverable_kernel_trap, recoverable_kernel_trap_test);
1750 #endif
1751