1 /*
2 * Copyright (c) 2007-2024 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 #include <debug.h>
33 #include <mach_ldebug.h>
34 #include <mach_kdp.h>
35
36 #include <kern/misc_protos.h>
37 #include <kern/thread.h>
38 #include <kern/timer_queue.h>
39 #include <kern/processor.h>
40 #include <kern/startup.h>
41 #include <kern/debug.h>
42 #include <kern/monotonic.h>
43 #include <prng/random.h>
44 #include <kern/ecc.h>
45 #include <machine/machine_routines.h>
46 #include <machine/commpage.h>
47 #include <machine/config.h>
48 #if HIBERNATION
49 #include <machine/pal_hibernate.h>
50 #endif /* HIBERNATION */
51 /* ARM64_TODO unify boot.h */
52 #if __arm64__
53 #include <pexpert/arm64/apt_msg.h>
54 #include <pexpert/arm64/boot.h>
55 #include <arm64/amcc_rorgn.h>
56 #else
57 #error Unsupported arch
58 #endif
59 #include <pexpert/arm/consistent_debug.h>
60 #include <pexpert/device_tree.h>
61 #include <arm64/proc_reg.h>
62 #include <arm/pmap.h>
63 #include <arm/caches_internal.h>
64 #include <arm/cpu_internal.h>
65 #include <arm/cpu_data_internal.h>
66 #include <arm/cpuid_internal.h>
67 #include <arm/misc_protos.h>
68 #include <arm/machine_cpu.h>
69 #include <arm/rtclock.h>
70 #include <vm/vm_map.h>
71
72 #include <libkern/kernel_mach_header.h>
73 #include <libkern/stack_protector.h>
74 #include <libkern/section_keywords.h>
75 #include <san/kasan.h>
76 #include <sys/kdebug.h>
77
78 #include <pexpert/pexpert.h>
79
80 #include <console/serial_protos.h>
81
82 #if CONFIG_TELEMETRY
83 #include <kern/telemetry.h>
84 #endif
85
86 #if KPERF
87 #include <kperf/kptimer.h>
88 #endif /* KPERF */
89
90 #if HIBERNATION
91 #include <IOKit/IOPlatformExpert.h>
92 #endif /* HIBERNATION */
93
94 extern void patch_low_glo(void);
95 extern int serial_init(void);
96 extern void sleep_token_buffer_init(void);
97
98 extern vm_offset_t intstack_top;
99 #if __arm64__
100 extern vm_offset_t excepstack_top;
101 #endif
102
103 extern const char version[];
104 extern const char version_variant[];
105 extern int disableConsoleOutput;
106
107 int pc_trace_buf[PC_TRACE_BUF_SIZE] = {0};
108 int pc_trace_cnt = PC_TRACE_BUF_SIZE;
109 int debug_task;
110
111 SECURITY_READ_ONLY_LATE(bool) static_kernelcache = false;
112
113 TUNABLE(bool, restore_boot, "-restore", false);
114
115 #if HAS_BP_RET
116 /* Enable both branch target retention (0x2) and branch direction retention (0x1) across sleep */
117 uint32_t bp_ret = 3;
118 extern void set_bp_ret(void);
119 #endif
120
121 #if SCHED_HYGIENE_DEBUG
122
123 #if XNU_PLATFORM_iPhoneOS
124 #define DEFAULT_INTERRUPT_MASKED_TIMEOUT 12000 /* 500us */
125 #elif XNU_PLATFORM_XROS
126 #define DEFAULT_INTERRUPT_MASKED_TIMEOUT 12000 /* 500us */
127 #else
128 #define DEFAULT_INTERRUPT_MASKED_TIMEOUT 0xd0000 /* 35.499ms */
129 #endif /* XNU_PLATFORM_iPhoneOS */
130
131 TUNABLE_DT_WRITEABLE(sched_hygiene_mode_t, interrupt_masked_debug_mode,
132 "machine-timeouts", "interrupt-masked-debug-mode",
133 "interrupt-masked-debug-mode",
134 SCHED_HYGIENE_MODE_PANIC,
135 TUNABLE_DT_CHECK_CHOSEN);
136
137 MACHINE_TIMEOUT_DEV_WRITEABLE(interrupt_masked_timeout, "interrupt-masked",
138 DEFAULT_INTERRUPT_MASKED_TIMEOUT, MACHINE_TIMEOUT_UNIT_TIMEBASE,
139 NULL);
140 #if __arm64__
141 #define SSHOT_INTERRUPT_MASKED_TIMEOUT 0xf9999 /* 64-bit: 42.599ms */
142 #endif
143 MACHINE_TIMEOUT_DEV_WRITEABLE(stackshot_interrupt_masked_timeout, "sshot-interrupt-masked",
144 SSHOT_INTERRUPT_MASKED_TIMEOUT, MACHINE_TIMEOUT_UNIT_TIMEBASE,
145 NULL);
146 #undef SSHOT_INTERRUPT_MASKED_TIMEOUT
147 #endif
148
149 /*
150 * A 6-second timeout will give the watchdog code a chance to run
151 * before a panic is triggered by the xcall routine.
152 */
153 #define XCALL_ACK_TIMEOUT_NS ((uint64_t) 6000000000)
154 uint64_t xcall_ack_timeout_abstime;
155
156 boot_args const_boot_args __attribute__((section("__DATA, __const")));
157 boot_args *BootArgs __attribute__((section("__DATA, __const")));
158
159 TUNABLE(uint32_t, arm_diag, "diag", 0);
160 #ifdef APPLETYPHOON
161 static unsigned cpus_defeatures = 0x0;
162 extern void cpu_defeatures_set(unsigned int);
163 #endif
164
165 #if __arm64__ && __ARM_GLOBAL_SLEEP_BIT__
166 extern volatile boolean_t arm64_stall_sleep;
167 #endif
168
169 extern boolean_t force_immediate_debug_halt;
170
171 #if HAS_APPLE_PAC
172 SECURITY_READ_ONLY_LATE(boolean_t) diversify_user_jop = TRUE;
173 #endif
174
175 SECURITY_READ_ONLY_LATE(uint64_t) gDramBase;
176 SECURITY_READ_ONLY_LATE(uint64_t) gDramSize;
177 SECURITY_READ_ONLY_LATE(ppnum_t) pmap_first_pnum;
178
179 SECURITY_READ_ONLY_LATE(bool) serial_console_enabled = false;
180
181 #if HAS_ARM_FEAT_SME
182 static SECURITY_READ_ONLY_LATE(bool) enable_sme = true;
183 #endif
184
185 #if APPLEVIRTUALPLATFORM
186 SECURITY_READ_ONLY_LATE(vm_offset_t) reset_vector_vaddr = 0;
187 #endif /* APPLEVIRTUALPLATFORM */
188
189 /*
190 * Forward definition
191 */
192 void arm_init(boot_args * args);
193
194 #if __arm64__
195 unsigned int page_shift_user32; /* for page_size as seen by a 32-bit task */
196
197 extern void configure_misc_apple_boot_args(void);
198 extern void configure_misc_apple_regs(bool is_boot_cpu);
199 extern void configure_timer_apple_regs(void);
200 extern void configure_late_apple_regs(bool cold_boot);
201 #endif /* __arm64__ */
202
203
204 /*
205 * JOP rebasing
206 */
207
208 #define dyldLogFunc(msg, ...)
209 #include <mach/dyld_kernel_fixups.h>
210
211 extern uint32_t __thread_starts_sect_start[] __asm("section$start$__TEXT$__thread_starts");
212 extern uint32_t __thread_starts_sect_end[] __asm("section$end$__TEXT$__thread_starts");
213 #if defined(HAS_APPLE_PAC)
214 extern void OSRuntimeSignStructors(kernel_mach_header_t * header);
215 extern void OSRuntimeSignStructorsInFileset(kernel_mach_header_t * header);
216 #endif /* defined(HAS_APPLE_PAC) */
217
218 extern vm_offset_t vm_kernel_slide;
219 extern vm_offset_t segLOWESTKC, segHIGHESTKC, segLOWESTROKC, segHIGHESTROKC;
220 extern vm_offset_t segLOWESTAuxKC, segHIGHESTAuxKC, segLOWESTROAuxKC, segHIGHESTROAuxKC;
221 extern vm_offset_t segLOWESTRXAuxKC, segHIGHESTRXAuxKC, segHIGHESTNLEAuxKC;
222
223 static void
arm_slide_rebase_and_sign_image(void)224 arm_slide_rebase_and_sign_image(void)
225 {
226 kernel_mach_header_t *k_mh, *kc_mh = NULL;
227 kernel_segment_command_t *seg;
228 uintptr_t slide;
229
230 k_mh = &_mh_execute_header;
231 if (kernel_mach_header_is_in_fileset(k_mh)) {
232 /*
233 * The kernel is part of a MH_FILESET kernel collection, determine slide
234 * based on first segment's mach-o vmaddr (requires first kernel load
235 * command to be LC_SEGMENT_64 of the __TEXT segment)
236 */
237 seg = (kernel_segment_command_t *)((uintptr_t)k_mh + sizeof(*k_mh));
238 assert(seg->cmd == LC_SEGMENT_KERNEL);
239 slide = (uintptr_t)k_mh - seg->vmaddr;
240
241 /*
242 * The kernel collection linker guarantees that the boot collection mach
243 * header vmaddr is the hardcoded kernel link address (as specified to
244 * ld64 when linking the kernel).
245 */
246 kc_mh = (kernel_mach_header_t*)(VM_KERNEL_LINK_ADDRESS + slide);
247 assert(kc_mh->filetype == MH_FILESET);
248
249 /*
250 * rebase and sign jops
251 * Note that we can't call any functions before this point, so
252 * we have to hard-code the knowledge that the base of the KC
253 * is the KC's mach-o header. This would change if any
254 * segment's VA started *before* the text segment
255 * (as the HIB segment does on x86).
256 */
257 const void *collection_base_pointers[KCNumKinds] = {[0] = kc_mh, };
258 kernel_collection_slide((struct mach_header_64 *)kc_mh, collection_base_pointers);
259
260 PE_set_kc_header(KCKindPrimary, kc_mh, slide);
261
262 /*
263 * iBoot doesn't slide load command vmaddrs in an MH_FILESET kernel
264 * collection, so adjust them now, and determine the vmaddr range
265 * covered by read-only segments for the CTRR rorgn.
266 */
267 kernel_collection_adjust_mh_addrs((struct mach_header_64 *)kc_mh, slide, false,
268 (uintptr_t *)&segLOWESTKC, (uintptr_t *)&segHIGHESTKC,
269 (uintptr_t *)&segLOWESTROKC, (uintptr_t *)&segHIGHESTROKC,
270 NULL, NULL, NULL);
271 #if defined(HAS_APPLE_PAC)
272 OSRuntimeSignStructorsInFileset(kc_mh);
273 #endif /* defined(HAS_APPLE_PAC) */
274 } else {
275 /*
276 * Static kernelcache: iBoot slid kernel MachO vmaddrs, determine slide
277 * using hardcoded kernel link address
278 */
279 slide = (uintptr_t)k_mh - VM_KERNEL_LINK_ADDRESS;
280
281 /* rebase and sign jops */
282 static_kernelcache = &__thread_starts_sect_end[0] != &__thread_starts_sect_start[0];
283 if (static_kernelcache) {
284 rebase_threaded_starts( &__thread_starts_sect_start[0],
285 &__thread_starts_sect_end[0],
286 (uintptr_t)k_mh, (uintptr_t)k_mh - slide, slide);
287 }
288 #if defined(HAS_APPLE_PAC)
289 OSRuntimeSignStructors(&_mh_execute_header);
290 #endif /* defined(HAS_APPLE_PAC) */
291 }
292
293
294 /*
295 * Initialize slide global here to avoid duplicating this logic in
296 * arm_vm_init()
297 */
298 vm_kernel_slide = slide;
299 }
300
301 void
arm_auxkc_init(void * mh,void * base)302 arm_auxkc_init(void *mh, void *base)
303 {
304 /*
305 * The kernel collection linker guarantees that the lowest vmaddr in an
306 * AuxKC collection is 0 (but note that the mach header is higher up since
307 * RW segments precede RO segments in the AuxKC).
308 */
309 uintptr_t slide = (uintptr_t)base;
310 kernel_mach_header_t *akc_mh = (kernel_mach_header_t*)mh;
311
312 assert(akc_mh->filetype == MH_FILESET);
313 PE_set_kc_header_and_base(KCKindAuxiliary, akc_mh, base, slide);
314
315 /* rebase and sign jops */
316 const void *collection_base_pointers[KCNumKinds];
317 memcpy(collection_base_pointers, PE_get_kc_base_pointers(), sizeof(collection_base_pointers));
318 kernel_collection_slide((struct mach_header_64 *)akc_mh, collection_base_pointers);
319
320 kernel_collection_adjust_mh_addrs((struct mach_header_64 *)akc_mh, slide, false,
321 (uintptr_t *)&segLOWESTAuxKC, (uintptr_t *)&segHIGHESTAuxKC, (uintptr_t *)&segLOWESTROAuxKC,
322 (uintptr_t *)&segHIGHESTROAuxKC, (uintptr_t *)&segLOWESTRXAuxKC, (uintptr_t *)&segHIGHESTRXAuxKC,
323 (uintptr_t *)&segHIGHESTNLEAuxKC);
324 #if defined(HAS_APPLE_PAC)
325 OSRuntimeSignStructorsInFileset(akc_mh);
326 #endif /* defined(HAS_APPLE_PAC) */
327 }
328
329 /*
330 * Routine: arm_setup_pre_sign
331 * Function: Perform HW initialization that must happen ahead of the first PAC sign
332 * operation.
333 */
334 static void
arm_setup_pre_sign(void)335 arm_setup_pre_sign(void)
336 {
337 #if __arm64__
338 /* DATA TBI, if enabled, affects the number of VA bits that contain the signature */
339 arm_set_kernel_tbi();
340 #endif /* __arm64 */
341 }
342
343 /*
344 * Routine: arm_init
345 * Function: Runs on the boot CPU, once, on entry from iBoot.
346 */
347
348 __startup_func
349 void
arm_init(boot_args * args)350 arm_init(
351 boot_args *args)
352 {
353 unsigned int maxmem;
354 uint32_t memsize;
355 uint64_t xmaxmem;
356 thread_t thread;
357 DTEntry chosen = NULL;
358 unsigned int dt_entry_size = 0;
359
360 arm_setup_pre_sign();
361
362 arm_slide_rebase_and_sign_image();
363
364 /* If kernel integrity is supported, use a constant copy of the boot args. */
365 const_boot_args = *args;
366 BootArgs = args = &const_boot_args;
367
368 #if APPLEVIRTUALPLATFORM
369 reset_vector_vaddr = (vm_offset_t) &LowResetVectorBase;
370 #endif /* APPLEVIRTUALPLATFORM */
371
372 cpu_data_init(&BootCpuData);
373 #if defined(HAS_APPLE_PAC)
374 /* bootstrap cpu process dependent key for kernel has been loaded by start.s */
375 BootCpuData.rop_key = ml_default_rop_pid();
376 BootCpuData.jop_key = ml_default_jop_pid();
377 #endif /* defined(HAS_APPLE_PAC) */
378
379 PE_init_platform(FALSE, args); /* Get platform expert set up */
380
381 #if __arm64__
382 configure_timer_apple_regs();
383 wfe_timeout_configure();
384 wfe_timeout_init();
385
386 configure_misc_apple_boot_args();
387 configure_misc_apple_regs(true);
388
389 #if (DEVELOPMENT || DEBUG)
390 unsigned long const *platform_stall_ptr = NULL;
391
392 if (SecureDTLookupEntry(NULL, "/chosen", &chosen) != kSuccess) {
393 panic("%s: Unable to find 'chosen' DT node", __FUNCTION__);
394 }
395
396 // Not usable TUNABLE here because TUNABLEs are parsed at a later point.
397 if (SecureDTGetProperty(chosen, "xnu_platform_stall", (void const **)&platform_stall_ptr,
398 &dt_entry_size) == kSuccess) {
399 xnu_platform_stall_value = *platform_stall_ptr;
400 }
401
402 platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_ARM_INIT);
403
404 chosen = NULL; // Force a re-lookup later on since VM addresses are not final at this point
405 dt_entry_size = 0;
406 #endif
407
408
409 {
410 /*
411 * Select the advertised kernel page size.
412 */
413 if (args->memSize > 1ULL * 1024 * 1024 * 1024) {
414 /*
415 * arm64 device with > 1GB of RAM:
416 * kernel uses 16KB pages.
417 */
418 PAGE_SHIFT_CONST = PAGE_MAX_SHIFT;
419 } else {
420 /*
421 * arm64 device with <= 1GB of RAM:
422 * kernel uses hardware page size
423 * (4KB for H6/H7, 16KB for H8+).
424 */
425 PAGE_SHIFT_CONST = ARM_PGSHIFT;
426 }
427
428 /* 32-bit apps always see 16KB page size */
429 page_shift_user32 = PAGE_MAX_SHIFT;
430 #ifdef APPLETYPHOON
431 if (PE_parse_boot_argn("cpus_defeatures", &cpus_defeatures, sizeof(cpus_defeatures))) {
432 if ((cpus_defeatures & 0xF) != 0) {
433 cpu_defeatures_set(cpus_defeatures & 0xF);
434 }
435 }
436 #endif
437 }
438 #endif
439 #if HAS_ARM_FEAT_SME
440 (void)PE_parse_boot_argn("enable_sme", &enable_sme, sizeof(enable_sme));
441 if (enable_sme) {
442 arm_sme_init(true);
443 }
444 #endif
445
446 ml_parse_cpu_topology();
447
448
449 master_cpu = ml_get_boot_cpu_number();
450 assert(master_cpu >= 0 && master_cpu <= ml_get_max_cpu_number());
451
452 BootCpuData.cpu_number = (unsigned short)master_cpu;
453 BootCpuData.intstack_top = (vm_offset_t) &intstack_top;
454 BootCpuData.istackptr = &intstack_top;
455 #if __arm64__
456 BootCpuData.excepstack_top = (vm_offset_t) &excepstack_top;
457 BootCpuData.excepstackptr = &excepstack_top;
458 #endif
459 CpuDataEntries[master_cpu].cpu_data_vaddr = &BootCpuData;
460 CpuDataEntries[master_cpu].cpu_data_paddr = (void *)((uintptr_t)(args->physBase)
461 + ((uintptr_t)&BootCpuData
462 - (uintptr_t)(args->virtBase)));
463
464 thread = thread_bootstrap();
465 thread->machine.CpuDatap = &BootCpuData;
466 thread->machine.pcpu_data_base_and_cpu_number =
467 ml_make_pcpu_base_and_cpu_number(0, BootCpuData.cpu_number);
468 machine_set_current_thread(thread);
469
470 /*
471 * Preemption is enabled for this thread so that it can lock mutexes without
472 * tripping the preemption check. In reality scheduling is not enabled until
473 * this thread completes, and there are no other threads to switch to, so
474 * preemption level is not really meaningful for the bootstrap thread.
475 */
476 thread->machine.preemption_count = 0;
477 cpu_bootstrap();
478
479 rtclock_early_init();
480
481 kernel_debug_string_early("kernel_startup_bootstrap");
482 kernel_startup_bootstrap();
483
484 /*
485 * Initialize the timer callout world
486 */
487 timer_call_init();
488
489 cpu_init();
490
491 processor_bootstrap();
492
493 if (PE_parse_boot_argn("maxmem", &maxmem, sizeof(maxmem))) {
494 xmaxmem = (uint64_t) maxmem * (1024 * 1024);
495 } else if (PE_get_default("hw.memsize", &memsize, sizeof(memsize))) {
496 xmaxmem = (uint64_t) memsize;
497 } else {
498 xmaxmem = 0;
499 }
500
501 #if SCHED_HYGIENE_DEBUG
502 {
503 int wdt_boot_arg = 0;
504 bool const wdt_disabled = (PE_parse_boot_argn("wdt", &wdt_boot_arg, sizeof(wdt_boot_arg)) && (wdt_boot_arg == -1));
505
506 /* Disable if WDT is disabled */
507 if (wdt_disabled || kern_feature_override(KF_INTERRUPT_MASKED_DEBUG_OVRD)) {
508 interrupt_masked_debug_mode = SCHED_HYGIENE_MODE_OFF;
509 }
510 if (wdt_disabled || kern_feature_override(KF_PREEMPTION_DISABLED_DEBUG_OVRD)) {
511 sched_preemption_disable_debug_mode = SCHED_HYGIENE_MODE_OFF;
512 }
513 }
514 #endif /* SCHED_HYGIENE_DEBUG */
515
516 nanoseconds_to_absolutetime(XCALL_ACK_TIMEOUT_NS, &xcall_ack_timeout_abstime);
517
518 #if HAS_BP_RET
519 PE_parse_boot_argn("bpret", &bp_ret, sizeof(bp_ret));
520 set_bp_ret(); // Apply branch predictor retention settings to boot CPU
521 #endif
522
523 PE_parse_boot_argn("immediate_NMI", &force_immediate_debug_halt, sizeof(force_immediate_debug_halt));
524
525 #if __ARM_PAN_AVAILABLE__
526 __builtin_arm_wsr("pan", 1);
527 #endif /* __ARM_PAN_AVAILABLE__ */
528
529
530 /*
531 * gPhysBase/Size only represent kernel-managed memory. These globals represent
532 * the actual DRAM base address and size as reported by iBoot through the
533 * device tree.
534 */
535 unsigned long const *dram_base;
536 unsigned long const *dram_size;
537
538 if (SecureDTLookupEntry(NULL, "/chosen", &chosen) != kSuccess) {
539 panic("%s: Unable to find 'chosen' DT node", __FUNCTION__);
540 }
541
542 if (SecureDTGetProperty(chosen, "dram-base", (void const **)&dram_base, &dt_entry_size) != kSuccess) {
543 panic("%s: Unable to find 'dram-base' entry in the 'chosen' DT node", __FUNCTION__);
544 }
545
546 if (SecureDTGetProperty(chosen, "dram-size", (void const **)&dram_size, &dt_entry_size) != kSuccess) {
547 panic("%s: Unable to find 'dram-size' entry in the 'chosen' DT node", __FUNCTION__);
548 }
549
550 gDramBase = *dram_base;
551 gDramSize = *dram_size;
552 pmap_first_pnum = (ppnum_t)atop(gDramBase);
553
554 arm_vm_init(xmaxmem, args);
555
556 if (debug_boot_arg) {
557 patch_low_glo();
558 }
559
560 #if __arm64__ && WITH_CLASSIC_S2R
561 sleep_token_buffer_init();
562 #endif
563
564 PE_consistent_debug_inherit();
565
566 /* Setup debugging output. */
567 const unsigned int serial_exists = serial_init();
568 kernel_startup_initialize_upto(STARTUP_SUB_KPRINTF);
569 kprintf("kprintf initialized\n");
570
571 serialmode = 0;
572 if (PE_parse_boot_argn("serial", &serialmode, sizeof(serialmode))) {
573 /* Do we want a serial keyboard and/or console? */
574 kprintf("Serial mode specified: %08X\n", serialmode);
575 disable_iolog_serial_output = (serialmode & SERIALMODE_NO_IOLOG) != 0;
576 enable_dklog_serial_output = restore_boot || (serialmode & SERIALMODE_DKLOG) != 0;
577 int force_sync = serialmode & SERIALMODE_SYNCDRAIN;
578 if (force_sync || PE_parse_boot_argn("drain_uart_sync", &force_sync, sizeof(force_sync))) {
579 if (force_sync) {
580 serialmode |= SERIALMODE_SYNCDRAIN;
581 kprintf(
582 "WARNING: Forcing uart driver to output synchronously."
583 "printf()s/IOLogs will impact kernel performance.\n"
584 "You are advised to avoid using 'drain_uart_sync' boot-arg.\n");
585 }
586 }
587 /* If on-demand is selected, disable serials until reception. */
588 bool on_demand = !!(serialmode & SERIALMODE_ON_DEMAND);
589 if (on_demand && !(serialmode & SERIALMODE_INPUT)) {
590 kprintf(
591 "WARNING: invalid serial boot-args : ON_DEMAND (0x%x) flag "
592 "requires INPUT(0x%x). Ignoring ON_DEMAND.\n",
593 SERIALMODE_ON_DEMAND, SERIALMODE_INPUT
594 );
595 on_demand = 0;
596 }
597 serial_set_on_demand(on_demand);
598 }
599 if (kern_feature_override(KF_SERIAL_OVRD)) {
600 serialmode = 0;
601 }
602
603 /* Start serial if requested and a serial device was enumerated in serial_init(). */
604 if ((serialmode & SERIALMODE_OUTPUT) && serial_exists) {
605 serial_console_enabled = true;
606 (void)switch_to_serial_console(); /* Switch into serial mode from video console */
607 disableConsoleOutput = FALSE; /* Allow printfs to happen */
608 }
609 PE_create_console();
610
611 /* setup console output */
612 PE_init_printf(FALSE);
613
614 #if __arm64__
615 #if DEBUG
616 dump_kva_space();
617 #endif
618 #endif
619
620 cpu_machine_idle_init(TRUE);
621
622 PE_init_platform(TRUE, &BootCpuData);
623
624 /* Initialize the debug infrastructure system-wide and on the local core. */
625 pe_arm_debug_init_early(&BootCpuData);
626
627 #if __arm64__
628 extern bool cpu_config_correct;
629 if (!cpu_config_correct) {
630 panic("The cpumask=N boot arg cannot be used together with cpus=N, and the boot CPU must be enabled");
631 }
632
633 ml_map_cpu_pio();
634
635 #if APPLE_ARM64_ARCH_FAMILY
636 configure_late_apple_regs(true);
637 #endif
638
639 #endif
640
641 cpu_timebase_init(TRUE);
642
643 #if KPERF
644 /* kptimer_curcpu_up() must be called after cpu_timebase_init */
645 kptimer_curcpu_up();
646 #endif /* KPERF */
647
648 PE_init_cpu();
649 #if __arm64__
650 apt_msg_init();
651 apt_msg_init_cpu();
652 #endif
653 fiq_context_init(TRUE);
654
655
656 #if HIBERNATION
657 pal_hib_init();
658 #endif /* HIBERNATION */
659
660 /*
661 * Initialize the stack protector for all future calls
662 * to C code. Since kernel_bootstrap() eventually
663 * switches stack context without returning through this
664 * function, we do not risk failing the check even though
665 * we mutate the guard word during execution.
666 */
667 __stack_chk_guard = (unsigned long)early_random();
668 /* Zero a byte of the protector to guard
669 * against string vulnerabilities
670 */
671 __stack_chk_guard &= ~(0xFFULL << 8);
672 machine_startup(args);
673 }
674
675 /*
676 * Routine: arm_init_cpu
677 * Function:
678 * Runs on S2R resume (all CPUs) and SMP boot (non-boot CPUs only).
679 */
680
681 void
arm_init_cpu(cpu_data_t * cpu_data_ptr,uint64_t __unused hib_header_phys)682 arm_init_cpu(
683 cpu_data_t *cpu_data_ptr,
684 uint64_t __unused hib_header_phys)
685 {
686 #if __ARM_PAN_AVAILABLE__
687 __builtin_arm_wsr("pan", 1);
688 #endif
689
690 #ifdef __arm64__
691 configure_timer_apple_regs();
692 configure_misc_apple_regs(false);
693 #endif
694 #if HAS_ARM_FEAT_SME
695 if (enable_sme) {
696 arm_sme_init(false);
697 }
698 #endif
699
700 os_atomic_andnot(&cpu_data_ptr->cpu_flags, SleepState, relaxed);
701
702
703 machine_set_current_thread(cpu_data_ptr->cpu_active_thread);
704
705 #if APPLE_ARM64_ARCH_FAMILY
706 configure_late_apple_regs(false);
707 #endif
708
709 #if HIBERNATION
710 if ((cpu_data_ptr == &BootCpuData) && (gIOHibernateState == kIOHibernateStateWakingFromHibernate) && ml_is_quiescing()) {
711 // the "normal" S2R code captures wake_abstime too early, so on a hibernation resume we fix it up here
712 extern uint64_t wake_abstime;
713 wake_abstime = gIOHibernateCurrentHeader->lastHibAbsTime;
714
715 // since the hw clock stops ticking across hibernation, we need to apply an offset;
716 // iBoot computes this offset for us and passes it via the hibernation header
717 extern uint64_t hwclock_conttime_offset;
718 hwclock_conttime_offset = gIOHibernateCurrentHeader->hwClockOffset;
719
720 // during hibernation, we captured the idle thread's state from inside the PPL context, so we have to
721 // fix up its preemption count
722 unsigned int expected_preemption_count = (gEnforcePlatformActionSafety ? 2 : 1);
723 if (get_preemption_level_for_thread(cpu_data_ptr->cpu_active_thread) !=
724 expected_preemption_count) {
725 panic("unexpected preemption count %u on boot cpu thread (should be %u)",
726 get_preemption_level_for_thread(cpu_data_ptr->cpu_active_thread),
727 expected_preemption_count);
728 }
729 cpu_data_ptr->cpu_active_thread->machine.preemption_count--;
730 }
731 #endif /* HIBERNATION */
732
733 #if __arm64__
734 wfe_timeout_init();
735 pmap_clear_user_ttb();
736 flush_mmu_tlb();
737 #endif
738
739 cpu_machine_idle_init(FALSE);
740
741 cpu_init();
742
743 #ifdef APPLETYPHOON
744 if ((cpus_defeatures & (0xF << 4 * cpu_data_ptr->cpu_number)) != 0) {
745 cpu_defeatures_set((cpus_defeatures >> 4 * cpu_data_ptr->cpu_number) & 0xF);
746 }
747 #endif
748 /* Initialize the timebase before serial_init, as some serial
749 * drivers use mach_absolute_time() to implement rate control
750 */
751 cpu_timebase_init(FALSE);
752
753 #if KPERF
754 /* kptimer_curcpu_up() must be called after cpu_timebase_init */
755 kptimer_curcpu_up();
756 #endif /* KPERF */
757
758 if (cpu_data_ptr == &BootCpuData && ml_is_quiescing()) {
759 #if __arm64__ && __ARM_GLOBAL_SLEEP_BIT__
760 /*
761 * Prevent CPUs from going into deep sleep until all
762 * CPUs are ready to do so.
763 */
764 arm64_stall_sleep = TRUE;
765 #endif
766 serial_init();
767 PE_init_platform(TRUE, NULL);
768 commpage_update_timebase();
769 }
770 PE_init_cpu();
771 #if __arm64__
772 apt_msg_init_cpu();
773 #endif
774
775 fiq_context_init(TRUE);
776 cpu_data_ptr->rtcPop = EndOfAllTime;
777 timer_resync_deadlines();
778
779 processor_t processor = PERCPU_GET_RELATIVE(processor, cpu_data, cpu_data_ptr);
780 bool should_kprintf = processor_should_kprintf(processor, true);
781
782 /* Start tracing (secondary CPU). */
783 #if DEVELOPMENT || DEBUG
784 PE_arm_debug_enable_trace(should_kprintf);
785 #endif /* DEVELOPMENT || DEBUG */
786
787 #if KERNEL_INTEGRITY_KTRR || KERNEL_INTEGRITY_CTRR
788 rorgn_validate_core();
789 #endif
790
791
792 if (should_kprintf) {
793 kprintf("arm_cpu_init(): cpu %d online\n", cpu_data_ptr->cpu_number);
794 }
795
796 if (cpu_data_ptr == &BootCpuData && ml_is_quiescing()) {
797 if (kdebug_enable == 0) {
798 __kdebug_only uint64_t elapsed = kdebug_wake();
799 KDBG(IOKDBG_CODE(DBG_HIBERNATE, 15), mach_absolute_time() - elapsed);
800 }
801
802 #if CONFIG_TELEMETRY
803 bootprofile_wake_from_sleep();
804 #endif /* CONFIG_TELEMETRY */
805 }
806 #if CONFIG_CPU_COUNTERS
807 mt_wake_per_core();
808 #endif /* CONFIG_CPU_COUNTERS */
809
810 #if defined(KERNEL_INTEGRITY_CTRR)
811 if (ctrr_cluster_locked[cpu_data_ptr->cpu_cluster_id] != CTRR_LOCKED) {
812 lck_spin_lock(&ctrr_cpu_start_lck);
813 ctrr_cluster_locked[cpu_data_ptr->cpu_cluster_id] = CTRR_LOCKED;
814 thread_wakeup(&ctrr_cluster_locked[cpu_data_ptr->cpu_cluster_id]);
815 lck_spin_unlock(&ctrr_cpu_start_lck);
816 }
817 #endif
818
819
820 secondary_cpu_main(NULL);
821 }
822
823 /*
824 * Routine: arm_init_idle_cpu
825 * Function: Resume from non-retention WFI. Called from the reset vector.
826 */
827 void __attribute__((noreturn))
arm_init_idle_cpu(cpu_data_t * cpu_data_ptr)828 arm_init_idle_cpu(
829 cpu_data_t *cpu_data_ptr)
830 {
831 #if __ARM_PAN_AVAILABLE__
832 __builtin_arm_wsr("pan", 1);
833 #endif
834
835 machine_set_current_thread(cpu_data_ptr->cpu_active_thread);
836
837 #if __arm64__
838 wfe_timeout_init();
839 pmap_clear_user_ttb();
840 flush_mmu_tlb();
841 #endif
842
843 #ifdef APPLETYPHOON
844 if ((cpus_defeatures & (0xF << 4 * cpu_data_ptr->cpu_number)) != 0) {
845 cpu_defeatures_set((cpus_defeatures >> 4 * cpu_data_ptr->cpu_number) & 0xF);
846 }
847 #endif
848
849 /*
850 * Update the active debug object to reflect that debug registers have been reset.
851 * This will force any thread with active debug state to resync the debug registers
852 * if it returns to userspace on this CPU.
853 */
854 if (cpu_data_ptr->cpu_user_debug != NULL) {
855 arm_debug_set(NULL);
856 }
857
858 fiq_context_init(FALSE);
859
860 cpu_idle_exit(TRUE);
861 }
862