diff mbox series

[v2,6/6] USB: gadget: f_hid: return ENODEV from read/write after deletion

Message ID 20191028114228.3679219-7-john@metanate.com (mailing list archive)
State New, archived
Headers show
Series USB: gadget: f_hid: fix lifetime issues | expand

Commit Message

John Keeping Oct. 28, 2019, 11:42 a.m. UTC
If a file descriptor to /dev/hidgN is kept open after the gadget
function has been deleted, reading or writing will block indefinitely
since no requests will ever be processed.

Add a flag to note that the function has been deleted and check this in
read & write if there is no other action to take.  When setting this
flag, also wake up any readers/writers so that they get ENODEV
immediately.

Signed-off-by: John Keeping <john@metanate.com>
---
v2:
- No changes

 drivers/usb/gadget/function/f_hid.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)
diff mbox series

Patch

diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c
index 3d848f7a4cca..a65bdf08ca54 100644
--- a/drivers/usb/gadget/function/f_hid.c
+++ b/drivers/usb/gadget/function/f_hid.c
@@ -59,6 +59,7 @@  struct f_hidg {
 	struct usb_request		*req;
 
 	struct kref			kref;
+	bool				deleted;
 	int				minor;
 	struct usb_function		func;
 
@@ -271,10 +272,14 @@  static ssize_t f_hidg_read(struct file *file, char __user *buffer,
 	/* wait for at least one buffer to complete */
 	while (!READ_COND) {
 		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
+		if (READ_ONCE(hidg->deleted))
+			return -ENODEV;
+
 		if (file->f_flags & O_NONBLOCK)
 			return -EAGAIN;
 
-		if (wait_event_interruptible(hidg->read_queue, READ_COND))
+		if (wait_event_interruptible(hidg->read_queue,
+				READ_COND || READ_ONCE(hidg->deleted)))
 			return -ERESTARTSYS;
 
 		spin_lock_irqsave(&hidg->read_spinlock, flags);
@@ -358,11 +363,14 @@  static ssize_t f_hidg_write(struct file *file, const char __user *buffer,
 	/* write queue */
 	while (!WRITE_COND) {
 		spin_unlock_irqrestore(&hidg->write_spinlock, flags);
+		if (READ_ONCE(hidg->deleted))
+			return -ENODEV;
+
 		if (file->f_flags & O_NONBLOCK)
 			return -EAGAIN;
 
-		if (wait_event_interruptible_exclusive(
-				hidg->write_queue, WRITE_COND))
+		if (wait_event_interruptible_exclusive(hidg->write_queue,
+				WRITE_COND || READ_ONCE(hidg->deleted)))
 			return -ERESTARTSYS;
 
 		spin_lock_irqsave(&hidg->write_spinlock, flags);
@@ -1070,6 +1078,10 @@  static void hidg_free(struct usb_function *f)
 
 	hidg = func_to_hidg(f);
 	opts = container_of(f->fi, struct f_hid_opts, func_inst);
+	WRITE_ONCE(hidg->deleted, true);
+	wake_up(&hidg->read_queue);
+	wake_up(&hidg->write_queue);
+
 	kref_put(&hidg->kref, hidg_release);
 	mutex_lock(&opts->lock);
 	--opts->refcnt;