rust: phy: extend abstractions for real-world PHY drivers
Subsystems (5)
v2 cover rust: phy: extend abstractions for real-world PHY drivers
This series extends the Rust PHY abstractions in rust/kernel/net/phy.rs with features needed to write production-quality Rust PHY drivers, and adds a Realtek RTL8211F driver as the first user of these APIs.
Patches 1-4 add new Device accessors, register manipulation helpers, driver callbacks (config_init, read_page/write_page, config_intr, handle_interrupt), and interrupt support infrastructure.
Patch 5 adds a Rust RTL8211F Gigabit Ethernet PHY driver that exercises all the new abstractions. The driver implements RGMII delay configuration, PHY EEE disable, paged register access, and interrupt-driven link detection. ALDPS, CLKOUT, and WoL are omitted as they require per-device private data not yet available in the abstraction. PME interrupts are not handled for the same reason.
config_init was previously proposed in an RFC for the Rockchip PHY driver [1] but not merged at that time. This series re-introduces it in a form consistent with the existing vtable infrastructure.
Changes since v1:
- Added cover letter (Andrew)
- Fixed Subject prefix to net-next (Andrew)
- Added RTL8211F driver as API user (Andrew)
- Fixed rustfmt issues reported by kernel test robot
- Removed RGMII from interface() doc example (Andrew)
[1] https://lore.kernel.org/lkml/20240201-rockchip-rust-phy_depend-v2-0-c5fa4faab924@christina-quast.de/
Artem Lytkin (5):
rust: phy: add read-only device field accessors
rust: phy: add paged register access and bit manipulation helpers
rust: phy: add config_init, read_page, and write_page callbacks
rust: phy: add interrupt support
net: phy: realtek: add Rust RTL8211F PHY driver
drivers/net/phy/realtek/Kconfig | 12 ++ drivers/net/phy/realtek/Makefile | 1 + drivers/net/phy/realtek/rtl8211f_rust.rs | 140 +++++++++++++++++++ rust/kernel/net/phy.rs | 260 +++++++++++++++++++++++++++++++ 4 files changed, 413 insertions(+) create mode 100644 drivers/net/phy/realtek/rtl8211f_rust.rs
PATCH v2 1/5 rust: phy: add read-only device field accessors
Add getter methods for commonly needed PHY device fields:
- speed(): Returns the current link speed as i32, matching the C struct field type (int speed).
- duplex(): Returns the current duplex mode as DuplexMode enum. Only the setter (set_duplex) existed previously.
- interface(): Returns the PHY interface mode (RGMII, SGMII, etc.) as a raw phy_interface_t value. A typed Rust enum is future work since phy_interface_t has 40+ variants tied to DT bindings.
- irq(): Returns the PHY's IRQ number.
These accessors are needed by Rust PHY drivers that must inspect hardware state, particularly during config_init and read_status callbacks.
--- rust/kernel/net/phy.rs | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+)
rust/kernel/net/phy.rs +41 -0
@@ -179,6 +179,47 @@ pub fn set_duplex(&mut self, mode: DuplexMode) {unsafe { (*phydev).duplex = vas c_int }; } +/// Gets the current speed setting. +pub fn speed (&self) ->i32 { +let phydev = self.0 .get (); +// SAFETY: The struct invariant ensures that we may access +// this field without additional synchronization. +unsafe { (*phydev).speed } + } + +/// Gets the current duplex mode. +pub fn duplex (&self) ->DuplexMode { +let phydev = self.0 .get (); +// SAFETY: The struct invariant ensures that we may access +// this field without additional synchronization. +let v =unsafe { (*phydev).duplex }; +match vas u32 { + bindings::DUPLEX_FULL =>DuplexMode ::Full , + bindings::DUPLEX_HALF =>DuplexMode ::Half , + _ =>DuplexMode ::Unknown , + } + } + +/// Gets the PHY interface mode as a raw `phy_interface_t` value. +/// +/// Common values include `bindings::phy_interface_t_PHY_INTERFACE_MODE_RGMII`, +/// `bindings::phy_interface_t_PHY_INTERFACE_MODE_SGMII`, etc. +/// A typed Rust enum is planned for future work. +pub fn interface (&self) ->u32 { +let phydev = self.0 .get (); +// SAFETY: The struct invariant ensures that we may access +// this field without additional synchronization. +unsafe { (*phydev).interface } + } + +/// Gets the PHY's IRQ number. +pub fn irq (&self) ->i32 { +let phydev = self.0 .get (); +// SAFETY: The struct invariant ensures that we may access +// this field without additional synchronization. +unsafe { (*phydev).irq } + } +/// Reads a PHY register. // This function reads a hardware register and updates the stats so takes `&mut self`. pub fn read <R : reg::Register >(&mut self, reg:R ) ->Result <u16 > {
Signature · 1 line
2.43.0
PATCH v2 2/5 rust: phy: add paged register access and bit manipulation helpers
In reply to Artem LytkinAdd Device methods for register manipulation beyond simple read/write:
- write_paged(): Writes a register on a specific page, completing the paged access surface (read_paged already existed upstream). Wraps phy_write_paged().
- modify() / modify_paged(): Atomic read-modify-write operations that clear bits in mask and set bits in set. Wraps phy_modify() and phy_modify_paged(). These return Result (not the old register value) since the C functions return 0 on success.
- set_bits() / clear_bits(): Convenience wrappers around modify() for the common case of setting or clearing specific bits.
These helpers are heavily used by real-world PHY drivers for configuring vendor-specific registers without races.
--- rust/kernel/net/phy.rs | 45 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-)
rust/kernel/net/phy.rs +43 -2
@@ -202,8 +202,7 @@ pub fn duplex(&self) -> DuplexMode {/// Gets the PHY interface mode as a raw `phy_interface_t` value. /// -/// Common values include `bindings::phy_interface_t_PHY_INTERFACE_MODE_RGMII`, -/// `bindings::phy_interface_t_PHY_INTERFACE_MODE_SGMII`, etc. +/// Values are `bindings::phy_interface_t_PHY_INTERFACE_MODE_*` constants. /// A typed Rust enum is planned for future work. pub fn interface (&self) ->u32 {let phydev = self.0 .get ();
@@ -241,6 +240,48 @@ pub fn read_paged(&mut self, page: u16, regnum: u16) -> Result<u16> {to_result (ret).map (|()| retas u16 ) } +/// Writes a paged register. +pub fn write_paged (&mut self, page:u16 , regnum:u16 , val:u16 ) ->Result { +let phydev = self.0 .get (); +// SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. +// So it's just an FFI call. +let ret =unsafe { bindings::phy_write_paged (phydev, page.into (), regnum.into (), val) }; + +to_result (ret) + } + +/// Performs a read-modify-write on a PHY register. +/// +/// Clears the bits set in `mask` and sets the bits in `set`. +pub fn modify (&mut self, regnum:u16 , mask:u16 , set:u16 ) ->Result { +let phydev = self.0 .get (); +// SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. +// So it's just an FFI call. +to_result (unsafe { bindings::phy_modify (phydev, regnum.into (), mask, set) }) + } + +/// Performs a read-modify-write on a paged PHY register. +/// +/// Selects the page, performs the modify, and restores the original page. +pub fn modify_paged (&mut self, page:u16 , regnum:u16 , mask:u16 , set:u16 ) ->Result { +let phydev = self.0 .get (); +// SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. +// So it's just an FFI call. +to_result (unsafe { + bindings::phy_modify_paged (phydev, page.into (), regnum.into (), mask, set) + }) + } + +/// Sets bits in a PHY register. +pub fn set_bits (&mut self, regnum:u16 , val:u16 ) ->Result { + self.modify (regnum,0 , val) + } + +/// Clears bits in a PHY register. +pub fn clear_bits (&mut self, regnum:u16 , val:u16 ) ->Result { + self.modify (regnum, val,0 ) + } +/// Resolves the advertisements into PHY settings. pub fn resolve_aneg_linkmode (&mut self) {let phydev = self.0 .get ();
Signature · 1 line
2.43.0
PATCH v2 3/5 rust: phy: add config_init, read_page, and write_page callbacks
In reply to Artem LytkinAdd three new driver callbacks to the PHY abstraction:
- config_init: Called to initialize the PHY after a reset. This is needed by nearly all real-world PHY drivers to configure vendor-specific registers (RGMII delays, LED settings, etc.). config_init was previously proposed in an RFC for the Rockchip PHY driver but not merged at that time. This re-introduces it in a form consistent with the existing vtable infrastructure.
- read_page / write_page: Required by page-based PHY chips (Realtek, Marvell) for the kernel's paged register access infrastructure. When these callbacks are registered, phy_read_paged(), phy_write_paged(), and phy_modify_paged() use them to switch register pages. Both must be implemented together.
Each callback follows the established Adapter<T> pattern with unsafe extern "C" fn bridging to the Rust Driver trait method, and conditional registration in create_phy_driver() via HAS_* flags generated by the #[vtable] macro.
--- rust/kernel/net/phy.rs | 83 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+)
rust/kernel/net/phy.rs +83 -0
@@ -388,6 +388,51 @@ struct Adapter<T: Driver> { }impl <T :Driver >Adapter <T > { +/// # Safety +/// +/// `phydev` must be passed by the corresponding callback in `phy_driver`. +unsafe extern "C" fn config_init_callback (phydev: *mut bindings::phy_device ) ->c_int { +from_result (|| { +// SAFETY: The C core calls config_init with the PHY mutex held +// (from phy_init_hw), so the accessors on `Device` are okay to call. +let dev =unsafe {Device ::from_raw (phydev) }; +T ::config_init (dev)?; +Ok (0 ) + }) + } + +/// # Safety +/// +/// `phydev` must be passed by the corresponding callback in `phy_driver`. +unsafe extern "C" fn read_page_callback (phydev: *mut bindings::phy_device ) ->c_int { +from_result (|| { +// SAFETY: This callback is called only in contexts +// where we hold `phy_device->lock`, so the accessors on +// `Device` are okay to call. +let dev =unsafe {Device ::from_raw (phydev) }; +let page =T ::read_page (dev)?; +Ok (page.into ()) + }) + } + +/// # Safety +/// +/// `phydev` must be passed by the corresponding callback in `phy_driver`. +unsafe extern "C" fn write_page_callback ( + phydev: *mut bindings::phy_device , + page:c_int , + ) ->c_int { +from_result (|| { +// SAFETY: This callback is called only in contexts +// where we hold `phy_device->lock`, so the accessors on +// `Device` are okay to call. +let dev =unsafe {Device ::from_raw (phydev) }; +let page = u16::try_from (page).map_err (|_| code::EINVAL )?; +T ::write_page (dev, page)?; +Ok (0 ) + }) + } +/// # Safety /// /// `phydev` must be passed by the corresponding callback in `phy_driver`.
@@ -580,6 +625,11 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable { flags: T::FLAGS, phy_id: T::PHY_DEVICE_ID.id(), phy_id_mask: T::PHY_DEVICE_ID.mask_as_int(), + config_init: if T::HAS_CONFIG_INIT { +Some (Adapter ::<T >::config_init_callback) + }else { +None + }, soft_reset: if T::HAS_SOFT_RESET {Some (Adapter ::<T >::soft_reset_callback) }else {
@@ -630,6 +680,16 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable { }else {None }, + read_page: if T::HAS_READ_PAGE { +Some (Adapter ::<T >::read_page_callback) + }else { +None + }, + write_page: if T::HAS_WRITE_PAGE { +Some (Adapter ::<T >::write_page_callback) + }else { +None + }, link_change_notify: if T::HAS_LINK_CHANGE_NOTIFY {Some (Adapter ::<T >::link_change_notify_callback) }else {
@@ -657,6 +717,11 @@ pub trait Driver {/// The default id and mask are zero. const PHY_DEVICE_ID :DeviceId =DeviceId ::new_with_custom_mask (0 ,0 ); +/// Called to initialize the PHY, including after a reset. +fn config_init (_dev: &mut Device ) ->Result { +build_error! (VTABLE_DEFAULT_ERROR ) + } +/// Issues a PHY software reset. fn soft_reset (_dev: &mut Device ) ->Result {build_error! (VTABLE_DEFAULT_ERROR )
@@ -709,6 +774,24 @@ fn write_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16, _val: u16) -> Resultbuild_error! (VTABLE_DEFAULT_ERROR ) } +/// Returns the current PHY register page number. +/// +/// Must be implemented together with [`Driver::write_page`]. The kernel's +/// paged register access infrastructure requires both callbacks to be +/// present. +fn read_page (_dev: &mut Device ) ->Result <u16 > { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Sets the current PHY register page number. +/// +/// Must be implemented together with [`Driver::read_page`]. The kernel's +/// paged register access infrastructure requires both callbacks to be +/// present. +fn write_page (_dev: &mut Device , _page:u16 ) ->Result { +build_error! (VTABLE_DEFAULT_ERROR ) + } +/// Callback for notification of link change. fn link_change_notify (_dev: &mut Device ) {} }
Signature · 1 line
2.43.0
PATCH v2 4/5 rust: phy: add interrupt support
In reply to Artem LytkinAdd interrupt handling support to the Rust PHY abstraction:
New driver callbacks:
- config_intr: Enables or disables PHY link state change interrupts.
- handle_interrupt: Called when the PHY's interrupt fires. Returns IrqReturn (reused from kernel::irq). Unlike other callbacks that use from_result(), this directly returns irqreturn_t matching the C callback signature.
New Device methods:
- trigger_machine(): Schedules a PHY state machine update. Used in interrupt handlers after detecting a link change event.
- phy_error(): Reports a PHY error and transitions the state machine to the error state. Produces a WARN_ON. Must be called with phy_device->lock held (which is the case inside handle_interrupt).
Both callbacks run with phy_device->lock held (from phy_interrupt() in the threaded IRQ context), consistent with the existing callback safety model.
These additions enable Rust PHY drivers to use interrupt-driven link detection, which is required for production-quality drivers like the Realtek RTL8211F.
--- rust/kernel/net/phy.rs | 93 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 3 deletions(-)
rust/kernel/net/phy.rs +90 -3
@@ -6,7 +6,7 @@//! //! C headers: [`include/linux/phy.h`](srctree/include/linux/phy.h). -use crate ::{device_id::RawDeviceId , error::*, prelude::*, types::Opaque }; +use crate ::{device_id::RawDeviceId , error::*, irq::IrqReturn , prelude::*, types::Opaque };use core::{marker::PhantomData , ptr::addr_of_mut};pub mod reg;
@@ -211,6 +211,20 @@ pub fn interface(&self) -> u32 {unsafe { (*phydev).interface } } +/// Returns `true` if PHY interrupts are enabled. +/// +/// This reflects the `phydev->interrupts` field which is set by the PHY +/// core before calling [`Driver::config_intr`] to indicate whether +/// interrupts should be enabled or disabled. +pub fn is_interrupts_enabled (&self) ->bool { +// TODO: the code to access the bit field will be replaced with automatically +// generated code by bindgen when it becomes possible. +// SAFETY: The struct invariant ensures that we may access +// this field without additional synchronization. +let bit_field =unsafe { &(*self.0 .get ())._bitfield_1 }; + bit_field.get (18 ,1 ) ==1 + } +/// Gets the PHY's IRQ number. pub fn irq (&self) ->i32 {let phydev = self.0 .get ();
@@ -358,6 +372,29 @@ pub fn genphy_read_abilities(&mut self) -> Result {// So it's just an FFI call. to_result (unsafe { bindings::genphy_read_abilities (phydev) }) } + +/// Triggers the PHY state machine to run. +/// +/// Used in interrupt handlers to schedule a state machine update +/// after processing an interrupt event. +pub fn trigger_machine (&mut self) { +let phydev = self.0 .get (); +// SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. +// So it's just an FFI call. +unsafe { bindings::phy_trigger_machine (phydev) }; + } + +/// Reports a PHY error and moves the state machine to the error state. +/// +/// Used in interrupt handlers when a register read fails. This will +/// produce a kernel `WARN_ON`. Must be called with `phy_device->lock` +/// held (which is the case inside [`Driver::handle_interrupt`]). +pub fn phy_error (&mut self) { +let phydev = self.0 .get (); +// SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. +// So it's just an FFI call. +unsafe { bindings::phy_error (phydev) }; + } }impl AsRef <kernel::device::Device >for Device {
@@ -393,8 +430,9 @@ impl<T: Driver> Adapter<T> {/// `phydev` must be passed by the corresponding callback in `phy_driver`. unsafe extern "C" fn config_init_callback (phydev: *mut bindings::phy_device ) ->c_int {from_result (|| { -// SAFETY: The C core calls config_init with the PHY mutex held -// (from phy_init_hw), so the accessors on `Device` are okay to call. +// SAFETY: This callback is called only in contexts +// where we hold `phy_device->lock`, so the accessors on +// `Device` are okay to call. let dev =unsafe {Device ::from_raw (phydev) };T ::config_init (dev)?;Ok (0 )
@@ -507,6 +545,30 @@ impl<T: Driver> Adapter<T> {/// # Safety /// /// `phydev` must be passed by the corresponding callback in `phy_driver`. +unsafe extern "C" fn config_intr_callback (phydev: *mut bindings::phy_device ) ->c_int { +from_result (|| { +// SAFETY: This callback is called only in contexts +// where we hold `phy_device->lock`, so the accessors on +// `Device` are okay to call. +let dev =unsafe {Device ::from_raw (phydev) }; +T ::config_intr (dev)?; +Ok (0 ) + }) + } + +/// # Safety +/// +/// `phydev` must be passed by the corresponding callback in `phy_driver`. +unsafe extern "C" fn handle_interrupt_callback ( + phydev: *mut bindings::phy_device , + ) -> bindings::irqreturn_t { +// SAFETY: This callback is called only in contexts +// where we hold `phy_device->lock` (from phy_interrupt), +// so the accessors on `Device` are okay to call. +let dev =unsafe {Device ::from_raw (phydev) }; +T ::handle_interrupt (dev)as core::ffi::c_uint + } +unsafe extern "C" fn config_aneg_callback (phydev: *mut bindings::phy_device ) ->c_int {from_result (|| {// SAFETY: This callback is called only in contexts
@@ -660,6 +722,16 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable { }else {None }, + config_intr: if T::HAS_CONFIG_INTR { +Some (Adapter ::<T >::config_intr_callback) + }else { +None + }, + handle_interrupt: if T::HAS_HANDLE_INTERRUPT { +Some (Adapter ::<T >::handle_interrupt_callback) + }else { +None + }, config_aneg: if T::HAS_CONFIG_ANEG {Some (Adapter ::<T >::config_aneg_callback) }else {
@@ -743,6 +815,21 @@ fn match_phy_device(_dev: &Device) -> bool {false } +/// Enables or disables PHY interrupts. +fn config_intr (_dev: &mut Device ) ->Result { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Handles a PHY interrupt. +/// +/// Called when the PHY's interrupt line fires. The driver should read the +/// interrupt status register to determine the cause and call +/// [`Device::trigger_machine`] to schedule a state machine update. +/// Returns [`IrqReturn::Handled`] if the interrupt was from this PHY. +fn handle_interrupt (_dev: &mut Device ) ->IrqReturn { +build_error! (VTABLE_DEFAULT_ERROR ) + } +/// Configures the advertisement and resets auto-negotiation /// if auto-negotiation is enabled. fn config_aneg (_dev: &mut Device ) ->Result {
Signature · 1 line
2.43.0
PATCH v2 5/5 net: phy: realtek: add Rust RTL8211F PHY driver
In reply to Artem LytkinAdd a Rust implementation of the Realtek RTL8211F Gigabit Ethernet PHY driver. This exercises the extended Rust PHY abstraction with config_init, read_page/write_page, and interrupt support callbacks.
The driver implements:
- config_init: Configures RGMII TX/RX internal delays based on the PHY interface mode, and disables PHY-level EEE so LPI is passed to the MAC. This matches the C driver's essential initialization. ALDPS and CLKOUT are left at hardware defaults since they depend on device tree properties and per-device private data not yet supported by the Rust PHY abstraction.
- read_page / write_page: Standard RTL821x page select register.
- config_intr: Enables/disables link status change interrupts.
- handle_interrupt: Reads INSR and triggers the state machine on link change. PME/WoL interrupts are documented as unsupported.
The PHY ID 0x001cc916 matches the RTL8211F specifically.
--- drivers/net/phy/realtek/Kconfig | 12 +++ drivers/net/phy/realtek/Makefile | 1 + drivers/net/phy/realtek/rtl8211f_rust.rs | 127 +++++++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 drivers/net/phy/realtek/rtl8211f_rust.rs
drivers/net/phy/realtek/Kconfig +12 -0
@@ -13,3 +13,15 @@ config REALTEK_PHY_HWMON Optional hwmon support for the temperature sensor endif # REALTEK_PHY + +config REALTEK_RTL8211F_RUST_PHY + tristate "Rust Realtek RTL8211F PHY driver" + depends on RUST && RUST_PHYLIB_ABSTRACTIONS && !REALTEK_PHY + help + Rust driver for the Realtek RTL8211F Gigabit Ethernet PHY. + This is a Rust implementation demonstrating the extended PHY + abstraction with config_init, paged register access, and + interrupt support. + + To compile this driver as a module, choose M here: the + module will be called rtl8211f_rust.
drivers/net/phy/realtek/Makefile +1 -0
@@ -2,3 +2,4 @@ realtek-y += realtek_main.o realtek-$(CONFIG_REALTEK_PHY_HWMON) += realtek_hwmon.o obj-$(CONFIG_REALTEK_PHY) += realtek.o +obj-$(CONFIG_REALTEK_RTL8211F_RUST_PHY) += rtl8211f_rust.o
drivers/net/phy/realtek/rtl8211f_rust.rs new file +127 -0
127 lines not on this page · raw message
Signature · 1 line
2.43.0
Andrew Lunn
maintainerRe: [PATCH net-next v2 5/5] net: phy: realtek: add Rust RTL8211F PHY driver
Quoted 2 lines · Artem Lytkin
Add a Rust implementation of the Realtek RTL8211F Gigabit Ethernet PHY driver.
We don't want duplicate C and Rust drivers. Sorry.
Just out of interest, what hardware have you tested on?
Andrew
---
pw-bot: cr