mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races
@ 2026-11-26  6:37 Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 1/6] usb: gadget: gadgetfs: fix ep0 request lifetime on unbind Jing Lin via B4 Relay
                   ` (5 more replies)
  0 siblings, 6 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

This series fixes the ep0 request lifetime on unbind, control buffer and
setup_abort state races, lost completed control-OUT transfers, event
counter underflow, and the const cast in gadgetfs_setup().

1/6 tracks active ep0 requests and waits for completion after
    usb_ep_dequeue() in gadgetfs_unbind() before freeing dev->req, while
    keeping descriptor buffers out of kfree().
2/6 copies delegated control-IN payloads into a private memdup_user()
    buffer before touching dev->req and drops responses superseded
    during the unlocked copy.
3/6 fixes setup_abort tracking across ep0_poll(), gadgetfs_disconnect(),
    and early returns or in-kernel requests in gadgetfs_setup().
4/6 preserves completed control-OUT payloads until ep0_read() collects
    them, leaving ep0 unqueued so the controller NAKs newly arriving
    control transfers in the meantime and replaying the deferred setup
    afterwards.
5/6 dequeues ep0 events before dropping dev->lock for copy_to_user() to
    prevent dev->ev_next underflow.
6/6 removes the const cast on ctrl->wLength in gadgetfs_setup().

The setup() callback runs in atomic context and may not sleep, so a
mutex cannot serialize it against ep0_read() and ep0_write(); shared ep0
state remains protected by dev->lock.

---
Changes in v9:
- Split the first two patches into single-purpose patches (1/6 through
  4/6) so each problem is addressed separately.
- Drop the rejected usb_ep_dequeue() fallback (ep0_req_free) in 1/6.
- Allocate a private buffer with memdup_user() for control-IN writes in
  2/6 instead of copying through a stack buffer, and clarify that the
  generation check narrows rather than eliminates the unlocked window.
- Preserve properly completed control-OUT transfers in 4/6 by deferring
  any subsequent SETUP (leaving ep0 without a queued request so the UDC
  NAKs it) until userspace reads the completed OUT payload, then replay
  the deferred SETUP.
- Drop the STATE_DEV_UNBOUND event-read changes from this series.  For
  context on how unbind can happen before close(ep0): unloading the UDC
  driver (usb_del_gadget_udc()) or writing to
  /sys/bus/gadget/drivers/gadgetfs/unbind runs gadgetfs_unbind() while
  userspace still holds the open ep0 descriptor, where a queued
  GADGETFS_SETUP event could otherwise put dev->state back into
  STATE_DEV_SETUP on the next read().  If that case is worth guarding
  against, a small follow-up patch can clear dev->ev_next and wake
  dev->wait in gadgetfs_unbind() and check STATE_DEV_UNBOUND before
  delivering events in ep0_read().
- Use a local events[N_EVENT] array in 5/6 instead of sharing a buffer
  with control-OUT reads.
- Link to v8: https://patch.msgid.link/20261110-gadgetfs-ep0-v8-v8-0-8f90434574fe@gmail.com

To: Neill Kapron <nkapron@google.com>
To: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Cc: Alan Stern <stern@rowland.harvard.edu>
Cc: linux-usb@vger.kernel.org
Cc: linux-kernel@vger.kernel.org
Cc: syzbot+c73e1942197af9f54ca3@syzkaller.appspotmail.com
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>

---
Jing Lin (6):
      usb: gadget: gadgetfs: fix ep0 request lifetime on unbind
      usb: gadget: gadgetfs: isolate ep0_write() buffer and reduce setup race
      usb: gadget: gadgetfs: fix ep0 setup_abort tracking and reporting
      usb: gadget: gadgetfs: NAK new setups until control-OUT data is read
      usb: gadget: gadgetfs: prevent ep0 event counter underflow
      usb: gadget: gadgetfs: avoid writing through the const setup pointer

 drivers/usb/gadget/legacy/inode.c | 514 +++++++++++++++++++++++++++-----------
 1 file changed, 366 insertions(+), 148 deletions(-)
---
base-commit: 90d6263e867be7089b3d3323bef8d2accd327c77
change-id: 20261126-gadgetfs-ep0-fc2255305a75

Best regards,
--  
Jing Lin <kayano050408@gmail.com>



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 1/6] usb: gadget: gadgetfs: fix ep0 request lifetime on unbind
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 2/6] usb: gadget: gadgetfs: isolate ep0_write() buffer and reduce setup race Jing Lin via B4 Relay
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

gadgetfs_unbind() frees the preallocated ep0 request after disconnecting
the gadget, assuming that no I/O remains active.

With controllers such as dummy_hcd, disconnecting does not necessarily
drain ep0, so a delayed userspace response can leave dev->req queued
when it is freed.  This triggers the warning in dummy_free_request() and
a use-after-free when dummy_udc_stop() subsequently drains the endpoint
queue.

Submit ep0 requests through a shared queue_ep0_req() helper that tracks
dev->ep0_req_queued under dev->lock and wakes dev->wait whenever the
flag clears.  Track dynamically allocated ep0 buffers separately in
dev->ep0_req_buf so clean_req() never frees descriptor storage inside
dev->buf.

In gadgetfs_unbind(), tear down non-ep0 endpoints first, then dequeue
any active ep0 request and wait under dev->lock with
wait_event_lock_irq() for completion to finish before freeing dev->req.

Fixes: 1da177e4c3f41 ("Linux-2.6.12-rc2")
Reported-by: syzbot+c73e1942197af9f54ca3@syzkaller.appspotmail.com
Closes: https://syzkaller.appspot.com/bug?extid=c73e1942197af9f54ca3
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 199 +++++++++++++++++++++++++-------------
 1 file changed, 133 insertions(+), 66 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index cc059a6ee262..911419a4e1a3 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -140,6 +140,8 @@ struct dev_data {
 					setup_abort : 1,
 					gadget_registered : 1;
 	unsigned			setup_wLength;
+	bool				ep0_req_queued;
+	void				*ep0_req_buf;
 
 	/* the rest is basically write-once */
 	struct usb_config_descriptor	*config, *hs_config;
@@ -984,21 +986,39 @@ static inline void ep0_readable (struct dev_data *dev)
 	kill_fasync (&dev->fasync, SIGIO, POLL_IN);
 }
 
-static void clean_req (struct usb_ep *ep, struct usb_request *req)
+static void dev_req_complete(struct usb_ep *ep, struct usb_request *req);
+
+static void clean_req(struct usb_ep *ep, struct usb_request *req)
 {
-	struct dev_data		*dev = ep->driver_data;
+	struct dev_data		*dev = req->context;
 
-	if (req->buf != dev->rbuf) {
-		kfree(req->buf);
-		req->buf = dev->rbuf;
-	}
-	req->complete = epio_complete;
+	/*
+	 * req->buf may also point into dev->buf, which holds the
+	 * descriptors; only the buffer allocated for the request may be
+	 * freed here.
+	 */
+	kfree(dev->ep0_req_buf);
+	dev->ep0_req_buf = NULL;
+	req->buf = dev->rbuf;
+	req->complete = dev_req_complete;
 	dev->setup_out_ready = 0;
 }
 
-static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
+static void dev_req_complete(struct usb_ep *ep, struct usb_request *req)
 {
-	struct dev_data		*dev = ep->driver_data;
+	struct dev_data		*dev = req->context;
+	unsigned long		flags;
+
+	spin_lock_irqsave(&dev->lock, flags);
+	clean_req(ep, req);
+	dev->ep0_req_queued = false;
+	wake_up(&dev->wait);
+	spin_unlock_irqrestore(&dev->lock, flags);
+}
+
+static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
+{
+	struct dev_data		*dev = req->context;
 	unsigned long		flags;
 	int			free = 1;
 
@@ -1009,29 +1029,36 @@ static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
 		if (!dev->setup_out_error)
 			free = 0;
 		dev->setup_out_ready = 1;
-		ep0_readable (dev);
+		ep0_readable(dev);
 	}
 
 	/* clean up as appropriate */
-	if (free && req->buf != &dev->rbuf)
-		clean_req (ep, req);
-	req->complete = epio_complete;
+	if (free)
+		clean_req(ep, req);
+	else
+		req->complete = dev_req_complete;
+	dev->ep0_req_queued = false;
+	wake_up(&dev->wait);
 	spin_unlock_irqrestore(&dev->lock, flags);
 }
 
-static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
+static int setup_req(struct usb_ep *ep, struct usb_request *req, u16 len)
 {
 	struct dev_data	*dev = ep->driver_data;
 
-	if (dev->setup_out_ready) {
-		DBG (dev, "ep0 request busy!\n");
+	if (dev->setup_out_ready || dev->ep0_req_queued) {
+		DBG(dev, "ep0 request busy!\n");
 		return -EBUSY;
 	}
-	if (len > sizeof (dev->rbuf))
-		req->buf = kmalloc(len, GFP_ATOMIC);
-	if (req->buf == NULL) {
+	if (len > sizeof(dev->rbuf)) {
+		dev->ep0_req_buf = kmalloc(len, GFP_ATOMIC);
+		if (!dev->ep0_req_buf) {
+			req->buf = dev->rbuf;
+			return -ENOMEM;
+		}
+		req->buf = dev->ep0_req_buf;
+	} else {
 		req->buf = dev->rbuf;
-		return -ENOMEM;
 	}
 	req->complete = ep0_complete;
 	req->length = len;
@@ -1039,6 +1066,35 @@ static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
 	return 0;
 }
 
+/* Called with dev->lock held. */
+static int queue_ep0_req(struct dev_data *dev, bool process_ctx)
+{
+	struct usb_ep		*ep = dev->gadget->ep0;
+	struct usb_request	*req = dev->req;
+	int			ret;
+
+	++dev->udc_usage;
+	dev->ep0_req_queued = true;
+	if (process_ctx)
+		spin_unlock_irq(&dev->lock);
+	else
+		spin_unlock(&dev->lock);
+
+	ret = usb_ep_queue(ep, req, process_ctx ? GFP_KERNEL : GFP_ATOMIC);
+
+	if (process_ctx)
+		spin_lock_irq(&dev->lock);
+	else
+		spin_lock(&dev->lock);
+	--dev->udc_usage;
+	if (ret < 0) {
+		clean_req(ep, req);
+		dev->ep0_req_queued = false;
+		wake_up(&dev->wait);
+	}
+	return ret;
+}
+
 static ssize_t
 ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 {
@@ -1072,14 +1128,10 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 			struct usb_ep		*ep = dev->gadget->ep0;
 			struct usb_request	*req = dev->req;
 
-			if ((retval = setup_req (ep, req, 0)) == 0) {
-				++dev->udc_usage;
-				spin_unlock_irq (&dev->lock);
-				retval = usb_ep_queue (ep, req, GFP_KERNEL);
-				spin_lock_irq (&dev->lock);
-				--dev->udc_usage;
-			}
+			retval = setup_req(ep, req, 0);
 			dev->state = STATE_DEV_CONNECTED;
+			if (retval == 0)
+				retval = queue_ep0_req(dev, true);
 
 			/* assume that was SET_CONFIGURATION */
 			if (dev->current_config) {
@@ -1271,22 +1323,20 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 			if (retval == 0) {
 				dev->state = STATE_DEV_CONNECTED;
 				++dev->udc_usage;
-				spin_unlock_irq (&dev->lock);
-				if (copy_from_user (dev->req->buf, buf, len))
+				spin_unlock_irq(&dev->lock);
+				if (copy_from_user(dev->req->buf, buf, len))
 					retval = -EFAULT;
-				else {
-					if (len < dev->setup_wLength)
-						dev->req->zero = 1;
-					retval = usb_ep_queue (
-						dev->gadget->ep0, dev->req,
-						GFP_KERNEL);
-				}
 				spin_lock_irq(&dev->lock);
 				--dev->udc_usage;
 				if (retval < 0) {
-					clean_req (dev->gadget->ep0, dev->req);
-				} else
-					retval = len;
+					clean_req(dev->gadget->ep0, dev->req);
+				} else {
+					if (len < dev->setup_wLength)
+						dev->req->zero = 1;
+					retval = queue_ep0_req(dev, true);
+					if (retval == 0)
+						retval = len;
+				}
 
 				return retval;
 			}
@@ -1482,7 +1532,11 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 		}
 	}
 
-	spin_lock (&dev->lock);
+	spin_lock(&dev->lock);
+	if (dev->ep0_req_queued) {
+		spin_unlock(&dev->lock);
+		return -EBUSY;
+	}
 	dev->setup_abort = 0;
 	if (dev->state == STATE_DEV_UNCONNECTED) {
 		if (gadget_is_dualspeed(gadget)
@@ -1509,7 +1563,6 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 		dev->setup_abort = 1;
 
 	req->buf = dev->rbuf;
-	req->context = NULL;
 	switch (ctrl->bRequest) {
 
 	case USB_REQ_GET_DESCRIPTOR:
@@ -1620,22 +1673,15 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 			dev->setup_out_error = 0;
 
 			/* read DATA stage for OUT right away */
-			if (unlikely (!dev->setup_in && w_length)) {
-				value = setup_req (gadget->ep0, dev->req,
-							w_length);
+			if (unlikely(!dev->setup_in && w_length)) {
+				value = setup_req(gadget->ep0, dev->req,
+						  w_length);
 				if (value < 0)
 					break;
 
-				++dev->udc_usage;
-				spin_unlock (&dev->lock);
-				value = usb_ep_queue (gadget->ep0, dev->req,
-							GFP_KERNEL);
-				spin_lock (&dev->lock);
-				--dev->udc_usage;
-				if (value < 0) {
-					clean_req (gadget->ep0, dev->req);
+				value = queue_ep0_req(dev, false);
+				if (value < 0)
 					break;
-				}
 
 				/* we can't currently stall these */
 				dev->setup_can_stall = 0;
@@ -1663,22 +1709,20 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 	if (value >= 0 && dev->state != STATE_DEV_SETUP) {
 		req->length = value;
 		req->zero = value < w_length;
+		req->complete = dev_req_complete;
 
-		++dev->udc_usage;
-		spin_unlock (&dev->lock);
-		value = usb_ep_queue (gadget->ep0, req, GFP_KERNEL);
-		spin_lock(&dev->lock);
-		--dev->udc_usage;
-		spin_unlock(&dev->lock);
+		value = queue_ep0_req(dev, false);
 		if (value < 0) {
-			DBG (dev, "ep_queue --> %d\n", value);
+			DBG(dev, "ep_queue --> %d\n", value);
 			req->status = 0;
 		}
+		spin_unlock(&dev->lock);
 		return value;
 	}
 
 	/* device stalls when value < 0 */
-	spin_unlock (&dev->lock);
+	req->buf = dev->rbuf;
+	spin_unlock(&dev->lock);
 	return value;
 }
 
@@ -1771,6 +1815,7 @@ static void
 gadgetfs_unbind (struct usb_gadget *gadget)
 {
 	struct dev_data		*dev = get_gadget_data (gadget);
+	struct usb_request	*req;
 
 	DBG (dev, "%s\n", __func__);
 
@@ -1784,12 +1829,32 @@ gadgetfs_unbind (struct usb_gadget *gadget)
 	spin_unlock_irq (&dev->lock);
 
 	destroy_ep_files (dev);
+
+	spin_lock_irq(&dev->lock);
+	req = dev->req;
+	dev->req = NULL;
+	if (req) {
+		if (dev->ep0_req_queued) {
+			spin_unlock_irq(&dev->lock);
+			usb_ep_dequeue(gadget->ep0, req);
+			spin_lock_irq(&dev->lock);
+			/*
+			 * usb_ep_dequeue() may return before the completion
+			 * routine runs; wait until completion finishes.
+			 */
+			wait_event_lock_irq(dev->wait, !dev->ep0_req_queued,
+					    dev->lock);
+		}
+		clean_req(gadget->ep0, req);
+	}
+	spin_unlock_irq(&dev->lock);
+
+	if (req)
+		usb_ep_free_request(gadget->ep0, req);
+
 	gadget->ep0->driver_data = NULL;
 	set_gadget_data (gadget, NULL);
 
-	/* we've already been disconnected ... no i/o is active */
-	if (dev->req)
-		usb_ep_free_request (gadget->ep0, dev->req);
 	DBG (dev, "%s done\n", __func__);
 	put_dev (dev);
 }
@@ -1816,11 +1881,13 @@ static int gadgetfs_bind(struct usb_gadget *gadget,
 	get_dev (dev);
 
 	/* preallocate control response and buffer */
+	dev->ep0_req_queued = false;
 	dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
 	if (!dev->req)
 		goto enomem;
-	dev->req->context = NULL;
-	dev->req->complete = epio_complete;
+	dev->req->context = dev;
+	dev->req->complete = dev_req_complete;
+	dev->req->buf = dev->rbuf;
 
 	if (activate_ep_files (dev) < 0)
 		goto enomem;

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 2/6] usb: gadget: gadgetfs: isolate ep0_write() buffer and reduce setup race
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 1/6] usb: gadget: gadgetfs: fix ep0 request lifetime on unbind Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 3/6] usb: gadget: gadgetfs: fix ep0 setup_abort tracking and reporting Jing Lin via B4 Relay
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

For a delegated control-IN request, ep0_write() prepares dev->req and
copies the response from userspace with copy_from_user() after dropping
dev->lock.  A control request that arrives during that unlocked copy can
point req->buf at dev->dev or dev->config, letting copy_from_user()
overwrite a descriptor buffer, or supersede the transfer that userspace
is responding to.

Copy non-empty control-IN payloads from userspace into a private buffer
with memdup_user() before leaving STATE_DEV_SETUP or modifying dev->req,
and count setup callbacks in dev->setup_generation so ep0_write() can
discard a superseded response after retaking dev->lock.  This eliminates
the copy_from_user() race window, leaving only the unavoidable window
after dev->lock is dropped to call usb_ep_queue().

Fixes: 1da177e4c3f41 ("Linux-2.6.12-rc2")
Suggested-by: Alan Stern <stern@rowland.harvard.edu>
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 65 +++++++++++++++++++++++++++------------
 1 file changed, 46 insertions(+), 19 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 911419a4e1a3..a0dc350a7a0d 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -142,6 +142,7 @@ struct dev_data {
 	unsigned			setup_wLength;
 	bool				ep0_req_queued;
 	void				*ep0_req_buf;
+	unsigned int			setup_generation;
 
 	/* the rest is basically write-once */
 	struct usb_config_descriptor	*config, *hs_config;
@@ -1319,27 +1320,50 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 
 		len = min_t(size_t, len, dev->setup_wLength);
 		if (dev->setup_in) {
-			retval = setup_req (dev->gadget->ep0, dev->req, len);
-			if (retval == 0) {
-				dev->state = STATE_DEV_CONNECTED;
-				++dev->udc_usage;
+			unsigned int	generation = dev->setup_generation;
+			bool		zero = len < dev->setup_wLength;
+			void		*kbuf = NULL;
+
+			if (len > 0) {
 				spin_unlock_irq(&dev->lock);
-				if (copy_from_user(dev->req->buf, buf, len))
-					retval = -EFAULT;
+				kbuf = memdup_user(buf, len);
 				spin_lock_irq(&dev->lock);
-				--dev->udc_usage;
-				if (retval < 0) {
-					clean_req(dev->gadget->ep0, dev->req);
-				} else {
-					if (len < dev->setup_wLength)
-						dev->req->zero = 1;
-					retval = queue_ep0_req(dev, true);
-					if (retval == 0)
-						retval = len;
-				}
+				if (IS_ERR(kbuf))
+					return PTR_ERR(kbuf);
+			}
 
-				return retval;
+			/*
+			 * Reject the write if a new control request arrived
+			 * while dev->lock was dropped for memdup_user().
+			 */
+			if (dev->setup_generation != generation) {
+				kfree(kbuf);
+				if (dev->setup_abort) {
+					dev->setup_abort = 0;
+					if (dev->state == STATE_DEV_SETUP)
+						dev->state = STATE_DEV_CONNECTED;
+				}
+				return -EIDRM;
+			}
+			if (dev->state != STATE_DEV_SETUP || !dev->setup_in) {
+				kfree(kbuf);
+				return -ECANCELED;
 			}
+			if (dev->setup_out_ready || dev->ep0_req_queued) {
+				kfree(kbuf);
+				return -EBUSY;
+			}
+
+			dev->state = STATE_DEV_CONNECTED;
+			dev->ep0_req_buf = kbuf;
+			dev->req->buf = len ? kbuf : dev->rbuf;
+			dev->req->length = len;
+			dev->req->zero = zero;
+			dev->req->complete = dev_req_complete;
+			retval = queue_ep0_req(dev, true);
+			if (retval == 0)
+				retval = len;
+			return retval;
 
 		/* can stall some OUT transfers */
 		} else if (dev->setup_can_stall) {
@@ -1520,6 +1544,10 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 	u16				w_value = le16_to_cpu(ctrl->wValue);
 	u16				w_length = le16_to_cpu(ctrl->wLength);
 
+	spin_lock(&dev->lock);
+	/* invalidate userspace copies started for an older control request */
+	dev->setup_generation++;
+
 	if (w_length > RBUF_SIZE) {
 		if (ctrl->bRequestType & USB_DIR_IN) {
 			/* Cast away the const, we are going to overwrite on purpose. */
@@ -1528,11 +1556,10 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 			*temp = cpu_to_le16(RBUF_SIZE);
 			w_length = RBUF_SIZE;
 		} else {
+			spin_unlock(&dev->lock);
 			return value;
 		}
 	}
-
-	spin_lock(&dev->lock);
 	if (dev->ep0_req_queued) {
 		spin_unlock(&dev->lock);
 		return -EBUSY;

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 3/6] usb: gadget: gadgetfs: fix ep0 setup_abort tracking and reporting
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 1/6] usb: gadget: gadgetfs: fix ep0 request lifetime on unbind Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 2/6] usb: gadget: gadgetfs: isolate ep0_write() buffer and reduce setup race Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 4/6] usb: gadget: gadgetfs: NAK new setups until control-OUT data is read Jing Lin via B4 Relay
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

Several ep0 state transitions lose setup_abort notifications or leave
dev->state stuck in STATE_DEV_SETUP:

1. ep0_poll() clears dev->setup_abort when reporting EPOLLHUP, so the
   following ep0_read() or ep0_write() never sees -EIDRM.

2. gadgetfs_disconnect() sets dev->state to STATE_DEV_UNCONNECTED before
   calling next_event(GADGETFS_DISCONNECT), skipping the STATE_DEV_SETUP
   check that sets dev->setup_abort.

3. gadgetfs_setup() skips setting dev->setup_abort on early returns,
   leaves an uncollected GADGETFS_SETUP event queued when a non-delegated
   request supersedes it, and leaves dev->state in STATE_DEV_SETUP when
   aborting an active delegated transfer so in-kernel responses are not
   queued.

Report EPOLLHUP in ep0_poll() without clearing setup_abort, consume
setup_abort via ep0_check_abort() in ep0_read() and ep0_write(), update
dev->state after next_event() in gadgetfs_disconnect(), and discard any
stale GADGETFS_SETUP event and record setup_abort at the start of
gadgetfs_setup().

Fixes: 1da177e4c3f41 ("Linux-2.6.12-rc2")
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 101 ++++++++++++++++++++++++--------------
 1 file changed, 65 insertions(+), 36 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index a0dc350a7a0d..4915906d782c 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1096,6 +1096,23 @@ static int queue_ep0_req(struct dev_data *dev, bool process_ctx)
 	return ret;
 }
 
+/*
+ * Consume a pending setup abort and report it to userspace.  Called with
+ * dev->lock held.  Return to the connected state so that the next event
+ * read is not misdirected into the control data path, without overwriting
+ * a state that disconnect or unbind already changed.
+ */
+static bool ep0_check_abort(struct dev_data *dev)
+{
+	if (!dev->setup_abort)
+		return false;
+
+	dev->setup_abort = 0;
+	if (dev->state == STATE_DEV_SETUP)
+		dev->state = STATE_DEV_CONNECTED;
+	return true;
+}
+
 static ssize_t
 ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 {
@@ -1110,8 +1127,7 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 	}
 
 	/* report fd mode change before acting on it */
-	if (dev->setup_abort) {
-		dev->setup_abort = 0;
+	if (ep0_check_abort(dev)) {
 		retval = -EIDRM;
 		goto done;
 	}
@@ -1262,11 +1278,29 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 	return retval;
 }
 
+/* Called with dev->lock held.  Drop a queued event of @type, if any. */
+static void ep0_discard_event(struct dev_data *dev,
+			      enum usb_gadgetfs_event_type type)
+{
+	unsigned int			i;
+
+	for (i = 0; i != dev->ev_next; i++) {
+		if (dev->event[i].type != type)
+			continue;
+		DBG(dev, "discard old event[%d] %d\n", i, type);
+		dev->ev_next--;
+		if (i == dev->ev_next)
+			break;
+		/* indices start at zero, for simplicity */
+		memmove(&dev->event[i], &dev->event[i + 1],
+			sizeof(struct usb_gadgetfs_event) * (dev->ev_next - i));
+	}
+}
+
 static struct usb_gadgetfs_event *
 next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
 {
 	struct usb_gadgetfs_event	*event;
-	unsigned			i;
 
 	switch (type) {
 	/* these events purge the queue */
@@ -1280,18 +1314,7 @@ next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
 	case GADGETFS_SETUP:		/* previous request timed out */
 	case GADGETFS_SUSPEND:		/* same effect */
 		/* these events can't be repeated */
-		for (i = 0; i != dev->ev_next; i++) {
-			if (dev->event [i].type != type)
-				continue;
-			DBG(dev, "discard old event[%d] %d\n", i, type);
-			dev->ev_next--;
-			if (i == dev->ev_next)
-				break;
-			/* indices start at zero, for simplicity */
-			memmove (&dev->event [i], &dev->event [i + 1],
-				sizeof (struct usb_gadgetfs_event)
-					* (dev->ev_next - i));
-		}
+		ep0_discard_event(dev, type);
 		break;
 	default:
 		BUG ();
@@ -1311,8 +1334,7 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 	ssize_t			retval = -ESRCH;
 
 	/* report fd mode change before acting on it */
-	if (dev->setup_abort) {
-		dev->setup_abort = 0;
+	if (ep0_check_abort(dev)) {
 		retval = -EIDRM;
 
 	/* data and/or status stage for control request */
@@ -1336,13 +1358,9 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 			 * Reject the write if a new control request arrived
 			 * while dev->lock was dropped for memdup_user().
 			 */
-			if (dev->setup_generation != generation) {
+			if (ep0_check_abort(dev) ||
+			    dev->setup_generation != generation) {
 				kfree(kbuf);
-				if (dev->setup_abort) {
-					dev->setup_abort = 0;
-					if (dev->state == STATE_DEV_SETUP)
-						dev->state = STATE_DEV_CONNECTED;
-				}
 				return -EIDRM;
 			}
 			if (dev->state != STATE_DEV_SETUP || !dev->setup_in) {
@@ -1433,9 +1451,8 @@ ep0_poll (struct file *fd, poll_table *wait)
 
 	spin_lock_irq(&dev->lock);
 
-	/* report fd mode change before acting on it */
+	/* report fd mode change without consuming it before read/write */
 	if (dev->setup_abort) {
-		dev->setup_abort = 0;
 		mask = EPOLLHUP;
 		goto out;
 	}
@@ -1548,6 +1565,24 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 	/* invalidate userspace copies started for an older control request */
 	dev->setup_generation++;
 
+	/*
+	 * If userspace has not collected a previous GADGETFS_SETUP event,
+	 * this SETUP supersedes it; drop it before any early return or
+	 * in-kernel handling so ep0_read() cannot enter STATE_DEV_SETUP
+	 * for an abandoned transfer.
+	 */
+	ep0_discard_event(dev, GADGETFS_SETUP);
+
+	/*
+	 * Record abort of an active delegated transfer and return to the
+	 * connected state before any early return or in-kernel response.
+	 */
+	if (dev->state == STATE_DEV_SETUP) {
+		dev->setup_abort = 1;
+		dev->state = STATE_DEV_CONNECTED;
+		ep0_readable(dev);
+	}
+
 	if (w_length > RBUF_SIZE) {
 		if (ctrl->bRequestType & USB_DIR_IN) {
 			/* Cast away the const, we are going to overwrite on purpose. */
@@ -1564,7 +1599,6 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 		spin_unlock(&dev->lock);
 		return -EBUSY;
 	}
-	dev->setup_abort = 0;
 	if (dev->state == STATE_DEV_UNCONNECTED) {
 		if (gadget_is_dualspeed(gadget)
 				&& gadget->speed == USB_SPEED_HIGH
@@ -1580,14 +1614,7 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 		event = next_event (dev, GADGETFS_CONNECT);
 		event->u.speed = gadget->speed;
 		ep0_readable (dev);
-
-	/* host may have given up waiting for response.  we can miss control
-	 * requests handled lower down (device/endpoint status and features);
-	 * then ep0_{read,write} will report the wrong status. controller
-	 * driver will have aborted pending i/o.
-	 */
-	} else if (dev->state == STATE_DEV_SETUP)
-		dev->setup_abort = 1;
+	}
 
 	req->buf = dev->rbuf;
 	switch (ctrl->bRequest) {
@@ -1937,12 +1964,13 @@ gadgetfs_disconnect (struct usb_gadget *gadget)
 	unsigned long		flags;
 
 	spin_lock_irqsave (&dev->lock, flags);
-	if (dev->state == STATE_DEV_UNCONNECTED)
+	if (dev->state == STATE_DEV_UNCONNECTED ||
+	    dev->state == STATE_DEV_UNBOUND)
 		goto exit;
-	dev->state = STATE_DEV_UNCONNECTED;
 
 	INFO (dev, "disconnected\n");
 	next_event (dev, GADGETFS_DISCONNECT);
+	dev->state = STATE_DEV_UNCONNECTED;
 	ep0_readable (dev);
 exit:
 	spin_unlock_irqrestore (&dev->lock, flags);
@@ -2145,6 +2173,7 @@ gadget_dev_open (struct inode *inode, struct file *fd)
 	spin_lock_irq(&dev->lock);
 	if (dev->state == STATE_DEV_DISABLED) {
 		dev->ev_next = 0;
+		dev->setup_abort = 0;
 		dev->state = STATE_DEV_OPENED;
 		fd->private_data = dev;
 		get_dev (dev);

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 4/6] usb: gadget: gadgetfs: NAK new setups until control-OUT data is read
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
                   ` (2 preceding siblings ...)
  2026-11-26  6:37 ` [PATCH v9 3/6] usb: gadget: gadgetfs: fix ep0 setup_abort tracking and reporting Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 5/6] usb: gadget: gadgetfs: prevent ep0 event counter underflow Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 6/6] usb: gadget: gadgetfs: avoid writing through the const setup pointer Jing Lin via B4 Relay
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

For a delegated 3-stage control-OUT transfer, gadgetfs_setup() submits
the data-stage request immediately and the controller acknowledges the
transfer to the host as soon as it completes, before userspace calls
ep0_read() to collect the payload.  If another control transfer arrives
in the meantime, aborting the earlier state erases the completed
transfer before userspace ever receives it, and reuses dev->req and
dev->rbuf while ep0_read() may be copying to userspace.

When a new setup packet arrives while a properly completed control-OUT
payload has not yet been read by userspace, save the setup packet in
dev->pending_setup and return without submitting an ep0 request so the
controller NAKs the new transfer until ep0_read() finishes copying the
completed payload.  Once the copy completes, replay dev->pending_setup
and stall ep0 with usb_ep_set_halt() if it fails.

Also check dev->setup_wLength == 0 for zero-length status acknowledgments
in ep0_read() and complete them with dev_req_complete() so zero-length
transfers never set setup_out_ready.

Fixes: 1da177e4c3f41 ("Linux-2.6.12-rc2")
Suggested-by: Alan Stern <stern@rowland.harvard.edu>
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 178 ++++++++++++++++++++++++++++++--------
 1 file changed, 140 insertions(+), 38 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 4915906d782c..12ae17f45898 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -143,6 +143,10 @@ struct dev_data {
 	bool				ep0_req_queued;
 	void				*ep0_req_buf;
 	unsigned int			setup_generation;
+	unsigned int			setup_out_len;
+	bool				setup_out_copying;
+	bool				setup_pending;
+	struct usb_ctrlrequest		pending_setup;
 
 	/* the rest is basically write-once */
 	struct usb_config_descriptor	*config, *hs_config;
@@ -1021,23 +1025,25 @@ static void ep0_complete(struct usb_ep *ep, struct usb_request *req)
 {
 	struct dev_data		*dev = req->context;
 	unsigned long		flags;
-	int			free = 1;
 
 	/* for control OUT, data must still get to userspace */
 	spin_lock_irqsave(&dev->lock, flags);
-	if (!dev->setup_in) {
+	if (dev->state == STATE_DEV_CONNECTED ||
+	    dev->state == STATE_DEV_SETUP) {
 		dev->setup_out_error = (req->status != 0);
-		if (!dev->setup_out_error)
-			free = 0;
+		if (dev->setup_out_error) {
+			dev->setup_out_len = 0;
+			clean_req(ep, req);
+		} else {
+			dev->setup_out_len = min_t(unsigned int, req->actual,
+						   sizeof(dev->rbuf));
+			req->complete = dev_req_complete;
+		}
 		dev->setup_out_ready = 1;
 		ep0_readable(dev);
-	}
-
-	/* clean up as appropriate */
-	if (free)
+	} else {
 		clean_req(ep, req);
-	else
-		req->complete = dev_req_complete;
+	}
 	dev->ep0_req_queued = false;
 	wake_up(&dev->wait);
 	spin_unlock_irqrestore(&dev->lock, flags);
@@ -1047,7 +1053,8 @@ static int setup_req(struct usb_ep *ep, struct usb_request *req, u16 len)
 {
 	struct dev_data	*dev = ep->driver_data;
 
-	if (dev->setup_out_ready || dev->ep0_req_queued) {
+	if (dev->setup_out_ready || dev->setup_out_copying ||
+	    dev->ep0_req_queued) {
 		DBG(dev, "ep0 request busy!\n");
 		return -EBUSY;
 	}
@@ -1113,6 +1120,39 @@ static bool ep0_check_abort(struct dev_data *dev)
 	return true;
 }
 
+static int gadgetfs_do_setup(struct dev_data *dev,
+			     const struct usb_ctrlrequest *ctrl,
+			     bool process_ctx);
+
+/*
+ * Replay a SETUP packet that was NAKed while userspace had not yet read
+ * a completed control-OUT data stage.  Called with dev->lock held from
+ * process context (IRQs disabled).
+ */
+static void ep0_process_pending_setup(struct dev_data *dev)
+{
+	struct usb_ctrlrequest	ctrl;
+	int			status;
+
+	if (!dev->setup_pending)
+		return;
+
+	ctrl = dev->pending_setup;
+	dev->setup_pending = false;
+	if (dev->state != STATE_DEV_CONNECTED &&
+	    dev->state != STATE_DEV_UNCONNECTED)
+		return;
+
+	status = gadgetfs_do_setup(dev, &ctrl, true);
+	if (status < 0) {
+		++dev->udc_usage;
+		spin_unlock_irq(&dev->lock);
+		(void)usb_ep_set_halt(dev->gadget->ep0);
+		spin_lock_irq(&dev->lock);
+		--dev->udc_usage;
+	}
+}
+
 static ssize_t
 ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 {
@@ -1141,14 +1181,20 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 			retval = -EL2HLT;
 			dev->state = STATE_DEV_CONNECTED;
 
-		} else if (len == 0) {		/* ack SET_CONFIGURATION etc */
-			struct usb_ep		*ep = dev->gadget->ep0;
+		} else if (dev->setup_wLength == 0) {	/* ack SET_CONFIGURATION etc */
 			struct usb_request	*req = dev->req;
 
-			retval = setup_req(ep, req, 0);
+			if (dev->setup_out_ready || dev->setup_out_copying ||
+			    dev->ep0_req_queued) {
+				retval = -EBUSY;
+				goto done;
+			}
+			req->buf = dev->rbuf;
+			req->complete = dev_req_complete;
+			req->length = 0;
+			req->zero = 0;
 			dev->state = STATE_DEV_CONNECTED;
-			if (retval == 0)
-				retval = queue_ep0_req(dev, true);
+			retval = queue_ep0_req(dev, true);
 
 			/* assume that was SET_CONFIGURATION */
 			if (dev->current_config) {
@@ -1171,32 +1217,47 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 			}
 			spin_unlock_irq (&dev->lock);
 			retval = wait_event_interruptible (dev->wait,
-					dev->setup_out_ready != 0);
+					dev->setup_out_ready ||
+					dev->setup_abort ||
+					dev->state != STATE_DEV_SETUP);
 
-			/* FIXME state could change from under us */
 			spin_lock_irq (&dev->lock);
 			if (retval)
 				goto done;
 
-			if (dev->state != STATE_DEV_SETUP) {
+			if (ep0_check_abort(dev)) {
+				retval = -EIDRM;
+				goto done;
+			}
+			if (dev->state != STATE_DEV_SETUP ||
+			    dev->setup_in || !dev->setup_out_ready) {
 				retval = -ECANCELED;
 				goto done;
 			}
 			dev->state = STATE_DEV_CONNECTED;
 
-			if (dev->setup_out_error)
+			if (dev->setup_out_error) {
+				dev->setup_out_ready = 0;
+				dev->setup_out_error = 0;
+				dev->setup_out_len = 0;
 				retval = -EIO;
-			else {
-				len = min (len, (size_t)dev->req->actual);
+			} else {
+				len = min_t(size_t, len, dev->setup_out_len);
+				dev->setup_out_ready = 0;
+				dev->setup_out_len = 0;
+				dev->setup_out_copying = true;
 				++dev->udc_usage;
 				spin_unlock_irq(&dev->lock);
-				if (copy_to_user (buf, dev->req->buf, len))
+				if (copy_to_user(buf, dev->rbuf, len))
 					retval = -EFAULT;
 				else
 					retval = len;
 				spin_lock_irq(&dev->lock);
 				--dev->udc_usage;
-				clean_req (dev->gadget->ep0, dev->req);
+				dev->setup_out_copying = false;
+				if (dev->req)
+					clean_req(dev->gadget->ep0, dev->req);
+				ep0_process_pending_setup(dev);
 				/* NOTE userspace can't yet choose to stall */
 			}
 		}
@@ -1367,7 +1428,8 @@ ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 				kfree(kbuf);
 				return -ECANCELED;
 			}
-			if (dev->setup_out_ready || dev->ep0_req_queued) {
+			if (dev->setup_out_ready || dev->setup_out_copying ||
+			    dev->ep0_req_queued) {
 				kfree(kbuf);
 				return -EBUSY;
 			}
@@ -1460,6 +1522,8 @@ ep0_poll (struct file *fd, poll_table *wait)
 	if (dev->state == STATE_DEV_SETUP) {
 		if (dev->setup_in || dev->setup_can_stall)
 			mask = EPOLLOUT;
+		else if (dev->setup_out_ready)
+			mask = EPOLLIN;
 	} else {
 		if (dev->ev_next != 0)
 			mask = EPOLLIN;
@@ -1551,19 +1615,23 @@ config_buf (struct dev_data *dev, u8 type, unsigned index)
 	return len;
 }
 
+/* Called with dev->lock held. */
 static int
-gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
+gadgetfs_do_setup(struct dev_data *dev, const struct usb_ctrlrequest *ctrl,
+		  bool process_ctx)
 {
-	struct dev_data			*dev = get_gadget_data (gadget);
+	struct usb_gadget		*gadget = dev->gadget;
 	struct usb_request		*req = dev->req;
 	int				value = -EOPNOTSUPP;
 	struct usb_gadgetfs_event	*event;
 	u16				w_value = le16_to_cpu(ctrl->wValue);
 	u16				w_length = le16_to_cpu(ctrl->wLength);
 
-	spin_lock(&dev->lock);
 	/* invalidate userspace copies started for an older control request */
 	dev->setup_generation++;
+	dev->setup_out_ready = 0;
+	dev->setup_out_error = 0;
+	dev->setup_out_len = 0;
 
 	/*
 	 * If userspace has not collected a previous GADGETFS_SETUP event,
@@ -1591,20 +1659,16 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 			*temp = cpu_to_le16(RBUF_SIZE);
 			w_length = RBUF_SIZE;
 		} else {
-			spin_unlock(&dev->lock);
 			return value;
 		}
 	}
-	if (dev->ep0_req_queued) {
-		spin_unlock(&dev->lock);
+	if (dev->ep0_req_queued)
 		return -EBUSY;
-	}
 	if (dev->state == STATE_DEV_UNCONNECTED) {
 		if (gadget_is_dualspeed(gadget)
 				&& gadget->speed == USB_SPEED_HIGH
 				&& dev->hs_config == NULL) {
-			spin_unlock(&dev->lock);
-			ERROR (dev, "no high speed config??\n");
+			ERROR(dev, "no high speed config??\n");
 			return -EINVAL;
 		}
 
@@ -1725,6 +1789,7 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 			dev->setup_wLength = w_length;
 			dev->setup_out_ready = 0;
 			dev->setup_out_error = 0;
+			dev->setup_out_len = 0;
 
 			/* read DATA stage for OUT right away */
 			if (unlikely(!dev->setup_in && w_length)) {
@@ -1733,7 +1798,7 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 				if (value < 0)
 					break;
 
-				value = queue_ep0_req(dev, false);
+				value = queue_ep0_req(dev, process_ctx);
 				if (value < 0)
 					break;
 
@@ -1745,7 +1810,6 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 			event = next_event (dev, GADGETFS_SETUP);
 			event->u.setup = *ctrl;
 			ep0_readable (dev);
-			spin_unlock (&dev->lock);
 			/*
 			 * Return USB_GADGET_DELAYED_STATUS as a workaround to
 			 * stop some UDC drivers (e.g. dwc3) from automatically
@@ -1765,17 +1829,43 @@ gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
 		req->zero = value < w_length;
 		req->complete = dev_req_complete;
 
-		value = queue_ep0_req(dev, false);
+		value = queue_ep0_req(dev, process_ctx);
 		if (value < 0) {
 			DBG(dev, "ep_queue --> %d\n", value);
 			req->status = 0;
 		}
-		spin_unlock(&dev->lock);
 		return value;
 	}
 
 	/* device stalls when value < 0 */
 	req->buf = dev->rbuf;
+	return value;
+}
+
+static int
+gadgetfs_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
+{
+	struct dev_data		*dev = get_gadget_data(gadget);
+	u16			w_length = le16_to_cpu(ctrl->wLength);
+	int			value;
+
+	spin_lock(&dev->lock);
+	/*
+	 * A properly completed control-OUT transfer has already been
+	 * acknowledged to the host; do not let a new SETUP erase it
+	 * before userspace reads the payload.  Leave ep0 without a
+	 * queued request so the controller NAKs the new transfer until
+	 * ep0_read() finishes collecting the data.
+	 */
+	if ((dev->setup_out_ready && !dev->setup_out_error) ||
+	    dev->setup_out_copying) {
+		dev->pending_setup = *ctrl;
+		dev->setup_pending = true;
+		spin_unlock(&dev->lock);
+		return w_length == 0 ? USB_GADGET_DELAYED_STATUS : 0;
+	}
+	dev->setup_pending = false;
+	value = gadgetfs_do_setup(dev, ctrl, false);
 	spin_unlock(&dev->lock);
 	return value;
 }
@@ -1875,6 +1965,10 @@ gadgetfs_unbind (struct usb_gadget *gadget)
 
 	spin_lock_irq (&dev->lock);
 	dev->state = STATE_DEV_UNBOUND;
+	dev->setup_out_ready = 0;
+	dev->setup_out_error = 0;
+	dev->setup_out_len = 0;
+	dev->setup_pending = false;
 	while (dev->udc_usage > 0) {
 		spin_unlock_irq(&dev->lock);
 		usleep_range(1000, 2000);
@@ -1969,6 +2063,10 @@ gadgetfs_disconnect (struct usb_gadget *gadget)
 		goto exit;
 
 	INFO (dev, "disconnected\n");
+	dev->setup_out_ready = 0;
+	dev->setup_out_error = 0;
+	dev->setup_out_len = 0;
+	dev->setup_pending = false;
 	next_event (dev, GADGETFS_DISCONNECT);
 	dev->state = STATE_DEV_UNCONNECTED;
 	ep0_readable (dev);
@@ -2174,6 +2272,10 @@ gadget_dev_open (struct inode *inode, struct file *fd)
 	if (dev->state == STATE_DEV_DISABLED) {
 		dev->ev_next = 0;
 		dev->setup_abort = 0;
+		dev->setup_out_ready = 0;
+		dev->setup_out_error = 0;
+		dev->setup_out_len = 0;
+		dev->setup_pending = false;
 		dev->state = STATE_DEV_OPENED;
 		fd->private_data = dev;
 		get_dev (dev);

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 5/6] usb: gadget: gadgetfs: prevent ep0 event counter underflow
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
                   ` (3 preceding siblings ...)
  2026-11-26  6:37 ` [PATCH v9 4/6] usb: gadget: gadgetfs: NAK new setups until control-OUT data is read Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  2026-11-26  6:37 ` [PATCH v9 6/6] usb: gadget: gadgetfs: avoid writing through the const setup pointer Jing Lin via B4 Relay
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

ep0_read() snapshots dev->ev_next, drops dev->lock while copy_to_user()
runs directly from dev->event[], and subtracts the snapshot afterwards.
A concurrent disconnect, connect, setup, or another reader can reset,
deduplicate, or consume the queue in that window.  This races on
dev->event[], can drop newly arrived GADGETFS_SETUP events, and wraps
dev->ev_next if the queue shrinks below the snapshot.

Dequeue the events into a local buffer and update dev->ev_next before
dropping dev->lock for copy_to_user().

Fixes: 1da177e4c3f41 ("Linux-2.6.12-rc2")
Cc: stable@vger.kernel.org
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 33 ++++++++++++++-------------------
 1 file changed, 14 insertions(+), 19 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index 12ae17f45898..bd77d0848db2 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1275,39 +1275,34 @@ ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 scan:
 	/* return queued events right away */
 	if (dev->ev_next != 0) {
-		unsigned		i, n;
+		struct usb_gadgetfs_event	events[N_EVENT];
+		unsigned int			i, n;
 
-		n = len / sizeof (struct usb_gadgetfs_event);
+		n = len / sizeof(struct usb_gadgetfs_event);
 		if (dev->ev_next < n)
 			n = dev->ev_next;
 
 		/* ep0 i/o has special semantics during STATE_DEV_SETUP */
 		for (i = 0; i < n; i++) {
-			if (dev->event [i].type == GADGETFS_SETUP) {
+			if (dev->event[i].type == GADGETFS_SETUP) {
 				dev->state = STATE_DEV_SETUP;
 				n = i + 1;
 				break;
 			}
 		}
-		spin_unlock_irq (&dev->lock);
-		len = n * sizeof (struct usb_gadgetfs_event);
-		if (copy_to_user (buf, &dev->event, len))
+		len = n * sizeof(struct usb_gadgetfs_event);
+		memcpy(events, &dev->event, len);
+		if (dev->ev_next > n) {
+			memmove(&dev->event[0], &dev->event[n],
+				sizeof(struct usb_gadgetfs_event)
+					* (dev->ev_next - n));
+		}
+		dev->ev_next -= n;
+		spin_unlock_irq(&dev->lock);
+		if (copy_to_user(buf, events, len))
 			retval = -EFAULT;
 		else
 			retval = len;
-		if (len > 0) {
-			/* NOTE this doesn't guard against broken drivers;
-			 * concurrent ep0 readers may lose events.
-			 */
-			spin_lock_irq (&dev->lock);
-			if (dev->ev_next > n) {
-				memmove(&dev->event[0], &dev->event[n],
-					sizeof (struct usb_gadgetfs_event)
-						* (dev->ev_next - n));
-			}
-			dev->ev_next -= n;
-			spin_unlock_irq (&dev->lock);
-		}
 		return retval;
 	}
 	if (fd->f_flags & O_NONBLOCK) {

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH v9 6/6] usb: gadget: gadgetfs: avoid writing through the const setup pointer
  2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
                   ` (4 preceding siblings ...)
  2026-11-26  6:37 ` [PATCH v9 5/6] usb: gadget: gadgetfs: prevent ep0 event counter underflow Jing Lin via B4 Relay
@ 2026-11-26  6:37 ` Jing Lin via B4 Relay
  5 siblings, 0 replies; 7+ messages in thread
From: Jing Lin via B4 Relay @ 2026-11-26  6:37 UTC (permalink / raw)
  To: Neill Kapron, Greg Kroah-Hartman
  Cc: Alan Stern, linux-usb, linux-kernel, syzbot+c73e1942197af9f54ca3,
	stable, Jing Lin

From: Jing Lin <kayano050408@gmail.com>

gadgetfs_setup() receives the setup packet as const, but clamps an
oversized control-IN request by casting away the constness and writing
the truncated length back into the caller's wLength field.

The setup() callback has no business modifying the setup packet, and
ctrl->wLength is only used afterwards when initializing event->u.setup.
Store the clamped w_length into event->u.setup.wLength directly instead.

Suggested-by: Alan Stern <stern@rowland.harvard.edu>
Signed-off-by: Jing Lin <kayano050408@gmail.com>
---
 drivers/usb/gadget/legacy/inode.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/drivers/usb/gadget/legacy/inode.c b/drivers/usb/gadget/legacy/inode.c
index bd77d0848db2..eb8b0d152d4f 100644
--- a/drivers/usb/gadget/legacy/inode.c
+++ b/drivers/usb/gadget/legacy/inode.c
@@ -1648,10 +1648,6 @@ gadgetfs_do_setup(struct dev_data *dev, const struct usb_ctrlrequest *ctrl,
 
 	if (w_length > RBUF_SIZE) {
 		if (ctrl->bRequestType & USB_DIR_IN) {
-			/* Cast away the const, we are going to overwrite on purpose. */
-			__le16 *temp = (__le16 *)&ctrl->wLength;
-
-			*temp = cpu_to_le16(RBUF_SIZE);
 			w_length = RBUF_SIZE;
 		} else {
 			return value;
@@ -1804,6 +1800,8 @@ gadgetfs_do_setup(struct dev_data *dev, const struct usb_ctrlrequest *ctrl,
 			/* state changes when reader collects event */
 			event = next_event (dev, GADGETFS_SETUP);
 			event->u.setup = *ctrl;
+			/* Report the length we can actually handle */
+			event->u.setup.wLength = cpu_to_le16(w_length);
 			ep0_readable (dev);
 			/*
 			 * Return USB_GADGET_DELAYED_STATUS as a workaround to

-- 
Git-155)



^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-11-26  6:37 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-26  6:37 [PATCH v9 0/6] usb: gadget: gadgetfs: fix ep0 request lifetime and control races Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 1/6] usb: gadget: gadgetfs: fix ep0 request lifetime on unbind Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 2/6] usb: gadget: gadgetfs: isolate ep0_write() buffer and reduce setup race Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 3/6] usb: gadget: gadgetfs: fix ep0 setup_abort tracking and reporting Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 4/6] usb: gadget: gadgetfs: NAK new setups until control-OUT data is read Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 5/6] usb: gadget: gadgetfs: prevent ep0 event counter underflow Jing Lin via B4 Relay
2026-11-26  6:37 ` [PATCH v9 6/6] usb: gadget: gadgetfs: avoid writing through the const setup pointer Jing Lin via B4 Relay

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®