Skip to contentSkip to conversation

net: phy: Add support for new Aeonsemi PHYs

PATCH Superseded Christian Marangi 4 participants 28 messages May 15, 2025 – May 19, 2025

Subsystems (10)

v10 of 12 Superseded Latest is v12 →

lore
Share & tools
lore

Christian Marangi

author maintainer
#0 lore raw

v10 cover net: phy: Add support for new Aeonsemi PHYs

Add support for new Aeonsemi 10G C45 PHYs. These PHYs intergate an IPC to setup some configuration and require special handling to sync with the parity bit. The parity bit is a way the IPC use to follow correct order of command sent.

Supported PHYs AS21011JB1, AS21011PB1, AS21010JB1, AS21010PB1, AS21511JB1, AS21511PB1, AS21510JB1, AS21510PB1, AS21210JB1, AS21210PB1 that all register with the PHY ID 0x7500 0x7500 before the firmware is loaded.

The big special thing about this PHY is that it does provide a generic PHY ID in C45 register that change to the correct one one the firmware is loaded.

In practice:
- MMD 0x7 ID 0x7500 0x9410 -> FW LOAD -> ID 0x7500 0x9422

To handle this, we operate on .match_phy_device where we check the PHY ID, if the ID match the generic one, we load the firmware and we return 0 (PHY driver doesn't match). Then PHY core will try the next PHY driver in the list and this time the PHY is correctly filled in and we register for it.

To help in the matching and not modify part of the PHY device struct, .match_phy_device is extended to provide also the current phy_driver is trying to match for. This add the extra benefits that some other PHY can simplify their .match_phy_device OP.

Changes v10:
- Add rust patch
Changes v9:
- Reorder AS21XXX_PHY kconfig before Airoha
- Add Reviewed-by tag from Andrew
Changes v8:
- Move IPC ready condition to dedicated function for poll timeout
- Fix typo aeon_ipcs_wait_cmd -> aeon_ipc_wait_cmd
- Merge aeon_ipc_send_msg and aeon_ipc_rcv_msg to
correctly handle locking
- Fix AEON_MAX_LDES typo
Changes v7:
- Make sure fw_version is NULL terminated
- Better describe logic for .match_phy_device
Changes v6:
- Out of RFC
- Add Reviewed-by tag from Russell
Changes v5:
- Add Reviewed-by tag from Rob
- Fix subject in DT patch
- Fix wrong Suggested-by tag in patch 1
- Rework nxp patch to 80 column
Changes v4:
- Add Reviewed-by tag
- Better handle PHY ID scan in as21xxx
- Also simplify nxp driver and fix .match_phy_device
Changes v3:
- Correct typo intergate->integrate
- Try to reduce to 80 column (where possible... define become unreasable if split)
- Rework to new .match_phy_device implementation
- Init active_low_led and fix other minor smatch war
- Drop inline tag (kbot doesn't like it but not reported by checkpatch???) Changes v2:
- Move to RFC as net-next closed :(
- Add lock for IPC command
- Better check size values from IPC
- Add PHY ID for all supported PHYs
- Drop .get_feature (correct values are exported by standard regs)
- Rework LED event to enum
- Update .yaml with changes requested (firmware-name required for generic PHY ID)
- Better document C22 in C45
- Document PHY name logic
- Introduce patch to load PHY 2 times

Christian Marangi (7):
net: phy: pass PHY driver to .match_phy_device OP
net: phy: bcm87xx: simplify .match_phy_device OP
net: phy: nxp-c45-tja11xx: simplify .match_phy_device OP
net: phy: introduce genphy_match_phy_device()
net: phy: Add support for Aeonsemi AS21xxx PHYs
dt-bindings: net: Document support for Aeonsemi PHYs
rust: net::phy sync with match_phy_device C changes

 .../bindings/net/aeonsemi,as21xxx.yaml        |  122 ++
 MAINTAINERS                                   |    7 +
 drivers/net/phy/Kconfig                       |   12 +
 drivers/net/phy/Makefile                      |    1 +
 drivers/net/phy/as21xxx.c                     | 1087 +++++++++++++++++
 drivers/net/phy/bcm87xx.c                     |   14 +-
 drivers/net/phy/icplus.c                      |    6 +-
 drivers/net/phy/marvell10g.c                  |   12 +-
 drivers/net/phy/micrel.c                      |    6 +-
 drivers/net/phy/nxp-c45-tja11xx.c             |   41 +-
 drivers/net/phy/nxp-tja11xx.c                 |    6 +-
 drivers/net/phy/phy_device.c                  |   52 +-
 drivers/net/phy/realtek/realtek_main.c        |   27 +-
 drivers/net/phy/teranetics.c                  |    3 +-
 include/linux/phy.h                           |    6 +-
 rust/kernel/net/phy.rs                        |   26 +-
 16 files changed, 1359 insertions(+), 69 deletions(-)
 create mode 100644 Documentation/devicetree/bindings/net/aeonsemi,as21xxx.yaml
 create mode 100644 drivers/net/phy/as21xxx.c
Signature · 1 line
2.48.1
author maintainer
#1 lore raw

PATCH v10 1/7 net: phy: pass PHY driver to .match_phy_device OP

Pass PHY driver pointer to .match_phy_device OP in addition to phydev. Having access to the PHY driver struct might be useful to check the PHY ID of the driver is being matched for in case the PHY ID scanned in the phydev is not consistent.

A scenario for this is a PHY that change PHY ID after a firmware is loaded, in such case, the PHY ID stored in PHY device struct is not valid anymore and PHY will manually scan the ID in the match_phy_device function.

Having the PHY driver info is also useful for those PHY driver that implement multiple simple .match_phy_device OP to match specific MMD PHY ID. With this extra info if the parsing logic is the same, the matching function can be generalized by using the phy_id in the PHY driver instead of hardcoding.

---
 drivers/net/phy/bcm87xx.c              |  6 ++++--
 drivers/net/phy/icplus.c               |  6 ++++--
 drivers/net/phy/marvell10g.c           | 12 ++++++++----
 drivers/net/phy/micrel.c               |  6 ++++--
 drivers/net/phy/nxp-c45-tja11xx.c      | 12 ++++++++----
 drivers/net/phy/nxp-tja11xx.c          |  6 ++++--
 drivers/net/phy/phy_device.c           |  2 +-
 drivers/net/phy/realtek/realtek_main.c | 27 +++++++++++++++++---------
 drivers/net/phy/teranetics.c           |  3 ++-
 include/linux/phy.h                    |  3 ++-
 10 files changed, 55 insertions(+), 28 deletions(-)
drivers/net/phy/bcm87xx.c +4 -2
index e81404bf8994..1e1e2259fc2b 100644
@@ -185,12 +185,14 @@ static irqreturn_t bcm87xx_handle_interrupt(struct phy_device *phydev)
 	return IRQ_HANDLED;
 }
 
-static int bcm8706_match_phy_device(struct phy_device *phydev)
+static int bcm8706_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phydev->c45_ids.device_ids[4] == PHY_ID_BCM8706;
 }
 
-static int bcm8727_match_phy_device(struct phy_device *phydev)
+static int bcm8727_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phydev->c45_ids.device_ids[4] == PHY_ID_BCM8727;
 }
drivers/net/phy/icplus.c +4 -2
index bbcc7d2b54cd..c0c4f19cfb6a 100644
@@ -520,12 +520,14 @@ static int ip101a_g_match_phy_device(struct phy_device *phydev, bool ip101a)
 	return ip101a == !ret;
 }
 
-static int ip101a_match_phy_device(struct phy_device *phydev)
+static int ip101a_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	return ip101a_g_match_phy_device(phydev, true);
 }
 
-static int ip101g_match_phy_device(struct phy_device *phydev)
+static int ip101g_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	return ip101a_g_match_phy_device(phydev, false);
 }
drivers/net/phy/marvell10g.c +8 -4
index 5354c8895163..13e81dff42c1 100644
@@ -1264,7 +1264,8 @@ static int mv3310_get_number_of_ports(struct phy_device *phydev)
 	return ret + 1;
 }
 
-static int mv3310_match_phy_device(struct phy_device *phydev)
+static int mv3310_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	if ((phydev->c45_ids.device_ids[MDIO_MMD_PMAPMD] &
 	     MARVELL_PHY_ID_MASK) != MARVELL_PHY_ID_88X3310)
@@ -1273,7 +1274,8 @@ static int mv3310_match_phy_device(struct phy_device *phydev)
 	return mv3310_get_number_of_ports(phydev) == 1;
 }
 
-static int mv3340_match_phy_device(struct phy_device *phydev)
+static int mv3340_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	if ((phydev->c45_ids.device_ids[MDIO_MMD_PMAPMD] &
 	     MARVELL_PHY_ID_MASK) != MARVELL_PHY_ID_88X3310)
@@ -1297,12 +1299,14 @@ static int mv211x_match_phy_device(struct phy_device *phydev, bool has_5g)
 	return !!(val & MDIO_PCS_SPEED_5G) == has_5g;
 }
 
-static int mv2110_match_phy_device(struct phy_device *phydev)
+static int mv2110_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	return mv211x_match_phy_device(phydev, true);
 }
 
-static int mv2111_match_phy_device(struct phy_device *phydev)
+static int mv2111_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	return mv211x_match_phy_device(phydev, false);
 }
drivers/net/phy/micrel.c +4 -2
index 71fb4410c31b..4d8460c93078 100644
@@ -768,7 +768,8 @@ static int ksz8051_ksz8795_match_phy_device(struct phy_device *phydev,
 		return !ret;
 }
 
-static int ksz8051_match_phy_device(struct phy_device *phydev)
+static int ksz8051_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return ksz8051_ksz8795_match_phy_device(phydev, true);
 }
@@ -888,7 +889,8 @@ static int ksz8061_config_init(struct phy_device *phydev)
 	return kszphy_config_init(phydev);
 }
 
-static int ksz8795_match_phy_device(struct phy_device *phydev)
+static int ksz8795_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return ksz8051_ksz8795_match_phy_device(phydev, false);
 }
drivers/net/phy/nxp-c45-tja11xx.c +8 -4
index f11dd32494c3..22921b192a8b 100644
@@ -1966,25 +1966,29 @@ static int nxp_c45_macsec_ability(struct phy_device *phydev)
 	return macsec_ability;
 }
 
-static int tja1103_match_phy_device(struct phy_device *phydev)
+static int tja1103_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1103, PHY_ID_MASK) &&
 	       !nxp_c45_macsec_ability(phydev);
 }
 
-static int tja1104_match_phy_device(struct phy_device *phydev)
+static int tja1104_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1103, PHY_ID_MASK) &&
 	       nxp_c45_macsec_ability(phydev);
 }
 
-static int tja1120_match_phy_device(struct phy_device *phydev)
+static int tja1120_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1120, PHY_ID_MASK) &&
 	       !nxp_c45_macsec_ability(phydev);
 }
 
-static int tja1121_match_phy_device(struct phy_device *phydev)
+static int tja1121_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1120, PHY_ID_MASK) &&
 	       nxp_c45_macsec_ability(phydev);
drivers/net/phy/nxp-tja11xx.c +4 -2
index 07e94a2478ac..3c38a8ddae2f 100644
@@ -651,12 +651,14 @@ static int tja1102_match_phy_device(struct phy_device *phydev, bool port0)
 	return !ret;
 }
 
-static int tja1102_p0_match_phy_device(struct phy_device *phydev)
+static int tja1102_p0_match_phy_device(struct phy_device *phydev,
+				       const struct phy_driver *phydrv)
 {
 	return tja1102_match_phy_device(phydev, true);
 }
 
-static int tja1102_p1_match_phy_device(struct phy_device *phydev)
+static int tja1102_p1_match_phy_device(struct phy_device *phydev,
+				       const struct phy_driver *phydrv)
 {
 	return tja1102_match_phy_device(phydev, false);
 }
drivers/net/phy/phy_device.c +1 -1
index 2eb735e68dd8..96a96c0334a7 100644
@@ -554,7 +554,7 @@ static int phy_bus_match(struct device *dev, const struct device_driver *drv)
 		return 0;
 
 	if (phydrv->match_phy_device)
-		return phydrv->match_phy_device(phydev);
+		return phydrv->match_phy_device(phydev, phydrv);
 
 	if (phydev->is_c45) {
 		for (i = 1; i < num_ids; i++) {
drivers/net/phy/realtek/realtek_main.c +18 -9
index 301fbe141b9b..6b655d3c7e1c 100644
@@ -1314,13 +1314,15 @@ static bool rtlgen_supports_mmd(struct phy_device *phydev)
 	return val > 0;
 }
 
-static int rtlgen_match_phy_device(struct phy_device *phydev)
+static int rtlgen_match_phy_device(struct phy_device *phydev,
+				   const struct phy_driver *phydrv)
 {
 	return phydev->phy_id == RTL_GENERIC_PHYID &&
 	       !rtlgen_supports_2_5gbps(phydev);
 }
 
-static int rtl8226_match_phy_device(struct phy_device *phydev)
+static int rtl8226_match_phy_device(struct phy_device *phydev,
+				    const struct phy_driver *phydrv)
 {
 	return phydev->phy_id == RTL_GENERIC_PHYID &&
 	       rtlgen_supports_2_5gbps(phydev) &&
@@ -1336,32 +1338,38 @@ static int rtlgen_is_c45_match(struct phy_device *phydev, unsigned int id,
 		return !is_c45 && (id == phydev->phy_id);
 }
 
-static int rtl8221b_match_phy_device(struct phy_device *phydev)
+static int rtl8221b_match_phy_device(struct phy_device *phydev,
+				     const struct phy_driver *phydrv)
 {
 	return phydev->phy_id == RTL_8221B && rtlgen_supports_mmd(phydev);
 }
 
-static int rtl8221b_vb_cg_c22_match_phy_device(struct phy_device *phydev)
+static int rtl8221b_vb_cg_c22_match_phy_device(struct phy_device *phydev,
+					       const struct phy_driver *phydrv)
 {
 	return rtlgen_is_c45_match(phydev, RTL_8221B_VB_CG, false);
 }
 
-static int rtl8221b_vb_cg_c45_match_phy_device(struct phy_device *phydev)
+static int rtl8221b_vb_cg_c45_match_phy_device(struct phy_device *phydev,
+					       const struct phy_driver *phydrv)
 {
 	return rtlgen_is_c45_match(phydev, RTL_8221B_VB_CG, true);
 }
 
-static int rtl8221b_vn_cg_c22_match_phy_device(struct phy_device *phydev)
+static int rtl8221b_vn_cg_c22_match_phy_device(struct phy_device *phydev,
+					       const struct phy_driver *phydrv)
 {
 	return rtlgen_is_c45_match(phydev, RTL_8221B_VN_CG, false);
 }
 
-static int rtl8221b_vn_cg_c45_match_phy_device(struct phy_device *phydev)
+static int rtl8221b_vn_cg_c45_match_phy_device(struct phy_device *phydev,
+					       const struct phy_driver *phydrv)
 {
 	return rtlgen_is_c45_match(phydev, RTL_8221B_VN_CG, true);
 }
 
-static int rtl_internal_nbaset_match_phy_device(struct phy_device *phydev)
+static int rtl_internal_nbaset_match_phy_device(struct phy_device *phydev,
+						const struct phy_driver *phydrv)
 {
 	if (phydev->is_c45)
 		return false;
@@ -1379,7 +1387,8 @@ static int rtl_internal_nbaset_match_phy_device(struct phy_device *phydev)
 	return rtlgen_supports_2_5gbps(phydev) && !rtlgen_supports_mmd(phydev);
 }
 
-static int rtl8251b_c45_match_phy_device(struct phy_device *phydev)
+static int rtl8251b_c45_match_phy_device(struct phy_device *phydev,
+					 const struct phy_driver *phydrv)
 {
 	return rtlgen_is_c45_match(phydev, RTL_8251B, true);
 }
drivers/net/phy/teranetics.c +2 -1
index 752d4bf7bb99..46c5ff7d7b56 100644
@@ -67,7 +67,8 @@ static int teranetics_read_status(struct phy_device *phydev)
 	return 0;
 }
 
-static int teranetics_match_phy_device(struct phy_device *phydev)
+static int teranetics_match_phy_device(struct phy_device *phydev,
+				       const struct phy_driver *phydrv)
 {
 	return phydev->c45_ids.device_ids[3] == PHY_ID_TN2020;
 }
include/linux/phy.h +2 -1
index 7c29d346d4b3..34ed85686b83 100644
@@ -990,7 +990,8 @@ struct phy_driver {
 	 * driver for the given phydev.	 If NULL, matching is based on
 	 * phy_id and phy_id_mask.
 	 */
-	int (*match_phy_device)(struct phy_device *phydev);
+	int (*match_phy_device)(struct phy_device *phydev,
+				const struct phy_driver *phydrv);
 
 	/**
 	 * @set_wol: Some devices (e.g. qnap TS-119P II) require PHY
Signature · 1 line
2.48.1
author maintainer
#2 lore raw

PATCH v10 2/7 net: phy: bcm87xx: simplify .match_phy_device OP

In reply to Christian Marangi

Simplify .match_phy_device OP by using a generic function and using the new phy_id PHY driver info instead of hardcoding the matching PHY ID.

---
 drivers/net/phy/bcm87xx.c | 14 ++++----------
 1 file changed, 4 insertions(+), 10 deletions(-)
drivers/net/phy/bcm87xx.c +4 -10
index 1e1e2259fc2b..299f9a8f30f4 100644
@@ -185,16 +185,10 @@ static irqreturn_t bcm87xx_handle_interrupt(struct phy_device *phydev)
 	return IRQ_HANDLED;
 }
 
-static int bcm8706_match_phy_device(struct phy_device *phydev,
+static int bcm87xx_match_phy_device(struct phy_device *phydev,
 				    const struct phy_driver *phydrv)
 {
-	return phydev->c45_ids.device_ids[4] == PHY_ID_BCM8706;
-}
-
-static int bcm8727_match_phy_device(struct phy_device *phydev,
-				    const struct phy_driver *phydrv)
-{
-	return phydev->c45_ids.device_ids[4] == PHY_ID_BCM8727;
+	return phydev->c45_ids.device_ids[4] == phydrv->phy_id;
 }
 
 static struct phy_driver bcm87xx_driver[] = {
@@ -208,7 +202,7 @@ static struct phy_driver bcm87xx_driver[] = {
 	.read_status	= bcm87xx_read_status,
 	.config_intr	= bcm87xx_config_intr,
 	.handle_interrupt = bcm87xx_handle_interrupt,
-	.match_phy_device = bcm8706_match_phy_device,
+	.match_phy_device = bcm87xx_match_phy_device,
 }, {
 	.phy_id		= PHY_ID_BCM8727,
 	.phy_id_mask	= 0xffffffff,
@@ -219,7 +213,7 @@ static struct phy_driver bcm87xx_driver[] = {
 	.read_status	= bcm87xx_read_status,
 	.config_intr	= bcm87xx_config_intr,
 	.handle_interrupt = bcm87xx_handle_interrupt,
-	.match_phy_device = bcm8727_match_phy_device,
+	.match_phy_device = bcm87xx_match_phy_device,
 } };
 
 module_phy_driver(bcm87xx_driver);
Signature · 1 line
2.48.1
author maintainer
#3 lore raw

PATCH v10 3/7 net: phy: nxp-c45-tja11xx: simplify .match_phy_device OP

In reply to Christian Marangi

Simplify .match_phy_device OP by using a generic function and using the new phy_id PHY driver info instead of hardcoding the matching PHY ID with new variant for macsec and no_macsec PHYs.

Also make use of PHY_ID_MATCH_MODEL macro and drop PHY_ID_MASK define to introduce phy_id and phy_id_mask again in phy_driver struct.

---
 drivers/net/phy/nxp-c45-tja11xx.c | 45 ++++++++++++++-----------------
 1 file changed, 20 insertions(+), 25 deletions(-)
drivers/net/phy/nxp-c45-tja11xx.c +20 -25
index 22921b192a8b..4c6d905f0a9f 100644
@@ -19,7 +19,6 @@
 
 #include "nxp-c45-tja11xx.h"
 
-#define PHY_ID_MASK			GENMASK(31, 4)
 /* Same id: TJA1103, TJA1104 */
 #define PHY_ID_TJA_1103			0x001BB010
 /* Same id: TJA1120, TJA1121 */
@@ -1966,32 +1965,24 @@ static int nxp_c45_macsec_ability(struct phy_device *phydev)
 	return macsec_ability;
 }
 
-static int tja1103_match_phy_device(struct phy_device *phydev,
-				    const struct phy_driver *phydrv)
+static int tja11xx_no_macsec_match_phy_device(struct phy_device *phydev,
+					      const struct phy_driver *phydrv)
 {
-	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1103, PHY_ID_MASK) &&
-	       !nxp_c45_macsec_ability(phydev);
-}
+	if (!phy_id_compare(phydev->phy_id, phydrv->phy_id,
+			    phydrv->phy_id_mask))
+		return 0;
 
-static int tja1104_match_phy_device(struct phy_device *phydev,
-				    const struct phy_driver *phydrv)
-{
-	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1103, PHY_ID_MASK) &&
-	       nxp_c45_macsec_ability(phydev);
+	return !nxp_c45_macsec_ability(phydev);
 }
 
-static int tja1120_match_phy_device(struct phy_device *phydev,
-				    const struct phy_driver *phydrv)
+static int tja11xx_macsec_match_phy_device(struct phy_device *phydev,
+					   const struct phy_driver *phydrv)
 {
-	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1120, PHY_ID_MASK) &&
-	       !nxp_c45_macsec_ability(phydev);
-}
+	if (!phy_id_compare(phydev->phy_id, phydrv->phy_id,
+			    phydrv->phy_id_mask))
+		return 0;
 
-static int tja1121_match_phy_device(struct phy_device *phydev,
-				    const struct phy_driver *phydrv)
-{
-	return phy_id_compare(phydev->phy_id, PHY_ID_TJA_1120, PHY_ID_MASK) &&
-	       nxp_c45_macsec_ability(phydev);
+	return nxp_c45_macsec_ability(phydev);
 }
 
 static const struct nxp_c45_regmap tja1120_regmap = {
@@ -2064,6 +2055,7 @@ static const struct nxp_c45_phy_data tja1120_phy_data = {
 
 static struct phy_driver nxp_c45_driver[] = {
 	{
+		PHY_ID_MATCH_MODEL(PHY_ID_TJA_1103),
 		.name			= "NXP C45 TJA1103",
 		.get_features		= nxp_c45_get_features,
 		.driver_data		= &tja1103_phy_data,
@@ -2085,9 +2077,10 @@ static struct phy_driver nxp_c45_driver[] = {
 		.get_sqi		= nxp_c45_get_sqi,
 		.get_sqi_max		= nxp_c45_get_sqi_max,
 		.remove			= nxp_c45_remove,
-		.match_phy_device	= tja1103_match_phy_device,
+		.match_phy_device	= tja11xx_no_macsec_match_phy_device,
 	},
 	{
+		PHY_ID_MATCH_MODEL(PHY_ID_TJA_1103),
 		.name			= "NXP C45 TJA1104",
 		.get_features		= nxp_c45_get_features,
 		.driver_data		= &tja1103_phy_data,
@@ -2109,9 +2102,10 @@ static struct phy_driver nxp_c45_driver[] = {
 		.get_sqi		= nxp_c45_get_sqi,
 		.get_sqi_max		= nxp_c45_get_sqi_max,
 		.remove			= nxp_c45_remove,
-		.match_phy_device	= tja1104_match_phy_device,
+		.match_phy_device	= tja11xx_macsec_match_phy_device,
 	},
 	{
+		PHY_ID_MATCH_MODEL(PHY_ID_TJA_1120),
 		.name			= "NXP C45 TJA1120",
 		.get_features		= nxp_c45_get_features,
 		.driver_data		= &tja1120_phy_data,
@@ -2134,9 +2128,10 @@ static struct phy_driver nxp_c45_driver[] = {
 		.get_sqi		= nxp_c45_get_sqi,
 		.get_sqi_max		= nxp_c45_get_sqi_max,
 		.remove			= nxp_c45_remove,
-		.match_phy_device	= tja1120_match_phy_device,
+		.match_phy_device	= tja11xx_no_macsec_match_phy_device,
 	},
 	{
+		PHY_ID_MATCH_MODEL(PHY_ID_TJA_1120),
 		.name			= "NXP C45 TJA1121",
 		.get_features		= nxp_c45_get_features,
 		.driver_data		= &tja1120_phy_data,
@@ -2159,7 +2154,7 @@ static struct phy_driver nxp_c45_driver[] = {
 		.get_sqi		= nxp_c45_get_sqi,
 		.get_sqi_max		= nxp_c45_get_sqi_max,
 		.remove			= nxp_c45_remove,
-		.match_phy_device	= tja1121_match_phy_device,
+		.match_phy_device	= tja11xx_macsec_match_phy_device,
 	},
 };
 
Signature · 1 line
2.48.1
author maintainer
#4 lore raw

PATCH v10 4/7 net: phy: introduce genphy_match_phy_device()

In reply to Christian Marangi

Introduce new API, genphy_match_phy_device(), to provide a way to check to match a PHY driver for a PHY device based on the info stored in the PHY device struct.

The function generalize the logic used in phy_bus_match() to check the PHY ID whether if C45 or C22 ID should be used for matching.

This is useful for custom .match_phy_device function that wants to use the generic logic under some condition. (example a PHY is already setup and provide the correct PHY ID)

---
 drivers/net/phy/phy_device.c | 52 +++++++++++++++++++++++++-----------
 include/linux/phy.h          |  3 +++
 2 files changed, 40 insertions(+), 15 deletions(-)
drivers/net/phy/phy_device.c +37 -15
index 96a96c0334a7..9282de0d591e 100644
@@ -543,20 +543,26 @@ static int phy_scan_fixups(struct phy_device *phydev)
 	return 0;
 }
 
-static int phy_bus_match(struct device *dev, const struct device_driver *drv)
+/**
+ * genphy_match_phy_device - match a PHY device with a PHY driver
+ * @phydev: target phy_device struct
+ * @phydrv: target phy_driver struct
+ *
+ * Description: Checks whether the given PHY device matches the specified
+ * PHY driver. For Clause 45 PHYs, iterates over the available device
+ * identifiers and compares them against the driver's expected PHY ID,
+ * applying the provided mask. For Clause 22 PHYs, a direct ID comparison
+ * is performed.
+ *
+ * Return: 1 if the PHY device matches the driver, 0 otherwise.
+ */
+int genphy_match_phy_device(struct phy_device *phydev,
+			    const struct phy_driver *phydrv)
 {
-	struct phy_device *phydev = to_phy_device(dev);
-	const struct phy_driver *phydrv = to_phy_driver(drv);
-	const int num_ids = ARRAY_SIZE(phydev->c45_ids.device_ids);
-	int i;
-
-	if (!(phydrv->mdiodrv.flags & MDIO_DEVICE_IS_PHY))
-		return 0;
-
-	if (phydrv->match_phy_device)
-		return phydrv->match_phy_device(phydev, phydrv);
-
 	if (phydev->is_c45) {
+		const int num_ids = ARRAY_SIZE(phydev->c45_ids.device_ids);
+		int i;
+
 		for (i = 1; i < num_ids; i++) {
 			if (phydev->c45_ids.device_ids[i] == 0xffffffff)
 				continue;
@@ -565,11 +571,27 @@ static int phy_bus_match(struct device *dev, const struct device_driver *drv)
 					   phydrv->phy_id, phydrv->phy_id_mask))
 				return 1;
 		}
+
 		return 0;
-	} else {
-		return phy_id_compare(phydev->phy_id, phydrv->phy_id,
-				      phydrv->phy_id_mask);
 	}
+
+	return phy_id_compare(phydev->phy_id, phydrv->phy_id,
+			      phydrv->phy_id_mask);
+}
+EXPORT_SYMBOL_GPL(genphy_match_phy_device);
+
+static int phy_bus_match(struct device *dev, const struct device_driver *drv)
+{
+	struct phy_device *phydev = to_phy_device(dev);
+	const struct phy_driver *phydrv = to_phy_driver(drv);
+
+	if (!(phydrv->mdiodrv.flags & MDIO_DEVICE_IS_PHY))
+		return 0;
+
+	if (phydrv->match_phy_device)
+		return phydrv->match_phy_device(phydev, phydrv);
+
+	return genphy_match_phy_device(phydev, phydrv);
 }
 
 static ssize_t
include/linux/phy.h +3 -0
index 34ed85686b83..48e80f089b17 100644
@@ -1868,6 +1868,9 @@ char *phy_attached_info_irq(struct phy_device *phydev)
 	__malloc;
 void phy_attached_info(struct phy_device *phydev);
 
+int genphy_match_phy_device(struct phy_device *phydev,
+			    const struct phy_driver *phydrv);
+
 /* Clause 22 PHY */
 int genphy_read_abilities(struct phy_device *phydev);
 int genphy_setup_forced(struct phy_device *phydev);
Signature · 1 line
2.48.1
author maintainer
#5 lore raw

PATCH v10 5/7 net: phy: Add support for Aeonsemi AS21xxx PHYs

In reply to Christian Marangi

Add support for Aeonsemi AS21xxx 10G C45 PHYs. These PHYs integrate an IPC to setup some configuration and require special handling to sync with the parity bit. The parity bit is a way the IPC use to follow correct order of command sent.

Supported PHYs AS21011JB1, AS21011PB1, AS21010JB1, AS21010PB1, AS21511JB1, AS21511PB1, AS21510JB1, AS21510PB1, AS21210JB1, AS21210PB1 that all register with the PHY ID 0x7500 0x7510 before the firmware is loaded.

They all support up to 5 LEDs with various HW mode supported.

While implementing it was found some strange coincidence with using the same logic for implementing C22 in MMD regs in Broadcom PHYs.

For reference here the AS21xxx PHY name logic:

AS21x1xxB1
^ ^^
| |J: Supports SyncE/PTP
| |P: No SyncE/PTP support
| 1: Supports 2nd Serdes
| 2: Not 2nd Serdes support
0: 10G, 5G, 2.5G
5: 5G, 2.5G
2: 2.5G

---
 MAINTAINERS               |    6 +
 drivers/net/phy/Kconfig   |   12 +
 drivers/net/phy/Makefile  |    1 +
 drivers/net/phy/as21xxx.c | 1087 +++++++++++++++++++++++++++++++++++++
 4 files changed, 1106 insertions(+)
 create mode 100644 drivers/net/phy/as21xxx.c
MAINTAINERS +6 -0
index 800d23264c94..6cc52e99c1f8 100644
@@ -646,6 +646,12 @@ F:	drivers/iio/accel/adxl380.h
 F:	drivers/iio/accel/adxl380_i2c.c
 F:	drivers/iio/accel/adxl380_spi.c
 
+AEONSEMI PHY DRIVER
+M:	Christian Marangi <[email protected]>
+L:	[email protected]
+S:	Maintained
+F:	drivers/net/phy/as21xxx.c
+
 AF8133J THREE-AXIS MAGNETOMETER DRIVER
 M:	Ondřej Jirman <[email protected]>
 S:	Maintained
drivers/net/phy/Kconfig +12 -0
index 677d56e06539..895f92ccfe1f 100644
@@ -76,6 +76,18 @@ config SFP
 
 comment "MII PHY device drivers"
 
+config AS21XXX_PHY
+	tristate "Aeonsemi AS21xxx PHYs"
+	help
+	  Currently supports the Aeonsemi AS21xxx PHY.
+
+	  These are C45 PHYs 10G that require all a generic firmware.
+
+	  Supported PHYs AS21011JB1, AS21011PB1, AS21010JB1, AS21010PB1,
+	  AS21511JB1, AS21511PB1, AS21510JB1, AS21510PB1, AS21210JB1,
+	  AS21210PB1 that all register with the PHY ID 0x7500 0x7500
+	  before the firmware is loaded.
+
 config AIR_EN8811H_PHY
 	tristate "Airoha EN8811H 2.5 Gigabit PHY"
 	help
drivers/net/phy/Makefile +1 -0
index 59ac3a9a3177..42f215905a29 100644
@@ -40,6 +40,7 @@ obj-$(CONFIG_AIR_EN8811H_PHY)   += air_en8811h.o
 obj-$(CONFIG_AMD_PHY)		+= amd.o
 obj-$(CONFIG_AMCC_QT2025_PHY)	+= qt2025.o
 obj-$(CONFIG_AQUANTIA_PHY)	+= aquantia/
+obj-$(CONFIG_AS21XXX_PHY)	+= as21xxx.o
 ifdef CONFIG_AX88796B_RUST_PHY
   obj-$(CONFIG_AX88796B_PHY)	+= ax88796b_rust.o
 else
drivers/net/phy/as21xxx.c new file +1087 -0

1,087 lines not on this page · raw message

Signature · 1 line
2.48.1
author maintainer
#6 lore raw

PATCH v10 6/7 dt-bindings: net: Document support for Aeonsemi PHYs

In reply to Christian Marangi

Add Aeonsemi PHYs and the requirement of a firmware to correctly work. Also document the max number of LEDs supported and what PHY ID expose when no firmware is loaded.

Supported PHYs AS21011JB1, AS21011PB1, AS21010JB1, AS21010PB1, AS21511JB1, AS21511PB1, AS21510JB1, AS21510PB1, AS21210JB1, AS21210PB1 that all register with the PHY ID 0x7500 0x9410 on C45 registers before the firmware is loaded.

---
 .../bindings/net/aeonsemi,as21xxx.yaml        | 122 ++++++++++++++++++
 MAINTAINERS                                   |   1 +
 2 files changed, 123 insertions(+)
 create mode 100644 Documentation/devicetree/bindings/net/aeonsemi,as21xxx.yaml
Documentation/devicetree/bindings/net/aeonsemi,as21xxx.yaml new file +122 -0
new file mode 100644
index 000000000000..69eb29dc4d7b
@@ -0,0 +1,122 @@
+# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/net/aeonsemi,as21xxx.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: Aeonsemi AS21XXX Ethernet PHY
+
+maintainers:
+  - Christian Marangi <[email protected]>
+
+description: |
+  Aeonsemi AS21xxx Ethernet PHYs requires a firmware to be loaded to actually
+  work. The same firmware is compatible with various PHYs of the same family.
+
+  A PHY with not firmware loaded will be exposed on the MDIO bus with ID
+  0x7500 0x7500 or 0x7500 0x9410 on C45 registers.
+
+  This can be done and is implemented by OEM in 2 different way:
+    - Attached SPI flash directly to the PHY with the firmware. The PHY
+      will self load the firmware in the presence of this configuration.
+    - Manually provided firmware loaded from a file in the filesystem.
+
+  Each PHY can support up to 5 LEDs.
+
+  AS2xxx PHY Name logic:
+
+  AS21x1xxB1
+      ^ ^^
+      | |J: Supports SyncE/PTP
+      | |P: No SyncE/PTP support
+      | 1: Supports 2nd Serdes
+      | 2: Not 2nd Serdes support
+      0: 10G, 5G, 2.5G
+      5: 5G, 2.5G
+      2: 2.5G
+
+allOf:
+  - $ref: ethernet-phy.yaml#
+
+select:
+  properties:
+    compatible:
+      contains:
+        enum:
+          - ethernet-phy-id7500.9410
+          - ethernet-phy-id7500.9402
+          - ethernet-phy-id7500.9412
+          - ethernet-phy-id7500.9422
+          - ethernet-phy-id7500.9432
+          - ethernet-phy-id7500.9442
+          - ethernet-phy-id7500.9452
+          - ethernet-phy-id7500.9462
+          - ethernet-phy-id7500.9472
+          - ethernet-phy-id7500.9482
+          - ethernet-phy-id7500.9492
+  required:
+    - compatible
+
+properties:
+  reg:
+    maxItems: 1
+
+  firmware-name:
+    description: specify the name of PHY firmware to load
+    maxItems: 1
+
+required:
+  - compatible
+  - reg
+
+if:
+  properties:
+    compatible:
+      contains:
+        const: ethernet-phy-id7500.9410
+then:
+  required:
+    - firmware-name
+else:
+  properties:
+    firmware-name: false
+
+unevaluatedProperties: false
+
+examples:
+  - |
+    #include <dt-bindings/leds/common.h>
+
+    mdio {
+        #address-cells = <1>;
+        #size-cells = <0>;
+
+        ethernet-phy@1f {
+            compatible = "ethernet-phy-id7500.9410",
+                         "ethernet-phy-ieee802.3-c45";
+
+            reg = <31>;
+            firmware-name = "as21x1x_fw.bin";
+
+            leds {
+                #address-cells = <1>;
+                #size-cells = <0>;
+
+                led@0 {
+                    reg = <0>;
+                    color = <LED_COLOR_ID_GREEN>;
+                    function = LED_FUNCTION_LAN;
+                    function-enumerator = <0>;
+                    default-state = "keep";
+                };
+
+                led@1 {
+                    reg = <1>;
+                    color = <LED_COLOR_ID_GREEN>;
+                    function = LED_FUNCTION_LAN;
+                    function-enumerator = <1>;
+                    default-state = "keep";
+                };
+            };
+        };
+    };
MAINTAINERS +1 -0
index 6cc52e99c1f8..d11038a90113 100644
@@ -650,6 +650,7 @@ AEONSEMI PHY DRIVER
 M:	Christian Marangi <[email protected]>
 L:	[email protected]
 S:	Maintained
+F:	Documentation/devicetree/bindings/net/aeonsemi,as21xxx.yaml
 F:	drivers/net/phy/as21xxx.c
 
 AF8133J THREE-AXIS MAGNETOMETER DRIVER
Signature · 1 line
2.48.1
author maintainer
#7 lore raw

PATCH v10 7/7 rust: net::phy sync with match_phy_device C changes

In reply to Christian Marangi

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
rust/kernel/net/phy.rs +23 -3
index a59469c785e3..936a137a8a29 100644
@@ -418,15 +418,18 @@ impl<T: Driver> Adapter<T> {
 
     /// # Safety
     ///
-    /// `phydev` must be passed by the corresponding callback in `phy_driver`.
+    /// `phydev` and `phydrv` must be passed by the corresponding callback in
+    //  `phy_driver`.
     unsafe extern "C" fn match_phy_device_callback(
         phydev: *mut bindings::phy_device,
+        phydrv: *const bindings::phy_driver
     ) -> crate::ffi::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.
         let dev = unsafe { Device::from_raw(phydev) };
-        T::match_phy_device(dev) as i32
+        let drv = unsafe { T::from_raw(phydrv) };
+        T::match_phy_device(dev, drv) as i32
     }
 
     /// # Safety
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
+        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 { &*ptr }
+    }
+
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }
 
Signature · 1 line
2.48.1
reviewer
#8 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 11 lines · Christian Marangi

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

You probably should do this in the same commit as the C changes, otherwise the in-between commits will error.

---
Cheers,
Benno

author maintainer
#9 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 8 lines · Benno Lossin
Quoted 7 lines · Christian Marangi

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

Quoted 8 lines
Quoted 4 lines
---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

You probably should do this in the same commit as the C changes, otherwise the in-between commits will error.

You are right, I will fix this in v11 but I would really want to know if the Rust changes are correct. It's not my main language so it's all discovering new stuff :D

Signature · 1 line
	Ansuel
reviewer
#10 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 14 lines · Christian Marangi
Quoted 13 lines · Benno Lossin
Quoted 11 lines · Christian Marangi

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
Quoted 7 lines
Quoted 3 lines

You probably should do this in the same commit as the C changes, otherwise the in-between commits will error.

You are right, I will fix this in v11 but I would really want to know if the Rust changes are correct. It's not my main language so it's all discovering new stuff :D

No worries :) I have lost some context on the PHY Rust bindings, so Fujita will probably have to review it, but if I find the time, I'll take a look.

---
Cheers,
Benno

#11 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

In reply to Christian Marangi
kernel test robot noticed the following build errors:

Hi Christian,

kernel test robot noticed the following build errors:

[auto build test ERROR on net-next/main]

url:    https://github.com/intel-lab-lkp/linux/commits/Christian-Marangi/net-phy-pass-PHY-driver-to-match_phy_device-OP/20250515-193151
base:   net-next/main
patch link:    https://lore.kernel.org/r/20250515112721.19323-8-ansuelsmth%40gmail.com
patch subject: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20250516/[email protected]/config)
compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff)
rustc: rustc 1.78.0 (9b00956e5 2024-04-29)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250516/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

PATH=/opt/cross/clang-18/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
INFO PATH=/opt/cross/rustc-1.78.0-bindgen-0.65.1/cargo/bin:/opt/cross/clang-18/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
/usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
make: Entering directory '/kbuild/src/consumer'
make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'

>> Diff in rust/kernel/net/phy.rs at line 422:
        //  `phy_driver`.
        unsafe extern "C" fn match_phy_device_callback(
            phydev: *mut bindings::phy_device,
   -        phydrv: *const bindings::phy_driver
   +        phydrv: *const bindings::phy_driver,
        ) -> crate::ffi::c_int {
            // SAFETY: This callback is called only in contexts
            // where we hold `phy_device->lock`, so the accessors on
>> Diff in rust/kernel/net/phy.rs at line 422:
        //  `phy_driver`.
        unsafe extern "C" fn match_phy_device_callback(
            phydev: *mut bindings::phy_device,
   -        phydrv: *const bindings::phy_driver
   +        phydrv: *const bindings::phy_driver,
        ) -> crate::ffi::c_int {
            // SAFETY: This callback is called only in contexts
            // where we hold `phy_device->lock`, so the accessors on
>> Diff in rust/kernel/net/phy.rs at line 422:
        //  `phy_driver`.
        unsafe extern "C" fn match_phy_device_callback(
            phydev: *mut bindings::phy_device,
   -        phydrv: *const bindings::phy_driver
   +        phydrv: *const bindings::phy_driver,
        ) -> crate::ffi::c_int {
            // SAFETY: This callback is called only in contexts
            // where we hold `phy_device->lock`, so the accessors on

make[2]: *** [Makefile:1826: rustfmt] Error 123
make[2]: Target 'rustfmtcheck' not remade because of errors. make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust' make[1]: *** [Makefile:248: __sub-make] Error 2
make[1]: Target 'rustfmtcheck' not remade because of errors.
make: *** [Makefile:248: __sub-make] Error 2
make: Target 'rustfmtcheck' not remade because of errors.
make: Leaving directory '/kbuild/src/consumer'

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
maintainer
#12 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

In reply to Christian Marangi

Hi,

Quoted 47 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
rust/kernel/net/phy.rs +11 -2
index a59469c785e3..936a137a8a29 100644
@@ -418,15 +418,18 @@ impl<T: Driver> Adapter<T> {
 
     /// # Safety
     ///
-    /// `phydev` must be passed by the corresponding callback in `phy_driver`.
+    /// `phydev` and `phydrv` must be passed by the corresponding callback in
+    //  `phy_driver`.
     unsafe extern "C" fn match_phy_device_callback(
         phydev: *mut bindings::phy_device,
+        phydrv: *const bindings::phy_driver
     ) -> crate::ffi::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.
         let dev = unsafe { Device::from_raw(phydev) };
-        T::match_phy_device(dev) as i32
+        let drv = unsafe { T::from_raw(phydrv) };
+        T::match_phy_device(dev, drv) as i32
     }
 
     /// # Safety
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 10 lines
rust/kernel/net/phy.rs +10 -0
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

rust/kernel/net/phy.rs fn get_features(_dev: &mut Device) -> Result { · line 627

Quoted 11 lines
rust/kernel/net/phy.rs +1 -1
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }

I think that it could be a bit simpler:

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

Or making it a trait method might be more idiomatic?

fn match_phy_device(&self, _dev: &mut Device) -> bool

Thanks!

reviewer
#13 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 17 lines · FUJITA Tomonori
Quoted 15 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…
rust/kernel/net/phy.rs +11 -0
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
Quoted 8 lines

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 5 lines
rust/kernel/net/phy.rs +5 -0
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Why is any type implementing Driver a transparent wrapper around bindings::phy_driver?

Quoted 14 lines

rust/kernel/net/phy.rs fn get_features(_dev: &mut Device) -> Result { · line 627

Quoted 11 lines
rust/kernel/net/phy.rs +1 -1
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }

I think that it could be a bit simpler:

Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

Or making it a trait method might be more idiomatic?

fn match_phy_device(&self, _dev: &mut Device) -> bool

Yeah that would make most sense.

---
Cheers,
Benno

author maintainer
#14 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 27 lines · Benno Lossin
Quoted 17 lines · FUJITA Tomonori
Quoted 15 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…
rust/kernel/net/phy.rs +11 -0
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
Quoted 8 lines

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 5 lines
rust/kernel/net/phy.rs +5 -0
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Quoted 3 lines

Why is any type implementing Driver a transparent wrapper around bindings::phy_driver?

Is this referred to a problem with using from_raw or more of a general question on how the rust wrapper are done for phy code?

Quoted 14 lines
Quoted 14 lines

rust/kernel/net/phy.rs fn get_features(_dev: &mut Device) -> Result { · line 627

Quoted 11 lines
rust/kernel/net/phy.rs +1 -1
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }

I think that it could be a bit simpler:

Quoted 8 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

Or making it a trait method might be more idiomatic?

fn match_phy_device(&self, _dev: &mut Device) -> bool

Yeah that would make most sense.

I think

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

more resemble the C parallel function so I think this suite the best, should make it easier to port if ever (am I wrong?)

Signature · 1 line
	Ansuel
reviewer
#15 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 28 lines · Christian Marangi
Quoted 27 lines · Benno Lossin
Quoted 25 lines · FUJITA Tomonori
Quoted 10 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…
rust/kernel/net/phy.rs +6 -0
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 10 lines
rust/kernel/net/phy.rs +10 -0
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Quoted 6 lines
Quoted 3 lines

Why is any type implementing Driver a transparent wrapper around bindings::phy_driver?

Is this referred to a problem with using from_raw or more of a general question on how the rust wrapper are done for phy code?

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Quoted 23 lines
Quoted 14 lines
Quoted 14 lines

rust/kernel/net/phy.rs fn get_features(_dev: &mut Device) -> Result { · line 627

Quoted 11 lines
rust/kernel/net/phy.rs +1 -1
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }

I think that it could be a bit simpler:

Quoted 8 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

Or making it a trait method might be more idiomatic?

fn match_phy_device(&self, _dev: &mut Device) -> bool

Yeah that would make most sense.

Quoted 6 lines

I think

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

more resemble the C parallel function so I think this suite the best, should make it easier to port if ever (am I wrong?)

I don't understand what you mean by "easier to port if ever". From a Rust perspective, it makes much more sense to use the &self receiver, since the driver is asked if it can take care of the device. If you want to keep the order how it is in C that is also fine, but if I were to write it, I'd use the receiver.

---
Cheers,
Benno

maintainer
#16 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Thanks for the review!

Quoted 36 lines · On Fri, 16 May 2025 22:16:23 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 28 lines · Christian Marangi
Quoted 27 lines · Benno Lossin
Quoted 25 lines · FUJITA Tomonori
Quoted 10 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…
rust/kernel/net/phy.rs +6 -0
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 10 lines
rust/kernel/net/phy.rs +10 -0
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Quoted 6 lines
Quoted 3 lines

Why is any type implementing Driver a transparent wrapper around bindings::phy_driver?

Is this referred to a problem with using from_raw or more of a general question on how the rust wrapper are done for phy code?

Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

reviewer
#17 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 51 lines · FUJITA Tomonori
Quoted 36 lines · On Fri, 16 May 2025 22:16:23 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 28 lines · Christian Marangi
Quoted 27 lines · Benno Lossin
Quoted 25 lines · FUJITA Tomonori
Quoted 10 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…
rust/kernel/net/phy.rs +6 -0
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 10 lines
rust/kernel/net/phy.rs +10 -0
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Quoted 6 lines
Quoted 3 lines

Why is any type implementing Driver a transparent wrapper around bindings::phy_driver?

Is this referred to a problem with using from_raw or more of a general question on how the rust wrapper are done for phy code?

Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

Yeah, but we could add accessor functions that provide that information. Although that doesn't really make sense at the moment, see below.

Quoted 4 lines

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

---
Cheers,
Benno

maintainer
#18 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 13 lines · On Sat, 17 May 2025 10:06:13 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 13 lines
Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

Quoted 7 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

Yeah, but we could add accessor functions that provide that information.

Yes. I thought that implementation was one of the options as well but realized it makes sense because inside match_phy_device() callback, a driver might call a helper function that takes a pointer to bindings::phy_driver (please see below for details).

Quoted 7 lines

Although that doesn't really make sense at the moment, see below.

Quoted 4 lines

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

#[vtable]

impl Driver for PhyA {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyB {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyC {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Then a driver could do something like 5th patch in the patchset:

#[vtable]

impl Driver for PhyD {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
       let val = dev.genphy_match_phy_device(drv);
       ...
    }
}
reviewer
#19 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 44 lines · FUJITA Tomonori
Quoted 13 lines · On Sat, 17 May 2025 10:06:13 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 13 lines
Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

Quoted 7 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

Yeah, but we could add accessor functions that provide that information.

Yes. I thought that implementation was one of the options as well but realized it makes sense because inside match_phy_device() callback, a driver might call a helper function that takes a pointer to bindings::phy_driver (please see below for details).

Quoted 7 lines

Although that doesn't really make sense at the moment, see below.

Quoted 4 lines

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

Quoted 7 lines

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

I wouldn't do it like this in Rust, instead this would be a "rustier" function signature:

    fn match_device_id<T: Driver>(dev: &mut phy::Device) -> bool {
        // do the comparison with T::PHY_DEVICE_ID
        dev.id() == T::PHY_DEVICE_ID
    }

And then in the impls for Phy{A,B,C,D} do this:

    impl Driver for PhyA {
        fn match_phy_device(dev: &mut phy::Device) -> bool {
            match_device_id::<Self>(dev)
        }
    }
Quoted 30 lines

#[vtable]

impl Driver for PhyA {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyB {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyC {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

Quoted 8 lines

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a function as well (though I wouldn't use the vtable for that).

---
Cheers,
Benno

Quoted 10 lines

Then a driver could do something like 5th patch in the patchset:

#[vtable]

impl Driver for PhyD {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
       let val = dev.genphy_match_phy_device(drv);
       ...
    }
}
author maintainer
#20 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 61 lines · Benno Lossin
Quoted 44 lines · FUJITA Tomonori
Quoted 13 lines · On Sat, 17 May 2025 10:06:13 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 13 lines
Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

Quoted 7 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

Yeah, but we could add accessor functions that provide that information.

Yes. I thought that implementation was one of the options as well but realized it makes sense because inside match_phy_device() callback, a driver might call a helper function that takes a pointer to bindings::phy_driver (please see below for details).

Quoted 7 lines

Although that doesn't really make sense at the moment, see below.

Quoted 4 lines

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

Quoted 7 lines

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

I wouldn't do it like this in Rust, instead this would be a "rustier" function signature:

    fn match_device_id<T: Driver>(dev: &mut phy::Device) -> bool {
        // do the comparison with T::PHY_DEVICE_ID
        dev.id() == T::PHY_DEVICE_ID
    }
Quoted 8 lines

And then in the impls for Phy{A,B,C,D} do this:

    impl Driver for PhyA {
        fn match_phy_device(dev: &mut phy::Device) -> bool {
            match_device_id::<Self>(dev)
        }
    }

My 2 cent about the discussion and I'm totally detached from how it works on Rust kernel code but shouldn't we try to keep parallel API and args between C and Rust?

I know maybe some thing doesn't make sense from C to Rust but doesn't deviates from C code introduce more confusion when something need to be ported from C to Rust?

Again no idea if this apply so I'm just curious about this.

Quoted 33 lines
Quoted 33 lines

#[vtable]

impl Driver for PhyA {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyB {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

#[vtable]

impl Driver for PhyC {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
        match_device_id(dev, drv)
    }
}

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 9 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a function as well (though I wouldn't use the vtable for that).

Mhh looking at some comments, maybe the module needs some extra love here and there.

Quoted 12 lines
Quoted 11 lines

Then a driver could do something like 5th patch in the patchset:

#[vtable]

impl Driver for PhyD {
    ...
    fn match_phy_device(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
       let val = dev.genphy_match_phy_device(drv);
       ...
    }
}
Signature · 1 line
	Ansuel
reviewer
#21 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 71 lines · Christian Marangi
Quoted 61 lines · Benno Lossin
Quoted 44 lines · FUJITA Tomonori
Quoted 13 lines · On Sat, 17 May 2025 10:06:13 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 13 lines
Quoted 6 lines

I looked at the phy.rs file again and now I'm pretty sure the above code is wrong. Self can be implemented on any type (even types like Infallible that do not have any valid bit patterns, since it's an empty enum). The abstraction for bindings::phy_driver is DriverVTable not an object of type Self, so you should cast to that pointer instead.

Yeah.

I don't want to delay this patchset due to Rust side changes so casting a pointer to bindings::phy_driver to DriverVTable is ok but the following signature doesn't look useful for Rust phy drivers:

Quoted 7 lines
Quoted 5 lines

fn match_phy_device(_dev: &mut Device, _drv: &DriverVTable) -> bool

struct DriverVTable is only used to create an array of bindings::phy_driver for C side, and it doesn't provide any information to the Rust driver.

Yeah, but we could add accessor functions that provide that information.

Yes. I thought that implementation was one of the options as well but realized it makes sense because inside match_phy_device() callback, a driver might call a helper function that takes a pointer to bindings::phy_driver (please see below for details).

Quoted 7 lines

Although that doesn't really make sense at the moment, see below.

Quoted 4 lines

In match_phy_device(), for example, a device driver accesses to PHY_DEVICE_ID, which the Driver trait provides. I think we need to create an instance of the device driver's own type that implements the Driver trait and make it accessible.

Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

Quoted 7 lines

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

I wouldn't do it like this in Rust, instead this would be a "rustier" function signature:

    fn match_device_id<T: Driver>(dev: &mut phy::Device) -> bool {
        // do the comparison with T::PHY_DEVICE_ID
        dev.id() == T::PHY_DEVICE_ID
    }
Quoted 8 lines

And then in the impls for Phy{A,B,C,D} do this:

    impl Driver for PhyA {
        fn match_phy_device(dev: &mut phy::Device) -> bool {
            match_device_id::<Self>(dev)
        }
    }
Quoted 3 lines

My 2 cent about the discussion and I'm totally detached from how it works on Rust kernel code but shouldn't we try to keep parallel API and args between C and Rust?

It depends :) There are several things to consider in this from safety to ease of use. Sometimes we diverge from the C implementation, because it makes it safe. For example, from the very beginning, mutexes in Rust have used guards, but those have only been recently-ish introduced in C. Mutexes in Rust also store the value inside of them, making it impossible to access the inner value without taking the lock. This makes the API safer, but diverges from C.

Now in this case, we're talking about making an API more rusty and thus diverging from the C side. One can argue for either side and we have to strike a balance, but in the end it'll probably be up to each subsystem how they will handle it. It's not as big of an argument as safety (which we strive very hard for).

In this concrete case, a DriverVTable is just an adapter type that we use to make a trait in Rust be compatible with a C vtable. From Rusts perspective, the single origin of truth is the trait and the vtable is derived from that. So from a Rust perspective it's much more natural to use the trait than the vtable. (This might also end up being more performant, since we statically know which ID the driver supports and the C side needs to dynamically look it up.)

Quoted 3 lines

I know maybe some thing doesn't make sense from C to Rust but doesn't deviates from C code introduce more confusion when something need to be ported from C to Rust?

Ideally we have people that work on both sides and can bridge that gap. If not, then having a Rust expert and a C expert work together has worked out great in the past. I don't see this becoming a big problem unless one of the sides is poorly maintained, which could also happen in C.

Quoted 1 line

Again no idea if this apply so I'm just curious about this.

No worries, glad to hear your perspective.

---
Cheers,
Benno

maintainer
#22 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

In reply to Benno Lossin
Quoted 24 lines · On Sat, 17 May 2025 21:02:51 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 8 lines
Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

Quoted 7 lines

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

I wouldn't do it like this in Rust, instead this would be a "rustier" function signature:

    fn match_device_id<T: Driver>(dev: &mut phy::Device) -> bool {
        // do the comparison with T::PHY_DEVICE_ID
        dev.id() == T::PHY_DEVICE_ID
    }
Quoted 7 lines

And then in the impls for Phy{A,B,C,D} do this:

    impl Driver for PhyA {
        fn match_phy_device(dev: &mut phy::Device) -> bool {
            match_device_id::<Self>(dev)
        }
    }

Ah, yes, this works well.

Quoted 7 lines
Quoted 7 lines

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 7 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a

Maybe a bool would be more appropriate here because the C's comment says:

Return: 1 if the PHY device matches the driver, 0 otherwise.

Quoted 1 line

function as well (though I wouldn't use the vtable for that).

What would you use instead?

reviewer
#23 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 52 lines · FUJITA Tomonori
Quoted 24 lines · On Sat, 17 May 2025 21:02:51 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 8 lines
Quoted 7 lines

I think that's wrong, nothing stops me from implementing Driver for an empty enum and that can't be instantiated. The reason that one wants to have this in C is because the same match function is used for different drivers (or maybe devices? I'm not too familiar with the terminology). In Rust, you must implement the match function for a single PHY_DEVICE_ID only, so maybe we don't need to change the signature at all?

Quoted 7 lines

I'm not sure I understand the last sentence. The Rust PHY abstraction allows one module to support multiple drivers. So we can could the similar trick that the second patch in this patchset does.

fn match_device_id(dev: &mut phy::Device, drv: &phy::DriverVTable) -> bool {
    // do comparison workking for three drivers
}

I wouldn't do it like this in Rust, instead this would be a "rustier" function signature:

    fn match_device_id<T: Driver>(dev: &mut phy::Device) -> bool {
        // do the comparison with T::PHY_DEVICE_ID
        dev.id() == T::PHY_DEVICE_ID
    }
Quoted 7 lines

And then in the impls for Phy{A,B,C,D} do this:

    impl Driver for PhyA {
        fn match_phy_device(dev: &mut phy::Device) -> bool {
            match_device_id::<Self>(dev)
        }
    }

Ah, yes, this works well.

Quoted 7 lines
Quoted 7 lines

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 7 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a

Quoted 8 lines

Maybe a bool would be more appropriate here because the C's comment says:

Return: 1 if the PHY device matches the driver, 0 otherwise.

Quoted 1 line

function as well (though I wouldn't use the vtable for that).

What would you use instead?

The concept that I sketched above:

    impl Device {
        fn genphy_match_phy_device<T: Driver>(&self) -> bool {
            self.phy_id() == T::PHY_DEVICE_ID.id
        }
    }

---
Cheers,
Benno

maintainer
#24 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 24 lines · On Mon, 19 May 2025 14:32:44 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 15 lines
Quoted 7 lines
Quoted 7 lines

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 7 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a

Quoted 8 lines

Maybe a bool would be more appropriate here because the C's comment says:

Return: 1 if the PHY device matches the driver, 0 otherwise.

Quoted 1 line

function as well (though I wouldn't use the vtable for that).

What would you use instead?

Quoted 7 lines

The concept that I sketched above:

    impl Device {
        fn genphy_match_phy_device<T: Driver>(&self) -> bool {
            self.phy_id() == T::PHY_DEVICE_ID.id
        }
    }

I think there might be a misunderstanding.

Rust's genphy_match_phy_device() is supposed to be a wrapper for C's genphy_match_phy_device():

https://lore.kernel.org/rust-for-linux/[email protected]/

reviewer
#25 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 34 lines · FUJITA Tomonori
Quoted 24 lines · On Mon, 19 May 2025 14:32:44 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 15 lines
Quoted 7 lines
Quoted 7 lines

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 7 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a

Quoted 8 lines

Maybe a bool would be more appropriate here because the C's comment says:

Return: 1 if the PHY device matches the driver, 0 otherwise.

Quoted 1 line

function as well (though I wouldn't use the vtable for that).

What would you use instead?

Quoted 7 lines

The concept that I sketched above:

    impl Device {
        fn genphy_match_phy_device<T: Driver>(&self) -> bool {
            self.phy_id() == T::PHY_DEVICE_ID.id
        }
    }
Quoted 6 lines

I think there might be a misunderstanding.

Rust's genphy_match_phy_device() is supposed to be a wrapper for C's genphy_match_phy_device():

https://lore.kernel.org/rust-for-linux/[email protected]/

Oh yeah you're right. But using DriverVTable for that doesn't sound nice...

---
Cheers,
Benno

maintainer
#26 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

Quoted 37 lines · On Mon, 19 May 2025 14:51:55 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 36 lines · FUJITA Tomonori
Quoted 24 lines · On Mon, 19 May 2025 14:32:44 +0200 "Benno Lossin" <[email protected]> wrote:
Quoted 15 lines
Quoted 7 lines
Quoted 7 lines

The other use case, as mentioned above, is when using the generic helper function inside match_phy_device() callback. For example, the 4th patch in this patchset adds genphy_match_phy_device():

int genphy_match_phy_device(struct phy_device *phydev,
const struct phy_driver *phydrv)

Quoted 7 lines
Quoted 5 lines

We could add a wrapper for this function as phy::Device's method like

impl Device {
    ...
    pub fn genphy_match_phy_device(&self, drv: &phy::DriverVTable) -> i32 

Not sure why this returns an i32, but we probably could have such a

Quoted 8 lines

Maybe a bool would be more appropriate here because the C's comment says:

Return: 1 if the PHY device matches the driver, 0 otherwise.

Quoted 1 line

function as well (though I wouldn't use the vtable for that).

What would you use instead?

Quoted 7 lines

The concept that I sketched above:

    impl Device {
        fn genphy_match_phy_device<T: Driver>(&self) -> bool {
            self.phy_id() == T::PHY_DEVICE_ID.id
        }
    }

I think there might be a misunderstanding.

Quoted 7 lines
Quoted 4 lines

Rust's genphy_match_phy_device() is supposed to be a wrapper for C's genphy_match_phy_device():

https://lore.kernel.org/rust-for-linux/[email protected]/

Oh yeah you're right. But using DriverVTable for that doesn't sound nice...

Agreed. We initially assumed that DriverVTable would be internal to driver registration and not something driver developers would use directly. Now that this has changed, it might be a good idea to rename it.

author maintainer
#27 lore raw

Re: [net-next PATCH v10 7/7] rust: net::phy sync with match_phy_device C changes

In reply to FUJITA Tomonori
Quoted 57 lines · FUJITA Tomonori

Hi,

Quoted 52 lines · On Thu, 15 May 2025 13:27:12 +0200 Christian Marangi <[email protected]>…

Sync match_phy_device callback wrapper in net:phy rust with the C changes where match_phy_device also provide the passed PHY driver.

As explained in the C commit, this is useful for match_phy_device to access the PHY ID defined in the PHY driver permitting more generalized functions.

---
 rust/kernel/net/phy.rs | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)
rust/kernel/net/phy.rs +16 -2
index a59469c785e3..936a137a8a29 100644
@@ -418,15 +418,18 @@ impl<T: Driver> Adapter<T> {
 
     /// # Safety
     ///
-    /// `phydev` must be passed by the corresponding callback in `phy_driver`.
+    /// `phydev` and `phydrv` must be passed by the corresponding callback in
+    //  `phy_driver`.
     unsafe extern "C" fn match_phy_device_callback(
         phydev: *mut bindings::phy_device,
+        phydrv: *const bindings::phy_driver
     ) -> crate::ffi::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.
         let dev = unsafe { Device::from_raw(phydev) };
-        T::match_phy_device(dev) as i32
+        let drv = unsafe { T::from_raw(phydrv) };
+        T::match_phy_device(dev, drv) as i32
     }
 
     /// # Safety
@@ -574,6 +577,23 @@ pub const fn create_phy_driver<T: Driver>() -> DriverVTable {
 /// This trait is used to create a [`DriverVTable`].
 #[vtable]
 pub trait Driver {
+    /// # Safety
+    ///
+    /// For the duration of `'a`,
+    /// - the pointer must point at a valid `phy_driver`, and the caller
+    ///   must be in a context where all methods defined on this struct
+    ///   are safe to call.
+    unsafe fn from_raw<'a>(ptr: *const bindings::phy_driver) -> &'a Self
+    where
+        Self: Sized,
+    {
+        // CAST: `Self` is a `repr(transparent)` wrapper around `bindings::phy_driver`.
Quoted 9 lines

rust/kernel/net/phy.rs pub const fn create_phy_driver<T: Driver>() -> DriverVTable { · line 595

Quoted 5 lines
rust/kernel/net/phy.rs +5 -0
+        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 { &*ptr }
+    }

We might need to update the comment. phy_driver is const so I think that we can access to it any time.

Any hint for a better comment?

Quoted 22 lines

rust/kernel/net/phy.rs fn get_features(_dev: &mut Device) -> Result { · line 627

Quoted 11 lines
rust/kernel/net/phy.rs +1 -1
     /// Defines certain other features this PHY supports.
     /// It is a combination of the flags in the [`flags`] module.
     const FLAGS: u32 = 0;
@@ -602,7 +622,7 @@ fn get_features(_dev: &mut Device) -> Result {
 
     /// Returns true if this is a suitable driver for the given phydev.
     /// If not implemented, matching is based on [`Driver::PHY_DEVICE_ID`].
-    fn match_phy_device(_dev: &Device) -> bool {
+    fn match_phy_device<T: Driver>(_dev: &mut Device, _drv: &T) -> bool {
         false
     }

I think that it could be a bit simpler:

fn match_phy_device(_dev: &mut Device, _drv: &Self) -> bool

Or making it a trait method might be more idiomatic?

fn match_phy_device(&self, _dev: &mut Device) -> bool

Thanks!

Signature · 1 line
	Ansuel