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