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