device_virtio_block/
lib.rs

1// Copyright 2021 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#[cfg(windows)]
6use std::num::NonZeroU32;
7use std::path::PathBuf;
8
9use anyhow::Context;
10use base::Tube;
11use cros_async::ExecutorKind;
12use devices::virtio::VirtioDevice;
13use devices::PciAddress;
14use devices::VirtioDeviceArgs;
15use devices::VirtioDeviceModule;
16use serde::Deserialize;
17use serde::Deserializer;
18use serde::Serialize;
19use serde::Serializer;
20use vm_control::AnyControlTube;
21
22pub mod asynchronous;
23mod interrupt_coalescer;
24pub mod sys;
25pub mod vhost_user;
26
27pub use asynchronous::BlockAsync;
28pub use vhost_user::run_block_device;
29pub use vhost_user::Options as BlockOptions;
30
31fn block_option_sparse_default() -> bool {
32    true
33}
34fn block_option_lock_default() -> bool {
35    true
36}
37fn block_option_block_size_default() -> u32 {
38    512
39}
40// TODO(b/237829580): Move to sys module once virtio block sys is refactored to
41// match the style guide.
42#[cfg(windows)]
43fn block_option_io_concurrency_default() -> NonZeroU32 {
44    NonZeroU32::new(1).unwrap()
45}
46
47/// Maximum length of a `DiskOption` identifier.
48///
49/// This is based on the virtio-block ID length limit.
50pub const DISK_ID_LEN: usize = 20;
51
52pub fn serialize_disk_id<S: Serializer>(
53    id: &Option<[u8; DISK_ID_LEN]>,
54    serializer: S,
55) -> Result<S::Ok, S::Error> {
56    match id {
57        None => serializer.serialize_none(),
58        Some(id) => {
59            // Find the first zero byte in the id.
60            let len = id.iter().position(|v| *v == 0).unwrap_or(DISK_ID_LEN);
61            serializer.serialize_some(
62                std::str::from_utf8(&id[0..len])
63                    .map_err(|e| serde::ser::Error::custom(e.to_string()))?,
64            )
65        }
66    }
67}
68
69fn deserialize_disk_id<'de, D: Deserializer<'de>>(
70    deserializer: D,
71) -> Result<Option<[u8; DISK_ID_LEN]>, D::Error> {
72    let id = Option::<String>::deserialize(deserializer)?;
73
74    match id {
75        None => Ok(None),
76        Some(id) => {
77            if id.len() > DISK_ID_LEN {
78                return Err(serde::de::Error::custom(format!(
79                    "disk id must be {DISK_ID_LEN} or fewer characters"
80                )));
81            }
82
83            let mut ret = [0u8; DISK_ID_LEN];
84            // Slicing id to value's length will never panic
85            // because we checked that value will fit into id above.
86            ret[..id.len()].copy_from_slice(id.as_bytes());
87            Ok(Some(ret))
88        }
89    }
90}
91
92#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "kebab-case")]
94pub enum DiskFormat {
95    #[default]
96    Auto,
97    Raw,
98}
99
100#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, serde_keyvalue::FromKeyValues)]
101#[serde(deny_unknown_fields, rename_all = "kebab-case")]
102// LINT.IfChange
103pub struct DiskOption {
104    pub path: PathBuf,
105    #[serde(default, rename = "ro")]
106    pub read_only: bool,
107    #[serde(default)]
108    /// Whether this disk should be the root device. Can only be set once. Only useful for adding
109    /// specific command-line options.
110    pub root: bool,
111    #[serde(default = "block_option_sparse_default")]
112    pub sparse: bool,
113    // camel_case variant allowed for backward compatibility.
114    #[serde(default, alias = "o_direct")]
115    pub direct: bool,
116    /// Whether to lock the disk files. Uses flock on Unix and FILE_SHARE_* flags on Windows.
117    #[serde(default = "block_option_lock_default")]
118    pub lock: bool,
119    // camel_case variant allowed for backward compatibility.
120    #[serde(default = "block_option_block_size_default", alias = "block_size")]
121    pub block_size: u32,
122    #[serde(
123        default,
124        serialize_with = "serialize_disk_id",
125        deserialize_with = "deserialize_disk_id"
126    )]
127    pub id: Option<[u8; DISK_ID_LEN]>,
128    // Deprecated: Use async_executor=overlapped[concurrency=N]"
129    // camel_case variant allowed for backward compatibility.
130    #[cfg(windows)]
131    #[serde(
132        default = "block_option_io_concurrency_default",
133        alias = "io_concurrency"
134    )]
135    pub io_concurrency: NonZeroU32,
136    #[serde(default)]
137    /// Experimental option to run multiple worker threads in parallel. If false, only single
138    /// thread runs by default. Note this option is not effective for vhost-user blk device.
139    pub multiple_workers: bool,
140    #[serde(default, alias = "async_executor")]
141    /// The async executor kind to simulate the block device with. This option takes
142    /// precedence over the async executor kind specified by the subcommand's option.
143    /// If None, the default or the specified by the subcommand's option would be used.
144    pub async_executor: Option<ExecutorKind>,
145    #[serde(default)]
146    //Option to choose virtqueue type. If true, use the packed virtqueue. If false
147    //or by default, use split virtqueue
148    pub packed_queue: bool,
149
150    /// Specify the boot index for this device that the BIOS will use when attempting to boot from
151    /// bootable devices. For example, if bootindex=2, then the BIOS will attempt to boot from the
152    /// device right after booting from the device with bootindex=1 fails.
153    pub bootindex: Option<usize>,
154
155    /// Specify PCI address will be used to attach this device
156    pub pci_address: Option<PciAddress>,
157    /// Specify whether to cache reads/writes.
158    #[serde(default)]
159    pub dontcache: bool,
160    /// Disk image format. When set to `Raw`, header auto-detection is skipped.
161    #[serde(default)]
162    pub format: DiskFormat,
163}
164// LINT.ThenChange(/src/crosvm/cmdline.rs)
165
166impl Default for DiskOption {
167    fn default() -> Self {
168        Self {
169            path: PathBuf::new(),
170            read_only: false,
171            root: false,
172            sparse: block_option_sparse_default(),
173            direct: false,
174            lock: block_option_lock_default(),
175            block_size: block_option_block_size_default(),
176            id: None,
177            #[cfg(windows)]
178            io_concurrency: block_option_io_concurrency_default(),
179            multiple_workers: false,
180            async_executor: None,
181            packed_queue: false,
182            bootindex: None,
183            pci_address: None,
184            dontcache: false,
185            format: DiskFormat::default(),
186        }
187    }
188}
189
190impl VirtioDeviceModule for DiskOption {
191    fn sort_name(&self) -> &'static str {
192        "block"
193    }
194
195    fn create(&self, args: &mut VirtioDeviceArgs<'_>) -> anyhow::Result<Box<dyn VirtioDevice>> {
196        base::info!("Trying to attach block device: {}", self.path.display());
197
198        let (disk_host_tube, disk_device_tube) = Tube::pair().context("failed to create tube")?;
199        (args.add_control_tube)(AnyControlTube::Disk(disk_host_tube));
200
201        let dev = BlockAsync::new(
202            devices::virtio::base_features(args.protection_type),
203            self.open()?,
204            self,
205            Some(disk_device_tube),
206            None,
207            None,
208        )
209        .context("failed to create block device")?;
210
211        Ok(Box::new(dev))
212    }
213
214    #[cfg(any(target_os = "android", target_os = "linux"))]
215    fn create_jail(
216        &self,
217        jail_config: Option<&jail::JailConfig>,
218    ) -> anyhow::Result<Option<minijail::Minijail>> {
219        let jail = jail::simple_jail(
220            jail_config,
221            &devices::virtio::VirtioDeviceType::Regular.seccomp_policy_file("block"),
222        )?;
223        Ok(jail)
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    #[cfg(any(target_os = "android", target_os = "linux"))]
230    use cros_async::sys::linux::ExecutorKindSys;
231    #[cfg(windows)]
232    use cros_async::sys::windows::ExecutorKindSys;
233    use serde_keyvalue::*;
234
235    use super::*;
236
237    fn from_block_arg(options: &str) -> Result<DiskOption, ParseError> {
238        from_key_values(options)
239    }
240
241    #[test]
242    fn check_default_matches_from_key_values() {
243        let path = "/path/to/disk.img";
244        let disk = DiskOption {
245            path: PathBuf::from(path),
246            ..Default::default()
247        };
248        assert_eq!(disk, from_key_values(path).unwrap());
249    }
250
251    #[test]
252    fn params_from_key_values() {
253        // Path argument is mandatory.
254        let err = from_block_arg("").unwrap_err();
255        assert_eq!(
256            err,
257            ParseError {
258                kind: ErrorKind::SerdeError("missing field `path`".into()),
259                pos: 0,
260            }
261        );
262
263        // Path is the default argument.
264        let params = from_block_arg("/path/to/disk.img").unwrap();
265        assert_eq!(
266            params,
267            DiskOption {
268                path: "/path/to/disk.img".into(),
269                ..Default::default()
270            }
271        );
272
273        // bootindex
274        let params = from_block_arg("/path/to/disk.img,bootindex=5").unwrap();
275        assert_eq!(
276            params,
277            DiskOption {
278                path: "/path/to/disk.img".into(),
279                bootindex: Some(5),
280                ..Default::default()
281            }
282        );
283
284        // Explicitly-specified path.
285        let params = from_block_arg("path=/path/to/disk.img").unwrap();
286        assert_eq!(
287            params,
288            DiskOption {
289                path: "/path/to/disk.img".into(),
290                ..Default::default()
291            }
292        );
293
294        // read_only
295        let params = from_block_arg("/some/path.img,ro").unwrap();
296        assert_eq!(
297            params,
298            DiskOption {
299                path: "/some/path.img".into(),
300                read_only: true,
301                ..Default::default()
302            }
303        );
304
305        // root
306        let params = from_block_arg("/some/path.img,root").unwrap();
307        assert_eq!(
308            params,
309            DiskOption {
310                path: "/some/path.img".into(),
311                root: true,
312                ..Default::default()
313            }
314        );
315
316        // sparse
317        let params = from_block_arg("/some/path.img,sparse").unwrap();
318        assert_eq!(
319            params,
320            DiskOption {
321                path: "/some/path.img".into(),
322                ..Default::default()
323            }
324        );
325        let params = from_block_arg("/some/path.img,sparse=false").unwrap();
326        assert_eq!(
327            params,
328            DiskOption {
329                path: "/some/path.img".into(),
330                sparse: false,
331                ..Default::default()
332            }
333        );
334
335        // direct
336        let params = from_block_arg("/some/path.img,direct").unwrap();
337        assert_eq!(
338            params,
339            DiskOption {
340                path: "/some/path.img".into(),
341                direct: true,
342                ..Default::default()
343            }
344        );
345
346        // o_direct (deprecated, kept for backward compatibility)
347        let params = from_block_arg("/some/path.img,o_direct").unwrap();
348        assert_eq!(
349            params,
350            DiskOption {
351                path: "/some/path.img".into(),
352                direct: true,
353                ..Default::default()
354            }
355        );
356
357        // block-size
358        let params = from_block_arg("/some/path.img,block-size=128").unwrap();
359        assert_eq!(
360            params,
361            DiskOption {
362                path: "/some/path.img".into(),
363                block_size: 128,
364                ..Default::default()
365            }
366        );
367
368        // block_size (deprecated, kept for backward compatibility)
369        let params = from_block_arg("/some/path.img,block_size=128").unwrap();
370        assert_eq!(
371            params,
372            DiskOption {
373                path: "/some/path.img".into(),
374                block_size: 128,
375                ..Default::default()
376            }
377        );
378
379        // io_concurrency
380        #[cfg(windows)]
381        {
382            let params = from_block_arg("/some/path.img,io_concurrency=4").unwrap();
383            assert_eq!(
384                params,
385                DiskOption {
386                    path: "/some/path.img".into(),
387                    io_concurrency: NonZeroU32::new(4).unwrap(),
388                    ..Default::default()
389                }
390            );
391            let params = from_block_arg("/some/path.img,async-executor=overlapped").unwrap();
392            assert_eq!(
393                params,
394                DiskOption {
395                    path: "/some/path.img".into(),
396                    async_executor: Some(ExecutorKindSys::Overlapped { concurrency: None }.into()),
397                    ..Default::default()
398                }
399            );
400            let params =
401                from_block_arg("/some/path.img,async-executor=\"overlapped,concurrency=4\"")
402                    .unwrap();
403            assert_eq!(
404                params,
405                DiskOption {
406                    path: "/some/path.img".into(),
407                    async_executor: Some(
408                        ExecutorKindSys::Overlapped {
409                            concurrency: Some(4)
410                        }
411                        .into()
412                    ),
413                    ..Default::default()
414                }
415            );
416        }
417
418        // id
419        let params = from_block_arg("/some/path.img,id=DISK").unwrap();
420        assert_eq!(
421            params,
422            DiskOption {
423                path: "/some/path.img".into(),
424                id: Some(*b"DISK\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"),
425                ..Default::default()
426            }
427        );
428        let err = from_block_arg("/some/path.img,id=DISK_ID_IS_WAY_TOO_LONG").unwrap_err();
429        assert_eq!(
430            err,
431            ParseError {
432                kind: ErrorKind::SerdeError("disk id must be 20 or fewer characters".into()),
433                pos: 0,
434            }
435        );
436
437        // async-executor
438        #[cfg(windows)]
439        let (ex_kind, ex_kind_opt) = (ExecutorKindSys::Handle.into(), "handle");
440        #[cfg(any(target_os = "android", target_os = "linux"))]
441        let (ex_kind, ex_kind_opt) = (ExecutorKindSys::Fd.into(), "epoll");
442        let params =
443            from_block_arg(&format!("/some/path.img,async-executor={ex_kind_opt}")).unwrap();
444        assert_eq!(
445            params,
446            DiskOption {
447                path: "/some/path.img".into(),
448                async_executor: Some(ex_kind),
449                ..Default::default()
450            }
451        );
452
453        // packed queue
454        let params = from_block_arg("/path/to/disk.img,packed-queue").unwrap();
455        assert_eq!(
456            params,
457            DiskOption {
458                path: "/path/to/disk.img".into(),
459                packed_queue: true,
460                ..Default::default()
461            }
462        );
463
464        // pci-address
465        let params = from_block_arg("/path/to/disk.img,pci-address=00:01.1").unwrap();
466        assert_eq!(
467            params,
468            DiskOption {
469                path: "/path/to/disk.img".into(),
470                pci_address: Some(PciAddress {
471                    bus: 0,
472                    dev: 1,
473                    func: 1,
474                }),
475                ..Default::default()
476            }
477        );
478
479        // lock=true
480        let params = from_block_arg("/path/to/disk.img,lock=true").unwrap();
481        assert_eq!(
482            params,
483            DiskOption {
484                path: "/path/to/disk.img".into(),
485                ..Default::default()
486            }
487        );
488        // lock=false
489        let params = from_block_arg("/path/to/disk.img,lock=false").unwrap();
490        assert_eq!(
491            params,
492            DiskOption {
493                path: "/path/to/disk.img".into(),
494                lock: false,
495                ..Default::default()
496            }
497        );
498
499        // dontcache
500        let params = from_block_arg("/path/to/disk.img,dontcache").unwrap();
501        assert_eq!(
502            params,
503            DiskOption {
504                path: "/path/to/disk.img".into(),
505                dontcache: true,
506                ..Default::default()
507            }
508        );
509        let params = from_block_arg("/path/to/disk.img,dontcache=false").unwrap();
510        assert_eq!(
511            params,
512            DiskOption {
513                path: "/path/to/disk.img".into(),
514                dontcache: false,
515                ..Default::default()
516            }
517        );
518
519        // format
520        let params = from_block_arg("/path/to/disk.img,format=raw").unwrap();
521        assert_eq!(
522            params,
523            DiskOption {
524                path: "/path/to/disk.img".into(),
525                format: DiskFormat::Raw,
526                ..Default::default()
527            }
528        );
529        let params = from_block_arg("/path/to/disk.img,format=auto").unwrap();
530        assert_eq!(
531            params,
532            DiskOption {
533                path: "/path/to/disk.img".into(),
534                format: DiskFormat::Auto,
535                ..Default::default()
536            }
537        );
538        assert!(from_block_arg("/path/to/disk.img,format=unknown").is_err());
539
540        // All together
541        let params = from_block_arg(&format!(
542            "/some/path.img,block_size=256,ro,root,sparse=false,id=DISK_LABEL\
543             ,direct,async-executor={ex_kind_opt},packed-queue=false,pci-address=00:01.1\
544             ,format=raw"
545        ))
546        .unwrap();
547        assert_eq!(
548            params,
549            DiskOption {
550                path: "/some/path.img".into(),
551                read_only: true,
552                root: true,
553                sparse: false,
554                direct: true,
555                block_size: 256,
556                id: Some(*b"DISK_LABEL\0\0\0\0\0\0\0\0\0\0"),
557                async_executor: Some(ex_kind),
558                pci_address: Some(PciAddress {
559                    bus: 0,
560                    dev: 1,
561                    func: 1,
562                }),
563                format: DiskFormat::Raw,
564                ..Default::default()
565            }
566        );
567    }
568
569    #[test]
570    fn open_with_raw_format_skips_autodetect() {
571        use base::VolatileSlice;
572
573        let dir = tempfile::tempdir().unwrap();
574        let headers: &[&[u8]] = &[
575            b"QFI\xfb",
576            b"composite_disk\x1d",
577            &0xED26FF3Au32.to_le_bytes(),
578        ];
579
580        for (i, magic) in headers.iter().enumerate() {
581            let path = dir.path().join(format!("disk_{i}.img"));
582            let mut contents = vec![0u8; 4096];
583            contents[..magic.len()].copy_from_slice(magic);
584            std::fs::write(&path, &contents).unwrap();
585
586            let detected =
587                disk::detect_image_type(&std::fs::File::open(&path).unwrap(), false).unwrap();
588
589            // When the format parser is compiled in, auto-detection invokes it and rejects the
590            // truncated header.
591            let auto_opt = DiskOption {
592                path: path.clone(),
593                read_only: true,
594                sparse: false,
595                lock: false,
596                format: DiskFormat::Auto,
597                ..Default::default()
598            };
599            if detected != disk::ImageType::Raw {
600                assert!(
601                    auto_opt.open().is_err(),
602                    "expected auto-detection to parse magic {magic:?}"
603                );
604            }
605
606            // Explicit raw format bypasses header detection and exposes the raw bytes directly.
607            let raw_opt = DiskOption {
608                format: DiskFormat::Raw,
609                ..auto_opt
610            };
611            let disk = raw_opt.open().unwrap();
612            assert_eq!(disk.get_len().unwrap(), 4096);
613
614            let mut read_back = vec![0u8; magic.len()];
615            disk.read_exact_at_volatile(VolatileSlice::new(&mut read_back), 0)
616                .unwrap();
617            assert_eq!(read_back.as_slice(), *magic);
618        }
619    }
620
621    #[test]
622    fn diskoption_serialize_deserialize() {
623        // With id == None
624        let original = DiskOption {
625            path: "./rootfs".into(),
626            ..Default::default()
627        };
628        let json = serde_json::to_string(&original).unwrap();
629        let deserialized = serde_json::from_str(&json).unwrap();
630        assert_eq!(original, deserialized);
631
632        // With id == Some
633        let original = DiskOption {
634            path: "./rootfs".into(),
635            id: Some(*b"BLK\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"),
636            async_executor: Some(ExecutorKind::default()),
637            format: DiskFormat::Raw,
638            ..Default::default()
639        };
640        let json = serde_json::to_string(&original).unwrap();
641        let deserialized = serde_json::from_str(&json).unwrap();
642        assert_eq!(original, deserialized);
643
644        // With id taking all the available space.
645        let original = DiskOption {
646            path: "./rootfs".into(),
647            id: Some(*b"QWERTYUIOPASDFGHJKL:"),
648            async_executor: Some(ExecutorKind::default()),
649            ..Default::default()
650        };
651        let json = serde_json::to_string(&original).unwrap();
652        let deserialized = serde_json::from_str(&json).unwrap();
653        assert_eq!(original, deserialized);
654    }
655}