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