Skip to main content

openhcl_boot/
main.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Bare-metal OpenHCL boot loader that prepares VTL2 before Linux starts.
5//!
6//! This measured payload validates its imported regions and host parameters,
7//! establishes the VTL2 address space and processor state, constructs Linux
8//! boot parameters and a device tree, and initializes the sidecar kernel when
9//! configured. It then transfers control to the OpenHCL Linux kernel.
10
11// See build.rs.
12#![cfg_attr(minimal_rt, no_std, no_main)]
13// UNSAFETY: Interacting with low level hardware and bootloader primitives.
14#![expect(unsafe_code)]
15
16mod arch;
17mod boot_logger;
18mod cmdline;
19mod dt;
20mod host_params;
21mod hypercall;
22mod memory;
23mod rt;
24mod sidecar;
25mod single_threaded;
26
27use crate::arch::setup_vtl2_memory;
28use crate::arch::setup_vtl2_vp;
29#[cfg(target_arch = "x86_64")]
30use crate::arch::tdx::get_tdx_tsc_reftime;
31use crate::arch::verify_imported_regions_hash;
32use crate::boot_logger::boot_logger_memory_init;
33use crate::boot_logger::boot_logger_runtime_init;
34use crate::hypercall::hvcall;
35use crate::memory::AddressSpaceManager;
36use crate::single_threaded::OffStackRef;
37use crate::single_threaded::off_stack;
38use arrayvec::ArrayString;
39use arrayvec::ArrayVec;
40use cmdline::BootCommandLineOptions;
41use core::fmt::Write;
42use dt::BootTimes;
43use dt::write_dt;
44use host_fdt_parser::ComInfo;
45use host_params::COMMAND_LINE_SIZE;
46use host_params::PartitionInfo;
47use host_params::shim_params::IsolationType;
48use host_params::shim_params::ShimParams;
49use hvdef::Vtl;
50use loader_defs::linux::SETUP_DTB;
51use loader_defs::linux::setup_data;
52use loader_defs::shim::ShimParamsRaw;
53use memory_range::RangeWalkResult;
54use memory_range::walk_ranges;
55use minimal_rt::enlightened_panic::enable_enlightened_panic;
56use sidecar::SidecarConfig;
57use sidecar_defs::SidecarOutput;
58use sidecar_defs::SidecarParams;
59use zerocopy::FromBytes;
60use zerocopy::FromZeros;
61use zerocopy::Immutable;
62use zerocopy::IntoBytes;
63use zerocopy::KnownLayout;
64
65#[derive(Debug)]
66struct CommandLineTooLong;
67
68impl From<core::fmt::Error> for CommandLineTooLong {
69    fn from(_: core::fmt::Error) -> Self {
70        Self
71    }
72}
73
74struct BuildKernelCommandLineParams<'a> {
75    params: &'a ShimParams,
76    cmdline: &'a mut ArrayString<COMMAND_LINE_SIZE>,
77    partition_info: &'a PartitionInfo,
78    can_trust_host: bool,
79    is_confidential_debug: bool,
80    sidecar: Option<&'a SidecarConfig<'a>>,
81    vtl2_pool_supported: bool,
82}
83
84/// Read and setup the underhill kernel command line into the specified buffer.
85fn build_kernel_command_line(
86    fn_params: BuildKernelCommandLineParams<'_>,
87) -> Result<(), CommandLineTooLong> {
88    let BuildKernelCommandLineParams {
89        params,
90        cmdline,
91        partition_info,
92        can_trust_host,
93        is_confidential_debug,
94        sidecar,
95        vtl2_pool_supported,
96    } = fn_params;
97
98    // For reference:
99    // https://www.kernel.org/doc/html/v5.15/admin-guide/kernel-parameters.html
100    const KERNEL_PARAMETERS: &[&str] = &[
101        // If a console is specified, then write everything to it.
102        "loglevel=8",
103        // Use a fixed 128KB log buffer by default.
104        "log_buf_len=128K",
105        // Enable time output on console for ohcldiag-dev.
106        "printk.time=1",
107        // Enable facility and level output on console for ohcldiag-dev.
108        "console_msg_format=syslog",
109        // Set uio parameter to configure vmbus ring buffer behavior.
110        "uio_hv_generic.no_mask=1",
111        // RELIABILITY: Dump anonymous pages and ELF headers only. Skip over
112        // huge pages and the shared pages.
113        "coredump_filter=0x33",
114        // PERF: No processor frequency governing.
115        "cpufreq.off=1",
116        // PERF: Disable the CPU idle time management entirely. It does not
117        // prevent the idle loop from running on idle CPUs, but it prevents
118        // the CPU idle time governors and drivers from being invoked.
119        "cpuidle.off=1",
120        // PERF: No perf checks for crypto algorithms to boot faster.
121        // Would have to evaluate the perf wins on the crypto manager vs
122        // delaying the boot up.
123        "cryptomgr.notests",
124        // PERF: Idle threads use HLT on x64 if there is no work.
125        // Believed to be a compromise between waking up the processor
126        // and the power consumption.
127        "idle=halt",
128        // WORKAROUND: Avoid init calls that assume presence of CMOS (Simple
129        // Boot Flag) or allocate the real-mode trampoline for APs.
130        "initcall_blacklist=init_real_mode,sbf_init",
131        // CONFIG-STATIC, PERF: Static loops-per-jiffy value to save time on boot.
132        "lpj=3000000",
133        // PERF: No broken timer check to boot faster.
134        "no_timer_check",
135        // CONFIG-STATIC, PERF: Using xsave makes VTL transitions being
136        // much slower. The xsave state is shared between VTLs, and we don't
137        // context switch it in the kernel when leaving/entering VTL2.
138        // Removing this will lead to corrupting register state and the
139        // undefined behaviour.
140        "noxsave",
141        // RELIABILITY: Panic on MCEs and faults in the kernel.
142        "oops=panic",
143        // RELIABILITY: Don't panic on kernel warnings.
144        "panic_on_warn=0",
145        // PERF, RELIABILITY: Don't print detailed information about the failing
146        // processes (memory maps, threads).
147        "panic_print=0",
148        // RELIABILITY: Reboot immediately on panic, no timeout.
149        "panic=-1",
150        // RELIABILITY: Don't print processor context information on a fatal
151        // signal. Our crash dump collection infrastructure seems reliable, and
152        // this information doesn't seem useful without a dump anyways.
153        // Additionally it may push important logs off the end of the kmsg
154        // page logged by the host.
155        //"print_fatal_signals=0",
156        // RELIABILITY: Unlimited logging to /dev/kmsg from userspace.
157        "printk.devkmsg=on",
158        // RELIABILITY: Reboot using a triple fault as the fastest method.
159        // That is also the method used for compatibility with earlier versions
160        // of the Microsoft HCL.
161        "reboot=t",
162        // CONFIG-STATIC: Type of the root file system.
163        "rootfstype=tmpfs",
164        // PERF: Deactivate kcompactd kernel thread, otherwise it will queue a
165        // scheduler timer periodically, which introduces jitters for VTL0.
166        "sysctl.vm.compaction_proactiveness=0",
167        // PERF: No TSC stability check when booting up to boot faster,
168        // also no validation during runtime.
169        "tsc=reliable",
170        // RELIABILITY: Panic on receiving an NMI.
171        "unknown_nmi_panic=1",
172        // Use vfio for MANA devices.
173        "vfio_pci.ids=1414:00ba",
174        // WORKAROUND: Enable no-IOMMU mode. This mode provides no device isolation,
175        // and no DMA translation.
176        "vfio.enable_unsafe_noiommu_mode=1",
177        // Specify the init path.
178        "rdinit=/underhill-init",
179        // Default to user-mode NVMe driver.
180        "OPENHCL_NVME_VFIO=1",
181        // The next three items reduce the memory overhead of the storvsc driver.
182        // Since it is only used for DVD, performance is not critical.
183        "hv_storvsc.storvsc_vcpus_per_sub_channel=2048",
184        // Fix number of hardware queues at 2.
185        "hv_storvsc.storvsc_max_hw_queues=2",
186        // Reduce the ring buffer size to 32K.
187        "hv_storvsc.storvsc_ringbuffer_size=0x8000",
188        // Disable eager mimalloc commit to prevent core dumps from being overly large
189        "MIMALLOC_ARENA_EAGER_COMMIT=0",
190        // Disable acpi runtime support. Unused in underhill, but some support
191        // is compiled in for the kernel (ie TDX mailbox protocol).
192        "acpi=off",
193    ];
194
195    const ARCH_KERNEL_PARAMETERS: &[&str] = cfg_select! {
196        target_arch = "x86_64" => &[
197            // Disable all attempts to use an IOMMU, including swiotlb.
198            "iommu=off",
199            // Don't probe for a PCI bus. PCI devices currently come from VPCI. When
200            // this changes, we will explicitly enumerate a PCI bus via devicetree.
201            "pci=off",
202        ],
203        target_arch = "aarch64" => &[],
204    };
205
206    for p in KERNEL_PARAMETERS {
207        write!(cmdline, "{p} ")?;
208    }
209
210    for p in ARCH_KERNEL_PARAMETERS {
211        write!(cmdline, "{p} ")?;
212    }
213
214    const HARDWARE_ISOLATED_KERNEL_PARAMETERS: &[&str] = &[
215        // Even with iommu=off, the SWIOTLB is still allocated on AARCH64
216        // (iommu=off ignored entirely), and CVMs (memory encryption forces it
217        // on). Set it to a single area in 8MB. The first parameter controls the
218        // area size in slabs (2KB per slab), the second controls the number of
219        // areas (default is # of CPUs).
220        //
221        // This is set to 8MB on hardware isolated VMs since there are some
222        // scenarios, such as provisioning over DVD, which require a larger size
223        // since the buffer is being used.
224        "swiotlb=4096,1",
225    ];
226
227    const NON_HARDWARE_ISOLATED_KERNEL_PARAMETERS: &[&str] = &[
228        // Even with iommu=off, the SWIOTLB is still allocated on AARCH64
229        // (iommu=off ignored entirely). Set it to the minimum, saving ~63 MiB.
230        // The first parameter controls the area size, the second controls the
231        // number of areas (default is # of CPUs). Set them both to the minimum.
232        "swiotlb=1,1",
233    ];
234
235    if params.isolation_type.is_hardware_isolated() {
236        for p in HARDWARE_ISOLATED_KERNEL_PARAMETERS {
237            write!(cmdline, "{p} ")?;
238        }
239    } else {
240        for p in NON_HARDWARE_ISOLATED_KERNEL_PARAMETERS {
241            write!(cmdline, "{p} ")?;
242        }
243    }
244
245    // Enable the com3 console by default if it's available and we're not
246    // isolated, or if we are isolated but also have debugging enabled.
247    //
248    // Otherwise, set the console to ttynull so the kernel does not default to
249    // com1. This is overridden by any user customizations in the static or
250    // dynamic command line, as this console argument provided by the bootloader
251    // comes first.
252    write!(cmdline, "console=")?;
253    match (&partition_info.com3_serial, can_trust_host) {
254        (ComInfo::Ns16550 { current_speed, .. }, true) => {
255            write!(cmdline, "ttyS2,{current_speed} ")?
256        }
257        (ComInfo::Pl011 { current_speed, .. }, true) => {
258            write!(cmdline, "ttyAMA0,{current_speed} ")?
259        }
260        _ => write!(cmdline, "ttynull ")?,
261    }
262
263    if params.isolation_type != IsolationType::None {
264        write!(
265            cmdline,
266            "{}=1 ",
267            underhill_confidentiality::OPENHCL_CONFIDENTIAL_ENV_VAR_NAME
268        )?;
269    }
270
271    if is_confidential_debug {
272        write!(
273            cmdline,
274            "{}=1 ",
275            underhill_confidentiality::OPENHCL_CONFIDENTIAL_DEBUG_ENV_VAR_NAME
276        )?;
277    }
278
279    // Generate the NVMe keep alive command line which should look something
280    // like: OPENHCL_NVME_KEEP_ALIVE=disabled,host,privatepool
281    // TODO: Move from command line to device tree when stabilized.
282    write!(cmdline, "OPENHCL_NVME_KEEP_ALIVE=")?;
283
284    if partition_info.boot_options.disable_nvme_keep_alive {
285        write!(cmdline, "disabled,")?;
286    }
287
288    if partition_info.nvme_keepalive {
289        write!(cmdline, "host,")?;
290    } else {
291        write!(cmdline, "nohost,")?;
292    }
293
294    if vtl2_pool_supported {
295        write!(cmdline, "privatepool ")?;
296    } else {
297        write!(cmdline, "noprivatepool ")?;
298    }
299
300    if let Some(sidecar) = sidecar {
301        write!(cmdline, "{} ", sidecar.kernel_command_line())?;
302    }
303
304    // Prepend the computed parameters to the original command line.
305    cmdline.write_str(&partition_info.cmdline)?;
306
307    Ok(())
308}
309
310// The Linux kernel requires that the FDT fit within a single 256KB mapping, as
311// that is the maximum size the kernel can use during its early boot processes.
312// We also want our FDT to be as large as possible to support as many vCPUs as
313// possible. We set it to 256KB, but it must also be page-aligned, as leaving it
314// unaligned runs the possibility of it taking up 1 too many pages, resulting in
315// a 260KB mapping, which will fail.
316const FDT_SIZE: usize = 256 * 1024;
317
318#[repr(C, align(4096))]
319#[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
320struct Fdt {
321    header: setup_data,
322    data: [u8; FDT_SIZE - size_of::<setup_data>()],
323}
324
325/// Raw shim parameters are provided via a relative offset from the base of
326/// where the shim is loaded. Return a ShimParams structure based on the raw
327/// offset based RawShimParams.
328fn shim_parameters(shim_params_raw_offset: isize) -> ShimParams {
329    unsafe extern "C" {
330        static __ehdr_start: u8;
331    }
332
333    let shim_base = core::ptr::addr_of!(__ehdr_start) as usize;
334
335    // SAFETY: The host is required to relocate everything by the same bias, so
336    //         the shim parameters should be at the build time specified offset
337    //         from the base address of the image.
338    let raw_shim_params = unsafe {
339        &*(shim_base.wrapping_add_signed(shim_params_raw_offset) as *const ShimParamsRaw)
340    };
341
342    ShimParams::new(shim_base as u64, raw_shim_params)
343}
344
345#[cfg_attr(not(target_arch = "x86_64"), expect(dead_code))]
346mod x86_boot {
347    use crate::PageAlign;
348    use crate::memory::AddressSpaceManager;
349    use crate::single_threaded::OffStackRef;
350    use crate::single_threaded::off_stack;
351    use crate::zeroed;
352    use core::mem::size_of;
353    use core::ops::Range;
354    use core::ptr;
355    use loader_defs::linux::E820_RAM;
356    use loader_defs::linux::E820_RESERVED;
357    use loader_defs::linux::SETUP_E820_EXT;
358    use loader_defs::linux::boot_params;
359    use loader_defs::linux::e820entry;
360    use loader_defs::linux::setup_data;
361    use loader_defs::shim::MemoryVtlType;
362    use memory_range::MemoryRange;
363    use zerocopy::FromZeros;
364    use zerocopy::Immutable;
365    use zerocopy::KnownLayout;
366
367    #[repr(C)]
368    #[derive(FromZeros, Immutable, KnownLayout)]
369    pub struct E820Ext {
370        pub header: setup_data,
371        pub entries: [e820entry; 512],
372    }
373
374    fn add_e820_entry(
375        entry: Option<&mut e820entry>,
376        range: MemoryRange,
377        typ: u32,
378    ) -> Result<(), BuildE820MapError> {
379        *entry.ok_or(BuildE820MapError::OutOfE820Entries)? = e820entry {
380            addr: range.start().into(),
381            size: range.len().into(),
382            typ: typ.into(),
383        };
384        Ok(())
385    }
386
387    #[derive(Debug)]
388    pub enum BuildE820MapError {
389        /// Out of e820 entries.
390        OutOfE820Entries,
391    }
392
393    /// Build the e820 map for the kernel representing usable VTL2 ram.
394    pub fn build_e820_map(
395        boot_params: &mut boot_params,
396        ext: &mut E820Ext,
397        address_space: &AddressSpaceManager,
398    ) -> Result<bool, BuildE820MapError> {
399        boot_params.e820_entries = 0;
400        let mut entries = boot_params
401            .e820_map
402            .iter_mut()
403            .chain(ext.entries.iter_mut());
404
405        let mut n = 0;
406        for (range, typ) in address_space.vtl2_ranges() {
407            match typ {
408                MemoryVtlType::VTL2_RAM => {
409                    add_e820_entry(entries.next(), range, E820_RAM)?;
410                    n += 1;
411                }
412                MemoryVtlType::VTL2_CONFIG
413                | MemoryVtlType::VTL2_SIDECAR_IMAGE
414                | MemoryVtlType::VTL2_SIDECAR_NODE
415                | MemoryVtlType::VTL2_RESERVED
416                | MemoryVtlType::VTL2_GPA_POOL
417                | MemoryVtlType::VTL2_TDX_PAGE_TABLES
418                | MemoryVtlType::VTL2_BOOTSHIM_LOG_BUFFER
419                | MemoryVtlType::VTL2_PERSISTED_STATE_HEADER
420                | MemoryVtlType::VTL2_PERSISTED_STATE_PROTOBUF => {
421                    add_e820_entry(entries.next(), range, E820_RESERVED)?;
422                    n += 1;
423                }
424
425                _ => {
426                    panic!("unexpected vtl2 ram type {typ:?} for range {range:#?}");
427                }
428            }
429        }
430
431        let base = n.min(boot_params.e820_map.len());
432        boot_params.e820_entries = base as u8;
433
434        if base < n {
435            ext.header.len = ((n - base) * size_of::<e820entry>()) as u32;
436            Ok(true)
437        } else {
438            Ok(false)
439        }
440    }
441
442    pub fn build_boot_params(
443        address_space: &AddressSpaceManager,
444        initrd: Range<u64>,
445        cmdline: &str,
446        setup_data_head: *const setup_data,
447        setup_data_tail: &mut &mut setup_data,
448    ) -> OffStackRef<'static, PageAlign<boot_params>> {
449        let mut boot_params_storage = off_stack!(PageAlign<boot_params>, zeroed());
450        let boot_params = &mut boot_params_storage.0;
451        boot_params.hdr.type_of_loader = 0xff; // Unknown loader type
452
453        // HACK: A kernel change just in the Underhill kernel tree has a workaround
454        // to disable probe_roms and reserve_bios_regions when X86_SUBARCH_LGUEST
455        // (1) is set by the bootloader. This stops the kernel from reading VTL0
456        // memory during kernel boot, which can have catastrophic consequences
457        // during a servicing operation when VTL0 has written values to memory, or
458        // unaccepted page accesses in an isolated partition.
459        //
460        // This is only intended as a stopgap until a suitable upstreamable kernel
461        // patch is made.
462        boot_params.hdr.hardware_subarch = 1.into();
463
464        boot_params.hdr.ramdisk_image = (initrd.start as u32).into();
465        boot_params.ext_ramdisk_image = (initrd.start >> 32) as u32;
466        let initrd_len = initrd.end - initrd.start;
467        boot_params.hdr.ramdisk_size = (initrd_len as u32).into();
468        boot_params.ext_ramdisk_size = (initrd_len >> 32) as u32;
469
470        let e820_ext = OffStackRef::leak(off_stack!(E820Ext, zeroed()));
471
472        let used_ext = build_e820_map(boot_params, e820_ext, address_space)
473            .expect("building e820 map must succeed");
474
475        if used_ext {
476            e820_ext.header.ty = SETUP_E820_EXT;
477            setup_data_tail.next = ptr::from_ref(&e820_ext.header) as u64;
478            *setup_data_tail = &mut e820_ext.header;
479        }
480
481        let cmd_line_addr = cmdline.as_ptr() as u64;
482        boot_params.hdr.cmd_line_ptr = (cmd_line_addr as u32).into();
483        boot_params.ext_cmd_line_ptr = (cmd_line_addr >> 32) as u32;
484
485        boot_params.hdr.setup_data = (setup_data_head as u64).into();
486
487        boot_params_storage
488    }
489}
490
491/// Build the cc_blob containing the location of different parameters associated with SEV.
492#[cfg(target_arch = "x86_64")]
493fn build_cc_blob_sev_info(
494    cc_blob: &mut loader_defs::linux::cc_blob_sev_info,
495    shim_params: &ShimParams,
496) {
497    // TODO SNP: Currently only the first CPUID page is passed through.
498    // Consider changing this.
499    cc_blob.magic = loader_defs::linux::CC_BLOB_SEV_INFO_MAGIC;
500    cc_blob.version = 0;
501    cc_blob._reserved = 0;
502    cc_blob.secrets_phys = shim_params.secrets_start();
503    cc_blob.secrets_len = hvdef::HV_PAGE_SIZE as u32;
504    cc_blob._rsvd1 = 0;
505    cc_blob.cpuid_phys = shim_params.cpuid_start();
506    cc_blob.cpuid_len = hvdef::HV_PAGE_SIZE as u32;
507    cc_blob._rsvd2 = 0;
508}
509
510#[repr(C, align(4096))]
511#[derive(FromZeros, Immutable, KnownLayout)]
512struct PageAlign<T>(T);
513
514const fn zeroed<T: FromZeros>() -> T {
515    // SAFETY: `T` implements `FromZeros`, so this is a safe initialization of `T`.
516    unsafe { core::mem::MaybeUninit::<T>::zeroed().assume_init() }
517}
518
519fn get_ref_time(isolation: IsolationType) -> Option<u64> {
520    match isolation {
521        #[cfg(target_arch = "x86_64")]
522        IsolationType::Tdx => get_tdx_tsc_reftime(),
523        #[cfg(target_arch = "x86_64")]
524        IsolationType::Snp => None,
525        _ => Some(minimal_rt::reftime::reference_time()),
526    }
527}
528
529/// Dump diagnostics when initrd CRC32 does not match the build-time value.
530///
531/// Contents:
532///
533/// - `base` / `size` / `expected` (build-time) / `got` (first read)
534///   CRCs.
535/// - `got2` — a second CRC re-computed immediately from the same virtual
536///   range. If `got2 != got`, initrd memory is not being read consistently
537///   (typical symptom of stale/mismatched cache lines after the SNP shared
538///   -> private transition, rather than data being wrong in memory).
539/// - `head` / `tail` — first and last 16 bytes as hex, to fingerprint what
540///   is actually in memory.
541/// - `eighths` — CRC32 of eight roughly-equal slices of the initrd. This
542///   is a coarse "which region diverges" locator that is cheap to compute
543///   and stable across boots, so it can be compared with a known-good
544///   build without needing a per-page dump (which would blow the log
545///   budget for real-sized initrds).
546//
547// SNP TODO: temporary diagnostic; remove once the SNP initrd CRC mismatch
548// is root-caused.
549fn build_initrd_crc_diagnostic(p: &ShimParams, first_computed_crc: u32) -> ArrayString<384> {
550    let initrd_bytes = p.initrd();
551
552    // A second read from the same VA. If this differs from the first read,
553    // the initrd memory is not being read consistently, which typically
554    // indicates stale/mismatched cache lines rather than actual data
555    // corruption.
556    let second_computed_crc = crc32fast::hash(initrd_bytes);
557
558    // First 16 and last 16 bytes, as fixed-size arrays so we can rely on
559    // Debug's `{:02x?}` slice formatting.
560    let mut head = [0u8; 16];
561    let head_len = head.len().min(initrd_bytes.len());
562    head[..head_len].copy_from_slice(&initrd_bytes[..head_len]);
563
564    let mut tail = [0u8; 16];
565    let tail_len = tail.len().min(initrd_bytes.len());
566    if tail_len > 0 {
567        let start = initrd_bytes.len() - tail_len;
568        tail[..tail_len].copy_from_slice(&initrd_bytes[start..]);
569    }
570
571    // Split the initrd into (up to) 8 roughly-equal slices and CRC each.
572    // Bytes past the aligned slices go into the last chunk.
573    let mut eighths = [0u32; 8];
574    let n = initrd_bytes.len();
575    if n > 0 {
576        let step = n.div_ceil(8);
577        for (i, e) in eighths.iter_mut().enumerate() {
578            let start = i * step;
579            if start >= n {
580                break;
581            }
582            let end = ((i + 1) * step).min(n);
583            *e = crc32fast::hash(&initrd_bytes[start..end]);
584        }
585    }
586
587    let mut buf = ArrayString::<384>::new();
588    let _ = write!(
589        &mut buf,
590        "initrd crc mismatch: iso={:?} base={:#x} size={:#x} \
591         exp={:#x} got={:#x} got2={:#x} head={:02x?} tail={:02x?} \
592         eighths=[{:#x},{:#x},{:#x},{:#x},{:#x},{:#x},{:#x},{:#x}]",
593        p.isolation_type,
594        p.initrd_base,
595        p.initrd_size,
596        p.initrd_crc,
597        first_computed_crc,
598        second_computed_crc,
599        &head[..head_len],
600        &tail[..tail_len],
601        eighths[0],
602        eighths[1],
603        eighths[2],
604        eighths[3],
605        eighths[4],
606        eighths[5],
607        eighths[6],
608        eighths[7],
609    );
610    buf
611}
612
613fn shim_main(shim_params_raw_offset: isize) -> ! {
614    let p = shim_parameters(shim_params_raw_offset);
615    if p.isolation_type == IsolationType::None {
616        enable_enlightened_panic();
617    }
618
619    #[cfg(feature = "cvm_boot_log")]
620    arch::initialize_serial_io(&p);
621
622    // Enable the in-memory log.
623    boot_logger_memory_init(p.log_buffer);
624
625    // Enable global log crate.
626    log::set_logger(&boot_logger::BOOT_LOGGER).unwrap();
627    // TODO: allow overriding filter at runtime
628    log::set_max_level(log::LevelFilter::Info);
629
630    let boot_reftime = get_ref_time(p.isolation_type);
631
632    // The support code for the fast hypercalls does not set
633    // the Guest ID if it is not set yet as opposed to the slow
634    // hypercall code path where that is done automatically.
635    // Thus the fast hypercalls will fail as the the Guest ID has
636    // to be set first hence initialize hypercall support
637    // explicitly.
638    if !p.isolation_type.is_hardware_isolated() {
639        hvcall().initialize();
640    }
641
642    let mut static_options = BootCommandLineOptions::new();
643    if let Some(cmdline) = p.command_line().command_line() {
644        static_options.parse(cmdline);
645    }
646
647    let static_confidential_debug = static_options.confidential_debug;
648    let can_trust_host = p.isolation_type == IsolationType::None || static_confidential_debug;
649
650    let mut dt_storage = off_stack!(PartitionInfo, PartitionInfo::new());
651    let address_space = OffStackRef::leak(off_stack!(
652        AddressSpaceManager,
653        AddressSpaceManager::new_const()
654    ));
655    let partition_info = match PartitionInfo::read_from_dt(
656        &p,
657        &mut dt_storage,
658        address_space,
659        static_options,
660        can_trust_host,
661    ) {
662        Ok(val) => val,
663        Err(e) => panic!("unable to read device tree params {:?}", e),
664    };
665
666    // Enable logging ASAP. This is fine even when isolated, as we don't have
667    // any access to secrets in the boot shim.
668    boot_logger_runtime_init(p.isolation_type, partition_info.com3_serial.clone());
669    log::info!("openhcl_boot: logging enabled");
670    log::info!("serial configuration: {:#x?}", partition_info.com3_serial);
671
672    // Confidential debug will show up in boot_options only if included in the
673    // static command line, or if can_trust_host is true (so the dynamic command
674    // line has been parsed).
675    let is_confidential_debug =
676        static_confidential_debug || partition_info.boot_options.confidential_debug;
677
678    // Fill out the non-devicetree derived parts of PartitionInfo.
679    if !p.isolation_type.is_hardware_isolated()
680        && hvcall().vtl() == Vtl::Vtl2
681        && hvdef::HvRegisterVsmCapabilities::from(
682            hvcall()
683                .get_register(hvdef::HvAllArchRegisterName::VsmCapabilities.into())
684                .expect("failed to query vsm capabilities")
685                .as_u64(),
686        )
687        .vtl0_alias_map_available()
688    {
689        // If the vtl0 alias map was not provided in the devicetree, attempt to
690        // derive it from the architectural physical address bits.
691        //
692        // The value in the ID_AA64MMFR0_EL1 register used to determine the
693        // physical address bits can only represent multiples of 4. As a result,
694        // the Surface Pro X (and systems with similar CPUs) cannot properly
695        // report their address width of 39 bits. This causes the calculated
696        // alias map to be incorrect, which results in panics when trying to
697        // read memory and getting invalid data.
698        if partition_info.vtl0_alias_map.is_none() {
699            partition_info.vtl0_alias_map =
700                Some(1 << (arch::physical_address_bits(p.isolation_type) - 1));
701        }
702    } else {
703        // Ignore any devicetree-provided alias map if the conditions above
704        // aren't met.
705        partition_info.vtl0_alias_map = None;
706    }
707
708    // Rebind partition_info as no longer mutable.
709    let partition_info: &PartitionInfo = partition_info;
710
711    if partition_info.cpus.is_empty() {
712        panic!("no cpus");
713    }
714
715    validate_vp_hw_ids(partition_info);
716
717    setup_vtl2_memory(&p, partition_info, address_space);
718    setup_vtl2_vp(partition_info);
719
720    verify_imported_regions_hash(&p);
721
722    let mut sidecar_params = off_stack!(PageAlign<SidecarParams>, zeroed());
723    let mut sidecar_output = off_stack!(PageAlign<SidecarOutput>, zeroed());
724    let sidecar = sidecar::start_sidecar(
725        &p,
726        partition_info,
727        address_space,
728        &mut sidecar_params.0,
729        &mut sidecar_output.0,
730    );
731
732    // Rebind address_space as no longer mutable.
733    let address_space: &AddressSpaceManager = address_space;
734
735    let mut cmdline = off_stack!(ArrayString<COMMAND_LINE_SIZE>, ArrayString::new_const());
736    build_kernel_command_line(BuildKernelCommandLineParams {
737        params: &p,
738        cmdline: &mut cmdline,
739        partition_info,
740        can_trust_host,
741        is_confidential_debug,
742        sidecar: sidecar.as_ref(),
743        vtl2_pool_supported: address_space.has_vtl2_pool(),
744    })
745    .unwrap();
746
747    let mut fdt = off_stack!(Fdt, zeroed());
748    fdt.header.len = fdt.data.len() as u32;
749    fdt.header.ty = SETUP_DTB;
750
751    #[cfg(target_arch = "x86_64")]
752    let mut setup_data_tail = &mut fdt.header;
753    #[cfg(target_arch = "x86_64")]
754    let setup_data_head = core::ptr::from_ref(setup_data_tail);
755
756    #[cfg(target_arch = "x86_64")]
757    if p.isolation_type == IsolationType::Snp {
758        let cc_blob = OffStackRef::leak(off_stack!(loader_defs::linux::cc_blob_sev_info, zeroed()));
759        build_cc_blob_sev_info(cc_blob, &p);
760
761        let cc_data = OffStackRef::leak(off_stack!(loader_defs::linux::cc_setup_data, zeroed()));
762        cc_data.header.len = size_of::<loader_defs::linux::cc_setup_data>() as u32;
763        cc_data.header.ty = loader_defs::linux::SETUP_CC_BLOB;
764        cc_data.cc_blob_address = core::ptr::from_ref(&*cc_blob) as u32;
765
766        // Chain in the setup data.
767        setup_data_tail.next = core::ptr::from_ref(&*cc_data) as u64;
768        setup_data_tail = &mut cc_data.header;
769    }
770
771    let initrd = p.initrd_base..p.initrd_base + p.initrd_size;
772
773    // Validate the initrd crc matches what was put at file generation time.
774    let computed_crc = crc32fast::hash(p.initrd());
775    if computed_crc != p.initrd_crc && is_confidential_debug {
776        let diag = build_initrd_crc_diagnostic(&p, computed_crc);
777        log::error!("{}", diag.as_str());
778        panic!("{}", diag.as_str());
779    }
780    assert_eq!(
781        computed_crc, p.initrd_crc,
782        "computed initrd crc does not match build time calculated crc"
783    );
784
785    #[cfg(target_arch = "x86_64")]
786    let boot_params = x86_boot::build_boot_params(
787        address_space,
788        initrd.clone(),
789        &cmdline,
790        setup_data_head,
791        &mut setup_data_tail,
792    );
793
794    // Compute the ending boot time. This has to be before writing to device
795    // tree, so this is as late as we can do it.
796
797    let boot_times = boot_reftime.map(|start| BootTimes {
798        start,
799        end: get_ref_time(p.isolation_type).unwrap_or(0),
800    });
801
802    // Validate that no imported regions that are pending are not part of vtl2
803    // ram.
804    for (range, result) in walk_ranges(
805        partition_info.vtl2_ram.iter().map(|r| (r.range, ())),
806        p.imported_regions(),
807    ) {
808        match result {
809            RangeWalkResult::Neither | RangeWalkResult::Left(_) | RangeWalkResult::Both(_, _) => {}
810            RangeWalkResult::Right(accepted) => {
811                // Ranges that are not a part of VTL2 ram must have been
812                // preaccepted, as usermode expect that to be the case.
813                assert!(
814                    accepted,
815                    "range {:#x?} not in vtl2 ram was not preaccepted at launch",
816                    range
817                );
818            }
819        }
820    }
821
822    write_dt(
823        &mut fdt.data,
824        partition_info,
825        address_space,
826        p.imported_regions().map(|r| {
827            // Discard if the range was previously pending - the bootloader has
828            // accepted all pending ranges.
829            //
830            // NOTE: No VTL0 memory today is marked as pending. The check above
831            // validates that, and this code may need to change if this becomes
832            // no longer true.
833            r.0
834        }),
835        initrd,
836        &cmdline,
837        sidecar.as_ref(),
838        boot_times,
839        p.isolation_type,
840    )
841    .unwrap();
842
843    rt::verify_stack_cookie();
844
845    log::info!("uninitializing hypercalls");
846    #[cfg(not(feature = "cvm_boot_log"))]
847    log::info!("about to jump to kernel");
848
849    hvcall().uninitialize();
850
851    #[cfg(feature = "cvm_boot_log")]
852    {
853        log::info!("uninitializing serial io");
854        log::info!("about to jump to kernel");
855        arch::uninitialize_serial_io(&p);
856    }
857
858    cfg_select! {
859        target_arch = "x86_64" => {
860            // SAFETY: the parameter blob is trusted.
861            let kernel_entry: extern "C" fn(u64, &loader_defs::linux::boot_params) -> ! =
862                unsafe { core::mem::transmute(p.kernel_entry_address) };
863            kernel_entry(0, &boot_params.0)
864        }
865        target_arch = "aarch64" => {
866            // SAFETY: the parameter blob is trusted.
867            let kernel_entry: extern "C" fn(
868                fdt_data: *const u8,
869                mbz0: u64,
870                mbz1: u64,
871                mbz2: u64,
872            ) -> ! = unsafe { core::mem::transmute(p.kernel_entry_address) };
873            // Disable MMU for kernel boot without EFI, as required by the boot protocol.
874            // Flush (and invalidate) the caches, as that is required for disabling MMU.
875            // SAFETY: Just changing a bit in the register and then jumping to the kernel.
876            unsafe {
877                core::arch::asm!(
878                    "
879                    mrs     {0}, sctlr_el1
880                    bic     {0}, {0}, #0x1
881                    msr     sctlr_el1, {0}
882                    tlbi    vmalle1
883                    dsb     sy
884                    isb     sy",
885                    lateout(reg) _,
886                );
887            }
888            kernel_entry(fdt.data.as_ptr(), 0, 0, 0)
889        }
890        _ => {
891            panic!("unsupported arch")
892        }
893    }
894}
895
896/// Ensure that mshv VP indexes for the CPUs listed in the partition info
897/// correspond to the N in the cpu@N devicetree node name. OpenVMM assumes that
898/// this will be the case.
899fn validate_vp_hw_ids(partition_info: &PartitionInfo) {
900    use host_params::MAX_CPU_COUNT;
901    use hypercall::HwId;
902
903    if partition_info.isolation.is_hardware_isolated() {
904        // TODO TDX SNP: we don't have a GHCB/GHCI page set up to communicate
905        // with the hypervisor here, so we can't easily perform the check. Since
906        // there is no security impact to this check, we can skip it for now; if
907        // the VM fails to boot, then this is due to a host contract violation.
908        //
909        // For TDX, we could use ENUM TOPOLOGY to validate that the TD VCPU
910        // indexes correspond to the APIC IDs in the right order. I am not
911        // certain if there are places where we depend on this mapping today.
912        return;
913    }
914
915    if hvcall().vtl() != Vtl::Vtl2 {
916        // If we're not using guest VSM, then the guest won't communicate
917        // directly with the hypervisor, so we can choose the VP indexes
918        // ourselves.
919        return;
920    }
921
922    // Ensure the host and hypervisor agree on VP index ordering.
923
924    let mut hw_ids = off_stack!(ArrayVec<HwId, MAX_CPU_COUNT>, ArrayVec::new_const());
925    hw_ids.clear();
926    hw_ids.extend(partition_info.cpus.iter().map(|c| c.reg as _));
927    let mut vp_indexes = off_stack!(ArrayVec<u32, MAX_CPU_COUNT>, ArrayVec::new_const());
928    vp_indexes.clear();
929    if let Err(err) = hvcall().get_vp_index_from_hw_id(&hw_ids, &mut vp_indexes) {
930        panic!(
931            "failed to get VP index for hardware ID {:#x}: {}",
932            hw_ids[vp_indexes.len().min(hw_ids.len() - 1)],
933            err
934        );
935    }
936    if let Some((i, &vp_index)) = vp_indexes
937        .iter()
938        .enumerate()
939        .find(|&(i, vp_index)| i as u32 != *vp_index)
940    {
941        panic!(
942            "CPU hardware ID {:#x} does not correspond to VP index {}",
943            hw_ids[i], vp_index
944        );
945    }
946}
947
948// See build.rs. See `mod rt` for the actual bootstrap code required to invoke
949// shim_main.
950#[cfg(not(minimal_rt))]
951fn main() {
952    unimplemented!("build with MINIMAL_RT_BUILD to produce a working boot loader");
953}
954
955#[cfg(test)]
956mod test {
957    use super::x86_boot::E820Ext;
958    use super::x86_boot::build_e820_map;
959    use crate::cmdline::BootCommandLineOptions;
960    use crate::dt::write_dt;
961    use crate::host_params::MAX_CPU_COUNT;
962    use crate::host_params::PartitionInfo;
963    use crate::host_params::shim_params::IsolationType;
964    use crate::memory::AddressSpaceManager;
965    use crate::memory::AddressSpaceManagerBuilder;
966    use arrayvec::ArrayString;
967    use arrayvec::ArrayVec;
968    use core::ops::Range;
969    use host_fdt_parser::ComInfo;
970    use host_fdt_parser::CpuEntry;
971    use host_fdt_parser::MemoryEntry;
972    use host_fdt_parser::VmbusInfo;
973    use igvm_defs::MemoryMapEntryType;
974    use loader_defs::linux::E820_RAM;
975    use loader_defs::linux::E820_RESERVED;
976    use loader_defs::linux::boot_params;
977    use loader_defs::linux::e820entry;
978    use memory_range::MemoryRange;
979    use memory_range::subtract_ranges;
980    use sidecar_defs::PerCpuState;
981    use zerocopy::FromZeros;
982
983    const HIGH_MMIO_GAP_END: u64 = 0x1000000000; //  64 GiB
984    const VMBUS_MMIO_GAP_SIZE: u64 = 0x10000000; // 256 MiB
985    const HIGH_MMIO_GAP_START: u64 = HIGH_MMIO_GAP_END - VMBUS_MMIO_GAP_SIZE;
986
987    /// Create partition info with given cpu count enabled and sequential
988    /// apic_ids.
989    fn new_partition_info(cpu_count: usize) -> PartitionInfo {
990        let mut cpus: ArrayVec<CpuEntry, MAX_CPU_COUNT> = ArrayVec::new();
991
992        for id in 0..(cpu_count as u64) {
993            cpus.push(CpuEntry { reg: id, vnode: 0 });
994        }
995
996        let mut mmio = ArrayVec::new();
997        mmio.push(
998            MemoryRange::try_new(HIGH_MMIO_GAP_START..HIGH_MMIO_GAP_END).expect("valid range"),
999        );
1000
1001        PartitionInfo {
1002            vtl2_ram: ArrayVec::new(),
1003            partition_ram: ArrayVec::new(),
1004            isolation: IsolationType::None,
1005            bsp_reg: cpus[0].reg as u32,
1006            cpus,
1007            sidecar_cpu_overrides: PerCpuState {
1008                per_cpu_state_specified: false,
1009                sidecar_starts_cpu: [true; sidecar_defs::NUM_CPUS_SUPPORTED_FOR_PER_CPU_STATE],
1010            },
1011            cmdline: ArrayString::new(),
1012            vmbus_vtl2: VmbusInfo { mmio },
1013            vmbus_vtl0: VmbusInfo {
1014                mmio: ArrayVec::new(),
1015            },
1016            com3_serial: ComInfo::None,
1017            gic: None,
1018            pmu_gsiv: None,
1019            memory_allocation_mode: host_fdt_parser::MemoryAllocationMode::Host,
1020            entropy: None,
1021            vtl0_alias_map: None,
1022            nvme_keepalive: false,
1023            boot_options: BootCommandLineOptions::new(),
1024        }
1025    }
1026
1027    // ensure we can boot with a _lot_ of vcpus
1028    #[test]
1029    #[cfg_attr(
1030        target_arch = "aarch64",
1031        ignore = "TODO: investigate why this doesn't always work on ARM"
1032    )]
1033    fn fdt_cpu_scaling() {
1034        const MAX_CPUS: usize = 2048;
1035
1036        let mut buf = [0; 0x40000];
1037        write_dt(
1038            &mut buf,
1039            &new_partition_info(MAX_CPUS),
1040            &AddressSpaceManager::new_const(),
1041            [],
1042            0..0,
1043            &ArrayString::from("test").unwrap_or_default(),
1044            None,
1045            None,
1046            IsolationType::None,
1047        )
1048        .unwrap();
1049    }
1050
1051    // Must match the DeviceTree blob generated with the standard tooling
1052    // to ensure being compliant to the standards (or, at least, compatibility
1053    // with a widely used implementation).
1054    // For details on regenerating the test content, see `fdt_dtc_decompile`
1055    // below.
1056    #[test]
1057    #[ignore = "TODO: temporarily broken"]
1058    fn fdt_dtc_check_content() {
1059        const MAX_CPUS: usize = 2;
1060        const BUF_SIZE: usize = 0x1000;
1061
1062        // Rust cannot infer the type.
1063        let dtb_data_spans: [(usize, &[u8]); 2] = [
1064            (
1065                /* Span starts at offset */ 0,
1066                b"\xd0\x0d\xfe\xed\x00\x00\x10\x00\x00\x00\x04\x38\x00\x00\x00\x38\
1067                \x00\x00\x00\x28\x00\x00\x00\x11\x00\x00\x00\x10\x00\x00\x00\x00\
1068                \x00\x00\x00\x4a\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x00\x00\x00\
1069                \x00\x00\x00\x00\x00\x00\x00\x00\x23\x61\x64\x64\x72\x65\x73\x73\
1070                \x2d\x63\x65\x6c\x6c\x73\x00\x23\x73\x69\x7a\x65\x2d\x63\x65\x6c\
1071                \x6c\x73\x00\x6d\x6f\x64\x65\x6c\x00\x72\x65\x67\x00\x64\x65\x76\
1072                \x69\x63\x65\x5f\x74\x79\x70\x65\x00\x73\x74\x61\x74\x75\x73\x00\
1073                \x63\x6f\x6d\x70\x61\x74\x69\x62\x6c\x65\x00\x72\x61\x6e\x67\x65\
1074                \x73",
1075            ),
1076            (
1077                /* Span starts at offset */ 0x430,
1078                b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
1079                \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x02\
1080                \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0f\x00\x00\x00\x00\
1081                \x00\x00\x00\x03\x00\x00\x00\x0f\x00\x00\x00\x1b\x6d\x73\x66\x74\
1082                \x2c\x75\x6e\x64\x65\x72\x68\x69\x6c\x6c\x00\x00\x00\x00\x00\x01\
1083                \x63\x70\x75\x73\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1084                \x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x04\
1085                \x00\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x01\x63\x70\x75\x40\
1086                \x30\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x25\
1087                \x63\x70\x75\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x21\
1088                \x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x05\x00\x00\x00\x31\
1089                \x6f\x6b\x61\x79\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\
1090                \x63\x70\x75\x40\x31\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1091                \x00\x00\x00\x25\x63\x70\x75\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1092                \x00\x00\x00\x21\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x05\
1093                \x00\x00\x00\x31\x6f\x6b\x61\x79\x00\x00\x00\x00\x00\x00\x00\x02\
1094                \x00\x00\x00\x02\x00\x00\x00\x01\x76\x6d\x62\x75\x73\x00\x00\x00\
1095                \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x02\
1096                \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0f\x00\x00\x00\x01\
1097                \x00\x00\x00\x03\x00\x00\x00\x0b\x00\x00\x00\x38\x6d\x73\x66\x74\
1098                \x2c\x76\x6d\x62\x75\x73\x00\x00\x00\x00\x00\x03\x00\x00\x00\x14\
1099                \x00\x00\x00\x43\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\
1100                \xf0\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\
1101                \x00\x00\x00\x09",
1102            ),
1103        ];
1104
1105        let mut sample_buf = [0u8; BUF_SIZE];
1106        for (span_start, bytes) in dtb_data_spans {
1107            sample_buf[span_start..span_start + bytes.len()].copy_from_slice(bytes);
1108        }
1109
1110        let mut buf = [0u8; BUF_SIZE];
1111        write_dt(
1112            &mut buf,
1113            &new_partition_info(MAX_CPUS),
1114            &AddressSpaceManager::new_const(),
1115            [],
1116            0..0,
1117            &ArrayString::from("test").unwrap_or_default(),
1118            None,
1119            None,
1120            IsolationType::None,
1121        )
1122        .unwrap();
1123
1124        assert!(sample_buf == buf);
1125    }
1126
1127    // This test should be manually enabled when need to regenerate
1128    // the sample content above and validate spec compliance with `dtc`.
1129    // Before running the test, please install the DeviceTree compiler:
1130    // ```shell
1131    // sudo apt-get update && sudo apt-get install device-tree-compiler
1132    // ```
1133    #[test]
1134    #[ignore = "enabling the test requires installing additional software, \
1135                and developers will experience a break."]
1136    fn fdt_dtc_decompile() {
1137        const MAX_CPUS: usize = 2048;
1138
1139        let mut buf = [0; 0x40000];
1140        write_dt(
1141            &mut buf,
1142            &new_partition_info(MAX_CPUS),
1143            &AddressSpaceManager::new_const(),
1144            [],
1145            0..0,
1146            &ArrayString::from("test").unwrap_or_default(),
1147            None,
1148            None,
1149            IsolationType::None,
1150        )
1151        .unwrap();
1152
1153        let input_dtb_file_name = "openhcl_boot.dtb";
1154        let output_dts_file_name = "openhcl_boot.dts";
1155        std::fs::write(input_dtb_file_name, buf).unwrap();
1156        let success = std::process::Command::new("dtc")
1157            .args([input_dtb_file_name, "-I", "dtb", "-o", output_dts_file_name])
1158            .status()
1159            .unwrap()
1160            .success();
1161        assert!(success);
1162    }
1163
1164    fn new_address_space_manager(
1165        ram: &[MemoryRange],
1166        bootshim_used: MemoryRange,
1167        persisted_range: MemoryRange,
1168        parameter_range: MemoryRange,
1169        reclaim: Option<MemoryRange>,
1170    ) -> AddressSpaceManager {
1171        let ram = ram
1172            .iter()
1173            .cloned()
1174            .map(|range| MemoryEntry {
1175                range,
1176                mem_type: MemoryMapEntryType::VTL2_PROTECTABLE,
1177                vnode: 0,
1178            })
1179            .collect::<Vec<_>>();
1180        let mut address_space = AddressSpaceManager::new_const();
1181        AddressSpaceManagerBuilder::new(
1182            &mut address_space,
1183            &ram,
1184            bootshim_used,
1185            persisted_range,
1186            subtract_ranges([parameter_range], reclaim),
1187        )
1188        .init()
1189        .unwrap();
1190        address_space
1191    }
1192
1193    fn check_e820(boot_params: &boot_params, ext: &E820Ext, expected: &[(Range<u64>, u32)]) {
1194        let actual = boot_params.e820_map[..boot_params.e820_entries as usize]
1195            .iter()
1196            .chain(
1197                ext.entries
1198                    .iter()
1199                    .take((ext.header.len as usize) / size_of::<e820entry>()),
1200            );
1201
1202        assert_eq!(actual.clone().count(), expected.len());
1203
1204        for (actual, (expected_range, expected_type)) in actual.zip(expected.iter()) {
1205            let addr: u64 = actual.addr.into();
1206            let size: u64 = actual.size.into();
1207            let typ: u32 = actual.typ.into();
1208            assert_eq!(addr, expected_range.start);
1209            assert_eq!(size, expected_range.end - expected_range.start);
1210            assert_eq!(typ, *expected_type);
1211        }
1212    }
1213
1214    const PAGE_SIZE: u64 = 0x1000;
1215    const ONE_MB: u64 = 0x10_0000;
1216
1217    #[test]
1218    fn test_e820_basic() {
1219        // memmap with no param reclaim
1220        let mut boot_params: boot_params = FromZeros::new_zeroed();
1221        let mut ext = FromZeros::new_zeroed();
1222        let bootshim_used = MemoryRange::try_new(ONE_MB..3 * ONE_MB).unwrap();
1223        let persisted_header_end = ONE_MB + PAGE_SIZE;
1224        let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1225        let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1226        let parameter_range = MemoryRange::try_new(2 * ONE_MB..3 * ONE_MB).unwrap();
1227        let address_space = new_address_space_manager(
1228            &[MemoryRange::new(ONE_MB..4 * ONE_MB)],
1229            bootshim_used,
1230            persisted_state,
1231            parameter_range,
1232            None,
1233        );
1234
1235        assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1236
1237        check_e820(
1238            &boot_params,
1239            &ext,
1240            &[
1241                (ONE_MB..(persisted_header_end), E820_RESERVED),
1242                (persisted_header_end..persisted_end, E820_RESERVED),
1243                (persisted_end..2 * ONE_MB, E820_RAM),
1244                (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1245                (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1246            ],
1247        );
1248
1249        // memmap with reclaim
1250        let mut boot_params: boot_params = FromZeros::new_zeroed();
1251        let mut ext = FromZeros::new_zeroed();
1252        let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1253        let persisted_header_end = ONE_MB + PAGE_SIZE;
1254        let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1255        let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1256        let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1257        let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1258        let address_space = new_address_space_manager(
1259            &[MemoryRange::new(ONE_MB..6 * ONE_MB)],
1260            bootshim_used,
1261            persisted_state,
1262            parameter_range,
1263            Some(reclaim),
1264        );
1265
1266        assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1267
1268        check_e820(
1269            &boot_params,
1270            &ext,
1271            &[
1272                (ONE_MB..(persisted_header_end), E820_RESERVED),
1273                (persisted_header_end..persisted_end, E820_RESERVED),
1274                (persisted_end..2 * ONE_MB, E820_RAM),
1275                (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1276                (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1277                (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1278                (5 * ONE_MB..6 * ONE_MB, E820_RAM),
1279            ],
1280        );
1281
1282        // two mem ranges
1283        let mut boot_params: boot_params = FromZeros::new_zeroed();
1284        let mut ext = FromZeros::new_zeroed();
1285        let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1286        let persisted_header_end = ONE_MB + PAGE_SIZE;
1287        let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1288        let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1289        let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1290        let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1291        let address_space = new_address_space_manager(
1292            &[
1293                MemoryRange::new(ONE_MB..4 * ONE_MB),
1294                MemoryRange::new(4 * ONE_MB..10 * ONE_MB),
1295            ],
1296            bootshim_used,
1297            persisted_state,
1298            parameter_range,
1299            Some(reclaim),
1300        );
1301
1302        assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1303
1304        check_e820(
1305            &boot_params,
1306            &ext,
1307            &[
1308                (ONE_MB..(persisted_header_end), E820_RESERVED),
1309                (persisted_header_end..persisted_end, E820_RESERVED),
1310                (persisted_end..2 * ONE_MB, E820_RAM),
1311                (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1312                (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1313                (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1314                (5 * ONE_MB..10 * ONE_MB, E820_RAM),
1315            ],
1316        );
1317
1318        // memmap in 1 mb chunks
1319        let mut boot_params: boot_params = FromZeros::new_zeroed();
1320        let mut ext = FromZeros::new_zeroed();
1321        let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1322        let persisted_header_end = ONE_MB + PAGE_SIZE;
1323        let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1324        let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1325        let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1326        let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1327        let address_space = new_address_space_manager(
1328            &[
1329                MemoryRange::new(ONE_MB..2 * ONE_MB),
1330                MemoryRange::new(2 * ONE_MB..3 * ONE_MB),
1331                MemoryRange::new(3 * ONE_MB..4 * ONE_MB),
1332                MemoryRange::new(4 * ONE_MB..5 * ONE_MB),
1333                MemoryRange::new(5 * ONE_MB..6 * ONE_MB),
1334                MemoryRange::new(6 * ONE_MB..7 * ONE_MB),
1335                MemoryRange::new(7 * ONE_MB..8 * ONE_MB),
1336            ],
1337            bootshim_used,
1338            persisted_state,
1339            parameter_range,
1340            Some(reclaim),
1341        );
1342
1343        assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1344
1345        check_e820(
1346            &boot_params,
1347            &ext,
1348            &[
1349                (ONE_MB..(persisted_header_end), E820_RESERVED),
1350                (persisted_header_end..persisted_end, E820_RESERVED),
1351                (persisted_end..2 * ONE_MB, E820_RAM),
1352                (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1353                (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1354                (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1355                (5 * ONE_MB..8 * ONE_MB, E820_RAM),
1356            ],
1357        );
1358    }
1359
1360    // test e820 with spillover into ext
1361    #[test]
1362    fn test_e820_huge() {
1363        use crate::memory::AllocationPolicy;
1364        use crate::memory::AllocationType;
1365
1366        // Create 64 RAM ranges, then allocate 256 ranges to test spillover
1367        // boot_params.e820_map has E820_MAX_ENTRIES_ZEROPAGE (128) entries
1368        const E820_MAX_ENTRIES_ZEROPAGE: usize = 128;
1369        const RAM_RANGES: usize = 64;
1370        const TOTAL_ALLOCATIONS: usize = 256;
1371
1372        // Create 64 large RAM ranges (64MB each = 64 * 1MB pages per range)
1373        let mut ranges = Vec::new();
1374        for i in 0..RAM_RANGES {
1375            let start = (i as u64) * 64 * ONE_MB;
1376            let end = start + 64 * ONE_MB;
1377            ranges.push(MemoryRange::new(start..end));
1378        }
1379
1380        let bootshim_used = MemoryRange::try_new(0..ONE_MB * 2).unwrap();
1381        let persisted_range = MemoryRange::try_new(0..ONE_MB).unwrap();
1382        let parameter_range = MemoryRange::try_new(ONE_MB..2 * ONE_MB).unwrap();
1383
1384        let mut address_space = {
1385            let ram = ranges
1386                .iter()
1387                .cloned()
1388                .map(|range| MemoryEntry {
1389                    range,
1390                    mem_type: MemoryMapEntryType::VTL2_PROTECTABLE,
1391                    vnode: 0,
1392                })
1393                .collect::<Vec<_>>();
1394            let mut address_space = AddressSpaceManager::new_const();
1395            AddressSpaceManagerBuilder::new(
1396                &mut address_space,
1397                &ram,
1398                bootshim_used,
1399                persisted_range,
1400                core::iter::once(parameter_range),
1401            )
1402            .init()
1403            .unwrap();
1404            address_space
1405        };
1406
1407        for i in 0..TOTAL_ALLOCATIONS {
1408            // Intersperse sidecar node allocations with gpa pool allocations,
1409            // as otherwise the address space manager will collapse adjacent
1410            // ranges of the same type.
1411            let _allocated = address_space
1412                .allocate(
1413                    None,
1414                    ONE_MB,
1415                    if i % 2 == 0 {
1416                        AllocationType::GpaPool
1417                    } else {
1418                        AllocationType::SidecarNode
1419                    },
1420                    AllocationPolicy::LowMemory,
1421                )
1422                .expect("should be able to allocate sidecar node");
1423        }
1424
1425        let mut boot_params: boot_params = FromZeros::new_zeroed();
1426        let mut ext = FromZeros::new_zeroed();
1427        let total_ranges = address_space.vtl2_ranges().count();
1428
1429        let used_ext = build_e820_map(&mut boot_params, &mut ext, &address_space).unwrap();
1430
1431        // Verify that we used the extension
1432        assert!(used_ext, "should use extension when there are many ranges");
1433
1434        // Verify the standard e820_map is full
1435        assert_eq!(boot_params.e820_entries, E820_MAX_ENTRIES_ZEROPAGE as u8);
1436
1437        // Verify the extension has the overflow entries
1438        let ext_entries = (ext.header.len as usize) / size_of::<e820entry>();
1439        assert_eq!(ext_entries, total_ranges - E820_MAX_ENTRIES_ZEROPAGE);
1440
1441        // Verify we have the expected number of total ranges
1442        let total_e820_entries = boot_params.e820_entries as usize + ext_entries;
1443        assert_eq!(total_e820_entries, total_ranges);
1444    }
1445}