vm_control/
api.rs

1// Copyright 2023 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//! vm_control API client for use within crosvm
6
7use base::AsRawDescriptor;
8use base::Event;
9use base::Protection;
10use base::RawDescriptor;
11use base::Tube;
12use base::TubeError;
13use hypervisor::Datamatch;
14use hypervisor::MemCacheType;
15use remain::sorted;
16use resources::Alloc;
17use serde::Deserialize;
18use serde::Serialize;
19use thiserror::Error;
20use vm_memory::GuestAddress;
21
22use crate::IoEventUpdateRequest;
23use crate::VmMemoryDestination;
24use crate::VmMemoryRegionId;
25use crate::VmMemoryRequest;
26use crate::VmMemoryResponse;
27use crate::VmMemoryResponseError;
28use crate::VmMemorySource;
29
30#[derive(Error, Debug)]
31#[sorted]
32pub enum ApiClientError {
33    #[error("API client tube recv failed: {0}")]
34    Recv(TubeError),
35    #[error("Request failed: {0}")]
36    RequestFailed(#[source] anyhow::Error),
37    #[error("API client tube send failed: {0}")]
38    Send(TubeError),
39    #[error("API client tube sending FDs failed: {0}")]
40    SendFds(TubeError),
41    #[error("Unexpected tube response")]
42    UnexpectedResponse,
43}
44
45pub type Result<T> = std::result::Result<T, ApiClientError>;
46
47#[derive(Serialize, Deserialize)]
48pub struct VmMemoryClient {
49    tube: Tube,
50}
51
52impl VmMemoryClient {
53    pub fn new(tube: Tube) -> Self {
54        VmMemoryClient { tube }
55    }
56
57    fn request(&self, request: &VmMemoryRequest) -> Result<VmMemoryResponse> {
58        self.tube.send(request).map_err(ApiClientError::Send)?;
59        self.tube
60            .recv::<VmMemoryResponse>()
61            .map_err(ApiClientError::Recv)
62    }
63
64    fn request_unit(&self, request: &VmMemoryRequest) -> Result<()> {
65        match self.request(request)? {
66            VmMemoryResponse::Ok => Ok(()),
67            VmMemoryResponse::Err(VmMemoryResponseError(e)) => {
68                Err(ApiClientError::RequestFailed(e))
69            }
70            _other => Err(ApiClientError::UnexpectedResponse),
71        }
72    }
73
74    /// Prepare a shared memory region to make later operations more efficient. This
75    /// may be a no-op depending on underlying platform support.
76    pub fn prepare_shared_memory_region(
77        &self,
78        alloc: Alloc,
79        cache: MemCacheType,
80        force: bool,
81    ) -> Result<()> {
82        self.request_unit(&VmMemoryRequest::PrepareSharedMemoryRegion {
83            alloc,
84            cache,
85            force,
86        })
87    }
88
89    pub fn register_memory(
90        &self,
91        source: VmMemorySource,
92        dest: VmMemoryDestination,
93        prot: Protection,
94        cache: MemCacheType,
95    ) -> Result<VmMemoryRegionId> {
96        let request = VmMemoryRequest::RegisterMemory {
97            source,
98            dest,
99            prot,
100            cache,
101        };
102        match self.request(&request)? {
103            VmMemoryResponse::Err(VmMemoryResponseError(e)) => {
104                Err(ApiClientError::RequestFailed(e))
105            }
106            VmMemoryResponse::RegisterMemory { region_id, .. } => Ok(region_id),
107            _other => Err(ApiClientError::UnexpectedResponse),
108        }
109    }
110
111    #[cfg(any(target_os = "android", target_os = "linux"))]
112    pub fn mmap_and_register_memory(
113        &self,
114        mapping_address: GuestAddress,
115        shm: base::SharedMemory,
116        file_mapping_info: Vec<crate::VmMemoryFileMapping>,
117    ) -> Result<u32> {
118        let num_file_mappings = file_mapping_info.len();
119        let req = VmMemoryRequest::MmapAndRegisterMemory {
120            shm,
121            dest: VmMemoryDestination::GuestPhysicalAddress(mapping_address.0),
122            num_file_mappings,
123        };
124
125        self.tube.send(&req).map_err(ApiClientError::Send)?;
126
127        // Since the number of FDs that can be sent via Tube at once is limited to
128        // SCM_MAX_FD, split `file_mappings` to chunks and send them
129        // repeatedly.
130        for m in file_mapping_info.chunks(base::unix::SCM_MAX_FD) {
131            self.tube
132                .send_with_max_fds(&m, m.len())
133                .map_err(ApiClientError::SendFds)?;
134        }
135
136        match self.tube.recv().map_err(ApiClientError::Recv)? {
137            VmMemoryResponse::RegisterMemory { slot, .. } => Ok(slot),
138            VmMemoryResponse::Err(VmMemoryResponseError(e)) => {
139                Err(ApiClientError::RequestFailed(e))
140            }
141            _ => Err(ApiClientError::UnexpectedResponse),
142        }
143    }
144
145    /// Call hypervisor to free the given memory ranges.
146    pub fn dynamically_free_memory_ranges(&self, ranges: Vec<(GuestAddress, u64)>) -> Result<()> {
147        self.request_unit(&VmMemoryRequest::DynamicallyFreeMemoryRanges { ranges })
148    }
149
150    /// Call hypervisor to reclaim a priorly freed memory range.
151    pub fn dynamically_reclaim_memory_ranges(
152        &self,
153        ranges: Vec<(GuestAddress, u64)>,
154    ) -> Result<()> {
155        self.request_unit(&VmMemoryRequest::DynamicallyReclaimMemoryRanges { ranges })
156    }
157
158    /// Unregister the given memory slot that was previously registered with `RegisterMemory`.
159    pub fn unregister_memory(&self, region: VmMemoryRegionId) -> Result<()> {
160        self.request_unit(&VmMemoryRequest::UnregisterMemory(region))
161    }
162
163    /// Register an eventfd with raw guest memory address.
164    pub fn register_io_event(&self, event: Event, addr: u64, datamatch: Datamatch) -> Result<()> {
165        self.request_unit(&VmMemoryRequest::IoEventRaw(IoEventUpdateRequest {
166            event,
167            addr,
168            datamatch,
169            register: true,
170        }))
171    }
172
173    /// Unregister an eventfd with raw guest memory address.
174    pub fn unregister_io_event(&self, event: Event, addr: u64, datamatch: Datamatch) -> Result<()> {
175        self.request_unit(&VmMemoryRequest::IoEventRaw(IoEventUpdateRequest {
176            event,
177            addr,
178            datamatch,
179            register: false,
180        }))
181    }
182
183    pub fn balloon_target_reached(&self, size: u64) -> Result<()> {
184        self.request_unit(&VmMemoryRequest::BalloonTargetReached { size })
185    }
186}
187
188impl AsRawDescriptor for VmMemoryClient {
189    fn as_raw_descriptor(&self) -> RawDescriptor {
190        self.tube.as_raw_descriptor()
191    }
192}