1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! vm_control API client for use within crosvm

use base::AsRawDescriptor;
use base::Event;
use base::Protection;
use base::RawDescriptor;
use base::Tube;
use base::TubeError;
use hypervisor::Datamatch;
use hypervisor::MemCacheType;
use remain::sorted;
use resources::Alloc;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
use vm_memory::GuestAddress;

use crate::IoEventUpdateRequest;
use crate::VmMemoryDestination;
use crate::VmMemoryRegionId;
use crate::VmMemoryRequest;
use crate::VmMemoryResponse;
use crate::VmMemorySource;

#[derive(Error, Debug)]
#[sorted]
pub enum ApiClientError {
    #[error("API client tube recv failed: {0}")]
    Recv(TubeError),
    #[error("Request failed: {0}")]
    RequestFailed(#[from] base::Error),
    #[error("API client tube send failed: {0}")]
    Send(TubeError),
    #[error("Unexpected tube response")]
    UnexpectedResponse,
}

pub type Result<T> = std::result::Result<T, ApiClientError>;

#[derive(Serialize, Deserialize)]
pub struct VmMemoryClient {
    tube: Tube,
}

impl VmMemoryClient {
    pub fn new(tube: Tube) -> Self {
        VmMemoryClient { tube }
    }

    fn request(&self, request: &VmMemoryRequest) -> Result<VmMemoryResponse> {
        self.tube.send(request).map_err(ApiClientError::Send)?;
        self.tube
            .recv::<VmMemoryResponse>()
            .map_err(ApiClientError::Recv)
    }

    fn request_unit(&self, request: &VmMemoryRequest) -> Result<()> {
        match self.request(request)? {
            VmMemoryResponse::Ok => Ok(()),
            VmMemoryResponse::Err(e) => Err(ApiClientError::RequestFailed(e)),
            _other => Err(ApiClientError::UnexpectedResponse),
        }
    }

    /// Prepare a shared memory region to make later operations more efficient. This
    /// may be a no-op depending on underlying platform support.
    pub fn prepare_shared_memory_region(&self, alloc: Alloc, cache: MemCacheType) -> Result<()> {
        self.request_unit(&VmMemoryRequest::PrepareSharedMemoryRegion { alloc, cache })
    }

    pub fn register_memory(
        &self,
        source: VmMemorySource,
        dest: VmMemoryDestination,
        prot: Protection,
        cache: MemCacheType,
    ) -> Result<VmMemoryRegionId> {
        let request = VmMemoryRequest::RegisterMemory {
            source,
            dest,
            prot,
            cache,
        };
        match self.request(&request)? {
            VmMemoryResponse::Err(e) => Err(ApiClientError::RequestFailed(e)),
            VmMemoryResponse::RegisterMemory(region_id) => Ok(region_id),
            _other => Err(ApiClientError::UnexpectedResponse),
        }
    }

    /// Call hypervisor to free the given memory range.
    pub fn dynamically_free_memory_range(
        &self,
        guest_address: GuestAddress,
        size: u64,
    ) -> Result<()> {
        self.request_unit(&VmMemoryRequest::DynamicallyFreeMemoryRange {
            guest_address,
            size,
        })
    }

    /// Call hypervisor to reclaim a priorly freed memory range.
    pub fn dynamically_reclaim_memory_range(
        &self,
        guest_address: GuestAddress,
        size: u64,
    ) -> Result<()> {
        self.request_unit(&VmMemoryRequest::DynamicallyReclaimMemoryRange {
            guest_address,
            size,
        })
    }

    /// Unregister the given memory slot that was previously registered with `RegisterMemory`.
    pub fn unregister_memory(&self, region: VmMemoryRegionId) -> Result<()> {
        self.request_unit(&VmMemoryRequest::UnregisterMemory(region))
    }

    /// Register an ioeventfd by looking up using Alloc info.
    pub fn register_io_event_with_alloc(
        &self,
        evt: Event,
        allocation: Alloc,
        offset: u64,
        datamatch: Datamatch,
    ) -> Result<()> {
        self.request_unit(&VmMemoryRequest::IoEventWithAlloc {
            evt,
            allocation,
            offset,
            datamatch,
            register: true,
        })
    }

    /// Unregister an eventfd by looking up using Alloc info.
    pub fn unregister_io_event_with_alloc(
        &self,
        evt: Event,
        allocation: Alloc,
        offset: u64,
        datamatch: Datamatch,
    ) -> Result<()> {
        self.request_unit(&VmMemoryRequest::IoEventWithAlloc {
            evt,
            allocation,
            offset,
            datamatch,
            register: false,
        })
    }

    /// Register an eventfd with raw guest memory address.
    pub fn register_io_event(&self, event: Event, addr: u64, datamatch: Datamatch) -> Result<()> {
        self.request_unit(&VmMemoryRequest::IoEventRaw(IoEventUpdateRequest {
            event,
            addr,
            datamatch,
            register: true,
        }))
    }

    /// Unregister an eventfd with raw guest memory address.
    pub fn unregister_io_event(&self, event: Event, addr: u64, datamatch: Datamatch) -> Result<()> {
        self.request_unit(&VmMemoryRequest::IoEventRaw(IoEventUpdateRequest {
            event,
            addr,
            datamatch,
            register: false,
        }))
    }

    pub fn balloon_target_reached(&self, size: u64) -> Result<()> {
        self.request_unit(&VmMemoryRequest::BalloonTargetReached { size })
    }
}

impl AsRawDescriptor for VmMemoryClient {
    fn as_raw_descriptor(&self) -> RawDescriptor {
        self.tube.as_raw_descriptor()
    }
}