Thread View: linux.kernel.netdev
9 messages
9 total messages
Started by SeungJong Ha
Tue, 17 Nov 2026 10:36
[PATCH net-next v3 0/3] rust: net: phy: suspend may run without phy_device->lock
Author: SeungJong Ha
Date: Tue, 17 Nov 2026 10:36
Date: Tue, 17 Nov 2026 10:36
63 lines
13953 bytes
13953 bytes
The Rust PHY abstraction tells every driver callback that PHYLIB holds
`phy_device->lock`, but phy_suspend() calls `suspend` without it, also
right after the state machine drops 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`, `write_mmd` and `match_phy_device`, which make
the same claim but are called under other conditions, and have no users.
Patch 2 makes `Device` generic over a lock context and documents when
the `Locked` callbacks run without the lock, and patch 3 gives `suspend`
the `MaybeLocked` one.
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.
[1] https://docs.kernel.org/dev-tools/context-analysis.html
---
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 (3):
rust: net: phy: drop unused read_mmd, write_mmd and match_phy_device
rust: net: phy: make Device generic over a lock context
rust: net: phy: pass a MaybeLocked device to suspend
drivers/net/phy/ax88796b_rust.rs | 4 +-
rust/kernel/net/phy.rs | 299 +++++++++++++++++----------------------
rust/kernel/net/phy/reg.rs | 17 ++-
3 files changed, 139 insertions(+), 181 deletions(-)
---
base-commit: 7ccc5e05043b1bb84326b19a2b05938d8f7a2ae6
change-id: 20261110-exp-phy-rs-maybelocked-ddc59993efba
Best regards,
--
SeungJong Ha <engineer.jjhama@gmail.com>
[PATCH net-next v3 2/3] rust: net: phy: make Device generic over a lock context
Author: SeungJong Ha
Date: Tue, 17 Nov 2026 10:36
Date: Tue, 17 Nov 2026 10:36
390 lines
28710 bytes
28710 bytes
Every PHY driver callback gets a `Device` that assumes `phy_device->lock`
is held, but suspend may run while another path holds it.
Make `Device` generic over a lock context, `Locked` (the default) or
`MaybeLocked`, as `device::Device` is, and move the methods that do not
need the lock to both contexts. The next patch moves suspend to
`MaybeLocked`.
Document when the `Locked` callbacks run without the lock, including the
existing phy_mii_ioctl() race, and fix their SAFETY comments.
No functional change.
Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
rust/kernel/net/phy.rs | 207 +++++++++++++++++++++++++++------------------
rust/kernel/net/phy/reg.rs | 17 ++--
2 files changed, 133 insertions(+), 91 deletions(-)
diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index 4604a9c0a511..8cbb4c19dac1 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -50,6 +50,55 @@ 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 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 from
+/// `phy_attach_direct()` and `mdio_bus_phy_resume()` while the state machine is not running, and
+/// from MAC drivers that call `phy_init_hw()` directly, which are then responsible for exclusive
+/// access. `phy_mii_ioctl()` also calls it without the lock while the state machine may run,
+/// which is an existing PHYLIB race.
+/// - [`Driver::read_status`], when a MAC driver calls `phy_read_status()` directly. The MAC
+/// driver is then responsible for exclusive access.
+///
+/// # 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 may call without `phy_device->lock` while
+/// another path holds it.
+///
+/// Only methods that do not rely on the lock are available. 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,48 +106,19 @@ 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
-/// 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`.
+/// - The invariants of `Ctx` hold for the lifetime of a `&mut Device<Ctx>`.
///
/// [`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>);
+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 +197,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();
@@ -238,14 +247,6 @@ pub fn genphy_resume(&mut self) -> Result {
to_result(unsafe { bindings::genphy_resume(phydev) })
}
- /// Suspends the PHY via `BMCR_PDOWN` bit.
- pub fn genphy_suspend(&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_suspend(phydev) })
- }
-
/// Checks the link status and updates current link state.
pub fn genphy_read_status<R: reg::Register>(&mut self) -> Result<u16> {
R::read_status(self)
@@ -276,7 +277,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)
+ }
+
+ /// Suspends the PHY via `BMCR_PDOWN` bit.
+ pub fn genphy_suspend(&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 only sets `BMCR_PDOWN`, serialized by the MDIO bus lock.
+ to_result(unsafe { bindings::genphy_suspend(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.
@@ -309,10 +355,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.
+ // `phy_mii_ioctl()` is an exception, see `Locked`. This is the `Locked` context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::soft_reset(dev)?;
Ok(0)
})
@@ -323,11 +369,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. This is the `Locked` context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::probe(dev)?;
Ok(0)
})
@@ -338,10 +382,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`. This is the `Locked` context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::get_features(dev)?;
Ok(0)
})
@@ -366,10 +409,9 @@ 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. This is the
+ // `Locked` context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::resume(dev)?;
Ok(0)
})
@@ -380,10 +422,9 @@ 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. This is the `Locked`
+ // context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::config_aneg(dev)?;
Ok(0)
})
@@ -394,10 +435,10 @@ 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. This is the `Locked`
+ // context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::read_status(dev)?;
Ok(0)
})
@@ -407,10 +448,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. This is the `Locked` context.
+ let dev = unsafe { Device::<Locked>::from_raw(phydev) };
T::link_change_notify(dev);
}
}
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
[PATCH net-next v3 3/3] rust: net: phy: pass a MaybeLocked device to suspend
Author: SeungJong Ha
Date: Tue, 17 Nov 2026 10:36
Date: Tue, 17 Nov 2026 10:36
67 lines
13573 bytes
13573 bytes
phy_suspend() calls `suspend` without `phy_device->lock`, also right
after the state machine drops it, so another path may hold the lock
meanwhile. Yet the callback gets a `Locked` device, and can call methods
such as set_speed() that rely on the lock.
Pass a `&mut Device<MaybeLocked>` and correct the SAFETY comment. Update
ax88796b_rust, the only user; it only calls genphy_suspend().
Signed-off-by: SeungJong Ha <engineer.jjhama@gmail.com>
---
drivers/net/phy/ax88796b_rust.rs | 4 ++--
rust/kernel/net/phy.rs | 9 ++++-----
2 files changed, 6 insertions(+), 7 deletions(-)
diff --git a/drivers/net/phy/ax88796b_rust.rs b/drivers/net/phy/ax88796b_rust.rs
index 2d24628a4e58..498704f1ef9d 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: &mut phy::Device<phy::MaybeLocked>) -> 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: &mut phy::Device<phy::MaybeLocked>) -> Result {
dev.genphy_suspend()
}
diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
index 8cbb4c19dac1..4b7b3ad09059 100644
--- a/rust/kernel/net/phy.rs
+++ b/rust/kernel/net/phy.rs
@@ -395,10 +395,9 @@ 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(phydev) };
+ // SAFETY: `phy_suspend()` does not take `phy_device->lock`, and `phy_state_machine()`
+ // calls it right after dropping the lock. This is the `MaybeLocked` context.
+ let dev = unsafe { Device::<MaybeLocked>::from_raw(phydev) };
T::suspend(dev)?;
Ok(0)
})
@@ -572,7 +571,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: &mut Device<MaybeLocked>) -> Result {
build_error!(VTABLE_DEFAULT_ERROR)
}
--
2.54.0
Re: [PATCH net-next v3 2/3] rust: net: phy: make Device generic over a lock context
Author: netdev-bot+sashiko
Date: Fri, 20 Nov 2026 01:37
Date: Fri, 20 Nov 2026 01:37
130 lines
13381 bytes
13381 bytes
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] This patch adds a formal `# Invariants` section to `Locked`:
"For the lifetime of a `&mut Device<Locked>`, no other thread accessesโฆ
--
rust: net: phy: make Device generic over a lock context
This patch makes the Rust PHY Device type generic over a lock context.
The context is either Locked (the default) or MaybeLocked, and methods
that do not need phy_device->lock move to both contexts. The patch also
documents when the Locked callbacks run without the lock and rewrites
their SAFETY comments.
> diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs
> index 4604a9c0a5111..8cbb4c19dac1d 100644
> --- a/rust/kernel/net/phy.rs
> +++ b/rust/kernel/net/phy.rs
> @@ -50,6 +50,55 @@ pub enum DuplexMode {
[ ... ]
> +/// - [`Driver::soft_reset`], which `phy_init_hw()` calls without the lock from
> +/// `phy_attach_direct()` and `mdio_bus_phy_resume()` while the state machine is not running, and
> +/// from MAC drivers that call `phy_init_hw()` directly, which are then responsible for exclusive
> +/// access. `phy_mii_ioctl()` also calls it without the lock while the state machine may run,
> +/// which is an existing PHYLIB race.
> +/// - [`Driver::read_status`], when a MAC driver calls `phy_read_status()` directly. The MAC
> +/// driver is then responsible for exclusive access.
> +///
> +/// # 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;
[ ... ]
> @@ -309,10 +355,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.
> + // `phy_mii_ioctl()` is an exception, see `Locked`. This is the `Locked` context.
> + let dev = unsafe { Device::<Locked>::from_raw(phydev) };
[Severity: Medium]
Does this SAFETY comment justify the from_raw() call?
The new Locked invariant says that no other thread accesses the
lock-protected phy_device state for the lifetime of a &mut Device<Locked>.
from_raw() now also requires the caller to be in the Ctx context.
However, this comment and the Locked docs above both say that
phy_mii_ioctl() reaches this callback without phydev->lock while the
state machine may be running.
An SIOCSMIIREG write to MII_BMCR with BMCR_RESET set takes this path:
ndo_eth_ioctl
phy_mii_ioctl()
phy_init_hw() /* no phydev->lock */
drv->soft_reset()
Adapter::soft_reset_callback()
Device::<Locked>::from_raw()
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 write
speed, duplex, link, autoneg and state.
This affects an in-tree driver. asix_soft_reset() in
drivers/net/phy/ax88796b_rust.rs calls genphy_soft_reset(), which is
only available on Device<Locked>. It reads phydev->autoneg and writes the
phydev->suspended bitfield.
Can that race with the state machine's writes to the same fields and to
the neighbouring bitfields? That would be a data race reachable from safe
Rust code.
The C-side race in phy_mii_ioctl() was there before this patch. The
Locked invariant and the "This is the Locked context" justification are
new here, though.
The commit message says:
Document when the `Locked` callbacks run without the lock, including the
existing phy_mii_ioctl() race, and fix their SAFETY comments.
For soft_reset, the new comment itself says the precondition is not met.
The later patches in the series only move suspend to MaybeLocked.
Would one of these work instead?
- take phydev->lock around phy_init_hw() in phy_mii_ioctl()
- weaken the Locked invariant and drop the accessors that rely on it
- give soft_reset a context that does not claim exclusive access
> T::soft_reset(dev)?;
> Ok(0)
> })
[ ... ]
--
Sashiko AI review ยท https://netdev-ai.bots.linux.dev/sashiko/#/patchset/20261117-exp-phy-rs-maybelocked-v3-0-4e183a7366a7%40gmail.com
Re: [PATCH net-next v3 2/3] rust: net: phy: make Device generic over a lock context
Author: SeungJong Ha
Date: Mon, 23 Nov 2026 03:11
Date: Mon, 23 Nov 2026 03:11
42 lines
12370 bytes
12370 bytes
2026๋ 11์ 20์ผ (๊ธ) ์ค์ 10:37, <netdev-bot+sashiko@kernel.org>๋์ด ์์ฑ: > [Severity: Medium] > > Does this SAFETY comment justify the from_raw() call? > > The new Locked invariant says that no other thread accesses the > lock-protected phy_device state for the lifetime of a &mut Device<Locked>. > from_raw() now also requires the caller to be in the Ctx context. > > However, this comment and the Locked docs above both say that > phy_mii_ioctl() reaches this callback without phydev->lock while the > state machine may be running. [...] > Would one of these work instead? > > - take phydev->lock around phy_init_hw() in phy_mii_ioctl() > - weaken the Locked invariant and drop the accessors that rely on it > - give soft_reset a context that does not claim exclusive access This is why the Locked docs list these exceptions. Taking phydev->lock around phy_init_hw() in phy_mii_ioctl() does not look safe as is: vsc85xx_config_init() takes the lock itself through vsc85xx_mac_if_set(), so it would deadlock. Fixing that race belongs in phy_mii_ioctl() and seems separate from this patch. The other two options would change drivers: ax88796b_rust's soft_reset needs genphy_soft_reset(), and the Locked callbacks need set_speed() and the other field accessors. Documenting the exception is the minimal compromise that keeps the abstraction usable without changing driver code. This series only separates the methods by lock context. Other contexts, such as the device contexts (Bound, Core) of device::Device, are a follow-up. Best regards, SeungJong Ha
Re: [PATCH net-next v3 2/3] rust: net: phy: make Device generic over a lock context
Author: Andrew Lunn
Date: Mon, 23 Nov 2026 04:31
Date: Mon, 23 Nov 2026 04:31
46 lines
10415 bytes
10415 bytes
On Mon, Nov 23, 2026 at 12:11:55PM +0900, SeungJong Ha wrote: > 2026๋ 11์ 20์ผ (๊ธ) ์ค์ 10:37, <netdev-bot+sashiko@kernel.org>๋์ด ์์ฑ: > > > > [Severity: Medium] > > > > Does this SAFETY comment justify the from_raw() call? > > > > The new Locked invariant says that no other thread accesses the > > lock-protected phy_device state for the lifetime of a &mut Device<Locked>. > > from_raw() now also requires the caller to be in the Ctx context. > > > > However, this comment and the Locked docs above both say that > > phy_mii_ioctl() reaches this callback without phydev->lock while the > > state machine may be running. > [...] > > Would one of these work instead? > > > > - take phydev->lock around phy_init_hw() in phy_mii_ioctl() > > - weaken the Locked invariant and drop the accessors that rely on it > > - give soft_reset a context that does not claim exclusive access > > This is why the Locked docs list these exceptions. Taking phydev->lock > around phy_init_hw() in phy_mii_ioctl() does not look safe as is: > vsc85xx_config_init() takes the lock itself through vsc85xx_mac_if_set(), > so it would deadlock. Fixing that race belongs in phy_mii_ioctl() and > seems separate from this patch. phy_mii_ioctl() is meant to be a foot gun, bad things are expected to happen if you use it. /** * phy_mii_ioctl - generic PHY MII ioctl interface * @phydev: the phy_device struct * @ifr: &struct ifreq for socket ioctl's * @cmd: ioctl cmd to execute * * Note that this function is currently incompatible with the * PHYCONTROL layer. It changes registers without regard to * current state. Use at own risk. */ I would not spend any time on this. Andrew
Re: [PATCH net-next v3 0/3] rust: net: phy: suspend may run without phy_device->lock
Author: FUJITA Tomonori
Date: Tue, 24 Nov 2026 12:57
Date: Tue, 24 Nov 2026 12:57
26 lines
14085 bytes
14085 bytes
On Tue, 17 Nov 2026 19:36:18 +0900 SeungJong Ha <engineer.jjhama@gmail.com> wrote: > Patch 1 drops `read_mmd`, `write_mmd` and `match_phy_device`, which make > the same claim but are called under other conditions, and have no users. > Patch 2 makes `Device` generic over a lock context and documents when > the `Locked` callbacks run without the lock, and patch 3 gives `suspend` > the `MaybeLocked` one. Can we use &Device and &mut Device instead of the new context types? &mut Device means exclusive access to the state that phy_device->lock protects. &Device makes no such claim. Methods that use that state (state(), set_speed(), ...) and read_paged() take &mut self. phy_id(), read(), write() and genphy_suspend() take &self. Then suspend, match_phy_device, read_mmd and write_mmd get &Device, and 1/3 is not needed. I would rather not drop callbacks. I want to make it easy to write new PHY drivers in Rust. For phy_mii_ioctl(), I agree with Andrew. The SAFETY comment can just say that this path is outside the guarantee. I tried this on 7.4-rc4. It builds, and the only driver change is the suspend signature in ax88796b_rust.
Re: [PATCH net-next v3 0/3] rust: net: phy: suspend may run without phy_device->lock
Author: SeungJong Ha
Date: Wed, 25 Nov 2026 09:40
Date: Wed, 25 Nov 2026 09:40
40 lines
14000 bytes
14000 bytes
On Tue, 24 Nov 2026 21:57:47 +0900 (JST), FUJITA Tomonori wrote: > > On Tue, 17 Nov 2026 19:36:18 +0900 > SeungJong Ha <engineer.jjhama@gmail.com> wrote: > > > Patch 1 drops `read_mmd`, `write_mmd` and `match_phy_device`, which make > > the same claim but are called under other conditions, and have no users. > > Patch 2 makes `Device` generic over a lock context and documents when > > the `Locked` callbacks run without the lock, and patch 3 gives `suspend` > > the `MaybeLocked` one. > > Can we use &Device and &mut Device instead of the new context types? [...] Yes, that is simpler. I will do that in v4. Two things to check first: - genphy_soft_reset() reads autoneg and writes suspended, so I would keep it on &mut self. soft_reset gets &mut Device, and the SAFETY comment says that the phy_mii_ioctl() path is outside the guarantee. - read() and write() take the MDIO bus lock, and &Device cannot say more than that the phy_device->lock state is off limits. In read_mmd and write_mmd the bus lock is already held, so they deadlock. A test driver whose read_mmd calls dev.read() hangs as soon as the PHY binds, and lockdep reports recursive locking on bus->mdio_lock. The path is phy_probe() -> genphy_read_abilities() -> genphy_c45_read_eee_abilities() -> phy_read_mmd(). In match_phy_device they reach a device that may be bound to another driver, which the netdev AI review pointed out on v1 [1]. Do you still want to keep these callbacks with &Device and document this, or wait until they can get accessors that fit their context? Best regards, SeungJong [1] https://lore.kernel.org/r/179454612500.2199510.688554972467066283@kernel.org
Re: [PATCH net-next v3 0/3] rust: net: phy: suspend may run without phy_device->lock
Author: FUJITA Tomonori
Date: Wed, 25 Nov 2026 23:11
Date: Wed, 25 Nov 2026 23:11
49 lines
15325 bytes
15325 bytes
On Wed, 25 Nov 2026 18:40:32 +0900 SeungJong Ha <engineer.jjhama@gmail.com> wrote: > On Tue, 24 Nov 2026 21:57:47 +0900 (JST), FUJITA Tomonori wrote: >> >> On Tue, 17 Nov 2026 19:36:18 +0900 >> SeungJong Ha <engineer.jjhama@gmail.com> wrote: >> >> > Patch 1 drops `read_mmd`, `write_mmd` and `match_phy_device`, which make >> > the same claim but are called under other conditions, and have no users. >> > Patch 2 makes `Device` generic over a lock context and documents when >> > the `Locked` callbacks run without the lock, and patch 3 gives `suspend` >> > the `MaybeLocked` one. >> >> Can we use &Device and &mut Device instead of the new context types? > [...] > > Yes, that is simpler. I will do that in v4. Two things to check first: > > - genphy_soft_reset() reads autoneg and writes suspended, so I would keep > it on &mut self. soft_reset gets &mut Device, and the SAFETY comment > says that the phy_mii_ioctl() path is outside the guarantee. Agreed. > - read() and write() take the MDIO bus lock, and &Device cannot say > more than that the phy_device->lock state is off limits. > > In read_mmd and write_mmd the bus lock is already held, so they > deadlock. A test driver whose read_mmd calls dev.read() hangs as soon > as the PHY binds, and lockdep reports recursive locking on > bus->mdio_lock. The path is phy_probe() -> genphy_read_abilities() -> > genphy_c45_read_eee_abilities() -> phy_read_mmd(). > > In match_phy_device they reach a device that may be bound to another > driver, which the netdev AI review pointed out on v1 [1]. > > Do you still want to keep these callbacks with &Device and document > this, or wait until they can get accessors that fit their context? Yes, please keep them with &Device and document it. The deadlock is not a soundness problem. I will add accessors for the bus-locked context, with a guard or a context type, as a follow-up. For match_phy_device, &Device fixes both problems in [1]: read_paged() needs &mut self, and read_mmd no longer gets &mut Device. > [1] https://lore.kernel.org/r/179454612500.2199510.688554972467066283@kernel.org
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads