GNU Linux-libre 4.4.284-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 static void wdm_in_callback(struct urb *urb)
161 {
162         struct wdm_device *desc = urb->context;
163         int status = urb->status;
164         int length = urb->actual_length;
165
166         spin_lock(&desc->iuspin);
167         clear_bit(WDM_RESPONDING, &desc->flags);
168
169         if (status) {
170                 switch (status) {
171                 case -ENOENT:
172                         dev_dbg(&desc->intf->dev,
173                                 "nonzero urb status received: -ENOENT");
174                         goto skip_error;
175                 case -ECONNRESET:
176                         dev_dbg(&desc->intf->dev,
177                                 "nonzero urb status received: -ECONNRESET");
178                         goto skip_error;
179                 case -ESHUTDOWN:
180                         dev_dbg(&desc->intf->dev,
181                                 "nonzero urb status received: -ESHUTDOWN");
182                         goto skip_error;
183                 case -EPIPE:
184                         dev_err(&desc->intf->dev,
185                                 "nonzero urb status received: -EPIPE\n");
186                         break;
187                 default:
188                         dev_err(&desc->intf->dev,
189                                 "Unexpected error %d\n", status);
190                         break;
191                 }
192         }
193
194         desc->rerr = status;
195         if (length + desc->length > desc->wMaxCommand) {
196                 /* The buffer would overflow */
197                 set_bit(WDM_OVERFLOW, &desc->flags);
198         } else {
199                 /* we may already be in overflow */
200                 if (!test_bit(WDM_OVERFLOW, &desc->flags)) {
201                         memmove(desc->ubuf + desc->length, desc->inbuf, length);
202                         desc->length += length;
203                         desc->reslength = length;
204                 }
205         }
206 skip_error:
207         wake_up(&desc->wait);
208
209         set_bit(WDM_READ, &desc->flags);
210         spin_unlock(&desc->iuspin);
211 }
212
213 static void wdm_int_callback(struct urb *urb)
214 {
215         int rv = 0;
216         int responding;
217         int status = urb->status;
218         struct wdm_device *desc;
219         struct usb_cdc_notification *dr;
220
221         desc = urb->context;
222         dr = (struct usb_cdc_notification *)desc->sbuf;
223
224         if (status) {
225                 switch (status) {
226                 case -ESHUTDOWN:
227                 case -ENOENT:
228                 case -ECONNRESET:
229                         return; /* unplug */
230                 case -EPIPE:
231                         set_bit(WDM_INT_STALL, &desc->flags);
232                         dev_err(&desc->intf->dev, "Stall on int endpoint\n");
233                         goto sw; /* halt is cleared in work */
234                 default:
235                         dev_err(&desc->intf->dev,
236                                 "nonzero urb status received: %d\n", status);
237                         break;
238                 }
239         }
240
241         if (urb->actual_length < sizeof(struct usb_cdc_notification)) {
242                 dev_err(&desc->intf->dev, "wdm_int_callback - %d bytes\n",
243                         urb->actual_length);
244                 goto exit;
245         }
246
247         switch (dr->bNotificationType) {
248         case USB_CDC_NOTIFY_RESPONSE_AVAILABLE:
249                 dev_dbg(&desc->intf->dev,
250                         "NOTIFY_RESPONSE_AVAILABLE received: index %d len %d",
251                         le16_to_cpu(dr->wIndex), le16_to_cpu(dr->wLength));
252                 break;
253
254         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
255
256                 dev_dbg(&desc->intf->dev,
257                         "NOTIFY_NETWORK_CONNECTION %s network",
258                         dr->wValue ? "connected to" : "disconnected from");
259                 goto exit;
260         case USB_CDC_NOTIFY_SPEED_CHANGE:
261                 dev_dbg(&desc->intf->dev, "SPEED_CHANGE received (len %u)",
262                         urb->actual_length);
263                 goto exit;
264         default:
265                 clear_bit(WDM_POLL_RUNNING, &desc->flags);
266                 dev_err(&desc->intf->dev,
267                         "unknown notification %d received: index %d len %d\n",
268                         dr->bNotificationType,
269                         le16_to_cpu(dr->wIndex),
270                         le16_to_cpu(dr->wLength));
271                 goto exit;
272         }
273
274         spin_lock(&desc->iuspin);
275         responding = test_and_set_bit(WDM_RESPONDING, &desc->flags);
276         if (!desc->resp_count++ && !responding
277                 && !test_bit(WDM_DISCONNECTING, &desc->flags)
278                 && !test_bit(WDM_SUSPENDING, &desc->flags)) {
279                 rv = usb_submit_urb(desc->response, GFP_ATOMIC);
280                 dev_dbg(&desc->intf->dev, "%s: usb_submit_urb %d",
281                         __func__, rv);
282         }
283         spin_unlock(&desc->iuspin);
284         if (rv < 0) {
285                 clear_bit(WDM_RESPONDING, &desc->flags);
286                 if (rv == -EPERM)
287                         return;
288                 if (rv == -ENOMEM) {
289 sw:
290                         rv = schedule_work(&desc->rxwork);
291                         if (rv)
292                                 dev_err(&desc->intf->dev,
293                                         "Cannot schedule work\n");
294                 }
295         }
296 exit:
297         rv = usb_submit_urb(urb, GFP_ATOMIC);
298         if (rv)
299                 dev_err(&desc->intf->dev,
300                         "%s - usb_submit_urb failed with result %d\n",
301                         __func__, rv);
302
303 }
304
305 static void kill_urbs(struct wdm_device *desc)
306 {
307         /* the order here is essential */
308         usb_kill_urb(desc->command);
309         usb_kill_urb(desc->validity);
310         usb_kill_urb(desc->response);
311 }
312
313 static void free_urbs(struct wdm_device *desc)
314 {
315         usb_free_urb(desc->validity);
316         usb_free_urb(desc->response);
317         usb_free_urb(desc->command);
318 }
319
320 static void cleanup(struct wdm_device *desc)
321 {
322         kfree(desc->sbuf);
323         kfree(desc->inbuf);
324         kfree(desc->orq);
325         kfree(desc->irq);
326         kfree(desc->ubuf);
327         free_urbs(desc);
328         kfree(desc);
329 }
330
331 static ssize_t wdm_write
332 (struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
333 {
334         u8 *buf;
335         int rv = -EMSGSIZE, r, we;
336         struct wdm_device *desc = file->private_data;
337         struct usb_ctrlrequest *req;
338
339         if (count > desc->wMaxCommand)
340                 count = desc->wMaxCommand;
341
342         spin_lock_irq(&desc->iuspin);
343         we = desc->werr;
344         desc->werr = 0;
345         spin_unlock_irq(&desc->iuspin);
346         if (we < 0)
347                 return usb_translate_errors(we);
348
349         buf = kmalloc(count, GFP_KERNEL);
350         if (!buf) {
351                 rv = -ENOMEM;
352                 goto outnl;
353         }
354
355         r = copy_from_user(buf, buffer, count);
356         if (r > 0) {
357                 rv = -EFAULT;
358                 goto out_free_mem;
359         }
360
361         /* concurrent writes and disconnect */
362         r = mutex_lock_interruptible(&desc->wlock);
363         rv = -ERESTARTSYS;
364         if (r)
365                 goto out_free_mem;
366
367         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
368                 rv = -ENODEV;
369                 goto out_free_mem_lock;
370         }
371
372         r = usb_autopm_get_interface(desc->intf);
373         if (r < 0) {
374                 rv = usb_translate_errors(r);
375                 goto out_free_mem_lock;
376         }
377
378         if (!(file->f_flags & O_NONBLOCK))
379                 r = wait_event_interruptible(desc->wait, !test_bit(WDM_IN_USE,
380                                                                 &desc->flags));
381         else
382                 if (test_bit(WDM_IN_USE, &desc->flags))
383                         r = -EAGAIN;
384
385         if (test_bit(WDM_RESETTING, &desc->flags))
386                 r = -EIO;
387
388         if (test_bit(WDM_DISCONNECTING, &desc->flags))
389                 r = -ENODEV;
390
391         if (r < 0) {
392                 rv = r;
393                 goto out_free_mem_pm;
394         }
395
396         req = desc->orq;
397         usb_fill_control_urb(
398                 desc->command,
399                 interface_to_usbdev(desc->intf),
400                 /* using common endpoint 0 */
401                 usb_sndctrlpipe(interface_to_usbdev(desc->intf), 0),
402                 (unsigned char *)req,
403                 buf,
404                 count,
405                 wdm_out_callback,
406                 desc
407         );
408
409         req->bRequestType = (USB_DIR_OUT | USB_TYPE_CLASS |
410                              USB_RECIP_INTERFACE);
411         req->bRequest = USB_CDC_SEND_ENCAPSULATED_COMMAND;
412         req->wValue = 0;
413         req->wIndex = desc->inum; /* already converted */
414         req->wLength = cpu_to_le16(count);
415         set_bit(WDM_IN_USE, &desc->flags);
416         desc->outbuf = buf;
417
418         rv = usb_submit_urb(desc->command, GFP_KERNEL);
419         if (rv < 0) {
420                 desc->outbuf = NULL;
421                 clear_bit(WDM_IN_USE, &desc->flags);
422                 wake_up_all(&desc->wait); /* for wdm_wait_for_response() */
423                 dev_err(&desc->intf->dev, "Tx URB error: %d\n", rv);
424                 rv = usb_translate_errors(rv);
425                 goto out_free_mem_pm;
426         } else {
427                 dev_dbg(&desc->intf->dev, "Tx URB has been submitted index=%d",
428                         le16_to_cpu(req->wIndex));
429         }
430
431         usb_autopm_put_interface(desc->intf);
432         mutex_unlock(&desc->wlock);
433 outnl:
434         return rv < 0 ? rv : count;
435
436 out_free_mem_pm:
437         usb_autopm_put_interface(desc->intf);
438 out_free_mem_lock:
439         mutex_unlock(&desc->wlock);
440 out_free_mem:
441         kfree(buf);
442         return rv;
443 }
444
445 /*
446  * clear WDM_READ flag and possibly submit the read urb if resp_count
447  * is non-zero.
448  *
449  * Called with desc->iuspin locked
450  */
451 static int clear_wdm_read_flag(struct wdm_device *desc)
452 {
453         int rv = 0;
454
455         clear_bit(WDM_READ, &desc->flags);
456
457         /* submit read urb only if the device is waiting for it */
458         if (!desc->resp_count || !--desc->resp_count)
459                 goto out;
460
461         set_bit(WDM_RESPONDING, &desc->flags);
462         spin_unlock_irq(&desc->iuspin);
463         rv = usb_submit_urb(desc->response, GFP_KERNEL);
464         spin_lock_irq(&desc->iuspin);
465         if (rv) {
466                 dev_err(&desc->intf->dev,
467                         "usb_submit_urb failed with result %d\n", rv);
468
469                 /* make sure the next notification trigger a submit */
470                 clear_bit(WDM_RESPONDING, &desc->flags);
471                 desc->resp_count = 0;
472         }
473 out:
474         return rv;
475 }
476
477 static ssize_t wdm_read
478 (struct file *file, char __user *buffer, size_t count, loff_t *ppos)
479 {
480         int rv, cntr;
481         int i = 0;
482         struct wdm_device *desc = file->private_data;
483
484
485         rv = mutex_lock_interruptible(&desc->rlock); /*concurrent reads */
486         if (rv < 0)
487                 return -ERESTARTSYS;
488
489         cntr = ACCESS_ONCE(desc->length);
490         if (cntr == 0) {
491                 desc->read = 0;
492 retry:
493                 if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
494                         rv = -ENODEV;
495                         goto err;
496                 }
497                 if (test_bit(WDM_OVERFLOW, &desc->flags)) {
498                         clear_bit(WDM_OVERFLOW, &desc->flags);
499                         rv = -ENOBUFS;
500                         goto err;
501                 }
502                 i++;
503                 if (file->f_flags & O_NONBLOCK) {
504                         if (!test_bit(WDM_READ, &desc->flags)) {
505                                 rv = cntr ? cntr : -EAGAIN;
506                                 goto err;
507                         }
508                         rv = 0;
509                 } else {
510                         rv = wait_event_interruptible(desc->wait,
511                                 test_bit(WDM_READ, &desc->flags));
512                 }
513
514                 /* may have happened while we slept */
515                 if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
516                         rv = -ENODEV;
517                         goto err;
518                 }
519                 if (test_bit(WDM_RESETTING, &desc->flags)) {
520                         rv = -EIO;
521                         goto err;
522                 }
523                 usb_mark_last_busy(interface_to_usbdev(desc->intf));
524                 if (rv < 0) {
525                         rv = -ERESTARTSYS;
526                         goto err;
527                 }
528
529                 spin_lock_irq(&desc->iuspin);
530
531                 if (desc->rerr) { /* read completed, error happened */
532                         rv = usb_translate_errors(desc->rerr);
533                         desc->rerr = 0;
534                         spin_unlock_irq(&desc->iuspin);
535                         goto err;
536                 }
537                 /*
538                  * recheck whether we've lost the race
539                  * against the completion handler
540                  */
541                 if (!test_bit(WDM_READ, &desc->flags)) { /* lost race */
542                         spin_unlock_irq(&desc->iuspin);
543                         goto retry;
544                 }
545
546                 if (!desc->reslength) { /* zero length read */
547                         dev_dbg(&desc->intf->dev, "%s: zero length - clearing WDM_READ\n", __func__);
548                         rv = clear_wdm_read_flag(desc);
549                         spin_unlock_irq(&desc->iuspin);
550                         if (rv < 0)
551                                 goto err;
552                         goto retry;
553                 }
554                 cntr = desc->length;
555                 spin_unlock_irq(&desc->iuspin);
556         }
557
558         if (cntr > count)
559                 cntr = count;
560         rv = copy_to_user(buffer, desc->ubuf, cntr);
561         if (rv > 0) {
562                 rv = -EFAULT;
563                 goto err;
564         }
565
566         spin_lock_irq(&desc->iuspin);
567
568         for (i = 0; i < desc->length - cntr; i++)
569                 desc->ubuf[i] = desc->ubuf[i + cntr];
570
571         desc->length -= cntr;
572         /* in case we had outstanding data */
573         if (!desc->length)
574                 clear_wdm_read_flag(desc);
575         spin_unlock_irq(&desc->iuspin);
576         rv = cntr;
577
578 err:
579         mutex_unlock(&desc->rlock);
580         return rv;
581 }
582
583 static int wdm_wait_for_response(struct file *file, long timeout)
584 {
585         struct wdm_device *desc = file->private_data;
586         long rv; /* Use long here because (int) MAX_SCHEDULE_TIMEOUT < 0. */
587
588         /*
589          * Needs both flags. We cannot do with one because resetting it would
590          * cause a race with write() yet we need to signal a disconnect.
591          */
592         rv = wait_event_interruptible_timeout(desc->wait,
593                               !test_bit(WDM_IN_USE, &desc->flags) ||
594                               test_bit(WDM_DISCONNECTING, &desc->flags),
595                               timeout);
596
597         /*
598          * To report the correct error. This is best effort.
599          * We are inevitably racing with the hardware.
600          */
601         if (test_bit(WDM_DISCONNECTING, &desc->flags))
602                 return -ENODEV;
603         if (!rv)
604                 return -EIO;
605         if (rv < 0)
606                 return -EINTR;
607
608         spin_lock_irq(&desc->iuspin);
609         rv = desc->werr;
610         desc->werr = 0;
611         spin_unlock_irq(&desc->iuspin);
612
613         return usb_translate_errors(rv);
614
615 }
616
617 /*
618  * You need to send a signal when you react to malicious or defective hardware.
619  * Also, don't abort when fsync() returned -EINVAL, for older kernels which do
620  * not implement wdm_flush() will return -EINVAL.
621  */
622 static int wdm_fsync(struct file *file, loff_t start, loff_t end, int datasync)
623 {
624         return wdm_wait_for_response(file, MAX_SCHEDULE_TIMEOUT);
625 }
626
627 /*
628  * Same with wdm_fsync(), except it uses finite timeout in order to react to
629  * malicious or defective hardware which ceased communication after close() was
630  * implicitly called due to process termination.
631  */
632 static int wdm_flush(struct file *file, fl_owner_t id)
633 {
634         return wdm_wait_for_response(file, WDM_FLUSH_TIMEOUT);
635 }
636
637 static unsigned int wdm_poll(struct file *file, struct poll_table_struct *wait)
638 {
639         struct wdm_device *desc = file->private_data;
640         unsigned long flags;
641         unsigned int mask = 0;
642
643         spin_lock_irqsave(&desc->iuspin, flags);
644         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
645                 mask = POLLHUP | POLLERR;
646                 spin_unlock_irqrestore(&desc->iuspin, flags);
647                 goto desc_out;
648         }
649         if (test_bit(WDM_READ, &desc->flags))
650                 mask = POLLIN | POLLRDNORM;
651         if (desc->rerr || desc->werr)
652                 mask |= POLLERR;
653         if (!test_bit(WDM_IN_USE, &desc->flags))
654                 mask |= POLLOUT | POLLWRNORM;
655         spin_unlock_irqrestore(&desc->iuspin, flags);
656
657         poll_wait(file, &desc->wait, wait);
658
659 desc_out:
660         return mask;
661 }
662
663 static int wdm_open(struct inode *inode, struct file *file)
664 {
665         int minor = iminor(inode);
666         int rv = -ENODEV;
667         struct usb_interface *intf;
668         struct wdm_device *desc;
669
670         mutex_lock(&wdm_mutex);
671         desc = wdm_find_device_by_minor(minor);
672         if (!desc)
673                 goto out;
674
675         intf = desc->intf;
676         if (test_bit(WDM_DISCONNECTING, &desc->flags))
677                 goto out;
678         file->private_data = desc;
679
680         rv = usb_autopm_get_interface(desc->intf);
681         if (rv < 0) {
682                 dev_err(&desc->intf->dev, "Error autopm - %d\n", rv);
683                 goto out;
684         }
685
686         /* using write lock to protect desc->count */
687         mutex_lock(&desc->wlock);
688         if (!desc->count++) {
689                 desc->werr = 0;
690                 desc->rerr = 0;
691                 rv = usb_submit_urb(desc->validity, GFP_KERNEL);
692                 if (rv < 0) {
693                         desc->count--;
694                         dev_err(&desc->intf->dev,
695                                 "Error submitting int urb - %d\n", rv);
696                         rv = usb_translate_errors(rv);
697                 }
698         } else {
699                 rv = 0;
700         }
701         mutex_unlock(&desc->wlock);
702         if (desc->count == 1)
703                 desc->manage_power(intf, 1);
704         usb_autopm_put_interface(desc->intf);
705 out:
706         mutex_unlock(&wdm_mutex);
707         return rv;
708 }
709
710 static int wdm_release(struct inode *inode, struct file *file)
711 {
712         struct wdm_device *desc = file->private_data;
713
714         mutex_lock(&wdm_mutex);
715
716         /* using write lock to protect desc->count */
717         mutex_lock(&desc->wlock);
718         desc->count--;
719         mutex_unlock(&desc->wlock);
720
721         if (!desc->count) {
722                 if (!test_bit(WDM_DISCONNECTING, &desc->flags)) {
723                         dev_dbg(&desc->intf->dev, "wdm_release: cleanup");
724                         kill_urbs(desc);
725                         spin_lock_irq(&desc->iuspin);
726                         desc->resp_count = 0;
727                         spin_unlock_irq(&desc->iuspin);
728                         desc->manage_power(desc->intf, 0);
729                 } else {
730                         /* must avoid dev_printk here as desc->intf is invalid */
731                         pr_debug(KBUILD_MODNAME " %s: device gone - cleaning up\n", __func__);
732                         cleanup(desc);
733                 }
734         }
735         mutex_unlock(&wdm_mutex);
736         return 0;
737 }
738
739 static long wdm_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
740 {
741         struct wdm_device *desc = file->private_data;
742         int rv = 0;
743
744         switch (cmd) {
745         case IOCTL_WDM_MAX_COMMAND:
746                 if (copy_to_user((void __user *)arg, &desc->wMaxCommand, sizeof(desc->wMaxCommand)))
747                         rv = -EFAULT;
748                 break;
749         default:
750                 rv = -ENOTTY;
751         }
752         return rv;
753 }
754
755 static const struct file_operations wdm_fops = {
756         .owner =        THIS_MODULE,
757         .read =         wdm_read,
758         .write =        wdm_write,
759         .fsync =        wdm_fsync,
760         .open =         wdm_open,
761         .flush =        wdm_flush,
762         .release =      wdm_release,
763         .poll =         wdm_poll,
764         .unlocked_ioctl = wdm_ioctl,
765         .compat_ioctl = wdm_ioctl,
766         .llseek =       noop_llseek,
767 };
768
769 static struct usb_class_driver wdm_class = {
770         .name =         "cdc-wdm%d",
771         .fops =         &wdm_fops,
772         .minor_base =   WDM_MINOR_BASE,
773 };
774
775 /* --- error handling --- */
776 static void wdm_rxwork(struct work_struct *work)
777 {
778         struct wdm_device *desc = container_of(work, struct wdm_device, rxwork);
779         unsigned long flags;
780         int rv = 0;
781         int responding;
782
783         spin_lock_irqsave(&desc->iuspin, flags);
784         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
785                 spin_unlock_irqrestore(&desc->iuspin, flags);
786         } else {
787                 responding = test_and_set_bit(WDM_RESPONDING, &desc->flags);
788                 spin_unlock_irqrestore(&desc->iuspin, flags);
789                 if (!responding)
790                         rv = usb_submit_urb(desc->response, GFP_KERNEL);
791                 if (rv < 0 && rv != -EPERM) {
792                         spin_lock_irqsave(&desc->iuspin, flags);
793                         clear_bit(WDM_RESPONDING, &desc->flags);
794                         if (!test_bit(WDM_DISCONNECTING, &desc->flags))
795                                 schedule_work(&desc->rxwork);
796                         spin_unlock_irqrestore(&desc->iuspin, flags);
797                 }
798         }
799 }
800
801 /* --- hotplug --- */
802
803 static int wdm_create(struct usb_interface *intf, struct usb_endpoint_descriptor *ep,
804                 u16 bufsize, int (*manage_power)(struct usb_interface *, int))
805 {
806         int rv = -ENOMEM;
807         struct wdm_device *desc;
808
809         desc = kzalloc(sizeof(struct wdm_device), GFP_KERNEL);
810         if (!desc)
811                 goto out;
812         INIT_LIST_HEAD(&desc->device_list);
813         mutex_init(&desc->rlock);
814         mutex_init(&desc->wlock);
815         spin_lock_init(&desc->iuspin);
816         init_waitqueue_head(&desc->wait);
817         desc->wMaxCommand = bufsize;
818         /* this will be expanded and needed in hardware endianness */
819         desc->inum = cpu_to_le16((u16)intf->cur_altsetting->desc.bInterfaceNumber);
820         desc->intf = intf;
821         INIT_WORK(&desc->rxwork, wdm_rxwork);
822
823         rv = -EINVAL;
824         if (!usb_endpoint_is_int_in(ep))
825                 goto err;
826
827         desc->wMaxPacketSize = usb_endpoint_maxp(ep);
828
829         desc->orq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
830         if (!desc->orq)
831                 goto err;
832         desc->irq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
833         if (!desc->irq)
834                 goto err;
835
836         desc->validity = usb_alloc_urb(0, GFP_KERNEL);
837         if (!desc->validity)
838                 goto err;
839
840         desc->response = usb_alloc_urb(0, GFP_KERNEL);
841         if (!desc->response)
842                 goto err;
843
844         desc->command = usb_alloc_urb(0, GFP_KERNEL);
845         if (!desc->command)
846                 goto err;
847
848         desc->ubuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
849         if (!desc->ubuf)
850                 goto err;
851
852         desc->sbuf = kmalloc(desc->wMaxPacketSize, GFP_KERNEL);
853         if (!desc->sbuf)
854                 goto err;
855
856         desc->inbuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
857         if (!desc->inbuf)
858                 goto err;
859
860         usb_fill_int_urb(
861                 desc->validity,
862                 interface_to_usbdev(intf),
863                 usb_rcvintpipe(interface_to_usbdev(intf), ep->bEndpointAddress),
864                 desc->sbuf,
865                 desc->wMaxPacketSize,
866                 wdm_int_callback,
867                 desc,
868                 ep->bInterval
869         );
870
871         desc->irq->bRequestType = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE);
872         desc->irq->bRequest = USB_CDC_GET_ENCAPSULATED_RESPONSE;
873         desc->irq->wValue = 0;
874         desc->irq->wIndex = desc->inum; /* already converted */
875         desc->irq->wLength = cpu_to_le16(desc->wMaxCommand);
876
877         usb_fill_control_urb(
878                 desc->response,
879                 interface_to_usbdev(intf),
880                 /* using common endpoint 0 */
881                 usb_rcvctrlpipe(interface_to_usbdev(desc->intf), 0),
882                 (unsigned char *)desc->irq,
883                 desc->inbuf,
884                 desc->wMaxCommand,
885                 wdm_in_callback,
886                 desc
887         );
888
889         desc->manage_power = manage_power;
890
891         spin_lock(&wdm_device_list_lock);
892         list_add(&desc->device_list, &wdm_device_list);
893         spin_unlock(&wdm_device_list_lock);
894
895         rv = usb_register_dev(intf, &wdm_class);
896         if (rv < 0)
897                 goto err;
898         else
899                 dev_info(&intf->dev, "%s: USB WDM device\n", dev_name(intf->usb_dev));
900 out:
901         return rv;
902 err:
903         spin_lock(&wdm_device_list_lock);
904         list_del(&desc->device_list);
905         spin_unlock(&wdm_device_list_lock);
906         cleanup(desc);
907         return rv;
908 }
909
910 static int wdm_manage_power(struct usb_interface *intf, int on)
911 {
912         /* need autopm_get/put here to ensure the usbcore sees the new value */
913         int rv = usb_autopm_get_interface(intf);
914
915         intf->needs_remote_wakeup = on;
916         if (!rv)
917                 usb_autopm_put_interface(intf);
918         return 0;
919 }
920
921 static int wdm_probe(struct usb_interface *intf, const struct usb_device_id *id)
922 {
923         int rv = -EINVAL;
924         struct usb_host_interface *iface;
925         struct usb_endpoint_descriptor *ep;
926         struct usb_cdc_dmm_desc *dmhd;
927         u8 *buffer = intf->altsetting->extra;
928         int buflen = intf->altsetting->extralen;
929         u16 maxcom = WDM_DEFAULT_BUFSIZE;
930
931         if (!buffer)
932                 goto err;
933         while (buflen > 2) {
934                 if (buffer[1] != USB_DT_CS_INTERFACE) {
935                         dev_err(&intf->dev, "skipping garbage\n");
936                         goto next_desc;
937                 }
938
939                 switch (buffer[2]) {
940                 case USB_CDC_HEADER_TYPE:
941                         break;
942                 case USB_CDC_DMM_TYPE:
943                         dmhd = (struct usb_cdc_dmm_desc *)buffer;
944                         maxcom = le16_to_cpu(dmhd->wMaxCommand);
945                         dev_dbg(&intf->dev,
946                                 "Finding maximum buffer length: %d", maxcom);
947                         break;
948                 default:
949                         dev_err(&intf->dev,
950                                 "Ignoring extra header, type %d, length %d\n",
951                                 buffer[2], buffer[0]);
952                         break;
953                 }
954 next_desc:
955                 buflen -= buffer[0];
956                 buffer += buffer[0];
957         }
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, "%s: %d open files - postponing cleanup\n", __func__, 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");