* [PATCH v6 1/3] rust: helpers: add SPI helpers [not found] <20261027054209.904654-1-847807867@qq.com> @ 2026-10-27 5:42 ` Shuai Liu 2026-10-27 5:42 ` [PATCH v6 2/3] rust: spi: add SPI driver abstractions Shuai Liu 2026-10-27 5:42 ` [PATCH v6 3/3] samples: rust: add SPI driver sample Shuai Liu 2 siblings, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-10-27 5:42 UTC (permalink / raw) To: linux-spi, rust-for-linux; +Cc: broonie, ojeda, dakr, linux-kernel, Shuai Liu Add C helpers for the SPI functions that are `static inline` in C and therefore cannot be accessed from Rust directly: spi_unregister_driver(), spi_write() and spi_read(). The helpers are guarded by CONFIG_SPI, since the SPI core functions they call are not available when SPI support is disabled. Also include <linux/spi/spi.h> in the bindgen bindings helper, so that the Rust side can access the SPI data types. Signed-off-by: Shuai Liu <847807867@qq.com> --- rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/spi.c | 25 +++++++++++++++++++++++++ 3 files changed, 27 insertions(+) create mode 100644 rust/helpers/spi.c diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index c706dda5b5ca..c9062aae959a 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -88,6 +88,7 @@ #include <linux/security.h> #include <linux/serdev.h> #include <linux/slab.h> +#include <linux/spi/spi.h> #include <linux/sys_soc.h> #include <linux/task_work.h> #include <linux/tracepoint.h> diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 9bb850294a2f..6b0f50c12f9c 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -96,6 +96,7 @@ #include "serdev.c" #include "signal.c" #include "slab.c" +#include "spi.c" #include "spinlock.c" #include "string.c" #include "srcu.c" diff --git a/rust/helpers/spi.c b/rust/helpers/spi.c new file mode 100644 index 000000000000..8609d54962c0 --- /dev/null +++ b/rust/helpers/spi.c @@ -0,0 +1,25 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/spi/spi.h> + +#ifdef CONFIG_SPI + +__rust_helper +void rust_helper_spi_unregister_driver(struct spi_driver *sdrv) +{ + spi_unregister_driver(sdrv); +} + +__rust_helper +int rust_helper_spi_write(struct spi_device *spi, const void *buf, size_t len) +{ + return spi_write(spi, buf, len); +} + +__rust_helper +int rust_helper_spi_read(struct spi_device *spi, void *buf, size_t len) +{ + return spi_read(spi, buf, len); +} + +#endif -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v6 2/3] rust: spi: add SPI driver abstractions [not found] <20261027054209.904654-1-847807867@qq.com> 2026-10-27 5:42 ` [PATCH v6 1/3] rust: helpers: add SPI helpers Shuai Liu @ 2026-10-27 5:42 ` Shuai Liu 2026-11-12 19:30 ` Mark Brown 2026-10-27 5:42 ` [PATCH v6 3/3] samples: rust: add SPI driver sample Shuai Liu 2 siblings, 1 reply; 14+ messages in thread From: Shuai Liu @ 2026-10-27 5:42 UTC (permalink / raw) To: linux-spi, rust-for-linux; +Cc: broonie, ojeda, dakr, linux-kernel, Shuai Liu Add the Rust abstractions for the SPI driver subsystem, allowing SPI drivers to be written in Rust. This adds the following abstractions: - `spi::DeviceId`: a driver-side device id. - `spi::Adapter`: the registration of SPI drivers, implementing `driver::DriverLayout` and `driver::RegistrationOps`. - `spi::Driver`: the trait that SPI drivers implement, with `probe()`, `shutdown()` and `unbind()` callbacks. - `spi::SpiDevice`: a representation of `struct spi_device`, providing device configuration accessors and the `write()`, `read()` and `write_then_read()` I/O operations on bound devices. - `module_spi_driver!` and `spi_device_table!` macros. The module is only built when CONFIG_SPI is enabled, since the SPI core functions it uses are not available otherwise. The device configuration accessors and the I/O operations are only available on `SpiDevice<Bound>`: an `ARef<SpiDevice>` may outlive the driver's unbind and the device's or controller's unregistration, and the SPI core's transfer path does not check the registration state, so performing I/O on an unbound device is not sound. Moreover, once the device is unbound, another driver may bind to the same `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. via `spi_setup()`), so reading the configuration would be a data race. Driver callbacks receive a `SpiDevice<Core>`, which dereferences to `SpiDevice<Bound>`. The `write()` and `read()` methods copy the data into DMA-safe bounce buffers before transferring, as the SPI core requires transfer buffers to be DMA-safe and the caller-provided slices may be located anywhere (e.g. on the stack). `write_then_read()` does not need this, since the C core's spi_write_then_read() already copies both buffers into internal DMA-safe bounce buffers. `write_then_read()` additionally validates that the sum of the two buffer lengths fits in `u32`, as the C core sums the two lengths as `unsigned int` when sizing its bounce buffer. Match data lookup follows the same order as the C core's spi_get_device_match_data(): first the OF/ACPI match data, then the SPI id table. Entries without driver data (e.g. `@none` id tables) are handled gracefully. Signed-off-by: Shuai Liu <847807867@qq.com> --- rust/kernel/Kconfig.test | 11 + rust/kernel/lib.rs | 2 + rust/kernel/spi.rs | 570 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 583 insertions(+) create mode 100644 rust/kernel/spi.rs diff --git a/rust/kernel/Kconfig.test b/rust/kernel/Kconfig.test index 3bf4194f28c7..bda70dcc7793 100644 --- a/rust/kernel/Kconfig.test +++ b/rust/kernel/Kconfig.test @@ -94,6 +94,17 @@ config RUST_BUG_KUNIT_TEST If unsure, say N. +config RUST_SPI_KUNIT_TEST + bool "KUnit tests for the Rust SPI driver abstractions" if !KUNIT_ALL_TESTS + depends on SPI=y + default KUNIT_ALL_TESTS + help + This option enables KUnit tests for the Rust SPI driver + abstractions. These are only for development and testing, not + for regular kernel use cases. + + If unsure, say N. + config RUST_TIME_KUNIT_TEST bool "KUnit tests for the Rust time API" if !KUNIT_ALL_TESTS default KUNIT_ALL_TESTS diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index a4747f75b163..cbe5a4ed825d 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -133,6 +133,8 @@ pub mod sizes; #[cfg(CONFIG_SOC_BUS)] pub mod soc; +#[cfg(CONFIG_SPI)] +pub mod spi; #[doc(hidden)] pub mod std_vendor; pub mod str; diff --git a/rust/kernel/spi.rs b/rust/kernel/spi.rs new file mode 100644 index 000000000000..a05378391844 --- /dev/null +++ b/rust/kernel/spi.rs @@ -0,0 +1,570 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! SPI Driver subsystem +//! +//! This module adds abstractions for the SPI driver subsystem, allowing drivers to be +//! written in Rust for SPI devices. + +// SPI Driver abstractions. +use crate::{ + acpi, + device, + device_id::{ + RawDeviceId, + RawDeviceIdIndex, // + }, + driver, + error::*, + of, + prelude::*, + sync::aref::AlwaysRefCounted, + types::Opaque, // +}; + +use core::{ + marker::PhantomData, + mem::offset_of, + ptr::NonNull, // +}; + +/// An SPI device id table. +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct DeviceId(bindings::spi_device_id); + +impl DeviceId { + const SPI_NAME_SIZE: usize = 32; + + /// Create a new device id from an SPI 'id' string. + #[inline(always)] + pub const fn new(id: &'static CStr) -> Self { + let src = id.to_bytes_with_nul(); + build_assert!(src.len() <= Self::SPI_NAME_SIZE, "ID exceeds 32 bytes"); + let mut spi: bindings::spi_device_id = pin_init::zeroed(); + let mut i = 0; + while i < src.len() { + spi.name[i] = src[i]; + i += 1; + } + + Self(spi) + } +} + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `spi_device_id` and does not add +// additional invariants, so it's safe to transmute to `RawType`. +unsafe impl RawDeviceId for DeviceId { + type RawType = bindings::spi_device_id; +} + +// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. +unsafe impl RawDeviceIdIndex for DeviceId { + const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::spi_device_id, driver_data); +} + +/// IdTable type for SPI +pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; + +/// Create a SPI `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! spi_device_table { + ($($tt:tt)*) => { + $crate::module_device_table!("spi", $crate::spi::DeviceId, $($tt)*); + }; +} + +/// An adapter for the registration of SPI drivers. +pub struct Adapter<T: Driver>(T); + +// SAFETY: +// - `bindings::spi_driver` is a C type declared as `repr(C)`. +// - `T::Data` is the type of the driver's device private data. +// - `struct spi_driver` embeds a `struct device_driver`. +// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. +unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> { + type DriverType = bindings::spi_driver; + type DriverData<'bound> = T::Data<'bound>; + const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver); +} + +// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> { + unsafe fn register( + sdrv: &Opaque<Self::DriverType>, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + build_assert!( + T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::SPI_ID_TABLE.is_some(), + "At least one of ACPI/OF/Legacy tables must be present when registering an spi driver" + ); + + let spi_table = match T::SPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let of_table = match T::OF_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let acpi_table = match T::ACPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + // SAFETY: It's safe to set the fields of `struct spi_driver` on initialization. + unsafe { + (*sdrv.get()).driver.name = name.as_char_ptr(); + (*sdrv.get()).probe = Some(Self::probe_callback); + (*sdrv.get()).remove = Some(Self::remove_callback); + (*sdrv.get()).shutdown = Some(Self::shutdown_callback); + (*sdrv.get()).id_table = spi_table; + (*sdrv.get()).driver.of_match_table = of_table; + (*sdrv.get()).driver.acpi_match_table = acpi_table; + } + + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + to_result(unsafe { bindings::__spi_register_driver(module.as_ptr(), sdrv.get()) }) + } + + unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) { + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + unsafe { bindings::spi_unregister_driver(sdrv.get()) } + } +} + +impl<T: Driver> Adapter<T> { + extern "C" fn probe_callback(sdev: *mut bindings::spi_device) -> kernel::ffi::c_int { + // SAFETY: The SPI bus only ever calls the probe callback with a valid pointer to a + // `struct spi_device`. + // + // INVARIANT: `sdev` is valid for the duration of `probe_callback()`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // Match the lookup order of the C core's `spi_get_device_match_data()`: first the + // OF/ACPI match data, then the SPI id table. + // + // SAFETY: `sdev` matched data is of type `Self::IdInfo`. + let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) } + .or_else(|| Self::spi_id_info(sdev)); + + from_result(|| { + let data = T::probe(sdev, info); + + sdev.as_ref().set_drvdata(data)?; + Ok(0) + }) + } + + extern "C" fn remove_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `sdev` is a valid pointer to a `struct spi_device`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `remove_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::unbind(sdev, data); + } + + extern "C" fn shutdown_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `shutdown_callback` is only ever called for a valid `sdev` + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `shutdown_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::shutdown(sdev, data); + } + + /// Returns the driver's private data from the matching entry in the [`spi::IdTable`], if any. + /// + /// If this returns `None`, it means there is no match with an entry in the [`spi::IdTable`]. + fn spi_id_info(dev: &SpiDevice) -> Option<&'static <Self as driver::Adapter>::IdInfo> { + // Ensure the driver has an SPI id table: the entries matched by `spi_get_device_id()` + // below come from the table registered in `register()`, i.e. `T::SPI_ID_TABLE`, which + // guarantees that every `driver_data` field is a valid `T::IdInfo`. + T::SPI_ID_TABLE.as_ref()?; + + // SAFETY: + // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`. + // + // `spi_get_device_id()` looks up the registered driver id table using the device's + // modalias and returns either a pointer to a matching entry or `NULL`. + let raw_id = unsafe { bindings::spi_get_device_id(dev.as_raw()) }; + + if raw_id.is_null() { + return None; + } + + // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct spi_device_id` and + // does not add additional invariants, so it's safe to transmute. + let id = unsafe { &*raw_id.cast::<DeviceId>() }; + + // SAFETY: `id` comes from the driver's id table (as established by the `T::SPI_ID_TABLE` + // check above). By the safety requirements of `info_unchecked_opt()`, this is either a + // valid `T::IdInfo` or `NULL` (e.g. for a `@none` table), which `info_unchecked_opt()` + // handles by returning `None`. + unsafe { id.info_unchecked_opt::<T::IdInfo>() } + } +} + +impl<T: Driver> driver::Adapter for Adapter<T> { + type IdInfo = T::IdInfo; + + fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> { + T::OF_ID_TABLE + } + + fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> { + T::ACPI_ID_TABLE + } +} + +/// Declares a kernel module that exposes a single spi driver. +/// +/// # Examples +/// +/// ```ignore +/// kernel::module_spi_driver! { +/// type: MyDriver, +/// name: "Module name", +/// authors: ["Author name"], +/// description: "Description", +/// license: "GPL v2", +/// } +/// ``` +#[macro_export] +macro_rules! module_spi_driver { + ($($f:tt)*) => { + $crate::module_driver!(<T>, $crate::spi::Adapter<T>, { $($f)* }); + }; +} + +/// The spi driver trait. +/// +/// Drivers must implement this trait in order to get a spi driver registered. +/// +/// # Example +/// +///``` +/// # use kernel::{device::Core, spi, of}; +/// +/// struct MyDriver; +/// +/// kernel::spi_device_table!( +/// SPI_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (spi::DeviceId::new(c"rust_driver_spi"), ()) +/// ] +/// ); +/// +/// kernel::of_device_table!( +/// OF_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (of::DeviceId::new(c"test,device"), ()) +/// ] +/// ); +/// +/// impl spi::Driver for MyDriver { +/// type IdInfo = (); +/// type Data<'bound> = Self; +/// const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); +/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); +/// +/// fn probe<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { +/// Err(ENODEV) +/// } +/// +/// fn shutdown<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// this: Pin<&Self::Data<'bound>>, +/// ) { +/// } +/// } +///``` +pub trait Driver { + /// The type holding information about each device id supported by the driver. + // TODO: Use `associated_type_defaults` once stabilized: + // + // ``` + // type IdInfo: 'static = (); + // ``` + type IdInfo: 'static; + + /// The type of the driver's bus device private data. + type Data<'bound>: Send + 'bound; + + /// The table of device ids supported by the driver. + const SPI_ID_TABLE: Option<IdTable<Self::IdInfo>> = None; + + /// The table of OF device ids supported by the driver. + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; + + /// The table of ACPI device ids supported by the driver. + const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None; + + /// SPI driver probe. + /// + /// Called when a new spi device is added or discovered. + /// Implementers should attempt to initialize the device here. + fn probe<'bound>( + dev: &'bound SpiDevice<device::Core<'_>>, + id_info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound; + + /// SPI driver shutdown. + /// + /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the + /// [`SpiDevice`] into a safe state. Implementing this callback is optional. + /// + /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware + /// to prevent undesired behavior during shutdown. + /// + /// This callback is distinct from final resource cleanup, as the driver instance remains valid + /// after it returns. Any deallocation or teardown of driver-owned resources should instead be + /// handled in `Drop`. + fn shutdown<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } + + /// SPI driver unbind. + /// + /// Called when the [`SpiDevice`] is unbound from its bound [`Driver`]. Implementing this + /// callback is optional. + /// + /// This callback serves as a place for drivers to perform teardown operations that require a + /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O + /// operations to gracefully tear down the device. + /// + /// Otherwise, release operations for driver resources should be performed in `Drop`. + fn unbind<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } +} + +/// The spi device representation. +/// +/// This structure represents the Rust abstraction for a C `struct spi_device`. The +/// implementation abstracts the usage of an existing C `struct spi_device` that +/// gets passed from the C side. +/// +/// # Invariants +/// +/// A [`SpiDevice`] instance represents a valid `struct spi_device` created by the C portion of +/// the kernel. +#[repr(transparent)] +pub struct SpiDevice<Ctx: device::DeviceContext = device::Normal>( + Opaque<bindings::spi_device>, + PhantomData<Ctx>, +); + +impl<Ctx: device::DeviceContext> SpiDevice<Ctx> { + fn as_raw(&self) -> *mut bindings::spi_device { + self.0.get() + } +} + +/// Device configuration accessors and I/O operations, restricted to bound devices. +/// +/// An `ARef<SpiDevice>` (i.e. a `SpiDevice<Normal>`) may outlive the driver's unbind and the +/// device's or controller's unregistration. The SPI core's transfer path does not check the +/// registration state, and the controller driver's resources (e.g. `spi->controller_state` or +/// MMIO mappings) may already have been released, so performing I/O on an unbound device is not +/// sound. Likewise, once the device is unbound, another driver may bind to the same +/// `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. +/// via `spi_setup()`), so reading the configuration accessors on an unbound device would be a +/// data race. Restricting these operations to [`SpiDevice<Bound>`] guarantees that the device is +/// still bound to a driver; driver callbacks receive a `SpiDevice<Core>`, which dereferences to +/// `SpiDevice<Bound>`. +impl SpiDevice<device::Bound> { + /// Returns the maximum speed of the SPI device. + #[inline] + pub fn max_speed_hz(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).max_speed_hz } + } + + /// Returns the number of bits per word of the SPI device. + #[inline] + pub fn bits_per_word(&self) -> u8 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).bits_per_word } + } + + /// Returns the mode flags of the SPI device. + #[inline] + pub fn mode(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).mode } + } + + /// Writes the data from `buf` to the SPI device. + /// + /// The data is copied into a DMA-safe bounce buffer before the transfer, since the + /// slice may be located anywhere (e.g. on the stack). + #[inline] + pub fn write(&self, buf: &[u8]) -> Result { + let mut bounce = KVec::with_capacity(buf.len(), GFP_KERNEL)?; + bounce.extend_from_slice(buf, GFP_KERNEL)?; + + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. `bounce` is valid for reads of length `bounce.len()` for the + // duration of the call, which SPI core guarantees not to outlive. + to_result(unsafe { + bindings::spi_write(self.as_raw(), bounce.as_ptr().cast(), bounce.len()) + }) + } + + /// Reads data from the SPI device into `buf`. + /// + /// The received data is collected in a DMA-safe bounce buffer and then copied into + /// `buf`, since the slice may be located anywhere (e.g. on the stack). + #[inline] + pub fn read(&self, buf: &mut [u8]) -> Result { + let mut bounce = KVec::with_capacity(buf.len(), GFP_KERNEL)?; + bounce.resize(buf.len(), 0, GFP_KERNEL)?; + + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. `bounce` is valid for writes of length `bounce.len()` for + // the duration of the call, which SPI core guarantees not to outlive. + to_result(unsafe { + bindings::spi_read(self.as_raw(), bounce.as_mut_ptr().cast(), bounce.len()) + })?; + + buf.copy_from_slice(&bounce); + Ok(()) + } + + /// Writes the data from `write_buf` to the SPI device, then reads data from the SPI device + /// into `read_buf`. + /// + /// The buffers don't need to be DMA-safe: the SPI core copies them into internal + /// DMA-safe bounce buffers. + /// + /// The sum of the lengths of the two buffers must fit in [`u32`]. + #[inline] + pub fn write_then_read(&self, write_buf: &[u8], read_buf: &mut [u8]) -> Result { + let n_tx = u32::try_from(write_buf.len())?; + let n_rx = u32::try_from(read_buf.len())?; + + // The C core sums the two lengths as `unsigned int` when selecting and sizing its + // bounce buffer, so a sum that doesn't fit in `u32` would wrap around to a small + // value and select a buffer that is too small for the transfer. + n_tx.checked_add(n_rx).ok_or(EINVAL)?; + + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. `write_buf` is valid for reads of length `n_tx` and `read_buf` + // is valid for writes of length `n_rx` for the duration of the call, which SPI core + // guarantees not to outlive. + to_result(unsafe { + bindings::spi_write_then_read( + self.as_raw(), + write_buf.as_ptr().cast(), + n_tx, + read_buf.as_mut_ptr().cast(), + n_rx, + ) + }) + } +} + +// SAFETY: `SpiDevice` is a transparent wrapper of `struct spi_device`. +// The offset is guaranteed to point to a valid device field inside `SpiDevice`. +unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for SpiDevice<Ctx> { + const OFFSET: usize = offset_of!(bindings::spi_device, dev); +} + +// SAFETY: `SpiDevice` is a transparent wrapper of a type that doesn't depend on +// `SpiDevice`'s generic argument. +kernel::impl_device_context_deref!(unsafe { SpiDevice }); +kernel::impl_device_context_into_aref!(SpiDevice); + +// SAFETY: Instances of `SpiDevice` are always reference-counted. +unsafe impl AlwaysRefCounted for SpiDevice { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. + unsafe { bindings::get_device(self.as_ref().as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull<Self>) { + // SAFETY: The safety requirements guarantee that the refcount is non-zero. + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) } + } +} + +impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for SpiDevice<Ctx> { + fn as_ref(&self) -> &device::Device<Ctx> { + let raw = self.as_raw(); + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid + // `struct spi_device`. + let dev = unsafe { &raw mut (*raw).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +// SAFETY: A `SpiDevice` is always reference-counted and can be released from any thread. +unsafe impl Send for SpiDevice {} + +// SAFETY: `SpiDevice` can be shared among threads because `SpiDevice<Normal>` has no methods +// that could mutate the device state or race with the C core (the configuration accessors and +// I/O operations are restricted to `SpiDevice<Bound>`). +unsafe impl Sync for SpiDevice {} + +// SAFETY: Same as `SpiDevice<Normal>` -- the underlying `struct spi_device` is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread safety. +unsafe impl Sync for SpiDevice<device::Bound> {} + +#[cfg(CONFIG_RUST_SPI_KUNIT_TEST)] +#[kunit_tests(rust_kernel_spi)] +mod tests { + use super::*; + + #[test] + fn device_id_name_size() { + assert_eq!(DeviceId::SPI_NAME_SIZE, bindings::SPI_NAME_SIZE as usize); + } + + #[test] + fn device_id_new_short_name() { + let id = DeviceId::new(c"rust_driver_spi"); + + let expected: &[u8] = b"rust_driver_spi\0"; + assert_eq!(&id.0.name[..expected.len()], expected); + + // The remaining bytes must be zeroed. + assert!(id.0.name[expected.len()..].iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_empty_name() { + let id = DeviceId::new(c""); + + assert!(id.0.name.iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_max_length_name() { + // 31 bytes plus the NUL terminator is the maximum accepted name length. + let id = DeviceId::new(c"abcdefghijklmnopqrstuvwxyz01234"); + + let expected: &[u8] = b"abcdefghijklmnopqrstuvwxyz01234\0"; + assert_eq!(&id.0.name[..], expected); + } +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v6 2/3] rust: spi: add SPI driver abstractions 2026-10-27 5:42 ` [PATCH v6 2/3] rust: spi: add SPI driver abstractions Shuai Liu @ 2026-11-12 19:30 ` Mark Brown 2026-11-13 2:04 ` Shuai Liu 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu 0 siblings, 2 replies; 14+ messages in thread From: Mark Brown @ 2026-11-12 19:30 UTC (permalink / raw) To: Shuai Liu; +Cc: linux-spi, rust-for-linux, broonie, ojeda, dakr, linux-kernel > The `write()` and `read()` methods copy the data into DMA-safe bounce > buffers before transferring, as the SPI core requires transfer buffers > to be DMA-safe and the caller-provided slices may be located anywhere > (e.g. on the stack). `write_then_read()` does not need this, since the > C core's spi_write_then_read() already copies both buffers into > internal DMA-safe bounce buffers. `write_then_read()` additionally > validates that the sum of the two buffer lengths fits in `u32`, as the > C core sums the two lengths as `unsigned int` when sizing its bounce > buffer. I do wonder if it's more sensible to go straight to the spi_sync()/spi_async() APIs - these APIs you're implementing are all convenience wrappers at the C level, I don't know how idiomatic they are in Rust but if there's a more Rust native way of doing this stuff it might be better to go with that and then arrange to map it onto the lower level C APIs rather than deal with the C wrappers. Of course if this is actually fairly sensible for Rust then leveraging the existing wrappers makes sense. -- Mark Brown <broonie@kernel.org> ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v6 2/3] rust: spi: add SPI driver abstractions 2026-11-12 19:30 ` Mark Brown @ 2026-11-13 2:04 ` Shuai Liu 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu 1 sibling, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:04 UTC (permalink / raw) To: Mark Brown Cc: linux-spi, rust-for-linux, ojeda, dakr, linux-kernel, 847807867 Hi Mark, Thanks for the review. Agreed -- mapping onto the lower-level APIs is the better design for the Rust layer, so v7 (coming shortly) reworks the device I/O around a single `SpiDevice::transfer()` primitive that maps onto spi_sync(): a sequence of `Transfer`s (write, read, or full duplex) is submitted as one spi_message, executed in order with the chip select asserted for the whole message. Since spi_sync() requires DMA-safe transfer buffers and Rust slices may be located anywhere (e.g. on the stack), the Rust layer owns the bounce-buffering: every transfer buffer is copied into a kmalloc'd buffer before submission, and received data is copied back afterwards. This removes the dependency on the C convenience wrappers (and their helpers) entirely, and adds full-duplex support, which the wrappers do not offer. `write()`, `read()` and `write_then_read()` remain as thin convenience methods built on top of `transfer()`: register-style access is what most SPI drivers need, and keeping the familiar names makes porting C drivers straightforward. Best regards, Shuai Liu ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v7 0/3] rust: spi: add SPI driver abstractions 2026-11-12 19:30 ` Mark Brown 2026-11-13 2:04 ` Shuai Liu @ 2026-11-13 2:05 ` Shuai Liu 2026-11-13 2:25 ` [PATCH v7 1/3] rust: helpers: add SPI helpers Shuai Liu ` (5 more replies) 1 sibling, 6 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:05 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Rework the device I/O to map onto the lower-level C APIs, as suggested by Mark Brown [1]: instead of leveraging the C convenience wrappers (spi_write(), spi_read() and spi_write_then_read()), all device I/O is now built on a single `SpiDevice::transfer()` primitive that maps onto spi_sync(). The convenience methods `write()`, `read()` and `write_then_read()` remain as thin wrappers on top of `transfer()`. `spi_sync()` requires DMA-safe transfer buffers and Rust slices may be located anywhere (e.g. on the stack), so the Rust layer owns the bounce-buffering: every transfer buffer is copied into a kmalloc'd buffer before submission, and received data is copied back afterwards. This removes the dependency on the C convenience wrappers (and their helpers) entirely, and adds full-duplex support via `Transfer::full_duplex()`, which the wrappers do not offer. Changes in v7: - Rework device I/O around a `transfer()` primitive that maps onto spi_sync(), per Mark Brown's review (patch 2). - Drop the spi_write()/spi_read() helpers; add spi_message_init()/spi_message_add_tail() helpers instead (patch 1). [1] https://lore.kernel.org/rust-for-linux/179451185979.339049.12323339081307899766.b4-review@b4/ Shuai Liu (3): rust: helpers: add SPI helpers rust: spi: add SPI driver abstractions samples: rust: add SPI driver sample rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/spi.c | 26 ++ rust/kernel/Kconfig.test | 11 + rust/kernel/lib.rs | 2 + rust/kernel/spi.rs | 673 ++++++++++++++++++++++++++++++++ samples/rust/Kconfig | 11 + samples/rust/Makefile | 1 + samples/rust/rust_driver_spi.rs | 66 ++++ 9 files changed, 792 insertions(+) create mode 100644 rust/helpers/spi.c create mode 100644 rust/kernel/spi.rs create mode 100644 samples/rust/rust_driver_spi.rs -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v7 1/3] rust: helpers: add SPI helpers 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu @ 2026-11-13 2:25 ` Shuai Liu [not found] ` <20261113022539.601421-1-847807867@qq.com> ` (4 subsequent siblings) 5 siblings, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add C helpers for the SPI functions that are `static inline` in C and therefore cannot be accessed from Rust directly: spi_unregister_driver(), spi_write() and spi_read(). The helpers are guarded by CONFIG_SPI, since the SPI core functions they call are not available when SPI support is disabled. Also include <linux/spi/spi.h> in the bindgen bindings helper, so that the Rust side can access the SPI data types. Signed-off-by: Shuai Liu <847807867@qq.com> --- rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/spi.c | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 rust/helpers/spi.c diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index c706dda5b5ca7..c9062aae959a1 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -88,6 +88,7 @@ #include <linux/security.h> #include <linux/serdev.h> #include <linux/slab.h> +#include <linux/spi/spi.h> #include <linux/sys_soc.h> #include <linux/task_work.h> #include <linux/tracepoint.h> diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 9bb850294a2f3..6b0f50c12f9ca 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -96,6 +96,7 @@ #include "serdev.c" #include "signal.c" #include "slab.c" +#include "spi.c" #include "spinlock.c" #include "string.c" #include "srcu.c" diff --git a/rust/helpers/spi.c b/rust/helpers/spi.c new file mode 100644 index 0000000000000..179a90e014e04 --- /dev/null +++ b/rust/helpers/spi.c @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/spi/spi.h> + +#ifdef CONFIG_SPI + +__rust_helper +void rust_helper_spi_unregister_driver(struct spi_driver *sdrv) +{ + spi_unregister_driver(sdrv); +} + +__rust_helper +void rust_helper_spi_message_init(struct spi_message *msg) +{ + spi_message_init(msg); +} + +__rust_helper +void rust_helper_spi_message_add_tail(struct spi_transfer *t, + struct spi_message *msg) +{ + spi_message_add_tail(t, msg); +} + +#endif -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
[parent not found: <20261113022539.601421-1-847807867@qq.com>]
* [PATCH v7 2/3] rust: spi: add SPI driver abstractions [not found] ` <20261113022539.601421-1-847807867@qq.com> @ 2026-11-13 2:25 ` Shuai Liu 2026-11-13 2:25 ` [PATCH v7 3/3] samples: rust: add SPI driver sample Shuai Liu 1 sibling, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add the Rust abstractions for the SPI driver subsystem, allowing SPI drivers to be written in Rust. This adds the following abstractions: - `spi::DeviceId`: a driver-side device id. - `spi::Adapter`: the registration of SPI drivers, implementing `driver::DriverLayout` and `driver::RegistrationOps`. - `spi::Driver`: the trait that SPI drivers implement, with `probe()`, `shutdown()` and `unbind()` callbacks. - `spi::SpiDevice`: a representation of `struct spi_device`, providing device configuration accessors and device I/O on bound devices. - `spi::Transfer`: a single SPI transfer that transmits, receives, or does both simultaneously (full duplex). - `module_spi_driver!` and `spi_device_table!` macros. The module is only built when CONFIG_SPI is enabled, since the SPI core functions it uses are not available otherwise. The device configuration accessors and the I/O operations are only available on `SpiDevice<Bound>`: an `ARef<SpiDevice>` may outlive the driver's unbind and the device's or controller's unregistration, and the SPI core's transfer path does not check the registration state, so performing I/O on an unbound device is not sound. Moreover, once the device is unbound, another driver may bind to the same `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. via `spi_setup()`), so reading the configuration would be a data race. Driver callbacks receive a `SpiDevice<Core>`, which dereferences to `SpiDevice<Bound>`. Device I/O is built on a single primitive, `SpiDevice::transfer()`, which maps to the C `spi_sync()` API: a sequence of `Transfer`s is submitted as one `spi_message`, executed in order with the chip select asserted for the whole message. The convenience methods `write()`, `read()` and `write_then_read()` are thin wrappers on top of it. `spi_sync()` requires transfer buffers to be DMA-safe, and Rust slices may be located anywhere (e.g. on the stack), so `transfer()` copies all data into DMA-safe bounce buffers before submitting the message and copies received data back afterwards. Unlike the previous approach of leveraging the C convenience wrappers, this maps directly onto the lower-level C APIs and also supports full-duplex transfers, which the C convenience wrappers do not offer. Match data lookup follows the same order as the C core's spi_get_device_match_data(): first the OF/ACPI match data, then the SPI id table. Entries without driver data (e.g. `@none` id tables) are handled gracefully. Signed-off-by: Shuai Liu <847807867@qq.com> Link: https://lore.kernel.org/rust-for-linux/179451185979.339049.12323339081307899766.b4-review@b4/ --- rust/kernel/Kconfig.test | 11 + rust/kernel/lib.rs | 2 + rust/kernel/spi.rs | 673 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 686 insertions(+) create mode 100644 rust/kernel/spi.rs diff --git a/rust/kernel/Kconfig.test b/rust/kernel/Kconfig.test index 3bf4194f28c7c..bda70dcc77934 100644 --- a/rust/kernel/Kconfig.test +++ b/rust/kernel/Kconfig.test @@ -94,6 +94,17 @@ config RUST_BUG_KUNIT_TEST If unsure, say N. +config RUST_SPI_KUNIT_TEST + bool "KUnit tests for the Rust SPI driver abstractions" if !KUNIT_ALL_TESTS + depends on SPI=y + default KUNIT_ALL_TESTS + help + This option enables KUnit tests for the Rust SPI driver + abstractions. These are only for development and testing, not + for regular kernel use cases. + + If unsure, say N. + config RUST_TIME_KUNIT_TEST bool "KUnit tests for the Rust time API" if !KUNIT_ALL_TESTS default KUNIT_ALL_TESTS diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index a4747f75b1632..cbe5a4ed825dc 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -133,6 +133,8 @@ pub mod sizes; #[cfg(CONFIG_SOC_BUS)] pub mod soc; +#[cfg(CONFIG_SPI)] +pub mod spi; #[doc(hidden)] pub mod std_vendor; pub mod str; diff --git a/rust/kernel/spi.rs b/rust/kernel/spi.rs new file mode 100644 index 0000000000000..424563baddb3e --- /dev/null +++ b/rust/kernel/spi.rs @@ -0,0 +1,673 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! SPI Driver subsystem +//! +//! This module adds abstractions for the SPI driver subsystem, allowing drivers to be +//! written in Rust for SPI devices. + +// SPI Driver abstractions. +use crate::{ + acpi, + device, + device_id::{ + RawDeviceId, + RawDeviceIdIndex, // + }, + driver, + error::*, + of, + prelude::*, + sync::aref::AlwaysRefCounted, + types::Opaque, // +}; + +use core::{ + marker::PhantomData, + mem::offset_of, + ptr::NonNull, // +}; + +/// An SPI device id table. +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct DeviceId(bindings::spi_device_id); + +impl DeviceId { + const SPI_NAME_SIZE: usize = 32; + + /// Create a new device id from an SPI 'id' string. + #[inline(always)] + pub const fn new(id: &'static CStr) -> Self { + let src = id.to_bytes_with_nul(); + build_assert!(src.len() <= Self::SPI_NAME_SIZE, "ID exceeds 32 bytes"); + let mut spi: bindings::spi_device_id = pin_init::zeroed(); + let mut i = 0; + while i < src.len() { + spi.name[i] = src[i]; + i += 1; + } + + Self(spi) + } +} + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `spi_device_id` and does not add +// additional invariants, so it's safe to transmute to `RawType`. +unsafe impl RawDeviceId for DeviceId { + type RawType = bindings::spi_device_id; +} + +// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. +unsafe impl RawDeviceIdIndex for DeviceId { + const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::spi_device_id, driver_data); +} + +/// IdTable type for SPI +pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; + +/// Create a SPI `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! spi_device_table { + ($($tt:tt)*) => { + $crate::module_device_table!("spi", $crate::spi::DeviceId, $($tt)*); + }; +} + +/// An adapter for the registration of SPI drivers. +pub struct Adapter<T: Driver>(T); + +// SAFETY: +// - `bindings::spi_driver` is a C type declared as `repr(C)`. +// - `T::Data` is the type of the driver's device private data. +// - `struct spi_driver` embeds a `struct device_driver`. +// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. +unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> { + type DriverType = bindings::spi_driver; + type DriverData<'bound> = T::Data<'bound>; + const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver); +} + +// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> { + unsafe fn register( + sdrv: &Opaque<Self::DriverType>, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + build_assert!( + T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::SPI_ID_TABLE.is_some(), + "At least one of ACPI/OF/Legacy tables must be present when registering an spi driver" + ); + + let spi_table = match T::SPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let of_table = match T::OF_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let acpi_table = match T::ACPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + // SAFETY: It's safe to set the fields of `struct spi_driver` on initialization. + unsafe { + (*sdrv.get()).driver.name = name.as_char_ptr(); + (*sdrv.get()).probe = Some(Self::probe_callback); + (*sdrv.get()).remove = Some(Self::remove_callback); + (*sdrv.get()).shutdown = Some(Self::shutdown_callback); + (*sdrv.get()).id_table = spi_table; + (*sdrv.get()).driver.of_match_table = of_table; + (*sdrv.get()).driver.acpi_match_table = acpi_table; + } + + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + to_result(unsafe { bindings::__spi_register_driver(module.as_ptr(), sdrv.get()) }) + } + + unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) { + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + unsafe { bindings::spi_unregister_driver(sdrv.get()) } + } +} + +impl<T: Driver> Adapter<T> { + extern "C" fn probe_callback(sdev: *mut bindings::spi_device) -> kernel::ffi::c_int { + // SAFETY: The SPI bus only ever calls the probe callback with a valid pointer to a + // `struct spi_device`. + // + // INVARIANT: `sdev` is valid for the duration of `probe_callback()`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // Match the lookup order of the C core's `spi_get_device_match_data()`: first the + // OF/ACPI match data, then the SPI id table. + // + // SAFETY: `sdev` matched data is of type `Self::IdInfo`. + let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) } + .or_else(|| Self::spi_id_info(sdev)); + + from_result(|| { + let data = T::probe(sdev, info); + + sdev.as_ref().set_drvdata(data)?; + Ok(0) + }) + } + + extern "C" fn remove_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `sdev` is a valid pointer to a `struct spi_device`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `remove_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::unbind(sdev, data); + } + + extern "C" fn shutdown_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `shutdown_callback` is only ever called for a valid `sdev` + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `shutdown_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::shutdown(sdev, data); + } + + /// Returns the driver's private data from the matching entry in the [`spi::IdTable`], if any. + /// + /// If this returns `None`, it means there is no match with an entry in the [`spi::IdTable`]. + fn spi_id_info(dev: &SpiDevice) -> Option<&'static <Self as driver::Adapter>::IdInfo> { + // Ensure the driver has an SPI id table: the entries matched by `spi_get_device_id()` + // below come from the table registered in `register()`, i.e. `T::SPI_ID_TABLE`, which + // guarantees that every `driver_data` field is a valid `T::IdInfo`. + T::SPI_ID_TABLE.as_ref()?; + + // SAFETY: + // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`. + // + // `spi_get_device_id()` looks up the registered driver id table using the device's + // modalias and returns either a pointer to a matching entry or `NULL`. + let raw_id = unsafe { bindings::spi_get_device_id(dev.as_raw()) }; + + if raw_id.is_null() { + return None; + } + + // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct spi_device_id` and + // does not add additional invariants, so it's safe to transmute. + let id = unsafe { &*raw_id.cast::<DeviceId>() }; + + // SAFETY: `id` comes from the driver's id table (as established by the `T::SPI_ID_TABLE` + // check above). By the safety requirements of `info_unchecked_opt()`, this is either a + // valid `T::IdInfo` or `NULL` (e.g. for a `@none` table), which `info_unchecked_opt()` + // handles by returning `None`. + unsafe { id.info_unchecked_opt::<T::IdInfo>() } + } +} + +impl<T: Driver> driver::Adapter for Adapter<T> { + type IdInfo = T::IdInfo; + + fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> { + T::OF_ID_TABLE + } + + fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> { + T::ACPI_ID_TABLE + } +} + +/// Declares a kernel module that exposes a single spi driver. +/// +/// # Examples +/// +/// ```ignore +/// kernel::module_spi_driver! { +/// type: MyDriver, +/// name: "Module name", +/// authors: ["Author name"], +/// description: "Description", +/// license: "GPL v2", +/// } +/// ``` +#[macro_export] +macro_rules! module_spi_driver { + ($($f:tt)*) => { + $crate::module_driver!(<T>, $crate::spi::Adapter<T>, { $($f)* }); + }; +} + +/// The spi driver trait. +/// +/// Drivers must implement this trait in order to get a spi driver registered. +/// +/// # Example +/// +///``` +/// # use kernel::{device::Core, spi, of}; +/// +/// struct MyDriver; +/// +/// kernel::spi_device_table!( +/// SPI_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (spi::DeviceId::new(c"rust_driver_spi"), ()) +/// ] +/// ); +/// +/// kernel::of_device_table!( +/// OF_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (of::DeviceId::new(c"test,device"), ()) +/// ] +/// ); +/// +/// impl spi::Driver for MyDriver { +/// type IdInfo = (); +/// type Data<'bound> = Self; +/// const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); +/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); +/// +/// fn probe<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { +/// Err(ENODEV) +/// } +/// +/// fn shutdown<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// this: Pin<&Self::Data<'bound>>, +/// ) { +/// } +/// } +///``` +pub trait Driver { + /// The type holding information about each device id supported by the driver. + // TODO: Use `associated_type_defaults` once stabilized: + // + // ``` + // type IdInfo: 'static = (); + // ``` + type IdInfo: 'static; + + /// The type of the driver's bus device private data. + type Data<'bound>: Send + 'bound; + + /// The table of device ids supported by the driver. + const SPI_ID_TABLE: Option<IdTable<Self::IdInfo>> = None; + + /// The table of OF device ids supported by the driver. + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; + + /// The table of ACPI device ids supported by the driver. + const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None; + + /// SPI driver probe. + /// + /// Called when a new spi device is added or discovered. + /// Implementers should attempt to initialize the device here. + fn probe<'bound>( + dev: &'bound SpiDevice<device::Core<'_>>, + id_info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound; + + /// SPI driver shutdown. + /// + /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the + /// [`SpiDevice`] into a safe state. Implementing this callback is optional. + /// + /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware + /// to prevent undesired behavior during shutdown. + /// + /// This callback is distinct from final resource cleanup, as the driver instance remains valid + /// after it returns. Any deallocation or teardown of driver-owned resources should instead be + /// handled in `Drop`. + fn shutdown<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } + + /// SPI driver unbind. + /// + /// Called when the [`SpiDevice`] is unbound from its bound [`Driver`]. Implementing this + /// callback is optional. + /// + /// This callback serves as a place for drivers to perform teardown operations that require a + /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O + /// operations to gracefully tear down the device. + /// + /// Otherwise, release operations for driver resources should be performed in `Drop`. + fn unbind<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } +} + +/// The spi device representation. +/// +/// This structure represents the Rust abstraction for a C `struct spi_device`. The +/// implementation abstracts the usage of an existing C `struct spi_device` that +/// gets passed from the C side. +/// +/// # Invariants +/// +/// A [`SpiDevice`] instance represents a valid `struct spi_device` created by the C portion of +/// the kernel. +#[repr(transparent)] +pub struct SpiDevice<Ctx: device::DeviceContext = device::Normal>( + Opaque<bindings::spi_device>, + PhantomData<Ctx>, +); + +impl<Ctx: device::DeviceContext> SpiDevice<Ctx> { + fn as_raw(&self) -> *mut bindings::spi_device { + self.0.get() + } +} + +/// A single SPI transfer. +/// +/// A transfer transmits, receives, or transmits and receives simultaneously (full duplex). +/// A sequence of transfers is submitted to the device as a single message with +/// [`SpiDevice::transfer`]. +/// +/// The buffers don't need to be DMA-safe: the data is copied into DMA-safe bounce buffers +/// internally, since Rust slices may be located anywhere (e.g. on the stack). +pub struct Transfer<'buf> { + tx: Option<&'buf [u8]>, + rx: Option<&'buf mut [u8]>, +} + +impl<'buf> Transfer<'buf> { + /// Creates a transfer that transmits the data in `tx`. + pub fn write(tx: &'buf [u8]) -> Self { + Self { + tx: Some(tx), + rx: None, + } + } + + /// Creates a transfer that receives data into `rx`. + pub fn read(rx: &'buf mut [u8]) -> Self { + Self { + tx: None, + rx: Some(rx), + } + } + + /// Creates a full-duplex transfer: `tx` is transmitted while `rx` is received + /// simultaneously. + /// + /// The two buffers must have the same length. Controllers with the + /// `SPI_CONTROLLER_HALF_DUPLEX` flag (or devices in 3-wire mode) reject full-duplex + /// transfers with [`EINVAL`]. + pub fn full_duplex(tx: &'buf [u8], rx: &'buf mut [u8]) -> Self { + Self { + tx: Some(tx), + rx: Some(rx), + } + } +} + +/// Device configuration accessors and I/O operations, restricted to bound devices. +/// +/// An `ARef<SpiDevice>` (i.e. a `SpiDevice<Normal>`) may outlive the driver's unbind and the +/// device's or controller's unregistration. The SPI core's transfer path does not check the +/// registration state, and the controller driver's resources (e.g. `spi->controller_state` or +/// MMIO mappings) may already have been released, so performing I/O on an unbound device is not +/// sound. Likewise, once the device is unbound, another driver may bind to the same +/// `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. +/// via `spi_setup()`), so reading the configuration accessors on an unbound device would be a +/// data race. Restricting these operations to [`SpiDevice<Bound>`] guarantees that the device is +/// still bound to a driver; driver callbacks receive a `SpiDevice<Core>`, which dereferences to +/// `SpiDevice<Bound>`. +impl SpiDevice<device::Bound> { + /// Returns the maximum speed of the SPI device. + #[inline] + pub fn max_speed_hz(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).max_speed_hz } + } + + /// Returns the number of bits per word of the SPI device. + #[inline] + pub fn bits_per_word(&self) -> u8 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).bits_per_word } + } + + /// Returns the mode flags of the SPI device. + #[inline] + pub fn mode(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).mode } + } + + /// Executes a sequence of [`Transfer`]s as a single SPI message. + /// + /// This is the primitive that all I/O methods are built on; it maps to the C `spi_sync()` + /// API. The transfers are executed in order with the chip select asserted for the whole + /// message. + /// + /// # Examples + /// + /// ```ignore + /// use kernel::spi::{self, Transfer}; + /// + /// fn read_register(dev: &spi::SpiDevice<kernel::device::Bound>, reg: u8) -> Result<u8> { + /// let cmd = [reg]; + /// let mut val = [0u8; 1]; + /// dev.transfer(&mut [Transfer::write(&cmd), Transfer::read(&mut val)])?; + /// Ok(val[0]) + /// } + /// ``` + pub fn transfer(&self, transfers: &mut [Transfer<'_>]) -> Result { + if transfers.is_empty() { + return Err(EINVAL); + } + + struct Bounce { + tx: KVec<u8>, + rx: KVec<u8>, + } + + // `spi_sync()` requires transfer buffers to be DMA-safe, but Rust slices may be + // located anywhere (e.g. on the stack), so the data is copied into DMA-safe bounce + // buffers. + let mut bounces: KVec<Bounce> = KVec::with_capacity(transfers.len(), GFP_KERNEL)?; + let mut xfers: KVec<bindings::spi_transfer> = + KVec::with_capacity(transfers.len(), GFP_KERNEL)?; + + for t in transfers.iter() { + if let (Some(tx), Some(rx)) = (&t.tx, &t.rx) { + if tx.len() != rx.len() { + return Err(EINVAL); + } + } + + let tx_len = t.tx.map_or(0, |buf| buf.len()); + let rx_len = t.rx.as_deref().map_or(0, |buf| buf.len()); + let len = tx_len.max(rx_len); + if len == 0 || len > u32::MAX as usize { + return Err(EINVAL); + } + + let tx = t.tx.unwrap_or(&[]); + let mut tx_bounce = KVec::with_capacity(tx.len(), GFP_KERNEL)?; + tx_bounce.extend_from_slice(tx, GFP_KERNEL)?; + + let mut rx_bounce = KVec::with_capacity(rx_len, GFP_KERNEL)?; + rx_bounce.resize(rx_len, 0, GFP_KERNEL)?; + + let xfer = bindings::spi_transfer { + tx_buf: if tx_bounce.is_empty() { + core::ptr::null() + } else { + tx_bounce.as_ptr().cast() + }, + rx_buf: if rx_bounce.is_empty() { + core::ptr::null_mut() + } else { + rx_bounce.as_mut_ptr().cast() + }, + len: len as u32, + ..pin_init::zeroed() + }; + xfers.push(xfer, GFP_KERNEL)?; + bounces.push( + Bounce { + tx: tx_bounce, + rx: rx_bounce, + }, + GFP_KERNEL, + )?; + } + + let mut msg: bindings::spi_message = pin_init::zeroed(); + + // SAFETY: `msg` is a valid `struct spi_message`. + unsafe { bindings::spi_message_init(&mut msg) }; + + for xfer in xfers.iter_mut() { + // SAFETY: `xfer` is a valid `struct spi_transfer` and `msg` has been initialized + // by `spi_message_init()` above. + unsafe { bindings::spi_message_add_tail(xfer, &mut msg) }; + } + + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. `msg` and the `struct spi_transfer`s linked into it are valid + // for the duration of the call, and `spi_sync()` is synchronous, so they are not + // accessed by the C core after it returns. + to_result(unsafe { bindings::spi_sync(self.as_raw(), &mut msg) })?; + + for (t, bounce) in transfers.iter_mut().zip(bounces.iter_mut()) { + if let Some(rx) = t.rx.as_deref_mut() { + rx.copy_from_slice(&bounce.rx); + } + } + + Ok(()) + } + + /// Writes the data from `buf` to the SPI device. + #[inline] + pub fn write(&self, buf: &[u8]) -> Result { + self.transfer(&mut [Transfer::write(buf)]) + } + + /// Reads data from the SPI device into `buf`. + #[inline] + pub fn read(&self, buf: &mut [u8]) -> Result { + self.transfer(&mut [Transfer::read(buf)]) + } + + /// Writes the data from `write_buf` to the SPI device, then reads data from the SPI device + /// into `read_buf`, with the chip select asserted for the whole operation. + /// + /// This performs the two phases sequentially; to transmit and receive simultaneously, use + /// [`Transfer::full_duplex`] with [`SpiDevice::transfer`]. + #[inline] + pub fn write_then_read(&self, write_buf: &[u8], read_buf: &mut [u8]) -> Result { + self.transfer(&mut [Transfer::write(write_buf), Transfer::read(read_buf)]) + } +} + +// SAFETY: `SpiDevice` is a transparent wrapper of `struct spi_device`. +// The offset is guaranteed to point to a valid device field inside `SpiDevice`. +unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for SpiDevice<Ctx> { + const OFFSET: usize = offset_of!(bindings::spi_device, dev); +} + +// SAFETY: `SpiDevice` is a transparent wrapper of a type that doesn't depend on +// `SpiDevice`'s generic argument. +kernel::impl_device_context_deref!(unsafe { SpiDevice }); +kernel::impl_device_context_into_aref!(SpiDevice); + +// SAFETY: Instances of `SpiDevice` are always reference-counted. +unsafe impl AlwaysRefCounted for SpiDevice { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. + unsafe { bindings::get_device(self.as_ref().as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull<Self>) { + // SAFETY: The safety requirements guarantee that the refcount is non-zero. + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) } + } +} + +impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for SpiDevice<Ctx> { + fn as_ref(&self) -> &device::Device<Ctx> { + let raw = self.as_raw(); + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid + // `struct spi_device`. + let dev = unsafe { &raw mut (*raw).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +// SAFETY: A `SpiDevice` is always reference-counted and can be released from any thread. +unsafe impl Send for SpiDevice {} + +// SAFETY: `SpiDevice` can be shared among threads because `SpiDevice<Normal>` has no methods +// that could mutate the device state or race with the C core (the configuration accessors and +// I/O operations are restricted to `SpiDevice<Bound>`). +unsafe impl Sync for SpiDevice {} + +// SAFETY: Same as `SpiDevice<Normal>` -- the underlying `struct spi_device` is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread safety. +unsafe impl Sync for SpiDevice<device::Bound> {} + +#[cfg(CONFIG_RUST_SPI_KUNIT_TEST)] +#[kunit_tests(rust_kernel_spi)] +mod tests { + use super::*; + + #[test] + fn device_id_name_size() { + assert_eq!(DeviceId::SPI_NAME_SIZE, bindings::SPI_NAME_SIZE as usize); + } + + #[test] + fn device_id_new_short_name() { + let id = DeviceId::new(c"rust_driver_spi"); + + let expected: &[u8] = b"rust_driver_spi\0"; + assert_eq!(&id.0.name[..expected.len()], expected); + + // The remaining bytes must be zeroed. + assert!(id.0.name[expected.len()..].iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_empty_name() { + let id = DeviceId::new(c""); + + assert!(id.0.name.iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_max_length_name() { + // 31 bytes plus the NUL terminator is the maximum accepted name length. + let id = DeviceId::new(c"abcdefghijklmnopqrstuvwxyz01234"); + + let expected: &[u8] = b"abcdefghijklmnopqrstuvwxyz01234\0"; + assert_eq!(&id.0.name[..], expected); + } +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v7 3/3] samples: rust: add SPI driver sample [not found] ` <20261113022539.601421-1-847807867@qq.com> 2026-11-13 2:25 ` [PATCH v7 2/3] rust: spi: add SPI driver abstractions Shuai Liu @ 2026-11-13 2:25 ` Shuai Liu 1 sibling, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add a sample driver for the Rust SPI abstractions to demonstrate their usage. Signed-off-by: Shuai Liu <847807867@qq.com> --- samples/rust/Kconfig | 11 ++++++ samples/rust/Makefile | 1 + samples/rust/rust_driver_spi.rs | 66 +++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 samples/rust/rust_driver_spi.rs diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 31d62533ef25f..f99bf52654a15 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -84,6 +84,17 @@ config SAMPLE_RUST_DEBUGFS_SCOPED If unsure, say N. +config SAMPLE_RUST_DRIVER_SPI + tristate "SPI Driver" + depends on SPI=y + help + This option builds the Rust SPI driver sample. + + To compile this as a module, choose M here: + the module will be called rust_driver_spi. + + If unsure, say N. + config SAMPLE_RUST_DRIVER_I2C tristate "I2C Driver" depends on I2C=y diff --git a/samples/rust/Makefile b/samples/rust/Makefile index b986b681cde5a..efe04638a990b 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o obj-$(CONFIG_SAMPLE_RUST_DEBUGFS_SCOPED) += rust_debugfs_scoped.o obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C) += rust_driver_i2c.o +obj-$(CONFIG_SAMPLE_RUST_DRIVER_SPI) += rust_driver_spi.o obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT) += rust_i2c_client.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o diff --git a/samples/rust/rust_driver_spi.rs b/samples/rust/rust_driver_spi.rs new file mode 100644 index 0000000000000..7eee7b7357947 --- /dev/null +++ b/samples/rust/rust_driver_spi.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust SPI driver sample. + +use kernel::{ + device::Core, + of, + prelude::*, + spi, // +}; + +struct SampleDriver; + +kernel::spi_device_table! { + SPI_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(spi::DeviceId::new(c"rust_driver_spi"), 0)] +} + +kernel::of_device_table! { + OF_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(of::DeviceId::new(c"test,rust_driver_spi"), 0)] +} + +impl spi::Driver for SampleDriver { + type IdInfo = u32; + type Data<'bound> = Self; + + const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); + + fn probe<'bound>( + sdev: &'bound spi::SpiDevice<Core<'_>>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self, Error> + 'bound { + let dev = sdev.as_ref(); + + dev_info!(dev, "Probe Rust SPI driver sample.\n"); + dev_info!(dev, "max_speed_hz: {}.\n", sdev.max_speed_hz()); + dev_info!(dev, "bits_per_word: {}.\n", sdev.bits_per_word()); + dev_info!(dev, "mode: {:#x}.\n", sdev.mode()); + + if let Some(info) = info { + dev_info!(dev, "Probed with info: '{}'.\n", info); + } + + Ok(Self) + } + + fn shutdown<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Shutdown Rust SPI driver sample.\n"); + } + + fn unbind<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Unbind Rust SPI driver sample.\n"); + } +} + +kernel::module_spi_driver! { + type: SampleDriver, + name: "rust_driver_spi", + authors: ["Shuai Liu"], + description: "Rust SPI driver", + license: "GPL v2", +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v7 1/3] rust: helpers: add SPI helpers 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu 2026-11-13 2:25 ` [PATCH v7 1/3] rust: helpers: add SPI helpers Shuai Liu [not found] ` <20261113022539.601421-1-847807867@qq.com> @ 2026-11-13 2:25 ` Shuai Liu [not found] ` <20261113022552.601873-1-847807867@qq.com> ` (2 subsequent siblings) 5 siblings, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add C helpers for the SPI functions that are `static inline` in C and therefore cannot be accessed from Rust directly: spi_unregister_driver(), spi_write() and spi_read(). The helpers are guarded by CONFIG_SPI, since the SPI core functions they call are not available when SPI support is disabled. Also include <linux/spi/spi.h> in the bindgen bindings helper, so that the Rust side can access the SPI data types. Signed-off-by: Shuai Liu <847807867@qq.com> --- rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/spi.c | 26 ++++++++++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 rust/helpers/spi.c diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index c706dda5b5ca7..c9062aae959a1 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -88,6 +88,7 @@ #include <linux/security.h> #include <linux/serdev.h> #include <linux/slab.h> +#include <linux/spi/spi.h> #include <linux/sys_soc.h> #include <linux/task_work.h> #include <linux/tracepoint.h> diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 9bb850294a2f3..6b0f50c12f9ca 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -96,6 +96,7 @@ #include "serdev.c" #include "signal.c" #include "slab.c" +#include "spi.c" #include "spinlock.c" #include "string.c" #include "srcu.c" diff --git a/rust/helpers/spi.c b/rust/helpers/spi.c new file mode 100644 index 0000000000000..179a90e014e04 --- /dev/null +++ b/rust/helpers/spi.c @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/spi/spi.h> + +#ifdef CONFIG_SPI + +__rust_helper +void rust_helper_spi_unregister_driver(struct spi_driver *sdrv) +{ + spi_unregister_driver(sdrv); +} + +__rust_helper +void rust_helper_spi_message_init(struct spi_message *msg) +{ + spi_message_init(msg); +} + +__rust_helper +void rust_helper_spi_message_add_tail(struct spi_transfer *t, + struct spi_message *msg) +{ + spi_message_add_tail(t, msg); +} + +#endif -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
[parent not found: <20261113022552.601873-1-847807867@qq.com>]
* [PATCH v7 2/3] rust: spi: add SPI driver abstractions [not found] ` <20261113022552.601873-1-847807867@qq.com> @ 2026-11-13 2:25 ` Shuai Liu 2026-11-13 2:25 ` [PATCH v7 3/3] samples: rust: add SPI driver sample Shuai Liu 1 sibling, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add the Rust abstractions for the SPI driver subsystem, allowing SPI drivers to be written in Rust. This adds the following abstractions: - `spi::DeviceId`: a driver-side device id. - `spi::Adapter`: the registration of SPI drivers, implementing `driver::DriverLayout` and `driver::RegistrationOps`. - `spi::Driver`: the trait that SPI drivers implement, with `probe()`, `shutdown()` and `unbind()` callbacks. - `spi::SpiDevice`: a representation of `struct spi_device`, providing device configuration accessors and device I/O on bound devices. - `spi::Transfer`: a single SPI transfer that transmits, receives, or does both simultaneously (full duplex). - `module_spi_driver!` and `spi_device_table!` macros. The module is only built when CONFIG_SPI is enabled, since the SPI core functions it uses are not available otherwise. The device configuration accessors and the I/O operations are only available on `SpiDevice<Bound>`: an `ARef<SpiDevice>` may outlive the driver's unbind and the device's or controller's unregistration, and the SPI core's transfer path does not check the registration state, so performing I/O on an unbound device is not sound. Moreover, once the device is unbound, another driver may bind to the same `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. via `spi_setup()`), so reading the configuration would be a data race. Driver callbacks receive a `SpiDevice<Core>`, which dereferences to `SpiDevice<Bound>`. Device I/O is built on a single primitive, `SpiDevice::transfer()`, which maps to the C `spi_sync()` API: a sequence of `Transfer`s is submitted as one `spi_message`, executed in order with the chip select asserted for the whole message. The convenience methods `write()`, `read()` and `write_then_read()` are thin wrappers on top of it. `spi_sync()` requires transfer buffers to be DMA-safe, and Rust slices may be located anywhere (e.g. on the stack), so `transfer()` copies all data into DMA-safe bounce buffers before submitting the message and copies received data back afterwards. Unlike the previous approach of leveraging the C convenience wrappers, this maps directly onto the lower-level C APIs and also supports full-duplex transfers, which the C convenience wrappers do not offer. Match data lookup follows the same order as the C core's spi_get_device_match_data(): first the OF/ACPI match data, then the SPI id table. Entries without driver data (e.g. `@none` id tables) are handled gracefully. Signed-off-by: Shuai Liu <847807867@qq.com> Link: https://lore.kernel.org/rust-for-linux/179451185979.339049.12323339081307899766.b4-review@b4/ --- rust/kernel/Kconfig.test | 11 + rust/kernel/lib.rs | 2 + rust/kernel/spi.rs | 673 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 686 insertions(+) create mode 100644 rust/kernel/spi.rs diff --git a/rust/kernel/Kconfig.test b/rust/kernel/Kconfig.test index 3bf4194f28c7c..bda70dcc77934 100644 --- a/rust/kernel/Kconfig.test +++ b/rust/kernel/Kconfig.test @@ -94,6 +94,17 @@ config RUST_BUG_KUNIT_TEST If unsure, say N. +config RUST_SPI_KUNIT_TEST + bool "KUnit tests for the Rust SPI driver abstractions" if !KUNIT_ALL_TESTS + depends on SPI=y + default KUNIT_ALL_TESTS + help + This option enables KUnit tests for the Rust SPI driver + abstractions. These are only for development and testing, not + for regular kernel use cases. + + If unsure, say N. + config RUST_TIME_KUNIT_TEST bool "KUnit tests for the Rust time API" if !KUNIT_ALL_TESTS default KUNIT_ALL_TESTS diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index a4747f75b1632..cbe5a4ed825dc 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -133,6 +133,8 @@ pub mod sizes; #[cfg(CONFIG_SOC_BUS)] pub mod soc; +#[cfg(CONFIG_SPI)] +pub mod spi; #[doc(hidden)] pub mod std_vendor; pub mod str; diff --git a/rust/kernel/spi.rs b/rust/kernel/spi.rs new file mode 100644 index 0000000000000..424563baddb3e --- /dev/null +++ b/rust/kernel/spi.rs @@ -0,0 +1,673 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! SPI Driver subsystem +//! +//! This module adds abstractions for the SPI driver subsystem, allowing drivers to be +//! written in Rust for SPI devices. + +// SPI Driver abstractions. +use crate::{ + acpi, + device, + device_id::{ + RawDeviceId, + RawDeviceIdIndex, // + }, + driver, + error::*, + of, + prelude::*, + sync::aref::AlwaysRefCounted, + types::Opaque, // +}; + +use core::{ + marker::PhantomData, + mem::offset_of, + ptr::NonNull, // +}; + +/// An SPI device id table. +#[repr(transparent)] +#[derive(Clone, Copy)] +pub struct DeviceId(bindings::spi_device_id); + +impl DeviceId { + const SPI_NAME_SIZE: usize = 32; + + /// Create a new device id from an SPI 'id' string. + #[inline(always)] + pub const fn new(id: &'static CStr) -> Self { + let src = id.to_bytes_with_nul(); + build_assert!(src.len() <= Self::SPI_NAME_SIZE, "ID exceeds 32 bytes"); + let mut spi: bindings::spi_device_id = pin_init::zeroed(); + let mut i = 0; + while i < src.len() { + spi.name[i] = src[i]; + i += 1; + } + + Self(spi) + } +} + +// SAFETY: `DeviceId` is a `#[repr(transparent)]` wrapper of `spi_device_id` and does not add +// additional invariants, so it's safe to transmute to `RawType`. +unsafe impl RawDeviceId for DeviceId { + type RawType = bindings::spi_device_id; +} + +// SAFETY: `DRIVER_DATA_OFFSET` is the offset to the `driver_data` field. +unsafe impl RawDeviceIdIndex for DeviceId { + const DRIVER_DATA_OFFSET: usize = core::mem::offset_of!(bindings::spi_device_id, driver_data); +} + +/// IdTable type for SPI +pub type IdTable<T> = &'static dyn kernel::device_id::IdTable<DeviceId, T>; + +/// Create a SPI `IdTable` with its alias for modpost. +#[macro_export] +macro_rules! spi_device_table { + ($($tt:tt)*) => { + $crate::module_device_table!("spi", $crate::spi::DeviceId, $($tt)*); + }; +} + +/// An adapter for the registration of SPI drivers. +pub struct Adapter<T: Driver>(T); + +// SAFETY: +// - `bindings::spi_driver` is a C type declared as `repr(C)`. +// - `T::Data` is the type of the driver's device private data. +// - `struct spi_driver` embeds a `struct device_driver`. +// - `DEVICE_DRIVER_OFFSET` is the correct byte offset to the embedded `struct device_driver`. +unsafe impl<T: Driver> driver::DriverLayout for Adapter<T> { + type DriverType = bindings::spi_driver; + type DriverData<'bound> = T::Data<'bound>; + const DEVICE_DRIVER_OFFSET: usize = core::mem::offset_of!(Self::DriverType, driver); +} + +// SAFETY: A call to `unregister` for a given instance of `DriverType` is guaranteed to be valid if +// a preceding call to `register` has been successful. +unsafe impl<T: Driver> driver::RegistrationOps for Adapter<T> { + unsafe fn register( + sdrv: &Opaque<Self::DriverType>, + name: &'static CStr, + module: &'static ThisModule, + ) -> Result { + build_assert!( + T::ACPI_ID_TABLE.is_some() || T::OF_ID_TABLE.is_some() || T::SPI_ID_TABLE.is_some(), + "At least one of ACPI/OF/Legacy tables must be present when registering an spi driver" + ); + + let spi_table = match T::SPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let of_table = match T::OF_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + let acpi_table = match T::ACPI_ID_TABLE { + Some(table) => table.as_ptr(), + None => core::ptr::null(), + }; + + // SAFETY: It's safe to set the fields of `struct spi_driver` on initialization. + unsafe { + (*sdrv.get()).driver.name = name.as_char_ptr(); + (*sdrv.get()).probe = Some(Self::probe_callback); + (*sdrv.get()).remove = Some(Self::remove_callback); + (*sdrv.get()).shutdown = Some(Self::shutdown_callback); + (*sdrv.get()).id_table = spi_table; + (*sdrv.get()).driver.of_match_table = of_table; + (*sdrv.get()).driver.acpi_match_table = acpi_table; + } + + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + to_result(unsafe { bindings::__spi_register_driver(module.as_ptr(), sdrv.get()) }) + } + + unsafe fn unregister(sdrv: &Opaque<Self::DriverType>) { + // SAFETY: `sdrv` is guaranteed to be a valid `DriverType`. + unsafe { bindings::spi_unregister_driver(sdrv.get()) } + } +} + +impl<T: Driver> Adapter<T> { + extern "C" fn probe_callback(sdev: *mut bindings::spi_device) -> kernel::ffi::c_int { + // SAFETY: The SPI bus only ever calls the probe callback with a valid pointer to a + // `struct spi_device`. + // + // INVARIANT: `sdev` is valid for the duration of `probe_callback()`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // Match the lookup order of the C core's `spi_get_device_match_data()`: first the + // OF/ACPI match data, then the SPI id table. + // + // SAFETY: `sdev` matched data is of type `Self::IdInfo`. + let info = unsafe { <Self as driver::Adapter>::id_info(sdev.as_ref()) } + .or_else(|| Self::spi_id_info(sdev)); + + from_result(|| { + let data = T::probe(sdev, info); + + sdev.as_ref().set_drvdata(data)?; + Ok(0) + }) + } + + extern "C" fn remove_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `sdev` is a valid pointer to a `struct spi_device`. + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `remove_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::unbind(sdev, data); + } + + extern "C" fn shutdown_callback(sdev: *mut bindings::spi_device) { + // SAFETY: `shutdown_callback` is only ever called for a valid `sdev` + let sdev = unsafe { &*sdev.cast::<SpiDevice<device::CoreInternal<'_>>>() }; + + // SAFETY: `shutdown_callback` is only ever called after a successful call to + // `probe_callback`, hence it's guaranteed that `SpiDevice::set_drvdata()` has been called + // and stored a `Pin<KBox<T::Data<'_>>>`. + let data = unsafe { sdev.as_ref().drvdata_borrow::<T::Data<'_>>() }; + + T::shutdown(sdev, data); + } + + /// Returns the driver's private data from the matching entry in the [`spi::IdTable`], if any. + /// + /// If this returns `None`, it means there is no match with an entry in the [`spi::IdTable`]. + fn spi_id_info(dev: &SpiDevice) -> Option<&'static <Self as driver::Adapter>::IdInfo> { + // Ensure the driver has an SPI id table: the entries matched by `spi_get_device_id()` + // below come from the table registered in `register()`, i.e. `T::SPI_ID_TABLE`, which + // guarantees that every `driver_data` field is a valid `T::IdInfo`. + T::SPI_ID_TABLE.as_ref()?; + + // SAFETY: + // - `dev` is guaranteed to be valid while it's alive, and so is `dev.as_raw()`. + // + // `spi_get_device_id()` looks up the registered driver id table using the device's + // modalias and returns either a pointer to a matching entry or `NULL`. + let raw_id = unsafe { bindings::spi_get_device_id(dev.as_raw()) }; + + if raw_id.is_null() { + return None; + } + + // SAFETY: `DeviceId` is a `#[repr(transparent)` wrapper of `struct spi_device_id` and + // does not add additional invariants, so it's safe to transmute. + let id = unsafe { &*raw_id.cast::<DeviceId>() }; + + // SAFETY: `id` comes from the driver's id table (as established by the `T::SPI_ID_TABLE` + // check above). By the safety requirements of `info_unchecked_opt()`, this is either a + // valid `T::IdInfo` or `NULL` (e.g. for a `@none` table), which `info_unchecked_opt()` + // handles by returning `None`. + unsafe { id.info_unchecked_opt::<T::IdInfo>() } + } +} + +impl<T: Driver> driver::Adapter for Adapter<T> { + type IdInfo = T::IdInfo; + + fn of_id_table() -> Option<of::IdTable<Self::IdInfo>> { + T::OF_ID_TABLE + } + + fn acpi_id_table() -> Option<acpi::IdTable<Self::IdInfo>> { + T::ACPI_ID_TABLE + } +} + +/// Declares a kernel module that exposes a single spi driver. +/// +/// # Examples +/// +/// ```ignore +/// kernel::module_spi_driver! { +/// type: MyDriver, +/// name: "Module name", +/// authors: ["Author name"], +/// description: "Description", +/// license: "GPL v2", +/// } +/// ``` +#[macro_export] +macro_rules! module_spi_driver { + ($($f:tt)*) => { + $crate::module_driver!(<T>, $crate::spi::Adapter<T>, { $($f)* }); + }; +} + +/// The spi driver trait. +/// +/// Drivers must implement this trait in order to get a spi driver registered. +/// +/// # Example +/// +///``` +/// # use kernel::{device::Core, spi, of}; +/// +/// struct MyDriver; +/// +/// kernel::spi_device_table!( +/// SPI_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (spi::DeviceId::new(c"rust_driver_spi"), ()) +/// ] +/// ); +/// +/// kernel::of_device_table!( +/// OF_TABLE, +/// <MyDriver as spi::Driver>::IdInfo, +/// [ +/// (of::DeviceId::new(c"test,device"), ()) +/// ] +/// ); +/// +/// impl spi::Driver for MyDriver { +/// type IdInfo = (); +/// type Data<'bound> = Self; +/// const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); +/// const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); +/// +/// fn probe<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// _id_info: Option<&'bound Self::IdInfo>, +/// ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound { +/// Err(ENODEV) +/// } +/// +/// fn shutdown<'bound>( +/// _sdev: &'bound spi::SpiDevice<Core<'_>>, +/// this: Pin<&Self::Data<'bound>>, +/// ) { +/// } +/// } +///``` +pub trait Driver { + /// The type holding information about each device id supported by the driver. + // TODO: Use `associated_type_defaults` once stabilized: + // + // ``` + // type IdInfo: 'static = (); + // ``` + type IdInfo: 'static; + + /// The type of the driver's bus device private data. + type Data<'bound>: Send + 'bound; + + /// The table of device ids supported by the driver. + const SPI_ID_TABLE: Option<IdTable<Self::IdInfo>> = None; + + /// The table of OF device ids supported by the driver. + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None; + + /// The table of ACPI device ids supported by the driver. + const ACPI_ID_TABLE: Option<acpi::IdTable<Self::IdInfo>> = None; + + /// SPI driver probe. + /// + /// Called when a new spi device is added or discovered. + /// Implementers should attempt to initialize the device here. + fn probe<'bound>( + dev: &'bound SpiDevice<device::Core<'_>>, + id_info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self::Data<'bound>, Error> + 'bound; + + /// SPI driver shutdown. + /// + /// Called by the kernel during system reboot or power-off to allow the [`Driver`] to bring the + /// [`SpiDevice`] into a safe state. Implementing this callback is optional. + /// + /// Typical actions include stopping transfers, disabling interrupts, or resetting the hardware + /// to prevent undesired behavior during shutdown. + /// + /// This callback is distinct from final resource cleanup, as the driver instance remains valid + /// after it returns. Any deallocation or teardown of driver-owned resources should instead be + /// handled in `Drop`. + fn shutdown<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } + + /// SPI driver unbind. + /// + /// Called when the [`SpiDevice`] is unbound from its bound [`Driver`]. Implementing this + /// callback is optional. + /// + /// This callback serves as a place for drivers to perform teardown operations that require a + /// `&Device<Core>` or `&Device<Bound>` reference. For instance, drivers may try to perform I/O + /// operations to gracefully tear down the device. + /// + /// Otherwise, release operations for driver resources should be performed in `Drop`. + fn unbind<'bound>(dev: &'bound SpiDevice<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) { + let _ = (dev, this); + } +} + +/// The spi device representation. +/// +/// This structure represents the Rust abstraction for a C `struct spi_device`. The +/// implementation abstracts the usage of an existing C `struct spi_device` that +/// gets passed from the C side. +/// +/// # Invariants +/// +/// A [`SpiDevice`] instance represents a valid `struct spi_device` created by the C portion of +/// the kernel. +#[repr(transparent)] +pub struct SpiDevice<Ctx: device::DeviceContext = device::Normal>( + Opaque<bindings::spi_device>, + PhantomData<Ctx>, +); + +impl<Ctx: device::DeviceContext> SpiDevice<Ctx> { + fn as_raw(&self) -> *mut bindings::spi_device { + self.0.get() + } +} + +/// A single SPI transfer. +/// +/// A transfer transmits, receives, or transmits and receives simultaneously (full duplex). +/// A sequence of transfers is submitted to the device as a single message with +/// [`SpiDevice::transfer`]. +/// +/// The buffers don't need to be DMA-safe: the data is copied into DMA-safe bounce buffers +/// internally, since Rust slices may be located anywhere (e.g. on the stack). +pub struct Transfer<'buf> { + tx: Option<&'buf [u8]>, + rx: Option<&'buf mut [u8]>, +} + +impl<'buf> Transfer<'buf> { + /// Creates a transfer that transmits the data in `tx`. + pub fn write(tx: &'buf [u8]) -> Self { + Self { + tx: Some(tx), + rx: None, + } + } + + /// Creates a transfer that receives data into `rx`. + pub fn read(rx: &'buf mut [u8]) -> Self { + Self { + tx: None, + rx: Some(rx), + } + } + + /// Creates a full-duplex transfer: `tx` is transmitted while `rx` is received + /// simultaneously. + /// + /// The two buffers must have the same length. Controllers with the + /// `SPI_CONTROLLER_HALF_DUPLEX` flag (or devices in 3-wire mode) reject full-duplex + /// transfers with [`EINVAL`]. + pub fn full_duplex(tx: &'buf [u8], rx: &'buf mut [u8]) -> Self { + Self { + tx: Some(tx), + rx: Some(rx), + } + } +} + +/// Device configuration accessors and I/O operations, restricted to bound devices. +/// +/// An `ARef<SpiDevice>` (i.e. a `SpiDevice<Normal>`) may outlive the driver's unbind and the +/// device's or controller's unregistration. The SPI core's transfer path does not check the +/// registration state, and the controller driver's resources (e.g. `spi->controller_state` or +/// MMIO mappings) may already have been released, so performing I/O on an unbound device is not +/// sound. Likewise, once the device is unbound, another driver may bind to the same +/// `struct spi_device` and mutate the device configuration with plain, non-atomic writes (e.g. +/// via `spi_setup()`), so reading the configuration accessors on an unbound device would be a +/// data race. Restricting these operations to [`SpiDevice<Bound>`] guarantees that the device is +/// still bound to a driver; driver callbacks receive a `SpiDevice<Core>`, which dereferences to +/// `SpiDevice<Bound>`. +impl SpiDevice<device::Bound> { + /// Returns the maximum speed of the SPI device. + #[inline] + pub fn max_speed_hz(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).max_speed_hz } + } + + /// Returns the number of bits per word of the SPI device. + #[inline] + pub fn bits_per_word(&self) -> u8 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).bits_per_word } + } + + /// Returns the mode flags of the SPI device. + #[inline] + pub fn mode(&self) -> u32 { + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. + unsafe { (*self.as_raw()).mode } + } + + /// Executes a sequence of [`Transfer`]s as a single SPI message. + /// + /// This is the primitive that all I/O methods are built on; it maps to the C `spi_sync()` + /// API. The transfers are executed in order with the chip select asserted for the whole + /// message. + /// + /// # Examples + /// + /// ```ignore + /// use kernel::spi::{self, Transfer}; + /// + /// fn read_register(dev: &spi::SpiDevice<kernel::device::Bound>, reg: u8) -> Result<u8> { + /// let cmd = [reg]; + /// let mut val = [0u8; 1]; + /// dev.transfer(&mut [Transfer::write(&cmd), Transfer::read(&mut val)])?; + /// Ok(val[0]) + /// } + /// ``` + pub fn transfer(&self, transfers: &mut [Transfer<'_>]) -> Result { + if transfers.is_empty() { + return Err(EINVAL); + } + + struct Bounce { + tx: KVec<u8>, + rx: KVec<u8>, + } + + // `spi_sync()` requires transfer buffers to be DMA-safe, but Rust slices may be + // located anywhere (e.g. on the stack), so the data is copied into DMA-safe bounce + // buffers. + let mut bounces: KVec<Bounce> = KVec::with_capacity(transfers.len(), GFP_KERNEL)?; + let mut xfers: KVec<bindings::spi_transfer> = + KVec::with_capacity(transfers.len(), GFP_KERNEL)?; + + for t in transfers.iter() { + if let (Some(tx), Some(rx)) = (&t.tx, &t.rx) { + if tx.len() != rx.len() { + return Err(EINVAL); + } + } + + let tx_len = t.tx.map_or(0, |buf| buf.len()); + let rx_len = t.rx.as_deref().map_or(0, |buf| buf.len()); + let len = tx_len.max(rx_len); + if len == 0 || len > u32::MAX as usize { + return Err(EINVAL); + } + + let tx = t.tx.unwrap_or(&[]); + let mut tx_bounce = KVec::with_capacity(tx.len(), GFP_KERNEL)?; + tx_bounce.extend_from_slice(tx, GFP_KERNEL)?; + + let mut rx_bounce = KVec::with_capacity(rx_len, GFP_KERNEL)?; + rx_bounce.resize(rx_len, 0, GFP_KERNEL)?; + + let xfer = bindings::spi_transfer { + tx_buf: if tx_bounce.is_empty() { + core::ptr::null() + } else { + tx_bounce.as_ptr().cast() + }, + rx_buf: if rx_bounce.is_empty() { + core::ptr::null_mut() + } else { + rx_bounce.as_mut_ptr().cast() + }, + len: len as u32, + ..pin_init::zeroed() + }; + xfers.push(xfer, GFP_KERNEL)?; + bounces.push( + Bounce { + tx: tx_bounce, + rx: rx_bounce, + }, + GFP_KERNEL, + )?; + } + + let mut msg: bindings::spi_message = pin_init::zeroed(); + + // SAFETY: `msg` is a valid `struct spi_message`. + unsafe { bindings::spi_message_init(&mut msg) }; + + for xfer in xfers.iter_mut() { + // SAFETY: `xfer` is a valid `struct spi_transfer` and `msg` has been initialized + // by `spi_message_init()` above. + unsafe { bindings::spi_message_add_tail(xfer, &mut msg) }; + } + + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a valid pointer to a + // `struct spi_device`. `msg` and the `struct spi_transfer`s linked into it are valid + // for the duration of the call, and `spi_sync()` is synchronous, so they are not + // accessed by the C core after it returns. + to_result(unsafe { bindings::spi_sync(self.as_raw(), &mut msg) })?; + + for (t, bounce) in transfers.iter_mut().zip(bounces.iter_mut()) { + if let Some(rx) = t.rx.as_deref_mut() { + rx.copy_from_slice(&bounce.rx); + } + } + + Ok(()) + } + + /// Writes the data from `buf` to the SPI device. + #[inline] + pub fn write(&self, buf: &[u8]) -> Result { + self.transfer(&mut [Transfer::write(buf)]) + } + + /// Reads data from the SPI device into `buf`. + #[inline] + pub fn read(&self, buf: &mut [u8]) -> Result { + self.transfer(&mut [Transfer::read(buf)]) + } + + /// Writes the data from `write_buf` to the SPI device, then reads data from the SPI device + /// into `read_buf`, with the chip select asserted for the whole operation. + /// + /// This performs the two phases sequentially; to transmit and receive simultaneously, use + /// [`Transfer::full_duplex`] with [`SpiDevice::transfer`]. + #[inline] + pub fn write_then_read(&self, write_buf: &[u8], read_buf: &mut [u8]) -> Result { + self.transfer(&mut [Transfer::write(write_buf), Transfer::read(read_buf)]) + } +} + +// SAFETY: `SpiDevice` is a transparent wrapper of `struct spi_device`. +// The offset is guaranteed to point to a valid device field inside `SpiDevice`. +unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for SpiDevice<Ctx> { + const OFFSET: usize = offset_of!(bindings::spi_device, dev); +} + +// SAFETY: `SpiDevice` is a transparent wrapper of a type that doesn't depend on +// `SpiDevice`'s generic argument. +kernel::impl_device_context_deref!(unsafe { SpiDevice }); +kernel::impl_device_context_into_aref!(SpiDevice); + +// SAFETY: Instances of `SpiDevice` are always reference-counted. +unsafe impl AlwaysRefCounted for SpiDevice { + fn inc_ref(&self) { + // SAFETY: The existence of a shared reference guarantees that the refcount is non-zero. + unsafe { bindings::get_device(self.as_ref().as_raw()) }; + } + + unsafe fn dec_ref(obj: NonNull<Self>) { + // SAFETY: The safety requirements guarantee that the refcount is non-zero. + unsafe { bindings::put_device(&raw mut (*obj.as_ref().as_raw()).dev) } + } +} + +impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for SpiDevice<Ctx> { + fn as_ref(&self) -> &device::Device<Ctx> { + let raw = self.as_raw(); + // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid + // `struct spi_device`. + let dev = unsafe { &raw mut (*raw).dev }; + + // SAFETY: `dev` points to a valid `struct device`. + unsafe { device::Device::from_raw(dev) } + } +} + +// SAFETY: A `SpiDevice` is always reference-counted and can be released from any thread. +unsafe impl Send for SpiDevice {} + +// SAFETY: `SpiDevice` can be shared among threads because `SpiDevice<Normal>` has no methods +// that could mutate the device state or race with the C core (the configuration accessors and +// I/O operations are restricted to `SpiDevice<Bound>`). +unsafe impl Sync for SpiDevice {} + +// SAFETY: Same as `SpiDevice<Normal>` -- the underlying `struct spi_device` is the same; +// `Bound` is a zero-sized type-state marker that does not affect thread safety. +unsafe impl Sync for SpiDevice<device::Bound> {} + +#[cfg(CONFIG_RUST_SPI_KUNIT_TEST)] +#[kunit_tests(rust_kernel_spi)] +mod tests { + use super::*; + + #[test] + fn device_id_name_size() { + assert_eq!(DeviceId::SPI_NAME_SIZE, bindings::SPI_NAME_SIZE as usize); + } + + #[test] + fn device_id_new_short_name() { + let id = DeviceId::new(c"rust_driver_spi"); + + let expected: &[u8] = b"rust_driver_spi\0"; + assert_eq!(&id.0.name[..expected.len()], expected); + + // The remaining bytes must be zeroed. + assert!(id.0.name[expected.len()..].iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_empty_name() { + let id = DeviceId::new(c""); + + assert!(id.0.name.iter().all(|&byte| byte == 0)); + } + + #[test] + fn device_id_new_max_length_name() { + // 31 bytes plus the NUL terminator is the maximum accepted name length. + let id = DeviceId::new(c"abcdefghijklmnopqrstuvwxyz01234"); + + let expected: &[u8] = b"abcdefghijklmnopqrstuvwxyz01234\0"; + assert_eq!(&id.0.name[..], expected); + } +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v7 3/3] samples: rust: add SPI driver sample [not found] ` <20261113022552.601873-1-847807867@qq.com> 2026-11-13 2:25 ` [PATCH v7 2/3] rust: spi: add SPI driver abstractions Shuai Liu @ 2026-11-13 2:25 ` Shuai Liu 1 sibling, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-11-13 2:25 UTC (permalink / raw) To: linux-spi Cc: rust-for-linux, Mark Brown, ojeda, dakr, linux-kernel, 847807867 Add a sample driver for the Rust SPI abstractions to demonstrate their usage. Signed-off-by: Shuai Liu <847807867@qq.com> --- samples/rust/Kconfig | 11 ++++++ samples/rust/Makefile | 1 + samples/rust/rust_driver_spi.rs | 66 +++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 samples/rust/rust_driver_spi.rs diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 31d62533ef25f..f99bf52654a15 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -84,6 +84,17 @@ config SAMPLE_RUST_DEBUGFS_SCOPED If unsure, say N. +config SAMPLE_RUST_DRIVER_SPI + tristate "SPI Driver" + depends on SPI=y + help + This option builds the Rust SPI driver sample. + + To compile this as a module, choose M here: + the module will be called rust_driver_spi. + + If unsure, say N. + config SAMPLE_RUST_DRIVER_I2C tristate "I2C Driver" depends on I2C=y diff --git a/samples/rust/Makefile b/samples/rust/Makefile index b986b681cde5a..efe04638a990b 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o obj-$(CONFIG_SAMPLE_RUST_DEBUGFS_SCOPED) += rust_debugfs_scoped.o obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C) += rust_driver_i2c.o +obj-$(CONFIG_SAMPLE_RUST_DRIVER_SPI) += rust_driver_spi.o obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT) += rust_i2c_client.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o diff --git a/samples/rust/rust_driver_spi.rs b/samples/rust/rust_driver_spi.rs new file mode 100644 index 0000000000000..7eee7b7357947 --- /dev/null +++ b/samples/rust/rust_driver_spi.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust SPI driver sample. + +use kernel::{ + device::Core, + of, + prelude::*, + spi, // +}; + +struct SampleDriver; + +kernel::spi_device_table! { + SPI_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(spi::DeviceId::new(c"rust_driver_spi"), 0)] +} + +kernel::of_device_table! { + OF_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(of::DeviceId::new(c"test,rust_driver_spi"), 0)] +} + +impl spi::Driver for SampleDriver { + type IdInfo = u32; + type Data<'bound> = Self; + + const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); + + fn probe<'bound>( + sdev: &'bound spi::SpiDevice<Core<'_>>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self, Error> + 'bound { + let dev = sdev.as_ref(); + + dev_info!(dev, "Probe Rust SPI driver sample.\n"); + dev_info!(dev, "max_speed_hz: {}.\n", sdev.max_speed_hz()); + dev_info!(dev, "bits_per_word: {}.\n", sdev.bits_per_word()); + dev_info!(dev, "mode: {:#x}.\n", sdev.mode()); + + if let Some(info) = info { + dev_info!(dev, "Probed with info: '{}'.\n", info); + } + + Ok(Self) + } + + fn shutdown<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Shutdown Rust SPI driver sample.\n"); + } + + fn unbind<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Unbind Rust SPI driver sample.\n"); + } +} + +kernel::module_spi_driver! { + type: SampleDriver, + name: "rust_driver_spi", + authors: ["Shuai Liu"], + description: "Rust SPI driver", + license: "GPL v2", +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v7 0/3] rust: spi: add SPI driver abstractions 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu ` (3 preceding siblings ...) [not found] ` <20261113022552.601873-1-847807867@qq.com> @ 2026-11-13 12:25 ` Mark Brown 2026-11-13 12:54 ` Mark Brown 5 siblings, 0 replies; 14+ messages in thread From: Mark Brown @ 2026-11-13 12:25 UTC (permalink / raw) To: Shuai Liu; +Cc: linux-spi, rust-for-linux, ojeda, dakr, linux-kernel [-- Attachment #1: Type: text/plain, Size: 768 bytes --] On Fri, Nov 13, 2026 at 10:05:28AM +0800, Shuai Liu wrote: > Rework the device I/O to map onto the lower-level C APIs, as suggested > by Mark Brown [1]: instead of leveraging the C convenience wrappers > (spi_write(), spi_read() and spi_write_then_read()), all device I/O is > now built on a single `SpiDevice::transfer()` primitive that maps onto > spi_sync(). The convenience methods `write()`, `read()` and > `write_then_read()` remain as thin wrappers on top of `transfer()`. Please don't send new patches in reply to old patches or serieses, this makes it harder for both people and tools to understand what is going on - it can bury things in mailboxes and make it difficult to keep track of what current patches are, both for the new patches and the old ones. [-- Attachment #2: signature.asc --] [-- Type: application/pgp-signature, Size: 488 bytes --] ^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [PATCH v7 0/3] rust: spi: add SPI driver abstractions 2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu ` (4 preceding siblings ...) 2026-11-13 12:25 ` [PATCH v7 0/3] rust: spi: add SPI driver abstractions Mark Brown @ 2026-11-13 12:54 ` Mark Brown 5 siblings, 0 replies; 14+ messages in thread From: Mark Brown @ 2026-11-13 12:54 UTC (permalink / raw) To: Shuai Liu; +Cc: linux-spi, rust-for-linux, ojeda, dakr, linux-kernel [-- Attachment #1: Type: text/plain, Size: 547 bytes --] On Fri, Nov 13, 2026 at 10:05:28AM +0800, Shuai Liu wrote: > Rework the device I/O to map onto the lower-level C APIs, as suggested > by Mark Brown [1]: instead of leveraging the C convenience wrappers > (spi_write(), spi_read() and spi_write_then_read()), all device I/O is > now built on a single `SpiDevice::transfer()` primitive that maps onto > spi_sync(). The convenience methods `write()`, `read()` and > `write_then_read()` remain as thin wrappers on top of `transfer()`. This doesn't apply against current code, please check and resend. [-- Attachment #2: signature.asc --] [-- Type: application/pgp-signature, Size: 488 bytes --] ^ permalink raw reply [flat|nested] 14+ messages in thread
* [PATCH v6 3/3] samples: rust: add SPI driver sample [not found] <20261027054209.904654-1-847807867@qq.com> 2026-10-27 5:42 ` [PATCH v6 1/3] rust: helpers: add SPI helpers Shuai Liu 2026-10-27 5:42 ` [PATCH v6 2/3] rust: spi: add SPI driver abstractions Shuai Liu @ 2026-10-27 5:42 ` Shuai Liu 2 siblings, 0 replies; 14+ messages in thread From: Shuai Liu @ 2026-10-27 5:42 UTC (permalink / raw) To: linux-spi, rust-for-linux; +Cc: broonie, ojeda, dakr, linux-kernel, Shuai Liu Add a sample driver for the Rust SPI abstractions to demonstrate their usage. Signed-off-by: Shuai Liu <847807867@qq.com> --- samples/rust/Kconfig | 11 ++++++ samples/rust/Makefile | 1 + samples/rust/rust_driver_spi.rs | 66 +++++++++++++++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 samples/rust/rust_driver_spi.rs diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig index 31d62533ef25..f99bf52654a1 100644 --- a/samples/rust/Kconfig +++ b/samples/rust/Kconfig @@ -84,6 +84,17 @@ config SAMPLE_RUST_DEBUGFS_SCOPED If unsure, say N. +config SAMPLE_RUST_DRIVER_SPI + tristate "SPI Driver" + depends on SPI=y + help + This option builds the Rust SPI driver sample. + + To compile this as a module, choose M here: + the module will be called rust_driver_spi. + + If unsure, say N. + config SAMPLE_RUST_DRIVER_I2C tristate "I2C Driver" depends on I2C=y diff --git a/samples/rust/Makefile b/samples/rust/Makefile index b986b681cde5..efe04638a990 100644 --- a/samples/rust/Makefile +++ b/samples/rust/Makefile @@ -8,6 +8,7 @@ obj-$(CONFIG_SAMPLE_RUST_DEBUGFS) += rust_debugfs.o obj-$(CONFIG_SAMPLE_RUST_DEBUGFS_SCOPED) += rust_debugfs_scoped.o obj-$(CONFIG_SAMPLE_RUST_DMA) += rust_dma.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_I2C) += rust_driver_i2c.o +obj-$(CONFIG_SAMPLE_RUST_DRIVER_SPI) += rust_driver_spi.o obj-$(CONFIG_SAMPLE_RUST_I2C_CLIENT) += rust_i2c_client.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI) += rust_driver_pci.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM) += rust_driver_platform.o diff --git a/samples/rust/rust_driver_spi.rs b/samples/rust/rust_driver_spi.rs new file mode 100644 index 000000000000..7eee7b735794 --- /dev/null +++ b/samples/rust/rust_driver_spi.rs @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Rust SPI driver sample. + +use kernel::{ + device::Core, + of, + prelude::*, + spi, // +}; + +struct SampleDriver; + +kernel::spi_device_table! { + SPI_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(spi::DeviceId::new(c"rust_driver_spi"), 0)] +} + +kernel::of_device_table! { + OF_TABLE, + <SampleDriver as spi::Driver>::IdInfo, + [(of::DeviceId::new(c"test,rust_driver_spi"), 0)] +} + +impl spi::Driver for SampleDriver { + type IdInfo = u32; + type Data<'bound> = Self; + + const SPI_ID_TABLE: Option<spi::IdTable<Self::IdInfo>> = Some(&SPI_TABLE); + const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE); + + fn probe<'bound>( + sdev: &'bound spi::SpiDevice<Core<'_>>, + info: Option<&'bound Self::IdInfo>, + ) -> impl PinInit<Self, Error> + 'bound { + let dev = sdev.as_ref(); + + dev_info!(dev, "Probe Rust SPI driver sample.\n"); + dev_info!(dev, "max_speed_hz: {}.\n", sdev.max_speed_hz()); + dev_info!(dev, "bits_per_word: {}.\n", sdev.bits_per_word()); + dev_info!(dev, "mode: {:#x}.\n", sdev.mode()); + + if let Some(info) = info { + dev_info!(dev, "Probed with info: '{}'.\n", info); + } + + Ok(Self) + } + + fn shutdown<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Shutdown Rust SPI driver sample.\n"); + } + + fn unbind<'bound>(sdev: &'bound spi::SpiDevice<Core<'_>>, _this: Pin<&Self>) { + dev_info!(sdev.as_ref(), "Unbind Rust SPI driver sample.\n"); + } +} + +kernel::module_spi_driver! { + type: SampleDriver, + name: "rust_driver_spi", + authors: ["Shuai Liu"], + description: "Rust SPI driver", + license: "GPL v2", +} -- 2.43.0 ^ permalink raw reply [flat|nested] 14+ messages in thread
end of thread, other threads:[~2026-11-13 12:55 UTC | newest]
Thread overview: 14+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
[not found] <20261027054209.904654-1-847807867@qq.com>
2026-10-27 5:42 ` [PATCH v6 1/3] rust: helpers: add SPI helpers Shuai Liu
2026-10-27 5:42 ` [PATCH v6 2/3] rust: spi: add SPI driver abstractions Shuai Liu
2026-11-12 19:30 ` Mark Brown
2026-11-13 2:04 ` Shuai Liu
2026-11-13 2:05 ` [PATCH v7 0/3] " Shuai Liu
2026-11-13 2:25 ` [PATCH v7 1/3] rust: helpers: add SPI helpers Shuai Liu
[not found] ` <20261113022539.601421-1-847807867@qq.com>
2026-11-13 2:25 ` [PATCH v7 2/3] rust: spi: add SPI driver abstractions Shuai Liu
2026-11-13 2:25 ` [PATCH v7 3/3] samples: rust: add SPI driver sample Shuai Liu
2026-11-13 2:25 ` [PATCH v7 1/3] rust: helpers: add SPI helpers Shuai Liu
[not found] ` <20261113022552.601873-1-847807867@qq.com>
2026-11-13 2:25 ` [PATCH v7 2/3] rust: spi: add SPI driver abstractions Shuai Liu
2026-11-13 2:25 ` [PATCH v7 3/3] samples: rust: add SPI driver sample Shuai Liu
2026-11-13 12:25 ` [PATCH v7 0/3] rust: spi: add SPI driver abstractions Mark Brown
2026-11-13 12:54 ` Mark Brown
2026-10-27 5:42 ` [PATCH v6 3/3] samples: rust: add SPI driver sample Shuai Liu
This is a public inbox, see mirroring instructions for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®