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