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