]> git.saurik.com Git - apple/xnu.git/blob - osfmk/i386/i386_init.c
xnu-7195.60.75.tar.gz
[apple/xnu.git] / osfmk / i386 / i386_init.c
1 /*
2 * Copyright (c) 2003-2019 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 Software.Distribution@CS.CMU.EDU
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
58 #include <mach/i386/vm_param.h>
59
60 #include <string.h>
61 #include <stdint.h>
62 #include <mach/vm_param.h>
63 #include <mach/vm_prot.h>
64 #include <mach/machine.h>
65 #include <mach/time_value.h>
66 #include <kern/spl.h>
67 #include <kern/assert.h>
68 #include <kern/debug.h>
69 #include <kern/misc_protos.h>
70 #include <kern/startup.h>
71 #include <kern/clock.h>
72 #include <kern/pms.h>
73 #include <kern/cpu_data.h>
74 #include <kern/processor.h>
75 #include <sys/kdebug.h>
76 #include <console/serial_protos.h>
77 #include <vm/vm_page.h>
78 #include <vm/pmap.h>
79 #include <vm/vm_kern.h>
80 #include <machine/pal_routines.h>
81 #include <i386/fpu.h>
82 #include <i386/pmap.h>
83 #include <i386/misc_protos.h>
84 #include <i386/cpu_threads.h>
85 #include <i386/cpuid.h>
86 #include <i386/lapic.h>
87 #include <i386/mp.h>
88 #include <i386/mp_desc.h>
89 #if CONFIG_MTRR
90 #include <i386/mtrr.h>
91 #endif
92 #include <i386/machine_routines.h>
93 #if CONFIG_MCA
94 #include <i386/machine_check.h>
95 #endif
96 #include <i386/ucode.h>
97 #include <i386/postcode.h>
98 #include <i386/Diagnostics.h>
99 #include <i386/pmCPU.h>
100 #include <i386/tsc.h>
101 #include <i386/locks.h> /* LcksOpts */
102 #include <i386/acpi.h>
103 #if DEBUG
104 #include <machine/pal_routines.h>
105 #endif
106 extern void xcpm_bootstrap(void);
107 #if DEVELOPMENT || DEBUG
108 #include <i386/trap.h>
109 #endif
110
111 #if MONOTONIC
112 #include <kern/monotonic.h>
113 #endif /* MONOTONIC */
114
115 #include <san/kasan.h>
116
117 #if DEBUG || DEVELOPMENT
118 #define DBG(x, ...) kprintf(x, ##__VA_ARGS__)
119 #define dyldLogFunc(x, ...) kprintf(x, ##__VA_ARGS__)
120 #else
121 #define DBG(x ...)
122 #endif
123
124 #include <libkern/kernel_mach_header.h>
125 #include <mach/dyld_kernel_fixups.h>
126
127
128 int debug_task;
129
130 int early_boot = 1;
131
132 static boot_args *kernelBootArgs;
133
134 extern int disableConsoleOutput;
135 extern const char version[];
136 extern const char version_variant[];
137 extern int nx_enabled;
138
139 /*
140 * Set initial values so that ml_phys_* routines can use the booter's ID mapping
141 * to touch physical space before the kernel's physical aperture exists.
142 */
143 uint64_t physmap_base = 0;
144 uint64_t physmap_max = 4 * GB;
145
146 pd_entry_t *KPTphys;
147 pd_entry_t *IdlePTD;
148 pdpt_entry_t *IdlePDPT;
149 pml4_entry_t *IdlePML4;
150
151 int kernPhysPML4Index;
152 int kernPhysPML4EntryCount;
153
154 /*
155 * These are 4K mapping page table pages from KPTphys[] that we wound
156 * up not using. They get ml_static_mfree()'d once the VM is initialized.
157 */
158 ppnum_t released_PT_ppn = 0;
159 uint32_t released_PT_cnt = 0;
160
161 #if DEVELOPMENT || DEBUG
162 int panic_on_cacheline_mismatch = -1;
163 char panic_on_trap_procname[64];
164 uint32_t panic_on_trap_mask;
165 #endif
166 bool last_branch_support_enabled;
167 int insn_copyin_count;
168 #if DEVELOPMENT || DEBUG
169 #define DEFAULT_INSN_COPYIN_COUNT x86_INSTRUCTION_STATE_MAX_INSN_BYTES
170 #else
171 #define DEFAULT_INSN_COPYIN_COUNT 192
172 #endif
173
174 char *physfree;
175 void idt64_remap(void);
176
177 /*
178 * Note: ALLOCPAGES() can only be used safely within Idle_PTs_init()
179 * due to the mutation of physfree.
180 */
181 static void *
182 ALLOCPAGES(int npages)
183 {
184 uintptr_t tmp = (uintptr_t)physfree;
185 bzero(physfree, npages * PAGE_SIZE);
186 physfree += npages * PAGE_SIZE;
187 tmp += VM_MIN_KERNEL_ADDRESS & ~LOW_4GB_MASK;
188 return (void *)tmp;
189 }
190
191 static void
192 fillkpt(pt_entry_t *base, int prot, uintptr_t src, int index, int count)
193 {
194 int i;
195 for (i = 0; i < count; i++) {
196 base[index] = src | prot | INTEL_PTE_VALID;
197 src += PAGE_SIZE;
198 index++;
199 }
200 }
201
202 extern pmap_paddr_t first_avail;
203
204 int break_kprintf = 0;
205
206 uint64_t
207 x86_64_pre_sleep(void)
208 {
209 IdlePML4[0] = IdlePML4[KERNEL_PML4_INDEX];
210 uint64_t oldcr3 = get_cr3_raw();
211 set_cr3_raw((uint32_t) (uintptr_t)ID_MAP_VTOP(IdlePML4));
212 return oldcr3;
213 }
214
215 void
216 x86_64_post_sleep(uint64_t new_cr3)
217 {
218 IdlePML4[0] = 0;
219 set_cr3_raw((uint32_t) new_cr3);
220 }
221
222
223
224
225 // Set up the physical mapping - NPHYSMAP GB of memory mapped at a high address
226 // NPHYSMAP is determined by the maximum supported RAM size plus 4GB to account
227 // the PCI hole (which is less 4GB but not more).
228
229 static int
230 physmap_init_L2(uint64_t *physStart, pt_entry_t **l2ptep)
231 {
232 unsigned i;
233 pt_entry_t *physmapL2 = ALLOCPAGES(1);
234
235 if (physmapL2 == NULL) {
236 DBG("physmap_init_L2 page alloc failed when initting L2 for physAddr 0x%llx.\n", *physStart);
237 *l2ptep = NULL;
238 return -1;
239 }
240
241 for (i = 0; i < NPDPG; i++) {
242 physmapL2[i] = *physStart
243 | INTEL_PTE_PS
244 | INTEL_PTE_VALID
245 | INTEL_PTE_NX
246 | INTEL_PTE_WRITE;
247
248 *physStart += NBPD;
249 }
250 *l2ptep = physmapL2;
251 return 0;
252 }
253
254 static int
255 physmap_init_L3(int startIndex, uint64_t highest_phys, uint64_t *physStart, pt_entry_t **l3ptep)
256 {
257 unsigned i;
258 int ret;
259 pt_entry_t *l2pte;
260 pt_entry_t *physmapL3 = ALLOCPAGES(1); /* ALLOCPAGES bzeroes the memory */
261
262 if (physmapL3 == NULL) {
263 DBG("physmap_init_L3 page alloc failed when initting L3 for physAddr 0x%llx.\n", *physStart);
264 *l3ptep = NULL;
265 return -1;
266 }
267
268 for (i = startIndex; i < NPDPTPG && *physStart < highest_phys; i++) {
269 if ((ret = physmap_init_L2(physStart, &l2pte)) < 0) {
270 return ret;
271 }
272
273 physmapL3[i] = ((uintptr_t)ID_MAP_VTOP(l2pte))
274 | INTEL_PTE_VALID
275 | INTEL_PTE_NX
276 | INTEL_PTE_WRITE;
277 }
278
279 *l3ptep = physmapL3;
280
281 return 0;
282 }
283
284 static void
285 physmap_init(uint8_t phys_random_L3, uint64_t *new_physmap_base, uint64_t *new_physmap_max)
286 {
287 pt_entry_t *l3pte;
288 int pml4_index, i;
289 int L3_start_index;
290 uint64_t physAddr = 0;
291 uint64_t highest_physaddr;
292 unsigned pdpte_count;
293
294 #if DEVELOPMENT || DEBUG
295 if (kernelBootArgs->PhysicalMemorySize > K64_MAXMEM) {
296 panic("Installed physical memory exceeds configured maximum.");
297 }
298 #endif
299
300 /*
301 * Add 4GB to the loader-provided physical memory size to account for MMIO space
302 * XXX in a perfect world, we'd scan PCI buses and count the max memory requested in BARs by
303 * XXX all enumerated device, then add more for hot-pluggable devices.
304 */
305 highest_physaddr = kernelBootArgs->PhysicalMemorySize + 4 * GB;
306
307 /*
308 * Calculate the number of PML4 entries we'll need. The total number of entries is
309 * pdpte_count = (((highest_physaddr) >> PDPT_SHIFT) + entropy_value +
310 * ((highest_physaddr & PDPT_MASK) == 0 ? 0 : 1))
311 * pml4e_count = pdpte_count >> (PML4_SHIFT - PDPT_SHIFT)
312 */
313 assert(highest_physaddr < (UINT64_MAX - PDPTMASK));
314 pdpte_count = (unsigned) (((highest_physaddr + PDPTMASK) >> PDPTSHIFT) + phys_random_L3);
315 kernPhysPML4EntryCount = (pdpte_count + ((1U << (PML4SHIFT - PDPTSHIFT)) - 1)) >> (PML4SHIFT - PDPTSHIFT);
316 if (kernPhysPML4EntryCount == 0) {
317 kernPhysPML4EntryCount = 1;
318 }
319 if (kernPhysPML4EntryCount > KERNEL_PHYSMAP_PML4_COUNT_MAX) {
320 #if DEVELOPMENT || DEBUG
321 panic("physmap too large");
322 #else
323 kprintf("[pmap] Limiting physmap to %d PML4s (was %d)\n", KERNEL_PHYSMAP_PML4_COUNT_MAX,
324 kernPhysPML4EntryCount);
325 kernPhysPML4EntryCount = KERNEL_PHYSMAP_PML4_COUNT_MAX;
326 #endif
327 }
328
329 kernPhysPML4Index = KERNEL_KEXTS_INDEX - kernPhysPML4EntryCount; /* utb: KERNEL_PHYSMAP_PML4_INDEX */
330
331 /*
332 * XXX: Make sure that the addresses returned for physmapL3 and physmapL2 plus their extents
333 * are in the system-available memory range
334 */
335
336
337 /* We assume NX support. Mark all levels of the PHYSMAP NX
338 * to avoid granting executability via a single bit flip.
339 */
340 #if DEVELOPMENT || DEBUG
341 uint32_t reg[4];
342 do_cpuid(0x80000000, reg);
343 if (reg[eax] >= 0x80000001) {
344 do_cpuid(0x80000001, reg);
345 assert(reg[edx] & CPUID_EXTFEATURE_XD);
346 }
347 #endif /* DEVELOPMENT || DEBUG */
348
349 L3_start_index = phys_random_L3;
350
351 for (pml4_index = kernPhysPML4Index;
352 pml4_index < (kernPhysPML4Index + kernPhysPML4EntryCount) && physAddr < highest_physaddr;
353 pml4_index++) {
354 if (physmap_init_L3(L3_start_index, highest_physaddr, &physAddr, &l3pte) < 0) {
355 panic("Physmap page table initialization failed");
356 /* NOTREACHED */
357 }
358
359 L3_start_index = 0;
360
361 IdlePML4[pml4_index] = ((uintptr_t)ID_MAP_VTOP(l3pte))
362 | INTEL_PTE_VALID
363 | INTEL_PTE_NX
364 | INTEL_PTE_WRITE;
365 }
366
367 *new_physmap_base = KVADDR(kernPhysPML4Index, phys_random_L3, 0, 0);
368 /*
369 * physAddr contains the last-mapped physical address, so that's what we
370 * add to physmap_base to derive the ending VA for the physmap.
371 */
372 *new_physmap_max = *new_physmap_base + physAddr;
373
374 DBG("Physical address map base: 0x%qx\n", *new_physmap_base);
375 for (i = kernPhysPML4Index; i < (kernPhysPML4Index + kernPhysPML4EntryCount); i++) {
376 DBG("Physical map idlepml4[%d]: 0x%llx\n", i, IdlePML4[i]);
377 }
378 }
379
380 void doublemap_init(uint8_t);
381
382 static void
383 Idle_PTs_init(void)
384 {
385 uint64_t rand64;
386 uint64_t new_physmap_base, new_physmap_max;
387
388 /* Allocate the "idle" kernel page tables: */
389 KPTphys = ALLOCPAGES(NKPT); /* level 1 */
390 IdlePTD = ALLOCPAGES(NPGPTD); /* level 2 */
391 IdlePDPT = ALLOCPAGES(1); /* level 3 */
392 IdlePML4 = ALLOCPAGES(1); /* level 4 */
393
394 // Fill the lowest level with everything up to physfree
395 fillkpt(KPTphys,
396 INTEL_PTE_WRITE, 0, 0, (int)(((uintptr_t)physfree) >> PAGE_SHIFT));
397
398 /* IdlePTD */
399 fillkpt(IdlePTD,
400 INTEL_PTE_WRITE, (uintptr_t)ID_MAP_VTOP(KPTphys), 0, NKPT);
401
402 // IdlePDPT entries
403 fillkpt(IdlePDPT,
404 INTEL_PTE_WRITE, (uintptr_t)ID_MAP_VTOP(IdlePTD), 0, NPGPTD);
405
406 // IdlePML4 single entry for kernel space.
407 fillkpt(IdlePML4 + KERNEL_PML4_INDEX,
408 INTEL_PTE_WRITE, (uintptr_t)ID_MAP_VTOP(IdlePDPT), 0, 1);
409
410 postcode(VSTART_PHYSMAP_INIT);
411
412 /*
413 * early_random() cannot be called more than one time before the cpu's
414 * gsbase is initialized, so use the full 64-bit value to extract the
415 * two 8-bit entropy values needed for address randomization.
416 */
417 rand64 = early_random();
418 physmap_init(rand64 & 0xFF, &new_physmap_base, &new_physmap_max);
419 doublemap_init((rand64 >> 8) & 0xFF);
420 idt64_remap();
421
422 postcode(VSTART_SET_CR3);
423
424 /*
425 * Switch to the page tables. We set physmap_base and physmap_max just
426 * before switching to the new page tables to avoid someone calling
427 * kprintf() or otherwise using physical memory in between.
428 * This is needed because kprintf() writes to physical memory using
429 * ml_phys_read_data and PHYSMAP_PTOV, which requires physmap_base to be
430 * set correctly.
431 */
432 physmap_base = new_physmap_base;
433 physmap_max = new_physmap_max;
434 set_cr3_raw((uintptr_t)ID_MAP_VTOP(IdlePML4));
435 }
436
437 /*
438 * Release any still unused, preallocated boot kernel page tables.
439 * start..end is the VA range currently unused.
440 */
441 void
442 Idle_PTs_release(vm_offset_t start, vm_offset_t end)
443 {
444 uint32_t i;
445 uint32_t index_start;
446 uint32_t index_limit;
447 ppnum_t pn_first;
448 ppnum_t pn;
449 uint32_t cnt;
450
451 /*
452 * Align start to the next large page boundary
453 */
454 start = ((start + I386_LPGMASK) & ~I386_LPGMASK);
455
456 /*
457 * convert start into an index in KPTphys[]
458 */
459 index_start = (uint32_t)((start - KERNEL_BASE) >> PAGE_SHIFT);
460
461 /*
462 * Find the ending index in KPTphys[]
463 */
464 index_limit = (uint32_t)((end - KERNEL_BASE) >> PAGE_SHIFT);
465
466 if (index_limit > NKPT * PTE_PER_PAGE) {
467 index_limit = NKPT * PTE_PER_PAGE;
468 }
469
470 /*
471 * Make sure all the 4K page tables are empty.
472 * If not, panic a development/debug kernel.
473 * On a production kernel, since this would stop us from booting,
474 * just abort the operation.
475 */
476 for (i = index_start; i < index_limit; ++i) {
477 assert(KPTphys[i] == 0);
478 if (KPTphys[i] != 0) {
479 return;
480 }
481 }
482
483 /*
484 * Now figure out the indices into the 2nd level page tables, IdlePTD[].
485 */
486 index_start >>= PTPGSHIFT;
487 index_limit >>= PTPGSHIFT;
488 if (index_limit > NPGPTD * PTE_PER_PAGE) {
489 index_limit = NPGPTD * PTE_PER_PAGE;
490 }
491
492 if (index_limit <= index_start) {
493 return;
494 }
495
496
497 /*
498 * Now check the pages referenced from Level 2 tables.
499 * They should be contiguous, assert fail if not on development/debug.
500 * In production, just fail the removal to allow the system to boot.
501 */
502 pn_first = 0;
503 cnt = 0;
504 for (i = index_start; i < index_limit; ++i) {
505 assert(IdlePTD[i] != 0);
506 if (IdlePTD[i] == 0) {
507 return;
508 }
509
510 pn = (ppnum_t)((PG_FRAME & IdlePTD[i]) >> PTSHIFT);
511 if (cnt == 0) {
512 pn_first = pn;
513 } else {
514 assert(pn == pn_first + cnt);
515 if (pn != pn_first + cnt) {
516 return;
517 }
518 }
519 ++cnt;
520 }
521
522 /*
523 * Good to go, clear the level 2 entries and invalidate the TLB
524 */
525 for (i = index_start; i < index_limit; ++i) {
526 IdlePTD[i] = 0;
527 }
528 set_cr3_raw(get_cr3_raw());
529
530 /*
531 * Remember these PFNs to be released later in pmap_lowmem_finalize()
532 */
533 released_PT_ppn = pn_first;
534 released_PT_cnt = cnt;
535 #if DEVELOPMENT || DEBUG
536 printf("Idle_PTs_release %d pages from PFN 0x%x\n", released_PT_cnt, released_PT_ppn);
537 #endif
538 }
539
540 extern void vstart_trap_handler;
541
542 #define BOOT_TRAP_VECTOR(t) \
543 [t] = { \
544 (uintptr_t) &vstart_trap_handler, \
545 KERNEL64_CS, \
546 0, \
547 ACC_P|ACC_PL_K|ACC_INTR_GATE, \
548 0 \
549 },
550
551 /* Recursive macro to iterate 0..31 */
552 #define L0(x, n) x(n)
553 #define L1(x, n) L0(x,n-1) L0(x,n)
554 #define L2(x, n) L1(x,n-2) L1(x,n)
555 #define L3(x, n) L2(x,n-4) L2(x,n)
556 #define L4(x, n) L3(x,n-8) L3(x,n)
557 #define L5(x, n) L4(x,n-16) L4(x,n)
558 #define FOR_0_TO_31(x) L5(x,31)
559
560 /*
561 * Bootstrap IDT. Active only during early startup.
562 * Only the trap vectors are defined since interrupts are masked.
563 * All traps point to a common handler.
564 */
565 struct fake_descriptor64 master_boot_idt64[IDTSZ]
566 __attribute__((section("__HIB,__desc")))
567 __attribute__((aligned(PAGE_SIZE))) = {
568 FOR_0_TO_31(BOOT_TRAP_VECTOR)
569 };
570
571 static void
572 vstart_idt_init(boolean_t master)
573 {
574 x86_64_desc_register_t vstart_idt = {
575 sizeof(master_boot_idt64),
576 master_boot_idt64
577 };
578
579 if (master) {
580 fix_desc64(master_boot_idt64, 32);
581 }
582 lidt((void *)&vstart_idt);
583 }
584
585 extern void *collection_base_pointers[KCNumKinds];
586
587 kern_return_t
588 i386_slide_individual_kext(kernel_mach_header_t *mh, uintptr_t slide)
589 {
590 int ret = kernel_collection_slide(mh, (const void **) (void *)collection_base_pointers);
591 if (ret != 0) {
592 printf("Sliding pageable kc was stopped\n");
593 return KERN_FAILURE;
594 }
595
596 kernel_collection_adjust_fileset_entry_addrs(mh, slide);
597 return KERN_SUCCESS;
598 }
599
600 kern_return_t
601 i386_slide_kext_collection_mh_addrs(kernel_mach_header_t *mh, uintptr_t slide, bool adjust_mach_headers)
602 {
603 int ret = kernel_collection_slide(mh, (const void **) (void *)collection_base_pointers);
604 if (ret != KERN_SUCCESS) {
605 printf("Kernel Collection slide was stopped with value %d\n", ret);
606 return KERN_FAILURE;
607 }
608
609 kernel_collection_adjust_mh_addrs(mh, slide, adjust_mach_headers,
610 NULL, NULL, NULL, NULL, NULL, NULL, NULL);
611
612 return KERN_SUCCESS;
613 }
614
615 static void
616 i386_slide_and_rebase_image(uintptr_t kstart_addr)
617 {
618 extern uintptr_t kc_highest_nonlinkedit_vmaddr;
619 kernel_mach_header_t *k_mh, *kc_mh = NULL;
620 kernel_segment_command_t *seg;
621 uintptr_t slide;
622
623 k_mh = &_mh_execute_header;
624 /*
625 * If we're not booting, an MH_FILESET, we don't need to slide
626 * anything because EFI has done that for us. When booting an
627 * MH_FILESET, EFI will slide the kernel proper, but not the kexts.
628 * Below, we infer the slide by comparing the slid address of the
629 * kernel's mach-o header and the unslid vmaddr of the first segment
630 * of the mach-o (which is assumed to always point to the mach-o
631 * header).
632 */
633 if (!kernel_mach_header_is_in_fileset(k_mh)) {
634 DBG("[MH] kcgen-style KC\n");
635 return;
636 }
637
638 /*
639 * The kernel is part of a MH_FILESET kernel collection: determine slide
640 * based on first segment's mach-o vmaddr.
641 */
642 seg = (kernel_segment_command_t *)((uintptr_t)k_mh + sizeof(*k_mh));
643 assert(seg->cmd == LC_SEGMENT_KERNEL);
644 slide = (uintptr_t)k_mh - seg->vmaddr;
645 DBG("[MH] Sliding new-style KC: %llu\n", (unsigned long long)slide);
646
647 /*
648 * The kernel collection mach-o header should be the start address
649 * passed to us by EFI.
650 */
651 kc_mh = (kernel_mach_header_t *)(kstart_addr);
652 assert(kc_mh->filetype == MH_FILESET);
653
654 PE_set_kc_header(KCKindPrimary, kc_mh, slide);
655
656 /*
657 * rebase/slide all the kexts in the collection
658 * (EFI should have already rebased the kernel)
659 */
660 kernel_collection_slide(kc_mh, (const void **) (void *)collection_base_pointers);
661
662
663 /*
664 * Now adjust the vmaddr fields of all mach-o headers
665 * and symbols in this MH_FILESET
666 */
667 kernel_collection_adjust_mh_addrs(kc_mh, slide, false,
668 NULL, NULL, NULL, NULL, NULL, NULL, &kc_highest_nonlinkedit_vmaddr);
669 }
670
671 /*
672 * vstart() is called in the natural mode (64bit for K64, 32 for K32)
673 * on a set of bootstrap pagetables which use large, 2MB pages to map
674 * all of physical memory in both. See idle_pt.c for details.
675 *
676 * In K64 this identity mapping is mirrored the top and bottom 512GB
677 * slots of PML4.
678 *
679 * The bootstrap processor called with argument boot_args_start pointing to
680 * the boot-args block. The kernel's (4K page) page tables are allocated and
681 * initialized before switching to these.
682 *
683 * Non-bootstrap processors are called with argument boot_args_start NULL.
684 * These processors switch immediately to the existing kernel page tables.
685 */
686 __attribute__((noreturn))
687 void
688 vstart(vm_offset_t boot_args_start)
689 {
690 boolean_t is_boot_cpu = !(boot_args_start == 0);
691 int cpu = 0;
692 uint32_t lphysfree;
693 #if DEBUG
694 uint64_t gsbase;
695 #endif
696
697
698 postcode(VSTART_ENTRY);
699
700 /*
701 * Set-up temporary trap handlers during page-table set-up.
702 */
703
704 if (is_boot_cpu) {
705 vstart_idt_init(TRUE);
706 postcode(VSTART_IDT_INIT);
707
708 /*
709 * Ensure that any %gs-relative access results in an immediate fault
710 * until gsbase is properly initialized below
711 */
712 wrmsr64(MSR_IA32_GS_BASE, EARLY_GSBASE_MAGIC);
713
714 /*
715 * Get startup parameters.
716 */
717 kernelBootArgs = (boot_args *)boot_args_start;
718 lphysfree = kernelBootArgs->kaddr + kernelBootArgs->ksize;
719 physfree = (void *)(uintptr_t)((lphysfree + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
720
721 pal_serial_init();
722
723 DBG("revision 0x%x\n", kernelBootArgs->Revision);
724 DBG("version 0x%x\n", kernelBootArgs->Version);
725 DBG("command line %s\n", kernelBootArgs->CommandLine);
726 DBG("memory map 0x%x\n", kernelBootArgs->MemoryMap);
727 DBG("memory map sz 0x%x\n", kernelBootArgs->MemoryMapSize);
728 DBG("kaddr 0x%x\n", kernelBootArgs->kaddr);
729 DBG("ksize 0x%x\n", kernelBootArgs->ksize);
730 DBG("physfree %p\n", physfree);
731 DBG("bootargs: %p, &ksize: %p &kaddr: %p\n",
732 kernelBootArgs,
733 &kernelBootArgs->ksize,
734 &kernelBootArgs->kaddr);
735 DBG("SMBIOS mem sz 0x%llx\n", kernelBootArgs->PhysicalMemorySize);
736 DBG("KC_hdrs_vaddr %p\n", (void *)kernelBootArgs->KC_hdrs_vaddr);
737
738 if (kernelBootArgs->Version >= 2 && kernelBootArgs->Revision >= 1 &&
739 kernelBootArgs->KC_hdrs_vaddr != 0) {
740 /*
741 * slide the header addresses in all mach-o segments and sections, and
742 * perform any new-style chained-fixup sliding for kexts, as necessary.
743 * Note that efiboot has already loaded the kernel and all LC_SEGMENT_64s
744 * that correspond to the kexts present in the primary KC, into slid addresses.
745 */
746 i386_slide_and_rebase_image((uintptr_t)ml_static_ptovirt(kernelBootArgs->KC_hdrs_vaddr));
747 }
748
749 /*
750 * Setup boot args given the physical start address.
751 * Note: PE_init_platform needs to be called before Idle_PTs_init
752 * because access to the DeviceTree is required to read the
753 * random seed before generating a random physical map slide.
754 */
755 kernelBootArgs = (boot_args *)
756 ml_static_ptovirt(boot_args_start);
757 DBG("i386_init(0x%lx) kernelBootArgs=%p\n",
758 (unsigned long)boot_args_start, kernelBootArgs);
759
760 #if KASAN
761 kasan_reserve_memory(kernelBootArgs);
762 #endif
763
764 PE_init_platform(FALSE, kernelBootArgs);
765 postcode(PE_INIT_PLATFORM_D);
766
767 Idle_PTs_init();
768 postcode(VSTART_IDLE_PTS_INIT);
769
770 #if KASAN
771 /* Init kasan and map whatever was stolen from physfree */
772 kasan_init();
773 kasan_notify_stolen((uintptr_t)ml_static_ptovirt((vm_offset_t)physfree));
774 #endif
775
776 #if MONOTONIC
777 mt_early_init();
778 #endif /* MONOTONIC */
779
780 first_avail = (vm_offset_t)ID_MAP_VTOP(physfree);
781
782 cpu_data_alloc(TRUE);
783
784 cpu_desc_init(cpu_datap(0));
785 postcode(VSTART_CPU_DESC_INIT);
786 cpu_desc_load(cpu_datap(0));
787
788 postcode(VSTART_CPU_MODE_INIT);
789 cpu_syscall_init(cpu_datap(0)); /* cpu_syscall_init() will be
790 * invoked on the APs
791 * via i386_init_slave()
792 */
793 } else {
794 /* Slave CPUs should use the basic IDT until i386_init_slave() */
795 vstart_idt_init(FALSE);
796
797 /* Switch to kernel's page tables (from the Boot PTs) */
798 set_cr3_raw((uintptr_t)ID_MAP_VTOP(IdlePML4));
799
800 /* Find our logical cpu number */
801 cpu = lapic_to_cpu[lapic_safe_apicid()];
802 #if DEBUG
803 gsbase = rdmsr64(MSR_IA32_GS_BASE);
804 #endif
805 cpu_desc_load(cpu_datap(cpu));
806 #if DEBUG
807 DBG("CPU: %d, GSBASE initial value: 0x%llx\n", cpu, (unsigned long long)gsbase);
808 #endif
809
810 /*
811 * Before we can discover our local APIC ID, we need to potentially
812 * initialize X2APIC, if it's enabled and firmware started us with
813 * the APIC in legacy mode.
814 */
815 lapic_init_slave();
816 }
817
818 early_boot = 0;
819 postcode(VSTART_EXIT);
820 x86_init_wrapper(is_boot_cpu ? (uintptr_t) i386_init
821 : (uintptr_t) i386_init_slave,
822 cpu_datap(cpu)->cpu_int_stack_top);
823 }
824
825 void
826 pstate_trace(void)
827 {
828 }
829
830 /*
831 * Cpu initialization. Running virtual, but without MACH VM
832 * set up.
833 */
834 void
835 i386_init(void)
836 {
837 unsigned int maxmem;
838 uint64_t maxmemtouse;
839 unsigned int cpus = 0;
840 boolean_t fidn;
841 boolean_t IA32e = TRUE;
842
843 postcode(I386_INIT_ENTRY);
844
845 pal_i386_init();
846 tsc_init();
847 rtclock_early_init(); /* mach_absolute_time() now functional */
848
849 kernel_debug_string_early("i386_init");
850 pstate_trace();
851
852 #if CONFIG_MCA
853 /* Initialize machine-check handling */
854 mca_cpu_init();
855 #endif
856
857 master_cpu = 0;
858
859 kernel_debug_string_early("kernel_startup_bootstrap");
860 kernel_startup_bootstrap();
861
862 /*
863 * Initialize the timer callout world
864 */
865 timer_call_init();
866
867 cpu_init();
868
869 postcode(CPU_INIT_D);
870
871 /* setup debugging output if one has been chosen */
872 kernel_startup_initialize_upto(STARTUP_SUB_KPRINTF);
873 kprintf("kprintf initialized\n");
874
875 if (!PE_parse_boot_argn("diag", &dgWork.dgFlags, sizeof(dgWork.dgFlags))) {
876 dgWork.dgFlags = 0;
877 }
878
879 if (PE_parse_boot_argn("insn_capcnt", &insn_copyin_count, sizeof(insn_copyin_count))) {
880 /*
881 * Enforce max and min values (allowing 0 to disable copying completely)
882 * for the instruction copyin count
883 */
884 if (insn_copyin_count > x86_INSTRUCTION_STATE_MAX_INSN_BYTES ||
885 (insn_copyin_count != 0 && insn_copyin_count < 64)) {
886 insn_copyin_count = DEFAULT_INSN_COPYIN_COUNT;
887 }
888 } else {
889 insn_copyin_count = DEFAULT_INSN_COPYIN_COUNT;
890 }
891
892 #if DEVELOPMENT || DEBUG
893 if (!PE_parse_boot_argn("panic_clmismatch", &panic_on_cacheline_mismatch,
894 sizeof(panic_on_cacheline_mismatch))) {
895 panic_on_cacheline_mismatch = 0;
896 }
897
898 if (!PE_parse_boot_argn("panic_on_trap_procname", &panic_on_trap_procname[0],
899 sizeof(panic_on_trap_procname))) {
900 panic_on_trap_procname[0] = 0;
901 }
902
903 if (!PE_parse_boot_argn("panic_on_trap_mask", &panic_on_trap_mask,
904 sizeof(panic_on_trap_mask))) {
905 if (panic_on_trap_procname[0] != 0) {
906 panic_on_trap_mask = DEFAULT_PANIC_ON_TRAP_MASK;
907 } else {
908 panic_on_trap_mask = 0;
909 }
910 }
911 #endif
912 /* But allow that to be overridden via boot-arg: */
913 if (!PE_parse_boot_argn("lbr_support", &last_branch_support_enabled,
914 sizeof(last_branch_support_enabled))) {
915 /* Disable LBR support by default due to its high context switch overhead */
916 last_branch_support_enabled = false;
917 }
918
919 serialmode = 0;
920 if (PE_parse_boot_argn("serial", &serialmode, sizeof(serialmode))) {
921 /* We want a serial keyboard and/or console */
922 kprintf("Serial mode specified: %08X\n", serialmode);
923 int force_sync = serialmode & SERIALMODE_SYNCDRAIN;
924 if (force_sync || PE_parse_boot_argn("drain_uart_sync", &force_sync, sizeof(force_sync))) {
925 if (force_sync) {
926 serialmode |= SERIALMODE_SYNCDRAIN;
927 kprintf(
928 "WARNING: Forcing uart driver to output synchronously."
929 "printf()s/IOLogs will impact kernel performance.\n"
930 "You are advised to avoid using 'drain_uart_sync' boot-arg.\n");
931 }
932 }
933 }
934 if (serialmode & SERIALMODE_OUTPUT) {
935 (void)switch_to_serial_console();
936 disableConsoleOutput = FALSE; /* Allow printfs to happen */
937 }
938
939 /* setup console output */
940 kernel_debug_string_early("PE_init_printf");
941 PE_init_printf(FALSE);
942
943 kprintf("version_variant = %s\n", version_variant);
944 kprintf("version = %s\n", version);
945
946 if (!PE_parse_boot_argn("maxmem", &maxmem, sizeof(maxmem))) {
947 maxmemtouse = 0;
948 } else {
949 maxmemtouse = ((uint64_t)maxmem) * MB;
950 }
951
952 max_cpus_from_firmware = acpi_count_enabled_logical_processors();
953
954 if (PE_parse_boot_argn("cpus", &cpus, sizeof(cpus))) {
955 if ((0 < cpus) && (cpus < max_ncpus)) {
956 max_ncpus = cpus;
957 }
958 }
959
960 /*
961 * debug support for > 4G systems
962 */
963 PE_parse_boot_argn("himemory_mode", &vm_himemory_mode, sizeof(vm_himemory_mode));
964 if (!vm_himemory_mode) {
965 kprintf("himemory_mode disabled\n");
966 }
967
968 if (!PE_parse_boot_argn("immediate_NMI", &fidn, sizeof(fidn))) {
969 force_immediate_debugger_NMI = FALSE;
970 } else {
971 force_immediate_debugger_NMI = fidn;
972 }
973
974 #if DEBUG
975 nanoseconds_to_absolutetime(URGENCY_NOTIFICATION_ASSERT_NS, &urgency_notification_assert_abstime_threshold);
976 #endif
977 PE_parse_boot_argn("urgency_notification_abstime",
978 &urgency_notification_assert_abstime_threshold,
979 sizeof(urgency_notification_assert_abstime_threshold));
980
981 if (!(cpuid_extfeatures() & CPUID_EXTFEATURE_XD)) {
982 nx_enabled = 0;
983 }
984
985 /*
986 * VM initialization, after this we're using page tables...
987 * Thn maximum number of cpus must be set beforehand.
988 */
989 kernel_debug_string_early("i386_vm_init");
990 i386_vm_init(maxmemtouse, IA32e, kernelBootArgs);
991
992 /* create the console for verbose or pretty mode */
993 /* Note: doing this prior to tsc_init() allows for graceful panic! */
994 PE_init_platform(TRUE, kernelBootArgs);
995 PE_create_console();
996
997 kernel_debug_string_early("power_management_init");
998 power_management_init();
999 xcpm_bootstrap();
1000
1001 #if MONOTONIC
1002 mt_cpu_up(cpu_datap(0));
1003 #endif /* MONOTONIC */
1004
1005 processor_bootstrap();
1006 thread_t thread = thread_bootstrap();
1007 machine_set_current_thread(thread);
1008
1009 pstate_trace();
1010 kernel_debug_string_early("machine_startup");
1011 machine_startup();
1012 pstate_trace();
1013 }
1014
1015 static void __dead2
1016 do_init_slave(boolean_t fast_restart)
1017 {
1018 void *init_param = FULL_SLAVE_INIT;
1019
1020 postcode(I386_INIT_SLAVE);
1021
1022 if (!fast_restart) {
1023 /* Ensure that caching and write-through are enabled */
1024 set_cr0(get_cr0() & ~(CR0_NW | CR0_CD));
1025
1026 DBG("i386_init_slave() CPU%d: phys (%d) active.\n",
1027 get_cpu_number(), get_cpu_phys_number());
1028
1029 assert(!ml_get_interrupts_enabled());
1030
1031 cpu_syscall_init(current_cpu_datap());
1032 pmap_cpu_init();
1033
1034 #if CONFIG_MCA
1035 mca_cpu_init();
1036 #endif
1037
1038 LAPIC_INIT();
1039 /*
1040 * Note that the true argument here does not necessarily mean we're
1041 * here from a resume (this code path is also executed on boot).
1042 * The implementation of lapic_configure checks to see if the
1043 * state variable has been initialized, as it would be before
1044 * sleep. If it has not been, it's construed as an indicator of
1045 * first boot.
1046 */
1047 lapic_configure(true);
1048 LAPIC_DUMP();
1049 LAPIC_CPU_MAP_DUMP();
1050
1051 init_fpu();
1052
1053 #if CONFIG_MTRR
1054 mtrr_update_cpu();
1055 #endif
1056 /* update CPU microcode and apply CPU workarounds */
1057 ucode_update_wake_and_apply_cpu_was();
1058
1059 /* Enable LBRs on non-boot CPUs */
1060 i386_lbr_init(cpuid_info(), false);
1061 } else {
1062 init_param = FAST_SLAVE_INIT;
1063 }
1064
1065 #if CONFIG_VMX
1066 /* resume VT operation */
1067 vmx_resume(FALSE);
1068 #endif
1069
1070 #if CONFIG_MTRR
1071 if (!fast_restart) {
1072 pat_init();
1073 }
1074 #endif
1075
1076 cpu_thread_init(); /* not strictly necessary */
1077
1078 cpu_init(); /* Sets cpu_running which starter cpu waits for */
1079
1080
1081 #if MONOTONIC
1082 mt_cpu_up(current_cpu_datap());
1083 #endif /* MONOTONIC */
1084
1085 slave_main(init_param);
1086
1087 panic("do_init_slave() returned from slave_main()");
1088 }
1089
1090 /*
1091 * i386_init_slave() is called from pstart.
1092 * We're in the cpu's interrupt stack with interrupts disabled.
1093 * At this point we are in legacy mode. We need to switch on IA32e
1094 * if the mode is set to 64-bits.
1095 */
1096 void
1097 i386_init_slave(void)
1098 {
1099 do_init_slave(FALSE);
1100 }
1101
1102 /*
1103 * i386_init_slave_fast() is called from pmCPUHalt.
1104 * We're running on the idle thread and need to fix up
1105 * some accounting and get it so that the scheduler sees this
1106 * CPU again.
1107 */
1108 void
1109 i386_init_slave_fast(void)
1110 {
1111 do_init_slave(TRUE);
1112 }
1113
1114
1115 /* TODO: Evaluate global PTEs for the double-mapped translations */
1116
1117 uint64_t dblmap_base, dblmap_max;
1118 kernel_segment_command_t *hdescseg;
1119
1120 pt_entry_t *dblmapL3;
1121 unsigned int dblallocs;
1122 uint64_t dblmap_dist;
1123 extern uint64_t idt64_hndl_table0[];
1124
1125
1126 void
1127 doublemap_init(uint8_t randL3)
1128 {
1129 dblmapL3 = ALLOCPAGES(1); // for 512 1GiB entries
1130 dblallocs++;
1131
1132 struct {
1133 pt_entry_t entries[PTE_PER_PAGE];
1134 } * dblmapL2 = ALLOCPAGES(1); // for 512 2MiB entries
1135 dblallocs++;
1136
1137 dblmapL3[randL3] = ((uintptr_t)ID_MAP_VTOP(&dblmapL2[0]))
1138 | INTEL_PTE_VALID
1139 | INTEL_PTE_WRITE;
1140
1141 hdescseg = getsegbynamefromheader(&_mh_execute_header, "__HIB");
1142
1143 vm_offset_t hdescb = hdescseg->vmaddr;
1144 unsigned long hdescsz = hdescseg->vmsize;
1145 unsigned long hdescszr = round_page_64(hdescsz);
1146 vm_offset_t hdescc = hdescb, hdesce = hdescb + hdescszr;
1147
1148 kernel_section_t *thdescsect = getsectbynamefromheader(&_mh_execute_header, "__HIB", "__text");
1149 vm_offset_t thdescb = thdescsect->addr;
1150 unsigned long thdescsz = thdescsect->size;
1151 unsigned long thdescszr = round_page_64(thdescsz);
1152 vm_offset_t thdesce = thdescb + thdescszr;
1153
1154 assert((hdescb & 0xFFF) == 0);
1155 /* Mirror HIB translations into the double-mapped pagetable subtree*/
1156 for (int i = 0; hdescc < hdesce; i++) {
1157 struct {
1158 pt_entry_t entries[PTE_PER_PAGE];
1159 } * dblmapL1 = ALLOCPAGES(1);
1160 dblallocs++;
1161 dblmapL2[0].entries[i] = ((uintptr_t)ID_MAP_VTOP(&dblmapL1[0])) | INTEL_PTE_VALID | INTEL_PTE_WRITE | INTEL_PTE_REF;
1162 int hdescn = (int) ((hdesce - hdescc) / PAGE_SIZE);
1163 for (int j = 0; j < MIN(PTE_PER_PAGE, hdescn); j++) {
1164 uint64_t template = INTEL_PTE_VALID;
1165 if ((hdescc >= thdescb) && (hdescc < thdesce)) {
1166 /* executable */
1167 } else {
1168 template |= INTEL_PTE_WRITE | INTEL_PTE_NX; /* Writeable, NX */
1169 }
1170 dblmapL1[0].entries[j] = ((uintptr_t)ID_MAP_VTOP(hdescc)) | template;
1171 hdescc += PAGE_SIZE;
1172 }
1173 }
1174
1175 IdlePML4[KERNEL_DBLMAP_PML4_INDEX] = ((uintptr_t)ID_MAP_VTOP(dblmapL3)) | INTEL_PTE_VALID | INTEL_PTE_WRITE | INTEL_PTE_REF;
1176
1177 dblmap_base = KVADDR(KERNEL_DBLMAP_PML4_INDEX, randL3, 0, 0);
1178 dblmap_max = dblmap_base + hdescszr;
1179 /* Calculate the double-map distance, which accounts for the current
1180 * KASLR slide
1181 */
1182
1183 dblmap_dist = dblmap_base - hdescb;
1184 idt64_hndl_table0[1] = DBLMAP(idt64_hndl_table0[1]); /* 64-bit exit trampoline */
1185 idt64_hndl_table0[3] = DBLMAP(idt64_hndl_table0[3]); /* 32-bit exit trampoline */
1186 idt64_hndl_table0[6] = (uint64_t)(uintptr_t)&kernel_stack_mask;
1187
1188 extern cpu_data_t cpshadows[], scdatas[];
1189 uintptr_t cd1 = (uintptr_t) &cpshadows[0];
1190 uintptr_t cd2 = (uintptr_t) &scdatas[0];
1191 /* Record the displacement from the kernel's per-CPU data pointer, eventually
1192 * programmed into GSBASE, to the "shadows" in the doublemapped
1193 * region. These are not aliases, but separate physical allocations
1194 * containing data required in the doublemapped trampolines.
1195 */
1196 idt64_hndl_table0[2] = dblmap_dist + cd1 - cd2;
1197
1198 DBG("Double map base: 0x%qx\n", dblmap_base);
1199 DBG("double map idlepml4[%d]: 0x%llx\n", KERNEL_DBLMAP_PML4_INDEX, IdlePML4[KERNEL_DBLMAP_PML4_INDEX]);
1200 assert(LDTSZ > LDTSZ_MIN);
1201 }
1202
1203 vm_offset_t dyn_dblmap(vm_offset_t, vm_offset_t);
1204
1205 #include <i386/pmap_internal.h>
1206
1207 /* Use of this routine is expected to be synchronized by callers
1208 * Creates non-executable aliases.
1209 */
1210 vm_offset_t
1211 dyn_dblmap(vm_offset_t cva, vm_offset_t sz)
1212 {
1213 vm_offset_t ava = dblmap_max;
1214
1215 assert((sz & PAGE_MASK) == 0);
1216 assert(cva != 0);
1217
1218 pmap_alias(ava, cva, cva + sz, VM_PROT_READ | VM_PROT_WRITE, PMAP_EXPAND_OPTIONS_ALIASMAP);
1219 dblmap_max += sz;
1220 return ava - cva;
1221 }
1222 /* Adjust offsets interior to the bootstrap interrupt descriptor table to redirect
1223 * control to the double-mapped interrupt vectors. The IDTR proper will be
1224 * programmed via cpu_desc_load()
1225 */
1226 void
1227 idt64_remap(void)
1228 {
1229 for (int i = 0; i < IDTSZ; i++) {
1230 master_idt64[i].offset64 = DBLMAP(master_idt64[i].offset64);
1231 }
1232 }