device_virtio_scsi/
lib.rs

1// Copyright 2023 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
5use std::path::PathBuf;
6
7use anyhow::Context;
8use devices::virtio::VirtioDevice;
9use devices::VirtioDeviceArgs;
10use devices::VirtioDeviceModule;
11use serde::Deserialize;
12use serde::Serialize;
13
14pub(crate) mod sys;
15
16pub mod commands;
17pub mod constants;
18mod device;
19
20pub use device::Controller;
21pub use device::DiskConfig;
22
23fn scsi_option_lock_default() -> bool {
24    true
25}
26fn scsi_option_block_size_default() -> u32 {
27    512
28}
29
30/// Parameters for setting up a SCSI device.
31#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, serde_keyvalue::FromKeyValues)]
32#[serde(deny_unknown_fields, rename_all = "kebab-case")]
33pub struct ScsiOption {
34    // Path to the SCSI image.
35    pub path: PathBuf,
36    // Indicates whether the device is ready only.
37    #[serde(default, rename = "ro")]
38    pub read_only: bool,
39    /// Whether to lock the disk files. Uses flock on Unix and FILE_SHARE_* flags on Windows.
40    #[serde(default = "scsi_option_lock_default")]
41    pub lock: bool,
42    // The block size of the device.
43    #[serde(default = "scsi_option_block_size_default")]
44    pub block_size: u32,
45    /// Whether this scsi device should be the root device. Can only be set once. Only useful for
46    /// adding specific command-line options.
47    #[serde(default)]
48    pub root: bool,
49}
50
51/// Module for creating a Virtio SCSI controller device.
52#[derive(Serialize, Deserialize)]
53pub struct VirtioScsiModule {
54    pub disks: Vec<ScsiOption>,
55}
56
57impl VirtioScsiModule {
58    pub fn new(disks: Vec<ScsiOption>) -> Self {
59        Self { disks }
60    }
61}
62
63impl VirtioDeviceModule for VirtioScsiModule {
64    fn sort_name(&self) -> &'static str {
65        "scsi"
66    }
67
68    fn create(&self, args: &mut VirtioDeviceArgs<'_>) -> anyhow::Result<Box<dyn VirtioDevice>> {
69        let base_features = devices::virtio::base_features(args.protection_type);
70        let disks = self
71            .disks
72            .iter()
73            .map(|op| {
74                base::info!("Trying to attach a scsi device: {}", op.path.display());
75                Ok(DiskConfig {
76                    file: op.open()?,
77                    block_size: op.block_size,
78                    read_only: op.read_only,
79                })
80            })
81            .collect::<anyhow::Result<Vec<_>>>()?;
82        let controller =
83            Controller::new(base_features, disks).context("failed to create a scsi controller")?;
84        Ok(Box::new(controller))
85    }
86
87    #[cfg(any(target_os = "android", target_os = "linux"))]
88    fn create_jail(
89        &self,
90        jail_config: Option<&jail::JailConfig>,
91    ) -> anyhow::Result<Option<minijail::Minijail>> {
92        let jail = jail::simple_jail(
93            jail_config,
94            &devices::virtio::VirtioDeviceType::Regular.seccomp_policy_file("scsi"),
95        )?;
96        Ok(jail)
97    }
98}
99
100#[cfg(test)]
101impl Default for ScsiOption {
102    fn default() -> Self {
103        Self {
104            path: PathBuf::new(),
105            read_only: false,
106            lock: scsi_option_lock_default(),
107            block_size: scsi_option_block_size_default(),
108            root: false,
109        }
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use std::path::Path;
116
117    use serde_keyvalue::from_key_values;
118
119    use super::*;
120
121    #[test]
122    fn parse_scsi_options() {
123        let scsi_option = from_key_values::<ScsiOption>("/path/to/image").unwrap();
124        assert_eq!(
125            scsi_option,
126            ScsiOption {
127                path: Path::new("/path/to/image").to_path_buf(),
128                ..Default::default()
129            }
130        );
131
132        let scsi_option = from_key_values::<ScsiOption>("/path/to/image,ro").unwrap();
133        assert_eq!(
134            scsi_option,
135            ScsiOption {
136                path: Path::new("/path/to/image").to_path_buf(),
137                read_only: true,
138                ..Default::default()
139            }
140        );
141
142        let scsi_option = from_key_values::<ScsiOption>("/path/to/image,block-size=1024").unwrap();
143        assert_eq!(
144            scsi_option,
145            ScsiOption {
146                path: Path::new("/path/to/image").to_path_buf(),
147                block_size: 1024,
148                ..Default::default()
149            }
150        );
151
152        let scsi_option =
153            from_key_values::<ScsiOption>("/path/to/image,block-size=1024,root").unwrap();
154        assert_eq!(
155            scsi_option,
156            ScsiOption {
157                path: Path::new("/path/to/image").to_path_buf(),
158                block_size: 1024,
159                root: true,
160                ..Default::default()
161            }
162        );
163    }
164}