1 // Copyright 2019 Red Hat, Inc. All Rights Reserved. 2 // 3 // Portions Copyright 2019 Intel Corporation. All Rights Reserved. 4 // 5 // Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 6 // 7 // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. 8 // 9 // SPDX-License-Identifier: (Apache-2.0 AND BSD-3-Clause) 10 11 use block::{ 12 build_serial, 13 qcow::{self, ImageType, QcowFile}, 14 Request, VirtioBlockConfig, 15 }; 16 use libc::EFD_NONBLOCK; 17 use log::*; 18 use option_parser::{OptionParser, OptionParserError, Toggle}; 19 use std::fs::File; 20 use std::fs::OpenOptions; 21 use std::io::Read; 22 use std::io::{Seek, SeekFrom, Write}; 23 use std::ops::Deref; 24 use std::ops::DerefMut; 25 use std::os::unix::fs::OpenOptionsExt; 26 use std::path::PathBuf; 27 use std::process; 28 use std::result; 29 use std::sync::atomic::{AtomicBool, Ordering}; 30 use std::sync::{Arc, Mutex, RwLock, RwLockWriteGuard}; 31 use std::time::Instant; 32 use std::vec::Vec; 33 use std::{convert, error, fmt, io}; 34 use vhost::vhost_user::message::*; 35 use vhost::vhost_user::Listener; 36 use vhost_user_backend::{VhostUserBackendMut, VhostUserDaemon, VringRwLock, VringState, VringT}; 37 use virtio_bindings::virtio_blk::*; 38 use virtio_bindings::virtio_config::VIRTIO_F_VERSION_1; 39 use virtio_bindings::virtio_ring::VIRTIO_RING_F_EVENT_IDX; 40 use virtio_queue::QueueT; 41 use vm_memory::GuestAddressSpace; 42 use vm_memory::{bitmap::AtomicBitmap, ByteValued, Bytes, GuestMemoryAtomic}; 43 use vmm_sys_util::{epoll::EventSet, eventfd::EventFd}; 44 45 type GuestMemoryMmap = vm_memory::GuestMemoryMmap<AtomicBitmap>; 46 47 const SECTOR_SHIFT: u8 = 9; 48 const SECTOR_SIZE: u64 = 0x01 << SECTOR_SHIFT; 49 const BLK_SIZE: u32 = 512; 50 // Current (2020) enterprise SSDs have a latency lower than 30us. 51 // Polling for 50us should be enough to cover for the device latency 52 // and the overhead of the emulation layer. 53 const POLL_QUEUE_US: u128 = 50; 54 55 trait DiskFile: Read + Seek + Write + Send {} 56 impl<D: Read + Seek + Write + Send> DiskFile for D {} 57 58 type Result<T> = std::result::Result<T, Error>; 59 type VhostUserBackendResult<T> = std::result::Result<T, std::io::Error>; 60 61 #[derive(Debug)] 62 enum Error { 63 /// Failed to create kill eventfd 64 CreateKillEventFd(io::Error), 65 /// Failed to parse configuration string 66 FailedConfigParse(OptionParserError), 67 /// Failed to handle event other than input event. 68 HandleEventNotEpollIn, 69 /// Failed to handle unknown event. 70 HandleEventUnknownEvent, 71 /// No path provided 72 PathParameterMissing, 73 /// No socket provided 74 SocketParameterMissing, 75 } 76 77 impl fmt::Display for Error { 78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 79 write!(f, "vhost_user_block_error: {self:?}") 80 } 81 } 82 83 impl error::Error for Error {} 84 85 impl convert::From<Error> for io::Error { 86 fn from(e: Error) -> Self { 87 io::Error::new(io::ErrorKind::Other, e) 88 } 89 } 90 91 struct VhostUserBlkThread { 92 disk_image: Arc<Mutex<dyn DiskFile>>, 93 serial: Vec<u8>, 94 disk_nsectors: u64, 95 event_idx: bool, 96 kill_evt: EventFd, 97 writeback: Arc<AtomicBool>, 98 mem: GuestMemoryAtomic<GuestMemoryMmap>, 99 } 100 101 impl VhostUserBlkThread { 102 fn new( 103 disk_image: Arc<Mutex<dyn DiskFile>>, 104 serial: Vec<u8>, 105 disk_nsectors: u64, 106 writeback: Arc<AtomicBool>, 107 mem: GuestMemoryAtomic<GuestMemoryMmap>, 108 ) -> Result<Self> { 109 Ok(VhostUserBlkThread { 110 disk_image, 111 serial, 112 disk_nsectors, 113 event_idx: false, 114 kill_evt: EventFd::new(EFD_NONBLOCK).map_err(Error::CreateKillEventFd)?, 115 writeback, 116 mem, 117 }) 118 } 119 120 fn process_queue( 121 &mut self, 122 vring: &mut RwLockWriteGuard<VringState<GuestMemoryAtomic<GuestMemoryMmap>>>, 123 ) -> bool { 124 let mut used_descs = false; 125 126 while let Some(mut desc_chain) = vring 127 .get_queue_mut() 128 .pop_descriptor_chain(self.mem.memory()) 129 { 130 debug!("got an element in the queue"); 131 let len; 132 match Request::parse(&mut desc_chain, None) { 133 Ok(mut request) => { 134 debug!("element is a valid request"); 135 request.set_writeback(self.writeback.load(Ordering::Acquire)); 136 let status = match request.execute( 137 &mut self.disk_image.lock().unwrap().deref_mut(), 138 self.disk_nsectors, 139 desc_chain.memory(), 140 &self.serial, 141 ) { 142 Ok(l) => { 143 len = l; 144 VIRTIO_BLK_S_OK 145 } 146 Err(e) => { 147 len = 1; 148 e.status() 149 } 150 }; 151 desc_chain 152 .memory() 153 .write_obj(status, request.status_addr) 154 .unwrap(); 155 } 156 Err(err) => { 157 error!("failed to parse available descriptor chain: {:?}", err); 158 len = 0; 159 } 160 } 161 162 vring 163 .get_queue_mut() 164 .add_used(desc_chain.memory(), desc_chain.head_index(), len) 165 .unwrap(); 166 used_descs = true; 167 } 168 169 let mut needs_signalling = false; 170 if self.event_idx { 171 if vring 172 .get_queue_mut() 173 .needs_notification(self.mem.memory().deref()) 174 .unwrap() 175 { 176 debug!("signalling queue"); 177 needs_signalling = true; 178 } else { 179 debug!("omitting signal (event_idx)"); 180 } 181 } else { 182 debug!("signalling queue"); 183 needs_signalling = true; 184 } 185 186 if needs_signalling { 187 vring.signal_used_queue().unwrap(); 188 } 189 190 used_descs 191 } 192 } 193 194 struct VhostUserBlkBackend { 195 threads: Vec<Mutex<VhostUserBlkThread>>, 196 config: VirtioBlockConfig, 197 rdonly: bool, 198 poll_queue: bool, 199 queues_per_thread: Vec<u64>, 200 queue_size: usize, 201 acked_features: u64, 202 writeback: Arc<AtomicBool>, 203 mem: GuestMemoryAtomic<GuestMemoryMmap>, 204 } 205 206 impl VhostUserBlkBackend { 207 fn new( 208 image_path: String, 209 num_queues: usize, 210 rdonly: bool, 211 direct: bool, 212 poll_queue: bool, 213 queue_size: usize, 214 mem: GuestMemoryAtomic<GuestMemoryMmap>, 215 ) -> Result<Self> { 216 let mut options = OpenOptions::new(); 217 options.read(true); 218 options.write(!rdonly); 219 if direct { 220 options.custom_flags(libc::O_DIRECT); 221 } 222 let image: File = options.open(&image_path).unwrap(); 223 let mut raw_img: qcow::RawFile = qcow::RawFile::new(image, direct); 224 225 let serial = build_serial(&PathBuf::from(&image_path)); 226 let image_type = qcow::detect_image_type(&mut raw_img).unwrap(); 227 let image = match image_type { 228 ImageType::Raw => Arc::new(Mutex::new(raw_img)) as Arc<Mutex<dyn DiskFile>>, 229 ImageType::Qcow2 => { 230 Arc::new(Mutex::new(QcowFile::from(raw_img).unwrap())) as Arc<Mutex<dyn DiskFile>> 231 } 232 }; 233 234 let nsectors = (image.lock().unwrap().seek(SeekFrom::End(0)).unwrap()) / SECTOR_SIZE; 235 let config = VirtioBlockConfig { 236 capacity: nsectors, 237 blk_size: BLK_SIZE, 238 size_max: 65535, 239 seg_max: 128 - 2, 240 min_io_size: 1, 241 opt_io_size: 1, 242 num_queues: num_queues as u16, 243 writeback: 1, 244 ..Default::default() 245 }; 246 247 let mut queues_per_thread = Vec::new(); 248 let mut threads = Vec::new(); 249 let writeback = Arc::new(AtomicBool::new(true)); 250 for i in 0..num_queues { 251 let thread = Mutex::new(VhostUserBlkThread::new( 252 image.clone(), 253 serial.clone(), 254 nsectors, 255 writeback.clone(), 256 mem.clone(), 257 )?); 258 threads.push(thread); 259 queues_per_thread.push(0b1 << i); 260 } 261 262 Ok(VhostUserBlkBackend { 263 threads, 264 config, 265 rdonly, 266 poll_queue, 267 queues_per_thread, 268 queue_size, 269 acked_features: 0, 270 writeback, 271 mem, 272 }) 273 } 274 275 fn update_writeback(&mut self) { 276 // Use writeback from config if VIRTIO_BLK_F_CONFIG_WCE 277 let writeback = 278 if self.acked_features & 1 << VIRTIO_BLK_F_CONFIG_WCE == 1 << VIRTIO_BLK_F_CONFIG_WCE { 279 self.config.writeback == 1 280 } else { 281 // Else check if VIRTIO_BLK_F_FLUSH negotiated 282 self.acked_features & 1 << VIRTIO_BLK_F_FLUSH == 1 << VIRTIO_BLK_F_FLUSH 283 }; 284 285 info!( 286 "Changing cache mode to {}", 287 if writeback { 288 "writeback" 289 } else { 290 "writethrough" 291 } 292 ); 293 self.writeback.store(writeback, Ordering::Release); 294 } 295 } 296 297 impl VhostUserBackendMut<VringRwLock<GuestMemoryAtomic<GuestMemoryMmap>>, AtomicBitmap> 298 for VhostUserBlkBackend 299 { 300 fn num_queues(&self) -> usize { 301 self.config.num_queues as usize 302 } 303 304 fn max_queue_size(&self) -> usize { 305 self.queue_size 306 } 307 308 fn features(&self) -> u64 { 309 let mut avail_features = 1 << VIRTIO_BLK_F_SEG_MAX 310 | 1 << VIRTIO_BLK_F_BLK_SIZE 311 | 1 << VIRTIO_BLK_F_FLUSH 312 | 1 << VIRTIO_BLK_F_TOPOLOGY 313 | 1 << VIRTIO_BLK_F_MQ 314 | 1 << VIRTIO_BLK_F_CONFIG_WCE 315 | 1 << VIRTIO_RING_F_EVENT_IDX 316 | 1 << VIRTIO_F_VERSION_1 317 | VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits(); 318 319 if self.rdonly { 320 avail_features |= 1 << VIRTIO_BLK_F_RO; 321 } 322 avail_features 323 } 324 325 fn acked_features(&mut self, features: u64) { 326 self.acked_features = features; 327 self.update_writeback(); 328 } 329 330 fn protocol_features(&self) -> VhostUserProtocolFeatures { 331 VhostUserProtocolFeatures::CONFIG 332 | VhostUserProtocolFeatures::MQ 333 | VhostUserProtocolFeatures::CONFIGURE_MEM_SLOTS 334 } 335 336 fn set_event_idx(&mut self, enabled: bool) { 337 for thread in self.threads.iter() { 338 thread.lock().unwrap().event_idx = enabled; 339 } 340 } 341 342 fn handle_event( 343 &mut self, 344 device_event: u16, 345 evset: EventSet, 346 vrings: &[VringRwLock<GuestMemoryAtomic<GuestMemoryMmap>>], 347 thread_id: usize, 348 ) -> VhostUserBackendResult<bool> { 349 if evset != EventSet::IN { 350 return Err(Error::HandleEventNotEpollIn.into()); 351 } 352 353 debug!("event received: {:?}", device_event); 354 355 let mut thread = self.threads[thread_id].lock().unwrap(); 356 match device_event { 357 0 => { 358 let mut vring = vrings[0].get_mut(); 359 360 if self.poll_queue { 361 // Actively poll the queue until POLL_QUEUE_US has passed 362 // without seeing a new request. 363 let mut now = Instant::now(); 364 loop { 365 if thread.process_queue(&mut vring) { 366 now = Instant::now(); 367 } else if now.elapsed().as_micros() > POLL_QUEUE_US { 368 break; 369 } 370 } 371 } 372 373 if thread.event_idx { 374 // vm-virtio's Queue implementation only checks avail_index 375 // once, so to properly support EVENT_IDX we need to keep 376 // calling process_queue() until it stops finding new 377 // requests on the queue. 378 loop { 379 vring 380 .get_queue_mut() 381 .enable_notification(self.mem.memory().deref()) 382 .unwrap(); 383 if !thread.process_queue(&mut vring) { 384 break; 385 } 386 } 387 } else { 388 // Without EVENT_IDX, a single call is enough. 389 thread.process_queue(&mut vring); 390 } 391 392 Ok(false) 393 } 394 _ => Err(Error::HandleEventUnknownEvent.into()), 395 } 396 } 397 398 fn get_config(&self, _offset: u32, _size: u32) -> Vec<u8> { 399 self.config.as_slice().to_vec() 400 } 401 402 fn set_config(&mut self, offset: u32, data: &[u8]) -> result::Result<(), io::Error> { 403 let config_slice = self.config.as_mut_slice(); 404 let data_len = data.len() as u32; 405 let config_len = config_slice.len() as u32; 406 if offset + data_len > config_len { 407 error!("Failed to write config space"); 408 return Err(io::Error::from_raw_os_error(libc::EINVAL)); 409 } 410 let (_, right) = config_slice.split_at_mut(offset as usize); 411 right.copy_from_slice(data); 412 self.update_writeback(); 413 Ok(()) 414 } 415 416 fn exit_event(&self, thread_index: usize) -> Option<EventFd> { 417 Some( 418 self.threads[thread_index] 419 .lock() 420 .unwrap() 421 .kill_evt 422 .try_clone() 423 .unwrap(), 424 ) 425 } 426 427 fn queues_per_thread(&self) -> Vec<u64> { 428 self.queues_per_thread.clone() 429 } 430 431 fn update_memory( 432 &mut self, 433 _mem: GuestMemoryAtomic<GuestMemoryMmap>, 434 ) -> VhostUserBackendResult<()> { 435 Ok(()) 436 } 437 } 438 439 struct VhostUserBlkBackendConfig { 440 path: String, 441 socket: String, 442 num_queues: usize, 443 queue_size: usize, 444 readonly: bool, 445 direct: bool, 446 poll_queue: bool, 447 } 448 449 impl VhostUserBlkBackendConfig { 450 fn parse(backend: &str) -> Result<Self> { 451 let mut parser = OptionParser::new(); 452 parser 453 .add("path") 454 .add("readonly") 455 .add("direct") 456 .add("num_queues") 457 .add("queue_size") 458 .add("socket") 459 .add("poll_queue"); 460 parser.parse(backend).map_err(Error::FailedConfigParse)?; 461 462 let path = parser.get("path").ok_or(Error::PathParameterMissing)?; 463 let readonly = parser 464 .convert::<Toggle>("readonly") 465 .map_err(Error::FailedConfigParse)? 466 .unwrap_or(Toggle(false)) 467 .0; 468 let direct = parser 469 .convert::<Toggle>("direct") 470 .map_err(Error::FailedConfigParse)? 471 .unwrap_or(Toggle(false)) 472 .0; 473 let num_queues = parser 474 .convert("num_queues") 475 .map_err(Error::FailedConfigParse)? 476 .unwrap_or(1); 477 let socket = parser.get("socket").ok_or(Error::SocketParameterMissing)?; 478 let poll_queue = parser 479 .convert::<Toggle>("poll_queue") 480 .map_err(Error::FailedConfigParse)? 481 .unwrap_or(Toggle(true)) 482 .0; 483 let queue_size = parser 484 .convert("queue_size") 485 .map_err(Error::FailedConfigParse)? 486 .unwrap_or(1024); 487 488 Ok(VhostUserBlkBackendConfig { 489 path, 490 socket, 491 num_queues, 492 queue_size, 493 readonly, 494 direct, 495 poll_queue, 496 }) 497 } 498 } 499 500 pub fn start_block_backend(backend_command: &str) { 501 let backend_config = match VhostUserBlkBackendConfig::parse(backend_command) { 502 Ok(config) => config, 503 Err(e) => { 504 println!("Failed parsing parameters {e:?}"); 505 process::exit(1); 506 } 507 }; 508 509 let mem = GuestMemoryAtomic::new(GuestMemoryMmap::new()); 510 511 let blk_backend = Arc::new(RwLock::new( 512 VhostUserBlkBackend::new( 513 backend_config.path, 514 backend_config.num_queues, 515 backend_config.readonly, 516 backend_config.direct, 517 backend_config.poll_queue, 518 backend_config.queue_size, 519 mem.clone(), 520 ) 521 .unwrap(), 522 )); 523 524 debug!("blk_backend is created!\n"); 525 526 let listener = Listener::new(&backend_config.socket, true).unwrap(); 527 528 let name = "vhost-user-blk-backend"; 529 let mut blk_daemon = VhostUserDaemon::new(name.to_string(), blk_backend.clone(), mem).unwrap(); 530 531 debug!("blk_daemon is created!\n"); 532 533 if let Err(e) = blk_daemon.start(listener) { 534 error!( 535 "Failed to start daemon for vhost-user-block with error: {:?}\n", 536 e 537 ); 538 process::exit(1); 539 } 540 541 if let Err(e) = blk_daemon.wait() { 542 error!("Error from the main thread: {:?}", e); 543 } 544 545 for thread in blk_backend.read().unwrap().threads.iter() { 546 if let Err(e) = thread.lock().unwrap().kill_evt.write(1) { 547 error!("Error shutting down worker thread: {:?}", e) 548 } 549 } 550 } 551