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