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