Skip to contentSkip to conversation

Rust abstractions for network PHY drivers

PATCH Applied FUJITA Tomonori 2 participants 6 messages Dec 13, 2023 – Dec 15, 2023

Subsystems (6)
lore
Share & tools
lore

FUJITA Tomonori

author maintainer
#0 lore raw

v11 cover Rust abstractions for network PHY drivers

No functional change since v10; only comment and commit log updates.

This patchset adds Rust abstractions for phylib. It doesn't fully cover the C APIs yet but I think that it's already useful. I implement two PHY drivers (Asix AX88772A PHYs and Realtek Generic FE-GE). Seems they work well with real hardware.

The first patch introduces Rust bindings for phylib.

The second patch adds a macro to declare a kernel module for PHYs drivers.

The third adds the Rust ETHERNET PHY LIBRARY entry to MAINTAINERS file; adds the binding file and me as a maintainer (as Andrew Lunn suggested) with Trevor Gross as a reviewer.

The last patch introduces the Rust version of Asix PHY driver, drivers/net/phy/ax88796b.c. The features are equivalent to the C version. You can choose C (by default) or Rust version on kernel configuration.

v11:
- adds Andrew, Alice, and Trevor's Reviewed-by
- comment update
v10: https://lore.kernel.org/netdev/[email protected]/T/
- adds Trevor's SoB to the third patch
- adds Benno's Reviewed-by to the second patch
v9: https://lore.kernel.org/netdev/[email protected]/T/
- adds a workaround to access to a bit field in phy_device
- fixes a comment typo
v8: https://lore.kernel.org/netdev/[email protected]/
- updates the safety comments on Device and its related code
- uses _phy_start_aneg instead of phy_start_aneg
- drops the patch for enum synchronization
- moves Sync From Registration to DriverVTable
- fixes doctest errors
- minor cleanups
v7: https://lore.kernel.org/netdev/[email protected]/T/
- renames get_link() to is_link_up()
- improves the macro format
- improves the commit log in the third patch
- improves comments
v6: https://lore.kernel.org/netdev/[email protected]/T/
- improves comments
- makes the requirement of phy_drivers_register clear
- fixes Makefile of the third patch
v5: https://lore.kernel.org/all/[email protected]/T/
- drops the rustified-enum option, writes match by hand; no *risk* of UB
- adds Miguel's patch for enum checking
- moves CONFIG_RUST_PHYLIB_ABSTRACTIONS to drivers/net/phy/Kconfig
- adds a new entry for this abstractions in MAINTAINERS
- changes some of Device's methods to take &mut self
- comment improvment
v4: https://lore.kernel.org/netdev/[email protected]/T/
- split the core patch
- making Device::from_raw() private
- comment improvement with code update
- commit message improvement
- avoiding using bindings::phy_driver in public functions
- using an anonymous constant in module_phy_driver macro
v3: https://lore.kernel.org/netdev/[email protected]/T/
- changes the base tree to net-next from rust-next
- makes this feature optional; only enabled with CONFIG_RUST_PHYLIB_BINDINGS=y
- cosmetic code and comment improvement
- adds copyright
v2: https://lore.kernel.org/netdev/[email protected]/T/
- build failure fix
- function renaming
v1: https://lore.kernel.org/netdev/[email protected]/T/

FUJITA Tomonori (4):
rust: core abstractions for network PHY drivers
rust: net::phy add module_phy_driver macro
MAINTAINERS: add Rust PHY abstractions for ETHERNET PHY LIBRARY
net: phy: add Rust Asix PHY driver

 MAINTAINERS                      |  16 +
 drivers/net/phy/Kconfig          |  16 +
 drivers/net/phy/Makefile         |   6 +-
 drivers/net/phy/ax88796b_rust.rs | 135 +++++
 rust/bindings/bindings_helper.h  |   3 +
 rust/kernel/lib.rs               |   3 +
 rust/kernel/net.rs               |   6 +
 rust/kernel/net/phy.rs           | 901 +++++++++++++++++++++++++++++++
 rust/uapi/uapi_helper.h          |   2 +
 9 files changed, 1087 insertions(+), 1 deletion(-)
 create mode 100644 drivers/net/phy/ax88796b_rust.rs
 create mode 100644 rust/kernel/net.rs
 create mode 100644 rust/kernel/net/phy.rs

base-commit: 172db56d90d29e47e7d0d64885d5dbd92c87ec42

Signature · 1 line
2.34.1
author maintainer
#1 lore raw

PATCH v11 1/4 rust: core abstractions for network PHY drivers

This patch adds abstractions to implement network PHY drivers; the driver registration and bindings for some of callback functions in struct phy_driver and many genphy_ functions.

This feature is enabled with CONFIG_RUST_PHYLIB_ABSTRACTIONS=y.

This patch enables unstable const_maybe_uninit_zeroed feature for kernel crate to enable unsafe code to handle a constant value with uninitialized data. With the feature, the abstractions can initialize a phy_driver structure with zero easily; instead of initializing all the members by hand. It's supposed to be stable in the not so distant future.

---
 drivers/net/phy/Kconfig         |   8 +
 rust/bindings/bindings_helper.h |   3 +
 rust/kernel/lib.rs              |   3 +
 rust/kernel/net.rs              |   6 +
 rust/kernel/net/phy.rs          | 755 ++++++++++++++++++++++++++++++++
 5 files changed, 775 insertions(+)
 create mode 100644 rust/kernel/net.rs
 create mode 100644 rust/kernel/net/phy.rs
drivers/net/phy/Kconfig +8 -0
index 25cfc5ded1da..8d00cece5e23 100644
@@ -60,6 +60,14 @@ config FIXED_PHY
 
 	  Currently tested with mpc866ads and mpc8349e-mitx.
 
+config RUST_PHYLIB_ABSTRACTIONS
+        bool "Rust PHYLIB abstractions support"
+        depends on RUST
+        depends on PHYLIB=y
+        help
+          Adds support needed for PHY drivers written in Rust. It provides
+          a wrapper around the C phylib core.
+
 config SFP
 	tristate "SFP cage support"
 	depends on I2C && PHYLINK
rust/bindings/bindings_helper.h +3 -0
index 85f013ed4ca4..eaf01df7d97a 100644
@@ -8,6 +8,9 @@
 
 #include <kunit/test.h>
 #include <linux/errname.h>
+#include <linux/ethtool.h>
+#include <linux/mdio.h>
+#include <linux/phy.h>
 #include <linux/slab.h>
 #include <linux/refcount.h>
 #include <linux/wait.h>
rust/kernel/lib.rs +3 -0
index e6aff80b521f..7ac39874aeac 100644
@@ -14,6 +14,7 @@
 #![no_std]
 #![feature(allocator_api)]
 #![feature(coerce_unsized)]
+#![feature(const_maybe_uninit_zeroed)]
 #![feature(dispatch_from_dyn)]
 #![feature(new_uninit)]
 #![feature(offset_of)]
@@ -38,6 +39,8 @@
 pub mod ioctl;
 #[cfg(CONFIG_KUNIT)]
 pub mod kunit;
+#[cfg(CONFIG_NET)]
+pub mod net;
 pub mod prelude;
 pub mod print;
 mod static_assert;
rust/kernel/net.rs new file +6 -0
new file mode 100644
index 000000000000..fe415cb369d3
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Networking.
+
+#[cfg(CONFIG_RUST_PHYLIB_ABSTRACTIONS)]
+pub mod phy;
rust/kernel/net/phy.rs new file +755 -0

755 lines not on this page · raw message

Signature · 1 line
2.34.1
author maintainer
#2 lore raw

PATCH v11 2/4 rust: net::phy add module_phy_driver macro

In reply to FUJITA Tomonori

This macro creates an array of kernel's struct phy_driver and registers it. This also corresponds to the kernel's MODULE_DEVICE_TABLE macro, which embeds the information for module loading into the module binary file.

A PHY driver should use this macro.

---
 rust/kernel/net/phy.rs | 146 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 146 insertions(+)
rust/kernel/net/phy.rs +146 -0
index b6142579e8fd..e457b3c7cb2f 100644
@@ -753,3 +753,149 @@ const fn as_int(&self) -> u32 {
         }
     }
 }
+
+/// Declares a kernel module for PHYs drivers.
+///
+/// This creates a static array of kernel's `struct phy_driver` and registers it.
+/// This also corresponds to the kernel's `MODULE_DEVICE_TABLE` macro, which embeds the information
+/// for module loading into the module binary file. Every driver needs an entry in `device_table`.
+///
+/// # Examples
+///
+/// ```
+/// # mod module_phy_driver_sample {
+/// use kernel::c_str;
+/// use kernel::net::phy::{self, DeviceId};
+/// use kernel::prelude::*;
+///
+/// kernel::module_phy_driver! {
+///     drivers: [PhySample],
+///     device_table: [
+///         DeviceId::new_with_driver::<PhySample>()
+///     ],
+///     name: "rust_sample_phy",
+///     author: "Rust for Linux Contributors",
+///     description: "Rust sample PHYs driver",
+///     license: "GPL",
+/// }
+///
+/// struct PhySample;
+///
+/// #[vtable]
+/// impl phy::Driver for PhySample {
+///     const NAME: &'static CStr = c_str!("PhySample");
+///     const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
+/// }
+/// # }
+/// ```
+///
+/// This expands to the following code:
+///
+/// ```ignore
+/// use kernel::c_str;
+/// use kernel::net::phy::{self, DeviceId};
+/// use kernel::prelude::*;
+///
+/// struct Module {
+///     _reg: ::kernel::net::phy::Registration,
+/// }
+///
+/// module! {
+///     type: Module,
+///     name: "rust_sample_phy",
+///     author: "Rust for Linux Contributors",
+///     description: "Rust sample PHYs driver",
+///     license: "GPL",
+/// }
+///
+/// struct PhySample;
+///
+/// #[vtable]
+/// impl phy::Driver for PhySample {
+///     const NAME: &'static CStr = c_str!("PhySample");
+///     const PHY_DEVICE_ID: phy::DeviceId = phy::DeviceId::new_with_exact_mask(0x00000001);
+/// }
+///
+/// const _: () = {
+///     static mut DRIVERS: [::kernel::net::phy::DriverVTable; 1] =
+///         [::kernel::net::phy::create_phy_driver::<PhySample>()];
+///
+///     impl ::kernel::Module for Module {
+///         fn init(module: &'static ThisModule) -> Result<Self> {
+///             let drivers = unsafe { &mut DRIVERS };
+///             let mut reg = ::kernel::net::phy::Registration::register(
+///                 module,
+///                 ::core::pin::Pin::static_mut(drivers),
+///             )?;
+///             Ok(Module { _reg: reg })
+///         }
+///     }
+/// };
+///
+/// #[cfg(MODULE)]
+/// #[no_mangle]
+/// static __mod_mdio__phydev_device_table: [::kernel::bindings::mdio_device_id; 2] = [
+///     ::kernel::bindings::mdio_device_id {
+///         phy_id: 0x00000001,
+///         phy_id_mask: 0xffffffff,
+///     },
+///     ::kernel::bindings::mdio_device_id {
+///         phy_id: 0,
+///         phy_id_mask: 0,
+///     },
+/// ];
+/// ```
+#[macro_export]
+macro_rules! module_phy_driver {
+    (@replace_expr $_t:tt $sub:expr) => {$sub};
+
+    (@count_devices $($x:expr),*) => {
+        0usize $(+ $crate::module_phy_driver!(@replace_expr $x 1usize))*
+    };
+
+    (@device_table [$($dev:expr),+]) => {
+        // SAFETY: C will not read off the end of this constant since the last element is zero.
+        #[cfg(MODULE)]
+        #[no_mangle]
+        static __mod_mdio__phydev_device_table: [$crate::bindings::mdio_device_id;
+            $crate::module_phy_driver!(@count_devices $($dev),+) + 1] = [
+            $($dev.mdio_device_id()),+,
+            $crate::bindings::mdio_device_id {
+                phy_id: 0,
+                phy_id_mask: 0
+            }
+        ];
+    };
+
+    (drivers: [$($driver:ident),+ $(,)?], device_table: [$($dev:expr),+ $(,)?], $($f:tt)*) => {
+        struct Module {
+            _reg: $crate::net::phy::Registration,
+        }
+
+        $crate::prelude::module! {
+            type: Module,
+            $($f)*
+        }
+
+        const _: () = {
+            static mut DRIVERS: [$crate::net::phy::DriverVTable;
+                $crate::module_phy_driver!(@count_devices $($driver),+)] =
+                [$($crate::net::phy::create_phy_driver::<$driver>()),+];
+
+            impl $crate::Module for Module {
+                fn init(module: &'static ThisModule) -> Result<Self> {
+                    // SAFETY: The anonymous constant guarantees that nobody else can access
+                    // the `DRIVERS` static. The array is used only in the C side.
+                    let drivers = unsafe { &mut DRIVERS };
+                    let mut reg = $crate::net::phy::Registration::register(
+                        module,
+                        ::core::pin::Pin::static_mut(drivers),
+                    )?;
+                    Ok(Module { _reg: reg })
+                }
+            }
+        };
+
+        $crate::module_phy_driver!(@device_table [$($dev),+]);
+    }
+}
Signature · 1 line
2.34.1
author maintainer
#3 lore raw

PATCH v11 3/4 MAINTAINERS: add Rust PHY abstractions for ETHERNET PHY LIBRARY

In reply to FUJITA Tomonori

Adds me as a maintainer and Trevor as a reviewer.

The files are placed at rust/kernel/ directory for now but the files are likely to be moved to net/ directory once a new Rust build system is implemented.

---
 MAINTAINERS | 8 ++++++++
 1 file changed, 8 insertions(+)
MAINTAINERS +8 -0
index 7fb66210069b..089394a0af2e 100644
@@ -7921,6 +7921,14 @@ F:	include/uapi/linux/mdio.h
 F:	include/uapi/linux/mii.h
 F:	net/core/of_net.c
 
+ETHERNET PHY LIBRARY [RUST]
+M:	FUJITA Tomonori <[email protected]>
+R:	Trevor Gross <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Maintained
+F:	rust/kernel/net/phy.rs
+
 EXEC & BINFMT API
 R:	Eric Biederman <[email protected]>
 R:	Kees Cook <[email protected]>
Signature · 1 line
2.34.1
author maintainer
#4 lore raw

PATCH v11 4/4 net: phy: add Rust Asix PHY driver

In reply to FUJITA Tomonori

This is the Rust implementation of drivers/net/phy/ax88796b.c. The features are equivalent. You can choose C or Rust version kernel configuration.

---
 MAINTAINERS                      |   8 ++
 drivers/net/phy/Kconfig          |   8 ++
 drivers/net/phy/Makefile         |   6 +-
 drivers/net/phy/ax88796b_rust.rs | 135 +++++++++++++++++++++++++++++++
 rust/uapi/uapi_helper.h          |   2 +
 5 files changed, 158 insertions(+), 1 deletion(-)
 create mode 100644 drivers/net/phy/ax88796b_rust.rs
MAINTAINERS +8 -0
index 089394a0af2e..bbc6db6bebf4 100644
@@ -3083,6 +3083,14 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/net/asix,ax88796c.yaml
 F:	drivers/net/ethernet/asix/ax88796c_*
 
+ASIX PHY DRIVER [RUST]
+M:	FUJITA Tomonori <[email protected]>
+R:	Trevor Gross <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Maintained
+F:	drivers/net/phy/ax88796b_rust.rs
+
 ASPEED CRYPTO DRIVER
 M:	Neal Liu <[email protected]>
 L:	[email protected] (moderated for non-subscribers)
drivers/net/phy/Kconfig +8 -0
index 8d00cece5e23..0f483c3dfed9 100644
@@ -112,6 +112,14 @@ config AX88796B_PHY
 	  Currently supports the Asix Electronics PHY found in the X-Surf 100
 	  AX88796B package.
 
+config AX88796B_RUST_PHY
+	bool "Rust reference driver for Asix PHYs"
+	depends on RUST_PHYLIB_ABSTRACTIONS && AX88796B_PHY
+	help
+	  Uses the Rust reference driver for Asix PHYs (ax88796b_rust.ko).
+	  The features are equivalent. It supports the Asix Electronics PHY
+	  found in the X-Surf 100 AX88796B package.
+
 config BROADCOM_PHY
 	tristate "Broadcom 54XX PHYs"
 	select BCM_NET_PHYLIB
drivers/net/phy/Makefile +5 -1
index f65e85c91fc1..ab450a46b855 100644
@@ -37,7 +37,11 @@ obj-$(CONFIG_ADIN1100_PHY)	+= adin1100.o
 obj-$(CONFIG_AMD_PHY)		+= amd.o
 obj-$(CONFIG_AQUANTIA_PHY)	+= aquantia/
 obj-$(CONFIG_AT803X_PHY)	+= at803x.o
-obj-$(CONFIG_AX88796B_PHY)	+= ax88796b.o
+ifdef CONFIG_AX88796B_RUST_PHY
+  obj-$(CONFIG_AX88796B_PHY)	+= ax88796b_rust.o
+else
+  obj-$(CONFIG_AX88796B_PHY)	+= ax88796b.o
+endif
 obj-$(CONFIG_BCM54140_PHY)	+= bcm54140.o
 obj-$(CONFIG_BCM63XX_PHY)	+= bcm63xx.o
 obj-$(CONFIG_BCM7XXX_PHY)	+= bcm7xxx.o
drivers/net/phy/ax88796b_rust.rs new file +135 -0

135 lines not on this page · raw message

rust/uapi/uapi_helper.h +2 -0
index 301f5207f023..08f5e9334c9e 100644
@@ -7,3 +7,5 @@
  */
 
 #include <uapi/asm-generic/ioctl.h>
+#include <uapi/linux/mii.h>
+#include <uapi/linux/ethtool.h>
Signature · 1 line
2.34.1
#5 lore raw
In reply to FUJITA Tomonori
This series was applied to netdev/net-next.git (main) by David S. Miller <[email protected]>:

Hello:

This series was applied to netdev/net-next.git (main) by David S. Miller <[email protected]>:

Quoted 8 lines · On Wed, 13 Dec 2023 09:42:07 +0900 you wrote:

No functional change since v10; only comment and commit log updates.

This patchset adds Rust abstractions for phylib. It doesn't fully cover the C APIs yet but I think that it's already useful. I implement two PHY drivers (Asix AX88772A PHYs and Realtek Generic FE-GE). Seems they work well with real hardware.

[...]

Here is the summary with links:
- [net-next,v11,1/4] rust: core abstractions for network PHY drivers

    https://git.kernel.org/netdev/net-next/c/f20fd5449ada
  - [net-next,v11,2/4] rust: net::phy add module_phy_driver macro
    https://git.kernel.org/netdev/net-next/c/2fe11d5ab35d
  - [net-next,v11,3/4] MAINTAINERS: add Rust PHY abstractions for ETHERNET PHY LIBRARY
    https://git.kernel.org/netdev/net-next/c/cbaa28f970a1
  - [net-next,v11,4/4] net: phy: add Rust Asix PHY driver
    https://git.kernel.org/netdev/net-next/c/cbe0e4150896

You are awesome, thank you!

Signature · 2 lines
Deet-doot-dot, I am a bot.
https://korg.docs.kernel.org/patchwork/pwbot.html