Re: [PATCH v2 2/2] usb: roles: wait for callbacks on unregister
From: Heikki Krogerus
Date: Fri Nov 20 2026 - 08:23:38 EST
On Tue, Nov 17, 2026 at 01:00:20PM +0000, Keisuke Tsukuda wrote:
> usb_role_switch_set_role() and usb_role_switch_get_role() check the
> registered flag before taking the switch lock. If a provider is
> unregistered during a role request, unregister can return while its
> callback is still running. The provider may then free memory used by
> the callback, causing a use-after-free. A caller that passed the check
> can also enter a callback after unregister returns.
>
> Move the registered checks under the switch lock and clear the flag while
> holding the same lock on unregister. This waits for active callbacks and
> rejects callers that acquire the lock after the flag is cleared. The
> preceding Apple DWC3 change avoids a lock inversion in its remove path.
>
> Fixes: fde0aa6c175a ("usb: common: Small class for USB role switches")
> Cc: stable@xxxxxxxxxxxxxxx
> Signed-off-by: Keisuke Tsukuda <tkdkei@xxxxxxxxxx>
Reviewed-by: Heikki Krogerus <heikki.krogerus@xxxxxxxxxxxxxxx>
> ---
> drivers/usb/roles/class.c | 18 ++++++++++++++----
> 1 file changed, 14 insertions(+), 4 deletions(-)
>
> diff --git a/drivers/usb/roles/class.c b/drivers/usb/roles/class.c
> --- a/drivers/usb/roles/class.c
> +++ b/drivers/usb/roles/class.c
> @@ -79,10 +79,11 @@
> if (IS_ERR_OR_NULL(sw))
> return 0;
>
> - if (!sw->registered)
> - return -EOPNOTSUPP;
> -
> mutex_lock(&sw->lock);
> + if (!sw->registered) {
> + ret = -EOPNOTSUPP;
> + goto unlock;
> + }
>
> ret = sw->set(sw, role);
> if (!ret) {
> @@ -90,6 +91,7 @@
> kobject_uevent(&sw->dev.kobj, KOBJ_CHANGE);
> }
>
> +unlock:
> mutex_unlock(&sw->lock);
>
> return ret;
> @@ -107,16 +109,21 @@
> {
> enum usb_role role;
>
> - if (IS_ERR_OR_NULL(sw) || !sw->registered)
> + if (IS_ERR_OR_NULL(sw))
> return USB_ROLE_NONE;
>
> mutex_lock(&sw->lock);
> + if (!sw->registered) {
> + role = USB_ROLE_NONE;
> + goto unlock;
> + }
>
> if (sw->get)
> role = sw->get(sw);
> else
> role = sw->role;
>
> +unlock:
> mutex_unlock(&sw->lock);
>
> return role;
> @@ -423,7 +430,10 @@
> {
> if (IS_ERR_OR_NULL(sw))
> return;
> + /* Wait for in-flight set/get callbacks before unregistering. */
> + mutex_lock(&sw->lock);
> sw->registered = false;
> + mutex_unlock(&sw->lock);
> if (dev_fwnode(&sw->dev))
> component_del(&sw->dev, &connector_ops);
> device_unregister(&sw->dev);
--
heikki