xref: /xnu-11215.1.10/osfmk/i386/AT386/model_dep.c (revision 8d741a5de7ff4191bf97d57b9f54c2f6d4a15585)
1 /*
2  * Copyright (c) 2000-2019 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * @OSF_COPYRIGHT@
30  */
31 /*
32  * Mach Operating System
33  * Copyright (c) 1991,1990,1989, 1988 Carnegie Mellon University
34  * All Rights Reserved.
35  *
36  * Permission to use, copy, modify and distribute this software and its
37  * documentation is hereby granted, provided that both the copyright
38  * notice and this permission notice appear in all copies of the
39  * software, derivative works or modified versions, and any portions
40  * thereof, and that both notices appear in supporting documentation.
41  *
42  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44  * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45  *
46  * Carnegie Mellon requests users of this software to return to
47  *
48  *  Software Distribution Coordinator  or  [email protected]
49  *  School of Computer Science
50  *  Carnegie Mellon University
51  *  Pittsburgh PA 15213-3890
52  *
53  * any improvements or extensions that they make and grant Carnegie Mellon
54  * the rights to redistribute these changes.
55  */
56 
57 /*
58  */
59 
60 /*
61  *	File:	model_dep.c
62  *	Author:	Avadis Tevanian, Jr., Michael Wayne Young
63  *
64  *	Copyright (C) 1986, Avadis Tevanian, Jr., Michael Wayne Young
65  *
66  *	Basic initialization for I386 - ISA bus machines.
67  */
68 
69 
70 #define __APPLE_API_PRIVATE 1
71 #define __APPLE_API_UNSTABLE 1
72 #include <kern/debug.h>
73 
74 #include <mach/i386/vm_param.h>
75 
76 #include <string.h>
77 #include <mach/vm_param.h>
78 #include <mach/vm_prot.h>
79 #include <mach/machine.h>
80 #include <mach/time_value.h>
81 #include <sys/kdebug.h>
82 #include <sys/time.h>
83 #include <kern/spl.h>
84 #include <kern/assert.h>
85 #include <kern/lock_group.h>
86 #include <kern/misc_protos.h>
87 #include <kern/startup.h>
88 #include <kern/clock.h>
89 #include <kern/cpu_data.h>
90 #include <kern/machine.h>
91 #include <kern/iotrace.h>
92 #include <kern/kern_stackshot.h>
93 #include <i386/postcode.h>
94 #include <i386/mp_desc.h>
95 #include <i386/misc_protos.h>
96 #include <i386/panic_notify.h>
97 #include <i386/thread.h>
98 #include <i386/trap_internal.h>
99 #include <i386/machine_routines.h>
100 #include <i386/mp.h>
101 #include <i386/cpuid.h>
102 #include <i386/fpu.h>
103 #include <i386/machine_cpu.h>
104 #include <i386/pmap.h>
105 #if CONFIG_MTRR
106 #include <i386/mtrr.h>
107 #endif
108 #include <i386/ucode.h>
109 #include <i386/pmCPU.h>
110 #include <i386/panic_hooks.h>
111 #include <i386/lbr.h>
112 
113 #include <architecture/i386/pio.h> /* inb() */
114 #include <pexpert/i386/boot.h>
115 
116 #include <kdp/kdp_dyld.h>
117 #include <kdp/kdp_core.h>
118 #include <kdp/kdp_common.h>
119 #include <vm/pmap.h>
120 #include <vm/vm_map_xnu.h>
121 #include <vm/vm_kern.h>
122 
123 #include <IOKit/IOBSD.h>
124 #include <IOKit/IOPlatformExpert.h>
125 #include <IOKit/IOHibernatePrivate.h>
126 
127 #include <pexpert/i386/efi.h>
128 
129 #include <kern/thread.h>
130 #include <kern/sched.h>
131 #include <mach-o/loader.h>
132 #include <mach-o/nlist.h>
133 
134 #include <libkern/kernel_mach_header.h>
135 #include <libkern/OSKextLibPrivate.h>
136 #include <libkern/crc.h>
137 
138 #if     DEBUG || DEVELOPMENT
139 #define DPRINTF(x ...)   kprintf(x)
140 #else
141 #define DPRINTF(x ...)
142 #endif
143 
144 #ifndef ROUNDUP
145 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
146 #endif
147 
148 #ifndef ROUNDDOWN
149 #define ROUNDDOWN(x, y) (((x)/(y))*(y))
150 #endif
151 
152 static void machine_conf(void);
153 void panic_print_symbol_name(vm_address_t search);
154 void RecordPanicStackshot(void);
155 
156 typedef enum paniclog_flush_type {
157 	kPaniclogFlushBase          = 1,/* Flush the initial log and paniclog header */
158 	kPaniclogFlushStackshot     = 2,/* Flush only the stackshot data, then flush the header */
159 	kPaniclogFlushOtherLog      = 3/* Flush the other log, then flush the header */
160 } paniclog_flush_type_t;
161 
162 void paniclog_flush_internal(paniclog_flush_type_t variant);
163 
164 extern const char       version[];
165 extern char             osversion[];
166 extern int              max_poll_quanta;
167 extern unsigned int     panic_is_inited;
168 
169 extern uint64_t roots_installed;
170 
171 /* #include <sys/proc.h> */
172 #define MAXCOMLEN 16
173 struct proc;
174 extern int              proc_pid(struct proc *p);
175 extern void             proc_name_kdp(struct proc *p, char * buf, int size);
176 
177 
178 /* Definitions for frame pointers */
179 #define FP_ALIGNMENT_MASK      ((uint32_t)(0x3))
180 #define FP_LR_OFFSET           ((uint32_t)4)
181 #define FP_LR_OFFSET64         ((uint32_t)8)
182 #define FP_MAX_NUM_TO_EVALUATE (50)
183 
184 volatile int pbtcpu = -1;
185 hw_lock_data_t pbtlock;         /* backtrace print lock */
186 uint32_t pbtcnt = 0;
187 
188 volatile int panic_double_fault_cpu = -1;
189 
190 #define PRINT_ARGS_FROM_STACK_FRAME     0
191 
192 typedef struct _cframe_t {
193 	struct _cframe_t    *prev;
194 	uintptr_t           caller;
195 #if PRINT_ARGS_FROM_STACK_FRAME
196 	unsigned            args[0];
197 #endif
198 } cframe_t;
199 
200 static unsigned commit_paniclog_to_nvram;
201 boolean_t coprocessor_paniclog_flush = FALSE;
202 
203 struct kcdata_descriptor kc_panic_data;
204 static boolean_t begun_panic_stackshot = FALSE;
205 
206 vm_offset_t panic_stackshot_buf = 0;
207 size_t panic_stackshot_buf_len = 0;
208 
209 size_t panic_stackshot_len = 0;
210 
211 boolean_t is_clock_configured = FALSE;
212 
213 static struct lbr_data lbrs[MAX_CPUS];
214 static uint32_t lbr_stack_size;
215 
216 /*
217  * Backtrace a single frame.
218  */
219 void
print_one_backtrace(pmap_t pmap,vm_offset_t topfp,const char * cur_marker,boolean_t is_64_bit)220 print_one_backtrace(pmap_t pmap, vm_offset_t topfp, const char *cur_marker,
221     boolean_t is_64_bit)
222 {
223 	unsigned int    i = 0;
224 	addr64_t        lr = 0;
225 	addr64_t        fp = topfp;
226 	addr64_t        fp_for_ppn = 0;
227 	ppnum_t         ppn = (ppnum_t)NULL;
228 	bool            dump_kernel_stack = (fp >= VM_MIN_KERNEL_ADDRESS);
229 
230 	do {
231 		if ((fp == 0) || ((fp & FP_ALIGNMENT_MASK) != 0)) {
232 			break;
233 		}
234 		if (dump_kernel_stack && ((fp < VM_MIN_KERNEL_ADDRESS) || (fp > VM_MAX_KERNEL_ADDRESS))) {
235 			break;
236 		}
237 		if ((!dump_kernel_stack) && (fp >= VM_MIN_KERNEL_ADDRESS)) {
238 			break;
239 		}
240 
241 		/* Check to see if current address will result in a different
242 		 *  ppn than previously computed (to avoid recomputation) via
243 		 *  (addr) ^ fp_for_ppn) >> PAGE_SHIFT) */
244 
245 		if ((((fp + FP_LR_OFFSET) ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
246 			ppn = pmap_find_phys(pmap, fp + FP_LR_OFFSET);
247 			fp_for_ppn = fp + (is_64_bit ? FP_LR_OFFSET64 : FP_LR_OFFSET);
248 		}
249 		if (ppn != (ppnum_t)NULL) {
250 			if (is_64_bit) {
251 				lr = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET64) & PAGE_MASK));
252 			} else {
253 				lr = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET) & PAGE_MASK));
254 			}
255 		} else {
256 			if (is_64_bit) {
257 				paniclog_append_noflush("%s\t  Could not read LR from frame at 0x%016llx\n", cur_marker, fp + FP_LR_OFFSET64);
258 			} else {
259 				paniclog_append_noflush("%s\t  Could not read LR from frame at 0x%08x\n", cur_marker, (uint32_t)(fp + FP_LR_OFFSET));
260 			}
261 			break;
262 		}
263 		if (((fp ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
264 			ppn = pmap_find_phys(pmap, fp);
265 			fp_for_ppn = fp;
266 		}
267 		if (ppn != (ppnum_t)NULL) {
268 			if (is_64_bit) {
269 				fp = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
270 			} else {
271 				fp = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
272 			}
273 		} else {
274 			if (is_64_bit) {
275 				paniclog_append_noflush("%s\t  Could not read FP from frame at 0x%016llx\n", cur_marker, fp);
276 			} else {
277 				paniclog_append_noflush("%s\t  Could not read FP from frame at 0x%08x\n", cur_marker, (uint32_t)fp);
278 			}
279 			break;
280 		}
281 		/*
282 		 * Counter 'i' may == FP_MAX_NUM_TO_EVALUATE when running one
283 		 * extra round to check whether we have all frames in order to
284 		 * indicate (in)complete backtrace below. This happens in a case
285 		 * where total frame count and FP_MAX_NUM_TO_EVALUATE are equal.
286 		 * Do not capture anything.
287 		 */
288 		if (i < FP_MAX_NUM_TO_EVALUATE && lr) {
289 			if (is_64_bit) {
290 				paniclog_append_noflush("%s\t0x%016llx\n", cur_marker, lr);
291 			} else {
292 				paniclog_append_noflush("%s\t0x%08x\n", cur_marker, (uint32_t)lr);
293 			}
294 		}
295 	} while ((++i <= FP_MAX_NUM_TO_EVALUATE) && (fp != topfp));
296 
297 	if (i > FP_MAX_NUM_TO_EVALUATE && fp != 0) {
298 		paniclog_append_noflush("Backtrace continues...\n");
299 	}
300 }
301 void
machine_startup(void)302 machine_startup(void)
303 {
304 	int     boot_arg;
305 
306 #if 0
307 	if (PE_get_hotkey( kPEControlKey )) {
308 		halt_in_debugger = halt_in_debugger ? 0 : 1;
309 	}
310 #endif
311 
312 	if (!PE_parse_boot_argn("nvram_paniclog", &commit_paniclog_to_nvram, sizeof(commit_paniclog_to_nvram))) {
313 		commit_paniclog_to_nvram = 1;
314 	}
315 
316 	/*
317 	 * Entering the debugger will put the CPUs into a "safe"
318 	 * power mode.
319 	 */
320 	if (PE_parse_boot_argn("pmsafe_debug", &boot_arg, sizeof(boot_arg))) {
321 		pmsafe_debug = boot_arg;
322 	}
323 
324 	hw_lock_init(&pbtlock);         /* initialize print backtrace lock */
325 
326 	if (PE_parse_boot_argn("yield", &boot_arg, sizeof(boot_arg))) {
327 		sched_poll_yield_shift = boot_arg;
328 	}
329 
330 	panic_notify_init();
331 
332 	machine_conf();
333 
334 	panic_hooks_init();
335 
336 	/*
337 	 * Start the system.
338 	 */
339 	kernel_bootstrap();
340 	/*NOTREACHED*/
341 }
342 
343 
344 static void
machine_conf(void)345 machine_conf(void)
346 {
347 	machine_info.memory_size = (typeof(machine_info.memory_size))mem_size;
348 }
349 
350 extern void *gPEEFIRuntimeServices;
351 extern void *gPEEFISystemTable;
352 
353 static void
efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)354 efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)
355 {
356 	EFI_RUNTIME_SERVICES_64 *runtime;
357 	uint32_t hdr_cksum;
358 	uint32_t cksum;
359 
360 	DPRINTF("Processing 64-bit EFI tables at %p\n", system_table);
361 	do {
362 		DPRINTF("Header:\n");
363 		DPRINTF("  Signature:   0x%016llx\n", system_table->Hdr.Signature);
364 		DPRINTF("  Revision:    0x%08x\n", system_table->Hdr.Revision);
365 		DPRINTF("  HeaderSize:  0x%08x\n", system_table->Hdr.HeaderSize);
366 		DPRINTF("  CRC32:       0x%08x\n", system_table->Hdr.CRC32);
367 		DPRINTF("RuntimeServices: 0x%016llx\n", system_table->RuntimeServices);
368 		if (system_table->Hdr.Signature != EFI_SYSTEM_TABLE_SIGNATURE) {
369 			kprintf("Bad EFI system table signature\n");
370 			break;
371 		}
372 		// Verify signature of the system table
373 		hdr_cksum = system_table->Hdr.CRC32;
374 		system_table->Hdr.CRC32 = 0;
375 		cksum = crc32(0L, system_table, system_table->Hdr.HeaderSize);
376 
377 		DPRINTF("System table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
378 		system_table->Hdr.CRC32 = hdr_cksum;
379 		if (cksum != hdr_cksum) {
380 			kprintf("Bad EFI system table checksum\n");
381 			break;
382 		}
383 
384 		gPEEFISystemTable     = system_table;
385 
386 		if (system_table->RuntimeServices == 0) {
387 			kprintf("No runtime table present\n");
388 			break;
389 		}
390 		DPRINTF("RuntimeServices table at 0x%qx\n", system_table->RuntimeServices);
391 		// 64-bit virtual address is OK for 64-bit EFI and 64/32-bit kernel.
392 		runtime = (EFI_RUNTIME_SERVICES_64 *) (uintptr_t)system_table->RuntimeServices;
393 		DPRINTF("Checking runtime services table %p\n", runtime);
394 		if (runtime->Hdr.Signature != EFI_RUNTIME_SERVICES_SIGNATURE) {
395 			kprintf("Bad EFI runtime table signature\n");
396 			break;
397 		}
398 
399 		// Verify signature of runtime services table
400 		hdr_cksum = runtime->Hdr.CRC32;
401 		runtime->Hdr.CRC32 = 0;
402 		cksum = crc32(0L, runtime, runtime->Hdr.HeaderSize);
403 
404 		DPRINTF("Runtime table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
405 		runtime->Hdr.CRC32 = hdr_cksum;
406 		if (cksum != hdr_cksum) {
407 			kprintf("Bad EFI runtime table checksum\n");
408 			break;
409 		}
410 
411 		gPEEFIRuntimeServices = runtime;
412 	} while (FALSE);
413 }
414 
415 /* Map in EFI runtime areas. */
416 static void
efi_init(void)417 efi_init(void)
418 {
419 	boot_args *args = (boot_args *)PE_state.bootArgs;
420 
421 	kprintf("Initializing EFI runtime services\n");
422 
423 	do {
424 		vm_offset_t vm_size, vm_addr;
425 		vm_map_offset_t phys_addr;
426 		EfiMemoryRange *mptr;
427 		unsigned int msize, mcount;
428 		unsigned int i;
429 
430 		msize = args->MemoryMapDescriptorSize;
431 		mcount = args->MemoryMapSize / msize;
432 
433 		DPRINTF("efi_init() kernel base: 0x%x size: 0x%x\n",
434 		    args->kaddr, args->ksize);
435 		DPRINTF("           efiSystemTable physical: 0x%x virtual: %p\n",
436 		    args->efiSystemTable,
437 		    (void *) ml_static_ptovirt(args->efiSystemTable));
438 		DPRINTF("           efiRuntimeServicesPageStart: 0x%x\n",
439 		    args->efiRuntimeServicesPageStart);
440 		DPRINTF("           efiRuntimeServicesPageCount: 0x%x\n",
441 		    args->efiRuntimeServicesPageCount);
442 		DPRINTF("           efiRuntimeServicesVirtualPageStart: 0x%016llx\n",
443 		    args->efiRuntimeServicesVirtualPageStart);
444 		mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
445 		for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
446 			if (((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME)) {
447 				vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
448 				vm_addr =   (vm_offset_t) mptr->VirtualStart;
449 				/* For K64 on EFI32, shadow-map into high KVA */
450 				if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
451 					vm_addr |= VM_MIN_KERNEL_ADDRESS;
452 				}
453 				phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
454 				DPRINTF(" Type: %x phys: %p EFIv: %p kv: %p size: %p\n",
455 				    mptr->Type,
456 				    (void *) (uintptr_t) phys_addr,
457 				    (void *) (uintptr_t) mptr->VirtualStart,
458 				    (void *) vm_addr,
459 				    (void *) vm_size);
460 				pmap_map_bd(vm_addr, phys_addr, phys_addr + round_page(vm_size),
461 				    (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
462 				    (mptr->Type == EfiMemoryMappedIO)       ? VM_WIMG_IO   : VM_WIMG_USE_DEFAULT);
463 			}
464 		}
465 
466 		if (args->Version != kBootArgsVersion2) {
467 			panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
468 		}
469 
470 		DPRINTF("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
471 		if (args->efiMode == kBootArgsEfiMode64) {
472 			efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
473 		} else {
474 			panic("Unsupported 32-bit EFI system table!");
475 		}
476 	} while (FALSE);
477 
478 	return;
479 }
480 
481 /* Returns TRUE if a page belongs to the EFI Runtime Services (code or data) */
482 boolean_t
bootloader_valid_page(ppnum_t ppn)483 bootloader_valid_page(ppnum_t ppn)
484 {
485 	boot_args *args = (boot_args *)PE_state.bootArgs;
486 	ppnum_t    pstart = args->efiRuntimeServicesPageStart;
487 	ppnum_t    pend = pstart + args->efiRuntimeServicesPageCount;
488 
489 	return pstart <= ppn && ppn < pend;
490 }
491 
492 /* Remap EFI runtime areas. */
493 void
hibernate_newruntime_map(void * map,vm_size_t map_size,uint32_t system_table_offset)494 hibernate_newruntime_map(void * map, vm_size_t map_size, uint32_t system_table_offset)
495 {
496 	boot_args *args = (boot_args *)PE_state.bootArgs;
497 
498 	kprintf("Reinitializing EFI runtime services\n");
499 
500 	do {
501 		vm_offset_t vm_size, vm_addr;
502 		vm_map_offset_t phys_addr;
503 		EfiMemoryRange *mptr;
504 		unsigned int msize, mcount;
505 		unsigned int i;
506 
507 		gPEEFISystemTable     = 0;
508 		gPEEFIRuntimeServices = 0;
509 
510 		system_table_offset += ptoa_32(args->efiRuntimeServicesPageStart);
511 
512 		kprintf("Old system table 0x%x, new 0x%x\n",
513 		    (uint32_t)args->efiSystemTable, system_table_offset);
514 
515 		args->efiSystemTable    = system_table_offset;
516 
517 		kprintf("Old map:\n");
518 		msize = args->MemoryMapDescriptorSize;
519 		mcount = args->MemoryMapSize / msize;
520 		mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
521 		for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
522 			if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
523 				vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
524 				vm_addr =   (vm_offset_t) mptr->VirtualStart;
525 				/* K64 on EFI32 */
526 				if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
527 					vm_addr |= VM_MIN_KERNEL_ADDRESS;
528 				}
529 				phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
530 
531 				kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
532 			}
533 		}
534 
535 		pmap_remove(kernel_pmap, i386_ptob(args->efiRuntimeServicesPageStart),
536 		    i386_ptob(args->efiRuntimeServicesPageStart + args->efiRuntimeServicesPageCount));
537 
538 		kprintf("New map:\n");
539 		msize = args->MemoryMapDescriptorSize;
540 		mcount = (unsigned int)(map_size / msize);
541 		mptr = map;
542 		for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
543 			if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
544 				vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
545 				vm_addr =   (vm_offset_t) mptr->VirtualStart;
546 				if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
547 					vm_addr |= VM_MIN_KERNEL_ADDRESS;
548 				}
549 				phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
550 
551 				kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
552 
553 				pmap_map(vm_addr, phys_addr, phys_addr + round_page(vm_size),
554 				    (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
555 				    (mptr->Type == EfiMemoryMappedIO)       ? VM_WIMG_IO   : VM_WIMG_USE_DEFAULT);
556 			}
557 		}
558 
559 		if (args->Version != kBootArgsVersion2) {
560 			panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
561 		}
562 
563 		kprintf("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
564 		if (args->efiMode == kBootArgsEfiMode64) {
565 			efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
566 		} else {
567 			panic("Unsupported 32-bit EFI system table!");
568 		}
569 	} while (FALSE);
570 
571 	kprintf("Done reinitializing EFI runtime services\n");
572 
573 	return;
574 }
575 
576 /*
577  * Find devices.  The system is alive.
578  */
579 void
machine_init(void)580 machine_init(void)
581 {
582 	/* Now with VM up, switch to dynamically allocated cpu data */
583 	cpu_data_realloc();
584 
585 	/* Ensure panic buffer is initialized. */
586 	debug_log_init();
587 
588 	/*
589 	 * Display CPU identification
590 	 */
591 	cpuid_cpu_display("CPU identification");
592 	cpuid_feature_display("CPU features");
593 	cpuid_extfeature_display("CPU extended features");
594 
595 	/*
596 	 * Initialize EFI runtime services.
597 	 */
598 	efi_init();
599 
600 	smp_init();
601 
602 	/*
603 	 * Set up to use floating point.
604 	 */
605 	init_fpu();
606 
607 	/*
608 	 * Configure clock devices.
609 	 */
610 	clock_config();
611 	is_clock_configured = TRUE;
612 
613 #if CONFIG_MTRR
614 	/*
615 	 * Initialize MTRR from boot processor.
616 	 */
617 	mtrr_init();
618 
619 	/*
620 	 * Set up PAT for boot processor.
621 	 */
622 	pat_init();
623 #endif
624 
625 	/*
626 	 * Free lowmem pages and complete other setup
627 	 */
628 	pmap_lowmem_finalize();
629 }
630 
631 /*
632  * Halt a cpu.
633  */
634 void
halt_cpu(void)635 halt_cpu(void)
636 {
637 	halt_all_cpus(FALSE);
638 }
639 
640 int reset_mem_on_reboot = 1;
641 
642 /*
643  * Halt the system or reboot.
644  */
645 __attribute__((noreturn))
646 void
halt_all_cpus(boolean_t reboot)647 halt_all_cpus(boolean_t reboot)
648 {
649 	if (reboot) {
650 		printf("MACH Reboot\n");
651 		PEHaltRestart( kPERestartCPU );
652 	} else {
653 		printf("CPU halted\n");
654 		PEHaltRestart( kPEHaltCPU );
655 	}
656 	while (1) {
657 		;
658 	}
659 }
660 
661 /* For use with the MP rendezvous mechanism
662  */
663 
664 uint64_t panic_restart_timeout = ~(0ULL);
665 
666 #define PANIC_RESTART_TIMEOUT (3ULL * NSEC_PER_SEC)
667 
668 /*
669  * We should always return from this function with the other log offset
670  * set in the panic_info structure.
671  */
672 void
RecordPanicStackshot()673 RecordPanicStackshot()
674 {
675 	int err = 0;
676 	size_t bytes_traced = 0, bytes_uncompressed = 0, bytes_used = 0, bytes_remaining = 0;
677 	char *stackshot_begin_loc = NULL;
678 
679 	/* Don't re-enter this code if we panic here */
680 	if (begun_panic_stackshot) {
681 		if (panic_info->mph_other_log_offset == 0) {
682 			panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
683 		}
684 		return;
685 	}
686 	begun_panic_stackshot = TRUE;
687 
688 	/* The panic log length should have been set before we came to capture a stackshot */
689 	if (panic_info->mph_panic_log_len == 0) {
690 		kdb_printf("Found zero length panic log, skipping capturing panic stackshot\n");
691 		if (panic_info->mph_other_log_offset == 0) {
692 			panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
693 		}
694 		return;
695 	}
696 
697 	if (panic_stackshot_active()) {
698 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_NESTED;
699 		panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
700 		kdb_printf("Panicked during stackshot, skipping panic stackshot\n");
701 		return;
702 	}
703 
704 	/* Try to capture an in memory panic_stackshot */
705 	if (extended_debug_log_enabled) {
706 		/* On coprocessor systems we write this into the extended debug log */
707 		stackshot_begin_loc = debug_buf_ptr;
708 		bytes_remaining = debug_buf_size - (unsigned int)((uintptr_t)stackshot_begin_loc - (uintptr_t)debug_buf_base);
709 	} else if (panic_stackshot_buf != 0) {
710 		/* On other systems we use the panic stackshot_buf */
711 		stackshot_begin_loc = (char *) panic_stackshot_buf;
712 		bytes_remaining = panic_stackshot_buf_len;
713 	} else {
714 		panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
715 		return;
716 	}
717 
718 
719 	err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
720 	    KCDATA_BUFFER_BEGIN_COMPRESSED, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
721 	if (err != KERN_SUCCESS) {
722 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
723 		panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
724 		kdb_printf("Failed to initialize kcdata buffer for in-memory panic stackshot, skipping ...\n");
725 		return;
726 	}
727 
728 	uint64_t stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT |
729 	    STACKSHOT_ENABLE_BT_FAULTING | STACKSHOT_ENABLE_UUID_FAULTING | STACKSHOT_FROM_PANIC | STACKSHOT_DO_COMPRESS |
730 	    STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_DISABLE_LATENCY_INFO | STACKSHOT_GET_DQ);
731 
732 	err = kcdata_init_compress(&kc_panic_data, KCDATA_BUFFER_BEGIN_STACKSHOT, kdp_memcpy, KCDCT_ZLIB);
733 	if (err != KERN_SUCCESS) {
734 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_COMPRESS;
735 		stackshot_flags &= ~STACKSHOT_DO_COMPRESS;
736 	}
737 
738 #if DEVELOPMENT
739 	/*
740 	 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
741 	 * panic stackshots from corefiles.
742 	 */
743 	stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
744 #endif
745 
746 	kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
747 	err = do_panic_stackshot(NULL);
748 	bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
749 	bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
750 	bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
751 
752 	if ((err != KERN_SUCCESS) && (bytes_used > 0)) {
753 		/*
754 		 * We ran out of space while trying to capture a stackshot, try again without user frames.
755 		 * It's not safe to log from here (in case we're writing in the middle of the debug buffer on coprocessor systems)
756 		 * but append a flag to the panic flags.
757 		 */
758 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_KERNEL_ONLY;
759 		panic_stackshot_reset_state();
760 
761 		/* Erase the stackshot data (this region is pre-populated with the NULL character) */
762 		memset(stackshot_begin_loc, '\0', bytes_used);
763 
764 		err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
765 		    KCDATA_BUFFER_BEGIN_STACKSHOT, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
766 		if (err != KERN_SUCCESS) {
767 			panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
768 			panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
769 			kdb_printf("Failed to re-initialize kcdata buffer for kernel only in-memory panic stackshot, skipping ...\n");
770 			return;
771 		}
772 
773 		stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_KCDATA_FORMAT | STACKSHOT_FROM_PANIC | STACKSHOT_DISABLE_LATENCY_INFO |
774 		    STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY | STACKSHOT_GET_DQ);
775 #if DEVELOPMENT
776 		/*
777 		 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
778 		 * panic stackshots from corefiles.
779 		 */
780 		stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
781 #endif
782 
783 		kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
784 		err = do_panic_stackshot(NULL);
785 		bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
786 		bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
787 		bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
788 	}
789 
790 	if (err == KERN_SUCCESS) {
791 		if (extended_debug_log_enabled) {
792 			debug_buf_ptr += bytes_traced;
793 		}
794 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_SUCCEEDED;
795 
796 		/* On other systems this is not in the debug buffer itself, it's in a separate buffer allocated at boot. */
797 		if (extended_debug_log_enabled) {
798 			panic_info->mph_stackshot_offset = PE_get_offset_into_panic_region(stackshot_begin_loc);
799 			panic_info->mph_stackshot_len = (uint32_t) bytes_traced;
800 		} else {
801 			panic_info->mph_stackshot_offset = panic_info->mph_stackshot_len = 0;
802 		}
803 
804 		panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
805 		if (stackshot_flags & STACKSHOT_DO_COMPRESS) {
806 			panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_DATA_COMPRESSED;
807 			kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu (Uncompressed %zu) **\n", bytes_traced, bytes_uncompressed);
808 		} else {
809 			kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu **\n", bytes_traced);
810 		}
811 
812 		/* Used by the code that writes the buffer to disk */
813 		panic_stackshot_buf = (vm_offset_t) stackshot_begin_loc;
814 		panic_stackshot_len = bytes_traced;
815 
816 		if (!extended_debug_log_enabled && (gIOPolledCoreFileMode == kIOPolledCoreFileModeStackshot)) {
817 			/* System configured to write panic stackshot to disk */
818 			kern_dump(KERN_DUMP_STACKSHOT_DISK);
819 		}
820 	} else {
821 		if (bytes_used > 0) {
822 			/* Erase the stackshot data (this region is pre-populated with the NULL character) */
823 			memset(stackshot_begin_loc, '\0', bytes_used);
824 			panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_INCOMPLETE;
825 
826 			panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
827 			kdb_printf("\n** In Memory Panic Stackshot Incomplete ** Bytes Filled %zu ** Err %d\n", bytes_used, err);
828 		} else {
829 			bzero(stackshot_begin_loc, bytes_used);
830 			panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
831 
832 			panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
833 			kdb_printf("\n** In Memory Panic Stackshot Failed ** Bytes Traced %zu, err %d\n", bytes_traced, err);
834 		}
835 	}
836 
837 	return;
838 }
839 
840 void
SavePanicInfo(__unused const char * message,void * panic_data,uint64_t panic_options,__unused const char * panic_initiator)841 SavePanicInfo(
842 	__unused const char *message, void *panic_data, uint64_t panic_options, __unused const char* panic_initiator)
843 {
844 	void *stackptr  = NULL;
845 	thread_t thread_to_trace = (thread_t) panic_data;
846 	cframe_t synthetic_stack_frame = { };
847 	char *debugger_msg = NULL;
848 	int cn = cpu_number();
849 
850 	/*
851 	 * Issue an I/O port read if one has been requested - this is an event logic
852 	 * analyzers can use as a trigger point.
853 	 */
854 	panic_notify();
855 
856 	/* Obtain frame pointer for stack to trace */
857 	if (panic_options & DEBUGGER_INTERNAL_OPTION_THREAD_BACKTRACE) {
858 		if (!mp_kdp_all_cpus_halted()) {
859 			debugger_msg = "Backtracing panicked thread because failed to halt all CPUs\n";
860 		} else if (thread_to_trace == THREAD_NULL) {
861 			debugger_msg = "Backtracing panicked thread because no thread pointer provided\n";
862 		} else if (kvtophys((vm_offset_t)thread_to_trace) == 0ULL) {
863 			debugger_msg = "Backtracing panicked thread because unable to access specified thread\n";
864 		} else if (thread_to_trace->kernel_stack == 0) {
865 			debugger_msg = "Backtracing panicked thread because kernel_stack is NULL for specified thread\n";
866 		} else if (kvtophys(STACK_IKS(thread_to_trace->kernel_stack) == 0ULL)) {
867 			debugger_msg = "Backtracing panicked thread because unable to access kernel_stack for specified thread\n";
868 		} else {
869 			debugger_msg = "Backtracing specified thread\n";
870 			/* We construct a synthetic stack frame so we can include the current instruction pointer */
871 			synthetic_stack_frame.prev = (cframe_t *)STACK_IKS(thread_to_trace->kernel_stack)->k_rbp;
872 			synthetic_stack_frame.caller = (uintptr_t) STACK_IKS(thread_to_trace->kernel_stack)->k_rip;
873 			stackptr = (void *) &synthetic_stack_frame;
874 		}
875 	}
876 
877 	if (stackptr == NULL) {
878 		__asm__ volatile ("movq %%rbp, %0" : "=m" (stackptr));
879 	}
880 
881 	/* Print backtrace - callee is internally synchronized */
882 	if (panic_options & DEBUGGER_OPTION_INITPROC_PANIC) {
883 		/* Special handling of launchd died panics */
884 		print_launchd_info();
885 	} else {
886 		panic_i386_backtrace(stackptr, ((panic_double_fault_cpu == cn) ? 80 : 48), debugger_msg, FALSE, NULL);
887 	}
888 
889 	if (panic_options & DEBUGGER_OPTION_COMPANION_PROC_INITIATED_PANIC) {
890 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_COMPANION_PROC_INITIATED_PANIC;
891 	}
892 
893 	if (panic_options & DEBUGGER_OPTION_INTEGRATED_COPROC_INITIATED_PANIC) {
894 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_INTEGRATED_COPROC_INITIATED_PANIC;
895 	}
896 
897 	if (panic_options & DEBUGGER_OPTION_USERSPACE_INITIATED_PANIC) {
898 		panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_USERSPACE_INITIATED_PANIC;
899 	}
900 
901 #if MACH_KDP
902 	/*
903 	 * If this panic is due to a PTE corruption event, use the kdp cross-cpu calling machinery to ask
904 	 * each CPU to dump their backtraces before proceeding.  This mechanism was preferred to adding new
905 	 * synchronization operations in NMIInterruptHandler and the normal panic flow; this mechanism allows
906 	 * each CPU to add their backtraces after all other primary panic output is complete while not adding
907 	 * additional complexity to the common panic path.
908 	 */
909 	if (NMI_panic_reason == PTE_CORRUPTION) {
910 		for (uint64_t cpu = 0; cpu < real_ncpus; cpu++) {
911 			if (cpu == cpu_number() || !cpu_is_running(cpu)) {
912 				continue;
913 			}
914 			(void) kdp_x86_xcpu_invoke(cpu, NMI_pte_corruption_callback, NULL, NULL, NSEC_PER_SEC /* 1 second timeout */);
915 		}
916 	}
917 #else
918 #error NMI PTE Corruption panic flow requires KDP
919 #endif
920 
921 	if (PE_get_offset_into_panic_region(debug_buf_ptr) < panic_info->mph_panic_log_offset) {
922 		kdb_printf("Invalid panic log offset found (not properly initialized?): debug_buf_ptr : 0x%p, panic_info: 0x%p mph_panic_log_offset: 0x%x\n",
923 		    debug_buf_ptr, panic_info, panic_info->mph_panic_log_offset);
924 		panic_info->mph_panic_log_len = 0;
925 	} else {
926 		panic_info->mph_panic_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_panic_log_offset;
927 	}
928 
929 	/* Flush the panic log */
930 	paniclog_flush_internal(kPaniclogFlushBase);
931 
932 	/* Try to take a panic stackshot */
933 	RecordPanicStackshot();
934 
935 	panic_info->mph_roots_installed = roots_installed;
936 
937 	/*
938 	 * Flush the panic log again with the stackshot or any relevant logging
939 	 * from when we tried to capture it.
940 	 */
941 	paniclog_flush_internal(kPaniclogFlushStackshot);
942 }
943 
944 void
paniclog_flush_internal(paniclog_flush_type_t variant)945 paniclog_flush_internal(paniclog_flush_type_t variant)
946 {
947 	/* Update the other log offset if we've opened the other log */
948 	if (panic_info->mph_other_log_offset != 0) {
949 		panic_info->mph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_other_log_offset;
950 	}
951 
952 	/*
953 	 * If we've detected that we're on a co-processor system, we flush the panic log via the kPEPanicSync
954 	 * panic callbacks, otherwise we flush via nvram (unless that has been disabled).
955 	 */
956 	if (coprocessor_paniclog_flush) {
957 		uint32_t overall_buffer_size = debug_buf_size;
958 		uint32_t size_to_flush = 0, offset_to_flush = 0;
959 		if (extended_debug_log_enabled) {
960 			/*
961 			 * debug_buf_size for the extended log does not include the length of the header.
962 			 * There may be some extra data at the end of the 'basic' log that wouldn't get flushed
963 			 * for the non-extended case (this is a concession we make to not shrink the paniclog data
964 			 * for non-coprocessor systems that only use the basic log).
965 			 */
966 			overall_buffer_size = debug_buf_size + sizeof(struct macos_panic_header);
967 		}
968 
969 		/* Update the CRC */
970 		panic_info->mph_crc = crc32(0L, &panic_info->mph_version, (overall_buffer_size - offsetof(struct macos_panic_header, mph_version)));
971 
972 		if (variant == kPaniclogFlushBase) {
973 			/* Flush the header and base panic log. */
974 			kprintf("Flushing base panic log\n");
975 			size_to_flush = ROUNDUP((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
976 			offset_to_flush = 0;
977 			PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
978 		} else if ((variant == kPaniclogFlushStackshot) || (variant == kPaniclogFlushOtherLog)) {
979 			if (variant == kPaniclogFlushStackshot) {
980 				/*
981 				 * We flush the stackshot before flushing the updated header because the stackshot
982 				 * can take a while to flush. We want the paniclog header to be as consistent as possible even
983 				 * if the stackshot isn't flushed completely. Flush starting from the end of the panic log.
984 				 */
985 				kprintf("Flushing panic log stackshot\n");
986 				offset_to_flush = ROUNDDOWN((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
987 				size_to_flush = ROUNDUP((panic_info->mph_stackshot_len + (panic_info->mph_stackshot_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
988 				PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
989 			}
990 
991 			/* Flush the other log -- everything after the stackshot */
992 			kprintf("Flushing panic 'other' log\n");
993 			offset_to_flush = ROUNDDOWN((panic_info->mph_stackshot_offset + panic_info->mph_stackshot_len), PANIC_FLUSH_BOUNDARY);
994 			size_to_flush = ROUNDUP((panic_info->mph_other_log_len + (panic_info->mph_other_log_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
995 			PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
996 
997 			/* Flush the header -- everything before the paniclog */
998 			kprintf("Flushing panic log header\n");
999 			size_to_flush = ROUNDUP(panic_info->mph_panic_log_offset, PANIC_FLUSH_BOUNDARY);
1000 			offset_to_flush = 0;
1001 			PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
1002 		}
1003 	} else if (commit_paniclog_to_nvram) {
1004 		assert(debug_buf_size != 0);
1005 		unsigned int bufpos;
1006 		unsigned long pi_size = 0;
1007 		uintptr_t cr0;
1008 
1009 		debug_putc(0);
1010 
1011 		/*
1012 		 * Now call the compressor
1013 		 * XXX Consider using the WKdm compressor in the
1014 		 * future, rather than just packing - would need to
1015 		 * be co-ordinated with crashreporter, which decodes
1016 		 * this post-restart. The compressor should be
1017 		 * capable of in-place compression.
1018 		 *
1019 		 * Don't include the macOS panic header (for co-processor systems only)
1020 		 */
1021 		bufpos = packA(debug_buf_base, (unsigned int) (debug_buf_ptr - debug_buf_base),
1022 		    debug_buf_size);
1023 		/*
1024 		 * If compression was successful, use the compressed length
1025 		 */
1026 		pi_size = bufpos ? bufpos : (unsigned) (debug_buf_ptr - debug_buf_base);
1027 
1028 		/*
1029 		 * The following sequence is a workaround for:
1030 		 * <rdar://problem/5915669> SnowLeopard10A67: AppleEFINVRAM should not invoke
1031 		 * any routines that use floating point (MMX in this case) when saving panic
1032 		 * logs to nvram/flash.
1033 		 */
1034 		cr0 = get_cr0();
1035 		clear_ts();
1036 
1037 		/*
1038 		 * Save panic log to non-volatile store
1039 		 * Panic info handler must truncate data that is
1040 		 * too long for this platform.
1041 		 * This call must save data synchronously,
1042 		 * since we can subsequently halt the system.
1043 		 */
1044 		kprintf("Attempting to commit panic log to NVRAM\n");
1045 		pi_size = PESavePanicInfo((unsigned char *)debug_buf_base,
1046 		    (uint32_t)pi_size );
1047 		set_cr0(cr0);
1048 
1049 		/*
1050 		 * Uncompress in-place, to permit examination of
1051 		 * the panic log by debuggers.
1052 		 */
1053 		if (bufpos) {
1054 			unpackA(debug_buf_base, bufpos);
1055 		}
1056 	}
1057 }
1058 
1059 void
paniclog_flush()1060 paniclog_flush()
1061 {
1062 	/* Called outside of this file to update logging appended to the "other" log */
1063 	paniclog_flush_internal(kPaniclogFlushOtherLog);
1064 	return;
1065 }
1066 
1067 char *
machine_boot_info(char * buf,__unused vm_size_t size)1068 machine_boot_info(char *buf, __unused vm_size_t size)
1069 {
1070 	*buf = '\0';
1071 	return buf;
1072 }
1073 
1074 /* Routines for address - symbol translation. Not called unless the "keepsyms"
1075  * boot-arg is supplied.
1076  */
1077 
1078 static int
panic_print_macho_symbol_name(kernel_mach_header_t * mh,vm_address_t search,const char * module_name)1079 panic_print_macho_symbol_name(kernel_mach_header_t *mh, vm_address_t search, const char *module_name)
1080 {
1081 	kernel_nlist_t      *sym = NULL;
1082 	struct load_command         *cmd;
1083 	kernel_segment_command_t    *orig_ts = NULL, *orig_le = NULL;
1084 	struct symtab_command       *orig_st = NULL;
1085 	unsigned int                        i;
1086 	char                                        *strings, *bestsym = NULL;
1087 	vm_address_t                        bestaddr = 0, diff, curdiff;
1088 
1089 	/* Assume that if it's loaded and linked into the kernel, it's a valid Mach-O */
1090 
1091 	cmd = (struct load_command *) &mh[1];
1092 	for (i = 0; i < mh->ncmds; i++) {
1093 		if (cmd->cmd == LC_SEGMENT_KERNEL) {
1094 			kernel_segment_command_t *orig_sg = (kernel_segment_command_t *) cmd;
1095 
1096 			if (strncmp(SEG_TEXT, orig_sg->segname,
1097 			    sizeof(orig_sg->segname)) == 0) {
1098 				orig_ts = orig_sg;
1099 			} else if (strncmp(SEG_LINKEDIT, orig_sg->segname,
1100 			    sizeof(orig_sg->segname)) == 0) {
1101 				orig_le = orig_sg;
1102 			} else if (strncmp("", orig_sg->segname,
1103 			    sizeof(orig_sg->segname)) == 0) {
1104 				orig_ts = orig_sg; /* pre-Lion i386 kexts have a single unnamed segment */
1105 			}
1106 		} else if (cmd->cmd == LC_SYMTAB) {
1107 			orig_st = (struct symtab_command *) cmd;
1108 		}
1109 
1110 		cmd = (struct load_command *) ((uintptr_t) cmd + cmd->cmdsize);
1111 	}
1112 
1113 	if ((orig_ts == NULL) || (orig_st == NULL) || (orig_le == NULL)) {
1114 		return 0;
1115 	}
1116 
1117 	if ((search < orig_ts->vmaddr) ||
1118 	    (search >= orig_ts->vmaddr + orig_ts->vmsize)) {
1119 		/* search out of range for this mach header */
1120 		return 0;
1121 	}
1122 
1123 	sym = (kernel_nlist_t *)(uintptr_t)(orig_le->vmaddr + orig_st->symoff - orig_le->fileoff);
1124 	strings = (char *)(uintptr_t)(orig_le->vmaddr + orig_st->stroff - orig_le->fileoff);
1125 	diff = search;
1126 
1127 	for (i = 0; i < orig_st->nsyms; i++) {
1128 		if (sym[i].n_type & N_STAB) {
1129 			continue;
1130 		}
1131 
1132 		if (sym[i].n_value <= search) {
1133 			curdiff = search - (vm_address_t)sym[i].n_value;
1134 			if (curdiff < diff) {
1135 				diff = curdiff;
1136 				bestaddr = sym[i].n_value;
1137 				bestsym = strings + sym[i].n_un.n_strx;
1138 			}
1139 		}
1140 	}
1141 
1142 	if (bestsym != NULL) {
1143 		if (diff != 0) {
1144 			paniclog_append_noflush("%s : %s + 0x%lx", module_name, bestsym, (unsigned long)diff);
1145 		} else {
1146 			paniclog_append_noflush("%s : %s", module_name, bestsym);
1147 		}
1148 		return 1;
1149 	}
1150 	return 0;
1151 }
1152 
1153 static void
panic_display_uptime(void)1154 panic_display_uptime(void)
1155 {
1156 	uint64_t        uptime;
1157 	absolutetime_to_nanoseconds(mach_absolute_time(), &uptime);
1158 
1159 	paniclog_append_noflush("\nSystem uptime in nanoseconds: %llu\n", uptime);
1160 }
1161 
1162 extern uint32_t         gIOHibernateCount;
1163 
1164 static void
panic_display_hib_count(void)1165 panic_display_hib_count(void)
1166 {
1167 	paniclog_append_noflush("Hibernation exit count: %u\n", gIOHibernateCount);
1168 }
1169 
1170 extern AbsoluteTime      gIOLastSleepAbsTime;
1171 extern AbsoluteTime      gIOLastWakeAbsTime;
1172 extern uint64_t          gAcpiLastSleepTscBase;
1173 extern uint64_t          gAcpiLastSleepNanoBase;
1174 extern uint64_t          gAcpiLastWakeTscBase;
1175 extern uint64_t          gAcpiLastWakeNanoBase;
1176 extern boolean_t         is_clock_configured;
1177 
1178 static void
panic_display_times(void)1179 panic_display_times(void)
1180 {
1181 	if (!is_clock_configured) {
1182 		paniclog_append_noflush("Warning: clock is not configured. Can't get time\n");
1183 		return;
1184 	}
1185 
1186 	paniclog_append_noflush("Last Sleep:           absolute           base_tsc          base_nano\n");
1187 	paniclog_append_noflush("  Uptime  : 0x%016llx\n", mach_absolute_time());
1188 	paniclog_append_noflush("  Sleep   : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastSleepAbsTime, gAcpiLastSleepTscBase, gAcpiLastSleepNanoBase);
1189 	paniclog_append_noflush("  Wake    : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastWakeAbsTime, gAcpiLastWakeTscBase, gAcpiLastWakeNanoBase);
1190 }
1191 
1192 static void
panic_display_disk_errors(void)1193 panic_display_disk_errors(void)
1194 {
1195 	if (panic_disk_error_description[0]) {
1196 		panic_disk_error_description[panic_disk_error_description_size - 1] = '\0';
1197 		paniclog_append_noflush("Root disk errors: \"%s\"\n", panic_disk_error_description);
1198 	}
1199 }
1200 
1201 static void
panic_display_shutdown_status(void)1202 panic_display_shutdown_status(void)
1203 {
1204 #if defined(__i386__) || defined(__x86_64__)
1205 	paniclog_append_noflush("System shutdown begun: %s\n", IOPMRootDomainGetWillShutdown() ? "YES" : "NO");
1206 	if (gIOPolledCoreFileMode == kIOPolledCoreFileModeNotInitialized) {
1207 		paniclog_append_noflush("Panic diags file unavailable, panic occurred prior to initialization\n");
1208 	} else if (gIOPolledCoreFileMode != kIOPolledCoreFileModeDisabled) {
1209 		/*
1210 		 * If we haven't marked the corefile as explicitly disabled, and we've made it past initialization, then we know the current
1211 		 * system was configured to use disk based diagnostics at some point.
1212 		 */
1213 		paniclog_append_noflush("Panic diags file available: %s (0x%x)\n", (gIOPolledCoreFileMode != kIOPolledCoreFileModeClosed && gIOPolledCoreFileMode != kIOPolledCoreFileModeUnlinked) ? "YES" : "NO", kdp_polled_corefile_error());
1214 	}
1215 #endif
1216 }
1217 
1218 extern const char version[];
1219 extern char osversion[];
1220 
1221 static volatile uint32_t config_displayed = 0;
1222 
1223 static void
panic_display_system_configuration(boolean_t launchd_exit)1224 panic_display_system_configuration(boolean_t launchd_exit)
1225 {
1226 	if (!launchd_exit) {
1227 		panic_display_process_name();
1228 	}
1229 	if (OSCompareAndSwap(0, 1, &config_displayed)) {
1230 		char buf[256];
1231 		if (!launchd_exit && strlcpy(buf, PE_boot_args(), sizeof(buf))) {
1232 			paniclog_append_noflush("Boot args: %s\n", buf);
1233 		}
1234 		paniclog_append_noflush("\nMac OS version:\n%s\n",
1235 		    (osversion[0] != 0) ? osversion : "Not yet set");
1236 		paniclog_append_noflush("\nKernel version:\n%s\n", version);
1237 		panic_display_kernel_uuid();
1238 		paniclog_append_noflush("roots installed: %lld\n", roots_installed);
1239 		if (!launchd_exit) {
1240 			panic_display_kernel_aslr();
1241 			panic_display_hibb();
1242 			panic_display_pal_info();
1243 		}
1244 		panic_display_model_name();
1245 		panic_display_disk_errors();
1246 		panic_display_shutdown_status();
1247 		if (!launchd_exit) {
1248 			panic_display_hib_count();
1249 			panic_display_uptime();
1250 			panic_display_times();
1251 			panic_display_compressor_stats();
1252 			panic_display_zalloc();
1253 			kext_dump_panic_lists(&paniclog_append_noflush);
1254 		}
1255 	}
1256 }
1257 
1258 extern kmod_info_t * kmod; /* the list of modules */
1259 
1260 static void
panic_print_kmod_symbol_name(vm_address_t search)1261 panic_print_kmod_symbol_name(vm_address_t search)
1262 {
1263 	u_int i;
1264 
1265 	if (gLoadedKextSummaries == NULL) {
1266 		return;
1267 	}
1268 	for (i = 0; i < gLoadedKextSummaries->numSummaries; ++i) {
1269 		OSKextLoadedKextSummary *summary = gLoadedKextSummaries->summaries + i;
1270 
1271 		if ((search >= summary->address) &&
1272 		    (search < (summary->address + summary->size))) {
1273 			kernel_mach_header_t *header = (kernel_mach_header_t *)(uintptr_t) summary->address;
1274 			if (panic_print_macho_symbol_name(header, search, summary->name) == 0) {
1275 				paniclog_append_noflush("%s + %llu", summary->name, (unsigned long)search - summary->address);
1276 			}
1277 			break;
1278 		}
1279 	}
1280 }
1281 
1282 static void
read_lbr_empty(void)1283 read_lbr_empty(void)
1284 {
1285 }
1286 
1287 void (*read_lbr)(void) = read_lbr_empty;
1288 
1289 static void
capture_lbr_state(void)1290 capture_lbr_state(void)
1291 {
1292 	thread_t thr_act = current_thread();
1293 	int i;
1294 	last_branch_state_t thread_lbr_data;
1295 	struct lbr_data *lbr = &lbrs[cpu_number()];
1296 
1297 	if (lbr_stack_size > 0) {
1298 		i386_lbr_disable();
1299 
1300 		if (i386_filtered_lbr_state_to_mach_thread_state(thr_act, &thread_lbr_data, false) == 0) {
1301 			for (i = 0; i < thread_lbr_data.lbr_count; i++) {
1302 				lbr->from[i] = thread_lbr_data.lbrs[i].from_ip;
1303 				lbr->to[i] = thread_lbr_data.lbrs[i].to_ip;
1304 			}
1305 		}
1306 	}
1307 
1308 	i386_lbr_enable();
1309 }
1310 
1311 struct panic_lbr_header_s {
1312 	uint32_t id;
1313 	uint8_t ncpus;
1314 	uint8_t lbr_count;
1315 	uint64_t pcarveout_va;
1316 };
1317 struct panic_lbr_header_s panic_lbr_header = {0};
1318 
1319 static void
copy_lbr_data_for_core(void)1320 copy_lbr_data_for_core(void)
1321 {
1322 	unsigned int cpu;
1323 
1324 	if (phys_carveout) {
1325 		// The minimum size of phys_carveout is 1MiB but just in case
1326 		if (phys_carveout_size >= sizeof(last_branch_state_t) * max_ncpus) {
1327 			for (cpu = 0; cpu < real_ncpus; cpu++) {
1328 				void *buf = (void *)(phys_carveout + lbr_stack_size * sizeof(uint64_t) * cpu);
1329 				memcpy(buf, lbrs[cpu].from, sizeof(uint64_t) * lbr_stack_size);
1330 				memcpy((uint64_t *)buf + lbr_stack_size * sizeof(uint64_t), lbrs[cpu].to,
1331 				    sizeof(uint64_t) * lbr_stack_size);
1332 			}
1333 			/* Write 'LBRS' identifier, the number of CPUs and the LBR stack size */
1334 			panic_lbr_header.id = LBR_MAGIC; /* 'LBRS' */
1335 			panic_lbr_header.ncpus = real_ncpus;
1336 			panic_lbr_header.lbr_count = lbr_stack_size;
1337 			panic_lbr_header.pcarveout_va = phys_carveout;
1338 		}
1339 	}
1340 }
1341 
1342 void
lbr_for_kmode_init(uint32_t lbr_count)1343 lbr_for_kmode_init(uint32_t lbr_count)
1344 {
1345 	uint32_t size;
1346 	int i;
1347 
1348 	lbr_stack_size = lbr_count;
1349 
1350 	/* Cannot use real_ncpus here as only one CPU is registered yet*/
1351 
1352 	size = sizeof(uint64_t) * lbr_stack_size;
1353 	for (i = 0; i < max_ncpus; i++) {
1354 		lbrs[i].from = kalloc_data(size, Z_WAITOK | Z_ZERO);
1355 		lbrs[i].to = kalloc_data(size, Z_WAITOK | Z_ZERO);
1356 		if (!lbrs[i].from || !lbrs[i].to) {
1357 			kprintf("LBR: Kalloc failed for lbrs.from/to\n");
1358 			if (lbrs[i].from) {
1359 				kfree_data(lbrs[i].from, size);
1360 			}
1361 			if (lbrs[i].to) {
1362 				kfree_data(lbrs[i].to, size);
1363 			}
1364 			while (--i >= 0) {
1365 				kfree_data(lbrs[i].from, size);
1366 				kfree_data(lbrs[i].to, size);
1367 			}
1368 			goto err;
1369 		}
1370 	}
1371 
1372 	read_lbr = capture_lbr_state;
1373 
1374 	return;
1375 
1376 err:
1377 	last_branch_enabled_modes = LBR_ENABLED_NONE;
1378 	return;
1379 }
1380 
1381 static void
write_lbr_to_panic_log(void)1382 write_lbr_to_panic_log(void)
1383 {
1384 	unsigned int cpu;
1385 	int i;
1386 
1387 	for (cpu = 0; cpu < real_ncpus; cpu++) {
1388 		paniclog_append_noflush("LBR Stack (CPU %d):\n", cpu);
1389 		for (i = 0; i < lbr_stack_size; i++) {
1390 			if (lbrs[cpu].from[i] == 0x0 && lbrs[cpu].to[i] == 0x0) {
1391 				continue;
1392 			}
1393 			paniclog_append_noflush("0x%llx : 0x%llx\n", lbrs[cpu].from[i], lbrs[cpu].to[i]);
1394 		}
1395 	}
1396 	if (debug_can_coredump_phys_carveout()) {
1397 		copy_lbr_data_for_core();
1398 	}
1399 }
1400 
1401 void
panic_print_symbol_name(vm_address_t search)1402 panic_print_symbol_name(vm_address_t search)
1403 {
1404 	/* try searching in the kernel */
1405 	if (panic_print_macho_symbol_name(&_mh_execute_header, search, "mach_kernel") == 0) {
1406 		/* that failed, now try to search for the right kext */
1407 		panic_print_kmod_symbol_name(search);
1408 	}
1409 }
1410 
1411 /* Generate a backtrace, given a frame pointer - this routine
1412  * should walk the stack safely. The trace is appended to the panic log
1413  * and conditionally, to the console. If the trace contains kernel module
1414  * addresses, display the module name, load address and dependencies.
1415  */
1416 
1417 #define DUMPFRAMES 32
1418 #define PBT_TIMEOUT_CYCLES (5 * 1000 * 1000 * 1000ULL)
1419 void
panic_i386_backtrace(void * _frame,int nframes,const char * msg,boolean_t regdump,x86_saved_state_t * regs)1420 panic_i386_backtrace(void *_frame, int nframes, const char *msg, boolean_t regdump, x86_saved_state_t *regs)
1421 {
1422 	cframe_t        *frame = (cframe_t *)_frame;
1423 	vm_offset_t raddrs[DUMPFRAMES];
1424 	vm_offset_t PC = 0;
1425 	int frame_index;
1426 	volatile uint32_t *ppbtcnt = &pbtcnt;
1427 	uint64_t bt_tsc_timeout;
1428 	boolean_t keepsyms = FALSE;
1429 	int cn = cpu_number();
1430 	boolean_t old_doprnt_hide_pointers = doprnt_hide_pointers;
1431 	thread_t cur_thread = current_thread();
1432 	task_t task;
1433 	struct proc *proc;
1434 
1435 	/* Turn off I/O tracing now that we're panicking */
1436 	iotrace_disable();
1437 
1438 	if (pbtcpu != cn) {
1439 		os_atomic_inc(&pbtcnt, relaxed);
1440 		/* Spin on print backtrace lock, which serializes output
1441 		 * Continue anyway if a timeout occurs.
1442 		 */
1443 		(void)hw_lock_to(&pbtlock, &hw_lock_spin_panic_policy, LCK_GRP_NULL);
1444 		pbtcpu = cn;
1445 	}
1446 
1447 	if (__improbable(doprnt_hide_pointers == TRUE)) {
1448 		/* If we're called directly, the Debugger() function will not be called,
1449 		 * so we need to reset the value in here. */
1450 		doprnt_hide_pointers = FALSE;
1451 	}
1452 
1453 	panic_check_hook();
1454 
1455 	PE_parse_boot_argn("keepsyms", &keepsyms, sizeof(keepsyms));
1456 
1457 	if (msg != NULL) {
1458 		paniclog_append_noflush("%s", msg);
1459 	}
1460 
1461 	if ((regdump == TRUE) && (regs != NULL)) {
1462 		x86_saved_state64_t     *ss64p = saved_state64(regs);
1463 		paniclog_append_noflush(
1464 			"RAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
1465 			"RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
1466 			"R8:  0x%016llx, R9:  0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
1467 			"R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
1468 			"RFL: 0x%016llx, RIP: 0x%016llx, CS:  0x%016llx, SS:  0x%016llx\n",
1469 			ss64p->rax, ss64p->rbx, ss64p->rcx, ss64p->rdx,
1470 			ss64p->isf.rsp, ss64p->rbp, ss64p->rsi, ss64p->rdi,
1471 			ss64p->r8, ss64p->r9, ss64p->r10, ss64p->r11,
1472 			ss64p->r12, ss64p->r13, ss64p->r14, ss64p->r15,
1473 			ss64p->isf.rflags, ss64p->isf.rip, ss64p->isf.cs,
1474 			ss64p->isf.ss);
1475 		PC = ss64p->isf.rip;
1476 	}
1477 
1478 	// print current task info
1479 	if (panic_get_thread_proc_task(cur_thread, &task, &proc)) {
1480 		paniclog_append_noflush("Panicked task %p: %d threads: ",
1481 		    task, task->thread_count);
1482 		if (proc) {
1483 			char name[MAXCOMLEN + 1];
1484 			proc_name_kdp(proc, name, sizeof(name));
1485 			paniclog_append_noflush("pid %d: %s", proc_pid(proc), name);
1486 		} else {
1487 			paniclog_append_noflush("unknown task");
1488 		}
1489 
1490 		paniclog_append_noflush("\n");
1491 	}
1492 
1493 	paniclog_append_noflush("Backtrace (CPU %d), panicked thread: %p, "
1494 #if PRINT_ARGS_FROM_STACK_FRAME
1495 	    "Frame : Return Address (4 potential args on stack)\n",
1496 #else
1497 	    "Frame : Return Address\n",
1498 #endif
1499 	    cn, cur_thread);
1500 
1501 	for (frame_index = 0; frame_index < nframes; frame_index++) {
1502 		vm_offset_t curframep = (vm_offset_t) frame;
1503 
1504 		if (!curframep) {
1505 			break;
1506 		}
1507 
1508 		if (curframep & 0x3) {
1509 			paniclog_append_noflush("Unaligned frame\n");
1510 			goto invalid;
1511 		}
1512 
1513 		if (!kvtophys(curframep) ||
1514 		    !kvtophys(curframep + sizeof(cframe_t) - 1)) {
1515 			paniclog_append_noflush("No mapping exists for frame pointer\n");
1516 			goto invalid;
1517 		}
1518 
1519 		paniclog_append_noflush("%p : 0x%lx ", frame, frame->caller);
1520 		if (frame_index < DUMPFRAMES) {
1521 			raddrs[frame_index] = frame->caller;
1522 		}
1523 
1524 #if PRINT_ARGS_FROM_STACK_FRAME
1525 		if (kvtophys((vm_offset_t)&(frame->args[3]))) {
1526 			paniclog_append_noflush("(0x%x 0x%x 0x%x 0x%x) ",
1527 			    frame->args[0], frame->args[1],
1528 			    frame->args[2], frame->args[3]);
1529 		}
1530 #endif
1531 
1532 		/* Display address-symbol translation only if the "keepsyms"
1533 		 * boot-arg is suppplied, since we unload LINKEDIT otherwise.
1534 		 * This routine is potentially unsafe; also, function
1535 		 * boundary identification is unreliable after a strip -x.
1536 		 */
1537 		if (keepsyms) {
1538 			panic_print_symbol_name((vm_address_t)frame->caller);
1539 		}
1540 
1541 		paniclog_append_noflush("\n");
1542 
1543 		frame = frame->prev;
1544 	}
1545 
1546 	if (frame_index >= nframes && (vm_offset_t)frame != 0) {
1547 		paniclog_append_noflush("\tBacktrace continues...\n");
1548 	}
1549 
1550 	goto out;
1551 
1552 invalid:
1553 	paniclog_append_noflush("Backtrace terminated-invalid frame pointer %p\n", frame);
1554 out:
1555 
1556 	/* Identify kernel modules in the backtrace and display their
1557 	 * load addresses and dependencies. This routine should walk
1558 	 * the kmod list safely.
1559 	 */
1560 	if (frame_index) {
1561 		kmod_panic_dump((vm_offset_t *)&raddrs[0], frame_index);
1562 	}
1563 
1564 	if (PC != 0) {
1565 		kmod_panic_dump(&PC, 1);
1566 	}
1567 
1568 	if (last_branch_enabled_modes == LBR_ENABLED_KERNELMODE) {
1569 		write_lbr_to_panic_log();
1570 	}
1571 
1572 	panic_display_system_configuration(FALSE);
1573 
1574 	doprnt_hide_pointers = old_doprnt_hide_pointers;
1575 
1576 	/* Release print backtrace lock, to permit other callers in the
1577 	 * event of panics on multiple processors.
1578 	 */
1579 	hw_lock_unlock(&pbtlock);
1580 	os_atomic_dec(&pbtcnt, relaxed);
1581 	/* Wait for other processors to complete output
1582 	 * Timeout and continue after PBT_TIMEOUT_CYCLES.
1583 	 */
1584 	bt_tsc_timeout = rdtsc64() + PBT_TIMEOUT_CYCLES;
1585 	while (*ppbtcnt && (rdtsc64() < bt_tsc_timeout)) {
1586 		;
1587 	}
1588 }
1589 
1590 static boolean_t
debug_copyin(pmap_t p,uint64_t uaddr,void * dest,size_t size)1591 debug_copyin(pmap_t p, uint64_t uaddr, void *dest, size_t size)
1592 {
1593 	size_t rem = size;
1594 	char *kvaddr = dest;
1595 
1596 	while (rem) {
1597 		ppnum_t upn = pmap_find_phys(p, uaddr);
1598 		uint64_t phys_src = ptoa_64(upn) | (uaddr & PAGE_MASK);
1599 		uint64_t phys_dest = kvtophys((vm_offset_t)kvaddr);
1600 		uint64_t src_rem = PAGE_SIZE - (phys_src & PAGE_MASK);
1601 		uint64_t dst_rem = PAGE_SIZE - (phys_dest & PAGE_MASK);
1602 		size_t cur_size = (uint32_t) MIN(src_rem, dst_rem);
1603 		cur_size = MIN(cur_size, rem);
1604 
1605 		if (upn && pmap_valid_page(upn) && phys_dest) {
1606 			bcopy_phys(phys_src, phys_dest, cur_size);
1607 		} else {
1608 			break;
1609 		}
1610 		uaddr += cur_size;
1611 		kvaddr += cur_size;
1612 		rem -= cur_size;
1613 	}
1614 	return rem == 0;
1615 }
1616 
1617 void
print_threads_registers(thread_t thread)1618 print_threads_registers(thread_t thread)
1619 {
1620 	x86_saved_state_t *savestate;
1621 
1622 	savestate = get_user_regs(thread);
1623 	paniclog_append_noflush(
1624 		"\nRAX: 0x%016llx, RBX: 0x%016llx, RCX: 0x%016llx, RDX: 0x%016llx\n"
1625 		"RSP: 0x%016llx, RBP: 0x%016llx, RSI: 0x%016llx, RDI: 0x%016llx\n"
1626 		"R8:  0x%016llx, R9:  0x%016llx, R10: 0x%016llx, R11: 0x%016llx\n"
1627 		"R12: 0x%016llx, R13: 0x%016llx, R14: 0x%016llx, R15: 0x%016llx\n"
1628 		"RFL: 0x%016llx, RIP: 0x%016llx, CS:  0x%016llx, SS:  0x%016llx\n\n",
1629 		savestate->ss_64.rax, savestate->ss_64.rbx, savestate->ss_64.rcx, savestate->ss_64.rdx,
1630 		savestate->ss_64.isf.rsp, savestate->ss_64.rbp, savestate->ss_64.rsi, savestate->ss_64.rdi,
1631 		savestate->ss_64.r8, savestate->ss_64.r9, savestate->ss_64.r10, savestate->ss_64.r11,
1632 		savestate->ss_64.r12, savestate->ss_64.r13, savestate->ss_64.r14, savestate->ss_64.r15,
1633 		savestate->ss_64.isf.rflags, savestate->ss_64.isf.rip, savestate->ss_64.isf.cs,
1634 		savestate->ss_64.isf.ss);
1635 }
1636 
1637 void
print_tasks_user_threads(task_t task)1638 print_tasks_user_threads(task_t task)
1639 {
1640 	thread_t                thread = current_thread();
1641 	x86_saved_state_t *savestate;
1642 	pmap_t                  pmap = 0;
1643 	uint64_t                rbp;
1644 	const char              *cur_marker = 0;
1645 	int             j;
1646 
1647 	for (j = 0, thread = (thread_t) queue_first(&task->threads); j < task->thread_count;
1648 	    ++j, thread = (thread_t) queue_next(&thread->task_threads)) {
1649 		paniclog_append_noflush("Thread %d: %p\n", j, thread);
1650 		pmap = get_task_pmap(task);
1651 		savestate = get_user_regs(thread);
1652 		rbp = savestate->ss_64.rbp;
1653 		paniclog_append_noflush("\t0x%016llx\n", savestate->ss_64.isf.rip);
1654 		print_one_backtrace(pmap, (vm_offset_t)rbp, cur_marker, TRUE);
1655 		paniclog_append_noflush("\n");
1656 	}
1657 }
1658 
1659 void
print_thread_num_that_crashed(task_t task)1660 print_thread_num_that_crashed(task_t task)
1661 {
1662 	thread_t                c_thread = current_thread();
1663 	thread_t                thread;
1664 	int             j;
1665 
1666 	for (j = 0, thread = (thread_t) queue_first(&task->threads); j < task->thread_count;
1667 	    ++j, thread = (thread_t) queue_next(&thread->task_threads)) {
1668 		if (c_thread == thread) {
1669 			paniclog_append_noflush("\nThread %d crashed\n", j);
1670 			break;
1671 		}
1672 	}
1673 }
1674 
1675 #define PANICLOG_UUID_BUF_SIZE 256
1676 
1677 void
print_uuid_info(task_t task)1678 print_uuid_info(task_t task)
1679 {
1680 	uint32_t                uuid_info_count = 0;
1681 	mach_vm_address_t       uuid_info_addr = 0;
1682 	boolean_t               have_map = (task->map != NULL) && (ml_validate_nofault((vm_offset_t)(task->map), sizeof(struct _vm_map)));
1683 	boolean_t               have_pmap = have_map && (task->map->pmap != NULL) && (ml_validate_nofault((vm_offset_t)(task->map->pmap), sizeof(struct pmap)));
1684 	int                             task_pid = pid_from_task(task);
1685 	char                    uuidbuf[PANICLOG_UUID_BUF_SIZE] = {0};
1686 	char                    *uuidbufptr = uuidbuf;
1687 	uint32_t                k;
1688 
1689 	if (have_pmap && task->active && task_pid > 0) {
1690 		/* Read dyld_all_image_infos struct from task memory to get UUID array count & location */
1691 		struct user64_dyld_all_image_infos task_image_infos;
1692 		if (debug_copyin(task->map->pmap, task->all_image_info_addr,
1693 		    &task_image_infos, sizeof(struct user64_dyld_all_image_infos))) {
1694 			uuid_info_count = (uint32_t)task_image_infos.uuidArrayCount;
1695 			uuid_info_addr = task_image_infos.uuidArray;
1696 		}
1697 
1698 		/* If we get a NULL uuid_info_addr (which can happen when we catch dyld
1699 		 * in the middle of updating this data structure), we zero the
1700 		 * uuid_info_count so that we won't even try to save load info for this task
1701 		 */
1702 		if (!uuid_info_addr) {
1703 			uuid_info_count = 0;
1704 		}
1705 	}
1706 
1707 	if (task_pid > 0 && uuid_info_count > 0) {
1708 		uint32_t uuid_info_size = sizeof(struct user64_dyld_uuid_info);
1709 		uint32_t uuid_array_size = uuid_info_count * uuid_info_size;
1710 		uint32_t uuid_copy_size = 0;
1711 		uint32_t uuid_image_count = 0;
1712 		char *current_uuid_buffer = NULL;
1713 		/* Copy in the UUID info array. It may be nonresident, in which case just fix up nloadinfos to 0 */
1714 
1715 		paniclog_append_noflush("\nuuid info:\n");
1716 		while (uuid_array_size) {
1717 			if (uuid_array_size <= PANICLOG_UUID_BUF_SIZE) {
1718 				uuid_copy_size = uuid_array_size;
1719 				uuid_image_count = uuid_array_size / uuid_info_size;
1720 			} else {
1721 				uuid_image_count = PANICLOG_UUID_BUF_SIZE / uuid_info_size;
1722 				uuid_copy_size = uuid_image_count * uuid_info_size;
1723 			}
1724 			if (have_pmap && !debug_copyin(task->map->pmap, uuid_info_addr, uuidbufptr,
1725 			    uuid_copy_size)) {
1726 				paniclog_append_noflush("Error!! Failed to copy UUID info for task %p pid %d\n", task, task_pid);
1727 				uuid_image_count = 0;
1728 				break;
1729 			}
1730 
1731 			if (uuid_image_count > 0) {
1732 				current_uuid_buffer = uuidbufptr;
1733 				for (k = 0; k < uuid_image_count; k++) {
1734 					paniclog_append_noflush(" %#llx", *(uint64_t *)current_uuid_buffer);
1735 					current_uuid_buffer += sizeof(uint64_t);
1736 					uint8_t *uuid = (uint8_t *)current_uuid_buffer;
1737 					paniclog_append_noflush("\tuuid = <%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x>\n",
1738 					    uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7], uuid[8],
1739 					    uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
1740 					current_uuid_buffer += 16;
1741 				}
1742 				bzero(&uuidbuf, sizeof(uuidbuf));
1743 			}
1744 			uuid_info_addr += uuid_copy_size;
1745 			uuid_array_size -= uuid_copy_size;
1746 		}
1747 	}
1748 }
1749 
1750 void
print_launchd_info(void)1751 print_launchd_info(void)
1752 {
1753 	task_t          task = current_task();
1754 	thread_t        thread = current_thread();
1755 	volatile        uint32_t *ppbtcnt = &pbtcnt;
1756 	uint64_t        bt_tsc_timeout;
1757 	int             cn = cpu_number();
1758 
1759 	if (pbtcpu != cn) {
1760 		os_atomic_inc(&pbtcnt, relaxed);
1761 		/* Spin on print backtrace lock, which serializes output
1762 		 * Continue anyway if a timeout occurs.
1763 		 */
1764 		(void)hw_lock_to(&pbtlock, &hw_lock_spin_panic_policy, LCK_GRP_NULL);
1765 		pbtcpu = cn;
1766 	}
1767 
1768 	print_uuid_info(task);
1769 	print_thread_num_that_crashed(task);
1770 	print_threads_registers(thread);
1771 	print_tasks_user_threads(task);
1772 
1773 	panic_display_system_configuration(TRUE);
1774 
1775 	/* Release print backtrace lock, to permit other callers in the
1776 	 * event of panics on multiple processors.
1777 	 */
1778 	hw_lock_unlock(&pbtlock);
1779 	os_atomic_dec(&pbtcnt, relaxed);
1780 	/* Wait for other processors to complete output
1781 	 * Timeout and continue after PBT_TIMEOUT_CYCLES.
1782 	 */
1783 	bt_tsc_timeout = rdtsc64() + PBT_TIMEOUT_CYCLES;
1784 	while (*ppbtcnt && (rdtsc64() < bt_tsc_timeout)) {
1785 		;
1786 	}
1787 }
1788 
1789 /*
1790  * Compares 2 EFI GUIDs. Returns true if they match.
1791  */
1792 static bool
efi_compare_guids(EFI_GUID * guid1,EFI_GUID * guid2)1793 efi_compare_guids(EFI_GUID *guid1, EFI_GUID *guid2)
1794 {
1795 	return (bcmp(guid1, guid2, sizeof(EFI_GUID)) == 0) ? true : false;
1796 }
1797 
1798 /*
1799  * Converts from an efiboot-originated virtual address to a physical
1800  * address.
1801  */
1802 static inline uint64_t
efi_efiboot_virtual_to_physical(uint64_t addr)1803 efi_efiboot_virtual_to_physical(uint64_t addr)
1804 {
1805 	if (addr >= VM_MIN_KERNEL_ADDRESS) {
1806 		return addr & (0x40000000ULL - 1);
1807 	} else {
1808 		return addr;
1809 	}
1810 }
1811 
1812 /*
1813  * Convers from a efiboot-originated virtual address to an accessible
1814  * pointer to that physical address by translating it to a physmap-relative
1815  * address.
1816  */
1817 static void *
efi_efiboot_virtual_to_physmap_virtual(uint64_t addr)1818 efi_efiboot_virtual_to_physmap_virtual(uint64_t addr)
1819 {
1820 	return PHYSMAP_PTOV(efi_efiboot_virtual_to_physical(addr));
1821 }
1822 
1823 /*
1824  * Returns the physical address of the firmware table identified
1825  * by the passed-in GUID, or 0 if the table could not be located.
1826  */
1827 static uint64_t
efi_get_cfgtbl_by_guid(EFI_GUID * guidp)1828 efi_get_cfgtbl_by_guid(EFI_GUID *guidp)
1829 {
1830 	EFI_CONFIGURATION_TABLE_64 *cfg_table_entp, *cfgTable;
1831 	boot_args *args = (boot_args *)PE_state.bootArgs;
1832 	EFI_SYSTEM_TABLE_64 *estp;
1833 	uint32_t i, hdr_cksum, cksum;
1834 
1835 	estp = (EFI_SYSTEM_TABLE_64 *)efi_efiboot_virtual_to_physmap_virtual(args->efiSystemTable);
1836 
1837 	assert(estp != 0);
1838 
1839 	// Verify signature of the system table
1840 	hdr_cksum = estp->Hdr.CRC32;
1841 	estp->Hdr.CRC32 = 0;
1842 	cksum = crc32(0L, estp, estp->Hdr.HeaderSize);
1843 	estp->Hdr.CRC32 = hdr_cksum;
1844 
1845 	if (cksum != hdr_cksum) {
1846 		DPRINTF("efi_get_cfgtbl_by_guid: EST CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
1847 		DPRINTF("Bad EFI system table checksum\n");
1848 		return 0;
1849 	}
1850 
1851 	/*
1852 	 * efiboot can (and will) change the address of ConfigurationTable (and each table's VendorTable address)
1853 	 * to a kernel-virtual address.  Reverse that to get the physical address, which we then use to get a
1854 	 * physmap-based virtual address.
1855 	 */
1856 	cfgTable = (EFI_CONFIGURATION_TABLE_64 *)efi_efiboot_virtual_to_physmap_virtual(estp->ConfigurationTable);
1857 
1858 	for (i = 0; i < estp->NumberOfTableEntries; i++) {
1859 		cfg_table_entp = (EFI_CONFIGURATION_TABLE_64 *)&cfgTable[i];
1860 
1861 		DPRINTF("EST: Comparing GUIDs for entry %d\n", i);
1862 		if (cfg_table_entp == 0) {
1863 			continue;
1864 		}
1865 
1866 		if (efi_compare_guids(&cfg_table_entp->VendorGuid, guidp) == true) {
1867 			DPRINTF("GUID match: returning %p\n", (void *)(uintptr_t)cfg_table_entp->VendorTable);
1868 			return efi_efiboot_virtual_to_physical(cfg_table_entp->VendorTable);
1869 		}
1870 	}
1871 
1872 	/* Not found */
1873 	return 0;
1874 }
1875 
1876 /*
1877  * Returns the physical address of the RSDP (either v1 or >=v2) or 0
1878  * if the RSDP could not be located.
1879  */
1880 uint64_t
efi_get_rsdp_physaddr(void)1881 efi_get_rsdp_physaddr(void)
1882 {
1883 	uint64_t rsdp_addr;
1884 #define ACPI_RSDP_GUID \
1885     { 0xeb9d2d30, 0x2d88, 0x11d3, {0x9a, 0x16, 0x0, 0x90, 0x27, 0x3f, 0xc1, 0x4d} }
1886 #define ACPI_20_RSDP_GUID \
1887     { 0x8868e871, 0xe4f1, 0x11d3, {0xbc, 0x22, 0x0, 0x80, 0xc7, 0x3c, 0x88, 0x81} }
1888 
1889 	static EFI_GUID EFI_RSDP_GUID_ACPI20 = ACPI_20_RSDP_GUID;
1890 	static EFI_GUID EFI_RSDP_GUID_ACPI10 = ACPI_RSDP_GUID;
1891 
1892 	if ((rsdp_addr = efi_get_cfgtbl_by_guid(&EFI_RSDP_GUID_ACPI20)) == 0) {
1893 		DPRINTF("RSDP ACPI 2.0 lookup failed.  Trying RSDP ACPI 1.0...\n");
1894 		rsdp_addr = efi_get_cfgtbl_by_guid(&EFI_RSDP_GUID_ACPI10);
1895 		if (rsdp_addr == 0) {
1896 			DPRINTF("RSDP ACPI 1.0 lookup failed also.\n");
1897 		}
1898 	}
1899 
1900 	return rsdp_addr;
1901 }
1902