John Hubbard
2025-Aug-19  03:11 UTC
[PATCH v3 1/3] rust: pci: provide access to PCI Class, subclass, implementation values
Allow callers to write Class::STORAGE_SCSI instead of
bindings::PCI_CLASS_STORAGE_SCSI, for example.
New APIs:
    Class::STORAGE_SCSI, Class::NETWORK_ETHERNET, etc.
    Class::as_u32()
    Class: TryFrom<u32> for Class
    Class::MASK_FULL, MASK_CLASS_SUBCLASS
    DeviceId::from_class_and_vendor()
    Device::pci_class_code_raw(), pci_class()
Cc: Danilo Krummrich <dakr at kernel.org>
Cc: Alexandre Courbot <acourbot at nvidia.com>
Signed-off-by: John Hubbard <jhubbard at nvidia.com>
---
 rust/kernel/pci.rs | 227 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 227 insertions(+)
diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 887ee611b553..bd34b1a54ecc 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -23,6 +23,204 @@
 };
 use kernel::prelude::*;
 
+/// PCI device class codes. Each entry contains the full 24-bit PCI
+/// class code (base class in bits 23-16, subclass in bits 15-8,
+/// programming interface in bits 7-0).
+///
+/// # Examples
+///
+/// ```
+/// # use kernel::{device::Core, pci::{self, Class}, prelude::*};
+/// fn probe_device(pdev: &pci::Device<Core>) -> Result<()>
{
+///     // Get the PCI class for this device
+///     let pci_class = pdev.pci_class();
+///     dev_info!(
+///         pdev.as_ref(),
+///         "Detected PCI class: (0x{:06x})\n",
+///         pci_class.as_u32()
+///     );
+///     Ok(())
+/// }
+/// ```
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(transparent)]
+pub struct Class(u32);
+
+macro_rules! define_all_pci_classes {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self =
Self(Self::to_24bit_class($binding));
+            )+
+        }
+
+        /// Try to convert a raw 24-bit class code value to a `Class`.
+        /// Returns `ENODEV` if the value doesn't match any known PCI Class
code.
+        impl TryFrom<u32> for Class {
+            type Error = Error;
+
+            fn try_from(value: u32) -> Result<Self, Self::Error> {
+                match value {
+                    $(x if x == Self::$variant.0 => Ok(Self::$variant),)+
+                    _ => Err(ENODEV),
+                }
+            }
+        }
+    };
+}
+
+impl Class {
+    /// Match the full class code.
+    pub const MASK_FULL: u32 = 0xffffff;
+
+    /// Match the upper 16 bits of the class code (base class and subclass
only).
+    pub const MASK_CLASS_SUBCLASS: u32 = 0xffff00;
+
+    /// Get the raw 24-bit class code value.
+    pub const fn as_u32(self) -> u32 {
+        self.0
+    }
+
+    // Converts a PCI class constant to 24-bit format.
+    //
+    // Many device drivers use only the upper 16 bits (base class and
subclass), but some
+    // use the full 24 bits. In order to support both cases, store the class
code as a 24-bit
+    // value, where 16-bit values are shifted up 8 bits.
+    const fn to_24bit_class(val: u32) -> u32 {
+        if val > 0xFFFF {
+            val
+        } else {
+            val << 8
+        }
+    }
+}
+
+define_all_pci_classes! {
+    NOT_DEFINED                = bindings::PCI_CLASS_NOT_DEFINED,              
// 0x000000
+    NOT_DEFINED_VGA            = bindings::PCI_CLASS_NOT_DEFINED_VGA,          
// 0x000100
+
+    STORAGE_SCSI               = bindings::PCI_CLASS_STORAGE_SCSI,             
// 0x010000
+    STORAGE_IDE                = bindings::PCI_CLASS_STORAGE_IDE,              
// 0x010100
+    STORAGE_FLOPPY             = bindings::PCI_CLASS_STORAGE_FLOPPY,           
// 0x010200
+    STORAGE_IPI                = bindings::PCI_CLASS_STORAGE_IPI,              
// 0x010300
+    STORAGE_RAID               = bindings::PCI_CLASS_STORAGE_RAID,             
// 0x010400
+    STORAGE_SATA               = bindings::PCI_CLASS_STORAGE_SATA,             
// 0x010600
+    STORAGE_SATA_AHCI          = bindings::PCI_CLASS_STORAGE_SATA_AHCI,        
// 0x010601
+    STORAGE_SAS                = bindings::PCI_CLASS_STORAGE_SAS,              
// 0x010700
+    STORAGE_EXPRESS            = bindings::PCI_CLASS_STORAGE_EXPRESS,          
// 0x010802
+    STORAGE_OTHER              = bindings::PCI_CLASS_STORAGE_OTHER,            
// 0x018000
+
+    NETWORK_ETHERNET           = bindings::PCI_CLASS_NETWORK_ETHERNET,         
// 0x020000
+    NETWORK_TOKEN_RING         = bindings::PCI_CLASS_NETWORK_TOKEN_RING,       
// 0x020100
+    NETWORK_FDDI               = bindings::PCI_CLASS_NETWORK_FDDI,             
// 0x020200
+    NETWORK_ATM                = bindings::PCI_CLASS_NETWORK_ATM,              
// 0x020300
+    NETWORK_OTHER              = bindings::PCI_CLASS_NETWORK_OTHER,            
// 0x028000
+
+    DISPLAY_VGA                = bindings::PCI_CLASS_DISPLAY_VGA,              
// 0x030000
+    DISPLAY_XGA                = bindings::PCI_CLASS_DISPLAY_XGA,              
// 0x030100
+    DISPLAY_3D                 = bindings::PCI_CLASS_DISPLAY_3D,               
// 0x030200
+    DISPLAY_OTHER              = bindings::PCI_CLASS_DISPLAY_OTHER,            
// 0x038000
+
+    MULTIMEDIA_VIDEO           = bindings::PCI_CLASS_MULTIMEDIA_VIDEO,         
// 0x040000
+    MULTIMEDIA_AUDIO           = bindings::PCI_CLASS_MULTIMEDIA_AUDIO,         
// 0x040100
+    MULTIMEDIA_PHONE           = bindings::PCI_CLASS_MULTIMEDIA_PHONE,         
// 0x040200
+    MULTIMEDIA_HD_AUDIO        = bindings::PCI_CLASS_MULTIMEDIA_HD_AUDIO,      
// 0x040300
+    MULTIMEDIA_OTHER           = bindings::PCI_CLASS_MULTIMEDIA_OTHER,         
// 0x048000
+
+    MEMORY_RAM                 = bindings::PCI_CLASS_MEMORY_RAM,               
// 0x050000
+    MEMORY_FLASH               = bindings::PCI_CLASS_MEMORY_FLASH,             
// 0x050100
+    MEMORY_CXL                 = bindings::PCI_CLASS_MEMORY_CXL,               
// 0x050200
+    MEMORY_OTHER               = bindings::PCI_CLASS_MEMORY_OTHER,             
// 0x058000
+
+    BRIDGE_HOST                = bindings::PCI_CLASS_BRIDGE_HOST,              
// 0x060000
+    BRIDGE_ISA                 = bindings::PCI_CLASS_BRIDGE_ISA,               
// 0x060100
+    BRIDGE_EISA                = bindings::PCI_CLASS_BRIDGE_EISA,              
// 0x060200
+    BRIDGE_MC                  = bindings::PCI_CLASS_BRIDGE_MC,                
// 0x060300
+    BRIDGE_PCI_NORMAL          = bindings::PCI_CLASS_BRIDGE_PCI_NORMAL,        
// 0x060400
+    BRIDGE_PCI_SUBTRACTIVE     = bindings::PCI_CLASS_BRIDGE_PCI_SUBTRACTIVE,   
// 0x060401
+    BRIDGE_PCMCIA              = bindings::PCI_CLASS_BRIDGE_PCMCIA,            
// 0x060500
+    BRIDGE_NUBUS               = bindings::PCI_CLASS_BRIDGE_NUBUS,             
// 0x060600
+    BRIDGE_CARDBUS             = bindings::PCI_CLASS_BRIDGE_CARDBUS,           
// 0x060700
+    BRIDGE_RACEWAY             = bindings::PCI_CLASS_BRIDGE_RACEWAY,           
// 0x060800
+    BRIDGE_OTHER               = bindings::PCI_CLASS_BRIDGE_OTHER,             
// 0x068000
+
+    COMMUNICATION_SERIAL       = bindings::PCI_CLASS_COMMUNICATION_SERIAL,     
// 0x070000
+    COMMUNICATION_PARALLEL     = bindings::PCI_CLASS_COMMUNICATION_PARALLEL,   
// 0x070100
+    COMMUNICATION_MULTISERIAL  = bindings::PCI_CLASS_COMMUNICATION_MULTISERIAL,
// 0x070200
+    COMMUNICATION_MODEM        = bindings::PCI_CLASS_COMMUNICATION_MODEM,      
// 0x070300
+    COMMUNICATION_OTHER        = bindings::PCI_CLASS_COMMUNICATION_OTHER,      
// 0x078000
+
+    SYSTEM_PIC                 = bindings::PCI_CLASS_SYSTEM_PIC,               
// 0x080000
+    SYSTEM_PIC_IOAPIC          = bindings::PCI_CLASS_SYSTEM_PIC_IOAPIC,        
// 0x080010
+    SYSTEM_PIC_IOXAPIC         = bindings::PCI_CLASS_SYSTEM_PIC_IOXAPIC,       
// 0x080020
+    SYSTEM_DMA                 = bindings::PCI_CLASS_SYSTEM_DMA,               
// 0x080100
+    SYSTEM_TIMER               = bindings::PCI_CLASS_SYSTEM_TIMER,             
// 0x080200
+    SYSTEM_RTC                 = bindings::PCI_CLASS_SYSTEM_RTC,               
// 0x080300
+    SYSTEM_PCI_HOTPLUG         = bindings::PCI_CLASS_SYSTEM_PCI_HOTPLUG,       
// 0x080400
+    SYSTEM_SDHCI               = bindings::PCI_CLASS_SYSTEM_SDHCI,             
// 0x080500
+    SYSTEM_RCEC                = bindings::PCI_CLASS_SYSTEM_RCEC,              
// 0x080700
+    SYSTEM_OTHER               = bindings::PCI_CLASS_SYSTEM_OTHER,             
// 0x088000
+
+    INPUT_KEYBOARD             = bindings::PCI_CLASS_INPUT_KEYBOARD,           
// 0x090000
+    INPUT_PEN                  = bindings::PCI_CLASS_INPUT_PEN,                
// 0x090100
+    INPUT_MOUSE                = bindings::PCI_CLASS_INPUT_MOUSE,              
// 0x090200
+    INPUT_SCANNER              = bindings::PCI_CLASS_INPUT_SCANNER,            
// 0x090300
+    INPUT_GAMEPORT             = bindings::PCI_CLASS_INPUT_GAMEPORT,           
// 0x090400
+    INPUT_OTHER                = bindings::PCI_CLASS_INPUT_OTHER,              
// 0x098000
+
+    DOCKING_GENERIC            = bindings::PCI_CLASS_DOCKING_GENERIC,          
// 0x0a0000
+    DOCKING_OTHER              = bindings::PCI_CLASS_DOCKING_OTHER,            
// 0x0a8000
+
+    PROCESSOR_386              = bindings::PCI_CLASS_PROCESSOR_386,            
// 0x0b0000
+    PROCESSOR_486              = bindings::PCI_CLASS_PROCESSOR_486,            
// 0x0b0100
+    PROCESSOR_PENTIUM          = bindings::PCI_CLASS_PROCESSOR_PENTIUM,        
// 0x0b0200
+    PROCESSOR_ALPHA            = bindings::PCI_CLASS_PROCESSOR_ALPHA,          
// 0x0b1000
+    PROCESSOR_POWERPC          = bindings::PCI_CLASS_PROCESSOR_POWERPC,        
// 0x0b2000
+    PROCESSOR_MIPS             = bindings::PCI_CLASS_PROCESSOR_MIPS,           
// 0x0b3000
+    PROCESSOR_CO               = bindings::PCI_CLASS_PROCESSOR_CO,             
// 0x0b4000
+
+    SERIAL_FIREWIRE            = bindings::PCI_CLASS_SERIAL_FIREWIRE,          
// 0x0c0000
+    SERIAL_FIREWIRE_OHCI       = bindings::PCI_CLASS_SERIAL_FIREWIRE_OHCI,     
// 0x0c0010
+    SERIAL_ACCESS              = bindings::PCI_CLASS_SERIAL_ACCESS,            
// 0x0c0100
+    SERIAL_SSA                 = bindings::PCI_CLASS_SERIAL_SSA,               
// 0x0c0200
+    SERIAL_USB_UHCI            = bindings::PCI_CLASS_SERIAL_USB_UHCI,          
// 0x0c0300
+    SERIAL_USB_OHCI            = bindings::PCI_CLASS_SERIAL_USB_OHCI,          
// 0x0c0310
+    SERIAL_USB_EHCI            = bindings::PCI_CLASS_SERIAL_USB_EHCI,          
// 0x0c0320
+    SERIAL_USB_XHCI            = bindings::PCI_CLASS_SERIAL_USB_XHCI,          
// 0x0c0330
+    SERIAL_USB_CDNS            = bindings::PCI_CLASS_SERIAL_USB_CDNS,          
// 0x0c0380
+    SERIAL_USB_DEVICE          = bindings::PCI_CLASS_SERIAL_USB_DEVICE,        
// 0x0c03fe
+    SERIAL_FIBER               = bindings::PCI_CLASS_SERIAL_FIBER,             
// 0x0c0400
+    SERIAL_SMBUS               = bindings::PCI_CLASS_SERIAL_SMBUS,             
// 0x0c0500
+    SERIAL_IPMI_SMIC           = bindings::PCI_CLASS_SERIAL_IPMI_SMIC,         
// 0x0c0700
+    SERIAL_IPMI_KCS            = bindings::PCI_CLASS_SERIAL_IPMI_KCS,          
// 0x0c0701
+    SERIAL_IPMI_BT             = bindings::PCI_CLASS_SERIAL_IPMI_BT,           
// 0x0c0702
+
+    WIRELESS_RF_CONTROLLER     = bindings::PCI_CLASS_WIRELESS_RF_CONTROLLER,   
// 0x0d1000
+    WIRELESS_WHCI              = bindings::PCI_CLASS_WIRELESS_WHCI,            
// 0x0d1010
+
+    INTELLIGENT_I2O            = bindings::PCI_CLASS_INTELLIGENT_I2O,          
// 0x0e0000
+
+    SATELLITE_TV               = bindings::PCI_CLASS_SATELLITE_TV,             
// 0x0f0000
+    SATELLITE_AUDIO            = bindings::PCI_CLASS_SATELLITE_AUDIO,          
// 0x0f0100
+    SATELLITE_VOICE            = bindings::PCI_CLASS_SATELLITE_VOICE,          
// 0x0f0300
+    SATELLITE_DATA             = bindings::PCI_CLASS_SATELLITE_DATA,           
// 0x0f0400
+
+    CRYPT_NETWORK              = bindings::PCI_CLASS_CRYPT_NETWORK,            
// 0x100000
+    CRYPT_ENTERTAINMENT        = bindings::PCI_CLASS_CRYPT_ENTERTAINMENT,      
// 0x100100
+    CRYPT_OTHER                = bindings::PCI_CLASS_CRYPT_OTHER,              
// 0x108000
+
+    SP_DPIO                    = bindings::PCI_CLASS_SP_DPIO,                  
// 0x110000
+    SP_OTHER                   = bindings::PCI_CLASS_SP_OTHER,                 
// 0x118000
+
+    ACCELERATOR_PROCESSING     = bindings::PCI_CLASS_ACCELERATOR_PROCESSING,   
// 0x120000
+
+    OTHERS                     = bindings::PCI_CLASS_OTHERS,                   
// 0xff0000
+}
+
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
 
@@ -157,6 +355,23 @@ pub const fn from_class(class: u32, class_mask: u32) ->
Self {
             override_only: 0,
         })
     }
+
+    /// Create a new `pci::DeviceId` from a class number, mask, and specific
vendor.
+    ///
+    /// This is more targeted than [`DeviceId::from_class`]: in addition to
matching by Vendor, it
+    /// also matches the PCI Class (up to the entire 24 bits, depending on the
mask).
+    pub const fn from_class_and_vendor(class: Class, class_mask: u32, vendor:
u32) -> Self {
+        Self(bindings::pci_device_id {
+            vendor,
+            device: DeviceId::PCI_ANY_ID,
+            subvendor: DeviceId::PCI_ANY_ID,
+            subdevice: DeviceId::PCI_ANY_ID,
+            class: class.as_u32(),
+            class_mask,
+            driver_data: 0,
+            override_only: 0,
+        })
+    }
 }
 
 // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id`
and does not add
@@ -410,6 +625,18 @@ pub fn resource_len(&self, bar: u32) ->
Result<bindings::resource_size_t> {
         // - by its type invariant `self.as_raw` is always a valid pointer to a
`struct pci_dev`.
         Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?)
})
     }
+
+    /// Returns the full 24-bit PCI class code as stored in hardware.
+    /// This includes base class, subclass, and programming interface.
+    pub fn pci_class_code_raw(&self) -> u32 {
+        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
+        unsafe { (*self.as_raw()).class }
+    }
+
+    /// Returns the PCI class as a `Class` struct.
+    pub fn pci_class(&self) -> Class {
+        Class(self.pci_class_code_raw())
+    }
 }
 
 impl Device<device::Bound> {
-- 
2.50.1
Danilo Krummrich
2025-Aug-19  09:09 UTC
[PATCH v3 1/3] rust: pci: provide access to PCI Class, subclass, implementation values
On Tue Aug 19, 2025 at 5:11 AM CEST, John Hubbard wrote:> +/// PCI device class codes. Each entry contains the full 24-bit PCI > +/// class code (base class in bits 23-16, subclass in bits 15-8, > +/// programming interface in bits 7-0). > +/// > +/// # Examples > +/// > +/// ``` > +/// # use kernel::{device::Core, pci::{self, Class}, prelude::*}; > +/// fn probe_device(pdev: &pci::Device<Core>) -> Result<()> { > +/// // Get the PCI class for this device > +/// let pci_class = pdev.pci_class(); > +/// dev_info!( > +/// pdev.as_ref(), > +/// "Detected PCI class: (0x{:06x})\n", > +/// pci_class.as_u32() > +/// );Maybe a bit cleaner to implement Display for pci::Class?> +/// Ok(()) > +/// } > +/// ``` > +#[derive(Debug, Clone, Copy, PartialEq, Eq)] > +#[repr(transparent)] > +pub struct Class(u32);[ Class impl and lots of pci class ids... ] I think we should move all this to a new Rust module (rust/kernel/pci/class.rs) to keep this file reasonably small. You can add use self::class::Class; use self::class::ClassMask; in this file to make it appear as e.g. kernel::pci::Class. Sorry I didn't mention this in the previous version.> /// An adapter for the registration of PCI drivers. > pub struct Adapter<T: Driver>(T); > > @@ -157,6 +355,23 @@ pub const fn from_class(class: u32, class_mask: u32) -> Self { > override_only: 0, > }) > } > + > + /// Create a new `pci::DeviceId` from a class number, mask, and specific vendor. > + /// > + /// This is more targeted than [`DeviceId::from_class`]: in addition to matching by Vendor, it > + /// also matches the PCI Class (up to the entire 24 bits, depending on the mask). > + pub const fn from_class_and_vendor(class: Class, class_mask: u32, vendor: u32) -> Self {I think it would be good if class_mask would be a new type ClassMask that only has the constants that are applicable for this field, i.e. MASK_FULL and MASK_CLASS_SUBCLASS.> + Self(bindings::pci_device_id { > + vendor, > + device: DeviceId::PCI_ANY_ID, > + subvendor: DeviceId::PCI_ANY_ID, > + subdevice: DeviceId::PCI_ANY_ID, > + class: class.as_u32(), > + class_mask, > + driver_data: 0, > + override_only: 0, > + }) > + } > } > > // SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `pci_device_id` and does not add > @@ -410,6 +625,18 @@ pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { > // - by its type invariant `self.as_raw` is always a valid pointer to a `struct pci_dev`. > Ok(unsafe { bindings::pci_resource_len(self.as_raw(), bar.try_into()?) }) > } > + > + /// Returns the full 24-bit PCI class code as stored in hardware. > + /// This includes base class, subclass, and programming interface. > + pub fn pci_class_code_raw(&self) -> u32 { > + // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`. > + unsafe { (*self.as_raw()).class } > + }Do we need this method? I think drivers can just call pdev.pci_class().as_u32() instead (which we could also name as_raw()).> + /// Returns the PCI class as a `Class` struct. > + pub fn pci_class(&self) -> Class { > + Class(self.pci_class_code_raw()) > + }This is good! At a first glance the name looks a bit odd or redundant, but people would clearly expect something different when this is called as pdev.class() (i.e. a struct class representation).