devices/virtio/
mod.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//! Implements virtio devices, queues, and transport mechanisms.
6
7pub mod async_utils;
8#[cfg(feature = "balloon")]
9mod balloon;
10mod descriptor_chain;
11mod descriptor_utils;
12pub mod device_constants;
13pub mod input;
14mod interrupt;
15mod iommu;
16#[cfg(feature = "pvclock")]
17pub mod pvclock;
18mod queue;
19#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
20mod video;
21mod virtio_device;
22mod virtio_mmio_device;
23mod virtio_pci_common_config;
24mod virtio_pci_device;
25
26#[cfg(feature = "gpu")]
27pub mod gpu;
28#[cfg(all(unix, feature = "media"))]
29pub mod media;
30pub mod resource_bridge;
31pub mod vhost;
32pub mod vhost_user_backend;
33pub mod vhost_user_frontend;
34
35pub use vmm_vhost::SharedMemoryRegion;
36
37#[cfg(feature = "balloon")]
38pub use self::balloon::Balloon;
39#[cfg(feature = "balloon")]
40pub use self::balloon::BalloonFeatures;
41pub use self::descriptor_chain::DescriptorChain;
42pub use self::descriptor_chain::DescriptorChainIter;
43pub use self::descriptor_utils::create_descriptor_chain;
44pub use self::descriptor_utils::DescriptorType;
45pub use self::descriptor_utils::Reader;
46pub use self::descriptor_utils::Writer;
47#[cfg(feature = "gpu")]
48pub use self::gpu::DisplayBackend;
49#[cfg(feature = "gpu")]
50pub use self::gpu::Gpu;
51#[cfg(feature = "gpu")]
52pub use self::gpu::GpuDisplayMode;
53#[cfg(feature = "gpu")]
54pub use self::gpu::GpuDisplayParameters;
55#[cfg(feature = "gpu")]
56pub use self::gpu::GpuMode;
57#[cfg(feature = "gpu")]
58pub use self::gpu::GpuMouseMode;
59#[cfg(feature = "gpu")]
60pub use self::gpu::GpuParameters;
61#[cfg(feature = "gpu")]
62pub use self::gpu::GpuWsi;
63pub use self::interrupt::Interrupt;
64pub use self::interrupt::InterruptSnapshot;
65pub use self::iommu::ipc_memory_mapper;
66pub use self::iommu::memory_mapper;
67pub use self::iommu::Iommu;
68pub use self::iommu::IommuError;
69pub use self::queue::split_descriptor_chain::Desc;
70pub use self::queue::split_descriptor_chain::SplitDescriptorChain;
71pub use self::queue::PeekedDescriptorChain;
72pub use self::queue::Queue;
73pub use self::queue::QueueConfig;
74pub use self::vhost_user_frontend::VhostUserFrontend;
75#[cfg(any(feature = "video-decoder", feature = "video-encoder"))]
76pub use self::video::VideoDevice;
77pub use self::virtio_device::SharedMemoryMapper;
78pub use self::virtio_device::SharedMemoryPrepareType;
79pub use self::virtio_device::VirtioDevice;
80pub use self::virtio_mmio_device::VirtioMmioDevice;
81pub use self::virtio_pci_device::PciCapabilityType;
82pub use self::virtio_pci_device::VirtioPciCap;
83pub use self::virtio_pci_device::VirtioPciDevice;
84pub use self::virtio_pci_device::VirtioPciShmCap;
85#[cfg(feature = "pvclock")]
86pub use self::DeviceType::Pvclock;
87
88cfg_if::cfg_if! {
89    if #[cfg(any(target_os = "android", target_os = "linux"))] {
90        mod p9;
91        mod pmem;
92
93        #[cfg(feature = "virtio_wl")]
94        pub mod wl;
95        pub mod fs;
96
97        pub use self::iommu::sys::linux::vfio_wrapper;
98        pub use self::p9::P9;
99        pub use self::pmem::Pmem;
100        pub use self::pmem::PmemConfig;
101        pub use self::pmem::MemSlotConfig;
102        #[cfg(feature = "virtio_wl")]
103        pub use self::wl::Wl;
104    } else if #[cfg(windows)] {
105    } else {
106        compile_error!("Unsupported platform");
107    }
108}
109
110use std::cmp;
111use std::convert::TryFrom;
112
113use futures::channel::oneshot;
114use hypervisor::ProtectionType;
115use serde::Deserialize;
116use serde::Serialize;
117use virtio_sys::virtio_config::VIRTIO_F_ACCESS_PLATFORM;
118use virtio_sys::virtio_config::VIRTIO_F_SUSPEND;
119use virtio_sys::virtio_config::VIRTIO_F_VERSION_1;
120use virtio_sys::virtio_ids;
121use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX;
122
123const DEVICE_RESET: u32 = 0x0;
124
125const INTERRUPT_STATUS_USED_RING: u32 = 0x1;
126pub const INTERRUPT_STATUS_CONFIG_CHANGED: u32 = 0x2;
127
128const VIRTIO_MSI_NO_VECTOR: u16 = 0xffff;
129
130#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
131#[serde(rename_all = "kebab-case")]
132#[repr(u32)]
133pub enum DeviceType {
134    Net = virtio_ids::VIRTIO_ID_NET,
135    Block = virtio_ids::VIRTIO_ID_BLOCK,
136    Console = virtio_ids::VIRTIO_ID_CONSOLE,
137    Rng = virtio_ids::VIRTIO_ID_RNG,
138    Balloon = virtio_ids::VIRTIO_ID_BALLOON,
139    Scsi = virtio_ids::VIRTIO_ID_SCSI,
140    #[serde(rename = "9p")]
141    P9 = virtio_ids::VIRTIO_ID_9P,
142    Gpu = virtio_ids::VIRTIO_ID_GPU,
143    Input = virtio_ids::VIRTIO_ID_INPUT,
144    Vsock = virtio_ids::VIRTIO_ID_VSOCK,
145    Iommu = virtio_ids::VIRTIO_ID_IOMMU,
146    Sound = virtio_ids::VIRTIO_ID_SOUND,
147    Fs = virtio_ids::VIRTIO_ID_FS,
148    Pmem = virtio_ids::VIRTIO_ID_PMEM,
149    #[serde(rename = "mac80211-hwsim")]
150    Mac80211HwSim = virtio_ids::VIRTIO_ID_MAC80211_HWSIM,
151    VideoEncoder = virtio_ids::VIRTIO_ID_VIDEO_ENCODER,
152    VideoDecoder = virtio_ids::VIRTIO_ID_VIDEO_DECODER,
153    Scmi = virtio_ids::VIRTIO_ID_SCMI,
154    Wl = virtio_ids::VIRTIO_ID_WL,
155    Tpm = virtio_ids::VIRTIO_ID_TPM,
156    Pvclock = virtio_ids::VIRTIO_ID_PVCLOCK,
157    Media = virtio_ids::VIRTIO_ID_MEDIA,
158}
159
160impl DeviceType {
161    /// Returns the minimum number of queues that a device of the corresponding type must support.
162    ///
163    /// Note that this does not mean a driver must activate these queues, only that they must be
164    /// implemented by a spec-compliant device.
165    pub fn min_queues(&self) -> usize {
166        match self {
167            DeviceType::Net => 3,           // rx, tx (TODO: b/314353246: ctrl is optional)
168            DeviceType::Block => 1,         // request queue
169            DeviceType::Console => 2,       // receiveq, transmitq
170            DeviceType::Rng => 1,           // request queue
171            DeviceType::Balloon => 2,       // inflateq, deflateq
172            DeviceType::Scsi => 3,          // controlq, eventq, request queue
173            DeviceType::P9 => 1,            // request queue
174            DeviceType::Gpu => 2,           // controlq, cursorq
175            DeviceType::Input => 2,         // eventq, statusq
176            DeviceType::Vsock => 3,         // rx, tx, event
177            DeviceType::Iommu => 2,         // requestq, eventq
178            DeviceType::Sound => 4,         // controlq, eventq, txq, rxq
179            DeviceType::Fs => 2,            // hiprio, request queue
180            DeviceType::Pmem => 1,          // request queue
181            DeviceType::Mac80211HwSim => 2, // tx, rx
182            DeviceType::VideoEncoder => 2,  // cmdq, eventq
183            DeviceType::VideoDecoder => 2,  // cmdq, eventq
184            DeviceType::Scmi => 2,          // cmdq, eventq
185            DeviceType::Wl => 2,            // in, out
186            DeviceType::Tpm => 1,           // request queue
187            DeviceType::Pvclock => 1,       // request queue
188            DeviceType::Media => 2,         // commandq, eventq
189        }
190    }
191}
192
193/// Prints a string representation of the given virtio device type.
194impl std::fmt::Display for DeviceType {
195    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
196        match &self {
197            DeviceType::Net => write!(f, "net"),
198            DeviceType::Block => write!(f, "block"),
199            DeviceType::Console => write!(f, "console"),
200            DeviceType::Rng => write!(f, "rng"),
201            DeviceType::Balloon => write!(f, "balloon"),
202            DeviceType::Scsi => write!(f, "scsi"),
203            DeviceType::P9 => write!(f, "9p"),
204            DeviceType::Input => write!(f, "input"),
205            DeviceType::Gpu => write!(f, "gpu"),
206            DeviceType::Vsock => write!(f, "vsock"),
207            DeviceType::Iommu => write!(f, "iommu"),
208            DeviceType::Sound => write!(f, "sound"),
209            DeviceType::Fs => write!(f, "fs"),
210            DeviceType::Pmem => write!(f, "pmem"),
211            DeviceType::Wl => write!(f, "wl"),
212            DeviceType::Tpm => write!(f, "tpm"),
213            DeviceType::Pvclock => write!(f, "pvclock"),
214            DeviceType::VideoDecoder => write!(f, "video-decoder"),
215            DeviceType::VideoEncoder => write!(f, "video-encoder"),
216            DeviceType::Mac80211HwSim => write!(f, "mac80211-hwsim"),
217            DeviceType::Scmi => write!(f, "scmi"),
218            DeviceType::Media => write!(f, "media"),
219        }
220    }
221}
222
223/// Copy virtio device configuration data from a subslice of `src` to a subslice of `dst`.
224/// Unlike std::slice::copy_from_slice(), this function copies as much as possible within
225/// the common subset of the two slices, truncating the requested range instead of
226/// panicking if the slices do not match in size.
227///
228/// `dst_offset` and `src_offset` specify the starting indexes of the `dst` and `src`
229/// slices, respectively; if either index is out of bounds, this function is a no-op
230/// rather than panicking.  This makes it safe to call with arbitrary user-controlled
231/// inputs.
232pub fn copy_config(dst: &mut [u8], dst_offset: u64, src: &[u8], src_offset: u64) {
233    if let Ok(dst_offset) = usize::try_from(dst_offset) {
234        if let Ok(src_offset) = usize::try_from(src_offset) {
235            if let Some(dst_slice) = dst.get_mut(dst_offset..) {
236                if let Some(src_slice) = src.get(src_offset..) {
237                    let len = cmp::min(dst_slice.len(), src_slice.len());
238                    let dst_subslice = &mut dst_slice[0..len];
239                    let src_subslice = &src_slice[0..len];
240                    dst_subslice.copy_from_slice(src_subslice);
241                }
242            }
243        }
244    }
245}
246
247/// Returns the set of reserved base features common to all virtio devices.
248pub fn base_features(protection_type: ProtectionType) -> u64 {
249    let mut features: u64 =
250        1 << VIRTIO_F_VERSION_1 | 1 << VIRTIO_RING_F_EVENT_IDX | 1 << VIRTIO_F_SUSPEND;
251
252    if protection_type != ProtectionType::Unprotected {
253        features |= 1 << VIRTIO_F_ACCESS_PLATFORM;
254    }
255
256    features
257}
258
259/// Type of virtio transport.
260///
261/// The virtio protocol can be transported by several means, which affects a few things for device
262/// creation - for instance, the seccomp policy we need to use when jailing the device.
263pub enum VirtioDeviceType {
264    /// A regular (in-VMM) virtio device.
265    Regular,
266    /// Socket-backed vhost-user device.
267    VhostUser,
268}
269
270impl VirtioDeviceType {
271    /// Returns the seccomp policy file that we will want to load for device `base`, depending on
272    /// the virtio transport type.
273    pub fn seccomp_policy_file(&self, base: &str) -> String {
274        match self {
275            VirtioDeviceType::Regular => format!("{base}_device"),
276            VirtioDeviceType::VhostUser => format!("{base}_device_vhost_user"),
277        }
278    }
279}
280
281/// Creates a oneshot channel, returning the rx end and adding the tx end to the
282/// provided `Vec`. Useful for creating oneshots that signal a virtqueue future
283/// to stop processing and exit.
284pub fn create_stop_oneshot(tx_vec: &mut Vec<oneshot::Sender<()>>) -> oneshot::Receiver<()> {
285    let (stop_tx, stop_rx) = futures::channel::oneshot::channel();
286    tx_vec.push(stop_tx);
287    stop_rx
288}
289
290/// When we request to stop the worker, this represents the terminal state
291/// for the thread (if it exists).
292pub enum StoppedWorker<Q> {
293    /// Worker stopped successfully & returned its queues.
294    WithQueues(Box<Q>),
295
296    /// Worker wasn't running when the stop was requested.
297    AlreadyStopped,
298
299    /// Worker was running but did not successfully return its queues. Something
300    /// has gone wrong (and will be in the error log). In the case of a device
301    /// reset this is fine since the next activation will replace the queues.
302    MissingQueues,
303}