1 /*
2 * Copyright (c) 2007-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 #include <debug.h>
30 #include <mach_kdp.h>
31
32 #include <kern/thread.h>
33 #include <machine/pmap.h>
34 #include <device/device_types.h>
35
36 #include <mach/vm_param.h>
37 #include <mach/clock_types.h>
38 #include <mach/machine.h>
39 #include <mach/kmod.h>
40 #include <pexpert/boot.h>
41 #include <pexpert/pexpert.h>
42
43 #include <ptrauth.h>
44
45 #include <kern/misc_protos.h>
46 #include <kern/startup.h>
47 #include <kern/clock.h>
48 #include <kern/debug.h>
49 #include <kern/processor.h>
50 #include <kdp/kdp_core.h>
51 #if ALTERNATE_DEBUGGER
52 #include <arm64/alternate_debugger.h>
53 #endif
54 #include <machine/atomic.h>
55 #include <machine/trap.h>
56 #include <kern/spl.h>
57 #include <pexpert/pexpert.h>
58 #include <kdp/kdp_callout.h>
59 #include <kdp/kdp_dyld.h>
60 #include <kdp/kdp_internal.h>
61 #include <kdp/kdp_common.h>
62 #include <uuid/uuid.h>
63 #include <sys/codesign.h>
64 #include <sys/time.h>
65
66 #include <IOKit/IOPlatformExpert.h>
67 #include <IOKit/IOKitServer.h>
68
69 #include <mach/vm_prot.h>
70 #include <vm/vm_map.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_shared_region.h>
73 #include <mach/time_value.h>
74 #include <machine/machparam.h> /* for btop */
75
76 #include <console/video_console.h>
77 #include <console/serial_protos.h>
78 #include <arm/cpu_data.h>
79 #include <arm/cpu_data_internal.h>
80 #include <arm/cpu_internal.h>
81 #include <arm/misc_protos.h>
82 #include <libkern/OSKextLibPrivate.h>
83 #include <vm/vm_kern.h>
84 #include <kern/kern_cdata.h>
85 #include <kern/ledger.h>
86
87
88 #if DEVELOPMENT || DEBUG
89 #include <kern/ext_paniclog.h>
90 #endif
91
92 #if MACH_KDP
93 void kdp_trap(unsigned int, struct arm_saved_state *);
94 #endif
95
96 extern kern_return_t do_stackshot(void *);
97 extern void kdp_snapshot_preflight(int pid, void * tracebuf,
98 uint32_t tracebuf_size, uint64_t flags,
99 kcdata_descriptor_t data_p,
100 uint64_t since_timestamp, uint32_t pagetable_mask);
101 extern int kdp_stack_snapshot_bytes_traced(void);
102 extern int kdp_stack_snapshot_bytes_uncompressed(void);
103
104 /*
105 * Increment the PANICLOG_VERSION if you change the format of the panic
106 * log in any way.
107 */
108 #define PANICLOG_VERSION 14
109 static struct kcdata_descriptor kc_panic_data;
110
111 extern char iBoot_version[];
112 #if defined(TARGET_OS_OSX) && defined(__arm64__)
113 extern char iBoot_Stage_2_version[];
114 #endif /* defined(TARGET_OS_OSX) && defined(__arm64__) */
115
116 extern volatile uint32_t debug_enabled;
117 extern unsigned int not_in_kdp;
118
119 extern int copyinframe(vm_address_t fp, uint32_t * frame);
120 extern void kdp_callouts(kdp_event_t event);
121
122 /* #include <sys/proc.h> */
123 #define MAXCOMLEN 16
124 struct proc;
125 extern int proc_pid(struct proc *p);
126 extern void proc_name_kdp(struct proc *, char *, int);
127
128 /*
129 * Make sure there's enough space to include the relevant bits in the format required
130 * within the space allocated for the panic version string in the panic header.
131 * The format required by OSAnalytics/DumpPanic is 'Product Version (OS Version)'.
132 */
133 #define PANIC_HEADER_VERSION_FMT_STR "%.14s (%.14s)"
134
135 extern const char version[];
136 extern char osversion[];
137 extern char osproductversion[];
138 extern char osreleasetype[];
139
140 #if defined(XNU_TARGET_OS_BRIDGE)
141 extern char macosproductversion[];
142 extern char macosversion[];
143 #endif
144
145 extern uint8_t gPlatformECID[8];
146 extern uint32_t gPlatformMemoryID;
147
148 extern uint64_t last_hwaccess_thread;
149
150 /*Choosing the size for gTargetTypeBuffer as 16 and size for gModelTypeBuffer as 32
151 * since the target name and model name typically doesn't exceed this size */
152 extern char gTargetTypeBuffer[16];
153 extern char gModelTypeBuffer[32];
154
155 extern struct timeval gIOLastSleepTime;
156 extern struct timeval gIOLastWakeTime;
157 extern boolean_t is_clock_configured;
158 extern boolean_t kernelcache_uuid_valid;
159 extern uuid_t kernelcache_uuid;
160 extern uuid_string_t bootsessionuuid_string;
161
162 extern uint64_t roots_installed;
163
164 /* Definitions for frame pointers */
165 #define FP_ALIGNMENT_MASK ((uint32_t)(0x3))
166 #define FP_LR_OFFSET ((uint32_t)4)
167 #define FP_LR_OFFSET64 ((uint32_t)8)
168 #define FP_MAX_NUM_TO_EVALUATE (50)
169
170 /* Timeout for all processors responding to debug crosscall */
171 MACHINE_TIMEOUT(debug_ack_timeout, "debug-ack", 240000, MACHINE_TIMEOUT_UNIT_TIMEBASE, NULL);
172
173 /* Forward functions definitions */
174 void panic_display_times(void);
175 void panic_print_symbol_name(vm_address_t search);
176
177
178 /* Global variables */
179 static uint32_t panic_bt_depth;
180 boolean_t PanicInfoSaved = FALSE;
181 boolean_t force_immediate_debug_halt = FALSE;
182 unsigned int debug_ack_timeout_count = 0;
183 volatile unsigned int debugger_sync = 0;
184 volatile unsigned int mp_kdp_trap = 0; /* CPUs signalled by the debug CPU will spin on this */
185 volatile unsigned int debug_cpus_spinning = 0; /* Number of signalled CPUs still spinning on mp_kdp_trap (in DebuggerXCall). */
186 unsigned int DebugContextCount = 0;
187
188 #if defined(__arm64__)
189 uint8_t PE_smc_stashed_x86_system_state = 0xFF;
190 uint8_t PE_smc_stashed_x86_power_state = 0xFF;
191 uint8_t PE_smc_stashed_x86_efi_boot_state = 0xFF;
192 uint8_t PE_smc_stashed_x86_shutdown_cause = 0xFF;
193 uint64_t PE_smc_stashed_x86_prev_power_transitions = UINT64_MAX;
194 uint32_t PE_pcie_stashed_link_state = UINT32_MAX;
195 uint64_t PE_nvram_stashed_x86_macos_slide = UINT64_MAX;
196 #endif
197
198
199 /*
200 * Backtrace a single frame.
201 */
202 static void
print_one_backtrace(pmap_t pmap,vm_offset_t topfp,const char * cur_marker,boolean_t is_64_bit,boolean_t print_kexts_in_backtrace)203 print_one_backtrace(pmap_t pmap, vm_offset_t topfp, const char *cur_marker,
204 boolean_t is_64_bit, boolean_t print_kexts_in_backtrace)
205 {
206 unsigned int i = 0;
207 addr64_t lr = 0;
208 addr64_t fp = topfp;
209 addr64_t fp_for_ppn = 0;
210 ppnum_t ppn = (ppnum_t)NULL;
211 vm_offset_t raddrs[FP_MAX_NUM_TO_EVALUATE] = { 0 };
212 bool dump_kernel_stack = (fp >= VM_MIN_KERNEL_ADDRESS);
213
214 #if defined(HAS_APPLE_PAC)
215 fp = (addr64_t)ptrauth_strip((void *)fp, ptrauth_key_frame_pointer);
216 #endif
217 do {
218 if ((fp == 0) || ((fp & FP_ALIGNMENT_MASK) != 0)) {
219 break;
220 }
221 if (dump_kernel_stack && ((fp < VM_MIN_KERNEL_ADDRESS) || (fp > VM_MAX_KERNEL_ADDRESS))) {
222 break;
223 }
224 if ((!dump_kernel_stack) && (fp >= VM_MIN_KERNEL_ADDRESS)) {
225 break;
226 }
227
228 /*
229 * Check to see if current address will result in a different
230 * ppn than previously computed (to avoid recomputation) via
231 * (addr) ^ fp_for_ppn) >> PAGE_SHIFT)
232 */
233 if ((((fp + FP_LR_OFFSET) ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
234 ppn = pmap_find_phys(pmap, fp + FP_LR_OFFSET);
235 fp_for_ppn = fp + (is_64_bit ? FP_LR_OFFSET64 : FP_LR_OFFSET);
236 }
237 if (ppn != (ppnum_t)NULL) {
238 if (is_64_bit) {
239 lr = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET64) & PAGE_MASK));
240 #if defined(HAS_APPLE_PAC)
241 /* return addresses on stack will be signed by arm64e ABI */
242 lr = (addr64_t) ptrauth_strip((void *)lr, ptrauth_key_return_address);
243 #endif
244 } else {
245 lr = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET) & PAGE_MASK));
246 }
247 } else {
248 if (is_64_bit) {
249 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%016llx\n", cur_marker, fp + FP_LR_OFFSET64);
250 } else {
251 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%08x\n", cur_marker, (uint32_t)(fp + FP_LR_OFFSET));
252 }
253 break;
254 }
255 if (((fp ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
256 ppn = pmap_find_phys(pmap, fp);
257 fp_for_ppn = fp;
258 }
259 if (ppn != (ppnum_t)NULL) {
260 if (is_64_bit) {
261 fp = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
262 #if defined(HAS_APPLE_PAC)
263 /* frame pointers on stack will be signed by arm64e ABI */
264 fp = (addr64_t) ptrauth_strip((void *)fp, ptrauth_key_frame_pointer);
265 #endif
266 } else {
267 fp = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
268 }
269 } else {
270 if (is_64_bit) {
271 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%016llx\n", cur_marker, fp);
272 } else {
273 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%08x\n", cur_marker, (uint32_t)fp);
274 }
275 break;
276 }
277 /*
278 * Counter 'i' may == FP_MAX_NUM_TO_EVALUATE when running one
279 * extra round to check whether we have all frames in order to
280 * indicate (in)complete backtrace below. This happens in a case
281 * where total frame count and FP_MAX_NUM_TO_EVALUATE are equal.
282 * Do not capture anything.
283 */
284 if (i < FP_MAX_NUM_TO_EVALUATE && lr) {
285 if (is_64_bit) {
286 paniclog_append_noflush("%s\t lr: 0x%016llx fp: 0x%016llx\n", cur_marker, lr, fp);
287 } else {
288 paniclog_append_noflush("%s\t lr: 0x%08x fp: 0x%08x\n", cur_marker, (uint32_t)lr, (uint32_t)fp);
289 }
290 raddrs[i] = lr;
291 }
292 } while ((++i <= FP_MAX_NUM_TO_EVALUATE) && (fp != topfp));
293
294 if (i > FP_MAX_NUM_TO_EVALUATE && fp != 0) {
295 paniclog_append_noflush("Backtrace continues...\n");
296 }
297
298 if (print_kexts_in_backtrace && i > 0) {
299 kmod_panic_dump(&raddrs[0], i);
300 }
301 }
302
303 #define SANE_TASK_LIMIT 256
304 #define TOP_RUNNABLE_LIMIT 5
305 #define PANICLOG_UUID_BUF_SIZE 256
306
307 extern void panic_print_vnodes(void);
308
309 static void
panic_display_tpidrs(void)310 panic_display_tpidrs(void)
311 {
312 #if defined(__arm64__)
313 paniclog_append_noflush("TPIDRx_ELy = {1: 0x%016llx 0: 0x%016llx 0ro: 0x%016llx }\n",
314 __builtin_arm_rsr64("TPIDR_EL1"), __builtin_arm_rsr64("TPIDR_EL0"),
315 __builtin_arm_rsr64("TPIDRRO_EL0"));
316 #endif //defined(__arm64__)
317 }
318
319 static void
panic_display_hung_cpus_help(void)320 panic_display_hung_cpus_help(void)
321 {
322 #if defined(__arm64__)
323 const uint32_t pcsr_offset = 0x90;
324
325 /*
326 * Print some info that might help in cases where nothing
327 * else does
328 */
329 const ml_topology_info_t *info = ml_get_topology_info();
330 if (info) {
331 unsigned i, retry;
332
333 for (i = 0; i < info->num_cpus; i++) {
334 if (info->cpus[i].cpu_UTTDBG_regs) {
335 volatile uint64_t *pcsr = (volatile uint64_t*)(info->cpus[i].cpu_UTTDBG_regs + pcsr_offset);
336 volatile uint32_t *pcsrTrigger = (volatile uint32_t*)pcsr;
337 uint64_t pc = 0;
338
339 // a number of retries are needed till this works
340 for (retry = 1024; retry && !pc; retry--) {
341 //a 32-bit read is required to make a PC sample be produced, else we'll only get a zero
342 (void)*pcsrTrigger;
343 pc = *pcsr;
344 }
345
346 //postprocessing (same as astris does)
347 if (pc >> 48) {
348 pc |= 0xffff000000000000ull;
349 }
350 paniclog_append_noflush("CORE %u recently retired instr at 0x%016llx\n", i, pc);
351 }
352 }
353 }
354 #endif //defined(__arm64__)
355 }
356
357
358 static void
panic_display_pvhs_locked(void)359 panic_display_pvhs_locked(void)
360 {
361 }
362
363 static void
panic_display_pvh_to_lock(void)364 panic_display_pvh_to_lock(void)
365 {
366 }
367
368 static void
panic_display_last_pc_lr(void)369 panic_display_last_pc_lr(void)
370 {
371 #if defined(__arm64__)
372 const int max_cpu = ml_get_max_cpu_number();
373
374 for (int cpu = 0; cpu <= max_cpu; cpu++) {
375 cpu_data_t *current_cpu_datap = cpu_datap(cpu);
376
377 if (current_cpu_datap == NULL) {
378 continue;
379 }
380
381 if (current_cpu_datap == getCpuDatap()) {
382 /**
383 * Skip printing the PC/LR if this is the CPU
384 * that initiated the panic.
385 */
386 paniclog_append_noflush("CORE %u is the one that panicked. Check the full backtrace for details.\n", cpu);
387 continue;
388 }
389
390 paniclog_append_noflush("CORE %u: PC=0x%016llx, LR=0x%016llx, FP=0x%016llx\n", cpu,
391 current_cpu_datap->ipi_pc, (uint64_t)VM_KERNEL_STRIP_PTR(current_cpu_datap->ipi_lr),
392 (uint64_t)VM_KERNEL_STRIP_PTR(current_cpu_datap->ipi_fp));
393 }
394 #endif
395 }
396
397 static void
do_print_all_backtraces(const char * message,uint64_t panic_options)398 do_print_all_backtraces(const char *message, uint64_t panic_options)
399 {
400 int logversion = PANICLOG_VERSION;
401 thread_t cur_thread = current_thread();
402 uintptr_t cur_fp;
403 task_t task;
404 struct proc *proc;
405 int print_vnodes = 0;
406 const char *nohilite_thread_marker = "\t";
407
408 /* end_marker_bytes set to 200 for printing END marker + stackshot summary info always */
409 int bytes_traced = 0, bytes_remaining = 0, end_marker_bytes = 200;
410 int bytes_uncompressed = 0;
411 uint64_t bytes_used = 0ULL;
412 int err = 0;
413 char *stackshot_begin_loc = NULL;
414 kc_format_t kc_format;
415 bool filesetKC = false;
416 #if CONFIG_EXT_PANICLOG
417 uint32_t ext_paniclog_bytes = 0;
418 #endif
419
420 #if defined(__arm64__)
421 __asm__ volatile ("add %0, xzr, fp":"=r"(cur_fp));
422 #else
423 #error Unknown architecture.
424 #endif
425 if (panic_bt_depth != 0) {
426 return;
427 }
428 panic_bt_depth++;
429
430 __unused bool result = PE_get_primary_kc_format(&kc_format);
431 assert(result == true);
432 filesetKC = kc_format == KCFormatFileset;
433
434 /* Truncate panic string to 1200 bytes */
435 paniclog_append_noflush("Debugger message: %.1200s\n", message);
436 if (debug_enabled) {
437 paniclog_append_noflush("Device: %s\n",
438 ('\0' != gTargetTypeBuffer[0]) ? gTargetTypeBuffer : "Not set yet");
439 paniclog_append_noflush("Hardware Model: %s\n",
440 ('\0' != gModelTypeBuffer[0]) ? gModelTypeBuffer:"Not set yet");
441 paniclog_append_noflush("ECID: %02X%02X%02X%02X%02X%02X%02X%02X\n", gPlatformECID[7],
442 gPlatformECID[6], gPlatformECID[5], gPlatformECID[4], gPlatformECID[3],
443 gPlatformECID[2], gPlatformECID[1], gPlatformECID[0]);
444 if (last_hwaccess_thread) {
445 paniclog_append_noflush("AppleHWAccess Thread: 0x%llx\n", last_hwaccess_thread);
446 }
447 paniclog_append_noflush("Boot args: %s\n", PE_boot_args());
448 }
449 paniclog_append_noflush("Memory ID: 0x%x\n", gPlatformMemoryID);
450 paniclog_append_noflush("OS release type: %.256s\n",
451 ('\0' != osreleasetype[0]) ? osreleasetype : "Not set yet");
452 paniclog_append_noflush("OS version: %.256s\n",
453 ('\0' != osversion[0]) ? osversion : "Not set yet");
454 #if defined(XNU_TARGET_OS_BRIDGE)
455 paniclog_append_noflush("macOS version: %.256s\n",
456 ('\0' != macosversion[0]) ? macosversion : "Not set");
457 #endif
458 paniclog_append_noflush("Kernel version: %.512s\n", version);
459
460 if (kernelcache_uuid_valid) {
461 if (filesetKC) {
462 paniclog_append_noflush("Fileset Kernelcache UUID: ");
463 } else {
464 paniclog_append_noflush("KernelCache UUID: ");
465 }
466 for (size_t index = 0; index < sizeof(uuid_t); index++) {
467 paniclog_append_noflush("%02X", kernelcache_uuid[index]);
468 }
469 paniclog_append_noflush("\n");
470 }
471 panic_display_kernel_uuid();
472
473 if (bootsessionuuid_string[0] != '\0') {
474 paniclog_append_noflush("Boot session UUID: %s\n", bootsessionuuid_string);
475 } else {
476 paniclog_append_noflush("Boot session UUID not yet initialized\n");
477 }
478
479 paniclog_append_noflush("iBoot version: %.128s\n", iBoot_version);
480 #if defined(TARGET_OS_OSX) && defined(__arm64__)
481 paniclog_append_noflush("iBoot Stage 2 version: %.128s\n", iBoot_Stage_2_version);
482 #endif /* defined(TARGET_OS_OSX) && defined(__arm64__) */
483
484 paniclog_append_noflush("secure boot?: %s\n", debug_enabled ? "NO": "YES");
485 paniclog_append_noflush("roots installed: %lld\n", roots_installed);
486 #if defined(XNU_TARGET_OS_BRIDGE)
487 paniclog_append_noflush("x86 EFI Boot State: ");
488 if (PE_smc_stashed_x86_efi_boot_state != 0xFF) {
489 paniclog_append_noflush("0x%x\n", PE_smc_stashed_x86_efi_boot_state);
490 } else {
491 paniclog_append_noflush("not available\n");
492 }
493 paniclog_append_noflush("x86 System State: ");
494 if (PE_smc_stashed_x86_system_state != 0xFF) {
495 paniclog_append_noflush("0x%x\n", PE_smc_stashed_x86_system_state);
496 } else {
497 paniclog_append_noflush("not available\n");
498 }
499 paniclog_append_noflush("x86 Power State: ");
500 if (PE_smc_stashed_x86_power_state != 0xFF) {
501 paniclog_append_noflush("0x%x\n", PE_smc_stashed_x86_power_state);
502 } else {
503 paniclog_append_noflush("not available\n");
504 }
505 paniclog_append_noflush("x86 Shutdown Cause: ");
506 if (PE_smc_stashed_x86_shutdown_cause != 0xFF) {
507 paniclog_append_noflush("0x%x\n", PE_smc_stashed_x86_shutdown_cause);
508 } else {
509 paniclog_append_noflush("not available\n");
510 }
511 paniclog_append_noflush("x86 Previous Power Transitions: ");
512 if (PE_smc_stashed_x86_prev_power_transitions != UINT64_MAX) {
513 paniclog_append_noflush("0x%llx\n", PE_smc_stashed_x86_prev_power_transitions);
514 } else {
515 paniclog_append_noflush("not available\n");
516 }
517 paniclog_append_noflush("PCIeUp link state: ");
518 if (PE_pcie_stashed_link_state != UINT32_MAX) {
519 paniclog_append_noflush("0x%x\n", PE_pcie_stashed_link_state);
520 } else {
521 paniclog_append_noflush("not available\n");
522 }
523 paniclog_append_noflush("macOS kernel slide: ");
524 if (PE_nvram_stashed_x86_macos_slide != UINT64_MAX) {
525 paniclog_append_noflush("%#llx\n", PE_nvram_stashed_x86_macos_slide);
526 } else {
527 paniclog_append_noflush("not available\n");
528 }
529 #endif
530 if (panic_data_buffers != NULL) {
531 paniclog_append_noflush("%s data: ", panic_data_buffers->producer_name);
532 uint8_t *panic_buffer_data = (uint8_t *) panic_data_buffers->buf;
533 for (int i = 0; i < panic_data_buffers->len; i++) {
534 paniclog_append_noflush("%02X", panic_buffer_data[i]);
535 }
536 paniclog_append_noflush("\n");
537 }
538 paniclog_append_noflush("Paniclog version: %d\n", logversion);
539
540 panic_display_kernel_aslr();
541 panic_display_times();
542 panic_display_zalloc();
543 panic_display_hung_cpus_help();
544 panic_display_tpidrs();
545 panic_display_pvhs_locked();
546 panic_display_pvh_to_lock();
547 panic_display_last_pc_lr();
548 #if CONFIG_ECC_LOGGING
549 panic_display_ecc_errors();
550 #endif /* CONFIG_ECC_LOGGING */
551 panic_display_compressor_stats();
552
553 #if DEVELOPMENT || DEBUG
554 if (cs_debug_unsigned_exec_failures != 0 || cs_debug_unsigned_mmap_failures != 0) {
555 paniclog_append_noflush("Unsigned code exec failures: %u\n", cs_debug_unsigned_exec_failures);
556 paniclog_append_noflush("Unsigned code mmap failures: %u\n", cs_debug_unsigned_mmap_failures);
557 }
558 #endif
559
560 // Highlight threads that used high amounts of CPU in the panic log if requested (historically requested for watchdog panics)
561 if (panic_options & DEBUGGER_OPTION_PRINT_CPU_USAGE_PANICLOG) {
562 thread_t top_runnable[5] = {0};
563 thread_t thread;
564 int total_cpu_usage = 0;
565
566 print_vnodes = 1;
567
568
569 for (thread = (thread_t)queue_first(&threads);
570 PANIC_VALIDATE_PTR(thread) && !queue_end(&threads, (queue_entry_t)thread);
571 thread = (thread_t)queue_next(&thread->threads)) {
572 total_cpu_usage += thread->cpu_usage;
573
574 // Look for the 5 runnable threads with highest priority
575 if (thread->state & TH_RUN) {
576 int k;
577 thread_t comparison_thread = thread;
578
579 for (k = 0; k < TOP_RUNNABLE_LIMIT; k++) {
580 if (top_runnable[k] == 0) {
581 top_runnable[k] = comparison_thread;
582 break;
583 } else if (comparison_thread->sched_pri > top_runnable[k]->sched_pri) {
584 thread_t temp = top_runnable[k];
585 top_runnable[k] = comparison_thread;
586 comparison_thread = temp;
587 } // if comparison thread has higher priority than previously saved thread
588 } // loop through highest priority runnable threads
589 } // Check if thread is runnable
590 } // Loop through all threads
591
592 // Print the relevant info for each thread identified
593 paniclog_append_noflush("Total cpu_usage: %d\n", total_cpu_usage);
594 paniclog_append_noflush("Thread task pri cpu_usage\n");
595
596 for (int i = 0; i < TOP_RUNNABLE_LIMIT; i++) {
597 if (top_runnable[i] &&
598 panic_get_thread_proc_task(top_runnable[i], &task, &proc) && proc) {
599 char name[MAXCOMLEN + 1];
600 proc_name_kdp(proc, name, sizeof(name));
601 paniclog_append_noflush("%p %s %d %d\n",
602 top_runnable[i], name, top_runnable[i]->sched_pri, top_runnable[i]->cpu_usage);
603 }
604 } // Loop through highest priority runnable threads
605 paniclog_append_noflush("\n");
606 }
607
608 // print current task info
609 if (panic_get_thread_proc_task(cur_thread, &task, &proc)) {
610 if (PANIC_VALIDATE_PTR(task->map) &&
611 PANIC_VALIDATE_PTR(task->map->pmap)) {
612 ledger_amount_t resident = 0;
613 if (task != kernel_task) {
614 ledger_get_balance(task->ledger, task_ledgers.phys_mem, &resident);
615 resident >>= VM_MAP_PAGE_SHIFT(task->map);
616 }
617 paniclog_append_noflush("Panicked task %p: %lld pages, %d threads: ",
618 task, resident, task->thread_count);
619 } else {
620 paniclog_append_noflush("Panicked task %p: %d threads: ",
621 task, task->thread_count);
622 }
623
624 if (proc) {
625 char name[MAXCOMLEN + 1];
626 proc_name_kdp(proc, name, sizeof(name));
627 paniclog_append_noflush("pid %d: %s", proc_pid(proc), name);
628 } else {
629 paniclog_append_noflush("unknown task");
630 }
631
632 paniclog_append_noflush("\n");
633 }
634
635 if (cur_fp < VM_MAX_KERNEL_ADDRESS) {
636 paniclog_append_noflush("Panicked thread: %p, backtrace: 0x%llx, tid: %llu\n",
637 cur_thread, (addr64_t)cur_fp, thread_tid(cur_thread));
638 #if __LP64__
639 print_one_backtrace(kernel_pmap, cur_fp, nohilite_thread_marker, TRUE, filesetKC);
640 #else
641 print_one_backtrace(kernel_pmap, cur_fp, nohilite_thread_marker, FALSE, filesetKC);
642 #endif
643 } else {
644 paniclog_append_noflush("Could not print panicked thread backtrace:"
645 "frame pointer outside kernel vm.\n");
646 }
647
648 paniclog_append_noflush("\n");
649 if (filesetKC) {
650 kext_dump_panic_lists(&paniclog_append_noflush);
651 paniclog_append_noflush("\n");
652 }
653 panic_info->eph_panic_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->eph_panic_log_offset;
654 /* set the os version data in the panic header in the format 'Product Version (OS Version)' (only if they have been set) */
655 if ((osversion[0] != '\0') && (osproductversion[0] != '\0')) {
656 snprintf((char *)&panic_info->eph_os_version, sizeof(panic_info->eph_os_version), PANIC_HEADER_VERSION_FMT_STR,
657 osproductversion, osversion);
658 }
659 #if defined(XNU_TARGET_OS_BRIDGE)
660 if ((macosversion[0] != '\0') && (macosproductversion[0] != '\0')) {
661 snprintf((char *)&panic_info->eph_macos_version, sizeof(panic_info->eph_macos_version), PANIC_HEADER_VERSION_FMT_STR,
662 macosproductversion, macosversion);
663 }
664 #endif
665 if (bootsessionuuid_string[0] != '\0') {
666 memcpy(panic_info->eph_bootsessionuuid_string, bootsessionuuid_string,
667 sizeof(panic_info->eph_bootsessionuuid_string));
668 }
669 panic_info->eph_roots_installed = roots_installed;
670
671 if (debug_ack_timeout_count) {
672 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_FAILED_DEBUGGERSYNC;
673 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
674 paniclog_append_noflush("!! debugger synchronization failed, no stackshot !!\n");
675 } else if (stackshot_active()) {
676 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_FAILED_NESTED;
677 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
678 paniclog_append_noflush("!! panicked during stackshot, skipping panic stackshot !!\n");
679 } else {
680 /* Align the stackshot buffer to an 8-byte address (especially important for armv7k devices) */
681 debug_buf_ptr += (8 - ((uintptr_t)debug_buf_ptr % 8));
682 stackshot_begin_loc = debug_buf_ptr;
683
684 bytes_remaining = debug_buf_size - (unsigned int)((uintptr_t)stackshot_begin_loc - (uintptr_t)debug_buf_base);
685 err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)debug_buf_ptr,
686 KCDATA_BUFFER_BEGIN_COMPRESSED, bytes_remaining - end_marker_bytes,
687 KCFLAG_USE_MEMCOPY);
688 if (err == KERN_SUCCESS) {
689 uint64_t stackshot_flags = (STACKSHOT_GET_GLOBAL_MEM_STATS | STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT |
690 STACKSHOT_ENABLE_BT_FAULTING | STACKSHOT_ENABLE_UUID_FAULTING | STACKSHOT_FROM_PANIC | STACKSHOT_DO_COMPRESS |
691 STACKSHOT_DISABLE_LATENCY_INFO | STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_GET_DQ |
692 STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT);
693
694 err = kcdata_init_compress(&kc_panic_data, KCDATA_BUFFER_BEGIN_STACKSHOT, kdp_memcpy, KCDCT_ZLIB);
695 if (err != KERN_SUCCESS) {
696 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_COMPRESS_FAILED;
697 stackshot_flags &= ~STACKSHOT_DO_COMPRESS;
698 }
699 if (filesetKC) {
700 stackshot_flags |= STACKSHOT_SAVE_KEXT_LOADINFO;
701 }
702
703 kdp_snapshot_preflight(-1, stackshot_begin_loc, bytes_remaining - end_marker_bytes,
704 stackshot_flags, &kc_panic_data, 0, 0);
705 err = do_stackshot(NULL);
706 bytes_traced = kdp_stack_snapshot_bytes_traced();
707 if (bytes_traced > 0 && !err) {
708 debug_buf_ptr += bytes_traced;
709 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_SUCCEEDED;
710 panic_info->eph_stackshot_offset = PE_get_offset_into_panic_region(stackshot_begin_loc);
711 panic_info->eph_stackshot_len = bytes_traced;
712
713 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
714 if (stackshot_flags & STACKSHOT_DO_COMPRESS) {
715 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_DATA_COMPRESSED;
716 bytes_uncompressed = kdp_stack_snapshot_bytes_uncompressed();
717 paniclog_append_noflush("\n** Stackshot Succeeded ** Bytes Traced %d (Uncompressed %d) **\n", bytes_traced, bytes_uncompressed);
718 } else {
719 paniclog_append_noflush("\n** Stackshot Succeeded ** Bytes Traced %d **\n", bytes_traced);
720 }
721 } else {
722 bytes_used = kcdata_memory_get_used_bytes(&kc_panic_data);
723 if (bytes_used > 0) {
724 /* Zero out the stackshot data */
725 bzero(stackshot_begin_loc, bytes_used);
726 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_FAILED_INCOMPLETE;
727
728 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
729 paniclog_append_noflush("\n** Stackshot Incomplete ** Bytes Filled %llu **\n", bytes_used);
730 } else {
731 bzero(stackshot_begin_loc, bytes_used);
732 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
733
734 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
735 paniclog_append_noflush("\n!! Stackshot Failed !! Bytes Traced %d, err %d\n", bytes_traced, err);
736 }
737 }
738 } else {
739 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
740 panic_info->eph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
741 paniclog_append_noflush("\n!! Stackshot Failed !!\nkcdata_memory_static_init returned %d", err);
742 }
743 }
744
745 #if CONFIG_EXT_PANICLOG
746 // Write ext paniclog at the end of the paniclog region.
747 ext_paniclog_bytes = ext_paniclog_write_panicdata();
748 panic_info->eph_ext_paniclog_offset = (ext_paniclog_bytes != 0) ?
749 PE_get_offset_into_panic_region((debug_buf_base + debug_buf_size) - ext_paniclog_bytes) :
750 0;
751 panic_info->eph_ext_paniclog_len = ext_paniclog_bytes;
752 #endif
753
754 assert(panic_info->eph_other_log_offset != 0);
755
756 if (print_vnodes != 0) {
757 panic_print_vnodes();
758 }
759
760 panic_bt_depth--;
761 }
762
763 /*
764 * Entry to print_all_backtraces is serialized by the debugger lock
765 */
766 static void
print_all_backtraces(const char * message,uint64_t panic_options)767 print_all_backtraces(const char *message, uint64_t panic_options)
768 {
769 unsigned int initial_not_in_kdp = not_in_kdp;
770
771 cpu_data_t * cpu_data_ptr = getCpuDatap();
772
773 assert(cpu_data_ptr->PAB_active == FALSE);
774 cpu_data_ptr->PAB_active = TRUE;
775
776 /*
777 * Because print all backtraces uses the pmap routines, it needs to
778 * avoid taking pmap locks. Right now, this is conditionalized on
779 * not_in_kdp.
780 */
781 not_in_kdp = 0;
782 do_print_all_backtraces(message, panic_options);
783
784 not_in_kdp = initial_not_in_kdp;
785
786 cpu_data_ptr->PAB_active = FALSE;
787 }
788
789 void
panic_display_times()790 panic_display_times()
791 {
792 if (kdp_clock_is_locked()) {
793 paniclog_append_noflush("Warning: clock is locked. Can't get time\n");
794 return;
795 }
796
797 extern lck_ticket_t clock_lock;
798 extern lck_grp_t clock_lock_grp;
799
800 if ((is_clock_configured) && (lck_ticket_lock_try(&clock_lock, &clock_lock_grp))) {
801 clock_sec_t secs, boot_secs;
802 clock_usec_t usecs, boot_usecs;
803
804 lck_ticket_unlock(&clock_lock);
805
806 clock_get_calendar_microtime(&secs, &usecs);
807 clock_get_boottime_microtime(&boot_secs, &boot_usecs);
808
809 paniclog_append_noflush("mach_absolute_time: 0x%llx\n", mach_absolute_time());
810 paniclog_append_noflush("Epoch Time: sec usec\n");
811 paniclog_append_noflush(" Boot : 0x%08x 0x%08x\n", (unsigned int)boot_secs, (unsigned int)boot_usecs);
812 paniclog_append_noflush(" Sleep : 0x%08x 0x%08x\n", (unsigned int)gIOLastSleepTime.tv_sec, (unsigned int)gIOLastSleepTime.tv_usec);
813 paniclog_append_noflush(" Wake : 0x%08x 0x%08x\n", (unsigned int)gIOLastWakeTime.tv_sec, (unsigned int)gIOLastWakeTime.tv_usec);
814 paniclog_append_noflush(" Calendar: 0x%08x 0x%08x\n\n", (unsigned int)secs, (unsigned int)usecs);
815 }
816 }
817
818 void
panic_print_symbol_name(vm_address_t search)819 panic_print_symbol_name(vm_address_t search)
820 {
821 #pragma unused(search)
822 // empty stub. Really only used on x86_64.
823 return;
824 }
825
826 void
SavePanicInfo(const char * message,__unused void * panic_data,uint64_t panic_options)827 SavePanicInfo(
828 const char *message, __unused void *panic_data, uint64_t panic_options)
829 {
830 /*
831 * This should be initialized by the time we get here, but
832 * if it is not, asserting about it will be of no use (it will
833 * come right back to here), so just loop right here and now.
834 * This prevents early-boot panics from becoming recursive and
835 * thus makes them easier to debug. If you attached to a device
836 * and see your PC here, look down a few frames to see your
837 * early-boot panic there.
838 */
839 while (!panic_info || panic_info->eph_panic_log_offset == 0) {
840 // rdar://87170225 (PanicHardening: audit panic code for naked spinloops)
841 // rdar://88094367 (Add test hooks for panic at different stages in XNU)
842 ;
843 }
844
845 if (panic_options & DEBUGGER_OPTION_PANICLOGANDREBOOT) {
846 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_BUTTON_RESET_PANIC;
847 }
848
849 if (panic_options & DEBUGGER_OPTION_COPROC_INITIATED_PANIC) {
850 panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_COPROC_INITIATED_PANIC;
851 }
852
853 #if defined(XNU_TARGET_OS_BRIDGE)
854 panic_info->eph_x86_power_state = PE_smc_stashed_x86_power_state;
855 panic_info->eph_x86_efi_boot_state = PE_smc_stashed_x86_efi_boot_state;
856 panic_info->eph_x86_system_state = PE_smc_stashed_x86_system_state;
857 #endif
858
859 /*
860 * On newer targets, panic data is stored directly into the iBoot panic region.
861 * If we re-enter SavePanicInfo (e.g. on a double panic) on such a target, update the
862 * panic CRC so that iBoot can hopefully find *something* useful in the panic region.
863 */
864 if (PanicInfoSaved && (debug_buf_base >= (char*)gPanicBase) && (debug_buf_base < (char*)gPanicBase + gPanicSize)) {
865 unsigned int pi_size = (unsigned int)(debug_buf_ptr - gPanicBase);
866 PE_update_panic_crc((unsigned char*)gPanicBase, &pi_size);
867 PE_sync_panic_buffers(); // extra precaution; panic path likely isn't reliable if we're here
868 }
869
870 if (PanicInfoSaved || (debug_buf_size == 0)) {
871 return;
872 }
873
874 PanicInfoSaved = TRUE;
875
876
877 print_all_backtraces(message, panic_options);
878
879 assert(panic_info->eph_panic_log_len != 0);
880 panic_info->eph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->eph_other_log_offset;
881
882 PEHaltRestart(kPEPanicSync);
883
884 /*
885 * Notifies registered IOPlatformPanicAction callbacks
886 * (which includes one to disable the memcache) and flushes
887 * the buffer contents from the cache
888 */
889 paniclog_flush();
890 }
891
892 void
paniclog_flush()893 paniclog_flush()
894 {
895 unsigned int panicbuf_length = 0;
896
897 panicbuf_length = (unsigned int)(debug_buf_ptr - gPanicBase);
898 if (!debug_buf_ptr || !panicbuf_length) {
899 return;
900 }
901
902 /*
903 * Updates the log length of the last part of the panic log.
904 */
905 panic_info->eph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->eph_other_log_offset;
906
907 /*
908 * Updates the metadata at the beginning of the panic buffer,
909 * updates the CRC.
910 */
911 PE_update_panic_crc((unsigned char *)gPanicBase, &panicbuf_length);
912
913 /*
914 * This is currently unused by platform KEXTs on embedded but is
915 * kept for compatibility with the published IOKit interfaces.
916 */
917 PESavePanicInfo((unsigned char *)gPanicBase, panicbuf_length);
918
919 PE_sync_panic_buffers();
920 }
921
922 /*
923 * @function DebuggerXCallEnter
924 *
925 * @abstract IPI other cores so this core can run in a single-threaded context.
926 *
927 * @discussion This function should be called with the debugger lock held. It
928 * signals the other cores to go into a busy loop so this core can run in a
929 * single-threaded context and inspect kernel memory.
930 *
931 * @param proceed_on_sync_failure If true, then go ahead and try to debug even
932 * if we can't synch with the other cores. This is inherently unsafe and should
933 * only be used if the kernel is going down in flames anyway.
934 *
935 * @param is_stackshot If true, this is a stackshot request.
936 *
937 * @result returns KERN_OPERATION_TIMED_OUT if synchronization times out and
938 * proceed_on_sync_failure is false.
939 */
940 kern_return_t
DebuggerXCallEnter(boolean_t proceed_on_sync_failure,bool is_stackshot)941 DebuggerXCallEnter(
942 boolean_t proceed_on_sync_failure, bool is_stackshot)
943 {
944 uint64_t max_mabs_time, current_mabs_time;
945 int cpu;
946 int max_cpu;
947 cpu_data_t *target_cpu_datap;
948 cpu_data_t *cpu_data_ptr = getCpuDatap();
949
950 /* Check for nested debugger entry. */
951 cpu_data_ptr->debugger_active++;
952 if (cpu_data_ptr->debugger_active != 1) {
953 return KERN_SUCCESS;
954 }
955
956 /*
957 * If debugger_sync is not 0, someone responded excessively late to the last
958 * debug request (we zero the sync variable in the return function). Zero it
959 * again here. This should prevent us from getting out of sync (heh) and
960 * timing out on every entry to the debugger if we timeout once.
961 */
962
963 debugger_sync = 0;
964 mp_kdp_trap = 1;
965 debug_cpus_spinning = 0;
966
967 #pragma unused(is_stackshot)
968
969 /*
970 * Try to signal all CPUs (except ourselves, of course). Use debugger_sync to
971 * synchronize with every CPU that we appeared to signal successfully (cpu_signal
972 * is not synchronous).
973 */
974 max_cpu = ml_get_max_cpu_number();
975
976 boolean_t immediate_halt = FALSE;
977 if (proceed_on_sync_failure && force_immediate_debug_halt) {
978 immediate_halt = TRUE;
979 }
980
981 if (!immediate_halt) {
982 for (cpu = 0; cpu <= max_cpu; cpu++) {
983 target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
984
985 if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
986 continue;
987 }
988
989 kern_return_t ret = cpu_signal(target_cpu_datap, SIGPdebug, (void *)NULL, NULL);
990 if (ret == KERN_SUCCESS) {
991 os_atomic_inc(&debugger_sync, relaxed);
992 os_atomic_inc(&debug_cpus_spinning, relaxed);
993 } else if (proceed_on_sync_failure) {
994 kprintf("cpu_signal failed in DebuggerXCallEnter\n");
995 }
996 }
997
998 max_mabs_time = os_atomic_load(&debug_ack_timeout, relaxed);
999
1000 if (max_mabs_time > 0) {
1001 current_mabs_time = mach_absolute_time();
1002 max_mabs_time += current_mabs_time;
1003 assert(max_mabs_time > current_mabs_time);
1004 }
1005
1006 /*
1007 * Wait for DEBUG_ACK_TIMEOUT ns for a response from everyone we IPI'd. If we
1008 * timeout, that is simply too bad; we don't have a true NMI, and one CPU may be
1009 * uninterruptibly spinning on someone else. The best we can hope for is that
1010 * all other CPUs have either responded or are spinning in a context that is
1011 * debugger safe.
1012 */
1013 while ((debugger_sync != 0) && (max_mabs_time == 0 || current_mabs_time < max_mabs_time)) {
1014 current_mabs_time = mach_absolute_time();
1015 }
1016 }
1017
1018 if (!proceed_on_sync_failure && (max_mabs_time > 0 && current_mabs_time >= max_mabs_time)) {
1019 __builtin_arm_dmb(DMB_ISH);
1020 for (cpu = 0; cpu <= max_cpu; cpu++) {
1021 target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
1022
1023 if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
1024 continue;
1025 }
1026 if (!(target_cpu_datap->cpu_signal & SIGPdebug)) {
1027 continue;
1028 }
1029 if (processor_array[cpu]->state <= PROCESSOR_PENDING_OFFLINE) {
1030 /*
1031 * This is a processor that was successfully sent a SIGPdebug signal
1032 * but which hasn't acknowledged it because it went offline with
1033 * interrupts disabled before the IPI was delivered, so count it
1034 * here.
1035 */
1036 os_atomic_dec(&debugger_sync, relaxed);
1037 kprintf("%s>found CPU %d offline, debugger_sync=%d\n", __FUNCTION__, cpu, debugger_sync);
1038 continue;
1039 }
1040
1041 kprintf("%s>Debugger synch pending on cpu %d\n", __FUNCTION__, cpu);
1042 }
1043
1044 if (debugger_sync == 0) {
1045 return KERN_SUCCESS;
1046 } else {
1047 DebuggerXCallReturn();
1048 kprintf("%s>returning KERN_OPERATION_TIMED_OUT\n", __FUNCTION__);
1049 return KERN_OPERATION_TIMED_OUT;
1050 }
1051 } else if (immediate_halt || (max_mabs_time > 0 && current_mabs_time >= max_mabs_time)) {
1052 /*
1053 * For the moment, we're aiming for a timeout that the user shouldn't notice,
1054 * but will be sufficient to let the other core respond.
1055 */
1056 __builtin_arm_dmb(DMB_ISH);
1057 for (cpu = 0; cpu <= max_cpu; cpu++) {
1058 target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
1059
1060 if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
1061 continue;
1062 }
1063 if (!(target_cpu_datap->cpu_signal & SIGPdebug) && !immediate_halt) {
1064 continue;
1065 }
1066 if (proceed_on_sync_failure) {
1067 paniclog_append_noflush("Attempting to forcibly halt cpu %d\n", cpu);
1068 dbgwrap_status_t halt_status = ml_dbgwrap_halt_cpu(cpu, 0);
1069 if (halt_status < 0) {
1070 paniclog_append_noflush("cpu %d failed to halt with error %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1071 } else {
1072 if (halt_status > 0) {
1073 paniclog_append_noflush("cpu %d halted with warning %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1074 }
1075 target_cpu_datap->halt_status = CPU_HALTED;
1076 }
1077 } else {
1078 kprintf("Debugger synch pending on cpu %d\n", cpu);
1079 }
1080 }
1081 if (proceed_on_sync_failure) {
1082 for (cpu = 0; cpu <= max_cpu; cpu++) {
1083 target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
1084
1085 if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr) ||
1086 (target_cpu_datap->halt_status == CPU_NOT_HALTED)) {
1087 continue;
1088 }
1089 dbgwrap_status_t halt_status = ml_dbgwrap_halt_cpu_with_state(cpu,
1090 NSEC_PER_SEC, &target_cpu_datap->halt_state);
1091 if ((halt_status < 0) || (halt_status == DBGWRAP_WARN_CPU_OFFLINE)) {
1092 paniclog_append_noflush("Unable to obtain state for cpu %d with status %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1093 } else {
1094 paniclog_append_noflush("cpu %d successfully halted\n", cpu);
1095 target_cpu_datap->halt_status = CPU_HALTED_WITH_STATE;
1096 }
1097 }
1098 if (immediate_halt) {
1099 paniclog_append_noflush("Immediate halt requested on all cores\n");
1100 } else {
1101 paniclog_append_noflush("Debugger synchronization timed out; waited %llu nanoseconds\n",
1102 os_atomic_load(&debug_ack_timeout, relaxed));
1103 }
1104 debug_ack_timeout_count++;
1105 return KERN_SUCCESS;
1106 } else {
1107 DebuggerXCallReturn();
1108 return KERN_OPERATION_TIMED_OUT;
1109 }
1110 } else {
1111 return KERN_SUCCESS;
1112 }
1113 }
1114
1115 /*
1116 * @function DebuggerXCallReturn
1117 *
1118 * @abstract Resume normal multicore operation after DebuggerXCallEnter()
1119 *
1120 * @discussion This function should be called with debugger lock held.
1121 */
1122 void
DebuggerXCallReturn(void)1123 DebuggerXCallReturn(
1124 void)
1125 {
1126 cpu_data_t *cpu_data_ptr = getCpuDatap();
1127 uint64_t max_mabs_time, current_mabs_time;
1128
1129 cpu_data_ptr->debugger_active--;
1130 if (cpu_data_ptr->debugger_active != 0) {
1131 return;
1132 }
1133
1134 mp_kdp_trap = 0;
1135 debugger_sync = 0;
1136
1137 max_mabs_time = os_atomic_load(&debug_ack_timeout, relaxed);
1138
1139 if (max_mabs_time > 0) {
1140 current_mabs_time = mach_absolute_time();
1141 max_mabs_time += current_mabs_time;
1142 assert(max_mabs_time > current_mabs_time);
1143 }
1144
1145 /*
1146 * Wait for other CPUs to stop spinning on mp_kdp_trap (see DebuggerXCall).
1147 * It's possible for one or more CPUs to not decrement debug_cpus_spinning,
1148 * since they may be stuck somewhere else with interrupts disabled.
1149 * Wait for DEBUG_ACK_TIMEOUT ns for a response and move on if we don't get it.
1150 *
1151 * Note that the same is done in DebuggerXCallEnter, when we wait for other
1152 * CPUS to update debugger_sync. If we time out, let's hope for all CPUs to be
1153 * spinning in a debugger-safe context
1154 */
1155 while ((os_atomic_load_exclusive(&debug_cpus_spinning, relaxed) != 0) &&
1156 (max_mabs_time == 0 || current_mabs_time < max_mabs_time)) {
1157 __builtin_arm_wfe();
1158 current_mabs_time = mach_absolute_time();
1159 }
1160 os_atomic_clear_exclusive();
1161 }
1162
1163 extern void wait_while_mp_kdp_trap(bool check_SIGPdebug);
1164 /*
1165 * Spin while mp_kdp_trap is set.
1166 *
1167 * processor_offline() calls this with check_SIGPdebug=true
1168 * to break out of the spin loop if the cpu has SIGPdebug
1169 * pending.
1170 */
1171 void
wait_while_mp_kdp_trap(bool check_SIGPdebug)1172 wait_while_mp_kdp_trap(bool check_SIGPdebug)
1173 {
1174 bool found_mp_kdp_trap = false;
1175 bool found_SIGPdebug = false;
1176
1177 while (os_atomic_load_exclusive(&mp_kdp_trap, relaxed) != 0) {
1178 found_mp_kdp_trap = true;
1179 if (check_SIGPdebug && cpu_has_SIGPdebug_pending()) {
1180 found_SIGPdebug = true;
1181 break;
1182 }
1183 __builtin_arm_wfe();
1184 }
1185 os_atomic_clear_exclusive();
1186
1187 if (check_SIGPdebug && found_mp_kdp_trap) {
1188 kprintf("%s>found_mp_kdp_trap=true found_SIGPdebug=%s\n", __FUNCTION__, found_SIGPdebug ? "true" : "false");
1189 }
1190 }
1191
1192 void
DebuggerXCall(void * ctx)1193 DebuggerXCall(
1194 void *ctx)
1195 {
1196 boolean_t save_context = FALSE;
1197 vm_offset_t kstackptr = 0;
1198 arm_saved_state_t *regs = (arm_saved_state_t *) ctx;
1199
1200 if (regs != NULL) {
1201 #if defined(__arm64__)
1202 current_cpu_datap()->ipi_pc = (uint64_t)get_saved_state_pc(regs);
1203 current_cpu_datap()->ipi_lr = (uint64_t)get_saved_state_lr(regs);
1204 current_cpu_datap()->ipi_fp = (uint64_t)get_saved_state_fp(regs);
1205 save_context = PSR64_IS_KERNEL(get_saved_state_cpsr(regs));
1206 #endif
1207 }
1208
1209 kstackptr = (vm_offset_t)current_thread()->machine.kstackptr;
1210
1211 #if defined(__arm64__)
1212 arm_kernel_saved_state_t *state = (arm_kernel_saved_state_t *)kstackptr;
1213
1214 if (save_context) {
1215 /* Save the interrupted context before acknowledging the signal */
1216 current_thread()->machine.kpcb = regs;
1217 } else if (regs) {
1218 /* zero old state so machine_trace_thread knows not to backtrace it */
1219 state->fp = 0;
1220 state->pc_was_in_userspace = true;
1221 state->lr = 0;
1222 state->sp = 0;
1223 state->ssbs = 0;
1224 state->uao = 0;
1225 state->dit = 0;
1226 }
1227 #endif
1228
1229 /*
1230 * When running in serial mode, the core capturing the dump may hold interrupts disabled
1231 * for a time longer than the timeout. That path includes logic to reset the timestamp
1232 * so that we do not eventually trigger the interrupt timeout assert().
1233 *
1234 * Here we check whether other cores have already gone over the timeout at this point
1235 * before spinning, so we at least cover the IPI reception path. After spinning, however,
1236 * we reset the timestamp so as to avoid hitting the interrupt timeout assert().
1237 */
1238 if ((serialmode & SERIALMODE_OUTPUT) || stackshot_active()) {
1239 INTERRUPT_MASKED_DEBUG_END();
1240 }
1241
1242 os_atomic_dec(&debugger_sync, relaxed);
1243
1244
1245 wait_while_mp_kdp_trap(false);
1246
1247 /**
1248 * Alert the triggering CPU that this CPU is done spinning. The CPU that
1249 * signalled all of the other CPUs will wait (in DebuggerXCallReturn) for
1250 * all of the CPUs to exit the above loop before continuing.
1251 */
1252 os_atomic_dec(&debug_cpus_spinning, relaxed);
1253
1254 #if SCHED_HYGIENE_DEBUG
1255 /*
1256 * We also abandon the measurement for preemption disable
1257 * timeouts, if any. Normally, time in interrupt handlers would be
1258 * subtracted from preemption disable time, and this will happen
1259 * up to this point here, but since we here "end" the interrupt
1260 * handler prematurely (from the point of view of interrupt masked
1261 * debugging), the time spinning would otherwise still be
1262 * attributed to preemption disable time, and potentially trigger
1263 * an event, which could be a panic.
1264 */
1265 abandon_preemption_disable_measurement();
1266 #endif /* SCHED_HYGIENE_DEBUG */
1267
1268 if ((serialmode & SERIALMODE_OUTPUT) || stackshot_active()) {
1269 INTERRUPT_MASKED_DEBUG_START(current_thread()->machine.int_handler_addr, current_thread()->machine.int_type);
1270 }
1271
1272 #if defined(__arm64__)
1273 current_thread()->machine.kpcb = NULL;
1274 #endif /* defined(__arm64__) */
1275
1276 /* Any cleanup for our pushed context should go here */
1277 }
1278
1279 void
DebuggerCall(unsigned int reason,void * ctx)1280 DebuggerCall(
1281 unsigned int reason,
1282 void *ctx)
1283 {
1284 #if !MACH_KDP
1285 #pragma unused(reason,ctx)
1286 #endif /* !MACH_KDP */
1287
1288 #if ALTERNATE_DEBUGGER
1289 alternate_debugger_enter();
1290 #endif
1291
1292 #if MACH_KDP
1293 kdp_trap(reason, (struct arm_saved_state *)ctx);
1294 #else
1295 /* TODO: decide what to do if no debugger config */
1296 #endif
1297 }
1298
1299 boolean_t
bootloader_valid_page(ppnum_t ppn)1300 bootloader_valid_page(ppnum_t ppn)
1301 {
1302 return pmap_bootloader_page(ppn);
1303 }
1304