[PATCH] phy: mdio: fix memory leak
From: Pavel Skripkin
Date: Mon Sep 27 2021 - 07:20:37 EST
Syzbot reported memory leak in MDIO bus interface, the problem was in
wrong state logic.
MDIOBUS_ALLOCATED indicates 2 states:
1. Bus is only allocated
2. Bus allocated and __mdiobus_register() fails, but
device_register() was called
In case of device_register() has been called we should call put_device()
to correctly free the memory allocated for this device, but mdiobus_free()
was just calling kfree(dev) in case of MDIOBUS_ALLOCATED state
To avoid this behaviour we can add new intermediate state, which means,
that we have called device_regiter(), but failed on any of the next steps.
Clean up process for this state is the same as for MDIOBUS_UNREGISTERED,
but MDIOBUS_UNREGISTERED name does not fit to the logic described above.
Fixes: 46abc02175b3 ("phylib: give mdio buses a device tree presence")
Reported-and-tested-by: syzbot+398e7dc692ddbbb4cfec@xxxxxxxxxxxxxxxxxxxxxxxxx
Signed-off-by: Pavel Skripkin <paskripkin@xxxxxxxxx>
---
drivers/net/phy/mdio_bus.c | 4 +++-
include/linux/phy.h | 1 +
2 files changed, 4 insertions(+), 1 deletion(-)
diff --git a/drivers/net/phy/mdio_bus.c b/drivers/net/phy/mdio_bus.c
index 53f034fc2ef7..ed764638b449 100644
--- a/drivers/net/phy/mdio_bus.c
+++ b/drivers/net/phy/mdio_bus.c
@@ -540,6 +540,8 @@ int __mdiobus_register(struct mii_bus *bus, struct module *owner)
return -EINVAL;
}
+ bus->state = MDIOBUS_DEV_REGISTERED;
+
mutex_init(&bus->mdio_lock);
mutex_init(&bus->shared_lock);
@@ -647,7 +649,7 @@ void mdiobus_free(struct mii_bus *bus)
return;
}
- BUG_ON(bus->state != MDIOBUS_UNREGISTERED);
+ BUG_ON(bus->state != MDIOBUS_UNREGISTERED && bus->state != MDIOBUS_DEV_REGISTERED);
bus->state = MDIOBUS_RELEASED;
put_device(&bus->dev);
diff --git a/include/linux/phy.h b/include/linux/phy.h
index 736e1d1a47c4..41d2ccdacd5e 100644
--- a/include/linux/phy.h
+++ b/include/linux/phy.h
@@ -343,6 +343,7 @@ struct mii_bus {
MDIOBUS_REGISTERED,
MDIOBUS_UNREGISTERED,
MDIOBUS_RELEASED,
+ MDIOBUS_DEV_REGISTERED,
} state;
/** @dev: Kernel device representation */
--
2.33.0