xref: /xnu-8796.101.5/osfmk/kern/startup.c (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
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/cpu_quiesce.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/startup.h>
94 #include <kern/task.h>
95 #include <kern/thread.h>
96 #include <kern/timer.h>
97 #if CONFIG_TELEMETRY
98 #include <kern/telemetry.h>
99 #endif
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.h>
110 #include <vm/vm_init.h>
111 #include <vm/vm_map.h>
112 #include <vm/vm_object.h>
113 #include <vm/vm_page.h>
114 #include <vm/vm_pageout.h>
115 #include <vm/vm_shared_region.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 CONFIG_XNUPOST
135 #include <tests/ktest.h>
136 #include <tests/xnupost.h>
137 #endif
138 
139 #if CONFIG_ATM
140 #include <atm/atm_internal.h>
141 #endif
142 
143 #if CONFIG_CSR
144 #include <sys/csr.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 KPC
163 #include <kern/kpc.h>
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 extern int serverperfmode;
218 
219 TUNABLE(startup_debug_t, startup_debug, "startup_debug", 0);
220 
221 static inline void
kernel_bootstrap_log(const char * message)222 kernel_bootstrap_log(const char *message)
223 {
224 	if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
225 	    startup_phase >= STARTUP_SUB_KPRINTF) {
226 		kprintf("kernel_bootstrap: %s\n", message);
227 	}
228 	kernel_debug_string_early(message);
229 }
230 
231 static inline void
kernel_bootstrap_thread_log(const char * message)232 kernel_bootstrap_thread_log(const char *message)
233 {
234 	if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
235 	    startup_phase >= STARTUP_SUB_KPRINTF) {
236 		kprintf("kernel_bootstrap_thread: %s\n", message);
237 	}
238 	kernel_debug_string_early(message);
239 }
240 
241 extern void
242 qsort(void *a, size_t n, size_t es, int (*cmp)(const void *, const void *));
243 
244 __startup_func
245 static int
startup_entry_cmp(const void * e1,const void * e2)246 startup_entry_cmp(const void *e1, const void *e2)
247 {
248 	const struct startup_entry *a = e1;
249 	const struct startup_entry *b = e2;
250 	if (a->subsystem == b->subsystem) {
251 		if (a->rank == b->rank) {
252 			return 0;
253 		}
254 		return a->rank > b->rank ? 1 : -1;
255 	}
256 	return a->subsystem > b->subsystem ? 1 : -1;
257 }
258 
259 __startup_func
260 void
kernel_startup_bootstrap(void)261 kernel_startup_bootstrap(void)
262 {
263 	/*
264 	 * Sort the various STARTUP() entries by subsystem/rank.
265 	 */
266 	size_t n = startup_entries_end - startup_entries;
267 
268 	if (n == 0) {
269 		panic("Section %s,%s missing",
270 		    STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
271 	}
272 	if (((uintptr_t)startup_entries_end - (uintptr_t)startup_entries) %
273 	    sizeof(struct startup_entry)) {
274 		panic("Section %s,%s has invalid size",
275 		    STARTUP_HOOK_SEGMENT, STARTUP_HOOK_SECTION);
276 	}
277 
278 	qsort(startup_entries, n, sizeof(struct startup_entry), startup_entry_cmp);
279 
280 	/*
281 	 * Then initialize all tunables, timeouts, and locks
282 	 */
283 	kernel_startup_initialize_upto(STARTUP_SUB_LOCKS);
284 }
285 
286 __startup_func
287 void
kernel_startup_tunable_init(const struct startup_tunable_spec * spec)288 kernel_startup_tunable_init(const struct startup_tunable_spec *spec)
289 {
290 	if (spec->var_is_str) {
291 		PE_parse_boot_arg_str(spec->name, spec->var_addr, spec->var_len);
292 	} else if (PE_parse_boot_argn(spec->name, spec->var_addr, spec->var_len)) {
293 		if (spec->var_is_bool) {
294 			/* make sure bool's are valued in {0, 1} */
295 			*(bool *)spec->var_addr = *(uint8_t *)spec->var_addr;
296 		}
297 	}
298 }
299 
300 __startup_func
301 void
kernel_startup_tunable_dt_init(const struct startup_tunable_dt_spec * spec)302 kernel_startup_tunable_dt_init(const struct startup_tunable_dt_spec *spec)
303 {
304 	DTEntry base;
305 
306 	if (SecureDTLookupEntry(NULL, spec->dt_base, &base) != kSuccess) {
307 		base = NULL;
308 	}
309 
310 	bool found_in_chosen = false;
311 
312 	if (spec->dt_chosen_override) {
313 		DTEntry chosen, chosen_base;
314 
315 		if (SecureDTLookupEntry(NULL, "chosen", &chosen) != kSuccess) {
316 			chosen = NULL;
317 		}
318 
319 		if (chosen != NULL && SecureDTLookupEntry(chosen, spec->dt_base, &chosen_base) == kSuccess) {
320 			base = chosen_base;
321 			found_in_chosen = true;
322 		}
323 	}
324 
325 	uint64_t const *data;
326 	unsigned int data_size = spec->var_len;
327 
328 	if (base != NULL && SecureDTGetProperty(base, spec->dt_name, (const void **)&data, &data_size) == kSuccess) {
329 		if (data_size != spec->var_len) {
330 			panic("unexpected tunable size %u in DT entry %s/%s/%s",
331 			    data_size, found_in_chosen ? "/chosen" : "", spec->dt_base, spec->dt_name);
332 		}
333 
334 		/* No need to handle bools specially, they are 1 byte integers in the DT. */
335 		memcpy(spec->var_addr, data, spec->var_len);
336 	}
337 
338 	/* boot-arg overrides. */
339 
340 	if (PE_parse_boot_argn(spec->boot_arg_name, spec->var_addr, spec->var_len)) {
341 		if (spec->var_is_bool) {
342 			*(bool *)spec->var_addr = *(uint8_t *)spec->var_addr;
343 		}
344 	}
345 }
346 
347 static void
kernel_startup_log(startup_subsystem_id_t subsystem)348 kernel_startup_log(startup_subsystem_id_t subsystem)
349 {
350 	static const char *names[] = {
351 		[STARTUP_SUB_TUNABLES] = "tunables",
352 		[STARTUP_SUB_TIMEOUTS] = "timeouts",
353 		[STARTUP_SUB_LOCKS] = "locks",
354 		[STARTUP_SUB_KPRINTF] = "kprintf",
355 
356 		[STARTUP_SUB_PMAP_STEAL] = "pmap_steal",
357 		[STARTUP_SUB_KMEM] = "kmem",
358 		[STARTUP_SUB_ZALLOC] = "zalloc",
359 		[STARTUP_SUB_PERCPU] = "percpu",
360 		[STARTUP_SUB_EVENT] = "event",
361 
362 		[STARTUP_SUB_CODESIGNING] = "codesigning",
363 		[STARTUP_SUB_KTRACE] = "ktrace",
364 		[STARTUP_SUB_OSLOG] = "oslog",
365 		[STARTUP_SUB_MACH_IPC] = "mach_ipc",
366 		[STARTUP_SUB_THREAD_CALL] = "thread_call",
367 		[STARTUP_SUB_SYSCTL] = "sysctl",
368 		[STARTUP_SUB_EARLY_BOOT] = "early_boot",
369 
370 		/* LOCKDOWN is special and its value won't fit here. */
371 	};
372 	static startup_subsystem_id_t logged = STARTUP_SUB_NONE;
373 
374 	if (subsystem <= logged) {
375 		return;
376 	}
377 
378 	if (subsystem < sizeof(names) / sizeof(names[0]) && names[subsystem]) {
379 		kernel_bootstrap_log(names[subsystem]);
380 	}
381 	logged = subsystem;
382 }
383 
384 __startup_func
385 void
event_register_handler(struct event_hdr * hdr)386 event_register_handler(struct event_hdr *hdr)
387 {
388 	struct event_hdr *head = hdr->next;
389 
390 	hdr->next = head->next;
391 	head->next = hdr;
392 }
393 
394 __startup_func
395 void
kernel_startup_initialize_upto(startup_subsystem_id_t upto)396 kernel_startup_initialize_upto(startup_subsystem_id_t upto)
397 {
398 	struct startup_entry *cur = startup_entry_cur;
399 
400 	assert(startup_phase < upto);
401 
402 	while (cur < startup_entries_end && cur->subsystem <= upto) {
403 		if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
404 		    startup_phase >= STARTUP_SUB_KPRINTF) {
405 			kprintf("%s[%d, rank %d]: %p(%p)\n", __func__,
406 			    cur->subsystem, cur->rank, cur->func, cur->arg);
407 		}
408 		startup_phase = cur->subsystem - 1;
409 		kernel_startup_log(cur->subsystem);
410 		cur->func(cur->arg);
411 		startup_entry_cur = ++cur;
412 	}
413 	kernel_startup_log(upto);
414 
415 	if ((startup_debug & STARTUP_DEBUG_VERBOSE) &&
416 	    upto >= STARTUP_SUB_KPRINTF) {
417 		kprintf("%s: reached phase %d\n", __func__, upto);
418 	}
419 	startup_phase = upto;
420 }
421 
422 void
kernel_bootstrap(void)423 kernel_bootstrap(void)
424 {
425 	kern_return_t   result;
426 	thread_t        thread;
427 	char            namep[16];
428 
429 	printf("%s\n", version); /* log kernel version */
430 
431 	scale_setup();
432 
433 	kernel_bootstrap_log("vm_mem_bootstrap");
434 	vm_mem_bootstrap();
435 
436 	machine_info.memory_size = (uint32_t)mem_size;
437 #if XNU_TARGET_OS_OSX
438 	machine_info.max_mem = max_mem_actual;
439 #else
440 	machine_info.max_mem = max_mem;
441 #endif /* XNU_TARGET_OS_OSX */
442 	machine_info.major_version = version_major;
443 	machine_info.minor_version = version_minor;
444 
445 #if CONFIG_ATM
446 	/* Initialize the Activity Trace Resource Manager. */
447 	kernel_bootstrap_log("atm_init");
448 	atm_init();
449 #endif
450 	kernel_startup_initialize_upto(STARTUP_SUB_OSLOG);
451 
452 #if CONFIG_UBSAN_MINIMAL
453 	kernel_bootstrap_log("UBSan minimal runtime init");
454 	ubsan_minimal_init();
455 #endif
456 
457 #if KASAN
458 	kernel_bootstrap_log("kasan_late_init");
459 	kasan_late_init();
460 #endif
461 
462 #if CONFIG_TELEMETRY
463 	kernel_bootstrap_log("telemetry_init");
464 	telemetry_init();
465 #endif
466 
467 	if (PE_i_can_has_debugger(NULL)) {
468 		if (PE_parse_boot_argn("-show_pointers", &namep, sizeof(namep))) {
469 			doprnt_hide_pointers = FALSE;
470 		}
471 		if (PE_parse_boot_argn("-no_slto_panic", &namep, sizeof(namep))) {
472 			extern boolean_t spinlock_timeout_panic;
473 			spinlock_timeout_panic = FALSE;
474 		}
475 	}
476 
477 	kernel_bootstrap_log("console_init");
478 	console_init();
479 
480 	kernel_bootstrap_log("stackshot_init");
481 	stackshot_init();
482 
483 	kernel_bootstrap_log("sched_init");
484 	sched_init();
485 
486 #if CONFIG_MACF
487 	kernel_bootstrap_log("mac_policy_init");
488 	mac_policy_init();
489 #endif
490 
491 	kernel_startup_initialize_upto(STARTUP_SUB_MACH_IPC);
492 
493 	/*
494 	 * As soon as the virtual memory system is up, we record
495 	 * that this CPU is using the kernel pmap.
496 	 */
497 	kernel_bootstrap_log("PMAP_ACTIVATE_KERNEL");
498 	PMAP_ACTIVATE_KERNEL(master_cpu);
499 
500 	kernel_bootstrap_log("mapping_free_prime");
501 	mapping_free_prime();                                           /* Load up with temporary mapping blocks */
502 
503 	kernel_bootstrap_log("machine_init");
504 	machine_init();
505 
506 	kernel_bootstrap_log("thread_machine_init_template");
507 	thread_machine_init_template();
508 
509 	kernel_bootstrap_log("clock_init");
510 	clock_init();
511 
512 	/*
513 	 *	Initialize the IPC, task, and thread subsystems.
514 	 */
515 #if CONFIG_THREAD_GROUPS
516 	kernel_bootstrap_log("thread_group_init");
517 	thread_group_init();
518 #endif
519 
520 #if CONFIG_COALITIONS
521 	kernel_bootstrap_log("coalitions_init");
522 	coalitions_init();
523 #endif
524 
525 	kernel_bootstrap_log("code_signing_init");
526 	code_signing_init();
527 	code_signing_configuration(NULL, NULL);
528 
529 	kernel_bootstrap_log("task_init");
530 	task_init();
531 
532 	kernel_bootstrap_log("thread_init");
533 	thread_init();
534 
535 	kernel_bootstrap_log("restartable_init");
536 	restartable_init();
537 
538 	kernel_bootstrap_log("workq_init");
539 	workq_init();
540 
541 	kernel_bootstrap_log("turnstiles_init");
542 	turnstiles_init();
543 
544 	kernel_bootstrap_log("mach_init_activity_id");
545 	mach_init_activity_id();
546 
547 	/* initialize host_statistics */
548 	host_statistics_init();
549 
550 	/* initialize exceptions */
551 	kernel_bootstrap_log("exception_init");
552 	exception_init();
553 
554 #if CONFIG_SCHED_SFI
555 	kernel_bootstrap_log("sfi_init");
556 	sfi_init();
557 #endif
558 
559 	/*
560 	 *	Create a kernel thread to execute the kernel bootstrap.
561 	 */
562 
563 	kernel_bootstrap_log("kernel_thread_create");
564 	result = kernel_thread_create((thread_continue_t)kernel_bootstrap_thread, NULL, MAXPRI_KERNEL, &thread);
565 
566 	if (result != KERN_SUCCESS) {
567 		panic("kernel_bootstrap: result = %08X", result);
568 	}
569 
570 	/* TODO: do a proper thread_start() (without the thread_setrun()) */
571 	thread->state = TH_RUN;
572 	thread->last_made_runnable_time = mach_absolute_time();
573 	thread_set_thread_name(thread, "kernel_bootstrap_thread");
574 
575 	thread_deallocate(thread);
576 
577 	kernel_bootstrap_log("load_context - done");
578 	load_context(thread);
579 	/*NOTREACHED*/
580 }
581 
582 SECURITY_READ_ONLY_LATE(vm_offset_t) vm_kernel_addrperm;
583 SECURITY_READ_ONLY_LATE(vm_offset_t) buf_kernel_addrperm;
584 SECURITY_READ_ONLY_LATE(vm_offset_t) vm_kernel_addrperm_ext;
585 SECURITY_READ_ONLY_LATE(uint64_t) vm_kernel_addrhash_salt;
586 SECURITY_READ_ONLY_LATE(uint64_t) vm_kernel_addrhash_salt_ext;
587 
588 /*
589  * Now running in a thread.  Kick off other services,
590  * invoke user bootstrap, enter pageout loop.
591  */
592 static void
kernel_bootstrap_thread(void)593 kernel_bootstrap_thread(void)
594 {
595 	processor_t processor = current_processor();
596 
597 #if (DEVELOPMENT || DEBUG)
598 	platform_stall_panic_or_spin(PLATFORM_STALL_XNU_LOCATION_KERNEL_BOOTSTRAP);
599 #endif
600 
601 	kernel_bootstrap_thread_log("idle_thread_create");
602 	/*
603 	 * Create the idle processor thread.
604 	 */
605 	idle_thread_create(processor);
606 
607 	/*
608 	 * N.B. Do not stick anything else
609 	 * before this point.
610 	 *
611 	 * Start up the scheduler services.
612 	 */
613 	kernel_bootstrap_thread_log("sched_startup");
614 	sched_startup();
615 
616 	/*
617 	 * Thread lifecycle maintenance (teardown, stack allocation)
618 	 */
619 	kernel_bootstrap_thread_log("thread_daemon_init");
620 	thread_daemon_init();
621 
622 	/*
623 	 * Thread callout service.
624 	 */
625 	kernel_startup_initialize_upto(STARTUP_SUB_THREAD_CALL);
626 
627 	/*
628 	 * Remain on current processor as
629 	 * additional processors come online.
630 	 */
631 	kernel_bootstrap_thread_log("thread_bind");
632 	thread_bind(processor);
633 
634 	/*
635 	 * Kick off memory mapping adjustments.
636 	 */
637 	kernel_bootstrap_thread_log("mapping_adjust");
638 	mapping_adjust();
639 
640 	/*
641 	 *	Create the clock service.
642 	 */
643 	kernel_bootstrap_thread_log("clock_service_create");
644 	clock_service_create();
645 
646 	/*
647 	 *	Create the device service.
648 	 */
649 	device_service_create();
650 
651 	phys_carveout_init();
652 
653 #if MACH_KDP
654 	kernel_bootstrap_log("kdp_init");
655 	kdp_init();
656 #endif
657 
658 #if ALTERNATE_DEBUGGER
659 	alternate_debugger_init();
660 #endif
661 
662 #if HYPERVISOR
663 	kernel_bootstrap_thread_log("hv_support_init");
664 	hv_support_init();
665 #endif
666 
667 #if CONFIG_TELEMETRY
668 	kernel_bootstrap_log("bootprofile_init");
669 	bootprofile_init();
670 #endif
671 
672 	kernel_startup_initialize_upto(STARTUP_SUB_SYSCTL);
673 
674 	/*
675 	 * Initialize the globals used for permuting kernel
676 	 * addresses that may be exported to userland as tokens
677 	 * using VM_KERNEL_ADDRPERM()/VM_KERNEL_ADDRPERM_EXTERNAL().
678 	 * Force the random number to be odd to avoid mapping a non-zero
679 	 * word-aligned address to zero via addition.
680 	 */
681 	vm_kernel_addrperm = (vm_offset_t)(early_random() | 1);
682 	buf_kernel_addrperm = (vm_offset_t)(early_random() | 1);
683 	vm_kernel_addrperm_ext = (vm_offset_t)(early_random() | 1);
684 	vm_kernel_addrhash_salt = early_random();
685 	vm_kernel_addrhash_salt_ext = early_random();
686 
687 #ifdef  IOKIT
688 	kernel_bootstrap_log("PE_init_iokit");
689 	PE_init_iokit();
690 #endif
691 
692 	assert(ml_get_interrupts_enabled() == FALSE);
693 
694 	/*
695 	 * Past this point, kernel subsystems that expect to operate with
696 	 * interrupts or preemption enabled may begin enforcement.
697 	 */
698 	kernel_startup_initialize_upto(STARTUP_SUB_EARLY_BOOT);
699 
700 #if SCHED_HYGIENE_DEBUG
701 	// Reset interrupts masked timeout before we enable interrupts
702 	ml_spin_debug_clear_self();
703 #endif
704 	(void) spllo();         /* Allow interruptions */
705 
706 	/*
707 	 * This will start displaying progress to the user, start as early as possible
708 	 */
709 	initialize_screen(NULL, kPEAcquireScreen);
710 
711 	/*
712 	 *	Initialize the shared region module.
713 	 */
714 	vm_commpage_init();
715 	vm_commpage_text_init();
716 
717 #if CONFIG_MACF
718 	kernel_bootstrap_log("mac_policy_initmach");
719 	mac_policy_initmach();
720 #if CONFIG_VNGUARD
721 	kernel_bootstrap_log("vnguard_policy_init");
722 	vnguard_policy_init();
723 #endif
724 #endif
725 
726 #if CONFIG_DTRACE
727 	kernel_bootstrap_log("dtrace_early_init");
728 	dtrace_early_init();
729 	sdt_early_init();
730 #endif
731 
732 #if CODE_SIGNING_MONITOR
733 	kernel_bootstrap_log("provisioning_profile_init");
734 	csm_initialize_provisioning_profiles();
735 #endif
736 
737 #ifndef BCM2837
738 	kernel_bootstrap_log("trust_cache_init");
739 
740 	/* Initialize the runtime for the trust cache interface */
741 	trust_cache_runtime_init();
742 
743 	/* Load the static and engineering trust caches */
744 	load_static_trust_cache();
745 #endif
746 
747 	kernel_startup_initialize_upto(STARTUP_SUB_LOCKDOWN);
748 
749 	/*
750 	 * Get rid of segments used to bootstrap kext loading. This removes
751 	 * the KLD, PRELINK symtab, LINKEDIT, and symtab segments/load commands.
752 	 * Must be done prior to lockdown so that we can free (and possibly relocate)
753 	 * the static KVA mappings used for the jettisoned bootstrap segments.
754 	 */
755 	kernel_bootstrap_log("OSKextRemoveKextBootstrap");
756 	OSKextRemoveKextBootstrap();
757 
758 	/* No changes to kernel text and rodata beyond this point. */
759 	kernel_bootstrap_log("machine_lockdown");
760 	machine_lockdown();
761 
762 #ifdef CONFIG_XNUPOST
763 	kern_return_t result = kernel_list_tests();
764 	result = kernel_do_post();
765 	if (result != KERN_SUCCESS) {
766 		panic("kernel_do_post: Tests failed with result = 0x%08x", result);
767 	}
768 	kernel_bootstrap_log("kernel_do_post - done");
769 #endif /* CONFIG_XNUPOST */
770 
771 #ifdef  IOKIT
772 	kernel_bootstrap_log("PE_lockdown_iokit");
773 	PE_lockdown_iokit();
774 #endif
775 	/*
776 	 * max_cpus must be nailed down by the time PE_lockdown_iokit() finishes,
777 	 * at the latest
778 	 */
779 	vm_set_restrictions(machine_info.max_cpus);
780 
781 
782 #if KPERF
783 	kperf_init_early();
784 #endif
785 
786 	/*
787 	 *	Start the user bootstrap.
788 	 */
789 #ifdef  MACH_BSD
790 	bsd_init();
791 #endif
792 
793 
794 	/*
795 	 * Get rid of pages used for early boot tracing.
796 	 */
797 	kdebug_free_early_buf();
798 
799 	serial_keyboard_init();         /* Start serial keyboard if wanted */
800 
801 	vm_page_init_local_q(machine_info.max_cpus);
802 
803 	thread_bind(PROCESSOR_NULL);
804 
805 	/*
806 	 * Now that all CPUs are available to run threads, this is essentially
807 	 * a background thread. Take this opportunity to initialize and free
808 	 * any remaining vm_pages that were delayed earlier by pmap_startup().
809 	 */
810 	vm_free_delayed_pages();
811 
812 	/*
813 	 *	Become the pageout daemon.
814 	 */
815 	vm_pageout();
816 	/*NOTREACHED*/
817 }
818 
819 /*
820  *	slave_main:
821  *
822  *	Load the first thread to start a processor.
823  *	This path will also be used by the master processor
824  *	after being offlined.
825  */
826 void
slave_main(void * machine_param)827 slave_main(void *machine_param)
828 {
829 	processor_t             processor = current_processor();
830 	thread_t                thread;
831 
832 	/*
833 	 *	Use the idle processor thread if there
834 	 *	is no dedicated start up thread.
835 	 */
836 	if (processor->processor_offlined == true) {
837 		/* Return to the saved processor_offline context */
838 		assert(processor->startup_thread == THREAD_NULL);
839 
840 		thread = processor->idle_thread;
841 		thread->parameter = machine_param;
842 	} else if (processor->startup_thread) {
843 		thread = processor->startup_thread;
844 		processor->startup_thread = THREAD_NULL;
845 	} else {
846 		thread = processor->idle_thread;
847 		thread->continuation = processor_start_thread;
848 		thread->parameter = machine_param;
849 	}
850 
851 	load_context(thread);
852 	/*NOTREACHED*/
853 }
854 
855 /*
856  *	processor_start_thread:
857  *
858  *	First thread to execute on a started processor.
859  *
860  *	Called at splsched.
861  */
862 void
processor_start_thread(void * machine_param,__unused wait_result_t result)863 processor_start_thread(void *machine_param,
864     __unused wait_result_t result)
865 {
866 	processor_t             processor = current_processor();
867 	thread_t                self = current_thread();
868 
869 	slave_machine_init(machine_param);
870 
871 	/*
872 	 *	If running the idle processor thread,
873 	 *	reenter the idle loop, else terminate.
874 	 */
875 	if (self == processor->idle_thread) {
876 		thread_block(idle_thread);
877 	}
878 
879 	thread_terminate(self);
880 	/*NOTREACHED*/
881 }
882 
883 /*
884  *	load_context:
885  *
886  *	Start the first thread on a processor.
887  *	This may be the first thread ever run on a processor, or
888  *	it could be a processor that was previously offlined.
889  */
890 static void __attribute__((noreturn))
load_context(thread_t thread)891 load_context(
892 	thread_t                thread)
893 {
894 	processor_t             processor = current_processor();
895 
896 
897 #define load_context_kprintf(x...) /* kprintf("load_context: " x) */
898 
899 	load_context_kprintf("machine_set_current_thread\n");
900 	machine_set_current_thread(thread);
901 
902 	load_context_kprintf("processor_up\n");
903 
904 	PMAP_ACTIVATE_KERNEL(processor->cpu_id);
905 
906 	/*
907 	 * Acquire a stack if none attached.  The panic
908 	 * should never occur since the thread is expected
909 	 * to have reserved stack.
910 	 */
911 	load_context_kprintf("thread %p, stack %lx, stackptr %lx\n", thread,
912 	    thread->kernel_stack, thread->machine.kstackptr);
913 	if (!thread->kernel_stack) {
914 		load_context_kprintf("stack_alloc_try\n");
915 		if (!stack_alloc_try(thread)) {
916 			panic("load_context");
917 		}
918 	}
919 
920 	/*
921 	 * The idle processor threads are not counted as
922 	 * running for load calculations.
923 	 */
924 	if (!(thread->state & TH_IDLE)) {
925 		SCHED(run_count_incr)(thread);
926 	}
927 
928 	processor->active_thread = thread;
929 	processor_state_update_explicit(processor, thread->sched_pri,
930 	    SFI_CLASS_KERNEL, PSET_SMP, thread_get_perfcontrol_class(thread), THREAD_URGENCY_NONE,
931 	    ((thread->state & TH_IDLE) || (thread->bound_processor != PROCESSOR_NULL)) ? TH_BUCKET_SCHED_MAX : thread->th_sched_bucket);
932 	processor->current_is_bound = thread->bound_processor != PROCESSOR_NULL;
933 	processor->current_is_NO_SMT = false;
934 	processor->current_is_eagerpreempt = false;
935 #if CONFIG_THREAD_GROUPS
936 	processor->current_thread_group = thread_group_get(thread);
937 #endif
938 	processor->starting_pri = thread->sched_pri;
939 	processor->deadline = UINT64_MAX;
940 	thread->last_processor = processor;
941 	processor_up(processor);
942 	struct recount_snap snap = { 0 };
943 	recount_snapshot(&snap);
944 	processor->last_dispatch = snap.rsn_time_mach;
945 	recount_processor_run(&processor->pr_recount, &snap);
946 	recount_update_snap(&snap);
947 
948 	cpu_quiescent_counter_join(processor->last_dispatch);
949 
950 	PMAP_ACTIVATE_USER(thread, processor->cpu_id);
951 
952 	load_context_kprintf("machine_load_context\n");
953 
954 #if KASAN_TBI
955 	__asan_handle_no_return();
956 #endif /* KASAN_TBI */
957 
958 	machine_load_context(thread);
959 	/*NOTREACHED*/
960 }
961 
962 void
scale_setup(void)963 scale_setup(void)
964 {
965 	int scale = 0;
966 #if defined(__LP64__)
967 	typeof(task_max) task_max_base = task_max;
968 
969 	/* Raise limits for servers with >= 16G */
970 	if ((serverperfmode != 0) && ((uint64_t)max_mem_actual >= (uint64_t)(16 * 1024 * 1024 * 1024ULL))) {
971 		scale = (int)((uint64_t)sane_size / (uint64_t)(8 * 1024 * 1024 * 1024ULL));
972 		/* limit to 128 G */
973 		if (scale > 16) {
974 			scale = 16;
975 		}
976 		task_max_base = 2500;
977 		/* Raise limits for machines with >= 3GB */
978 	} else if ((uint64_t)max_mem_actual >= (uint64_t)(3 * 1024 * 1024 * 1024ULL)) {
979 		if ((uint64_t)max_mem_actual < (uint64_t)(8 * 1024 * 1024 * 1024ULL)) {
980 			scale = 2;
981 		} else {
982 			/* limit to 64GB */
983 			scale = MIN(16, (int)((uint64_t)max_mem_actual / (uint64_t)(4 * 1024 * 1024 * 1024ULL)));
984 		}
985 	}
986 
987 	task_max = MAX(task_max, task_max_base * scale);
988 
989 	if (scale != 0) {
990 		task_threadmax = task_max;
991 		thread_max = task_max * 5;
992 	}
993 
994 #endif
995 
996 	bsd_scale_setup(scale);
997 }
998