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