1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or [email protected]
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56 /*
57 */
58
59 /*
60 * Hardware trap/fault handler.
61 */
62
63 #include <mach_kdp.h>
64 #include <mach_ldebug.h>
65
66 #include <types.h>
67 #include <i386/eflags.h>
68 #include <i386/trap_internal.h>
69 #include <i386/pmap.h>
70 #include <i386/fpu.h>
71 #include <i386/panic_notify.h>
72 #include <i386/lapic.h>
73
74 #include <mach/exception.h>
75 #include <mach/kern_return.h>
76 #include <mach/vm_param.h>
77 #include <mach/i386/thread_status.h>
78
79 #include <vm/vm_kern.h>
80 #include <vm/vm_fault.h>
81
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 static uint32_t bound_chk_violations_event;
515
516 static void
xnu_soft_trap_handle_breakpoint(__unused void * tstate,uint16_t comment)517 xnu_soft_trap_handle_breakpoint(
518 __unused void *tstate,
519 uint16_t comment)
520 {
521 if (comment == CLANG_SOFT_TRAP_BOUND_CHK) {
522 os_atomic_inc(&bound_chk_violations_event, relaxed);
523 }
524 }
525
526 KERNEL_BRK_DESCRIPTOR_DEFINE(clang_desc,
527 .type = KERNEL_BRK_TYPE_CLANG,
528 .base = CLANG_X86_TRAP_START,
529 .max = CLANG_X86_TRAP_END,
530 .options = KERNEL_BRK_UNRECOVERABLE,
531 .handle_breakpoint = NULL);
532
533 KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_soft_traps_desc,
534 .type = KERNEL_BRK_TYPE_TELEMETRY,
535 .base = XNU_SOFT_TRAP_START,
536 .max = XNU_SOFT_TRAP_END,
537 .options = KERNEL_BRK_RECOVERABLE | KERNEL_BRK_CORE_ANALYTICS,
538 .handle_breakpoint = xnu_soft_trap_handle_breakpoint);
539
540 KERNEL_BRK_DESCRIPTOR_DEFINE(libcxx_desc,
541 .type = KERNEL_BRK_TYPE_LIBCXX,
542 .base = LIBCXX_TRAP_START,
543 .max = LIBCXX_TRAP_END,
544 .options = KERNEL_BRK_UNRECOVERABLE,
545 .handle_breakpoint = NULL);
546
547 KERNEL_BRK_DESCRIPTOR_DEFINE(xnu_hard_traps_desc,
548 .type = KERNEL_BRK_TYPE_XNU,
549 .base = XNU_HARD_TRAP_START,
550 .max = XNU_HARD_TRAP_END,
551 .options = KERNEL_BRK_UNRECOVERABLE,
552 .handle_breakpoint = NULL);
553
554 static bool
handle_kernel_breakpoint(x86_saved_state64_t * state)555 handle_kernel_breakpoint(x86_saved_state64_t *state)
556 {
557 uint16_t comment;
558 const struct kernel_brk_descriptor *desc;
559 uint8_t inst_buf[8];
560 uint32_t prefix16 = 0x80B90F67; /* Encoding prefix for ud1 <16-bit code>(%eax), %eax */
561 uint32_t prefix8 = 0x40B90F67; /* Encoding prefix for ud1 <8-bit code>(%eax), %eax */
562 bool found_prefix8 = false;
563
564 vm_size_t sz = ml_nofault_copy(state->isf.rip, (vm_offset_t)inst_buf, sizeof(inst_buf));
565 if (sz != sizeof(inst_buf)) {
566 return false;
567 }
568
569 if (bcmp(inst_buf, &prefix16, sizeof(prefix16)) == 0) {
570 /* The two bytes following the prefix is our code */
571 comment = inst_buf[5] << 8 | inst_buf[4];
572 } else if (bcmp(inst_buf, &prefix8, sizeof(prefix8)) == 0) {
573 /* The one byte following the prefix is our code */
574 found_prefix8 = true;
575 comment = inst_buf[4];
576 } else {
577 return false;
578 }
579
580 desc = find_brk_descriptor_by_comment(comment);
581
582 if (!desc) {
583 return false;
584 }
585
586 if (desc->options & KERNEL_BRK_TELEMETRY_OPTIONS) {
587 telemetry_kernel_brk(desc->type, desc->options, (void *)state, comment);
588 }
589
590 if (desc->handle_breakpoint) {
591 desc->handle_breakpoint(state, comment); /* May trigger panic */
592 }
593
594 /* Still alive? Check if we should recover. */
595 if (desc->options & KERNEL_BRK_RECOVERABLE) {
596 /* ud1 can be five or eight-byte long depending on the prefix */
597 set_recovery_ip(state, state->isf.rip + (found_prefix8 ? 5 : 8));
598 return true;
599 }
600
601 return false;
602 }
603
604 /*
605 * Trap from kernel mode. Only page-fault errors are recoverable,
606 * and then only in special circumstances. All other errors are
607 * fatal. Return value indicates if trap was handled.
608 */
609
610 void
kernel_trap(x86_saved_state_t * state,uintptr_t * lo_spp)611 kernel_trap(
612 x86_saved_state_t *state,
613 uintptr_t *lo_spp)
614 {
615 x86_saved_state64_t *saved_state;
616 int code;
617 user_addr_t vaddr;
618 int type;
619 vm_map_t map = 0; /* protected by T_PAGE_FAULT */
620 kern_return_t result = KERN_FAILURE;
621 kern_return_t fault_result = KERN_SUCCESS;
622 thread_t thread;
623 boolean_t intr;
624 vm_prot_t prot;
625 struct recovery *rp;
626 vm_offset_t kern_ip;
627 int is_user;
628 int trap_pl = get_preemption_level();
629
630 thread = current_thread();
631
632 if (__improbable(is_saved_state32(state))) {
633 panic("kernel_trap(%p) with 32-bit state", state);
634 }
635 saved_state = saved_state64(state);
636
637 /* Record cpu where state was captured */
638 saved_state->isf.cpu = cpu_number();
639
640 vaddr = (user_addr_t)saved_state->cr2;
641 type = saved_state->isf.trapno;
642 code = (int)(saved_state->isf.err & 0xffff);
643 intr = (saved_state->isf.rflags & EFL_IF) != 0; /* state of ints at trap */
644 kern_ip = (vm_offset_t)saved_state->isf.rip;
645
646 is_user = (vaddr < VM_MAX_USER_PAGE_ADDRESS);
647
648 #if DEVELOPMENT || DEBUG
649 uint32_t traptrace_index = traptrace_start(type, kern_ip, mach_absolute_time(), saved_state->rbp);
650 #endif
651
652 #if CONFIG_DTRACE
653 /*
654 * Is there a DTrace hook?
655 */
656 if (__improbable(tempDTraceTrapHook != NULL)) {
657 if (tempDTraceTrapHook(type, state, lo_spp, 0) == KERN_SUCCESS) {
658 /*
659 * If it succeeds, we are done...
660 */
661 goto common_return;
662 }
663 }
664
665 /* Handle traps originated from probe context. */
666 if (thread != THREAD_NULL && thread->t_dtrace_inprobe) {
667 if (dtrace_handle_trap(type, state)) {
668 goto common_return;
669 }
670 }
671
672 #endif /* CONFIG_DTRACE */
673
674 /*
675 * we come here with interrupts off as we don't want to recurse
676 * on preemption below. but we do want to re-enable interrupts
677 * as soon we possibly can to hold latency down
678 */
679 if (__improbable(T_PREEMPT == type)) {
680 ast_taken_kernel();
681
682 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
683 (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
684 0, 0, 0, VM_KERNEL_UNSLIDE(kern_ip), 0);
685
686 goto common_return;
687 }
688
689 user_addr_t kd_vaddr = is_user ? vaddr : VM_KERNEL_UNSLIDE(vaddr);
690 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
691 (MACHDBG_CODE(DBG_MACH_EXCP_KTRAP_x86, type)) | DBG_FUNC_NONE,
692 (unsigned)(kd_vaddr >> 32), (unsigned)kd_vaddr, is_user,
693 VM_KERNEL_UNSLIDE(kern_ip), 0);
694
695
696 if (T_PAGE_FAULT == type) {
697 /*
698 * assume we're faulting in the kernel map
699 */
700 map = kernel_map;
701
702 if (__probable((thread != THREAD_NULL) && (thread->map != kernel_map) &&
703 (vaddr < VM_MAX_USER_PAGE_ADDRESS))) {
704 /* fault occurred in userspace */
705 map = thread->map;
706
707 /* Intercept a potential Supervisor Mode Execute
708 * Protection fault. These criteria identify
709 * both NX faults and SMEP faults, but both
710 * are fatal. We avoid checking PTEs (racy).
711 * (The VM could just redrive a SMEP fault, hence
712 * the intercept).
713 */
714 if (__improbable((code == (T_PF_PROT | T_PF_EXECUTE)) &&
715 (pmap_smep_enabled) && (saved_state->isf.rip == vaddr))) {
716 goto debugger_entry;
717 }
718
719 /*
720 * Additionally check for SMAP faults...
721 * which are characterized by page-present and
722 * the AC bit unset (i.e. not from copyin/out path).
723 */
724 if (__improbable(code & T_PF_PROT &&
725 pmap_smap_enabled &&
726 (saved_state->isf.rflags & EFL_AC) == 0)) {
727 goto debugger_entry;
728 }
729
730 /*
731 * If we're not sharing cr3 with the user
732 * and we faulted in copyio,
733 * then switch cr3 here and dismiss the fault.
734 */
735 if (no_shared_cr3 &&
736 (thread->machine.specFlags & CopyIOActive) &&
737 map->pmap->pm_cr3 != get_cr3_base()) {
738 pmap_assert(current_cpu_datap()->cpu_pmap_pcid_enabled == FALSE);
739 set_cr3_raw(map->pmap->pm_cr3);
740 return;
741 }
742 if (__improbable(vaddr < PAGE_SIZE) &&
743 ((thread->machine.specFlags & CopyIOActive) == 0)) {
744 goto debugger_entry;
745 }
746 }
747 }
748
749 (void) ml_set_interrupts_enabled(intr);
750
751 switch (type) {
752 case T_NO_FPU:
753 fpnoextflt();
754 goto common_return;
755
756 case T_FPU_FAULT:
757 fpextovrflt();
758 goto common_return;
759
760 case T_FLOATING_POINT_ERROR:
761 fpexterrflt();
762 goto common_return;
763
764 case T_SSE_FLOAT_ERROR:
765 fpSSEexterrflt();
766 goto common_return;
767
768 case T_INVALID_OPCODE:
769 if (handle_kernel_breakpoint(saved_state)) {
770 goto common_return;
771 }
772 fpUDflt(kern_ip);
773 goto debugger_entry;
774
775 case T_DEBUG:
776 /*
777 * Re-enable LBR tracing for core/panic files if necessary. i386_lbr_enable confirms LBR should be re-enabled.
778 */
779 i386_lbr_enable();
780 if ((saved_state->isf.rflags & EFL_TF) == 0 && NO_WATCHPOINTS) {
781 /* We've somehow encountered a debug
782 * register match that does not belong
783 * to the kernel debugger.
784 * This isn't supposed to happen.
785 */
786 reset_dr7();
787 goto common_return;
788 }
789 goto debugger_entry;
790 case T_INT3:
791 goto debugger_entry;
792 case T_PAGE_FAULT:
793
794 #if CONFIG_DTRACE
795 if (thread != THREAD_NULL && thread->t_dtrace_inprobe) { /* Executing under dtrace_probe? */
796 if (dtrace_tally_fault(vaddr)) { /* Should a fault under dtrace be ignored? */
797 /*
798 * DTrace has "anticipated" the possibility of this fault, and has
799 * established the suitable recovery state. Drop down now into the
800 * recovery handling code in "case T_GENERAL_PROTECTION:".
801 */
802 goto FALL_THROUGH;
803 }
804 }
805 #endif /* CONFIG_DTRACE */
806
807 prot = VM_PROT_READ;
808
809 if (code & T_PF_WRITE) {
810 prot |= VM_PROT_WRITE;
811 }
812 if (code & T_PF_EXECUTE) {
813 prot |= VM_PROT_EXECUTE;
814 }
815
816 fault_result = result = vm_fault(map,
817 vaddr,
818 prot,
819 FALSE, VM_KERN_MEMORY_NONE,
820 THREAD_UNINT, NULL, 0);
821
822 if (result == KERN_SUCCESS) {
823 goto common_return;
824 }
825 /*
826 * fall through
827 */
828 #if CONFIG_DTRACE
829 FALL_THROUGH:
830 #endif /* CONFIG_DTRACE */
831
832 case T_GENERAL_PROTECTION:
833 /*
834 * If there is a failure recovery address
835 * for this fault, go there.
836 */
837 for (rp = recover_table; rp < recover_table_end; rp++) {
838 if (kern_ip == rp->fault_addr) {
839 set_recovery_ip(saved_state, rp->recover_addr);
840 goto common_return;
841 }
842 }
843
844 /*
845 * Unanticipated page-fault errors in kernel
846 * should not happen.
847 *
848 * fall through...
849 */
850 OS_FALLTHROUGH;
851 default:
852 /*
853 * Exception 15 is reserved but some chips may generate it
854 * spuriously. Seen at startup on AMD Athlon-64.
855 */
856 if (type == 15) {
857 kprintf("kernel_trap() ignoring spurious trap 15\n");
858 goto common_return;
859 }
860 debugger_entry:
861 /* Ensure that the i386_kernel_state at the base of the
862 * current thread's stack (if any) is synchronized with the
863 * context at the moment of the trap, to facilitate
864 * access through the debugger.
865 */
866 sync_iss_to_iks(state);
867 #if MACH_KDP
868 if (kdp_i386_trap(type, saved_state, result, (vm_offset_t)vaddr)) {
869 goto common_return;
870 }
871 #endif
872 }
873 if (type == T_PAGE_FAULT) {
874 panic_fault_address = vaddr;
875 }
876 pal_cli();
877 panic_trap(saved_state, trap_pl, fault_result);
878 /*
879 * NO RETURN
880 */
881
882 common_return:
883 #if DEVELOPMENT || DEBUG
884 if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
885 traptrace_end(traptrace_index, mach_absolute_time());
886 }
887 #endif
888 return;
889 }
890
891 static void
set_recovery_ip(x86_saved_state64_t * saved_state,vm_offset_t ip)892 set_recovery_ip(x86_saved_state64_t *saved_state, vm_offset_t ip)
893 {
894 saved_state->isf.rip = ip;
895 }
896
897 static void
panic_trap(x86_saved_state64_t * regs,uint32_t pl,kern_return_t fault_result)898 panic_trap(x86_saved_state64_t *regs, uint32_t pl, kern_return_t fault_result)
899 {
900 const char *trapname = "Unknown";
901 pal_cr_t cr0, cr2, cr3, cr4;
902 boolean_t potential_smep_fault = FALSE, potential_kernel_NX_fault = FALSE;
903 boolean_t potential_smap_fault = FALSE;
904
905 pal_get_control_registers( &cr0, &cr2, &cr3, &cr4 );
906 assert(ml_get_interrupts_enabled() == FALSE);
907 current_cpu_datap()->cpu_fatal_trap_state = regs;
908 /*
909 * Issue an I/O port read if one has been requested - this is an
910 * event logic analyzers can use as a trigger point.
911 */
912 panic_notify();
913
914 kprintf("CPU %d panic trap number 0x%x, rip 0x%016llx\n",
915 cpu_number(), regs->isf.trapno, regs->isf.rip);
916 kprintf("cr0 0x%016llx cr2 0x%016llx cr3 0x%016llx cr4 0x%016llx\n",
917 cr0, cr2, cr3, cr4);
918
919 if (regs->isf.trapno < TRAP_TYPES) {
920 trapname = trap_type[regs->isf.trapno];
921 }
922
923 if ((regs->isf.trapno == T_PAGE_FAULT) && (regs->isf.err == (T_PF_PROT | T_PF_EXECUTE)) && (regs->isf.rip == regs->cr2)) {
924 if (pmap_smep_enabled && (regs->isf.rip < VM_MAX_USER_PAGE_ADDRESS)) {
925 potential_smep_fault = TRUE;
926 } else if (regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
927 potential_kernel_NX_fault = TRUE;
928 }
929 } else if (pmap_smap_enabled &&
930 regs->isf.trapno == T_PAGE_FAULT &&
931 regs->isf.err & T_PF_PROT &&
932 regs->cr2 < VM_MAX_USER_PAGE_ADDRESS &&
933 regs->isf.rip >= VM_MIN_KERNEL_AND_KEXT_ADDRESS) {
934 potential_smap_fault = TRUE;
935 }
936
937 #undef panic
938 panic("Kernel trap at 0x%016llx, type %d=%s, registers:\n"
939 "CR0: 0x%016llx, CR2: 0x%016llx, CR3: 0x%016llx, CR4: 0x%016llx\n"
940 "RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
941 "RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
942 "R8: 0x%016llx, R9: 0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
943 "R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
944 "RFL: 0x%016llx, RIP: 0x%016llx, CS: 0x%016llx, SS: 0x%016llx\n"
945 "Fault CR2: 0x%016llx, Error code: 0x%016llx, Fault CPU: 0x%x%s%s%s%s, PL: %d, VF: %d\n",
946 regs->isf.rip, regs->isf.trapno, trapname,
947 cr0, cr2, cr3, cr4,
948 regs->rax, regs->rbx, regs->rcx, regs->rdx,
949 regs->isf.rsp, regs->rbp, regs->rsi, regs->rdi,
950 regs->r8, regs->r9, regs->r10, regs->r11,
951 regs->r12, regs->r13, regs->r14, regs->r15,
952 regs->isf.rflags, regs->isf.rip, regs->isf.cs & 0xFFFF,
953 regs->isf.ss & 0xFFFF, regs->cr2, regs->isf.err, regs->isf.cpu,
954 virtualized ? " VMM" : "",
955 potential_kernel_NX_fault ? " Kernel NX fault" : "",
956 potential_smep_fault ? " SMEP/User NX fault" : "",
957 potential_smap_fault ? " SMAP fault" : "",
958 pl,
959 fault_result);
960 }
961
962 #if CONFIG_DTRACE
963 extern kern_return_t dtrace_user_probe(x86_saved_state_t *);
964 #endif
965
966 #if DEBUG
967 uint32_t fsigs[2];
968 uint32_t fsigns, fsigcs;
969 #endif
970
971 /*
972 * Trap from user mode.
973 */
974 void
user_trap(x86_saved_state_t * saved_state)975 user_trap(
976 x86_saved_state_t *saved_state)
977 {
978 int exc;
979 int err;
980 mach_exception_code_t code;
981 mach_exception_subcode_t subcode;
982 int type;
983 user_addr_t vaddr;
984 vm_prot_t prot;
985 thread_t thread = current_thread();
986 kern_return_t kret;
987 user_addr_t rip;
988 unsigned long dr6 = 0; /* 32 bit for i386, 64 bit for x86_64 */
989 int current_cpu = cpu_number();
990 #if DEVELOPMENT || DEBUG
991 bool inspect_cacheline = false;
992 uint32_t traptrace_index;
993 #endif
994 assert((is_saved_state32(saved_state) && !thread_is_64bit_addr(thread)) ||
995 (is_saved_state64(saved_state) && thread_is_64bit_addr(thread)));
996
997 if (is_saved_state64(saved_state)) {
998 x86_saved_state64_t *regs;
999
1000 regs = saved_state64(saved_state);
1001
1002 /* Record cpu where state was captured */
1003 regs->isf.cpu = current_cpu;
1004
1005 type = regs->isf.trapno;
1006 err = (int)regs->isf.err & 0xffff;
1007 vaddr = (user_addr_t)regs->cr2;
1008 rip = (user_addr_t)regs->isf.rip;
1009 #if DEVELOPMENT || DEBUG
1010 traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->rbp);
1011 #endif
1012 } else {
1013 x86_saved_state32_t *regs;
1014
1015 regs = saved_state32(saved_state);
1016
1017 /* Record cpu where state was captured */
1018 regs->cpu = current_cpu;
1019
1020 type = regs->trapno;
1021 err = regs->err & 0xffff;
1022 vaddr = (user_addr_t)regs->cr2;
1023 rip = (user_addr_t)regs->eip;
1024 #if DEVELOPMENT || DEBUG
1025 traptrace_index = traptrace_start(type, rip, mach_absolute_time(), regs->ebp);
1026 #endif
1027 }
1028
1029 #if DEVELOPMENT || DEBUG
1030 /*
1031 * Copy the cacheline of code into the thread's instruction stream save area
1032 * before enabling interrupts (the assumption is that we have not otherwise faulted or
1033 * trapped since the original cache line stores). If the saved code is not valid,
1034 * we'll catch it below when we process the copyin() for unhandled faults.
1035 */
1036 if (thread->machine.insn_copy_optout == false &&
1037 (type == T_PAGE_FAULT || type == T_INVALID_OPCODE || type == T_GENERAL_PROTECTION)) {
1038 #define CACHELINE_SIZE 64
1039 THREAD_TO_PCB(thread)->insn_cacheline[CACHELINE_SIZE] = (uint8_t)(rip & (CACHELINE_SIZE - 1));
1040 bcopy(&cpu_shadowp(current_cpu)->cpu_rtimes[0],
1041 &THREAD_TO_PCB(thread)->insn_cacheline[0],
1042 sizeof(THREAD_TO_PCB(thread)->insn_cacheline) - 1);
1043 inspect_cacheline = true;
1044 }
1045 #endif
1046
1047 if (type == T_DEBUG) {
1048 if (thread->machine.ids) {
1049 unsigned long clear = 0;
1050 /* Stash and clear this processor's DR6 value, in the event
1051 * this was a debug register match
1052 */
1053 __asm__ volatile ("mov %%db6, %0" : "=r" (dr6));
1054 __asm__ volatile ("mov %0, %%db6" : : "r" (clear));
1055 }
1056 /* [Re]Enable LBRs *BEFORE* enabling interrupts to ensure we hit the right CPU */
1057 i386_lbr_enable();
1058 }
1059
1060 if (type == T_PAGE_FAULT) {
1061 thread_reset_pcs_will_fault(thread);
1062 }
1063
1064 pal_sti();
1065
1066 KERNEL_DEBUG_CONSTANT_IST(KDEBUG_TRACE,
1067 (MACHDBG_CODE(DBG_MACH_EXCP_UTRAP_x86, type)) | DBG_FUNC_NONE,
1068 (unsigned)(vaddr >> 32), (unsigned)vaddr,
1069 (unsigned)(rip >> 32), (unsigned)rip, 0);
1070
1071 code = 0;
1072 subcode = 0;
1073 exc = 0;
1074
1075 #if CONFIG_DTRACE
1076 /*
1077 * DTrace does not consume all user traps, only INT_3's for now.
1078 * Avoid needlessly calling tempDTraceTrapHook here, and let the
1079 * INT_3 case handle them.
1080 */
1081 #endif
1082
1083 DEBUG_KPRINT_SYSCALL_MASK(1,
1084 "user_trap: type=0x%x(%s) err=0x%x cr2=%p rip=%p\n",
1085 type, trap_type[type], err, (void *)(long) vaddr, (void *)(long) rip);
1086
1087 switch (type) {
1088 case T_DIVIDE_ERROR:
1089 exc = EXC_ARITHMETIC;
1090 code = EXC_I386_DIV;
1091 break;
1092
1093 case T_DEBUG:
1094 {
1095 pcb_t pcb;
1096 /*
1097 * Update the PCB with this processor's DR6 value
1098 * in the event this was a debug register match.
1099 */
1100 pcb = THREAD_TO_PCB(thread);
1101 if (pcb->ids) {
1102 /*
1103 * We can get and set the status register
1104 * in 32-bit mode even on a 64-bit thread
1105 * because the high order bits are not
1106 * used on x86_64
1107 */
1108 if (thread_is_64bit_addr(thread)) {
1109 x86_debug_state64_t *ids = pcb->ids;
1110 ids->dr6 = dr6;
1111 } else { /* 32 bit thread */
1112 x86_debug_state32_t *ids = pcb->ids;
1113 ids->dr6 = (uint32_t) dr6;
1114 }
1115 }
1116 exc = EXC_BREAKPOINT;
1117 code = EXC_I386_SGL;
1118 break;
1119 }
1120 case T_INT3:
1121 #if CONFIG_DTRACE
1122 if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
1123 return; /* If it succeeds, we are done... */
1124 }
1125 #endif
1126 exc = EXC_BREAKPOINT;
1127 code = EXC_I386_BPT;
1128 break;
1129
1130 case T_OVERFLOW:
1131 exc = EXC_ARITHMETIC;
1132 code = EXC_I386_INTO;
1133 break;
1134
1135 case T_OUT_OF_BOUNDS:
1136 exc = EXC_SOFTWARE;
1137 code = EXC_I386_BOUND;
1138 break;
1139
1140 case T_INVALID_OPCODE:
1141 if (fpUDflt(rip) == 1) {
1142 exc = EXC_BAD_INSTRUCTION;
1143 code = EXC_I386_INVOP;
1144 }
1145 break;
1146
1147 case T_NO_FPU:
1148 fpnoextflt();
1149 break;
1150
1151 case T_FPU_FAULT:
1152 fpextovrflt();
1153 /*
1154 * Raise exception.
1155 */
1156 exc = EXC_BAD_ACCESS;
1157 code = VM_PROT_READ | VM_PROT_EXECUTE;
1158 subcode = 0;
1159 break;
1160
1161 case T_INVALID_TSS: /* invalid TSS == iret with NT flag set */
1162 exc = EXC_BAD_INSTRUCTION;
1163 code = EXC_I386_INVTSSFLT;
1164 subcode = err;
1165 break;
1166
1167 case T_SEGMENT_NOT_PRESENT:
1168 exc = EXC_BAD_INSTRUCTION;
1169 code = EXC_I386_SEGNPFLT;
1170 subcode = err;
1171 break;
1172
1173 case T_STACK_FAULT:
1174 exc = EXC_BAD_INSTRUCTION;
1175 code = EXC_I386_STKFLT;
1176 subcode = err;
1177 break;
1178
1179 case T_GENERAL_PROTECTION:
1180 /*
1181 * There's a wide range of circumstances which generate this
1182 * class of exception. From user-space, many involve bad
1183 * addresses (such as a non-canonical 64-bit address).
1184 * So we map this to EXC_BAD_ACCESS (and thereby SIGSEGV).
1185 * The trouble is cr2 doesn't contain the faulting address;
1186 * we'd need to decode the faulting instruction to really
1187 * determine this. We'll leave that to debuggers.
1188 * However, attempted execution of privileged instructions
1189 * (e.g. cli) also generate GP faults and so we map these to
1190 * to EXC_BAD_ACCESS (and thence SIGSEGV) also - rather than
1191 * EXC_BAD_INSTRUCTION which is more accurate. We just can't
1192 * win!
1193 */
1194 exc = EXC_BAD_ACCESS;
1195 code = EXC_I386_GPFLT;
1196 subcode = err;
1197 break;
1198
1199 case T_PAGE_FAULT:
1200 {
1201 prot = VM_PROT_READ;
1202
1203 if (err & T_PF_WRITE) {
1204 prot |= VM_PROT_WRITE;
1205 }
1206 if (__improbable(err & T_PF_EXECUTE)) {
1207 prot |= VM_PROT_EXECUTE;
1208 }
1209 #if DEVELOPMENT || DEBUG
1210 bool do_simd_hash = thread_fpsimd_hash_enabled();
1211 uint32_t fsig = 0;
1212 fsig = do_simd_hash ? thread_fpsimd_hash(thread) : 0;
1213 #if DEBUG
1214 fsigs[0] = fsig;
1215 #endif
1216 #endif
1217 kret = vm_fault(thread->map,
1218 vaddr,
1219 prot, FALSE, VM_KERN_MEMORY_NONE,
1220 THREAD_ABORTSAFE, NULL, 0);
1221 #if DEVELOPMENT || DEBUG
1222 if (do_simd_hash && fsig) {
1223 uint32_t fsig2 = thread_fpsimd_hash(thread);
1224 #if DEBUG
1225 fsigcs++;
1226 fsigs[1] = fsig2;
1227 #endif
1228 if (fsig != fsig2) {
1229 panic("FP/SIMD state hash mismatch across fault thread: %p 0x%x->0x%x", thread, fsig, fsig2);
1230 }
1231 } else {
1232 #if DEBUG
1233 fsigns++;
1234 #endif
1235 }
1236 #endif
1237 if (__probable((kret == KERN_SUCCESS) || (kret == KERN_ABORTED))) {
1238 break;
1239 } else if (__improbable(kret == KERN_FAILURE)) {
1240 /*
1241 * For a user trap, vm_fault() should never return KERN_FAILURE.
1242 * If it does, we're leaking preemption disables somewhere in the kernel.
1243 */
1244 panic("vm_fault() KERN_FAILURE from user fault on thread %p", thread);
1245 }
1246
1247 /* PAL debug hook (empty on x86) */
1248 pal_dbg_page_fault(thread, vaddr, kret);
1249 exc = EXC_BAD_ACCESS;
1250 code = kret;
1251 subcode = vaddr;
1252 }
1253 break;
1254
1255 case T_SSE_FLOAT_ERROR:
1256 fpSSEexterrflt();
1257 exc = EXC_ARITHMETIC;
1258 code = EXC_I386_SSEEXTERR;
1259 subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_MXCSR;
1260 break;
1261
1262
1263 case T_FLOATING_POINT_ERROR:
1264 fpexterrflt();
1265 exc = EXC_ARITHMETIC;
1266 code = EXC_I386_EXTERR;
1267 subcode = ((struct x86_fx_thread_state *)thread->machine.ifps)->fx_status;
1268 break;
1269
1270 case T_DTRACE_RET:
1271 #if CONFIG_DTRACE
1272 if (dtrace_user_probe(saved_state) == KERN_SUCCESS) {
1273 return; /* If it succeeds, we are done... */
1274 }
1275 #endif
1276 /*
1277 * If we get an INT 0x7f when we do not expect to,
1278 * treat it as an illegal instruction
1279 */
1280 exc = EXC_BAD_INSTRUCTION;
1281 code = EXC_I386_INVOP;
1282 break;
1283
1284 default:
1285 panic("Unexpected user trap, type %d", type);
1286 }
1287
1288 if (type == T_PAGE_FAULT) {
1289 thread_reset_pcs_done_faulting(thread);
1290 }
1291
1292 if (exc != 0) {
1293 uint16_t cs;
1294 boolean_t intrs;
1295
1296 if (is_saved_state64(saved_state)) {
1297 cs = saved_state64(saved_state)->isf.cs;
1298 } else {
1299 cs = saved_state32(saved_state)->cs;
1300 }
1301
1302 if (last_branch_enabled_modes == LBR_ENABLED_USERMODE) {
1303 intrs = ml_set_interrupts_enabled(FALSE);
1304 /*
1305 * This is a bit racy (it's possible for this thread to migrate to another CPU, then
1306 * migrate back, but that seems rather rare in practice), but good enough to ensure
1307 * the LBRs are saved before proceeding with exception/signal dispatch.
1308 */
1309 if (current_cpu == cpu_number()) {
1310 i386_lbr_synch(thread);
1311 }
1312 ml_set_interrupts_enabled(intrs);
1313 }
1314
1315 /*
1316 * Do not try to copyin from the instruction stream if the page fault was due
1317 * to an access to rip and was unhandled.
1318 * Do not deal with cases when %cs != USER[64]_CS
1319 * And of course there's no need to copy the instruction stream if the boot-arg
1320 * was set to 0.
1321 */
1322 if (thread->machine.insn_copy_optout == false && insn_copyin_count > 0 &&
1323 (cs == USER64_CS || cs == USER_CS) && (type != T_PAGE_FAULT || vaddr != rip)) {
1324 #if DEVELOPMENT || DEBUG
1325 copy_instruction_stream(thread, rip, type, inspect_cacheline);
1326 #else
1327 copy_instruction_stream(thread, rip, type);
1328 #endif
1329 }
1330
1331 #if DEVELOPMENT || DEBUG
1332 if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
1333 traptrace_end(traptrace_index, mach_absolute_time());
1334 }
1335 #endif
1336 /*
1337 * Note: Codepaths that directly return from user_trap() have pending
1338 * ASTs processed in locore
1339 */
1340 i386_exception(exc, code, subcode);
1341 /* NOTREACHED */
1342 } else {
1343 #if DEVELOPMENT || DEBUG
1344 if (traptrace_index != TRAPTRACE_INVALID_INDEX) {
1345 traptrace_end(traptrace_index, mach_absolute_time());
1346 }
1347 #endif
1348 }
1349 }
1350
1351 /*
1352 * Copyin up to x86_INSTRUCTION_STATE_MAX_INSN_BYTES bytes from the page that includes `rip`,
1353 * ensuring that we stay on the same page, clipping the start or end, as needed.
1354 * Add the clipped amount back at the start or end, depending on where it fits.
1355 * Consult the variable populated by the boot-arg `insn_capcnt'
1356 */
1357 static __attribute__((noinline)) void
copy_instruction_stream(thread_t thread,uint64_t rip,int __unused trap_code,bool inspect_cacheline)1358 copy_instruction_stream(thread_t thread, uint64_t rip, int __unused trap_code
1359 #if DEVELOPMENT || DEBUG
1360 , bool inspect_cacheline
1361 #endif
1362 )
1363 {
1364 #if x86_INSTRUCTION_STATE_MAX_INSN_BYTES > 4096
1365 #error x86_INSTRUCTION_STATE_MAX_INSN_BYTES cannot exceed a page in size.
1366 #endif
1367 pcb_t pcb = THREAD_TO_PCB(thread);
1368 vm_map_offset_t pagemask = ~vm_map_page_mask(current_map());
1369 vm_map_offset_t rip_page = rip & pagemask;
1370 vm_map_offset_t start_addr;
1371 vm_map_offset_t insn_offset;
1372 vm_map_offset_t end_addr = rip + (insn_copyin_count / 2);
1373 void *stack_buffer;
1374 int copyin_err = 0;
1375 #if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
1376 void *procname;
1377 #endif
1378
1379 #if DEVELOPMENT || DEBUG
1380 assert(insn_copyin_count <= x86_INSTRUCTION_STATE_MAX_INSN_BYTES);
1381 #else
1382 if (insn_copyin_count > x86_INSTRUCTION_STATE_MAX_INSN_BYTES ||
1383 insn_copyin_count < 64 /* CACHELINE_SIZE */) {
1384 return;
1385 }
1386 #endif
1387
1388 #pragma clang diagnostic push
1389 #pragma clang diagnostic ignored "-Walloca"
1390 stack_buffer = __builtin_alloca(insn_copyin_count);
1391 #pragma clang diagnostic pop
1392
1393 if (rip >= (insn_copyin_count / 2)) {
1394 start_addr = rip - (insn_copyin_count / 2);
1395 } else {
1396 start_addr = 0;
1397 }
1398
1399 if (start_addr < rip_page) {
1400 insn_offset = (insn_copyin_count / 2) - (rip_page - start_addr);
1401 end_addr += (rip_page - start_addr);
1402 start_addr = rip_page;
1403 } else if (end_addr >= (rip_page + (~pagemask + 1))) {
1404 start_addr -= (end_addr - (rip_page + (~pagemask + 1))); /* Adjust start address backward */
1405 /* Adjust instruction offset due to start address change */
1406 insn_offset = (insn_copyin_count / 2) + (end_addr - (rip_page + (~pagemask + 1)));
1407 end_addr = rip_page + (~pagemask + 1); /* clip to the start of the next page (non-inclusive */
1408 } else {
1409 insn_offset = insn_copyin_count / 2;
1410 }
1411
1412 disable_preemption(); /* Prevent copyin from faulting in the instruction stream */
1413 if (
1414 #if DEVELOPMENT || DEBUG
1415 (insnstream_force_cacheline_mismatch < 2) &&
1416 #endif
1417 ((end_addr > start_addr) && (copyin_err = copyin(start_addr, stack_buffer, end_addr - start_addr)) == 0)) {
1418 enable_preemption();
1419
1420 if (pcb->insn_state == 0) {
1421 pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
1422 }
1423
1424 if (pcb->insn_state != 0) {
1425 bcopy(stack_buffer, pcb->insn_state->insn_bytes, end_addr - start_addr);
1426 bzero(&pcb->insn_state->insn_bytes[end_addr - start_addr],
1427 insn_copyin_count - (end_addr - start_addr));
1428
1429 pcb->insn_state->insn_stream_valid_bytes = (int)(end_addr - start_addr);
1430 pcb->insn_state->insn_offset = (int)insn_offset;
1431
1432 #if DEVELOPMENT || DEBUG
1433 /* Now try to validate the cacheline we read at early-fault time matches the code
1434 * copied in. Before we do that, we have to make sure the buffer contains a valid
1435 * cacheline by looking for the 2 sentinel values written in the event the cacheline
1436 * could not be copied.
1437 */
1438 #define CACHELINE_DATA_NOT_PRESENT 0xdeadc0debeefcafeULL
1439 #define CACHELINE_MASK (CACHELINE_SIZE - 1)
1440
1441 if (inspect_cacheline &&
1442 (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
1443 *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
1444 /*
1445 * The position of the cacheline in the instruction buffer is at offset
1446 * insn_offset - (rip & CACHELINE_MASK)
1447 */
1448 if (__improbable((rip & CACHELINE_MASK) > insn_offset)) {
1449 printf("thread %p code cacheline @ %p clipped wrt copied-in code (offset %d)\n",
1450 thread, (void *)(rip & ~CACHELINE_MASK), (int)(rip & CACHELINE_MASK));
1451 } else if (bcmp(&pcb->insn_state->insn_bytes[insn_offset - (rip & CACHELINE_MASK)],
1452 &pcb->insn_cacheline[0], CACHELINE_SIZE) != 0
1453 || insnstream_force_cacheline_mismatch
1454 ) {
1455 #if x86_INSTRUCTION_STATE_CACHELINE_SIZE != CACHELINE_SIZE
1456 #error cacheline size mismatch
1457 #endif
1458 bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
1459 x86_INSTRUCTION_STATE_CACHELINE_SIZE);
1460 /* Mark the instruction stream as being out-of-synch */
1461 pcb->insn_state->out_of_synch = 1;
1462
1463 printf("thread %p code cacheline @ %p mismatches with copied-in code [trap 0x%x]\n",
1464 thread, (void *)(rip & ~CACHELINE_MASK), trap_code);
1465 for (int i = 0; i < 8; i++) {
1466 printf("\t[%d] cl=0x%08llx vs. ci=0x%08llx\n", i, *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[i * 8],
1467 *(uint64_t *)(uintptr_t)&pcb->insn_state->insn_bytes[(i * 8) + insn_offset - (rip & CACHELINE_MASK)]);
1468 }
1469 if (panic_on_cacheline_mismatch) {
1470 panic("Cacheline mismatch while processing unhandled exception.");
1471 }
1472 } else {
1473 pcb->insn_state->out_of_synch = 0;
1474 }
1475 } else if (inspect_cacheline) {
1476 printf("thread %p could not capture code cacheline at fault IP %p [offset %d]\n",
1477 (void *)thread, (void *)rip, (int)(insn_offset - (rip & CACHELINE_MASK)));
1478 pcb->insn_state->out_of_synch = 0;
1479 }
1480 #else
1481 pcb->insn_state->out_of_synch = 0;
1482 #endif /* DEVELOPMENT || DEBUG */
1483
1484 #if defined(MACH_BSD) && (DEVELOPMENT || DEBUG)
1485 if (panic_on_trap_procname[0] != 0) {
1486 task_t task = get_threadtask(thread);
1487 char procnamebuf[65] = {0};
1488
1489 if (get_bsdtask_info(task) != NULL) {
1490 procname = proc_name_address(get_bsdtask_info(task));
1491 strlcpy(procnamebuf, procname, sizeof(procnamebuf));
1492
1493 if (strcasecmp(panic_on_trap_procname, procnamebuf) == 0 &&
1494 ((1U << trap_code) & panic_on_trap_mask) != 0) {
1495 panic("Panic requested on trap type 0x%x for process `%s'", trap_code,
1496 panic_on_trap_procname);
1497 /*NORETURN*/
1498 }
1499 }
1500 }
1501 #endif /* MACH_BSD && (DEVELOPMENT || DEBUG) */
1502 }
1503 } else {
1504 enable_preemption();
1505
1506 pcb->insn_state_copyin_failure_errorcode = copyin_err;
1507 #if DEVELOPMENT || DEBUG
1508 if (inspect_cacheline && pcb->insn_state == 0) {
1509 pcb->insn_state = kalloc_data(sizeof(x86_instruction_state_t), Z_WAITOK);
1510 }
1511 if (pcb->insn_state != 0) {
1512 pcb->insn_state->insn_stream_valid_bytes = 0;
1513 pcb->insn_state->insn_offset = 0;
1514
1515 if (inspect_cacheline &&
1516 (*(uint64_t *)(uintptr_t)&pcb->insn_cacheline[0] != CACHELINE_DATA_NOT_PRESENT &&
1517 *(uint64_t *)(uintptr_t)&pcb->insn_cacheline[8] != CACHELINE_DATA_NOT_PRESENT)) {
1518 /*
1519 * We can still copy the cacheline into the instruction state structure
1520 * if it contains valid data
1521 */
1522 pcb->insn_state->out_of_synch = 1;
1523 bcopy(&pcb->insn_cacheline[0], &pcb->insn_state->insn_cacheline[0],
1524 x86_INSTRUCTION_STATE_CACHELINE_SIZE);
1525 }
1526 }
1527 #endif /* DEVELOPMENT || DEBUG */
1528 }
1529 }
1530
1531 /*
1532 * Handle exceptions for i386.
1533 *
1534 * If we are an AT bus machine, we must turn off the AST for a
1535 * delayed floating-point exception.
1536 *
1537 * If we are providing floating-point emulation, we may have
1538 * to retrieve the real register values from the floating point
1539 * emulator.
1540 */
1541 void
i386_exception(int exc,mach_exception_code_t code,mach_exception_subcode_t subcode)1542 i386_exception(
1543 int exc,
1544 mach_exception_code_t code,
1545 mach_exception_subcode_t subcode)
1546 {
1547 mach_exception_data_type_t codes[EXCEPTION_CODE_MAX];
1548
1549 DEBUG_KPRINT_SYSCALL_MACH("i386_exception: exc=%d code=0x%llx subcode=0x%llx\n",
1550 exc, code, subcode);
1551 codes[0] = code; /* new exception interface */
1552 codes[1] = subcode;
1553 exception_triage(exc, codes, 2);
1554 /*NOTREACHED*/
1555 }
1556
1557
1558 /* Synchronize a thread's x86_kernel_state (if any) with the given
1559 * x86_saved_state_t obtained from the trap/IPI handler; called in
1560 * kernel_trap() prior to entering the debugger, and when receiving
1561 * an "MP_KDP" IPI. Called with null saved_state if an incoming IPI
1562 * was detected from the kernel while spinning with interrupts masked.
1563 */
1564
1565 void
sync_iss_to_iks(x86_saved_state_t * saved_state)1566 sync_iss_to_iks(x86_saved_state_t *saved_state)
1567 {
1568 struct x86_kernel_state *iks = NULL;
1569 vm_offset_t kstack;
1570 boolean_t record_active_regs = FALSE;
1571
1572 /* The PAL may have a special way to sync registers */
1573 if (saved_state && saved_state->flavor == THREAD_STATE_NONE) {
1574 pal_get_kern_regs( saved_state );
1575 }
1576
1577 if (current_thread() != NULL &&
1578 (kstack = current_thread()->kernel_stack) != 0) {
1579 x86_saved_state64_t *regs = saved_state64(saved_state);
1580
1581 iks = STACK_IKS(kstack);
1582
1583 /* Did we take the trap/interrupt in kernel mode? */
1584 if (saved_state == NULL || /* NULL => polling in kernel */
1585 regs == USER_REGS64(current_thread())) {
1586 record_active_regs = TRUE;
1587 } else {
1588 iks->k_rbx = regs->rbx;
1589 iks->k_rsp = regs->isf.rsp;
1590 iks->k_rbp = regs->rbp;
1591 iks->k_r12 = regs->r12;
1592 iks->k_r13 = regs->r13;
1593 iks->k_r14 = regs->r14;
1594 iks->k_r15 = regs->r15;
1595 iks->k_rip = regs->isf.rip;
1596 }
1597 }
1598
1599 if (record_active_regs == TRUE) {
1600 /* Show the trap handler path */
1601 __asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
1602 __asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
1603 __asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
1604 __asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
1605 __asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
1606 __asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
1607 __asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
1608 /* "Current" instruction pointer */
1609 __asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:"
1610 : "=m" (iks->k_rip)
1611 :
1612 : "rax");
1613 }
1614 }
1615
1616 /*
1617 * This is used by the NMI interrupt handler (from mp.c) to
1618 * uncondtionally sync the trap handler context to the IKS
1619 * irrespective of whether the NMI was fielded in kernel
1620 * or user space.
1621 */
1622 void
sync_iss_to_iks_unconditionally(__unused x86_saved_state_t * saved_state)1623 sync_iss_to_iks_unconditionally(__unused x86_saved_state_t *saved_state)
1624 {
1625 struct x86_kernel_state *iks;
1626 vm_offset_t kstack;
1627
1628 if ((kstack = current_thread()->kernel_stack) != 0) {
1629 iks = STACK_IKS(kstack);
1630 /* Display the trap handler path */
1631 __asm__ volatile ("movq %%rbx, %0" : "=m" (iks->k_rbx));
1632 __asm__ volatile ("movq %%rsp, %0" : "=m" (iks->k_rsp));
1633 __asm__ volatile ("movq %%rbp, %0" : "=m" (iks->k_rbp));
1634 __asm__ volatile ("movq %%r12, %0" : "=m" (iks->k_r12));
1635 __asm__ volatile ("movq %%r13, %0" : "=m" (iks->k_r13));
1636 __asm__ volatile ("movq %%r14, %0" : "=m" (iks->k_r14));
1637 __asm__ volatile ("movq %%r15, %0" : "=m" (iks->k_r15));
1638 /* "Current" instruction pointer */
1639 __asm__ volatile ("leaq 1f(%%rip), %%rax; mov %%rax, %0\n1:" : "=m" (iks->k_rip)::"rax");
1640 }
1641 }
1642
1643 #if DEBUG
1644 #define TERI 1
1645 #endif
1646
1647 #if TERI
1648 extern void thread_exception_return_internal(void) __dead2;
1649
1650 void
thread_exception_return(void)1651 thread_exception_return(void)
1652 {
1653 thread_t thread = current_thread();
1654 task_t task = current_task();
1655
1656 ml_set_interrupts_enabled(FALSE);
1657 if (thread_is_64bit_addr(thread) != task_has_64Bit_addr(task)) {
1658 panic("Task/thread bitness mismatch %p %p, task: %d, thread: %d",
1659 thread, task, thread_is_64bit_addr(thread), task_has_64Bit_addr(task));
1660 }
1661
1662 if (thread_is_64bit_addr(thread)) {
1663 if ((gdt_desc_p(USER64_CS)->access & ACC_PL_U) == 0) {
1664 panic("64-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER64_CS));
1665 }
1666 } else {
1667 if ((gdt_desc_p(USER_CS)->access & ACC_PL_U) == 0) {
1668 panic("32-GDT mismatch %p, descriptor: %p", thread, gdt_desc_p(USER_CS));
1669 }
1670 }
1671 assert(get_preemption_level() == 0);
1672 thread_exception_return_internal();
1673 }
1674 #endif
1675
1676 #if DEVELOPMENT || DEBUG
1677 static int trap_handled;
1678
1679 static void
handle_recoverable_kernel_trap(__unused void * tstate,uint16_t comment)1680 handle_recoverable_kernel_trap(
1681 __unused void *tstate,
1682 uint16_t comment)
1683 {
1684 assert(comment == TEST_RECOVERABLE_SOFT_TRAP);
1685
1686 printf("Recoverable trap handled.\n");
1687 trap_handled = 1;
1688 }
1689
1690 KERNEL_BRK_DESCRIPTOR_DEFINE(test_desc,
1691 .type = KERNEL_BRK_TYPE_TEST,
1692 .base = TEST_RECOVERABLE_SOFT_TRAP,
1693 .max = TEST_RECOVERABLE_SOFT_TRAP,
1694 .options = KERNEL_BRK_RECOVERABLE,
1695 .handle_breakpoint = handle_recoverable_kernel_trap);
1696
1697 static int
recoverable_kernel_trap_test(__unused int64_t in,int64_t * out)1698 recoverable_kernel_trap_test(__unused int64_t in, int64_t *out)
1699 {
1700 ml_recoverable_trap(TEST_RECOVERABLE_SOFT_TRAP);
1701
1702 *out = trap_handled;
1703 return 0;
1704 }
1705
1706 SYSCTL_TEST_REGISTER(recoverable_kernel_trap, recoverable_kernel_trap_test);
1707 #endif
1708