1 // Copyright 2019 Intel Corporation. All Rights Reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 // 4 // Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 5 // SPDX-License-Identifier: Apache-2.0 6 // 7 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. 8 // Use of this source code is governed by a BSD-style license that can be 9 // found in the THIRD-PARTY file. 10 11 mod csm; 12 mod device; 13 mod packet; 14 mod unix; 15 16 pub use self::device::Vsock; 17 pub use self::unix::VsockUnixBackend; 18 pub use self::unix::VsockUnixError; 19 20 pub use packet::VsockPacket; 21 use std::os::unix::io::RawFd; 22 23 mod defs { 24 25 /// Max vsock packet data/buffer size. 26 pub const MAX_PKT_BUF_SIZE: usize = 64 * 1024; 27 28 pub mod uapi { 29 30 /// Vsock packet operation IDs. 31 /// Defined in `/include/uapi/linux/virtio_vsock.h`. 32 /// 33 /// Connection request. 34 pub const VSOCK_OP_REQUEST: u16 = 1; 35 /// Connection response. 36 pub const VSOCK_OP_RESPONSE: u16 = 2; 37 /// Connection reset. 38 pub const VSOCK_OP_RST: u16 = 3; 39 /// Connection clean shutdown. 40 pub const VSOCK_OP_SHUTDOWN: u16 = 4; 41 /// Connection data (read/write). 42 pub const VSOCK_OP_RW: u16 = 5; 43 /// Flow control credit update. 44 pub const VSOCK_OP_CREDIT_UPDATE: u16 = 6; 45 /// Flow control credit update request. 46 pub const VSOCK_OP_CREDIT_REQUEST: u16 = 7; 47 48 /// Vsock packet flags. 49 /// Defined in `/include/uapi/linux/virtio_vsock.h`. 50 /// 51 /// Valid with a VSOCK_OP_SHUTDOWN packet: the packet sender will receive no more data. 52 pub const VSOCK_FLAGS_SHUTDOWN_RCV: u32 = 1; 53 /// Valid with a VSOCK_OP_SHUTDOWN packet: the packet sender will send no more data. 54 pub const VSOCK_FLAGS_SHUTDOWN_SEND: u32 = 2; 55 56 /// Vsock packet type. 57 /// Defined in `/include/uapi/linux/virtio_vsock.h`. 58 /// 59 /// Stream / connection-oriented packet (the only currently valid type). 60 pub const VSOCK_TYPE_STREAM: u16 = 1; 61 62 pub const VSOCK_HOST_CID: u64 = 2; 63 } 64 } 65 66 #[derive(Debug)] 67 pub enum VsockError { 68 /// The vsock data/buffer virtio descriptor length is smaller than expected. 69 BufDescTooSmall, 70 /// The vsock data/buffer virtio descriptor is expected, but missing. 71 BufDescMissing, 72 /// Chained GuestMemory error. 73 GuestMemory, 74 /// Bounds check failed on guest memory pointer. 75 GuestMemoryBounds, 76 /// The vsock header descriptor length is too small. 77 HdrDescTooSmall(u32), 78 /// The vsock header `len` field holds an invalid value. 79 InvalidPktLen(u32), 80 /// A data fetch was attempted when no data was available. 81 NoData, 82 /// A data buffer was expected for the provided packet, but it is missing. 83 PktBufMissing, 84 /// Encountered an unexpected write-only virtio descriptor. 85 UnreadableDescriptor, 86 /// Encountered an unexpected read-only virtio descriptor. 87 UnwritableDescriptor, 88 } 89 type Result<T> = std::result::Result<T, VsockError>; 90 91 #[derive(Debug)] 92 pub enum VsockEpollHandlerError { 93 /// The vsock data/buffer virtio descriptor length is smaller than expected. 94 BufDescTooSmall, 95 /// The vsock data/buffer virtio descriptor is expected, but missing. 96 BufDescMissing, 97 /// Chained GuestMemory error. 98 GuestMemory, 99 /// Bounds check failed on guest memory pointer. 100 GuestMemoryBounds, 101 /// The vsock header descriptor length is too small. 102 HdrDescTooSmall(u32), 103 /// The vsock header `len` field holds an invalid value. 104 InvalidPktLen(u32), 105 /// A data fetch was attempted when no data was available. 106 NoData, 107 /// A data buffer was expected for the provided packet, but it is missing. 108 PktBufMissing, 109 /// Encountered an unexpected write-only virtio descriptor. 110 UnreadableDescriptor, 111 /// Encountered an unexpected read-only virtio descriptor. 112 UnwritableDescriptor, 113 } 114 115 /// A passive, event-driven object, that needs to be notified whenever an epoll-able event occurs. 116 /// An event-polling control loop will use `get_polled_fd()` and `get_polled_evset()` to query 117 /// the listener for the file descriptor and the set of events it's interested in. When such an 118 /// event occurs, the control loop will route the event to the listener via `notify()`. 119 /// 120 pub trait VsockEpollListener { 121 /// Get the file descriptor the listener needs polled. 122 fn get_polled_fd(&self) -> RawFd; 123 124 /// Get the set of events for which the listener wants to be notified. 125 fn get_polled_evset(&self) -> epoll::Events; 126 127 /// Notify the listener that one ore more events have occurred. 128 fn notify(&mut self, evset: epoll::Events); 129 } 130 131 /// Any channel that handles vsock packet traffic: sending and receiving packets. Since we're 132 /// implementing the device model here, our responsibility is to always process the sending of 133 /// packets (i.e. the TX queue). So, any locally generated data, addressed to the driver (e.g. 134 /// a connection response or RST), will have to be queued, until we get to processing the RX queue. 135 /// 136 /// Note: `recv_pkt()` and `send_pkt()` are named analogous to `Read::read()` and `Write::write()`, 137 /// respectively. I.e. 138 /// - `recv_pkt(&mut pkt)` will read data from the channel, and place it into `pkt`; and 139 /// - `send_pkt(&pkt)` will fetch data from `pkt`, and place it into the channel. 140 pub trait VsockChannel { 141 /// Read/receive an incoming packet from the channel. 142 fn recv_pkt(&mut self, pkt: &mut VsockPacket) -> Result<()>; 143 144 /// Write/send a packet through the channel. 145 fn send_pkt(&mut self, pkt: &VsockPacket) -> Result<()>; 146 147 /// Checks whether there is pending incoming data inside the channel, meaning that a subsequent 148 /// call to `recv_pkt()` won't fail. 149 fn has_pending_rx(&self) -> bool; 150 } 151 152 /// The vsock backend, which is basically an epoll-event-driven vsock channel, that needs to be 153 /// sendable through a mpsc channel (the latter due to how `vmm::EpollContext` works). 154 /// Currently, the only implementation we have is `crate::virtio::unix::muxer::VsockMuxer`, which 155 /// translates guest-side vsock connections to host-side Unix domain socket connections. 156 pub trait VsockBackend: VsockChannel + VsockEpollListener + Send {} 157 158 #[cfg(test)] 159 mod tests { 160 use super::device::{VsockEpollHandler, RX_QUEUE_EVENT, TX_QUEUE_EVENT}; 161 use super::packet::VSOCK_PKT_HDR_SIZE; 162 use super::*; 163 use crate::device::{VirtioInterrupt, VirtioInterruptType}; 164 use crate::epoll_helper::EpollHelperHandler; 165 use crate::EpollHelper; 166 use crate::GuestMemoryMmap; 167 use libc::EFD_NONBLOCK; 168 use std::os::unix::io::AsRawFd; 169 use std::path::PathBuf; 170 use std::sync::{Arc, RwLock}; 171 use vm_memory::{GuestAddress, GuestMemoryAtomic}; 172 use vm_virtio::queue::testing::VirtQueue as GuestQ; 173 use vm_virtio::queue::Queue; 174 use vm_virtio::queue::{VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE}; 175 use vmm_sys_util::eventfd::EventFd; 176 177 pub struct NoopVirtioInterrupt {} 178 179 impl VirtioInterrupt for NoopVirtioInterrupt { 180 fn trigger( 181 &self, 182 _int_type: &VirtioInterruptType, 183 _queue: Option<&Queue>, 184 ) -> std::result::Result<(), std::io::Error> { 185 Ok(()) 186 } 187 } 188 189 pub struct TestBackend { 190 pub evfd: EventFd, 191 pub rx_err: Option<VsockError>, 192 pub tx_err: Option<VsockError>, 193 pub pending_rx: bool, 194 pub rx_ok_cnt: usize, 195 pub tx_ok_cnt: usize, 196 pub evset: Option<epoll::Events>, 197 } 198 impl TestBackend { 199 pub fn new() -> Self { 200 Self { 201 evfd: EventFd::new(EFD_NONBLOCK).unwrap(), 202 rx_err: None, 203 tx_err: None, 204 pending_rx: false, 205 rx_ok_cnt: 0, 206 tx_ok_cnt: 0, 207 evset: None, 208 } 209 } 210 pub fn set_rx_err(&mut self, err: Option<VsockError>) { 211 self.rx_err = err; 212 } 213 pub fn set_tx_err(&mut self, err: Option<VsockError>) { 214 self.tx_err = err; 215 } 216 pub fn set_pending_rx(&mut self, prx: bool) { 217 self.pending_rx = prx; 218 } 219 } 220 impl VsockChannel for TestBackend { 221 fn recv_pkt(&mut self, _pkt: &mut VsockPacket) -> Result<()> { 222 match self.rx_err.take() { 223 None => { 224 self.rx_ok_cnt += 1; 225 Ok(()) 226 } 227 Some(e) => Err(e), 228 } 229 } 230 fn send_pkt(&mut self, _pkt: &VsockPacket) -> Result<()> { 231 match self.tx_err.take() { 232 None => { 233 self.tx_ok_cnt += 1; 234 Ok(()) 235 } 236 Some(e) => Err(e), 237 } 238 } 239 fn has_pending_rx(&self) -> bool { 240 self.pending_rx 241 } 242 } 243 impl VsockEpollListener for TestBackend { 244 fn get_polled_fd(&self) -> RawFd { 245 self.evfd.as_raw_fd() 246 } 247 fn get_polled_evset(&self) -> epoll::Events { 248 epoll::Events::EPOLLIN 249 } 250 fn notify(&mut self, evset: epoll::Events) { 251 self.evset = Some(evset); 252 } 253 } 254 impl VsockBackend for TestBackend {} 255 256 pub struct TestContext { 257 pub cid: u64, 258 pub mem: GuestMemoryMmap, 259 pub mem_size: usize, 260 pub device: Vsock<TestBackend>, 261 } 262 263 impl TestContext { 264 pub fn new() -> Self { 265 const CID: u64 = 52; 266 const MEM_SIZE: usize = 1024 * 1024 * 128; 267 Self { 268 cid: CID, 269 mem: GuestMemoryMmap::from_ranges(&[(GuestAddress(0), MEM_SIZE)]).unwrap(), 270 mem_size: MEM_SIZE, 271 device: Vsock::new( 272 String::from("vsock"), 273 CID, 274 PathBuf::from("/test/sock"), 275 TestBackend::new(), 276 false, 277 seccompiler::SeccompAction::Trap, 278 EventFd::new(EFD_NONBLOCK).unwrap(), 279 ) 280 .unwrap(), 281 } 282 } 283 284 pub fn create_epoll_handler_context(&self) -> EpollHandlerContext { 285 const QSIZE: u16 = 2; 286 287 let guest_rxvq = GuestQ::new(GuestAddress(0x0010_0000), &self.mem, QSIZE as u16); 288 let guest_txvq = GuestQ::new(GuestAddress(0x0020_0000), &self.mem, QSIZE as u16); 289 let guest_evvq = GuestQ::new(GuestAddress(0x0030_0000), &self.mem, QSIZE as u16); 290 let rxvq = guest_rxvq.create_queue(); 291 let txvq = guest_txvq.create_queue(); 292 let evvq = guest_evvq.create_queue(); 293 294 // Set up one available descriptor in the RX queue. 295 guest_rxvq.dtable[0].set( 296 0x0040_0000, 297 VSOCK_PKT_HDR_SIZE as u32, 298 VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT, 299 1, 300 ); 301 guest_rxvq.dtable[1].set(0x0040_1000, 4096, VIRTQ_DESC_F_WRITE, 0); 302 guest_rxvq.avail.ring[0].set(0); 303 guest_rxvq.avail.idx.set(1); 304 305 // Set up one available descriptor in the TX queue. 306 guest_txvq.dtable[0].set(0x0050_0000, VSOCK_PKT_HDR_SIZE as u32, VIRTQ_DESC_F_NEXT, 1); 307 guest_txvq.dtable[1].set(0x0050_1000, 4096, 0, 0); 308 guest_txvq.avail.ring[0].set(0); 309 guest_txvq.avail.idx.set(1); 310 311 let queues = vec![rxvq, txvq, evvq]; 312 let queue_evts = vec![ 313 EventFd::new(EFD_NONBLOCK).unwrap(), 314 EventFd::new(EFD_NONBLOCK).unwrap(), 315 EventFd::new(EFD_NONBLOCK).unwrap(), 316 ]; 317 let interrupt_cb = Arc::new(NoopVirtioInterrupt {}); 318 319 EpollHandlerContext { 320 guest_rxvq, 321 guest_txvq, 322 guest_evvq, 323 handler: VsockEpollHandler { 324 mem: GuestMemoryAtomic::new(self.mem.clone()), 325 queues, 326 queue_evts, 327 kill_evt: EventFd::new(EFD_NONBLOCK).unwrap(), 328 pause_evt: EventFd::new(EFD_NONBLOCK).unwrap(), 329 interrupt_cb, 330 backend: Arc::new(RwLock::new(TestBackend::new())), 331 }, 332 } 333 } 334 } 335 336 pub struct EpollHandlerContext<'a> { 337 pub handler: VsockEpollHandler<TestBackend>, 338 pub guest_rxvq: GuestQ<'a>, 339 pub guest_txvq: GuestQ<'a>, 340 pub guest_evvq: GuestQ<'a>, 341 } 342 343 impl<'a> EpollHandlerContext<'a> { 344 pub fn signal_txq_event(&mut self) { 345 self.handler.queue_evts[1].write(1).unwrap(); 346 let events = epoll::Events::EPOLLIN; 347 let event = epoll::Event::new(events, TX_QUEUE_EVENT as u64); 348 let mut epoll_helper = 349 EpollHelper::new(&self.handler.kill_evt, &self.handler.pause_evt).unwrap(); 350 self.handler.handle_event(&mut epoll_helper, &event); 351 } 352 pub fn signal_rxq_event(&mut self) { 353 self.handler.queue_evts[0].write(1).unwrap(); 354 let events = epoll::Events::EPOLLIN; 355 let event = epoll::Event::new(events, RX_QUEUE_EVENT as u64); 356 let mut epoll_helper = 357 EpollHelper::new(&self.handler.kill_evt, &self.handler.pause_evt).unwrap(); 358 self.handler.handle_event(&mut epoll_helper, &event); 359 } 360 } 361 } 362