Skip to contentSkip to conversation

rust, nova-core: PCI Class, Vendor support

PATCH Superseded John Hubbard 5 participants 15 messages Aug 18, 2025 – Aug 22, 2025

Subsystems (8)
DRM drivers PCI Rust DRM Rust +4 more subsystems

v2 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
#0 lore raw

v2 cover rust, nova-core: PCI Class, Vendor support

Hi Danilo and all,

I'm quite pleased with how this ended up! The new code in nova-core is nicely readable, and now we've paved the way for other PCI device drivers as well.

Quite a few "use kernel::bindings" lines were removed, as a result.

Changes since v1:

1) Use the pci_device_table for filtering, instead of open-coding filters in the .probe() callback.

2) Add PCI Class (class, subclass, implementation) and PCI Vendor to Rust for Linux.

3) Rebased onto the latest nova-next branch, which is here:
https://gitlab.freedesktop.org/drm/nova.git

v1 is here:

    https://lore.kernel.org/[email protected]
Cc Danilo Krummrich <[email protected]>

John Hubbard (3):
rust: pci: provide access to PCI Class, subclass, implementation
values
gpu: nova-core: avoid probing non-display/compute PCI functions
rust: pci: provide access to PCI Vendor values

 drivers/gpu/nova-core/driver.rs       |  33 +-
 rust/kernel/pci.rs                    | 525 +++++++++++++++++++++++++-
 samples/rust/rust_dma.rs              |   3 +-
 samples/rust/rust_driver_auxiliary.rs |   4 +-
 samples/rust/rust_driver_pci.rs       |   4 +-
 5 files changed, 557 insertions(+), 12 deletions(-)

base-commit: 0dfc23ac2c5b3a62ab27fb9b6ee582b4bb5ce33c

Signature · 1 line
2.50.1
#1 lore raw

PATCH v2 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::from_u32(), as_u32()
    Class::MASK_FULL, MASK_CLASS_SUBCLASS
    DeviceId::from_class_and_vendor()
    Device::class_code_raw(), class_enum()
Cc Danilo Krummrich <[email protected]>
---
 rust/kernel/pci.rs | 202 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 202 insertions(+)
rust/kernel/pci.rs +202 -0
index 887ee611b553..9caa1d342d52 100644
@@ -23,6 +23,179 @@
 };
 use kernel::prelude::*;
 
+macro_rules! define_all_pci_classes {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// 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 }
+        }
+
+        /// 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).
+        ///
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Class(u32);
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(to_24bit_class($binding));
+            )+
+
+            /// 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;
+
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 24-bit class code value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
+
+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 +330,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 +600,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 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, or `None` if the class code is invalid.
+    pub fn class_enum(&self) -> Option<Class> {
+        Class::from_u32(self.class_code_raw())
+    }
 }
 
 impl Device<device::Bound> {
Signature · 1 line
2.50.1
#2 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

Quoted 26 lines · John Hubbard

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::from_u32(), as_u32()
    Class::MASK_FULL, MASK_CLASS_SUBCLASS
    DeviceId::from_class_and_vendor()
    Device::class_code_raw(), class_enum()
Cc Danilo Krummrich <[email protected]>
---
 rust/kernel/pci.rs | 202 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 202 insertions(+)
rust/kernel/pci.rs +2 -0
index 887ee611b553..9caa1d342d52 100644
@@ -23,6 +23,179 @@
 };
 use kernel::prelude::*;
 
+macro_rules! define_all_pci_classes {
+    (

rust/kernel/pci.rs line 37

Quoted 10 lines
rust/kernel/pci.rs +10 -0
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// 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 }
+        }

This convenience function doesn't look like it needs to be defined inside the macro.

rust/kernel/pci.rs line 46

Quoted 9 lines
rust/kernel/pci.rs +9 -0
+
+        /// 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).
+        ///
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Class(u32);

Same for this struct.

rust/kernel/pci.rs line 52

Quoted 6 lines
rust/kernel/pci.rs +6 -0
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(to_24bit_class($binding));
+            )+

This obviously needs to be part of the macro...

rust/kernel/pci.rs line 58

Quoted 6 lines
rust/kernel/pci.rs +6 -0
+
+            /// 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;

But these two definitions (and as_u32 below) can again be part of their own impl block outside of it.

Quoted 5 lines
rust/kernel/pci.rs +5 -0
+
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {

rust/kernel/pci.rs line 73

Quoted 10 lines
rust/kernel/pci.rs +10 -0
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 24-bit class code value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }

So I believe that if you move the declarations that do not depend on the macro parameters outside of if, the macro's body could be limited to the following:

       impl Class {
           $(
               #[allow(missing_docs)]
               pub const $variant: Self = Self(to_24bit_class($binding));
           )+

           /// Create a `Class` from the raw class code value, or `None` if the value doesn't
           /// match any known class.
           pub fn from_u32(value: u32) -> Option<Self> {
               match value {
                   $(x if x == Self::$variant.0 => Some(Self::$variant),)+
                   _ => None,
               }
           }

Shorter macros are generally considered better. :)

#3 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

Quoted 1 line · Alexandre Courbot

On Mon Aug 18, 2025 at 10:33 AM JST, John Hubbard wrote:

...

Quoted 90 lines
Quoted 10 lines
rust/kernel/pci.rs +2 -0
index 887ee611b553..9caa1d342d52 100644
@@ -23,6 +23,179 @@
 };
 use kernel::prelude::*;
 
+macro_rules! define_all_pci_classes {
+    (

rust/kernel/pci.rs line 37

Quoted 10 lines
rust/kernel/pci.rs +10 -0
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// 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 }
+        }

This convenience function doesn't look like it needs to be defined inside the macro.

rust/kernel/pci.rs line 46

Quoted 9 lines
rust/kernel/pci.rs +9 -0
+
+        /// 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).
+        ///
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Class(u32);

Same for this struct.

rust/kernel/pci.rs line 52

Quoted 6 lines
rust/kernel/pci.rs +6 -0
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(to_24bit_class($binding));
+            )+

This obviously needs to be part of the macro...

rust/kernel/pci.rs line 58

Quoted 6 lines
rust/kernel/pci.rs +6 -0
+
+            /// 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;

But these two definitions (and as_u32 below) can again be part of their own impl block outside of it.

Quoted 5 lines
rust/kernel/pci.rs +5 -0
+
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {

rust/kernel/pci.rs line 73

Quoted 10 lines
rust/kernel/pci.rs +10 -0
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 24-bit class code value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }

So I believe that if you move the declarations that do not depend on the macro parameters outside of if, the macro's body could be limited to the following:

       impl Class {
           $(
               #[allow(missing_docs)]
               pub const $variant: Self = Self(to_24bit_class($binding));
           )+

           /// Create a `Class` from the raw class code value, or `None` if the value doesn't
           /// match any known class.
           pub fn from_u32(value: u32) -> Option<Self> {
               match value {
                   $(x if x == Self::$variant.0 => Some(Self::$variant),)+
                   _ => None,
               }
           }
Quoted 1 line

Shorter macros are generally considered better. :)

All of the above comments make sense, I'll make those changes. Thanks for the review!

thanks,

Signature · 1 line
John Hubbard
maintainer
#4 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

In reply to John Hubbard

rust/kernel/pci.rs line 67

Quoted 8 lines · John Hubbard
rust/kernel/pci.rs +8 -0
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }

Additional to the comments from Alex, I think one should be impl TryFrom<u32> for Class.

Quoted 26 lines
rust/kernel/pci.rs +19 -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 +600,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.

rust/kernel/pci.rs pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { · line 614

Quoted 10 lines
rust/kernel/pci.rs +10 -0
+    /// This includes base class, subclass, and programming interface.
+    pub fn 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, or `None` if the class code is invalid.
+    pub fn class_enum(&self) -> Option<Class> {
+        Class::from_u32(self.class_code_raw())
+    }

I don't think we have struct pci_dev instances without a valid class code, can we? Maybe we should convert infallibly here.

#5 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

Quoted 10 lines · Danilo Krummrich

rust/kernel/pci.rs line 67

Quoted 8 lines · John Hubbard
rust/kernel/pci.rs +8 -0
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
Quoted 2 lines

Additional to the comments from Alex, I think one should be impl TryFrom<u32> for Class.

Will do.

Quoted 32 lines
Quoted 32 lines
rust/kernel/pci.rs +24 -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 +600,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 class_code_raw(&self) -> u32 {
+        // SAFETY: `self.as_raw` is a valid pointer to a `struct pci_dev`.
+        unsafe { (*self.as_raw()).class }
+    }
Quoted 8 lines

rust/kernel/pci.rs pub fn resource_len(&self, bar: u32) -> Result<bindings::resource_size_t> { · line 614

Quoted 5 lines
rust/kernel/pci.rs +5 -0
+
+    /// Returns the PCI class as a `Class` struct, or `None` if the class code is invalid.
+    pub fn class_enum(&self) -> Option<Class> {
+        Class::from_u32(self.class_code_raw())
+    }

I don't think we have struct pci_dev instances without a valid class code, can we? Maybe we should convert infallibly here.

Interesting. Let me un-dizzy myself about the lifetimes here, and verify if that claim is true. :)

thanks,

Signature · 1 line
John Hubbard
Reviewed-by on v2 1/3
#6 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

In reply to John Hubbard
Quoted 131 lines · John Hubbard

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::from_u32(), as_u32()
    Class::MASK_FULL, MASK_CLASS_SUBCLASS
    DeviceId::from_class_and_vendor()
    Device::class_code_raw(), class_enum()
Cc Danilo Krummrich <[email protected]>
---
 rust/kernel/pci.rs | 202 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 202 insertions(+)
rust/kernel/pci.rs +88 -0
index 887ee611b553..9caa1d342d52 100644
@@ -23,6 +23,179 @@
 };
 use kernel::prelude::*;
 
+macro_rules! define_all_pci_classes {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// 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 }
+        }
+
+        /// 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).
+        ///
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Class(u32);
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(to_24bit_class($binding));
+            )+
+
+            /// 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;
+
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 24-bit class code value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
+
+define_all_pci_classes! {
+    NOT_DEFINED                = bindings::PCI_CLASS_NOT_DEFINED,                // 0x000000
+
+    ...
+
+    OTHERS                     = bindings::PCI_CLASS_OTHERS,                     // 0xff0000
+}
+
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
 
@@ -157,6 +330,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 +600,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 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, or `None` if the class code is invalid.
+    pub fn class_enum(&self) -> Option<Class> {
+        Class::from_u32(self.class_code_raw())
+    }
 }
 
 impl Device<device::Bound> {
Signature · 1 line
2.50.1

All of the functions could probably be #[inline]ed, though I'm not sure how much it affects the const functions, since they're already evaluated at compile-time.

#7 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

Quoted 129 lines · Elle Rhumsaa
Quoted 128 lines · John Hubbard

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::from_u32(), as_u32()
     Class::MASK_FULL, MASK_CLASS_SUBCLASS
     DeviceId::from_class_and_vendor()
     Device::class_code_raw(), class_enum()
Cc Danilo Krummrich <[email protected]>
---
  rust/kernel/pci.rs | 202 +++++++++++++++++++++++++++++++++++++++++++++
  1 file changed, 202 insertions(+)
rust/kernel/pci.rs +88 -0
index 887ee611b553..9caa1d342d52 100644
@@ -23,6 +23,179 @@
  };
  use kernel::prelude::*;
 
+macro_rules! define_all_pci_classes {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// 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 }
+        }
+
+        /// 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).
+        ///
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Class(u32);
+
+        impl Class {
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self(to_24bit_class($binding));
+            )+
+
+            /// 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;
+
+            /// Create a `Class` from the raw class code value, or `None` if the value doesn't
+            /// match any known class.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 24-bit class code value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
+
+define_all_pci_classes! {
+    NOT_DEFINED                = bindings::PCI_CLASS_NOT_DEFINED,                // 0x000000
+
+    ...
+
+    OTHERS                     = bindings::PCI_CLASS_OTHERS,                     // 0xff0000
+}
+
  /// An adapter for the registration of PCI drivers.
  pub struct Adapter<T: Driver>(T);
 
@@ -157,6 +330,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 +600,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 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, or `None` if the class code is invalid.
+    pub fn class_enum(&self) -> Option<Class> {
+        Class::from_u32(self.class_code_raw())
+    }
  }
 
Quoted 7 lines
Quoted 3 lines
rust/kernel/pci.rs +0 -0
  impl Device<device::Bound> {
Signature · 1 line
2.50.1

All of the functions could probably be #[inline]ed, though I'm not sure how much it affects the const functions, since they're already evaluated at compile-time.

These are not in a hot path, which is why the other, similar functions nearby are not inlined.

Quoted 2 lines

Thanks for the review of the series!

thanks,

Signature · 1 line
John Hubbard
#8 lore raw

Re: [PATCH v2 1/3] rust: pci: provide access to PCI Class, subclass, implementation values

In reply to Elle Rhumsaa
Quoted 4 lines · Elle Rhumsaa

All of the functions could probably be #[inline]ed, though I'm not sure how much it affects the const functions, since they're already evaluated at compile-time.

I don't think that is guaranteed unless called from a const context.

Cheers,
Miguel

#9 lore raw

PATCH v2 2/3 gpu: nova-core: avoid probing non-display/compute PCI functions

In reply to John Hubbard

NovaCore has so far been too imprecise about figuring out if .probe() has found a supported PCI PF (Physical Function). By that I mean:
.probe() sets up BAR0 (which involves a lot of very careful devres and Device<Bound> details behind the scenes). And then if it is dealing with a non-supported device such as the .1 audio PF on many GPUs, it fails out due to an unexpected BAR0 size. We have been fortunate that the BAR0 sizes are different.

Really, we should be filtering on PCI class ID instead. These days I think we can confidently pick out Nova's supported PF's via PCI class ID. And if not, then we'll revisit.

The approach here is to filter on "Display VGA" or "Display 3D", which is how PCI class IDs express "this is a modern GPU's PF".

Cc Danilo Krummrich <[email protected]>
---
 drivers/gpu/nova-core/driver.rs | 27 ++++++++++++++++++++++-----
 1 file changed, 22 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/driver.rs +22 -5
index 274989ea1fb4..4ec5b861a345 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::{auxiliary, bindings, c_str, device::Core, pci, prelude::*, sizes::SZ_16M, sync::Arc};
+use kernel::{
+    auxiliary, bindings, c_str, device::Core, pci, pci::Class, prelude::*, sizes::SZ_16M, sync::Arc,
+};
 
 use crate::gpu::Gpu;
 
@@ -18,10 +20,25 @@ pub(crate) struct NovaCore {
     PCI_TABLE,
     MODULE_PCI_TABLE,
     <NovaCore as pci::Driver>::IdInfo,
-    [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_NVIDIA, bindings::PCI_ANY_ID as u32),
-        ()
-    )]
+    [
+        // Modern NVIDIA GPUs will show up as either VGA or 3D controllers.
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_VGA,
+                Class::MASK_CLASS_SUBCLASS,
+                bindings::PCI_VENDOR_ID_NVIDIA
+            ),
+            ()
+        ),
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_3D,
+                Class::MASK_CLASS_SUBCLASS,
+                bindings::PCI_VENDOR_ID_NVIDIA
+            ),
+            ()
+        ),
+    ]
 );
 
 impl pci::Driver for NovaCore {
Signature · 1 line
2.50.1
Reviewed-by on v2 2/3
#10 lore raw

Re: [PATCH v2 2/3] gpu: nova-core: avoid probing non-display/compute PCI functions

Quoted 67 lines · John Hubbard

NovaCore has so far been too imprecise about figuring out if .probe() has found a supported PCI PF (Physical Function). By that I mean:
.probe() sets up BAR0 (which involves a lot of very careful devres and Device<Bound> details behind the scenes). And then if it is dealing with a non-supported device such as the .1 audio PF on many GPUs, it fails out due to an unexpected BAR0 size. We have been fortunate that the BAR0 sizes are different.

Really, we should be filtering on PCI class ID instead. These days I think we can confidently pick out Nova's supported PF's via PCI class ID. And if not, then we'll revisit.

The approach here is to filter on "Display VGA" or "Display 3D", which is how PCI class IDs express "this is a modern GPU's PF".

Cc Danilo Krummrich <[email protected]>
---
 drivers/gpu/nova-core/driver.rs | 27 ++++++++++++++++++++++-----
 1 file changed, 22 insertions(+), 5 deletions(-)
drivers/gpu/nova-core/driver.rs +22 -5
index 274989ea1fb4..4ec5b861a345 100644
@@ -1,6 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
 
-use kernel::{auxiliary, bindings, c_str, device::Core, pci, prelude::*, sizes::SZ_16M, sync::Arc};
+use kernel::{
+    auxiliary, bindings, c_str, device::Core, pci, pci::Class, prelude::*, sizes::SZ_16M, sync::Arc,
+};
 
 use crate::gpu::Gpu;
 
@@ -18,10 +20,25 @@ pub(crate) struct NovaCore {
     PCI_TABLE,
     MODULE_PCI_TABLE,
     <NovaCore as pci::Driver>::IdInfo,
-    [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_NVIDIA, bindings::PCI_ANY_ID as u32),
-        ()
-    )]
+    [
+        // Modern NVIDIA GPUs will show up as either VGA or 3D controllers.
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_VGA,
+                Class::MASK_CLASS_SUBCLASS,
+                bindings::PCI_VENDOR_ID_NVIDIA
+            ),
+            ()
+        ),
+        (
+            pci::DeviceId::from_class_and_vendor(
+                Class::DISPLAY_3D,
+                Class::MASK_CLASS_SUBCLASS,
+                bindings::PCI_VENDOR_ID_NVIDIA
+            ),
+            ()
+        ),
+    ]
 );
 
 impl pci::Driver for NovaCore {
Signature · 1 line
2.50.1
#11 lore raw

PATCH v2 3/3 rust: pci: provide access to PCI Vendor values

In reply to John Hubbard

This allows callers to write Vendor::SOME_COMPANY instead of bindings::PCI_VENDOR_ID_SOME_COMPANY.

It also allows removing "use kernel::bindings" entirely from most of the affected files here.

Apply this to the various Rust for Linux callers who were previously using bindings::PCI_VENDOR_ID_*.

New APIs:
Vendor::SOME_COMPANY
Vendor::from_u32(), as_u32() DeviceId::from_class_and_vendor() now takes Vendor type

Cc Danilo Krummrich <[email protected]>
---
 drivers/gpu/nova-core/driver.rs       |  12 +-
 rust/kernel/pci.rs                    | 327 +++++++++++++++++++++++++-
 samples/rust/rust_dma.rs              |   3 +-
 samples/rust/rust_driver_auxiliary.rs |   4 +-
 samples/rust/rust_driver_pci.rs       |   4 +-
 5 files changed, 338 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/driver.rs +9 -3
index 4ec5b861a345..d0272289f863 100644
@@ -1,7 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use kernel::{
-    auxiliary, bindings, c_str, device::Core, pci, pci::Class, prelude::*, sizes::SZ_16M, sync::Arc,
+    auxiliary, c_str,
+    device::Core,
+    pci,
+    pci::{Class, Vendor},
+    prelude::*,
+    sizes::SZ_16M,
+    sync::Arc,
 };
 
 use crate::gpu::Gpu;
@@ -26,7 +32,7 @@ pub(crate) struct NovaCore {
             pci::DeviceId::from_class_and_vendor(
                 Class::DISPLAY_VGA,
                 Class::MASK_CLASS_SUBCLASS,
-                bindings::PCI_VENDOR_ID_NVIDIA
+                Vendor::NVIDIA
             ),
             ()
         ),
@@ -34,7 +40,7 @@ pub(crate) struct NovaCore {
             pci::DeviceId::from_class_and_vendor(
                 Class::DISPLAY_3D,
                 Class::MASK_CLASS_SUBCLASS,
-                bindings::PCI_VENDOR_ID_NVIDIA
+                Vendor::NVIDIA
             ),
             ()
         ),
rust/kernel/pci.rs +324 -3

346 lines not on this page · raw message

samples/rust/rust_dma.rs +1 -2
index c5e7cce68654..520c59b930dc 100644
@@ -5,7 +5,6 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    bindings,
     device::Core,
     dma::{CoherentAllocation, Device, DmaMask},
     pci,
@@ -46,7 +45,7 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}
     MODULE_PCI_TABLE,
     <DmaSampleDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         ()
     )]
 );
samples/rust/rust_driver_auxiliary.rs +2 -2
index f2a820683fc3..d8470e4bf88b 100644
@@ -5,7 +5,7 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    auxiliary, bindings, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
+    auxiliary, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
 };
 
 use pin_init::PinInit;
@@ -51,7 +51,7 @@ struct ParentDriver {
     MODULE_PCI_TABLE,
     <ParentDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         ()
     )]
 );
samples/rust/rust_driver_pci.rs +2 -2
index 606946ff4d7f..a3a7a0837961 100644
@@ -4,7 +4,7 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
-use kernel::{bindings, c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
+use kernel::{c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
 
 struct Regs;
 
@@ -38,7 +38,7 @@ struct SampleDriver {
     MODULE_PCI_TABLE,
     <SampleDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         TestIndex::NO_EVENTFD
     )]
 );
Signature · 1 line
2.50.1
maintainer
#12 lore raw

Re: [PATCH v2 3/3] rust: pci: provide access to PCI Vendor values

rust/kernel/pci.rs pub const fn as_u32(self) -> u32 { · line 226

Quoted 8 lines · John Hubbard
rust/kernel/pci.rs +8 -0
+            /// Create a `Vendor` from the raw vendor ID value, or `None` if the value doesn't
+            /// match any known vendor.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }

Same here, I think this should be impl TryFrom<u32> for Vendor.

Quoted 25 lines
rust/kernel/pci.rs +10 -2
+
+            /// Get the raw 16-bit vendor ID value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
 
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
@@ -335,9 +656,9 @@ pub const fn from_class(class: u32, class_mask: u32) -> Self {
     ///
     /// 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 {
+    pub const fn from_class_and_vendor(class: Class, class_mask: u32, vendor: Vendor) -> Self {
         Self(bindings::pci_device_id {
-            vendor,
+            vendor: vendor.as_u32(),
             device: DeviceId::PCI_ANY_ID,
             subvendor: DeviceId::PCI_ANY_ID,
             subdevice: DeviceId::PCI_ANY_ID,

rust/kernel/pci.rs macro_rules! pci_device_table { · line 720

Quoted 5 lines
rust/kernel/pci.rs +1 -1
@@ -396,7 +717,7 @@ macro_rules! pci_device_table {
 ///     <MyDriver as pci::Driver>::IdInfo,
 ///     [
 ///         (
-///             pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32),
+///             pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), bindings::PCI_ANY_ID as u32),

We should change DeviceId::from_id() to consume a pci::Vendor value directly.

#13 lore raw

Re: [PATCH v2 3/3] rust: pci: provide access to PCI Vendor values

Quoted 11 lines · Danilo Krummrich

rust/kernel/pci.rs pub const fn as_u32(self) -> u32 { · line 226

Quoted 8 lines · John Hubbard
rust/kernel/pci.rs +8 -0
+            /// Create a `Vendor` from the raw vendor ID value, or `None` if the value doesn't
+            /// match any known vendor.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }

Same here, I think this should be impl TryFrom<u32> for Vendor.

OK.

Quoted 25 lines
Quoted 25 lines
rust/kernel/pci.rs +10 -2
+
+            /// Get the raw 16-bit vendor ID value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
 
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
@@ -335,9 +656,9 @@ pub const fn from_class(class: u32, class_mask: u32) -> Self {
     ///
     /// 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 {
+    pub const fn from_class_and_vendor(class: Class, class_mask: u32, vendor: Vendor) -> Self {
         Self(bindings::pci_device_id {
-            vendor,
+            vendor: vendor.as_u32(),
             device: DeviceId::PCI_ANY_ID,
             subvendor: DeviceId::PCI_ANY_ID,
             subdevice: DeviceId::PCI_ANY_ID,
Quoted 8 lines

rust/kernel/pci.rs macro_rules! pci_device_table { · line 720

Quoted 6 lines
rust/kernel/pci.rs +1 -1
@@ -396,7 +717,7 @@ macro_rules! pci_device_table {
 ///     <MyDriver as pci::Driver>::IdInfo,
 ///     [
 ///         (
-///             pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32),
+///             pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), bindings::PCI_ANY_ID as u32),

We should change DeviceId::from_id() to consume a pci::Vendor value directly.

Interesting. OK.

Thanks for the review!

thanks,

Signature · 1 line
John Hubbard
Reviewed-by on v2 3/3
#14 lore raw

Re: [PATCH v2 3/3] rust: pci: provide access to PCI Vendor values

In reply to John Hubbard
Quoted 205 lines · John Hubbard

This allows callers to write Vendor::SOME_COMPANY instead of bindings::PCI_VENDOR_ID_SOME_COMPANY.

It also allows removing "use kernel::bindings" entirely from most of the affected files here.

Apply this to the various Rust for Linux callers who were previously using bindings::PCI_VENDOR_ID_*.

New APIs:
Vendor::SOME_COMPANY
Vendor::from_u32(), as_u32() DeviceId::from_class_and_vendor() now takes Vendor type

Cc Danilo Krummrich <[email protected]>
---
 drivers/gpu/nova-core/driver.rs       |  12 +-
 rust/kernel/pci.rs                    | 327 +++++++++++++++++++++++++-
 samples/rust/rust_dma.rs              |   3 +-
 samples/rust/rust_driver_auxiliary.rs |   4 +-
 samples/rust/rust_driver_pci.rs       |   4 +-
 5 files changed, 338 insertions(+), 12 deletions(-)
drivers/gpu/nova-core/driver.rs +9 -3
index 4ec5b861a345..d0272289f863 100644
@@ -1,7 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use kernel::{
-    auxiliary, bindings, c_str, device::Core, pci, pci::Class, prelude::*, sizes::SZ_16M, sync::Arc,
+    auxiliary, c_str,
+    device::Core,
+    pci,
+    pci::{Class, Vendor},
+    prelude::*,
+    sizes::SZ_16M,
+    sync::Arc,
 };
 
 use crate::gpu::Gpu;
@@ -26,7 +32,7 @@ pub(crate) struct NovaCore {
             pci::DeviceId::from_class_and_vendor(
                 Class::DISPLAY_VGA,
                 Class::MASK_CLASS_SUBCLASS,
-                bindings::PCI_VENDOR_ID_NVIDIA
+                Vendor::NVIDIA
             ),
             ()
         ),
@@ -34,7 +40,7 @@ pub(crate) struct NovaCore {
             pci::DeviceId::from_class_and_vendor(
                 Class::DISPLAY_3D,
                 Class::MASK_CLASS_SUBCLASS,
-                bindings::PCI_VENDOR_ID_NVIDIA
+                Vendor::NVIDIA
             ),
             ()
         ),
rust/kernel/pci.rs +48 -3
index 9caa1d342d52..7a42b91ad873 100644
@@ -196,6 +196,327 @@ pub const fn as_u32(self) -> u32 {
     OTHERS                     = bindings::PCI_CLASS_OTHERS,                     // 0xff0000
 }
 
+macro_rules! define_all_pci_vendors {
+    (
+        $($variant:ident = $binding:expr,)+
+    ) => {
+        /// PCI vendor IDs.
+        ///
+        /// Each entry contains the 16-bit PCI vendor ID as assigned by the PCI SIG.
+        /// These IDs uniquely identify the manufacturer of a PCI device.
+        /// All values are derived from kernel constants.
+        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+        #[repr(transparent)]
+        pub struct Vendor(u32);
+
+        impl Vendor {
+            // Associated constants derived from kernel bindings
+            $(
+                #[allow(missing_docs)]
+                pub const $variant: Self = Self($binding);
+            )+
+
+            /// Create a `Vendor` from the raw vendor ID value, or `None` if the value doesn't
+            /// match any known vendor.
+            pub fn from_u32(value: u32) -> Option<Self> {
+                match value {
+                    $(x if x == Self::$variant.0 => Some(Self::$variant),)+
+                    _ => None,
+                }
+            }
+
+            /// Get the raw 16-bit vendor ID value.
+            pub const fn as_u32(self) -> u32 {
+                self.0
+            }
+        }
+    };
+}
+
+define_all_pci_vendors! {
+    PCI_SIG                  = bindings::PCI_VENDOR_ID_PCI_SIG,                  // 0x0001
+
+    ...
+
+    NCUBE                    = bindings::PCI_VENDOR_ID_NCUBE,                    // 0x10ff
+}
+
 /// An adapter for the registration of PCI drivers.
 pub struct Adapter<T: Driver>(T);
 
@@ -335,9 +656,9 @@ pub const fn from_class(class: u32, class_mask: u32) -> Self {
     ///
     /// 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 {
+    pub const fn from_class_and_vendor(class: Class, class_mask: u32, vendor: Vendor) -> Self {
         Self(bindings::pci_device_id {
-            vendor,
+            vendor: vendor.as_u32(),
             device: DeviceId::PCI_ANY_ID,
             subvendor: DeviceId::PCI_ANY_ID,
             subdevice: DeviceId::PCI_ANY_ID,
@@ -396,7 +717,7 @@ macro_rules! pci_device_table {
 ///     <MyDriver as pci::Driver>::IdInfo,
 ///     [
 ///         (
-///             pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, bindings::PCI_ANY_ID as u32),
+///             pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), bindings::PCI_ANY_ID as u32),
 ///             (),
 ///         )
 ///     ]
samples/rust/rust_dma.rs +1 -2
index c5e7cce68654..520c59b930dc 100644
@@ -5,7 +5,6 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    bindings,
     device::Core,
     dma::{CoherentAllocation, Device, DmaMask},
     pci,
@@ -46,7 +45,7 @@ unsafe impl kernel::transmute::FromBytes for MyStruct {}
     MODULE_PCI_TABLE,
     <DmaSampleDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         ()
     )]
 );
samples/rust/rust_driver_auxiliary.rs +2 -2
index f2a820683fc3..d8470e4bf88b 100644
@@ -5,7 +5,7 @@
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
 use kernel::{
-    auxiliary, bindings, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
+    auxiliary, c_str, device::Core, driver, error::Error, pci, prelude::*, InPlaceModule,
 };
 
 use pin_init::PinInit;
@@ -51,7 +51,7 @@ struct ParentDriver {
     MODULE_PCI_TABLE,
     <ParentDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         ()
     )]
 );
samples/rust/rust_driver_pci.rs +2 -2
index 606946ff4d7f..a3a7a0837961 100644
@@ -4,7 +4,7 @@
 //!
 //! To make this driver probe, QEMU must be run with `-device pci-testdev`.
 
-use kernel::{bindings, c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
+use kernel::{c_str, device::Core, devres::Devres, pci, prelude::*, types::ARef};
 
 struct Regs;
 
@@ -38,7 +38,7 @@ struct SampleDriver {
     MODULE_PCI_TABLE,
     <SampleDriver as pci::Driver>::IdInfo,
     [(
-        pci::DeviceId::from_id(bindings::PCI_VENDOR_ID_REDHAT, 0x5),
+        pci::DeviceId::from_id(pci::Vendor::REDHAT.as_u32(), 0x5),
         TestIndex::NO_EVENTFD
     )]
 );
Signature · 1 line
2.50.1