rust: phy: add read-only device field accessors
Subsystems (4)
PATCH 1/4 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 2/4 rust: phy: add paged register access and bit manipulation helpers
Add 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 | 43 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+)
rust/kernel/net/phy.rs +43 -0
@@ -241,6 +241,49 @@ 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
kernel test robot
build botRe: [PATCH 2/4] rust: phy: add paged register access and bit manipulation helpers
kernel test robot noticed the following build errors:
Hi Artem,
kernel test robot noticed the following build errors:
[auto build test ERROR on rust/rust-next]
[also build test ERROR on linus/master v7.0-rc5 next-20260323] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Artem-Lytkin/rust-phy-add-paged-register-access-and-bit-manipulation-helpers/20260324-155532 base: https://github.com/Rust-for-Linux/linux rust-next patch link: https://lore.kernel.org/r/20260323201925.8405-2-iprintercanon%40gmail.com patch subject: [PATCH 2/4] rust: phy: add paged register access and bit manipulation helpers config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260324/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260324/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS=\ -fno-crash-diagnostics\ -Wno-error=return-type\ -Wreturn-type\ -funsigned-char\ -Wundef\ -falign-functions=64 W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
make: Entering directory '/kbuild/src/consumer'
make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>> Diff in rust/kernel/net/phy.rs:246:
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) };
+ let ret = unsafe { bindings::phy_write_paged(phydev, page.into(), regnum.into(), val) };
to_result(ret)
}
>> Diff in rust/kernel/net/phy.rs:246:
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) };
+ let ret = unsafe { bindings::phy_write_paged(phydev, page.into(), regnum.into(), val) };
to_result(ret)
}
>> Diff in rust/kernel/net/phy.rs:246:
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) };
+ let ret = unsafe { bindings::phy_write_paged(phydev, page.into(), regnum.into(), val) };
to_result(ret)
} make[2]: *** [Makefile:1912: rustfmt] Error 123
make[2]: Target 'rustfmtcheck' not remade because of errors. make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust' make[1]: *** [Makefile:248: __sub-make] Error 2
make[1]: Target 'rustfmtcheck' not remade because of errors.
make: *** [Makefile:248: __sub-make] Error 2
make: Target 'rustfmtcheck' not remade because of errors.
make: Leaving directory '/kbuild/src/consumer'
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
PATCH 3/4 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
@@ -390,6 +390,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`.
@@ -582,6 +627,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 {
@@ -632,6 +682,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 {
@@ -659,6 +719,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 )
@@ -711,6 +776,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 4/4 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 | 79 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-)
rust/kernel/net/phy.rs +78 -1
@@ -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;
@@ -360,6 +360,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 {
@@ -509,6 +532,35 @@ impl<T: Driver> Adapter<T> {/// # Safety /// /// `phydev` must be passed by the corresponding callback in `phy_driver`. +/// # 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
@@ -662,6 +714,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 {
@@ -745,6 +807,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
kernel test robot
build botRe: [PATCH 4/4] rust: phy: add interrupt support
kernel test robot noticed the following build warnings:
Hi Artem,
kernel test robot noticed the following build warnings:
[auto build test WARNING on rust/rust-next]
[also build test WARNING on linus/master v7.0-rc5 next-20260323] [If your patch is applied to the wrong git tree, kindly drop us a note. And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Artem-Lytkin/rust-phy-add-paged-register-access-and-bit-manipulation-helpers/20260324-155532 base: https://github.com/Rust-for-Linux/linux rust-next patch link: https://lore.kernel.org/r/20260323201925.8405-4-iprintercanon%40gmail.com patch subject: [PATCH 4/4] rust: phy: add interrupt support config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20260324/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) rustc: rustc 1.88.0 (6b00bc388 2025-06-23) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260324/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All warnings (new ones prefixed by >>):
>> warning: unsafe function's docs are missing a `# Safety` section
--> rust/kernel/net/phy.rs:564:5
|
564 | unsafe extern "C" fn config_aneg_callback(phydev: *mut bindings::phy_device) -> c_int {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc
= note: -W clippy::missing-safety-doc implied by -W clippy::all
= help: to override -W clippy::all add #[allow(clippy::missing_safety_doc)]
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
Quoted 1 line · Artem Lytkin
Add getter methods for commonly needed PHY device fields:
Hi Artem
Please always include a patch [0/X] which explains the big picture of the patchset. It will also be used as part of the git merge commit message.
Please set the Subject line correctly:
https://www.kernel.org/doc/html/latest/process/maintainer-netdev.html
These patches are for net-next.
Every new API needs a user. Please submit this code together with a PHY driver which actually uses them.
Andrew
---
pw-bot: cr
Quoted 1 line
+ /// Common values include
bindings::phy_interface_t_PHY_INTERFACE_MODE_RGMII,
PHY_INTERFACE_MODE_RGMII is actually an uncommon one, and frequently wrong. I would not use this as an example.
Andrew