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