xen/events: reset active flag for lateeoi events later
[linux-2.6-microblaze.git] / drivers / usb / class / cdc-wdm.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * cdc-wdm.c
4  *
5  * This driver supports USB CDC WCM Device Management.
6  *
7  * Copyright (c) 2007-2009 Oliver Neukum
8  *
9  * Some code taken from cdc-acm.c
10  *
11  * Released under the GPLv2.
12  *
13  * Many thanks to Carl Nordbeck
14  */
15 #include <linux/kernel.h>
16 #include <linux/errno.h>
17 #include <linux/ioctl.h>
18 #include <linux/slab.h>
19 #include <linux/module.h>
20 #include <linux/mutex.h>
21 #include <linux/uaccess.h>
22 #include <linux/bitops.h>
23 #include <linux/poll.h>
24 #include <linux/usb.h>
25 #include <linux/usb/cdc.h>
26 #include <asm/byteorder.h>
27 #include <asm/unaligned.h>
28 #include <linux/usb/cdc-wdm.h>
29
30 #define DRIVER_AUTHOR "Oliver Neukum"
31 #define DRIVER_DESC "USB Abstract Control Model driver for USB WCM Device Management"
32
33 static const struct usb_device_id wdm_ids[] = {
34         {
35                 .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS |
36                                  USB_DEVICE_ID_MATCH_INT_SUBCLASS,
37                 .bInterfaceClass = USB_CLASS_COMM,
38                 .bInterfaceSubClass = USB_CDC_SUBCLASS_DMM
39         },
40         { }
41 };
42
43 MODULE_DEVICE_TABLE (usb, wdm_ids);
44
45 #define WDM_MINOR_BASE  176
46
47
48 #define WDM_IN_USE              1
49 #define WDM_DISCONNECTING       2
50 #define WDM_RESULT              3
51 #define WDM_READ                4
52 #define WDM_INT_STALL           5
53 #define WDM_POLL_RUNNING        6
54 #define WDM_RESPONDING          7
55 #define WDM_SUSPENDING          8
56 #define WDM_RESETTING           9
57 #define WDM_OVERFLOW            10
58
59 #define WDM_MAX                 16
60
61 /* we cannot wait forever at flush() */
62 #define WDM_FLUSH_TIMEOUT       (30 * HZ)
63
64 /* CDC-WMC r1.1 requires wMaxCommand to be "at least 256 decimal (0x100)" */
65 #define WDM_DEFAULT_BUFSIZE     256
66
67 static DEFINE_MUTEX(wdm_mutex);
68 static DEFINE_SPINLOCK(wdm_device_list_lock);
69 static LIST_HEAD(wdm_device_list);
70
71 /* --- method tables --- */
72
73 struct wdm_device {
74         u8                      *inbuf; /* buffer for response */
75         u8                      *outbuf; /* buffer for command */
76         u8                      *sbuf; /* buffer for status */
77         u8                      *ubuf; /* buffer for copy to user space */
78
79         struct urb              *command;
80         struct urb              *response;
81         struct urb              *validity;
82         struct usb_interface    *intf;
83         struct usb_ctrlrequest  *orq;
84         struct usb_ctrlrequest  *irq;
85         spinlock_t              iuspin;
86
87         unsigned long           flags;
88         u16                     bufsize;
89         u16                     wMaxCommand;
90         u16                     wMaxPacketSize;
91         __le16                  inum;
92         int                     reslength;
93         int                     length;
94         int                     read;
95         int                     count;
96         dma_addr_t              shandle;
97         dma_addr_t              ihandle;
98         struct mutex            wlock;
99         struct mutex            rlock;
100         wait_queue_head_t       wait;
101         struct work_struct      rxwork;
102         struct work_struct      service_outs_intr;
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         unsigned long flags;
149
150         desc = urb->context;
151         spin_lock_irqsave(&desc->iuspin, flags);
152         desc->werr = urb->status;
153         spin_unlock_irqrestore(&desc->iuspin, flags);
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         unsigned long flags;
163         struct wdm_device *desc = urb->context;
164         int status = urb->status;
165         int length = urb->actual_length;
166
167         spin_lock_irqsave(&desc->iuspin, flags);
168         clear_bit(WDM_RESPONDING, &desc->flags);
169
170         if (status) {
171                 switch (status) {
172                 case -ENOENT:
173                         dev_dbg(&desc->intf->dev,
174                                 "nonzero urb status received: -ENOENT\n");
175                         goto skip_error;
176                 case -ECONNRESET:
177                         dev_dbg(&desc->intf->dev,
178                                 "nonzero urb status received: -ECONNRESET\n");
179                         goto skip_error;
180                 case -ESHUTDOWN:
181                         dev_dbg(&desc->intf->dev,
182                                 "nonzero urb status received: -ESHUTDOWN\n");
183                         goto skip_error;
184                 case -EPIPE:
185                         dev_err(&desc->intf->dev,
186                                 "nonzero urb status received: -EPIPE\n");
187                         break;
188                 default:
189                         dev_err(&desc->intf->dev,
190                                 "Unexpected error %d\n", status);
191                         break;
192                 }
193         }
194
195         /*
196          * only set a new error if there is no previous error.
197          * Errors are only cleared during read/open
198          * Avoid propagating -EPIPE (stall) to userspace since it is
199          * better handled as an empty read
200          */
201         if (desc->rerr == 0 && status != -EPIPE)
202                 desc->rerr = status;
203
204         if (length + desc->length > desc->wMaxCommand) {
205                 /* The buffer would overflow */
206                 set_bit(WDM_OVERFLOW, &desc->flags);
207         } else {
208                 /* we may already be in overflow */
209                 if (!test_bit(WDM_OVERFLOW, &desc->flags)) {
210                         memmove(desc->ubuf + desc->length, desc->inbuf, length);
211                         desc->length += length;
212                         desc->reslength = length;
213                 }
214         }
215 skip_error:
216
217         if (desc->rerr) {
218                 /*
219                  * Since there was an error, userspace may decide to not read
220                  * any data after poll'ing.
221                  * We should respond to further attempts from the device to send
222                  * data, so that we can get unstuck.
223                  */
224                 schedule_work(&desc->service_outs_intr);
225         } else {
226                 set_bit(WDM_READ, &desc->flags);
227                 wake_up(&desc->wait);
228         }
229         spin_unlock_irqrestore(&desc->iuspin, flags);
230 }
231
232 static void wdm_int_callback(struct urb *urb)
233 {
234         unsigned long flags;
235         int rv = 0;
236         int responding;
237         int status = urb->status;
238         struct wdm_device *desc;
239         struct usb_cdc_notification *dr;
240
241         desc = urb->context;
242         dr = (struct usb_cdc_notification *)desc->sbuf;
243
244         if (status) {
245                 switch (status) {
246                 case -ESHUTDOWN:
247                 case -ENOENT:
248                 case -ECONNRESET:
249                         return; /* unplug */
250                 case -EPIPE:
251                         set_bit(WDM_INT_STALL, &desc->flags);
252                         dev_err(&desc->intf->dev, "Stall on int endpoint\n");
253                         goto sw; /* halt is cleared in work */
254                 default:
255                         dev_err(&desc->intf->dev,
256                                 "nonzero urb status received: %d\n", status);
257                         break;
258                 }
259         }
260
261         if (urb->actual_length < sizeof(struct usb_cdc_notification)) {
262                 dev_err(&desc->intf->dev, "wdm_int_callback - %d bytes\n",
263                         urb->actual_length);
264                 goto exit;
265         }
266
267         switch (dr->bNotificationType) {
268         case USB_CDC_NOTIFY_RESPONSE_AVAILABLE:
269                 dev_dbg(&desc->intf->dev,
270                         "NOTIFY_RESPONSE_AVAILABLE received: index %d len %d\n",
271                         le16_to_cpu(dr->wIndex), le16_to_cpu(dr->wLength));
272                 break;
273
274         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
275
276                 dev_dbg(&desc->intf->dev,
277                         "NOTIFY_NETWORK_CONNECTION %s network\n",
278                         dr->wValue ? "connected to" : "disconnected from");
279                 goto exit;
280         case USB_CDC_NOTIFY_SPEED_CHANGE:
281                 dev_dbg(&desc->intf->dev, "SPEED_CHANGE received (len %u)\n",
282                         urb->actual_length);
283                 goto exit;
284         default:
285                 clear_bit(WDM_POLL_RUNNING, &desc->flags);
286                 dev_err(&desc->intf->dev,
287                         "unknown notification %d received: index %d len %d\n",
288                         dr->bNotificationType,
289                         le16_to_cpu(dr->wIndex),
290                         le16_to_cpu(dr->wLength));
291                 goto exit;
292         }
293
294         spin_lock_irqsave(&desc->iuspin, flags);
295         responding = test_and_set_bit(WDM_RESPONDING, &desc->flags);
296         if (!desc->resp_count++ && !responding
297                 && !test_bit(WDM_DISCONNECTING, &desc->flags)
298                 && !test_bit(WDM_SUSPENDING, &desc->flags)) {
299                 rv = usb_submit_urb(desc->response, GFP_ATOMIC);
300                 dev_dbg(&desc->intf->dev, "submit response URB %d\n", rv);
301         }
302         spin_unlock_irqrestore(&desc->iuspin, flags);
303         if (rv < 0) {
304                 clear_bit(WDM_RESPONDING, &desc->flags);
305                 if (rv == -EPERM)
306                         return;
307                 if (rv == -ENOMEM) {
308 sw:
309                         rv = schedule_work(&desc->rxwork);
310                         if (rv)
311                                 dev_err(&desc->intf->dev,
312                                         "Cannot schedule work\n");
313                 }
314         }
315 exit:
316         rv = usb_submit_urb(urb, GFP_ATOMIC);
317         if (rv)
318                 dev_err(&desc->intf->dev,
319                         "%s - usb_submit_urb failed with result %d\n",
320                         __func__, rv);
321
322 }
323
324 static void kill_urbs(struct wdm_device *desc)
325 {
326         /* the order here is essential */
327         usb_kill_urb(desc->command);
328         usb_kill_urb(desc->validity);
329         usb_kill_urb(desc->response);
330 }
331
332 static void free_urbs(struct wdm_device *desc)
333 {
334         usb_free_urb(desc->validity);
335         usb_free_urb(desc->response);
336         usb_free_urb(desc->command);
337 }
338
339 static void cleanup(struct wdm_device *desc)
340 {
341         kfree(desc->sbuf);
342         kfree(desc->inbuf);
343         kfree(desc->orq);
344         kfree(desc->irq);
345         kfree(desc->ubuf);
346         free_urbs(desc);
347         kfree(desc);
348 }
349
350 static ssize_t wdm_write
351 (struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
352 {
353         u8 *buf;
354         int rv = -EMSGSIZE, r, we;
355         struct wdm_device *desc = file->private_data;
356         struct usb_ctrlrequest *req;
357
358         if (count > desc->wMaxCommand)
359                 count = desc->wMaxCommand;
360
361         spin_lock_irq(&desc->iuspin);
362         we = desc->werr;
363         desc->werr = 0;
364         spin_unlock_irq(&desc->iuspin);
365         if (we < 0)
366                 return usb_translate_errors(we);
367
368         buf = memdup_user(buffer, count);
369         if (IS_ERR(buf))
370                 return PTR_ERR(buf);
371
372         /* concurrent writes and disconnect */
373         r = mutex_lock_interruptible(&desc->wlock);
374         rv = -ERESTARTSYS;
375         if (r)
376                 goto out_free_mem;
377
378         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
379                 rv = -ENODEV;
380                 goto out_free_mem_lock;
381         }
382
383         r = usb_autopm_get_interface(desc->intf);
384         if (r < 0) {
385                 rv = usb_translate_errors(r);
386                 goto out_free_mem_lock;
387         }
388
389         if (!(file->f_flags & O_NONBLOCK))
390                 r = wait_event_interruptible(desc->wait, !test_bit(WDM_IN_USE,
391                                                                 &desc->flags));
392         else
393                 if (test_bit(WDM_IN_USE, &desc->flags))
394                         r = -EAGAIN;
395
396         if (test_bit(WDM_RESETTING, &desc->flags))
397                 r = -EIO;
398
399         if (test_bit(WDM_DISCONNECTING, &desc->flags))
400                 r = -ENODEV;
401
402         if (r < 0) {
403                 rv = r;
404                 goto out_free_mem_pm;
405         }
406
407         req = desc->orq;
408         usb_fill_control_urb(
409                 desc->command,
410                 interface_to_usbdev(desc->intf),
411                 /* using common endpoint 0 */
412                 usb_sndctrlpipe(interface_to_usbdev(desc->intf), 0),
413                 (unsigned char *)req,
414                 buf,
415                 count,
416                 wdm_out_callback,
417                 desc
418         );
419
420         req->bRequestType = (USB_DIR_OUT | USB_TYPE_CLASS |
421                              USB_RECIP_INTERFACE);
422         req->bRequest = USB_CDC_SEND_ENCAPSULATED_COMMAND;
423         req->wValue = 0;
424         req->wIndex = desc->inum; /* already converted */
425         req->wLength = cpu_to_le16(count);
426         set_bit(WDM_IN_USE, &desc->flags);
427         desc->outbuf = buf;
428
429         rv = usb_submit_urb(desc->command, GFP_KERNEL);
430         if (rv < 0) {
431                 desc->outbuf = NULL;
432                 clear_bit(WDM_IN_USE, &desc->flags);
433                 wake_up_all(&desc->wait); /* for wdm_wait_for_response() */
434                 dev_err(&desc->intf->dev, "Tx URB error: %d\n", rv);
435                 rv = usb_translate_errors(rv);
436                 goto out_free_mem_pm;
437         } else {
438                 dev_dbg(&desc->intf->dev, "Tx URB has been submitted index=%d\n",
439                         le16_to_cpu(req->wIndex));
440         }
441
442         usb_autopm_put_interface(desc->intf);
443         mutex_unlock(&desc->wlock);
444         return count;
445
446 out_free_mem_pm:
447         usb_autopm_put_interface(desc->intf);
448 out_free_mem_lock:
449         mutex_unlock(&desc->wlock);
450 out_free_mem:
451         kfree(buf);
452         return rv;
453 }
454
455 /*
456  * Submit the read urb if resp_count is non-zero.
457  *
458  * Called with desc->iuspin locked
459  */
460 static int service_outstanding_interrupt(struct wdm_device *desc)
461 {
462         int rv = 0;
463
464         /* submit read urb only if the device is waiting for it */
465         if (!desc->resp_count || !--desc->resp_count)
466                 goto out;
467
468         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
469                 rv = -ENODEV;
470                 goto out;
471         }
472         if (test_bit(WDM_RESETTING, &desc->flags)) {
473                 rv = -EIO;
474                 goto out;
475         }
476
477         set_bit(WDM_RESPONDING, &desc->flags);
478         spin_unlock_irq(&desc->iuspin);
479         rv = usb_submit_urb(desc->response, GFP_KERNEL);
480         spin_lock_irq(&desc->iuspin);
481         if (rv) {
482                 if (!test_bit(WDM_DISCONNECTING, &desc->flags))
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 = READ_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 = -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 __poll_t wdm_poll(struct file *file, struct poll_table_struct *wait)
658 {
659         struct wdm_device *desc = file->private_data;
660         unsigned long flags;
661         __poll_t mask = 0;
662
663         spin_lock_irqsave(&desc->iuspin, flags);
664         if (test_bit(WDM_DISCONNECTING, &desc->flags)) {
665                 mask = EPOLLHUP | EPOLLERR;
666                 spin_unlock_irqrestore(&desc->iuspin, flags);
667                 goto desc_out;
668         }
669         if (test_bit(WDM_READ, &desc->flags))
670                 mask = EPOLLIN | EPOLLRDNORM;
671         if (desc->rerr || desc->werr)
672                 mask |= EPOLLERR;
673         if (!test_bit(WDM_IN_USE, &desc->flags))
674                 mask |= EPOLLOUT | EPOLLWRNORM;
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 = compat_ptr_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 static void service_interrupt_work(struct work_struct *work)
822 {
823         struct wdm_device *desc;
824
825         desc = container_of(work, struct wdm_device, service_outs_intr);
826
827         spin_lock_irq(&desc->iuspin);
828         service_outstanding_interrupt(desc);
829         if (!desc->resp_count) {
830                 set_bit(WDM_READ, &desc->flags);
831                 wake_up(&desc->wait);
832         }
833         spin_unlock_irq(&desc->iuspin);
834 }
835
836 /* --- hotplug --- */
837
838 static int wdm_create(struct usb_interface *intf, struct usb_endpoint_descriptor *ep,
839                 u16 bufsize, int (*manage_power)(struct usb_interface *, int))
840 {
841         int rv = -ENOMEM;
842         struct wdm_device *desc;
843
844         desc = kzalloc(sizeof(struct wdm_device), GFP_KERNEL);
845         if (!desc)
846                 goto out;
847         INIT_LIST_HEAD(&desc->device_list);
848         mutex_init(&desc->rlock);
849         mutex_init(&desc->wlock);
850         spin_lock_init(&desc->iuspin);
851         init_waitqueue_head(&desc->wait);
852         desc->wMaxCommand = bufsize;
853         /* this will be expanded and needed in hardware endianness */
854         desc->inum = cpu_to_le16((u16)intf->cur_altsetting->desc.bInterfaceNumber);
855         desc->intf = intf;
856         INIT_WORK(&desc->rxwork, wdm_rxwork);
857         INIT_WORK(&desc->service_outs_intr, service_interrupt_work);
858
859         rv = -EINVAL;
860         if (!usb_endpoint_is_int_in(ep))
861                 goto err;
862
863         desc->wMaxPacketSize = usb_endpoint_maxp(ep);
864
865         desc->orq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
866         if (!desc->orq)
867                 goto err;
868         desc->irq = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
869         if (!desc->irq)
870                 goto err;
871
872         desc->validity = usb_alloc_urb(0, GFP_KERNEL);
873         if (!desc->validity)
874                 goto err;
875
876         desc->response = usb_alloc_urb(0, GFP_KERNEL);
877         if (!desc->response)
878                 goto err;
879
880         desc->command = usb_alloc_urb(0, GFP_KERNEL);
881         if (!desc->command)
882                 goto err;
883
884         desc->ubuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
885         if (!desc->ubuf)
886                 goto err;
887
888         desc->sbuf = kmalloc(desc->wMaxPacketSize, GFP_KERNEL);
889         if (!desc->sbuf)
890                 goto err;
891
892         desc->inbuf = kmalloc(desc->wMaxCommand, GFP_KERNEL);
893         if (!desc->inbuf)
894                 goto err;
895
896         usb_fill_int_urb(
897                 desc->validity,
898                 interface_to_usbdev(intf),
899                 usb_rcvintpipe(interface_to_usbdev(intf), ep->bEndpointAddress),
900                 desc->sbuf,
901                 desc->wMaxPacketSize,
902                 wdm_int_callback,
903                 desc,
904                 ep->bInterval
905         );
906
907         desc->irq->bRequestType = (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE);
908         desc->irq->bRequest = USB_CDC_GET_ENCAPSULATED_RESPONSE;
909         desc->irq->wValue = 0;
910         desc->irq->wIndex = desc->inum; /* already converted */
911         desc->irq->wLength = cpu_to_le16(desc->wMaxCommand);
912
913         usb_fill_control_urb(
914                 desc->response,
915                 interface_to_usbdev(intf),
916                 /* using common endpoint 0 */
917                 usb_rcvctrlpipe(interface_to_usbdev(desc->intf), 0),
918                 (unsigned char *)desc->irq,
919                 desc->inbuf,
920                 desc->wMaxCommand,
921                 wdm_in_callback,
922                 desc
923         );
924
925         desc->manage_power = manage_power;
926
927         spin_lock(&wdm_device_list_lock);
928         list_add(&desc->device_list, &wdm_device_list);
929         spin_unlock(&wdm_device_list_lock);
930
931         rv = usb_register_dev(intf, &wdm_class);
932         if (rv < 0)
933                 goto err;
934         else
935                 dev_info(&intf->dev, "%s: USB WDM device\n", dev_name(intf->usb_dev));
936 out:
937         return rv;
938 err:
939         spin_lock(&wdm_device_list_lock);
940         list_del(&desc->device_list);
941         spin_unlock(&wdm_device_list_lock);
942         cleanup(desc);
943         return rv;
944 }
945
946 static int wdm_manage_power(struct usb_interface *intf, int on)
947 {
948         /* need autopm_get/put here to ensure the usbcore sees the new value */
949         int rv = usb_autopm_get_interface(intf);
950
951         intf->needs_remote_wakeup = on;
952         if (!rv)
953                 usb_autopm_put_interface(intf);
954         return 0;
955 }
956
957 static int wdm_probe(struct usb_interface *intf, const struct usb_device_id *id)
958 {
959         int rv = -EINVAL;
960         struct usb_host_interface *iface;
961         struct usb_endpoint_descriptor *ep;
962         struct usb_cdc_parsed_header hdr;
963         u8 *buffer = intf->altsetting->extra;
964         int buflen = intf->altsetting->extralen;
965         u16 maxcom = WDM_DEFAULT_BUFSIZE;
966
967         if (!buffer)
968                 goto err;
969
970         cdc_parse_cdc_header(&hdr, intf, buffer, buflen);
971
972         if (hdr.usb_cdc_dmm_desc)
973                 maxcom = le16_to_cpu(hdr.usb_cdc_dmm_desc->wMaxCommand);
974
975         iface = intf->cur_altsetting;
976         if (iface->desc.bNumEndpoints != 1)
977                 goto err;
978         ep = &iface->endpoint[0].desc;
979
980         rv = wdm_create(intf, ep, maxcom, &wdm_manage_power);
981
982 err:
983         return rv;
984 }
985
986 /**
987  * usb_cdc_wdm_register - register a WDM subdriver
988  * @intf: usb interface the subdriver will associate with
989  * @ep: interrupt endpoint to monitor for notifications
990  * @bufsize: maximum message size to support for read/write
991  * @manage_power: call-back invoked during open and release to
992  *                manage the device's power
993  * Create WDM usb class character device and associate it with intf
994  * without binding, allowing another driver to manage the interface.
995  *
996  * The subdriver will manage the given interrupt endpoint exclusively
997  * and will issue control requests referring to the given intf. It
998  * will otherwise avoid interferring, and in particular not do
999  * usb_set_intfdata/usb_get_intfdata on intf.
1000  *
1001  * The return value is a pointer to the subdriver's struct usb_driver.
1002  * The registering driver is responsible for calling this subdriver's
1003  * disconnect, suspend, resume, pre_reset and post_reset methods from
1004  * its own.
1005  */
1006 struct usb_driver *usb_cdc_wdm_register(struct usb_interface *intf,
1007                                         struct usb_endpoint_descriptor *ep,
1008                                         int bufsize,
1009                                         int (*manage_power)(struct usb_interface *, int))
1010 {
1011         int rv;
1012
1013         rv = wdm_create(intf, ep, bufsize, manage_power);
1014         if (rv < 0)
1015                 goto err;
1016
1017         return &wdm_driver;
1018 err:
1019         return ERR_PTR(rv);
1020 }
1021 EXPORT_SYMBOL(usb_cdc_wdm_register);
1022
1023 static void wdm_disconnect(struct usb_interface *intf)
1024 {
1025         struct wdm_device *desc;
1026         unsigned long flags;
1027
1028         usb_deregister_dev(intf, &wdm_class);
1029         desc = wdm_find_device(intf);
1030         mutex_lock(&wdm_mutex);
1031
1032         /* the spinlock makes sure no new urbs are generated in the callbacks */
1033         spin_lock_irqsave(&desc->iuspin, flags);
1034         set_bit(WDM_DISCONNECTING, &desc->flags);
1035         set_bit(WDM_READ, &desc->flags);
1036         spin_unlock_irqrestore(&desc->iuspin, flags);
1037         wake_up_all(&desc->wait);
1038         mutex_lock(&desc->rlock);
1039         mutex_lock(&desc->wlock);
1040         cancel_work_sync(&desc->rxwork);
1041         cancel_work_sync(&desc->service_outs_intr);
1042         kill_urbs(desc);
1043         mutex_unlock(&desc->wlock);
1044         mutex_unlock(&desc->rlock);
1045
1046         /* the desc->intf pointer used as list key is now invalid */
1047         spin_lock(&wdm_device_list_lock);
1048         list_del(&desc->device_list);
1049         spin_unlock(&wdm_device_list_lock);
1050
1051         if (!desc->count)
1052                 cleanup(desc);
1053         else
1054                 dev_dbg(&intf->dev, "%d open files - postponing cleanup\n", desc->count);
1055         mutex_unlock(&wdm_mutex);
1056 }
1057
1058 #ifdef CONFIG_PM
1059 static int wdm_suspend(struct usb_interface *intf, pm_message_t message)
1060 {
1061         struct wdm_device *desc = wdm_find_device(intf);
1062         int rv = 0;
1063
1064         dev_dbg(&desc->intf->dev, "wdm%d_suspend\n", intf->minor);
1065
1066         /* if this is an autosuspend the caller does the locking */
1067         if (!PMSG_IS_AUTO(message)) {
1068                 mutex_lock(&desc->rlock);
1069                 mutex_lock(&desc->wlock);
1070         }
1071         spin_lock_irq(&desc->iuspin);
1072
1073         if (PMSG_IS_AUTO(message) &&
1074                         (test_bit(WDM_IN_USE, &desc->flags)
1075                         || test_bit(WDM_RESPONDING, &desc->flags))) {
1076                 spin_unlock_irq(&desc->iuspin);
1077                 rv = -EBUSY;
1078         } else {
1079
1080                 set_bit(WDM_SUSPENDING, &desc->flags);
1081                 spin_unlock_irq(&desc->iuspin);
1082                 /* callback submits work - order is essential */
1083                 kill_urbs(desc);
1084                 cancel_work_sync(&desc->rxwork);
1085                 cancel_work_sync(&desc->service_outs_intr);
1086         }
1087         if (!PMSG_IS_AUTO(message)) {
1088                 mutex_unlock(&desc->wlock);
1089                 mutex_unlock(&desc->rlock);
1090         }
1091
1092         return rv;
1093 }
1094 #endif
1095
1096 static int recover_from_urb_loss(struct wdm_device *desc)
1097 {
1098         int rv = 0;
1099
1100         if (desc->count) {
1101                 rv = usb_submit_urb(desc->validity, GFP_NOIO);
1102                 if (rv < 0)
1103                         dev_err(&desc->intf->dev,
1104                                 "Error resume submitting int urb - %d\n", rv);
1105         }
1106         return rv;
1107 }
1108
1109 #ifdef CONFIG_PM
1110 static int wdm_resume(struct usb_interface *intf)
1111 {
1112         struct wdm_device *desc = wdm_find_device(intf);
1113         int rv;
1114
1115         dev_dbg(&desc->intf->dev, "wdm%d_resume\n", intf->minor);
1116
1117         clear_bit(WDM_SUSPENDING, &desc->flags);
1118         rv = recover_from_urb_loss(desc);
1119
1120         return rv;
1121 }
1122 #endif
1123
1124 static int wdm_pre_reset(struct usb_interface *intf)
1125 {
1126         struct wdm_device *desc = wdm_find_device(intf);
1127
1128         /*
1129          * we notify everybody using poll of
1130          * an exceptional situation
1131          * must be done before recovery lest a spontaneous
1132          * message from the device is lost
1133          */
1134         spin_lock_irq(&desc->iuspin);
1135         set_bit(WDM_RESETTING, &desc->flags);   /* inform read/write */
1136         set_bit(WDM_READ, &desc->flags);        /* unblock read */
1137         clear_bit(WDM_IN_USE, &desc->flags);    /* unblock write */
1138         desc->rerr = -EINTR;
1139         spin_unlock_irq(&desc->iuspin);
1140         wake_up_all(&desc->wait);
1141         mutex_lock(&desc->rlock);
1142         mutex_lock(&desc->wlock);
1143         kill_urbs(desc);
1144         cancel_work_sync(&desc->rxwork);
1145         cancel_work_sync(&desc->service_outs_intr);
1146         return 0;
1147 }
1148
1149 static int wdm_post_reset(struct usb_interface *intf)
1150 {
1151         struct wdm_device *desc = wdm_find_device(intf);
1152         int rv;
1153
1154         clear_bit(WDM_OVERFLOW, &desc->flags);
1155         clear_bit(WDM_RESETTING, &desc->flags);
1156         rv = recover_from_urb_loss(desc);
1157         mutex_unlock(&desc->wlock);
1158         mutex_unlock(&desc->rlock);
1159         return rv;
1160 }
1161
1162 static struct usb_driver wdm_driver = {
1163         .name =         "cdc_wdm",
1164         .probe =        wdm_probe,
1165         .disconnect =   wdm_disconnect,
1166 #ifdef CONFIG_PM
1167         .suspend =      wdm_suspend,
1168         .resume =       wdm_resume,
1169         .reset_resume = wdm_resume,
1170 #endif
1171         .pre_reset =    wdm_pre_reset,
1172         .post_reset =   wdm_post_reset,
1173         .id_table =     wdm_ids,
1174         .supports_autosuspend = 1,
1175         .disable_hub_initiated_lpm = 1,
1176 };
1177
1178 module_usb_driver(wdm_driver);
1179
1180 MODULE_AUTHOR(DRIVER_AUTHOR);
1181 MODULE_DESCRIPTION(DRIVER_DESC);
1182 MODULE_LICENSE("GPL");