vm_control/
device_id.rs

1// Copyright 2025 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//! Device ID types.
6
7#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8pub enum PlatformDeviceId {
9    Pit = 1,
10    Pic = 2,
11    Ioapic = 3,
12    Serial = 4,
13    Cmos = 5,
14    I8042 = 6,
15    Pl030 = 7,
16    ACPIPMResource = 8,
17    GoldfishBattery = 9,
18    DebugConsole = 10,
19    ProxyDevice = 11,
20    VfioPlatformDevice = 12,
21    DirectGsi = 13,
22    DirectIo = 14,
23    DirectMmio = 15,
24    UserspaceIrqChip = 16,
25    VmWatchdog = 17,
26    Pflash = 18,
27    VirtioMmio = 19,
28    AcAdapter = 20,
29    VirtualPmc = 21,
30    VirtCpufreq = 22,
31    FwCfg = 23,
32    SmcccTrng = 24,
33    Mock = 0xff,
34}
35
36/// A wrapper structure for pci device and vendor id.
37#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
38pub struct PciId {
39    vendor_id: u16,
40    device_id: u16,
41}
42
43impl PciId {
44    pub fn new(vendor_id: u16, device_id: u16) -> Self {
45        Self {
46            vendor_id,
47            device_id,
48        }
49    }
50}
51
52impl From<PciId> for u32 {
53    fn from(pci_id: PciId) -> Self {
54        // vendor ID is the lower 16 bits and device id is the upper 16 bits
55        pci_id.vendor_id as u32 | (pci_id.device_id as u32) << 16
56    }
57}
58
59impl From<u32> for PciId {
60    fn from(value: u32) -> Self {
61        let vendor_id = (value & 0xFFFF) as u16;
62        let device_id = (value >> 16) as u16;
63        Self::new(vendor_id, device_id)
64    }
65}
66
67#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
68pub enum DeviceId {
69    /// PCI Device, use its PciId directly.
70    PciDeviceId(PciId),
71    /// Platform device, use a unique Id.
72    PlatformDeviceId(PlatformDeviceId),
73}
74
75impl From<PciId> for DeviceId {
76    fn from(v: PciId) -> Self {
77        Self::PciDeviceId(v)
78    }
79}
80
81impl From<PlatformDeviceId> for DeviceId {
82    fn from(v: PlatformDeviceId) -> Self {
83        Self::PlatformDeviceId(v)
84    }
85}
86
87impl DeviceId {
88    pub fn metrics_id(self) -> u32 {
89        match self {
90            DeviceId::PciDeviceId(pci_id) => pci_id.into(),
91            DeviceId::PlatformDeviceId(id) => {
92                static_assertions::const_assert!(std::mem::size_of::<PlatformDeviceId>() <= 2);
93                0xFFFF0000 | id as u32
94            }
95        }
96    }
97}