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