1use super::AFTER_INIT;
8use super::CommandErrorWriter;
9use super::ENABLE_LOG;
10use super::VSM_CAPABILITIES;
11use super::VTL_RETURN_OFFSET;
12use super::VpGlobals;
13use super::addr_space;
14use super::temporary_map;
15use crate::arch::x86_64::get_hv_vp_register;
16use crate::arch::x86_64::hypercall;
17use crate::arch::x86_64::log;
18use arrayvec::ArrayVec;
19use core::fmt::Display;
20use core::fmt::Write;
21use core::hint::spin_loop;
22use core::mem::MaybeUninit;
23use core::ptr::addr_of;
24use core::ptr::addr_of_mut;
25use core::sync::atomic::AtomicU32;
26use core::sync::atomic::Ordering::Acquire;
27use core::sync::atomic::Ordering::Relaxed;
28use core::sync::atomic::Ordering::Release;
29use hvdef::HvError;
30use hvdef::HvRegisterVsmCodePageOffsets;
31use hvdef::HvX64RegisterName;
32use hvdef::HvX64SegmentRegister;
33use hvdef::HypercallCode;
34use hvdef::hypercall::EnableVpVtlX64;
35use hvdef::hypercall::HvInputVtl;
36use hvdef::hypercall::StartVirtualProcessorX64;
37use memory_range::AlignedSubranges;
38use memory_range::MemoryRange;
39use minimal_rt::arch::hypercall::HYPERCALL_PAGE;
40use minimal_rt::enlightened_panic;
41use sidecar_defs::ControlPage;
42use sidecar_defs::CpuStatus;
43use sidecar_defs::PAGE_SIZE;
44use sidecar_defs::PER_VP_PAGES;
45use sidecar_defs::PER_VP_SHMEM_PAGES;
46use sidecar_defs::SidecarNodeOutput;
47use sidecar_defs::SidecarNodeParams;
48use sidecar_defs::SidecarOutput;
49use sidecar_defs::SidecarParams;
50use sidecar_defs::required_memory;
51use x86defs::Exception;
52use x86defs::GdtEntry;
53use x86defs::IdtAttributes;
54use x86defs::IdtEntry64;
55use x86defs::Pte;
56use zerocopy::FromZeros;
57
58unsafe extern "C" {
59 static IMAGE_PDE: Pte;
60}
61
62#[unsafe(naked)]
68unsafe extern "C" fn irq_entry() -> ! {
69 core::arch::naked_asm!(
70 "push rax",
71 "push rcx",
72 "push rdx",
73 "push rsi",
74 "push rdi",
75 "push r8",
76 "push r9",
77 "push r10",
78 "push r11",
79 "call {irq_handler}",
80 "pop r11",
81 "pop r10",
82 "pop r9",
83 "pop r8",
84 "pop rdi",
85 "pop rsi",
86 "pop rdx",
87 "pop rcx",
88 "pop rax",
89 "iretq",
90 irq_handler = sym super::irq_handler,
91 );
92}
93
94#[unsafe(naked)]
100unsafe extern "C" fn exc_gpf() -> ! {
101 core::arch::naked_asm!(
102 "mov rdi, 0xd",
103 "mov rsi, rsp",
104 "jmp {exception_handler}",
105 exception_handler = sym super::exception_handler,
106 );
107}
108
109#[unsafe(naked)]
115unsafe extern "C" fn exc_pf() -> ! {
116 core::arch::naked_asm!(
117 "mov rdi, 0xe",
118 "mov rsi, rsp",
119 "jmp {exception_handler}",
120 exception_handler = sym super::exception_handler,
121 );
122}
123
124static GDT: [GdtEntry; 4] = {
125 let default_data_attributes = x86defs::X64_DEFAULT_DATA_SEGMENT_ATTRIBUTES.as_bits();
126 let default_code_attributes = x86defs::X64_DEFAULT_CODE_SEGMENT_ATTRIBUTES.as_bits();
127 let zero = GdtEntry {
128 limit_low: 0,
129 base_low: 0,
130 base_middle: 0,
131 attr_low: 0,
132 attr_high: 0,
133 base_high: 0,
134 };
135
136 [
137 zero,
138 zero,
139 GdtEntry {
140 limit_low: 0xffff,
141 attr_low: default_code_attributes as u8,
142 attr_high: (default_code_attributes >> 8) as u8,
143 ..zero
144 },
145 GdtEntry {
146 limit_low: 0xffff,
147 attr_low: default_data_attributes as u8,
148 attr_high: (default_data_attributes >> 8) as u8,
149 ..zero
150 },
151 ]
152};
153
154const IRQ: u8 = 0x20;
155
156static mut IDT: [IdtEntry64; IRQ as usize + 1] = {
157 let zero = IdtEntry64 {
158 offset_low: 0,
159 selector: 0,
160 attributes: IdtAttributes::new(),
161 offset_middle: 0,
162 offset_high: 0,
163 reserved: 0,
164 };
165 [zero; IRQ as usize + 1]
166};
167
168enum InitError {
169 RequiredMemory { required: u64, actual: u64 },
170 GetVsmCodePageOffset(HvError),
171 GetVsmCapabilities(HvError),
172}
173
174impl Display for InitError {
175 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176 match self {
177 InitError::RequiredMemory { required, actual } => {
178 write!(
179 f,
180 "failed to provide required memory: {:#x}, actual: {:#x}",
181 required, actual
182 )
183 }
184 InitError::GetVsmCodePageOffset(err) => {
185 write!(f, "failed to get vsm code page offset: {err}")
186 }
187 InitError::GetVsmCapabilities(err) => {
188 write!(f, "failed to get vsm capabilities: {err}")
189 }
190 }
191 }
192}
193
194enum InitVpError {
195 EnableVtl2(HvError),
196 StartVp(HvError),
197}
198
199impl Display for InitVpError {
200 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
201 match self {
202 InitVpError::EnableVtl2(err) => write!(f, "failed to enable vtl2: {err}"),
203 InitVpError::StartVp(err) => write!(f, "failed to start vp: {err}"),
204 }
205 }
206}
207
208#[cfg_attr(not(minimal_rt), expect(dead_code))]
211pub extern "C" fn start(params: u64, output: u64) -> bool {
212 enlightened_panic::enable_enlightened_panic();
213
214 let [mut params_mapper, mut output_mapper, mut temp_mapper] = [0, 1, 2].map(|i| {
215 unsafe { temporary_map::Mapper::new(i) }
217 });
218 let params = unsafe { params_mapper.map::<SidecarParams>(params) };
221 let mut output = unsafe { output_mapper.map::<SidecarOutput>(output) };
224 match init(&mut temp_mapper, ¶ms, &mut output) {
225 Ok(()) => {
226 AFTER_INIT.store(true, Release);
227 true
228 }
229 Err(err) => {
230 let _ = write!(CommandErrorWriter(&mut output.error), "{err}");
231 false
232 }
233 }
234}
235
236fn init(
238 mapper: &mut temporary_map::Mapper,
239 params: &SidecarParams,
240 output: &mut SidecarOutput,
241) -> Result<(), InitError> {
242 let &SidecarParams {
243 hypercall_page,
244 enable_logging,
245 node_count,
246 ref nodes,
247 ref initial_state,
248 } = params;
249
250 ENABLE_LOG.store(enable_logging, Relaxed);
251 let nodes = &nodes[..node_count as usize];
252
253 {
256 let hypercall_page = unsafe { mapper.map::<[u8; 4096]>(hypercall_page) };
259 unsafe { (&raw mut HYPERCALL_PAGE).copy_from_nonoverlapping(&*hypercall_page, 1) };
261 }
262
263 {
265 let idt = unsafe { &mut *addr_of_mut!(IDT) };
267
268 let offset = exc_pf as *const () as u64;
269 idt[Exception::PAGE_FAULT.0 as usize] = IdtEntry64 {
270 offset_low: offset as u16,
271 selector: 2 * 8,
272 attributes: IdtAttributes::new().with_present(false).with_gate_type(0xf),
273 offset_middle: (offset >> 16) as u16,
274 offset_high: (offset >> 32) as u32,
275 reserved: 0,
276 };
277
278 let offset = exc_gpf as *const () as u64;
279 idt[Exception::GENERAL_PROTECTION_FAULT.0 as usize] = IdtEntry64 {
280 offset_low: offset as u16,
281 selector: 2 * 8,
282 attributes: IdtAttributes::new().with_present(false).with_gate_type(0xf),
283 offset_middle: (offset >> 16) as u16,
284 offset_high: (offset >> 32) as u32,
285 reserved: 0,
286 };
287
288 let offset = irq_entry as *const () as u64;
289 idt[IRQ as usize] = IdtEntry64 {
290 offset_low: offset as u16,
291 selector: 2 * 8,
292 attributes: IdtAttributes::new().with_present(true).with_gate_type(0xe),
293 offset_middle: (offset >> 16) as u16,
294 offset_high: (offset >> 32) as u32,
295 reserved: 0,
296 };
297 }
298
299 {
301 let value = HvRegisterVsmCodePageOffsets::from(
302 get_hv_vp_register(
303 HvInputVtl::CURRENT_VTL,
304 HvX64RegisterName::VsmCodePageOffsets.into(),
305 )
306 .map_err(InitError::GetVsmCodePageOffset)?
307 .as_u64(),
308 );
309 unsafe { VTL_RETURN_OFFSET = value.return_offset() }
311 }
312
313 {
315 let value = get_hv_vp_register(
316 HvInputVtl::CURRENT_VTL,
317 HvX64RegisterName::VsmCapabilities.into(),
318 )
319 .map_err(InitError::GetVsmCapabilities)?;
320 unsafe { VSM_CAPABILITIES = value.as_u64().into() }
322 }
323
324 let node_init = unsafe { &mut *addr_of_mut!(NODE_INIT) };
326
327 for (node_index, (node, node_output)) in nodes.iter().zip(&mut output.nodes).enumerate() {
329 let &SidecarNodeParams {
330 memory_base,
331 memory_size,
332 base_vp,
333 vp_count,
334 } = node;
335 let memory = MemoryRange::new(memory_base..memory_base + memory_size);
336
337 log!("node {node_index}: {vp_count} VPs starting at VP {base_vp}, memory {memory}");
338
339 let required = required_memory(vp_count) as u64;
340 if memory_size < required {
341 return Err(InitError::RequiredMemory {
342 required,
343 actual: memory_size,
344 });
345 }
346
347 let (control_page_range, memory) = memory.split_at_offset(PAGE_SIZE as u64);
348 let (shmem_pages, memory) =
349 memory.split_at_offset(vp_count as u64 * PER_VP_SHMEM_PAGES as u64 * PAGE_SIZE as u64);
350
351 *node_output = SidecarNodeOutput {
352 control_page: control_page_range.start(),
353 shmem_pages_base: shmem_pages.start(),
354 shmem_pages_size: shmem_pages.len(),
355 };
356
357 {
359 let mut control = unsafe { mapper.map::<ControlPage>(control_page_range.start()) };
362 let ControlPage {
363 index,
364 base_cpu,
365 cpu_count,
366 request_vector,
367 response_cpu,
368 response_vector,
369 needs_attention,
370 reserved,
371 cpu_status,
372 } = &mut *control;
373 *index = (node_index as u32).into();
374 *base_cpu = base_vp.into();
375 *cpu_count = vp_count.into();
376 *request_vector = (IRQ as u32).into();
377 *response_cpu = 0.into();
378 *response_vector = 0.into();
379 *needs_attention = 0.into();
380 reserved.fill(0);
381 cpu_status[0] = CpuStatus::REMOVED.0.into();
384 cpu_status[1..vp_count as usize].fill_with(|| CpuStatus::RUN.0.into());
385 cpu_status[vp_count as usize..].fill_with(|| CpuStatus::REMOVED.0.into());
386
387 if initial_state.per_cpu_state_specified {
392 log!(
393 "node {node_index}: applying per-cpu overrides, base_vp={base_vp}, vp_count={vp_count}"
394 );
395 let overrides = &initial_state.sidecar_starts_cpu
396 [base_vp as usize..(base_vp + vp_count) as usize];
397 for (i, &should_start) in overrides.iter().enumerate() {
398 cpu_status[i] = if should_start {
399 CpuStatus::RUN.0.into()
400 } else {
401 let vp = base_vp + i as u32;
402 log!("node {node_index}: VP {vp} (idx {i}) -> REMOVED");
403 CpuStatus::REMOVED.0.into()
404 };
405 }
406 }
407
408 if !cpu_status[1..vp_count as usize]
415 .iter()
416 .any(|status| status.load(Relaxed) == CpuStatus::RUN.0)
417 {
418 panic!(
419 "sidecar node {node_index} (base_vp={base_vp}, vp_count={vp_count}) has no sidecar-started APs"
420 );
421 }
422 }
423
424 node_init.push(NodeInit {
425 node: NodeDefinition {
426 base_vp,
427 vp_count,
428 control_page_pa: control_page_range.start(),
429 shmem_pages,
430 memory,
431 },
432 next_vp: AtomicU32::new(1), });
434 }
435
436 let node_init = unsafe { &*addr_of!(NODE_INIT) };
441 start_aps(node_init, mapper);
442
443 {
445 for (node, output) in nodes.iter().zip(&output.nodes) {
446 let control = unsafe { mapper.map::<ControlPage>(output.control_page) };
449 for status in &control.cpu_status[0..node.vp_count as usize] {
450 while status.load(Acquire) == CpuStatus::RUN.0 {
451 spin_loop();
452 }
453 }
454 }
455 }
456
457 Ok(())
458}
459
460struct NodeInit {
461 node: NodeDefinition,
462 next_vp: AtomicU32,
463}
464
465static mut NODE_INIT: ArrayVec<NodeInit, { sidecar_defs::MAX_NODES }> = ArrayVec::new_const();
466
467fn start_aps(node_init: &[NodeInit], mapper: &mut temporary_map::Mapper) {
468 for node in node_init {
469 loop {
470 let node_cpu_index = node.next_vp.fetch_add(1, Relaxed);
471 assert!(node_cpu_index != u32::MAX);
472 if node_cpu_index >= node.node.vp_count {
473 break;
474 }
475
476 let is_removed = {
479 let control = unsafe { mapper.map::<ControlPage>(node.node.control_page_pa) };
481 control.cpu_status[node_cpu_index as usize].load(Relaxed) == CpuStatus::REMOVED.0
482 };
483
484 let vp = node.node.base_vp + node_cpu_index;
485 if is_removed {
486 log!("start_aps: skipping VP {vp} (idx {node_cpu_index}): REMOVED");
487 continue;
488 }
489
490 match node.node.start(mapper, node_cpu_index) {
491 Ok(()) => {}
492 Err(err) => panic!("failed to start VP {vp}: {err}"),
493 }
494 }
495 }
496}
497
498unsafe fn ap_init() -> ! {
501 {
503 let node_init = unsafe { &*addr_of!(NODE_INIT) };
505 let mut mapper = unsafe { temporary_map::Mapper::new(0) };
507 start_aps(node_init, &mut mapper)
508 }
509 unsafe { super::vp::ap_entry() }
511}
512
513struct NodeDefinition {
514 base_vp: u32,
515 vp_count: u32,
516 control_page_pa: u64,
517 shmem_pages: MemoryRange,
518 memory: MemoryRange,
519}
520
521impl NodeDefinition {
522 fn start(
523 &self,
524 mapper: &mut temporary_map::Mapper,
525 node_cpu_index: u32,
526 ) -> Result<(), InitVpError> {
527 let hv_vp_index = self.base_vp + node_cpu_index;
528
529 let shmem_pages = self.shmem_pages.start()
530 + node_cpu_index as u64 * PER_VP_SHMEM_PAGES as u64 * PAGE_SIZE as u64;
531 let command_page_pa = shmem_pages;
532 let reg_page_pa = shmem_pages + PAGE_SIZE as u64;
533 let memory_start =
534 self.memory.start() + node_cpu_index as u64 * PER_VP_PAGES as u64 * PAGE_SIZE as u64;
535 let memory =
536 MemoryRange::new(memory_start..memory_start + PER_VP_PAGES as u64 * PAGE_SIZE as u64);
537
538 let mut memory = AlignedSubranges::new(memory)
539 .with_max_range_len(PAGE_SIZE as u64)
540 .map(|r| r.start());
541 let pml4_pa = memory.next().unwrap();
542 let pdpt_pa = memory.next().unwrap();
543 let pd_pa = memory.next().unwrap();
544 let pt_pa = memory.next().unwrap();
545
546 let pte_table = |addr| {
547 Pte::new()
548 .with_address(addr)
549 .with_read_write(true)
550 .with_present(true)
551 };
552
553 {
554 let mut pml4 = unsafe { mapper.map::<[Pte; 512]>(pml4_pa) };
557 pml4[511] = pte_table(pdpt_pa);
558 }
559 {
560 let mut pdpt = unsafe { mapper.map::<Pte>(pdpt_pa) };
563 *pdpt = pte_table(pd_pa);
564 }
565 {
566 let mut pd = unsafe { mapper.map::<[Pte; 512]>(pd_pa) };
569 pd[0] = unsafe { IMAGE_PDE };
571 pd[1] = pte_table(pt_pa);
572 }
573 let globals_pa = {
574 let mut pt = unsafe { mapper.map::<[Pte; 512]>(pt_pa) };
577 addr_space::init_ap(
578 &mut pt,
579 pt_pa,
580 self.control_page_pa,
581 command_page_pa,
582 reg_page_pa,
583 &mut memory,
584 )
585 };
586 {
587 let mut globals = unsafe { mapper.map::<MaybeUninit<VpGlobals>>(globals_pa) };
590 globals.write(VpGlobals {
591 hv_vp_index,
592 node_cpu_index,
593 overlays_mapped: false,
594 register_page_mapped: false,
595 });
596 }
597
598 let cs = HvX64SegmentRegister {
599 base: 0,
600 limit: !0,
601 selector: 2 * 8,
602 attributes: x86defs::X64_DEFAULT_CODE_SEGMENT_ATTRIBUTES.into(),
603 };
604 let ds = HvX64SegmentRegister {
605 base: 0,
606 limit: !0,
607 selector: 3 * 8,
608 attributes: x86defs::X64_DEFAULT_DATA_SEGMENT_ATTRIBUTES.into(),
609 };
610 let gdtr = hvdef::HvX64TableRegister {
611 base: addr_of!(GDT) as u64,
612 limit: size_of_val(&GDT) as u16 - 1,
613 pad: [0; 3],
614 };
615 let idtr = hvdef::HvX64TableRegister {
616 base: addr_of!(IDT) as u64,
617 limit: size_of_val(unsafe { &*addr_of!(IDT) }) as u16 - 1,
619 pad: [0; 3],
620 };
621 let context = hvdef::hypercall::InitialVpContextX64 {
622 rip: ap_init as *const () as u64,
623 rsp: addr_space::stack().end() - 8, rflags: x86defs::RFlags::at_reset().into(),
625 cs,
626 ds,
627 es: ds,
628 fs: ds,
629 gs: ds,
630 ss: ds,
631 tr: HvX64SegmentRegister {
632 base: 0,
633 limit: 0xffff,
634 selector: 0,
635 attributes: x86defs::X64_BUSY_TSS_SEGMENT_ATTRIBUTES.into(),
636 },
637 ldtr: FromZeros::new_zeroed(),
638 idtr,
639 gdtr,
640 efer: x86defs::X64_EFER_LMA | x86defs::X64_EFER_LME | x86defs::X64_EFER_NXE,
641 cr0: x86defs::X64_CR0_PG | x86defs::X64_CR0_PE | x86defs::X64_CR0_NE,
642 cr3: pml4_pa,
643 cr4: x86defs::X64_CR4_PAE | x86defs::X64_CR4_MCE | x86defs::X64_CR4_FXSR,
644 msr_cr_pat: x86defs::X86X_MSR_DEFAULT_PAT,
645 };
646
647 {
648 let input_page = unsafe { &mut *addr_space::hypercall_input().cast() };
650 let EnableVpVtlX64 {
651 partition_id,
652 vp_index,
653 target_vtl,
654 reserved,
655 vp_vtl_context,
656 } = input_page;
657
658 *partition_id = hvdef::HV_PARTITION_ID_SELF;
659 *vp_index = hv_vp_index;
660 *target_vtl = hvdef::Vtl::Vtl2.into();
661 *vp_vtl_context = context;
662 *reserved = [0; 3];
663 }
664 match hypercall(HypercallCode::HvCallEnableVpVtl, 0) {
665 Ok(()) | Err(HvError::VtlAlreadyEnabled) => {}
666 Err(err) => return Err(InitVpError::EnableVtl2(err)),
667 }
668
669 {
670 let input_page = unsafe { &mut *addr_space::hypercall_input().cast() };
672 let StartVirtualProcessorX64 {
673 partition_id,
674 vp_index,
675 target_vtl,
676 rsvd0,
677 rsvd1,
678 vp_context,
679 } = input_page;
680
681 *partition_id = hvdef::HV_PARTITION_ID_SELF;
682 *vp_index = hv_vp_index;
683 *target_vtl = hvdef::Vtl::Vtl2.into();
684 *rsvd0 = 0;
685 *rsvd1 = 0;
686 *vp_context = context;
687 }
688 hypercall(HypercallCode::HvCallStartVirtualProcessor, 0).map_err(InitVpError::StartVp)?;
689
690 Ok(())
691 }
692}