Re: [PATCH v2 2/4] usb: gadget: udc: Forget a deactivation when the gadget driver unbinds

From: Alan Stern

Date: Sat Nov 14 2026 - 16:07:53 EST


On Fri, Nov 13, 2026 at 01:28:17PM +0400, Alexey Charkov wrote:
> A gadget driver deactivates the gadget through usb_gadget_deactivate()
> until its functions are ready, so the deactivation means nothing to the
> next driver. Yet the UDC core keeps gadget->deactivated set across
> unbind. Only configfs resets it, from its own unbind callback and
> without connect_lock, so a legacy gadget driver that unbinds while
> deactivated leaves the next driver unable to connect.
>
> Clear the flag under connect_lock once the driver has unbound, including
> when the bind fails after the driver has deactivated the gadget.
>
> Suggested-by: Alan Stern <stern@xxxxxxxxxxxxxxxxxxx>
> Signed-off-by: Alexey Charkov <alchark@xxxxxxxxxxx>
> ---
> drivers/usb/gadget/udc/core.c | 13 +++++++++++++
> 1 file changed, 13 insertions(+)
>
> diff --git a/drivers/usb/gadget/udc/core.c b/drivers/usb/gadget/udc/core.c
> index 577bc15f61a1..84dc0820c2cb 100644
> --- a/drivers/usb/gadget/udc/core.c
> +++ b/drivers/usb/gadget/udc/core.c
> @@ -1647,6 +1647,13 @@ static int gadget_match_driver(struct device *dev, const struct device_driver *d
> return 1;
> }
>
> +/* Forget the state that a gadget driver left behind, so the next starts afresh */
> +static void usb_udc_forget_driver_locked(struct usb_udc *udc)
> + __must_hold(&udc->connect_lock)
> +{
> + udc->gadget->deactivated = false;
> +}

Is there any reason for making this a separate subroutine? Just do
the assignment inline in the two places where it occurs.

> +
> static int gadget_bind_driver(struct device *dev)
> {
> struct usb_gadget *gadget = dev_to_usb_gadget(dev);
> @@ -1705,6 +1712,11 @@ static int gadget_bind_driver(struct device *dev)
> dev_err(&udc->dev, "failed to start %s: %d\n",
> driver->function, ret);
>
> + /* The driver may have deactivated the gadget before failing */
> + mutex_lock(&udc->connect_lock);
> + usb_udc_forget_driver_locked(udc);
> + mutex_unlock(&udc->connect_lock);
> +
> mutex_lock(&udc_lock);
> udc->driver = NULL;
> driver->is_bound = false;
> @@ -1734,6 +1746,7 @@ static void gadget_unbind_driver(struct device *dev)
>
> mutex_lock(&udc->connect_lock);
> usb_gadget_udc_stop_locked(udc);
> + usb_udc_forget_driver_locked(udc);
> mutex_unlock(&udc->connect_lock);
>
> mutex_lock(&udc_lock);

Also, you may as well merge the 3/4 patch with this one. After all,
they are both concerned with the same thing.

Alan Stern

PS: I'll review the 4/4 patch later.