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