Skip to main content

loader/
paravisor.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Paravisor specific loader definitions and implementation.
5
6use crate::common::ChunkBuf;
7use crate::common::ImportFileRegion;
8use crate::common::ReadSeek;
9use crate::cpuid::HV_PSP_CPUID_PAGE;
10use crate::importer::Aarch64Register;
11use crate::importer::BootPageAcceptance;
12use crate::importer::IgvmParameterType;
13use crate::importer::ImageLoad;
14use crate::importer::IsolationConfig;
15use crate::importer::IsolationType;
16use crate::importer::SegmentRegister;
17use crate::importer::StartupMemoryType;
18use crate::importer::TableRegister;
19use crate::importer::X86Register;
20use crate::linux::InitrdAddressType;
21use crate::linux::InitrdConfig;
22use crate::linux::InitrdInfo;
23use crate::linux::KernelInfo;
24use crate::linux::load_kernel_and_initrd_arm64;
25use aarch64defs::Cpsr64;
26use aarch64defs::IntermPhysAddrSize;
27use aarch64defs::SctlrEl1;
28use aarch64defs::TranslationBaseEl1;
29use aarch64defs::TranslationControlEl1;
30use aarch64defs::TranslationGranule0;
31use aarch64defs::TranslationGranule1;
32use hvdef::HV_PAGE_SIZE;
33use hvdef::Vtl;
34use igvm::registers::AArch64Register;
35use loader_defs::paravisor::*;
36use loader_defs::shim::ShimParamsRaw;
37use memory_range::MemoryRange;
38use page_table::aarch64::Arm64PageSize;
39use page_table::aarch64::MemoryAttributeEl1;
40use page_table::aarch64::MemoryAttributeIndirectionEl1;
41use page_table::x64::MappedRange;
42use page_table::x64::PAGE_TABLE_MAX_BYTES;
43use page_table::x64::PAGE_TABLE_MAX_COUNT;
44use page_table::x64::PageTable;
45use page_table::x64::PageTableBuilder;
46use page_table::x64::X64_LARGE_PAGE_SIZE;
47use page_table::x64::align_up_to_large_page_size;
48use page_table::x64::align_up_to_page_size;
49use page_table::x64::calculate_pde_table_count;
50use std::io::Read;
51use std::io::Seek;
52use thiserror::Error;
53use x86defs::GdtEntry;
54use x86defs::SegmentSelector;
55use x86defs::X64_BUSY_TSS_SEGMENT_ATTRIBUTES;
56use x86defs::X64_DEFAULT_CODE_SEGMENT_ATTRIBUTES;
57use x86defs::X64_DEFAULT_DATA_SEGMENT_ATTRIBUTES;
58use x86defs::cpuid::CpuidFunction;
59use zerocopy::FromZeros;
60use zerocopy::IntoBytes;
61
62#[derive(Debug)]
63pub struct Vtl0Linux<'a> {
64    pub command_line: &'a std::ffi::CString,
65    pub load_info: crate::linux::LoadInfo,
66}
67
68#[derive(Debug)]
69pub struct Vtl0Config<'a> {
70    pub supports_pcat: bool,
71    /// The load info and the VP context page.
72    pub supports_uefi: Option<(crate::uefi::LoadInfo, Vec<u8>)>,
73    pub supports_linux: Option<Vtl0Linux<'a>>,
74}
75
76// See HclDefs.h
77pub const HCL_SECURE_VTL: Vtl = Vtl::Vtl2;
78
79/// Size of the persisted region (2MB).
80const PERSISTED_REGION_SIZE: u64 = 2 * 1024 * 1024;
81
82fn avoid_page_table_large_page_boundary(offset: u64, large_page_size: u64) -> u64 {
83    if offset.is_multiple_of(large_page_size) {
84        offset + HV_PAGE_SIZE
85    } else {
86        offset
87    }
88}
89
90#[derive(Debug, Error)]
91pub enum Error {
92    #[error("memory is unaligned: {0}")]
93    MemoryUnaligned(u64),
94    #[error("command line too large: {0}")]
95    CommandLineSize(usize),
96    #[error("kernel load error")]
97    Kernel(#[source] crate::linux::Error),
98    #[error("shim load error")]
99    Shim(#[source] crate::elf::Error),
100    #[error("invalid initrd size: {0}")]
101    InvalidInitrdSize(u64),
102    #[error("memory used: {0} is greater than available")]
103    NotEnoughMemory(u64),
104    #[error("importer error")]
105    Importer(#[from] anyhow::Error),
106    #[error("failed to import initrd")]
107    ImportInitrd(#[source] crate::common::ImportFileRegionError),
108    #[error("failed to read initrd for CRC")]
109    InitrdRead(#[source] std::io::Error),
110    #[error("PageTableBuilder: {0}")]
111    PageTableBuilder(#[from] page_table::Error),
112}
113
114/// Kernel Command line type.
115pub enum CommandLineType<'a> {
116    /// The command line is a static string.
117    Static(&'a str),
118    /// The command line is dynamic and host appendable via the chosen node in
119    /// device tree, with initial data specified by the provided CStr. An empty
120    /// base_string may be provided to allow the host to specify the full kernel
121    /// command line.
122    HostAppendable(&'a str),
123}
124
125/// Load the underhill kernel on x64.
126///
127/// An optional initrd may be specified.
128///
129/// An optional `memory_page_base` may be specified. This will disable
130/// relocation support for underhill.
131pub fn load_openhcl_x64<F>(
132    importer: &mut dyn ImageLoad<X86Register>,
133    kernel_image: &mut F,
134    shim: &mut F,
135    sidecar: Option<&mut F>,
136    command_line: CommandLineType<'_>,
137    mut initrd: Option<(&mut dyn ReadSeek, u64)>,
138    memory_page_base: Option<u64>,
139    memory_page_count: u64,
140    vtl0_config: Vtl0Config<'_>,
141) -> Result<(), Error>
142where
143    F: Read + Seek,
144{
145    let IsolationConfig {
146        isolation_type,
147        paravisor_present,
148        shared_gpa_boundary_bits,
149    } = importer.isolation_config();
150
151    // If no explicit memory base is specified, load with relocation support.
152    let with_relocation = memory_page_base.is_none() && isolation_type == IsolationType::None;
153
154    let memory_start_address = memory_page_base
155        .map(|page_number| page_number * HV_PAGE_SIZE)
156        .unwrap_or(PARAVISOR_DEFAULT_MEMORY_BASE_ADDRESS);
157
158    let memory_size = memory_page_count * HV_PAGE_SIZE;
159
160    // OpenHCL is laid out as the following:
161    // --- High Memory, 2MB aligned ---
162    // free space
163    //
164    // page tables
165    // 16 pages reserved for bootshim heap
166    // 8K bootshim logs
167    // IGVM parameters
168    // reserved vtl2 ranges
169    // initrd
170    // openhcl_boot
171    // sidecar, if configured
172    // - pad to next 2MB -
173    // kernel
174    // optional 2mb bounce buf for CVM
175    // persisted state region
176    // --- Low memory, 2MB aligned ---
177
178    // Paravisor memory ranges must be 2MB (large page) aligned.
179    if !memory_start_address.is_multiple_of(X64_LARGE_PAGE_SIZE) {
180        return Err(Error::MemoryUnaligned(memory_start_address));
181    }
182
183    if !memory_size.is_multiple_of(X64_LARGE_PAGE_SIZE) {
184        return Err(Error::MemoryUnaligned(memory_size));
185    }
186
187    // The whole memory range must be present and VTL2 protectable for the
188    // underhill kernel to work.
189    importer.verify_startup_memory_available(
190        memory_start_address / HV_PAGE_SIZE,
191        memory_page_count,
192        if paravisor_present {
193            StartupMemoryType::Vtl2ProtectableRam
194        } else {
195            StartupMemoryType::Ram
196        },
197    )?;
198
199    let kernel_acceptance = match isolation_type {
200        IsolationType::Snp | IsolationType::Tdx => BootPageAcceptance::Shared,
201        _ => BootPageAcceptance::Exclusive,
202    };
203
204    let mut offset = memory_start_address;
205
206    // Reserve the first 2MB for a potential persisted state region. The first
207    // 4K page is always the persisted state header, and the bootshim may decide
208    // to use the the remaining pages for the protobuf payload.
209    let persisted_region_base = offset;
210    let persisted_region_size = PERSISTED_REGION_SIZE;
211    offset += persisted_region_size;
212
213    // If hardware isolated, reserve a 2MB range for bounce buffering shared
214    // pages. This is done first because we know the start address is 2MB
215    // aligned, with the next consumers wanting 2MB aligned ranges. This is
216    // reserved at load time in order to guarantee the pagetables have entries
217    // for this identity mapping.
218    //
219    // Leave this as a gap, as there's no need to accept or describe this range
220    // in the IGVM file.
221    let bounce_buffer = if matches!(isolation_type, IsolationType::Snp | IsolationType::Tdx) {
222        let bounce_buffer_gpa = offset;
223        assert_eq!(bounce_buffer_gpa % X64_LARGE_PAGE_SIZE, 0);
224        let range = MemoryRange::new(bounce_buffer_gpa..bounce_buffer_gpa + X64_LARGE_PAGE_SIZE);
225
226        offset += range.len();
227        Some(range)
228    } else {
229        None
230    };
231
232    tracing::trace!(offset, "loading the kernel");
233
234    // The x86_64 uncompressed kernel we use doesn't show any difference
235    // in the code sections upon flipping CONFIG_RELOCATABLE. In total,
236    // there are 6 places where a difference is found: dates in the Linux
237    // banner, GNU build ID, and metadata entries in the empty initrd image
238    // (it always is embedded into the kernel). No sections with relocations
239    // appear if CONFIG_RELOCATABLE is set.
240    // Assume that at least the kernel entry contains PIC and no loader
241    // assistance with the relocations records (if any) is required.
242    let load_info = crate::elf::load_static_elf(
243        importer,
244        kernel_image,
245        offset,
246        0,
247        true,
248        kernel_acceptance,
249        "underhill-kernel",
250    )
251    .map_err(|e| Error::Kernel(crate::linux::Error::ElfLoader(e)))?;
252    tracing::trace!("Kernel loaded at {load_info:x?}");
253    let crate::elf::LoadInfo {
254        minimum_address_used: _min_addr,
255        next_available_address: mut offset,
256        entrypoint: kernel_entrypoint,
257    } = load_info;
258
259    assert_eq!(offset & (HV_PAGE_SIZE - 1), 0);
260
261    // If an AP kernel was provided, load it next.
262    let (sidecar_size, sidecar_entrypoint) = if let Some(sidecar) = sidecar {
263        // Sidecar load addr must be 2MB aligned
264        offset = align_up_to_large_page_size(offset);
265
266        let load_info = crate::elf::load_static_elf(
267            importer,
268            sidecar,
269            0,
270            offset,
271            false,
272            BootPageAcceptance::Exclusive,
273            "sidecar-kernel",
274        )
275        .map_err(|e| Error::Kernel(crate::linux::Error::ElfLoader(e)))?;
276
277        (
278            load_info.next_available_address - offset,
279            load_info.entrypoint,
280        )
281    } else {
282        (0, 0)
283    };
284
285    let sidecar_base = offset;
286    offset += sidecar_size;
287
288    let load_info = crate::elf::load_static_elf(
289        importer,
290        shim,
291        0,
292        offset,
293        false,
294        BootPageAcceptance::Exclusive,
295        "underhill-boot-shim",
296    )
297    .map_err(Error::Shim)?;
298    tracing::trace!("The boot shim loaded at {load_info:x?}");
299    let crate::elf::LoadInfo {
300        minimum_address_used: shim_base_addr,
301        next_available_address: mut offset,
302        entrypoint: shim_entry_address,
303    } = load_info;
304
305    // Compute initrd CRC before the file reference is consumed by the importer.
306    let mut buf = ChunkBuf::new();
307    let initrd_crc = if let Some((ref mut initrd_file, initrd_len)) = initrd {
308        buf.crc32(*initrd_file, initrd_len)
309            .map_err(Error::InitrdRead)?
310    } else {
311        crc32fast::hash(&[])
312    };
313
314    // Optionally import initrd if specified.
315    let ramdisk = if let Some((initrd_file, initrd_len)) = initrd {
316        let initrd_base = offset;
317        let initrd_size = align_up_to_page_size(initrd_len);
318
319        buf.import_file_region(
320            importer,
321            ImportFileRegion {
322                file: initrd_file,
323                file_offset: 0,
324                file_length: initrd_len,
325                gpa: initrd_base,
326                memory_length: initrd_len,
327                acceptance: kernel_acceptance,
328                tag: "underhill-initrd",
329            },
330        )
331        .map_err(Error::ImportInitrd)?;
332
333        offset += initrd_size;
334        Some((initrd_base, initrd_len))
335    } else {
336        None
337    };
338
339    let gdt_base_address = offset;
340    let gdt_size = HV_PAGE_SIZE;
341    offset += gdt_size;
342
343    let boot_params_base = offset;
344    let boot_params_size = HV_PAGE_SIZE;
345
346    offset += boot_params_size;
347
348    let cmdline_base = offset;
349    let (cmdline, policy) = match command_line {
350        CommandLineType::Static(val) => (val, CommandLinePolicy::STATIC),
351        CommandLineType::HostAppendable(val) => (val, CommandLinePolicy::APPEND_CHOSEN),
352    };
353
354    if cmdline.len() > COMMAND_LINE_SIZE {
355        return Err(Error::CommandLineSize(cmdline.len()));
356    }
357
358    let mut static_command_line = [0; COMMAND_LINE_SIZE];
359    static_command_line[..cmdline.len()].copy_from_slice(cmdline.as_bytes());
360    let paravisor_command_line = ParavisorCommandLine {
361        policy,
362        static_command_line_len: cmdline.len() as u16,
363        static_command_line,
364    };
365
366    importer.import_pages(
367        cmdline_base / HV_PAGE_SIZE,
368        1,
369        "underhill-command-line",
370        BootPageAcceptance::Exclusive,
371        paravisor_command_line.as_bytes(),
372    )?;
373
374    offset += HV_PAGE_SIZE;
375
376    // Reserve space for the VTL2 reserved region.
377    let reserved_region_size = PARAVISOR_RESERVED_VTL2_PAGE_COUNT_MAX * HV_PAGE_SIZE;
378    let reserved_region_start = offset;
379    offset += reserved_region_size;
380
381    tracing::debug!(reserved_region_start);
382
383    let parameter_region_size = PARAVISOR_VTL2_CONFIG_REGION_PAGE_COUNT_MAX * HV_PAGE_SIZE;
384    let parameter_region_start = offset;
385    offset += parameter_region_size;
386
387    tracing::debug!(parameter_region_start);
388
389    // Reserve 8K for the bootshim log buffer. Import these pages so they are
390    // available early without extra acceptance calls.
391    let bootshim_log_size = HV_PAGE_SIZE * 2;
392    let bootshim_log_start = offset;
393    offset += bootshim_log_size;
394
395    importer.import_pages(
396        bootshim_log_start / HV_PAGE_SIZE,
397        bootshim_log_size / HV_PAGE_SIZE,
398        "ohcl-boot-shim-log-buffer",
399        BootPageAcceptance::Exclusive,
400        &[],
401    )?;
402
403    // Reserve 16 pages for a bootshim heap. This is only used to parse the
404    // protobuf payload from the previous instance in a servicing boot.
405    //
406    // Import these pages as it greatly simplifies the early startup code in the
407    // bootshim for isolated guests. This allows the bootshim to use these pages
408    // early on without extra acceptance calls.
409    let heap_start = offset;
410    let heap_size = 16 * HV_PAGE_SIZE;
411    importer.import_pages(
412        heap_start / HV_PAGE_SIZE,
413        heap_size / HV_PAGE_SIZE,
414        "ohcl-boot-shim-heap",
415        BootPageAcceptance::Exclusive,
416        &[],
417    )?;
418    offset += heap_size;
419
420    // Some loaders only fix up identity map entries that overlap the relocation
421    // region, so keep the page table region in the same large page as it.
422    offset = avoid_page_table_large_page_boundary(offset, X64_LARGE_PAGE_SIZE);
423
424    // The end of memory used by the loader, excluding pagetables.
425    let end_of_underhill_mem = offset;
426
427    // Page tables live at the end of VTL2 ram used by the bootshim.
428    //
429    // Size the available page table memory as 5 pages + 2 * 1GB of memory. This
430    // allows underhill to be mapped across a 512 GB boundary when using more
431    // than 1 GB, as the PDPTE will span 2 PML4E entries. Each GB of memory
432    // mapped requires 1 page for 2MB pages. Give 2 extra base pages and 1
433    // additional page per GB of mapped memory to allow the page table
434    // relocation code to be simpler, and not need to reclaim free pages from
435    // tables that have no valid entries.
436    //
437    // FUTURE: It would be better to change it so the shim only needs to map
438    //         itself, kernel, initrd and IGVM parameters. This requires
439    //         changing how the e820 map is constructed for the kernel along
440    //         with changing the contract on where the IGVM parameters live
441    //         within VTL2's memory.
442    let local_map = match isolation_type {
443        IsolationType::Snp | IsolationType::Tdx => {
444            Some((PARAVISOR_LOCAL_MAP_VA, PARAVISOR_LOCAL_MAP_SIZE))
445        }
446        _ => None,
447    };
448
449    let page_table_base_page_count = 5;
450    let page_table_dynamic_page_count = {
451        // Double the count to allow for simpler reconstruction.
452        calculate_pde_table_count(memory_start_address, memory_size) * 2
453            + local_map.map_or(0, |v| calculate_pde_table_count(v.0, v.1))
454    };
455    let page_table_isolation_page_count = match isolation_type {
456        IsolationType::Tdx => {
457            // TDX requires up to an extra 3 pages to map the reset vector as a
458            // 4K page.
459            3
460        }
461        _ => 0,
462    };
463    let page_table_page_count = page_table_base_page_count
464        + page_table_dynamic_page_count
465        + page_table_isolation_page_count;
466    let page_table_region_size = HV_PAGE_SIZE * page_table_page_count;
467    let page_table_region_start = offset;
468    offset += page_table_region_size;
469
470    tracing::debug!(page_table_region_start, page_table_region_size);
471
472    // Construct the memory ranges that will be identity mapped
473    let mut ranges: Vec<MappedRange> = Vec::new();
474
475    ranges.push(MappedRange::new(
476        memory_start_address,
477        memory_start_address + memory_size,
478    ));
479
480    if let Some((local_map_start, size)) = local_map {
481        ranges.push(MappedRange::new(local_map_start, local_map_start + size));
482    }
483
484    if isolation_type == IsolationType::Tdx {
485        const RESET_VECTOR_ADDR: u64 = 0xffff_f000;
486        ranges.push(MappedRange::new(
487            RESET_VECTOR_ADDR,
488            RESET_VECTOR_ADDR + page_table::x64::X64_PAGE_SIZE,
489        ));
490    }
491
492    ranges.sort_by_key(|r| r.start());
493
494    // Initialize the page table builder, and build the page table
495    let mut page_table_work_buffer: Vec<PageTable> =
496        vec![PageTable::new_zeroed(); PAGE_TABLE_MAX_COUNT];
497    let mut page_table: Vec<u8> = vec![0; PAGE_TABLE_MAX_BYTES];
498    let mut page_table_builder = PageTableBuilder::new(
499        page_table_region_start,
500        page_table_work_buffer.as_mut_slice(),
501        page_table.as_mut_slice(),
502        ranges.as_slice(),
503    )?;
504
505    if isolation_type == IsolationType::Snp {
506        page_table_builder = page_table_builder.with_confidential_bit(51);
507    }
508
509    let page_table = page_table_builder.build()?;
510
511    assert!((page_table.len() as u64).is_multiple_of(HV_PAGE_SIZE));
512    let page_table_page_base = page_table_region_start / HV_PAGE_SIZE;
513    assert!(page_table.len() as u64 <= page_table_region_size);
514    let offset = offset;
515
516    if with_relocation {
517        // Indicate relocation information. Don't include page table region.
518        importer.relocation_region(
519            memory_start_address,
520            end_of_underhill_mem - memory_start_address,
521            X64_LARGE_PAGE_SIZE,
522            PARAVISOR_DEFAULT_MEMORY_BASE_ADDRESS,
523            1 << 48,
524            true,
525            true,
526            0, // BSP
527        )?;
528
529        // Tell the loader page table relocation information.
530        importer.page_table_relocation(
531            page_table_region_start,
532            page_table_region_size / HV_PAGE_SIZE,
533            page_table.len() as u64 / HV_PAGE_SIZE,
534            0,
535        )?;
536    }
537
538    // The memory used by the loader must be smaller than the memory available.
539    if offset > memory_start_address + memory_size {
540        return Err(Error::NotEnoughMemory(offset - memory_start_address));
541    }
542
543    let (initrd_base, initrd_size) = ramdisk.unwrap_or((0, 0));
544    // Shim parameters for locations are relative to the base of where the shim is loaded.
545    let calculate_shim_offset = |addr: u64| addr.wrapping_sub(shim_base_addr).cast_signed();
546    let shim_params = ShimParamsRaw {
547        kernel_entry_offset: calculate_shim_offset(kernel_entrypoint),
548        cmdline_offset: calculate_shim_offset(cmdline_base),
549        initrd_offset: calculate_shim_offset(initrd_base),
550        initrd_size,
551        initrd_crc,
552        supported_isolation_type: match isolation_type {
553            // To the shim, None and VBS isolation are the same. The shim
554            // queries CPUID when running to determine if page acceptance needs
555            // to be done.
556            IsolationType::None | IsolationType::Vbs => {
557                loader_defs::shim::SupportedIsolationType::VBS
558            }
559            IsolationType::Snp => loader_defs::shim::SupportedIsolationType::SNP,
560            IsolationType::Tdx => loader_defs::shim::SupportedIsolationType::TDX,
561        },
562        memory_start_offset: calculate_shim_offset(memory_start_address),
563        memory_size,
564        parameter_region_offset: calculate_shim_offset(parameter_region_start),
565        parameter_region_size,
566        vtl2_reserved_region_offset: calculate_shim_offset(reserved_region_start),
567        vtl2_reserved_region_size: reserved_region_size,
568        sidecar_offset: calculate_shim_offset(sidecar_base),
569        sidecar_size,
570        sidecar_entry_offset: calculate_shim_offset(sidecar_entrypoint),
571        used_start: calculate_shim_offset(memory_start_address),
572        used_end: calculate_shim_offset(offset),
573        bounce_buffer_start: bounce_buffer.map_or(0, |r| calculate_shim_offset(r.start())),
574        bounce_buffer_size: bounce_buffer.map_or(0, |r| r.len()),
575        log_buffer_start: calculate_shim_offset(bootshim_log_start),
576        log_buffer_size: bootshim_log_size,
577        heap_start_offset: calculate_shim_offset(heap_start),
578        heap_size,
579        persisted_state_region_offset: calculate_shim_offset(persisted_region_base),
580        persisted_state_region_size: persisted_region_size,
581    };
582
583    tracing::debug!(boot_params_base, "shim gpa");
584
585    importer
586        .import_pages(
587            boot_params_base / HV_PAGE_SIZE,
588            boot_params_size / HV_PAGE_SIZE,
589            "underhill-shim-params",
590            BootPageAcceptance::Exclusive,
591            shim_params.as_bytes(),
592        )
593        .map_err(Error::Importer)?;
594
595    importer.import_pages(
596        page_table_page_base,
597        page_table_page_count,
598        "underhill-page-tables",
599        BootPageAcceptance::Exclusive,
600        page_table,
601    )?;
602
603    // Set selectors and control registers
604    // Setup two selectors and segment registers.
605    // ds, es, fs, gs, ss are linearSelector
606    // cs is linearCode64Selector
607
608    // GDT is laid out as (counting by the small entries):
609    //  0: null descriptor,
610    //  1: null descriptor,
611    //  2: linear code64 descriptor,
612    //  3. linear descriptor for data
613    //  4: here you can add more descriptors.
614
615    let default_data_attributes: u16 = X64_DEFAULT_DATA_SEGMENT_ATTRIBUTES.into();
616    let default_code64_attributes: u16 = X64_DEFAULT_CODE_SEGMENT_ATTRIBUTES.into();
617    let gdt = [
618        // A large null descriptor.
619        GdtEntry::new_zeroed(),
620        GdtEntry::new_zeroed(),
621        // Code descriptor for the long mode.
622        GdtEntry {
623            limit_low: 0xffff,
624            attr_low: default_code64_attributes as u8,
625            attr_high: (default_code64_attributes >> 8) as u8,
626            ..GdtEntry::new_zeroed()
627        },
628        // Data descriptor.
629        GdtEntry {
630            limit_low: 0xffff,
631            attr_low: default_data_attributes as u8,
632            attr_high: (default_data_attributes >> 8) as u8,
633            ..GdtEntry::new_zeroed()
634        },
635    ];
636
637    const LINEAR_CODE64_DESCRIPTOR_INDEX: usize = 2;
638    const LINEAR_DATA_DESCRIPTOR_INDEX: usize = 3;
639    const RPL: u8 = 0x00; // requested priviledge level: the highest
640
641    let linear_code64_descriptor_selector =
642        SegmentSelector::from_gdt_index(LINEAR_CODE64_DESCRIPTOR_INDEX as u16, RPL);
643    let linear_data_descriptor_selector =
644        SegmentSelector::from_gdt_index(LINEAR_DATA_DESCRIPTOR_INDEX as u16, RPL);
645
646    importer.import_pages(
647        gdt_base_address / HV_PAGE_SIZE,
648        gdt_size / HV_PAGE_SIZE,
649        "underhill-gdt",
650        BootPageAcceptance::Exclusive,
651        gdt.as_bytes(),
652    )?;
653
654    let mut import_reg = |register| {
655        importer
656            .import_vp_register(register)
657            .map_err(Error::Importer)
658    };
659
660    // Import GDTR and selectors.
661    import_reg(X86Register::Gdtr(TableRegister {
662        base: gdt_base_address,
663        limit: (size_of_val(&gdt) - 1) as u16,
664    }))?;
665
666    let ds = SegmentRegister {
667        selector: linear_data_descriptor_selector.into_bits(),
668        base: 0,
669        limit: 0xffffffff,
670        attributes: default_data_attributes,
671    };
672    import_reg(X86Register::Ds(ds))?;
673    import_reg(X86Register::Es(ds))?;
674    import_reg(X86Register::Fs(ds))?;
675    import_reg(X86Register::Gs(ds))?;
676    import_reg(X86Register::Ss(ds))?;
677
678    let cs = SegmentRegister {
679        selector: linear_code64_descriptor_selector.into_bits(),
680        base: 0,
681        limit: 0xffffffff,
682        attributes: default_code64_attributes,
683    };
684    import_reg(X86Register::Cs(cs))?;
685
686    // TODO: Workaround an OS repo bug where enabling a higher VTL zeros TR
687    //       instead of setting it to the reset default state. Manually set it
688    //       to the reset default state until the OS repo is fixed.
689    //
690    //       In the future, we should just not set this at all.
691    import_reg(X86Register::Tr(SegmentRegister {
692        selector: 0x0000,
693        base: 0x00000000,
694        limit: 0x0000FFFF,
695        attributes: X64_BUSY_TSS_SEGMENT_ATTRIBUTES.into(),
696    }))?;
697
698    // Set system registers to state expected by the boot shim, 64 bit mode with
699    // paging enabled.
700
701    // Set CR0
702    import_reg(X86Register::Cr0(
703        x86defs::Cr0::new()
704            .with_pg(true)
705            .with_pe(true)
706            .with_ne(true)
707            .into_bits(),
708    ))?;
709
710    // Set CR3 to point to page table
711    import_reg(X86Register::Cr3(page_table_region_start))?;
712
713    // Set CR4
714    import_reg(X86Register::Cr4(
715        x86defs::Cr4::new()
716            .with_pae(true)
717            .with_mce(true)
718            .with_osxsave(true)
719            .into_bits(),
720    ))?;
721
722    // Set EFER to LMA, LME, and NXE for 64 bit mode.
723    import_reg(X86Register::Efer(
724        x86defs::Efer::new()
725            .with_lma(true)
726            .with_lme(true)
727            .with_nxe(true)
728            .into_bits(),
729    ))?;
730
731    // Set PAT
732    import_reg(X86Register::Pat(x86defs::X86X_MSR_DEFAULT_PAT))?;
733
734    // Setup remaining registers
735    // Set %rsi to relative location of boot_params_base
736    let relative_boot_params_base = boot_params_base - shim_base_addr;
737    import_reg(X86Register::Rsi(relative_boot_params_base))?;
738
739    // Set %rip to the shim entry point.
740    import_reg(X86Register::Rip(shim_entry_address))?;
741
742    // Load parameter regions.
743    let config_region_page_base = parameter_region_start / HV_PAGE_SIZE;
744
745    // Slit
746    let slit_page_base = config_region_page_base + PARAVISOR_CONFIG_SLIT_PAGE_INDEX;
747    let slit_parameter_area = importer.create_parameter_area(
748        slit_page_base,
749        PARAVISOR_CONFIG_SLIT_SIZE_PAGES as u32,
750        "underhill-slit",
751    )?;
752    importer.import_parameter(slit_parameter_area, 0, IgvmParameterType::Slit)?;
753
754    // Pptt
755    let pptt_page_base = config_region_page_base + PARAVISOR_CONFIG_PPTT_PAGE_INDEX;
756    let pptt_parameter_area = importer.create_parameter_area(
757        pptt_page_base,
758        PARAVISOR_CONFIG_PPTT_SIZE_PAGES as u32,
759        "underhill-pptt",
760    )?;
761    importer.import_parameter(pptt_parameter_area, 0, IgvmParameterType::Pptt)?;
762
763    // device tree
764    let dt_page_base = config_region_page_base + PARAVISOR_CONFIG_DEVICE_TREE_PAGE_INDEX;
765    let dt_parameter_area = importer.create_parameter_area(
766        dt_page_base,
767        PARAVISOR_CONFIG_DEVICE_TREE_SIZE_PAGES as u32,
768        "underhill-device-tree",
769    )?;
770    importer.import_parameter(dt_parameter_area, 0, IgvmParameterType::DeviceTree)?;
771
772    if isolation_type == IsolationType::Snp {
773        let reserved_region_page_base = reserved_region_start / HV_PAGE_SIZE;
774        let secrets_page_base: u64 =
775            reserved_region_page_base + PARAVISOR_RESERVED_VTL2_SNP_SECRETS_PAGE_INDEX;
776        importer.import_pages(
777            secrets_page_base,
778            PARAVISOR_RESERVED_VTL2_SNP_SECRETS_SIZE_PAGES,
779            "underhill-snp-secrets-page",
780            BootPageAcceptance::SecretsPage,
781            &[],
782        )?;
783
784        let cpuid_page = create_snp_cpuid_page();
785        let cpuid_page_base =
786            reserved_region_page_base + PARAVISOR_RESERVED_VTL2_SNP_CPUID_PAGE_INDEX;
787        importer.import_pages(
788            cpuid_page_base,
789            1,
790            "underhill-snp-cpuid-page",
791            BootPageAcceptance::CpuidPage,
792            cpuid_page.as_bytes(),
793        )?;
794
795        importer.import_pages(
796            cpuid_page_base + 1,
797            1,
798            "underhill-snp-cpuid-extended-state-page",
799            BootPageAcceptance::CpuidExtendedStatePage,
800            &[],
801        )?;
802
803        let vmsa_page_base =
804            reserved_region_page_base + PARAVISOR_RESERVED_VTL2_SNP_VMSA_PAGE_INDEX;
805        importer.set_vp_context_page(vmsa_page_base)?;
806    }
807
808    // Load measured config.
809    // The measured config is at page 0. Free pages start at page 1.
810    let mut free_page = 1;
811    let mut measured_config = ParavisorMeasuredVtl0Config {
812        magic: ParavisorMeasuredVtl0Config::MAGIC,
813        ..FromZeros::new_zeroed()
814    };
815
816    let Vtl0Config {
817        supports_pcat,
818        supports_uefi,
819        supports_linux,
820    } = vtl0_config;
821
822    if supports_pcat {
823        measured_config.supported_vtl0.set_pcat_supported(true);
824    }
825
826    if let Some((uefi, vp_context)) = &supports_uefi {
827        measured_config.supported_vtl0.set_uefi_supported(true);
828        let vp_context_page = free_page;
829        free_page += 1;
830        measured_config.uefi_info = UefiInfo {
831            firmware: PageRegionDescriptor {
832                base_page_number: uefi.firmware_base / HV_PAGE_SIZE,
833                page_count: uefi.total_size / HV_PAGE_SIZE,
834            },
835            vtl0_vp_context: PageRegionDescriptor {
836                base_page_number: vp_context_page,
837                page_count: 1,
838            },
839        };
840
841        // Deposit the UEFI vp context.
842        importer.import_pages(
843            vp_context_page,
844            1,
845            "openhcl-uefi-vp-context",
846            BootPageAcceptance::Exclusive,
847            vp_context,
848        )?;
849    }
850
851    if let Some(linux) = supports_linux {
852        measured_config
853            .supported_vtl0
854            .set_linux_direct_supported(true);
855
856        let kernel_region = PageRegionDescriptor::new(
857            linux.load_info.kernel.gpa / HV_PAGE_SIZE,
858            align_up_to_page_size(linux.load_info.kernel.size) / HV_PAGE_SIZE,
859        );
860
861        let (initrd_region, initrd_size) = match linux.load_info.initrd {
862            Some(info) => {
863                if !info.gpa.is_multiple_of(HV_PAGE_SIZE) {
864                    return Err(Error::MemoryUnaligned(info.gpa));
865                }
866                (
867                    // initrd info is aligned up to the next page.
868                    PageRegionDescriptor::new(
869                        info.gpa / HV_PAGE_SIZE,
870                        align_up_to_page_size(info.size) / HV_PAGE_SIZE,
871                    ),
872                    info.size,
873                )
874            }
875            None => (PageRegionDescriptor::EMPTY, 0),
876        };
877
878        let command_line_page = free_page;
879        // free_page += 1;
880
881        // Import the command line as a C string.
882        importer
883            .import_pages(
884                command_line_page,
885                1,
886                "underhill-vtl0-linux-command-line",
887                BootPageAcceptance::Exclusive,
888                linux.command_line.as_bytes_with_nul(),
889            )
890            .map_err(Error::Importer)?;
891        let command_line = PageRegionDescriptor::new(command_line_page, 1);
892
893        measured_config.linux_info = LinuxInfo {
894            kernel_region,
895            kernel_entrypoint: linux.load_info.kernel.entrypoint,
896            initrd_region,
897            initrd_size,
898            command_line,
899        };
900    }
901
902    importer
903        .import_pages(
904            PARAVISOR_VTL0_MEASURED_CONFIG_BASE_PAGE_X64,
905            1,
906            "underhill-measured-config",
907            BootPageAcceptance::Exclusive,
908            measured_config.as_bytes(),
909        )
910        .map_err(Error::Importer)?;
911
912    let vtl2_measured_config = ParavisorMeasuredVtl2Config {
913        magic: ParavisorMeasuredVtl2Config::MAGIC,
914        vtom_offset_bit: shared_gpa_boundary_bits.unwrap_or(0),
915        padding: [0; 7],
916    };
917
918    importer
919        .import_pages(
920            config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_PAGE_INDEX,
921            PARAVISOR_MEASURED_VTL2_CONFIG_SIZE_PAGES,
922            "underhill-vtl2-measured-config",
923            BootPageAcceptance::Exclusive,
924            vtl2_measured_config.as_bytes(),
925        )
926        .map_err(Error::Importer)?;
927
928    let imported_region_base =
929        config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_ACCEPTED_MEMORY_PAGE_INDEX;
930
931    importer.set_imported_regions_config_page(imported_region_base);
932
933    // Also announce the per-page expected-hashes region. The IGVM file
934    // loader populates it in finalize alongside the imported-regions page
935    // (both regions are derived from the same set of shared pages). See
936    // `openhcl_boot::verify_imported_regions_hash` diagnostic changes.
937    let expected_page_hashes_base =
938        config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_PAGE_HASHES_PAGE_INDEX;
939    importer.set_expected_page_hashes_config_page(expected_page_hashes_base);
940    Ok(())
941}
942
943/// Create a hypervisor SNP CPUID page with the default values.
944fn create_snp_cpuid_page() -> HV_PSP_CPUID_PAGE {
945    let mut cpuid_page = HV_PSP_CPUID_PAGE::new_zeroed();
946
947    // TODO SNP: The list used here is based earlier Microsoft projects.
948    // 1. ExtendedStateEnumeration should be part of BootPageAcceptance::CpuidExtendedStatePage,
949    // but it is unclear whether Linux supports a second page. The need for the second page is that
950    // the entries in it are actually based on supported features on a specific host.
951    // 2. ExtendedStateEnumeration should specify Xfem = 3
952    for (i, required_leaf) in crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_PARAVISOR
953        .iter()
954        .enumerate()
955    {
956        let entry = &mut cpuid_page.cpuid_leaf_info[i];
957        entry.eax_in = required_leaf.eax;
958        entry.ecx_in = required_leaf.ecx;
959        if required_leaf.eax == CpuidFunction::ExtendedStateEnumeration.0 {
960            entry.xfem_in = 1;
961        }
962        cpuid_page.count += 1;
963    }
964
965    cpuid_page
966}
967
968/// Load the underhill kernel on arm64.
969///
970/// An optional initrd may be specified.
971///
972/// An optional `memory_page_base` may be specified. This will disable
973/// relocation support for underhill.
974pub fn load_openhcl_arm64<F>(
975    importer: &mut dyn ImageLoad<Aarch64Register>,
976    kernel_image: &mut F,
977    shim: &mut F,
978    command_line: CommandLineType<'_>,
979    mut initrd: Option<(&mut dyn ReadSeek, u64)>,
980    memory_page_base: Option<u64>,
981    memory_page_count: u64,
982    vtl0_config: Vtl0Config<'_>,
983) -> Result<(), Error>
984where
985    F: Read + Seek,
986{
987    let Vtl0Config {
988        supports_pcat,
989        supports_uefi,
990        supports_linux,
991    } = vtl0_config;
992
993    assert!(!supports_pcat);
994    assert!(supports_uefi.is_some() || supports_linux.is_some());
995
996    let paravisor_present = importer.isolation_config().paravisor_present;
997
998    // If no explicit memory base is specified, load with relocation support.
999    let with_relocation = memory_page_base.is_none();
1000
1001    let memory_start_address = memory_page_base
1002        .map(|page_number| page_number * HV_PAGE_SIZE)
1003        .unwrap_or(PARAVISOR_DEFAULT_MEMORY_BASE_ADDRESS);
1004
1005    let memory_size = memory_page_count * HV_PAGE_SIZE;
1006
1007    // Paravisor memory ranges must be 2MB (large page) aligned.
1008    if !memory_start_address.is_multiple_of(u64::from(Arm64PageSize::Large)) {
1009        return Err(Error::MemoryUnaligned(memory_start_address));
1010    }
1011
1012    if !memory_size.is_multiple_of(u64::from(Arm64PageSize::Large)) {
1013        return Err(Error::MemoryUnaligned(memory_size));
1014    }
1015
1016    // The whole memory range must be present and VTL2 protectable for the
1017    // underhill kernel to work.
1018    importer.verify_startup_memory_available(
1019        memory_start_address / HV_PAGE_SIZE,
1020        memory_page_count,
1021        if paravisor_present {
1022            StartupMemoryType::Vtl2ProtectableRam
1023        } else {
1024            StartupMemoryType::Ram
1025        },
1026    )?;
1027
1028    let mut next_addr = memory_start_address;
1029
1030    // Reserve the first 2MB for a potential persisted state region. The first
1031    // 4K page is always the persisted state header, and the bootshim may decide
1032    // to use the the remaining pages for the protobuf payload.
1033    let persisted_region_base = next_addr;
1034    let persisted_region_size = PERSISTED_REGION_SIZE;
1035    next_addr += persisted_region_size;
1036
1037    tracing::trace!(next_addr, "loading the kernel");
1038
1039    // Compute initrd CRC before the file reference is consumed by the loader.
1040    let initrd_crc = if let Some((ref mut initrd_file, initrd_len)) = initrd {
1041        ChunkBuf::new()
1042            .crc32(*initrd_file, initrd_len)
1043            .map_err(Error::InitrdRead)?
1044    } else {
1045        crc32fast::hash(&[])
1046    };
1047
1048    // The aarch64 Linux kernel image is most commonly found as a flat binary with a
1049    // header rather than an ELF.
1050    // DeviceTree is generated dynamically by the boot shim.
1051    let initrd_address_type = InitrdAddressType::AfterKernel;
1052    let initrd_config = initrd.map(|(initrd_file, initrd_size)| InitrdConfig {
1053        initrd_address: initrd_address_type,
1054        initrd: initrd_file,
1055        size: initrd_size,
1056    });
1057    let device_tree_blob = None;
1058    let crate::linux::LoadInfo {
1059        kernel:
1060            KernelInfo {
1061                gpa: kernel_base,
1062                size: kernel_size,
1063                entrypoint: kernel_entry_point,
1064            },
1065        initrd: initrd_info,
1066        dtb,
1067        ..
1068    } = load_kernel_and_initrd_arm64(
1069        importer,
1070        kernel_image,
1071        next_addr,
1072        initrd_config,
1073        device_tree_blob,
1074    )
1075    .map_err(Error::Kernel)?;
1076
1077    assert!(
1078        dtb.is_none(),
1079        "DeviceTree is generated dynamically by the boot shim."
1080    );
1081
1082    tracing::trace!(kernel_base, "kernel loaded");
1083
1084    let InitrdInfo {
1085        gpa: initrd_gpa,
1086        size: initrd_size,
1087    } = if let Some(initrd_info) = initrd_info {
1088        assert!(initrd_address_type == InitrdAddressType::AfterKernel);
1089        next_addr = initrd_info.gpa + initrd_info.size;
1090        initrd_info
1091    } else {
1092        next_addr = kernel_base + kernel_size;
1093        InitrdInfo { gpa: 0, size: 0 }
1094    };
1095
1096    next_addr = align_up_to_page_size(next_addr);
1097
1098    tracing::trace!(next_addr, "loading the boot shim");
1099
1100    let crate::elf::LoadInfo {
1101        minimum_address_used: shim_base_addr,
1102        next_available_address: mut next_addr,
1103        entrypoint: shim_entry_point,
1104    } = crate::elf::load_static_elf(
1105        importer,
1106        shim,
1107        0,
1108        next_addr,
1109        false,
1110        BootPageAcceptance::Exclusive,
1111        "underhill-boot-shim",
1112    )
1113    .map_err(Error::Shim)?;
1114
1115    tracing::trace!(shim_base_addr, "boot shim loaded");
1116
1117    tracing::trace!(next_addr, "loading the command line");
1118
1119    let cmdline_base = next_addr;
1120    let (cmdline, policy) = match command_line {
1121        CommandLineType::Static(val) => (val, CommandLinePolicy::STATIC),
1122        CommandLineType::HostAppendable(val) => (val, CommandLinePolicy::APPEND_CHOSEN),
1123    };
1124
1125    if cmdline.len() > COMMAND_LINE_SIZE {
1126        return Err(Error::CommandLineSize(cmdline.len()));
1127    }
1128
1129    let mut static_command_line = [0; COMMAND_LINE_SIZE];
1130    static_command_line[..cmdline.len()].copy_from_slice(cmdline.as_bytes());
1131    let paravisor_command_line = ParavisorCommandLine {
1132        policy,
1133        static_command_line_len: cmdline.len() as u16,
1134        static_command_line,
1135    };
1136
1137    importer.import_pages(
1138        cmdline_base / HV_PAGE_SIZE,
1139        1,
1140        "underhill-command-line",
1141        BootPageAcceptance::Exclusive,
1142        paravisor_command_line.as_bytes(),
1143    )?;
1144
1145    next_addr += HV_PAGE_SIZE;
1146
1147    tracing::trace!(next_addr, "loading the boot shim parameters");
1148
1149    let shim_params_base = next_addr;
1150    let shim_params_size = HV_PAGE_SIZE;
1151
1152    next_addr += shim_params_size;
1153
1154    let parameter_region_size = PARAVISOR_VTL2_CONFIG_REGION_PAGE_COUNT_MAX * HV_PAGE_SIZE;
1155    let parameter_region_start = next_addr;
1156    next_addr += parameter_region_size;
1157
1158    tracing::debug!(parameter_region_start);
1159
1160    // Reserve 8K for the bootshim log buffer.
1161    let bootshim_log_size = HV_PAGE_SIZE * 2;
1162    let bootshim_log_start = next_addr;
1163    next_addr += bootshim_log_size;
1164
1165    importer.import_pages(
1166        bootshim_log_start / HV_PAGE_SIZE,
1167        bootshim_log_size / HV_PAGE_SIZE,
1168        "ohcl-boot-shim-log-buffer",
1169        BootPageAcceptance::Exclusive,
1170        &[],
1171    )?;
1172
1173    // Reserve 16 pages for a bootshim heap. This is only used to parse the
1174    // protobuf payload from the previous instance in a servicing boot.
1175    //
1176    // Import these pages as it greatly simplifies the early startup code in the
1177    // bootshim for isolated guests. This allows the bootshim to use these pages
1178    // early on without extra acceptance calls.
1179    let heap_start = next_addr;
1180    let heap_size = 16 * HV_PAGE_SIZE;
1181    importer.import_pages(
1182        heap_start / HV_PAGE_SIZE,
1183        heap_size / HV_PAGE_SIZE,
1184        "ohcl-boot-shim-heap",
1185        BootPageAcceptance::Exclusive,
1186        &[],
1187    )?;
1188    next_addr += heap_size;
1189
1190    // Some loaders only fix up identity map entries that overlap the relocation
1191    // region, so keep the page table region in the same large page as it.
1192    next_addr = avoid_page_table_large_page_boundary(next_addr, u64::from(Arm64PageSize::Large));
1193
1194    // The end of memory used by the loader, excluding pagetables.
1195    let end_of_underhill_mem = next_addr;
1196
1197    // Page tables live at the end of the VTL2 imported region, which allows it
1198    // to be relocated separately.
1199    let page_table_base_page_count = 5;
1200    let page_table_dynamic_page_count = 2 * page_table_base_page_count;
1201    let page_table_page_count = page_table_base_page_count + page_table_dynamic_page_count;
1202    let page_table_region_size = HV_PAGE_SIZE * page_table_page_count;
1203    let page_table_region_start = next_addr;
1204    next_addr += page_table_region_size;
1205
1206    tracing::debug!(page_table_region_start, page_table_region_size);
1207
1208    let next_addr = next_addr;
1209
1210    // The memory used by the loader must be smaller than the memory available.
1211    if next_addr > memory_start_address + memory_size {
1212        return Err(Error::NotEnoughMemory(next_addr - memory_start_address));
1213    }
1214
1215    // Shim parameters for locations are relative to the base of where the shim is loaded.
1216    let calculate_shim_offset =
1217        |addr: u64| -> i64 { addr.wrapping_sub(shim_base_addr).cast_signed() };
1218    let shim_params = ShimParamsRaw {
1219        kernel_entry_offset: calculate_shim_offset(kernel_entry_point),
1220        cmdline_offset: calculate_shim_offset(cmdline_base),
1221        initrd_offset: calculate_shim_offset(initrd_gpa),
1222        initrd_size,
1223        initrd_crc,
1224        supported_isolation_type: match importer.isolation_config().isolation_type {
1225            IsolationType::None | IsolationType::Vbs => {
1226                loader_defs::shim::SupportedIsolationType::VBS
1227            }
1228            _ => panic!("only None and VBS are supported for ARM64"),
1229        },
1230        memory_start_offset: calculate_shim_offset(memory_start_address),
1231        memory_size,
1232        parameter_region_offset: calculate_shim_offset(parameter_region_start),
1233        parameter_region_size,
1234        vtl2_reserved_region_offset: 0,
1235        vtl2_reserved_region_size: 0,
1236        sidecar_offset: 0,
1237        sidecar_size: 0,
1238        sidecar_entry_offset: 0,
1239        used_start: calculate_shim_offset(memory_start_address),
1240        used_end: calculate_shim_offset(next_addr),
1241        bounce_buffer_start: 0,
1242        bounce_buffer_size: 0,
1243        log_buffer_start: calculate_shim_offset(bootshim_log_start),
1244        log_buffer_size: bootshim_log_size,
1245        heap_start_offset: calculate_shim_offset(heap_start),
1246        heap_size,
1247        persisted_state_region_offset: calculate_shim_offset(persisted_region_base),
1248        persisted_state_region_size: persisted_region_size,
1249    };
1250
1251    importer
1252        .import_pages(
1253            shim_params_base / HV_PAGE_SIZE,
1254            shim_params_size / HV_PAGE_SIZE,
1255            "underhill-shim-params",
1256            BootPageAcceptance::Exclusive,
1257            shim_params.as_bytes(),
1258        )
1259        .map_err(Error::Importer)?;
1260
1261    let mut measured_config = ParavisorMeasuredVtl0Config {
1262        magic: ParavisorMeasuredVtl0Config::MAGIC,
1263        ..FromZeros::new_zeroed()
1264    };
1265
1266    if let Some((uefi, vp_context)) = &supports_uefi {
1267        measured_config.supported_vtl0.set_uefi_supported(true);
1268        let vp_context_page = PARAVISOR_VTL0_MEASURED_CONFIG_BASE_PAGE_AARCH64 + 1;
1269        measured_config.uefi_info = UefiInfo {
1270            firmware: PageRegionDescriptor {
1271                base_page_number: uefi.firmware_base / HV_PAGE_SIZE,
1272                page_count: uefi.total_size / HV_PAGE_SIZE,
1273            },
1274            vtl0_vp_context: PageRegionDescriptor {
1275                base_page_number: vp_context_page,
1276                page_count: 1,
1277            },
1278        };
1279
1280        // Deposit the UEFI vp context.
1281        importer.import_pages(
1282            vp_context_page,
1283            1,
1284            "openhcl-uefi-vp-context",
1285            BootPageAcceptance::Exclusive,
1286            vp_context,
1287        )?;
1288    }
1289
1290    importer
1291        .import_pages(
1292            PARAVISOR_VTL0_MEASURED_CONFIG_BASE_PAGE_AARCH64,
1293            1,
1294            "underhill-measured-config",
1295            BootPageAcceptance::Exclusive,
1296            measured_config.as_bytes(),
1297        )
1298        .map_err(Error::Importer)?;
1299
1300    tracing::trace!(page_table_region_start, "loading the page tables");
1301
1302    let memory_attribute_indirection = MemoryAttributeIndirectionEl1([
1303        MemoryAttributeEl1::Device_nGnRnE,
1304        MemoryAttributeEl1::Normal_NonCacheable,
1305        MemoryAttributeEl1::Normal_WriteThrough,
1306        MemoryAttributeEl1::Normal_WriteBack,
1307        MemoryAttributeEl1::Device_nGnRnE,
1308        MemoryAttributeEl1::Device_nGnRnE,
1309        MemoryAttributeEl1::Device_nGnRnE,
1310        MemoryAttributeEl1::Device_nGnRnE,
1311    ]);
1312    let mut page_tables: Vec<u8> = vec![0; page_table_region_size as usize];
1313    let page_tables = page_table::aarch64::build_identity_page_tables_aarch64(
1314        page_table_region_start,
1315        memory_start_address,
1316        memory_size,
1317        memory_attribute_indirection,
1318        page_tables.as_mut_slice(),
1319    );
1320    assert!((page_tables.len() as u64).is_multiple_of(HV_PAGE_SIZE));
1321    let page_table_page_base = page_table_region_start / HV_PAGE_SIZE;
1322    assert!(page_tables.len() as u64 <= page_table_region_size);
1323    assert!(page_table_region_size as usize > page_tables.len());
1324
1325    if with_relocation {
1326        // Indicate relocation information. Don't include page table region.
1327        importer.relocation_region(
1328            memory_start_address,
1329            end_of_underhill_mem - memory_start_address,
1330            Arm64PageSize::Large.into(),
1331            PARAVISOR_DEFAULT_MEMORY_BASE_ADDRESS,
1332            1 << 48,
1333            true,
1334            false,
1335            0, // BSP
1336        )?;
1337
1338        // Tell the loader page table relocation information.
1339        importer.page_table_relocation(
1340            page_table_region_start,
1341            page_table_region_size / HV_PAGE_SIZE,
1342            page_tables.len() as u64 / HV_PAGE_SIZE,
1343            0,
1344        )?;
1345    }
1346
1347    importer.import_pages(
1348        page_table_page_base,
1349        page_table_page_count,
1350        "underhill-page-tables",
1351        BootPageAcceptance::Exclusive,
1352        page_tables,
1353    )?;
1354
1355    tracing::trace!("Importing register state");
1356
1357    let mut import_reg = |register| {
1358        importer
1359            .import_vp_register(register)
1360            .map_err(Error::Importer)
1361    };
1362
1363    // Set %X0 to relative location of boot_params_base
1364    let relative_boot_params_base = shim_params_base - shim_base_addr;
1365    import_reg(AArch64Register::X0(relative_boot_params_base).into())?;
1366
1367    // Set %pc to the shim entry point.
1368    import_reg(AArch64Register::Pc(shim_entry_point).into())?;
1369
1370    // System registers
1371
1372    import_reg(AArch64Register::Cpsr(Cpsr64::new().with_sp(true).with_el(1).into()).into())?;
1373
1374    // This is what Hyper-V uses. qemu/KVM, and qemu/max use slightly
1375    // different flags.
1376    // KVM sets these in addition to what the Hyper-V uses:
1377    //
1378    // .with_sa(true)
1379    // .with_itd(true)
1380    // .with_sed(true)
1381    //
1382    // Windows sets:
1383    //
1384    // .with_sa(true)
1385    // .with_sa0(true)
1386    // .with_n_aa(true)
1387    // .with_sed(true)
1388    // .with_dze(true)
1389    // .with_en_ib(true)
1390    // .with_dssbs(true)
1391    //
1392    // Maybe could enforce the `s`tack `a`lignment, here, too. Depends on
1393    // the compiler generating code aligned accesses for the stack.
1394    //
1395    // Hyper-V sets:
1396    import_reg(
1397        AArch64Register::SctlrEl1(
1398            SctlrEl1::new()
1399                // MMU enable for EL1&0 stage 1 address translation.
1400                // It can be turned off in VTL2 for debugging.
1401                // The family of the `at` instructions and the `PAR_EL1` register are
1402                // useful for debugging MMU issues.
1403                .with_m(true)
1404                // Stage 1 Cacheability control, for data accesses.
1405                .with_c(true)
1406                // Stage 1 Cacheability control, for code.
1407                .with_i(true)
1408                // Reserved flags, must be set
1409                .with_eos(true)
1410                .with_tscxt(true)
1411                .with_eis(true)
1412                .with_span(true)
1413                .with_n_tlsmd(true)
1414                .with_lsmaoe(true)
1415                .into(),
1416        )
1417        .into(),
1418    )?;
1419
1420    // Hyper-V UEFI and qemu/KVM use the same value for TCR_EL1.
1421    // They set `t0sz` to `28` as they map memory pretty low.
1422    // In the paravisor case, need more flexibility.
1423    // For the details, refer to the "Learning the architecture" series
1424    // on the ARM website.
1425    import_reg(
1426        AArch64Register::TcrEl1(
1427            TranslationControlEl1::new()
1428                .with_t0sz(0x11)
1429                .with_irgn0(1)
1430                .with_orgn0(1)
1431                .with_sh0(3)
1432                .with_tg0(TranslationGranule0::TG_4KB)
1433                // Disable TTBR1_EL1 walks (i.e. the upper half).
1434                .with_epd1(1)
1435                // Due to erratum #822227, need to set a valid TG1 regardless of EPD1.
1436                .with_tg1(TranslationGranule1::TG_4KB)
1437                .with_ips(IntermPhysAddrSize::IPA_48_BITS_256_TB)
1438                .into(),
1439        )
1440        .into(),
1441    )?;
1442
1443    // The Memory Attribute Indirection
1444    import_reg(AArch64Register::MairEl1(memory_attribute_indirection.into()).into())?;
1445    import_reg(
1446        AArch64Register::Ttbr0El1(
1447            TranslationBaseEl1::new()
1448                .with_baddr(page_table_region_start)
1449                .into(),
1450        )
1451        .into(),
1452    )?;
1453
1454    // VBAR is in the undefined state, setting it to 0 albeit
1455    // without the vector exception table. The shim can configure that on its own
1456    // if need be.
1457    import_reg(AArch64Register::VbarEl1(0).into())?;
1458
1459    // Load parameter regions.
1460    let config_region_page_base = parameter_region_start / HV_PAGE_SIZE;
1461
1462    // Slit
1463    let slit_page_base = config_region_page_base + PARAVISOR_CONFIG_SLIT_PAGE_INDEX;
1464    let slit_parameter_area = importer.create_parameter_area(
1465        slit_page_base,
1466        PARAVISOR_CONFIG_SLIT_SIZE_PAGES as u32,
1467        "underhill-slit",
1468    )?;
1469    importer.import_parameter(slit_parameter_area, 0, IgvmParameterType::Slit)?;
1470
1471    // Pptt
1472    let pptt_page_base = config_region_page_base + PARAVISOR_CONFIG_PPTT_PAGE_INDEX;
1473    let pptt_parameter_area = importer.create_parameter_area(
1474        pptt_page_base,
1475        PARAVISOR_CONFIG_PPTT_SIZE_PAGES as u32,
1476        "underhill-pptt",
1477    )?;
1478    importer.import_parameter(pptt_parameter_area, 0, IgvmParameterType::Pptt)?;
1479
1480    // device tree
1481    let dt_page_base = config_region_page_base + PARAVISOR_CONFIG_DEVICE_TREE_PAGE_INDEX;
1482    let dt_parameter_area = importer.create_parameter_area(
1483        dt_page_base,
1484        PARAVISOR_CONFIG_DEVICE_TREE_SIZE_PAGES as u32,
1485        "underhill-device-tree",
1486    )?;
1487    importer.import_parameter(dt_parameter_area, 0, IgvmParameterType::DeviceTree)?;
1488
1489    let vtl2_measured_config = ParavisorMeasuredVtl2Config {
1490        magic: ParavisorMeasuredVtl2Config::MAGIC,
1491        vtom_offset_bit: 0,
1492        padding: [0; 7],
1493    };
1494
1495    importer
1496        .import_pages(
1497            config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_PAGE_INDEX,
1498            PARAVISOR_MEASURED_VTL2_CONFIG_SIZE_PAGES,
1499            "underhill-vtl2-measured-config",
1500            BootPageAcceptance::Exclusive,
1501            vtl2_measured_config.as_bytes(),
1502        )
1503        .map_err(Error::Importer)?;
1504
1505    let imported_region_base =
1506        config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_ACCEPTED_MEMORY_PAGE_INDEX;
1507
1508    importer.set_imported_regions_config_page(imported_region_base);
1509
1510    // Also announce the per-page expected-hashes region (see comments in
1511    // the x86 sibling above).
1512    let expected_page_hashes_base =
1513        config_region_page_base + PARAVISOR_MEASURED_VTL2_CONFIG_PAGE_HASHES_PAGE_INDEX;
1514    importer.set_expected_page_hashes_config_page(expected_page_hashes_base);
1515
1516    Ok(())
1517}
1518
1519#[cfg(test)]
1520mod page_table_layout_tests {
1521    use super::*;
1522
1523    #[test]
1524    fn page_table_region_avoids_large_page_boundary() {
1525        for large_page_size in [X64_LARGE_PAGE_SIZE, u64::from(Arm64PageSize::Large)] {
1526            assert_eq!(
1527                avoid_page_table_large_page_boundary(large_page_size, large_page_size),
1528                large_page_size + HV_PAGE_SIZE
1529            );
1530            assert_eq!(
1531                avoid_page_table_large_page_boundary(
1532                    large_page_size - HV_PAGE_SIZE,
1533                    large_page_size
1534                ),
1535                large_page_size - HV_PAGE_SIZE
1536            );
1537        }
1538    }
1539}