mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH net-next v4 0/2] rust: net: phy: pass &Device to callbacks without exclusive access
@ 2026-11-26 14:08 SeungJong Ha
  2026-11-26 14:08 ` [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock SeungJong Ha
  2026-11-26 14:08 ` [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd SeungJong Ha
  0 siblings, 2 replies; 5+ messages in thread
From: SeungJong Ha @ 2026-11-26 14:08 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 gives every driver callback a `&mut Device` and
says that PHYLIB holds `phy_device->lock`, but phy_suspend() calls
`suspend` without it, also right after the state machine drops the
lock, and read_mmd and write_mmd run with the MDIO bus lock held
instead. This was found while auditing the SAFETY comments of Rust
abstractions against their C callers, and confirmed with Clang's
context analysis [1].

As FUJITA suggested on v3, the series uses `&Device` and `&mut Device`
for this instead of new context types. Patch 1 makes `&mut Device` mean
exclusive access to the state that `phy_device->lock` protects, fits the
method receivers to that, and documents when the `&mut Device` callbacks
run without the lock. Patch 2 passes a `&Device` to suspend, read_mmd
and write_mmd. The generated code of ax88796b_rust and qt2025 does not
change.

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.

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

---
Changes in v4:
- Use `&Device` and `&mut Device` instead of the `Locked` and
  `MaybeLocked` context types (FUJITA)
- Keep `read_mmd`, `write_mmd` and `match_phy_device`. Pass `&Device` to
  `read_mmd` and `write_mmd`, and document that read() and write()
  deadlock there (FUJITA)
- Make read(), write() and genphy_suspend() take `&self`.
  `match_phy_device` can access registers as C implementations do,
  while read_paged() stays `&mut self`
- Make the getters of the state that `phy_device->lock` protects take
  `&mut self`
- Name the fields that `phy_device->lock` protects in the `Device`
  documentation
- Say that the phy_mii_ioctl() path is outside the guarantee (Andrew,
  FUJITA)
- Link to v3: https://lore.kernel.org/r/20261117-exp-phy-rs-maybelocked-v3-0-4e183a7366a7@gmail.com

Changes in v3:
- Give `suspend` the `MaybeLocked` context, and make `genphy_suspend()`
  available in both contexts (netdev AI review)
- Move `soft_reset` and `genphy_soft_reset()` back to `Locked`, since
  `genphy_soft_reset()` in `MaybeLocked` could race with lock holders
  in `suspend`, and document phy_mii_ioctl() as an existing PHYLIB race
  instead (netdev AI review)
- Drop `match_phy_device` as well (netdev AI review)
- Fix the `get_features`, `soft_reset`, `read_status` and `resume`
  SAFETY comments, and name the context at each `from_raw()` call
- List the exceptions in the `Locked` documentation, including MAC
  drivers that call phy_init_hw() or phy_read_status() directly
- Link to v2: https://lore.kernel.org/r/20261115-exp-phy-rs-maybelocked-v2-0-8fa7897a0352@gmail.com

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

---
SeungJong Ha (2):
      rust: net: phy: take &self in methods that do not need phy_device->lock
      rust: net: phy: pass &Device to suspend, read_mmd and write_mmd

 drivers/net/phy/ax88796b_rust.rs |   4 +-
 rust/kernel/net/phy.rs           | 165 +++++++++++++++++++++------------------
 rust/kernel/net/phy/reg.rs       |  12 +--
 3 files changed, 99 insertions(+), 82 deletions(-)
---
base-commit: 5f049e811762d6784392d9984ce910257224824b
change-id: 20261110-exp-phy-rs-maybelocked-ddc59993efba

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


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

* [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock
  2026-11-26 14:08 [PATCH net-next v4 0/2] rust: net: phy: pass &Device to callbacks without exclusive access SeungJong Ha
@ 2026-11-26 14:08 ` SeungJong Ha
  2026-11-27 15:01   ` netdev-bot+sashiko
  2026-11-26 14:08 ` [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd SeungJong Ha
  1 sibling, 1 reply; 5+ messages in thread
From: SeungJong Ha @ 2026-11-26 14:08 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

Every callback gets a `&mut Device`, which assumes exclusive access to
the device, but some callbacks run while another path holds
`phy_device->lock`.

Make `&mut Device` mean exclusive access to the state that
`phy_device->lock` protects, so that safe code cannot use that state
without the access. The methods that use it take `&mut self`, including
state(), is_link_up() and the autoneg getters, which read it.

Document when PHYLIB calls the `&mut Device` callbacks without the lock,
with the phy_mii_ioctl() path outside the guarantee, and fix their
SAFETY comments.

phy_id(), read(), write() and genphy_suspend() do not use that state:
the MDIO bus lock serializes register access, and phy_id does not change
after the device is created. They take `&self`, so that the callbacks
that get a `&Device` in the next patch can still use them.

No functional change.

Suggested-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
 rust/kernel/net/phy.rs     | 141 ++++++++++++++++++++++++---------------------
 rust/kernel/net/phy/reg.rs |  12 ++--
 2 files changed, 82 insertions(+), 71 deletions(-)

diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index c4e7b1d6c6f4..bb2cc6b3c94c 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -57,50 +57,71 @@ 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.
 ///
+/// A `&mut Device` has exclusive access to the state of the `phy_device` that `phy_device->lock`
+/// protects, such as `state`, `link`, `autoneg`, `autoneg_complete`, `speed` and `duplex`, and the
+/// methods that use that state take `&mut self`. A `&Device` makes no such claim.
+///
+/// PHYLIB calls the callbacks that get a `&mut Device` with `phy_device->lock` held, except:
+///
+/// - [`Driver::probe`] and [`Driver::get_features`], which `phy_probe()` calls without the lock
+///   before the device is attached.
+/// - [`Driver::soft_reset`], which `phy_init_hw()` calls without the lock while the state machine
+///   is not running, or from a MAC driver that then ensures exclusive access. `phy_mii_ioctl()`,
+///   which PHYLIB documents as "use at own risk", is outside this guarantee.
+/// - [`Driver::read_status`], when a MAC driver calls `phy_read_status()` directly. The MAC
+///   driver is then responsible for exclusive access.
+///
 /// # Invariants
 ///
-/// - Referencing a `phy_device` using this struct asserts that you are in
-///   a context where all methods defined on this struct are safe to call.
-/// - This struct always has a valid `self.0.mdio.dev`.
+/// - `self.0` is a valid `phy_device`, and `self.0.mdio.dev` is a valid `struct device`.
+/// - For the lifetime of a `&mut Device`, no other thread accesses the state of the `phy_device`
+///   that `phy_device->lock` protects.
 ///
 /// [`struct phy_device`]: srctree/include/linux/phy.h
-// During the calls to most functions in [`Driver`], the C side (`PHYLIB`) holds a lock that is
-// unique for every instance of [`Device`]. `PHYLIB` uses a different serialization technique for
-// [`Driver::resume`] and [`Driver::suspend`]: `PHYLIB` updates `phy_device`'s state with
-// the lock held, thus guaranteeing that [`Driver::resume`] has exclusive access to the instance.
-// [`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>);
 
 impl Device {
-    /// Creates a new [`Device`] instance from a raw pointer.
+    /// Creates a new shared [`Device`] reference 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 {
+    /// - the pointer must point at a valid `phy_device`.
+    /// - `(*ptr).mdio.dev` must be valid.
+    unsafe fn from_raw<'a>(ptr: *mut bindings::phy_device) -> &'a 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`.
+        // SAFETY: By the function requirements the pointer is valid for `'a`.
+        unsafe { &*ptr }
+    }
+
+    /// Creates a new mutable [`Device`] reference from a raw pointer.
+    ///
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_device`.
+    /// - `(*ptr).mdio.dev` must be valid.
+    /// - the caller must have the exclusive access that [`Device`] describes.
+    unsafe fn from_raw_mut<'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 references to the same `phy_device`, e.g. in a concurrent `&Device` callback.
         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.
+        // 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 }
     }
 
     /// Gets the state of PHY state machine states.
-    pub fn state(&self) -> DeviceState {
+    pub fn state(&mut self) -> DeviceState {
         let phydev = self.0.get();
         // SAFETY: The struct invariant ensures that we may access
         // this field without additional synchronization.
@@ -124,7 +145,7 @@ pub fn state(&self) -> DeviceState {
     ///
     /// It returns true if the link is up.
     #[inline]
-    pub fn is_link_up(&self) -> bool {
+    pub fn is_link_up(&mut self) -> bool {
         let phydev = self.0.get().cast_const();
         // SAFETY: By the type invariant of `Device`, `phydev` points to a valid
         // `struct phy_device`, and there is no concurrent write to this field.
@@ -136,7 +157,7 @@ pub fn is_link_up(&self) -> bool {
     ///
     /// It returns true if auto-negotiation is enabled.
     #[inline]
-    pub fn is_autoneg_enabled(&self) -> bool {
+    pub fn is_autoneg_enabled(&mut self) -> bool {
         let phydev = self.0.get().cast_const();
         // SAFETY: By the type invariant of `Device`, `phydev` points to a valid
         // `struct phy_device`, and there is no concurrent write to this field.
@@ -148,7 +169,7 @@ pub fn is_autoneg_enabled(&self) -> bool {
     ///
     /// It returns true if auto-negotiation is completed.
     #[inline]
-    pub fn is_autoneg_completed(&self) -> bool {
+    pub fn is_autoneg_completed(&mut self) -> bool {
         let phydev = self.0.get().cast_const();
         // SAFETY: By the type invariant of `Device`, `phydev` points to a valid
         // `struct phy_device`, and there is no concurrent write to this field.
@@ -178,13 +199,13 @@ pub fn set_duplex(&mut self, mode: DuplexMode) {
     }
 
     /// 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> {
+    // The MDIO bus lock serializes the access, so this takes `&self`.
+    pub fn read<R: reg::Register>(&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 {
+    pub fn write<R: reg::Register>(&self, reg: R, val: u16) -> Result {
         reg.write(self, val)
     }
 
@@ -192,7 +213,8 @@ pub fn write<R: reg::Register>(&mut self, reg: R, val: u16) -> Result {
     pub fn read_paged(&mut self, page: u16, regnum: u16) -> Result<u16> {
         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.
+        // `phy_read_paged()` needs `phydev->drv`, which is set in every callback that gets a
+        // `&mut Device`.
         let ret = unsafe { bindings::phy_read_paged(phydev, page.into(), regnum.into()) };
 
         to_result(ret).map(|()| ret as u16)
@@ -239,10 +261,10 @@ pub fn genphy_resume(&mut self) -> Result {
     }
 
     /// Suspends the PHY via `BMCR_PDOWN` bit.
-    pub fn genphy_suspend(&mut self) -> Result {
+    pub fn genphy_suspend(&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.
+        // SAFETY: `phydev` is pointing to a valid object by the type invariant of `Self`. The C
+        // function only sets `BMCR_PDOWN`, serialized by the MDIO bus lock.
         to_result(unsafe { bindings::genphy_suspend(phydev) })
     }
 
@@ -309,10 +331,10 @@ 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.
-            let dev = unsafe { Device::from_raw(phydev) };
+            // SAFETY: `phy_init_hw()` calls this with `phy_device->lock` held, or without it while
+            // the state machine is not running or a MAC driver ensures exclusive access. The
+            // `phy_mii_ioctl()` path is outside this guarantee, see `Device`.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::soft_reset(dev)?;
             Ok(0)
         })
@@ -323,11 +345,9 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn probe_callback(phydev: *mut bindings::phy_device) -> c_int {
         from_result(|| {
-            // SAFETY: This callback is called only in contexts
-            // where we can exclusively access `phy_device` because
-            // it's not published yet, so the accessors on `Device` are okay
-            // to call.
-            let dev = unsafe { Device::from_raw(phydev) };
+            // SAFETY: `phy_probe()` calls this before the device is attached, when no other PHYLIB
+            // path accesses it.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::probe(dev)?;
             Ok(0)
         })
@@ -338,10 +358,9 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn get_features_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) };
+            // SAFETY: `phy_probe()` calls this without `phy_device->lock`, under the same
+            // assumption as `probe`.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::get_features(dev)?;
             Ok(0)
         })
@@ -355,7 +374,7 @@ impl<T: Driver> Adapter<T> {
             // SAFETY: The C core code ensures that the accessors on
             // `Device` are okay to call even though `phy_device->lock`
             // might not be held.
-            let dev = unsafe { Device::from_raw(phydev) };
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::suspend(dev)?;
             Ok(0)
         })
@@ -366,10 +385,8 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn resume_callback(phydev: *mut bindings::phy_device) -> c_int {
         from_result(|| {
-            // SAFETY: The C core code ensures that the accessors on
-            // `Device` are okay to call even though `phy_device->lock`
-            // might not be held.
-            let dev = unsafe { Device::from_raw(phydev) };
+            // SAFETY: `__phy_resume()` asserts that `phy_device->lock` is held.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::resume(dev)?;
             Ok(0)
         })
@@ -380,10 +397,8 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn config_aneg_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) };
+            // SAFETY: PHYLIB holds `phy_device->lock` when it calls this.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::config_aneg(dev)?;
             Ok(0)
         })
@@ -394,10 +409,9 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn read_status_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) };
+            // SAFETY: PHYLIB holds `phy_device->lock` when it calls this, or a MAC driver that
+            // calls `phy_read_status()` directly ensures exclusive access.
+            let dev = unsafe { Device::from_raw_mut(phydev) };
             T::read_status(dev)?;
             Ok(0)
         })
@@ -410,9 +424,8 @@ impl<T: Driver> Adapter<T> {
         phydev: *mut bindings::phy_device,
         _phydrv: *const bindings::phy_driver,
     ) -> c_int {
-        // SAFETY: This callback is called only in contexts
-        // where we hold `phy_device->lock`, so the accessors on
-        // `Device` are okay to call.
+        // SAFETY: `phy_bus_match()` calls this without any PHY lock, possibly on a device
+        // that is bound to another driver. A `&Device` makes no claim about the lock.
         let dev = unsafe { Device::from_raw(phydev) };
         T::match_phy_device(dev).into()
     }
@@ -429,7 +442,7 @@ impl<T: Driver> Adapter<T> {
             // 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 dev = unsafe { Device::from_raw_mut(phydev) };
             // CAST: the C side verifies devnum < 32.
             let ret = T::read_mmd(dev, devnum as u8, regnum)?;
             Ok(ret.into())
@@ -449,7 +462,7 @@ impl<T: Driver> Adapter<T> {
             // 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 dev = unsafe { Device::from_raw_mut(phydev) };
             T::write_mmd(dev, devnum as u8, regnum, val)?;
             Ok(0)
         })
@@ -459,10 +472,8 @@ impl<T: Driver> Adapter<T> {
     ///
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn link_change_notify_callback(phydev: *mut bindings::phy_device) {
-        // 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) };
+        // SAFETY: PHYLIB holds `phy_device->lock` when it calls this.
+        let dev = unsafe { Device::from_raw_mut(phydev) };
         T::link_change_notify(dev);
     }
 }
diff --git a/rust/kernel/net/phy/reg.rs b/rust/kernel/net/phy/reg.rs
index 80e22c264ea8..f96cc06bfe3a 100644
--- a/rust/kernel/net/phy/reg.rs
+++ b/rust/kernel/net/phy/reg.rs
@@ -44,10 +44,10 @@ pub trait Sealed {}
 /// ```
 pub trait Register: private::Sealed {
     /// Reads a PHY register.
-    fn read(&self, dev: &mut Device) -> Result<u16>;
+    fn read(&self, dev: &Device) -> Result<u16>;
 
     /// Writes a PHY register.
-    fn write(&self, dev: &mut Device, val: u16) -> Result;
+    fn write(&self, dev: &Device, val: u16) -> Result;
 
     /// Checks the link status and updates current link state.
     fn read_status(dev: &mut Device) -> Result<u16>;
@@ -104,7 +104,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(&self, dev: &Device) -> 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 +116,7 @@ fn read(&self, dev: &mut Device) -> Result<u16> {
         Ok(ret as u16)
     }
 
-    fn write(&self, dev: &mut Device, val: u16) -> Result {
+    fn write(&self, dev: &Device, 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 +196,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(&self, dev: &Device) -> 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 +206,7 @@ fn read(&self, dev: &mut Device) -> Result<u16> {
         Ok(ret as u16)
     }
 
-    fn write(&self, dev: &mut Device, val: u16) -> Result {
+    fn write(&self, dev: &Device, 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] 5+ messages in thread

* [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd
  2026-11-26 14:08 [PATCH net-next v4 0/2] rust: net: phy: pass &Device to callbacks without exclusive access SeungJong Ha
  2026-11-26 14:08 ` [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock SeungJong Ha
@ 2026-11-26 14:08 ` SeungJong Ha
  2026-11-27 15:01   ` netdev-bot+sashiko
  1 sibling, 1 reply; 5+ messages in thread
From: SeungJong Ha @ 2026-11-26 14:08 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_suspend() calls `suspend` without `phy_device->lock`, also right
after the state machine drops it, and __phy_read_mmd() and
__phy_write_mmd() call `read_mmd` and `write_mmd` with the MDIO bus lock
held but not necessarily `phy_device->lock`. Yet these callbacks get a
`&mut Device` and can call methods such as set_speed() that rely on the
lock.

Pass a `&Device` instead, and document that read() and write() deadlock
in `read_mmd` and `write_mmd`. Update ax88796b_rust, the only user of
`suspend`; it only calls genphy_suspend().

Suggested-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
 drivers/net/phy/ax88796b_rust.rs |  4 ++--
 rust/kernel/net/phy.rs           | 36 +++++++++++++++++++++---------------
 2 files changed, 23 insertions(+), 17 deletions(-)

diff --git a/drivers/net/phy/ax88796b_rust.rs b/drivers/net/phy/ax88796b_rust.rs
index 2d24628a4e58..890ae79d8561 100644
--- a/drivers/net/phy/ax88796b_rust.rs
+++ b/drivers/net/phy/ax88796b_rust.rs
@@ -77,7 +77,7 @@ fn read_status(dev: &mut phy::Device) -> Result<u16> {
         Ok(0)
     }
 
-    fn suspend(dev: &mut phy::Device) -> Result {
+    fn suspend(dev: &phy::Device) -> Result {
         dev.genphy_suspend()
     }
 
@@ -107,7 +107,7 @@ impl Driver for PhyAX88772C {
     const NAME: &'static CStr = c"Asix Electronics AX88772C";
     const PHY_DEVICE_ID: DeviceId = DeviceId::new_with_exact_mask(0x003b1881);
 
-    fn suspend(dev: &mut phy::Device) -> Result {
+    fn suspend(dev: &phy::Device) -> Result {
         dev.genphy_suspend()
     }
 
diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index bb2cc6b3c94c..d04a651ae62b 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -371,10 +371,10 @@ impl<T: Driver> Adapter<T> {
     /// `phydev` must be passed by the corresponding callback in `phy_driver`.
     unsafe extern "C" fn suspend_callback(phydev: *mut bindings::phy_device) -> c_int {
         from_result(|| {
-            // SAFETY: The C core code ensures that the accessors on
-            // `Device` are okay to call even though `phy_device->lock`
-            // might not be held.
-            let dev = unsafe { Device::from_raw_mut(phydev) };
+            // SAFETY: `phydev` is valid for the duration of the callback. `phy_suspend()` does not
+            // take `phy_device->lock`, and `phy_state_machine()` calls it right after dropping the
+            // lock, so this gets a `&Device`.
+            let dev = unsafe { Device::from_raw(phydev) };
             T::suspend(dev)?;
             Ok(0)
         })
@@ -439,10 +439,10 @@ impl<T: Driver> Adapter<T> {
         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_mut(phydev) };
+            // SAFETY: `phydev` is valid for the duration of the callback. PHYLIB calls this with
+            // the MDIO bus lock held but not necessarily `phy_device->lock`, so this gets a
+            // `&Device`.
+            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())
@@ -459,10 +459,10 @@ impl<T: Driver> Adapter<T> {
         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_mut(phydev) };
+            // SAFETY: `phydev` is valid for the duration of the callback. PHYLIB calls this with
+            // the MDIO bus lock held but not necessarily `phy_device->lock`, so this gets a
+            // `&Device`.
+            let dev = unsafe { Device::from_raw(phydev) };
             T::write_mmd(dev, devnum as u8, regnum, val)?;
             Ok(0)
         })
@@ -617,7 +617,7 @@ fn read_status(_dev: &mut Device) -> Result<u16> {
     }
 
     /// Suspends the hardware, saving state if needed.
-    fn suspend(_dev: &mut Device) -> Result {
+    fn suspend(_dev: &Device) -> Result {
         build_error!(VTABLE_DEFAULT_ERROR)
     }
 
@@ -627,12 +627,18 @@ fn resume(_dev: &mut Device) -> Result {
     }
 
     /// Overrides the default MMD read function for reading a MMD register.
-    fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result<u16> {
+    ///
+    /// PHYLIB calls this with the MDIO bus lock held, so calling [`Device::read`] or
+    /// [`Device::write`] here deadlocks.
+    fn read_mmd(_dev: &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 {
+    ///
+    /// PHYLIB calls this with the MDIO bus lock held, so calling [`Device::read`] or
+    /// [`Device::write`] here deadlocks.
+    fn write_mmd(_dev: &Device, _devnum: u8, _regnum: u16, _val: u16) -> Result {
         build_error!(VTABLE_DEFAULT_ERROR)
     }
 

-- 
2.54.0


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

* Re: [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock
  2026-11-26 14:08 ` [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock SeungJong Ha
@ 2026-11-27 15:01   ` netdev-bot+sashiko
  0 siblings, 0 replies; 5+ messages in thread
From: netdev-bot+sashiko @ 2026-11-27 15:01 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 1 potential
issue(s) to consider.

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

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] In rust/kernel/net/phy.rs, `Adapter::soft_reset_callback`
  still builds a `&mut Device` with `Device::from_raw_mut()` on a path…

--

rust: net: phy: take &self in methods that do not need phy_device->lock

This commit splits Device::from_raw() into a shared from_raw() and a new
from_raw_mut(). It redefines &mut Device to mean exclusive access to the
phy_device state that phy_device->lock protects. The getters for that state
now take &mut self, and phy_id(), read(), write() and genphy_suspend() now
take &self. The callback SAFETY comments are updated to say when PHYLIB
calls the callbacks without the lock.

> diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> index c4e7b1d6c6f4a..bb2cc6b3c94c8 100644
> --- a/rust/kernel/net/phy.rs
> +++ b/rust/kernel/net/phy.rs
> @@ -57,50 +57,71 @@ pub enum DuplexMode {

[ ... ]

> +/// PHYLIB calls the callbacks that get a `&mut Device` with `phy_device->lock` held, except:
> +///
> +/// - [`Driver::probe`] and [`Driver::get_features`], which `phy_probe()` calls without the lock
> +///   before the device is attached.
> +/// - [`Driver::soft_reset`], which `phy_init_hw()` calls without the lock while the state machine
> +///   is not running, or from a MAC driver that then ensures exclusive access. `phy_mii_ioctl()`,
> +///   which PHYLIB documents as "use at own risk", is outside this guarantee.
> +/// - [`Driver::read_status`], when a MAC driver calls `phy_read_status()` directly. The MAC
> +///   driver is then responsible for exclusive access.
> +///
>  /// # Invariants
>  ///
> -/// - Referencing a `phy_device` using this struct asserts that you are in
> -///   a context where all methods defined on this struct are safe to call.
> -/// - This struct always has a valid `self.0.mdio.dev`.
> +/// - `self.0` is a valid `phy_device`, and `self.0.mdio.dev` is a valid `struct device`.
> +/// - For the lifetime of a `&mut Device`, no other thread accesses the state of the `phy_device`
> +///   that `phy_device->lock` protects.

[ ... ]

> +    /// Creates a new mutable [`Device`] reference from a raw pointer.
> +    ///
> +    /// # Safety
> +    ///
> +    /// For the duration of `'a`,
> +    /// - the pointer must point at a valid `phy_device`.
> +    /// - `(*ptr).mdio.dev` must be valid.
> +    /// - the caller must have the exclusive access that [`Device`] describes.
> +    unsafe fn from_raw_mut<'a>(ptr: *mut bindings::phy_device) -> &'a mut Self {

[ ... ]

> @@ -309,10 +331,10 @@ 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.
> -            let dev = unsafe { Device::from_raw(phydev) };
> +            // SAFETY: `phy_init_hw()` calls this with `phy_device->lock` held, or without it while
> +            // the state machine is not running or a MAC driver ensures exclusive access. The
> +            // `phy_mii_ioctl()` path is outside this guarantee, see `Device`.
> +            let dev = unsafe { Device::from_raw_mut(phydev) };

[Severity: Medium]
Is it sound to call Device::from_raw_mut() in soft_reset_callback() when
the SAFETY comment says the phy_mii_ioctl() path does not give the
exclusive access that from_raw_mut() now requires?

The new invariant on Device says that for the lifetime of a &mut Device,
no other thread accesses the phy_device state that phy_device->lock
protects. However, phy_mii_ioctl() reaches this callback without
phydev->lock, and the PHY state machine may be running at that point:

phy_mii_ioctl()     /* SIOCSMIIREG, BMCR write with BMCR_RESET */
  phy_init_hw(phydev)
    phydev->drv->soft_reset(phydev)
      Adapter::soft_reset_callback()
        Device::from_raw_mut(phydev)
          T::soft_reset(dev)

drivers/net/phy/phy.c:phy_mii_ioctl() {
    ...
		if (prtad == phydev->mdio.addr &&
		    devad == MII_BMCR &&
		    val & BMCR_RESET)
			return phy_init_hw(phydev);
    ...
}

At the same time, phy_state_machine() can hold phydev->lock and run
read_status_callback(). That creates a second &mut Device and writes link,
speed and duplex.

Safe code in a driver's soft_reset can call state(), is_link_up(),
is_autoneg_enabled(), is_autoneg_completed(), set_speed() and set_duplex().
Wouldn't that be a data race reachable from safe Rust?

The commit message says the goal is "so that safe code cannot use that
state without the access". Documenting phy_mii_ioctl() as "outside this
guarantee" does not seem to enforce that.

soft_reset already got a &mut Device before this patch. This patch states
the exclusivity precondition explicitly, though, and the new SAFETY comment
says it is not met on this path. The only in-tree user, asix_soft_reset()
in ax88796b_rust, calls only dev.write() and genphy_soft_reset(). The last
patch in the series, "rust: net: phy: pass &Device to suspend, read_mmd and
write_mmd", leaves soft_reset_callback() unchanged.

Could Driver::soft_reset take a &Device instead, so this path does not
create a &mut Device?

>              T::soft_reset(dev)?;
>              Ok(0)
>          })

[ ... ]

-- 
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261126-exp-phy-rs-maybelocked-v4-0-16f9a10bb579%40gmail.com

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

* Re: [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd
  2026-11-26 14:08 ` [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd SeungJong Ha
@ 2026-11-27 15:01   ` netdev-bot+sashiko
  0 siblings, 0 replies; 5+ messages in thread
From: netdev-bot+sashiko @ 2026-11-27 15:01 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 more severe
issue(s) in other patches of this series. This mail is only an FYI, in case
you want to address the nit picks below when you respin.

Low priority / nit picks for your consideration:

- [Low] This patch adds doc comments to `Driver::read_mmd` and
  `Driver::write_mmd` in rust/kernel/net/phy.rs.

--

rust: net: phy: pass &Device to suspend, read_mmd and write_mmd

This commit changes the suspend, read_mmd and write_mmd callbacks in the
Rust PHY abstraction to take &Device instead of &mut Device. The reason is
that PHYLIB does not always hold phy_device->lock when it calls them. It
also documents that read() and write() deadlock inside read_mmd and
write_mmd, and updates ax88796b_rust to match.

> diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> index bb2cc6b3c94c8..d04a651ae62b2 100644
> --- a/rust/kernel/net/phy.rs
> +++ b/rust/kernel/net/phy.rs

[ ... ]

> @@ -627,12 +627,18 @@ fn resume(_dev: &mut Device) -> Result {
>      }
>  
>      /// Overrides the default MMD read function for reading a MMD register.
> -    fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result<u16> {
> +    ///
> +    /// PHYLIB calls this with the MDIO bus lock held, so calling [`Device::read`] or
> +    /// [`Device::write`] here deadlocks.
> +    fn read_mmd(_dev: &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 {
> +    ///
> +    /// PHYLIB calls this with the MDIO bus lock held, so calling [`Device::read`] or
> +    /// [`Device::write`] here deadlocks.
> +    fn write_mmd(_dev: &Device, _devnum: u8, _regnum: u16, _val: u16) -> Result {

[Severity: Low]
Should this list of deadlocking methods include Device::genphy_suspend()
as well?

The previous patch in the series ("rust: net: phy: take &self in methods
that do not need phy_device->lock") changed genphy_suspend() to take &self.
That means read_mmd and write_mmd can call it through the &Device they now
receive:

rust/kernel/net/phy.rs:Device::genphy_suspend() {
    pub fn genphy_suspend(&self) -> Result {
        let phydev = self.0.get();
        ...
        to_result(unsafe { bindings::genphy_suspend(phydev) })
    }
}

On the C side, that call takes the MDIO bus lock a second time:

phy_read_mmd()
  phy_lock_mdio_bus(phydev)
  __phy_read_mmd()
    phydev->drv->read_mmd()          <- Rust read_mmd callback
      Device::genphy_suspend()
        genphy_suspend()
          phy_set_bits(phydev, MII_BMCR, BMCR_PDOWN)
            phy_modify()
              phy_lock_mdio_bus(phydev)   <- deadlock on bus->mdio_lock

phy_write_mmd()->__phy_write_mmd()->drv->write_mmd follows the same path.

As far as I can tell, read(), write() and genphy_suspend() are the only
&Device methods that access the hardware. All three take the MDIO bus
lock, and the abstraction has no unlocked accessor along the lines of
__phy_read() or __mdiobus_read().

If that is right, a read_mmd or write_mmd override cannot safely reach the
bus at all. Could the doc comment say this, or at least name
genphy_suspend() next to read() and write()?

No in-tree Rust driver implements read_mmd or write_mmd today. Before this
series, &mut Device methods such as read_paged() could already deadlock
here in the same way. The incomplete wording itself is new in this patch.

>          build_error!(VTABLE_DEFAULT_ERROR)
>      }
>

-- 
Sashiko AI review · https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261126-exp-phy-rs-maybelocked-v4-0-16f9a10bb579%40gmail.com

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

end of thread, other threads:[~2026-11-27 15:01 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26 14:08 [PATCH net-next v4 0/2] rust: net: phy: pass &Device to callbacks without exclusive access SeungJong Ha
2026-11-26 14:08 ` [PATCH net-next v4 1/2] rust: net: phy: take &self in methods that do not need phy_device->lock SeungJong Ha
2026-11-27 15:01   ` netdev-bot+sashiko
2026-11-26 14:08 ` [PATCH net-next v4 2/2] rust: net: phy: pass &Device to suspend, read_mmd and write_mmd SeungJong Ha
2026-11-27 15:01   ` 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®