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