xref: /cloud-hypervisor/virtio-devices/src/lib.rs (revision 3ce0fef7fd546467398c914dbc74d8542e45cf6f)
1 // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 //
3 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style license that can be
5 // found in the LICENSE-BSD-3-Clause file.
6 //
7 // Copyright © 2019 Intel Corporation
8 //
9 // SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
10 
11 //! Implements virtio devices, queues, and transport mechanisms.
12 
13 #[macro_use]
14 extern crate event_monitor;
15 #[macro_use]
16 extern crate log;
17 
18 use serde::{Deserialize, Serialize};
19 use std::convert::TryInto;
20 use std::io;
21 use thiserror::Error;
22 
23 #[macro_use]
24 mod device;
25 pub mod balloon;
26 pub mod block;
27 mod console;
28 pub mod epoll_helper;
29 mod iommu;
30 pub mod mem;
31 pub mod net;
32 mod pmem;
33 mod rng;
34 pub mod seccomp_filters;
35 mod thread_helper;
36 pub mod transport;
37 pub mod vdpa;
38 pub mod vhost_user;
39 pub mod vsock;
40 pub mod watchdog;
41 
42 pub use self::balloon::Balloon;
43 pub use self::block::{Block, BlockState};
44 pub use self::console::{Console, ConsoleResizer, Endpoint};
45 pub use self::device::{
46     DmaRemapping, UserspaceMapping, VirtioCommon, VirtioDevice, VirtioInterrupt,
47     VirtioInterruptType, VirtioSharedMemoryList,
48 };
49 pub use self::epoll_helper::{
50     EpollHelper, EpollHelperError, EpollHelperHandler, EPOLL_HELPER_EVENT_LAST,
51 };
52 pub use self::iommu::{AccessPlatformMapping, Iommu, IommuMapping};
53 pub use self::mem::{BlocksState, Mem, VirtioMemMappingSource, VIRTIO_MEM_ALIGN_SIZE};
54 pub use self::net::{Net, NetCtrlEpollHandler};
55 pub use self::pmem::Pmem;
56 pub use self::rng::Rng;
57 pub use self::vdpa::{Vdpa, VdpaDmaMapping};
58 pub use self::vsock::Vsock;
59 pub use self::watchdog::Watchdog;
60 use vm_memory::{bitmap::AtomicBitmap, GuestAddress, GuestMemory};
61 use vm_virtio::VirtioDeviceType;
62 
63 type GuestMemoryMmap = vm_memory::GuestMemoryMmap<AtomicBitmap>;
64 type GuestRegionMmap = vm_memory::GuestRegionMmap<AtomicBitmap>;
65 type MmapRegion = vm_memory::MmapRegion<AtomicBitmap>;
66 
67 const DEVICE_INIT: u32 = 0x00;
68 const DEVICE_ACKNOWLEDGE: u32 = 0x01;
69 const DEVICE_DRIVER: u32 = 0x02;
70 const DEVICE_DRIVER_OK: u32 = 0x04;
71 const DEVICE_FEATURES_OK: u32 = 0x08;
72 const DEVICE_FAILED: u32 = 0x80;
73 
74 const VIRTIO_F_RING_INDIRECT_DESC: u32 = 28;
75 const VIRTIO_F_RING_EVENT_IDX: u32 = 29;
76 const VIRTIO_F_VERSION_1: u32 = 32;
77 const VIRTIO_F_IOMMU_PLATFORM: u32 = 33;
78 const VIRTIO_F_IN_ORDER: u32 = 35;
79 const VIRTIO_F_ORDER_PLATFORM: u32 = 36;
80 #[allow(dead_code)]
81 const VIRTIO_F_SR_IOV: u32 = 37;
82 const VIRTIO_F_NOTIFICATION_DATA: u32 = 38;
83 
84 #[derive(Error, Debug)]
85 pub enum ActivateError {
86     #[error("Failed to activate virtio device")]
87     BadActivate,
88     #[error("Failed to clone exit event fd: {0}")]
89     CloneExitEventFd(std::io::Error),
90     #[error("Failed to spawn thread: {0}")]
91     ThreadSpawn(std::io::Error),
92     #[error("Failed to setup vhost-user-fs daemon: {0}")]
93     VhostUserFsSetup(vhost_user::Error),
94     #[error("Failed to setup vhost-user daemon: {0}")]
95     VhostUserSetup(vhost_user::Error),
96     #[error("Failed to create seccomp filter: {0}")]
97     CreateSeccompFilter(seccompiler::Error),
98     #[error("Failed to create rate limiter: {0}")]
99     CreateRateLimiter(std::io::Error),
100     #[error("Failed to activate the vDPA device: {0}")]
101     ActivateVdpa(vdpa::Error),
102 }
103 
104 pub type ActivateResult = std::result::Result<(), ActivateError>;
105 
106 pub type DeviceEventT = u16;
107 
108 #[derive(Error, Debug)]
109 pub enum Error {
110     #[error("Failed to single used queue: {0}")]
111     FailedSignalingUsedQueue(io::Error),
112     #[error("I/O Error: {0}")]
113     IoError(io::Error),
114     #[error("Failed to update memory vhost-user: {0}")]
115     VhostUserUpdateMemory(vhost_user::Error),
116     #[error("Failed to add memory region vhost-user: {0}")]
117     VhostUserAddMemoryRegion(vhost_user::Error),
118     #[error("Failed to set shared memory region")]
119     SetShmRegionsNotSupported,
120     #[error("Failed to process net queue: {0}")]
121     NetQueuePair(::net_util::NetQueuePairError),
122     #[error("Failed to : {0}")]
123     QueueAddUsed(virtio_queue::Error),
124     #[error("Failed to : {0}")]
125     QueueIterator(virtio_queue::Error),
126 }
127 
128 #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
129 pub struct TokenBucketConfig {
130     pub size: u64,
131     pub one_time_burst: Option<u64>,
132     pub refill_time: u64,
133 }
134 
135 #[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
136 #[serde(deny_unknown_fields)]
137 pub struct RateLimiterConfig {
138     pub bandwidth: Option<TokenBucketConfig>,
139     pub ops: Option<TokenBucketConfig>,
140 }
141 
142 impl TryInto<rate_limiter::RateLimiter> for RateLimiterConfig {
143     type Error = io::Error;
144 
145     fn try_into(self) -> std::result::Result<rate_limiter::RateLimiter, Self::Error> {
146         let bw = self.bandwidth.unwrap_or_default();
147         let ops = self.ops.unwrap_or_default();
148         rate_limiter::RateLimiter::new(
149             bw.size,
150             bw.one_time_burst.unwrap_or(0),
151             bw.refill_time,
152             ops.size,
153             ops.one_time_burst.unwrap_or(0),
154             ops.refill_time,
155         )
156     }
157 }
158 
159 /// Convert an absolute address into an address space (GuestMemory)
160 /// to a host pointer and verify that the provided size define a valid
161 /// range within a single memory region.
162 /// Return None if it is out of bounds or if addr+size overlaps a single region.
163 pub fn get_host_address_range<M: GuestMemory + ?Sized>(
164     mem: &M,
165     addr: GuestAddress,
166     size: usize,
167 ) -> Option<*mut u8> {
168     if mem.check_range(addr, size) {
169         Some(mem.get_host_address(addr).unwrap())
170     } else {
171         None
172     }
173 }
174