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 use std::os::unix::io::AsRawFd; 12 use std::path::PathBuf; 13 use std::sync::atomic::AtomicBool; 14 use std::sync::{Arc, Barrier, RwLock}; 15 use std::{io, result}; 16 17 use anyhow::anyhow; 18 use byteorder::{ByteOrder, LittleEndian}; 19 use seccompiler::SeccompAction; 20 use serde::{Deserialize, Serialize}; 21 use virtio_queue::{Queue, QueueOwnedT, QueueT}; 22 use vm_memory::{GuestAddressSpace, GuestMemoryAtomic}; 23 use vm_migration::{Migratable, MigratableError, Pausable, Snapshot, Snapshottable, Transportable}; 24 use vm_virtio::AccessPlatform; 25 use vmm_sys_util::eventfd::EventFd; 26 27 /// This is the `VirtioDevice` implementation for our vsock device. It handles the virtio-level 28 /// device logic: feature negotiation, device configuration, and device activation. 29 /// The run-time device logic (i.e. event-driven data handling) is implemented by 30 /// `super::epoll_handler::EpollHandler`. 31 /// 32 /// We aim to conform to the VirtIO v1.1 spec: 33 /// https://docs.oasis-open.org/virtio/virtio/v1.1/virtio-v1.1.html 34 /// 35 /// The vsock device has two input parameters: a CID to identify the device, and a `VsockBackend` 36 /// to use for offloading vsock traffic. 37 /// 38 /// Upon its activation, the vsock device creates its `EpollHandler`, passes it the event-interested 39 /// file descriptors, and registers these descriptors with the VMM `EpollContext`. Going forward, 40 /// the `EpollHandler` will get notified whenever an event occurs on the just-registered FDs: 41 /// - an RX queue FD; 42 /// - a TX queue FD; 43 /// - an event queue FD; and 44 /// - a backend FD. 45 /// 46 use super::{VsockBackend, VsockPacket}; 47 use crate::seccomp_filters::Thread; 48 use crate::thread_helper::spawn_virtio_thread; 49 use crate::{ 50 ActivateResult, EpollHelper, EpollHelperError, EpollHelperHandler, Error as DeviceError, 51 GuestMemoryMmap, VirtioCommon, VirtioDevice, VirtioDeviceType, VirtioInterrupt, 52 VirtioInterruptType, EPOLL_HELPER_EVENT_LAST, VIRTIO_F_IN_ORDER, VIRTIO_F_IOMMU_PLATFORM, 53 VIRTIO_F_VERSION_1, 54 }; 55 56 const QUEUE_SIZE: u16 = 256; 57 const NUM_QUEUES: usize = 3; 58 const QUEUE_SIZES: &[u16] = &[QUEUE_SIZE; NUM_QUEUES]; 59 60 // New descriptors are pending on the rx queue. 61 pub const RX_QUEUE_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 1; 62 // New descriptors are pending on the tx queue. 63 pub const TX_QUEUE_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 2; 64 // New descriptors are pending on the event queue. 65 pub const EVT_QUEUE_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 3; 66 // Notification coming from the backend. 67 pub const BACKEND_EVENT: u16 = EPOLL_HELPER_EVENT_LAST + 4; 68 69 /// The `VsockEpollHandler` implements the runtime logic of our vsock device: 70 /// 1. Respond to TX queue events by wrapping virtio buffers into `VsockPacket`s, then sending those 71 /// packets to the `VsockBackend`; 72 /// 2. Forward backend FD event notifications to the `VsockBackend`; 73 /// 3. Fetch incoming packets from the `VsockBackend` and place them into the virtio RX queue; 74 /// 4. Whenever we have processed some virtio buffers (either TX or RX), let the driver know by 75 /// raising our assigned IRQ. 76 /// 77 /// In a nutshell, the `VsockEpollHandler` logic looks like this: 78 /// - on TX queue event: 79 /// - fetch all packets from the TX queue and send them to the backend; then 80 /// - if the backend has queued up any incoming packets, fetch them into any available RX buffers. 81 /// - on RX queue event: 82 /// - fetch any incoming packets, queued up by the backend, into newly available RX buffers. 83 /// - on backend event: 84 /// - forward the event to the backend; then 85 /// - again, attempt to fetch any incoming packets queued by the backend into virtio RX buffers. 86 /// 87 pub struct VsockEpollHandler<B: VsockBackend> { 88 pub mem: GuestMemoryAtomic<GuestMemoryMmap>, 89 pub queues: Vec<Queue>, 90 pub queue_evts: Vec<EventFd>, 91 pub kill_evt: EventFd, 92 pub pause_evt: EventFd, 93 pub interrupt_cb: Arc<dyn VirtioInterrupt>, 94 pub backend: Arc<RwLock<B>>, 95 pub access_platform: Option<Arc<dyn AccessPlatform>>, 96 } 97 98 impl<B> VsockEpollHandler<B> 99 where 100 B: VsockBackend, 101 { 102 /// Signal the guest driver that we've used some virtio buffers that it had previously made 103 /// available. 104 /// 105 fn signal_used_queue(&self, queue_index: u16) -> result::Result<(), DeviceError> { 106 debug!("vsock: raising IRQ"); 107 108 self.interrupt_cb 109 .trigger(VirtioInterruptType::Queue(queue_index)) 110 .map_err(|e| { 111 error!("Failed to signal used queue: {:?}", e); 112 DeviceError::FailedSignalingUsedQueue(e) 113 }) 114 } 115 116 /// Walk the driver-provided RX queue buffers and attempt to fill them up with any data that we 117 /// have pending. 118 /// 119 fn process_rx(&mut self) -> result::Result<(), DeviceError> { 120 debug!("vsock: epoll_handler::process_rx()"); 121 122 let mut used_descs = false; 123 124 while let Some(mut desc_chain) = self.queues[0].pop_descriptor_chain(self.mem.memory()) { 125 let used_len = match VsockPacket::from_rx_virtq_head( 126 &mut desc_chain, 127 self.access_platform.as_ref(), 128 ) { 129 Ok(mut pkt) => { 130 if self.backend.write().unwrap().recv_pkt(&mut pkt).is_ok() { 131 pkt.hdr().len() as u32 + pkt.len() 132 } else { 133 // We are using a consuming iterator over the virtio buffers, so, if we can't 134 // fill in this buffer, we'll need to undo the last iterator step. 135 self.queues[0].go_to_previous_position(); 136 break; 137 } 138 } 139 Err(e) => { 140 warn!("vsock: RX queue error: {:?}", e); 141 0 142 } 143 }; 144 145 self.queues[0] 146 .add_used(desc_chain.memory(), desc_chain.head_index(), used_len) 147 .map_err(DeviceError::QueueAddUsed)?; 148 used_descs = true; 149 } 150 151 if used_descs { 152 self.signal_used_queue(0) 153 } else { 154 Ok(()) 155 } 156 } 157 158 /// Walk the driver-provided TX queue buffers, package them up as vsock packets, and send them to 159 /// the backend for processing. 160 /// 161 fn process_tx(&mut self) -> result::Result<(), DeviceError> { 162 debug!("vsock: epoll_handler::process_tx()"); 163 164 let mut used_descs = false; 165 166 while let Some(mut desc_chain) = self.queues[1].pop_descriptor_chain(self.mem.memory()) { 167 let pkt = match VsockPacket::from_tx_virtq_head( 168 &mut desc_chain, 169 self.access_platform.as_ref(), 170 ) { 171 Ok(pkt) => pkt, 172 Err(e) => { 173 error!("vsock: error reading TX packet: {:?}", e); 174 self.queues[1] 175 .add_used(desc_chain.memory(), desc_chain.head_index(), 0) 176 .map_err(DeviceError::QueueAddUsed)?; 177 used_descs = true; 178 continue; 179 } 180 }; 181 182 if self.backend.write().unwrap().send_pkt(&pkt).is_err() { 183 self.queues[1].go_to_previous_position(); 184 break; 185 } 186 187 self.queues[1] 188 .add_used(desc_chain.memory(), desc_chain.head_index(), 0) 189 .map_err(DeviceError::QueueAddUsed)?; 190 used_descs = true; 191 } 192 193 if used_descs { 194 self.signal_used_queue(1) 195 } else { 196 Ok(()) 197 } 198 } 199 200 fn run( 201 &mut self, 202 paused: Arc<AtomicBool>, 203 paused_sync: Arc<Barrier>, 204 ) -> result::Result<(), EpollHelperError> { 205 let mut helper = EpollHelper::new(&self.kill_evt, &self.pause_evt)?; 206 helper.add_event(self.queue_evts[0].as_raw_fd(), RX_QUEUE_EVENT)?; 207 helper.add_event(self.queue_evts[1].as_raw_fd(), TX_QUEUE_EVENT)?; 208 helper.add_event(self.queue_evts[2].as_raw_fd(), EVT_QUEUE_EVENT)?; 209 helper.add_event(self.backend.read().unwrap().get_polled_fd(), BACKEND_EVENT)?; 210 helper.run(paused, paused_sync, self)?; 211 212 Ok(()) 213 } 214 } 215 216 impl<B> EpollHelperHandler for VsockEpollHandler<B> 217 where 218 B: VsockBackend, 219 { 220 fn handle_event( 221 &mut self, 222 _helper: &mut EpollHelper, 223 event: &epoll::Event, 224 ) -> result::Result<(), EpollHelperError> { 225 let evset = match epoll::Events::from_bits(event.events) { 226 Some(evset) => evset, 227 None => { 228 let evbits = event.events; 229 warn!("epoll: ignoring unknown event set: 0x{:x}", evbits); 230 return Ok(()); 231 } 232 }; 233 234 let ev_type = event.data as u16; 235 match ev_type { 236 RX_QUEUE_EVENT => { 237 debug!("vsock: RX queue event"); 238 self.queue_evts[0].read().map_err(|e| { 239 EpollHelperError::HandleEvent(anyhow!("Failed to get RX queue event: {:?}", e)) 240 })?; 241 if self.backend.read().unwrap().has_pending_rx() { 242 self.process_rx().map_err(|e| { 243 EpollHelperError::HandleEvent(anyhow!( 244 "Failed to process RX queue: {:?}", 245 e 246 )) 247 })?; 248 } 249 } 250 TX_QUEUE_EVENT => { 251 debug!("vsock: TX queue event"); 252 self.queue_evts[1].read().map_err(|e| { 253 EpollHelperError::HandleEvent(anyhow!("Failed to get TX queue event: {:?}", e)) 254 })?; 255 256 self.process_tx().map_err(|e| { 257 EpollHelperError::HandleEvent(anyhow!("Failed to process TX queue: {:?}", e)) 258 })?; 259 260 // The backend may have queued up responses to the packets we sent during TX queue 261 // processing. If that happened, we need to fetch those responses and place them 262 // into RX buffers. 263 if self.backend.read().unwrap().has_pending_rx() { 264 self.process_rx().map_err(|e| { 265 EpollHelperError::HandleEvent(anyhow!( 266 "Failed to process RX queue: {:?}", 267 e 268 )) 269 })?; 270 } 271 } 272 EVT_QUEUE_EVENT => { 273 debug!("vsock: EVT queue event"); 274 self.queue_evts[2].read().map_err(|e| { 275 EpollHelperError::HandleEvent(anyhow!("Failed to get EVT queue event: {:?}", e)) 276 })?; 277 } 278 BACKEND_EVENT => { 279 debug!("vsock: backend event"); 280 self.backend.write().unwrap().notify(evset); 281 // After the backend has been kicked, it might've freed up some resources, so we 282 // can attempt to send it more data to process. 283 // In particular, if `self.backend.send_pkt()` halted the TX queue processing (by 284 // returning an error) at some point in the past, now is the time to try walking the 285 // TX queue again. 286 self.process_tx().map_err(|e| { 287 EpollHelperError::HandleEvent(anyhow!("Failed to process TX queue: {:?}", e)) 288 })?; 289 if self.backend.read().unwrap().has_pending_rx() { 290 self.process_rx().map_err(|e| { 291 EpollHelperError::HandleEvent(anyhow!( 292 "Failed to process RX queue: {:?}", 293 e 294 )) 295 })?; 296 } 297 } 298 _ => { 299 return Err(EpollHelperError::HandleEvent(anyhow!( 300 "Unknown event for virtio-vsock" 301 ))); 302 } 303 } 304 305 Ok(()) 306 } 307 } 308 309 /// Virtio device exposing virtual socket to the guest. 310 pub struct Vsock<B: VsockBackend> { 311 common: VirtioCommon, 312 id: String, 313 cid: u64, 314 backend: Arc<RwLock<B>>, 315 path: PathBuf, 316 seccomp_action: SeccompAction, 317 exit_evt: EventFd, 318 } 319 320 #[derive(Serialize, Deserialize)] 321 pub struct VsockState { 322 pub avail_features: u64, 323 pub acked_features: u64, 324 } 325 326 impl<B> Vsock<B> 327 where 328 B: VsockBackend + Sync, 329 { 330 /// Create a new virtio-vsock device with the given VM CID and vsock 331 /// backend. 332 #[allow(clippy::too_many_arguments)] 333 pub fn new( 334 id: String, 335 cid: u32, 336 path: PathBuf, 337 backend: B, 338 iommu: bool, 339 seccomp_action: SeccompAction, 340 exit_evt: EventFd, 341 state: Option<VsockState>, 342 ) -> io::Result<Vsock<B>> { 343 let (avail_features, acked_features, paused) = if let Some(state) = state { 344 info!("Restoring virtio-vsock {}", id); 345 (state.avail_features, state.acked_features, true) 346 } else { 347 let mut avail_features = (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_F_IN_ORDER); 348 349 if iommu { 350 avail_features |= 1u64 << VIRTIO_F_IOMMU_PLATFORM; 351 } 352 (avail_features, 0, false) 353 }; 354 355 Ok(Vsock { 356 common: VirtioCommon { 357 device_type: VirtioDeviceType::Vsock as u32, 358 avail_features, 359 acked_features, 360 paused_sync: Some(Arc::new(Barrier::new(2))), 361 queue_sizes: QUEUE_SIZES.to_vec(), 362 min_queues: NUM_QUEUES as u16, 363 paused: Arc::new(AtomicBool::new(paused)), 364 ..Default::default() 365 }, 366 id, 367 cid: cid.into(), 368 backend: Arc::new(RwLock::new(backend)), 369 path, 370 seccomp_action, 371 exit_evt, 372 }) 373 } 374 375 fn state(&self) -> VsockState { 376 VsockState { 377 avail_features: self.common.avail_features, 378 acked_features: self.common.acked_features, 379 } 380 } 381 } 382 383 impl<B> Drop for Vsock<B> 384 where 385 B: VsockBackend, 386 { 387 fn drop(&mut self) { 388 if let Some(kill_evt) = self.common.kill_evt.take() { 389 // Ignore the result because there is nothing we can do about it. 390 let _ = kill_evt.write(1); 391 } 392 self.common.wait_for_epoll_threads(); 393 } 394 } 395 396 impl<B> VirtioDevice for Vsock<B> 397 where 398 B: VsockBackend + Sync + 'static, 399 { 400 fn device_type(&self) -> u32 { 401 self.common.device_type 402 } 403 404 fn queue_max_sizes(&self) -> &[u16] { 405 &self.common.queue_sizes 406 } 407 408 fn features(&self) -> u64 { 409 self.common.avail_features 410 } 411 412 fn ack_features(&mut self, value: u64) { 413 self.common.ack_features(value) 414 } 415 416 fn read_config(&self, offset: u64, data: &mut [u8]) { 417 match offset { 418 0 if data.len() == 8 => LittleEndian::write_u64(data, self.cid), 419 0 if data.len() == 4 => LittleEndian::write_u32(data, (self.cid & 0xffff_ffff) as u32), 420 4 if data.len() == 4 => { 421 LittleEndian::write_u32(data, ((self.cid >> 32) & 0xffff_ffff) as u32) 422 } 423 _ => warn!( 424 "vsock: virtio-vsock received invalid read request of {} bytes at offset {}", 425 data.len(), 426 offset 427 ), 428 } 429 } 430 431 fn activate( 432 &mut self, 433 mem: GuestMemoryAtomic<GuestMemoryMmap>, 434 interrupt_cb: Arc<dyn VirtioInterrupt>, 435 queues: Vec<(usize, Queue, EventFd)>, 436 ) -> ActivateResult { 437 self.common.activate(&queues, &interrupt_cb)?; 438 let (kill_evt, pause_evt) = self.common.dup_eventfds(); 439 440 let mut virtqueues = Vec::new(); 441 let mut queue_evts = Vec::new(); 442 for (_, queue, queue_evt) in queues { 443 virtqueues.push(queue); 444 queue_evts.push(queue_evt); 445 } 446 447 let mut handler = VsockEpollHandler { 448 mem, 449 queues: virtqueues, 450 queue_evts, 451 kill_evt, 452 pause_evt, 453 interrupt_cb, 454 backend: self.backend.clone(), 455 access_platform: self.common.access_platform.clone(), 456 }; 457 458 let paused = self.common.paused.clone(); 459 let paused_sync = self.common.paused_sync.clone(); 460 let mut epoll_threads = Vec::new(); 461 462 spawn_virtio_thread( 463 &self.id, 464 &self.seccomp_action, 465 Thread::VirtioVsock, 466 &mut epoll_threads, 467 &self.exit_evt, 468 move || handler.run(paused, paused_sync.unwrap()), 469 )?; 470 471 self.common.epoll_threads = Some(epoll_threads); 472 473 event!("virtio-device", "activated", "id", &self.id); 474 Ok(()) 475 } 476 477 fn reset(&mut self) -> Option<Arc<dyn VirtioInterrupt>> { 478 let result = self.common.reset(); 479 event!("virtio-device", "reset", "id", &self.id); 480 result 481 } 482 483 fn shutdown(&mut self) { 484 std::fs::remove_file(&self.path).ok(); 485 } 486 487 fn set_access_platform(&mut self, access_platform: Arc<dyn AccessPlatform>) { 488 self.common.set_access_platform(access_platform) 489 } 490 } 491 492 impl<B> Pausable for Vsock<B> 493 where 494 B: VsockBackend + Sync + 'static, 495 { 496 fn pause(&mut self) -> result::Result<(), MigratableError> { 497 self.common.pause() 498 } 499 500 fn resume(&mut self) -> result::Result<(), MigratableError> { 501 self.common.resume() 502 } 503 } 504 505 impl<B> Snapshottable for Vsock<B> 506 where 507 B: VsockBackend + Sync + 'static, 508 { 509 fn id(&self) -> String { 510 self.id.clone() 511 } 512 513 fn snapshot(&mut self) -> std::result::Result<Snapshot, MigratableError> { 514 Snapshot::new_from_state(&self.state()) 515 } 516 } 517 impl<B> Transportable for Vsock<B> where B: VsockBackend + Sync + 'static {} 518 impl<B> Migratable for Vsock<B> where B: VsockBackend + Sync + 'static {} 519 520 #[cfg(test)] 521 mod tests { 522 use libc::EFD_NONBLOCK; 523 524 use super::super::tests::{NoopVirtioInterrupt, TestContext}; 525 use super::super::*; 526 use super::*; 527 use crate::ActivateError; 528 529 #[test] 530 fn test_virtio_device() { 531 let mut ctx = TestContext::new(); 532 let avail_features = (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_F_IN_ORDER); 533 let device_features = avail_features; 534 let driver_features: u64 = avail_features | 1 | (1 << 32); 535 let device_pages = [ 536 (device_features & 0xffff_ffff) as u32, 537 (device_features >> 32) as u32, 538 ]; 539 let driver_pages = [ 540 (driver_features & 0xffff_ffff) as u32, 541 (driver_features >> 32) as u32, 542 ]; 543 assert_eq!(ctx.device.device_type(), VirtioDeviceType::Vsock as u32); 544 assert_eq!(ctx.device.queue_max_sizes(), QUEUE_SIZES); 545 assert_eq!(ctx.device.features() as u32, device_pages[0]); 546 assert_eq!((ctx.device.features() >> 32) as u32, device_pages[1]); 547 548 // Ack device features, page 0. 549 ctx.device.ack_features(u64::from(driver_pages[0])); 550 // Ack device features, page 1. 551 ctx.device.ack_features(u64::from(driver_pages[1]) << 32); 552 // Check that no side effect are present, and that the acked features are exactly the same 553 // as the device features. 554 assert_eq!( 555 ctx.device.common.acked_features, 556 device_features & driver_features 557 ); 558 559 // Test reading 32-bit chunks. 560 let mut data = [0u8; 8]; 561 ctx.device.read_config(0, &mut data[..4]); 562 assert_eq!( 563 u64::from(LittleEndian::read_u32(&data)), 564 ctx.cid & 0xffff_ffff 565 ); 566 ctx.device.read_config(4, &mut data[4..]); 567 assert_eq!( 568 u64::from(LittleEndian::read_u32(&data[4..])), 569 (ctx.cid >> 32) & 0xffff_ffff 570 ); 571 572 // Test reading 64-bit. 573 let mut data = [0u8; 8]; 574 ctx.device.read_config(0, &mut data); 575 assert_eq!(LittleEndian::read_u64(&data), ctx.cid); 576 577 // Check that out-of-bounds reading doesn't mutate the destination buffer. 578 let mut data = [0u8, 1, 2, 3, 4, 5, 6, 7]; 579 ctx.device.read_config(2, &mut data); 580 assert_eq!(data, [0u8, 1, 2, 3, 4, 5, 6, 7]); 581 582 // Just covering lines here, since the vsock device has no writable config. 583 // A warning is, however, logged, if the guest driver attempts to write any config data. 584 ctx.device.write_config(0, &data[..4]); 585 586 let memory = GuestMemoryAtomic::new(ctx.mem.clone()); 587 588 // Test a bad activation. 589 let bad_activate = 590 ctx.device 591 .activate(memory.clone(), Arc::new(NoopVirtioInterrupt {}), Vec::new()); 592 match bad_activate { 593 Err(ActivateError::BadActivate) => (), 594 other => panic!("{other:?}"), 595 } 596 597 // Test a correct activation. 598 ctx.device 599 .activate( 600 memory, 601 Arc::new(NoopVirtioInterrupt {}), 602 vec![ 603 ( 604 0, 605 Queue::new(256).unwrap(), 606 EventFd::new(EFD_NONBLOCK).unwrap(), 607 ), 608 ( 609 1, 610 Queue::new(256).unwrap(), 611 EventFd::new(EFD_NONBLOCK).unwrap(), 612 ), 613 ( 614 2, 615 Queue::new(256).unwrap(), 616 EventFd::new(EFD_NONBLOCK).unwrap(), 617 ), 618 ], 619 ) 620 .unwrap(); 621 } 622 623 #[test] 624 fn test_irq() { 625 // Test case: successful IRQ signaling. 626 { 627 let test_ctx = TestContext::new(); 628 let ctx = test_ctx.create_epoll_handler_context(); 629 630 let _queue: Queue = Queue::new(256).unwrap(); 631 ctx.handler.signal_used_queue(0).unwrap(); 632 } 633 } 634 635 #[test] 636 fn test_txq_event() { 637 // Test case: 638 // - the driver has something to send (there's data in the TX queue); and 639 // - the backend has no pending RX data. 640 { 641 let test_ctx = TestContext::new(); 642 let mut ctx = test_ctx.create_epoll_handler_context(); 643 644 ctx.handler.backend.write().unwrap().set_pending_rx(false); 645 ctx.signal_txq_event(); 646 647 // The available TX descriptor should have been used. 648 assert_eq!(ctx.guest_txvq.used.idx.get(), 1); 649 // The available RX descriptor should be untouched. 650 assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); 651 } 652 653 // Test case: 654 // - the driver has something to send (there's data in the TX queue); and 655 // - the backend also has some pending RX data. 656 { 657 let test_ctx = TestContext::new(); 658 let mut ctx = test_ctx.create_epoll_handler_context(); 659 660 ctx.handler.backend.write().unwrap().set_pending_rx(true); 661 ctx.signal_txq_event(); 662 663 // Both available RX and TX descriptors should have been used. 664 assert_eq!(ctx.guest_txvq.used.idx.get(), 1); 665 assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); 666 } 667 668 // Test case: 669 // - the driver has something to send (there's data in the TX queue); and 670 // - the backend errors out and cannot process the TX queue. 671 { 672 let test_ctx = TestContext::new(); 673 let mut ctx = test_ctx.create_epoll_handler_context(); 674 675 ctx.handler.backend.write().unwrap().set_pending_rx(false); 676 ctx.handler 677 .backend 678 .write() 679 .unwrap() 680 .set_tx_err(Some(VsockError::NoData)); 681 ctx.signal_txq_event(); 682 683 // Both RX and TX queues should be untouched. 684 assert_eq!(ctx.guest_txvq.used.idx.get(), 0); 685 assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); 686 } 687 688 // Test case: 689 // - the driver supplied a malformed TX buffer. 690 { 691 let test_ctx = TestContext::new(); 692 let mut ctx = test_ctx.create_epoll_handler_context(); 693 694 // Invalidate the packet header descriptor, by setting its length to 0. 695 ctx.guest_txvq.dtable[0].len.set(0); 696 ctx.signal_txq_event(); 697 698 // The available descriptor should have been consumed, but no packet should have 699 // reached the backend. 700 assert_eq!(ctx.guest_txvq.used.idx.get(), 1); 701 assert_eq!(ctx.handler.backend.read().unwrap().tx_ok_cnt, 0); 702 } 703 704 // Test case: spurious TXQ_EVENT. 705 { 706 let test_ctx = TestContext::new(); 707 let mut ctx = test_ctx.create_epoll_handler_context(); 708 709 let events = epoll::Events::EPOLLIN; 710 let event = epoll::Event::new(events, TX_QUEUE_EVENT as u64); 711 let mut epoll_helper = 712 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 713 714 ctx.handler 715 .handle_event(&mut epoll_helper, &event) 716 .expect_err("handle_event() should have failed"); 717 } 718 } 719 720 #[test] 721 fn test_rxq_event() { 722 // Test case: 723 // - there is pending RX data in the backend; and 724 // - the driver makes RX buffers available; and 725 // - the backend successfully places its RX data into the queue. 726 { 727 let test_ctx = TestContext::new(); 728 let mut ctx = test_ctx.create_epoll_handler_context(); 729 730 ctx.handler.backend.write().unwrap().set_pending_rx(true); 731 ctx.handler 732 .backend 733 .write() 734 .unwrap() 735 .set_rx_err(Some(VsockError::NoData)); 736 ctx.signal_rxq_event(); 737 738 // The available RX buffer should've been left untouched. 739 assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); 740 } 741 742 // Test case: 743 // - there is pending RX data in the backend; and 744 // - the driver makes RX buffers available; and 745 // - the backend errors out, when attempting to receive data. 746 { 747 let test_ctx = TestContext::new(); 748 let mut ctx = test_ctx.create_epoll_handler_context(); 749 750 ctx.handler.backend.write().unwrap().set_pending_rx(true); 751 ctx.signal_rxq_event(); 752 753 // The available RX buffer should have been used. 754 assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); 755 } 756 757 // Test case: the driver provided a malformed RX descriptor chain. 758 { 759 let test_ctx = TestContext::new(); 760 let mut ctx = test_ctx.create_epoll_handler_context(); 761 762 // Invalidate the packet header descriptor, by setting its length to 0. 763 ctx.guest_rxvq.dtable[0].len.set(0); 764 765 // The chain should've been processed, without employing the backend. 766 ctx.handler.process_rx().unwrap(); 767 assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); 768 assert_eq!(ctx.handler.backend.read().unwrap().rx_ok_cnt, 0); 769 } 770 771 // Test case: spurious RXQ_EVENT. 772 { 773 let test_ctx = TestContext::new(); 774 let mut ctx = test_ctx.create_epoll_handler_context(); 775 ctx.handler.backend.write().unwrap().set_pending_rx(false); 776 777 let events = epoll::Events::EPOLLIN; 778 let event = epoll::Event::new(events, RX_QUEUE_EVENT as u64); 779 let mut epoll_helper = 780 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 781 782 assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); 783 ctx.handler 784 .handle_event(&mut epoll_helper, &event) 785 .expect_err("handle_event() should have failed"); 786 } 787 } 788 789 #[test] 790 fn test_evq_event() { 791 // Test case: spurious EVQ_EVENT. 792 { 793 let test_ctx = TestContext::new(); 794 let mut ctx = test_ctx.create_epoll_handler_context(); 795 ctx.handler.backend.write().unwrap().set_pending_rx(false); 796 797 let events = epoll::Events::EPOLLIN; 798 let event = epoll::Event::new(events, EVT_QUEUE_EVENT as u64); 799 let mut epoll_helper = 800 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 801 802 assert_eq!(ctx.guest_evvq.used.idx.get(), 0); 803 804 ctx.handler 805 .handle_event(&mut epoll_helper, &event) 806 .expect_err("handle_event() should have failed"); 807 } 808 } 809 810 #[test] 811 fn test_backend_event() { 812 // Test case: 813 // - a backend event is received; and 814 // - the backend has pending RX data. 815 { 816 let test_ctx = TestContext::new(); 817 let mut ctx = test_ctx.create_epoll_handler_context(); 818 819 ctx.handler.backend.write().unwrap().set_pending_rx(true); 820 821 let events = epoll::Events::EPOLLIN; 822 let event = epoll::Event::new(events, BACKEND_EVENT as u64); 823 let mut epoll_helper = 824 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 825 ctx.handler.handle_event(&mut epoll_helper, &event).unwrap(); 826 827 // The backend should've received this event. 828 assert_eq!( 829 ctx.handler.backend.read().unwrap().evset, 830 Some(epoll::Events::EPOLLIN) 831 ); 832 // TX queue processing should've been triggered. 833 assert_eq!(ctx.guest_txvq.used.idx.get(), 1); 834 // RX queue processing should've been triggered. 835 assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); 836 } 837 838 // Test case: 839 // - a backend event is received; and 840 // - the backend doesn't have any pending RX data. 841 { 842 let test_ctx = TestContext::new(); 843 let mut ctx = test_ctx.create_epoll_handler_context(); 844 845 ctx.handler.backend.write().unwrap().set_pending_rx(false); 846 847 let events = epoll::Events::EPOLLIN; 848 let event = epoll::Event::new(events, BACKEND_EVENT as u64); 849 let mut epoll_helper = 850 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 851 ctx.handler.handle_event(&mut epoll_helper, &event).unwrap(); 852 853 // The backend should've received this event. 854 assert_eq!( 855 ctx.handler.backend.read().unwrap().evset, 856 Some(epoll::Events::EPOLLIN) 857 ); 858 // TX queue processing should've been triggered. 859 assert_eq!(ctx.guest_txvq.used.idx.get(), 1); 860 // The RX queue should've been left untouched. 861 assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); 862 } 863 } 864 865 #[test] 866 fn test_unknown_event() { 867 let test_ctx = TestContext::new(); 868 let mut ctx = test_ctx.create_epoll_handler_context(); 869 870 let events = epoll::Events::EPOLLIN; 871 let event = epoll::Event::new(events, 0xff); 872 let mut epoll_helper = 873 EpollHelper::new(&ctx.handler.kill_evt, &ctx.handler.pause_evt).unwrap(); 874 875 ctx.handler 876 .handle_event(&mut epoll_helper, &event) 877 .expect_err("handle_event() should have failed"); 878 } 879 } 880