mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [net-next PATCH RESEND v2 0/3] rust: net: phy: soft_reset may run without phy_device->lock
@ 2026-11-15  6:47 SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 1/3] rust: net: phy: drop read_mmd and write_mmd from Driver SeungJong Ha
                   ` (2 more replies)
  0 siblings, 3 replies; 6+ messages in thread
From: SeungJong Ha @ 2026-11-15  6:47 UTC (permalink / raw)
  To: FUJITA Tomonori, Trevor Gross, David S. Miller, Eric Dumazet,
	Jakub Kicinski, Paolo Abeni, Simon Horman, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Andrew Lunn, Heiner Kallweit, Russell King
  Cc: netdev, rust-for-linux, linux-kernel, SeungJong Ha

The Rust PHY abstraction tells `soft_reset` that PHYLIB holds
`phy_device->lock`, but phy_init_hw() calls it both with and without the
lock. This was found while auditing the SAFETY comments of Rust
abstractions against their C callers, and confirmed with Clang's context
analysis [1].

Patch 1 drops `read_mmd` and `write_mmd`, which make the same claim, run
under the MDIO bus lock instead, and have no users. Patch 2 makes
`Device` generic over a lock context, and patch 3 gives `soft_reset` the
`MaybeLocked` one.

`match_phy_device` is left as it is. It runs on devices that may be
unbound or bound to another driver, which is a binding question rather
than a locking one; I think it fits better with moving `phy::Device`
onto `device::DeviceContext`, as `pci::Device` does.

No in-tree driver is affected, so if this is not worth doing before
there is a real user, I am happy to drop it.

The audit, the patches and their changelogs were done with an AI coding
assistant (Claude Code, Claude Opus 5.5) and reviewed line by line by
me. Compile-tested only.

Changes in v2:
- Keep `&mut self` on the moved methods, so that `match_phy_device` does
  not gain register access (netdev AI review)
- Give only `soft_reset` the `MaybeLocked` context
- Drop `read_mmd` and `write_mmd` instead of leaving them `Locked`
- Document how PHYLIB calls the `Locked` callbacks, and fix the
  `from_raw()`, `phy_id()` and `genphy_soft_reset()` SAFETY comments
- Link to v1: https://lore.kernel.org/r/20261110-exp-phy-rs-maybelocked-v1-0-3023cc9055e9@gmail.com

[1] https://docs.kernel.org/dev-tools/context-analysis.html

---
Changes in v2:
- EDITME: describe what is new in this series revision.
- EDITME: use bulletpoints and terse descriptions.
- Link to v1: https://patch.msgid.link/20261110-exp-phy-rs-maybelocked-v1-0-3023cc9055e9@gmail.com

---
SeungJong Ha (3):
      rust: net: phy: drop read_mmd and write_mmd from Driver
      rust: net: phy: make Device generic over a lock context
      rust: net: phy: pass a MaybeLocked device to soft_reset

 drivers/net/phy/ax88796b_rust.rs |   8 +-
 rust/kernel/net/phy.rs           | 206 +++++++++++++++++++--------------------
 rust/kernel/net/phy/reg.rs       |  17 ++--
 3 files changed, 112 insertions(+), 119 deletions(-)
---
base-commit: 573af801552999954caa8347e4490b04cf4763f0
change-id: 20261110-exp-phy-rs-maybelocked-ddc59993efba

Best regards,
--
SeungJong Ha <engineer.jjhama@gmail.com>
-- 
SeungJong Ha <engineer.jjhama@gmail.com>


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH RESEND net-next v2 1/3] rust: net: phy: drop read_mmd and write_mmd from Driver
  2026-11-15  6:47 [net-next PATCH RESEND v2 0/3] rust: net: phy: soft_reset may run without phy_device->lock SeungJong Ha
@ 2026-11-15  6:47 ` SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset SeungJong Ha
  2 siblings, 0 replies; 6+ messages in thread
From: SeungJong Ha @ 2026-11-15  6:47 UTC (permalink / raw)
  To: FUJITA Tomonori, Trevor Gross, David S. Miller, Eric Dumazet,
	Jakub Kicinski, Paolo Abeni, Simon Horman, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Andrew Lunn, Heiner Kallweit, Russell King
  Cc: netdev, rust-for-linux, linux-kernel, SeungJong Ha

The read_mmd and write_mmd callbacks hand the driver a `&mut Device`
whose SAFETY comment says PHYLIB holds `phy_device->lock`. It does not
have to: __phy_read_mmd() and __phy_write_mmd() call them with the MDIO
bus lock held but not necessarily `phy_device->lock`, e.g. from
phy_read_mmd() in a hwmon read. The register accessors on `Device` take
the bus lock again, so using them there would deadlock.

No Rust driver implements these callbacks, and none has since they were
added with the abstraction. Drop them until there is a user and a way to
express the MDIO bus lock context.

Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
 rust/kernel/net/phy.rs | 58 --------------------------------------------------
 1 file changed, 58 deletions(-)

diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index c4e7b1d6c6f4..7ca3f2329e6a 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -417,44 +417,6 @@ impl<T: Driver> Adapter<T> {
         T::match_phy_device(dev).into()
     }
 
-    /// # Safety
-    ///
-    /// `phydev` must be passed by the corresponding callback in `phy_driver`.
-    unsafe extern "C" fn read_mmd_callback(
-        phydev: *mut bindings::phy_device,
-        devnum: i32,
-        regnum: u16,
-    ) -> i32 {
-        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) };
-            // CAST: the C side verifies devnum < 32.
-            let ret = T::read_mmd(dev, devnum as u8, regnum)?;
-            Ok(ret.into())
-        })
-    }
-
-    /// # Safety
-    ///
-    /// `phydev` must be passed by the corresponding callback in `phy_driver`.
-    unsafe extern "C" fn write_mmd_callback(
-        phydev: *mut bindings::phy_device,
-        devnum: i32,
-        regnum: u16,
-        val: u16,
-    ) -> i32 {
-        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::write_mmd(dev, devnum as u8, regnum, val)?;
-            Ok(0)
-        })
-    }
-
     /// # Safety
     ///
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
@@ -536,16 +498,6 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
         } else {
             None
         },
-        read_mmd: if T::HAS_READ_MMD {
-            Some(Adapter::<T>::read_mmd_callback)
-        } else {
-            None
-        },
-        write_mmd: if T::HAS_WRITE_MMD {
-            Some(Adapter::<T>::write_mmd_callback)
-        } else {
-            None
-        },
         link_change_notify: if T::HAS_LINK_CHANGE_NOTIFY {
             Some(Adapter::<T>::link_change_notify_callback)
         } else {
@@ -615,16 +567,6 @@ fn resume(_dev: &mut Device) -> Result {
         build_error!(VTABLE_DEFAULT_ERROR)
     }
 
-    /// Overrides the default MMD read function for reading a MMD register.
-    fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result<u16> {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
-
-    /// Overrides the default MMD write function for writing a MMD register.
-    fn write_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16, _val: u16) -> Result {
-        build_error!(VTABLE_DEFAULT_ERROR)
-    }
-
     /// Callback for notification of link change.
     fn link_change_notify(_dev: &mut Device) {}
 }

-- 
2.54.0


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context
  2026-11-15  6:47 [net-next PATCH RESEND v2 0/3] rust: net: phy: soft_reset may run without phy_device->lock SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 1/3] rust: net: phy: drop read_mmd and write_mmd from Driver SeungJong Ha
@ 2026-11-15  6:47 ` SeungJong Ha
  2026-11-16  7:33   ` netdev-bot+sashiko
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset SeungJong Ha
  2 siblings, 1 reply; 6+ messages in thread
From: SeungJong Ha @ 2026-11-15  6:47 UTC (permalink / raw)
  To: FUJITA Tomonori, Trevor Gross, David S. Miller, Eric Dumazet,
	Jakub Kicinski, Paolo Abeni, Simon Horman, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Andrew Lunn, Heiner Kallweit, Russell King
  Cc: netdev, rust-for-linux, linux-kernel, SeungJong Ha

Some PHY driver callbacks run without `phy_device->lock`, but every
callback gets a `Device` whose type says the lock is held.

Make `Device` generic over a lock context, `Locked` (the default) or
`MaybeLocked`, as `device::Device` is over its device context, and move
the methods that do not need the lock to both contexts. Update the
documentation and SAFETY comments to match. The next patch uses
`MaybeLocked`.

No functional change.

Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
 rust/kernel/net/phy.rs     | 141 ++++++++++++++++++++++++++++++---------------
 rust/kernel/net/phy/reg.rs |  17 +++---
 2 files changed, 105 insertions(+), 53 deletions(-)

diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index 7ca3f2329e6a..105a1b727a08 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -50,6 +50,51 @@ pub enum DuplexMode {
     Unknown,
 }
 
+/// A trait implemented by all contexts a [`Device`] can be used in.
+///
+/// - [`Locked`]: Serialized against every access made under `phy_device->lock`. The default
+///   context of [`Device`].
+/// - [`MaybeLocked`]: `phy_device->lock` may or may not be held.
+pub trait PhyContext: private::Sealed {}
+
+/// The [`Device`] context of every [`Driver`] callback that does not take a
+/// [`Device<MaybeLocked>`].
+///
+/// PHYLIB calls these callbacks in one of three ways:
+///
+/// - With `phy_device->lock` held: every callback not listed below.
+/// - Without the lock, but where PHYLIB ensures by other means that no other path accesses the
+///   instance: [`Driver::probe`] and [`Driver::get_features`], which are called from
+///   `phy_probe()`, and [`Driver::suspend`] and [`Driver::resume`].
+/// - Without the lock, possibly on an unbound device or one bound to another driver:
+///   [`Driver::match_phy_device`], which therefore only gets a shared reference.
+///
+/// # Invariants
+///
+/// For the lifetime of a `&mut Device<Locked>`, no other thread accesses the state of the
+/// `phy_device` that `phy_device->lock` protects.
+pub struct Locked;
+
+/// The [`Device`] context of callbacks that PHYLIB calls both with and without
+/// `phy_device->lock` held.
+///
+/// A callback in this context must not take `phy_device->lock`.
+///
+/// # Invariants
+///
+/// None beyond those of [`Device`].
+pub struct MaybeLocked;
+
+mod private {
+    pub trait Sealed {}
+
+    impl Sealed for super::Locked {}
+    impl Sealed for super::MaybeLocked {}
+}
+
+impl PhyContext for Locked {}
+impl PhyContext for MaybeLocked {}
+
 /// An instance of a PHY device.
 ///
 /// Wraps the kernel's [`struct phy_device`].
@@ -57,6 +102,9 @@ pub enum DuplexMode {
 /// A [`Device`] instance is created when a callback in [`Driver`] is executed. A PHY driver
 /// executes [`Driver`]'s methods during the callback.
 ///
+/// `Ctx` is the [`PhyContext`] of the callback. Methods that rely on the exclusive access that
+/// [`Locked`] describes are implemented for [`Device<Locked>`] only.
+///
 /// # Invariants
 ///
 /// - Referencing a `phy_device` using this struct asserts that you are in
@@ -71,34 +119,9 @@ pub enum DuplexMode {
 // [`Driver::resume`] and [`Driver::suspend`] also are called where only one thread can access
 // to the instance.
 #[repr(transparent)]
-pub struct Device(Opaque<bindings::phy_device>);
+pub struct Device<Ctx: PhyContext = Locked>(Opaque<bindings::phy_device>, PhantomData<Ctx>);
 
 impl Device {
-    /// Creates a new [`Device`] instance from a raw pointer.
-    ///
-    /// # Safety
-    ///
-    /// For the duration of `'a`,
-    /// - the pointer must point at a valid `phy_device`, and the caller
-    ///   must be in a context where all methods defined on this struct
-    ///   are safe to call.
-    /// - `(*ptr).mdio.dev` must be a valid.
-    unsafe fn from_raw<'a>(ptr: *mut bindings::phy_device) -> &'a mut Self {
-        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_device`.
-        let ptr = ptr.cast::<Self>();
-        // SAFETY: by the function requirements the pointer is valid and we have unique access for
-        // the duration of `'a`.
-        unsafe { &mut *ptr }
-    }
-
-    /// Gets the id of the PHY.
-    pub fn phy_id(&self) -> u32 {
-        let phydev = self.0.get();
-        // SAFETY: The struct invariant ensures that we may access
-        // this field without additional synchronization.
-        unsafe { (*phydev).phy_id }
-    }
-
     /// Gets the state of PHY state machine states.
     pub fn state(&self) -> DeviceState {
         let phydev = self.0.get();
@@ -177,17 +200,6 @@ pub fn set_duplex(&mut self, mode: DuplexMode) {
         unsafe { (*phydev).duplex = v as c_int };
     }
 
-    /// 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> {
-        reg.read(self)
-    }
-
-    /// Writes a PHY register.
-    pub fn write<R: reg::Register>(&mut self, reg: R, val: u16) -> Result {
-        reg.write(self, val)
-    }
-
     /// Reads a paged register.
     pub fn read_paged(&mut self, page: u16, regnum: u16) -> Result<u16> {
         let phydev = self.0.get();
@@ -206,14 +218,6 @@ pub fn resolve_aneg_linkmode(&mut self) {
         unsafe { bindings::phy_resolve_aneg_linkmode(phydev) };
     }
 
-    /// Executes software reset the PHY via `BMCR_RESET` bit.
-    pub fn genphy_soft_reset(&mut self) -> 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::genphy_soft_reset(phydev) })
-    }
-
     /// Initializes the PHY.
     pub fn init_hw(&mut self) -> Result {
         let phydev = self.0.get();
@@ -276,7 +280,52 @@ pub fn genphy_read_abilities(&mut self) -> Result {
     }
 }
 
-impl AsRef<kernel::device::Device> for Device {
+impl<Ctx: PhyContext> Device<Ctx> {
+    /// Creates a new [`Device`] instance from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_device`, and the caller
+    ///   must be in the `Ctx` context, see [`Locked`] and [`MaybeLocked`].
+    /// - `(*ptr).mdio.dev` must be a valid.
+    unsafe fn from_raw<'a>(ptr: *mut bindings::phy_device) -> &'a mut Self {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_device`.
+        let ptr = ptr.cast::<Self>();
+        // SAFETY: By the function requirements the pointer is valid for `'a`. `Opaque` permits
+        // other `&mut` to the same `phy_device`, e.g. in a concurrent `MaybeLocked` callback.
+        unsafe { &mut *ptr }
+    }
+
+    /// Gets the id of the PHY.
+    pub fn phy_id(&self) -> u32 {
+        let phydev = self.0.get();
+        // SAFETY: `phydev` is valid by the type invariant of `Self`. `phy_id` is set by
+        // `phy_device_create()` and never written afterwards.
+        unsafe { (*phydev).phy_id }
+    }
+
+    /// 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> {
+        reg.read(self)
+    }
+
+    /// Writes a PHY register.
+    pub fn write<R: reg::Register>(&mut self, reg: R, val: u16) -> Result {
+        reg.write(self, val)
+    }
+
+    /// Executes software reset the PHY via `BMCR_RESET` bit.
+    pub fn genphy_soft_reset(&mut self) -> Result {
+        let phydev = self.0.get();
+        // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. The C
+        // function does not require `phy_device->lock`; PHYLIB itself calls it without the lock.
+        to_result(unsafe { bindings::genphy_soft_reset(phydev) })
+    }
+}
+
+impl<Ctx: PhyContext> AsRef<kernel::device::Device> for Device<Ctx> {
     fn as_ref(&self) -> &kernel::device::Device {
         let phydev = self.0.get();
         // SAFETY: The struct invariant ensures that `mdio.dev` is valid.
diff --git a/rust/kernel/net/phy/reg.rs b/rust/kernel/net/phy/reg.rs
index 80e22c264ea8..e6892f3b855f 100644
--- a/rust/kernel/net/phy/reg.rs
+++ b/rust/kernel/net/phy/reg.rs
@@ -8,7 +8,10 @@
 //! Ethernet management interface clauses 22 and 45 register namespaces, as
 //! defined in IEEE 802.3.
 
-use super::Device;
+use super::{
+    Device,
+    PhyContext, //
+};
 use crate::{
     build_assert::build_assert,
     error::*,
@@ -44,10 +47,10 @@ pub trait Sealed {}
 /// ```
 pub trait Register: private::Sealed {
     /// Reads a PHY register.
-    fn read(&self, dev: &mut Device) -> Result<u16>;
+    fn read<C: PhyContext>(&self, dev: &mut Device<C>) -> Result<u16>;
 
     /// Writes a PHY register.
-    fn write(&self, dev: &mut Device, val: u16) -> Result;
+    fn write<C: PhyContext>(&self, dev: &mut Device<C>, val: u16) -> Result;
 
     /// Checks the link status and updates current link state.
     fn read_status(dev: &mut Device) -> Result<u16>;
@@ -104,7 +107,7 @@ pub const fn vendor_specific<const N: u8>() -> Self {
 impl private::Sealed for C22 {}
 
 impl Register for C22 {
-    fn read(&self, dev: &mut Device) -> Result<u16> {
+    fn read<C: PhyContext>(&self, dev: &mut Device<C>) -> Result<u16> {
         let phydev = dev.0.get();
         // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Device`.
         // So it's just an FFI call, open code of `phy_read()` with a valid `phy_device` pointer
@@ -116,7 +119,7 @@ fn read(&self, dev: &mut Device) -> Result<u16> {
         Ok(ret as u16)
     }
 
-    fn write(&self, dev: &mut Device, val: u16) -> Result {
+    fn write<C: PhyContext>(&self, dev: &mut Device<C>, val: u16) -> Result {
         let phydev = dev.0.get();
         // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Device`.
         // So it's just an FFI call, open code of `phy_write()` with a valid `phy_device` pointer
@@ -196,7 +199,7 @@ pub fn new(devad: Mmd, regnum: u16) -> Self {
 impl private::Sealed for C45 {}
 
 impl Register for C45 {
-    fn read(&self, dev: &mut Device) -> Result<u16> {
+    fn read<C: PhyContext>(&self, dev: &mut Device<C>) -> Result<u16> {
         let phydev = dev.0.get();
         // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Device`.
         // So it's just an FFI call.
@@ -206,7 +209,7 @@ fn read(&self, dev: &mut Device) -> Result<u16> {
         Ok(ret as u16)
     }
 
-    fn write(&self, dev: &mut Device, val: u16) -> Result {
+    fn write<C: PhyContext>(&self, dev: &mut Device<C>, val: u16) -> Result {
         let phydev = dev.0.get();
         // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Device`.
         // So it's just an FFI call.

-- 
2.54.0


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset
  2026-11-15  6:47 [net-next PATCH RESEND v2 0/3] rust: net: phy: soft_reset may run without phy_device->lock SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 1/3] rust: net: phy: drop read_mmd and write_mmd from Driver SeungJong Ha
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context SeungJong Ha
@ 2026-11-15  6:47 ` SeungJong Ha
  2026-11-16  7:33   ` netdev-bot+sashiko
  2 siblings, 1 reply; 6+ messages in thread
From: SeungJong Ha @ 2026-11-15  6:47 UTC (permalink / raw)
  To: FUJITA Tomonori, Trevor Gross, David S. Miller, Eric Dumazet,
	Jakub Kicinski, Paolo Abeni, Simon Horman, Miguel Ojeda,
	Boqun Feng, Gary Guo, Björn Roy Baron, Benno Lossin,
	Andreas Hindborg, Alice Ryhl, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Andrew Lunn, Heiner Kallweit, Russell King
  Cc: netdev, rust-for-linux, linux-kernel, SeungJong Ha

phy_init_hw() calls `soft_reset` both with and without
`phy_device->lock`, but `soft_reset_callback` hands the driver a
`Locked` device and its SAFETY comment says the lock is held.

Pass a `&mut Device<MaybeLocked>` instead and correct the SAFETY
comment. Update ax88796b_rust, the only implementation.

Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
 drivers/net/phy/ax88796b_rust.rs | 8 ++++----
 rust/kernel/net/phy.rs           | 7 +++----
 2 files changed, 7 insertions(+), 8 deletions(-)

diff --git a/drivers/net/phy/ax88796b_rust.rs b/drivers/net/phy/ax88796b_rust.rs
index 2d24628a4e58..88e6e3c88b44 100644
--- a/drivers/net/phy/ax88796b_rust.rs
+++ b/drivers/net/phy/ax88796b_rust.rs
@@ -30,7 +30,7 @@
 // BMCR_RESET bit and poll for the reset bit to be cleared.
 // Toggle BMCR_RESET bit off to accommodate broken AX8796B PHY implementation
 // such as used on the Individual Computers' X-Surf 100 Zorro card.
-fn asix_soft_reset(dev: &mut phy::Device) -> Result {
+fn asix_soft_reset(dev: &mut phy::Device<phy::MaybeLocked>) -> Result {
     dev.write(C22::BMCR, 0)?;
     dev.genphy_soft_reset()
 }
@@ -85,7 +85,7 @@ fn resume(dev: &mut phy::Device) -> Result {
         dev.genphy_resume()
     }
 
-    fn soft_reset(dev: &mut phy::Device) -> Result {
+    fn soft_reset(dev: &mut phy::Device<phy::MaybeLocked>) -> Result {
         asix_soft_reset(dev)
     }
 
@@ -115,7 +115,7 @@ fn resume(dev: &mut phy::Device) -> Result {
         dev.genphy_resume()
     }
 
-    fn soft_reset(dev: &mut phy::Device) -> Result {
+    fn soft_reset(dev: &mut phy::Device<phy::MaybeLocked>) -> Result {
         asix_soft_reset(dev)
     }
 }
@@ -127,7 +127,7 @@ impl Driver for PhyAX88796B {
     const NAME: &'static CStr = c"Asix Electronics AX88796B";
     const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_model_mask(0x003b1841);
 
-    fn soft_reset(dev: &mut phy::Device) -> Result {
+    fn soft_reset(dev: &mut phy::Device<phy::MaybeLocked>) -> Result {
         asix_soft_reset(dev)
     }
 }
diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index 105a1b727a08..46602798e8ac 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -358,9 +358,8 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn soft_reset_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.
+            // SAFETY: `phydev` is valid for the callback. `phy_init_hw()` calls `soft_reset` both
+            // with and without `phy_device->lock`, which is the `MaybeLocked` context.
             let dev = unsafe { Device::from_raw(phydev) };
             T::soft_reset(dev)?;
             Ok(0)
@@ -575,7 +574,7 @@ pub trait Driver {
     const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_custom_mask(0, 0);
 
     /// Issues a PHY software reset.
-    fn soft_reset(_dev: &mut Device) -> Result {
+    fn soft_reset(_dev: &mut Device<MaybeLocked>) -> Result {
         build_error!(VTABLE_DEFAULT_ERROR)
     }
 

-- 
2.54.0


^ permalink raw reply	[flat|nested] 6+ messages in thread

* Re: [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context SeungJong Ha
@ 2026-11-16  7:33   ` netdev-bot+sashiko
  0 siblings, 0 replies; 6+ messages in thread
From: netdev-bot+sashiko @ 2026-11-16  7:33 UTC (permalink / raw)
  To: engineer.jjhama
  Cc: fujita.tomonori, tmgross, davem, edumazet, kuba, pabeni, horms,
	ojeda, boqun, gary, bjorn3_gh, lossin, a.hindborg, aliceryhl,
	dakr, daniel.almeida, tamird, acourbot, work, andrew, hkallweit1,
	linux, netdev, rust-for-linux, linux-kernel

Thank you for your contribution! Sashiko AI review found 4 potential
issue(s) to consider.

Critical: 0 · High: 0 · Medium: 2 · Low: 2

If you believe none of the issues are legitimate, please reply to each
issue of Medium severity or higher and explain why the AI is wrong.
If any of them are legitimate and you plan to respin, please let patchwork
know by including "pw-bot: cr" as a separate line at the end of your reply
(one such reply per series is enough).

- [Medium] `match_phy_device` is still given a `Device<Locked>` even
  though, as the new docs themselves say, it runs without…
- [Medium] The new `Locked` doc (rust/kernel/net/phy.rs:66-68) puts
  `Driver::suspend` under "Without the lock, but where PHYLIB ensures by…
- [Low] The commit message says "Update the documentation and SAFETY
  comments to match", but the callback SAFETY comments in `Adapter<T>`…
- [Low] The new `Locked` doc (rust/kernel/net/phy.rs:66-68) lists
  `Driver::resume` among callbacks PHYLIB calls "Without the lock".

--

rust: net: phy: make Device generic over a lock context

This commit makes the Rust PHY Device type generic over a lock context,
Locked (the default) or MaybeLocked. It moves phy_id(), read(), write()
and genphy_soft_reset() into an impl block that covers both contexts, and
documents which PHYLIB callbacks run with or without phy_device->lock.

> diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> index 7ca3f2329e6a2..105a1b727a088 100644
> --- a/rust/kernel/net/phy.rs
> +++ b/rust/kernel/net/phy.rs
> @@ -50,6 +50,51 @@ pub enum DuplexMode {
>      Unknown,
>  }
>  

[ ... ]

> +/// The [`Device`] context of every [`Driver`] callback that does not take a
> +/// [`Device<MaybeLocked>`].
> +///
> +/// PHYLIB calls these callbacks in one of three ways:
> +///
> +/// - With `phy_device->lock` held: every callback not listed below.
> +/// - Without the lock, but where PHYLIB ensures by other means that no other path accesses the
> +///   instance: [`Driver::probe`] and [`Driver::get_features`], which are called from
> +///   `phy_probe()`, and [`Driver::suspend`] and [`Driver::resume`].

[Severity: Medium]
Does PHYLIB really guarantee exclusive access for Driver::suspend?

phy_state_machine() releases the lock before the post-work step:

drivers/net/phy/phy.c:phy_state_machine() {
    ...
	mutex_lock(&phydev->lock);
	state_work = _phy_state_machine(phydev);
	mutex_unlock(&phydev->lock);

	_phy_state_machine_post_work(phydev, state_work);
    ...
}

For PHY_HALTED or PHY_ERROR, _phy_state_machine() returns
PHY_STATE_WORK_SUSPEND. The unlocked part then calls:

_phy_state_machine_post_work()
    phy_suspend()
        phydrv->suspend(phydev)

and no lock is held during that call.

Meanwhile, phy_ethtool_ksettings_set() or phy_start_aneg() can take
phydev->lock, write phydev->autoneg, speed and duplex, and call
_phy_start_aneg()->config_aneg. A halted PHY doesn't count as started, so
that path is reachable.

In that case suspend_callback() and config_aneg_callback() each hold a
&mut Device<Locked> for the same phy_device, on different CPUs. Safe code
in the suspend callback (set_speed(), set_duplex(), genphy_update_link()
and so on) would then race with the lock holder.

Wouldn't that break the new Locked invariant further down, which says no
other thread touches the lock-protected state while a &mut Device<Locked>
exists?

The old struct comment made a similar claim. This patch turns it into a
formal invariant, though, and suspend still gets a type that says the
lock is held.

[Severity: Low]
Is Driver::resume actually called without the lock? The only call site of
phydrv->resume seems to be __phy_resume(), and it asserts that the lock is
held:

drivers/net/phy/phy_device.c:__phy_resume() {
    ...
	lockdep_assert_held(&phydev->lock);

	if (!phydrv || !phydrv->resume)
		return 0;

	ret = phydrv->resume(phydev);
    ...
}

phy_resume() also takes phydev->lock around that call. The SAFETY comment
in resume_callback(), which this patch leaves unchanged, says the lock
"might not be held", so it has the same inaccuracy.

> +/// - Without the lock, possibly on an unbound device or one bound to another driver:
> +///   [`Driver::match_phy_device`], which therefore only gets a shared reference.
> +///
> +/// # Invariants
> +///
> +/// For the lifetime of a `&mut Device<Locked>`, no other thread accesses the state of the
> +/// `phy_device` that `phy_device->lock` protects.
> +pub struct Locked;

[Severity: Medium]
Does a shared reference give match_phy_device any protection here? The
invariant only covers &mut Device<Locked>. match_phy_device_callback()
still creates one through from_raw() and passes a &Device<Locked> to
T::match_phy_device():

rust/kernel/net/phy.rs:Adapter::match_phy_device_callback() {
    ...
        let dev = unsafe { Device::from_raw(phydev) };
        T::match_phy_device(dev).into()
}

phy_bus_match() calls phydrv->match_phy_device() without the lock.
__driver_attach() calls driver_match_device() on every device on the bus
before it checks dev->driver, so this includes PHYs already bound to
other drivers.

So when a Rust PHY driver that implements match_phy_device is loaded:

phy_drivers_register()
  driver_register()
    bus_add_driver()
      __driver_attach()
        phy_bus_match()
          match_phy_device_callback()

safe code can call state(), is_link_up(), is_autoneg_enabled() or
is_autoneg_completed() on a PHY whose phy_state_machine() is running
under phydev->lock for another driver. Those accessors do plain reads,
justified by "there is no concurrent write to this field". At the same
time, _phy_state_machine() writes fields such as phydev->link.

Isn't this still a callback that runs without the lock but gets a Device
whose type says the lock is held? The commit message gives that as the
problem to fix, and it still applies at the end of the series.

[ ... ]

> @@ -276,7 +280,52 @@ pub fn genphy_read_abilities(&mut self) -> Result {
>      }
>  }
>  
> -impl AsRef<kernel::device::Device> for Device {
> +impl<Ctx: PhyContext> Device<Ctx> {
> +    /// Creates a new [`Device`] instance from a raw pointer.
> +    ///
> +    /// # Safety
> +    ///
> +    /// For the duration of `'a`,
> +    /// - the pointer must point at a valid `phy_device`, and the caller
> +    ///   must be in the `Ctx` context, see [`Locked`] and [`MaybeLocked`].
> +    /// - `(*ptr).mdio.dev` must be a valid.
> +    unsafe fn from_raw<'a>(ptr: *mut bindings::phy_device) -> &'a mut Self {

[Severity: Low]
The commit message says:

    Update the documentation and SAFETY comments to match.

The from_raw() callers in Adapter<T> weren't updated, though. None of
them says which context it is in or why; they all get Ctx = Locked by
inference.

Some of those comments now contradict the new Locked docs.
get_features_callback() still says:

            // 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) };

The Locked docs say get_features is called from phy_probe() without the
lock, and the C code agrees:

drivers/net/phy/phy_device.c:phy_probe() {
    ...
	else if (phydrv->get_features)
		err = phydrv->get_features(phydev);
    ...
}

match_phy_device_callback() has the same comment, while the Locked docs
say match_phy_device runs without the lock.

The invariant on struct Device ("a context where all methods defined on
this struct are safe to call") still describes the old single-context
model. So does the comment block above the struct definition.

A later patch in the series, "rust: net: phy: pass a MaybeLocked device
to soft_reset", updates only the soft_reset_callback() comment. The
get_features and match_phy_device comments are still out of date at the
end of the series.

-- 
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261115-exp-phy-rs-maybelocked-v2-0-8fa7897a0352%40gmail.com

^ permalink raw reply	[flat|nested] 6+ messages in thread

* Re: [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset
  2026-11-15  6:47 ` [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset SeungJong Ha
@ 2026-11-16  7:33   ` netdev-bot+sashiko
  0 siblings, 0 replies; 6+ messages in thread
From: netdev-bot+sashiko @ 2026-11-16  7:33 UTC (permalink / raw)
  To: engineer.jjhama
  Cc: fujita.tomonori, tmgross, davem, edumazet, kuba, pabeni, horms,
	ojeda, boqun, gary, bjorn3_gh, lossin, a.hindborg, aliceryhl,
	dakr, daniel.almeida, tamird, acourbot, work, andrew, hkallweit1,
	linux, netdev, rust-for-linux, linux-kernel

Thank you for your contribution! Sashiko AI review found 2 potential
issue(s) to consider.

Critical: 0 · High: 0 · Medium: 1 · Low: 1

If you believe none of the issues are legitimate, please reply to each
issue of Medium severity or higher and explain why the AI is wrong.
If any of them are legitimate and you plan to respin, please let patchwork
know by including "pw-bot: cr" as a separate line at the end of your reply
(one such reply per series is enough).

- [Medium] The new SAFETY reasoning for the MaybeLocked soft_reset path
  misses the phy_mii_ioctl() path, where soft_reset runs at the same…
- [Low] Two sibling callbacks in rust/kernel/net/phy.rs still carry the
  false lock-held SAFETY comment that this patch removes from…

--

rust: net: phy: pass a MaybeLocked device to soft_reset

This changes the Rust PHY abstraction so that Driver::soft_reset gets a
Device<MaybeLocked> rather than a Locked device. The reason is that
phy_init_hw() calls soft_reset both with and without phydev->lock. The
SAFETY comment in soft_reset_callback is updated to match, and
ax88796b_rust is converted to the new signature.

> diff --git a/drivers/net/phy/ax88796b_rust.rs b/drivers/net/phy/ax88796b_rust.rs
> index 2d24628a4e581..88e6e3c88b448 100644
> --- a/drivers/net/phy/ax88796b_rust.rs
> +++ b/drivers/net/phy/ax88796b_rust.rs
> @@ -30,7 +30,7 @@
>  // BMCR_RESET bit and poll for the reset bit to be cleared.
>  // Toggle BMCR_RESET bit off to accommodate broken AX8796B PHY implementation
>  // such as used on the Individual Computers' X-Surf 100 Zorro card.
> -fn asix_soft_reset(dev: &mut phy::Device) -> Result {
> +fn asix_soft_reset(dev: &mut phy::Device<phy::MaybeLocked>) -> Result {
>      dev.write(C22::BMCR, 0)?;
>      dev.genphy_soft_reset()
>  }

[Severity: Medium]
Is it sound to call genphy_soft_reset() on a Device<MaybeLocked> when the
caller is phy_mii_ioctl()?

When SIOCSMIIREG writes BMCR_RESET to MII_BMCR, phy_mii_ioctl() calls
phy_init_hw() with only RTNL held. phydev->lock is not taken:

phy_mii_ioctl()
  phy_init_hw()
    phydev->drv->soft_reset()
      Adapter::soft_reset_callback()
        asix_soft_reset()
          genphy_soft_reset()

The C genphy_soft_reset() reads phydev->autoneg and writes
phydev->suspended. If autoneg is disabled it also calls
genphy_setup_forced(), which writes pause and asym_pause. After that,
phy_init_hw() writes phydev->suspended = 0 itself.

In struct phy_device, suspended, autoneg, link, autoneg_complete, pause
and asym_pause are bitfields in the same block. A write to suspended is
therefore a read-modify-write of the storage that also holds link and
autoneg_complete.

phy_state_machine() takes only phydev->lock, not RTNL:

    mutex_lock(&phydev->lock);
    state_work = _phy_state_machine(phydev);
    mutex_unlock(&phydev->lock);

Under that lock it runs Locked callbacks such as read_status and
config_aneg, and it updates link. __phy_resume() also writes suspended
under lockdep_assert_held(&phydev->lock).

Nothing keeps the ioctl path and the state machine from running at the
same time. Could a link or pause update be lost here?

This seems to contradict a few statements in the series:

- The Locked invariant says that while a &mut Device<Locked> is alive, no
  other thread touches the state that phy_device->lock protects.

- The SAFETY comment in Device::genphy_soft_reset says the C function
  does not need phy_device->lock because PHYLIB itself calls it without
  the lock. The unlocked PHYLIB callers, phy_attach_direct() and
  mdio_bus_phy_resume(), rely on the state machine not running. The ioctl
  caller has no such exclusion.

- The MaybeLocked documentation gives no invariants beyond those of
  Device, yet genphy_soft_reset() is available in every context.

The race itself is older than this series. C drivers that use
genphy_soft_reset() have it too, and phy_mii_ioctl() is documented as
incompatible with the PHYCONTROL layer. However, this patch is the first
to call genphy_soft_reset() on a MaybeLocked device based on the new
soundness claims.

Would it make sense to take genphy_soft_reset() out of the generic impl?
Alternatively, the MaybeLocked/Locked docs could describe the exclusion
that the unlocked callers rely on, and note that the phy_mii_ioctl() path
breaks it.

[ ... ]

> diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> index 105a1b727a088..46602798e8aca 100644
> --- a/rust/kernel/net/phy.rs
> +++ b/rust/kernel/net/phy.rs
> @@ -358,9 +358,8 @@ impl<T: Driver> Adapter<T> {
>      /// `phydev` must be passed by the corresponding callback in `phy_driver`.
>      unsafe extern "C" fn soft_reset_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.
> +            // SAFETY: `phydev` is valid for the callback. `phy_init_hw()` calls `soft_reset` both
> +            // with and without `phy_device->lock`, which is the `MaybeLocked` context.
>              let dev = unsafe { Device::from_raw(phydev) };
>              T::soft_reset(dev)?;
>              Ok(0)

[Severity: Low]
This fixes the lock-held SAFETY comment in soft_reset_callback(). Two
other callbacks in the same file, get_features_callback() and
match_phy_device_callback(), still have the same text:

    // 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) };

Is that still accurate for either of them? phy_probe() calls
get_features without taking phydev->lock:

    else if (phydrv->get_features)
        err = phydrv->get_features(phydev);

phy_bus_match() calls match_phy_device during driver-core matching. It
also runs without the lock, and the device may be unbound or bound to
another driver:

    if (phydrv->match_phy_device)
        return phydrv->match_phy_device(phydev, phydrv);

The Locked documentation added earlier in this series already says that
both callbacks run without the lock, so the file now contradicts itself.
The earlier commit "rust: net: phy: make Device generic over a lock
context" also says it will "Update the documentation and SAFETY comments
to match".

match_phy_device_callback() also still creates a &mut Device<Locked>,
which is only coerced to &Device when it is passed to
T::match_phy_device(). The Locked invariant cannot hold for a device that
is bound to another driver.

Could that SAFETY comment explain why the short-lived exclusive reference
is acceptable, rather than saying the lock is held?

-- 
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261115-exp-phy-rs-maybelocked-v2-0-8fa7897a0352%40gmail.com

^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2026-11-16  7:33 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-15  6:47 [net-next PATCH RESEND v2 0/3] rust: net: phy: soft_reset may run without phy_device->lock SeungJong Ha
2026-11-15  6:47 ` [PATCH RESEND net-next v2 1/3] rust: net: phy: drop read_mmd and write_mmd from Driver SeungJong Ha
2026-11-15  6:47 ` [PATCH RESEND net-next v2 2/3] rust: net: phy: make Device generic over a lock context SeungJong Ha
2026-11-16  7:33   ` netdev-bot+sashiko
2026-11-15  6:47 ` [PATCH RESEND net-next v2 3/3] rust: net: phy: pass a MaybeLocked device to soft_reset SeungJong Ha
2026-11-16  7:33   ` netdev-bot+sashiko

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®