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