Subject: [PATCH] phy: fix possible double lock calling link changed handler

From: Alessandro B Maurici <[email-masked]>
Date: Mon, 22 Nov 2021 23:55:48 -0300

From: Alessandro B Maurici <[email-masked]>

Releases the phy lock before calling phy_link_change to avoid any worker
thread lockup. Some network drivers(eg Microchip's LAN743x), make a call to
phy_ethtool_get_link_ksettings inside the link change handler, and, due to
the commit c10a485c3de5 ("phy: phy_ethtool_ksettings_get: Lock the phy for
consistency"), this will cause a lockup.
As that mutex call is needed for consistency, we need to release the lock,
if previously locked, before calling the handler to prevent issues.

Signed-off-by: Alessandro B Maurici <[email-masked]>
---
 drivers/net/phy/phy.c | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/drivers/net/phy/phy.c b/drivers/net/phy/phy.c
index beb2b66da132..0914e339e623 100644
--- a/drivers/net/phy/phy.c
+++ b/drivers/net/phy/phy.c
@@ -58,13 +58,31 @@ static const char *phy_state_to_str(enum phy_state st)
 
 static void phy_link_up(struct phy_device *phydev)
 {
+	bool must_relock = false;
+
+	if (mutex_is_locked(&phydev->lock)) {
+		must_relock = true;
+		mutex_unlock(&phydev->lock);
+	}
 	phydev->phy_link_change(phydev, true);
+	if (must_relock)
+		mutex_lock(&phydev->lock);
+
 	phy_led_trigger_change_speed(phydev);
 }
 
 static void phy_link_down(struct phy_device *phydev)
 {
+	bool must_relock = false;
+
+	if (mutex_is_locked(&phydev->lock)) {
+		must_relock = true;
+		mutex_unlock(&phydev->lock);
+	}
 	phydev->phy_link_change(phydev, false);
+	if (must_relock)
+		mutex_lock(&phydev->lock);
+
 	phy_led_trigger_change_speed(phydev);
 }