1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * @OSF_COPYRIGHT@
30 */
31 /*
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988 Carnegie Mellon University
34 * All Rights Reserved.
35 *
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
41 *
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
45 *
46 * Carnegie Mellon requests users of this software to return to
47 *
48 * Software Distribution Coordinator or [email protected]
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
52 *
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
55 */
56 /*
57 * NOTICE: This file was modified by McAfee Research in 2004 to introduce
58 * support for mandatory and extensible security protections. This notice
59 * is included in support of clause 2.2 (b) of the Apple Public License,
60 * Version 2.0.
61 */
62 /*
63 */
64
65 /*
66 * Mach kernel startup.
67 */
68
69 #include <debug.h>
70 #include <mach_kdp.h>
71
72 #include <mach/boolean.h>
73 #include <mach/machine.h>
74 #include <mach/thread_act.h>
75 #include <mach/task_special_ports.h>
76 #include <mach/vm_param.h>
77 #include <kern/assert.h>
78 #include <kern/mach_param.h>
79 #include <kern/misc_protos.h>
80 #include <kern/clock.h>
81 #include <kern/coalition.h>
82 #include <kern/cpu_number.h>
83 #include <kern/ledger.h>
84 #include <kern/machine.h>
85 #include <kern/processor.h>
86 #include <kern/restartable.h>
87 #include <kern/sched_prim.h>
88 #include <kern/turnstile.h>
89 #if CONFIG_SCHED_SFI
90 #include <kern/sfi.h>
91 #endif
92 #include <kern/smr.h>
93 #include <kern/startup.h>
94 #include <kern/task.h>
95 #include <kern/thread.h>
96 #include <kern/timer.h>
97 #if CONFIG_TELEMETRY
98 #include <kern/telemetry.h>
99 #include <kern/trap_telemetry.h>
100 #endif
101 #include <kern/kpc.h>
102 #include <kern/zalloc.h>
103 #include <kern/locks.h>
104 #include <kern/debug.h>
105 #if KPERF
106 #include <kperf/kperf.h>
107 #endif /* KPERF */
108 #include <corpses/task_corpse.h>
109 #include <prng/random.h>
110 #include <console/serial_protos.h>
111 #include <vm/vm_kern_xnu.h>
112 #include <vm/vm_init_xnu.h>
113 #include <vm/vm_map.h>
114 #include <vm/vm_object_xnu.h>
115 #include <vm/vm_page.h>
116 #include <vm/vm_pageout_xnu.h>
117 #include <vm/vm_shared_region_xnu.h>
118 #include <machine/pmap.h>
119 #include <machine/commpage.h>
120 #include <machine/machine_routines.h>
121 #include <machine/static_if.h>
122 #include <libkern/version.h>
123 #include <pexpert/device_tree.h>
124 #include <sys/codesign.h>
125 #include <sys/kdebug.h>
126 #include <sys/random.h>
127 #include <sys/ktrace.h>
128 #include <sys/trust_caches.h>
129 #include <sys/code_signing.h>
130 #include <libkern/section_keywords.h>
131
132 #include <kern/waitq.h>
133 #include <ipc/ipc_voucher.h>
134 #include <mach/host_info.h>
135 #include <pthread/workqueue_internal.h>
136
137 #if SOCKETS
138 extern void mbuf_tag_init(void);
139 #endif
140
141 #if CONFIG_XNUPOST
142 #include <tests/ktest.h>
143 #include <tests/xnupost.h>
144 #endif
145
146 #if CONFIG_ATM
147 #include <atm/atm_internal.h>
148 #endif
149
150 #if ALTERNATE_DEBUGGER
151 #include <arm64/alternate_debugger.h>
152 #endif
153
154 #if MACH_KDP
155 #include <kdp/kdp.h>
156 #endif
157
158 #if CONFIG_MACF
159 #include <security/mac_mach_internal.h>
160 #if CONFIG_VNGUARD
161 extern void vnguard_policy_init(void);
162 #endif
163 #endif
164
165 #if HYPERVISOR
166 #include <kern/hv_support.h>
167 #endif
168
169 #if CONFIG_UBSAN_MINIMAL
170 #include <san/ubsan_minimal.h>
171 #endif
172
173 #include <san/kasan.h>
174
175 #include <i386/pmCPU.h>
176 static void kernel_bootstrap_thread(void);
177
178 static void load_context(
179 thread_t thread);
180
181 #if CONFIG_ECC_LOGGING
182 #include <kern/ecc.h>
183 #endif
184
185 #if (defined(__i386__) || defined(__x86_64__)) && CONFIG_VMX
186 #include <i386/vmx/vmx_cpu.h>
187 #endif
188
189 #if CONFIG_DTRACE
190 extern void dtrace_early_init(void);
191 extern void sdt_early_init(void);
192 #endif
193
194 // libkern/OSKextLib.cpp
195 extern void OSKextRemoveKextBootstrap(void);
196
197 void scale_setup(void);
198 extern void bsd_scale_setup(int);
199 extern unsigned int semaphore_max;
200 extern void stackshot_init(void);
201
202 /*
203 * Running in virtual memory, on the interrupt stack.
204 */
205
206 extern struct startup_entry startup_entries[]
207 __SECTION_START_SYM(STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
208
209 extern struct startup_entry startup_entries_end[]
210 __SECTION_END_SYM(STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
211
212 static struct startup_entry *__startup_data startup_entry_cur = startup_entries;
213
214 SECURITY_READ_ONLY_LATE(startup_subsystem_id_t) startup_phase = STARTUP_SUB_NONE;
215
216 TUNABLE(startup_debug_t, startup_debug, "startup_debug", 0);
217
218 /* Indicates a server boot when set */
219 TUNABLE(int, serverperfmode, "serverperfmode", 0);
220
221 static inline void
kernel_bootstrap_log(const char * message)222 kernel_bootstrap_log(const char *message)
223 {
224 if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
225 startup_phase >= STARTUP_SUB_KPRINTF) {
226 kprintf("kernel_bootstrap: %s\n", message);
227 }
228 kernel_debug_string_early(message);
229 }
230
231 static inline void
kernel_bootstrap_thread_log(const char * message)232 kernel_bootstrap_thread_log(const char *message)
233 {
234 if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
235 startup_phase >= STARTUP_SUB_KPRINTF) {
236 kprintf("kernel_bootstrap_thread: %s\n", message);
237 }
238 kernel_debug_string_early(message);
239 }
240
241 extern void
242 qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *));
243
244 __startup_func
245 static int
startup_entry_cmp(const void * e1,const void * e2)246 startup_entry_cmp(const void *e1, const void *e2)
247 {
248 const struct startup_entry *a = e1;
249 const struct startup_entry *b = e2;
250 if (a->subsystem == b->subsystem) {
251 if (a->rank == b->rank) {
252 return 0;
253 }
254 return a->rank > b->rank ? 1 : -1;
255 }
256 return a->subsystem > b->subsystem ? 1 : -1;
257 }
258
259 __startup_func
260 void
kernel_startup_bootstrap(void)261 kernel_startup_bootstrap(void)
262 {
263 /*
264 * Sort the various STARTUP() entries by subsystem/rank.
265 */
266 size_t n = startup_entries_end - startup_entries;
267
268 if (n == 0) {
269 panic("Section %s,%s missing",
270 STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
271 }
272 if (((uintptr_t)startup_entries_end - (uintptr_t)startup_entries) %
273 sizeof(struct startup_entry)) {
274 panic("Section %s,%s has invalid size",
275 STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
276 }
277
278 qsort(startup_entries, n, sizeof(struct startup_entry), startup_entry_cmp);
279
280 #if !CONFIG_SPTM && !defined(__BUILDING_XNU_LIBRARY__)
281 /* static_if relies on TEXT editing and not supported in user-mode build*/
282 static_if_init(PE_boot_args());
283 #endif
284
285 /*
286 * Then initialize all tunables, timeouts, and locks
287 */
288 kernel_startup_initialize_upto(STARTUP_SUB_LOCKS);
289 }
290
291 __startup_func
292 void
kernel_startup_tunable_init(const struct startup_tunable_spec * spec)293 kernel_startup_tunable_init(const struct startup_tunable_spec *spec)
294 {
295 if (spec->var_is_str) {
296 PE_parse_boot_arg_str(spec->name, spec->var_addr, spec->var_len);
297 } else if (PE_parse_boot_argn(spec->name, spec->var_addr, spec->var_len)) {
298 if (spec->var_is_bool) {
299 /* make sure bool's are valued in {0, 1} */
300 *(bool *)spec->var_addr = *(uint8_t *)spec->var_addr;
301 }
302 }
303 }
304
305 __startup_func
306 void
kernel_startup_tunable_dt_source_init(const struct startup_tunable_dt_source_spec * spec)307 kernel_startup_tunable_dt_source_init(const struct startup_tunable_dt_source_spec *spec)
308 {
309 DTEntry base;
310
311 *spec->source_addr = STARTUP_SOURCE_DEFAULT;
312 if (SecureDTLookupEntry(NULL, spec->dt_base, &base) != kSuccess) {
313 base = NULL;
314 }
315
316 bool found_in_chosen = false;
317
318 if (spec->dt_chosen_override) {
319 DTEntry chosen, chosen_base;
320
321 if (SecureDTLookupEntry(NULL, "chosen", &chosen) != kSuccess) {
322 chosen = NULL;
323 }
324
325 if (chosen != NULL && SecureDTLookupEntry(chosen, spec->dt_base, &chosen_base) == kSuccess) {
326 base = chosen_base;
327 found_in_chosen = true;
328 *spec->source_addr = STARTUP_SOURCE_DEVICETREE;
329 }
330 }
331
332 uint64_t const *data;
333 unsigned int data_size = spec->var_len;
334
335 if (base != NULL && SecureDTGetProperty(base, spec->dt_name, (const void **)&data, &data_size) == kSuccess) {
336 if (data_size != spec->var_len) {
337 panic("unexpected tunable size %u in DT entry %s/%s/%s",
338 data_size, found_in_chosen ? "/chosen" : "", spec->dt_base, spec->dt_name);
339 }
340
341 /* No need to handle bools specially, they are 1 byte integers in the DT. */
342 memcpy(spec->var_addr, data, spec->var_len);
343 *spec->source_addr = STARTUP_SOURCE_DEVICETREE;
344 }
345
346 /* boot-arg overrides. */
347
348 if (spec->boot_arg_name != NULL) {
349 if (PE_parse_boot_argn(spec->boot_arg_name, spec->var_addr, spec->var_len)) {
350 if (spec->var_is_bool) {
351 *(bool *)spec->var_addr = *(uint8_t *)spec->var_addr;
352 }
353 *spec->source_addr = STARTUP_SOURCE_BOOTPARAM;
354 }
355 }
356 }
357
358 __startup_func
359 void
kernel_startup_tunable_dt_init(const struct startup_tunable_dt_spec * spec)360 kernel_startup_tunable_dt_init(const struct startup_tunable_dt_spec *spec)
361 {
362 DTEntry base;
363
364 if (SecureDTLookupEntry(NULL, spec->dt_base, &base) != kSuccess) {
365 base = NULL;
366 }
367
368 bool found_in_chosen = false;
369
370 if (spec->dt_chosen_override) {
371 DTEntry chosen, chosen_base;
372
373 if (SecureDTLookupEntry(NULL, "chosen", &chosen) != kSuccess) {
374 chosen = NULL;
375 }
376
377 if (chosen != NULL && SecureDTLookupEntry(chosen, spec->dt_base, &chosen_base) == kSuccess) {
378 base = chosen_base;
379 found_in_chosen = true;
380 }
381 }
382
383 uint64_t const *data;
384 unsigned int data_size = spec->var_len;
385
386 if (base != NULL && SecureDTGetProperty(base, spec->dt_name, (const void **)&data, &data_size) == kSuccess) {
387 if (data_size != spec->var_len) {
388 panic("unexpected tunable size %u in DT entry %s/%s/%s",
389 data_size, found_in_chosen ? "/chosen" : "", spec->dt_base, spec->dt_name);
390 }
391
392 /* No need to handle bools specially, they are 1 byte integers in the DT. */
393 memcpy(spec->var_addr, data, spec->var_len);
394 }
395
396 /* boot-arg overrides. */
397
398 if (spec->boot_arg_name != NULL) {
399 if (PE_parse_boot_argn(spec->boot_arg_name, spec->var_addr, spec->var_len)) {
400 if (spec->var_is_bool) {
401 *(bool *)spec->var_addr = *(uint8_t *)spec->var_addr;
402 }
403 }
404 }
405 }
406
407 static void
kernel_startup_log(startup_subsystem_id_t subsystem)408 kernel_startup_log(startup_subsystem_id_t subsystem)
409 {
410 static const char *names[] = {
411 [STARTUP_SUB_TUNABLES] = "tunables",
412 [STARTUP_SUB_TIMEOUTS] = "timeouts",
413 [STARTUP_SUB_LOCKS] = "locks",
414 [STARTUP_SUB_KPRINTF] = "kprintf",
415
416 [STARTUP_SUB_PMAP_STEAL] = "pmap_steal",
417 [STARTUP_SUB_KMEM] = "kmem",
418 [STARTUP_SUB_ZALLOC] = "zalloc",
419 [STARTUP_SUB_PERCPU] = "percpu",
420 [STARTUP_SUB_EVENT] = "event",
421
422 [STARTUP_SUB_CODESIGNING] = "codesigning",
423 [STARTUP_SUB_KTRACE] = "ktrace",
424 [STARTUP_SUB_OSLOG] = "oslog",
425 [STARTUP_SUB_MACH_IPC] = "mach_ipc",
426 [STARTUP_SUB_THREAD_CALL] = "thread_call",
427 [STARTUP_SUB_SYSCTL] = "sysctl",
428 [STARTUP_SUB_EARLY_BOOT] = "early_boot",
429
430 /* LOCKDOWN is special and its value won't fit here. */
431 };
432 static startup_subsystem_id_t logged = STARTUP_SUB_NONE;
433
434 if (subsystem <= logged) {
435 return;
436 }
437
438 if (subsystem < sizeof(names) / sizeof(names[0]) && names[subsystem]) {
439 kernel_bootstrap_log(names[subsystem]);
440 }
441 logged = subsystem;
442 }
443
444 __startup_func
445 void
event_register_handler(struct event_hdr * hdr)446 event_register_handler(struct event_hdr *hdr)
447 {
448 struct event_hdr *head = hdr->next;
449
450 hdr->next = head->next;
451 head->next = hdr;
452 }
453
454 __startup_func
455 void
kernel_startup_initialize_upto(startup_subsystem_id_t upto)456 kernel_startup_initialize_upto(startup_subsystem_id_t upto)
457 {
458 struct startup_entry *cur = startup_entry_cur;
459
460 assert(startup_phase < upto);
461
462 while (cur < startup_entries_end && cur->subsystem <= upto) {
463 if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
464 startup_phase >= STARTUP_SUB_KPRINTF) {
465 kprintf("%s[%d, rank %d]: %p(%p)\n", __func__,
466 cur->subsystem, cur->rank, cur->func, cur->arg);
467 }
468 startup_phase = cur->subsystem - 1;
469 kernel_startup_log(cur->subsystem);
470 cur->func(cur->arg);
471 startup_entry_cur = ++cur;
472 }
473 kernel_startup_log(upto);
474
475 if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
476 upto >= STARTUP_SUB_KPRINTF) {
477 kprintf("%s: reached phase %d\n", __func__, upto);
478 }
479 startup_phase = upto;
480 }
481
482 #ifdef __BUILDING_XNU_LIB_UNITTEST__
483 /* unit-test initialization needs to pick specific phases */
484 void
kernel_startup_initialize_only(startup_subsystem_id_t sysid)485 kernel_startup_initialize_only(startup_subsystem_id_t sysid)
486 {
487 assert(startup_phase < sysid);
488 struct startup_entry *cur = startup_entry_cur;
489 while (cur < startup_entries_end && cur->subsystem <= sysid) {
490 if (cur->subsystem == sysid) {
491 startup_phase = cur->subsystem - 1;
492 kernel_startup_log(cur->subsystem);
493 cur->func(cur->arg);
494 }
495 startup_entry_cur = ++cur;
496 }
497 startup_phase = sysid;
498 }
499 #endif
500
501 void
kernel_bootstrap(void)502 kernel_bootstrap(void)
503 {
504 kern_return_t result;
505 thread_t thread;
506 char namep[16];
507
508 code_signing_config_t cs_config;
509
510 printf("%s\n", version); /* log kernel version */
511
512 #if HAS_UPSI_FAILURE_INJECTION
513 check_for_failure_injection(XNU_STAGE_BOOTSTRAP_START);
514 #endif
515
516 scale_setup();
517
518 kernel_bootstrap_log("vm_mem_bootstrap");
519 vm_mem_bootstrap();
520
521 machine_info.memory_size = (uint32_t)mem_size;
522 #if XNU_TARGET_OS_OSX
523 machine_info.max_mem = max_mem_actual;
524 #else
525 machine_info.max_mem = max_mem;
526 #endif /* XNU_TARGET_OS_OSX */
527 machine_info.major_version = version_major;
528 machine_info.minor_version = version_minor;
529
530 #if CONFIG_ATM
531 /* Initialize the Activity Trace Resource Manager. */
532 kernel_bootstrap_log("atm_init");
533 atm_init();
534 #endif
535 kernel_startup_initialize_upto(STARTUP_SUB_OSLOG);
536
537 #if CONFIG_UBSAN_MINIMAL
538 kernel_bootstrap_log("UBSan minimal runtime init");
539 ubsan_minimal_init();
540 #endif
541
542 #if KASAN
543 kernel_bootstrap_log("kasan_late_init");
544 kasan_late_init();
545 #endif
546
547 #if CONFIG_TELEMETRY
548 kernel_bootstrap_log("trap_telemetry_init");
549 trap_telemetry_init();
550 #endif
551
552 if (PE_i_can_has_debugger(NULL)) {
553 if (PE_parse_boot_argn("-show_pointers", &namep, sizeof(namep))) {
554 doprnt_hide_pointers = FALSE;
555 }
556 if (PE_parse_boot_argn("-no_slto_panic", &namep, sizeof(namep))) {
557 extern boolean_t spinlock_timeout_panic;
558 spinlock_timeout_panic = FALSE;
559 }
560 }
561
562 kernel_bootstrap_log("console_init");
563 console_init();
564
565 kernel_bootstrap_log("stackshot_init");
566 stackshot_init();
567
568 kernel_bootstrap_log("sched_init");
569 sched_init();
570
571 #if CONFIG_MACF
572 kernel_bootstrap_log("mac_policy_init");
573 mac_policy_init();
574 #endif
575
576 kernel_startup_initialize_upto(STARTUP_SUB_MACH_IPC);
577
578 /*
579 * As soon as the virtual memory system is up, we record
580 * that this CPU is using the kernel pmap.
581 */
582 kernel_bootstrap_log("PMAP_ACTIVATE_KERNEL");
583 PMAP_ACTIVATE_KERNEL(master_cpu);
584
585 kernel_bootstrap_log("mapping_free_prime");
586 mapping_free_prime(); /* Load up with temporary mapping blocks */
587
588 kernel_bootstrap_log("machine_init");
589 machine_init();
590
591 kernel_bootstrap_log("thread_machine_init_template");
592 thread_machine_init_template();
593
594 kernel_bootstrap_log("clock_init");
595 clock_init();
596
597 /*
598 * Initialize the IPC, task, and thread subsystems.
599 */
600 #if CONFIG_THREAD_GROUPS
601 kernel_bootstrap_log("thread_group_init");
602 thread_group_init();
603 #endif
604
605 #if CONFIG_COALITIONS
606 kernel_bootstrap_log("coalitions_init");
607 coalitions_init();
608 #endif
609
610 kernel_bootstrap_log("code_signing_init");
611 code_signing_init();
612 code_signing_configuration(NULL, &cs_config);
613 #if XNU_TARGET_OS_OSX && (DEVELOPMENT || DEBUG)
614 if (cs_config & CS_CONFIG_GET_OUT_OF_MY_WAY) {
615 AMFI_bootarg_disable_mach_hardening = true;
616 }
617 #endif /* XNU_TARGET_OS_OSX && (DEVELOPMENT || DEBUG) */
618
619 kernel_bootstrap_log("task_init");
620 task_init();
621
622 kernel_bootstrap_log("thread_init");
623 thread_init();
624
625 kernel_bootstrap_log("restartable_init");
626 restartable_init();
627
628 kernel_bootstrap_log("workq_init");
629 workq_init();
630
631 kernel_bootstrap_log("turnstiles_init");
632 turnstiles_init();
633
634 #if PAGE_SLEEP_WITH_INHERITOR
635 kernel_bootstrap_log("page_worker_init");
636 page_worker_init();
637 #endif /* PAGE_SLEEP_WITH_INHERITOR */
638
639 kernel_bootstrap_log("mach_init_activity_id");
640 mach_init_activity_id();
641
642 /* initialize host_statistics */
643 host_statistics_init();
644
645 /* initialize exceptions */
646 kernel_bootstrap_log("exception_init");
647 exception_init();
648
649 #if CONFIG_SCHED_SFI
650 kernel_bootstrap_log("sfi_init");
651 sfi_init();
652 #endif
653
654 /*
655 * Create a kernel thread to execute the kernel bootstrap.
656 */
657
658 kernel_bootstrap_log("kernel_thread_create");
659 result = kernel_thread_create((thread_continue_t)kernel_bootstrap_thread, NULL, MAXPRI_KERNEL, &thread);
660
661 if (result != KERN_SUCCESS) {
662 panic("kernel_bootstrap: result = %08X", result);
663 }
664
665 /* TODO: do a proper thread_start() (without the thread_setrun()) */
666 thread->state = TH_RUN;
667 thread->last_made_runnable_time = mach_absolute_time();
668 thread_set_thread_name(thread, "kernel_bootstrap_thread");
669
670 thread_deallocate(thread);
671
672 kernel_bootstrap_log("load_context - done");
673 load_context(thread);
674 /*NOTREACHED*/
675 }
676
677 SECURITY_READ_ONLY_LATE(vm_offset_t) vm_kernel_addrperm;
678 SECURITY_READ_ONLY_LATE(vm_offset_t) buf_kernel_addrperm;
679 SECURITY_READ_ONLY_LATE(vm_offset_t) vm_kernel_addrperm_ext;
680 SECURITY_READ_ONLY_LATE(uint64_t) vm_kernel_addrhash_salt;
681 SECURITY_READ_ONLY_LATE(uint64_t) vm_kernel_addrhash_salt_ext;
682
683 /*
684 * Now running in a thread. Kick off other services,
685 * invoke user bootstrap, enter pageout loop.
686 */
687 static void
kernel_bootstrap_thread(void)688 kernel_bootstrap_thread(void)
689 {
690 processor_t processor = current_processor();
691
692 #if HAS_UPSI_FAILURE_INJECTION
693 check_for_failure_injection(XNU_STAGE_SCHEDULER_START);
694 #endif
695
696 kernel_bootstrap_thread_log("idle_thread_create");
697 /*
698 * Create the idle processor thread for the boot processor.
699 */
700 idle_thread_create(processor, idle_thread);
701
702 /*
703 * N.B. Do not stick anything else
704 * before this point.
705 *
706 * Start up the scheduler services.
707 */
708 kernel_bootstrap_thread_log("sched_startup");
709 sched_startup();
710
711 /*
712 * Thread lifecycle maintenance (teardown, stack allocation)
713 */
714 kernel_bootstrap_thread_log("thread_daemon_init");
715 thread_daemon_init();
716
717 /*
718 * Thread callout service.
719 */
720 kernel_startup_initialize_upto(STARTUP_SUB_THREAD_CALL);
721
722 /*
723 * Remain on current processor as
724 * additional processors come online.
725 */
726 kernel_bootstrap_thread_log("thread_bind");
727 suspend_cluster_powerdown();
728 thread_bind(processor);
729
730 /*
731 * Kick off memory mapping adjustments.
732 */
733 kernel_bootstrap_thread_log("mapping_adjust");
734 mapping_adjust();
735
736 /*
737 * Create the clock service.
738 */
739 kernel_bootstrap_thread_log("clock_service_create");
740 clock_service_create();
741
742 /*
743 * Create the device service.
744 */
745 device_service_create();
746
747 phys_carveout_init();
748
749 /* Now that carveouts are allocated, start tracing (primary CPU). */
750 #if __arm64__ && (DEVELOPMENT || DEBUG)
751 pe_arm_debug_init_late();
752 PE_arm_debug_enable_trace(true);
753 #endif /* __arm64__ && (DEVELOPMENT || DEBUG) */
754
755 #if MACH_KDP
756 kernel_bootstrap_log("kdp_init");
757 kdp_init();
758 #endif
759
760 #if ALTERNATE_DEBUGGER
761 alternate_debugger_init();
762 #endif
763
764 #if HYPERVISOR
765 kernel_bootstrap_thread_log("hv_support_init");
766 hv_support_init();
767 #endif
768
769 kernel_startup_initialize_upto(STARTUP_SUB_SYSCTL);
770
771 /*
772 * Initialize the globals used for permuting kernel
773 * addresses that may be exported to userland as tokens
774 * using VM_KERNEL_ADDRPERM()/VM_KERNEL_ADDRPERM_EXTERNAL().
775 * Force the random number to be odd to avoid mapping a non-zero
776 * word-aligned address to zero via addition.
777 */
778 vm_kernel_addrperm = (vm_offset_t)(early_random() | 1);
779 buf_kernel_addrperm = (vm_offset_t)(early_random() | 1);
780 vm_kernel_addrperm_ext = (vm_offset_t)(early_random() | 1);
781 vm_kernel_addrhash_salt = early_random();
782 vm_kernel_addrhash_salt_ext = early_random();
783
784 #ifdef IOKIT
785 kernel_bootstrap_log("PE_init_iokit");
786 PE_init_iokit();
787 #endif
788
789 assert(ml_get_interrupts_enabled() == FALSE);
790
791 /*
792 * Past this point, kernel subsystems that expect to operate with
793 * interrupts or preemption enabled may begin enforcement.
794 */
795 kernel_startup_initialize_upto(STARTUP_SUB_EARLY_BOOT);
796
797 #if SCHED_HYGIENE_DEBUG
798 // Reset interrupts masked timeout before we enable interrupts
799 ml_spin_debug_clear_self();
800 #endif
801 (void) spllo(); /* Allow interruptions */
802
803 /*
804 * This will start displaying progress to the user, start as early as possible
805 */
806 initialize_screen(NULL, kPEAcquireScreen);
807
808 /*
809 * Initialize the shared region module.
810 */
811 vm_commpage_init();
812 vm_commpage_text_init();
813
814 #if CONFIG_MACF
815 kernel_bootstrap_log("mac_policy_initmach");
816 mac_policy_initmach();
817 #if CONFIG_VNGUARD
818 kernel_bootstrap_log("vnguard_policy_init");
819 vnguard_policy_init();
820 #endif
821 #endif
822
823 #if CONFIG_DTRACE
824 kernel_bootstrap_log("dtrace_early_init");
825 dtrace_early_init();
826 sdt_early_init();
827 #endif
828
829 #if CODE_SIGNING_MONITOR
830 /*
831 * Lockdown mode is initialized as a startup function within the early boot
832 * category, which means it has been initialized by now. Query the state and
833 * pass it to the code-signing-monitor if required.
834 */
835 kernel_bootstrap_log("code-signing-monitor lockdown mode");
836 csm_check_lockdown_mode();
837 #endif
838
839 #if CODE_SIGNING_MONITOR
840 kernel_bootstrap_log("provisioning_profile_init");
841 csm_initialize_provisioning_profiles();
842 #endif
843
844 kernel_bootstrap_log("trust_cache_init");
845
846 /* Initialize the runtime for the trust cache interface */
847 trust_cache_runtime_init();
848
849 /* Load the static and engineering trust caches */
850 load_static_trust_cache();
851
852 kernel_startup_initialize_upto(STARTUP_SUB_LOCKDOWN);
853
854 /*
855 * Get rid of segments used to bootstrap kext loading. This removes
856 * the KLD, PRELINK symtab, LINKEDIT, and symtab segments/load commands.
857 * Must be done prior to lockdown so that we can free (and possibly relocate)
858 * the static KVA mappings used for the jettisoned bootstrap segments.
859 */
860 kernel_bootstrap_log("OSKextRemoveKextBootstrap");
861 OSKextRemoveKextBootstrap();
862
863 #if SOCKETS
864 /*
865 * Initialize callback table before machine lockdown
866 */
867 mbuf_tag_init();
868 #endif
869
870 /* No changes to kernel text and rodata beyond this point. */
871 kernel_bootstrap_log("machine_lockdown");
872 machine_lockdown();
873
874 #ifdef CONFIG_XNUPOST
875 kern_return_t result = kernel_list_tests();
876 result = kernel_do_post();
877 if (result != KERN_SUCCESS) {
878 panic("kernel_do_post: Tests failed with result = 0x%08x", result);
879 }
880 kernel_bootstrap_log("kernel_do_post - done");
881 #endif /* CONFIG_XNUPOST */
882
883 #ifdef IOKIT
884 kernel_bootstrap_log("PE_lockdown_iokit");
885 PE_lockdown_iokit();
886 #endif
887 /*
888 * max_cpus must be nailed down by the time PE_lockdown_iokit() finishes,
889 * at the latest
890 */
891 vm_set_restrictions(machine_info.max_cpus);
892
893
894 #if KPERF
895 kperf_init_early();
896 #endif
897
898 /*
899 * Start the user bootstrap.
900 */
901 #ifdef MACH_BSD
902 bsd_init();
903 #endif
904
905
906 /*
907 * Get rid of pages used for early boot tracing.
908 */
909 kdebug_free_early_buf();
910
911 serial_keyboard_init(); /* Start serial keyboard if wanted */
912
913 vm_page_init_local_q(machine_info.max_cpus);
914
915 thread_bind(PROCESSOR_NULL);
916 resume_cluster_powerdown();
917
918 #if XNU_VM_HAS_DELAYED_PAGES
919 /*
920 * Now that all CPUs are available to run threads, this is essentially
921 * a background thread. Take this opportunity to initialize and free
922 * any remaining vm_pages that were delayed earlier by pmap_startup().
923 */
924 vm_free_delayed_pages();
925 #endif /* XNU_VM_HAS_DELAYED_PAGES */
926
927 vm_pages_array_finalize();
928
929 /*
930 * Become the pageout daemon.
931 */
932 vm_pageout();
933 /*NOTREACHED*/
934 }
935
936 /*
937 * secondary_cpu_main:
938 *
939 * Load the first thread to start a processor, or
940 * load the previous thread context when restarting a processor
941 * from shutdown.
942 * This path will also be used by the master processor
943 * after being offlined.
944 */
945 void
secondary_cpu_main(void * machine_param)946 secondary_cpu_main(void *machine_param)
947 {
948 processor_t processor = current_processor();
949 thread_t thread = processor->idle_thread;
950
951 thread->parameter = machine_param;
952
953 load_context(thread);
954 /*NOTREACHED*/
955 }
956
957 /*
958 * processor_start_thread:
959 *
960 * First thread to execute on a started processor.
961 *
962 * Called at splsched.
963 */
964 void
processor_start_thread(void * machine_param,__unused wait_result_t result)965 processor_start_thread(void *machine_param,
966 __unused wait_result_t result)
967 {
968 assert(ml_get_interrupts_enabled() == FALSE);
969 assert(current_thread() == current_processor()->idle_thread);
970
971 #if CONFIG_KCOV
972 kcov_start_cpu(current_processor()->cpu_id);
973 #endif
974
975 #if USE_APPLEARMSMP
976 /*
977 * On AppleARMSMP platforms, the cpu_boot_thread registers the AIC and
978 * FastIPI interrupt handlers before the secondary CPU is booted, so we
979 * can expect the self-IPI to deliver immediately.
980 */
981 bool wait_for_cpu_signal = true;
982 #else /* USE_APPLEARMSMP */
983 /*
984 * On AppleARMCPU platforms, the AIC and AppleARMCPU threads must be
985 * scheduled after the secondary CPUs boot in order to register the IPI
986 * interrupt handlers, so we can not be guaranteed when the self-IPI
987 * will deliver. The threads may even need to run on this CPU, so we
988 * can't spin against the self-IPI being delivered.
989 * See rdar://125383535.
990 */
991 bool wait_for_cpu_signal = false;
992 #endif /* USE_APPLEARMSMP */
993
994 processor_cpu_reinit(machine_param, wait_for_cpu_signal, false);
995
996 thread_block(idle_thread);
997 /*NOTREACHED*/
998 }
999
1000 /*
1001 * load_context:
1002 *
1003 * Start the first thread on a processor.
1004 * This may be the first thread ever run on a processor, or
1005 * it could be a processor that was previously offlined.
1006 */
1007 static void __attribute__((noreturn))
load_context(thread_t thread)1008 load_context(
1009 thread_t thread)
1010 {
1011 processor_t processor = current_processor();
1012
1013
1014 #define load_context_kprintf(x...) /* kprintf("load_context: " x) */
1015
1016 load_context_kprintf("machine_set_current_thread\n");
1017 machine_set_current_thread(thread);
1018
1019 load_context_kprintf("processor_up\n");
1020
1021 PMAP_ACTIVATE_KERNEL(processor->cpu_id);
1022
1023 /*
1024 * Acquire a stack if none attached. The panic
1025 * should never occur since the thread is expected
1026 * to have reserved stack.
1027 */
1028 load_context_kprintf("thread %p, stack %lx, stackptr %lx\n", thread,
1029 thread->kernel_stack, thread->machine.kstackptr);
1030 if (!thread->kernel_stack) {
1031 load_context_kprintf("stack_alloc_try\n");
1032 if (!stack_alloc_try(thread)) {
1033 panic("load_context");
1034 }
1035 }
1036
1037 /*
1038 * The idle processor threads are not counted as
1039 * running for load calculations.
1040 */
1041 if (!(thread->state & TH_IDLE)) {
1042 SCHED(run_count_incr)(thread);
1043 }
1044
1045 processor->active_thread = thread;
1046 processor_state_update_from_thread(processor, thread, false);
1047 processor->starting_pri = thread->sched_pri;
1048 processor->deadline = UINT64_MAX;
1049 thread->last_processor = processor;
1050 processor_up(processor);
1051 struct recount_snap snap = { 0 };
1052 recount_snapshot(&snap);
1053 processor->last_dispatch = snap.rsn_time_mach;
1054 recount_processor_online(processor, &snap);
1055
1056 smr_cpu_join(processor, processor->last_dispatch);
1057
1058 PMAP_ACTIVATE_USER(thread, processor->cpu_id);
1059
1060 load_context_kprintf("machine_load_context\n");
1061
1062 #if KASAN_TBI
1063 __asan_handle_no_return();
1064 #endif /* KASAN_TBI */
1065
1066 machine_load_context(thread);
1067 /*NOTREACHED*/
1068 }
1069
1070 extern unsigned int kern_feature_overrides;
1071
1072 void
scale_setup(void)1073 scale_setup(void)
1074 {
1075 boolean_t pe_serverperfmode = FALSE;
1076 int scale = 0;
1077
1078 /*
1079 * kern_feature_override_init() will update kern_feature_override
1080 * based on the serverperfmode=1 boot-arg being present,
1081 * but doesn't take the device-tree setting into account on purpose.
1082 */
1083
1084 pe_serverperfmode = PE_get_default("kern.serverperfmode",
1085 &pe_serverperfmode, sizeof(pe_serverperfmode));
1086 if (pe_serverperfmode) {
1087 serverperfmode = (pe_serverperfmode != 0);
1088 }
1089 #if defined(__LP64__)
1090 typeof(task_max) task_max_base = task_max;
1091
1092
1093 /* Raise limits for servers with >= 16G */
1094 if (serverperfmode && ((uint64_t)max_mem_actual >= (uint64_t)(16 * 1024 * 1024 * 1024ULL))) {
1095 scale = (int)((uint64_t)sane_size / (uint64_t)(8 * 1024 * 1024 * 1024ULL));
1096 /* limit to 128 G */
1097 if (scale > 16) {
1098 scale = 16;
1099 }
1100 task_max_base = 2500;
1101 /* Raise limits for machines with >= 3GB */
1102 } else if ((uint64_t)max_mem_actual >= (uint64_t)(3 * 1024 * 1024 * 1024ULL)) {
1103 if ((uint64_t)max_mem_actual < (uint64_t)(8 * 1024 * 1024 * 1024ULL)) {
1104 scale = 2;
1105 } else {
1106 /* limit to 64GB */
1107 scale = MIN(16, (int)((uint64_t)max_mem_actual / (uint64_t)(4 * 1024 * 1024 * 1024ULL)));
1108 }
1109 }
1110
1111 task_max = MAX(task_max, task_max_base * scale);
1112
1113 if (scale != 0) {
1114 task_threadmax = task_max;
1115 thread_max = task_max * 5;
1116 }
1117
1118 #endif
1119
1120 bsd_scale_setup(scale);
1121 }
1122