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