vm_control/
lib.rs

1// Copyright 2017 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Handles IPC for controlling the main VM process.
6//!
7//! The VM Control IPC protocol is synchronous, meaning that each `VmRequest` sent over a connection
8//! will receive a `VmResponse` for that request next time data is received over that connection.
9//!
10//! The wire message format is a little-endian C-struct of fixed size, along with a file descriptor
11//! if the request type expects one.
12
13pub mod api;
14
15mod any_control_tube;
16pub use any_control_tube::AnyControlTube;
17
18mod device_id;
19pub use device_id::DeviceId;
20pub use device_id::PciId;
21pub use device_id::PlatformDeviceId;
22
23#[cfg(feature = "gdb")]
24pub mod gdb;
25pub mod gpu;
26
27use base::debug;
28#[cfg(any(target_os = "android", target_os = "linux"))]
29use base::linux::MemoryMappingBuilderUnix;
30#[cfg(any(target_os = "android", target_os = "linux"))]
31use base::sys::call_with_extended_max_files;
32#[cfg(any(target_os = "android", target_os = "linux"))]
33use base::MemoryMappingArena;
34#[cfg(windows)]
35use base::MemoryMappingBuilderWindows;
36use hypervisor::BalloonEvent;
37use hypervisor::MemCacheType;
38use hypervisor::MemRegion;
39use snapshot::AnySnapshot;
40
41#[cfg(feature = "balloon")]
42mod balloon_tube;
43pub mod client;
44pub mod sys;
45
46#[cfg(target_arch = "x86_64")]
47use std::arch::x86_64::_rdtsc;
48use std::collections::BTreeMap;
49use std::collections::BTreeSet;
50use std::collections::HashMap;
51use std::convert::TryInto;
52use std::fmt;
53use std::fmt::Display;
54use std::fs::File;
55use std::path::Path;
56use std::path::PathBuf;
57use std::result::Result as StdResult;
58use std::str::FromStr;
59use std::sync::mpsc;
60use std::sync::Arc;
61use std::time::Instant;
62
63use anyhow::bail;
64use anyhow::Context;
65use base::error;
66use base::info;
67use base::warn;
68use base::with_as_descriptor;
69use base::AsRawDescriptor;
70use base::Descriptor;
71use base::Error as SysError;
72use base::Event;
73use base::ExternalMapping;
74#[cfg(feature = "gpu")]
75use base::IntoRawDescriptor;
76use base::MappedRegion;
77use base::MemoryMappingBuilder;
78use base::MmapError;
79use base::Protection;
80use base::Result;
81use base::SafeDescriptor;
82use base::SharedMemory;
83use base::Tube;
84use hypervisor::Datamatch;
85use hypervisor::IoEventAddress;
86use hypervisor::IrqRoute;
87use hypervisor::IrqSource;
88pub use hypervisor::MemSlot;
89use hypervisor::Vm;
90use hypervisor::VmCap;
91use libc::EINVAL;
92use libc::EIO;
93use libc::ENODEV;
94use libc::ENOTSUP;
95use libc::EPERM;
96use libc::ERANGE;
97#[cfg(feature = "registered_events")]
98use protos::registered_events;
99use remain::sorted;
100use resources::Alloc;
101use resources::SystemAllocator;
102#[cfg(feature = "gpu")]
103use rutabaga_gfx::RutabagaDescriptor;
104#[cfg(feature = "gpu")]
105use rutabaga_gfx::RutabagaFromRawDescriptor;
106#[cfg(feature = "gpu")]
107use rutabaga_gfx::RutabagaGralloc;
108#[cfg(feature = "gpu")]
109use rutabaga_gfx::RutabagaMagmaHandle;
110#[cfg(feature = "gpu")]
111use rutabaga_gfx::RutabagaMappedRegion;
112#[cfg(feature = "gpu")]
113use rutabaga_gfx::VulkanInfo;
114use serde::de::Error;
115use serde::Deserialize;
116use serde::Serialize;
117use snapshot::SnapshotReader;
118use snapshot::SnapshotWriter;
119use swap::SwapStatus;
120use sync::Mutex;
121#[cfg(any(target_os = "android", target_os = "linux"))]
122pub use sys::FsMappingRequest;
123#[cfg(windows)]
124pub use sys::InitialAudioSessionState;
125#[cfg(any(target_os = "android", target_os = "linux"))]
126pub use sys::VmMemoryMappingRequest;
127#[cfg(any(target_os = "android", target_os = "linux"))]
128pub use sys::VmMemoryMappingResponse;
129use thiserror::Error;
130pub use vm_control_product::GpuSendToMain;
131pub use vm_control_product::GpuSendToService;
132pub use vm_control_product::ServiceSendToGpu;
133use vm_memory::GuestAddress;
134
135#[cfg(feature = "balloon")]
136pub use crate::balloon_tube::BalloonControlCommand;
137#[cfg(feature = "balloon")]
138pub use crate::balloon_tube::BalloonTube;
139#[cfg(feature = "gdb")]
140pub use crate::gdb::VcpuDebug;
141#[cfg(feature = "gdb")]
142pub use crate::gdb::VcpuDebugStatus;
143#[cfg(feature = "gdb")]
144pub use crate::gdb::VcpuDebugStatusMessage;
145use crate::gpu::GpuControlCommand;
146use crate::gpu::GpuControlResult;
147
148/// Control the state of a particular VM CPU.
149#[derive(Clone, Debug)]
150pub enum VcpuControl {
151    #[cfg(feature = "gdb")]
152    Debug(VcpuDebug),
153    RunState(VmRunMode),
154    MakeRT,
155    // Request the current state of the vCPU. The result is sent back over the included channel.
156    GetStates(mpsc::Sender<VmRunMode>),
157    // Request the vcpu write a snapshot of itself to the writer, then send a `Result` back over
158    // the channel after completion/failure.
159    Snapshot(SnapshotWriter, mpsc::Sender<anyhow::Result<()>>),
160    Restore(VcpuRestoreRequest),
161    #[cfg(any(target_os = "android", target_os = "linux"))]
162    Throttle(u32),
163}
164
165/// Request to restore a Vcpu from a given snapshot, and report the results
166/// back via the provided channel.
167#[derive(Clone, Debug)]
168pub struct VcpuRestoreRequest {
169    pub result_sender: mpsc::Sender<anyhow::Result<()>>,
170    pub snapshot_reader: SnapshotReader,
171    #[cfg(target_arch = "x86_64")]
172    pub host_tsc_reference_moment: u64,
173}
174
175/// Mode of execution for the VM.
176#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
177pub enum VmRunMode {
178    /// The default run mode indicating the VCPUs are running.
179    #[default]
180    Running,
181    /// Indicates that the VCPUs are suspending execution until the `Running` mode is set.
182    Suspending,
183    /// Indicates that the VM is exiting all processes.
184    Exiting,
185    /// Indicates that the VM is in a breakpoint waiting for the debugger to do continue.
186    Breakpoint,
187}
188
189impl Display for VmRunMode {
190    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
191        use self::VmRunMode::*;
192
193        match self {
194            Running => write!(f, "running"),
195            Suspending => write!(f, "suspending"),
196            Exiting => write!(f, "exiting"),
197            Breakpoint => write!(f, "breakpoint"),
198        }
199    }
200}
201
202// Trait for devices that get notification on specific PCI PME
203pub trait PmeNotify: Send {
204    fn notify(&mut self, _requester_id: u16) {}
205}
206
207pub trait PmResource {
208    fn pwrbtn_evt(&mut self) {}
209    fn slpbtn_evt(&mut self) {}
210    fn rtc_evt(&mut self, _clear_evt: Event) {}
211    fn gpe_evt(&mut self, _gpe: u32, _clear_evt: Option<Event>) {}
212    fn pme_evt(&mut self, _requester_id: u16) {}
213    fn register_pme_notify_dev(&mut self, _bus: u8, _notify_dev: Arc<Mutex<dyn PmeNotify>>) {}
214}
215
216/// The maximum number of devices that can be listed in one `UsbControlCommand`.
217///
218/// This value was set to be equal to `xhci_regs::MAX_PORTS` for convenience, but it is not
219/// necessary for correctness. Importing that value directly would be overkill because it would
220/// require adding a big dependency for a single const.
221pub const USB_CONTROL_MAX_PORTS: usize = 16;
222
223#[derive(Serialize, Deserialize, Debug)]
224pub enum DiskControlCommand {
225    /// Resize a disk to `new_size` in bytes.
226    Resize { new_size: u64 },
227}
228
229impl Display for DiskControlCommand {
230    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
231        use self::DiskControlCommand::*;
232
233        match self {
234            Resize { new_size } => write!(f, "disk_resize {new_size}"),
235        }
236    }
237}
238
239#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
240pub enum DiskControlResult {
241    Ok,
242    Err(SysError),
243}
244
245#[derive(Serialize, Deserialize, Debug, Clone)]
246pub enum FsAllowlistCommand {
247    AddPaths { paths: Vec<PathBuf> },
248    RemovePaths { paths: Vec<PathBuf> },
249}
250
251#[derive(Serialize, Deserialize, Debug, Clone)]
252pub enum FsAllowlistResponse {
253    Ok,
254    Err(String),
255}
256
257/// Wire protocol request for virtio-snd host audio permission delegation.
258#[repr(u8)]
259#[derive(Copy, Clone, Debug, PartialEq, Eq)]
260pub enum AudioPermissionRequest {
261    /// Audio capture stream starting; request host permission.
262    Check = 1,
263}
264
265impl AudioPermissionRequest {
266    pub const fn to_wire(self) -> u8 {
267        self as u8
268    }
269}
270
271impl TryFrom<u8> for AudioPermissionRequest {
272    type Error = u8;
273
274    fn try_from(val: u8) -> StdResult<Self, Self::Error> {
275        match val {
276            1 => Ok(Self::Check),
277            unknown => Err(unknown),
278        }
279    }
280}
281
282/// Wire protocol response for virtio-snd host audio permission delegation.
283#[repr(u8)]
284#[derive(Copy, Clone, Debug, PartialEq, Eq)]
285pub enum AudioPermissionResponse {
286    /// Permission granted by the user or host policy.
287    Granted = 1,
288    /// Permission denied by the user, host policy, or client disconnect.
289    Denied = 2,
290}
291
292impl AudioPermissionResponse {
293    pub const fn to_wire(self) -> u8 {
294        self as u8
295    }
296}
297
298impl TryFrom<u8> for AudioPermissionResponse {
299    type Error = u8;
300
301    fn try_from(val: u8) -> StdResult<Self, Self::Error> {
302        match val {
303            1 => Ok(Self::Granted),
304            2 => Ok(Self::Denied),
305            unknown => Err(unknown),
306        }
307    }
308}
309
310/// Net control commands for adding and removing tap devices.
311#[cfg(feature = "pci-hotplug")]
312#[derive(Serialize, Deserialize, Debug)]
313pub enum NetControlCommand {
314    AddTap(String),
315    RemoveTap(u8),
316}
317
318#[derive(Serialize, Deserialize, Debug)]
319pub enum UsbControlCommand {
320    AttachDevice {
321        #[serde(with = "with_as_descriptor")]
322        file: File,
323    },
324    AttachSecurityKey {
325        #[serde(with = "with_as_descriptor")]
326        file: File,
327    },
328    DetachDevice {
329        port: u8,
330    },
331    ListDevice {
332        ports: [u8; USB_CONTROL_MAX_PORTS],
333    },
334}
335
336#[derive(Serialize, Deserialize, Copy, Clone, Debug, Default)]
337pub struct UsbControlAttachedDevice {
338    pub port: u8,
339    pub vendor_id: u16,
340    pub product_id: u16,
341}
342
343impl UsbControlAttachedDevice {
344    pub fn valid(self) -> bool {
345        self.port != 0
346    }
347}
348
349#[cfg(feature = "pci-hotplug")]
350#[derive(Serialize, Deserialize, Debug, Clone)]
351#[must_use]
352/// Result for hotplug and removal of PCI device.
353pub enum PciControlResult {
354    AddOk { bus: u8 },
355    ErrString(String),
356    RemoveOk,
357}
358
359#[cfg(feature = "pci-hotplug")]
360impl Display for PciControlResult {
361    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362        use self::PciControlResult::*;
363
364        match self {
365            AddOk { bus } => write!(f, "add_ok {bus}"),
366            ErrString(e) => write!(f, "error: {e}"),
367            RemoveOk => write!(f, "remove_ok"),
368        }
369    }
370}
371
372#[derive(Serialize, Deserialize, Debug, Clone)]
373pub enum UsbControlResult {
374    Ok { port: u8 },
375    NoAvailablePort,
376    NoSuchDevice,
377    NoSuchPort,
378    FailedToOpenDevice,
379    Devices([UsbControlAttachedDevice; USB_CONTROL_MAX_PORTS]),
380    FailedToInitHostDevice,
381}
382
383impl Display for UsbControlResult {
384    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
385        use self::UsbControlResult::*;
386
387        match self {
388            UsbControlResult::Ok { port } => write!(f, "ok {port}"),
389            NoAvailablePort => write!(f, "no_available_port"),
390            NoSuchDevice => write!(f, "no_such_device"),
391            NoSuchPort => write!(f, "no_such_port"),
392            FailedToOpenDevice => write!(f, "failed_to_open_device"),
393            Devices(devices) => {
394                write!(f, "devices")?;
395                for d in devices.iter().filter(|d| d.valid()) {
396                    write!(f, " {} {:04x} {:04x}", d.port, d.vendor_id, d.product_id)?;
397                }
398                std::result::Result::Ok(())
399            }
400            FailedToInitHostDevice => write!(f, "failed_to_init_host_device"),
401        }
402    }
403}
404
405/// Commands for snapshot feature
406#[derive(Serialize, Deserialize, Debug)]
407pub enum SnapshotCommand {
408    Take {
409        snapshot_path: PathBuf,
410        compress_memory: bool,
411        encrypt: bool,
412    },
413}
414
415/// Commands for actions on devices and the devices control thread.
416#[derive(Serialize, Deserialize, Debug)]
417pub enum DeviceControlCommand {
418    SleepDevices,
419    WakeDevices,
420    SnapshotDevices { snapshot_writer: SnapshotWriter },
421    RestoreDevices { snapshot_reader: SnapshotReader },
422    GetDevicesState,
423    Exit,
424}
425
426/// Commands to control the IRQ handler thread.
427#[derive(Serialize, Deserialize)]
428pub enum IrqHandlerRequest {
429    /// No response is sent for this command.
430    AddIrqControlTubes(Vec<Tube>),
431    /// Refreshes the set of event tokens (Events) from the Irqchip that the IRQ
432    /// handler waits on to forward IRQs to their final destination (e.g. via
433    /// Irqchip::service_irq_event).
434    ///
435    /// If the set of tokens exposed by the Irqchip changes while the VM is
436    /// running (such as for snapshot restore), this command must be sent
437    /// otherwise the VM will not receive IRQs as expected.
438    RefreshIrqEventTokens,
439    WakeAndNotifyIteration,
440    /// No response is sent for this command.
441    Exit,
442}
443
444const EXPECTED_MAX_IRQ_FLUSH_ITERATIONS: usize = 100;
445
446/// Response for [IrqHandlerRequest].
447#[derive(Serialize, Deserialize, Debug)]
448pub enum IrqHandlerResponse {
449    /// Sent when the IRQ event tokens have been refreshed.
450    IrqEventTokenRefreshComplete,
451    /// Specifies the number of tokens serviced in the requested iteration
452    /// (less the token for the `WakeAndNotifyIteration` request).
453    HandlerIterationComplete(usize),
454}
455
456/// Source of a `VmMemoryRequest::RegisterMemory` mapping.
457#[derive(Serialize, Deserialize)]
458pub enum VmMemorySource {
459    /// Register shared memory represented by the given descriptor.
460    /// On Windows, descriptor MUST be a mapping handle.
461    SharedMemory(SharedMemory),
462    /// Register a file mapping from the given descriptor.
463    Descriptor {
464        /// File descriptor to map.
465        descriptor: SafeDescriptor,
466        /// Offset within the file in bytes.
467        offset: u64,
468        /// Size of the mapping in bytes.
469        size: u64,
470    },
471    /// Register memory mapped by Vulkano.
472    Vulkan {
473        descriptor: SafeDescriptor,
474        handle_type: u32,
475        memory_idx: u32,
476        device_uuid: [u8; 16],
477        driver_uuid: [u8; 16],
478        size: u64,
479    },
480    /// Register the current rutabaga external mapping.
481    ExternalMapping { ptr: u64, size: u64 },
482}
483
484// The following are wrappers to avoid base dependencies in the rutabaga crate
485#[cfg(feature = "gpu")]
486fn to_rutabaga_desciptor(s: SafeDescriptor) -> RutabagaDescriptor {
487    // SAFETY:
488    // Safe because we own the SafeDescriptor at this point.
489    unsafe { RutabagaDescriptor::from_raw_descriptor(s.into_raw_descriptor()) }
490}
491
492#[cfg(feature = "gpu")]
493struct RutabagaMemoryRegion {
494    region: Box<dyn RutabagaMappedRegion>,
495}
496
497#[cfg(feature = "gpu")]
498impl RutabagaMemoryRegion {
499    pub fn new(region: Box<dyn RutabagaMappedRegion>) -> RutabagaMemoryRegion {
500        RutabagaMemoryRegion { region }
501    }
502}
503
504#[cfg(feature = "gpu")]
505// SAFETY:
506//
507// Self guarantees `ptr`..`ptr+size` is an mmaped region owned by this object that
508// can't be unmapped during the `MappedRegion`'s lifetime.
509unsafe impl MappedRegion for RutabagaMemoryRegion {
510    fn as_ptr(&self) -> *mut u8 {
511        self.region.as_ptr()
512    }
513
514    fn size(&self) -> usize {
515        self.region.size()
516    }
517}
518
519impl Display for VmMemorySource {
520    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
521        use self::VmMemorySource::*;
522
523        match self {
524            SharedMemory(..) => write!(f, "VmMemorySource::SharedMemory"),
525            Descriptor { .. } => write!(f, "VmMemorySource::Descriptor"),
526            Vulkan { .. } => write!(f, "VmMemorySource::Vulkan"),
527            ExternalMapping { .. } => write!(f, "VmMemorySource::ExternalMapping"),
528        }
529    }
530}
531
532impl VmMemorySource {
533    /// Map the resource and return its mapping and size in bytes.
534    fn map(
535        self,
536        #[cfg(feature = "gpu")] gralloc: &mut RutabagaGralloc,
537        prot: Protection,
538    ) -> anyhow::Result<(Box<dyn MappedRegion>, u64, Option<SafeDescriptor>)> {
539        let (mem_region, size, descriptor) = match self {
540            VmMemorySource::Descriptor {
541                descriptor,
542                offset,
543                size,
544            } => (
545                map_descriptor(&descriptor, offset, size, prot)?,
546                size,
547                Some(descriptor),
548            ),
549
550            VmMemorySource::SharedMemory(shm) => {
551                (map_descriptor(&shm, 0, shm.size(), prot)?, shm.size(), None)
552            }
553            #[cfg(feature = "gpu")]
554            VmMemorySource::Vulkan {
555                descriptor,
556                handle_type,
557                memory_idx,
558                device_uuid,
559                driver_uuid,
560                size,
561            } => {
562                let device_id = rutabaga_gfx::DeviceId {
563                    device_uuid,
564                    driver_uuid,
565                };
566                let mapped_region = gralloc
567                        .import_and_map(
568                            RutabagaMagmaHandle {
569                                os_handle: to_rutabaga_desciptor(descriptor),
570                                handle_type,
571                            },
572                            VulkanInfo {
573                                memory_idx,
574                                device_id,
575                            },
576                            size,
577                        )
578                        .with_context(|| {
579                            format!(
580                                "gralloc failed to import and map, handle type: {handle_type}, memory index {memory_idx}, \
581                                size: {size}"
582                            )
583                        })?;
584                let mapped_region: Box<dyn MappedRegion> =
585                    Box::new(RutabagaMemoryRegion::new(mapped_region));
586                (mapped_region, size, None)
587            }
588            #[cfg(not(feature = "gpu"))]
589            VmMemorySource::Vulkan { .. } => {
590                return Err(anyhow::anyhow!(
591                    "vulkan mapping is not supported without GPU feature"
592                ));
593            }
594            VmMemorySource::ExternalMapping { ptr, size } => {
595                let mapped_region: Box<dyn MappedRegion> = Box::new(ExternalMapping {
596                    ptr,
597                    size: size as usize,
598                });
599                (mapped_region, size, None)
600            }
601        };
602        Ok((mem_region, size, descriptor))
603    }
604}
605
606/// Destination of a `VmMemoryRequest::RegisterMemory` mapping in guest address space.
607#[derive(Serialize, Deserialize)]
608pub enum VmMemoryDestination {
609    /// Map at an offset within an existing PCI BAR allocation.
610    ExistingAllocation { allocation: Alloc, offset: u64 },
611    /// Map at the specified guest physical address.
612    GuestPhysicalAddress(u64),
613}
614
615impl VmMemoryDestination {
616    /// Allocate and return the guest address of a memory mapping destination.
617    pub fn allocate(self, allocator: &mut SystemAllocator, size: u64) -> Result<GuestAddress> {
618        let addr = match self {
619            VmMemoryDestination::ExistingAllocation { allocation, offset } => allocator
620                .mmio_allocator_any()
621                .address_from_pci_offset(allocation, offset, size)
622                .map_err(|_e| SysError::new(EINVAL))?,
623            VmMemoryDestination::GuestPhysicalAddress(gpa) => gpa,
624        };
625        Ok(GuestAddress(addr))
626    }
627}
628
629/// Request to register or unregister an ioevent.
630#[derive(Serialize, Deserialize)]
631pub struct IoEventUpdateRequest {
632    pub event: Event,
633    pub addr: u64,
634    pub datamatch: Datamatch,
635    pub register: bool,
636}
637
638/// Request to mmap a file to a shared memory.
639/// This request is supposed to follow a `VmMemoryRequest::MmapAndRegisterMemory` request that
640/// contains `SharedMemory` that `file` is mmaped to.
641#[cfg(any(target_os = "android", target_os = "linux"))]
642#[derive(Serialize, Deserialize)]
643pub struct VmMemoryFileMapping {
644    #[serde(with = "with_as_descriptor")]
645    pub file: File,
646    pub length: usize,
647    pub mem_offset: usize,
648    pub file_offset: u64,
649}
650
651#[derive(Serialize, Deserialize)]
652pub enum VmMemoryRequest {
653    /// Prepare a shared memory region to make later operations more efficient. This
654    /// may be a no-op depending on underlying platform support.
655    PrepareSharedMemoryRegion {
656        alloc: Alloc,
657        cache: MemCacheType,
658        force: bool,
659    },
660    /// Register a memory to be mapped to the guest.
661    RegisterMemory {
662        /// Source of the memory to register (mapped file descriptor, shared memory region, etc.)
663        source: VmMemorySource,
664        /// Where to map the memory in the guest.
665        dest: VmMemoryDestination,
666        /// Whether to map the memory read only (true) or read-write (false).
667        prot: Protection,
668        /// Cache attribute for guest memory setting
669        cache: MemCacheType,
670    },
671    #[cfg(any(target_os = "android", target_os = "linux"))]
672    /// Call mmap to `shm` and register the memory region as a read-only guest memory.
673    /// This request is followed by an array of `VmMemoryFileMapping` with length
674    /// `num_file_mappings`
675    MmapAndRegisterMemory {
676        /// Source of the memory to register (mapped file descriptor, shared memory region, etc.)
677        shm: SharedMemory,
678        /// Where to map the memory in the guest.
679        dest: VmMemoryDestination,
680        /// Length of the array of `VmMemoryFileMapping` that follows.
681        num_file_mappings: usize,
682    },
683    /// Call hypervisor to free the given memory range.
684    DynamicallyFreeMemoryRanges { ranges: Vec<(GuestAddress, u64)> },
685    /// Call hypervisor to reclaim a priorly freed memory range.
686    DynamicallyReclaimMemoryRanges { ranges: Vec<(GuestAddress, u64)> },
687    /// Balloon allocation/deallocation target reached.
688    BalloonTargetReached { size: u64 },
689    /// Unregister the given memory slot that was previously registered with `RegisterMemory`.
690    UnregisterMemory(VmMemoryRegionId),
691    /// Register an eventfd with raw guest memory address.
692    IoEventRaw(IoEventUpdateRequest),
693}
694
695/// Struct for managing `VmMemoryRequest`s IOMMU related state.
696pub struct VmMemoryRequestIommuClient {
697    tube: Arc<Mutex<Tube>>,
698    registered_memory: BTreeSet<VmMemoryRegionId>,
699}
700
701impl VmMemoryRequestIommuClient {
702    /// Constructs `VmMemoryRequestIommuClient` from a tube for communication with the viommu.
703    pub fn new(tube: Arc<Mutex<Tube>>) -> Self {
704        Self {
705            tube,
706            registered_memory: BTreeSet::new(),
707        }
708    }
709}
710
711enum RegisteredMemory {
712    FixedMapping {
713        slot: MemSlot,
714        offset: usize,
715        size: usize,
716    },
717    DynamicMapping {
718        slot: MemSlot,
719    },
720}
721
722pub struct VmMappedMemoryRegion {
723    guest_address: GuestAddress,
724    slot: MemSlot,
725}
726
727#[derive(Default)]
728pub struct VmMemoryRegionState {
729    mapped_regions: HashMap<Alloc, VmMappedMemoryRegion>,
730    registered_memory: BTreeMap<VmMemoryRegionId, RegisteredMemory>,
731}
732
733fn try_map_to_prepared_region(
734    vm: &dyn Vm,
735    region_state: &mut VmMemoryRegionState,
736    source: &VmMemorySource,
737    dest: &VmMemoryDestination,
738    prot: &Protection,
739) -> Option<VmMemoryResponse> {
740    let VmMemoryDestination::ExistingAllocation {
741        allocation,
742        offset: dest_offset,
743    } = dest
744    else {
745        return None;
746    };
747
748    let VmMappedMemoryRegion {
749        guest_address,
750        slot,
751    } = region_state.mapped_regions.get(allocation)?;
752
753    let (descriptor, file_offset, size) = match source {
754        VmMemorySource::Descriptor {
755            descriptor,
756            offset,
757            size,
758        } => (
759            Descriptor(descriptor.as_raw_descriptor()),
760            *offset,
761            *size as usize,
762        ),
763        VmMemorySource::SharedMemory(shm) => {
764            let size = shm.size() as usize;
765            (Descriptor(shm.as_raw_descriptor()), 0, size)
766        }
767        _ => {
768            let error = anyhow::anyhow!(
769                "source {} is not compatible with fixed mapping into prepared memory region",
770                source
771            );
772            return Some(VmMemoryResponse::Err(error.into()));
773        }
774    };
775    if let Err(err) = vm
776        .add_fd_mapping(
777            *slot,
778            *dest_offset as usize,
779            size,
780            &descriptor,
781            file_offset,
782            *prot,
783        )
784        .context("failed to add fd mapping when trying to map to prepared region")
785    {
786        return Some(VmMemoryResponse::Err(err.into()));
787    }
788
789    let guest_address = GuestAddress(guest_address.0 + dest_offset);
790    let region_id = VmMemoryRegionId(guest_address);
791    region_state.registered_memory.insert(
792        region_id,
793        RegisteredMemory::FixedMapping {
794            slot: *slot,
795            offset: *dest_offset as usize,
796            size,
797        },
798    );
799
800    Some(VmMemoryResponse::RegisterMemory {
801        region_id,
802        slot: *slot,
803    })
804}
805
806impl VmMemoryRequest {
807    /// Executes this request on the given Vm.
808    ///
809    /// # Arguments
810    /// * `vm` - The `Vm` to perform the request on.
811    /// * `allocator` - Used to allocate addresses.
812    ///
813    /// This does not return a result, instead encapsulating the success or failure in a
814    /// `VmMemoryResponse` with the intended purpose of sending the response back over the socket
815    /// that received this `VmMemoryResponse`.
816    pub fn execute(
817        self,
818        #[cfg(any(target_os = "android", target_os = "linux"))] tube: &Tube,
819        vm: &dyn Vm,
820        sys_allocator: &mut SystemAllocator,
821        #[cfg(feature = "gpu")] gralloc: &mut RutabagaGralloc,
822        iommu_client: Option<&mut VmMemoryRequestIommuClient>,
823        region_state: &mut VmMemoryRegionState,
824        remote_peer: bool,
825    ) -> VmMemoryResponse {
826        use self::VmMemoryRequest::*;
827        match self {
828            PrepareSharedMemoryRegion {
829                alloc,
830                cache,
831                force,
832            } => {
833                // Currently the iommu_client is only used by virtio-gpu when used alongside GPU
834                // pci-passthrough.
835                //
836                // TODO(b/323368701): Make compatible with iommu_client by ensuring that
837                // VirtioIOMMUVfioCommand::VfioDmabufMap is submitted for both dynamic mappings and
838                // fixed mappings (i.e. whether or not try_map_to_prepared_region succeeds in
839                // RegisterMemory case below).
840                assert!(iommu_client.is_none());
841
842                if !sys::should_prepare_memory_region(force) {
843                    return VmMemoryResponse::Ok;
844                }
845
846                match sys::prepare_shared_memory_region(vm, sys_allocator, alloc, cache)
847                    .context("failed to prepare shared memory region")
848                {
849                    Ok(region) => {
850                        region_state.mapped_regions.insert(alloc, region);
851                        VmMemoryResponse::Ok
852                    }
853                    Err(e) => VmMemoryResponse::Err(e.into()),
854                }
855            }
856            RegisterMemory {
857                source,
858                dest,
859                prot,
860                cache,
861            } => {
862                // ExternalMapping contains raw pointers and so should only be allowed for peers
863                // within the main process.
864                if remote_peer && matches!(source, VmMemorySource::ExternalMapping { .. }) {
865                    return VmMemoryResponse::Err(anyhow::Error::new(SysError::new(EPERM)).into());
866                }
867
868                if let Some(resp) =
869                    try_map_to_prepared_region(vm, region_state, &source, &dest, &prot)
870                {
871                    return resp;
872                }
873
874                // Correct on Windows because callers of this IPC guarantee descriptor is a mapping
875                // handle.
876                let (mapped_region, size, descriptor) = match source
877                    .map(
878                        #[cfg(feature = "gpu")]
879                        gralloc,
880                        prot,
881                    )
882                    .context("gralloc mapping")
883                {
884                    Ok((region, size, descriptor)) => (region, size, descriptor),
885                    Err(e) => return VmMemoryResponse::Err(e.into()),
886                };
887
888                let guest_addr = match dest
889                    .allocate(sys_allocator, size)
890                    .context("VM memory destination allocation fails")
891                {
892                    Ok(addr) => addr,
893                    Err(e) => return VmMemoryResponse::Err(e.into()),
894                };
895
896                let slot = match vm
897                    .add_memory_region(
898                        guest_addr,
899                        mapped_region,
900                        prot == Protection::read(),
901                        false,
902                        cache,
903                    )
904                    .context("failed to add memory region when registering memory")
905                {
906                    Ok(slot) => slot,
907                    Err(e) => return VmMemoryResponse::Err(e.into()),
908                };
909
910                let region_id = VmMemoryRegionId(guest_addr);
911                if let (Some(descriptor), Some(iommu_client)) = (descriptor, iommu_client) {
912                    let request =
913                        VirtioIOMMURequest::VfioCommand(VirtioIOMMUVfioCommand::VfioDmabufMap {
914                            region_id,
915                            gpa: guest_addr.0,
916                            size,
917                            dma_buf: descriptor,
918                        });
919
920                    match virtio_iommu_request(&iommu_client.tube.lock(), &request) {
921                        Ok(VirtioIOMMUResponse::VfioResponse(VirtioIOMMUVfioResult::Ok)) => (),
922                        resp => {
923                            let error = anyhow::anyhow!(
924                                "Unexpected virtio-iommu message response when registering memory: \
925                                 {:?}", resp);
926                            if let Err(e) = vm.remove_memory_region(slot) {
927                                // There is nothing we can do here, so we just log a warning
928                                // message.
929                                warn!("failed to remove memory region: {:?}", e);
930                            }
931                            return VmMemoryResponse::Err(error.into());
932                        }
933                    };
934
935                    iommu_client.registered_memory.insert(region_id);
936                }
937
938                region_state
939                    .registered_memory
940                    .insert(region_id, RegisteredMemory::DynamicMapping { slot });
941                VmMemoryResponse::RegisterMemory { region_id, slot }
942            }
943            #[cfg(any(target_os = "android", target_os = "linux"))]
944            MmapAndRegisterMemory {
945                shm,
946                dest,
947                num_file_mappings,
948            } => {
949                // Define a callback to be executed with extended limit of file counts.
950                // It recieves `num_file_mappings` FDs and call `add_fd_mapping` for each.
951                let callback = || {
952                    let mem = match MemoryMappingBuilder::new(shm.size() as usize)
953                        .from_shared_memory(&shm)
954                        .build()
955                        .context("failed to build MemoryMapping from shared memory")
956                    {
957                        Ok(mem) => mem,
958                        Err(e) => return Err(VmMemoryResponse::Err(e.into())),
959                    };
960                    let mut mmap_arena = MemoryMappingArena::from(mem);
961
962                    // If `num_file_mappings` exceeds `SCM_MAX_FD`, `file_mappings` are sent in
963                    // chunks of length `SCM_MAX_FD`.
964                    let mut file_mappings = Vec::with_capacity(num_file_mappings);
965                    let mut read = 0;
966                    while read < num_file_mappings {
967                        let len = std::cmp::min(num_file_mappings - read, base::unix::SCM_MAX_FD);
968                        let mps: Vec<VmMemoryFileMapping> = match tube
969                            .recv_with_max_fds(len)
970                            .with_context(|| format!("get {num_file_mappings} FDs to be mapped"))
971                        {
972                            Ok(m) => m,
973                            Err(e) => return Err(VmMemoryResponse::Err(e.into())),
974                        };
975                        file_mappings.extend(mps.into_iter());
976                        read += len;
977                    }
978
979                    for VmMemoryFileMapping {
980                        mem_offset,
981                        length,
982                        file,
983                        file_offset,
984                    } in file_mappings
985                    {
986                        if let Err(e) = mmap_arena
987                            .add_fd_mapping(
988                                mem_offset,
989                                length,
990                                &file,
991                                file_offset,
992                                Protection::read(),
993                            )
994                            .context(
995                                "failed to add fd mapping when handling mmap and register memory",
996                            )
997                        {
998                            return Err(VmMemoryResponse::Err(e.into()));
999                        }
1000                    }
1001                    Ok(mmap_arena)
1002                };
1003                let mmap_arena = match call_with_extended_max_files(callback)
1004                    .context("failed to set max count of file descriptors")
1005                {
1006                    Ok(Ok(m)) => m,
1007                    Ok(Err(e)) => {
1008                        return e;
1009                    }
1010                    Err(e) => {
1011                        error!("{e:?}");
1012                        return VmMemoryResponse::Err(e.into());
1013                    }
1014                };
1015
1016                let size = shm.size();
1017                let guest_addr = match dest.allocate(sys_allocator, size).context(
1018                    "VM memory destination allocation fails when handling mmap and register memory",
1019                ) {
1020                    Ok(addr) => addr,
1021                    Err(e) => return VmMemoryResponse::Err(e.into()),
1022                };
1023
1024                let slot = match vm
1025                    .add_memory_region(
1026                        guest_addr,
1027                        Box::new(mmap_arena),
1028                        true,
1029                        false,
1030                        MemCacheType::CacheCoherent,
1031                    )
1032                    .context("failed to add memory region when handling mmap and register memory")
1033                {
1034                    Ok(slot) => slot,
1035                    Err(e) => return VmMemoryResponse::Err(e.into()),
1036                };
1037
1038                let region_id = VmMemoryRegionId(guest_addr);
1039
1040                region_state
1041                    .registered_memory
1042                    .insert(region_id, RegisteredMemory::DynamicMapping { slot });
1043
1044                VmMemoryResponse::RegisterMemory { region_id, slot }
1045            }
1046            UnregisterMemory(id) => match region_state.registered_memory.remove(&id) {
1047                Some(RegisteredMemory::DynamicMapping { slot }) => match vm
1048                    .remove_memory_region(slot)
1049                    .context(
1050                        "failed to remove memory region when unregistering dynamic mapping memory",
1051                    ) {
1052                    Ok(_) => {
1053                        if let Some(iommu_client) = iommu_client {
1054                            if iommu_client.registered_memory.remove(&id) {
1055                                let request = VirtioIOMMURequest::VfioCommand(
1056                                    VirtioIOMMUVfioCommand::VfioDmabufUnmap(id),
1057                                );
1058
1059                                match virtio_iommu_request(&iommu_client.tube.lock(), &request) {
1060                                    Ok(VirtioIOMMUResponse::VfioResponse(
1061                                        VirtioIOMMUVfioResult::Ok,
1062                                    )) => VmMemoryResponse::Ok,
1063                                    resp => {
1064                                        let error = anyhow::anyhow!(
1065                                            "Unexpected virtio-iommu message response when \
1066                                             unregistering memory: {:?}",
1067                                            resp
1068                                        );
1069                                        VmMemoryResponse::Err(error.into())
1070                                    }
1071                                }
1072                            } else {
1073                                VmMemoryResponse::Ok
1074                            }
1075                        } else {
1076                            VmMemoryResponse::Ok
1077                        }
1078                    }
1079                    Err(e) => VmMemoryResponse::Err(e.into()),
1080                },
1081                Some(RegisteredMemory::FixedMapping { slot, offset, size }) => {
1082                    match vm.remove_mapping(slot, offset, size).context(
1083                        "failed to remove memory mapping when unregistering fixed mapping memory",
1084                    ) {
1085                        Ok(()) => VmMemoryResponse::Ok,
1086                        Err(e) => VmMemoryResponse::Err(e.into()),
1087                    }
1088                }
1089                None => {
1090                    let error =
1091                        anyhow::anyhow!("can't find the memory region when unregistering memory");
1092                    VmMemoryResponse::Err(error.into())
1093                }
1094            },
1095            DynamicallyFreeMemoryRanges { ranges } => {
1096                let mut r = VmMemoryResponse::Ok;
1097                for (guest_address, size) in ranges {
1098                    match vm
1099                        .handle_balloon_event(BalloonEvent::Inflate(MemRegion {
1100                            guest_address,
1101                            size,
1102                        }))
1103                        .context(
1104                            "failed to handle the inflate balloon event when freeing memory ranges \
1105                             dynamically",
1106                        ) {
1107                        Ok(_) => {}
1108                        Err(e) => {
1109                            error!("{:?}", e);
1110                            r = VmMemoryResponse::Err(e.into());
1111                            break;
1112                        }
1113                    }
1114                }
1115                r
1116            }
1117            DynamicallyReclaimMemoryRanges { ranges } => {
1118                let mut r = VmMemoryResponse::Ok;
1119                for (guest_address, size) in ranges {
1120                    match vm
1121                        .handle_balloon_event(BalloonEvent::Deflate(MemRegion {
1122                            guest_address,
1123                            size,
1124                        }))
1125                        .context(
1126                            "failed to handle the deflate balloon event when reclaiming memory \
1127                             ranges dynamically",
1128                        ) {
1129                        Ok(_) => {}
1130                        Err(e) => {
1131                            error!("{:?}", e);
1132                            r = VmMemoryResponse::Err(e.into());
1133                            break;
1134                        }
1135                    }
1136                }
1137                r
1138            }
1139            BalloonTargetReached { size } => {
1140                match vm
1141                    .handle_balloon_event(BalloonEvent::BalloonTargetReached(size))
1142                    .context("failed to handle the target reached balloon event")
1143                {
1144                    Ok(_) => VmMemoryResponse::Ok,
1145                    Err(e) => VmMemoryResponse::Err(e.into()),
1146                }
1147            }
1148            IoEventRaw(request) => {
1149                let res = if request.register {
1150                    vm.register_ioevent(
1151                        request.event,
1152                        IoEventAddress::Mmio(request.addr),
1153                        request.datamatch,
1154                    )
1155                    .context("failed to register IO event")
1156                } else {
1157                    vm.unregister_ioevent(
1158                        request.event,
1159                        IoEventAddress::Mmio(request.addr),
1160                        request.datamatch,
1161                    )
1162                    .context("failed to unregister IO event")
1163                };
1164                match res {
1165                    Ok(_) => VmMemoryResponse::Ok,
1166                    Err(e) => VmMemoryResponse::Err(e.into()),
1167                }
1168            }
1169        }
1170    }
1171}
1172
1173#[derive(Serialize, Deserialize, Debug, PartialOrd, PartialEq, Eq, Ord, Clone, Copy)]
1174/// Identifer for registered memory regions. Globally unique.
1175// The current implementation uses guest physical address as the unique identifier.
1176pub struct VmMemoryRegionId(pub GuestAddress);
1177
1178#[derive(Serialize, Deserialize, Debug)]
1179pub enum VmMemoryResponse {
1180    /// The request to register memory into guest address space was successful.
1181    RegisterMemory {
1182        region_id: VmMemoryRegionId,
1183        slot: u32,
1184    },
1185    Ok,
1186    Err(VmMemoryResponseError),
1187}
1188
1189impl<T> From<Result<T>> for VmMemoryResponse {
1190    fn from(r: Result<T>) -> Self {
1191        match r {
1192            Ok(_) => VmMemoryResponse::Ok,
1193            Err(e) => VmMemoryResponse::Err(anyhow::Error::new(e).into()),
1194        }
1195    }
1196}
1197
1198#[derive(Debug, thiserror::Error)]
1199#[error("Vm memory response error: {0}")]
1200pub struct VmMemoryResponseError(#[from] pub anyhow::Error);
1201
1202impl TryFrom<FlatVmMemoryResponseError> for VmMemoryResponseError {
1203    type Error = anyhow::Error;
1204    fn try_from(value: FlatVmMemoryResponseError) -> StdResult<Self, Self::Error> {
1205        let inner = value
1206            .0
1207            .into_iter()
1208            .fold(
1209                None,
1210                |error: Option<anyhow::Error>, current_context| match error {
1211                    Some(error) => Some(error.context(current_context)),
1212                    None => Some(anyhow::Error::msg(current_context)),
1213                },
1214            )
1215            .context("should carry at least one error")?;
1216        Ok(Self(inner))
1217    }
1218}
1219
1220impl Serialize for VmMemoryResponseError {
1221    fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error>
1222    where
1223        S: serde::Serializer,
1224    {
1225        let flat: FlatVmMemoryResponseError = self.into();
1226        flat.serialize(serializer)
1227    }
1228}
1229
1230impl<'de> Deserialize<'de> for VmMemoryResponseError {
1231    fn deserialize<D>(deserializer: D) -> StdResult<Self, D::Error>
1232    where
1233        D: serde::Deserializer<'de>,
1234    {
1235        let flat = FlatVmMemoryResponseError::deserialize(deserializer)?;
1236        flat.try_into()
1237            .map_err(|e: anyhow::Error| D::Error::custom(e.to_string()))
1238    }
1239}
1240
1241#[derive(Debug, Serialize, Deserialize)]
1242struct FlatVmMemoryResponseError(Vec<String>);
1243
1244impl From<&VmMemoryResponseError> for FlatVmMemoryResponseError {
1245    fn from(value: &VmMemoryResponseError) -> Self {
1246        let contexts = value
1247            .0
1248            .chain()
1249            .map(ToString::to_string)
1250            .rev()
1251            .collect::<Vec<_>>();
1252        Self(contexts)
1253    }
1254}
1255
1256#[derive(Serialize, Deserialize, Debug)]
1257pub enum VmIrqRequest {
1258    /// Allocate one gsi, and associate gsi to irqfd with register_irqfd()
1259    AllocateOneMsi {
1260        irqfd: Event,
1261        device_id: DeviceId,
1262        queue_id: usize,
1263        device_name: String,
1264    },
1265    /// Allocate a specific gsi to irqfd with register_irqfd(). This must only
1266    /// be used when it is known that the gsi is free. Only the snapshot
1267    /// subsystem can make this guarantee, and use of this request by any other
1268    /// caller is strongly discouraged.
1269    AllocateOneMsiAtGsi {
1270        irqfd: Event,
1271        gsi: u32,
1272        device_id: DeviceId,
1273        queue_id: usize,
1274        device_name: String,
1275    },
1276    /// Add one msi route entry into the IRQ chip.
1277    AddMsiRoute {
1278        gsi: u32,
1279        msi_address: u64,
1280        msi_data: u32,
1281        #[cfg(target_arch = "aarch64")]
1282        pci_address: resources::PciAddress,
1283    },
1284    // unregister_irqfs() and release gsi
1285    ReleaseOneIrq {
1286        gsi: u32,
1287        irqfd: Event,
1288    },
1289}
1290
1291/// Data to set up an IRQ event or IRQ route on the IRQ chip.
1292/// VmIrqRequest::execute can't take an `IrqChip` argument, because of a dependency cycle between
1293/// devices and vm_control, so it takes a Fn that processes an `IrqSetup`.
1294pub enum IrqSetup<'a> {
1295    Event(u32, &'a Event, DeviceId, usize, String),
1296    Route(IrqRoute),
1297    UnRegister(u32, &'a Event),
1298}
1299
1300impl VmIrqRequest {
1301    /// Executes this request on the given Vm.
1302    ///
1303    /// # Arguments
1304    /// * `set_up_irq` - A function that applies an `IrqSetup` to an IRQ chip.
1305    ///
1306    /// This does not return a result, instead encapsulating the success or failure in a
1307    /// `VmIrqResponse` with the intended purpose of sending the response back over the socket
1308    /// that received this `VmIrqResponse`.
1309    pub fn execute<F>(&self, set_up_irq: F, sys_allocator: &mut SystemAllocator) -> VmIrqResponse
1310    where
1311        F: FnOnce(IrqSetup) -> Result<()>,
1312    {
1313        use self::VmIrqRequest::*;
1314        match *self {
1315            AllocateOneMsi {
1316                ref irqfd,
1317                device_id,
1318                queue_id,
1319                ref device_name,
1320            } => {
1321                if let Some(irq_num) = sys_allocator.allocate_irq() {
1322                    match set_up_irq(IrqSetup::Event(
1323                        irq_num,
1324                        irqfd,
1325                        device_id,
1326                        queue_id,
1327                        device_name.clone(),
1328                    )) {
1329                        Ok(_) => VmIrqResponse::AllocateOneMsi { gsi: irq_num },
1330                        Err(e) => VmIrqResponse::Err(e),
1331                    }
1332                } else {
1333                    VmIrqResponse::Err(SysError::new(EINVAL))
1334                }
1335            }
1336            AllocateOneMsiAtGsi {
1337                ref irqfd,
1338                gsi,
1339                device_id,
1340                queue_id,
1341                ref device_name,
1342            } => {
1343                match set_up_irq(IrqSetup::Event(
1344                    gsi,
1345                    irqfd,
1346                    device_id,
1347                    queue_id,
1348                    device_name.clone(),
1349                )) {
1350                    Ok(_) => VmIrqResponse::Ok,
1351                    Err(e) => VmIrqResponse::Err(e),
1352                }
1353            }
1354            AddMsiRoute {
1355                gsi,
1356                msi_address,
1357                msi_data,
1358                #[cfg(target_arch = "aarch64")]
1359                pci_address,
1360            } => {
1361                let route = IrqRoute {
1362                    gsi,
1363                    source: IrqSource::Msi {
1364                        address: msi_address,
1365                        data: msi_data,
1366                        #[cfg(target_arch = "aarch64")]
1367                        pci_address,
1368                    },
1369                };
1370                match set_up_irq(IrqSetup::Route(route)) {
1371                    Ok(_) => VmIrqResponse::Ok,
1372                    Err(e) => VmIrqResponse::Err(e),
1373                }
1374            }
1375            ReleaseOneIrq { gsi, ref irqfd } => {
1376                let _ = set_up_irq(IrqSetup::UnRegister(gsi, irqfd));
1377                sys_allocator.release_irq(gsi);
1378                VmIrqResponse::Ok
1379            }
1380        }
1381    }
1382}
1383
1384#[derive(Serialize, Deserialize, Debug)]
1385pub enum VmIrqResponse {
1386    AllocateOneMsi { gsi: u32 },
1387    Ok,
1388    Err(SysError),
1389}
1390
1391#[derive(Serialize, Deserialize, Debug, Clone)]
1392pub enum DevicesState {
1393    Sleep,
1394    Wake,
1395}
1396
1397#[derive(Serialize, Deserialize, Debug, Clone)]
1398pub enum BatControlResult {
1399    Ok,
1400    NoBatDevice,
1401    NoSuchHealth,
1402    NoSuchProperty,
1403    NoSuchStatus,
1404    NoSuchBatType,
1405    StringParseIntErr,
1406    StringParseBoolErr,
1407}
1408
1409impl Display for BatControlResult {
1410    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1411        use self::BatControlResult::*;
1412
1413        match self {
1414            Ok => write!(f, "Setting battery property successfully"),
1415            NoBatDevice => write!(f, "No battery device created"),
1416            NoSuchHealth => write!(f, "Invalid Battery health setting. Only support: unknown/good/overheat/dead/overvoltage/unexpectedfailure/cold/watchdogtimerexpire/safetytimerexpire/overcurrent"),
1417            NoSuchProperty => write!(f, "Battery doesn't have such property. Only support: status/health/present/capacity/aconline"),
1418            NoSuchStatus => write!(f, "Invalid Battery status setting. Only support: unknown/charging/discharging/notcharging/full"),
1419            NoSuchBatType => write!(f, "Invalid Battery type setting. Only support: goldfish"),
1420            StringParseIntErr => write!(f, "Battery property target ParseInt error"),
1421            StringParseBoolErr => write!(f, "Battery property target ParseBool error"),
1422        }
1423    }
1424}
1425
1426#[derive(Serialize, Deserialize, Copy, Clone, Debug, Default, PartialEq, Eq)]
1427#[serde(rename_all = "kebab-case")]
1428pub enum BatteryType {
1429    #[default]
1430    Goldfish,
1431}
1432
1433impl FromStr for BatteryType {
1434    type Err = BatControlResult;
1435
1436    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
1437        match s {
1438            "goldfish" => Ok(BatteryType::Goldfish),
1439            _ => Err(BatControlResult::NoSuchBatType),
1440        }
1441    }
1442}
1443
1444#[derive(Serialize, Deserialize, Debug)]
1445pub enum BatProperty {
1446    Status,
1447    Health,
1448    Present,
1449    Capacity,
1450    ACOnline,
1451    SetFakeBatConfig,
1452    CancelFakeBatConfig,
1453}
1454
1455impl FromStr for BatProperty {
1456    type Err = BatControlResult;
1457
1458    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
1459        match s {
1460            "status" => Ok(BatProperty::Status),
1461            "health" => Ok(BatProperty::Health),
1462            "present" => Ok(BatProperty::Present),
1463            "capacity" => Ok(BatProperty::Capacity),
1464            "aconline" => Ok(BatProperty::ACOnline),
1465            "set_fake_bat_config" => Ok(BatProperty::SetFakeBatConfig),
1466            "cancel_fake_bat_config" => Ok(BatProperty::CancelFakeBatConfig),
1467            _ => Err(BatControlResult::NoSuchProperty),
1468        }
1469    }
1470}
1471
1472impl Display for BatProperty {
1473    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1474        match *self {
1475            BatProperty::Status => write!(f, "status"),
1476            BatProperty::Health => write!(f, "health"),
1477            BatProperty::Present => write!(f, "present"),
1478            BatProperty::Capacity => write!(f, "capacity"),
1479            BatProperty::ACOnline => write!(f, "aconline"),
1480            BatProperty::SetFakeBatConfig => write!(f, "set_fake_bat_config"),
1481            BatProperty::CancelFakeBatConfig => write!(f, "cancel_fake_bat_config"),
1482        }
1483    }
1484}
1485
1486#[derive(Serialize, Deserialize, Debug)]
1487pub enum BatStatus {
1488    Unknown,
1489    Charging,
1490    DisCharging,
1491    NotCharging,
1492    Full,
1493}
1494
1495impl BatStatus {
1496    pub fn new(status: String) -> std::result::Result<Self, BatControlResult> {
1497        match status.as_str() {
1498            "unknown" => Ok(BatStatus::Unknown),
1499            "charging" => Ok(BatStatus::Charging),
1500            "discharging" => Ok(BatStatus::DisCharging),
1501            "notcharging" => Ok(BatStatus::NotCharging),
1502            "full" => Ok(BatStatus::Full),
1503            _ => Err(BatControlResult::NoSuchStatus),
1504        }
1505    }
1506}
1507
1508impl FromStr for BatStatus {
1509    type Err = BatControlResult;
1510
1511    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
1512        match s {
1513            "unknown" => Ok(BatStatus::Unknown),
1514            "charging" => Ok(BatStatus::Charging),
1515            "discharging" => Ok(BatStatus::DisCharging),
1516            "notcharging" => Ok(BatStatus::NotCharging),
1517            "full" => Ok(BatStatus::Full),
1518            _ => Err(BatControlResult::NoSuchStatus),
1519        }
1520    }
1521}
1522
1523impl From<BatStatus> for u32 {
1524    fn from(status: BatStatus) -> Self {
1525        status as u32
1526    }
1527}
1528
1529#[derive(Serialize, Deserialize, Debug)]
1530pub enum BatHealth {
1531    Unknown,
1532    Good,
1533    Overheat,
1534    Dead,
1535    OverVoltage,
1536    UnexpectedFailure,
1537    Cold,
1538    WatchdogTimerExpire,
1539    SafetyTimerExpire,
1540    OverCurrent,
1541}
1542
1543impl FromStr for BatHealth {
1544    type Err = BatControlResult;
1545
1546    fn from_str(s: &str) -> StdResult<Self, Self::Err> {
1547        match s {
1548            "unknown" => Ok(BatHealth::Unknown),
1549            "good" => Ok(BatHealth::Good),
1550            "overheat" => Ok(BatHealth::Overheat),
1551            "dead" => Ok(BatHealth::Dead),
1552            "overvoltage" => Ok(BatHealth::OverVoltage),
1553            "unexpectedfailure" => Ok(BatHealth::UnexpectedFailure),
1554            "cold" => Ok(BatHealth::Cold),
1555            "watchdogtimerexpire" => Ok(BatHealth::WatchdogTimerExpire),
1556            "safetytimerexpire" => Ok(BatHealth::SafetyTimerExpire),
1557            "overcurrent" => Ok(BatHealth::OverCurrent),
1558            _ => Err(BatControlResult::NoSuchHealth),
1559        }
1560    }
1561}
1562
1563impl From<BatHealth> for u32 {
1564    fn from(status: BatHealth) -> Self {
1565        status as u32
1566    }
1567}
1568
1569#[derive(Serialize, Deserialize, Debug)]
1570pub enum BatControlCommand {
1571    SetStatus(BatStatus),
1572    SetHealth(BatHealth),
1573    SetPresent(u32),
1574    SetCapacity(u32),
1575    SetACOnline(u32),
1576    SetFakeBatConfig(u32),
1577    CancelFakeConfig,
1578}
1579
1580impl BatControlCommand {
1581    pub fn new(property: String, target: String) -> std::result::Result<Self, BatControlResult> {
1582        let cmd = property.parse::<BatProperty>()?;
1583        match cmd {
1584            BatProperty::Status => Ok(BatControlCommand::SetStatus(target.parse::<BatStatus>()?)),
1585            BatProperty::Health => Ok(BatControlCommand::SetHealth(target.parse::<BatHealth>()?)),
1586            BatProperty::Present => Ok(BatControlCommand::SetPresent(
1587                target
1588                    .parse::<u32>()
1589                    .map_err(|_| BatControlResult::StringParseIntErr)?,
1590            )),
1591            BatProperty::Capacity => Ok(BatControlCommand::SetCapacity(
1592                target
1593                    .parse::<u32>()
1594                    .map_err(|_| BatControlResult::StringParseIntErr)?,
1595            )),
1596            BatProperty::ACOnline => Ok(BatControlCommand::SetACOnline(
1597                target
1598                    .parse::<u32>()
1599                    .map_err(|_| BatControlResult::StringParseIntErr)?,
1600            )),
1601            BatProperty::SetFakeBatConfig => Ok(BatControlCommand::SetFakeBatConfig(
1602                target
1603                    .parse::<u32>()
1604                    .map_err(|_| BatControlResult::StringParseIntErr)?,
1605            )),
1606            BatProperty::CancelFakeBatConfig => Ok(BatControlCommand::CancelFakeConfig),
1607        }
1608    }
1609}
1610
1611/// Used for VM to control battery properties.
1612pub struct BatControl {
1613    pub type_: BatteryType,
1614    pub control_tube: Tube,
1615}
1616
1617/// Used for VM to control for virtio-snd
1618#[derive(Serialize, Deserialize, Debug)]
1619pub enum SndControlCommand {
1620    MuteAll(bool),
1621}
1622
1623// Used to mark hotplug pci device's device type
1624#[derive(Serialize, Deserialize, Debug, Clone)]
1625pub enum HotPlugDeviceType {
1626    UpstreamPort,
1627    DownstreamPort,
1628    EndPoint,
1629}
1630
1631// Used for VM to hotplug pci devices
1632#[derive(Serialize, Deserialize, Debug, Clone)]
1633pub struct HotPlugDeviceInfo {
1634    pub device_type: HotPlugDeviceType,
1635    pub path: PathBuf,
1636    pub hp_interrupt: bool,
1637}
1638
1639/// A request from a device to the main process to perform some operation on the VM.
1640#[derive(Serialize, Deserialize, Debug)]
1641pub enum DeviceControlRequest {
1642    /// Inject a general-purpose event. If `clear_evt` is provided, when the irq associated
1643    /// with the GPE is resampled, it will be re-asserted as long as `clear_evt` is not
1644    /// signaled.
1645    Gpe { gpe: u32, clear_evt: Option<Event> },
1646    /// Inject a PCI PME.
1647    PciPme(u16),
1648    /// Command to add/remove multiple vfio-pci devices.
1649    HotPlugVfioCommand {
1650        device: HotPlugDeviceInfo,
1651        add: bool,
1652    },
1653}
1654
1655/// Response to a `DeviceControlRequest`.
1656#[derive(Serialize, Deserialize, Debug)]
1657#[must_use]
1658pub enum DeviceControlResponse {
1659    Ok,
1660    Err(SysError),
1661}
1662
1663impl Display for DeviceControlResponse {
1664    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1665        match self {
1666            DeviceControlResponse::Ok => write!(f, "ok"),
1667            DeviceControlResponse::Err(e) => write!(f, "error: {e}"),
1668        }
1669    }
1670}
1671
1672impl From<DeviceControlResponse> for VmResponse {
1673    fn from(response: DeviceControlResponse) -> Self {
1674        match response {
1675            DeviceControlResponse::Ok => VmResponse::Ok,
1676            DeviceControlResponse::Err(e) => VmResponse::Err(e),
1677        }
1678    }
1679}
1680
1681impl DeviceControlRequest {
1682    /// Executes this request on the given VM power management resource.
1683    pub fn execute(
1684        &self,
1685        pm: &mut Option<Arc<Mutex<dyn PmResource + Send>>>,
1686    ) -> DeviceControlResponse {
1687        match self {
1688            DeviceControlRequest::Gpe { gpe, clear_evt } => {
1689                if let Some(pm) = pm.as_ref() {
1690                    match clear_evt.as_ref().map(|e| e.try_clone()).transpose() {
1691                        Ok(clear_evt) => {
1692                            pm.lock().gpe_evt(*gpe, clear_evt);
1693                            DeviceControlResponse::Ok
1694                        }
1695                        Err(err) => {
1696                            error!("Error cloning clear_evt: {:?}", err);
1697                            DeviceControlResponse::Err(SysError::new(EIO))
1698                        }
1699                    }
1700                } else {
1701                    error!("{:#?} not supported", *self);
1702                    DeviceControlResponse::Err(SysError::new(ENOTSUP))
1703                }
1704            }
1705            DeviceControlRequest::PciPme(requester_id) => {
1706                if let Some(pm) = pm.as_ref() {
1707                    pm.lock().pme_evt(*requester_id);
1708                    DeviceControlResponse::Ok
1709                } else {
1710                    error!("{:#?} not supported", *self);
1711                    DeviceControlResponse::Err(SysError::new(ENOTSUP))
1712                }
1713            }
1714            DeviceControlRequest::HotPlugVfioCommand { .. } => {
1715                panic!("HotPlugVfioCommand should be handled by the platform run loop");
1716            }
1717        }
1718    }
1719}
1720
1721/// Message for communicating a suspend or resume to the virtio-pvclock device.
1722#[derive(Serialize, Deserialize, Debug, Clone)]
1723pub enum PvClockCommand {
1724    Suspend,
1725    Resume,
1726}
1727
1728/// Message used by virtio-pvclock to communicate command results.
1729#[derive(Serialize, Deserialize, Debug)]
1730pub enum PvClockCommandResponse {
1731    Ok,
1732    Resumed { total_suspended_ticks: u64 },
1733    DeviceInactive,
1734    Err(SysError),
1735}
1736
1737/// Commands for vmm-swap feature
1738#[derive(Serialize, Deserialize, Debug)]
1739pub enum SwapCommand {
1740    Enable,
1741    Trim,
1742    SwapOut,
1743    Disable { slow_file_cleanup: bool },
1744    Status,
1745}
1746
1747///
1748/// A request to the main process to perform some operation on the VM.
1749///
1750/// Unless otherwise noted, each request should expect a `VmResponse::Ok` to be received on success.
1751#[derive(Serialize, Deserialize, Debug)]
1752pub enum VmRequest {
1753    /// Break the VM's run loop and exit.
1754    Exit,
1755    /// Trigger a power button event in the guest.
1756    Powerbtn,
1757    /// Trigger a sleep button event in the guest.
1758    Sleepbtn,
1759    /// Trigger a RTC interrupt in the guest. When the irq associated with the RTC is
1760    /// resampled, it will be re-asserted as long as `clear_evt` is not signaled.
1761    Rtc { clear_evt: Event },
1762    /// Suspend the VM's VCPUs until resume.
1763    SuspendVcpus,
1764    /// Swap the memory content into files on a disk
1765    Swap(SwapCommand),
1766    /// Resume the VM's VCPUs that were previously suspended.
1767    ResumeVcpus,
1768    /// Command to control devices.
1769    DeviceControl(DeviceControlRequest),
1770    /// Make the VM's RT VCPU real-time.
1771    MakeRT,
1772    /// Command for balloon driver.
1773    #[cfg(feature = "balloon")]
1774    BalloonCommand(BalloonControlCommand),
1775    /// Send a command to a disk chosen by `disk_index`.
1776    /// `disk_index` is a 0-based count of `--disk`, `--rwdisk`, and `-r` command-line options.
1777    DiskCommand {
1778        disk_index: usize,
1779        command: DiskControlCommand,
1780    },
1781    /// Command to use controller.
1782    UsbCommand(UsbControlCommand),
1783    /// Command to modify the gpu.
1784    GpuCommand(GpuControlCommand),
1785    /// Command to set battery.
1786    BatCommand(BatteryType, BatControlCommand),
1787    /// Command to control snd devices
1788    #[cfg(feature = "audio")]
1789    SndCommand(SndControlCommand),
1790    /// Command to add/remove network tap device as virtio-pci device
1791    #[cfg(feature = "pci-hotplug")]
1792    HotPlugNetCommand(NetControlCommand),
1793    /// Command to Snapshot devices
1794    Snapshot(SnapshotCommand),
1795    /// Register for event notification
1796    RegisterListener {
1797        socket_addr: String,
1798        event: RegisteredEvent,
1799    },
1800    /// Unregister for notifications for event
1801    UnregisterListener {
1802        socket_addr: String,
1803        event: RegisteredEvent,
1804    },
1805    /// Unregister for all event notification
1806    Unregister { socket_addr: String },
1807    /// Suspend VM VCPUs and Devices until resume.
1808    SuspendVm,
1809    /// Resume VM VCPUs and Devices.
1810    ResumeVm,
1811    /// Returns Vcpus PID/TID
1812    VcpuPidTid,
1813    /// Throttles the requested vCPU for microseconds
1814    Throttle(usize, u32),
1815    /// Returns unique descriptor of this VM.
1816    GetVmDescriptor,
1817    /// Registers memory in guest.
1818    RegisterMemory {
1819        fd: SafeDescriptor,
1820        offset: u64,
1821        range_start: u64,
1822        range_end: u64,
1823        cache_coherent: bool,
1824    },
1825    /// Unregisters memory in guest.
1826    UnregisterMemory { region_id: u64 },
1827}
1828
1829/// NOTE: when making any changes to this enum please also update
1830/// RegisteredEventFfi in crosvm_control/src/lib.rs
1831#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, Clone, Copy)]
1832pub enum RegisteredEvent {
1833    VirtioBalloonWsReport,
1834    VirtioBalloonResize,
1835    VirtioBalloonOOMDeflation,
1836}
1837
1838#[derive(Serialize, Deserialize, Debug)]
1839pub enum RegisteredEventWithData {
1840    VirtioBalloonWsReport {
1841        ws_buckets: Vec<balloon_control::WSBucket>,
1842        balloon_actual: u64,
1843    },
1844    VirtioBalloonResize,
1845    VirtioBalloonOOMDeflation,
1846}
1847
1848impl RegisteredEventWithData {
1849    pub fn into_event(&self) -> RegisteredEvent {
1850        match self {
1851            Self::VirtioBalloonWsReport { .. } => RegisteredEvent::VirtioBalloonWsReport,
1852            Self::VirtioBalloonResize => RegisteredEvent::VirtioBalloonResize,
1853            Self::VirtioBalloonOOMDeflation => RegisteredEvent::VirtioBalloonOOMDeflation,
1854        }
1855    }
1856
1857    #[cfg(feature = "registered_events")]
1858    pub fn into_proto(&self) -> registered_events::RegisteredEvent {
1859        match self {
1860            Self::VirtioBalloonWsReport {
1861                ws_buckets,
1862                balloon_actual,
1863            } => {
1864                let mut report = registered_events::VirtioBalloonWsReport {
1865                    balloon_actual: *balloon_actual,
1866                    ..registered_events::VirtioBalloonWsReport::new()
1867                };
1868                for ws in ws_buckets {
1869                    report.ws_buckets.push(registered_events::VirtioWsBucket {
1870                        age: ws.age,
1871                        file_bytes: ws.bytes[0],
1872                        anon_bytes: ws.bytes[1],
1873                        ..registered_events::VirtioWsBucket::new()
1874                    });
1875                }
1876                let mut event = registered_events::RegisteredEvent::new();
1877                event.set_ws_report(report);
1878                event
1879            }
1880            Self::VirtioBalloonResize => {
1881                let mut event = registered_events::RegisteredEvent::new();
1882                event.set_resize(registered_events::VirtioBalloonResize::new());
1883                event
1884            }
1885            Self::VirtioBalloonOOMDeflation => {
1886                let mut event = registered_events::RegisteredEvent::new();
1887                event.set_oom_deflation(registered_events::VirtioBalloonOOMDeflation::new());
1888                event
1889            }
1890        }
1891    }
1892
1893    pub fn from_ws(ws: &balloon_control::BalloonWS, balloon_actual: u64) -> Self {
1894        RegisteredEventWithData::VirtioBalloonWsReport {
1895            ws_buckets: ws.ws.clone(),
1896            balloon_actual,
1897        }
1898    }
1899}
1900
1901pub fn handle_disk_command(command: &DiskControlCommand, disk_host_tube: &Tube) -> VmResponse {
1902    // Forward the request to the block device process via its control socket.
1903    if let Err(e) = disk_host_tube.send(command) {
1904        error!("disk socket send failed: {}", e);
1905        return VmResponse::Err(SysError::new(EINVAL));
1906    }
1907
1908    // Wait for the disk control command to be processed
1909    match disk_host_tube.recv() {
1910        Ok(DiskControlResult::Ok) => VmResponse::Ok,
1911        Ok(DiskControlResult::Err(e)) => VmResponse::Err(e),
1912        Err(e) => {
1913            error!("disk socket recv failed: {}", e);
1914            VmResponse::Err(SysError::new(EINVAL))
1915        }
1916    }
1917}
1918
1919/// WARNING: descriptor must be a mapping handle on Windows.
1920fn map_descriptor(
1921    descriptor: &dyn AsRawDescriptor,
1922    offset: u64,
1923    size: u64,
1924    prot: Protection,
1925) -> Result<Box<dyn MappedRegion>> {
1926    let size: usize = size.try_into().map_err(|_e| SysError::new(ERANGE))?;
1927    match MemoryMappingBuilder::new(size)
1928        .from_descriptor(descriptor)
1929        .offset(offset)
1930        .protection(prot)
1931        .build()
1932    {
1933        Ok(mmap) => Ok(Box::new(mmap)),
1934        Err(MmapError::SystemCallFailed(e)) => Err(e),
1935        _ => Err(SysError::new(EINVAL)),
1936    }
1937}
1938
1939// Get vCPU state. vCPUs are expected to all hold the same state.
1940// In this function, there may be a time where vCPUs are not holding the same state
1941// as they transition from one state to the other. This is expected, and the final result
1942// should be all vCPUs holding the same state.
1943fn get_vcpu_state(kick_vcpus: impl Fn(VcpuControl), vcpu_num: usize) -> anyhow::Result<VmRunMode> {
1944    let (send_chan, recv_chan) = mpsc::channel();
1945    kick_vcpus(VcpuControl::GetStates(send_chan));
1946    if vcpu_num == 0 {
1947        bail!("vcpu_num is zero");
1948    }
1949    let mut current_mode_vec: Vec<VmRunMode> = Vec::new();
1950    for _ in 0..vcpu_num {
1951        match recv_chan.recv() {
1952            Ok(state) => current_mode_vec.push(state),
1953            Err(e) => {
1954                bail!("Failed to get vCPU state: {}", e);
1955            }
1956        };
1957    }
1958    let first_state = current_mode_vec[0];
1959    if first_state == VmRunMode::Exiting {
1960        panic!("Attempt to snapshot while exiting.");
1961    }
1962    if current_mode_vec.iter().any(|x| *x != first_state) {
1963        // We do not panic here. It could be that vCPUs are transitioning from one mode to another.
1964        bail!("Unknown VM state: vCPUs hold different states.");
1965    }
1966    Ok(first_state)
1967}
1968
1969/// A guard to guarantee that all the vCPUs are suspended during the scope.
1970///
1971/// When this guard is dropped, it rolls back the state of CPUs.
1972pub struct VcpuSuspendGuard<'a> {
1973    saved_run_mode: VmRunMode,
1974    kick_vcpus: &'a dyn Fn(VcpuControl),
1975}
1976
1977impl<'a> VcpuSuspendGuard<'a> {
1978    /// Check the all vCPU state and suspend the vCPUs if they are running.
1979    ///
1980    /// This returns [VcpuSuspendGuard] to rollback the vcpu state.
1981    ///
1982    /// # Arguments
1983    ///
1984    /// * `kick_vcpus` - A funtion to send [VcpuControl] message to all the vCPUs and interrupt
1985    ///   them.
1986    /// * `vcpu_num` - The number of vCPUs.
1987    pub fn new(kick_vcpus: &'a impl Fn(VcpuControl), vcpu_num: usize) -> anyhow::Result<Self> {
1988        // get initial vcpu state
1989        let saved_run_mode = get_vcpu_state(kick_vcpus, vcpu_num)?;
1990        match saved_run_mode {
1991            VmRunMode::Running => {
1992                kick_vcpus(VcpuControl::RunState(VmRunMode::Suspending));
1993                // Blocking call, waiting for response to ensure vCPU state was updated.
1994                // In case of failure, where a vCPU still has the state running, start up vcpus and
1995                // abort operation.
1996                let current_mode = get_vcpu_state(kick_vcpus, vcpu_num)?;
1997                if current_mode != VmRunMode::Suspending {
1998                    kick_vcpus(VcpuControl::RunState(saved_run_mode));
1999                    bail!("vCPUs failed to all suspend. Kicking back all vCPUs to their previous state: {saved_run_mode}");
2000                }
2001            }
2002            VmRunMode::Suspending => {
2003                // do nothing. keep the state suspending.
2004            }
2005            other => {
2006                bail!("vcpus are not in running/suspending state, but {}", other);
2007            }
2008        };
2009        Ok(Self {
2010            saved_run_mode,
2011            kick_vcpus,
2012        })
2013    }
2014}
2015
2016impl Drop for VcpuSuspendGuard<'_> {
2017    fn drop(&mut self) {
2018        if self.saved_run_mode != VmRunMode::Suspending {
2019            (self.kick_vcpus)(VcpuControl::RunState(self.saved_run_mode));
2020        }
2021    }
2022}
2023
2024/// A guard to guarantee that all devices are sleeping during its scope.
2025///
2026/// When this guard is dropped, it wakes the devices.
2027pub struct DeviceSleepGuard<'a> {
2028    device_control_tube: &'a Tube,
2029    devices_state: DevicesState,
2030}
2031
2032impl<'a> DeviceSleepGuard<'a> {
2033    fn new(device_control_tube: &'a Tube) -> anyhow::Result<Self> {
2034        device_control_tube
2035            .send(&DeviceControlCommand::GetDevicesState)
2036            .context("send command to devices control socket")?;
2037        let devices_state = match device_control_tube
2038            .recv()
2039            .context("receive from devices control socket")?
2040        {
2041            VmResponse::DevicesState(state) => state,
2042            resp => bail!("failed to get devices state. Unexpected behavior: {}", resp),
2043        };
2044        if let DevicesState::Wake = devices_state {
2045            device_control_tube
2046                .send(&DeviceControlCommand::SleepDevices)
2047                .context("send command to devices control socket")?;
2048            match device_control_tube
2049                .recv()
2050                .context("receive from devices control socket")?
2051            {
2052                VmResponse::Ok => (),
2053                resp => bail!("device sleep failed: {}", resp),
2054            }
2055        }
2056        Ok(Self {
2057            device_control_tube,
2058            devices_state,
2059        })
2060    }
2061}
2062
2063impl Drop for DeviceSleepGuard<'_> {
2064    fn drop(&mut self) {
2065        if let DevicesState::Wake = self.devices_state {
2066            if let Err(e) = self
2067                .device_control_tube
2068                .send(&DeviceControlCommand::WakeDevices)
2069            {
2070                panic!("failed to request device wake after snapshot: {e}");
2071            }
2072            match self.device_control_tube.recv() {
2073                Ok(VmResponse::Ok) => (),
2074                Ok(resp) => panic!("unexpected response to device wake request: {resp}"),
2075                Err(e) => panic!("failed to get reply for device wake request: {e}"),
2076            }
2077        }
2078    }
2079}
2080
2081impl VmRequest {
2082    /// Executes this request on the given Vm and other mutable state.
2083    ///
2084    /// This does not return a result, instead encapsulating the success or failure in a
2085    /// `VmResponse` with the intended purpose of sending the response back over the  socket that
2086    /// received this `VmRequest`.
2087    ///
2088    /// `suspended_pvclock_state`: If the hypervisor has its own pvclock (not the same as
2089    /// virtio-pvclock) and the VM is suspended (not just the vCPUs, but the full VM), then
2090    /// `suspended_pvclock_state` will be used to store the ClockState saved just after the vCPUs
2091    /// were suspended. It is important that we save the value right after the vCPUs are suspended
2092    /// and restore it right before the vCPUs are resumed (instead of, more naturally, during the
2093    /// snapshot/restore steps) because the pvclock continues to tick even when the vCPUs are
2094    /// suspended.
2095    #[allow(unused_variables)]
2096    pub fn execute(
2097        &self,
2098        vm: &dyn Vm,
2099        disk_host_tubes: &[Tube],
2100        snd_host_tubes: &[Tube],
2101        pm: &mut Option<Arc<Mutex<dyn PmResource + Send>>>,
2102        gpu_control_tube: Option<&Tube>,
2103        usb_control_tube: Option<&Tube>,
2104        bat_control: &mut Option<BatControl>,
2105        kick_vcpus: impl Fn(VcpuControl),
2106        #[cfg(any(target_os = "android", target_os = "linux"))] kick_vcpu: impl Fn(usize, VcpuControl),
2107        force_s2idle: bool,
2108        #[cfg(feature = "swap")] swap_controller: Option<&swap::SwapController>,
2109        device_control_tube: &Tube,
2110        vcpu_size: usize,
2111        irq_handler_control: &Tube,
2112        snapshot_irqchip: impl Fn() -> anyhow::Result<AnySnapshot>,
2113        suspended_pvclock_state: &mut Option<hypervisor::ClockState>,
2114    ) -> VmResponse {
2115        match self {
2116            VmRequest::Exit => {
2117                panic!("VmRequest::Exit should be handled by the platform run loop");
2118            }
2119            VmRequest::Powerbtn => {
2120                if let Some(pm) = pm {
2121                    pm.lock().pwrbtn_evt();
2122                    VmResponse::Ok
2123                } else {
2124                    error!("{:#?} not supported", *self);
2125                    VmResponse::Err(SysError::new(ENOTSUP))
2126                }
2127            }
2128            VmRequest::Sleepbtn => {
2129                if let Some(pm) = pm {
2130                    pm.lock().slpbtn_evt();
2131                    VmResponse::Ok
2132                } else {
2133                    error!("{:#?} not supported", *self);
2134                    VmResponse::Err(SysError::new(ENOTSUP))
2135                }
2136            }
2137            VmRequest::Rtc { clear_evt } => {
2138                if let Some(pm) = pm.as_ref() {
2139                    match clear_evt.try_clone() {
2140                        Ok(clear_evt) => {
2141                            // RTC event will asynchronously trigger wakeup.
2142                            pm.lock().rtc_evt(clear_evt);
2143                            VmResponse::Ok
2144                        }
2145                        Err(err) => {
2146                            error!("Error cloning clear_evt: {:?}", err);
2147                            VmResponse::Err(SysError::new(EIO))
2148                        }
2149                    }
2150                } else {
2151                    error!("{:#?} not supported", *self);
2152                    VmResponse::Err(SysError::new(ENOTSUP))
2153                }
2154            }
2155            VmRequest::SuspendVcpus => {
2156                if !force_s2idle {
2157                    kick_vcpus(VcpuControl::RunState(VmRunMode::Suspending));
2158                    let current_mode = match get_vcpu_state(kick_vcpus, vcpu_size) {
2159                        Ok(state) => state,
2160                        Err(e) => {
2161                            error!("failed to get vcpu state: {e}");
2162                            return VmResponse::Err(SysError::new(EIO));
2163                        }
2164                    };
2165                    if current_mode != VmRunMode::Suspending {
2166                        error!("vCPUs failed to all suspend.");
2167                        return VmResponse::Err(SysError::new(EIO));
2168                    }
2169                }
2170                VmResponse::Ok
2171            }
2172            VmRequest::ResumeVcpus => {
2173                if let Err(e) = device_control_tube.send(&DeviceControlCommand::GetDevicesState) {
2174                    error!("failed to send GetDevicesState: {}", e);
2175                    return VmResponse::Err(SysError::new(EIO));
2176                }
2177                let devices_state = match device_control_tube.recv() {
2178                    Ok(VmResponse::DevicesState(state)) => state,
2179                    Ok(resp) => {
2180                        error!("failed to get devices state. Unexpected behavior: {}", resp);
2181                        return VmResponse::Err(SysError::new(EINVAL));
2182                    }
2183                    Err(e) => {
2184                        error!("failed to get devices state. Unexpected behavior: {}", e);
2185                        return VmResponse::Err(SysError::new(EINVAL));
2186                    }
2187                };
2188                if let DevicesState::Sleep = devices_state {
2189                    error!("Trying to wake Vcpus while Devices are asleep. Did you mean to use `crosvm resume --full`?");
2190                    return VmResponse::Err(SysError::new(EINVAL));
2191                }
2192
2193                if force_s2idle {
2194                    // During resume also emulate powerbtn event which will allow to wakeup fully
2195                    // suspended guest.
2196                    if let Some(pm) = pm {
2197                        pm.lock().pwrbtn_evt();
2198                    } else {
2199                        error!("triggering power btn during resume not supported");
2200                        return VmResponse::Err(SysError::new(ENOTSUP));
2201                    }
2202                }
2203
2204                kick_vcpus(VcpuControl::RunState(VmRunMode::Running));
2205                VmResponse::Ok
2206            }
2207            VmRequest::Swap(SwapCommand::Enable) => {
2208                #[cfg(feature = "swap")]
2209                if let Some(swap_controller) = swap_controller {
2210                    // Suspend all vcpus and devices while vmm-swap is enabling (move the guest
2211                    // memory contents to the staging memory) to guarantee no processes other than
2212                    // the swap monitor process access the guest memory.
2213                    let _vcpu_guard = match VcpuSuspendGuard::new(&kick_vcpus, vcpu_size) {
2214                        Ok(guard) => guard,
2215                        Err(e) => {
2216                            error!("failed to suspend vcpus: {:?}", e);
2217                            return VmResponse::Err(SysError::new(EINVAL));
2218                        }
2219                    };
2220                    // TODO(b/253386409): Use `devices::Suspendable::sleep()` instead of sending
2221                    // `SIGSTOP` signal.
2222                    let _devices_guard = match swap_controller.suspend_devices() {
2223                        Ok(guard) => guard,
2224                        Err(e) => {
2225                            error!("failed to suspend devices: {:?}", e);
2226                            return VmResponse::Err(SysError::new(EINVAL));
2227                        }
2228                    };
2229
2230                    return match swap_controller.enable() {
2231                        Ok(()) => VmResponse::Ok,
2232                        Err(e) => {
2233                            error!("swap enable failed: {}", e);
2234                            VmResponse::Err(SysError::new(EINVAL))
2235                        }
2236                    };
2237                }
2238                VmResponse::Err(SysError::new(ENOTSUP))
2239            }
2240            VmRequest::Swap(SwapCommand::Trim) => {
2241                #[cfg(feature = "swap")]
2242                if let Some(swap_controller) = swap_controller {
2243                    return match swap_controller.trim() {
2244                        Ok(()) => VmResponse::Ok,
2245                        Err(e) => {
2246                            error!("swap trim failed: {}", e);
2247                            VmResponse::Err(SysError::new(EINVAL))
2248                        }
2249                    };
2250                }
2251                VmResponse::Err(SysError::new(ENOTSUP))
2252            }
2253            VmRequest::Swap(SwapCommand::SwapOut) => {
2254                #[cfg(feature = "swap")]
2255                if let Some(swap_controller) = swap_controller {
2256                    return match swap_controller.swap_out() {
2257                        Ok(()) => VmResponse::Ok,
2258                        Err(e) => {
2259                            error!("swap out failed: {}", e);
2260                            VmResponse::Err(SysError::new(EINVAL))
2261                        }
2262                    };
2263                }
2264                VmResponse::Err(SysError::new(ENOTSUP))
2265            }
2266            VmRequest::Swap(SwapCommand::Disable {
2267                #[cfg(feature = "swap")]
2268                slow_file_cleanup,
2269                ..
2270            }) => {
2271                #[cfg(feature = "swap")]
2272                if let Some(swap_controller) = swap_controller {
2273                    return match swap_controller.disable(*slow_file_cleanup) {
2274                        Ok(()) => VmResponse::Ok,
2275                        Err(e) => {
2276                            error!("swap disable failed: {}", e);
2277                            VmResponse::Err(SysError::new(EINVAL))
2278                        }
2279                    };
2280                }
2281                VmResponse::Err(SysError::new(ENOTSUP))
2282            }
2283            VmRequest::Swap(SwapCommand::Status) => {
2284                #[cfg(feature = "swap")]
2285                if let Some(swap_controller) = swap_controller {
2286                    return match swap_controller.status() {
2287                        Ok(status) => VmResponse::SwapStatus(status),
2288                        Err(e) => {
2289                            error!("swap status failed: {}", e);
2290                            VmResponse::Err(SysError::new(EINVAL))
2291                        }
2292                    };
2293                }
2294                VmResponse::Err(SysError::new(ENOTSUP))
2295            }
2296            VmRequest::SuspendVm => {
2297                info!("Starting crosvm suspend");
2298                kick_vcpus(VcpuControl::RunState(VmRunMode::Suspending));
2299                let current_mode = match get_vcpu_state(kick_vcpus, vcpu_size) {
2300                    Ok(state) => state,
2301                    Err(e) => {
2302                        error!("failed to get vcpu state: {e}");
2303                        return VmResponse::Err(SysError::new(EIO));
2304                    }
2305                };
2306                if current_mode != VmRunMode::Suspending {
2307                    error!("vCPUs failed to all suspend.");
2308                    return VmResponse::Err(SysError::new(EIO));
2309                }
2310                // Snapshot the pvclock ASAP after stopping vCPUs.
2311                if vm.check_capability(VmCap::PvClock) {
2312                    if suspended_pvclock_state.is_none() {
2313                        *suspended_pvclock_state = Some(match vm.get_pvclock() {
2314                            Ok(x) => x,
2315                            Err(e) => {
2316                                error!("suspend_pvclock failed: {e:?}");
2317                                return VmResponse::Err(SysError::new(EIO));
2318                            }
2319                        });
2320                    }
2321                }
2322                if let Err(e) = device_control_tube
2323                    .send(&DeviceControlCommand::SleepDevices)
2324                    .context("send command to devices control socket")
2325                {
2326                    error!("{:?}", e);
2327                    return VmResponse::Err(SysError::new(EIO));
2328                };
2329                match device_control_tube
2330                    .recv()
2331                    .context("receive from devices control socket")
2332                {
2333                    Ok(VmResponse::Ok) => {
2334                        info!("Finished crosvm suspend successfully");
2335                        VmResponse::Ok
2336                    }
2337                    Ok(resp) => {
2338                        error!("device sleep failed: {}", resp);
2339                        VmResponse::Err(SysError::new(EIO))
2340                    }
2341                    Err(e) => {
2342                        error!("receive from devices control socket: {:?}", e);
2343                        VmResponse::Err(SysError::new(EIO))
2344                    }
2345                }
2346            }
2347            VmRequest::ResumeVm => {
2348                info!("Starting crosvm resume");
2349                if let Err(e) = device_control_tube
2350                    .send(&DeviceControlCommand::WakeDevices)
2351                    .context("send command to devices control socket")
2352                {
2353                    error!("{:?}", e);
2354                    return VmResponse::Err(SysError::new(EIO));
2355                };
2356                match device_control_tube
2357                    .recv()
2358                    .context("receive from devices control socket")
2359                {
2360                    Ok(VmResponse::Ok) => {
2361                        info!("Finished crosvm resume successfully");
2362                    }
2363                    Ok(resp) => {
2364                        error!("device wake failed: {}", resp);
2365                        return VmResponse::Err(SysError::new(EIO));
2366                    }
2367                    Err(e) => {
2368                        error!("receive from devices control socket: {:?}", e);
2369                        return VmResponse::Err(SysError::new(EIO));
2370                    }
2371                }
2372                // Resume the pvclock as late as possible before starting vCPUs.
2373                if vm.check_capability(VmCap::PvClock) {
2374                    // If None, then we aren't suspended, which is a valid case.
2375                    if let Some(x) = &suspended_pvclock_state.take() {
2376                        if let Err(e) = vm.set_pvclock(x) {
2377                            error!("resume_pvclock failed: {e:?}");
2378                            return VmResponse::Err(SysError::new(EIO));
2379                        }
2380                    }
2381                }
2382                kick_vcpus(VcpuControl::RunState(VmRunMode::Running));
2383                VmResponse::Ok
2384            }
2385            VmRequest::DeviceControl(req) => req.execute(pm).into(),
2386            VmRequest::MakeRT => {
2387                kick_vcpus(VcpuControl::MakeRT);
2388                VmResponse::Ok
2389            }
2390            #[cfg(feature = "balloon")]
2391            VmRequest::BalloonCommand(_) => unreachable!("Should be handled with BalloonTube"),
2392            VmRequest::DiskCommand {
2393                disk_index,
2394                ref command,
2395            } => match &disk_host_tubes.get(*disk_index) {
2396                Some(tube) => handle_disk_command(command, tube),
2397                None => VmResponse::Err(SysError::new(ENODEV)),
2398            },
2399            VmRequest::GpuCommand(ref cmd) => match gpu_control_tube {
2400                Some(gpu_control) => {
2401                    let res = gpu_control.send(cmd);
2402                    if let Err(e) = res {
2403                        error!("fail to send command to gpu control socket: {}", e);
2404                        return VmResponse::Err(SysError::new(EIO));
2405                    }
2406                    match gpu_control.recv() {
2407                        Ok(response) => VmResponse::GpuResponse(response),
2408                        Err(e) => {
2409                            error!("fail to recv command from gpu control socket: {}", e);
2410                            VmResponse::Err(SysError::new(EIO))
2411                        }
2412                    }
2413                }
2414                None => {
2415                    error!("gpu control is not enabled in crosvm");
2416                    VmResponse::Err(SysError::new(EIO))
2417                }
2418            },
2419            VmRequest::UsbCommand(ref cmd) => {
2420                let usb_control_tube = match usb_control_tube {
2421                    Some(t) => t,
2422                    None => {
2423                        error!("attempted to execute USB request without control tube");
2424                        return VmResponse::Err(SysError::new(ENODEV));
2425                    }
2426                };
2427                let res = usb_control_tube.send(cmd);
2428                if let Err(e) = res {
2429                    error!("fail to send command to usb control socket: {}", e);
2430                    return VmResponse::Err(SysError::new(EIO));
2431                }
2432                match usb_control_tube.recv() {
2433                    Ok(response) => VmResponse::UsbResponse(response),
2434                    Err(e) => {
2435                        error!("fail to recv command from usb control socket: {}", e);
2436                        VmResponse::Err(SysError::new(EIO))
2437                    }
2438                }
2439            }
2440            VmRequest::BatCommand(type_, ref cmd) => {
2441                match bat_control {
2442                    Some(battery) => {
2443                        if battery.type_ != *type_ {
2444                            error!("ignored battery command due to battery type: expected {:?}, got {:?}", battery.type_, type_);
2445                            return VmResponse::Err(SysError::new(EINVAL));
2446                        }
2447
2448                        let res = battery.control_tube.send(cmd);
2449                        if let Err(e) = res {
2450                            error!("fail to send command to bat control socket: {}", e);
2451                            return VmResponse::Err(SysError::new(EIO));
2452                        }
2453
2454                        match battery.control_tube.recv() {
2455                            Ok(response) => VmResponse::BatResponse(response),
2456                            Err(e) => {
2457                                error!("fail to recv command from bat control socket: {}", e);
2458                                VmResponse::Err(SysError::new(EIO))
2459                            }
2460                        }
2461                    }
2462                    None => VmResponse::BatResponse(BatControlResult::NoBatDevice),
2463                }
2464            }
2465            #[cfg(feature = "audio")]
2466            VmRequest::SndCommand(ref cmd) => match cmd {
2467                SndControlCommand::MuteAll(muted) => {
2468                    for tube in snd_host_tubes {
2469                        let res = tube.send(&SndControlCommand::MuteAll(*muted));
2470                        if let Err(e) = res {
2471                            error!("fail to send command to snd control socket: {}", e);
2472                            return VmResponse::Err(SysError::new(EIO));
2473                        }
2474
2475                        match tube.recv() {
2476                            Ok(VmResponse::Ok) => {
2477                                debug!("device is successfully muted");
2478                            }
2479                            Ok(resp) => {
2480                                error!("mute failed: {}", resp);
2481                                return VmResponse::ErrString("fail to mute the device".to_owned());
2482                            }
2483                            Err(e) => return VmResponse::Err(SysError::new(EIO)),
2484                        }
2485                    }
2486                    VmResponse::Ok
2487                }
2488            },
2489            #[cfg(feature = "pci-hotplug")]
2490            VmRequest::HotPlugNetCommand(ref _net_cmd) => {
2491                VmResponse::ErrString("hot plug not supported".to_owned())
2492            }
2493            VmRequest::Snapshot(SnapshotCommand::Take {
2494                ref snapshot_path,
2495                compress_memory,
2496                encrypt,
2497            }) => {
2498                info!("Starting crosvm snapshot");
2499                match do_snapshot(
2500                    snapshot_path.to_path_buf(),
2501                    kick_vcpus,
2502                    irq_handler_control,
2503                    device_control_tube,
2504                    vcpu_size,
2505                    snapshot_irqchip,
2506                    *compress_memory,
2507                    *encrypt,
2508                    suspended_pvclock_state,
2509                    vm,
2510                ) {
2511                    Ok(()) => {
2512                        info!("Finished crosvm snapshot successfully");
2513                        VmResponse::Ok
2514                    }
2515                    Err(e) => {
2516                        error!("failed to handle snapshot: {:?}", e);
2517                        VmResponse::Err(SysError::new(EIO))
2518                    }
2519                }
2520            }
2521            VmRequest::RegisterListener {
2522                socket_addr: _,
2523                event: _,
2524            } => VmResponse::Ok,
2525            VmRequest::UnregisterListener {
2526                socket_addr: _,
2527                event: _,
2528            } => VmResponse::Ok,
2529            VmRequest::Unregister { socket_addr: _ } => VmResponse::Ok,
2530            VmRequest::VcpuPidTid => unreachable!(),
2531            VmRequest::Throttle(_, _) => unreachable!(),
2532            VmRequest::GetVmDescriptor => {
2533                let vm_fd = match vm.try_clone_descriptor() {
2534                    Ok(vm_fd) => vm_fd,
2535                    Err(e) => {
2536                        error!("failed to get vm_fd: {:?}", e);
2537                        return VmResponse::Err(e);
2538                    }
2539                };
2540                VmResponse::VmDescriptor {
2541                    hypervisor: vm.hypervisor_kind(),
2542                    vm_fd,
2543                }
2544            }
2545            VmRequest::RegisterMemory { .. } => unreachable!(),
2546            VmRequest::UnregisterMemory { .. } => unreachable!(),
2547        }
2548    }
2549}
2550
2551/// Snapshot the VM to file at `snapshot_path`
2552fn do_snapshot(
2553    snapshot_path: PathBuf,
2554    kick_vcpus: impl Fn(VcpuControl),
2555    irq_handler_control: &Tube,
2556    device_control_tube: &Tube,
2557    vcpu_size: usize,
2558    snapshot_irqchip: impl Fn() -> anyhow::Result<AnySnapshot>,
2559    compress_memory: bool,
2560    encrypt: bool,
2561    suspended_pvclock_state: &mut Option<hypervisor::ClockState>,
2562    vm: &dyn Vm,
2563) -> anyhow::Result<()> {
2564    let snapshot_start = Instant::now();
2565
2566    let _vcpu_guard = VcpuSuspendGuard::new(&kick_vcpus, vcpu_size)?;
2567    let _device_guard = DeviceSleepGuard::new(device_control_tube)?;
2568
2569    // We want to flush all pending IRQs to the interrupt controller. There are two cases:
2570    //
2571    // MSIs: these are directly delivered to the interrupt controller.
2572    // We must verify the handler thread cycles once to deliver these interrupts.
2573    //
2574    // Legacy interrupts: in the case of a split IRQ chip, these interrupts may
2575    // flow through the userspace IOAPIC. If the hypervisor does not support
2576    // irqfds (e.g. WHPX), a single iteration will only flush the IRQ to the
2577    // IOAPIC. The underlying MSI will be asserted at this point, but if the
2578    // IRQ handler doesn't run another iteration, it won't be delivered to the
2579    // interrupt controller. This is why we cycle the handler thread twice (doing so
2580    // ensures we process the underlying MSI).
2581    //
2582    // We can handle both of these cases by iterating until there are no tokens
2583    // serviced on the requested iteration. Note that in the legacy case, this
2584    // ensures at least two iterations.
2585    //
2586    // Note: within crosvm, *all* interrupts are eventually converted into the
2587    // same mechanicism that MSIs use. This is why we say "underlying" MSI for
2588    // a legacy IRQ.
2589    {
2590        let mut flush_attempts = 0;
2591        loop {
2592            irq_handler_control
2593                .send(&IrqHandlerRequest::WakeAndNotifyIteration)
2594                .context("failed to send flush command to IRQ handler thread")?;
2595            let resp = irq_handler_control
2596                .recv()
2597                .context("failed to recv flush response from IRQ handler thread")?;
2598            match resp {
2599                IrqHandlerResponse::HandlerIterationComplete(tokens_serviced) => {
2600                    if tokens_serviced == 0 {
2601                        break;
2602                    }
2603                }
2604                _ => bail!("received unexpected reply from IRQ handler: {:?}", resp),
2605            }
2606            flush_attempts += 1;
2607            if flush_attempts > EXPECTED_MAX_IRQ_FLUSH_ITERATIONS {
2608                warn!(
2609                    "flushing IRQs for snapshot may be stalled after iteration {}, expected <= {}
2610                      iterations",
2611                    flush_attempts, EXPECTED_MAX_IRQ_FLUSH_ITERATIONS
2612                );
2613            }
2614        }
2615        info!("flushed IRQs in {} iterations", flush_attempts);
2616    }
2617    let snapshot_writer = SnapshotWriter::new(snapshot_path, encrypt)?;
2618
2619    // Snapshot hypervisor's paravirtualized clock.
2620    snapshot_writer.write_fragment("pvclock", &AnySnapshot::to_any(suspended_pvclock_state)?)?;
2621
2622    // Snapshot Vcpus
2623    info!("VCPUs snapshotting...");
2624    let (send_chan, recv_chan) = mpsc::channel();
2625    kick_vcpus(VcpuControl::Snapshot(
2626        snapshot_writer.add_namespace("vcpu")?,
2627        send_chan,
2628    ));
2629    // Validate all Vcpus snapshot successfully
2630    for _ in 0..vcpu_size {
2631        recv_chan
2632            .recv()
2633            .context("Failed to recv Vcpu snapshot response")?
2634            .context("Failed to snapshot Vcpu")?;
2635    }
2636    info!("VCPUs snapshotted.");
2637
2638    // Snapshot irqchip
2639    info!("Snapshotting irqchip...");
2640    let irqchip_snap = snapshot_irqchip()?;
2641    snapshot_writer
2642        .write_fragment("irqchip", &irqchip_snap)
2643        .context("Failed to write irqchip state")?;
2644    info!("Snapshotted irqchip.");
2645
2646    // Snapshot memory
2647    {
2648        let mem_snap_start = Instant::now();
2649        // Use 64MB chunks when writing the memory snapshot (if encryption is used).
2650        const MEMORY_SNAP_ENCRYPTED_CHUNK_SIZE_BYTES: usize = 1024 * 1024 * 64;
2651        // SAFETY:
2652        // VM & devices are stopped.
2653        let guest_memory_metadata = unsafe {
2654            vm.get_memory()
2655                .snapshot(
2656                    &mut snapshot_writer.raw_fragment_with_chunk_size(
2657                        "mem",
2658                        MEMORY_SNAP_ENCRYPTED_CHUNK_SIZE_BYTES,
2659                    )?,
2660                    compress_memory,
2661                )
2662                .context("failed to snapshot memory")?
2663        };
2664        snapshot_writer.write_fragment("mem_metadata", &guest_memory_metadata)?;
2665
2666        let mem_snap_duration_ms = mem_snap_start.elapsed().as_millis();
2667        info!(
2668            "snapshot: memory snapshotted {}MB in {}ms",
2669            vm.get_memory().memory_size() / 1024 / 1024,
2670            mem_snap_duration_ms
2671        );
2672        metrics::log_metric_with_details(
2673            metrics::MetricEventType::SnapshotSaveMemoryLatency,
2674            mem_snap_duration_ms as i64,
2675            &metrics_events::RecordDetails {},
2676        );
2677    }
2678    // Snapshot devices
2679    info!("Devices snapshotting...");
2680    device_control_tube
2681        .send(&DeviceControlCommand::SnapshotDevices { snapshot_writer })
2682        .context("send command to devices control socket")?;
2683    let resp: VmResponse = device_control_tube
2684        .recv()
2685        .context("receive from devices control socket")?;
2686    if !matches!(resp, VmResponse::Ok) {
2687        bail!("unexpected SnapshotDevices response: {resp}");
2688    }
2689    info!("Devices snapshotted.");
2690
2691    let snap_duration_ms = snapshot_start.elapsed().as_millis();
2692    info!(
2693        "snapshot: completed snapshot in {}ms; VM mem size: {}MB",
2694        snap_duration_ms,
2695        vm.get_memory().memory_size() / 1024 / 1024,
2696    );
2697    metrics::log_metric_with_details(
2698        metrics::MetricEventType::SnapshotSaveOverallLatency,
2699        snap_duration_ms as i64,
2700        &metrics_events::RecordDetails {},
2701    );
2702    Ok(())
2703}
2704
2705/// Restore the VM to the snapshot at `restore_path`.
2706///
2707/// Same as `VmRequest::execute` with a `VmRequest::Restore`. Exposed as a separate function
2708/// because not all the `VmRequest::execute` arguments are available in the "cold restore" flow.
2709pub fn do_restore(
2710    restore_path: &Path,
2711    kick_vcpus: impl Fn(VcpuControl),
2712    kick_vcpu: impl Fn(VcpuControl, usize),
2713    irq_handler_control: &Tube,
2714    device_control_tube: &Tube,
2715    vcpu_size: usize,
2716    mut restore_irqchip: impl FnMut(AnySnapshot) -> anyhow::Result<()>,
2717    require_encrypted: bool,
2718    suspended_pvclock_state: &mut Option<hypervisor::ClockState>,
2719    vm: &dyn Vm,
2720) -> anyhow::Result<()> {
2721    let restore_start = Instant::now();
2722    let _guard = VcpuSuspendGuard::new(&kick_vcpus, vcpu_size);
2723    let _devices_guard = DeviceSleepGuard::new(device_control_tube)?;
2724
2725    let snapshot_reader = SnapshotReader::new(restore_path, require_encrypted)?;
2726
2727    // Restore hypervisor's paravirtualized clock.
2728    *suspended_pvclock_state = snapshot_reader.read_fragment("pvclock")?;
2729
2730    // Restore IrqChip
2731    let irq_snapshot: AnySnapshot = snapshot_reader.read_fragment("irqchip")?;
2732    restore_irqchip(irq_snapshot)?;
2733
2734    // Restore Vcpu(s)
2735    let vcpu_snapshot_reader = snapshot_reader.namespace("vcpu")?;
2736    let vcpu_snapshot_count = vcpu_snapshot_reader.list_fragments()?.len();
2737    if vcpu_snapshot_count != vcpu_size {
2738        bail!(
2739            "bad cpu count in snapshot: expected={} got={}",
2740            vcpu_size,
2741            vcpu_snapshot_count,
2742        );
2743    }
2744    #[cfg(target_arch = "x86_64")]
2745    let host_tsc_reference_moment = {
2746        // SAFETY: rdtsc takes no arguments.
2747        unsafe { _rdtsc() }
2748    };
2749    let (send_chan, recv_chan) = mpsc::channel();
2750    for vcpu_id in 0..vcpu_size {
2751        kick_vcpu(
2752            VcpuControl::Restore(VcpuRestoreRequest {
2753                result_sender: send_chan.clone(),
2754                snapshot_reader: vcpu_snapshot_reader.clone(),
2755                #[cfg(target_arch = "x86_64")]
2756                host_tsc_reference_moment,
2757            }),
2758            vcpu_id,
2759        );
2760    }
2761    for _ in 0..vcpu_size {
2762        recv_chan
2763            .recv()
2764            .context("Failed to recv restore response")?
2765            .context("Failed to restore vcpu")?;
2766    }
2767
2768    // Restore Memory
2769    {
2770        let mem_restore_start = Instant::now();
2771        let guest_memory_metadata = snapshot_reader.read_fragment("mem_metadata")?;
2772        // SAFETY:
2773        // VM & devices are stopped.
2774        unsafe {
2775            vm.get_memory().restore(
2776                guest_memory_metadata,
2777                &mut snapshot_reader.raw_fragment("mem")?,
2778            )?
2779        };
2780        let mem_restore_duration_ms = mem_restore_start.elapsed().as_millis();
2781        info!(
2782            "snapshot: memory restored {}MB in {}ms",
2783            vm.get_memory().memory_size() / 1024 / 1024,
2784            mem_restore_duration_ms
2785        );
2786        metrics::log_metric_with_details(
2787            metrics::MetricEventType::SnapshotRestoreMemoryLatency,
2788            mem_restore_duration_ms as i64,
2789            &metrics_events::RecordDetails {},
2790        );
2791    }
2792    // Restore devices
2793    device_control_tube
2794        .send(&DeviceControlCommand::RestoreDevices {
2795            snapshot_reader: snapshot_reader.clone(),
2796        })
2797        .context("send restore devices command to devices control socket")?;
2798    let resp: VmResponse = device_control_tube
2799        .recv()
2800        .context("receive from devices control socket")?;
2801    if !matches!(resp, VmResponse::Ok) {
2802        bail!("unexpected RestoreDevices response: {resp}");
2803    }
2804
2805    // refresh the IRQ tokens.
2806    {
2807        irq_handler_control
2808            .send(&IrqHandlerRequest::RefreshIrqEventTokens)
2809            .context("failed to send refresh irq event token command to IRQ handler thread")?;
2810        let resp: IrqHandlerResponse = irq_handler_control
2811            .recv()
2812            .context("failed to recv refresh response from IRQ handler thread")?;
2813        if !matches!(resp, IrqHandlerResponse::IrqEventTokenRefreshComplete) {
2814            bail!(
2815                "received unexpected reply from IRQ handler thread: {:?}",
2816                resp
2817            );
2818        }
2819    }
2820
2821    let restore_duration_ms = restore_start.elapsed().as_millis();
2822    info!(
2823        "snapshot: completed restore in {}ms; mem size: {}",
2824        restore_duration_ms,
2825        vm.get_memory().memory_size(),
2826    );
2827
2828    metrics::log_metric_with_details(
2829        metrics::MetricEventType::SnapshotRestoreOverallLatency,
2830        restore_duration_ms as i64,
2831        &metrics_events::RecordDetails {},
2832    );
2833    Ok(())
2834}
2835
2836pub type HypervisorKind = hypervisor::HypervisorKind;
2837
2838/// Indication of success or failure of a `VmRequest`.
2839///
2840/// Success is usually indicated `VmResponse::Ok` unless there is data associated with the response.
2841#[derive(Serialize, Deserialize, Debug)]
2842#[must_use]
2843pub enum VmResponse {
2844    /// Indicates the request was executed successfully.
2845    Ok,
2846    /// Indicates the request encountered some error during execution.
2847    Err(SysError),
2848    /// Indicates the request encountered some error during execution.
2849    ErrString(String),
2850    /// The memory was registered into guest address space in memory slot number `slot`.
2851    RegisterMemory { slot: u32 },
2852    /// Variant of the register memory but with region_id.
2853    RegisterMemory2 { region_id: u64 },
2854    /// Results of balloon control commands.
2855    #[cfg(feature = "balloon")]
2856    BalloonStats {
2857        stats: balloon_control::BalloonStats,
2858        balloon_actual: u64,
2859    },
2860    /// Results of balloon WS-R command
2861    #[cfg(feature = "balloon")]
2862    BalloonWS {
2863        ws: balloon_control::BalloonWS,
2864        balloon_actual: u64,
2865    },
2866    /// Results of PCI hot plug
2867    #[cfg(feature = "pci-hotplug")]
2868    PciHotPlugResponse { bus: u8 },
2869    /// Results of usb control commands.
2870    UsbResponse(UsbControlResult),
2871    /// Results of gpu control commands.
2872    GpuResponse(GpuControlResult),
2873    /// Results of battery control commands.
2874    BatResponse(BatControlResult),
2875    /// Results of swap status command.
2876    SwapStatus(SwapStatus),
2877    /// Gets the state of Devices (sleep/wake)
2878    DevicesState(DevicesState),
2879    /// Map of the Vcpu PID/TIDs
2880    VcpuPidTidResponse {
2881        pid_tid_map: BTreeMap<usize, (u32, u32)>,
2882    },
2883    VmDescriptor {
2884        hypervisor: HypervisorKind,
2885        vm_fd: SafeDescriptor,
2886    },
2887}
2888
2889impl Display for VmResponse {
2890    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2891        use self::VmResponse::*;
2892
2893        match self {
2894            Ok => write!(f, "ok"),
2895            Err(e) => write!(f, "error: {e}"),
2896            ErrString(e) => write!(f, "error: {e}"),
2897            RegisterMemory { slot } => write!(f, "memory registered in slot {slot}"),
2898            RegisterMemory2 { region_id } => {
2899                write!(f, "memory registered in region id {region_id}")
2900            }
2901            #[cfg(feature = "balloon")]
2902            VmResponse::BalloonStats {
2903                stats,
2904                balloon_actual,
2905            } => {
2906                write!(
2907                    f,
2908                    "stats: {}\nballoon_actual: {}",
2909                    serde_json::to_string_pretty(&stats)
2910                        .unwrap_or_else(|_| "invalid_response".to_string()),
2911                    balloon_actual
2912                )
2913            }
2914            #[cfg(feature = "balloon")]
2915            VmResponse::BalloonWS { ws, balloon_actual } => {
2916                write!(
2917                    f,
2918                    "ws: {}, balloon_actual: {}",
2919                    serde_json::to_string_pretty(&ws)
2920                        .unwrap_or_else(|_| "invalid_response".to_string()),
2921                    balloon_actual,
2922                )
2923            }
2924            UsbResponse(result) => write!(f, "usb control request get result {result:?}"),
2925            #[cfg(feature = "pci-hotplug")]
2926            PciHotPlugResponse { bus } => write!(f, "pci hotplug bus {bus:?}"),
2927            GpuResponse(result) => write!(f, "gpu control request result {result:?}"),
2928            BatResponse(result) => write!(f, "{result}"),
2929            SwapStatus(status) => {
2930                write!(
2931                    f,
2932                    "{}",
2933                    serde_json::to_string(&status)
2934                        .unwrap_or_else(|_| "invalid_response".to_string()),
2935                )
2936            }
2937            DevicesState(status) => write!(f, "devices status: {status:?}"),
2938            VcpuPidTidResponse { pid_tid_map } => write!(f, "vcpu pid tid map: {pid_tid_map:?}"),
2939            VmDescriptor { hypervisor, vm_fd } => {
2940                write!(f, "hypervisor: {hypervisor:?}, vm_fd: {vm_fd:?}")
2941            }
2942        }
2943    }
2944}
2945
2946/// Enum that allows remote control of a wait context (used between the Windows GpuDisplay & the
2947/// GPU worker).
2948#[derive(Serialize, Deserialize)]
2949pub enum ModifyWaitContext {
2950    Add(#[serde(with = "with_as_descriptor")] Descriptor),
2951}
2952
2953#[sorted]
2954#[derive(Error, Debug)]
2955pub enum VirtioIOMMUVfioError {
2956    #[error("socket failed")]
2957    SocketFailed,
2958    #[error("unexpected response: {0}")]
2959    UnexpectedResponse(VirtioIOMMUResponse),
2960    #[error("unknown command: `{0}`")]
2961    UnknownCommand(String),
2962    #[error("{0}")]
2963    VfioControl(VirtioIOMMUVfioResult),
2964}
2965
2966#[derive(Serialize, Deserialize, Debug)]
2967pub enum VirtioIOMMUVfioCommand {
2968    // Add the vfio device attached to virtio-iommu.
2969    VfioDeviceAdd {
2970        endpoint_addr: u32,
2971        wrapper_id: u32,
2972        #[serde(with = "with_as_descriptor")]
2973        container: File,
2974    },
2975    // Delete the vfio device attached to virtio-iommu.
2976    VfioDeviceDel {
2977        endpoint_addr: u32,
2978    },
2979    // Map a dma-buf into vfio iommu table
2980    VfioDmabufMap {
2981        region_id: VmMemoryRegionId,
2982        gpa: u64,
2983        size: u64,
2984        dma_buf: SafeDescriptor,
2985    },
2986    // Unmap a dma-buf from vfio iommu table
2987    VfioDmabufUnmap(VmMemoryRegionId),
2988}
2989
2990#[derive(Serialize, Deserialize, Debug)]
2991pub enum VirtioIOMMUVfioResult {
2992    Ok,
2993    NotInPCIRanges,
2994    NoAvailableContainer,
2995    NoSuchDevice,
2996    NoSuchMappedDmabuf,
2997    InvalidParam,
2998}
2999
3000impl Display for VirtioIOMMUVfioResult {
3001    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3002        use self::VirtioIOMMUVfioResult::*;
3003
3004        match self {
3005            Ok => write!(f, "successfully"),
3006            NotInPCIRanges => write!(f, "not in the pci ranges of virtio-iommu"),
3007            NoAvailableContainer => write!(f, "no available vfio container"),
3008            NoSuchDevice => write!(f, "no such a vfio device"),
3009            NoSuchMappedDmabuf => write!(f, "no such a mapped dmabuf"),
3010            InvalidParam => write!(f, "invalid parameters"),
3011        }
3012    }
3013}
3014
3015/// A request to the virtio-iommu process to perform some operations.
3016///
3017/// Unless otherwise noted, each request should expect a `VirtioIOMMUResponse::Ok` to be received on
3018/// success.
3019#[derive(Serialize, Deserialize, Debug)]
3020pub enum VirtioIOMMURequest {
3021    /// Command for vfio related operations.
3022    VfioCommand(VirtioIOMMUVfioCommand),
3023}
3024
3025/// Indication of success or failure of a `VirtioIOMMURequest`.
3026///
3027/// Success is usually indicated `VirtioIOMMUResponse::Ok` unless there is data associated with the
3028/// response.
3029#[derive(Serialize, Deserialize, Debug)]
3030pub enum VirtioIOMMUResponse {
3031    /// Indicates the request was executed successfully.
3032    Ok,
3033    /// Indicates the request encountered some error during execution.
3034    Err(SysError),
3035    /// Results for Vfio commands.
3036    VfioResponse(VirtioIOMMUVfioResult),
3037}
3038
3039impl Display for VirtioIOMMUResponse {
3040    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3041        use self::VirtioIOMMUResponse::*;
3042        match self {
3043            Ok => write!(f, "ok"),
3044            Err(e) => write!(f, "error: {e}"),
3045            VfioResponse(result) => write!(
3046                f,
3047                "The vfio-related virtio-iommu request got result: {result:?}"
3048            ),
3049        }
3050    }
3051}
3052
3053/// Send VirtioIOMMURequest without waiting for the response
3054pub fn virtio_iommu_request_async(
3055    iommu_control_tube: &Tube,
3056    req: &VirtioIOMMURequest,
3057) -> VirtioIOMMUResponse {
3058    match iommu_control_tube.send(&req) {
3059        Ok(_) => VirtioIOMMUResponse::Ok,
3060        Err(e) => {
3061            error!("virtio-iommu socket send failed: {:?}", e);
3062            VirtioIOMMUResponse::Err(SysError::last())
3063        }
3064    }
3065}
3066
3067pub type VirtioIOMMURequestResult = std::result::Result<VirtioIOMMUResponse, ()>;
3068
3069/// Send VirtioIOMMURequest and wait to get the response
3070pub fn virtio_iommu_request(
3071    iommu_control_tube: &Tube,
3072    req: &VirtioIOMMURequest,
3073) -> VirtioIOMMURequestResult {
3074    let response = match virtio_iommu_request_async(iommu_control_tube, req) {
3075        VirtioIOMMUResponse::Ok => match iommu_control_tube.recv() {
3076            Ok(response) => response,
3077            Err(e) => {
3078                error!("virtio-iommu socket recv failed: {:?}", e);
3079                VirtioIOMMUResponse::Err(SysError::last())
3080            }
3081        },
3082        resp => resp,
3083    };
3084    Ok(response)
3085}
3086
3087#[cfg(test)]
3088mod tests {
3089    use anyhow::anyhow;
3090
3091    use super::*;
3092
3093    #[test]
3094    fn vm_memory_response_error_should_serialize_and_deserialize_correctly() {
3095        let source_error: VmMemoryResponseError = anyhow!("root cause")
3096            .context("context 1")
3097            .context("context 2")
3098            .into();
3099        let serialized_bytes =
3100            serde_json::to_vec(&source_error).expect("should serialize to json successfully");
3101        let target_error = serde_json::from_slice::<VmMemoryResponseError>(&serialized_bytes)
3102            .expect("should deserialize from json successfully");
3103        assert_eq!(source_error.0.to_string(), target_error.0.to_string());
3104        assert_eq!(
3105            source_error
3106                .0
3107                .chain()
3108                .map(ToString::to_string)
3109                .collect::<Vec<_>>(),
3110            target_error
3111                .0
3112                .chain()
3113                .map(ToString::to_string)
3114                .collect::<Vec<_>>()
3115        );
3116    }
3117
3118    #[test]
3119    fn vm_memory_response_error_deserialization_should_handle_malformat_correctly() {
3120        let flat_source = FlatVmMemoryResponseError(vec![]);
3121        let serialized_bytes =
3122            serde_json::to_vec(&flat_source).expect("should serialize to json successfully");
3123        serde_json::from_slice::<VmMemoryResponseError>(&serialized_bytes)
3124            .expect_err("deserialize with 0 error messages should fail");
3125    }
3126
3127    #[test]
3128    fn test_device_control_request_serde() {
3129        let req = DeviceControlRequest::Gpe {
3130            gpe: 5,
3131            clear_evt: None,
3132        };
3133        let bytes = serde_json::to_vec(&req).unwrap();
3134        let deserialized: DeviceControlRequest = serde_json::from_slice(&bytes).unwrap();
3135        match deserialized {
3136            DeviceControlRequest::Gpe { gpe, clear_evt } => {
3137                assert_eq!(gpe, 5);
3138                assert!(clear_evt.is_none());
3139            }
3140            _ => panic!("unexpected request variant"),
3141        }
3142
3143        let resp = DeviceControlResponse::Ok;
3144        let bytes = serde_json::to_vec(&resp).unwrap();
3145        let deserialized: DeviceControlResponse = serde_json::from_slice(&bytes).unwrap();
3146        match deserialized {
3147            DeviceControlResponse::Ok => {}
3148            _ => panic!("unexpected response variant"),
3149        }
3150
3151        let vm_req = VmRequest::DeviceControl(DeviceControlRequest::Gpe {
3152            gpe: 5,
3153            clear_evt: None,
3154        });
3155        let bytes = serde_json::to_vec(&vm_req).unwrap();
3156        let deserialized: VmRequest = serde_json::from_slice(&bytes).unwrap();
3157        match deserialized {
3158            VmRequest::DeviceControl(DeviceControlRequest::Gpe { gpe, clear_evt }) => {
3159                assert_eq!(gpe, 5);
3160                assert!(clear_evt.is_none());
3161            }
3162            _ => panic!("unexpected request variant"),
3163        }
3164        // Ensure that VmRequest cannot be deserialized as DeviceControlRequest directly.
3165        assert!(serde_json::from_slice::<DeviceControlRequest>(&bytes).is_err());
3166    }
3167
3168    #[test]
3169    fn test_audio_permission_wire_protocol() {
3170        // Request wire conversions
3171        assert_eq!(AudioPermissionRequest::Check.to_wire(), 1u8);
3172        assert_eq!(
3173            AudioPermissionRequest::try_from(1u8),
3174            Ok(AudioPermissionRequest::Check)
3175        );
3176        assert_eq!(AudioPermissionRequest::try_from(0u8), Err(0u8));
3177        assert_eq!(AudioPermissionRequest::try_from(255u8), Err(255u8));
3178
3179        // Response wire conversions
3180        assert_eq!(AudioPermissionResponse::Granted.to_wire(), 1u8);
3181        assert_eq!(AudioPermissionResponse::Denied.to_wire(), 2u8);
3182        assert_eq!(
3183            AudioPermissionResponse::try_from(1u8),
3184            Ok(AudioPermissionResponse::Granted)
3185        );
3186        assert_eq!(
3187            AudioPermissionResponse::try_from(2u8),
3188            Ok(AudioPermissionResponse::Denied)
3189        );
3190        assert_eq!(AudioPermissionResponse::try_from(0u8), Err(0u8));
3191        assert_eq!(AudioPermissionResponse::try_from(3u8), Err(3u8));
3192    }
3193
3194    #[cfg(any(target_os = "android", target_os = "linux"))]
3195    #[test]
3196    fn test_should_prepare_memory_region_force() {
3197        if cfg!(target_pointer_width = "64") {
3198            assert!(sys::should_prepare_memory_region(true));
3199        } else {
3200            assert!(!sys::should_prepare_memory_region(true));
3201            assert!(!sys::should_prepare_memory_region(false));
3202        }
3203    }
3204}