xref: /openbmc/linux/drivers/usb/class/cdc-wdm.c (revision aac5987a)
1 /*
2  * cdc-wdm.c
3  *
4  * This driver supports USB CDC WCM Device Management.
5  *
6  * Copyright (c) 2007-2009 Oliver Neukum
7  *
8  * Some code taken from cdc-acm.c
9  *
10  * Released under the GPLv2.
11  *
12  * Many thanks to Carl Nordbeck
13  */
14 #include <linux/kernel.h>
15 #include <linux/errno.h>
16 #include <linux/ioctl.h>
17 #include <linux/slab.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/uaccess.h>
21 #include <linux/bitops.h>
22 #include <linux/poll.h>
23 #include <linux/usb.h>
24 #include <linux/usb/cdc.h>
25 #include <asm/byteorder.h>
26 #include <asm/unaligned.h>
27 #include <linux/usb/cdc-wdm.h>
28 
29 /*
30  * Version Information
31  */
32 #define DRIVER_VERSION "v0.03"
33 #define DRIVER_AUTHOR "Oliver Neukum"
34 #define DRIVER_DESC "USB Abstract Control Model driver for USB WCM Device Management"
35 
36 static const struct usb_device_id wdm_ids[] = {
37 	{
38 		.match_flags = USB_DEVICE_ID_MATCH_INT_CLASS |
39 				 USB_DEVICE_ID_MATCH_INT_SUBCLASS,
40 		.bInterfaceClass = USB_CLASS_COMM,
41 		.bInterfaceSubClass = USB_CDC_SUBCLASS_DMM
42 	},
43 	{ }
44 };
45 
46 MODULE_DEVICE_TABLE (usb, wdm_ids);
47 
48 #define WDM_MINOR_BASE	176
49 
50 
51 #define WDM_IN_USE		1
52 #define WDM_DISCONNECTING	2
53 #define WDM_RESULT		3
54 #define WDM_READ		4
55 #define WDM_INT_STALL		5
56 #define WDM_POLL_RUNNING	6
57 #define WDM_RESPONDING		7
58 #define WDM_SUSPENDING		8
59 #define WDM_RESETTING		9
60 #define WDM_OVERFLOW		10
61 #define WDM_DRAIN_ON_OPEN	11
62 
63 #define WDM_MAX			16
64 
65 /* CDC-WMC r1.1 requires wMaxCommand to be "at least 256 decimal (0x100)" */
66 #define WDM_DEFAULT_BUFSIZE	256
67 
68 static DEFINE_MUTEX(wdm_mutex);
69 static DEFINE_SPINLOCK(wdm_device_list_lock);
70 static LIST_HEAD(wdm_device_list);
71 
72 /* --- method tables --- */
73 
74 struct wdm_device {
75 	u8			*inbuf; /* buffer for response */
76 	u8			*outbuf; /* buffer for command */
77 	u8			*sbuf; /* buffer for status */
78 	u8			*ubuf; /* buffer for copy to user space */
79 
80 	struct urb		*command;
81 	struct urb		*response;
82 	struct urb		*validity;
83 	struct usb_interface	*intf;
84 	struct usb_ctrlrequest	*orq;
85 	struct usb_ctrlrequest	*irq;
86 	spinlock_t		iuspin;
87 
88 	unsigned long		flags;
89 	u16			bufsize;
90 	u16			wMaxCommand;
91 	u16			wMaxPacketSize;
92 	__le16			inum;
93 	int			reslength;
94 	int			length;
95 	int			read;
96 	int			count;
97 	dma_addr_t		shandle;
98 	dma_addr_t		ihandle;
99 	struct mutex		wlock;
100 	struct mutex		rlock;
101 	wait_queue_head_t	wait;
102 	struct work_struct	rxwork;
103 	int			werr;
104 	int			rerr;
105 	int                     resp_count;
106 
107 	struct list_head	device_list;
108 	int			(*manage_power)(struct usb_interface *, int);
109 };
110 
111 static struct usb_driver wdm_driver;
112 
113 /* return intfdata if we own the interface, else look up intf in the list */
114 static struct wdm_device *wdm_find_device(struct usb_interface *intf)
115 {
116 	struct wdm_device *desc;
117 
118 	spin_lock(&wdm_device_list_lock);
119 	list_for_each_entry(desc, &wdm_device_list, device_list)
120 		if (desc->intf == intf)
121 			goto found;
122 	desc = NULL;
123 found:
124 	spin_unlock(&wdm_device_list_lock);
125 
126 	return desc;
127 }
128 
129 static struct wdm_device *wdm_find_device_by_minor(int minor)
130 {
131 	struct wdm_device *desc;
132 
133 	spin_lock(&wdm_device_list_lock);
134 	list_for_each_entry(desc, &wdm_device_list, device_list)
135 		if (desc->intf->minor == minor)
136 			goto found;
137 	desc = NULL;
138 found:
139 	spin_unlock(&wdm_device_list_lock);
140 
141 	return desc;
142 }
143 
144 /* --- callbacks --- */
145 static void wdm_out_callback(struct urb *urb)
146 {
147 	struct wdm_device *desc;
148 	desc = urb->context;
149 	spin_lock(&desc->iuspin);
150 	desc->werr = urb->status;
151 	spin_unlock(&desc->iuspin);
152 	kfree(desc->outbuf);
153 	desc->outbuf = NULL;
154 	clear_bit(WDM_IN_USE, &desc->flags);
155 	wake_up(&desc->wait);
156 }
157 
158 /* forward declaration */
159 static int service_outstanding_interrupt(struct wdm_device *desc);
160 
161 static void wdm_in_callback(struct urb *urb)
162 {
163 	struct wdm_device *desc = urb->context;
164 	int status = urb->status;
165 	int length = urb->actual_length;
166 
167 	spin_lock(&desc->iuspin);
168 	clear_bit(WDM_RESPONDING, &desc->flags);
169 
170 	if (status) {
171 		switch (status) {
172 		case -ENOENT:
173 			dev_dbg(&desc->intf->dev,
174 				"nonzero urb status received: -ENOENT\n");
175 			goto skip_error;
176 		case -ECONNRESET:
177 			dev_dbg(&desc->intf->dev,
178 				"nonzero urb status received: -ECONNRESET\n");
179 			goto skip_error;
180 		case -ESHUTDOWN:
181 			dev_dbg(&desc->intf->dev,
182 				"nonzero urb status received: -ESHUTDOWN\n");
183 			goto skip_error;
184 		case -EPIPE:
185 			dev_dbg(&desc->intf->dev,
186 				"nonzero urb status received: -EPIPE\n");
187 			break;
188 		default:
189 			dev_err(&desc->intf->dev,
190 				"Unexpected error %d\n", status);
191 			break;
192 		}
193 	}
194 
195 	/*
196 	 * only set a new error if there is no previous error.
197 	 * Errors are only cleared during read/open
198 	 */
199 	if (desc->rerr  == 0)
200 		desc->rerr = status;
201 
202 	if (length + desc->length > desc->wMaxCommand) {
203 		/* The buffer would overflow */
204 		set_bit(WDM_OVERFLOW, &desc->flags);
205 	} else {
206 		/* we may already be in overflow */
207 		if (!test_bit(WDM_OVERFLOW, &desc->flags)) {
208 			memmove(desc->ubuf + desc->length, desc->inbuf, length);
209 			desc->length += length;
210 			desc->reslength = length;
211 		}
212 	}
213 
214 	/*
215 	 * Handling devices with the WDM_DRAIN_ON_OPEN flag set:
216 	 * If desc->resp_count is unset, then the urb was submitted
217 	 * without a prior notification.  If the device returned any
218 	 * data, then this implies that it had messages queued without
219 	 * notifying us.  Continue reading until that queue is flushed.
220 	 */
221 	if (!desc->resp_count) {
222 		if (!length) {
223 			/* do not propagate the expected -EPIPE */
224 			desc->rerr = 0;
225 			goto unlock;
226 		}
227 		dev_dbg(&desc->intf->dev, "got %d bytes without notification\n", length);
228 		set_bit(WDM_RESPONDING, &desc->flags);
229 		usb_submit_urb(desc->response, GFP_ATOMIC);
230 	}
231 
232 skip_error:
233 	set_bit(WDM_READ, &desc->flags);
234 	wake_up(&desc->wait);
235 
236 	if (desc->rerr) {
237 		/*
238 		 * Since there was an error, userspace may decide to not read
239 		 * any data after poll'ing.
240 		 * We should respond to further attempts from the device to send
241 		 * data, so that we can get unstuck.
242 		 */
243 		service_outstanding_interrupt(desc);
244 	}
245 
246 unlock:
247 	spin_unlock(&desc->iuspin);
248 }
249 
250 static void wdm_int_callback(struct urb *urb)
251 {
252 	int rv = 0;
253 	int responding;
254 	int status = urb->status;
255 	struct wdm_device *desc;
256 	struct usb_cdc_notification *dr;
257 
258 	desc = urb->context;
259 	dr = (struct usb_cdc_notification *)desc->sbuf;
260 
261 	if (status) {
262 		switch (status) {
263 		case -ESHUTDOWN:
264 		case -ENOENT:
265 		case -ECONNRESET:
266 			return; /* unplug */
267 		case -EPIPE:
268 			set_bit(WDM_INT_STALL, &desc->flags);
269 			dev_err(&desc->intf->dev, "Stall on int endpoint\n");
270 			goto sw; /* halt is cleared in work */
271 		default:
272 			dev_err(&desc->intf->dev,
273 				"nonzero urb status received: %d\n", status);
274 			break;
275 		}
276 	}
277 
278 	if (urb->actual_length < sizeof(struct usb_cdc_notification)) {
279 		dev_err(&desc->intf->dev, "wdm_int_callback - %d bytes\n",
280 			urb->actual_length);
281 		goto exit;
282 	}
283 
284 	switch (dr->bNotificationType) {
285 	case USB_CDC_NOTIFY_RESPONSE_AVAILABLE:
286 		dev_dbg(&desc->intf->dev,
287 			"NOTIFY_RESPONSE_AVAILABLE received: index %d len %d\n",
288 			le16_to_cpu(dr->wIndex), le16_to_cpu(dr->wLength));
289 		break;
290 
291 	case USB_CDC_NOTIFY_NETWORK_CONNECTION:
292 
293 		dev_dbg(&desc->intf->dev,
294 			"NOTIFY_NETWORK_CONNECTION %s network\n",
295 			dr->wValue ? "connected to" : "disconnected from");
296 		goto exit;
297 	case USB_CDC_NOTIFY_SPEED_CHANGE:
298 		dev_dbg(&desc->intf->dev, "SPEED_CHANGE received (len %u)\n",
299 			urb->actual_length);
300 		goto exit;
301 	default:
302 		clear_bit(WDM_POLL_RUNNING, &desc->flags);
303 		dev_err(&desc->intf->dev,
304 			"unknown notification %d received: index %d len %d\n",
305 			dr->bNotificationType,
306 			le16_to_cpu(dr->wIndex),
307 			le16_to_cpu(dr->wLength));
308 		goto exit;
309 	}
310 
311 	spin_lock(&desc->iuspin);
312 	responding = test_and_set_bit(WDM_RESPONDING, &desc->flags);
313 	if (!desc->resp_count++ && !responding
314 		&& !test_bit(WDM_DISCONNECTING, &desc->flags)
315 		&& !test_bit(WDM_SUSPENDING, &desc->flags)) {
316 		rv = usb_submit_urb(desc->response, GFP_ATOMIC);
317 		dev_dbg(&desc->intf->dev, "submit response URB %d\n", rv);
318 	}
319 	spin_unlock(&desc->iuspin);
320 	if (rv < 0) {
321 		clear_bit(WDM_RESPONDING, &desc->flags);
322 		if (rv == -EPERM)
323 			return;
324 		if (rv == -ENOMEM) {
325 sw:
326 			rv = schedule_work(&desc->rxwork);
327 			if (rv)
328 				dev_err(&desc->intf->dev,
329 					"Cannot schedule work\n");
330 		}
331 	}
332 exit:
333 	rv = usb_submit_urb(urb, GFP_ATOMIC);
334 	if (rv)
335 		dev_err(&desc->intf->dev,
336 			"%s - usb_submit_urb failed with result %d\n",
337 			__func__, rv);
338 
339 }
340 
341 static void kill_urbs(struct wdm_device *desc)
342 {
343 	/* the order here is essential */
344 	usb_kill_urb(desc->command);
345 	usb_kill_urb(desc->validity);
346 	usb_kill_urb(desc->response);
347 }
348 
349 static void free_urbs(struct wdm_device *desc)
350 {
351 	usb_free_urb(desc->validity);
352 	usb_free_urb(desc->response);
353 	usb_free_urb(desc->command);
354 }
355 
356 static void cleanup(struct wdm_device *desc)
357 {
358 	kfree(desc->sbuf);
359 	kfree(desc->inbuf);
360 	kfree(desc->orq);
361 	kfree(desc->irq);
362 	kfree(desc->ubuf);
363 	free_urbs(desc);
364 	kfree(desc);
365 }
366 
367 static ssize_t wdm_write
368 (struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
369 {
370 	u8 *buf;
371 	int rv = -EMSGSIZE, r, we;
372 	struct wdm_device *desc = file->private_data;
373 	struct usb_ctrlrequest *req;
374 
375 	if (count > desc->wMaxCommand)
376 		count = desc->wMaxCommand;
377 
378 	spin_lock_irq(&desc->iuspin);
379 	we = desc->werr;
380 	desc->werr = 0;
381 	spin_unlock_irq(&desc->iuspin);
382 	if (we < 0)
383 		return usb_translate_errors(we);
384 
385 	buf = kmalloc(count, GFP_KERNEL);
386 	if (!buf) {
387 		rv = -ENOMEM;
388 		goto outnl;
389 	}
390 
391 	r = copy_from_user(buf, buffer, count);
392 	if (r > 0) {
393 		rv = -EFAULT;
394 		goto out_free_mem;
395 	}
396 
397 	/* concurrent writes and disconnect */
398 	r = mutex_lock_interruptible(&desc->wlock);
399 	rv = -ERESTARTSYS;
400 	if (r)
401 		goto out_free_mem;
402 
403 	if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
404 		rv = -ENODEV;
405 		goto out_free_mem_lock;
406 	}
407 
408 	r = usb_autopm_get_interface(desc->intf);
409 	if (r < 0) {
410 		rv = usb_translate_errors(r);
411 		goto out_free_mem_lock;
412 	}
413 
414 	if (!(file->f_flags & O_NONBLOCK))
415 		r = wait_event_interruptible(desc->wait, !test_bit(WDM_IN_USE,
416 								&desc->flags));
417 	else
418 		if (test_bit(WDM_IN_USE, &desc->flags))
419 			r = -EAGAIN;
420 
421 	if (test_bit(WDM_RESETTING, &desc->flags))
422 		r = -EIO;
423 
424 	if (r < 0) {
425 		rv = r;
426 		goto out_free_mem_pm;
427 	}
428 
429 	req = desc->orq;
430 	usb_fill_control_urb(
431 		desc->command,
432 		interface_to_usbdev(desc->intf),
433 		/* using common endpoint 0 */
434 		usb_sndctrlpipe(interface_to_usbdev(desc->intf), 0),
435 		(unsigned char *)req,
436 		buf,
437 		count,
438 		wdm_out_callback,
439 		desc
440 	);
441 
442 	req->bRequestType = (USB_DIR_OUT | USB_TYPE_CLASS |
443 			     USB_RECIP_INTERFACE);
444 	req->bRequest = USB_CDC_SEND_ENCAPSULATED_COMMAND;
445 	req->wValue = 0;
446 	req->wIndex = desc->inum; /* already converted */
447 	req->wLength = cpu_to_le16(count);
448 	set_bit(WDM_IN_USE, &desc->flags);
449 	desc->outbuf = buf;
450 
451 	rv = usb_submit_urb(desc->command, GFP_KERNEL);
452 	if (rv < 0) {
453 		desc->outbuf = NULL;
454 		clear_bit(WDM_IN_USE, &desc->flags);
455 		dev_err(&desc->intf->dev, "Tx URB error: %d\n", rv);
456 		rv = usb_translate_errors(rv);
457 		goto out_free_mem_pm;
458 	} else {
459 		dev_dbg(&desc->intf->dev, "Tx URB has been submitted index=%d\n",
460 			le16_to_cpu(req->wIndex));
461 	}
462 
463 	usb_autopm_put_interface(desc->intf);
464 	mutex_unlock(&desc->wlock);
465 outnl:
466 	return rv < 0 ? rv : count;
467 
468 out_free_mem_pm:
469 	usb_autopm_put_interface(desc->intf);
470 out_free_mem_lock:
471 	mutex_unlock(&desc->wlock);
472 out_free_mem:
473 	kfree(buf);
474 	return rv;
475 }
476 
477 /*
478  * Submit the read urb if resp_count is non-zero.
479  *
480  * Called with desc->iuspin locked
481  */
482 static int service_outstanding_interrupt(struct wdm_device *desc)
483 {
484 	int rv = 0;
485 
486 	/* submit read urb only if the device is waiting for it */
487 	if (!desc->resp_count || !--desc->resp_count)
488 		goto out;
489 
490 	set_bit(WDM_RESPONDING, &desc->flags);
491 	spin_unlock_irq(&desc->iuspin);
492 	rv = usb_submit_urb(desc->response, GFP_KERNEL);
493 	spin_lock_irq(&desc->iuspin);
494 	if (rv) {
495 		dev_err(&desc->intf->dev,
496 			"usb_submit_urb failed with result %d\n", rv);
497 
498 		/* make sure the next notification trigger a submit */
499 		clear_bit(WDM_RESPONDING, &desc->flags);
500 		desc->resp_count = 0;
501 	}
502 out:
503 	return rv;
504 }
505 
506 static ssize_t wdm_read
507 (struct file *file, char __user *buffer, size_t count, loff_t *ppos)
508 {
509 	int rv, cntr;
510 	int i = 0;
511 	struct wdm_device *desc = file->private_data;
512 
513 
514 	rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
515 	if (rv < 0)
516 		return -ERESTARTSYS;
517 
518 	cntr = ACCESS_ONCE(desc->length);
519 	if (cntr == 0) {
520 		desc->read = 0;
521 retry:
522 		if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
523 			rv = -ENODEV;
524 			goto err;
525 		}
526 		if (test_bit(WDM_OVERFLOW, &desc->flags)) {
527 			clear_bit(WDM_OVERFLOW, &desc->flags);
528 			rv = -ENOBUFS;
529 			goto err;
530 		}
531 		i++;
532 		if (file->f_flags & O_NONBLOCK) {
533 			if (!test_bit(WDM_READ, &desc->flags)) {
534 				rv = -EAGAIN;
535 				goto err;
536 			}
537 			rv = 0;
538 		} else {
539 			rv = wait_event_interruptible(desc->wait,
540 				test_bit(WDM_READ, &desc->flags));
541 		}
542 
543 		/* may have happened while we slept */
544 		if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
545 			rv = -ENODEV;
546 			goto err;
547 		}
548 		if (test_bit(WDM_RESETTING, &desc->flags)) {
549 			rv = -EIO;
550 			goto err;
551 		}
552 		usb_mark_last_busy(interface_to_usbdev(desc->intf));
553 		if (rv < 0) {
554 			rv = -ERESTARTSYS;
555 			goto err;
556 		}
557 
558 		spin_lock_irq(&desc->iuspin);
559 
560 		if (desc->rerr) { /* read completed, error happened */
561 			rv = usb_translate_errors(desc->rerr);
562 			desc->rerr = 0;
563 			spin_unlock_irq(&desc->iuspin);
564 			goto err;
565 		}
566 		/*
567 		 * recheck whether we've lost the race
568 		 * against the completion handler
569 		 */
570 		if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
571 			spin_unlock_irq(&desc->iuspin);
572 			goto retry;
573 		}
574 
575 		if (!desc->reslength) { /* zero length read */
576 			dev_dbg(&desc->intf->dev, "zero length - clearing WDM_READ\n");
577 			clear_bit(WDM_READ, &desc->flags);
578 			rv = service_outstanding_interrupt(desc);
579 			spin_unlock_irq(&desc->iuspin);
580 			if (rv < 0)
581 				goto err;
582 			goto retry;
583 		}
584 		cntr = desc->length;
585 		spin_unlock_irq(&desc->iuspin);
586 	}
587 
588 	if (cntr > count)
589 		cntr = count;
590 	rv = copy_to_user(buffer, desc->ubuf, cntr);
591 	if (rv > 0) {
592 		rv = -EFAULT;
593 		goto err;
594 	}
595 
596 	spin_lock_irq(&desc->iuspin);
597 
598 	for (i = 0; i < desc->length - cntr; i++)
599 		desc->ubuf[i] = desc->ubuf[i + cntr];
600 
601 	desc->length -= cntr;
602 	/* in case we had outstanding data */
603 	if (!desc->length) {
604 		clear_bit(WDM_READ, &desc->flags);
605 		service_outstanding_interrupt(desc);
606 	}
607 	spin_unlock_irq(&desc->iuspin);
608 	rv = cntr;
609 
610 err:
611 	mutex_unlock(&desc->rlock);
612 	return rv;
613 }
614 
615 static int wdm_flush(struct file *file, fl_owner_t id)
616 {
617 	struct wdm_device *desc = file->private_data;
618 
619 	wait_event(desc->wait, !test_bit(WDM_IN_USE, &desc->flags));
620 
621 	/* cannot dereference desc->intf if WDM_DISCONNECTING */
622 	if (desc->werr < 0 && !test_bit(WDM_DISCONNECTING, &desc->flags))
623 		dev_err(&desc->intf->dev, "Error in flush path: %d\n",
624 			desc->werr);
625 
626 	return usb_translate_errors(desc->werr);
627 }
628 
629 static unsigned int wdm_poll(struct file *file, struct poll_table_struct *wait)
630 {
631 	struct wdm_device *desc = file->private_data;
632 	unsigned long flags;
633 	unsigned int mask = 0;
634 
635 	spin_lock_irqsave(&desc->iuspin, flags);
636 	if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
637 		mask = POLLHUP | POLLERR;
638 		spin_unlock_irqrestore(&desc->iuspin, flags);
639 		goto desc_out;
640 	}
641 	if (test_bit(WDM_READ, &desc->flags))
642 		mask = POLLIN | POLLRDNORM;
643 	if (desc->rerr || desc->werr)
644 		mask |= POLLERR;
645 	if (!test_bit(WDM_IN_USE, &desc->flags))
646 		mask |= POLLOUT | POLLWRNORM;
647 	spin_unlock_irqrestore(&desc->iuspin, flags);
648 
649 	poll_wait(file, &desc->wait, wait);
650 
651 desc_out:
652 	return mask;
653 }
654 
655 static int wdm_open(struct inode *inode, struct file *file)
656 {
657 	int minor = iminor(inode);
658 	int rv = -ENODEV;
659 	struct usb_interface *intf;
660 	struct wdm_device *desc;
661 
662 	mutex_lock(&wdm_mutex);
663 	desc = wdm_find_device_by_minor(minor);
664 	if (!desc)
665 		goto out;
666 
667 	intf = desc->intf;
668 	if (test_bit(WDM_DISCONNECTING, &desc->flags))
669 		goto out;
670 	file->private_data = desc;
671 
672 	rv = usb_autopm_get_interface(desc->intf);
673 	if (rv < 0) {
674 		dev_err(&desc->intf->dev, "Error autopm - %d\n", rv);
675 		goto out;
676 	}
677 
678 	/* using write lock to protect desc->count */
679 	mutex_lock(&desc->wlock);
680 	if (!desc->count++) {
681 		desc->werr = 0;
682 		desc->rerr = 0;
683 		rv = usb_submit_urb(desc->validity, GFP_KERNEL);
684 		if (rv < 0) {
685 			desc->count--;
686 			dev_err(&desc->intf->dev,
687 				"Error submitting int urb - %d\n", rv);
688 			rv = usb_translate_errors(rv);
689 		} else if (test_bit(WDM_DRAIN_ON_OPEN, &desc->flags)) {
690 			/*
691 			 * Some devices keep pending messages queued
692 			 * without resending notifications.  We must
693 			 * flush the message queue before we can
694 			 * assume a one-to-one relationship between
695 			 * notifications and messages in the queue
696 			 */
697 			dev_dbg(&desc->intf->dev, "draining queued data\n");
698 			set_bit(WDM_RESPONDING, &desc->flags);
699 			rv = usb_submit_urb(desc->response, GFP_KERNEL);
700 		}
701 	} else {
702 		rv = 0;
703 	}
704 	mutex_unlock(&desc->wlock);
705 	if (desc->count == 1)
706 		desc->manage_power(intf, 1);
707 	usb_autopm_put_interface(desc->intf);
708 out:
709 	mutex_unlock(&wdm_mutex);
710 	return rv;
711 }
712 
713 static int wdm_release(struct inode *inode, struct file *file)
714 {
715 	struct wdm_device *desc = file->private_data;
716 
717 	mutex_lock(&wdm_mutex);
718 
719 	/* using write lock to protect desc->count */
720 	mutex_lock(&desc->wlock);
721 	desc->count--;
722 	mutex_unlock(&desc->wlock);
723 
724 	if (!desc->count) {
725 		if (!test_bit(WDM_DISCONNECTING, &desc->flags)) {
726 			dev_dbg(&desc->intf->dev, "wdm_release: cleanup\n");
727 			kill_urbs(desc);
728 			spin_lock_irq(&desc->iuspin);
729 			desc->resp_count = 0;
730 			spin_unlock_irq(&desc->iuspin);
731 			desc->manage_power(desc->intf, 0);
732 		} else {
733 			/* must avoid dev_printk here as desc->intf is invalid */
734 			pr_debug(KBUILD_MODNAME " %s: device gone - cleaning up\n", __func__);
735 			cleanup(desc);
736 		}
737 	}
738 	mutex_unlock(&wdm_mutex);
739 	return 0;
740 }
741 
742 static long wdm_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
743 {
744 	struct wdm_device *desc = file->private_data;
745 	int rv = 0;
746 
747 	switch (cmd) {
748 	case IOCTL_WDM_MAX_COMMAND:
749 		if (copy_to_user((void __user *)arg, &desc->wMaxCommand, sizeof(desc->wMaxCommand)))
750 			rv = -EFAULT;
751 		break;
752 	default:
753 		rv = -ENOTTY;
754 	}
755 	return rv;
756 }
757 
758 static const struct file_operations wdm_fops = {
759 	.owner =	THIS_MODULE,
760 	.read =		wdm_read,
761 	.write =	wdm_write,
762 	.open =		wdm_open,
763 	.flush =	wdm_flush,
764 	.release =	wdm_release,
765 	.poll =		wdm_poll,
766 	.unlocked_ioctl = wdm_ioctl,
767 	.compat_ioctl = wdm_ioctl,
768 	.llseek =	noop_llseek,
769 };
770 
771 static struct usb_class_driver wdm_class = {
772 	.name =		"cdc-wdm%d",
773 	.fops =		&wdm_fops,
774 	.minor_base =	WDM_MINOR_BASE,
775 };
776 
777 /* --- error handling --- */
778 static void wdm_rxwork(struct work_struct *work)
779 {
780 	struct wdm_device *desc = container_of(work, struct wdm_device, rxwork);
781 	unsigned long flags;
782 	int rv = 0;
783 	int responding;
784 
785 	spin_lock_irqsave(&desc->iuspin, flags);
786 	if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
787 		spin_unlock_irqrestore(&desc->iuspin, flags);
788 	} else {
789 		responding = test_and_set_bit(WDM_RESPONDING, &desc->flags);
790 		spin_unlock_irqrestore(&desc->iuspin, flags);
791 		if (!responding)
792 			rv = usb_submit_urb(desc->response, GFP_KERNEL);
793 		if (rv < 0 && rv != -EPERM) {
794 			spin_lock_irqsave(&desc->iuspin, flags);
795 			clear_bit(WDM_RESPONDING, &desc->flags);
796 			if (!test_bit(WDM_DISCONNECTING, &desc->flags))
797 				schedule_work(&desc->rxwork);
798 			spin_unlock_irqrestore(&desc->iuspin, flags);
799 		}
800 	}
801 }
802 
803 /* --- hotplug --- */
804 
805 static int wdm_create(struct usb_interface *intf, struct usb_endpoint_descriptor *ep,
806 		u16 bufsize, int (*manage_power)(struct usb_interface *, int),
807 		bool drain_on_open)
808 {
809 	int rv = -ENOMEM;
810 	struct wdm_device *desc;
811 
812 	desc = kzalloc(sizeof(struct wdm_device), GFP_KERNEL);
813 	if (!desc)
814 		goto out;
815 	INIT_LIST_HEAD(&desc->device_list);
816 	mutex_init(&desc->rlock);
817 	mutex_init(&desc->wlock);
818 	spin_lock_init(&desc->iuspin);
819 	init_waitqueue_head(&desc->wait);
820 	desc->wMaxCommand = bufsize;
821 	/* this will be expanded and needed in hardware endianness */
822 	desc->inum = cpu_to_le16((u16)intf->cur_altsetting->desc.bInterfaceNumber);
823 	desc->intf = intf;
824 	INIT_WORK(&desc->rxwork, wdm_rxwork);
825 
826 	rv = -EINVAL;
827 	if (!usb_endpoint_is_int_in(ep))
828 		goto err;
829 
830 	desc->wMaxPacketSize = usb_endpoint_maxp(ep);
831 
832 	desc->orq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
833 	if (!desc->orq)
834 		goto err;
835 	desc->irq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
836 	if (!desc->irq)
837 		goto err;
838 
839 	desc->validity = usb_alloc_urb(0, GFP_KERNEL);
840 	if (!desc->validity)
841 		goto err;
842 
843 	desc->response = usb_alloc_urb(0, GFP_KERNEL);
844 	if (!desc->response)
845 		goto err;
846 
847 	desc->command = usb_alloc_urb(0, GFP_KERNEL);
848 	if (!desc->command)
849 		goto err;
850 
851 	desc->ubuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
852 	if (!desc->ubuf)
853 		goto err;
854 
855 	desc->sbuf = kmalloc(desc->wMaxPacketSize, GFP_KERNEL);
856 	if (!desc->sbuf)
857 		goto err;
858 
859 	desc->inbuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
860 	if (!desc->inbuf)
861 		goto err;
862 
863 	usb_fill_int_urb(
864 		desc->validity,
865 		interface_to_usbdev(intf),
866 		usb_rcvintpipe(interface_to_usbdev(intf), ep->bEndpointAddress),
867 		desc->sbuf,
868 		desc->wMaxPacketSize,
869 		wdm_int_callback,
870 		desc,
871 		ep->bInterval
872 	);
873 
874 	desc->irq->bRequestType = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE);
875 	desc->irq->bRequest = USB_CDC_GET_ENCAPSULATED_RESPONSE;
876 	desc->irq->wValue = 0;
877 	desc->irq->wIndex = desc->inum; /* already converted */
878 	desc->irq->wLength = cpu_to_le16(desc->wMaxCommand);
879 
880 	usb_fill_control_urb(
881 		desc->response,
882 		interface_to_usbdev(intf),
883 		/* using common endpoint 0 */
884 		usb_rcvctrlpipe(interface_to_usbdev(desc->intf), 0),
885 		(unsigned char *)desc->irq,
886 		desc->inbuf,
887 		desc->wMaxCommand,
888 		wdm_in_callback,
889 		desc
890 	);
891 
892 	desc->manage_power = manage_power;
893 
894 	/*
895 	 * "drain_on_open" enables a hack to work around a firmware
896 	 * issue observed on network functions, in particular MBIM
897 	 * functions.
898 	 *
899 	 * Quoting section 7 of the CDC-WMC r1.1 specification:
900 	 *
901 	 *  "The firmware shall interpret GetEncapsulatedResponse as a
902 	 *   request to read response bytes. The firmware shall send
903 	 *   the next wLength bytes from the response. The firmware
904 	 *   shall allow the host to retrieve data using any number of
905 	 *   GetEncapsulatedResponse requests. The firmware shall
906 	 *   return a zero- length reply if there are no data bytes
907 	 *   available.
908 	 *
909 	 *   The firmware shall send ResponseAvailable notifications
910 	 *   periodically, using any appropriate algorithm, to inform
911 	 *   the host that there is data available in the reply
912 	 *   buffer. The firmware is allowed to send ResponseAvailable
913 	 *   notifications even if there is no data available, but
914 	 *   this will obviously reduce overall performance."
915 	 *
916 	 * These requirements, although they make equally sense, are
917 	 * often not implemented by network functions. Some firmwares
918 	 * will queue data indefinitely, without ever resending a
919 	 * notification. The result is that the driver and firmware
920 	 * loses "syncronization" if the driver ever fails to respond
921 	 * to a single notification, something which easily can happen
922 	 * on release(). When this happens, the driver will appear to
923 	 * never receive notifications for the most current data. Each
924 	 * notification will only cause a single read, which returns
925 	 * the oldest data in the firmware's queue.
926 	 *
927 	 * The "drain_on_open" hack resolves the situation by draining
928 	 * data from the firmware until none is returned, without a
929 	 * prior notification.
930 	 *
931 	 * This will inevitably race with the firmware, risking that
932 	 * we read data from the device before handling the associated
933 	 * notification. To make things worse, some of the devices
934 	 * needing the hack do not implement the "return zero if no
935 	 * data is available" requirement either. Instead they return
936 	 * an error on the subsequent read in this case.  This means
937 	 * that "winning" the race can cause an unexpected EIO to
938 	 * userspace.
939 	 *
940 	 * "winning" the race is more likely on resume() than on
941 	 * open(), and the unexpected error is more harmful in the
942 	 * middle of an open session. The hack is therefore only
943 	 * applied on open(), and not on resume() where it logically
944 	 * would be equally necessary. So we define open() as the only
945 	 * driver <-> device "syncronization point".  Should we happen
946 	 * to lose a notification after open(), then syncronization
947 	 * will be lost until release()
948 	 *
949 	 * The hack should not be enabled for CDC WDM devices
950 	 * conforming to the CDC-WMC r1.1 specification.  This is
951 	 * ensured by setting drain_on_open to false in wdm_probe().
952 	 */
953 	if (drain_on_open)
954 		set_bit(WDM_DRAIN_ON_OPEN, &desc->flags);
955 
956 	spin_lock(&wdm_device_list_lock);
957 	list_add(&desc->device_list, &wdm_device_list);
958 	spin_unlock(&wdm_device_list_lock);
959 
960 	rv = usb_register_dev(intf, &wdm_class);
961 	if (rv < 0)
962 		goto err;
963 	else
964 		dev_info(&intf->dev, "%s: USB WDM device\n", dev_name(intf->usb_dev));
965 out:
966 	return rv;
967 err:
968 	spin_lock(&wdm_device_list_lock);
969 	list_del(&desc->device_list);
970 	spin_unlock(&wdm_device_list_lock);
971 	cleanup(desc);
972 	return rv;
973 }
974 
975 static int wdm_manage_power(struct usb_interface *intf, int on)
976 {
977 	/* need autopm_get/put here to ensure the usbcore sees the new value */
978 	int rv = usb_autopm_get_interface(intf);
979 
980 	intf->needs_remote_wakeup = on;
981 	if (!rv)
982 		usb_autopm_put_interface(intf);
983 	return 0;
984 }
985 
986 static int wdm_probe(struct usb_interface *intf, const struct usb_device_id *id)
987 {
988 	int rv = -EINVAL;
989 	struct usb_host_interface *iface;
990 	struct usb_endpoint_descriptor *ep;
991 	struct usb_cdc_parsed_header hdr;
992 	u8 *buffer = intf->altsetting->extra;
993 	int buflen = intf->altsetting->extralen;
994 	u16 maxcom = WDM_DEFAULT_BUFSIZE;
995 
996 	if (!buffer)
997 		goto err;
998 
999 	cdc_parse_cdc_header(&hdr, intf, buffer, buflen);
1000 
1001 	if (hdr.usb_cdc_dmm_desc)
1002 		maxcom = le16_to_cpu(hdr.usb_cdc_dmm_desc->wMaxCommand);
1003 
1004 	iface = intf->cur_altsetting;
1005 	if (iface->desc.bNumEndpoints != 1)
1006 		goto err;
1007 	ep = &iface->endpoint[0].desc;
1008 
1009 	rv = wdm_create(intf, ep, maxcom, &wdm_manage_power, false);
1010 
1011 err:
1012 	return rv;
1013 }
1014 
1015 /**
1016  * usb_cdc_wdm_register - register a WDM subdriver
1017  * @intf: usb interface the subdriver will associate with
1018  * @ep: interrupt endpoint to monitor for notifications
1019  * @bufsize: maximum message size to support for read/write
1020  *
1021  * Create WDM usb class character device and associate it with intf
1022  * without binding, allowing another driver to manage the interface.
1023  *
1024  * The subdriver will manage the given interrupt endpoint exclusively
1025  * and will issue control requests referring to the given intf. It
1026  * will otherwise avoid interferring, and in particular not do
1027  * usb_set_intfdata/usb_get_intfdata on intf.
1028  *
1029  * The return value is a pointer to the subdriver's struct usb_driver.
1030  * The registering driver is responsible for calling this subdriver's
1031  * disconnect, suspend, resume, pre_reset and post_reset methods from
1032  * its own.
1033  */
1034 struct usb_driver *usb_cdc_wdm_register(struct usb_interface *intf,
1035 					struct usb_endpoint_descriptor *ep,
1036 					int bufsize,
1037 					int (*manage_power)(struct usb_interface *, int))
1038 {
1039 	int rv = -EINVAL;
1040 
1041 	rv = wdm_create(intf, ep, bufsize, manage_power, true);
1042 	if (rv < 0)
1043 		goto err;
1044 
1045 	return &wdm_driver;
1046 err:
1047 	return ERR_PTR(rv);
1048 }
1049 EXPORT_SYMBOL(usb_cdc_wdm_register);
1050 
1051 static void wdm_disconnect(struct usb_interface *intf)
1052 {
1053 	struct wdm_device *desc;
1054 	unsigned long flags;
1055 
1056 	usb_deregister_dev(intf, &wdm_class);
1057 	desc = wdm_find_device(intf);
1058 	mutex_lock(&wdm_mutex);
1059 
1060 	/* the spinlock makes sure no new urbs are generated in the callbacks */
1061 	spin_lock_irqsave(&desc->iuspin, flags);
1062 	set_bit(WDM_DISCONNECTING, &desc->flags);
1063 	set_bit(WDM_READ, &desc->flags);
1064 	/* to terminate pending flushes */
1065 	clear_bit(WDM_IN_USE, &desc->flags);
1066 	spin_unlock_irqrestore(&desc->iuspin, flags);
1067 	wake_up_all(&desc->wait);
1068 	mutex_lock(&desc->rlock);
1069 	mutex_lock(&desc->wlock);
1070 	kill_urbs(desc);
1071 	cancel_work_sync(&desc->rxwork);
1072 	mutex_unlock(&desc->wlock);
1073 	mutex_unlock(&desc->rlock);
1074 
1075 	/* the desc->intf pointer used as list key is now invalid */
1076 	spin_lock(&wdm_device_list_lock);
1077 	list_del(&desc->device_list);
1078 	spin_unlock(&wdm_device_list_lock);
1079 
1080 	if (!desc->count)
1081 		cleanup(desc);
1082 	else
1083 		dev_dbg(&intf->dev, "%d open files - postponing cleanup\n", desc->count);
1084 	mutex_unlock(&wdm_mutex);
1085 }
1086 
1087 #ifdef CONFIG_PM
1088 static int wdm_suspend(struct usb_interface *intf, pm_message_t message)
1089 {
1090 	struct wdm_device *desc = wdm_find_device(intf);
1091 	int rv = 0;
1092 
1093 	dev_dbg(&desc->intf->dev, "wdm%d_suspend\n", intf->minor);
1094 
1095 	/* if this is an autosuspend the caller does the locking */
1096 	if (!PMSG_IS_AUTO(message)) {
1097 		mutex_lock(&desc->rlock);
1098 		mutex_lock(&desc->wlock);
1099 	}
1100 	spin_lock_irq(&desc->iuspin);
1101 
1102 	if (PMSG_IS_AUTO(message) &&
1103 			(test_bit(WDM_IN_USE, &desc->flags)
1104 			|| test_bit(WDM_RESPONDING, &desc->flags))) {
1105 		spin_unlock_irq(&desc->iuspin);
1106 		rv = -EBUSY;
1107 	} else {
1108 
1109 		set_bit(WDM_SUSPENDING, &desc->flags);
1110 		spin_unlock_irq(&desc->iuspin);
1111 		/* callback submits work - order is essential */
1112 		kill_urbs(desc);
1113 		cancel_work_sync(&desc->rxwork);
1114 	}
1115 	if (!PMSG_IS_AUTO(message)) {
1116 		mutex_unlock(&desc->wlock);
1117 		mutex_unlock(&desc->rlock);
1118 	}
1119 
1120 	return rv;
1121 }
1122 #endif
1123 
1124 static int recover_from_urb_loss(struct wdm_device *desc)
1125 {
1126 	int rv = 0;
1127 
1128 	if (desc->count) {
1129 		rv = usb_submit_urb(desc->validity, GFP_NOIO);
1130 		if (rv < 0)
1131 			dev_err(&desc->intf->dev,
1132 				"Error resume submitting int urb - %d\n", rv);
1133 	}
1134 	return rv;
1135 }
1136 
1137 #ifdef CONFIG_PM
1138 static int wdm_resume(struct usb_interface *intf)
1139 {
1140 	struct wdm_device *desc = wdm_find_device(intf);
1141 	int rv;
1142 
1143 	dev_dbg(&desc->intf->dev, "wdm%d_resume\n", intf->minor);
1144 
1145 	clear_bit(WDM_SUSPENDING, &desc->flags);
1146 	rv = recover_from_urb_loss(desc);
1147 
1148 	return rv;
1149 }
1150 #endif
1151 
1152 static int wdm_pre_reset(struct usb_interface *intf)
1153 {
1154 	struct wdm_device *desc = wdm_find_device(intf);
1155 
1156 	/*
1157 	 * we notify everybody using poll of
1158 	 * an exceptional situation
1159 	 * must be done before recovery lest a spontaneous
1160 	 * message from the device is lost
1161 	 */
1162 	spin_lock_irq(&desc->iuspin);
1163 	set_bit(WDM_RESETTING, &desc->flags);	/* inform read/write */
1164 	set_bit(WDM_READ, &desc->flags);	/* unblock read */
1165 	clear_bit(WDM_IN_USE, &desc->flags);	/* unblock write */
1166 	desc->rerr = -EINTR;
1167 	spin_unlock_irq(&desc->iuspin);
1168 	wake_up_all(&desc->wait);
1169 	mutex_lock(&desc->rlock);
1170 	mutex_lock(&desc->wlock);
1171 	kill_urbs(desc);
1172 	cancel_work_sync(&desc->rxwork);
1173 	return 0;
1174 }
1175 
1176 static int wdm_post_reset(struct usb_interface *intf)
1177 {
1178 	struct wdm_device *desc = wdm_find_device(intf);
1179 	int rv;
1180 
1181 	clear_bit(WDM_OVERFLOW, &desc->flags);
1182 	clear_bit(WDM_RESETTING, &desc->flags);
1183 	rv = recover_from_urb_loss(desc);
1184 	mutex_unlock(&desc->wlock);
1185 	mutex_unlock(&desc->rlock);
1186 	return 0;
1187 }
1188 
1189 static struct usb_driver wdm_driver = {
1190 	.name =		"cdc_wdm",
1191 	.probe =	wdm_probe,
1192 	.disconnect =	wdm_disconnect,
1193 #ifdef CONFIG_PM
1194 	.suspend =	wdm_suspend,
1195 	.resume =	wdm_resume,
1196 	.reset_resume =	wdm_resume,
1197 #endif
1198 	.pre_reset =	wdm_pre_reset,
1199 	.post_reset =	wdm_post_reset,
1200 	.id_table =	wdm_ids,
1201 	.supports_autosuspend = 1,
1202 	.disable_hub_initiated_lpm = 1,
1203 };
1204 
1205 module_usb_driver(wdm_driver);
1206 
1207 MODULE_AUTHOR(DRIVER_AUTHOR);
1208 MODULE_DESCRIPTION(DRIVER_DESC);
1209 MODULE_LICENSE("GPL");
1210