1#![cfg_attr(minimal_rt, no_std, no_main)]
13#![expect(unsafe_code)]
15
16mod arch;
17mod boot_logger;
18mod cmdline;
19mod dt;
20mod host_params;
21mod hypercall;
22mod memory;
23mod rt;
24mod sidecar;
25mod single_threaded;
26
27use crate::arch::setup_vtl2_memory;
28use crate::arch::setup_vtl2_vp;
29#[cfg(target_arch = "x86_64")]
30use crate::arch::tdx::get_tdx_tsc_reftime;
31use crate::arch::verify_imported_regions_hash;
32use crate::boot_logger::boot_logger_memory_init;
33use crate::boot_logger::boot_logger_runtime_init;
34use crate::hypercall::hvcall;
35use crate::memory::AddressSpaceManager;
36use crate::single_threaded::OffStackRef;
37use crate::single_threaded::off_stack;
38use arrayvec::ArrayString;
39use arrayvec::ArrayVec;
40use cmdline::BootCommandLineOptions;
41use core::fmt::Write;
42use dt::BootTimes;
43use dt::write_dt;
44use host_fdt_parser::ComInfo;
45use host_params::COMMAND_LINE_SIZE;
46use host_params::PartitionInfo;
47use host_params::shim_params::IsolationType;
48use host_params::shim_params::ShimParams;
49use hvdef::Vtl;
50use loader_defs::linux::SETUP_DTB;
51use loader_defs::linux::setup_data;
52use loader_defs::shim::ShimParamsRaw;
53use memory_range::RangeWalkResult;
54use memory_range::walk_ranges;
55use minimal_rt::enlightened_panic::enable_enlightened_panic;
56use sidecar::SidecarConfig;
57use sidecar_defs::SidecarOutput;
58use sidecar_defs::SidecarParams;
59use zerocopy::FromBytes;
60use zerocopy::FromZeros;
61use zerocopy::Immutable;
62use zerocopy::IntoBytes;
63use zerocopy::KnownLayout;
64
65#[derive(Debug)]
66struct CommandLineTooLong;
67
68impl From<core::fmt::Error> for CommandLineTooLong {
69 fn from(_: core::fmt::Error) -> Self {
70 Self
71 }
72}
73
74struct BuildKernelCommandLineParams<'a> {
75 params: &'a ShimParams,
76 cmdline: &'a mut ArrayString<COMMAND_LINE_SIZE>,
77 partition_info: &'a PartitionInfo,
78 can_trust_host: bool,
79 is_confidential_debug: bool,
80 sidecar: Option<&'a SidecarConfig<'a>>,
81 vtl2_pool_supported: bool,
82}
83
84fn build_kernel_command_line(
86 fn_params: BuildKernelCommandLineParams<'_>,
87) -> Result<(), CommandLineTooLong> {
88 let BuildKernelCommandLineParams {
89 params,
90 cmdline,
91 partition_info,
92 can_trust_host,
93 is_confidential_debug,
94 sidecar,
95 vtl2_pool_supported,
96 } = fn_params;
97
98 const KERNEL_PARAMETERS: &[&str] = &[
101 "loglevel=8",
103 "log_buf_len=128K",
105 "printk.time=1",
107 "console_msg_format=syslog",
109 "uio_hv_generic.no_mask=1",
111 "coredump_filter=0x33",
114 "cpufreq.off=1",
116 "cpuidle.off=1",
120 "cryptomgr.notests",
124 "idle=halt",
128 "initcall_blacklist=init_real_mode,sbf_init",
131 "lpj=3000000",
133 "no_timer_check",
135 "noxsave",
141 "oops=panic",
143 "panic_on_warn=0",
145 "panic_print=0",
148 "panic=-1",
150 "printk.devkmsg=on",
158 "reboot=t",
162 "rootfstype=tmpfs",
164 "sysctl.vm.compaction_proactiveness=0",
167 "tsc=reliable",
170 "unknown_nmi_panic=1",
172 "vfio_pci.ids=1414:00ba",
174 "vfio.enable_unsafe_noiommu_mode=1",
177 "rdinit=/underhill-init",
179 "OPENHCL_NVME_VFIO=1",
181 "hv_storvsc.storvsc_vcpus_per_sub_channel=2048",
184 "hv_storvsc.storvsc_max_hw_queues=2",
186 "hv_storvsc.storvsc_ringbuffer_size=0x8000",
188 "MIMALLOC_ARENA_EAGER_COMMIT=0",
190 "acpi=off",
193 ];
194
195 const ARCH_KERNEL_PARAMETERS: &[&str] = cfg_select! {
196 target_arch = "x86_64" => &[
197 "iommu=off",
199 "pci=off",
202 ],
203 target_arch = "aarch64" => &[],
204 };
205
206 for p in KERNEL_PARAMETERS {
207 write!(cmdline, "{p} ")?;
208 }
209
210 for p in ARCH_KERNEL_PARAMETERS {
211 write!(cmdline, "{p} ")?;
212 }
213
214 const HARDWARE_ISOLATED_KERNEL_PARAMETERS: &[&str] = &[
215 "swiotlb=4096,1",
225 ];
226
227 const NON_HARDWARE_ISOLATED_KERNEL_PARAMETERS: &[&str] = &[
228 "swiotlb=1,1",
233 ];
234
235 if params.isolation_type.is_hardware_isolated() {
236 for p in HARDWARE_ISOLATED_KERNEL_PARAMETERS {
237 write!(cmdline, "{p} ")?;
238 }
239 } else {
240 for p in NON_HARDWARE_ISOLATED_KERNEL_PARAMETERS {
241 write!(cmdline, "{p} ")?;
242 }
243 }
244
245 write!(cmdline, "console=")?;
253 match (&partition_info.com3_serial, can_trust_host) {
254 (ComInfo::Ns16550 { current_speed, .. }, true) => {
255 write!(cmdline, "ttyS2,{current_speed} ")?
256 }
257 (ComInfo::Pl011 { current_speed, .. }, true) => {
258 write!(cmdline, "ttyAMA0,{current_speed} ")?
259 }
260 _ => write!(cmdline, "ttynull ")?,
261 }
262
263 if params.isolation_type != IsolationType::None {
264 write!(
265 cmdline,
266 "{}=1 ",
267 underhill_confidentiality::OPENHCL_CONFIDENTIAL_ENV_VAR_NAME
268 )?;
269 }
270
271 if is_confidential_debug {
272 write!(
273 cmdline,
274 "{}=1 ",
275 underhill_confidentiality::OPENHCL_CONFIDENTIAL_DEBUG_ENV_VAR_NAME
276 )?;
277 }
278
279 write!(cmdline, "OPENHCL_NVME_KEEP_ALIVE=")?;
283
284 if partition_info.boot_options.disable_nvme_keep_alive {
285 write!(cmdline, "disabled,")?;
286 }
287
288 if partition_info.nvme_keepalive {
289 write!(cmdline, "host,")?;
290 } else {
291 write!(cmdline, "nohost,")?;
292 }
293
294 if vtl2_pool_supported {
295 write!(cmdline, "privatepool ")?;
296 } else {
297 write!(cmdline, "noprivatepool ")?;
298 }
299
300 if let Some(sidecar) = sidecar {
301 write!(cmdline, "{} ", sidecar.kernel_command_line())?;
302 }
303
304 cmdline.write_str(&partition_info.cmdline)?;
306
307 Ok(())
308}
309
310const FDT_SIZE: usize = 256 * 1024;
317
318#[repr(C, align(4096))]
319#[derive(FromBytes, IntoBytes, Immutable, KnownLayout)]
320struct Fdt {
321 header: setup_data,
322 data: [u8; FDT_SIZE - size_of::<setup_data>()],
323}
324
325fn shim_parameters(shim_params_raw_offset: isize) -> ShimParams {
329 unsafe extern "C" {
330 static __ehdr_start: u8;
331 }
332
333 let shim_base = core::ptr::addr_of!(__ehdr_start) as usize;
334
335 let raw_shim_params = unsafe {
339 &*(shim_base.wrapping_add_signed(shim_params_raw_offset) as *const ShimParamsRaw)
340 };
341
342 ShimParams::new(shim_base as u64, raw_shim_params)
343}
344
345#[cfg_attr(not(target_arch = "x86_64"), expect(dead_code))]
346mod x86_boot {
347 use crate::PageAlign;
348 use crate::memory::AddressSpaceManager;
349 use crate::single_threaded::OffStackRef;
350 use crate::single_threaded::off_stack;
351 use crate::zeroed;
352 use core::mem::size_of;
353 use core::ops::Range;
354 use core::ptr;
355 use loader_defs::linux::E820_RAM;
356 use loader_defs::linux::E820_RESERVED;
357 use loader_defs::linux::SETUP_E820_EXT;
358 use loader_defs::linux::boot_params;
359 use loader_defs::linux::e820entry;
360 use loader_defs::linux::setup_data;
361 use loader_defs::shim::MemoryVtlType;
362 use memory_range::MemoryRange;
363 use zerocopy::FromZeros;
364 use zerocopy::Immutable;
365 use zerocopy::KnownLayout;
366
367 #[repr(C)]
368 #[derive(FromZeros, Immutable, KnownLayout)]
369 pub struct E820Ext {
370 pub header: setup_data,
371 pub entries: [e820entry; 512],
372 }
373
374 fn add_e820_entry(
375 entry: Option<&mut e820entry>,
376 range: MemoryRange,
377 typ: u32,
378 ) -> Result<(), BuildE820MapError> {
379 *entry.ok_or(BuildE820MapError::OutOfE820Entries)? = e820entry {
380 addr: range.start().into(),
381 size: range.len().into(),
382 typ: typ.into(),
383 };
384 Ok(())
385 }
386
387 #[derive(Debug)]
388 pub enum BuildE820MapError {
389 OutOfE820Entries,
391 }
392
393 pub fn build_e820_map(
395 boot_params: &mut boot_params,
396 ext: &mut E820Ext,
397 address_space: &AddressSpaceManager,
398 ) -> Result<bool, BuildE820MapError> {
399 boot_params.e820_entries = 0;
400 let mut entries = boot_params
401 .e820_map
402 .iter_mut()
403 .chain(ext.entries.iter_mut());
404
405 let mut n = 0;
406 for (range, typ) in address_space.vtl2_ranges() {
407 match typ {
408 MemoryVtlType::VTL2_RAM => {
409 add_e820_entry(entries.next(), range, E820_RAM)?;
410 n += 1;
411 }
412 MemoryVtlType::VTL2_CONFIG
413 | MemoryVtlType::VTL2_SIDECAR_IMAGE
414 | MemoryVtlType::VTL2_SIDECAR_NODE
415 | MemoryVtlType::VTL2_RESERVED
416 | MemoryVtlType::VTL2_GPA_POOL
417 | MemoryVtlType::VTL2_TDX_PAGE_TABLES
418 | MemoryVtlType::VTL2_BOOTSHIM_LOG_BUFFER
419 | MemoryVtlType::VTL2_PERSISTED_STATE_HEADER
420 | MemoryVtlType::VTL2_PERSISTED_STATE_PROTOBUF => {
421 add_e820_entry(entries.next(), range, E820_RESERVED)?;
422 n += 1;
423 }
424
425 _ => {
426 panic!("unexpected vtl2 ram type {typ:?} for range {range:#?}");
427 }
428 }
429 }
430
431 let base = n.min(boot_params.e820_map.len());
432 boot_params.e820_entries = base as u8;
433
434 if base < n {
435 ext.header.len = ((n - base) * size_of::<e820entry>()) as u32;
436 Ok(true)
437 } else {
438 Ok(false)
439 }
440 }
441
442 pub fn build_boot_params(
443 address_space: &AddressSpaceManager,
444 initrd: Range<u64>,
445 cmdline: &str,
446 setup_data_head: *const setup_data,
447 setup_data_tail: &mut &mut setup_data,
448 ) -> OffStackRef<'static, PageAlign<boot_params>> {
449 let mut boot_params_storage = off_stack!(PageAlign<boot_params>, zeroed());
450 let boot_params = &mut boot_params_storage.0;
451 boot_params.hdr.type_of_loader = 0xff; boot_params.hdr.hardware_subarch = 1.into();
463
464 boot_params.hdr.ramdisk_image = (initrd.start as u32).into();
465 boot_params.ext_ramdisk_image = (initrd.start >> 32) as u32;
466 let initrd_len = initrd.end - initrd.start;
467 boot_params.hdr.ramdisk_size = (initrd_len as u32).into();
468 boot_params.ext_ramdisk_size = (initrd_len >> 32) as u32;
469
470 let e820_ext = OffStackRef::leak(off_stack!(E820Ext, zeroed()));
471
472 let used_ext = build_e820_map(boot_params, e820_ext, address_space)
473 .expect("building e820 map must succeed");
474
475 if used_ext {
476 e820_ext.header.ty = SETUP_E820_EXT;
477 setup_data_tail.next = ptr::from_ref(&e820_ext.header) as u64;
478 *setup_data_tail = &mut e820_ext.header;
479 }
480
481 let cmd_line_addr = cmdline.as_ptr() as u64;
482 boot_params.hdr.cmd_line_ptr = (cmd_line_addr as u32).into();
483 boot_params.ext_cmd_line_ptr = (cmd_line_addr >> 32) as u32;
484
485 boot_params.hdr.setup_data = (setup_data_head as u64).into();
486
487 boot_params_storage
488 }
489}
490
491#[cfg(target_arch = "x86_64")]
493fn build_cc_blob_sev_info(
494 cc_blob: &mut loader_defs::linux::cc_blob_sev_info,
495 shim_params: &ShimParams,
496) {
497 cc_blob.magic = loader_defs::linux::CC_BLOB_SEV_INFO_MAGIC;
500 cc_blob.version = 0;
501 cc_blob._reserved = 0;
502 cc_blob.secrets_phys = shim_params.secrets_start();
503 cc_blob.secrets_len = hvdef::HV_PAGE_SIZE as u32;
504 cc_blob._rsvd1 = 0;
505 cc_blob.cpuid_phys = shim_params.cpuid_start();
506 cc_blob.cpuid_len = hvdef::HV_PAGE_SIZE as u32;
507 cc_blob._rsvd2 = 0;
508}
509
510#[repr(C, align(4096))]
511#[derive(FromZeros, Immutable, KnownLayout)]
512struct PageAlign<T>(T);
513
514const fn zeroed<T: FromZeros>() -> T {
515 unsafe { core::mem::MaybeUninit::<T>::zeroed().assume_init() }
517}
518
519fn get_ref_time(isolation: IsolationType) -> Option<u64> {
520 match isolation {
521 #[cfg(target_arch = "x86_64")]
522 IsolationType::Tdx => get_tdx_tsc_reftime(),
523 #[cfg(target_arch = "x86_64")]
524 IsolationType::Snp => None,
525 _ => Some(minimal_rt::reftime::reference_time()),
526 }
527}
528
529fn build_initrd_crc_diagnostic(p: &ShimParams, first_computed_crc: u32) -> ArrayString<384> {
550 let initrd_bytes = p.initrd();
551
552 let second_computed_crc = crc32fast::hash(initrd_bytes);
557
558 let mut head = [0u8; 16];
561 let head_len = head.len().min(initrd_bytes.len());
562 head[..head_len].copy_from_slice(&initrd_bytes[..head_len]);
563
564 let mut tail = [0u8; 16];
565 let tail_len = tail.len().min(initrd_bytes.len());
566 if tail_len > 0 {
567 let start = initrd_bytes.len() - tail_len;
568 tail[..tail_len].copy_from_slice(&initrd_bytes[start..]);
569 }
570
571 let mut eighths = [0u32; 8];
574 let n = initrd_bytes.len();
575 if n > 0 {
576 let step = n.div_ceil(8);
577 for (i, e) in eighths.iter_mut().enumerate() {
578 let start = i * step;
579 if start >= n {
580 break;
581 }
582 let end = ((i + 1) * step).min(n);
583 *e = crc32fast::hash(&initrd_bytes[start..end]);
584 }
585 }
586
587 let mut buf = ArrayString::<384>::new();
588 let _ = write!(
589 &mut buf,
590 "initrd crc mismatch: iso={:?} base={:#x} size={:#x} \
591 exp={:#x} got={:#x} got2={:#x} head={:02x?} tail={:02x?} \
592 eighths=[{:#x},{:#x},{:#x},{:#x},{:#x},{:#x},{:#x},{:#x}]",
593 p.isolation_type,
594 p.initrd_base,
595 p.initrd_size,
596 p.initrd_crc,
597 first_computed_crc,
598 second_computed_crc,
599 &head[..head_len],
600 &tail[..tail_len],
601 eighths[0],
602 eighths[1],
603 eighths[2],
604 eighths[3],
605 eighths[4],
606 eighths[5],
607 eighths[6],
608 eighths[7],
609 );
610 buf
611}
612
613fn shim_main(shim_params_raw_offset: isize) -> ! {
614 let p = shim_parameters(shim_params_raw_offset);
615 if p.isolation_type == IsolationType::None {
616 enable_enlightened_panic();
617 }
618
619 #[cfg(feature = "cvm_boot_log")]
620 arch::initialize_serial_io(&p);
621
622 boot_logger_memory_init(p.log_buffer);
624
625 log::set_logger(&boot_logger::BOOT_LOGGER).unwrap();
627 log::set_max_level(log::LevelFilter::Info);
629
630 let boot_reftime = get_ref_time(p.isolation_type);
631
632 if !p.isolation_type.is_hardware_isolated() {
639 hvcall().initialize();
640 }
641
642 let mut static_options = BootCommandLineOptions::new();
643 if let Some(cmdline) = p.command_line().command_line() {
644 static_options.parse(cmdline);
645 }
646
647 let static_confidential_debug = static_options.confidential_debug;
648 let can_trust_host = p.isolation_type == IsolationType::None || static_confidential_debug;
649
650 let mut dt_storage = off_stack!(PartitionInfo, PartitionInfo::new());
651 let address_space = OffStackRef::leak(off_stack!(
652 AddressSpaceManager,
653 AddressSpaceManager::new_const()
654 ));
655 let partition_info = match PartitionInfo::read_from_dt(
656 &p,
657 &mut dt_storage,
658 address_space,
659 static_options,
660 can_trust_host,
661 ) {
662 Ok(val) => val,
663 Err(e) => panic!("unable to read device tree params {:?}", e),
664 };
665
666 boot_logger_runtime_init(p.isolation_type, partition_info.com3_serial.clone());
669 log::info!("openhcl_boot: logging enabled");
670 log::info!("serial configuration: {:#x?}", partition_info.com3_serial);
671
672 let is_confidential_debug =
676 static_confidential_debug || partition_info.boot_options.confidential_debug;
677
678 if !p.isolation_type.is_hardware_isolated()
680 && hvcall().vtl() == Vtl::Vtl2
681 && hvdef::HvRegisterVsmCapabilities::from(
682 hvcall()
683 .get_register(hvdef::HvAllArchRegisterName::VsmCapabilities.into())
684 .expect("failed to query vsm capabilities")
685 .as_u64(),
686 )
687 .vtl0_alias_map_available()
688 {
689 if partition_info.vtl0_alias_map.is_none() {
699 partition_info.vtl0_alias_map =
700 Some(1 << (arch::physical_address_bits(p.isolation_type) - 1));
701 }
702 } else {
703 partition_info.vtl0_alias_map = None;
706 }
707
708 let partition_info: &PartitionInfo = partition_info;
710
711 if partition_info.cpus.is_empty() {
712 panic!("no cpus");
713 }
714
715 validate_vp_hw_ids(partition_info);
716
717 setup_vtl2_memory(&p, partition_info, address_space);
718 setup_vtl2_vp(partition_info);
719
720 verify_imported_regions_hash(&p);
721
722 let mut sidecar_params = off_stack!(PageAlign<SidecarParams>, zeroed());
723 let mut sidecar_output = off_stack!(PageAlign<SidecarOutput>, zeroed());
724 let sidecar = sidecar::start_sidecar(
725 &p,
726 partition_info,
727 address_space,
728 &mut sidecar_params.0,
729 &mut sidecar_output.0,
730 );
731
732 let address_space: &AddressSpaceManager = address_space;
734
735 let mut cmdline = off_stack!(ArrayString<COMMAND_LINE_SIZE>, ArrayString::new_const());
736 build_kernel_command_line(BuildKernelCommandLineParams {
737 params: &p,
738 cmdline: &mut cmdline,
739 partition_info,
740 can_trust_host,
741 is_confidential_debug,
742 sidecar: sidecar.as_ref(),
743 vtl2_pool_supported: address_space.has_vtl2_pool(),
744 })
745 .unwrap();
746
747 let mut fdt = off_stack!(Fdt, zeroed());
748 fdt.header.len = fdt.data.len() as u32;
749 fdt.header.ty = SETUP_DTB;
750
751 #[cfg(target_arch = "x86_64")]
752 let mut setup_data_tail = &mut fdt.header;
753 #[cfg(target_arch = "x86_64")]
754 let setup_data_head = core::ptr::from_ref(setup_data_tail);
755
756 #[cfg(target_arch = "x86_64")]
757 if p.isolation_type == IsolationType::Snp {
758 let cc_blob = OffStackRef::leak(off_stack!(loader_defs::linux::cc_blob_sev_info, zeroed()));
759 build_cc_blob_sev_info(cc_blob, &p);
760
761 let cc_data = OffStackRef::leak(off_stack!(loader_defs::linux::cc_setup_data, zeroed()));
762 cc_data.header.len = size_of::<loader_defs::linux::cc_setup_data>() as u32;
763 cc_data.header.ty = loader_defs::linux::SETUP_CC_BLOB;
764 cc_data.cc_blob_address = core::ptr::from_ref(&*cc_blob) as u32;
765
766 setup_data_tail.next = core::ptr::from_ref(&*cc_data) as u64;
768 setup_data_tail = &mut cc_data.header;
769 }
770
771 let initrd = p.initrd_base..p.initrd_base + p.initrd_size;
772
773 let computed_crc = crc32fast::hash(p.initrd());
775 if computed_crc != p.initrd_crc && is_confidential_debug {
776 let diag = build_initrd_crc_diagnostic(&p, computed_crc);
777 log::error!("{}", diag.as_str());
778 panic!("{}", diag.as_str());
779 }
780 assert_eq!(
781 computed_crc, p.initrd_crc,
782 "computed initrd crc does not match build time calculated crc"
783 );
784
785 #[cfg(target_arch = "x86_64")]
786 let boot_params = x86_boot::build_boot_params(
787 address_space,
788 initrd.clone(),
789 &cmdline,
790 setup_data_head,
791 &mut setup_data_tail,
792 );
793
794 let boot_times = boot_reftime.map(|start| BootTimes {
798 start,
799 end: get_ref_time(p.isolation_type).unwrap_or(0),
800 });
801
802 for (range, result) in walk_ranges(
805 partition_info.vtl2_ram.iter().map(|r| (r.range, ())),
806 p.imported_regions(),
807 ) {
808 match result {
809 RangeWalkResult::Neither | RangeWalkResult::Left(_) | RangeWalkResult::Both(_, _) => {}
810 RangeWalkResult::Right(accepted) => {
811 assert!(
814 accepted,
815 "range {:#x?} not in vtl2 ram was not preaccepted at launch",
816 range
817 );
818 }
819 }
820 }
821
822 write_dt(
823 &mut fdt.data,
824 partition_info,
825 address_space,
826 p.imported_regions().map(|r| {
827 r.0
834 }),
835 initrd,
836 &cmdline,
837 sidecar.as_ref(),
838 boot_times,
839 p.isolation_type,
840 )
841 .unwrap();
842
843 rt::verify_stack_cookie();
844
845 log::info!("uninitializing hypercalls");
846 #[cfg(not(feature = "cvm_boot_log"))]
847 log::info!("about to jump to kernel");
848
849 hvcall().uninitialize();
850
851 #[cfg(feature = "cvm_boot_log")]
852 {
853 log::info!("uninitializing serial io");
854 log::info!("about to jump to kernel");
855 arch::uninitialize_serial_io(&p);
856 }
857
858 cfg_select! {
859 target_arch = "x86_64" => {
860 let kernel_entry: extern "C" fn(u64, &loader_defs::linux::boot_params) -> ! =
862 unsafe { core::mem::transmute(p.kernel_entry_address) };
863 kernel_entry(0, &boot_params.0)
864 }
865 target_arch = "aarch64" => {
866 let kernel_entry: extern "C" fn(
868 fdt_data: *const u8,
869 mbz0: u64,
870 mbz1: u64,
871 mbz2: u64,
872 ) -> ! = unsafe { core::mem::transmute(p.kernel_entry_address) };
873 unsafe {
877 core::arch::asm!(
878 "
879 mrs {0}, sctlr_el1
880 bic {0}, {0}, #0x1
881 msr sctlr_el1, {0}
882 tlbi vmalle1
883 dsb sy
884 isb sy",
885 lateout(reg) _,
886 );
887 }
888 kernel_entry(fdt.data.as_ptr(), 0, 0, 0)
889 }
890 _ => {
891 panic!("unsupported arch")
892 }
893 }
894}
895
896fn validate_vp_hw_ids(partition_info: &PartitionInfo) {
900 use host_params::MAX_CPU_COUNT;
901 use hypercall::HwId;
902
903 if partition_info.isolation.is_hardware_isolated() {
904 return;
913 }
914
915 if hvcall().vtl() != Vtl::Vtl2 {
916 return;
920 }
921
922 let mut hw_ids = off_stack!(ArrayVec<HwId, MAX_CPU_COUNT>, ArrayVec::new_const());
925 hw_ids.clear();
926 hw_ids.extend(partition_info.cpus.iter().map(|c| c.reg as _));
927 let mut vp_indexes = off_stack!(ArrayVec<u32, MAX_CPU_COUNT>, ArrayVec::new_const());
928 vp_indexes.clear();
929 if let Err(err) = hvcall().get_vp_index_from_hw_id(&hw_ids, &mut vp_indexes) {
930 panic!(
931 "failed to get VP index for hardware ID {:#x}: {}",
932 hw_ids[vp_indexes.len().min(hw_ids.len() - 1)],
933 err
934 );
935 }
936 if let Some((i, &vp_index)) = vp_indexes
937 .iter()
938 .enumerate()
939 .find(|&(i, vp_index)| i as u32 != *vp_index)
940 {
941 panic!(
942 "CPU hardware ID {:#x} does not correspond to VP index {}",
943 hw_ids[i], vp_index
944 );
945 }
946}
947
948#[cfg(not(minimal_rt))]
951fn main() {
952 unimplemented!("build with MINIMAL_RT_BUILD to produce a working boot loader");
953}
954
955#[cfg(test)]
956mod test {
957 use super::x86_boot::E820Ext;
958 use super::x86_boot::build_e820_map;
959 use crate::cmdline::BootCommandLineOptions;
960 use crate::dt::write_dt;
961 use crate::host_params::MAX_CPU_COUNT;
962 use crate::host_params::PartitionInfo;
963 use crate::host_params::shim_params::IsolationType;
964 use crate::memory::AddressSpaceManager;
965 use crate::memory::AddressSpaceManagerBuilder;
966 use arrayvec::ArrayString;
967 use arrayvec::ArrayVec;
968 use core::ops::Range;
969 use host_fdt_parser::ComInfo;
970 use host_fdt_parser::CpuEntry;
971 use host_fdt_parser::MemoryEntry;
972 use host_fdt_parser::VmbusInfo;
973 use igvm_defs::MemoryMapEntryType;
974 use loader_defs::linux::E820_RAM;
975 use loader_defs::linux::E820_RESERVED;
976 use loader_defs::linux::boot_params;
977 use loader_defs::linux::e820entry;
978 use memory_range::MemoryRange;
979 use memory_range::subtract_ranges;
980 use sidecar_defs::PerCpuState;
981 use zerocopy::FromZeros;
982
983 const HIGH_MMIO_GAP_END: u64 = 0x1000000000; const VMBUS_MMIO_GAP_SIZE: u64 = 0x10000000; const HIGH_MMIO_GAP_START: u64 = HIGH_MMIO_GAP_END - VMBUS_MMIO_GAP_SIZE;
986
987 fn new_partition_info(cpu_count: usize) -> PartitionInfo {
990 let mut cpus: ArrayVec<CpuEntry, MAX_CPU_COUNT> = ArrayVec::new();
991
992 for id in 0..(cpu_count as u64) {
993 cpus.push(CpuEntry { reg: id, vnode: 0 });
994 }
995
996 let mut mmio = ArrayVec::new();
997 mmio.push(
998 MemoryRange::try_new(HIGH_MMIO_GAP_START..HIGH_MMIO_GAP_END).expect("valid range"),
999 );
1000
1001 PartitionInfo {
1002 vtl2_ram: ArrayVec::new(),
1003 partition_ram: ArrayVec::new(),
1004 isolation: IsolationType::None,
1005 bsp_reg: cpus[0].reg as u32,
1006 cpus,
1007 sidecar_cpu_overrides: PerCpuState {
1008 per_cpu_state_specified: false,
1009 sidecar_starts_cpu: [true; sidecar_defs::NUM_CPUS_SUPPORTED_FOR_PER_CPU_STATE],
1010 },
1011 cmdline: ArrayString::new(),
1012 vmbus_vtl2: VmbusInfo { mmio },
1013 vmbus_vtl0: VmbusInfo {
1014 mmio: ArrayVec::new(),
1015 },
1016 com3_serial: ComInfo::None,
1017 gic: None,
1018 pmu_gsiv: None,
1019 memory_allocation_mode: host_fdt_parser::MemoryAllocationMode::Host,
1020 entropy: None,
1021 vtl0_alias_map: None,
1022 nvme_keepalive: false,
1023 boot_options: BootCommandLineOptions::new(),
1024 }
1025 }
1026
1027 #[test]
1029 #[cfg_attr(
1030 target_arch = "aarch64",
1031 ignore = "TODO: investigate why this doesn't always work on ARM"
1032 )]
1033 fn fdt_cpu_scaling() {
1034 const MAX_CPUS: usize = 2048;
1035
1036 let mut buf = [0; 0x40000];
1037 write_dt(
1038 &mut buf,
1039 &new_partition_info(MAX_CPUS),
1040 &AddressSpaceManager::new_const(),
1041 [],
1042 0..0,
1043 &ArrayString::from("test").unwrap_or_default(),
1044 None,
1045 None,
1046 IsolationType::None,
1047 )
1048 .unwrap();
1049 }
1050
1051 #[test]
1057 #[ignore = "TODO: temporarily broken"]
1058 fn fdt_dtc_check_content() {
1059 const MAX_CPUS: usize = 2;
1060 const BUF_SIZE: usize = 0x1000;
1061
1062 let dtb_data_spans: [(usize, &[u8]); 2] = [
1064 (
1065 0,
1066 b"\xd0\x0d\xfe\xed\x00\x00\x10\x00\x00\x00\x04\x38\x00\x00\x00\x38\
1067 \x00\x00\x00\x28\x00\x00\x00\x11\x00\x00\x00\x10\x00\x00\x00\x00\
1068 \x00\x00\x00\x4a\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x00\x00\x00\
1069 \x00\x00\x00\x00\x00\x00\x00\x00\x23\x61\x64\x64\x72\x65\x73\x73\
1070 \x2d\x63\x65\x6c\x6c\x73\x00\x23\x73\x69\x7a\x65\x2d\x63\x65\x6c\
1071 \x6c\x73\x00\x6d\x6f\x64\x65\x6c\x00\x72\x65\x67\x00\x64\x65\x76\
1072 \x69\x63\x65\x5f\x74\x79\x70\x65\x00\x73\x74\x61\x74\x75\x73\x00\
1073 \x63\x6f\x6d\x70\x61\x74\x69\x62\x6c\x65\x00\x72\x61\x6e\x67\x65\
1074 \x73",
1075 ),
1076 (
1077 0x430,
1078 b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
1079 \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x02\
1080 \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0f\x00\x00\x00\x00\
1081 \x00\x00\x00\x03\x00\x00\x00\x0f\x00\x00\x00\x1b\x6d\x73\x66\x74\
1082 \x2c\x75\x6e\x64\x65\x72\x68\x69\x6c\x6c\x00\x00\x00\x00\x00\x01\
1083 \x63\x70\x75\x73\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1084 \x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x04\
1085 \x00\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x01\x63\x70\x75\x40\
1086 \x30\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x25\
1087 \x63\x70\x75\x00\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x21\
1088 \x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x05\x00\x00\x00\x31\
1089 \x6f\x6b\x61\x79\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\
1090 \x63\x70\x75\x40\x31\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1091 \x00\x00\x00\x25\x63\x70\x75\x00\x00\x00\x00\x03\x00\x00\x00\x04\
1092 \x00\x00\x00\x21\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x05\
1093 \x00\x00\x00\x31\x6f\x6b\x61\x79\x00\x00\x00\x00\x00\x00\x00\x02\
1094 \x00\x00\x00\x02\x00\x00\x00\x01\x76\x6d\x62\x75\x73\x00\x00\x00\
1095 \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x02\
1096 \x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0f\x00\x00\x00\x01\
1097 \x00\x00\x00\x03\x00\x00\x00\x0b\x00\x00\x00\x38\x6d\x73\x66\x74\
1098 \x2c\x76\x6d\x62\x75\x73\x00\x00\x00\x00\x00\x03\x00\x00\x00\x14\
1099 \x00\x00\x00\x43\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\
1100 \xf0\x00\x00\x00\x10\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\
1101 \x00\x00\x00\x09",
1102 ),
1103 ];
1104
1105 let mut sample_buf = [0u8; BUF_SIZE];
1106 for (span_start, bytes) in dtb_data_spans {
1107 sample_buf[span_start..span_start + bytes.len()].copy_from_slice(bytes);
1108 }
1109
1110 let mut buf = [0u8; BUF_SIZE];
1111 write_dt(
1112 &mut buf,
1113 &new_partition_info(MAX_CPUS),
1114 &AddressSpaceManager::new_const(),
1115 [],
1116 0..0,
1117 &ArrayString::from("test").unwrap_or_default(),
1118 None,
1119 None,
1120 IsolationType::None,
1121 )
1122 .unwrap();
1123
1124 assert!(sample_buf == buf);
1125 }
1126
1127 #[test]
1134 #[ignore = "enabling the test requires installing additional software, \
1135 and developers will experience a break."]
1136 fn fdt_dtc_decompile() {
1137 const MAX_CPUS: usize = 2048;
1138
1139 let mut buf = [0; 0x40000];
1140 write_dt(
1141 &mut buf,
1142 &new_partition_info(MAX_CPUS),
1143 &AddressSpaceManager::new_const(),
1144 [],
1145 0..0,
1146 &ArrayString::from("test").unwrap_or_default(),
1147 None,
1148 None,
1149 IsolationType::None,
1150 )
1151 .unwrap();
1152
1153 let input_dtb_file_name = "openhcl_boot.dtb";
1154 let output_dts_file_name = "openhcl_boot.dts";
1155 std::fs::write(input_dtb_file_name, buf).unwrap();
1156 let success = std::process::Command::new("dtc")
1157 .args([input_dtb_file_name, "-I", "dtb", "-o", output_dts_file_name])
1158 .status()
1159 .unwrap()
1160 .success();
1161 assert!(success);
1162 }
1163
1164 fn new_address_space_manager(
1165 ram: &[MemoryRange],
1166 bootshim_used: MemoryRange,
1167 persisted_range: MemoryRange,
1168 parameter_range: MemoryRange,
1169 reclaim: Option<MemoryRange>,
1170 ) -> AddressSpaceManager {
1171 let ram = ram
1172 .iter()
1173 .cloned()
1174 .map(|range| MemoryEntry {
1175 range,
1176 mem_type: MemoryMapEntryType::VTL2_PROTECTABLE,
1177 vnode: 0,
1178 })
1179 .collect::<Vec<_>>();
1180 let mut address_space = AddressSpaceManager::new_const();
1181 AddressSpaceManagerBuilder::new(
1182 &mut address_space,
1183 &ram,
1184 bootshim_used,
1185 persisted_range,
1186 subtract_ranges([parameter_range], reclaim),
1187 )
1188 .init()
1189 .unwrap();
1190 address_space
1191 }
1192
1193 fn check_e820(boot_params: &boot_params, ext: &E820Ext, expected: &[(Range<u64>, u32)]) {
1194 let actual = boot_params.e820_map[..boot_params.e820_entries as usize]
1195 .iter()
1196 .chain(
1197 ext.entries
1198 .iter()
1199 .take((ext.header.len as usize) / size_of::<e820entry>()),
1200 );
1201
1202 assert_eq!(actual.clone().count(), expected.len());
1203
1204 for (actual, (expected_range, expected_type)) in actual.zip(expected.iter()) {
1205 let addr: u64 = actual.addr.into();
1206 let size: u64 = actual.size.into();
1207 let typ: u32 = actual.typ.into();
1208 assert_eq!(addr, expected_range.start);
1209 assert_eq!(size, expected_range.end - expected_range.start);
1210 assert_eq!(typ, *expected_type);
1211 }
1212 }
1213
1214 const PAGE_SIZE: u64 = 0x1000;
1215 const ONE_MB: u64 = 0x10_0000;
1216
1217 #[test]
1218 fn test_e820_basic() {
1219 let mut boot_params: boot_params = FromZeros::new_zeroed();
1221 let mut ext = FromZeros::new_zeroed();
1222 let bootshim_used = MemoryRange::try_new(ONE_MB..3 * ONE_MB).unwrap();
1223 let persisted_header_end = ONE_MB + PAGE_SIZE;
1224 let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1225 let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1226 let parameter_range = MemoryRange::try_new(2 * ONE_MB..3 * ONE_MB).unwrap();
1227 let address_space = new_address_space_manager(
1228 &[MemoryRange::new(ONE_MB..4 * ONE_MB)],
1229 bootshim_used,
1230 persisted_state,
1231 parameter_range,
1232 None,
1233 );
1234
1235 assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1236
1237 check_e820(
1238 &boot_params,
1239 &ext,
1240 &[
1241 (ONE_MB..(persisted_header_end), E820_RESERVED),
1242 (persisted_header_end..persisted_end, E820_RESERVED),
1243 (persisted_end..2 * ONE_MB, E820_RAM),
1244 (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1245 (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1246 ],
1247 );
1248
1249 let mut boot_params: boot_params = FromZeros::new_zeroed();
1251 let mut ext = FromZeros::new_zeroed();
1252 let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1253 let persisted_header_end = ONE_MB + PAGE_SIZE;
1254 let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1255 let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1256 let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1257 let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1258 let address_space = new_address_space_manager(
1259 &[MemoryRange::new(ONE_MB..6 * ONE_MB)],
1260 bootshim_used,
1261 persisted_state,
1262 parameter_range,
1263 Some(reclaim),
1264 );
1265
1266 assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1267
1268 check_e820(
1269 &boot_params,
1270 &ext,
1271 &[
1272 (ONE_MB..(persisted_header_end), E820_RESERVED),
1273 (persisted_header_end..persisted_end, E820_RESERVED),
1274 (persisted_end..2 * ONE_MB, E820_RAM),
1275 (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1276 (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1277 (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1278 (5 * ONE_MB..6 * ONE_MB, E820_RAM),
1279 ],
1280 );
1281
1282 let mut boot_params: boot_params = FromZeros::new_zeroed();
1284 let mut ext = FromZeros::new_zeroed();
1285 let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1286 let persisted_header_end = ONE_MB + PAGE_SIZE;
1287 let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1288 let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1289 let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1290 let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1291 let address_space = new_address_space_manager(
1292 &[
1293 MemoryRange::new(ONE_MB..4 * ONE_MB),
1294 MemoryRange::new(4 * ONE_MB..10 * ONE_MB),
1295 ],
1296 bootshim_used,
1297 persisted_state,
1298 parameter_range,
1299 Some(reclaim),
1300 );
1301
1302 assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1303
1304 check_e820(
1305 &boot_params,
1306 &ext,
1307 &[
1308 (ONE_MB..(persisted_header_end), E820_RESERVED),
1309 (persisted_header_end..persisted_end, E820_RESERVED),
1310 (persisted_end..2 * ONE_MB, E820_RAM),
1311 (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1312 (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1313 (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1314 (5 * ONE_MB..10 * ONE_MB, E820_RAM),
1315 ],
1316 );
1317
1318 let mut boot_params: boot_params = FromZeros::new_zeroed();
1320 let mut ext = FromZeros::new_zeroed();
1321 let bootshim_used = MemoryRange::try_new(ONE_MB..5 * ONE_MB).unwrap();
1322 let persisted_header_end = ONE_MB + PAGE_SIZE;
1323 let persisted_end = ONE_MB + 4 * PAGE_SIZE;
1324 let persisted_state = MemoryRange::try_new(ONE_MB..persisted_end).unwrap();
1325 let parameter_range = MemoryRange::try_new(2 * ONE_MB..5 * ONE_MB).unwrap();
1326 let reclaim = MemoryRange::try_new(3 * ONE_MB..4 * ONE_MB).unwrap();
1327 let address_space = new_address_space_manager(
1328 &[
1329 MemoryRange::new(ONE_MB..2 * ONE_MB),
1330 MemoryRange::new(2 * ONE_MB..3 * ONE_MB),
1331 MemoryRange::new(3 * ONE_MB..4 * ONE_MB),
1332 MemoryRange::new(4 * ONE_MB..5 * ONE_MB),
1333 MemoryRange::new(5 * ONE_MB..6 * ONE_MB),
1334 MemoryRange::new(6 * ONE_MB..7 * ONE_MB),
1335 MemoryRange::new(7 * ONE_MB..8 * ONE_MB),
1336 ],
1337 bootshim_used,
1338 persisted_state,
1339 parameter_range,
1340 Some(reclaim),
1341 );
1342
1343 assert!(build_e820_map(&mut boot_params, &mut ext, &address_space).is_ok());
1344
1345 check_e820(
1346 &boot_params,
1347 &ext,
1348 &[
1349 (ONE_MB..(persisted_header_end), E820_RESERVED),
1350 (persisted_header_end..persisted_end, E820_RESERVED),
1351 (persisted_end..2 * ONE_MB, E820_RAM),
1352 (2 * ONE_MB..3 * ONE_MB, E820_RESERVED),
1353 (3 * ONE_MB..4 * ONE_MB, E820_RAM),
1354 (4 * ONE_MB..5 * ONE_MB, E820_RESERVED),
1355 (5 * ONE_MB..8 * ONE_MB, E820_RAM),
1356 ],
1357 );
1358 }
1359
1360 #[test]
1362 fn test_e820_huge() {
1363 use crate::memory::AllocationPolicy;
1364 use crate::memory::AllocationType;
1365
1366 const E820_MAX_ENTRIES_ZEROPAGE: usize = 128;
1369 const RAM_RANGES: usize = 64;
1370 const TOTAL_ALLOCATIONS: usize = 256;
1371
1372 let mut ranges = Vec::new();
1374 for i in 0..RAM_RANGES {
1375 let start = (i as u64) * 64 * ONE_MB;
1376 let end = start + 64 * ONE_MB;
1377 ranges.push(MemoryRange::new(start..end));
1378 }
1379
1380 let bootshim_used = MemoryRange::try_new(0..ONE_MB * 2).unwrap();
1381 let persisted_range = MemoryRange::try_new(0..ONE_MB).unwrap();
1382 let parameter_range = MemoryRange::try_new(ONE_MB..2 * ONE_MB).unwrap();
1383
1384 let mut address_space = {
1385 let ram = ranges
1386 .iter()
1387 .cloned()
1388 .map(|range| MemoryEntry {
1389 range,
1390 mem_type: MemoryMapEntryType::VTL2_PROTECTABLE,
1391 vnode: 0,
1392 })
1393 .collect::<Vec<_>>();
1394 let mut address_space = AddressSpaceManager::new_const();
1395 AddressSpaceManagerBuilder::new(
1396 &mut address_space,
1397 &ram,
1398 bootshim_used,
1399 persisted_range,
1400 core::iter::once(parameter_range),
1401 )
1402 .init()
1403 .unwrap();
1404 address_space
1405 };
1406
1407 for i in 0..TOTAL_ALLOCATIONS {
1408 let _allocated = address_space
1412 .allocate(
1413 None,
1414 ONE_MB,
1415 if i % 2 == 0 {
1416 AllocationType::GpaPool
1417 } else {
1418 AllocationType::SidecarNode
1419 },
1420 AllocationPolicy::LowMemory,
1421 )
1422 .expect("should be able to allocate sidecar node");
1423 }
1424
1425 let mut boot_params: boot_params = FromZeros::new_zeroed();
1426 let mut ext = FromZeros::new_zeroed();
1427 let total_ranges = address_space.vtl2_ranges().count();
1428
1429 let used_ext = build_e820_map(&mut boot_params, &mut ext, &address_space).unwrap();
1430
1431 assert!(used_ext, "should use extension when there are many ranges");
1433
1434 assert_eq!(boot_params.e820_entries, E820_MAX_ENTRIES_ZEROPAGE as u8);
1436
1437 let ext_entries = (ext.header.len as usize) / size_of::<e820entry>();
1439 assert_eq!(ext_entries, total_ranges - E820_MAX_ENTRIES_ZEROPAGE);
1440
1441 let total_e820_entries = boot_params.e820_entries as usize + ext_entries;
1443 assert_eq!(total_e820_entries, total_ranges);
1444 }
1445}