Skip to main content

loader/uefi/
config.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! UEFI specific configuration format and construction.
5
6use bitfield_struct::bitfield;
7use core::mem::size_of;
8use guid::Guid;
9use zerocopy::FromBytes;
10use zerocopy::Immutable;
11use zerocopy::IntoBytes;
12use zerocopy::KnownLayout;
13
14fn align_8(x: usize) -> usize {
15    (x + 7) & !7
16}
17
18/// A configuration blob builder for passing config information to UEFI.
19#[derive(Debug)]
20pub struct Blob {
21    data: Vec<u8>,
22    count: u32,
23}
24
25impl Blob {
26    /// Creates a new configuration blob with a placeholder StructureCount structure
27    pub fn new() -> Self {
28        let mut blob = Self {
29            data: Vec::new(),
30            count: 0,
31        };
32        blob.add(&StructureCount {
33            total_structure_count: 0,
34            total_config_blob_size: 0,
35        });
36        blob
37    }
38
39    /// Aligns and appends a sized structure and its appropriate header to the configuration blob.
40    pub fn add<T: BlobStructure>(&mut self, data: &T) -> &mut Self {
41        self.add_raw(T::STRUCTURE_TYPE, data.as_bytes())
42    }
43
44    /// Aligns and appends a null terminated C string and its appropriate header
45    /// to the configuration blob.
46    ///
47    /// If the data is zero-sized, the configuration blob is not updated.
48    ///
49    /// If the data does not include a null terminator (e.g: because the data
50    /// was pulled from a Rust string), a null terminator is appended to the end
51    /// of the data.
52    pub fn add_cstring(&mut self, structure_type: BlobStructureType, data: &[u8]) -> &mut Self {
53        if !data.is_empty() {
54            self.add_raw_inner(structure_type, data, !data.ends_with(&[0]))
55        } else {
56            self
57        }
58    }
59
60    /// Aligns and appends the raw byte data of a potentially dynamically sized structure
61    /// and its appropriate header to the configuration blob.
62    pub fn add_raw(&mut self, structure_type: BlobStructureType, data: &[u8]) -> &mut Self {
63        self.add_raw_inner(structure_type, data, false)
64    }
65
66    fn add_raw_inner(
67        &mut self,
68        structure_type: BlobStructureType,
69        data: &[u8],
70        add_null_term: bool,
71    ) -> &mut Self {
72        // Align up to 8 bytes.
73        let aligned_data_len = align_8(data.len() + add_null_term as usize);
74        self.data.extend_from_slice(
75            Header {
76                structure_type: structure_type as u32,
77                length: (size_of::<Header>() + aligned_data_len) as u32,
78            }
79            .as_bytes(),
80        );
81        self.data.extend_from_slice(data);
82        if add_null_term {
83            self.data.push(0);
84        }
85        // Pad with zeroes.
86        self.data
87            .extend_from_slice(&[0; 7][..aligned_data_len - (data.len() + add_null_term as usize)]);
88        self.count += 1;
89        self
90    }
91
92    /// Returns a serialized binary format of the whole configuration blob. Done by updating the structure count and
93    /// returning the complete binary config blob.
94    pub fn complete(mut self) -> Vec<u8> {
95        let total_config_blob_size = self.data.len() as u32;
96        self.data[size_of::<Header>()..size_of::<Header>() + size_of::<StructureCount>()]
97            .copy_from_slice(
98                StructureCount {
99                    total_structure_count: self.count,
100                    total_config_blob_size,
101                }
102                .as_bytes(),
103            );
104        self.data
105    }
106}
107
108impl Default for Blob {
109    fn default() -> Self {
110        Self::new()
111    }
112}
113
114pub trait BlobStructure: IntoBytes + FromBytes + Immutable + KnownLayout {
115    const STRUCTURE_TYPE: BlobStructureType;
116}
117
118macro_rules! blobtypes {
119    {
120        $($name:ident,)*
121    } => {
122        $(
123            impl BlobStructure for $name {
124                const STRUCTURE_TYPE: BlobStructureType = BlobStructureType::$name;
125            }
126        )*
127    }
128}
129
130blobtypes! {
131    StructureCount,
132    BiosInformation,
133    Entropy,
134    BiosGuid,
135    Smbios31ProcessorInformation,
136    Flags,
137    ProcessorInformation,
138    MmioRanges,
139    NvdimmCount,
140    VpciInstanceFilter,
141    Gic,
142}
143
144/// Config structure types.
145#[repr(u32)]
146pub enum BlobStructureType {
147    StructureCount = 0x00,
148    BiosInformation = 0x01,
149    #[deprecated(note = "use AcpiTable")]
150    Srat = 0x02,
151    MemoryMap = 0x03,
152    Entropy = 0x04,
153    BiosGuid = 0x05,
154    SmbiosSystemSerialNumber = 0x06,
155    SmbiosBaseSerialNumber = 0x07,
156    SmbiosChassisSerialNumber = 0x08,
157    SmbiosChassisAssetTag = 0x09,
158    SmbiosBiosLockString = 0x0A,
159    Smbios31ProcessorInformation = 0x0B,
160    SmbiosSocketDesignation = 0x0C,
161    SmbiosProcessorManufacturer = 0x0D,
162    SmbiosProcessorVersion = 0x0E,
163    SmbiosProcessorSerialNumber = 0x0F,
164    SmbiosProcessorAssetTag = 0x10,
165    SmbiosProcessorPartNumber = 0x11,
166    Flags = 0x12,
167    ProcessorInformation = 0x13,
168    MmioRanges = 0x14,
169    Aarch64Mpidr = 0x15,
170    AcpiTable = 0x16,
171    NvdimmCount = 0x17,
172    #[deprecated(note = "use AcpiTable")]
173    Madt = 0x18,
174    VpciInstanceFilter = 0x19,
175    SmbiosSystemManufacturer = 0x1A,
176    SmbiosSystemProductName = 0x1B,
177    SmbiosSystemVersion = 0x1C,
178    SmbiosSystemSkuNumber = 0x1D,
179    SmbiosSystemFamily = 0x1E,
180    SmbiosMemoryDeviceSerialNumber = 0x1F,
181    #[deprecated(note = "use AcpiTable")]
182    Slit = 0x20,
183    #[deprecated(note = "use AcpiTable")]
184    Aspt = 0x21,
185    #[deprecated(note = "use AcpiTable")]
186    Pptt = 0x22,
187    Gic = 0x23,
188    #[deprecated(note = "use AcpiTable")]
189    Mcfg = 0x24,
190    #[deprecated(note = "use AcpiTable")]
191    Ssdt = 0x25,
192    #[deprecated(note = "use AcpiTable")]
193    Hmat = 0x26,
194    #[deprecated(note = "use AcpiTable")]
195    Iort = 0x27,
196    PcieBarApertures = 0x28,
197}
198
199//
200// Config Structures.
201//
202// NOTE: All config structures _must_ be aligned to 8 bytes, as AARCH64 does not
203// support unaligned accesses. For variable length structures, they must be
204// padded appropriately to 8 byte boundaries.
205//
206
207//
208// Common config header.
209//
210// NOTE: Length is the length of the overall structure in bytes, including the
211// header.
212//
213#[repr(C)]
214#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
215pub struct Header {
216    pub structure_type: u32,
217    pub length: u32,
218}
219
220//
221// NOTE: TotalStructureCount is the count of all structures in the config blob,
222// including this structure.
223//
224// NOTE: TotalConfigBlobSize is in bytes.
225//
226#[repr(C)]
227#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
228pub struct StructureCount {
229    pub total_structure_count: u32,
230    pub total_config_blob_size: u32,
231}
232
233#[repr(C)]
234#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
235pub struct BiosInformation {
236    pub bios_size_pages: u32,
237    // struct {
238    //     UINT32 LegacyMemoryMap : 1;
239    //     UINT32 Reserved : 31;
240    // } Flags;
241    pub flags: u32,
242}
243
244//
245// Memory map range flags beginning with VDev version 5.
246//
247// VM_MEMORY_RANGE_FLAG_PLATFORM_RESERVED is mapped to EfiReservedMemoryType.
248// This means the memory range is reserved and not regular RAM.
249//
250// VM_MEMORY_RANGE_FLAG_PERSISTENT is mapped to EfiPersistentMemory.
251// This means the memory range is byte-addressable and non-volatile, like PMem.
252//
253// VM_MEMORY_RANGE_FLAG_SPECIAL_PURPOSE is mapped to EfiConventionalMemory.
254// This flag instructs the guest to mark the memory with the EFI_MEMORY_SP bit.
255//
256pub const VM_MEMORY_RANGE_FLAG_PLATFORM_RESERVED: u32 = 0x1;
257pub const VM_MEMORY_RANGE_FLAG_PERSISTENT: u32 = 0x2;
258pub const VM_MEMORY_RANGE_FLAG_SPECIFIC_PURPOSE: u32 = 0x4;
259
260#[repr(C)]
261#[derive(Debug, IntoBytes, Immutable, KnownLayout, FromBytes)]
262pub struct MemoryRangeV5 {
263    pub base_address: u64,
264    pub length: u64,
265    pub flags: u32,
266    pub reserved: u32,
267}
268
269#[repr(C)]
270#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
271pub struct Entropy(pub [u8; 64]);
272
273impl Default for Entropy {
274    fn default() -> Self {
275        Entropy([0; 64])
276    }
277}
278
279#[repr(C)]
280#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
281pub struct BiosGuid(pub Guid);
282
283#[repr(C)]
284#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
285pub struct Smbios31ProcessorInformation {
286    pub processor_id: u64,
287    pub external_clock: u16,
288    pub max_speed: u16,
289    pub current_speed: u16,
290    pub processor_characteristics: u16,
291    pub processor_family2: u16,
292    pub processor_type: u8,
293    pub voltage: u8,
294    pub status: u8,
295    pub processor_upgrade: u8,
296    pub reserved: u16,
297}
298
299#[bitfield(u64, debug = false)]
300#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
301pub struct Flags {
302    pub serial_controllers_enabled: bool,
303    pub pause_after_boot_failure: bool,
304    pub pxe_ip_v6: bool,
305    pub debugger_enabled: bool,
306    pub load_oemp_table: bool,
307    pub tpm_enabled: bool,
308    pub hibernate_enabled: bool,
309
310    #[bits(2)]
311    pub console: ConsolePort,
312
313    pub memory_attributes_table_enabled: bool,
314    pub virtual_battery_enabled: bool,
315    pub sgx_memory_enabled: bool,
316    pub is_vmbfs_boot: bool,
317    pub measure_additional_pcrs: bool,
318    pub disable_frontpage: bool,
319    pub default_boot_always_attempt: bool,
320    pub low_power_s0_idle_enabled: bool,
321    pub vpci_boot_enabled: bool,
322    pub proc_idle_enabled: bool,
323    pub disable_sha384_pcr: bool,
324    pub media_present_enabled_by_default: bool,
325
326    #[bits(2)]
327    pub memory_protection: MemoryProtection,
328
329    pub enable_imc_when_isolated: bool,
330    pub watchdog_enabled: bool,
331    pub tpm_locality_regs_enabled: bool,
332    pub dhcp6_link_layer_address: bool,
333    pub cxl_memory_enabled: bool,
334    pub mtrrs_initialized_at_load: bool,
335    pub disable_sha1_pcr: bool,
336    pub vmbus_disabled: bool,
337    pub pci_resources_pre_assigned: bool,
338    pub force_dma_bounce_enabled: bool,
339    pub ipmi_enabled: bool,
340    pub tpm_large_buffers_enabled: bool,
341
342    #[bits(29)]
343    _reserved: u64,
344}
345
346#[derive(Clone, Copy)]
347pub enum ConsolePort {
348    Default = 0b00,
349    Com1 = 0b01,
350    Com2 = 0b10,
351    None = 0b11,
352}
353
354impl ConsolePort {
355    const fn from_bits(bits: u64) -> Self {
356        match bits {
357            0b00 => Self::Default,
358            0b01 => Self::Com1,
359            0b10 => Self::Com2,
360            0b11 => Self::None,
361            _ => unreachable!(),
362        }
363    }
364
365    const fn into_bits(self) -> u64 {
366        self as u64
367    }
368}
369
370pub enum MemoryProtection {
371    Disabled = 0b00,
372    Default = 0b01,
373    Strict = 0b10,
374    Relaxed = 0b11,
375}
376
377impl MemoryProtection {
378    const fn from_bits(bits: u64) -> Self {
379        match bits {
380            0b00 => Self::Disabled,
381            0b01 => Self::Default,
382            0b10 => Self::Strict,
383            0b11 => Self::Relaxed,
384            _ => unreachable!(),
385        }
386    }
387
388    const fn into_bits(self) -> u64 {
389        self as u64
390    }
391}
392
393#[repr(C)]
394#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
395pub struct ProcessorInformation {
396    pub max_processor_count: u32,
397    pub processor_count: u32,
398    pub processors_per_virtual_socket: u32,
399    pub threads_per_processor: u32,
400}
401
402#[repr(C)]
403#[derive(IntoBytes, Immutable, KnownLayout, FromBytes, Copy, Clone)]
404pub struct Mmio {
405    pub mmio_page_number_start: u64,
406    pub mmio_size_in_pages: u64,
407}
408
409#[repr(C)]
410#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
411pub struct MmioRanges(pub [Mmio; 2]);
412
413#[repr(C)]
414#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
415pub struct NvdimmCount {
416    pub count: u16,
417    pub padding: [u16; 3],
418}
419
420#[repr(C)]
421#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
422pub struct VpciInstanceFilter {
423    pub instance_guid: Guid,
424}
425
426#[repr(C)]
427#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
428pub struct Gic {
429    pub gic_distributor_base: u64,
430    pub gic_redistributors_base: u64,
431}
432
433// Describes the BAR Aperture for each PCIe Root Complex / Host bridge. There
434// should be one entry per host bridge that UEFI should enumerate. The MCFG
435// table may contain additional segments that are not described to UEFI via
436// these structures, which UEFI will ignore.
437//
438// This structure is used to pass this information to UEFI instead of having
439// UEFI parse the SSDT.
440#[repr(C)]
441#[derive(IntoBytes, Immutable, KnownLayout, FromBytes)]
442pub struct PcieBarApertureEntry {
443    pub segment: u16,
444    pub start_bus: u8,
445    pub end_bus: u8,
446    /// The UID here must match the UID described in the SSDT for the
447    /// corresponding host bridge.
448    pub uid: u32,
449    pub low_mmio_base: u64,
450    pub low_mmio_length: u64,
451    pub high_mmio_base: u64,
452    pub high_mmio_length: u64,
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    fn read<T>(bytes: &[u8]) -> T
460    where
461        T: FromBytes + Immutable + KnownLayout,
462    {
463        T::read_from_prefix(bytes)
464            .expect("byte slice should always be big enough")
465            .0
466    }
467
468    fn add_one_dynamic(length: usize) {
469        let padded_length = align_8(length);
470        let madt = vec![0xCC; length];
471
472        let data = {
473            let mut blob = Blob::new();
474            blob.add_raw(BlobStructureType::AcpiTable, &madt);
475            blob.complete()
476        };
477
478        assert_eq!(data.len() % 8, 0);
479
480        let header: Header = read(&data[..]);
481        let structure: StructureCount = read(&data[size_of::<Header>()..]);
482
483        let header_exp = Header {
484            structure_type: 0x00,
485            length: (size_of::<Header>() + size_of::<StructureCount>()) as u32,
486        };
487        let structure_exp = StructureCount {
488            total_structure_count: 2,
489            total_config_blob_size: (2 * size_of::<Header>()
490                + size_of::<StructureCount>()
491                + padded_length) as u32,
492        };
493
494        assert_eq!(header.structure_type, header_exp.structure_type);
495        assert_eq!(header.length, header_exp.length);
496        assert_eq!(
497            structure.total_structure_count,
498            structure_exp.total_structure_count
499        );
500        assert_eq!(
501            structure.total_config_blob_size,
502            structure_exp.total_config_blob_size
503        );
504
505        let header: Header = read(&data[size_of::<Header>() + size_of::<StructureCount>()..]);
506        let structure = &data[2 * size_of::<Header>() + size_of::<StructureCount>()..][..length];
507
508        let header_exp = Header {
509            structure_type: 0x16,
510            length: (size_of::<Header>() + padded_length) as u32,
511        };
512        let structure_exp = &madt[..];
513
514        assert_eq!(header.structure_type, header_exp.structure_type);
515        assert_eq!(header.length, header_exp.length);
516        assert_eq!(structure, structure_exp);
517    }
518
519    #[test]
520    fn add_none() {
521        let data = {
522            let blob = Blob::new();
523            blob.complete()
524        };
525
526        assert_eq!(data.len() % 8, 0);
527
528        let header: Header = read(&data[..]);
529        let structure: StructureCount = read(&data[size_of::<Header>()..]);
530
531        let header_exp = Header {
532            structure_type: 0x00,
533            length: (size_of::<Header>() + size_of::<StructureCount>()) as u32,
534        };
535        let structure_exp = StructureCount {
536            total_structure_count: 1,
537            total_config_blob_size: (size_of::<Header>() + size_of::<StructureCount>()) as u32,
538        };
539
540        assert_eq!(header.structure_type, header_exp.structure_type);
541        assert_eq!(header.length, header_exp.length);
542        assert_eq!(
543            structure.total_structure_count,
544            structure_exp.total_structure_count
545        );
546        assert_eq!(
547            structure.total_config_blob_size,
548            structure_exp.total_config_blob_size
549        );
550    }
551
552    #[test]
553    fn add_one_fixed() {
554        let biosinfo = BiosInformation {
555            bios_size_pages: 12345678,
556            flags: 1 << 31,
557        };
558
559        let data = {
560            let mut blob = Blob::new();
561            blob.add(&BiosInformation {
562                bios_size_pages: 12345678,
563                flags: 1 << 31,
564            });
565            blob.complete()
566        };
567
568        assert_eq!(data.len() % 8, 0);
569
570        let header: Header = read(&data[..]);
571        let structure: StructureCount = read(&data[size_of::<Header>()..]);
572
573        let header_exp = Header {
574            structure_type: 0x00,
575            length: (size_of::<Header>() + size_of::<StructureCount>()) as u32,
576        };
577        let structure_exp = StructureCount {
578            total_structure_count: 2,
579            total_config_blob_size: (2 * size_of::<Header>()
580                + size_of::<StructureCount>()
581                + size_of::<BiosInformation>()) as u32,
582        };
583
584        assert_eq!(header.structure_type, header_exp.structure_type);
585        assert_eq!(header.length, header_exp.length);
586        assert_eq!(
587            structure.total_structure_count,
588            structure_exp.total_structure_count
589        );
590        assert_eq!(
591            structure.total_config_blob_size,
592            structure_exp.total_config_blob_size
593        );
594
595        let header: Header = read(&data[size_of::<Header>() + size_of::<StructureCount>()..]);
596        let structure: BiosInformation =
597            read(&data[2 * size_of::<Header>() + size_of::<StructureCount>()..]);
598
599        let header_exp = Header {
600            structure_type: 0x01,
601            length: (size_of::<Header>() + size_of::<BiosInformation>()) as u32,
602        };
603
604        assert_eq!(header.structure_type, header_exp.structure_type);
605        assert_eq!(header.length, header_exp.length);
606        assert_eq!(structure.bios_size_pages, biosinfo.bios_size_pages);
607        assert_eq!(structure.flags, biosinfo.flags);
608    }
609
610    #[test]
611    fn add_one_dynamic_misaligned() {
612        add_one_dynamic(43);
613    }
614
615    #[test]
616    fn add_one_dynamic_aligned() {
617        add_one_dynamic(40);
618    }
619
620    #[test]
621    fn add_two() {
622        const LENGTH: usize = 93;
623        const PADDED_LENGTH: usize = 96;
624        let madt = vec![0xCC; LENGTH];
625        let procinfo = ProcessorInformation {
626            max_processor_count: 4,
627            processor_count: 3,
628            processors_per_virtual_socket: 2,
629            threads_per_processor: 1,
630        };
631
632        let data = {
633            let mut blob = Blob::new();
634            blob.add_raw(BlobStructureType::AcpiTable, &madt)
635                .add(&procinfo);
636            blob.complete()
637        };
638
639        assert_eq!(data.len() % 8, 0);
640
641        let header: Header = read(&data[..]);
642        let structure: StructureCount = read(&data[size_of::<Header>()..]);
643
644        let header_exp = Header {
645            structure_type: 0x00,
646            length: (size_of::<Header>() + size_of::<StructureCount>()) as u32,
647        };
648        let structure_exp = StructureCount {
649            total_structure_count: 3,
650            total_config_blob_size: (3 * size_of::<Header>()
651                + size_of::<StructureCount>()
652                + PADDED_LENGTH
653                + size_of::<ProcessorInformation>()) as u32,
654        };
655
656        assert_eq!(header.structure_type, header_exp.structure_type);
657        assert_eq!(header.length, header_exp.length);
658        assert_eq!(
659            structure.total_structure_count,
660            structure_exp.total_structure_count
661        );
662        assert_eq!(
663            structure.total_config_blob_size,
664            structure_exp.total_config_blob_size
665        );
666
667        let header: Header = read(&data[size_of::<Header>() + size_of::<StructureCount>()..]);
668        let structure = &data[2 * size_of::<Header>() + size_of::<StructureCount>()..][..LENGTH];
669        let padding = &data[2 * size_of::<Header>() + size_of::<StructureCount>() + LENGTH..]
670            [..PADDED_LENGTH - LENGTH];
671
672        let header_exp = Header {
673            structure_type: 0x16,
674            length: (size_of::<Header>() + PADDED_LENGTH) as u32,
675        };
676        let structure_exp = &madt[..];
677
678        assert_eq!(header.structure_type, header_exp.structure_type);
679        assert_eq!(header.length, header_exp.length);
680        assert_eq!(structure.as_bytes(), structure_exp.as_bytes());
681        assert_eq!(padding, &[0; PADDED_LENGTH - LENGTH]);
682
683        let header: Header =
684            read(&data[2 * size_of::<Header>() + size_of::<StructureCount>() + PADDED_LENGTH..]);
685        let structure: ProcessorInformation =
686            read(&data[3 * size_of::<Header>() + size_of::<StructureCount>() + PADDED_LENGTH..]);
687
688        let header_exp = Header {
689            structure_type: 0x13,
690            length: (size_of::<Header>() + size_of::<ProcessorInformation>()) as u32,
691        };
692
693        assert_eq!(header.structure_type, header_exp.structure_type);
694        assert_eq!(header.length, header_exp.length);
695        assert_eq!(structure.max_processor_count, procinfo.max_processor_count);
696        assert_eq!(structure.processor_count, procinfo.processor_count);
697        assert_eq!(
698            structure.processors_per_virtual_socket,
699            procinfo.processors_per_virtual_socket
700        );
701        assert_eq!(
702            structure.threads_per_processor,
703            procinfo.threads_per_processor
704        );
705    }
706}