xref: /cloud-hypervisor/vmm/src/cpu.rs (revision f6cd3bd86ded632da437b6dd6077f4237d2f71fe)
1 // Copyright © 2020, Oracle and/or its affiliates.
2 //
3 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 //
5 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
6 // Use of this source code is governed by a BSD-style license that can be
7 // found in the LICENSE-BSD-3-Clause file.
8 //
9 // Copyright © 2019 Intel Corporation
10 //
11 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
12 //
13 
14 use crate::config::CpusConfig;
15 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
16 use crate::coredump::{
17     CpuElf64Writable, CpuSegment, CpuState as DumpCpusState, DumpState, Elf64Writable,
18     GuestDebuggableError, NoteDescType, X86_64ElfPrStatus, X86_64UserRegs, COREDUMP_NAME_SIZE,
19     NT_PRSTATUS,
20 };
21 #[cfg(feature = "guest_debug")]
22 use crate::gdb::{get_raw_tid, Debuggable, DebuggableError};
23 #[cfg(target_arch = "x86_64")]
24 use crate::memory_manager::MemoryManager;
25 use crate::seccomp_filters::{get_seccomp_filter, Thread};
26 #[cfg(target_arch = "x86_64")]
27 use crate::vm::physical_bits;
28 use crate::GuestMemoryMmap;
29 use crate::CPU_MANAGER_SNAPSHOT_ID;
30 use acpi_tables::{aml, sdt::Sdt, Aml};
31 use anyhow::anyhow;
32 #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
33 use arch::aarch64::regs;
34 #[cfg(target_arch = "x86_64")]
35 use arch::x86_64::get_x2apic_id;
36 use arch::EntryPoint;
37 use arch::NumaNodes;
38 #[cfg(target_arch = "aarch64")]
39 use devices::gic::Gic;
40 use devices::interrupt_controller::InterruptController;
41 #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
42 use gdbstub_arch::aarch64::reg::AArch64CoreRegs as CoreRegs;
43 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
44 use gdbstub_arch::x86::reg::{X86SegmentRegs, X86_64CoreRegs as CoreRegs};
45 #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
46 use hypervisor::aarch64::StandardRegisters;
47 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
48 use hypervisor::arch::x86::msr_index;
49 #[cfg(target_arch = "x86_64")]
50 use hypervisor::arch::x86::CpuIdEntry;
51 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
52 use hypervisor::arch::x86::MsrEntry;
53 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
54 use hypervisor::arch::x86::{SpecialRegisters, StandardRegisters};
55 #[cfg(target_arch = "aarch64")]
56 use hypervisor::kvm::kvm_bindings;
57 #[cfg(all(target_arch = "aarch64", feature = "kvm"))]
58 use hypervisor::kvm::kvm_ioctls::Cap;
59 #[cfg(feature = "tdx")]
60 use hypervisor::kvm::{TdxExitDetails, TdxExitStatus};
61 #[cfg(target_arch = "x86_64")]
62 use hypervisor::CpuVendor;
63 use hypervisor::{CpuState, HypervisorCpuError, HypervisorType, VmExit, VmOps};
64 use libc::{c_void, siginfo_t};
65 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
66 use linux_loader::elf::Elf64_Nhdr;
67 use seccompiler::{apply_filter, SeccompAction};
68 use std::collections::BTreeMap;
69 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
70 use std::io::Write;
71 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
72 use std::mem::size_of;
73 use std::os::unix::thread::JoinHandleExt;
74 use std::sync::atomic::{AtomicBool, Ordering};
75 use std::sync::{Arc, Barrier, Mutex};
76 use std::{cmp, io, result, thread};
77 use thiserror::Error;
78 use tracer::trace_scoped;
79 use vm_device::BusDevice;
80 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
81 use vm_memory::ByteValued;
82 #[cfg(feature = "guest_debug")]
83 use vm_memory::{Bytes, GuestAddressSpace};
84 use vm_memory::{GuestAddress, GuestMemoryAtomic};
85 use vm_migration::{
86     snapshot_from_id, Migratable, MigratableError, Pausable, Snapshot, SnapshotData, Snapshottable,
87     Transportable,
88 };
89 use vmm_sys_util::eventfd::EventFd;
90 use vmm_sys_util::signal::{register_signal_handler, SIGRTMIN};
91 use zerocopy::AsBytes;
92 #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
93 /// Extract the specified bits of a 64-bit integer.
94 /// For example, to extrace 2 bits from offset 1 (zero based) of `6u64`,
95 /// following expression should return 3 (`0b11`):
96 /// `extract_bits_64!(0b0000_0110u64, 1, 2)`
97 ///
98 macro_rules! extract_bits_64 {
99     ($value: tt, $offset: tt, $length: tt) => {
100         ($value >> $offset) & (!0u64 >> (64 - $length))
101     };
102 }
103 
104 #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
105 macro_rules! extract_bits_64_without_offset {
106     ($value: tt, $length: tt) => {
107         $value & (!0u64 >> (64 - $length))
108     };
109 }
110 
111 pub const CPU_MANAGER_ACPI_SIZE: usize = 0xc;
112 
113 #[derive(Debug, Error)]
114 pub enum Error {
115     #[error("Error creating vCPU: {0}")]
116     VcpuCreate(#[source] anyhow::Error),
117 
118     #[error("Error running bCPU: {0}")]
119     VcpuRun(#[source] anyhow::Error),
120 
121     #[error("Error spawning vCPU thread: {0}")]
122     VcpuSpawn(#[source] io::Error),
123 
124     #[error("Error generating common CPUID: {0}")]
125     CommonCpuId(#[source] arch::Error),
126 
127     #[error("Error configuring vCPU: {0}")]
128     VcpuConfiguration(#[source] arch::Error),
129 
130     #[error("Still pending removed vcpu")]
131     VcpuPendingRemovedVcpu,
132 
133     #[cfg(target_arch = "aarch64")]
134     #[error("Error fetching preferred target: {0}")]
135     VcpuArmPreferredTarget(#[source] hypervisor::HypervisorVmError),
136 
137     #[cfg(target_arch = "aarch64")]
138     #[error("Error initialising vCPU: {0}")]
139     VcpuArmInit(#[source] hypervisor::HypervisorCpuError),
140 
141     #[error("Failed to join on vCPU threads: {0:?}")]
142     ThreadCleanup(std::boxed::Box<dyn std::any::Any + std::marker::Send>),
143 
144     #[error("Error adding CpuManager to MMIO bus: {0}")]
145     BusError(#[source] vm_device::BusError),
146 
147     #[error("Requested vCPUs exceed maximum")]
148     DesiredVCpuCountExceedsMax,
149 
150     #[error("Cannot create seccomp filter: {0}")]
151     CreateSeccompFilter(#[source] seccompiler::Error),
152 
153     #[error("Cannot apply seccomp filter: {0}")]
154     ApplySeccompFilter(#[source] seccompiler::Error),
155 
156     #[error("Error starting vCPU after restore: {0}")]
157     StartRestoreVcpu(#[source] anyhow::Error),
158 
159     #[error("Unexpected VmExit")]
160     UnexpectedVmExit,
161 
162     #[error("Failed to allocate MMIO address for CpuManager")]
163     AllocateMmmioAddress,
164 
165     #[cfg(feature = "tdx")]
166     #[error("Error initializing TDX: {0}")]
167     InitializeTdx(#[source] hypervisor::HypervisorCpuError),
168 
169     #[cfg(target_arch = "aarch64")]
170     #[error("Error initializing PMU: {0}")]
171     InitPmu(#[source] hypervisor::HypervisorCpuError),
172 
173     #[cfg(feature = "guest_debug")]
174     #[error("Error during CPU debug: {0}")]
175     CpuDebug(#[source] hypervisor::HypervisorCpuError),
176 
177     #[cfg(feature = "guest_debug")]
178     #[error("Error translating virtual address: {0}")]
179     TranslateVirtualAddress(#[source] anyhow::Error),
180 
181     #[cfg(target_arch = "x86_64")]
182     #[error("Error setting up AMX: {0}")]
183     AmxEnable(#[source] anyhow::Error),
184 
185     #[error("Maximum number of vCPUs exceeds host limit")]
186     MaximumVcpusExceeded,
187 
188     #[cfg(feature = "sev_snp")]
189     #[error("Failed to set sev control register: {0}")]
190     SetSevControlRegister(#[source] hypervisor::HypervisorCpuError),
191 
192     #[cfg(target_arch = "x86_64")]
193     #[error("Failed to inject NMI")]
194     NmiError(hypervisor::HypervisorCpuError),
195 }
196 pub type Result<T> = result::Result<T, Error>;
197 
198 #[cfg(target_arch = "x86_64")]
199 #[allow(dead_code)]
200 #[repr(packed)]
201 #[derive(AsBytes)]
202 struct LocalX2Apic {
203     pub r#type: u8,
204     pub length: u8,
205     pub _reserved: u16,
206     pub apic_id: u32,
207     pub flags: u32,
208     pub processor_id: u32,
209 }
210 
211 #[allow(dead_code)]
212 #[repr(packed)]
213 #[derive(Default, AsBytes)]
214 struct Ioapic {
215     pub r#type: u8,
216     pub length: u8,
217     pub ioapic_id: u8,
218     _reserved: u8,
219     pub apic_address: u32,
220     pub gsi_base: u32,
221 }
222 
223 #[cfg(target_arch = "aarch64")]
224 #[allow(dead_code)]
225 #[repr(packed)]
226 #[derive(AsBytes)]
227 struct GicC {
228     pub r#type: u8,
229     pub length: u8,
230     pub reserved0: u16,
231     pub cpu_interface_number: u32,
232     pub uid: u32,
233     pub flags: u32,
234     pub parking_version: u32,
235     pub performance_interrupt: u32,
236     pub parked_address: u64,
237     pub base_address: u64,
238     pub gicv_base_address: u64,
239     pub gich_base_address: u64,
240     pub vgic_interrupt: u32,
241     pub gicr_base_address: u64,
242     pub mpidr: u64,
243     pub proc_power_effi_class: u8,
244     pub reserved1: u8,
245     pub spe_overflow_interrupt: u16,
246 }
247 
248 #[cfg(target_arch = "aarch64")]
249 #[allow(dead_code)]
250 #[repr(packed)]
251 #[derive(AsBytes)]
252 struct GicD {
253     pub r#type: u8,
254     pub length: u8,
255     pub reserved0: u16,
256     pub gic_id: u32,
257     pub base_address: u64,
258     pub global_irq_base: u32,
259     pub version: u8,
260     pub reserved1: [u8; 3],
261 }
262 
263 #[cfg(target_arch = "aarch64")]
264 #[allow(dead_code)]
265 #[repr(packed)]
266 #[derive(AsBytes)]
267 struct GicR {
268     pub r#type: u8,
269     pub length: u8,
270     pub reserved: u16,
271     pub base_address: u64,
272     pub range_length: u32,
273 }
274 
275 #[cfg(target_arch = "aarch64")]
276 #[allow(dead_code)]
277 #[repr(packed)]
278 #[derive(AsBytes)]
279 struct GicIts {
280     pub r#type: u8,
281     pub length: u8,
282     pub reserved0: u16,
283     pub translation_id: u32,
284     pub base_address: u64,
285     pub reserved1: u32,
286 }
287 
288 #[cfg(target_arch = "aarch64")]
289 #[allow(dead_code)]
290 #[repr(packed)]
291 #[derive(AsBytes)]
292 struct ProcessorHierarchyNode {
293     pub r#type: u8,
294     pub length: u8,
295     pub reserved: u16,
296     pub flags: u32,
297     pub parent: u32,
298     pub acpi_processor_id: u32,
299     pub num_private_resources: u32,
300 }
301 
302 #[allow(dead_code)]
303 #[repr(packed)]
304 #[derive(Default, AsBytes)]
305 struct InterruptSourceOverride {
306     pub r#type: u8,
307     pub length: u8,
308     pub bus: u8,
309     pub source: u8,
310     pub gsi: u32,
311     pub flags: u16,
312 }
313 
314 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
315 macro_rules! round_up {
316     ($n:expr,$d:expr) => {
317         (($n / ($d + 1)) + 1) * $d
318     };
319 }
320 
321 /// A wrapper around creating and using a kvm-based VCPU.
322 pub struct Vcpu {
323     // The hypervisor abstracted CPU.
324     vcpu: Arc<dyn hypervisor::Vcpu>,
325     id: u8,
326     #[cfg(target_arch = "aarch64")]
327     mpidr: u64,
328     saved_state: Option<CpuState>,
329     #[cfg(target_arch = "x86_64")]
330     vendor: CpuVendor,
331 }
332 
333 impl Vcpu {
334     /// Constructs a new VCPU for `vm`.
335     ///
336     /// # Arguments
337     ///
338     /// * `id` - Represents the CPU number between [0, max vcpus).
339     /// * `vm` - The virtual machine this vcpu will get attached to.
340     /// * `vm_ops` - Optional object for exit handling.
341     /// * `cpu_vendor` - CPU vendor as reported by __cpuid(0x0)
342     pub fn new(
343         id: u8,
344         apic_id: u8,
345         vm: &Arc<dyn hypervisor::Vm>,
346         vm_ops: Option<Arc<dyn VmOps>>,
347         #[cfg(target_arch = "x86_64")] cpu_vendor: CpuVendor,
348     ) -> Result<Self> {
349         let vcpu = vm
350             .create_vcpu(apic_id, vm_ops)
351             .map_err(|e| Error::VcpuCreate(e.into()))?;
352         // Initially the cpuid per vCPU is the one supported by this VM.
353         Ok(Vcpu {
354             vcpu,
355             id,
356             #[cfg(target_arch = "aarch64")]
357             mpidr: 0,
358             saved_state: None,
359             #[cfg(target_arch = "x86_64")]
360             vendor: cpu_vendor,
361         })
362     }
363 
364     /// Configures a vcpu and should be called once per vcpu when created.
365     ///
366     /// # Arguments
367     ///
368     /// * `kernel_entry_point` - Kernel entry point address in guest memory and boot protocol used.
369     /// * `guest_memory` - Guest memory.
370     /// * `cpuid` - (x86_64) CpuId, wrapper over the `kvm_cpuid2` structure.
371     pub fn configure(
372         &mut self,
373         #[cfg(target_arch = "aarch64")] vm: &Arc<dyn hypervisor::Vm>,
374         boot_setup: Option<(EntryPoint, &GuestMemoryAtomic<GuestMemoryMmap>)>,
375         #[cfg(target_arch = "x86_64")] cpuid: Vec<CpuIdEntry>,
376         #[cfg(target_arch = "x86_64")] kvm_hyperv: bool,
377         #[cfg(target_arch = "x86_64")] topology: Option<(u8, u8, u8)>,
378     ) -> Result<()> {
379         #[cfg(target_arch = "aarch64")]
380         {
381             self.init(vm)?;
382             self.mpidr = arch::configure_vcpu(&self.vcpu, self.id, boot_setup)
383                 .map_err(Error::VcpuConfiguration)?;
384         }
385         info!("Configuring vCPU: cpu_id = {}", self.id);
386         #[cfg(target_arch = "x86_64")]
387         arch::configure_vcpu(
388             &self.vcpu,
389             self.id,
390             boot_setup,
391             cpuid,
392             kvm_hyperv,
393             self.vendor,
394             topology,
395         )
396         .map_err(Error::VcpuConfiguration)?;
397 
398         Ok(())
399     }
400 
401     /// Gets the MPIDR register value.
402     #[cfg(target_arch = "aarch64")]
403     pub fn get_mpidr(&self) -> u64 {
404         self.mpidr
405     }
406 
407     /// Gets the saved vCPU state.
408     #[cfg(target_arch = "aarch64")]
409     pub fn get_saved_state(&self) -> Option<CpuState> {
410         self.saved_state.clone()
411     }
412 
413     /// Initializes an aarch64 specific vcpu for booting Linux.
414     #[cfg(target_arch = "aarch64")]
415     pub fn init(&self, vm: &Arc<dyn hypervisor::Vm>) -> Result<()> {
416         let mut kvi: kvm_bindings::kvm_vcpu_init = kvm_bindings::kvm_vcpu_init::default();
417 
418         // This reads back the kernel's preferred target type.
419         vm.get_preferred_target(&mut kvi)
420             .map_err(Error::VcpuArmPreferredTarget)?;
421         // We already checked that the capability is supported.
422         kvi.features[0] |= 1 << kvm_bindings::KVM_ARM_VCPU_PSCI_0_2;
423         if vm
424             .as_any()
425             .downcast_ref::<hypervisor::kvm::KvmVm>()
426             .unwrap()
427             .check_extension(Cap::ArmPmuV3)
428         {
429             kvi.features[0] |= 1 << kvm_bindings::KVM_ARM_VCPU_PMU_V3;
430         }
431         // Non-boot cpus are powered off initially.
432         if self.id > 0 {
433             kvi.features[0] |= 1 << kvm_bindings::KVM_ARM_VCPU_POWER_OFF;
434         }
435         self.vcpu.vcpu_init(&kvi).map_err(Error::VcpuArmInit)
436     }
437 
438     /// Runs the VCPU until it exits, returning the reason.
439     ///
440     /// Note that the state of the VCPU and associated VM must be setup first for this to do
441     /// anything useful.
442     pub fn run(&self) -> std::result::Result<VmExit, HypervisorCpuError> {
443         self.vcpu.run()
444     }
445 
446     #[cfg(feature = "sev_snp")]
447     pub fn set_sev_control_register(&self, vmsa_pfn: u64) -> Result<()> {
448         self.vcpu
449             .set_sev_control_register(vmsa_pfn)
450             .map_err(Error::SetSevControlRegister)
451     }
452 }
453 
454 impl Pausable for Vcpu {}
455 impl Snapshottable for Vcpu {
456     fn id(&self) -> String {
457         self.id.to_string()
458     }
459 
460     fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> {
461         let saved_state = self
462             .vcpu
463             .state()
464             .map_err(|e| MigratableError::Snapshot(anyhow!("Could not get vCPU state {:?}", e)))?;
465 
466         self.saved_state = Some(saved_state.clone());
467 
468         Ok(Snapshot::from_data(SnapshotData::new_from_state(
469             &saved_state,
470         )?))
471     }
472 }
473 
474 pub struct CpuManager {
475     config: CpusConfig,
476     #[cfg_attr(target_arch = "aarch64", allow(dead_code))]
477     interrupt_controller: Option<Arc<Mutex<dyn InterruptController>>>,
478     #[cfg(target_arch = "x86_64")]
479     cpuid: Vec<CpuIdEntry>,
480     #[cfg_attr(target_arch = "aarch64", allow(dead_code))]
481     vm: Arc<dyn hypervisor::Vm>,
482     vcpus_kill_signalled: Arc<AtomicBool>,
483     vcpus_pause_signalled: Arc<AtomicBool>,
484     vcpus_kick_signalled: Arc<AtomicBool>,
485     exit_evt: EventFd,
486     #[cfg_attr(target_arch = "aarch64", allow(dead_code))]
487     reset_evt: EventFd,
488     #[cfg(feature = "guest_debug")]
489     vm_debug_evt: EventFd,
490     vcpu_states: Vec<VcpuState>,
491     selected_cpu: u8,
492     vcpus: Vec<Arc<Mutex<Vcpu>>>,
493     seccomp_action: SeccompAction,
494     vm_ops: Arc<dyn VmOps>,
495     #[cfg_attr(target_arch = "aarch64", allow(dead_code))]
496     acpi_address: Option<GuestAddress>,
497     proximity_domain_per_cpu: BTreeMap<u8, u32>,
498     affinity: BTreeMap<u8, Vec<usize>>,
499     dynamic: bool,
500     hypervisor: Arc<dyn hypervisor::Hypervisor>,
501     #[cfg(feature = "sev_snp")]
502     sev_snp_enabled: bool,
503 }
504 
505 const CPU_ENABLE_FLAG: usize = 0;
506 const CPU_INSERTING_FLAG: usize = 1;
507 const CPU_REMOVING_FLAG: usize = 2;
508 const CPU_EJECT_FLAG: usize = 3;
509 
510 const CPU_STATUS_OFFSET: u64 = 4;
511 const CPU_SELECTION_OFFSET: u64 = 0;
512 
513 impl BusDevice for CpuManager {
514     fn read(&mut self, _base: u64, offset: u64, data: &mut [u8]) {
515         // The Linux kernel, quite reasonably, doesn't zero the memory it gives us.
516         data.fill(0);
517 
518         match offset {
519             CPU_SELECTION_OFFSET => {
520                 data[0] = self.selected_cpu;
521             }
522             CPU_STATUS_OFFSET => {
523                 if self.selected_cpu < self.max_vcpus() {
524                     let state = &self.vcpu_states[usize::from(self.selected_cpu)];
525                     if state.active() {
526                         data[0] |= 1 << CPU_ENABLE_FLAG;
527                     }
528                     if state.inserting {
529                         data[0] |= 1 << CPU_INSERTING_FLAG;
530                     }
531                     if state.removing {
532                         data[0] |= 1 << CPU_REMOVING_FLAG;
533                     }
534                 } else {
535                     warn!("Out of range vCPU id: {}", self.selected_cpu);
536                 }
537             }
538             _ => {
539                 warn!(
540                     "Unexpected offset for accessing CPU manager device: {:#}",
541                     offset
542                 );
543             }
544         }
545     }
546 
547     fn write(&mut self, _base: u64, offset: u64, data: &[u8]) -> Option<Arc<Barrier>> {
548         match offset {
549             CPU_SELECTION_OFFSET => {
550                 self.selected_cpu = data[0];
551             }
552             CPU_STATUS_OFFSET => {
553                 if self.selected_cpu < self.max_vcpus() {
554                     let state = &mut self.vcpu_states[usize::from(self.selected_cpu)];
555                     // The ACPI code writes back a 1 to acknowledge the insertion
556                     if (data[0] & (1 << CPU_INSERTING_FLAG) == 1 << CPU_INSERTING_FLAG)
557                         && state.inserting
558                     {
559                         state.inserting = false;
560                     }
561                     // Ditto for removal
562                     if (data[0] & (1 << CPU_REMOVING_FLAG) == 1 << CPU_REMOVING_FLAG)
563                         && state.removing
564                     {
565                         state.removing = false;
566                     }
567                     // Trigger removal of vCPU
568                     if data[0] & (1 << CPU_EJECT_FLAG) == 1 << CPU_EJECT_FLAG {
569                         if let Err(e) = self.remove_vcpu(self.selected_cpu) {
570                             error!("Error removing vCPU: {:?}", e);
571                         }
572                     }
573                 } else {
574                     warn!("Out of range vCPU id: {}", self.selected_cpu);
575                 }
576             }
577             _ => {
578                 warn!(
579                     "Unexpected offset for accessing CPU manager device: {:#}",
580                     offset
581                 );
582             }
583         }
584         None
585     }
586 }
587 
588 #[derive(Default)]
589 struct VcpuState {
590     inserting: bool,
591     removing: bool,
592     pending_removal: Arc<AtomicBool>,
593     handle: Option<thread::JoinHandle<()>>,
594     kill: Arc<AtomicBool>,
595     vcpu_run_interrupted: Arc<AtomicBool>,
596     paused: Arc<AtomicBool>,
597 }
598 
599 impl VcpuState {
600     fn active(&self) -> bool {
601         self.handle.is_some()
602     }
603 
604     fn signal_thread(&self) {
605         if let Some(handle) = self.handle.as_ref() {
606             loop {
607                 // SAFETY: FFI call with correct arguments
608                 unsafe {
609                     libc::pthread_kill(handle.as_pthread_t() as _, SIGRTMIN());
610                 }
611                 if self.vcpu_run_interrupted.load(Ordering::SeqCst) {
612                     break;
613                 } else {
614                     // This is more effective than thread::yield_now() at
615                     // avoiding a priority inversion with the vCPU thread
616                     thread::sleep(std::time::Duration::from_millis(1));
617                 }
618             }
619         }
620     }
621 
622     fn join_thread(&mut self) -> Result<()> {
623         if let Some(handle) = self.handle.take() {
624             handle.join().map_err(Error::ThreadCleanup)?
625         }
626 
627         Ok(())
628     }
629 
630     fn unpark_thread(&self) {
631         if let Some(handle) = self.handle.as_ref() {
632             handle.thread().unpark()
633         }
634     }
635 }
636 
637 impl CpuManager {
638     #[allow(unused_variables)]
639     #[allow(clippy::too_many_arguments)]
640     pub fn new(
641         config: &CpusConfig,
642         vm: Arc<dyn hypervisor::Vm>,
643         exit_evt: EventFd,
644         reset_evt: EventFd,
645         #[cfg(feature = "guest_debug")] vm_debug_evt: EventFd,
646         hypervisor: &Arc<dyn hypervisor::Hypervisor>,
647         seccomp_action: SeccompAction,
648         vm_ops: Arc<dyn VmOps>,
649         #[cfg(feature = "tdx")] tdx_enabled: bool,
650         numa_nodes: &NumaNodes,
651         #[cfg(feature = "sev_snp")] sev_snp_enabled: bool,
652     ) -> Result<Arc<Mutex<CpuManager>>> {
653         if u32::from(config.max_vcpus) > hypervisor.get_max_vcpus() {
654             return Err(Error::MaximumVcpusExceeded);
655         }
656 
657         let mut vcpu_states = Vec::with_capacity(usize::from(config.max_vcpus));
658         vcpu_states.resize_with(usize::from(config.max_vcpus), VcpuState::default);
659         let hypervisor_type = hypervisor.hypervisor_type();
660         #[cfg(target_arch = "x86_64")]
661         let cpu_vendor = hypervisor.get_cpu_vendor();
662 
663         #[cfg(target_arch = "x86_64")]
664         if config.features.amx {
665             const ARCH_GET_XCOMP_GUEST_PERM: usize = 0x1024;
666             const ARCH_REQ_XCOMP_GUEST_PERM: usize = 0x1025;
667             const XFEATURE_XTILEDATA: usize = 18;
668             const XFEATURE_XTILEDATA_MASK: usize = 1 << XFEATURE_XTILEDATA;
669 
670             // SAFETY: the syscall is only modifying kernel internal
671             // data structures that the kernel is itself expected to safeguard.
672             let amx_tile = unsafe {
673                 libc::syscall(
674                     libc::SYS_arch_prctl,
675                     ARCH_REQ_XCOMP_GUEST_PERM,
676                     XFEATURE_XTILEDATA,
677                 )
678             };
679 
680             if amx_tile != 0 {
681                 return Err(Error::AmxEnable(anyhow!("Guest AMX usage not supported")));
682             } else {
683                 let mask: usize = 0;
684                 // SAFETY: the mask being modified (not marked mutable as it is
685                 // modified in unsafe only which is permitted) isn't in use elsewhere.
686                 let result = unsafe {
687                     libc::syscall(libc::SYS_arch_prctl, ARCH_GET_XCOMP_GUEST_PERM, &mask)
688                 };
689                 if result != 0 || (mask & XFEATURE_XTILEDATA_MASK) != XFEATURE_XTILEDATA_MASK {
690                     return Err(Error::AmxEnable(anyhow!("Guest AMX usage not supported")));
691                 }
692             }
693         }
694 
695         let proximity_domain_per_cpu: BTreeMap<u8, u32> = {
696             let mut cpu_list = Vec::new();
697             for (proximity_domain, numa_node) in numa_nodes.iter() {
698                 for cpu in numa_node.cpus.iter() {
699                     cpu_list.push((*cpu, *proximity_domain))
700                 }
701             }
702             cpu_list
703         }
704         .into_iter()
705         .collect();
706 
707         let affinity = if let Some(cpu_affinity) = config.affinity.as_ref() {
708             cpu_affinity
709                 .iter()
710                 .map(|a| (a.vcpu, a.host_cpus.clone()))
711                 .collect()
712         } else {
713             BTreeMap::new()
714         };
715 
716         #[cfg(feature = "tdx")]
717         let dynamic = !tdx_enabled;
718         #[cfg(not(feature = "tdx"))]
719         let dynamic = true;
720 
721         Ok(Arc::new(Mutex::new(CpuManager {
722             config: config.clone(),
723             interrupt_controller: None,
724             #[cfg(target_arch = "x86_64")]
725             cpuid: Vec::new(),
726             vm,
727             vcpus_kill_signalled: Arc::new(AtomicBool::new(false)),
728             vcpus_pause_signalled: Arc::new(AtomicBool::new(false)),
729             vcpus_kick_signalled: Arc::new(AtomicBool::new(false)),
730             vcpu_states,
731             exit_evt,
732             reset_evt,
733             #[cfg(feature = "guest_debug")]
734             vm_debug_evt,
735             selected_cpu: 0,
736             vcpus: Vec::with_capacity(usize::from(config.max_vcpus)),
737             seccomp_action,
738             vm_ops,
739             acpi_address: None,
740             proximity_domain_per_cpu,
741             affinity,
742             dynamic,
743             hypervisor: hypervisor.clone(),
744             #[cfg(feature = "sev_snp")]
745             sev_snp_enabled,
746         })))
747     }
748 
749     #[cfg(target_arch = "x86_64")]
750     pub fn populate_cpuid(
751         &mut self,
752         memory_manager: &Arc<Mutex<MemoryManager>>,
753         hypervisor: &Arc<dyn hypervisor::Hypervisor>,
754         #[cfg(feature = "tdx")] tdx: bool,
755     ) -> Result<()> {
756         let sgx_epc_sections = memory_manager
757             .lock()
758             .unwrap()
759             .sgx_epc_region()
760             .as_ref()
761             .map(|sgx_epc_region| sgx_epc_region.epc_sections().values().cloned().collect());
762 
763         self.cpuid = {
764             let phys_bits = physical_bits(hypervisor, self.config.max_phys_bits);
765             arch::generate_common_cpuid(
766                 hypervisor,
767                 &arch::CpuidConfig {
768                     sgx_epc_sections,
769                     phys_bits,
770                     kvm_hyperv: self.config.kvm_hyperv,
771                     #[cfg(feature = "tdx")]
772                     tdx,
773                     amx: self.config.features.amx,
774                 },
775             )
776             .map_err(Error::CommonCpuId)?
777         };
778 
779         Ok(())
780     }
781 
782     fn create_vcpu(&mut self, cpu_id: u8, snapshot: Option<Snapshot>) -> Result<Arc<Mutex<Vcpu>>> {
783         info!("Creating vCPU: cpu_id = {}", cpu_id);
784 
785         #[cfg(target_arch = "x86_64")]
786         let topology = self.get_vcpu_topology();
787         #[cfg(target_arch = "x86_64")]
788         let x2apic_id = arch::x86_64::get_x2apic_id(cpu_id as u32, topology);
789         #[cfg(target_arch = "aarch64")]
790         let x2apic_id = cpu_id as u32;
791 
792         let mut vcpu = Vcpu::new(
793             cpu_id,
794             x2apic_id as u8,
795             &self.vm,
796             Some(self.vm_ops.clone()),
797             #[cfg(target_arch = "x86_64")]
798             self.hypervisor.get_cpu_vendor(),
799         )?;
800 
801         if let Some(snapshot) = snapshot {
802             // AArch64 vCPUs should be initialized after created.
803             #[cfg(target_arch = "aarch64")]
804             vcpu.init(&self.vm)?;
805 
806             let state: CpuState = snapshot.to_state().map_err(|e| {
807                 Error::VcpuCreate(anyhow!("Could not get vCPU state from snapshot {:?}", e))
808             })?;
809             vcpu.vcpu
810                 .set_state(&state)
811                 .map_err(|e| Error::VcpuCreate(anyhow!("Could not set the vCPU state {:?}", e)))?;
812 
813             vcpu.saved_state = Some(state);
814         }
815 
816         let vcpu = Arc::new(Mutex::new(vcpu));
817 
818         // Adding vCPU to the CpuManager's vCPU list.
819         self.vcpus.push(vcpu.clone());
820 
821         Ok(vcpu)
822     }
823 
824     pub fn configure_vcpu(
825         &self,
826         vcpu: Arc<Mutex<Vcpu>>,
827         boot_setup: Option<(EntryPoint, &GuestMemoryAtomic<GuestMemoryMmap>)>,
828     ) -> Result<()> {
829         let mut vcpu = vcpu.lock().unwrap();
830 
831         #[cfg(feature = "sev_snp")]
832         if self.sev_snp_enabled {
833             if let Some((kernel_entry_point, _)) = boot_setup {
834                 vcpu.set_sev_control_register(
835                     kernel_entry_point.entry_addr.0 / crate::igvm::HV_PAGE_SIZE,
836                 )?;
837             }
838 
839             // Traditional way to configure vcpu doesn't work for SEV-SNP guests.
840             // All the vCPU configuration for SEV-SNP guest is provided via VMSA.
841             return Ok(());
842         }
843 
844         #[cfg(target_arch = "x86_64")]
845         assert!(!self.cpuid.is_empty());
846 
847         #[cfg(target_arch = "x86_64")]
848         let topology = self.config.topology.clone().map_or_else(
849             || {
850                 #[cfg(feature = "mshv")]
851                 if matches!(self.hypervisor.hypervisor_type(), HypervisorType::Mshv) {
852                     return Some((1, self.boot_vcpus(), 1));
853                 }
854                 None
855             },
856             |t| Some((t.threads_per_core, t.cores_per_die, t.dies_per_package)),
857         );
858         #[cfg(target_arch = "x86_64")]
859         vcpu.configure(
860             boot_setup,
861             self.cpuid.clone(),
862             self.config.kvm_hyperv,
863             topology,
864         )?;
865 
866         #[cfg(target_arch = "aarch64")]
867         vcpu.configure(&self.vm, boot_setup)?;
868 
869         Ok(())
870     }
871 
872     /// Only create new vCPUs if there aren't any inactive ones to reuse
873     fn create_vcpus(
874         &mut self,
875         desired_vcpus: u8,
876         snapshot: Option<Snapshot>,
877     ) -> Result<Vec<Arc<Mutex<Vcpu>>>> {
878         let mut vcpus: Vec<Arc<Mutex<Vcpu>>> = vec![];
879         info!(
880             "Request to create new vCPUs: desired = {}, max = {}, allocated = {}, present = {}",
881             desired_vcpus,
882             self.config.max_vcpus,
883             self.vcpus.len(),
884             self.present_vcpus()
885         );
886 
887         if desired_vcpus > self.config.max_vcpus {
888             return Err(Error::DesiredVCpuCountExceedsMax);
889         }
890 
891         // Only create vCPUs in excess of all the allocated vCPUs.
892         for cpu_id in self.vcpus.len() as u8..desired_vcpus {
893             vcpus.push(self.create_vcpu(
894                 cpu_id,
895                 // TODO: The special format of the CPU id can be removed once
896                 // ready to break live upgrade.
897                 snapshot_from_id(snapshot.as_ref(), cpu_id.to_string().as_str()),
898             )?);
899         }
900 
901         Ok(vcpus)
902     }
903 
904     #[cfg(target_arch = "aarch64")]
905     pub fn init_pmu(&self, irq: u32) -> Result<bool> {
906         for cpu in self.vcpus.iter() {
907             let cpu = cpu.lock().unwrap();
908             // Check if PMU attr is available, if not, log the information.
909             if cpu.vcpu.has_pmu_support() {
910                 cpu.vcpu.init_pmu(irq).map_err(Error::InitPmu)?;
911             } else {
912                 debug!(
913                     "PMU attribute is not supported in vCPU{}, skip PMU init!",
914                     cpu.id
915                 );
916                 return Ok(false);
917             }
918         }
919 
920         Ok(true)
921     }
922 
923     pub fn vcpus(&self) -> Vec<Arc<Mutex<Vcpu>>> {
924         self.vcpus.clone()
925     }
926 
927     fn start_vcpu(
928         &mut self,
929         vcpu: Arc<Mutex<Vcpu>>,
930         vcpu_id: u8,
931         vcpu_thread_barrier: Arc<Barrier>,
932         inserting: bool,
933     ) -> Result<()> {
934         let reset_evt = self.reset_evt.try_clone().unwrap();
935         let exit_evt = self.exit_evt.try_clone().unwrap();
936         #[cfg(feature = "kvm")]
937         let hypervisor_type = self.hypervisor.hypervisor_type();
938         #[cfg(feature = "guest_debug")]
939         let vm_debug_evt = self.vm_debug_evt.try_clone().unwrap();
940         let panic_exit_evt = self.exit_evt.try_clone().unwrap();
941         let vcpu_kill_signalled = self.vcpus_kill_signalled.clone();
942         let vcpu_pause_signalled = self.vcpus_pause_signalled.clone();
943         let vcpu_kick_signalled = self.vcpus_kick_signalled.clone();
944 
945         let vcpu_kill = self.vcpu_states[usize::from(vcpu_id)].kill.clone();
946         let vcpu_run_interrupted = self.vcpu_states[usize::from(vcpu_id)]
947             .vcpu_run_interrupted
948             .clone();
949         let panic_vcpu_run_interrupted = vcpu_run_interrupted.clone();
950         let vcpu_paused = self.vcpu_states[usize::from(vcpu_id)].paused.clone();
951 
952         // Prepare the CPU set the current vCPU is expected to run onto.
953         let cpuset = self.affinity.get(&vcpu_id).map(|host_cpus| {
954             // SAFETY: all zeros is a valid pattern
955             let mut cpuset: libc::cpu_set_t = unsafe { std::mem::zeroed() };
956             // SAFETY: FFI call, trivially safe
957             unsafe { libc::CPU_ZERO(&mut cpuset) };
958             for host_cpu in host_cpus {
959                 // SAFETY: FFI call, trivially safe
960                 unsafe { libc::CPU_SET(*host_cpu, &mut cpuset) };
961             }
962             cpuset
963         });
964 
965         // Retrieve seccomp filter for vcpu thread
966         let vcpu_seccomp_filter = get_seccomp_filter(
967             &self.seccomp_action,
968             Thread::Vcpu,
969             self.hypervisor.hypervisor_type(),
970         )
971         .map_err(Error::CreateSeccompFilter)?;
972 
973         #[cfg(target_arch = "x86_64")]
974         let interrupt_controller_clone = self.interrupt_controller.as_ref().cloned();
975 
976         info!("Starting vCPU: cpu_id = {}", vcpu_id);
977 
978         let handle = Some(
979             thread::Builder::new()
980                 .name(format!("vcpu{vcpu_id}"))
981                 .spawn(move || {
982                     // Schedule the thread to run on the expected CPU set
983                     if let Some(cpuset) = cpuset.as_ref() {
984                         // SAFETY: FFI call with correct arguments
985                         let ret = unsafe {
986                             libc::sched_setaffinity(
987                                 0,
988                                 std::mem::size_of::<libc::cpu_set_t>(),
989                                 cpuset as *const libc::cpu_set_t,
990                             )
991                         };
992 
993                         if ret != 0 {
994                             error!(
995                                 "Failed scheduling the vCPU {} on the expected CPU set: {}",
996                                 vcpu_id,
997                                 io::Error::last_os_error()
998                             );
999                             return;
1000                         }
1001                     }
1002 
1003                     // Apply seccomp filter for vcpu thread.
1004                     if !vcpu_seccomp_filter.is_empty() {
1005                         if let Err(e) =
1006                             apply_filter(&vcpu_seccomp_filter).map_err(Error::ApplySeccompFilter)
1007                         {
1008                             error!("Error applying seccomp filter: {:?}", e);
1009                             return;
1010                         }
1011                     }
1012                     extern "C" fn handle_signal(_: i32, _: *mut siginfo_t, _: *mut c_void) {}
1013                     // This uses an async signal safe handler to kill the vcpu handles.
1014                     register_signal_handler(SIGRTMIN(), handle_signal)
1015                         .expect("Failed to register vcpu signal handler");
1016                     // Block until all CPUs are ready.
1017                     vcpu_thread_barrier.wait();
1018 
1019                     std::panic::catch_unwind(move || {
1020                         loop {
1021                             // If we are being told to pause, we park the thread
1022                             // until the pause boolean is toggled.
1023                             // The resume operation is responsible for toggling
1024                             // the boolean and unpark the thread.
1025                             // We enter a loop because park() could spuriously
1026                             // return. We will then park() again unless the
1027                             // pause boolean has been toggled.
1028 
1029                             // Need to use Ordering::SeqCst as we have multiple
1030                             // loads and stores to different atomics and we need
1031                             // to see them in a consistent order in all threads
1032 
1033                             if vcpu_pause_signalled.load(Ordering::SeqCst) {
1034                                 // As a pause can be caused by PIO & MMIO exits then we need to ensure they are
1035                                 // completed by returning to KVM_RUN. From the kernel docs:
1036                                 //
1037                                 // For KVM_EXIT_IO, KVM_EXIT_MMIO, KVM_EXIT_OSI, KVM_EXIT_PAPR, KVM_EXIT_XEN,
1038                                 // KVM_EXIT_EPR, KVM_EXIT_X86_RDMSR and KVM_EXIT_X86_WRMSR the corresponding
1039                                 // operations are complete (and guest state is consistent) only after userspace
1040                                 // has re-entered the kernel with KVM_RUN.  The kernel side will first finish
1041                                 // incomplete operations and then check for pending signals.
1042                                 // The pending state of the operation is not preserved in state which is
1043                                 // visible to userspace, thus userspace should ensure that the operation is
1044                                 // completed before performing a live migration.  Userspace can re-enter the
1045                                 // guest with an unmasked signal pending or with the immediate_exit field set
1046                                 // to complete pending operations without allowing any further instructions
1047                                 // to be executed.
1048 
1049                                 #[cfg(feature = "kvm")]
1050                                 if matches!(hypervisor_type, HypervisorType::Kvm) {
1051                                     vcpu.lock().as_ref().unwrap().vcpu.set_immediate_exit(true);
1052                                     if !matches!(vcpu.lock().unwrap().run(), Ok(VmExit::Ignore)) {
1053                                         error!("Unexpected VM exit on \"immediate_exit\" run");
1054                                         break;
1055                                     }
1056                                     vcpu.lock().as_ref().unwrap().vcpu.set_immediate_exit(false);
1057                                 }
1058 
1059                                 vcpu_run_interrupted.store(true, Ordering::SeqCst);
1060 
1061                                 vcpu_paused.store(true, Ordering::SeqCst);
1062                                 while vcpu_pause_signalled.load(Ordering::SeqCst) {
1063                                     thread::park();
1064                                 }
1065                                 vcpu_run_interrupted.store(false, Ordering::SeqCst);
1066                             }
1067 
1068                             if vcpu_kick_signalled.load(Ordering::SeqCst) {
1069                                 vcpu_run_interrupted.store(true, Ordering::SeqCst);
1070                                 #[cfg(target_arch = "x86_64")]
1071                                 match vcpu.lock().as_ref().unwrap().vcpu.nmi() {
1072                                     Ok(()) => {},
1073                                     Err(e) => {
1074                                         error!("Error when inject nmi {}", e);
1075                                         break;
1076                                     }
1077                                 }
1078                             }
1079 
1080                             // We've been told to terminate
1081                             if vcpu_kill_signalled.load(Ordering::SeqCst)
1082                                 || vcpu_kill.load(Ordering::SeqCst)
1083                             {
1084                                 vcpu_run_interrupted.store(true, Ordering::SeqCst);
1085                                 break;
1086                             }
1087 
1088                             #[cfg(feature = "tdx")]
1089                             let mut vcpu = vcpu.lock().unwrap();
1090                             #[cfg(not(feature = "tdx"))]
1091                             let vcpu = vcpu.lock().unwrap();
1092                             // vcpu.run() returns false on a triple-fault so trigger a reset
1093                             match vcpu.run() {
1094                                 Ok(run) => match run {
1095                                     #[cfg(feature = "kvm")]
1096                                     VmExit::Debug => {
1097                                         info!("VmExit::Debug");
1098                                         #[cfg(feature = "guest_debug")]
1099                                         {
1100                                             vcpu_pause_signalled.store(true, Ordering::SeqCst);
1101                                             let raw_tid = get_raw_tid(vcpu_id as usize);
1102                                             vm_debug_evt.write(raw_tid as u64).unwrap();
1103                                         }
1104                                     }
1105                                     #[cfg(target_arch = "x86_64")]
1106                                     VmExit::IoapicEoi(vector) => {
1107                                         if let Some(interrupt_controller) =
1108                                             &interrupt_controller_clone
1109                                         {
1110                                             interrupt_controller
1111                                                 .lock()
1112                                                 .unwrap()
1113                                                 .end_of_interrupt(vector);
1114                                         }
1115                                     }
1116                                     VmExit::Ignore => {}
1117                                     VmExit::Hyperv => {}
1118                                     VmExit::Reset => {
1119                                         info!("VmExit::Reset");
1120                                         vcpu_run_interrupted.store(true, Ordering::SeqCst);
1121                                         reset_evt.write(1).unwrap();
1122                                         break;
1123                                     }
1124                                     VmExit::Shutdown => {
1125                                         info!("VmExit::Shutdown");
1126                                         vcpu_run_interrupted.store(true, Ordering::SeqCst);
1127                                         exit_evt.write(1).unwrap();
1128                                         break;
1129                                     }
1130                                     #[cfg(feature = "tdx")]
1131                                     VmExit::Tdx => {
1132                                         if let Some(vcpu) = Arc::get_mut(&mut vcpu.vcpu) {
1133                                             match vcpu.get_tdx_exit_details() {
1134                                                 Ok(details) => match details {
1135                                                     TdxExitDetails::GetQuote => warn!("TDG_VP_VMCALL_GET_QUOTE not supported"),
1136                                                     TdxExitDetails::SetupEventNotifyInterrupt => {
1137                                                         warn!("TDG_VP_VMCALL_SETUP_EVENT_NOTIFY_INTERRUPT not supported")
1138                                                     }
1139                                                 },
1140                                                 Err(e) => error!("Unexpected TDX VMCALL: {}", e),
1141                                             }
1142                                             vcpu.set_tdx_status(TdxExitStatus::InvalidOperand);
1143                                         } else {
1144                                             // We should never reach this code as
1145                                             // this means the design from the code
1146                                             // is wrong.
1147                                             unreachable!("Couldn't get a mutable reference from Arc<dyn Vcpu> as there are multiple instances");
1148                                         }
1149                                     }
1150                                 },
1151 
1152                                 Err(e) => {
1153                                     error!("VCPU generated error: {:?}", Error::VcpuRun(e.into()));
1154                                     vcpu_run_interrupted.store(true, Ordering::SeqCst);
1155                                     exit_evt.write(1).unwrap();
1156                                     break;
1157                                 }
1158                             }
1159 
1160                             // We've been told to terminate
1161                             if vcpu_kill_signalled.load(Ordering::SeqCst)
1162                                 || vcpu_kill.load(Ordering::SeqCst)
1163                             {
1164                                 vcpu_run_interrupted.store(true, Ordering::SeqCst);
1165                                 break;
1166                             }
1167                         }
1168                     })
1169                     .or_else(|_| {
1170                         panic_vcpu_run_interrupted.store(true, Ordering::SeqCst);
1171                         error!("vCPU thread panicked");
1172                         panic_exit_evt.write(1)
1173                     })
1174                     .ok();
1175                 })
1176                 .map_err(Error::VcpuSpawn)?,
1177         );
1178 
1179         // On hot plug calls into this function entry_point is None. It is for
1180         // those hotplug CPU additions that we need to set the inserting flag.
1181         self.vcpu_states[usize::from(vcpu_id)].handle = handle;
1182         self.vcpu_states[usize::from(vcpu_id)].inserting = inserting;
1183 
1184         Ok(())
1185     }
1186 
1187     /// Start up as many vCPUs threads as needed to reach `desired_vcpus`
1188     fn activate_vcpus(
1189         &mut self,
1190         desired_vcpus: u8,
1191         inserting: bool,
1192         paused: Option<bool>,
1193     ) -> Result<()> {
1194         if desired_vcpus > self.config.max_vcpus {
1195             return Err(Error::DesiredVCpuCountExceedsMax);
1196         }
1197 
1198         let vcpu_thread_barrier = Arc::new(Barrier::new(
1199             (desired_vcpus - self.present_vcpus() + 1) as usize,
1200         ));
1201 
1202         if let Some(paused) = paused {
1203             self.vcpus_pause_signalled.store(paused, Ordering::SeqCst);
1204         }
1205 
1206         info!(
1207             "Starting vCPUs: desired = {}, allocated = {}, present = {}, paused = {}",
1208             desired_vcpus,
1209             self.vcpus.len(),
1210             self.present_vcpus(),
1211             self.vcpus_pause_signalled.load(Ordering::SeqCst)
1212         );
1213 
1214         // This reuses any inactive vCPUs as well as any that were newly created
1215         for vcpu_id in self.present_vcpus()..desired_vcpus {
1216             let vcpu = Arc::clone(&self.vcpus[vcpu_id as usize]);
1217             self.start_vcpu(vcpu, vcpu_id, vcpu_thread_barrier.clone(), inserting)?;
1218         }
1219 
1220         // Unblock all CPU threads.
1221         vcpu_thread_barrier.wait();
1222         Ok(())
1223     }
1224 
1225     fn mark_vcpus_for_removal(&mut self, desired_vcpus: u8) {
1226         // Mark vCPUs for removal, actual removal happens on ejection
1227         for cpu_id in desired_vcpus..self.present_vcpus() {
1228             self.vcpu_states[usize::from(cpu_id)].removing = true;
1229             self.vcpu_states[usize::from(cpu_id)]
1230                 .pending_removal
1231                 .store(true, Ordering::SeqCst);
1232         }
1233     }
1234 
1235     pub fn check_pending_removed_vcpu(&mut self) -> bool {
1236         for state in self.vcpu_states.iter() {
1237             if state.active() && state.pending_removal.load(Ordering::SeqCst) {
1238                 return true;
1239             }
1240         }
1241         false
1242     }
1243 
1244     fn remove_vcpu(&mut self, cpu_id: u8) -> Result<()> {
1245         info!("Removing vCPU: cpu_id = {}", cpu_id);
1246         let state = &mut self.vcpu_states[usize::from(cpu_id)];
1247         state.kill.store(true, Ordering::SeqCst);
1248         state.signal_thread();
1249         state.join_thread()?;
1250         state.handle = None;
1251 
1252         // Once the thread has exited, clear the "kill" so that it can reused
1253         state.kill.store(false, Ordering::SeqCst);
1254         state.pending_removal.store(false, Ordering::SeqCst);
1255 
1256         Ok(())
1257     }
1258 
1259     pub fn create_boot_vcpus(
1260         &mut self,
1261         snapshot: Option<Snapshot>,
1262     ) -> Result<Vec<Arc<Mutex<Vcpu>>>> {
1263         trace_scoped!("create_boot_vcpus");
1264 
1265         self.create_vcpus(self.boot_vcpus(), snapshot)
1266     }
1267 
1268     // Starts all the vCPUs that the VM is booting with. Blocks until all vCPUs are running.
1269     pub fn start_boot_vcpus(&mut self, paused: bool) -> Result<()> {
1270         self.activate_vcpus(self.boot_vcpus(), false, Some(paused))
1271     }
1272 
1273     pub fn start_restored_vcpus(&mut self) -> Result<()> {
1274         self.activate_vcpus(self.vcpus.len() as u8, false, Some(true))
1275             .map_err(|e| {
1276                 Error::StartRestoreVcpu(anyhow!("Failed to start restored vCPUs: {:#?}", e))
1277             })?;
1278 
1279         Ok(())
1280     }
1281 
1282     pub fn resize(&mut self, desired_vcpus: u8) -> Result<bool> {
1283         if desired_vcpus.cmp(&self.present_vcpus()) == cmp::Ordering::Equal {
1284             return Ok(false);
1285         }
1286 
1287         if !self.dynamic {
1288             return Ok(false);
1289         }
1290 
1291         if self.check_pending_removed_vcpu() {
1292             return Err(Error::VcpuPendingRemovedVcpu);
1293         }
1294 
1295         match desired_vcpus.cmp(&self.present_vcpus()) {
1296             cmp::Ordering::Greater => {
1297                 let vcpus = self.create_vcpus(desired_vcpus, None)?;
1298                 for vcpu in vcpus {
1299                     self.configure_vcpu(vcpu, None)?
1300                 }
1301                 self.activate_vcpus(desired_vcpus, true, None)?;
1302                 Ok(true)
1303             }
1304             cmp::Ordering::Less => {
1305                 self.mark_vcpus_for_removal(desired_vcpus);
1306                 Ok(true)
1307             }
1308             _ => Ok(false),
1309         }
1310     }
1311 
1312     pub fn shutdown(&mut self) -> Result<()> {
1313         // Tell the vCPUs to stop themselves next time they go through the loop
1314         self.vcpus_kill_signalled.store(true, Ordering::SeqCst);
1315 
1316         // Toggle the vCPUs pause boolean
1317         self.vcpus_pause_signalled.store(false, Ordering::SeqCst);
1318 
1319         // Unpark all the VCPU threads.
1320         for state in self.vcpu_states.iter() {
1321             state.unpark_thread();
1322         }
1323 
1324         // Signal to the spawned threads (vCPUs and console signal handler). For the vCPU threads
1325         // this will interrupt the KVM_RUN ioctl() allowing the loop to check the boolean set
1326         // above.
1327         for state in self.vcpu_states.iter() {
1328             state.signal_thread();
1329         }
1330 
1331         // Wait for all the threads to finish. This removes the state from the vector.
1332         for mut state in self.vcpu_states.drain(..) {
1333             state.join_thread()?;
1334         }
1335 
1336         Ok(())
1337     }
1338 
1339     #[cfg(feature = "tdx")]
1340     pub fn initialize_tdx(&self, hob_address: u64) -> Result<()> {
1341         for vcpu in &self.vcpus {
1342             vcpu.lock()
1343                 .unwrap()
1344                 .vcpu
1345                 .tdx_init(hob_address)
1346                 .map_err(Error::InitializeTdx)?;
1347         }
1348         Ok(())
1349     }
1350 
1351     pub fn boot_vcpus(&self) -> u8 {
1352         self.config.boot_vcpus
1353     }
1354 
1355     pub fn max_vcpus(&self) -> u8 {
1356         self.config.max_vcpus
1357     }
1358 
1359     #[cfg(target_arch = "x86_64")]
1360     pub fn common_cpuid(&self) -> Vec<CpuIdEntry> {
1361         assert!(!self.cpuid.is_empty());
1362         self.cpuid.clone()
1363     }
1364 
1365     fn present_vcpus(&self) -> u8 {
1366         self.vcpu_states
1367             .iter()
1368             .fold(0, |acc, state| acc + state.active() as u8)
1369     }
1370 
1371     #[cfg(target_arch = "aarch64")]
1372     pub fn get_mpidrs(&self) -> Vec<u64> {
1373         self.vcpus
1374             .iter()
1375             .map(|cpu| cpu.lock().unwrap().get_mpidr())
1376             .collect()
1377     }
1378 
1379     #[cfg(target_arch = "aarch64")]
1380     pub fn get_saved_states(&self) -> Vec<CpuState> {
1381         self.vcpus
1382             .iter()
1383             .map(|cpu| cpu.lock().unwrap().get_saved_state().unwrap())
1384             .collect()
1385     }
1386 
1387     pub fn get_vcpu_topology(&self) -> Option<(u8, u8, u8)> {
1388         self.config
1389             .topology
1390             .clone()
1391             .map(|t| (t.threads_per_core, t.cores_per_die, t.packages))
1392     }
1393 
1394     pub fn create_madt(&self) -> Sdt {
1395         use crate::acpi;
1396         // This is also checked in the commandline parsing.
1397         assert!(self.config.boot_vcpus <= self.config.max_vcpus);
1398 
1399         let mut madt = Sdt::new(*b"APIC", 44, 5, *b"CLOUDH", *b"CHMADT  ", 1);
1400         #[cfg(target_arch = "x86_64")]
1401         {
1402             madt.write(36, arch::layout::APIC_START.0);
1403 
1404             for cpu in 0..self.config.max_vcpus {
1405                 let x2apic_id = get_x2apic_id(cpu.into(), self.get_vcpu_topology());
1406 
1407                 let lapic = LocalX2Apic {
1408                     r#type: acpi::ACPI_X2APIC_PROCESSOR,
1409                     length: 16,
1410                     processor_id: cpu.into(),
1411                     apic_id: x2apic_id,
1412                     flags: if cpu < self.config.boot_vcpus {
1413                         1 << MADT_CPU_ENABLE_FLAG
1414                     } else {
1415                         0
1416                     } | 1 << MADT_CPU_ONLINE_CAPABLE_FLAG,
1417                     _reserved: 0,
1418                 };
1419                 madt.append(lapic);
1420             }
1421 
1422             madt.append(Ioapic {
1423                 r#type: acpi::ACPI_APIC_IO,
1424                 length: 12,
1425                 ioapic_id: 0,
1426                 apic_address: arch::layout::IOAPIC_START.0 as u32,
1427                 gsi_base: 0,
1428                 ..Default::default()
1429             });
1430 
1431             madt.append(InterruptSourceOverride {
1432                 r#type: acpi::ACPI_APIC_XRUPT_OVERRIDE,
1433                 length: 10,
1434                 bus: 0,
1435                 source: 4,
1436                 gsi: 4,
1437                 flags: 0,
1438             });
1439         }
1440 
1441         #[cfg(target_arch = "aarch64")]
1442         {
1443             /* Notes:
1444              * Ignore Local Interrupt Controller Address at byte offset 36 of MADT table.
1445              */
1446 
1447             // See section 5.2.12.14 GIC CPU Interface (GICC) Structure in ACPI spec.
1448             for cpu in 0..self.config.boot_vcpus {
1449                 let vcpu = &self.vcpus[cpu as usize];
1450                 let mpidr = vcpu.lock().unwrap().get_mpidr();
1451                 /* ARMv8 MPIDR format:
1452                      Bits [63:40] Must be zero
1453                      Bits [39:32] Aff3 : Match Aff3 of target processor MPIDR
1454                      Bits [31:24] Must be zero
1455                      Bits [23:16] Aff2 : Match Aff2 of target processor MPIDR
1456                      Bits [15:8] Aff1 : Match Aff1 of target processor MPIDR
1457                      Bits [7:0] Aff0 : Match Aff0 of target processor MPIDR
1458                 */
1459                 let mpidr_mask = 0xff_00ff_ffff;
1460                 let gicc = GicC {
1461                     r#type: acpi::ACPI_APIC_GENERIC_CPU_INTERFACE,
1462                     length: 80,
1463                     reserved0: 0,
1464                     cpu_interface_number: cpu as u32,
1465                     uid: cpu as u32,
1466                     flags: 1,
1467                     parking_version: 0,
1468                     performance_interrupt: 0,
1469                     parked_address: 0,
1470                     base_address: 0,
1471                     gicv_base_address: 0,
1472                     gich_base_address: 0,
1473                     vgic_interrupt: 0,
1474                     gicr_base_address: 0,
1475                     mpidr: mpidr & mpidr_mask,
1476                     proc_power_effi_class: 0,
1477                     reserved1: 0,
1478                     spe_overflow_interrupt: 0,
1479                 };
1480 
1481                 madt.append(gicc);
1482             }
1483             let vgic_config = Gic::create_default_config(self.config.boot_vcpus.into());
1484 
1485             // GIC Distributor structure. See section 5.2.12.15 in ACPI spec.
1486             let gicd = GicD {
1487                 r#type: acpi::ACPI_APIC_GENERIC_DISTRIBUTOR,
1488                 length: 24,
1489                 reserved0: 0,
1490                 gic_id: 0,
1491                 base_address: vgic_config.dist_addr,
1492                 global_irq_base: 0,
1493                 version: 3,
1494                 reserved1: [0; 3],
1495             };
1496             madt.append(gicd);
1497 
1498             // See 5.2.12.17 GIC Redistributor (GICR) Structure in ACPI spec.
1499             let gicr = GicR {
1500                 r#type: acpi::ACPI_APIC_GENERIC_REDISTRIBUTOR,
1501                 length: 16,
1502                 reserved: 0,
1503                 base_address: vgic_config.redists_addr,
1504                 range_length: vgic_config.redists_size as u32,
1505             };
1506             madt.append(gicr);
1507 
1508             // See 5.2.12.18 GIC Interrupt Translation Service (ITS) Structure in ACPI spec.
1509             let gicits = GicIts {
1510                 r#type: acpi::ACPI_APIC_GENERIC_TRANSLATOR,
1511                 length: 20,
1512                 reserved0: 0,
1513                 translation_id: 0,
1514                 base_address: vgic_config.msi_addr,
1515                 reserved1: 0,
1516             };
1517             madt.append(gicits);
1518 
1519             madt.update_checksum();
1520         }
1521 
1522         madt
1523     }
1524 
1525     #[cfg(target_arch = "aarch64")]
1526     pub fn create_pptt(&self) -> Sdt {
1527         let pptt_start = 0;
1528         let mut cpus = 0;
1529         let mut uid = 0;
1530         // If topology is not specified, the default setting is:
1531         // 1 package, multiple cores, 1 thread per core
1532         // This is also the behavior when PPTT is missing.
1533         let (threads_per_core, cores_per_package, packages) =
1534             self.get_vcpu_topology().unwrap_or((1, self.max_vcpus(), 1));
1535 
1536         let mut pptt = Sdt::new(*b"PPTT", 36, 2, *b"CLOUDH", *b"CHPPTT  ", 1);
1537 
1538         for cluster_idx in 0..packages {
1539             if cpus < self.config.boot_vcpus as usize {
1540                 let cluster_offset = pptt.len() - pptt_start;
1541                 let cluster_hierarchy_node = ProcessorHierarchyNode {
1542                     r#type: 0,
1543                     length: 20,
1544                     reserved: 0,
1545                     flags: 0x2,
1546                     parent: 0,
1547                     acpi_processor_id: cluster_idx as u32,
1548                     num_private_resources: 0,
1549                 };
1550                 pptt.append(cluster_hierarchy_node);
1551 
1552                 for core_idx in 0..cores_per_package {
1553                     let core_offset = pptt.len() - pptt_start;
1554 
1555                     if threads_per_core > 1 {
1556                         let core_hierarchy_node = ProcessorHierarchyNode {
1557                             r#type: 0,
1558                             length: 20,
1559                             reserved: 0,
1560                             flags: 0x2,
1561                             parent: cluster_offset as u32,
1562                             acpi_processor_id: core_idx as u32,
1563                             num_private_resources: 0,
1564                         };
1565                         pptt.append(core_hierarchy_node);
1566 
1567                         for _thread_idx in 0..threads_per_core {
1568                             let thread_hierarchy_node = ProcessorHierarchyNode {
1569                                 r#type: 0,
1570                                 length: 20,
1571                                 reserved: 0,
1572                                 flags: 0xE,
1573                                 parent: core_offset as u32,
1574                                 acpi_processor_id: uid as u32,
1575                                 num_private_resources: 0,
1576                             };
1577                             pptt.append(thread_hierarchy_node);
1578                             uid += 1;
1579                         }
1580                     } else {
1581                         let thread_hierarchy_node = ProcessorHierarchyNode {
1582                             r#type: 0,
1583                             length: 20,
1584                             reserved: 0,
1585                             flags: 0xA,
1586                             parent: cluster_offset as u32,
1587                             acpi_processor_id: uid as u32,
1588                             num_private_resources: 0,
1589                         };
1590                         pptt.append(thread_hierarchy_node);
1591                         uid += 1;
1592                     }
1593                 }
1594                 cpus += (cores_per_package * threads_per_core) as usize;
1595             }
1596         }
1597 
1598         pptt.update_checksum();
1599         pptt
1600     }
1601 
1602     #[cfg(feature = "guest_debug")]
1603     fn get_regs(&self, cpu_id: u8) -> Result<StandardRegisters> {
1604         self.vcpus[usize::from(cpu_id)]
1605             .lock()
1606             .unwrap()
1607             .vcpu
1608             .get_regs()
1609             .map_err(Error::CpuDebug)
1610     }
1611 
1612     #[cfg(feature = "guest_debug")]
1613     fn set_regs(&self, cpu_id: u8, regs: &StandardRegisters) -> Result<()> {
1614         self.vcpus[usize::from(cpu_id)]
1615             .lock()
1616             .unwrap()
1617             .vcpu
1618             .set_regs(regs)
1619             .map_err(Error::CpuDebug)
1620     }
1621 
1622     #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
1623     fn get_sregs(&self, cpu_id: u8) -> Result<SpecialRegisters> {
1624         self.vcpus[usize::from(cpu_id)]
1625             .lock()
1626             .unwrap()
1627             .vcpu
1628             .get_sregs()
1629             .map_err(Error::CpuDebug)
1630     }
1631 
1632     #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
1633     fn set_sregs(&self, cpu_id: u8, sregs: &SpecialRegisters) -> Result<()> {
1634         self.vcpus[usize::from(cpu_id)]
1635             .lock()
1636             .unwrap()
1637             .vcpu
1638             .set_sregs(sregs)
1639             .map_err(Error::CpuDebug)
1640     }
1641 
1642     #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
1643     fn translate_gva(
1644         &self,
1645         _guest_memory: &GuestMemoryAtomic<GuestMemoryMmap>,
1646         cpu_id: u8,
1647         gva: u64,
1648     ) -> Result<u64> {
1649         let (gpa, _) = self.vcpus[usize::from(cpu_id)]
1650             .lock()
1651             .unwrap()
1652             .vcpu
1653             .translate_gva(gva, /* flags: unused */ 0)
1654             .map_err(|e| Error::TranslateVirtualAddress(e.into()))?;
1655         Ok(gpa)
1656     }
1657 
1658     ///
1659     /// On AArch64, `translate_gva` API is not provided by KVM. We implemented
1660     /// it in VMM by walking through translation tables.
1661     ///
1662     /// Address translation is big topic, here we only focus the scenario that
1663     /// happens in VMM while debugging kernel. This `translate_gva`
1664     /// implementation is restricted to:
1665     /// - Exception Level 1
1666     /// - Translate high address range only (kernel space)
1667     ///
1668     /// This implementation supports following Arm-v8a features related to
1669     /// address translation:
1670     /// - FEAT_LPA
1671     /// - FEAT_LVA
1672     /// - FEAT_LPA2
1673     ///
1674     #[cfg(all(target_arch = "aarch64", feature = "guest_debug"))]
1675     fn translate_gva(
1676         &self,
1677         guest_memory: &GuestMemoryAtomic<GuestMemoryMmap>,
1678         cpu_id: u8,
1679         gva: u64,
1680     ) -> Result<u64> {
1681         let tcr_el1: u64 = self.vcpus[usize::from(cpu_id)]
1682             .lock()
1683             .unwrap()
1684             .vcpu
1685             .get_sys_reg(regs::TCR_EL1)
1686             .map_err(|e| Error::TranslateVirtualAddress(e.into()))?;
1687         let ttbr1_el1: u64 = self.vcpus[usize::from(cpu_id)]
1688             .lock()
1689             .unwrap()
1690             .vcpu
1691             .get_sys_reg(regs::TTBR1_EL1)
1692             .map_err(|e| Error::TranslateVirtualAddress(e.into()))?;
1693         let id_aa64mmfr0_el1: u64 = self.vcpus[usize::from(cpu_id)]
1694             .lock()
1695             .unwrap()
1696             .vcpu
1697             .get_sys_reg(regs::ID_AA64MMFR0_EL1)
1698             .map_err(|e| Error::TranslateVirtualAddress(e.into()))?;
1699 
1700         // Bit 55 of the VA determines the range, high (0xFFFxxx...)
1701         // or low (0x000xxx...).
1702         let high_range = extract_bits_64!(gva, 55, 1);
1703         if high_range == 0 {
1704             info!("VA (0x{:x}) range is not supported!", gva);
1705             return Ok(gva);
1706         }
1707 
1708         // High range size offset
1709         let tsz = extract_bits_64!(tcr_el1, 16, 6);
1710         // Granule size
1711         let tg = extract_bits_64!(tcr_el1, 30, 2);
1712         // Indication of 48-bits (0) or 52-bits (1) for FEAT_LPA2
1713         let ds = extract_bits_64!(tcr_el1, 59, 1);
1714 
1715         if tsz == 0 {
1716             info!("VA translation is not ready!");
1717             return Ok(gva);
1718         }
1719 
1720         // VA size is determined by TCR_BL1.T1SZ
1721         let va_size = 64 - tsz;
1722         // Number of bits in VA consumed in each level of translation
1723         let stride = match tg {
1724             3 => 13, // 64KB granule size
1725             1 => 11, // 16KB granule size
1726             _ => 9,  // 4KB, default
1727         };
1728         // Starting level of walking
1729         let mut level = 4 - (va_size - 4) / stride;
1730 
1731         // PA or IPA size is determined
1732         let tcr_ips = extract_bits_64!(tcr_el1, 32, 3);
1733         let pa_range = extract_bits_64_without_offset!(id_aa64mmfr0_el1, 4);
1734         // The IPA size in TCR_BL1 and PA Range in ID_AA64MMFR0_EL1 should match.
1735         // To be safe, we use the minimum value if they are different.
1736         let pa_range = std::cmp::min(tcr_ips, pa_range);
1737         // PA size in bits
1738         let pa_size = match pa_range {
1739             0 => 32,
1740             1 => 36,
1741             2 => 40,
1742             3 => 42,
1743             4 => 44,
1744             5 => 48,
1745             6 => 52,
1746             _ => {
1747                 return Err(Error::TranslateVirtualAddress(anyhow!(format!(
1748                     "PA range not supported {pa_range}"
1749                 ))))
1750             }
1751         };
1752 
1753         let indexmask_grainsize = (!0u64) >> (64 - (stride + 3));
1754         let mut indexmask = (!0u64) >> (64 - (va_size - (stride * (4 - level))));
1755         // If FEAT_LPA2 is present, the translation table descriptor holds
1756         // 50 bits of the table address of next level.
1757         // Otherwise, it is 48 bits.
1758         let descaddrmask = if ds == 1 {
1759             !0u64 >> (64 - 50) // mask with 50 least significant bits
1760         } else {
1761             !0u64 >> (64 - 48) // mask with 48 least significant bits
1762         };
1763         let descaddrmask = descaddrmask & !indexmask_grainsize;
1764 
1765         // Translation table base address
1766         let mut descaddr: u64 = extract_bits_64_without_offset!(ttbr1_el1, 48);
1767         // In the case of FEAT_LPA and FEAT_LPA2, the initial translation table
1768         // address bits [48:51] comes from TTBR1_EL1 bits [2:5].
1769         if pa_size == 52 {
1770             descaddr |= extract_bits_64!(ttbr1_el1, 2, 4) << 48;
1771         }
1772 
1773         // Loop through tables of each level
1774         loop {
1775             // Table offset for current level
1776             let table_offset: u64 = (gva >> (stride * (4 - level))) & indexmask;
1777             descaddr |= table_offset;
1778             descaddr &= !7u64;
1779 
1780             let mut buf = [0; 8];
1781             guest_memory
1782                 .memory()
1783                 .read(&mut buf, GuestAddress(descaddr))
1784                 .map_err(|e| Error::TranslateVirtualAddress(e.into()))?;
1785             let descriptor = u64::from_le_bytes(buf);
1786 
1787             descaddr = descriptor & descaddrmask;
1788             // In the case of FEAT_LPA, the next-level translation table address
1789             // bits [48:51] comes from bits [12:15] of the current descriptor.
1790             // For FEAT_LPA2, the next-level translation table address
1791             // bits [50:51] comes from bits [8:9] of the current descriptor,
1792             // bits [48:49] comes from bits [48:49] of the descriptor which was
1793             // handled previously.
1794             if pa_size == 52 {
1795                 if ds == 1 {
1796                     // FEAT_LPA2
1797                     descaddr |= extract_bits_64!(descriptor, 8, 2) << 50;
1798                 } else {
1799                     // FEAT_LPA
1800                     descaddr |= extract_bits_64!(descriptor, 12, 4) << 48;
1801                 }
1802             }
1803 
1804             if (descriptor & 2) != 0 && (level < 3) {
1805                 // This is a table entry. Go down to next level.
1806                 level += 1;
1807                 indexmask = indexmask_grainsize;
1808                 continue;
1809             }
1810 
1811             break;
1812         }
1813 
1814         // We have reached either:
1815         // - a page entry at level 3 or
1816         // - a block entry at level 1 or 2
1817         let page_size = 1u64 << ((stride * (4 - level)) + 3);
1818         descaddr &= !(page_size - 1);
1819         descaddr |= gva & (page_size - 1);
1820 
1821         Ok(descaddr)
1822     }
1823 
1824     pub(crate) fn set_acpi_address(&mut self, acpi_address: GuestAddress) {
1825         self.acpi_address = Some(acpi_address);
1826     }
1827 
1828     pub(crate) fn set_interrupt_controller(
1829         &mut self,
1830         interrupt_controller: Arc<Mutex<dyn InterruptController>>,
1831     ) {
1832         self.interrupt_controller = Some(interrupt_controller);
1833     }
1834 
1835     pub(crate) fn vcpus_kill_signalled(&self) -> &Arc<AtomicBool> {
1836         &self.vcpus_kill_signalled
1837     }
1838 
1839     #[cfg(feature = "igvm")]
1840     pub(crate) fn get_cpuid_leaf(
1841         &self,
1842         cpu_id: u8,
1843         eax: u32,
1844         ecx: u32,
1845         xfem: u64,
1846         xss: u64,
1847     ) -> Result<[u32; 4]> {
1848         let leaf_info = self.vcpus[usize::from(cpu_id)]
1849             .lock()
1850             .unwrap()
1851             .vcpu
1852             .get_cpuid_values(eax, ecx, xfem, xss)
1853             .unwrap();
1854         Ok(leaf_info)
1855     }
1856 
1857     #[cfg(feature = "sev_snp")]
1858     pub(crate) fn sev_snp_enabled(&self) -> bool {
1859         self.sev_snp_enabled
1860     }
1861 
1862     pub(crate) fn nmi(&self) -> Result<()> {
1863         self.vcpus_kick_signalled.store(true, Ordering::SeqCst);
1864 
1865         for state in self.vcpu_states.iter() {
1866             state.signal_thread();
1867         }
1868 
1869         self.vcpus_kick_signalled.store(false, Ordering::SeqCst);
1870 
1871         Ok(())
1872     }
1873 }
1874 
1875 struct Cpu {
1876     cpu_id: u8,
1877     proximity_domain: u32,
1878     dynamic: bool,
1879     #[cfg(target_arch = "x86_64")]
1880     topology: Option<(u8, u8, u8)>,
1881 }
1882 
1883 #[cfg(target_arch = "x86_64")]
1884 const MADT_CPU_ENABLE_FLAG: usize = 0;
1885 
1886 #[cfg(target_arch = "x86_64")]
1887 const MADT_CPU_ONLINE_CAPABLE_FLAG: usize = 1;
1888 
1889 impl Cpu {
1890     #[cfg(target_arch = "x86_64")]
1891     fn generate_mat(&self) -> Vec<u8> {
1892         let x2apic_id = arch::x86_64::get_x2apic_id(self.cpu_id.into(), self.topology);
1893 
1894         let lapic = LocalX2Apic {
1895             r#type: crate::acpi::ACPI_X2APIC_PROCESSOR,
1896             length: 16,
1897             processor_id: self.cpu_id.into(),
1898             apic_id: x2apic_id,
1899             flags: 1 << MADT_CPU_ENABLE_FLAG,
1900             _reserved: 0,
1901         };
1902 
1903         let mut mat_data: Vec<u8> = vec![0; std::mem::size_of_val(&lapic)];
1904         // SAFETY: mat_data is large enough to hold lapic
1905         unsafe { *(mat_data.as_mut_ptr() as *mut LocalX2Apic) = lapic };
1906 
1907         mat_data
1908     }
1909 }
1910 
1911 impl Aml for Cpu {
1912     fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) {
1913         #[cfg(target_arch = "x86_64")]
1914         let mat_data: Vec<u8> = self.generate_mat();
1915         #[allow(clippy::if_same_then_else)]
1916         if self.dynamic {
1917             aml::Device::new(
1918                 format!("C{:03X}", self.cpu_id).as_str().into(),
1919                 vec![
1920                     &aml::Name::new("_HID".into(), &"ACPI0007"),
1921                     &aml::Name::new("_UID".into(), &self.cpu_id),
1922                     // Currently, AArch64 cannot support following fields.
1923                     /*
1924                     _STA return value:
1925                     Bit [0] – Set if the device is present.
1926                     Bit [1] – Set if the device is enabled and decoding its resources.
1927                     Bit [2] – Set if the device should be shown in the UI.
1928                     Bit [3] – Set if the device is functioning properly (cleared if device failed its diagnostics).
1929                     Bit [4] – Set if the battery is present.
1930                     Bits [31:5] – Reserved (must be cleared).
1931                     */
1932                     #[cfg(target_arch = "x86_64")]
1933                     &aml::Method::new(
1934                         "_STA".into(),
1935                         0,
1936                         false,
1937                         // Call into CSTA method which will interrogate device
1938                         vec![&aml::Return::new(&aml::MethodCall::new(
1939                             "CSTA".into(),
1940                             vec![&self.cpu_id],
1941                         ))],
1942                     ),
1943                     &aml::Method::new(
1944                         "_PXM".into(),
1945                         0,
1946                         false,
1947                         vec![&aml::Return::new(&self.proximity_domain)],
1948                     ),
1949                     // The Linux kernel expects every CPU device to have a _MAT entry
1950                     // containing the LAPIC for this processor with the enabled bit set
1951                     // even it if is disabled in the MADT (non-boot CPU)
1952                     #[cfg(target_arch = "x86_64")]
1953                     &aml::Name::new("_MAT".into(), &aml::BufferData::new(mat_data)),
1954                     // Trigger CPU ejection
1955                     #[cfg(target_arch = "x86_64")]
1956                     &aml::Method::new(
1957                         "_EJ0".into(),
1958                         1,
1959                         false,
1960                         // Call into CEJ0 method which will actually eject device
1961                         vec![&aml::MethodCall::new("CEJ0".into(), vec![&self.cpu_id])],
1962                     ),
1963                 ],
1964             )
1965             .to_aml_bytes(sink);
1966         } else {
1967             aml::Device::new(
1968                 format!("C{:03X}", self.cpu_id).as_str().into(),
1969                 vec![
1970                     &aml::Name::new("_HID".into(), &"ACPI0007"),
1971                     &aml::Name::new("_UID".into(), &self.cpu_id),
1972                     #[cfg(target_arch = "x86_64")]
1973                     &aml::Method::new(
1974                         "_STA".into(),
1975                         0,
1976                         false,
1977                         // Mark CPU present see CSTA implementation
1978                         vec![&aml::Return::new(&0xfu8)],
1979                     ),
1980                     &aml::Method::new(
1981                         "_PXM".into(),
1982                         0,
1983                         false,
1984                         vec![&aml::Return::new(&self.proximity_domain)],
1985                     ),
1986                     // The Linux kernel expects every CPU device to have a _MAT entry
1987                     // containing the LAPIC for this processor with the enabled bit set
1988                     // even it if is disabled in the MADT (non-boot CPU)
1989                     #[cfg(target_arch = "x86_64")]
1990                     &aml::Name::new("_MAT".into(), &aml::BufferData::new(mat_data)),
1991                 ],
1992             )
1993             .to_aml_bytes(sink);
1994         }
1995     }
1996 }
1997 
1998 struct CpuNotify {
1999     cpu_id: u8,
2000 }
2001 
2002 impl Aml for CpuNotify {
2003     fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) {
2004         let object = aml::Path::new(&format!("C{:03X}", self.cpu_id));
2005         aml::If::new(
2006             &aml::Equal::new(&aml::Arg(0), &self.cpu_id),
2007             vec![&aml::Notify::new(&object, &aml::Arg(1))],
2008         )
2009         .to_aml_bytes(sink)
2010     }
2011 }
2012 
2013 struct CpuMethods {
2014     max_vcpus: u8,
2015     dynamic: bool,
2016 }
2017 
2018 impl Aml for CpuMethods {
2019     fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) {
2020         if self.dynamic {
2021             // CPU status method
2022             aml::Method::new(
2023                 "CSTA".into(),
2024                 1,
2025                 true,
2026                 vec![
2027                     // Take lock defined above
2028                     &aml::Acquire::new("\\_SB_.PRES.CPLK".into(), 0xffff),
2029                     // Write CPU number (in first argument) to I/O port via field
2030                     &aml::Store::new(&aml::Path::new("\\_SB_.PRES.CSEL"), &aml::Arg(0)),
2031                     &aml::Store::new(&aml::Local(0), &aml::ZERO),
2032                     // Check if CPEN bit is set, if so make the local variable 0xf (see _STA for details of meaning)
2033                     &aml::If::new(
2034                         &aml::Equal::new(&aml::Path::new("\\_SB_.PRES.CPEN"), &aml::ONE),
2035                         vec![&aml::Store::new(&aml::Local(0), &0xfu8)],
2036                     ),
2037                     // Release lock
2038                     &aml::Release::new("\\_SB_.PRES.CPLK".into()),
2039                     // Return 0 or 0xf
2040                     &aml::Return::new(&aml::Local(0)),
2041                 ],
2042             )
2043             .to_aml_bytes(sink);
2044 
2045             let mut cpu_notifies = Vec::new();
2046             for cpu_id in 0..self.max_vcpus {
2047                 cpu_notifies.push(CpuNotify { cpu_id });
2048             }
2049 
2050             let mut cpu_notifies_refs: Vec<&dyn Aml> = Vec::new();
2051             for cpu_id in 0..self.max_vcpus {
2052                 cpu_notifies_refs.push(&cpu_notifies[usize::from(cpu_id)]);
2053             }
2054 
2055             aml::Method::new("CTFY".into(), 2, true, cpu_notifies_refs).to_aml_bytes(sink);
2056 
2057             aml::Method::new(
2058                 "CEJ0".into(),
2059                 1,
2060                 true,
2061                 vec![
2062                     &aml::Acquire::new("\\_SB_.PRES.CPLK".into(), 0xffff),
2063                     // Write CPU number (in first argument) to I/O port via field
2064                     &aml::Store::new(&aml::Path::new("\\_SB_.PRES.CSEL"), &aml::Arg(0)),
2065                     // Set CEJ0 bit
2066                     &aml::Store::new(&aml::Path::new("\\_SB_.PRES.CEJ0"), &aml::ONE),
2067                     &aml::Release::new("\\_SB_.PRES.CPLK".into()),
2068                 ],
2069             )
2070             .to_aml_bytes(sink);
2071 
2072             aml::Method::new(
2073                 "CSCN".into(),
2074                 0,
2075                 true,
2076                 vec![
2077                     // Take lock defined above
2078                     &aml::Acquire::new("\\_SB_.PRES.CPLK".into(), 0xffff),
2079                     &aml::Store::new(&aml::Local(0), &aml::ZERO),
2080                     &aml::While::new(
2081                         &aml::LessThan::new(&aml::Local(0), &self.max_vcpus),
2082                         vec![
2083                             // Write CPU number (in first argument) to I/O port via field
2084                             &aml::Store::new(&aml::Path::new("\\_SB_.PRES.CSEL"), &aml::Local(0)),
2085                             // Check if CINS bit is set
2086                             &aml::If::new(
2087                                 &aml::Equal::new(&aml::Path::new("\\_SB_.PRES.CINS"), &aml::ONE),
2088                                 // Notify device if it is
2089                                 vec![
2090                                     &aml::MethodCall::new(
2091                                         "CTFY".into(),
2092                                         vec![&aml::Local(0), &aml::ONE],
2093                                     ),
2094                                     // Reset CINS bit
2095                                     &aml::Store::new(
2096                                         &aml::Path::new("\\_SB_.PRES.CINS"),
2097                                         &aml::ONE,
2098                                     ),
2099                                 ],
2100                             ),
2101                             // Check if CRMV bit is set
2102                             &aml::If::new(
2103                                 &aml::Equal::new(&aml::Path::new("\\_SB_.PRES.CRMV"), &aml::ONE),
2104                                 // Notify device if it is (with the eject constant 0x3)
2105                                 vec![
2106                                     &aml::MethodCall::new(
2107                                         "CTFY".into(),
2108                                         vec![&aml::Local(0), &3u8],
2109                                     ),
2110                                     // Reset CRMV bit
2111                                     &aml::Store::new(
2112                                         &aml::Path::new("\\_SB_.PRES.CRMV"),
2113                                         &aml::ONE,
2114                                     ),
2115                                 ],
2116                             ),
2117                             &aml::Add::new(&aml::Local(0), &aml::Local(0), &aml::ONE),
2118                         ],
2119                     ),
2120                     // Release lock
2121                     &aml::Release::new("\\_SB_.PRES.CPLK".into()),
2122                 ],
2123             )
2124             .to_aml_bytes(sink)
2125         } else {
2126             aml::Method::new("CSCN".into(), 0, true, vec![]).to_aml_bytes(sink)
2127         }
2128     }
2129 }
2130 
2131 impl Aml for CpuManager {
2132     fn to_aml_bytes(&self, sink: &mut dyn acpi_tables::AmlSink) {
2133         #[cfg(target_arch = "x86_64")]
2134         if let Some(acpi_address) = self.acpi_address {
2135             // CPU hotplug controller
2136             aml::Device::new(
2137                 "_SB_.PRES".into(),
2138                 vec![
2139                     &aml::Name::new("_HID".into(), &aml::EISAName::new("PNP0A06")),
2140                     &aml::Name::new("_UID".into(), &"CPU Hotplug Controller"),
2141                     // Mutex to protect concurrent access as we write to choose CPU and then read back status
2142                     &aml::Mutex::new("CPLK".into(), 0),
2143                     &aml::Name::new(
2144                         "_CRS".into(),
2145                         &aml::ResourceTemplate::new(vec![&aml::AddressSpace::new_memory(
2146                             aml::AddressSpaceCacheable::NotCacheable,
2147                             true,
2148                             acpi_address.0,
2149                             acpi_address.0 + CPU_MANAGER_ACPI_SIZE as u64 - 1,
2150                             None,
2151                         )]),
2152                     ),
2153                     // OpRegion and Fields map MMIO range into individual field values
2154                     &aml::OpRegion::new(
2155                         "PRST".into(),
2156                         aml::OpRegionSpace::SystemMemory,
2157                         &(acpi_address.0 as usize),
2158                         &CPU_MANAGER_ACPI_SIZE,
2159                     ),
2160                     &aml::Field::new(
2161                         "PRST".into(),
2162                         aml::FieldAccessType::Byte,
2163                         aml::FieldLockRule::NoLock,
2164                         aml::FieldUpdateRule::WriteAsZeroes,
2165                         vec![
2166                             aml::FieldEntry::Reserved(32),
2167                             aml::FieldEntry::Named(*b"CPEN", 1),
2168                             aml::FieldEntry::Named(*b"CINS", 1),
2169                             aml::FieldEntry::Named(*b"CRMV", 1),
2170                             aml::FieldEntry::Named(*b"CEJ0", 1),
2171                             aml::FieldEntry::Reserved(4),
2172                             aml::FieldEntry::Named(*b"CCMD", 8),
2173                         ],
2174                     ),
2175                     &aml::Field::new(
2176                         "PRST".into(),
2177                         aml::FieldAccessType::DWord,
2178                         aml::FieldLockRule::NoLock,
2179                         aml::FieldUpdateRule::Preserve,
2180                         vec![
2181                             aml::FieldEntry::Named(*b"CSEL", 32),
2182                             aml::FieldEntry::Reserved(32),
2183                             aml::FieldEntry::Named(*b"CDAT", 32),
2184                         ],
2185                     ),
2186                 ],
2187             )
2188             .to_aml_bytes(sink);
2189         }
2190 
2191         // CPU devices
2192         let hid = aml::Name::new("_HID".into(), &"ACPI0010");
2193         let uid = aml::Name::new("_CID".into(), &aml::EISAName::new("PNP0A05"));
2194         // Bundle methods together under a common object
2195         let methods = CpuMethods {
2196             max_vcpus: self.config.max_vcpus,
2197             dynamic: self.dynamic,
2198         };
2199         let mut cpu_data_inner: Vec<&dyn Aml> = vec![&hid, &uid, &methods];
2200 
2201         #[cfg(target_arch = "x86_64")]
2202         let topology = self.get_vcpu_topology();
2203         let mut cpu_devices = Vec::new();
2204         for cpu_id in 0..self.config.max_vcpus {
2205             let proximity_domain = *self.proximity_domain_per_cpu.get(&cpu_id).unwrap_or(&0);
2206             let cpu_device = Cpu {
2207                 cpu_id,
2208                 proximity_domain,
2209                 dynamic: self.dynamic,
2210                 #[cfg(target_arch = "x86_64")]
2211                 topology,
2212             };
2213 
2214             cpu_devices.push(cpu_device);
2215         }
2216 
2217         for cpu_device in cpu_devices.iter() {
2218             cpu_data_inner.push(cpu_device);
2219         }
2220 
2221         aml::Device::new("_SB_.CPUS".into(), cpu_data_inner).to_aml_bytes(sink)
2222     }
2223 }
2224 
2225 impl Pausable for CpuManager {
2226     fn pause(&mut self) -> std::result::Result<(), MigratableError> {
2227         // Tell the vCPUs to pause themselves next time they exit
2228         self.vcpus_pause_signalled.store(true, Ordering::SeqCst);
2229 
2230         // Signal to the spawned threads (vCPUs and console signal handler). For the vCPU threads
2231         // this will interrupt the KVM_RUN ioctl() allowing the loop to check the boolean set
2232         // above.
2233         for state in self.vcpu_states.iter() {
2234             state.signal_thread();
2235         }
2236 
2237         for vcpu in self.vcpus.iter() {
2238             let mut vcpu = vcpu.lock().unwrap();
2239             vcpu.pause()?;
2240             #[cfg(all(feature = "kvm", target_arch = "x86_64"))]
2241             if !self.config.kvm_hyperv {
2242                 vcpu.vcpu.notify_guest_clock_paused().map_err(|e| {
2243                     MigratableError::Pause(anyhow!(
2244                         "Could not notify guest it has been paused {:?}",
2245                         e
2246                     ))
2247                 })?;
2248             }
2249         }
2250 
2251         // The vCPU thread will change its paused state before parking, wait here for each
2252         // activated vCPU change their state to ensure they have parked.
2253         for state in self.vcpu_states.iter() {
2254             if state.active() {
2255                 while !state.paused.load(Ordering::SeqCst) {
2256                     // To avoid a priority inversion with the vCPU thread
2257                     thread::sleep(std::time::Duration::from_millis(1));
2258                 }
2259             }
2260         }
2261 
2262         Ok(())
2263     }
2264 
2265     fn resume(&mut self) -> std::result::Result<(), MigratableError> {
2266         for vcpu in self.vcpus.iter() {
2267             vcpu.lock().unwrap().resume()?;
2268         }
2269 
2270         // Toggle the vCPUs pause boolean
2271         self.vcpus_pause_signalled.store(false, Ordering::SeqCst);
2272 
2273         // Unpark all the VCPU threads.
2274         // Once unparked, the next thing they will do is checking for the pause
2275         // boolean. Since it'll be set to false, they will exit their pause loop
2276         // and go back to vmx root.
2277         for state in self.vcpu_states.iter() {
2278             state.paused.store(false, Ordering::SeqCst);
2279             state.unpark_thread();
2280         }
2281         Ok(())
2282     }
2283 }
2284 
2285 impl Snapshottable for CpuManager {
2286     fn id(&self) -> String {
2287         CPU_MANAGER_SNAPSHOT_ID.to_string()
2288     }
2289 
2290     fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> {
2291         let mut cpu_manager_snapshot = Snapshot::default();
2292 
2293         // The CpuManager snapshot is a collection of all vCPUs snapshots.
2294         for vcpu in &self.vcpus {
2295             let mut vcpu = vcpu.lock().unwrap();
2296             cpu_manager_snapshot.add_snapshot(vcpu.id(), vcpu.snapshot()?);
2297         }
2298 
2299         Ok(cpu_manager_snapshot)
2300     }
2301 }
2302 
2303 impl Transportable for CpuManager {}
2304 impl Migratable for CpuManager {}
2305 
2306 #[cfg(feature = "guest_debug")]
2307 impl Debuggable for CpuManager {
2308     #[cfg(feature = "kvm")]
2309     fn set_guest_debug(
2310         &self,
2311         cpu_id: usize,
2312         addrs: &[GuestAddress],
2313         singlestep: bool,
2314     ) -> std::result::Result<(), DebuggableError> {
2315         self.vcpus[cpu_id]
2316             .lock()
2317             .unwrap()
2318             .vcpu
2319             .set_guest_debug(addrs, singlestep)
2320             .map_err(DebuggableError::SetDebug)
2321     }
2322 
2323     fn debug_pause(&mut self) -> std::result::Result<(), DebuggableError> {
2324         Ok(())
2325     }
2326 
2327     fn debug_resume(&mut self) -> std::result::Result<(), DebuggableError> {
2328         Ok(())
2329     }
2330 
2331     #[cfg(target_arch = "x86_64")]
2332     fn read_regs(&self, cpu_id: usize) -> std::result::Result<CoreRegs, DebuggableError> {
2333         // General registers: RAX, RBX, RCX, RDX, RSI, RDI, RBP, RSP, r8-r15
2334         let gregs = self
2335             .get_regs(cpu_id as u8)
2336             .map_err(DebuggableError::ReadRegs)?;
2337         let regs = [
2338             gregs.rax, gregs.rbx, gregs.rcx, gregs.rdx, gregs.rsi, gregs.rdi, gregs.rbp, gregs.rsp,
2339             gregs.r8, gregs.r9, gregs.r10, gregs.r11, gregs.r12, gregs.r13, gregs.r14, gregs.r15,
2340         ];
2341 
2342         // GDB exposes 32-bit eflags instead of 64-bit rflags.
2343         // https://github.com/bminor/binutils-gdb/blob/master/gdb/features/i386/64bit-core.xml
2344         let eflags = gregs.rflags as u32;
2345         let rip = gregs.rip;
2346 
2347         // Segment registers: CS, SS, DS, ES, FS, GS
2348         let sregs = self
2349             .get_sregs(cpu_id as u8)
2350             .map_err(DebuggableError::ReadRegs)?;
2351         let segments = X86SegmentRegs {
2352             cs: sregs.cs.selector as u32,
2353             ss: sregs.ss.selector as u32,
2354             ds: sregs.ds.selector as u32,
2355             es: sregs.es.selector as u32,
2356             fs: sregs.fs.selector as u32,
2357             gs: sregs.gs.selector as u32,
2358         };
2359 
2360         // TODO: Add other registers
2361 
2362         Ok(CoreRegs {
2363             regs,
2364             eflags,
2365             rip,
2366             segments,
2367             ..Default::default()
2368         })
2369     }
2370 
2371     #[cfg(target_arch = "aarch64")]
2372     fn read_regs(&self, cpu_id: usize) -> std::result::Result<CoreRegs, DebuggableError> {
2373         let gregs = self
2374             .get_regs(cpu_id as u8)
2375             .map_err(DebuggableError::ReadRegs)?;
2376         Ok(CoreRegs {
2377             x: gregs.regs.regs,
2378             sp: gregs.regs.sp,
2379             pc: gregs.regs.pc,
2380             ..Default::default()
2381         })
2382     }
2383 
2384     #[cfg(target_arch = "x86_64")]
2385     fn write_regs(
2386         &self,
2387         cpu_id: usize,
2388         regs: &CoreRegs,
2389     ) -> std::result::Result<(), DebuggableError> {
2390         let orig_gregs = self
2391             .get_regs(cpu_id as u8)
2392             .map_err(DebuggableError::ReadRegs)?;
2393         let gregs = StandardRegisters {
2394             rax: regs.regs[0],
2395             rbx: regs.regs[1],
2396             rcx: regs.regs[2],
2397             rdx: regs.regs[3],
2398             rsi: regs.regs[4],
2399             rdi: regs.regs[5],
2400             rbp: regs.regs[6],
2401             rsp: regs.regs[7],
2402             r8: regs.regs[8],
2403             r9: regs.regs[9],
2404             r10: regs.regs[10],
2405             r11: regs.regs[11],
2406             r12: regs.regs[12],
2407             r13: regs.regs[13],
2408             r14: regs.regs[14],
2409             r15: regs.regs[15],
2410             rip: regs.rip,
2411             // Update the lower 32-bit of rflags.
2412             rflags: (orig_gregs.rflags & !(u32::MAX as u64)) | (regs.eflags as u64),
2413         };
2414 
2415         self.set_regs(cpu_id as u8, &gregs)
2416             .map_err(DebuggableError::WriteRegs)?;
2417 
2418         // Segment registers: CS, SS, DS, ES, FS, GS
2419         // Since GDB care only selectors, we call get_sregs() first.
2420         let mut sregs = self
2421             .get_sregs(cpu_id as u8)
2422             .map_err(DebuggableError::ReadRegs)?;
2423         sregs.cs.selector = regs.segments.cs as u16;
2424         sregs.ss.selector = regs.segments.ss as u16;
2425         sregs.ds.selector = regs.segments.ds as u16;
2426         sregs.es.selector = regs.segments.es as u16;
2427         sregs.fs.selector = regs.segments.fs as u16;
2428         sregs.gs.selector = regs.segments.gs as u16;
2429 
2430         self.set_sregs(cpu_id as u8, &sregs)
2431             .map_err(DebuggableError::WriteRegs)?;
2432 
2433         // TODO: Add other registers
2434 
2435         Ok(())
2436     }
2437 
2438     #[cfg(target_arch = "aarch64")]
2439     fn write_regs(
2440         &self,
2441         cpu_id: usize,
2442         regs: &CoreRegs,
2443     ) -> std::result::Result<(), DebuggableError> {
2444         let mut gregs = self
2445             .get_regs(cpu_id as u8)
2446             .map_err(DebuggableError::ReadRegs)?;
2447 
2448         gregs.regs.regs = regs.x;
2449         gregs.regs.sp = regs.sp;
2450         gregs.regs.pc = regs.pc;
2451 
2452         self.set_regs(cpu_id as u8, &gregs)
2453             .map_err(DebuggableError::WriteRegs)?;
2454 
2455         Ok(())
2456     }
2457 
2458     fn read_mem(
2459         &self,
2460         guest_memory: &GuestMemoryAtomic<GuestMemoryMmap>,
2461         cpu_id: usize,
2462         vaddr: GuestAddress,
2463         len: usize,
2464     ) -> std::result::Result<Vec<u8>, DebuggableError> {
2465         let mut buf = vec![0; len];
2466         let mut total_read = 0_u64;
2467 
2468         while total_read < len as u64 {
2469             let gaddr = vaddr.0 + total_read;
2470             let paddr = match self.translate_gva(guest_memory, cpu_id as u8, gaddr) {
2471                 Ok(paddr) => paddr,
2472                 Err(_) if gaddr == u64::MIN => gaddr, // Silently return GVA as GPA if GVA == 0.
2473                 Err(e) => return Err(DebuggableError::TranslateGva(e)),
2474             };
2475             let psize = arch::PAGE_SIZE as u64;
2476             let read_len = std::cmp::min(len as u64 - total_read, psize - (paddr & (psize - 1)));
2477             guest_memory
2478                 .memory()
2479                 .read(
2480                     &mut buf[total_read as usize..total_read as usize + read_len as usize],
2481                     GuestAddress(paddr),
2482                 )
2483                 .map_err(DebuggableError::ReadMem)?;
2484             total_read += read_len;
2485         }
2486         Ok(buf)
2487     }
2488 
2489     fn write_mem(
2490         &self,
2491         guest_memory: &GuestMemoryAtomic<GuestMemoryMmap>,
2492         cpu_id: usize,
2493         vaddr: &GuestAddress,
2494         data: &[u8],
2495     ) -> std::result::Result<(), DebuggableError> {
2496         let mut total_written = 0_u64;
2497 
2498         while total_written < data.len() as u64 {
2499             let gaddr = vaddr.0 + total_written;
2500             let paddr = match self.translate_gva(guest_memory, cpu_id as u8, gaddr) {
2501                 Ok(paddr) => paddr,
2502                 Err(_) if gaddr == u64::MIN => gaddr, // Silently return GVA as GPA if GVA == 0.
2503                 Err(e) => return Err(DebuggableError::TranslateGva(e)),
2504             };
2505             let psize = arch::PAGE_SIZE as u64;
2506             let write_len = std::cmp::min(
2507                 data.len() as u64 - total_written,
2508                 psize - (paddr & (psize - 1)),
2509             );
2510             guest_memory
2511                 .memory()
2512                 .write(
2513                     &data[total_written as usize..total_written as usize + write_len as usize],
2514                     GuestAddress(paddr),
2515                 )
2516                 .map_err(DebuggableError::WriteMem)?;
2517             total_written += write_len;
2518         }
2519         Ok(())
2520     }
2521 
2522     fn active_vcpus(&self) -> usize {
2523         self.present_vcpus() as usize
2524     }
2525 }
2526 
2527 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
2528 impl Elf64Writable for CpuManager {}
2529 
2530 #[cfg(all(target_arch = "x86_64", feature = "guest_debug"))]
2531 impl CpuElf64Writable for CpuManager {
2532     fn cpu_write_elf64_note(
2533         &mut self,
2534         dump_state: &DumpState,
2535     ) -> std::result::Result<(), GuestDebuggableError> {
2536         let mut coredump_file = dump_state.file.as_ref().unwrap();
2537         for vcpu in &self.vcpus {
2538             let note_size = self.get_note_size(NoteDescType::Elf, 1);
2539             let mut pos: usize = 0;
2540             let mut buf = vec![0; note_size as usize];
2541             let descsz = size_of::<X86_64ElfPrStatus>();
2542             let vcpu_id = vcpu.lock().unwrap().id;
2543 
2544             let note = Elf64_Nhdr {
2545                 n_namesz: COREDUMP_NAME_SIZE,
2546                 n_descsz: descsz as u32,
2547                 n_type: NT_PRSTATUS,
2548             };
2549 
2550             let bytes: &[u8] = note.as_slice();
2551             buf.splice(0.., bytes.to_vec());
2552             pos += round_up!(size_of::<Elf64_Nhdr>(), 4);
2553             buf.resize(pos + 4, 0);
2554             buf.splice(pos.., "CORE".to_string().into_bytes());
2555 
2556             pos += round_up!(COREDUMP_NAME_SIZE as usize, 4);
2557             buf.resize(pos + 32 + 4, 0);
2558             let pid = vcpu_id as u64;
2559             let bytes: &[u8] = pid.as_slice();
2560             buf.splice(pos + 32.., bytes.to_vec()); /* pr_pid */
2561 
2562             pos += descsz - size_of::<X86_64UserRegs>() - size_of::<u64>();
2563 
2564             let orig_rax: u64 = 0;
2565             let gregs = self.vcpus[usize::from(vcpu_id)]
2566                 .lock()
2567                 .unwrap()
2568                 .vcpu
2569                 .get_regs()
2570                 .map_err(|_e| GuestDebuggableError::Coredump(anyhow!("get regs failed")))?;
2571 
2572             let regs1 = [
2573                 gregs.r15, gregs.r14, gregs.r13, gregs.r12, gregs.rbp, gregs.rbx, gregs.r11,
2574                 gregs.r10,
2575             ];
2576             let regs2 = [
2577                 gregs.r9, gregs.r8, gregs.rax, gregs.rcx, gregs.rdx, gregs.rsi, gregs.rdi, orig_rax,
2578             ];
2579 
2580             let sregs = self.vcpus[usize::from(vcpu_id)]
2581                 .lock()
2582                 .unwrap()
2583                 .vcpu
2584                 .get_sregs()
2585                 .map_err(|_e| GuestDebuggableError::Coredump(anyhow!("get sregs failed")))?;
2586 
2587             debug!(
2588                 "rip 0x{:x} rsp 0x{:x} gs 0x{:x} cs 0x{:x} ss 0x{:x} ds 0x{:x}",
2589                 gregs.rip,
2590                 gregs.rsp,
2591                 sregs.gs.base,
2592                 sregs.cs.selector,
2593                 sregs.ss.selector,
2594                 sregs.ds.selector,
2595             );
2596 
2597             let regs = X86_64UserRegs {
2598                 regs1,
2599                 regs2,
2600                 rip: gregs.rip,
2601                 cs: sregs.cs.selector as u64,
2602                 eflags: gregs.rflags,
2603                 rsp: gregs.rsp,
2604                 ss: sregs.ss.selector as u64,
2605                 fs_base: sregs.fs.base,
2606                 gs_base: sregs.gs.base,
2607                 ds: sregs.ds.selector as u64,
2608                 es: sregs.es.selector as u64,
2609                 fs: sregs.fs.selector as u64,
2610                 gs: sregs.gs.selector as u64,
2611             };
2612 
2613             // let bytes: &[u8] = unsafe { any_as_u8_slice(&regs) };
2614             let bytes: &[u8] = regs.as_slice();
2615             buf.resize(note_size as usize, 0);
2616             buf.splice(pos.., bytes.to_vec());
2617             buf.resize(note_size as usize, 0);
2618 
2619             coredump_file
2620                 .write(&buf)
2621                 .map_err(GuestDebuggableError::CoredumpFile)?;
2622         }
2623 
2624         Ok(())
2625     }
2626 
2627     fn cpu_write_vmm_note(
2628         &mut self,
2629         dump_state: &DumpState,
2630     ) -> std::result::Result<(), GuestDebuggableError> {
2631         let mut coredump_file = dump_state.file.as_ref().unwrap();
2632         for vcpu in &self.vcpus {
2633             let note_size = self.get_note_size(NoteDescType::Vmm, 1);
2634             let mut pos: usize = 0;
2635             let mut buf = vec![0; note_size as usize];
2636             let descsz = size_of::<DumpCpusState>();
2637             let vcpu_id = vcpu.lock().unwrap().id;
2638 
2639             let note = Elf64_Nhdr {
2640                 n_namesz: COREDUMP_NAME_SIZE,
2641                 n_descsz: descsz as u32,
2642                 n_type: 0,
2643             };
2644 
2645             let bytes: &[u8] = note.as_slice();
2646             buf.splice(0.., bytes.to_vec());
2647             pos += round_up!(size_of::<Elf64_Nhdr>(), 4);
2648 
2649             buf.resize(pos + 4, 0);
2650             buf.splice(pos.., "QEMU".to_string().into_bytes());
2651 
2652             pos += round_up!(COREDUMP_NAME_SIZE as usize, 4);
2653 
2654             let gregs = self.vcpus[usize::from(vcpu_id)]
2655                 .lock()
2656                 .unwrap()
2657                 .vcpu
2658                 .get_regs()
2659                 .map_err(|_e| GuestDebuggableError::Coredump(anyhow!("get regs failed")))?;
2660 
2661             let regs1 = [
2662                 gregs.rax, gregs.rbx, gregs.rcx, gregs.rdx, gregs.rsi, gregs.rdi, gregs.rsp,
2663                 gregs.rbp,
2664             ];
2665 
2666             let regs2 = [
2667                 gregs.r8, gregs.r9, gregs.r10, gregs.r11, gregs.r12, gregs.r13, gregs.r14,
2668                 gregs.r15,
2669             ];
2670 
2671             let sregs = self.vcpus[usize::from(vcpu_id)]
2672                 .lock()
2673                 .unwrap()
2674                 .vcpu
2675                 .get_sregs()
2676                 .map_err(|_e| GuestDebuggableError::Coredump(anyhow!("get sregs failed")))?;
2677 
2678             let mut msrs = vec![MsrEntry {
2679                 index: msr_index::MSR_KERNEL_GS_BASE,
2680                 ..Default::default()
2681             }];
2682 
2683             self.vcpus[vcpu_id as usize]
2684                 .lock()
2685                 .unwrap()
2686                 .vcpu
2687                 .get_msrs(&mut msrs)
2688                 .map_err(|_e| GuestDebuggableError::Coredump(anyhow!("get msr failed")))?;
2689             let kernel_gs_base = msrs[0].data;
2690 
2691             let cs = CpuSegment::new(sregs.cs);
2692             let ds = CpuSegment::new(sregs.ds);
2693             let es = CpuSegment::new(sregs.es);
2694             let fs = CpuSegment::new(sregs.fs);
2695             let gs = CpuSegment::new(sregs.gs);
2696             let ss = CpuSegment::new(sregs.ss);
2697             let ldt = CpuSegment::new(sregs.ldt);
2698             let tr = CpuSegment::new(sregs.tr);
2699             let gdt = CpuSegment::new_from_table(sregs.gdt);
2700             let idt = CpuSegment::new_from_table(sregs.idt);
2701             let cr = [sregs.cr0, sregs.cr8, sregs.cr2, sregs.cr3, sregs.cr4];
2702             let regs = DumpCpusState {
2703                 version: 1,
2704                 size: size_of::<DumpCpusState>() as u32,
2705                 regs1,
2706                 regs2,
2707                 rip: gregs.rip,
2708                 rflags: gregs.rflags,
2709                 cs,
2710                 ds,
2711                 es,
2712                 fs,
2713                 gs,
2714                 ss,
2715                 ldt,
2716                 tr,
2717                 gdt,
2718                 idt,
2719                 cr,
2720                 kernel_gs_base,
2721             };
2722 
2723             let bytes: &[u8] = regs.as_slice();
2724             buf.resize(note_size as usize, 0);
2725             buf.splice(pos.., bytes.to_vec());
2726             buf.resize(note_size as usize, 0);
2727 
2728             coredump_file
2729                 .write(&buf)
2730                 .map_err(GuestDebuggableError::CoredumpFile)?;
2731         }
2732 
2733         Ok(())
2734     }
2735 }
2736 
2737 #[cfg(all(feature = "kvm", target_arch = "x86_64"))]
2738 #[cfg(test)]
2739 mod tests {
2740     use arch::layout::BOOT_STACK_POINTER;
2741     use arch::layout::ZERO_PAGE_START;
2742     use arch::x86_64::interrupts::*;
2743     use arch::x86_64::regs::*;
2744     use hypervisor::arch::x86::{FpuState, LapicState, StandardRegisters};
2745     use linux_loader::loader::bootparam::setup_header;
2746 
2747     #[test]
2748     fn test_setlint() {
2749         let hv = hypervisor::new().unwrap();
2750         let vm = hv.create_vm().expect("new VM fd creation failed");
2751         assert!(hv.check_required_extensions().is_ok());
2752         // Calling get_lapic will fail if there is no irqchip before hand.
2753         assert!(vm.create_irq_chip().is_ok());
2754         let vcpu = vm.create_vcpu(0, None).unwrap();
2755         let klapic_before: LapicState = vcpu.get_lapic().unwrap();
2756 
2757         // Compute the value that is expected to represent LVT0 and LVT1.
2758         let lint0 = klapic_before.get_klapic_reg(APIC_LVT0);
2759         let lint1 = klapic_before.get_klapic_reg(APIC_LVT1);
2760         let lint0_mode_expected = set_apic_delivery_mode(lint0, APIC_MODE_EXTINT);
2761         let lint1_mode_expected = set_apic_delivery_mode(lint1, APIC_MODE_NMI);
2762 
2763         set_lint(&vcpu).unwrap();
2764 
2765         // Compute the value that represents LVT0 and LVT1 after set_lint.
2766         let klapic_actual: LapicState = vcpu.get_lapic().unwrap();
2767         let lint0_mode_actual = klapic_actual.get_klapic_reg(APIC_LVT0);
2768         let lint1_mode_actual = klapic_actual.get_klapic_reg(APIC_LVT1);
2769         assert_eq!(lint0_mode_expected, lint0_mode_actual);
2770         assert_eq!(lint1_mode_expected, lint1_mode_actual);
2771     }
2772 
2773     #[test]
2774     fn test_setup_fpu() {
2775         let hv = hypervisor::new().unwrap();
2776         let vm = hv.create_vm().expect("new VM fd creation failed");
2777         let vcpu = vm.create_vcpu(0, None).unwrap();
2778         setup_fpu(&vcpu).unwrap();
2779 
2780         let expected_fpu: FpuState = FpuState {
2781             fcw: 0x37f,
2782             mxcsr: 0x1f80,
2783             ..Default::default()
2784         };
2785         let actual_fpu: FpuState = vcpu.get_fpu().unwrap();
2786         // TODO: auto-generate kvm related structures with PartialEq on.
2787         assert_eq!(expected_fpu.fcw, actual_fpu.fcw);
2788         // Setting the mxcsr register from FpuState inside setup_fpu does not influence anything.
2789         // See 'kvm_arch_vcpu_ioctl_set_fpu' from arch/x86/kvm/x86.c.
2790         // The mxcsr will stay 0 and the assert below fails. Decide whether or not we should
2791         // remove it at all.
2792         // assert!(expected_fpu.mxcsr == actual_fpu.mxcsr);
2793     }
2794 
2795     #[test]
2796     fn test_setup_msrs() {
2797         use hypervisor::arch::x86::{msr_index, MsrEntry};
2798 
2799         let hv = hypervisor::new().unwrap();
2800         let vm = hv.create_vm().expect("new VM fd creation failed");
2801         let vcpu = vm.create_vcpu(0, None).unwrap();
2802         setup_msrs(&vcpu).unwrap();
2803 
2804         // This test will check against the last MSR entry configured (the tenth one).
2805         // See create_msr_entries for details.
2806         let mut msrs = vec![MsrEntry {
2807             index: msr_index::MSR_IA32_MISC_ENABLE,
2808             ..Default::default()
2809         }];
2810 
2811         // get_msrs returns the number of msrs that it succeed in reading. We only want to read 1
2812         // in this test case scenario.
2813         let read_msrs = vcpu.get_msrs(&mut msrs).unwrap();
2814         assert_eq!(read_msrs, 1);
2815 
2816         // Official entries that were setup when we did setup_msrs. We need to assert that the
2817         // tenth one (i.e the one with index msr_index::MSR_IA32_MISC_ENABLE has the data we
2818         // expect.
2819         let entry_vec = vcpu.boot_msr_entries();
2820         assert_eq!(entry_vec.as_slice()[9], msrs.as_slice()[0]);
2821     }
2822 
2823     #[test]
2824     fn test_setup_regs_for_pvh() {
2825         let hv = hypervisor::new().unwrap();
2826         let vm = hv.create_vm().expect("new VM fd creation failed");
2827         let vcpu = vm.create_vcpu(0, None).unwrap();
2828 
2829         let expected_regs: StandardRegisters = StandardRegisters {
2830             rflags: 0x0000000000000002u64,
2831             rbx: arch::layout::PVH_INFO_START.0,
2832             rip: 1,
2833             ..Default::default()
2834         };
2835 
2836         setup_regs(
2837             &vcpu,
2838             arch::EntryPoint {
2839                 entry_addr: vm_memory::GuestAddress(expected_regs.rip),
2840                 setup_header: None,
2841             },
2842         )
2843         .unwrap();
2844 
2845         let actual_regs: StandardRegisters = vcpu.get_regs().unwrap();
2846         assert_eq!(actual_regs, expected_regs);
2847     }
2848 
2849     #[test]
2850     fn test_setup_regs_for_bzimage() {
2851         let hv = hypervisor::new().unwrap();
2852         let vm = hv.create_vm().expect("new VM fd creation failed");
2853         let vcpu = vm.create_vcpu(0, None).unwrap();
2854 
2855         let expected_regs: StandardRegisters = StandardRegisters {
2856             rflags: 0x0000000000000002u64,
2857             rip: 1,
2858             rsp: BOOT_STACK_POINTER.0,
2859             rsi: ZERO_PAGE_START.0,
2860             ..Default::default()
2861         };
2862 
2863         setup_regs(
2864             &vcpu,
2865             arch::EntryPoint {
2866                 entry_addr: vm_memory::GuestAddress(expected_regs.rip),
2867                 setup_header: Some(setup_header {
2868                     ..Default::default()
2869                 }),
2870             },
2871         )
2872         .unwrap();
2873 
2874         let actual_regs: StandardRegisters = vcpu.get_regs().unwrap();
2875         assert_eq!(actual_regs, expected_regs);
2876     }
2877 }
2878 
2879 #[cfg(target_arch = "aarch64")]
2880 #[cfg(test)]
2881 mod tests {
2882     use arch::{aarch64::regs, layout};
2883     use hypervisor::kvm::aarch64::is_system_register;
2884     use hypervisor::kvm::kvm_bindings::{
2885         kvm_regs, kvm_vcpu_init, user_pt_regs, KVM_REG_ARM64, KVM_REG_ARM64_SYSREG,
2886         KVM_REG_ARM_CORE, KVM_REG_SIZE_U64,
2887     };
2888     use hypervisor::{arm64_core_reg_id, offset_of};
2889     use std::mem;
2890 
2891     #[test]
2892     fn test_setup_regs() {
2893         let hv = hypervisor::new().unwrap();
2894         let vm = hv.create_vm().unwrap();
2895         let vcpu = vm.create_vcpu(0, None).unwrap();
2896 
2897         let res = vcpu.setup_regs(0, 0x0, layout::FDT_START.0);
2898         // Must fail when vcpu is not initialized yet.
2899         assert!(res.is_err());
2900 
2901         let mut kvi: kvm_vcpu_init = kvm_vcpu_init::default();
2902         vm.get_preferred_target(&mut kvi).unwrap();
2903         vcpu.vcpu_init(&kvi).unwrap();
2904 
2905         assert!(vcpu.setup_regs(0, 0x0, layout::FDT_START.0).is_ok());
2906     }
2907 
2908     #[test]
2909     fn test_read_mpidr() {
2910         let hv = hypervisor::new().unwrap();
2911         let vm = hv.create_vm().unwrap();
2912         let vcpu = vm.create_vcpu(0, None).unwrap();
2913         let mut kvi: kvm_vcpu_init = kvm_vcpu_init::default();
2914         vm.get_preferred_target(&mut kvi).unwrap();
2915 
2916         // Must fail when vcpu is not initialized yet.
2917         assert!(vcpu.get_sys_reg(regs::MPIDR_EL1).is_err());
2918 
2919         vcpu.vcpu_init(&kvi).unwrap();
2920         assert_eq!(vcpu.get_sys_reg(regs::MPIDR_EL1).unwrap(), 0x80000000);
2921     }
2922 
2923     #[test]
2924     fn test_is_system_register() {
2925         let offset = offset_of!(user_pt_regs, pc);
2926         let regid = arm64_core_reg_id!(KVM_REG_SIZE_U64, offset);
2927         assert!(!is_system_register(regid));
2928         let regid = KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM64_SYSREG as u64;
2929         assert!(is_system_register(regid));
2930     }
2931 
2932     #[test]
2933     fn test_save_restore_core_regs() {
2934         let hv = hypervisor::new().unwrap();
2935         let vm = hv.create_vm().unwrap();
2936         let vcpu = vm.create_vcpu(0, None).unwrap();
2937         let mut kvi: kvm_vcpu_init = kvm_vcpu_init::default();
2938         vm.get_preferred_target(&mut kvi).unwrap();
2939 
2940         // Must fail when vcpu is not initialized yet.
2941         let res = vcpu.get_regs();
2942         assert!(res.is_err());
2943         assert_eq!(
2944             format!("{}", res.unwrap_err()),
2945             "Failed to get core register: Exec format error (os error 8)"
2946         );
2947 
2948         let mut state = kvm_regs::default();
2949         let res = vcpu.set_regs(&state);
2950         assert!(res.is_err());
2951         assert_eq!(
2952             format!("{}", res.unwrap_err()),
2953             "Failed to set core register: Exec format error (os error 8)"
2954         );
2955 
2956         vcpu.vcpu_init(&kvi).unwrap();
2957         let res = vcpu.get_regs();
2958         assert!(res.is_ok());
2959         state = res.unwrap();
2960         assert_eq!(state.regs.pstate, 0x3C5);
2961 
2962         assert!(vcpu.set_regs(&state).is_ok());
2963     }
2964 
2965     #[test]
2966     fn test_get_set_mpstate() {
2967         let hv = hypervisor::new().unwrap();
2968         let vm = hv.create_vm().unwrap();
2969         let vcpu = vm.create_vcpu(0, None).unwrap();
2970         let mut kvi: kvm_vcpu_init = kvm_vcpu_init::default();
2971         vm.get_preferred_target(&mut kvi).unwrap();
2972 
2973         let res = vcpu.get_mp_state();
2974         assert!(res.is_ok());
2975         assert!(vcpu.set_mp_state(res.unwrap()).is_ok());
2976     }
2977 }
2978