Skip to main content

loader/uefi/
mod.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! UEFI specific loader definitions and implementation.
5
6pub mod config;
7pub mod firmware_version;
8
9cfg_select! {
10    guest_arch = "aarch64" => {
11        use aarch64 as arch;
12    }
13    guest_arch = "x86_64" => {
14        use x86_64 as arch;
15    }
16}
17
18pub use arch::CONFIG_BLOB_GPA_BASE;
19pub use arch::IMAGE_SIZE;
20pub use arch::load;
21
22use thiserror::Error;
23use uefi_specs::uefi::firmware_volume;
24use zerocopy::FromBytes;
25use zerocopy::Immutable;
26use zerocopy::IntoBytes;
27use zerocopy::KnownLayout;
28
29// Constant defining the offset within the image where the SEC volume starts.
30// TODO: Revisit this when we reorganize the firmware layout. One option
31// would be to just put the SEC volume at the start of the image, so no need
32// for this offset.
33const SEC_FIRMWARE_VOLUME_OFFSET: u64 = 0x005E0000;
34
35/// Expand a 3 byte sequence into little-endian integer.
36fn expand_3byte_integer(size: [u8; 3]) -> u64 {
37    ((size[2] as u64) << 16) + ((size[1] as u64) << 8) + size[0] as u64
38}
39
40const fn signature_16(v: &[u8; 2]) -> u16 {
41    v[0] as u16 | (v[1] as u16) << 8
42}
43
44const IMAGE_DOS_SIGNATURE: u16 = 0x5A4D; // MZ
45const IMAGE_NT_SIGNATURE: u32 = 0x00004550; // PE00
46const TE_IMAGE_HEADER_SIGNATURE: u16 = signature_16(b"VZ");
47
48#[repr(C)]
49#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
50struct ImageDosHeader {
51    e_magic: u16,      // Magic number
52    e_cblp: u16,       // Bytes on last page of file
53    e_cp: u16,         // Pages in file
54    e_crlc: u16,       // Relocations
55    e_cparhdr: u16,    // Size of header in paragraphs
56    e_minalloc: u16,   // Minimum extra paragraphs needed
57    e_maxalloc: u16,   // Maximum extra paragraphs needed
58    e_ss: u16,         // Initial (relative) SS value
59    e_sp: u16,         // Initial SP value
60    e_csum: u16,       // Checksum
61    e_ip: u16,         // Initial IP value
62    e_cs: u16,         // Initial (relative) CS value
63    e_lfarlc: u16,     // File address of relocation table
64    e_ovno: u16,       // Overlay number
65    e_res: [u16; 4],   // Reserved words
66    e_oemid: u16,      // OEM identifier (for e_oeminfo)
67    e_oeminfo: u16,    // OEM information; e_oemid specific
68    e_res2: [u16; 10], // Reserved words
69    e_lfanew: i32,     // File address of new exe header
70}
71
72#[repr(C)]
73#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
74struct TeImageHeader {
75    signature: u16,
76    machine: u16,
77    number_of_sections: u8,
78    subsystem: u8,
79    stripped_size: u16,
80    address_of_entry_point: u32,
81    base_of_code: u32,
82    image_base: u64,
83    data_directory: [ImageDataDirectory; 2],
84}
85
86#[repr(C)]
87#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
88struct ImageNtHeaders32 {
89    signature: u32,
90    file_header: ImageFileHeader,
91    optional_header: ImageOptionalHeader32,
92}
93
94#[repr(C)]
95#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
96struct ImageFileHeader {
97    machine: u16,
98    number_of_sections: u16,
99    time_date_stamp: u32,
100    pointer_to_symbol_table: u32,
101    number_of_symbols: u32,
102    size_of_optional_header: u16,
103    characteristics: u16,
104}
105
106#[repr(C)]
107#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
108struct ImageOptionalHeader32 {
109    magic: u16,
110    major_linker_version: u8,
111    minor_linker_version: u8,
112    size_of_code: u32,
113    size_of_initialized_data: u32,
114    size_of_uninitialized_data: u32,
115    address_of_entry_point: u32,
116    base_of_code: u32,
117    base_of_data: u32,
118    image_base: u32,
119    section_alignment: u32,
120    file_alignment: u32,
121    major_operating_system_version: u16,
122    minor_operating_system_version: u16,
123    major_image_version: u16,
124    minor_image_version: u16,
125    major_subsystem_version: u16,
126    minor_subsystem_version: u16,
127    win32_version_value: u32,
128    size_of_image: u32,
129    size_of_headers: u32,
130    check_sum: u32,
131    subsystem: u16,
132    dll_characteristics: u16,
133    size_of_stack_reserve: u32,
134    size_of_stack_commit: u32,
135    size_of_heap_reserve: u32,
136    size_of_heap_commit: u32,
137    loader_flags: u32,
138    number_of_rva_and_sizes: u32,
139    data_directory: [ImageDataDirectory; 16],
140}
141
142#[repr(C)]
143#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
144struct ImageDataDirectory {
145    virtual_address: u32,
146    size: u32,
147}
148
149fn pe_get_entry_point_offset(pe32_data: &[u8]) -> Option<u32> {
150    let dos_header = ImageDosHeader::read_from_prefix(pe32_data).ok()?.0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
151    let nt_headers_offset = if dos_header.e_magic == IMAGE_DOS_SIGNATURE {
152        // DOS image header is present, so read the PE header after the DOS image header.
153        dos_header.e_lfanew as usize
154    } else {
155        // DOS image header is not present, so PE header is at the image base.
156        0
157    };
158
159    let signature = u32::read_from_prefix(&pe32_data[nt_headers_offset..])
160        .ok()?
161        .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
162
163    // Calculate the entry point relative to the start of the image.
164    // AddressOfEntryPoint is common for PE32 & PE32+
165    if signature as u16 == TE_IMAGE_HEADER_SIGNATURE {
166        let te = TeImageHeader::read_from_prefix(&pe32_data[nt_headers_offset..])
167            .ok()?
168            .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
169        Some(te.address_of_entry_point + size_of_val(&te) as u32 - te.stripped_size as u32)
170    } else if signature == IMAGE_NT_SIGNATURE {
171        let pe = ImageNtHeaders32::read_from_prefix(&pe32_data[nt_headers_offset..])
172            .ok()?
173            .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
174        Some(pe.optional_header.address_of_entry_point)
175    } else {
176        None
177    }
178}
179
180/// Get the SEC entry point offset from the firmware base.
181fn get_sec_entry_point_offset(image: &[u8]) -> Option<u64> {
182    // Skip to SEC volume start.
183    let mut image_offset = SEC_FIRMWARE_VOLUME_OFFSET;
184
185    // Expect a firmware volume header for SEC volume.
186    let fvh =
187        firmware_volume::FirmwareVolumeHeader::read_from_prefix(&image[image_offset as usize..])
188            .ok()?
189            .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
190    if fvh.signature != firmware_volume::FV_SIGNATURE {
191        return None;
192    }
193
194    // Skip past firmware volume header to beginning of firmware volume.
195    image_offset += fvh.header_length as u64;
196
197    // Find the first SEC CORE file type.
198    let mut sec_core_file_header = None;
199    let mut volume_offset = 0;
200    while volume_offset < fvh.fv_length {
201        let new_volume_offset = (volume_offset + 7) & !7;
202        if new_volume_offset > volume_offset {
203            image_offset += new_volume_offset - volume_offset;
204            volume_offset = new_volume_offset;
205        }
206        let fh = firmware_volume::FfsFileHeader::read_from_prefix(&image[image_offset as usize..])
207            .ok()?
208            .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
209        if fh.file_type == firmware_volume::FILETYPE_SECURITY_CORE {
210            sec_core_file_header = Some(fh);
211            break;
212        }
213
214        image_offset += expand_3byte_integer(fh.size);
215        volume_offset += expand_3byte_integer(fh.size);
216    }
217
218    // There should always be a Security Core file.
219    let sec_core_file_header = sec_core_file_header?;
220    let sec_core_file_size = expand_3byte_integer(sec_core_file_header.size);
221
222    // Move past the firmware file header.
223    image_offset += size_of::<firmware_volume::FfsFileHeader>() as u64;
224    volume_offset += size_of::<firmware_volume::FfsFileHeader>() as u64;
225
226    // Loop through the firmware file sections looking for PE section.
227    let mut file_offset = volume_offset;
228    while file_offset < sec_core_file_size {
229        //
230        // Section headers are 8 byte aligned with respect to the beginning of the file stream.
231        //
232        let new_file_offset = (file_offset + 3) & !3;
233        if new_file_offset > file_offset {
234            image_offset += new_file_offset - file_offset;
235            file_offset += new_file_offset - file_offset;
236        }
237
238        let sh =
239            firmware_volume::CommonSectionHeader::read_from_prefix(&image[image_offset as usize..])
240                .ok()?
241                .0; // TODO: zerocopy: use-rest-of-range, option-to-error (https://github.com/microsoft/openvmm/issues/759)
242        if sh.section_type == firmware_volume::SECTION_PE32 {
243            let pe_offset = pe_get_entry_point_offset(
244                &image[image_offset as usize + size_of::<firmware_volume::CommonSectionHeader>()..],
245            )?;
246            image_offset +=
247                size_of::<firmware_volume::CommonSectionHeader>() as u64 + pe_offset as u64;
248            break;
249        }
250        image_offset += expand_3byte_integer(sh.size);
251        file_offset += expand_3byte_integer(sh.size);
252    }
253
254    Some(image_offset)
255}
256
257/// Definitions shared by UEFI and the loader when loaded with parameters passed in IGVM format.
258mod igvm {
259    use zerocopy::FromBytes;
260
261    use zerocopy::Immutable;
262    use zerocopy::IntoBytes;
263    use zerocopy::KnownLayout;
264
265    /// The structure used to tell UEFI where the IGVM loaded parameters are.
266    #[repr(C)]
267    #[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
268    pub struct UEFI_IGVM_PARAMETER_INFO {
269        pub parameter_page_count: u32,
270        pub cpuid_pages_offset: u32,
271        pub vp_context_page_number: u64,
272        pub loader_block_offset: u32,
273        pub command_line_offset: u32,
274        pub command_line_page_count: u32,
275        pub memory_map_offset: u32,
276        pub memory_map_page_count: u32,
277        pub madt_offset: u32,
278        pub madt_page_count: u32,
279        pub srat_offset: u32,
280        pub srat_page_count: u32,
281        pub maximum_processor_count: u32,
282        pub uefi_memory_map_offset: u32,
283        pub uefi_memory_map_page_count: u32,
284    }
285
286    pub const UEFI_IGVM_LOADER_BLOCK_NUMBER_OF_PROCESSORS_FIELD_OFFSET: usize = 0;
287}
288
289#[derive(Debug, Error)]
290pub enum Error {
291    #[error("Firmware size invalid")]
292    InvalidImageSize,
293    #[error("Unable to find SEC volume entry point")]
294    NoSecEntryPoint,
295    #[error("Invalid shared gpa boundary")]
296    InvalidSharedGpaBoundary,
297    #[error("Invalid config type")]
298    InvalidConfigType(String),
299    #[error("x86_64 UEFI firmware requires the hypervisor to be enabled")]
300    HvRequired,
301    #[error("Importer error")]
302    Importer(#[source] anyhow::Error),
303    #[error("PageTableBuilder: {0}")]
304    PageTableBuilder(#[from] page_table::Error),
305}
306
307#[derive(Debug)]
308pub enum ConfigType {
309    ConfigBlob(config::Blob),
310    Igvm,
311    None,
312}
313
314#[derive(Debug)]
315pub struct LoadInfo {
316    /// The GPA the firmware was loaded at.
317    pub firmware_base: u64,
318    /// The size of the firmware image loaded, in bytes.
319    pub firmware_size: u64,
320    /// The total size used by the loader starting at the firmware_base,
321    /// including the firmware image and misc data, in bytes.
322    pub total_size: u64,
323}
324
325pub mod x86_64 {
326    use super::ConfigType;
327    use super::Error;
328    use super::LoadInfo;
329    use crate::common::DEFAULT_GDT_SIZE;
330    use crate::common::import_default_gdt;
331    use crate::cpuid::HV_PSP_CPUID_PAGE;
332    use crate::importer::BootPageAcceptance;
333    use crate::importer::IgvmParameterType;
334    use crate::importer::ImageLoad;
335    use crate::importer::IsolationType;
336    use crate::importer::StartupMemoryType;
337    use crate::importer::X86Register;
338    use crate::uefi::SEC_FIRMWARE_VOLUME_OFFSET;
339    use crate::uefi::get_sec_entry_point_offset;
340    use hvdef::HV_PAGE_SIZE;
341    use page_table::IdentityMapSize;
342    use page_table::x64::IdentityMapBuilder;
343    use page_table::x64::PAGE_TABLE_MAX_BYTES;
344    use page_table::x64::PAGE_TABLE_MAX_COUNT;
345    use page_table::x64::PageTable;
346    use page_table::x64::align_up_to_page_size;
347    use zerocopy::FromZeros;
348    use zerocopy::IntoBytes;
349
350    pub const IMAGE_SIZE: u64 = 0x00600000; // 6 MB. See MsvmPkg\MsvmPkgX64.fdf
351    const IMAGE_GPA_BASE: u64 = 0x100000; // 1MB
352    const PAGE_TABLE_GPA_BASE: u64 = IMAGE_GPA_BASE + IMAGE_SIZE; // 7MB - 0x700000
353    const PAGE_TABLE_SIZE: u64 = HV_PAGE_SIZE * 6;
354    const GDT_GPA_BASE: u64 = PAGE_TABLE_GPA_BASE + PAGE_TABLE_SIZE; // 0x707000
355    const MISC_PAGES_GPA_BASE: u64 = GDT_GPA_BASE + DEFAULT_GDT_SIZE; // 0x707000
356    const MISC_PAGES_SIZE: u64 = HV_PAGE_SIZE * 2;
357    pub const CONFIG_BLOB_GPA_BASE: u64 = MISC_PAGES_GPA_BASE + MISC_PAGES_SIZE; // 0x709000
358
359    /// Load a UEFI image with the provided config type.
360    ///
361    /// On x86_64 the firmware always runs under Hyper-V, so `hv_enabled` must
362    /// be `true`.
363    pub fn load(
364        importer: &mut dyn ImageLoad<X86Register>,
365        image: &[u8],
366        config: ConfigType,
367        hv_enabled: bool,
368    ) -> Result<LoadInfo, Error> {
369        if !hv_enabled {
370            return Err(Error::HvRequired);
371        }
372
373        if image.len() != IMAGE_SIZE as usize {
374            return Err(Error::InvalidImageSize);
375        }
376
377        let sec_entry_point = get_sec_entry_point_offset(image).ok_or(Error::NoSecEntryPoint)?;
378
379        let isolation = importer.isolation_config();
380
381        // Build the page tables. This depends on if we have a paravisor present or not:
382        //      - If this is an SNP VM with no paravisor, then build a set of page tables
383        //        to map the bottom 4GB of memory with shared visibility.
384        //      - Otherwise, build the standard UEFI page tables. Bottom 4GB of address space,
385        //        identity mapped with 2 MB pages.
386        let mut page_table_work_buffer: Vec<PageTable> =
387            vec![PageTable::new_zeroed(); PAGE_TABLE_MAX_COUNT];
388        let mut page_tables: Vec<u8> = vec![0; PAGE_TABLE_MAX_BYTES];
389        let page_table_builder = IdentityMapBuilder::new(
390            PAGE_TABLE_GPA_BASE,
391            IdentityMapSize::Size4Gb,
392            page_table_work_buffer.as_mut_slice(),
393            page_tables.as_mut_slice(),
394        )?;
395        let mut shared_vis_page_table_work_buffer: Vec<PageTable> = Vec::new();
396        let mut shared_vis_page_tables: Vec<u8> = Vec::new();
397        let (page_tables, shared_vis_page_tables) =
398            if isolation.isolation_type == IsolationType::Snp && !isolation.paravisor_present {
399                if let ConfigType::ConfigBlob(_) = config {
400                    return Err(Error::InvalidConfigType(
401                        "Enlightened UEFI must use IGVM parameters".into(),
402                    ));
403                }
404
405                let shared_vis_page_table_gpa = CONFIG_BLOB_GPA_BASE + HV_PAGE_SIZE;
406                let shared_gpa_boundary_bits = isolation
407                    .shared_gpa_boundary_bits
408                    .ok_or(Error::InvalidSharedGpaBoundary)?;
409                let shared_gpa_boundary = 1 << shared_gpa_boundary_bits;
410
411                shared_vis_page_table_work_buffer
412                    .resize(PAGE_TABLE_MAX_COUNT, PageTable::new_zeroed());
413                shared_vis_page_tables.resize(PAGE_TABLE_MAX_BYTES, 0);
414                let shared_vis_builder = IdentityMapBuilder::new(
415                    shared_vis_page_table_gpa,
416                    IdentityMapSize::Size4Gb,
417                    shared_vis_page_table_work_buffer.as_mut_slice(),
418                    shared_vis_page_tables.as_mut_slice(),
419                )?
420                .with_address_bias(shared_gpa_boundary);
421
422                // The extra page tables are placed after the first config blob
423                // page.  They will be accounted for when the IGVM parameters are
424                // built.
425                let shared_vis_page_tables = shared_vis_builder.build();
426
427                let page_tables = page_table_builder
428                    .with_pml4e_link((shared_vis_page_table_gpa, shared_gpa_boundary))
429                    .build();
430
431                (page_tables, Some(shared_vis_page_tables))
432            } else {
433                let page_tables = page_table_builder.build();
434                (page_tables, None)
435            };
436
437        // Size must match expected compiled constant
438        assert_eq!(page_tables.len(), PAGE_TABLE_SIZE as usize);
439
440        // Import image, page tables, GDT entries.
441        let image_page_count = image.len() as u64 / HV_PAGE_SIZE;
442        importer
443            .import_pages(
444                IMAGE_GPA_BASE / HV_PAGE_SIZE,
445                image_page_count,
446                "uefi-image",
447                BootPageAcceptance::Exclusive,
448                image,
449            )
450            .map_err(Error::Importer)?;
451
452        let mut total_page_count = IMAGE_GPA_BASE / HV_PAGE_SIZE + image_page_count;
453
454        importer
455            .import_pages(
456                PAGE_TABLE_GPA_BASE / HV_PAGE_SIZE,
457                PAGE_TABLE_SIZE / HV_PAGE_SIZE,
458                "uefi-page-tables",
459                BootPageAcceptance::Exclusive,
460                page_tables,
461            )
462            .map_err(Error::Importer)?;
463
464        total_page_count += PAGE_TABLE_SIZE / HV_PAGE_SIZE;
465
466        // The default GDT is used with a page count of one.
467        assert_eq!(DEFAULT_GDT_SIZE, HV_PAGE_SIZE);
468        import_default_gdt(importer, GDT_GPA_BASE / HV_PAGE_SIZE).map_err(Error::Importer)?;
469        total_page_count += DEFAULT_GDT_SIZE / HV_PAGE_SIZE;
470
471        // Reserve free pages. Currently these are only used by UEFI PEI for making hypercalls.
472        importer
473            .import_pages(
474                MISC_PAGES_GPA_BASE / HV_PAGE_SIZE,
475                MISC_PAGES_SIZE / HV_PAGE_SIZE,
476                "uefi-misc-pages",
477                BootPageAcceptance::Exclusive,
478                &[],
479            )
480            .map_err(Error::Importer)?;
481
482        total_page_count += MISC_PAGES_SIZE / HV_PAGE_SIZE;
483
484        // Import the config blobg, if set. Some callers may not load UEFI
485        // configuration at this time, such as if running with a paravisor.
486        match config {
487            ConfigType::Igvm => {
488                total_page_count += set_igvm_parameters(
489                    importer,
490                    CONFIG_BLOB_GPA_BASE / HV_PAGE_SIZE,
491                    match isolation.isolation_type {
492                        IsolationType::Snp => shared_vis_page_tables
493                            .as_ref()
494                            .expect("should be shared vis page tables"),
495                        _ => &[],
496                    },
497                )?
498            }
499            ConfigType::ConfigBlob(config) => {
500                let data = config.complete();
501                assert!(!data.is_empty());
502                let config_blob_page_count = (data.len() as u64).div_ceil(HV_PAGE_SIZE);
503                importer
504                    .import_pages(
505                        CONFIG_BLOB_GPA_BASE / HV_PAGE_SIZE,
506                        config_blob_page_count,
507                        "uefi-config-blob",
508                        BootPageAcceptance::Exclusive,
509                        &data,
510                    )
511                    .map_err(Error::Importer)?;
512
513                total_page_count += config_blob_page_count;
514            }
515            ConfigType::None => {}
516        }
517
518        // UEFI expects that the memory from GPA 0 up until the end of the config
519        // blob is present, at a minimum. Note that ImageGpaBase is not 0.
520        importer
521            .verify_startup_memory_available(0, total_page_count, StartupMemoryType::Ram)
522            .map_err(Error::Importer)?;
523
524        let mut import_reg = |register| {
525            importer
526                .import_vp_register(register)
527                .map_err(Error::Importer)
528        };
529
530        // Set CR0
531        import_reg(X86Register::Cr0(
532            x86defs::Cr0::new()
533                .with_pg(true)
534                .with_ne(true)
535                .with_mp(true)
536                .with_pe(true)
537                .into_bits(),
538        ))?;
539
540        // Set CR3 to point to page table which starts right after the image.
541        import_reg(X86Register::Cr3(PAGE_TABLE_GPA_BASE))?;
542
543        // Set CR4
544        import_reg(X86Register::Cr4(
545            x86defs::Cr4::new()
546                .with_pae(true)
547                .with_mce(true)
548                .with_fxsr(true)
549                .with_xmmexcpt(true)
550                .into_bits(),
551        ))?;
552
553        // Set EFER to LME, LMA, and NXE for 64 bit mode.
554        import_reg(X86Register::Efer(
555            x86defs::Efer::new()
556                .with_lma(true)
557                .with_lme(true)
558                .with_nxe(true)
559                .into_bits(),
560        ))?;
561
562        // Set PAT
563        import_reg(X86Register::Pat(x86defs::X86X_MSR_DEFAULT_PAT))?;
564
565        // Set register state to values SEC entry point expects.
566        // RBP - start of BFV (sec FV)
567        import_reg(X86Register::Rbp(
568            IMAGE_GPA_BASE + SEC_FIRMWARE_VOLUME_OFFSET,
569        ))?;
570
571        // Set RIP to SEC entry point.
572        import_reg(X86Register::Rip(IMAGE_GPA_BASE + sec_entry_point))?;
573
574        // Set R8-R11 to the hypervisor isolation CPUID leaf values.
575        let isolation_cpuid = isolation.get_cpuid();
576
577        import_reg(X86Register::R8(isolation_cpuid.eax as u64))?;
578        import_reg(X86Register::R9(isolation_cpuid.ebx as u64))?;
579        import_reg(X86Register::R10(isolation_cpuid.ecx as u64))?;
580        import_reg(X86Register::R11(isolation_cpuid.edx as u64))?;
581
582        // Enable MTRRs, default MTRR is uncached, and set lowest 640KB as WB
583        import_reg(X86Register::MtrrDefType(0xc00))?;
584        import_reg(X86Register::MtrrFix64k00000(0x0606060606060606))?;
585        import_reg(X86Register::MtrrFix16k80000(0x0606060606060606))?;
586
587        Ok(LoadInfo {
588            firmware_base: IMAGE_GPA_BASE,
589            firmware_size: image.len() as u64,
590            total_size: total_page_count * HV_PAGE_SIZE,
591        })
592    }
593
594    /// A simple page allocator that supports allocating pages counting up from a base page.
595    struct PageAllocator {
596        base: u32,
597        total_count: u32,
598    }
599
600    impl PageAllocator {
601        /// Create a `PageAllocator` starting at the given page `base`.
602        fn new(base: u32) -> PageAllocator {
603            PageAllocator {
604                base,
605                total_count: 0,
606            }
607        }
608
609        /// Allocate `count` number of pages. Returns the base page number for the allocation.
610        fn allocate(&mut self, count: u32) -> u32 {
611            let allocation = self.base + self.total_count;
612            self.total_count += count;
613
614            allocation
615        }
616
617        /// Get the total number of pages allocated.
618        fn total(&self) -> u32 {
619            self.total_count
620        }
621    }
622
623    /// Construct the UEFI parameter information in IGVM format. `config_area_base_page` specifies the GPA page number
624    /// at the start of the config region. The number of pages used in the config region is returned.
625    fn set_igvm_parameters(
626        importer: &mut dyn ImageLoad<X86Register>,
627        config_area_base_page: u64,
628        shared_visibility_page_tables: &[u8],
629    ) -> Result<u64, Error> {
630        let mut parameter_info = super::igvm::UEFI_IGVM_PARAMETER_INFO::new_zeroed();
631
632        // IGVM UEFI_IGVM_PARAMETER_INFO page offsets are relative to 1, as the first page is taken by the
633        // UEFI_IGVM_PARAMETER_INFO structure. Allocate a page for the UEFI_IGVM_PARAMETER_INFO structure.
634        let mut allocator = PageAllocator::new(0);
635        allocator.allocate(1);
636
637        // Set up the parameter info structure with offsets to each of the
638        // additional parameters. Each table allocates a constant number of
639        // pages.
640        let table_page_count = 20;
641
642        // The first structure is the loader block, which happens after the parameter info structure and shared
643        // visibility page tables.
644        let page_table_page_count =
645            align_up_to_page_size(shared_visibility_page_tables.len() as u64) / HV_PAGE_SIZE;
646        let page_table_offset = allocator.allocate(page_table_page_count as u32);
647        parameter_info.loader_block_offset = allocator.allocate(1);
648
649        let command_line_page_count = 1;
650        parameter_info.command_line_offset = allocator.allocate(command_line_page_count);
651        parameter_info.command_line_page_count = command_line_page_count;
652
653        parameter_info.memory_map_offset = allocator.allocate(table_page_count);
654        parameter_info.memory_map_page_count = table_page_count;
655
656        parameter_info.madt_offset = allocator.allocate(table_page_count);
657        parameter_info.madt_page_count = table_page_count;
658
659        parameter_info.srat_offset = allocator.allocate(table_page_count);
660        parameter_info.srat_page_count = table_page_count;
661
662        // Reserve additional pre-accepted pages for UEFI to use to reconstruct
663        // portions of the config blob.
664        parameter_info.uefi_memory_map_offset = allocator.allocate(table_page_count);
665        parameter_info.uefi_memory_map_page_count = table_page_count;
666
667        // If this is an SNP image with no paravisor, then reserve additional pages as required.
668        let isolation = importer.isolation_config();
669        if isolation.isolation_type == IsolationType::Snp {
670            // NOTE: Currently UEFI expects this parameter load style to have no paravisor. Disallow that here.
671            if isolation.paravisor_present {
672                return Err(Error::InvalidConfigType(
673                    "IGVM ConfigType specified but paravisor is present.".into(),
674                ));
675            }
676
677            // Supply the address of the parameter info block so it can be used
678            // before PEI parses the config information.
679            importer
680                .import_vp_register(X86Register::R12(config_area_base_page * HV_PAGE_SIZE))
681                .map_err(Error::Importer)?;
682
683            // Reserve two pages to hold CPUID information. The first CPUID page
684            // contains initialized data to query CPUID leaves. The second page
685            // contains no data, as it will be populated by the host when the
686            // image is loaded.
687            parameter_info.cpuid_pages_offset = allocator.allocate(2);
688
689            let cpuid_page = create_snp_cpuid_page();
690
691            importer
692                .import_pages(
693                    config_area_base_page + parameter_info.cpuid_pages_offset as u64,
694                    1,
695                    "uefi-cpuid-page",
696                    BootPageAcceptance::CpuidPage,
697                    cpuid_page.as_bytes(),
698                )
699                .map_err(Error::Importer)?;
700
701            importer
702                .import_pages(
703                    config_area_base_page + parameter_info.cpuid_pages_offset as u64 + 1,
704                    1,
705                    "uefi-cpuid-extended-page",
706                    BootPageAcceptance::CpuidExtendedStatePage,
707                    &[],
708                )
709                .map_err(Error::Importer)?;
710
711            // Reserve a page to use to hold the VMSA.  This must be reported to
712            // UEFI so that the page can be marked as a permanent firmware
713            // allocation.
714            //
715            // Note that this page must not be counted within the size of the
716            // config block, since it has different memory protection properties.
717            // The first page following the config block is chosen for the
718            // allocation.
719            let vp_context_page_number = config_area_base_page + allocator.total() as u64;
720            importer
721                .set_vp_context_page(vp_context_page_number)
722                .map_err(Error::Importer)?;
723
724            parameter_info.vp_context_page_number = vp_context_page_number;
725        } else {
726            // If this is not an SNP image, then the VP context page does not
727            // need to be reported to UEFI. Put in the TDX reset page value for
728            // consistency with old code; this probably is unnecessary (or the
729            // UEFI firmware should just be improved to not need this).
730            parameter_info.vp_context_page_number = 0xfffff;
731        }
732
733        // Encode the total amount of pages used by all parameters.
734        parameter_info.parameter_page_count = allocator.total();
735
736        importer
737            .import_pages(
738                config_area_base_page,
739                1,
740                "uefi-config-base-page",
741                BootPageAcceptance::Exclusive,
742                parameter_info.as_bytes(),
743            )
744            .map_err(Error::Importer)?;
745
746        importer
747            .import_pages(
748                config_area_base_page + parameter_info.uefi_memory_map_offset as u64,
749                parameter_info.uefi_memory_map_page_count as u64,
750                "uefi-memory-map-scratch",
751                BootPageAcceptance::ExclusiveUnmeasured,
752                &[],
753            )
754            .map_err(Error::Importer)?;
755
756        let loader_block = importer
757            .create_parameter_area(
758                config_area_base_page + parameter_info.loader_block_offset as u64,
759                1,
760                "uefi-loader-block",
761            )
762            .map_err(Error::Importer)?;
763        importer
764            .import_parameter(
765                loader_block,
766                super::igvm::UEFI_IGVM_LOADER_BLOCK_NUMBER_OF_PROCESSORS_FIELD_OFFSET as u32,
767                IgvmParameterType::VpCount,
768            )
769            .map_err(Error::Importer)?;
770
771        let command_line = importer
772            .create_parameter_area(
773                config_area_base_page + parameter_info.command_line_offset as u64,
774                parameter_info.command_line_page_count,
775                "uefi-command-line",
776            )
777            .map_err(Error::Importer)?;
778        importer
779            .import_parameter(command_line, 0, IgvmParameterType::CommandLine)
780            .map_err(Error::Importer)?;
781
782        let memory_map = importer
783            .create_parameter_area(
784                config_area_base_page + parameter_info.memory_map_offset as u64,
785                parameter_info.memory_map_page_count,
786                "uefi-memory-map",
787            )
788            .map_err(Error::Importer)?;
789        importer
790            .import_parameter(memory_map, 0, IgvmParameterType::MemoryMap)
791            .map_err(Error::Importer)?;
792
793        let madt = importer
794            .create_parameter_area(
795                config_area_base_page + parameter_info.madt_offset as u64,
796                parameter_info.madt_page_count,
797                "uefi-madt",
798            )
799            .map_err(Error::Importer)?;
800        importer
801            .import_parameter(madt, 0, IgvmParameterType::Madt)
802            .map_err(Error::Importer)?;
803
804        let srat = importer
805            .create_parameter_area(
806                config_area_base_page + parameter_info.srat_offset as u64,
807                parameter_info.srat_page_count,
808                "uefi-srat",
809            )
810            .map_err(Error::Importer)?;
811        importer
812            .import_parameter(srat, 0, IgvmParameterType::Srat)
813            .map_err(Error::Importer)?;
814
815        if page_table_page_count != 0 {
816            importer
817                .import_pages(
818                    config_area_base_page + page_table_offset as u64,
819                    page_table_page_count,
820                    "uefi-igvm-page-tables",
821                    BootPageAcceptance::Exclusive,
822                    shared_visibility_page_tables,
823                )
824                .map_err(Error::Importer)?;
825        }
826
827        Ok(allocator.total() as u64)
828    }
829
830    /// Create a hypervisor SNP CPUID page with the default values.
831    fn create_snp_cpuid_page() -> HV_PSP_CPUID_PAGE {
832        let mut cpuid_page = HV_PSP_CPUID_PAGE::new_zeroed();
833
834        for (i, required_leaf) in crate::cpuid::SNP_REQUIRED_CPUID_LEAF_LIST_UEFI
835            .iter()
836            .enumerate()
837        {
838            cpuid_page.cpuid_leaf_info[i].eax_in = required_leaf.eax;
839            cpuid_page.cpuid_leaf_info[i].ecx_in = required_leaf.ecx;
840            cpuid_page.count += 1;
841        }
842
843        cpuid_page
844    }
845}
846
847pub mod aarch64 {
848    use super::ConfigType;
849    use super::Error;
850    use super::LoadInfo;
851    use crate::importer::Aarch64Register;
852    use crate::importer::BootPageAcceptance;
853    use crate::importer::ImageLoad;
854    use aarch64defs::Cpsr64;
855    use aarch64defs::Pte;
856    use aarch64defs::SctlrEl1;
857    use aarch64defs::TranslationControlEl1;
858    use aarch64defs::TranslationGranule0;
859    use hvdef::HV_PAGE_SIZE;
860
861    use zerocopy::IntoBytes;
862
863    pub const IMAGE_SIZE: u64 = 0x800000;
864    pub const CONFIG_BLOB_GPA_BASE: u64 = 0x824000;
865
866    /// Load a UEFI image with the provided config type.
867    ///
868    /// `hv_enabled` selects the SEC platform type passed to the firmware in
869    /// `x2`: Hyper-V when enlightenments are exposed, or generic when they are
870    /// not.
871    pub fn load(
872        importer: &mut dyn ImageLoad<Aarch64Register>,
873        image: &[u8],
874        config: ConfigType,
875        hv_enabled: bool,
876    ) -> Result<LoadInfo, Error> {
877        if image.len() != IMAGE_SIZE as usize {
878            return Err(Error::InvalidImageSize);
879        }
880
881        const BYTES_2MB: u64 = 0x200000;
882
883        let image_size = (image.len() as u64 + BYTES_2MB - 1) & !(BYTES_2MB - 1);
884        importer
885            .import_pages(
886                0,
887                image_size / HV_PAGE_SIZE,
888                "uefi-image",
889                BootPageAcceptance::Exclusive,
890                image,
891            )
892            .map_err(Error::Importer)?;
893
894        // The stack.
895        let stack_offset = image_size;
896        let stack_size = 32 * HV_PAGE_SIZE;
897        let stack_end = stack_offset + stack_size;
898        importer
899            .import_pages(
900                stack_offset / HV_PAGE_SIZE,
901                stack_size / HV_PAGE_SIZE,
902                "uefi-stack",
903                BootPageAcceptance::Exclusive,
904                &[],
905            )
906            .map_err(Error::Importer)?;
907
908        // The page tables.
909        let page_table_offset = stack_end;
910        let page_tables = page_tables(page_table_offset, 1 << 30 /* TODO */);
911        importer
912            .import_pages(
913                page_table_offset / HV_PAGE_SIZE,
914                page_tables.as_bytes().len() as u64 / HV_PAGE_SIZE,
915                "uefi-page-tables",
916                BootPageAcceptance::Exclusive,
917                page_tables.as_bytes(),
918            )
919            .map_err(Error::Importer)?;
920
921        let blob_offset = CONFIG_BLOB_GPA_BASE;
922
923        // The config blob.
924        let blob_size = match config {
925            ConfigType::ConfigBlob(blob) => {
926                let blob = blob.complete();
927                let blob_size = (blob.len() as u64 + HV_PAGE_SIZE - 1) & !(HV_PAGE_SIZE - 1);
928                importer
929                    .import_pages(
930                        blob_offset / HV_PAGE_SIZE,
931                        blob_size / HV_PAGE_SIZE,
932                        "uefi-config-blob",
933                        BootPageAcceptance::Exclusive,
934                        &blob,
935                    )
936                    .map_err(Error::Importer)?;
937
938                blob_size
939            }
940            ConfigType::None => 0,
941            ConfigType::Igvm => {
942                return Err(Error::InvalidConfigType("igvm not supported".to_owned()));
943            }
944        };
945
946        let total_size = blob_offset + blob_size;
947
948        let mut import_reg = |reg| importer.import_vp_register(reg).map_err(Error::Importer);
949
950        import_reg(Aarch64Register::Cpsr(
951            Cpsr64::new().with_sp(true).with_el(1).into(),
952        ))?;
953        import_reg(Aarch64Register::X0(0x1000))?;
954        import_reg(Aarch64Register::Pc(0x1000))?;
955        import_reg(Aarch64Register::X1(stack_end))?;
956        let platform_type = if hv_enabled {
957            loader_defs::uefi::SecPlatformType::HYPERV
958        } else {
959            loader_defs::uefi::SecPlatformType::GENERIC
960        };
961        import_reg(Aarch64Register::X2(platform_type.0))?;
962
963        import_reg(Aarch64Register::Ttbr0El1(page_table_offset))?;
964
965        // Memory attribute indirection register.
966        const ARM64_MAIR_CACHE_WBWA: u64 = 0xff;
967        const ARM64_MAIR_CACHE_NC: u64 = 0x00;
968        const ARM64_MAIR_CACHE_WTNA: u64 = 0xaa;
969        const ARM64_MAIR_CACHE_WC: u64 = 0x44;
970
971        import_reg(Aarch64Register::MairEl1(
972            ARM64_MAIR_CACHE_WBWA
973                | (ARM64_MAIR_CACHE_NC << 8)
974                | (ARM64_MAIR_CACHE_WTNA << 16)
975                | (ARM64_MAIR_CACHE_WC << 24)
976                | (ARM64_MAIR_CACHE_WBWA << 32)
977                | (ARM64_MAIR_CACHE_NC << 40)
978                | (ARM64_MAIR_CACHE_WTNA << 48)
979                | (ARM64_MAIR_CACHE_WC << 56),
980        ))?;
981
982        // System control register.
983        import_reg(Aarch64Register::SctlrEl1(
984            SctlrEl1::new()
985                .with_m(true)
986                .with_c(true)
987                .with_i(true)
988                // Reserved flags, must be set
989                .with_eos(true)
990                .with_tscxt(true)
991                .with_eis(true)
992                .with_span(true)
993                .with_n_tlsmd(true)
994                .with_lsmaoe(true)
995                .into(),
996        ))?;
997
998        // Translation control register.
999        import_reg(Aarch64Register::TcrEl1(
1000            TranslationControlEl1::new()
1001                .with_t0sz(16)
1002                .with_irgn0(1)
1003                .with_orgn0(1)
1004                .with_sh0(3)
1005                .with_tg0(TranslationGranule0::TG_4KB)
1006                .with_t1sz(16)
1007                .with_epd1(1)
1008                .into(),
1009        ))?;
1010
1011        Ok(LoadInfo {
1012            firmware_base: 0,
1013            firmware_size: image.len() as u64,
1014            total_size,
1015        })
1016    }
1017
1018    const MAIR_INDEX_WB: u64 = 0;
1019    const MAIR_INDEX_UC: u64 = 1;
1020    const SHAREABILITY_INNER: u64 = 3;
1021
1022    fn large_leaf_entry(normal: bool, address: u64) -> u64 {
1023        Pte::new()
1024            .with_valid(true)
1025            .with_access_flag(true)
1026            .with_shareability(SHAREABILITY_INNER)
1027            .with_user_no_execute(true)
1028            .with_attribute_index(if normal { MAIR_INDEX_WB } else { MAIR_INDEX_UC })
1029            .with_pfn(address >> 12)
1030            .into()
1031    }
1032
1033    fn non_leaf_entry(address: u64) -> u64 {
1034        Pte::new()
1035            .with_valid(true)
1036            .with_not_large_page(true)
1037            .with_pfn(address >> 12)
1038            .into()
1039    }
1040
1041    fn leaf_entry(normal: bool, address: u64) -> u64 {
1042        Pte::from(large_leaf_entry(normal, address))
1043            .with_not_large_page(true)
1044            .into()
1045    }
1046
1047    fn table_index(va: u64, level: u32) -> usize {
1048        let index = va >> (9 * (3 - level) + 12);
1049        let index = index & ((1 << 9) - 1);
1050        index as usize
1051    }
1052
1053    fn page_tables(address: u64, end_of_ram: u64) -> Vec<[u64; 512]> {
1054        const PT_SIZE: u64 = 4096;
1055        const VA_4GB: u64 = 1 << 32;
1056        const VA_1GB: u64 = 1 << 30;
1057        const VA_2MB: u64 = 2 << 20;
1058        const VA_4KB: u64 = 4 << 10;
1059
1060        let mut buffer = vec![[0u64; PT_SIZE as usize / 8]; 4];
1061        let [level0, level1, level2, level3] = buffer.as_mut_slice() else {
1062            unreachable!()
1063        };
1064
1065        // Allocate temporary buffer to hold page tables. We need 4 page tables:
1066        // - PML4 table (level 0 table in ARM terminology).
1067        // - PDP table (level 1 table).
1068        // - PD table (level 2 table) to map the 1 GB region that contains the
1069        //   split between normal and device memory.
1070        // - PT table (level 3 table) to map the 2 MB region that contains the
1071        //   split between normal and device memory.
1072
1073        // Link level 1 translation table.
1074        level0[0] = non_leaf_entry(address + PT_SIZE);
1075
1076        // Create an identity map for the address space from 0 to 4 GB.
1077        // The range [0, 4GB - MMIO Space Size) is mapped as normal memory, the
1078        // range [4 GB - MMIO Space Size, 4 GB) is mapped as device memory.
1079
1080        let mut normal = true;
1081        let mut va = 0;
1082        let mut end_va = end_of_ram;
1083        while va < VA_4GB {
1084            //
1085            // Switch to device memory if we are are within the MMIO space.
1086            //
1087            if normal && va == end_va {
1088                normal = false;
1089                end_va = VA_4GB;
1090                continue;
1091            }
1092
1093            // Try to use a 1 GB page (level 1 block entry) if possible.
1094            let level1_index = table_index(va, 1);
1095            if !Pte::from(level1[level1_index]).valid()
1096                && ((va & (VA_1GB - 1)) == 0)
1097                && (end_va - va >= VA_1GB)
1098            {
1099                level1[level1_index] = large_leaf_entry(normal, va);
1100                va += VA_1GB;
1101                continue;
1102            }
1103
1104            //
1105            // Allocate and link level 2 translation table (PD) if it does not yet
1106            // exist.
1107            //
1108            if !Pte::from(level1[level1_index]).valid() {
1109                level1[level1_index] = non_leaf_entry(address + PT_SIZE * 2);
1110            }
1111
1112            //
1113            // Try to use a 2 MB page (level 2 block entry) if possible.
1114            //
1115            let level2_index = table_index(va, 2);
1116            if !Pte::from(level2[level2_index]).valid()
1117                && ((va & (VA_2MB - 1)) == 0)
1118                && (end_va - va >= VA_2MB)
1119            {
1120                level2[level2_index] = large_leaf_entry(normal, va);
1121                va += VA_2MB;
1122                continue;
1123            }
1124
1125            //
1126            // Allocate and link level 1 translation table (PT) if it does not yet
1127            // exist.
1128            //
1129            if !Pte::from(level2[level2_index]).valid() {
1130                level2[level2_index] = non_leaf_entry(address + PT_SIZE * 3);
1131            }
1132
1133            let level3_index = table_index(va, 3);
1134            level3[level3_index] = leaf_entry(normal, va);
1135            va += VA_4KB;
1136        }
1137
1138        buffer
1139    }
1140}