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