forked from firecracker-microvm/firecracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevice.rs
More file actions
1966 lines (1684 loc) · 74.8 KB
/
Copy pathdevice.rs
File metadata and controls
1966 lines (1684 loc) · 74.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
use std::cmp;
use std::convert::From;
use std::fs::{File, OpenOptions};
use std::io::{Seek, SeekFrom};
use std::net::SocketAddr;
use std::ops::Deref;
use std::os::linux::fs::MetadataExt;
use std::path::PathBuf;
use std::sync::Arc;
use block_io::FileEngine;
use crucible::volume::Volume;
use crucible_client_types::RegionExtentInfo;
use serde::{Deserialize, Serialize};
use vm_memory::ByteValued;
use vmm_sys_util::eventfd::EventFd;
use super::io::async_io;
use super::request::*;
use super::{BLOCK_QUEUE_SIZES, SECTOR_SHIFT, SECTOR_SIZE, VirtioBlockError, io as block_io};
use crate::devices::virtio::ActivateError;
use crate::devices::virtio::block::CacheType;
use crate::devices::virtio::block::virtio::io::{BlockIoError, CrucibleEngine};
use crate::devices::virtio::block::virtio::metrics::{BlockDeviceMetrics, BlockMetricsPerDevice};
use crate::devices::virtio::device::{ActiveState, DeviceState, VirtioDevice};
use crate::devices::virtio::generated::virtio_blk::{
VIRTIO_BLK_F_FLUSH, VIRTIO_BLK_F_RO, VIRTIO_BLK_ID_BYTES,
};
use crate::devices::virtio::generated::virtio_config::VIRTIO_F_VERSION_1;
use crate::devices::virtio::generated::virtio_ids::VIRTIO_ID_BLOCK;
use crate::devices::virtio::generated::virtio_ring::VIRTIO_RING_F_EVENT_IDX;
use crate::devices::virtio::queue::{InvalidAvailIdx, Queue};
use crate::devices::virtio::transport::{VirtioInterrupt, VirtioInterruptType};
use crate::impl_device_type;
use crate::logger::{IncMetric, error, warn};
use crate::rate_limiter::{BucketUpdate, RateLimiter};
use crate::utils::u64_to_usize;
use crate::vmm_config::RateLimiterConfig;
use crate::vmm_config::crucible::CrucibleConfig;
use crate::vmm_config::drive::BlockDeviceConfig;
use crate::vstate::memory::GuestMemoryMmap;
/// The engine file type, either Sync or Async (through io_uring).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
pub enum FileEngineType {
/// Use an Async engine, based on io_uring.
Async,
/// Use a Sync engine, based on blocking system calls.
#[default]
Sync,
// Use a Crucible, remote network block storage backend.
Crucible,
}
/// Helper object for setting up all `Block` fields derived from its backing file.
#[derive(Debug)]
pub struct DiskProperties {
pub file_path: String,
pub file_engine: FileEngine,
pub nsectors: u64,
pub image_id: [u8; VIRTIO_BLK_ID_BYTES as usize],
}
impl DiskProperties {
// Helper function that opens the file with the proper access permissions
fn open_file(disk_image_path: &str, is_disk_read_only: bool) -> Result<File, VirtioBlockError> {
OpenOptions::new()
.read(true)
.write(!is_disk_read_only)
.open(PathBuf::from(&disk_image_path))
.map_err(|x| VirtioBlockError::BackingFile(x, disk_image_path.to_string()))
}
fn volume_size(
rt: &tokio::runtime::Runtime,
targets: &[SocketAddr],
) -> Result<(RegionExtentInfo, u64), VirtioBlockError> {
let region_extent_info = rt.block_on(async {
CrucibleEngine::lookup_extent_info(&targets)
.await
.map_err(|err| {
error!("Error looking up crucible region extent into: {:?}", err);
VirtioBlockError::Config
})
})?;
let disk_size = region_extent_info.block_size
* region_extent_info.blocks_per_extent
* region_extent_info.extent_count as u64;
Ok((region_extent_info, disk_size))
}
// Helper function that gets the size of the file
fn file_size(disk_image_path: &str, disk_image: &mut File) -> Result<u64, VirtioBlockError> {
let disk_size = disk_image
.seek(SeekFrom::End(0))
.map_err(|x| VirtioBlockError::BackingFile(x, disk_image_path.to_string()))?;
// We only support disk size, which uses the first two words of the configuration space.
// If the image is not a multiple of the sector size, the tail bits are not exposed.
if disk_size % u64::from(SECTOR_SIZE) != 0 {
warn!(
"Disk size {} is not a multiple of sector size {}; the remainder will not be \
visible to the guest.",
disk_size, SECTOR_SIZE
);
}
Ok(disk_size)
}
pub fn from_file(
disk_image_path: String,
is_disk_read_only: bool,
file_engine_type: FileEngineType,
) -> Result<Self, VirtioBlockError> {
let mut disk_image = Self::open_file(&disk_image_path, is_disk_read_only)?;
let disk_size = Self::file_size(&disk_image_path, &mut disk_image)?;
let image_id = Self::build_disk_image_id(&disk_image);
let engine = FileEngine::from_file(disk_image, file_engine_type)
.map_err(VirtioBlockError::FileEngine)?;
Ok(Self {
file_path: disk_image_path,
file_engine: engine,
nsectors: disk_size >> SECTOR_SHIFT,
image_id,
})
}
pub fn from_crucible(crucible_config: &CrucibleConfig) -> Result<Self, VirtioBlockError> {
// Firecracker doesn't use async rust or tokio, but crucible library operations
// depend on an async runtime. We might want to push this up the stack at some
// point.
let rt =
Arc::new(tokio::runtime::Runtime::new().expect("Could not construct a tokio runtime"));
let (disk_size, crucible_engine) = match crucible_config {
CrucibleConfig::Network {
downstairs_targets,
volume_generation,
} => {
let targets = downstairs_targets
.iter()
.map(|target| {
target.parse::<SocketAddr>().map_err(|err| {
error!(
"Error parsing crucible target: {}, error: {:?}",
target, err
);
VirtioBlockError::Config
})
})
.collect::<Result<Vec<SocketAddr>, VirtioBlockError>>()?;
let (region_extent_info, disk_size) = Self::volume_size(&rt, &targets)?;
let options = crucible_client_types::CrucibleOpts {
target: targets,
..Default::default()
};
let crucible_engine = CrucibleEngine::with_network_volume(
rt,
options,
region_extent_info,
*volume_generation,
)
.map_err(|err| VirtioBlockError::FileEngine(BlockIoError::Crucible(err)))?;
(disk_size, crucible_engine)
}
CrucibleConfig::InMemory {
block_size,
disk_size,
} => {
let crucible_engine =
CrucibleEngine::with_in_memory_volume(rt, *block_size, *disk_size)
.map_err(|err| VirtioBlockError::FileEngine(BlockIoError::Crucible(err)))?;
(*disk_size as u64, crucible_engine)
}
};
// TODO: stop hardcoding a default image id
let mut image_id = [0; VIRTIO_BLK_ID_BYTES as usize];
let engine = FileEngine::Crucible(crucible_engine);
Ok(Self {
file_path: "n/a".to_string(), // TODO: Shouldn't require file_path
file_engine: engine,
nsectors: disk_size >> SECTOR_SHIFT,
image_id,
})
}
/// Create a new disk from the given VirtoioBlockConfig.
pub fn from_config(config: &VirtioBlockConfig) -> Result<Self, VirtioBlockError> {
match config.file_engine_type {
FileEngineType::Sync | FileEngineType::Async => Self::from_file(config.path_on_host.clone(), config.is_read_only, config.file_engine_type),
FileEngineType::Crucible => Self::from_crucible(&config.crucible.as_ref().expect("Crucible block device configuration must always be present in the 'crucible' field when file_engine_type is 'Crucible'")),
}
}
/// Update the path to the file backing the block device
pub fn update(
&mut self,
disk_image_path: String,
is_disk_read_only: bool,
) -> Result<(), VirtioBlockError> {
let mut disk_image = Self::open_file(&disk_image_path, is_disk_read_only)?;
let disk_size = Self::file_size(&disk_image_path, &mut disk_image)?;
self.image_id = Self::build_disk_image_id(&disk_image);
self.file_engine
.update_file_path(disk_image)
.map_err(VirtioBlockError::FileEngine)?;
self.nsectors = disk_size >> SECTOR_SHIFT;
self.file_path = disk_image_path;
Ok(())
}
fn build_device_id(disk_file: &File) -> Result<String, VirtioBlockError> {
let blk_metadata = disk_file
.metadata()
.map_err(VirtioBlockError::GetFileMetadata)?;
// This is how kvmtool does it.
let device_id = format!(
"{}{}{}",
blk_metadata.st_dev(),
blk_metadata.st_rdev(),
blk_metadata.st_ino()
);
Ok(device_id)
}
fn build_disk_image_id(disk_file: &File) -> [u8; VIRTIO_BLK_ID_BYTES as usize] {
let mut default_id = [0; VIRTIO_BLK_ID_BYTES as usize];
match Self::build_device_id(disk_file) {
Err(_) => {
warn!("Could not generate device id. We'll use a default.");
}
Ok(disk_id_string) => {
// The kernel only knows to read a maximum of VIRTIO_BLK_ID_BYTES.
// This will also zero out any leftover bytes.
let disk_id = disk_id_string.as_bytes();
let bytes_to_copy = cmp::min(disk_id.len(), VIRTIO_BLK_ID_BYTES as usize);
default_id[..bytes_to_copy].copy_from_slice(&disk_id[..bytes_to_copy]);
}
}
default_id
}
}
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
#[repr(C)]
pub struct ConfigSpace {
pub capacity: u64,
}
// SAFETY: `ConfigSpace` contains only PODs in `repr(C)` or `repr(transparent)`, without padding.
unsafe impl ByteValued for ConfigSpace {}
/// Use this structure to set up the Block Device before booting the kernel.
#[derive(Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct VirtioBlockConfig {
/// Unique identifier of the drive.
pub drive_id: String,
/// Part-UUID. Represents the unique id of the boot partition of this device. It is
/// optional and it will be used only if the `is_root_device` field is true.
pub partuuid: Option<String>,
/// If set to true, it makes the current device the root block device.
/// Setting this flag to true will mount the block device in the
/// guest under /dev/vda unless the partuuid is present.
pub is_root_device: bool,
/// If set to true, the drive will ignore flush requests coming from
/// the guest driver.
#[serde(default)]
pub cache_type: CacheType,
/// If set to true, the drive is opened in read-only mode. Otherwise, the
/// drive is opened as read-write.
pub is_read_only: bool,
/// Path of the backing file on the host. Only set when the io_engine is 'Sync' or 'Async'.
pub path_on_host: String,
/// Crucible configuration for network attached storage.
/// Only set when io_engine is 'Crucible'
pub crucible: Option<CrucibleConfig>,
/// Rate Limiter for I/O operations.
pub rate_limiter: Option<RateLimiterConfig>,
/// The type of IO engine used by the device.
#[serde(default)]
#[serde(rename = "io_engine")]
pub file_engine_type: FileEngineType,
}
impl TryFrom<&BlockDeviceConfig> for VirtioBlockConfig {
type Error = VirtioBlockError;
fn try_from(value: &BlockDeviceConfig) -> Result<Self, Self::Error> {
if value.path_on_host.is_some() && value.socket.is_none() {
Ok(Self {
drive_id: value.drive_id.clone(),
partuuid: value.partuuid.clone(),
is_root_device: value.is_root_device,
cache_type: value.cache_type,
is_read_only: value.is_read_only.unwrap_or(false),
path_on_host: value.path_on_host.as_ref().unwrap().clone(),
crucible: value.crucible.clone(),
rate_limiter: value.rate_limiter,
file_engine_type: value.file_engine_type.unwrap_or_default(),
})
} else {
Err(VirtioBlockError::Config)
}
}
}
impl From<VirtioBlockConfig> for BlockDeviceConfig {
fn from(value: VirtioBlockConfig) -> Self {
Self {
drive_id: value.drive_id,
partuuid: value.partuuid,
is_root_device: value.is_root_device,
cache_type: value.cache_type,
is_read_only: Some(value.is_read_only),
path_on_host: Some(value.path_on_host),
crucible: value.crucible,
rate_limiter: value.rate_limiter,
file_engine_type: Some(value.file_engine_type),
socket: None,
}
}
}
/// Virtio device for exposing block level read/write operations on a host file.
#[derive(Debug)]
pub struct VirtioBlock {
// Virtio fields.
pub avail_features: u64,
pub acked_features: u64,
pub config_space: ConfigSpace,
pub activate_evt: EventFd,
// Transport related fields.
pub queues: Vec<Queue>,
pub queue_evts: [EventFd; 1],
pub device_state: DeviceState,
// Implementation specific fields.
pub id: String,
pub partuuid: Option<String>,
pub cache_type: CacheType,
pub root_device: bool,
pub read_only: bool,
// Host file and properties.
pub disk: DiskProperties,
pub rate_limiter: RateLimiter,
pub is_io_engine_throttled: bool,
pub metrics: Arc<BlockDeviceMetrics>,
}
macro_rules! unwrap_async_file_engine_or_return {
($file_engine: expr) => {
match $file_engine {
FileEngine::Async(engine) => engine,
FileEngine::Crucible(_) => {
error!("The block device doesn't use an async IO engine");
return;
}
FileEngine::Sync(_) => {
error!("The block device doesn't use an async IO engine");
return;
}
}
};
}
impl VirtioBlock {
/// Create a new virtio block device from the given block configuration. The
/// block device could be an underlying file system file, or a remote network
/// attached block volume.
pub fn new(config: VirtioBlockConfig) -> Result<VirtioBlock, VirtioBlockError> {
let disk_properties = DiskProperties::from_config(&config)?;
let rate_limiter = config
.rate_limiter
.map(RateLimiterConfig::try_into)
.transpose()
.map_err(VirtioBlockError::RateLimiter)?
.unwrap_or_default();
let mut avail_features = (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_RING_F_EVENT_IDX);
if config.cache_type == CacheType::Writeback {
avail_features |= 1u64 << VIRTIO_BLK_F_FLUSH;
}
if config.is_read_only {
avail_features |= 1u64 << VIRTIO_BLK_F_RO;
};
let queue_evts = [EventFd::new(libc::EFD_NONBLOCK).map_err(VirtioBlockError::EventFd)?];
let queues = BLOCK_QUEUE_SIZES.iter().map(|&s| Queue::new(s)).collect();
let config_space = ConfigSpace {
capacity: disk_properties.nsectors.to_le(),
};
Ok(VirtioBlock {
avail_features,
acked_features: 0u64,
config_space,
activate_evt: EventFd::new(libc::EFD_NONBLOCK).map_err(VirtioBlockError::EventFd)?,
queues,
queue_evts,
device_state: DeviceState::Inactive,
id: config.drive_id.clone(),
partuuid: config.partuuid,
cache_type: config.cache_type,
root_device: config.is_root_device,
read_only: config.is_read_only,
disk: disk_properties,
rate_limiter,
is_io_engine_throttled: false,
metrics: BlockMetricsPerDevice::alloc(config.drive_id),
})
}
/// Returns a copy of a device config
pub fn config(&self) -> VirtioBlockConfig {
let rl: RateLimiterConfig = (&self.rate_limiter).into();
VirtioBlockConfig {
drive_id: self.id.clone(),
// TODO: Fix
crucible: None,
path_on_host: self.disk.file_path.clone(),
is_root_device: self.root_device,
partuuid: self.partuuid.clone(),
is_read_only: self.read_only,
cache_type: self.cache_type,
rate_limiter: rl.into_option(),
file_engine_type: self.file_engine_type(),
}
}
/// Process a single event in the Virtio queue.
///
/// This function is called by the event manager when the guest notifies us
/// about new buffers in the queue.
pub(crate) fn process_queue_event(&mut self) {
self.metrics.queue_event_count.inc();
if let Err(err) = self.queue_evts[0].read() {
error!("Failed to get queue event: {:?}", err);
self.metrics.event_fails.inc();
} else if self.rate_limiter.is_blocked() {
self.metrics.rate_limiter_throttled_events.inc();
} else if self.is_io_engine_throttled {
self.metrics.io_engine_throttled_events.inc();
} else {
self.process_virtio_queues().unwrap()
}
}
/// Process device virtio queue(s).
pub fn process_virtio_queues(&mut self) -> Result<(), InvalidAvailIdx> {
self.process_queue(0)
}
pub(crate) fn process_rate_limiter_event(&mut self) {
self.metrics.rate_limiter_event_count.inc();
// Upon rate limiter event, call the rate limiter handler
// and restart processing the queue.
if self.rate_limiter.event_handler().is_ok() {
self.process_queue(0).unwrap()
}
}
/// Device specific function for peaking inside a queue and processing descriptors.
pub fn process_queue(&mut self, queue_index: usize) -> Result<(), InvalidAvailIdx> {
// This is safe since we checked in the event handler that the device is activated.
let active_state = self.device_state.active_state().unwrap();
let queue = &mut self.queues[queue_index];
let mut used_any = false;
while let Some(head) = queue.pop_or_enable_notification()? {
self.metrics.remaining_reqs_count.add(queue.len().into());
let processing_result =
match Request::parse(&head, &active_state.mem, self.disk.nsectors) {
Ok(request) => {
if request.rate_limit(&mut self.rate_limiter) {
// Stop processing the queue and return this descriptor chain to the
// avail ring, for later processing.
queue.undo_pop();
self.metrics.rate_limiter_throttled_events.inc();
break;
}
request.process(
&mut self.disk,
head.index,
&active_state.mem,
&self.metrics,
)
}
Err(err) => {
error!("Failed to parse available descriptor chain: {:?}", err);
self.metrics.execute_fails.inc();
ProcessingResult::Executed(FinishedRequest {
num_bytes_to_mem: 0,
desc_idx: head.index,
})
}
};
match processing_result {
ProcessingResult::Submitted => {}
ProcessingResult::Throttled => {
queue.undo_pop();
self.is_io_engine_throttled = true;
break;
}
ProcessingResult::Executed(finished) => {
used_any = true;
queue
.add_used(head.index, finished.num_bytes_to_mem)
.unwrap_or_else(|err| {
error!(
"Failed to add available descriptor head {}: {}",
head.index, err
)
});
}
}
}
queue.advance_used_ring_idx();
if used_any && queue.prepare_kick() {
active_state
.interrupt
.trigger(VirtioInterruptType::Queue(0))
.unwrap_or_else(|_| {
self.metrics.event_fails.inc();
});
}
if let FileEngine::Async(ref mut engine) = self.disk.file_engine
&& let Err(err) = engine.kick_submission_queue()
{
error!("BlockError submitting pending block requests: {:?}", err);
}
if !used_any {
self.metrics.no_avail_buffer.inc();
}
Ok(())
}
fn process_async_completion_queue(&mut self) {
let engine = unwrap_async_file_engine_or_return!(&mut self.disk.file_engine);
// This is safe since we checked in the event handler that the device is activated.
let active_state = self.device_state.active_state().unwrap();
let queue = &mut self.queues[0];
loop {
match engine.pop(&active_state.mem) {
Err(error) => {
error!("Failed to read completed io_uring entry: {:?}", error);
break;
}
Ok(None) => break,
Ok(Some(cqe)) => {
let res = cqe.result();
let user_data = cqe.user_data();
let (pending, res) = match res {
Ok(count) => (user_data, Ok(count)),
Err(error) => (
user_data,
Err(IoErr::FileEngine(block_io::BlockIoError::Async(
async_io::AsyncIoError::IO(error),
))),
),
};
let finished = pending.finish(&active_state.mem, res, &self.metrics);
queue
.add_used(finished.desc_idx, finished.num_bytes_to_mem)
.unwrap_or_else(|err| {
error!(
"Failed to add available descriptor head {}: {}",
finished.desc_idx, err
)
});
}
}
}
queue.advance_used_ring_idx();
if queue.prepare_kick() {
active_state
.interrupt
.trigger(VirtioInterruptType::Queue(0))
.unwrap_or_else(|_| {
self.metrics.event_fails.inc();
});
}
}
pub fn process_async_completion_event(&mut self) {
let engine = unwrap_async_file_engine_or_return!(&mut self.disk.file_engine);
if let Err(err) = engine.completion_evt().read() {
error!("Failed to get async completion event: {:?}", err);
} else {
self.process_async_completion_queue();
if self.is_io_engine_throttled {
self.is_io_engine_throttled = false;
self.process_queue(0).unwrap()
}
}
}
/// Update the backing file and the config space of the block device.
pub fn update_disk_image(&mut self, disk_image_path: String) -> Result<(), VirtioBlockError> {
self.disk.update(disk_image_path, self.read_only)?;
self.config_space.capacity = self.disk.nsectors.to_le(); // virtio_block_config_space();
// Kick the driver to pick up the changes. (But only if the device is already activated).
if self.is_activated() {
self.interrupt_trigger()
.trigger(VirtioInterruptType::Config)
.unwrap();
}
self.metrics.update_count.inc();
Ok(())
}
/// Updates the parameters for the rate limiter
pub fn update_rate_limiter(&mut self, bytes: BucketUpdate, ops: BucketUpdate) {
self.rate_limiter.update_buckets(bytes, ops);
}
/// Retrieve the file engine type.
pub fn file_engine_type(&self) -> FileEngineType {
match self.disk.file_engine {
FileEngine::Sync(_) => FileEngineType::Sync,
FileEngine::Async(_) => FileEngineType::Async,
FileEngine::Crucible(_) => FileEngineType::Crucible,
}
}
fn drain_and_flush(&mut self, discard: bool) {
if let Err(err) = self.disk.file_engine.drain_and_flush(discard) {
error!("Failed to drain ops and flush block data: {:?}", err);
}
}
/// Prepare device for being snapshotted.
pub fn prepare_save(&mut self) {
if !self.is_activated() {
return;
}
self.drain_and_flush(false);
if let FileEngine::Async(ref _engine) = self.disk.file_engine {
self.process_async_completion_queue();
}
}
}
impl VirtioDevice for VirtioBlock {
impl_device_type!(VIRTIO_ID_BLOCK);
fn avail_features(&self) -> u64 {
self.avail_features
}
fn acked_features(&self) -> u64 {
self.acked_features
}
fn set_acked_features(&mut self, acked_features: u64) {
self.acked_features = acked_features;
}
fn queues(&self) -> &[Queue] {
&self.queues
}
fn queues_mut(&mut self) -> &mut [Queue] {
&mut self.queues
}
fn queue_events(&self) -> &[EventFd] {
&self.queue_evts
}
fn interrupt_trigger(&self) -> &dyn VirtioInterrupt {
self.device_state
.active_state()
.expect("Device is not initialized")
.interrupt
.deref()
}
fn read_config(&self, offset: u64, data: &mut [u8]) {
if let Some(config_space_bytes) = self.config_space.as_slice().get(u64_to_usize(offset)..) {
let len = config_space_bytes.len().min(data.len());
data[..len].copy_from_slice(&config_space_bytes[..len]);
} else {
error!("Failed to read config space");
self.metrics.cfg_fails.inc();
}
}
fn write_config(&mut self, offset: u64, data: &[u8]) {
let config_space_bytes = self.config_space.as_mut_slice();
let start = usize::try_from(offset).ok();
let end = start.and_then(|s| s.checked_add(data.len()));
let Some(dst) = start
.zip(end)
.and_then(|(start, end)| config_space_bytes.get_mut(start..end))
else {
error!("Failed to write config space");
self.metrics.cfg_fails.inc();
return;
};
dst.copy_from_slice(data);
}
fn activate(
&mut self,
mem: GuestMemoryMmap,
interrupt: Arc<dyn VirtioInterrupt>,
) -> Result<(), ActivateError> {
for q in self.queues.iter_mut() {
q.initialize(&mem)
.map_err(ActivateError::QueueMemoryError)?;
}
let event_idx = self.has_feature(u64::from(VIRTIO_RING_F_EVENT_IDX));
if event_idx {
for queue in &mut self.queues {
queue.enable_notif_suppression();
}
}
if self.activate_evt.write(1).is_err() {
self.metrics.activate_fails.inc();
return Err(ActivateError::EventFd);
}
self.device_state = DeviceState::Activated(ActiveState { mem, interrupt });
Ok(())
}
fn is_activated(&self) -> bool {
self.device_state.is_activated()
}
}
impl Drop for VirtioBlock {
fn drop(&mut self) {
match self.cache_type {
CacheType::Unsafe => {
if let Err(err) = self.disk.file_engine.drain(true) {
error!("Failed to drain ops on drop: {:?}", err);
}
}
CacheType::Writeback => {
self.drain_and_flush(true);
}
};
}
}
#[cfg(test)]
mod tests {
use std::fs::metadata;
use std::io::{Read, Write};
use std::os::unix::ffi::OsStrExt;
use std::thread;
use std::time::Duration;
use vmm_sys_util::tempfile::TempFile;
use super::*;
use crate::check_metric_after_block;
use crate::devices::virtio::block::virtio::IO_URING_NUM_ENTRIES;
use crate::devices::virtio::block::virtio::test_utils::{
default_block, read_blk_req_descriptors, set_queue, set_rate_limiter,
simulate_async_completion_event, simulate_queue_and_async_completion_events,
simulate_queue_event,
};
use crate::devices::virtio::queue::{VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE};
use crate::devices::virtio::test_utils::{VirtQueue, default_interrupt, default_mem};
use crate::rate_limiter::TokenType;
use crate::vstate::memory::{Address, Bytes, GuestAddress};
#[test]
fn test_from_config() {
let block_config = BlockDeviceConfig {
drive_id: "".to_string(),
partuuid: None,
is_root_device: false,
cache_type: CacheType::Unsafe,
is_read_only: Some(true),
path_on_host: Some("path".to_string()),
rate_limiter: None,
file_engine_type: Default::default(),
socket: None,
};
VirtioBlockConfig::try_from(&block_config).unwrap();
let block_config = BlockDeviceConfig {
drive_id: "".to_string(),
partuuid: None,
is_root_device: false,
cache_type: CacheType::Unsafe,
is_read_only: None,
path_on_host: None,
rate_limiter: None,
file_engine_type: Default::default(),
socket: Some("sock".to_string()),
};
VirtioBlockConfig::try_from(&block_config).unwrap_err();
let block_config = BlockDeviceConfig {
drive_id: "".to_string(),
partuuid: None,
is_root_device: false,
cache_type: CacheType::Unsafe,
is_read_only: Some(true),
path_on_host: Some("path".to_string()),
rate_limiter: None,
file_engine_type: Default::default(),
socket: Some("sock".to_string()),
};
VirtioBlockConfig::try_from(&block_config).unwrap_err();
}
#[test]
fn test_disk_backing_file_helper() {
let num_sectors = 2;
let f = TempFile::new().unwrap();
let size = u64::from(SECTOR_SIZE) * num_sectors;
f.as_file().set_len(size).unwrap();
for engine in [FileEngineType::Sync, FileEngineType::Async] {
let disk_properties =
DiskProperties::new(String::from(f.as_path().to_str().unwrap()), true, engine)
.unwrap();
assert_eq!(size, u64::from(SECTOR_SIZE) * num_sectors);
assert_eq!(disk_properties.nsectors, num_sectors);
// Testing `backing_file.virtio_block_disk_image_id()` implies
// duplicating that logic in tests, so skipping it.
let res = DiskProperties::new("invalid-disk-path".to_string(), true, engine);
assert!(
matches!(res, Err(VirtioBlockError::BackingFile(_, _))),
"{:?}",
res
);
}
}
#[test]
fn test_virtio_features() {
for engine in [FileEngineType::Sync, FileEngineType::Async] {
let mut block = default_block(engine);
assert_eq!(block.device_type(), VIRTIO_ID_BLOCK);
let features: u64 = (1u64 << VIRTIO_F_VERSION_1) | (1u64 << VIRTIO_RING_F_EVENT_IDX);
assert_eq!(
block.avail_features_by_page(0),
(features & 0xffffffff) as u32,
);
assert_eq!(block.avail_features_by_page(1), (features >> 32) as u32);
for i in 2..10 {
assert_eq!(block.avail_features_by_page(i), 0u32);
}
for i in 0..10 {
block.ack_features_by_page(i, u32::MAX);
}
assert_eq!(block.acked_features, features);
}
}
#[test]
fn test_virtio_read_config() {
for engine in [FileEngineType::Sync, FileEngineType::Async] {
let block = default_block(engine);
let mut actual_config_space = ConfigSpace::default();
block.read_config(0, actual_config_space.as_mut_slice());
// This will read the number of sectors.
// The block's backing file size is 0x1000, so there are 8 (4096/512) sectors.
// The config space is little endian.
let expected_config_space = ConfigSpace { capacity: 8 };
assert_eq!(actual_config_space, expected_config_space);
// Invalid read.
let expected_config_space = ConfigSpace { capacity: 696969 };
actual_config_space = expected_config_space;
block.read_config(
std::mem::size_of::<ConfigSpace>() as u64 + 1,
actual_config_space.as_mut_slice(),
);
// Validate read failed (the config space was not updated).
assert_eq!(actual_config_space, expected_config_space);
}
}
#[test]
fn test_virtio_write_config() {
for engine in [FileEngineType::Sync, FileEngineType::Async] {
let mut block = default_block(engine);
let expected_config_space = ConfigSpace { capacity: 696969 };
block.write_config(0, expected_config_space.as_slice());
let mut actual_config_space = ConfigSpace::default();
block.read_config(0, actual_config_space.as_mut_slice());
assert_eq!(actual_config_space, expected_config_space);
// If privileged user writes to `/dev/mem`, in block config space - byte by byte.
let expected_config_space = ConfigSpace {
capacity: 0x1122334455667788,
};
let expected_config_space_slice = expected_config_space.as_slice();
for (i, b) in expected_config_space_slice.iter().enumerate() {
block.write_config(i as u64, &[*b]);
}
block.read_config(0, actual_config_space.as_mut_slice());
assert_eq!(actual_config_space, expected_config_space);
// Invalid write.
let new_config_space = ConfigSpace {
capacity: 0xDEADBEEF,
};
block.write_config(5, new_config_space.as_slice());
// Make sure nothing got written.
block.read_config(0, actual_config_space.as_mut_slice());
assert_eq!(actual_config_space, expected_config_space);
// Large offset that may cause an overflow.
block.write_config(u64::MAX, new_config_space.as_slice());
// Make sure nothing got written.
block.read_config(0, actual_config_space.as_mut_slice());
assert_eq!(actual_config_space, expected_config_space);
}
}
#[test]
fn test_invalid_request() {
for engine in [FileEngineType::Sync, FileEngineType::Async] {
let mut block = default_block(engine);
let mem = default_mem();
let interrupt = default_interrupt();
let vq = VirtQueue::new(GuestAddress(0), &mem, 16);
set_queue(&mut block, 0, vq.create_queue());
block.activate(mem.clone(), interrupt).unwrap();
read_blk_req_descriptors(&vq);
let request_type_addr = GuestAddress(vq.dtable[0].addr.get());
// Request is invalid because the first descriptor is write-only.
vq.dtable[0]
.flags
.set(VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_WRITE);
mem.write_obj::<u32>(VIRTIO_BLK_T_IN, request_type_addr)
.unwrap();
simulate_queue_event(&mut block, Some(true));