devices/
device_module.rs

1// Copyright 2026 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 anyhow::Result;
6use hypervisor::ProtectionType;
7use hypervisor::Vm;
8#[cfg(any(target_os = "android", target_os = "linux"))]
9use jail::JailConfig;
10#[cfg(any(target_os = "android", target_os = "linux"))]
11pub use minijail::Minijail;
12use resources::SystemAllocator;
13use vm_control::AnyControlTube;
14
15use crate::virtio::VirtioDevice;
16
17/// Arguments to `VirtioDeviceModule::create`.
18pub struct VirtioDeviceArgs<'a> {
19    pub vm: &'a dyn Vm,
20    pub resources: &'a mut SystemAllocator,
21    pub add_control_tube: &'a mut dyn FnMut(AnyControlTube),
22    pub protection_type: ProtectionType,
23}
24
25/// A module that creates a single virtio device and provides hooks to integrate it into the VMM.
26///
27/// The goal of this API is to allow nearly all of a device's code to live together, including
28/// logic that was historically spread across the code base, like wiring up control tubes. To add a
29/// new device, you should just need to write one of these modules, add cmdline params, and insert
30/// the module into `crosvm::config::Config`.
31///
32/// Generally, types implementing this trait should only contain data derived from the cmdline
33/// arguments. If a device needs, say, some information from the hypervisor, then pass that data
34/// through `VirtioDeviceArgs`.
35///
36/// Requires serde because `Config` requires serde (for Windows).
37pub trait VirtioDeviceModule: serde::Serialize + serde::de::DeserializeOwned {
38    /// Name of the device used to determine init processing order.
39    fn sort_name(&self) -> &'static str;
40
41    /// Create an instance of this device.
42    fn create(&self, cx: &mut VirtioDeviceArgs<'_>) -> Result<Box<dyn VirtioDevice>>;
43
44    /// Optionally create a jail for this device.
45    #[cfg(any(target_os = "android", target_os = "linux"))]
46    fn create_jail(&self, jail_config: &JailConfig) -> Result<Option<Minijail>>;
47}