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