Re: [PATCH] usb: gadget: f_ecm: serialize notification state with a spinlock
From: Greg Kroah-Hartman
Date: Fri Nov 20 2026 - 09:27:47 EST
On Mon, Oct 26, 2026 at 04:00:31PM +1000, Yu Zhang wrote:
> ecm_do_notify() guards re-entry only with an atomic_read() of
> notify_count, then fills ecm->notify_req, does atomic_inc() and
> usb_ep_queue(). This check-fill-inc-queue sequence is not atomic and
> runs from three contexts that share no lock: ecm_notify_complete(),
> ecm_open()/ecm_close() (netdev up/down via u_ether) and ecm_set_alt().
>
> When the completion handler decrements notify_count to 0 and re-enters
> ecm_do_notify(), a concurrent ecm_close()/ecm_set_alt() can observe
> notify_count == 0 in the window between the atomic_dec() and the next
> atomic_inc(), and queue the same ecm->notify_req a second time. The
> request is then added to the endpoint queue twice (list_add corruption),
> and notify_state is updated concurrently.
>
> struct f_ecm has carried a FIXME about this missing locking. The sibling
> f_ncm already serializes the identical state machine with a per-instance
> spinlock. Do the same in f_ecm: take ecm->lock across the is_open update
> and ecm_notify() in open/close/set_alt and across the state update in
> ecm_notify_complete(), dropping it only around usb_ep_queue().
>
> Signed-off-by: Yu Zhang <yuz08559@xxxxxxxxx>
> ---
> drivers/usb/gadget/function/f_ecm.c | 19 ++++++++++++++++---
> 1 file changed, 16 insertions(+), 3 deletions(-)
>
> diff --git a/drivers/usb/gadget/function/f_ecm.c b/drivers/usb/gadget/function/f_ecm.c
> index e495bac..d699832 100644
> --- a/drivers/usb/gadget/function/f_ecm.c
> +++ b/drivers/usb/gadget/function/f_ecm.c
> @@ -59,9 +59,8 @@ struct f_ecm {
> atomic_t notify_count;
> bool is_open;
>
> - /* FIXME is_open needs some irq-ish locking
> - * ... possibly the same as port.ioport
> - */
> + /* protects the notification state machine */
> + spinlock_t lock;
> };
>
> static inline struct f_ecm *func_to_ecm(struct usb_function *f)
> @@ -414,7 +413,11 @@ static void ecm_do_notify(struct f_ecm *ecm)
> event->wIndex = cpu_to_le16(ecm->ctrl_id);
>
> atomic_inc(&ecm->notify_count);
> +
> + /* usb_ep_queue() can complete the request re-entrantly */
> + spin_unlock(&ecm->lock);
Please use a guard()