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 <i386/postcode.h>
92 #include <i386/mp_desc.h>
93 #include <i386/misc_protos.h>
94 #include <i386/panic_notify.h>
95 #include <i386/thread.h>
96 #include <i386/trap.h>
97 #include <i386/machine_routines.h>
98 #include <i386/mp.h>
99 #include <i386/cpuid.h>
100 #include <i386/fpu.h>
101 #include <i386/machine_cpu.h>
102 #include <i386/pmap.h>
103 #if CONFIG_MTRR
104 #include <i386/mtrr.h>
105 #endif
106 #include <i386/ucode.h>
107 #include <i386/pmCPU.h>
108 #include <i386/panic_hooks.h>
109 #include <i386/lbr.h>
110
111 #include <architecture/i386/pio.h> /* inb() */
112 #include <pexpert/i386/boot.h>
113
114 #include <kdp/kdp_dyld.h>
115 #include <kdp/kdp_core.h>
116 #include <vm/pmap.h>
117 #include <vm/vm_map.h>
118 #include <vm/vm_kern.h>
119
120 #include <IOKit/IOBSD.h>
121 #include <IOKit/IOPlatformExpert.h>
122 #include <IOKit/IOHibernatePrivate.h>
123
124 #include <pexpert/i386/efi.h>
125
126 #include <kern/thread.h>
127 #include <kern/sched.h>
128 #include <mach-o/loader.h>
129 #include <mach-o/nlist.h>
130
131 #include <libkern/kernel_mach_header.h>
132 #include <libkern/OSKextLibPrivate.h>
133 #include <libkern/crc.h>
134
135 #if DEBUG || DEVELOPMENT
136 #define DPRINTF(x ...) kprintf(x)
137 #else
138 #define DPRINTF(x ...)
139 #endif
140
141 #ifndef ROUNDUP
142 #define ROUNDUP(a, b) (((a) + ((b) - 1)) & (~((b) - 1)))
143 #endif
144
145 #ifndef ROUNDDOWN
146 #define ROUNDDOWN(x, y) (((x)/(y))*(y))
147 #endif
148
149 static void machine_conf(void);
150 void panic_print_symbol_name(vm_address_t search);
151 void RecordPanicStackshot(void);
152
153 typedef enum paniclog_flush_type {
154 kPaniclogFlushBase = 1,/* Flush the initial log and paniclog header */
155 kPaniclogFlushStackshot = 2,/* Flush only the stackshot data, then flush the header */
156 kPaniclogFlushOtherLog = 3/* Flush the other log, then flush the header */
157 } paniclog_flush_type_t;
158
159 void paniclog_flush_internal(paniclog_flush_type_t variant);
160
161 extern const char version[];
162 extern char osversion[];
163 extern int max_poll_quanta;
164 extern unsigned int panic_is_inited;
165
166 /* #include <sys/proc.h> */
167 #define MAXCOMLEN 16
168 struct proc;
169 extern int proc_pid(struct proc *p);
170 extern void proc_name_kdp(struct proc *p, char * buf, int size);
171
172
173 /* Definitions for frame pointers */
174 #define FP_ALIGNMENT_MASK ((uint32_t)(0x3))
175 #define FP_LR_OFFSET ((uint32_t)4)
176 #define FP_LR_OFFSET64 ((uint32_t)8)
177 #define FP_MAX_NUM_TO_EVALUATE (50)
178
179 volatile int pbtcpu = -1;
180 hw_lock_data_t pbtlock; /* backtrace print lock */
181 uint32_t pbtcnt = 0;
182
183 volatile int panic_double_fault_cpu = -1;
184
185 #define PRINT_ARGS_FROM_STACK_FRAME 0
186
187 typedef struct _cframe_t {
188 struct _cframe_t *prev;
189 uintptr_t caller;
190 #if PRINT_ARGS_FROM_STACK_FRAME
191 unsigned args[0];
192 #endif
193 } cframe_t;
194
195 static unsigned commit_paniclog_to_nvram;
196 boolean_t coprocessor_paniclog_flush = FALSE;
197
198 struct kcdata_descriptor kc_panic_data;
199 static boolean_t begun_panic_stackshot = FALSE;
200 extern kern_return_t do_stackshot(void *);
201
202 extern void kdp_snapshot_preflight(int pid, void * tracebuf,
203 uint32_t tracebuf_size, uint64_t flags,
204 kcdata_descriptor_t data_p,
205 uint64_t since_timestamp, uint32_t pagetable_mask);
206 extern int kdp_stack_snapshot_bytes_traced(void);
207 extern int kdp_stack_snapshot_bytes_uncompressed(void);
208
209 extern void stackshot_memcpy(void *dst, const void *src, size_t len);
210 vm_offset_t panic_stackshot_buf = 0;
211 size_t panic_stackshot_buf_len = 0;
212
213 size_t panic_stackshot_len = 0;
214
215 boolean_t is_clock_configured = FALSE;
216
217 static struct lbr_data lbrs[MAX_CPUS];
218 static uint32_t lbr_stack_size;
219
220 /*
221 * Backtrace a single frame.
222 */
223 void
print_one_backtrace(pmap_t pmap,vm_offset_t topfp,const char * cur_marker,boolean_t is_64_bit)224 print_one_backtrace(pmap_t pmap, vm_offset_t topfp, const char *cur_marker,
225 boolean_t is_64_bit)
226 {
227 unsigned int i = 0;
228 addr64_t lr = 0;
229 addr64_t fp = topfp;
230 addr64_t fp_for_ppn = 0;
231 ppnum_t ppn = (ppnum_t)NULL;
232 bool dump_kernel_stack = (fp >= VM_MIN_KERNEL_ADDRESS);
233
234 do {
235 if ((fp == 0) || ((fp & FP_ALIGNMENT_MASK) != 0)) {
236 break;
237 }
238 if (dump_kernel_stack && ((fp < VM_MIN_KERNEL_ADDRESS) || (fp > VM_MAX_KERNEL_ADDRESS))) {
239 break;
240 }
241 if ((!dump_kernel_stack) && (fp >= VM_MIN_KERNEL_ADDRESS)) {
242 break;
243 }
244
245 /* Check to see if current address will result in a different
246 * ppn than previously computed (to avoid recomputation) via
247 * (addr) ^ fp_for_ppn) >> PAGE_SHIFT) */
248
249 if ((((fp + FP_LR_OFFSET) ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
250 ppn = pmap_find_phys(pmap, fp + FP_LR_OFFSET);
251 fp_for_ppn = fp + (is_64_bit ? FP_LR_OFFSET64 : FP_LR_OFFSET);
252 }
253 if (ppn != (ppnum_t)NULL) {
254 if (is_64_bit) {
255 lr = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET64) & PAGE_MASK));
256 } else {
257 lr = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | ((fp + FP_LR_OFFSET) & PAGE_MASK));
258 }
259 } else {
260 if (is_64_bit) {
261 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%016llx\n", cur_marker, fp + FP_LR_OFFSET64);
262 } else {
263 paniclog_append_noflush("%s\t Could not read LR from frame at 0x%08x\n", cur_marker, (uint32_t)(fp + FP_LR_OFFSET));
264 }
265 break;
266 }
267 if (((fp ^ fp_for_ppn) >> PAGE_SHIFT) != 0x0U) {
268 ppn = pmap_find_phys(pmap, fp);
269 fp_for_ppn = fp;
270 }
271 if (ppn != (ppnum_t)NULL) {
272 if (is_64_bit) {
273 fp = ml_phys_read_double_64(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
274 } else {
275 fp = ml_phys_read_word(((((vm_offset_t)ppn) << PAGE_SHIFT)) | (fp & PAGE_MASK));
276 }
277 } else {
278 if (is_64_bit) {
279 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%016llx\n", cur_marker, fp);
280 } else {
281 paniclog_append_noflush("%s\t Could not read FP from frame at 0x%08x\n", cur_marker, (uint32_t)fp);
282 }
283 break;
284 }
285 /*
286 * Counter 'i' may == FP_MAX_NUM_TO_EVALUATE when running one
287 * extra round to check whether we have all frames in order to
288 * indicate (in)complete backtrace below. This happens in a case
289 * where total frame count and FP_MAX_NUM_TO_EVALUATE are equal.
290 * Do not capture anything.
291 */
292 if (i < FP_MAX_NUM_TO_EVALUATE && lr) {
293 if (is_64_bit) {
294 paniclog_append_noflush("%s\t0x%016llx\n", cur_marker, lr);
295 } else {
296 paniclog_append_noflush("%s\t0x%08x\n", cur_marker, (uint32_t)lr);
297 }
298 }
299 } while ((++i <= FP_MAX_NUM_TO_EVALUATE) && (fp != topfp));
300
301 if (i > FP_MAX_NUM_TO_EVALUATE && fp != 0) {
302 paniclog_append_noflush("Backtrace continues...\n");
303 }
304 }
305 void
machine_startup(void)306 machine_startup(void)
307 {
308 int boot_arg;
309
310 #if 0
311 if (PE_get_hotkey( kPEControlKey )) {
312 halt_in_debugger = halt_in_debugger ? 0 : 1;
313 }
314 #endif
315
316 if (!PE_parse_boot_argn("nvram_paniclog", &commit_paniclog_to_nvram, sizeof(commit_paniclog_to_nvram))) {
317 commit_paniclog_to_nvram = 1;
318 }
319
320 /*
321 * Entering the debugger will put the CPUs into a "safe"
322 * power mode.
323 */
324 if (PE_parse_boot_argn("pmsafe_debug", &boot_arg, sizeof(boot_arg))) {
325 pmsafe_debug = boot_arg;
326 }
327
328 hw_lock_init(&pbtlock); /* initialize print backtrace lock */
329
330 if (PE_parse_boot_argn("yield", &boot_arg, sizeof(boot_arg))) {
331 sched_poll_yield_shift = boot_arg;
332 }
333
334 panic_notify_init();
335
336 machine_conf();
337
338 panic_hooks_init();
339
340 /*
341 * Start the system.
342 */
343 kernel_bootstrap();
344 /*NOTREACHED*/
345 }
346
347
348 static void
machine_conf(void)349 machine_conf(void)
350 {
351 machine_info.memory_size = (typeof(machine_info.memory_size))mem_size;
352 }
353
354 extern void *gPEEFIRuntimeServices;
355 extern void *gPEEFISystemTable;
356
357 static void
efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)358 efi_set_tables_64(EFI_SYSTEM_TABLE_64 * system_table)
359 {
360 EFI_RUNTIME_SERVICES_64 *runtime;
361 uint32_t hdr_cksum;
362 uint32_t cksum;
363
364 DPRINTF("Processing 64-bit EFI tables at %p\n", system_table);
365 do {
366 DPRINTF("Header:\n");
367 DPRINTF(" Signature: 0x%016llx\n", system_table->Hdr.Signature);
368 DPRINTF(" Revision: 0x%08x\n", system_table->Hdr.Revision);
369 DPRINTF(" HeaderSize: 0x%08x\n", system_table->Hdr.HeaderSize);
370 DPRINTF(" CRC32: 0x%08x\n", system_table->Hdr.CRC32);
371 DPRINTF("RuntimeServices: 0x%016llx\n", system_table->RuntimeServices);
372 if (system_table->Hdr.Signature != EFI_SYSTEM_TABLE_SIGNATURE) {
373 kprintf("Bad EFI system table signature\n");
374 break;
375 }
376 // Verify signature of the system table
377 hdr_cksum = system_table->Hdr.CRC32;
378 system_table->Hdr.CRC32 = 0;
379 cksum = crc32(0L, system_table, system_table->Hdr.HeaderSize);
380
381 DPRINTF("System table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
382 system_table->Hdr.CRC32 = hdr_cksum;
383 if (cksum != hdr_cksum) {
384 kprintf("Bad EFI system table checksum\n");
385 break;
386 }
387
388 gPEEFISystemTable = system_table;
389
390 if (system_table->RuntimeServices == 0) {
391 kprintf("No runtime table present\n");
392 break;
393 }
394 DPRINTF("RuntimeServices table at 0x%qx\n", system_table->RuntimeServices);
395 // 64-bit virtual address is OK for 64-bit EFI and 64/32-bit kernel.
396 runtime = (EFI_RUNTIME_SERVICES_64 *) (uintptr_t)system_table->RuntimeServices;
397 DPRINTF("Checking runtime services table %p\n", runtime);
398 if (runtime->Hdr.Signature != EFI_RUNTIME_SERVICES_SIGNATURE) {
399 kprintf("Bad EFI runtime table signature\n");
400 break;
401 }
402
403 // Verify signature of runtime services table
404 hdr_cksum = runtime->Hdr.CRC32;
405 runtime->Hdr.CRC32 = 0;
406 cksum = crc32(0L, runtime, runtime->Hdr.HeaderSize);
407
408 DPRINTF("Runtime table calculated CRC32 = 0x%x, header = 0x%x\n", cksum, hdr_cksum);
409 runtime->Hdr.CRC32 = hdr_cksum;
410 if (cksum != hdr_cksum) {
411 kprintf("Bad EFI runtime table checksum\n");
412 break;
413 }
414
415 gPEEFIRuntimeServices = runtime;
416 } while (FALSE);
417 }
418
419 /* Map in EFI runtime areas. */
420 static void
efi_init(void)421 efi_init(void)
422 {
423 boot_args *args = (boot_args *)PE_state.bootArgs;
424
425 kprintf("Initializing EFI runtime services\n");
426
427 do {
428 vm_offset_t vm_size, vm_addr;
429 vm_map_offset_t phys_addr;
430 EfiMemoryRange *mptr;
431 unsigned int msize, mcount;
432 unsigned int i;
433
434 msize = args->MemoryMapDescriptorSize;
435 mcount = args->MemoryMapSize / msize;
436
437 DPRINTF("efi_init() kernel base: 0x%x size: 0x%x\n",
438 args->kaddr, args->ksize);
439 DPRINTF(" efiSystemTable physical: 0x%x virtual: %p\n",
440 args->efiSystemTable,
441 (void *) ml_static_ptovirt(args->efiSystemTable));
442 DPRINTF(" efiRuntimeServicesPageStart: 0x%x\n",
443 args->efiRuntimeServicesPageStart);
444 DPRINTF(" efiRuntimeServicesPageCount: 0x%x\n",
445 args->efiRuntimeServicesPageCount);
446 DPRINTF(" efiRuntimeServicesVirtualPageStart: 0x%016llx\n",
447 args->efiRuntimeServicesVirtualPageStart);
448 mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
449 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
450 if (((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME)) {
451 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
452 vm_addr = (vm_offset_t) mptr->VirtualStart;
453 /* For K64 on EFI32, shadow-map into high KVA */
454 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
455 vm_addr |= VM_MIN_KERNEL_ADDRESS;
456 }
457 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
458 DPRINTF(" Type: %x phys: %p EFIv: %p kv: %p size: %p\n",
459 mptr->Type,
460 (void *) (uintptr_t) phys_addr,
461 (void *) (uintptr_t) mptr->VirtualStart,
462 (void *) vm_addr,
463 (void *) vm_size);
464 pmap_map_bd(vm_addr, phys_addr, phys_addr + round_page(vm_size),
465 (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
466 (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT);
467 }
468 }
469
470 if (args->Version != kBootArgsVersion2) {
471 panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
472 }
473
474 DPRINTF("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
475 if (args->efiMode == kBootArgsEfiMode64) {
476 efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
477 } else {
478 panic("Unsupported 32-bit EFI system table!");
479 }
480 } while (FALSE);
481
482 return;
483 }
484
485 /* Returns TRUE if a page belongs to the EFI Runtime Services (code or data) */
486 boolean_t
bootloader_valid_page(ppnum_t ppn)487 bootloader_valid_page(ppnum_t ppn)
488 {
489 boot_args *args = (boot_args *)PE_state.bootArgs;
490 ppnum_t pstart = args->efiRuntimeServicesPageStart;
491 ppnum_t pend = pstart + args->efiRuntimeServicesPageCount;
492
493 return pstart <= ppn && ppn < pend;
494 }
495
496 /* Remap EFI runtime areas. */
497 void
hibernate_newruntime_map(void * map,vm_size_t map_size,uint32_t system_table_offset)498 hibernate_newruntime_map(void * map, vm_size_t map_size, uint32_t system_table_offset)
499 {
500 boot_args *args = (boot_args *)PE_state.bootArgs;
501
502 kprintf("Reinitializing EFI runtime services\n");
503
504 do {
505 vm_offset_t vm_size, vm_addr;
506 vm_map_offset_t phys_addr;
507 EfiMemoryRange *mptr;
508 unsigned int msize, mcount;
509 unsigned int i;
510
511 gPEEFISystemTable = 0;
512 gPEEFIRuntimeServices = 0;
513
514 system_table_offset += ptoa_32(args->efiRuntimeServicesPageStart);
515
516 kprintf("Old system table 0x%x, new 0x%x\n",
517 (uint32_t)args->efiSystemTable, system_table_offset);
518
519 args->efiSystemTable = system_table_offset;
520
521 kprintf("Old map:\n");
522 msize = args->MemoryMapDescriptorSize;
523 mcount = args->MemoryMapSize / msize;
524 mptr = (EfiMemoryRange *)ml_static_ptovirt(args->MemoryMap);
525 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
526 if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
527 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
528 vm_addr = (vm_offset_t) mptr->VirtualStart;
529 /* K64 on EFI32 */
530 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
531 vm_addr |= VM_MIN_KERNEL_ADDRESS;
532 }
533 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
534
535 kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
536 }
537 }
538
539 pmap_remove(kernel_pmap, i386_ptob(args->efiRuntimeServicesPageStart),
540 i386_ptob(args->efiRuntimeServicesPageStart + args->efiRuntimeServicesPageCount));
541
542 kprintf("New map:\n");
543 msize = args->MemoryMapDescriptorSize;
544 mcount = (unsigned int)(map_size / msize);
545 mptr = map;
546 for (i = 0; i < mcount; i++, mptr = (EfiMemoryRange *)(((vm_offset_t)mptr) + msize)) {
547 if ((mptr->Attribute & EFI_MEMORY_RUNTIME) == EFI_MEMORY_RUNTIME) {
548 vm_size = (vm_offset_t)i386_ptob((uint32_t)mptr->NumberOfPages);
549 vm_addr = (vm_offset_t) mptr->VirtualStart;
550 if (vm_addr < VM_MIN_KERNEL_ADDRESS) {
551 vm_addr |= VM_MIN_KERNEL_ADDRESS;
552 }
553 phys_addr = (vm_map_offset_t) mptr->PhysicalStart;
554
555 kprintf("mapping[%u] %qx @ %lx, %llu\n", mptr->Type, phys_addr, (unsigned long)vm_addr, mptr->NumberOfPages);
556
557 pmap_map(vm_addr, phys_addr, phys_addr + round_page(vm_size),
558 (mptr->Type == kEfiRuntimeServicesCode) ? VM_PROT_READ | VM_PROT_EXECUTE : VM_PROT_READ | VM_PROT_WRITE,
559 (mptr->Type == EfiMemoryMappedIO) ? VM_WIMG_IO : VM_WIMG_USE_DEFAULT);
560 }
561 }
562
563 if (args->Version != kBootArgsVersion2) {
564 panic("Incompatible boot args version %d revision %d", args->Version, args->Revision);
565 }
566
567 kprintf("Boot args version %d revision %d mode %d\n", args->Version, args->Revision, args->efiMode);
568 if (args->efiMode == kBootArgsEfiMode64) {
569 efi_set_tables_64((EFI_SYSTEM_TABLE_64 *) ml_static_ptovirt(args->efiSystemTable));
570 } else {
571 panic("Unsupported 32-bit EFI system table!");
572 }
573 } while (FALSE);
574
575 kprintf("Done reinitializing EFI runtime services\n");
576
577 return;
578 }
579
580 /*
581 * Find devices. The system is alive.
582 */
583 void
machine_init(void)584 machine_init(void)
585 {
586 /* Now with VM up, switch to dynamically allocated cpu data */
587 cpu_data_realloc();
588
589 /* Ensure panic buffer is initialized. */
590 debug_log_init();
591
592 /*
593 * Display CPU identification
594 */
595 cpuid_cpu_display("CPU identification");
596 cpuid_feature_display("CPU features");
597 cpuid_extfeature_display("CPU extended features");
598
599 /*
600 * Initialize EFI runtime services.
601 */
602 efi_init();
603
604 smp_init();
605
606 /*
607 * Set up to use floating point.
608 */
609 init_fpu();
610
611 /*
612 * Configure clock devices.
613 */
614 clock_config();
615 is_clock_configured = TRUE;
616
617 #if CONFIG_MTRR
618 /*
619 * Initialize MTRR from boot processor.
620 */
621 mtrr_init();
622
623 /*
624 * Set up PAT for boot processor.
625 */
626 pat_init();
627 #endif
628
629 /*
630 * Free lowmem pages and complete other setup
631 */
632 pmap_lowmem_finalize();
633 }
634
635 /*
636 * Halt a cpu.
637 */
638 void
halt_cpu(void)639 halt_cpu(void)
640 {
641 halt_all_cpus(FALSE);
642 }
643
644 int reset_mem_on_reboot = 1;
645
646 /*
647 * Halt the system or reboot.
648 */
649 __attribute__((noreturn))
650 void
halt_all_cpus(boolean_t reboot)651 halt_all_cpus(boolean_t reboot)
652 {
653 if (reboot) {
654 printf("MACH Reboot\n");
655 PEHaltRestart( kPERestartCPU );
656 } else {
657 printf("CPU halted\n");
658 PEHaltRestart( kPEHaltCPU );
659 }
660 while (1) {
661 ;
662 }
663 }
664
665 /* For use with the MP rendezvous mechanism
666 */
667
668 uint64_t panic_restart_timeout = ~(0ULL);
669
670 #define PANIC_RESTART_TIMEOUT (3ULL * NSEC_PER_SEC)
671
672 /*
673 * We should always return from this function with the other log offset
674 * set in the panic_info structure.
675 */
676 void
RecordPanicStackshot()677 RecordPanicStackshot()
678 {
679 int err = 0;
680 size_t bytes_traced = 0, bytes_uncompressed = 0, bytes_used = 0, bytes_remaining = 0;
681 char *stackshot_begin_loc = NULL;
682
683 /* Don't re-enter this code if we panic here */
684 if (begun_panic_stackshot) {
685 if (panic_info->mph_other_log_offset == 0) {
686 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
687 }
688 return;
689 }
690 begun_panic_stackshot = TRUE;
691
692 /* The panic log length should have been set before we came to capture a stackshot */
693 if (panic_info->mph_panic_log_len == 0) {
694 kdb_printf("Found zero length panic log, skipping capturing panic stackshot\n");
695 if (panic_info->mph_other_log_offset == 0) {
696 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
697 }
698 return;
699 }
700
701 if (stackshot_active()) {
702 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_NESTED;
703 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
704 kdb_printf("Panicked during stackshot, skipping panic stackshot\n");
705 return;
706 }
707
708 /* Try to capture an in memory panic_stackshot */
709 if (extended_debug_log_enabled) {
710 /* On coprocessor systems we write this into the extended debug log */
711 stackshot_begin_loc = debug_buf_ptr;
712 bytes_remaining = debug_buf_size - (unsigned int)((uintptr_t)stackshot_begin_loc - (uintptr_t)debug_buf_base);
713 } else if (panic_stackshot_buf != 0) {
714 /* On other systems we use the panic stackshot_buf */
715 stackshot_begin_loc = (char *) panic_stackshot_buf;
716 bytes_remaining = panic_stackshot_buf_len;
717 } else {
718 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
719 return;
720 }
721
722
723 err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
724 KCDATA_BUFFER_BEGIN_COMPRESSED, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
725 if (err != KERN_SUCCESS) {
726 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
727 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
728 kdb_printf("Failed to initialize kcdata buffer for in-memory panic stackshot, skipping ...\n");
729 return;
730 }
731
732 uint64_t stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_SAVE_LOADINFO | STACKSHOT_KCDATA_FORMAT |
733 STACKSHOT_ENABLE_BT_FAULTING | STACKSHOT_ENABLE_UUID_FAULTING | STACKSHOT_FROM_PANIC | STACKSHOT_DO_COMPRESS |
734 STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_DISABLE_LATENCY_INFO | STACKSHOT_GET_DQ);
735
736 err = kcdata_init_compress(&kc_panic_data, KCDATA_BUFFER_BEGIN_STACKSHOT, stackshot_memcpy, KCDCT_ZLIB);
737 if (err != KERN_SUCCESS) {
738 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_COMPRESS;
739 stackshot_flags &= ~STACKSHOT_DO_COMPRESS;
740 }
741
742 #if DEVELOPMENT
743 /*
744 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
745 * panic stackshots from corefiles.
746 */
747 stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
748 #endif
749
750 kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
751 err = do_stackshot(NULL);
752 bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
753 bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
754 bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
755
756 if ((err != KERN_SUCCESS) && (bytes_used > 0)) {
757 /*
758 * We ran out of space while trying to capture a stackshot, try again without user frames.
759 * It's not safe to log from here (in case we're writing in the middle of the debug buffer on coprocessor systems)
760 * but append a flag to the panic flags.
761 */
762 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_KERNEL_ONLY;
763 panic_stackshot_reset_state();
764
765 /* Erase the stackshot data (this region is pre-populated with the NULL character) */
766 memset(stackshot_begin_loc, '\0', bytes_used);
767
768 err = kcdata_memory_static_init(&kc_panic_data, (mach_vm_address_t)stackshot_begin_loc,
769 KCDATA_BUFFER_BEGIN_STACKSHOT, (unsigned int) bytes_remaining, KCFLAG_USE_MEMCOPY);
770 if (err != KERN_SUCCESS) {
771 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
772 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
773 kdb_printf("Failed to re-initialize kcdata buffer for kernel only in-memory panic stackshot, skipping ...\n");
774 return;
775 }
776
777 stackshot_flags = (STACKSHOT_SAVE_KEXT_LOADINFO | STACKSHOT_KCDATA_FORMAT | STACKSHOT_FROM_PANIC | STACKSHOT_DISABLE_LATENCY_INFO |
778 STACKSHOT_NO_IO_STATS | STACKSHOT_THREAD_WAITINFO | STACKSHOT_ACTIVE_KERNEL_THREADS_ONLY | STACKSHOT_GET_DQ);
779 #if DEVELOPMENT
780 /*
781 * Include the shared cache layout in panic stackshots on DEVELOPMENT kernels so that we can symbolicate
782 * panic stackshots from corefiles.
783 */
784 stackshot_flags |= STACKSHOT_COLLECT_SHAREDCACHE_LAYOUT;
785 #endif
786
787 kdp_snapshot_preflight(-1, (void *) stackshot_begin_loc, (uint32_t) bytes_remaining, stackshot_flags, &kc_panic_data, 0, 0);
788 err = do_stackshot(NULL);
789 bytes_traced = (size_t) kdp_stack_snapshot_bytes_traced();
790 bytes_uncompressed = (size_t) kdp_stack_snapshot_bytes_uncompressed();
791 bytes_used = (size_t) kcdata_memory_get_used_bytes(&kc_panic_data);
792 }
793
794 if (err == KERN_SUCCESS) {
795 if (extended_debug_log_enabled) {
796 debug_buf_ptr += bytes_traced;
797 }
798 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_SUCCEEDED;
799
800 /* On other systems this is not in the debug buffer itself, it's in a separate buffer allocated at boot. */
801 if (extended_debug_log_enabled) {
802 panic_info->mph_stackshot_offset = PE_get_offset_into_panic_region(stackshot_begin_loc);
803 panic_info->mph_stackshot_len = (uint32_t) bytes_traced;
804 } else {
805 panic_info->mph_stackshot_offset = panic_info->mph_stackshot_len = 0;
806 }
807
808 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
809 if (stackshot_flags & STACKSHOT_DO_COMPRESS) {
810 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_DATA_COMPRESSED;
811 kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu (Uncompressed %zu) **\n", bytes_traced, bytes_uncompressed);
812 } else {
813 kdb_printf("\n** In Memory Panic Stackshot Succeeded ** Bytes Traced %zu **\n", bytes_traced);
814 }
815
816 /* Used by the code that writes the buffer to disk */
817 panic_stackshot_buf = (vm_offset_t) stackshot_begin_loc;
818 panic_stackshot_len = bytes_traced;
819
820 if (!extended_debug_log_enabled && (gIOPolledCoreFileMode == kIOPolledCoreFileModeStackshot)) {
821 /* System configured to write panic stackshot to disk */
822 kern_dump(KERN_DUMP_STACKSHOT_DISK);
823 }
824 } else {
825 if (bytes_used > 0) {
826 /* Erase the stackshot data (this region is pre-populated with the NULL character) */
827 memset(stackshot_begin_loc, '\0', bytes_used);
828 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_INCOMPLETE;
829
830 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
831 kdb_printf("\n** In Memory Panic Stackshot Incomplete ** Bytes Filled %zu ** Err %d\n", bytes_used, err);
832 } else {
833 bzero(stackshot_begin_loc, bytes_used);
834 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_STACKSHOT_FAILED_ERROR;
835
836 panic_info->mph_other_log_offset = PE_get_offset_into_panic_region(debug_buf_ptr);
837 kdb_printf("\n** In Memory Panic Stackshot Failed ** Bytes Traced %zu, err %d\n", bytes_traced, err);
838 }
839 }
840
841 return;
842 }
843
844 void
SavePanicInfo(__unused const char * message,void * panic_data,uint64_t panic_options)845 SavePanicInfo(
846 __unused const char *message, void *panic_data, uint64_t panic_options)
847 {
848 void *stackptr = NULL;
849 thread_t thread_to_trace = (thread_t) panic_data;
850 cframe_t synthetic_stack_frame = { };
851 char *debugger_msg = NULL;
852 int cn = cpu_number();
853
854 /*
855 * Issue an I/O port read if one has been requested - this is an event logic
856 * analyzers can use as a trigger point.
857 */
858 panic_notify();
859
860 /* Obtain frame pointer for stack to trace */
861 if (panic_options & DEBUGGER_INTERNAL_OPTION_THREAD_BACKTRACE) {
862 if (!mp_kdp_all_cpus_halted()) {
863 debugger_msg = "Backtracing panicked thread because failed to halt all CPUs\n";
864 } else if (thread_to_trace == THREAD_NULL) {
865 debugger_msg = "Backtracing panicked thread because no thread pointer provided\n";
866 } else if (kvtophys((vm_offset_t)thread_to_trace) == 0ULL) {
867 debugger_msg = "Backtracing panicked thread because unable to access specified thread\n";
868 } else if (thread_to_trace->kernel_stack == 0) {
869 debugger_msg = "Backtracing panicked thread because kernel_stack is NULL for specified thread\n";
870 } else if (kvtophys(STACK_IKS(thread_to_trace->kernel_stack) == 0ULL)) {
871 debugger_msg = "Backtracing panicked thread because unable to access kernel_stack for specified thread\n";
872 } else {
873 debugger_msg = "Backtracing specified thread\n";
874 /* We construct a synthetic stack frame so we can include the current instruction pointer */
875 synthetic_stack_frame.prev = (cframe_t *)STACK_IKS(thread_to_trace->kernel_stack)->k_rbp;
876 synthetic_stack_frame.caller = (uintptr_t) STACK_IKS(thread_to_trace->kernel_stack)->k_rip;
877 stackptr = (void *) &synthetic_stack_frame;
878 }
879 }
880
881 if (stackptr == NULL) {
882 __asm__ volatile ("movq %%rbp, %0" : "=m" (stackptr));
883 }
884
885 /* Print backtrace - callee is internally synchronized */
886 if (panic_options & DEBUGGER_OPTION_INITPROC_PANIC) {
887 /* Special handling of launchd died panics */
888 print_launchd_info();
889 } else {
890 panic_i386_backtrace(stackptr, ((panic_double_fault_cpu == cn) ? 80 : 48), debugger_msg, FALSE, NULL);
891 }
892
893 if (panic_options & DEBUGGER_OPTION_COPROC_INITIATED_PANIC) {
894 panic_info->mph_panic_flags |= MACOS_PANIC_HEADER_FLAG_COPROC_INITIATED_PANIC;
895 }
896
897 #if MACH_KDP
898 /*
899 * If this panic is due to a PTE corruption event, use the kdp cross-cpu calling machinery to ask
900 * each CPU to dump their backtraces before proceeding. This mechanism was preferred to adding new
901 * synchronization operations in NMIInterruptHandler and the normal panic flow; this mechanism allows
902 * each CPU to add their backtraces after all other primary panic output is complete while not adding
903 * additional complexity to the common panic path.
904 */
905 if (NMI_panic_reason == PTE_CORRUPTION) {
906 for (uint64_t cpu = 0; cpu < real_ncpus; cpu++) {
907 if (cpu == cpu_number() || !cpu_is_running(cpu)) {
908 continue;
909 }
910 (void) kdp_x86_xcpu_invoke(cpu, NMI_pte_corruption_callback, NULL, NULL, NSEC_PER_SEC /* 1 second timeout */);
911 }
912 }
913 #else
914 #error NMI PTE Corruption panic flow requires KDP
915 #endif
916
917 if (PE_get_offset_into_panic_region(debug_buf_ptr) < panic_info->mph_panic_log_offset) {
918 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",
919 debug_buf_ptr, panic_info, panic_info->mph_panic_log_offset);
920 panic_info->mph_panic_log_len = 0;
921 } else {
922 panic_info->mph_panic_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_panic_log_offset;
923 }
924
925 /* Flush the panic log */
926 paniclog_flush_internal(kPaniclogFlushBase);
927
928 /* Try to take a panic stackshot */
929 RecordPanicStackshot();
930
931 /*
932 * Flush the panic log again with the stackshot or any relevant logging
933 * from when we tried to capture it.
934 */
935 paniclog_flush_internal(kPaniclogFlushStackshot);
936 }
937
938 void
paniclog_flush_internal(paniclog_flush_type_t variant)939 paniclog_flush_internal(paniclog_flush_type_t variant)
940 {
941 /* Update the other log offset if we've opened the other log */
942 if (panic_info->mph_other_log_offset != 0) {
943 panic_info->mph_other_log_len = PE_get_offset_into_panic_region(debug_buf_ptr) - panic_info->mph_other_log_offset;
944 }
945
946 /*
947 * If we've detected that we're on a co-processor system, we flush the panic log via the kPEPanicSync
948 * panic callbacks, otherwise we flush via nvram (unless that has been disabled).
949 */
950 if (coprocessor_paniclog_flush) {
951 uint32_t overall_buffer_size = debug_buf_size;
952 uint32_t size_to_flush = 0, offset_to_flush = 0;
953 if (extended_debug_log_enabled) {
954 /*
955 * debug_buf_size for the extended log does not include the length of the header.
956 * There may be some extra data at the end of the 'basic' log that wouldn't get flushed
957 * for the non-extended case (this is a concession we make to not shrink the paniclog data
958 * for non-coprocessor systems that only use the basic log).
959 */
960 overall_buffer_size = debug_buf_size + sizeof(struct macos_panic_header);
961 }
962
963 /* Update the CRC */
964 panic_info->mph_crc = crc32(0L, &panic_info->mph_version, (overall_buffer_size - offsetof(struct macos_panic_header, mph_version)));
965
966 if (variant == kPaniclogFlushBase) {
967 /* Flush the header and base panic log. */
968 kprintf("Flushing base panic log\n");
969 size_to_flush = ROUNDUP((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
970 offset_to_flush = 0;
971 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
972 } else if ((variant == kPaniclogFlushStackshot) || (variant == kPaniclogFlushOtherLog)) {
973 if (variant == kPaniclogFlushStackshot) {
974 /*
975 * We flush the stackshot before flushing the updated header because the stackshot
976 * can take a while to flush. We want the paniclog header to be as consistent as possible even
977 * if the stackshot isn't flushed completely. Flush starting from the end of the panic log.
978 */
979 kprintf("Flushing panic log stackshot\n");
980 offset_to_flush = ROUNDDOWN((panic_info->mph_panic_log_offset + panic_info->mph_panic_log_len), PANIC_FLUSH_BOUNDARY);
981 size_to_flush = ROUNDUP((panic_info->mph_stackshot_len + (panic_info->mph_stackshot_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
982 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
983 }
984
985 /* Flush the other log -- everything after the stackshot */
986 kprintf("Flushing panic 'other' log\n");
987 offset_to_flush = ROUNDDOWN((panic_info->mph_stackshot_offset + panic_info->mph_stackshot_len), PANIC_FLUSH_BOUNDARY);
988 size_to_flush = ROUNDUP((panic_info->mph_other_log_len + (panic_info->mph_other_log_offset - offset_to_flush)), PANIC_FLUSH_BOUNDARY);
989 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
990
991 /* Flush the header -- everything before the paniclog */
992 kprintf("Flushing panic log header\n");
993 size_to_flush = ROUNDUP(panic_info->mph_panic_log_offset, PANIC_FLUSH_BOUNDARY);
994 offset_to_flush = 0;
995 PESavePanicInfoAction(panic_info, offset_to_flush, size_to_flush);
996 }
997 } else if (commit_paniclog_to_nvram) {
998 assert(debug_buf_size != 0);
999 unsigned int bufpos;
1000 unsigned long pi_size = 0;
1001 uintptr_t cr0;
1002
1003 debug_putc(0);
1004
1005 /*
1006 * Now call the compressor
1007 * XXX Consider using the WKdm compressor in the
1008 * future, rather than just packing - would need to
1009 * be co-ordinated with crashreporter, which decodes
1010 * this post-restart. The compressor should be
1011 * capable of in-place compression.
1012 *
1013 * Don't include the macOS panic header (for co-processor systems only)
1014 */
1015 bufpos = packA(debug_buf_base, (unsigned int) (debug_buf_ptr - debug_buf_base),
1016 debug_buf_size);
1017 /*
1018 * If compression was successful, use the compressed length
1019 */
1020 pi_size = bufpos ? bufpos : (unsigned) (debug_buf_ptr - debug_buf_base);
1021
1022 /*
1023 * The following sequence is a workaround for:
1024 * <rdar://problem/5915669> SnowLeopard10A67: AppleEFINVRAM should not invoke
1025 * any routines that use floating point (MMX in this case) when saving panic
1026 * logs to nvram/flash.
1027 */
1028 cr0 = get_cr0();
1029 clear_ts();
1030
1031 /*
1032 * Save panic log to non-volatile store
1033 * Panic info handler must truncate data that is
1034 * too long for this platform.
1035 * This call must save data synchronously,
1036 * since we can subsequently halt the system.
1037 */
1038 kprintf("Attempting to commit panic log to NVRAM\n");
1039 pi_size = PESavePanicInfo((unsigned char *)debug_buf_base,
1040 (uint32_t)pi_size );
1041 set_cr0(cr0);
1042
1043 /*
1044 * Uncompress in-place, to permit examination of
1045 * the panic log by debuggers.
1046 */
1047 if (bufpos) {
1048 unpackA(debug_buf_base, bufpos);
1049 }
1050 }
1051 }
1052
1053 void
paniclog_flush()1054 paniclog_flush()
1055 {
1056 /* Called outside of this file to update logging appended to the "other" log */
1057 paniclog_flush_internal(kPaniclogFlushOtherLog);
1058 return;
1059 }
1060
1061 char *
machine_boot_info(char * buf,__unused vm_size_t size)1062 machine_boot_info(char *buf, __unused vm_size_t size)
1063 {
1064 *buf = '\0';
1065 return buf;
1066 }
1067
1068 /* Routines for address - symbol translation. Not called unless the "keepsyms"
1069 * boot-arg is supplied.
1070 */
1071
1072 static int
panic_print_macho_symbol_name(kernel_mach_header_t * mh,vm_address_t search,const char * module_name)1073 panic_print_macho_symbol_name(kernel_mach_header_t *mh, vm_address_t search, const char *module_name)
1074 {
1075 kernel_nlist_t *sym = NULL;
1076 struct load_command *cmd;
1077 kernel_segment_command_t *orig_ts = NULL, *orig_le = NULL;
1078 struct symtab_command *orig_st = NULL;
1079 unsigned int i;
1080 char *strings, *bestsym = NULL;
1081 vm_address_t bestaddr = 0, diff, curdiff;
1082
1083 /* Assume that if it's loaded and linked into the kernel, it's a valid Mach-O */
1084
1085 cmd = (struct load_command *) &mh[1];
1086 for (i = 0; i < mh->ncmds; i++) {
1087 if (cmd->cmd == LC_SEGMENT_KERNEL) {
1088 kernel_segment_command_t *orig_sg = (kernel_segment_command_t *) cmd;
1089
1090 if (strncmp(SEG_TEXT, orig_sg->segname,
1091 sizeof(orig_sg->segname)) == 0) {
1092 orig_ts = orig_sg;
1093 } else if (strncmp(SEG_LINKEDIT, orig_sg->segname,
1094 sizeof(orig_sg->segname)) == 0) {
1095 orig_le = orig_sg;
1096 } else if (strncmp("", orig_sg->segname,
1097 sizeof(orig_sg->segname)) == 0) {
1098 orig_ts = orig_sg; /* pre-Lion i386 kexts have a single unnamed segment */
1099 }
1100 } else if (cmd->cmd == LC_SYMTAB) {
1101 orig_st = (struct symtab_command *) cmd;
1102 }
1103
1104 cmd = (struct load_command *) ((uintptr_t) cmd + cmd->cmdsize);
1105 }
1106
1107 if ((orig_ts == NULL) || (orig_st == NULL) || (orig_le == NULL)) {
1108 return 0;
1109 }
1110
1111 if ((search < orig_ts->vmaddr) ||
1112 (search >= orig_ts->vmaddr + orig_ts->vmsize)) {
1113 /* search out of range for this mach header */
1114 return 0;
1115 }
1116
1117 sym = (kernel_nlist_t *)(uintptr_t)(orig_le->vmaddr + orig_st->symoff - orig_le->fileoff);
1118 strings = (char *)(uintptr_t)(orig_le->vmaddr + orig_st->stroff - orig_le->fileoff);
1119 diff = search;
1120
1121 for (i = 0; i < orig_st->nsyms; i++) {
1122 if (sym[i].n_type & N_STAB) {
1123 continue;
1124 }
1125
1126 if (sym[i].n_value <= search) {
1127 curdiff = search - (vm_address_t)sym[i].n_value;
1128 if (curdiff < diff) {
1129 diff = curdiff;
1130 bestaddr = sym[i].n_value;
1131 bestsym = strings + sym[i].n_un.n_strx;
1132 }
1133 }
1134 }
1135
1136 if (bestsym != NULL) {
1137 if (diff != 0) {
1138 paniclog_append_noflush("%s : %s + 0x%lx", module_name, bestsym, (unsigned long)diff);
1139 } else {
1140 paniclog_append_noflush("%s : %s", module_name, bestsym);
1141 }
1142 return 1;
1143 }
1144 return 0;
1145 }
1146
1147 static void
panic_display_uptime(void)1148 panic_display_uptime(void)
1149 {
1150 uint64_t uptime;
1151 absolutetime_to_nanoseconds(mach_absolute_time(), &uptime);
1152
1153 paniclog_append_noflush("\nSystem uptime in nanoseconds: %llu\n", uptime);
1154 }
1155
1156 extern uint32_t gIOHibernateCount;
1157
1158 static void
panic_display_hib_count(void)1159 panic_display_hib_count(void)
1160 {
1161 paniclog_append_noflush("Hibernation exit count: %u\n", gIOHibernateCount);
1162 }
1163
1164 extern AbsoluteTime gIOLastSleepAbsTime;
1165 extern AbsoluteTime gIOLastWakeAbsTime;
1166 extern uint64_t gAcpiLastSleepTscBase;
1167 extern uint64_t gAcpiLastSleepNanoBase;
1168 extern uint64_t gAcpiLastWakeTscBase;
1169 extern uint64_t gAcpiLastWakeNanoBase;
1170 extern boolean_t is_clock_configured;
1171
1172 static void
panic_display_times(void)1173 panic_display_times(void)
1174 {
1175 if (!is_clock_configured) {
1176 paniclog_append_noflush("Warning: clock is not configured. Can't get time\n");
1177 return;
1178 }
1179
1180 paniclog_append_noflush("Last Sleep: absolute base_tsc base_nano\n");
1181 paniclog_append_noflush(" Uptime : 0x%016llx\n", mach_absolute_time());
1182 paniclog_append_noflush(" Sleep : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastSleepAbsTime, gAcpiLastSleepTscBase, gAcpiLastSleepNanoBase);
1183 paniclog_append_noflush(" Wake : 0x%016llx 0x%016llx 0x%016llx\n", gIOLastWakeAbsTime, gAcpiLastWakeTscBase, gAcpiLastWakeNanoBase);
1184 }
1185
1186 static void
panic_display_disk_errors(void)1187 panic_display_disk_errors(void)
1188 {
1189 if (panic_disk_error_description[0]) {
1190 panic_disk_error_description[panic_disk_error_description_size - 1] = '\0';
1191 paniclog_append_noflush("Root disk errors: \"%s\"\n", panic_disk_error_description);
1192 }
1193 }
1194
1195 static void
panic_display_shutdown_status(void)1196 panic_display_shutdown_status(void)
1197 {
1198 #if defined(__i386__) || defined(__x86_64__)
1199 paniclog_append_noflush("System shutdown begun: %s\n", IOPMRootDomainGetWillShutdown() ? "YES" : "NO");
1200 if (gIOPolledCoreFileMode == kIOPolledCoreFileModeNotInitialized) {
1201 paniclog_append_noflush("Panic diags file unavailable, panic occurred prior to initialization\n");
1202 } else if (gIOPolledCoreFileMode != kIOPolledCoreFileModeDisabled) {
1203 /*
1204 * If we haven't marked the corefile as explicitly disabled, and we've made it past initialization, then we know the current
1205 * system was configured to use disk based diagnostics at some point.
1206 */
1207 paniclog_append_noflush("Panic diags file available: %s (0x%x)\n", (gIOPolledCoreFileMode != kIOPolledCoreFileModeClosed) ? "YES" : "NO", kdp_polled_corefile_error());
1208 }
1209 #endif
1210 }
1211
1212 extern const char version[];
1213 extern char osversion[];
1214
1215 static volatile uint32_t config_displayed = 0;
1216
1217 static void
panic_display_system_configuration(boolean_t launchd_exit)1218 panic_display_system_configuration(boolean_t launchd_exit)
1219 {
1220 if (!launchd_exit) {
1221 panic_display_process_name();
1222 }
1223 if (OSCompareAndSwap(0, 1, &config_displayed)) {
1224 char buf[256];
1225 if (!launchd_exit && strlcpy(buf, PE_boot_args(), sizeof(buf))) {
1226 paniclog_append_noflush("Boot args: %s\n", buf);
1227 }
1228 paniclog_append_noflush("\nMac OS version:\n%s\n",
1229 (osversion[0] != 0) ? osversion : "Not yet set");
1230 paniclog_append_noflush("\nKernel version:\n%s\n", version);
1231 panic_display_kernel_uuid();
1232 if (!launchd_exit) {
1233 panic_display_kernel_aslr();
1234 panic_display_hibb();
1235 panic_display_pal_info();
1236 }
1237 panic_display_model_name();
1238 panic_display_disk_errors();
1239 panic_display_shutdown_status();
1240 if (!launchd_exit) {
1241 panic_display_hib_count();
1242 panic_display_uptime();
1243 panic_display_times();
1244 panic_display_zalloc();
1245 kext_dump_panic_lists(&paniclog_append_noflush);
1246 }
1247 }
1248 }
1249
1250 extern kmod_info_t * kmod; /* the list of modules */
1251
1252 static void
panic_print_kmod_symbol_name(vm_address_t search)1253 panic_print_kmod_symbol_name(vm_address_t search)
1254 {
1255 u_int i;
1256
1257 if (gLoadedKextSummaries == NULL) {
1258 return;
1259 }
1260 for (i = 0; i < gLoadedKextSummaries->numSummaries; ++i) {
1261 OSKextLoadedKextSummary *summary = gLoadedKextSummaries->summaries + i;
1262
1263 if ((search >= summary->address) &&
1264 (search < (summary->address + summary->size))) {
1265 kernel_mach_header_t *header = (kernel_mach_header_t *)(uintptr_t) summary->address;
1266 if (panic_print_macho_symbol_name(header, search, summary->name) == 0) {
1267 paniclog_append_noflush("%s + %llu", summary->name, (unsigned long)search - summary->address);
1268 }
1269 break;
1270 }
1271 }
1272 }
1273
1274 static void
read_lbr_empty(void)1275 read_lbr_empty(void)
1276 {
1277 }
1278
1279 void (*read_lbr)(void) = read_lbr_empty;
1280
1281 static void
capture_lbr_state(void)1282 capture_lbr_state(void)
1283 {
1284 thread_t thr_act = current_thread();
1285 int i;
1286 last_branch_state_t thread_lbr_data;
1287 struct lbr_data *lbr = &lbrs[cpu_number()];
1288
1289 if (lbr_stack_size > 0) {
1290 i386_lbr_disable();
1291
1292 if (i386_filtered_lbr_state_to_mach_thread_state(thr_act, &thread_lbr_data, false) == 0) {
1293 for (i = 0; i < thread_lbr_data.lbr_count; i++) {
1294 lbr->from[i] = thread_lbr_data.lbrs[i].from_ip;
1295 lbr->to[i] = thread_lbr_data.lbrs[i].to_ip;
1296 }
1297 }
1298 }
1299
1300 i386_lbr_enable();
1301 }
1302
1303 static void
copy_lbr_data_for_core(void)1304 copy_lbr_data_for_core(void)
1305 {
1306 unsigned int cpu;
1307 struct {
1308 uint32_t id;
1309 uint8_t ncpus;
1310 uint8_t lbr_count;
1311 } metadata;
1312
1313 /* These two buffers are captured in the core file and placed in named segments */
1314 if (phys_carveout && phys_carveout_metadata) {
1315 // The minimum size of phys_carveout is 1MiB but just in case
1316 if (phys_carveout_size >= sizeof(last_branch_state_t) * max_ncpus) {
1317 for (cpu = 0; cpu < real_ncpus; cpu++) {
1318 void *buf = (void *)(phys_carveout + lbr_stack_size * sizeof(uint64_t) * cpu);
1319 memcpy(buf, lbrs[cpu].from, sizeof(uint64_t) * lbr_stack_size);
1320 memcpy((uint64_t *)buf + lbr_stack_size * sizeof(uint64_t), lbrs[cpu].to,
1321 sizeof(uint64_t) * lbr_stack_size);
1322 }
1323 /* Write 'LBRS' identifier, the number of CPUs and the LBR stack size */
1324 metadata.id = LBR_MAGIC; /* 'LBRS' */
1325 metadata.ncpus = real_ncpus;
1326 metadata.lbr_count = lbr_stack_size;
1327 memcpy((void*)phys_carveout_metadata, (void*)&metadata, sizeof(metadata));
1328 }
1329 }
1330 }
1331
1332 void
lbr_for_kmode_init(uint32_t lbr_count)1333 lbr_for_kmode_init(uint32_t lbr_count)
1334 {
1335 uint32_t size;
1336 int i;
1337
1338 lbr_stack_size = lbr_count;
1339
1340 /* Cannot use real_ncpus here as only one CPU is registered yet*/
1341
1342 size = sizeof(uint64_t) * lbr_stack_size;
1343 for (i = 0; i < max_ncpus; i++) {
1344 lbrs[i].from = kalloc_data(size, Z_WAITOK | Z_ZERO);
1345 lbrs[i].to = kalloc_data(size, Z_WAITOK | Z_ZERO);
1346 if (!lbrs[i].from || !lbrs[i].to) {
1347 kprintf("LBR: Kalloc failed for lbrs.from/to\n");
1348 if (lbrs[i].from) {
1349 kfree_data(lbrs[i].from, size);
1350 }
1351 if (lbrs[i].to) {
1352 kfree_data(lbrs[i].to, size);
1353 }
1354 while (--i >= 0) {
1355 kfree_data(lbrs[i].from, size);
1356 kfree_data(lbrs[i].to, size);
1357 }
1358 goto err;
1359 }
1360 }
1361
1362 read_lbr = capture_lbr_state;
1363
1364 return;
1365
1366 err:
1367 last_branch_enabled_modes = LBR_ENABLED_NONE;
1368 return;
1369 }
1370
1371 static void
write_lbr_to_panic_log(void)1372 write_lbr_to_panic_log(void)
1373 {
1374 unsigned int cpu;
1375 int i;
1376
1377 for (cpu = 0; cpu < real_ncpus; cpu++) {
1378 paniclog_append_noflush("LBR Stack (CPU %d):\n", cpu);
1379 for (i = 0; i < lbr_stack_size; i++) {
1380 if (lbrs[cpu].from[i] == 0x0 && lbrs[cpu].to[i] == 0x0) {
1381 continue;
1382 }
1383 paniclog_append_noflush("0x%llx : 0x%llx\n", lbrs[cpu].from[i], lbrs[cpu].to[i]);
1384 }
1385 }
1386 if (debug_can_coredump_phys_carveout()) {
1387 copy_lbr_data_for_core();
1388 }
1389 }
1390
1391 void
panic_print_symbol_name(vm_address_t search)1392 panic_print_symbol_name(vm_address_t search)
1393 {
1394 /* try searching in the kernel */
1395 if (panic_print_macho_symbol_name(&_mh_execute_header, search, "mach_kernel") == 0) {
1396 /* that failed, now try to search for the right kext */
1397 panic_print_kmod_symbol_name(search);
1398 }
1399 }
1400
1401 /* Generate a backtrace, given a frame pointer - this routine
1402 * should walk the stack safely. The trace is appended to the panic log
1403 * and conditionally, to the console. If the trace contains kernel module
1404 * addresses, display the module name, load address and dependencies.
1405 */
1406
1407 static hw_lock_timeout_status_t
panic_btlock_handler_spin(void * _lock,uint64_t timeout,uint64_t start,uint64_t now,uint64_t interrupt_time)1408 panic_btlock_handler_spin(void *_lock, uint64_t timeout, uint64_t start, uint64_t now, uint64_t interrupt_time)
1409 {
1410 #pragma unused(_lock, timeout, start, now, interrupt_time)
1411 return HW_LOCK_TIMEOUT_RETURN;
1412 }
1413
1414
1415 #define DUMPFRAMES 32
1416 #define PBT_TIMEOUT_CYCLES (5 * 1000 * 1000 * 1000ULL)
1417 void
panic_i386_backtrace(void * _frame,int nframes,const char * msg,boolean_t regdump,x86_saved_state_t * regs)1418 panic_i386_backtrace(void *_frame, int nframes, const char *msg, boolean_t regdump, x86_saved_state_t *regs)
1419 {
1420 cframe_t *frame = (cframe_t *)_frame;
1421 vm_offset_t raddrs[DUMPFRAMES];
1422 vm_offset_t PC = 0;
1423 int frame_index;
1424 volatile uint32_t *ppbtcnt = &pbtcnt;
1425 uint64_t bt_tsc_timeout;
1426 boolean_t keepsyms = FALSE;
1427 int cn = cpu_number();
1428 boolean_t old_doprnt_hide_pointers = doprnt_hide_pointers;
1429 thread_t cur_thread = current_thread();
1430 task_t task;
1431 struct proc *proc;
1432
1433 #if DEVELOPMENT || DEBUG
1434 /* Turn off I/O tracing now that we're panicking */
1435 mmiotrace_enabled = 0;
1436 #endif
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, LockTimeOutTSC * 4, panic_btlock_handler_spin, 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, LockTimeOutTSC * 4, panic_btlock_handler_spin, 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