2 * Copyright (c) 2003-2019 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989, 1988 Carnegie Mellon University
34 * All Rights Reserved.
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.
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.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
58 #include <mach/i386/vm_param.h>
62 #include <mach/vm_param.h>
63 #include <mach/vm_prot.h>
64 #include <mach/machine.h>
65 #include <mach/time_value.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>
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>
79 #include <vm/vm_kern.h>
80 #include <machine/pal_routines.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>
88 #include <i386/mp_desc.h>
90 #include <i386/mtrr.h>
92 #include <i386/machine_routines.h>
94 #include <i386/machine_check.h>
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 */
103 #include <machine/pal_routines.h>
107 #include <kern/monotonic.h>
108 #endif /* MONOTONIC */
110 #include <san/kasan.h>
113 #define DBG(x ...) kprintf(x)
122 static boot_args
*kernelBootArgs
;
124 extern int disableConsoleOutput
;
125 extern const char version
[];
126 extern const char version_variant
[];
127 extern int nx_enabled
;
130 * Set initial values so that ml_phys_* routines can use the booter's ID mapping
131 * to touch physical space before the kernel's physical aperture exists.
133 uint64_t physmap_base
= 0;
134 uint64_t physmap_max
= 4 * GB
;
138 pdpt_entry_t
*IdlePDPT
;
139 pml4_entry_t
*IdlePML4
;
141 int kernPhysPML4Index
;
142 int kernPhysPML4EntryCount
;
145 * These are 4K mapping page table pages from KPTphys[] that we wound
146 * up not using. They get ml_static_mfree()'d once the VM is initialized.
148 ppnum_t released_PT_ppn
= 0;
149 uint32_t released_PT_cnt
= 0;
152 void idt64_remap(void);
155 * Note: ALLOCPAGES() can only be used safely within Idle_PTs_init()
156 * due to the mutation of physfree.
159 ALLOCPAGES(int npages
)
161 uintptr_t tmp
= (uintptr_t)physfree
;
162 bzero(physfree
, npages
* PAGE_SIZE
);
163 physfree
+= npages
* PAGE_SIZE
;
164 tmp
+= VM_MIN_KERNEL_ADDRESS
& ~LOW_4GB_MASK
;
169 fillkpt(pt_entry_t
*base
, int prot
, uintptr_t src
, int index
, int count
)
172 for (i
= 0; i
< count
; i
++) {
173 base
[index
] = src
| prot
| INTEL_PTE_VALID
;
179 extern pmap_paddr_t first_avail
;
181 int break_kprintf
= 0;
184 x86_64_pre_sleep(void)
186 IdlePML4
[0] = IdlePML4
[KERNEL_PML4_INDEX
];
187 uint64_t oldcr3
= get_cr3_raw();
188 set_cr3_raw((uint32_t) (uintptr_t)ID_MAP_VTOP(IdlePML4
));
193 x86_64_post_sleep(uint64_t new_cr3
)
196 set_cr3_raw((uint32_t) new_cr3
);
202 // Set up the physical mapping - NPHYSMAP GB of memory mapped at a high address
203 // NPHYSMAP is determined by the maximum supported RAM size plus 4GB to account
204 // the PCI hole (which is less 4GB but not more).
207 physmap_init_L2(uint64_t *physStart
, pt_entry_t
**l2ptep
)
210 pt_entry_t
*physmapL2
= ALLOCPAGES(1);
212 if (physmapL2
== NULL
) {
213 DBG("physmap_init_L2 page alloc failed when initting L2 for physAddr 0x%llx.\n", *physStart
);
218 for (i
= 0; i
< NPDPG
; i
++) {
219 physmapL2
[i
] = *physStart
232 physmap_init_L3(int startIndex
, uint64_t highest_phys
, uint64_t *physStart
, pt_entry_t
**l3ptep
)
237 pt_entry_t
*physmapL3
= ALLOCPAGES(1); /* ALLOCPAGES bzeroes the memory */
239 if (physmapL3
== NULL
) {
240 DBG("physmap_init_L3 page alloc failed when initting L3 for physAddr 0x%llx.\n", *physStart
);
245 for (i
= startIndex
; i
< NPDPTPG
&& *physStart
< highest_phys
; i
++) {
246 if ((ret
= physmap_init_L2(physStart
, &l2pte
)) < 0) {
250 physmapL3
[i
] = ((uintptr_t)ID_MAP_VTOP(l2pte
))
262 physmap_init(uint8_t phys_random_L3
)
267 uint64_t physAddr
= 0;
268 uint64_t highest_physaddr
;
269 unsigned pdpte_count
;
271 #if DEVELOPMENT || DEBUG
272 if (kernelBootArgs
->PhysicalMemorySize
> K64_MAXMEM
) {
273 panic("Installed physical memory exceeds configured maximum.");
278 * Add 4GB to the loader-provided physical memory size to account for MMIO space
279 * XXX in a perfect world, we'd scan PCI buses and count the max memory requested in BARs by
280 * XXX all enumerated device, then add more for hot-pluggable devices.
282 highest_physaddr
= kernelBootArgs
->PhysicalMemorySize
+ 4 * GB
;
285 * Calculate the number of PML4 entries we'll need. The total number of entries is
286 * pdpte_count = (((highest_physaddr) >> PDPT_SHIFT) + entropy_value +
287 * ((highest_physaddr & PDPT_MASK) == 0 ? 0 : 1))
288 * pml4e_count = pdpte_count >> (PML4_SHIFT - PDPT_SHIFT)
290 assert(highest_physaddr
< (UINT64_MAX
- PDPTMASK
));
291 pdpte_count
= (unsigned) (((highest_physaddr
+ PDPTMASK
) >> PDPTSHIFT
) + phys_random_L3
);
292 kernPhysPML4EntryCount
= (pdpte_count
+ ((1U << (PML4SHIFT
- PDPTSHIFT
)) - 1)) >> (PML4SHIFT
- PDPTSHIFT
);
293 if (kernPhysPML4EntryCount
== 0) {
294 kernPhysPML4EntryCount
= 1;
296 if (kernPhysPML4EntryCount
> KERNEL_PHYSMAP_PML4_COUNT_MAX
) {
297 #if DEVELOPMENT || DEBUG
298 panic("physmap too large");
300 kprintf("[pmap] Limiting physmap to %d PML4s (was %d)\n", KERNEL_PHYSMAP_PML4_COUNT_MAX
,
301 kernPhysPML4EntryCount
);
302 kernPhysPML4EntryCount
= KERNEL_PHYSMAP_PML4_COUNT_MAX
;
306 kernPhysPML4Index
= KERNEL_KEXTS_INDEX
- kernPhysPML4EntryCount
; /* utb: KERNEL_PHYSMAP_PML4_INDEX */
309 * XXX: Make sure that the addresses returned for physmapL3 and physmapL2 plus their extents
310 * are in the system-available memory range
314 /* We assume NX support. Mark all levels of the PHYSMAP NX
315 * to avoid granting executability via a single bit flip.
317 #if DEVELOPMENT || DEBUG
319 do_cpuid(0x80000000, reg
);
320 if (reg
[eax
] >= 0x80000001) {
321 do_cpuid(0x80000001, reg
);
322 assert(reg
[edx
] & CPUID_EXTFEATURE_XD
);
324 #endif /* DEVELOPMENT || DEBUG */
326 L3_start_index
= phys_random_L3
;
328 for (pml4_index
= kernPhysPML4Index
;
329 pml4_index
< (kernPhysPML4Index
+ kernPhysPML4EntryCount
) && physAddr
< highest_physaddr
;
331 if (physmap_init_L3(L3_start_index
, highest_physaddr
, &physAddr
, &l3pte
) < 0) {
332 panic("Physmap page table initialization failed");
338 IdlePML4
[pml4_index
] = ((uintptr_t)ID_MAP_VTOP(l3pte
))
344 physmap_base
= KVADDR(kernPhysPML4Index
, phys_random_L3
, 0, 0);
346 * physAddr contains the last-mapped physical address, so that's what we
347 * add to physmap_base to derive the ending VA for the physmap.
349 physmap_max
= physmap_base
+ physAddr
;
351 DBG("Physical address map base: 0x%qx\n", physmap_base
);
352 for (i
= kernPhysPML4Index
; i
< (kernPhysPML4Index
+ kernPhysPML4EntryCount
); i
++) {
353 DBG("Physical map idlepml4[%d]: 0x%llx\n", i
, IdlePML4
[i
]);
357 void doublemap_init(uint8_t);
364 /* Allocate the "idle" kernel page tables: */
365 KPTphys
= ALLOCPAGES(NKPT
); /* level 1 */
366 IdlePTD
= ALLOCPAGES(NPGPTD
); /* level 2 */
367 IdlePDPT
= ALLOCPAGES(1); /* level 3 */
368 IdlePML4
= ALLOCPAGES(1); /* level 4 */
370 // Fill the lowest level with everything up to physfree
372 INTEL_PTE_WRITE
, 0, 0, (int)(((uintptr_t)physfree
) >> PAGE_SHIFT
));
376 INTEL_PTE_WRITE
, (uintptr_t)ID_MAP_VTOP(KPTphys
), 0, NKPT
);
380 INTEL_PTE_WRITE
, (uintptr_t)ID_MAP_VTOP(IdlePTD
), 0, NPGPTD
);
382 // IdlePML4 single entry for kernel space.
383 fillkpt(IdlePML4
+ KERNEL_PML4_INDEX
,
384 INTEL_PTE_WRITE
, (uintptr_t)ID_MAP_VTOP(IdlePDPT
), 0, 1);
386 postcode(VSTART_PHYSMAP_INIT
);
389 * early_random() cannot be called more than one time before the cpu's
390 * gsbase is initialized, so use the full 64-bit value to extract the
391 * two 8-bit entropy values needed for address randomization.
393 rand64
= early_random();
394 physmap_init(rand64
& 0xFF);
395 doublemap_init((rand64
>> 8) & 0xFF);
398 postcode(VSTART_SET_CR3
);
400 // Switch to the page tables..
401 set_cr3_raw((uintptr_t)ID_MAP_VTOP(IdlePML4
));
405 * Release any still unused, preallocated boot kernel page tables.
406 * start..end is the VA range currently unused.
409 Idle_PTs_release(vm_offset_t start
, vm_offset_t end
)
412 uint32_t index_start
;
413 uint32_t index_limit
;
419 * Align start to the next large page boundary
421 start
= ((start
+ I386_LPGMASK
) & ~I386_LPGMASK
);
424 * convert start into an index in KPTphys[]
426 index_start
= (uint32_t)((start
- KERNEL_BASE
) >> PAGE_SHIFT
);
429 * Find the ending index in KPTphys[]
431 index_limit
= (uint32_t)((end
- KERNEL_BASE
) >> PAGE_SHIFT
);
433 if (index_limit
> NKPT
* PTE_PER_PAGE
) {
434 index_limit
= NKPT
* PTE_PER_PAGE
;
438 * Make sure all the 4K page tables are empty.
439 * If not, panic a development/debug kernel.
440 * On a production kernel, since this would stop us from booting,
441 * just abort the operation.
443 for (i
= index_start
; i
< index_limit
; ++i
) {
444 assert(KPTphys
[i
] == 0);
445 if (KPTphys
[i
] != 0) {
451 * Now figure out the indices into the 2nd level page tables, IdlePTD[].
453 index_start
>>= PTPGSHIFT
;
454 index_limit
>>= PTPGSHIFT
;
455 if (index_limit
> NPGPTD
* PTE_PER_PAGE
) {
456 index_limit
= NPGPTD
* PTE_PER_PAGE
;
459 if (index_limit
<= index_start
) {
465 * Now check the pages referenced from Level 2 tables.
466 * They should be contiguous, assert fail if not on development/debug.
467 * In production, just fail the removal to allow the system to boot.
471 for (i
= index_start
; i
< index_limit
; ++i
) {
472 assert(IdlePTD
[i
] != 0);
473 if (IdlePTD
[i
] == 0) {
477 pn
= (ppnum_t
)((PG_FRAME
& IdlePTD
[i
]) >> PTSHIFT
);
481 assert(pn
== pn_first
+ cnt
);
482 if (pn
!= pn_first
+ cnt
) {
490 * Good to go, clear the level 2 entries and invalidate the TLB
492 for (i
= index_start
; i
< index_limit
; ++i
) {
495 set_cr3_raw(get_cr3_raw());
498 * Remember these PFNs to be released later in pmap_lowmem_finalize()
500 released_PT_ppn
= pn_first
;
501 released_PT_cnt
= cnt
;
502 #if DEVELOPMENT || DEBUG
503 printf("Idle_PTs_release %d pages from PFN 0x%x\n", released_PT_cnt
, released_PT_ppn
);
507 extern void vstart_trap_handler
;
509 #define BOOT_TRAP_VECTOR(t) \
511 (uintptr_t) &vstart_trap_handler, \
514 ACC_P|ACC_PL_K|ACC_INTR_GATE, \
518 /* Recursive macro to iterate 0..31 */
519 #define L0(x, n) x(n)
520 #define L1(x, n) L0(x,n-1) L0(x,n)
521 #define L2(x, n) L1(x,n-2) L1(x,n)
522 #define L3(x, n) L2(x,n-4) L2(x,n)
523 #define L4(x, n) L3(x,n-8) L3(x,n)
524 #define L5(x, n) L4(x,n-16) L4(x,n)
525 #define FOR_0_TO_31(x) L5(x,31)
528 * Bootstrap IDT. Active only during early startup.
529 * Only the trap vectors are defined since interrupts are masked.
530 * All traps point to a common handler.
532 struct fake_descriptor64 master_boot_idt64
[IDTSZ
]
533 __attribute__((section("__HIB,__desc")))
534 __attribute__((aligned(PAGE_SIZE
))) = {
535 FOR_0_TO_31(BOOT_TRAP_VECTOR
)
539 vstart_idt_init(void)
541 x86_64_desc_register_t vstart_idt
= {
542 sizeof(master_boot_idt64
),
546 fix_desc64(master_boot_idt64
, 32);
547 lidt((void *)&vstart_idt
);
551 * vstart() is called in the natural mode (64bit for K64, 32 for K32)
552 * on a set of bootstrap pagetables which use large, 2MB pages to map
553 * all of physical memory in both. See idle_pt.c for details.
555 * In K64 this identity mapping is mirrored the top and bottom 512GB
558 * The bootstrap processor called with argument boot_args_start pointing to
559 * the boot-args block. The kernel's (4K page) page tables are allocated and
560 * initialized before switching to these.
562 * Non-bootstrap processors are called with argument boot_args_start NULL.
563 * These processors switch immediately to the existing kernel page tables.
565 __attribute__((noreturn
))
567 vstart(vm_offset_t boot_args_start
)
569 boolean_t is_boot_cpu
= !(boot_args_start
== 0);
573 postcode(VSTART_ENTRY
);
577 * Set-up temporary trap handlers during page-table set-up.
580 postcode(VSTART_IDT_INIT
);
583 * Ensure that any %gs-relative access results in an immediate fault
584 * until gsbase is properly initialized below
586 wrmsr64(MSR_IA32_GS_BASE
, EARLY_GSBASE_MAGIC
);
589 * Get startup parameters.
591 kernelBootArgs
= (boot_args
*)boot_args_start
;
592 lphysfree
= kernelBootArgs
->kaddr
+ kernelBootArgs
->ksize
;
593 physfree
= (void *)(uintptr_t)((lphysfree
+ PAGE_SIZE
- 1) & ~(PAGE_SIZE
- 1));
597 DBG("revision 0x%x\n", kernelBootArgs
->Revision
);
598 DBG("version 0x%x\n", kernelBootArgs
->Version
);
599 DBG("command line %s\n", kernelBootArgs
->CommandLine
);
600 DBG("memory map 0x%x\n", kernelBootArgs
->MemoryMap
);
601 DBG("memory map sz 0x%x\n", kernelBootArgs
->MemoryMapSize
);
602 DBG("kaddr 0x%x\n", kernelBootArgs
->kaddr
);
603 DBG("ksize 0x%x\n", kernelBootArgs
->ksize
);
604 DBG("physfree %p\n", physfree
);
605 DBG("bootargs: %p, &ksize: %p &kaddr: %p\n",
607 &kernelBootArgs
->ksize
,
608 &kernelBootArgs
->kaddr
);
609 DBG("SMBIOS mem sz 0x%llx\n", kernelBootArgs
->PhysicalMemorySize
);
612 * Setup boot args given the physical start address.
613 * Note: PE_init_platform needs to be called before Idle_PTs_init
614 * because access to the DeviceTree is required to read the
615 * random seed before generating a random physical map slide.
617 kernelBootArgs
= (boot_args
*)
618 ml_static_ptovirt(boot_args_start
);
619 DBG("i386_init(0x%lx) kernelBootArgs=%p\n",
620 (unsigned long)boot_args_start
, kernelBootArgs
);
623 kasan_reserve_memory(kernelBootArgs
);
626 PE_init_platform(FALSE
, kernelBootArgs
);
627 postcode(PE_INIT_PLATFORM_D
);
630 postcode(VSTART_IDLE_PTS_INIT
);
633 /* Init kasan and map whatever was stolen from physfree */
635 kasan_notify_stolen((uintptr_t)ml_static_ptovirt((vm_offset_t
)physfree
));
640 #endif /* MONOTONIC */
642 first_avail
= (vm_offset_t
)ID_MAP_VTOP(physfree
);
644 cpu_data_alloc(TRUE
);
646 cpu_desc_init(cpu_datap(0));
647 postcode(VSTART_CPU_DESC_INIT
);
648 cpu_desc_load(cpu_datap(0));
650 postcode(VSTART_CPU_MODE_INIT
);
651 cpu_syscall_init(cpu_datap(0)); /* cpu_syscall_init() will be
653 * via i386_init_slave()
656 /* Switch to kernel's page tables (from the Boot PTs) */
657 set_cr3_raw((uintptr_t)ID_MAP_VTOP(IdlePML4
));
658 /* Find our logical cpu number */
659 cpu
= lapic_to_cpu
[(LAPIC_READ(ID
) >> LAPIC_ID_SHIFT
) & LAPIC_ID_MASK
];
660 DBG("CPU: %d, GSBASE initial value: 0x%llx\n", cpu
, rdmsr64(MSR_IA32_GS_BASE
));
661 cpu_desc_load(cpu_datap(cpu
));
665 postcode(VSTART_EXIT
);
666 x86_init_wrapper(is_boot_cpu
? (uintptr_t) i386_init
667 : (uintptr_t) i386_init_slave
,
668 cpu_datap(cpu
)->cpu_int_stack_top
);
677 * Cpu initialization. Running virtual, but without MACH VM
684 uint64_t maxmemtouse
;
685 unsigned int cpus
= 0;
687 boolean_t IA32e
= TRUE
;
689 postcode(I386_INIT_ENTRY
);
693 rtclock_early_init(); /* mach_absolute_time() now functionsl */
695 kernel_debug_string_early("i386_init");
699 /* Initialize machine-check handling */
708 * Initialize the timer callout world
714 postcode(CPU_INIT_D
);
716 printf_init(); /* Init this in case we need debugger */
717 panic_init(); /* Init this in case we need debugger */
719 /* setup debugging output if one has been chosen */
720 kernel_debug_string_early("PE_init_kprintf");
721 PE_init_kprintf(FALSE
);
723 kernel_debug_string_early("kernel_early_bootstrap");
724 kernel_early_bootstrap();
726 if (!PE_parse_boot_argn("diag", &dgWork
.dgFlags
, sizeof(dgWork
.dgFlags
))) {
731 if (PE_parse_boot_argn("serial", &serialmode
, sizeof(serialmode
))) {
732 /* We want a serial keyboard and/or console */
733 kprintf("Serial mode specified: %08X\n", serialmode
);
734 int force_sync
= serialmode
& SERIALMODE_SYNCDRAIN
;
735 if (force_sync
|| PE_parse_boot_argn("drain_uart_sync", &force_sync
, sizeof(force_sync
))) {
737 serialmode
|= SERIALMODE_SYNCDRAIN
;
739 "WARNING: Forcing uart driver to output synchronously."
740 "printf()s/IOLogs will impact kernel performance.\n"
741 "You are advised to avoid using 'drain_uart_sync' boot-arg.\n");
745 if (serialmode
& SERIALMODE_OUTPUT
) {
746 (void)switch_to_serial_console();
747 disableConsoleOutput
= FALSE
; /* Allow printfs to happen */
750 /* setup console output */
751 kernel_debug_string_early("PE_init_printf");
752 PE_init_printf(FALSE
);
754 kprintf("version_variant = %s\n", version_variant
);
755 kprintf("version = %s\n", version
);
757 if (!PE_parse_boot_argn("maxmem", &maxmem
, sizeof(maxmem
))) {
760 maxmemtouse
= ((uint64_t)maxmem
) * MB
;
763 if (PE_parse_boot_argn("cpus", &cpus
, sizeof(cpus
))) {
764 if ((0 < cpus
) && (cpus
< max_ncpus
)) {
770 * debug support for > 4G systems
772 PE_parse_boot_argn("himemory_mode", &vm_himemory_mode
, sizeof(vm_himemory_mode
));
773 if (!vm_himemory_mode
) {
774 kprintf("himemory_mode disabled\n");
777 if (!PE_parse_boot_argn("immediate_NMI", &fidn
, sizeof(fidn
))) {
778 force_immediate_debugger_NMI
= FALSE
;
780 force_immediate_debugger_NMI
= fidn
;
784 nanoseconds_to_absolutetime(URGENCY_NOTIFICATION_ASSERT_NS
, &urgency_notification_assert_abstime_threshold
);
786 PE_parse_boot_argn("urgency_notification_abstime",
787 &urgency_notification_assert_abstime_threshold
,
788 sizeof(urgency_notification_assert_abstime_threshold
));
790 if (!(cpuid_extfeatures() & CPUID_EXTFEATURE_XD
)) {
795 * VM initialization, after this we're using page tables...
796 * Thn maximum number of cpus must be set beforehand.
798 kernel_debug_string_early("i386_vm_init");
799 i386_vm_init(maxmemtouse
, IA32e
, kernelBootArgs
);
801 /* create the console for verbose or pretty mode */
802 /* Note: doing this prior to tsc_init() allows for graceful panic! */
803 PE_init_platform(TRUE
, kernelBootArgs
);
806 kernel_debug_string_early("power_management_init");
807 power_management_init();
810 mt_cpu_up(cpu_datap(0));
811 #endif /* MONOTONIC */
813 processor_bootstrap();
817 kernel_debug_string_early("machine_startup");
823 do_init_slave(boolean_t fast_restart
)
825 void *init_param
= FULL_SLAVE_INIT
;
827 postcode(I386_INIT_SLAVE
);
830 /* Ensure that caching and write-through are enabled */
831 set_cr0(get_cr0() & ~(CR0_NW
| CR0_CD
));
833 DBG("i386_init_slave() CPU%d: phys (%d) active.\n",
834 get_cpu_number(), get_cpu_phys_number());
836 assert(!ml_get_interrupts_enabled());
838 cpu_syscall_init(current_cpu_datap());
848 LAPIC_CPU_MAP_DUMP();
855 /* update CPU microcode */
858 /* Do CPU workarounds after the microcode update */
861 init_param
= FAST_SLAVE_INIT
;
865 /* resume VT operation */
875 cpu_thread_init(); /* not strictly necessary */
877 cpu_init(); /* Sets cpu_running which starter cpu waits for */
881 mt_cpu_up(current_cpu_datap());
882 #endif /* MONOTONIC */
884 slave_main(init_param
);
886 panic("do_init_slave() returned from slave_main()");
890 * i386_init_slave() is called from pstart.
891 * We're in the cpu's interrupt stack with interrupts disabled.
892 * At this point we are in legacy mode. We need to switch on IA32e
893 * if the mode is set to 64-bits.
896 i386_init_slave(void)
898 do_init_slave(FALSE
);
902 * i386_init_slave_fast() is called from pmCPUHalt.
903 * We're running on the idle thread and need to fix up
904 * some accounting and get it so that the scheduler sees this
908 i386_init_slave_fast(void)
913 #include <libkern/kernel_mach_header.h>
915 /* TODO: Evaluate global PTEs for the double-mapped translations */
917 uint64_t dblmap_base
, dblmap_max
;
918 kernel_segment_command_t
*hdescseg
;
920 pt_entry_t
*dblmapL3
;
921 unsigned int dblallocs
;
922 uint64_t dblmap_dist
;
923 extern uint64_t idt64_hndl_table0
[];
927 doublemap_init(uint8_t randL3
)
929 dblmapL3
= ALLOCPAGES(1); // for 512 1GiB entries
933 pt_entry_t entries
[PTE_PER_PAGE
];
934 } * dblmapL2
= ALLOCPAGES(1); // for 512 2MiB entries
937 dblmapL3
[randL3
] = ((uintptr_t)ID_MAP_VTOP(&dblmapL2
[0]))
941 hdescseg
= getsegbynamefromheader(&_mh_execute_header
, "__HIB");
943 vm_offset_t hdescb
= hdescseg
->vmaddr
;
944 unsigned long hdescsz
= hdescseg
->vmsize
;
945 unsigned long hdescszr
= round_page_64(hdescsz
);
946 vm_offset_t hdescc
= hdescb
, hdesce
= hdescb
+ hdescszr
;
948 kernel_section_t
*thdescsect
= getsectbynamefromheader(&_mh_execute_header
, "__HIB", "__text");
949 vm_offset_t thdescb
= thdescsect
->addr
;
950 unsigned long thdescsz
= thdescsect
->size
;
951 unsigned long thdescszr
= round_page_64(thdescsz
);
952 vm_offset_t thdesce
= thdescb
+ thdescszr
;
954 assert((hdescb
& 0xFFF) == 0);
955 /* Mirror HIB translations into the double-mapped pagetable subtree*/
956 for (int i
= 0; hdescc
< hdesce
; i
++) {
958 pt_entry_t entries
[PTE_PER_PAGE
];
959 } * dblmapL1
= ALLOCPAGES(1);
961 dblmapL2
[0].entries
[i
] = ((uintptr_t)ID_MAP_VTOP(&dblmapL1
[0])) | INTEL_PTE_VALID
| INTEL_PTE_WRITE
| INTEL_PTE_REF
;
962 int hdescn
= (int) ((hdesce
- hdescc
) / PAGE_SIZE
);
963 for (int j
= 0; j
< MIN(PTE_PER_PAGE
, hdescn
); j
++) {
964 uint64_t template = INTEL_PTE_VALID
;
965 if ((hdescc
>= thdescb
) && (hdescc
< thdesce
)) {
968 template |= INTEL_PTE_WRITE
| INTEL_PTE_NX
; /* Writeable, NX */
970 dblmapL1
[0].entries
[j
] = ((uintptr_t)ID_MAP_VTOP(hdescc
)) | template;
975 IdlePML4
[KERNEL_DBLMAP_PML4_INDEX
] = ((uintptr_t)ID_MAP_VTOP(dblmapL3
)) | INTEL_PTE_VALID
| INTEL_PTE_WRITE
| INTEL_PTE_REF
;
977 dblmap_base
= KVADDR(KERNEL_DBLMAP_PML4_INDEX
, randL3
, 0, 0);
978 dblmap_max
= dblmap_base
+ hdescszr
;
979 /* Calculate the double-map distance, which accounts for the current
983 dblmap_dist
= dblmap_base
- hdescb
;
984 idt64_hndl_table0
[1] = DBLMAP(idt64_hndl_table0
[1]); /* 64-bit exit trampoline */
985 idt64_hndl_table0
[3] = DBLMAP(idt64_hndl_table0
[3]); /* 32-bit exit trampoline */
986 idt64_hndl_table0
[6] = (uint64_t)(uintptr_t)&kernel_stack_mask
;
988 extern cpu_data_t cpshadows
[], scdatas
[];
989 uintptr_t cd1
= (uintptr_t) &cpshadows
[0];
990 uintptr_t cd2
= (uintptr_t) &scdatas
[0];
991 /* Record the displacement from the kernel's per-CPU data pointer, eventually
992 * programmed into GSBASE, to the "shadows" in the doublemapped
993 * region. These are not aliases, but separate physical allocations
994 * containing data required in the doublemapped trampolines.
996 idt64_hndl_table0
[2] = dblmap_dist
+ cd1
- cd2
;
998 DBG("Double map base: 0x%qx\n", dblmap_base
);
999 DBG("double map idlepml4[%d]: 0x%llx\n", KERNEL_DBLMAP_PML4_INDEX
, IdlePML4
[KERNEL_DBLMAP_PML4_INDEX
]);
1000 assert(LDTSZ
> LDTSZ_MIN
);
1003 vm_offset_t
dyn_dblmap(vm_offset_t
, vm_offset_t
);
1005 #include <i386/pmap_internal.h>
1007 /* Use of this routine is expected to be synchronized by callers
1008 * Creates non-executable aliases.
1011 dyn_dblmap(vm_offset_t cva
, vm_offset_t sz
)
1013 vm_offset_t ava
= dblmap_max
;
1015 assert((sz
& PAGE_MASK
) == 0);
1018 pmap_alias(ava
, cva
, cva
+ sz
, VM_PROT_READ
| VM_PROT_WRITE
, PMAP_EXPAND_OPTIONS_ALIASMAP
);
1022 /* Adjust offsets interior to the bootstrap interrupt descriptor table to redirect
1023 * control to the double-mapped interrupt vectors. The IDTR proper will be
1024 * programmed via cpu_desc_load()
1029 for (int i
= 0; i
< IDTSZ
; i
++) {
1030 master_idt64
[i
].offset64
= DBLMAP(master_idt64
[i
].offset64
);