xref: /xnu-8792.81.2/osfmk/arm/model_dep.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
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 
776 	if ((is_clock_configured) && (lck_ticket_lock_try(&clock_lock, LCK_GRP_NULL))) {
777 		clock_sec_t     secs, boot_secs;
778 		clock_usec_t    usecs, boot_usecs;
779 
780 		lck_ticket_unlock(&clock_lock);
781 
782 		clock_get_calendar_microtime(&secs, &usecs);
783 		clock_get_boottime_microtime(&boot_secs, &boot_usecs);
784 
785 		paniclog_append_noflush("mach_absolute_time: 0x%llx\n", mach_absolute_time());
786 		paniclog_append_noflush("Epoch Time:        sec       usec\n");
787 		paniclog_append_noflush("  Boot    : 0x%08x 0x%08x\n", (unsigned int)boot_secs, (unsigned int)boot_usecs);
788 		paniclog_append_noflush("  Sleep   : 0x%08x 0x%08x\n", (unsigned int)gIOLastSleepTime.tv_sec, (unsigned int)gIOLastSleepTime.tv_usec);
789 		paniclog_append_noflush("  Wake    : 0x%08x 0x%08x\n", (unsigned int)gIOLastWakeTime.tv_sec, (unsigned int)gIOLastWakeTime.tv_usec);
790 		paniclog_append_noflush("  Calendar: 0x%08x 0x%08x\n\n", (unsigned int)secs, (unsigned int)usecs);
791 	}
792 }
793 
794 void
panic_print_symbol_name(vm_address_t search)795 panic_print_symbol_name(vm_address_t search)
796 {
797 #pragma unused(search)
798 	// empty stub. Really only used on x86_64.
799 	return;
800 }
801 
802 void
SavePanicInfo(const char * message,__unused void * panic_data,uint64_t panic_options)803 SavePanicInfo(
804 	const char *message, __unused void *panic_data, uint64_t panic_options)
805 {
806 	/*
807 	 * This should be initialized by the time we get here, but
808 	 * if it is not, asserting about it will be of no use (it will
809 	 * come right back to here), so just loop right here and now.
810 	 * This prevents early-boot panics from becoming recursive and
811 	 * thus makes them easier to debug. If you attached to a device
812 	 * and see your PC here, look down a few frames to see your
813 	 * early-boot panic there.
814 	 */
815 	while (!panic_info || panic_info->eph_panic_log_offset == 0) {
816 		// rdar://87170225 (PanicHardening: audit panic code for naked spinloops)
817 		// rdar://88094367 (Add test hooks for panic at different stages in XNU)
818 		;
819 	}
820 
821 	if (panic_options & DEBUGGER_OPTION_PANICLOGANDREBOOT) {
822 		panic_info->eph_panic_flags  |= EMBEDDED_PANIC_HEADER_FLAG_BUTTON_RESET_PANIC;
823 	}
824 
825 	if (panic_options & DEBUGGER_OPTION_COPROC_INITIATED_PANIC) {
826 		panic_info->eph_panic_flags |= EMBEDDED_PANIC_HEADER_FLAG_COPROC_INITIATED_PANIC;
827 	}
828 
829 #if defined(XNU_TARGET_OS_BRIDGE)
830 	panic_info->eph_x86_power_state = PE_smc_stashed_x86_power_state;
831 	panic_info->eph_x86_efi_boot_state = PE_smc_stashed_x86_efi_boot_state;
832 	panic_info->eph_x86_system_state = PE_smc_stashed_x86_system_state;
833 #endif
834 
835 	/*
836 	 * On newer targets, panic data is stored directly into the iBoot panic region.
837 	 * If we re-enter SavePanicInfo (e.g. on a double panic) on such a target, update the
838 	 * panic CRC so that iBoot can hopefully find *something* useful in the panic region.
839 	 */
840 	if (PanicInfoSaved && (debug_buf_base >= (char*)gPanicBase) && (debug_buf_base < (char*)gPanicBase + gPanicSize)) {
841 		unsigned int pi_size = (unsigned int)(debug_buf_ptr - gPanicBase);
842 		PE_update_panic_crc((unsigned char*)gPanicBase, &pi_size);
843 		PE_sync_panic_buffers(); // extra precaution; panic path likely isn't reliable if we're here
844 	}
845 
846 	if (PanicInfoSaved || (debug_buf_size == 0)) {
847 		return;
848 	}
849 
850 	PanicInfoSaved = TRUE;
851 
852 	print_all_backtraces(message, panic_options);
853 
854 	assert(panic_info->eph_panic_log_len != 0);
855 	panic_info->eph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->eph_other_log_offset;
856 
857 	PEHaltRestart(kPEPanicSync);
858 
859 	/*
860 	 * Notifies registered IOPlatformPanicAction callbacks
861 	 * (which includes one to disable the memcache) and flushes
862 	 * the buffer contents from the cache
863 	 */
864 	paniclog_flush();
865 }
866 
867 void
paniclog_flush()868 paniclog_flush()
869 {
870 	unsigned int panicbuf_length = 0;
871 
872 	panicbuf_length = (unsigned int)(debug_buf_ptr - gPanicBase);
873 	if (!panicbuf_length) {
874 		return;
875 	}
876 
877 	/*
878 	 * Updates the log length of the last part of the panic log.
879 	 */
880 	panic_info->eph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->eph_other_log_offset;
881 
882 	/*
883 	 * Updates the metadata at the beginning of the panic buffer,
884 	 * updates the CRC.
885 	 */
886 	PE_update_panic_crc((unsigned char *)gPanicBase, &panicbuf_length);
887 
888 	/*
889 	 * This is currently unused by platform KEXTs on embedded but is
890 	 * kept for compatibility with the published IOKit interfaces.
891 	 */
892 	PESavePanicInfo((unsigned char *)gPanicBase, panicbuf_length);
893 
894 	PE_sync_panic_buffers();
895 }
896 
897 /*
898  * @function DebuggerXCallEnter
899  *
900  * @abstract IPI other cores so this core can run in a single-threaded context.
901  *
902  * @discussion This function should be called with the debugger lock held.  It
903  * signals the other cores to go into a busy loop so this core can run in a
904  * single-threaded context and inspect kernel memory.
905  *
906  * @param proceed_on_sync_failure If true, then go ahead and try to debug even
907  * if we can't synch with the other cores.  This is inherently unsafe and should
908  * only be used if the kernel is going down in flames anyway.
909  *
910  * @param is_stackshot If true, this is a stackshot request.
911  *
912  * @result returns KERN_OPERATION_TIMED_OUT if synchronization times out and
913  * proceed_on_sync_failure is false.
914  */
915 kern_return_t
DebuggerXCallEnter(boolean_t proceed_on_sync_failure,bool is_stackshot)916 DebuggerXCallEnter(
917 	boolean_t proceed_on_sync_failure, bool is_stackshot)
918 {
919 	uint64_t max_mabs_time, current_mabs_time;
920 	int cpu;
921 	int max_cpu;
922 	cpu_data_t      *target_cpu_datap;
923 	cpu_data_t      *cpu_data_ptr = getCpuDatap();
924 
925 	/* Check for nested debugger entry. */
926 	cpu_data_ptr->debugger_active++;
927 	if (cpu_data_ptr->debugger_active != 1) {
928 		return KERN_SUCCESS;
929 	}
930 
931 	/*
932 	 * If debugger_sync is not 0, someone responded excessively late to the last
933 	 * debug request (we zero the sync variable in the return function).  Zero it
934 	 * again here.  This should prevent us from getting out of sync (heh) and
935 	 * timing out on every entry to the debugger if we timeout once.
936 	 */
937 
938 	debugger_sync = 0;
939 	mp_kdp_trap = 1;
940 	debug_cpus_spinning = 0;
941 
942 #pragma unused(is_stackshot)
943 
944 	/*
945 	 * Try to signal all CPUs (except ourselves, of course).  Use debugger_sync to
946 	 * synchronize with every CPU that we appeared to signal successfully (cpu_signal
947 	 * is not synchronous).
948 	 */
949 	max_cpu = ml_get_max_cpu_number();
950 
951 	boolean_t immediate_halt = FALSE;
952 	if (proceed_on_sync_failure && force_immediate_debug_halt) {
953 		immediate_halt = TRUE;
954 	}
955 
956 	if (!immediate_halt) {
957 		for (cpu = 0; cpu <= max_cpu; cpu++) {
958 			target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
959 
960 			if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
961 				continue;
962 			}
963 
964 			kern_return_t ret = cpu_signal(target_cpu_datap, SIGPdebug, (void *)NULL, NULL);
965 			if (ret == KERN_SUCCESS) {
966 				os_atomic_inc(&debugger_sync, relaxed);
967 				os_atomic_inc(&debug_cpus_spinning, relaxed);
968 			} else if (proceed_on_sync_failure) {
969 				kprintf("cpu_signal failed in DebuggerXCallEnter\n");
970 			}
971 		}
972 
973 		max_mabs_time = os_atomic_load(&debug_ack_timeout, relaxed);
974 
975 		if (max_mabs_time > 0) {
976 			current_mabs_time = mach_absolute_time();
977 			max_mabs_time += current_mabs_time;
978 			assert(max_mabs_time > current_mabs_time);
979 		}
980 
981 		/*
982 		 * Wait for DEBUG_ACK_TIMEOUT ns for a response from everyone we IPI'd.  If we
983 		 * timeout, that is simply too bad; we don't have a true NMI, and one CPU may be
984 		 * uninterruptibly spinning on someone else.  The best we can hope for is that
985 		 * all other CPUs have either responded or are spinning in a context that is
986 		 * debugger safe.
987 		 */
988 		while ((debugger_sync != 0) && (max_mabs_time == 0 || current_mabs_time < max_mabs_time)) {
989 			current_mabs_time = mach_absolute_time();
990 		}
991 	}
992 
993 	if (!proceed_on_sync_failure && (max_mabs_time > 0 && current_mabs_time >= max_mabs_time)) {
994 		__builtin_arm_dmb(DMB_ISH);
995 		for (cpu = 0; cpu <= max_cpu; cpu++) {
996 			target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
997 
998 			if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
999 				continue;
1000 			}
1001 			if (!(target_cpu_datap->cpu_signal & SIGPdebug)) {
1002 				continue;
1003 			}
1004 			if (processor_array[cpu]->state <= PROCESSOR_PENDING_OFFLINE) {
1005 				/*
1006 				 * This is a processor that was successfully sent a SIGPdebug signal
1007 				 * but which hasn't acknowledged it because it went offline with
1008 				 * interrupts disabled before the IPI was delivered, so count it
1009 				 * here.
1010 				 */
1011 				os_atomic_dec(&debugger_sync, relaxed);
1012 				kprintf("%s>found CPU %d offline, debugger_sync=%d\n", __FUNCTION__, cpu, debugger_sync);
1013 				continue;
1014 			}
1015 
1016 			kprintf("%s>Debugger synch pending on cpu %d\n", __FUNCTION__, cpu);
1017 		}
1018 
1019 		if (debugger_sync == 0) {
1020 			return KERN_SUCCESS;
1021 		} else {
1022 			DebuggerXCallReturn();
1023 			kprintf("%s>returning KERN_OPERATION_TIMED_OUT\n", __FUNCTION__);
1024 			return KERN_OPERATION_TIMED_OUT;
1025 		}
1026 	} else if (immediate_halt || (max_mabs_time > 0 && current_mabs_time >= max_mabs_time)) {
1027 		/*
1028 		 * For the moment, we're aiming for a timeout that the user shouldn't notice,
1029 		 * but will be sufficient to let the other core respond.
1030 		 */
1031 		__builtin_arm_dmb(DMB_ISH);
1032 		for (cpu = 0; cpu <= max_cpu; cpu++) {
1033 			target_cpu_datap = (cpu_data_t *)CpuDataEntries[cpu].cpu_data_vaddr;
1034 
1035 			if ((target_cpu_datap == NULL) || (target_cpu_datap == cpu_data_ptr)) {
1036 				continue;
1037 			}
1038 			if (!(target_cpu_datap->cpu_signal & SIGPdebug) && !immediate_halt) {
1039 				continue;
1040 			}
1041 			if (proceed_on_sync_failure) {
1042 				paniclog_append_noflush("Attempting to forcibly halt cpu %d\n", cpu);
1043 				dbgwrap_status_t halt_status = ml_dbgwrap_halt_cpu(cpu, 0);
1044 				if (halt_status < 0) {
1045 					paniclog_append_noflush("cpu %d failed to halt with error %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1046 				} else {
1047 					if (halt_status > 0) {
1048 						paniclog_append_noflush("cpu %d halted with warning %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1049 					}
1050 					target_cpu_datap->halt_status = CPU_HALTED;
1051 				}
1052 			} else {
1053 				kprintf("Debugger synch pending on cpu %d\n", cpu);
1054 			}
1055 		}
1056 		if (proceed_on_sync_failure) {
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 				    (target_cpu_datap->halt_status == CPU_NOT_HALTED)) {
1062 					continue;
1063 				}
1064 				dbgwrap_status_t halt_status = ml_dbgwrap_halt_cpu_with_state(cpu,
1065 				    NSEC_PER_SEC, &target_cpu_datap->halt_state);
1066 				if ((halt_status < 0) || (halt_status == DBGWRAP_WARN_CPU_OFFLINE)) {
1067 					paniclog_append_noflush("Unable to obtain state for cpu %d with status %d: %s\n", cpu, halt_status, ml_dbgwrap_strerror(halt_status));
1068 				} else {
1069 					paniclog_append_noflush("cpu %d successfully halted\n", cpu);
1070 					target_cpu_datap->halt_status = CPU_HALTED_WITH_STATE;
1071 				}
1072 			}
1073 			if (immediate_halt) {
1074 				paniclog_append_noflush("Immediate halt requested on all cores\n");
1075 			} else {
1076 				paniclog_append_noflush("Debugger synchronization timed out; waited %llu nanoseconds\n",
1077 				    os_atomic_load(&debug_ack_timeout, relaxed));
1078 			}
1079 			debug_ack_timeout_count++;
1080 			return KERN_SUCCESS;
1081 		} else {
1082 			DebuggerXCallReturn();
1083 			return KERN_OPERATION_TIMED_OUT;
1084 		}
1085 	} else {
1086 		return KERN_SUCCESS;
1087 	}
1088 }
1089 
1090 /*
1091  * @function DebuggerXCallReturn
1092  *
1093  * @abstract Resume normal multicore operation after DebuggerXCallEnter()
1094  *
1095  * @discussion This function should be called with debugger lock held.
1096  */
1097 void
DebuggerXCallReturn(void)1098 DebuggerXCallReturn(
1099 	void)
1100 {
1101 	cpu_data_t      *cpu_data_ptr = getCpuDatap();
1102 	uint64_t max_mabs_time, current_mabs_time;
1103 
1104 	cpu_data_ptr->debugger_active--;
1105 	if (cpu_data_ptr->debugger_active != 0) {
1106 		return;
1107 	}
1108 
1109 	mp_kdp_trap = 0;
1110 	debugger_sync = 0;
1111 
1112 	max_mabs_time = os_atomic_load(&debug_ack_timeout, relaxed);
1113 
1114 	if (max_mabs_time > 0) {
1115 		current_mabs_time = mach_absolute_time();
1116 		max_mabs_time += current_mabs_time;
1117 		assert(max_mabs_time > current_mabs_time);
1118 	}
1119 
1120 	/*
1121 	 * Wait for other CPUs to stop spinning on mp_kdp_trap (see DebuggerXCall).
1122 	 * It's possible for one or more CPUs to not decrement debug_cpus_spinning,
1123 	 * since they may be stuck somewhere else with interrupts disabled.
1124 	 * Wait for DEBUG_ACK_TIMEOUT ns for a response and move on if we don't get it.
1125 	 *
1126 	 * Note that the same is done in DebuggerXCallEnter, when we wait for other
1127 	 * CPUS to update debugger_sync. If we time out, let's hope for all CPUs to be
1128 	 * spinning in a debugger-safe context
1129 	 */
1130 	while ((os_atomic_load_exclusive(&debug_cpus_spinning, relaxed) != 0) &&
1131 	    (max_mabs_time == 0 || current_mabs_time < max_mabs_time)) {
1132 		__builtin_arm_wfe();
1133 		current_mabs_time = mach_absolute_time();
1134 	}
1135 	os_atomic_clear_exclusive();
1136 }
1137 
1138 extern void wait_while_mp_kdp_trap(bool check_SIGPdebug);
1139 /*
1140  * Spin while mp_kdp_trap is set.
1141  *
1142  * processor_offline() calls this with check_SIGPdebug=true
1143  * to break out of the spin loop if the cpu has SIGPdebug
1144  * pending.
1145  */
1146 void
wait_while_mp_kdp_trap(bool check_SIGPdebug)1147 wait_while_mp_kdp_trap(bool check_SIGPdebug)
1148 {
1149 	bool found_mp_kdp_trap = false;
1150 	bool found_SIGPdebug = false;
1151 
1152 	while (os_atomic_load_exclusive(&mp_kdp_trap, relaxed) != 0) {
1153 		found_mp_kdp_trap = true;
1154 		if (check_SIGPdebug && cpu_has_SIGPdebug_pending()) {
1155 			found_SIGPdebug = true;
1156 			break;
1157 		}
1158 		__builtin_arm_wfe();
1159 	}
1160 	os_atomic_clear_exclusive();
1161 
1162 	if (check_SIGPdebug && found_mp_kdp_trap) {
1163 		kprintf("%s>found_mp_kdp_trap=true found_SIGPdebug=%s\n", __FUNCTION__, found_SIGPdebug ? "true" : "false");
1164 	}
1165 }
1166 
1167 void
DebuggerXCall(void * ctx)1168 DebuggerXCall(
1169 	void            *ctx)
1170 {
1171 	boolean_t               save_context = FALSE;
1172 	vm_offset_t             kstackptr = 0;
1173 	arm_saved_state_t       *regs = (arm_saved_state_t *) ctx;
1174 
1175 	if (regs != NULL) {
1176 #if defined(__arm64__)
1177 		current_cpu_datap()->ipi_pc = (uint64_t)get_saved_state_pc(regs);
1178 		current_cpu_datap()->ipi_lr = (uint64_t)get_saved_state_lr(regs);
1179 		current_cpu_datap()->ipi_fp = (uint64_t)get_saved_state_fp(regs);
1180 		save_context = PSR64_IS_KERNEL(get_saved_state_cpsr(regs));
1181 #endif
1182 	}
1183 
1184 	kstackptr = current_thread()->machine.kstackptr;
1185 
1186 #if defined(__arm64__)
1187 	arm_kernel_saved_state_t *state = (arm_kernel_saved_state_t *)kstackptr;
1188 
1189 	if (save_context) {
1190 		/* Save the interrupted context before acknowledging the signal */
1191 		current_thread()->machine.kpcb = regs;
1192 	} else if (regs) {
1193 		/* zero old state so machine_trace_thread knows not to backtrace it */
1194 		state->fp = 0;
1195 		state->pc_was_in_userspace = true;
1196 		state->lr = 0;
1197 		state->sp = 0;
1198 		state->ssbs = 0;
1199 		state->uao = 0;
1200 		state->dit = 0;
1201 	}
1202 #endif
1203 
1204 	/*
1205 	 * When running in serial mode, the core capturing the dump may hold interrupts disabled
1206 	 * for a time longer than the timeout. That path includes logic to reset the timestamp
1207 	 * so that we do not eventually trigger the interrupt timeout assert().
1208 	 *
1209 	 * Here we check whether other cores have already gone over the timeout at this point
1210 	 * before spinning, so we at least cover the IPI reception path. After spinning, however,
1211 	 * we reset the timestamp so as to avoid hitting the interrupt timeout assert().
1212 	 */
1213 	if ((serialmode & SERIALMODE_OUTPUT) || stackshot_active()) {
1214 		INTERRUPT_MASKED_DEBUG_END();
1215 	}
1216 
1217 	os_atomic_dec(&debugger_sync, relaxed);
1218 
1219 
1220 	wait_while_mp_kdp_trap(false);
1221 
1222 	/**
1223 	 * Alert the triggering CPU that this CPU is done spinning. The CPU that
1224 	 * signalled all of the other CPUs will wait (in DebuggerXCallReturn) for
1225 	 * all of the CPUs to exit the above loop before continuing.
1226 	 */
1227 	os_atomic_dec(&debug_cpus_spinning, relaxed);
1228 
1229 #if SCHED_HYGIENE_DEBUG
1230 	/*
1231 	 * We also abandon the measurement for preemption disable
1232 	 * timeouts, if any. Normally, time in interrupt handlers would be
1233 	 * subtracted from preemption disable time, and this will happen
1234 	 * up to this point here, but since we here "end" the interrupt
1235 	 * handler prematurely (from the point of view of interrupt masked
1236 	 * debugging), the time spinning would otherwise still be
1237 	 * attributed to preemption disable time, and potentially trigger
1238 	 * an event, which could be a panic.
1239 	 */
1240 	abandon_preemption_disable_measurement();
1241 #endif /* SCHED_HYGIENE_DEBUG */
1242 
1243 	if ((serialmode & SERIALMODE_OUTPUT) || stackshot_active()) {
1244 		INTERRUPT_MASKED_DEBUG_START(current_thread()->machine.int_handler_addr, current_thread()->machine.int_type);
1245 	}
1246 
1247 #if defined(__arm64__)
1248 	current_thread()->machine.kpcb = NULL;
1249 #endif /* defined(__arm64__) */
1250 
1251 	/* Any cleanup for our pushed context should go here */
1252 }
1253 
1254 void
DebuggerCall(unsigned int reason,void * ctx)1255 DebuggerCall(
1256 	unsigned int    reason,
1257 	void            *ctx)
1258 {
1259 #if     !MACH_KDP
1260 #pragma unused(reason,ctx)
1261 #endif /* !MACH_KDP */
1262 
1263 #if ALTERNATE_DEBUGGER
1264 	alternate_debugger_enter();
1265 #endif
1266 
1267 #if     MACH_KDP
1268 	kdp_trap(reason, (struct arm_saved_state *)ctx);
1269 #else
1270 	/* TODO: decide what to do if no debugger config */
1271 #endif
1272 }
1273 
1274 boolean_t
bootloader_valid_page(ppnum_t ppn)1275 bootloader_valid_page(ppnum_t ppn)
1276 {
1277 	return pmap_bootloader_page(ppn);
1278 }
1279