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