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    HvcDevicePowerManager = 25,
34    Mock = 0xff,
35}
36
37/// A wrapper structure for pci device and vendor id.
38#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub struct PciId {
40    vendor_id: u16,
41    device_id: u16,
42}
43
44impl PciId {
45    pub fn new(vendor_id: u16, device_id: u16) -> Self {
46        Self {
47            vendor_id,
48            device_id,
49        }
50    }
51}
52
53impl From<PciId> for u32 {
54    fn from(pci_id: PciId) -> Self {
55        // vendor ID is the lower 16 bits and device id is the upper 16 bits
56        pci_id.vendor_id as u32 | (pci_id.device_id as u32) << 16
57    }
58}
59
60impl From<u32> for PciId {
61    fn from(value: u32) -> Self {
62        let vendor_id = (value & 0xFFFF) as u16;
63        let device_id = (value >> 16) as u16;
64        Self::new(vendor_id, device_id)
65    }
66}
67
68#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
69pub enum DeviceId {
70    /// PCI Device, use its PciId directly.
71    PciDeviceId(PciId),
72    /// Platform device, use a unique Id.
73    PlatformDeviceId(PlatformDeviceId),
74}
75
76impl From<PciId> for DeviceId {
77    fn from(v: PciId) -> Self {
78        Self::PciDeviceId(v)
79    }
80}
81
82impl From<PlatformDeviceId> for DeviceId {
83    fn from(v: PlatformDeviceId) -> Self {
84        Self::PlatformDeviceId(v)
85    }
86}
87
88impl DeviceId {
89    pub fn metrics_id(self) -> u32 {
90        match self {
91            DeviceId::PciDeviceId(pci_id) => pci_id.into(),
92            DeviceId::PlatformDeviceId(id) => {
93                static_assertions::const_assert!(std::mem::size_of::<PlatformDeviceId>() <= 2);
94                0xFFFF0000 | id as u32
95            }
96        }
97    }
98}