rk312x: usb power optimize by turning off differential receiver in suspend mode
[firefly-linux-kernel-4.4.55.git] / drivers / usb / gadget / f_accessory.c
1 /*
2  * Gadget Function Driver for Android USB accessories
3  *
4  * Copyright (C) 2011 Google, Inc.
5  * Author: Mike Lockwood <lockwood@android.com>
6  *
7  * This software is licensed under the terms of the GNU General Public
8  * License version 2, as published by the Free Software Foundation, and
9  * may be copied, distributed, and modified under those terms.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
20
21 #include <linux/module.h>
22 #include <linux/init.h>
23 #include <linux/poll.h>
24 #include <linux/delay.h>
25 #include <linux/wait.h>
26 #include <linux/err.h>
27 #include <linux/interrupt.h>
28 #include <linux/kthread.h>
29 #include <linux/freezer.h>
30
31 #include <linux/types.h>
32 #include <linux/file.h>
33 #include <linux/device.h>
34 #include <linux/miscdevice.h>
35
36 #include <linux/hid.h>
37 #include <linux/hiddev.h>
38 #include <linux/usb.h>
39 #include <linux/usb/ch9.h>
40 #include <linux/usb/f_accessory.h>
41
42 #define BULK_BUFFER_SIZE    16384
43 #define ACC_STRING_SIZE     256
44
45 #define PROTOCOL_VERSION    2
46
47 /* String IDs */
48 #define INTERFACE_STRING_INDEX  0
49
50 /* number of tx and rx requests to allocate */
51 #define TX_REQ_MAX 4
52 #define RX_REQ_MAX 2
53
54 struct acc_hid_dev {
55         struct list_head        list;
56         struct hid_device *hid;
57         struct acc_dev *dev;
58         /* accessory defined ID */
59         int id;
60         /* HID report descriptor */
61         u8 *report_desc;
62         /* length of HID report descriptor */
63         int report_desc_len;
64         /* number of bytes of report_desc we have received so far */
65         int report_desc_offset;
66 };
67
68 struct acc_dev {
69         struct usb_function function;
70         struct usb_composite_dev *cdev;
71         spinlock_t lock;
72
73         struct usb_ep *ep_in;
74         struct usb_ep *ep_out;
75
76         /* set to 1 when we connect */
77         int online:1;
78         /* Set to 1 when we disconnect.
79          * Not cleared until our file is closed.
80          */
81         int disconnected:1;
82
83         /* strings sent by the host */
84         char manufacturer[ACC_STRING_SIZE];
85         char model[ACC_STRING_SIZE];
86         char description[ACC_STRING_SIZE];
87         char version[ACC_STRING_SIZE];
88         char uri[ACC_STRING_SIZE];
89         char serial[ACC_STRING_SIZE];
90
91         /* for acc_complete_set_string */
92         int string_index;
93
94         /* set to 1 if we have a pending start request */
95         int start_requested;
96
97         int audio_mode;
98
99         /* synchronize access to our device file */
100         atomic_t open_excl;
101
102         struct list_head tx_idle;
103
104         wait_queue_head_t read_wq;
105         wait_queue_head_t write_wq;
106         struct usb_request *rx_req[RX_REQ_MAX];
107         int rx_done;
108
109         /* delayed work for handling ACCESSORY_START */
110         struct delayed_work start_work;
111
112         /* worker for registering and unregistering hid devices */
113         struct work_struct hid_work;
114
115         /* list of active HID devices */
116         struct list_head        hid_list;
117
118         /* list of new HID devices to register */
119         struct list_head        new_hid_list;
120
121         /* list of dead HID devices to unregister */
122         struct list_head        dead_hid_list;
123 };
124
125 static struct usb_interface_descriptor acc_interface_desc = {
126         .bLength                = USB_DT_INTERFACE_SIZE,
127         .bDescriptorType        = USB_DT_INTERFACE,
128         .bInterfaceNumber       = 0,
129         .bNumEndpoints          = 2,
130         .bInterfaceClass        = USB_CLASS_VENDOR_SPEC,
131         .bInterfaceSubClass     = USB_SUBCLASS_VENDOR_SPEC,
132         .bInterfaceProtocol     = 0,
133 };
134
135 static struct usb_endpoint_descriptor acc_highspeed_in_desc = {
136         .bLength                = USB_DT_ENDPOINT_SIZE,
137         .bDescriptorType        = USB_DT_ENDPOINT,
138         .bEndpointAddress       = USB_DIR_IN,
139         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
140         .wMaxPacketSize         = __constant_cpu_to_le16(512),
141 };
142
143 static struct usb_endpoint_descriptor acc_highspeed_out_desc = {
144         .bLength                = USB_DT_ENDPOINT_SIZE,
145         .bDescriptorType        = USB_DT_ENDPOINT,
146         .bEndpointAddress       = USB_DIR_OUT,
147         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
148         .wMaxPacketSize         = __constant_cpu_to_le16(512),
149 };
150
151 static struct usb_endpoint_descriptor acc_fullspeed_in_desc = {
152         .bLength                = USB_DT_ENDPOINT_SIZE,
153         .bDescriptorType        = USB_DT_ENDPOINT,
154         .bEndpointAddress       = USB_DIR_IN,
155         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
156 };
157
158 static struct usb_endpoint_descriptor acc_fullspeed_out_desc = {
159         .bLength                = USB_DT_ENDPOINT_SIZE,
160         .bDescriptorType        = USB_DT_ENDPOINT,
161         .bEndpointAddress       = USB_DIR_OUT,
162         .bmAttributes           = USB_ENDPOINT_XFER_BULK,
163 };
164
165 static struct usb_descriptor_header *fs_acc_descs[] = {
166         (struct usb_descriptor_header *) &acc_interface_desc,
167         (struct usb_descriptor_header *) &acc_fullspeed_in_desc,
168         (struct usb_descriptor_header *) &acc_fullspeed_out_desc,
169         NULL,
170 };
171
172 static struct usb_descriptor_header *hs_acc_descs[] = {
173         (struct usb_descriptor_header *) &acc_interface_desc,
174         (struct usb_descriptor_header *) &acc_highspeed_in_desc,
175         (struct usb_descriptor_header *) &acc_highspeed_out_desc,
176         NULL,
177 };
178
179 static struct usb_string acc_string_defs[] = {
180         [INTERFACE_STRING_INDEX].s      = "Android Accessory Interface",
181         {  },   /* end of list */
182 };
183
184 static struct usb_gadget_strings acc_string_table = {
185         .language               = 0x0409,       /* en-US */
186         .strings                = acc_string_defs,
187 };
188
189 static struct usb_gadget_strings *acc_strings[] = {
190         &acc_string_table,
191         NULL,
192 };
193
194 /* temporary variable used between acc_open() and acc_gadget_bind() */
195 static struct acc_dev *_acc_dev;
196
197 static inline struct acc_dev *func_to_dev(struct usb_function *f)
198 {
199         return container_of(f, struct acc_dev, function);
200 }
201
202 static struct usb_request *acc_request_new(struct usb_ep *ep, int buffer_size)
203 {
204         struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
205         if (!req)
206                 return NULL;
207
208         /* now allocate buffers for the requests */
209         req->buf = kmalloc(buffer_size, GFP_KERNEL);
210         if (!req->buf) {
211                 usb_ep_free_request(ep, req);
212                 return NULL;
213         }
214
215         return req;
216 }
217
218 static void acc_request_free(struct usb_request *req, struct usb_ep *ep)
219 {
220         if (req) {
221                 kfree(req->buf);
222                 usb_ep_free_request(ep, req);
223         }
224 }
225
226 /* add a request to the tail of a list */
227 static void req_put(struct acc_dev *dev, struct list_head *head,
228                 struct usb_request *req)
229 {
230         unsigned long flags;
231
232         spin_lock_irqsave(&dev->lock, flags);
233         list_add_tail(&req->list, head);
234         spin_unlock_irqrestore(&dev->lock, flags);
235 }
236
237 /* remove a request from the head of a list */
238 static struct usb_request *req_get(struct acc_dev *dev, struct list_head *head)
239 {
240         unsigned long flags;
241         struct usb_request *req;
242
243         spin_lock_irqsave(&dev->lock, flags);
244         if (list_empty(head)) {
245                 req = 0;
246         } else {
247                 req = list_first_entry(head, struct usb_request, list);
248                 list_del(&req->list);
249         }
250         spin_unlock_irqrestore(&dev->lock, flags);
251         return req;
252 }
253
254 static void acc_set_disconnected(struct acc_dev *dev)
255 {
256         dev->online = 0;
257         dev->disconnected = 1;
258 }
259
260 static void acc_complete_in(struct usb_ep *ep, struct usb_request *req)
261 {
262         struct acc_dev *dev = _acc_dev;
263
264         if (req->status == -ESHUTDOWN) {
265                 pr_debug("acc_complete_in set disconnected");
266                 acc_set_disconnected(dev);
267         }
268
269         req_put(dev, &dev->tx_idle, req);
270
271         wake_up(&dev->write_wq);
272 }
273
274 static void acc_complete_out(struct usb_ep *ep, struct usb_request *req)
275 {
276         struct acc_dev *dev = _acc_dev;
277
278         dev->rx_done = 1;
279         if (req->status == -ESHUTDOWN) {
280                 pr_debug("acc_complete_out set disconnected");
281                 acc_set_disconnected(dev);
282         }
283
284         wake_up(&dev->read_wq);
285 }
286
287 static void acc_complete_set_string(struct usb_ep *ep, struct usb_request *req)
288 {
289         struct acc_dev  *dev = ep->driver_data;
290         char *string_dest = NULL;
291         int length = req->actual;
292
293         if (req->status != 0) {
294                 pr_err("acc_complete_set_string, err %d\n", req->status);
295                 return;
296         }
297
298         switch (dev->string_index) {
299         case ACCESSORY_STRING_MANUFACTURER:
300                 string_dest = dev->manufacturer;
301                 break;
302         case ACCESSORY_STRING_MODEL:
303                 string_dest = dev->model;
304                 break;
305         case ACCESSORY_STRING_DESCRIPTION:
306                 string_dest = dev->description;
307                 break;
308         case ACCESSORY_STRING_VERSION:
309                 string_dest = dev->version;
310                 break;
311         case ACCESSORY_STRING_URI:
312                 string_dest = dev->uri;
313                 break;
314         case ACCESSORY_STRING_SERIAL:
315                 string_dest = dev->serial;
316                 break;
317         }
318         if (string_dest) {
319                 unsigned long flags;
320
321                 if (length >= ACC_STRING_SIZE)
322                         length = ACC_STRING_SIZE - 1;
323
324                 spin_lock_irqsave(&dev->lock, flags);
325                 memcpy(string_dest, req->buf, length);
326                 /* ensure zero termination */
327                 string_dest[length] = 0;
328                 spin_unlock_irqrestore(&dev->lock, flags);
329         } else {
330                 pr_err("unknown accessory string index %d\n",
331                         dev->string_index);
332         }
333 }
334
335 static void acc_complete_set_hid_report_desc(struct usb_ep *ep,
336                 struct usb_request *req)
337 {
338         struct acc_hid_dev *hid = req->context;
339         struct acc_dev *dev = hid->dev;
340         int length = req->actual;
341
342         if (req->status != 0) {
343                 pr_err("acc_complete_set_hid_report_desc, err %d\n",
344                         req->status);
345                 return;
346         }
347
348         memcpy(hid->report_desc + hid->report_desc_offset, req->buf, length);
349         hid->report_desc_offset += length;
350         if (hid->report_desc_offset == hid->report_desc_len) {
351                 /* After we have received the entire report descriptor
352                  * we schedule work to initialize the HID device
353                  */
354                 schedule_work(&dev->hid_work);
355         }
356 }
357
358 static void acc_complete_send_hid_event(struct usb_ep *ep,
359                 struct usb_request *req)
360 {
361         struct acc_hid_dev *hid = req->context;
362         int length = req->actual;
363
364         if (req->status != 0) {
365                 pr_err("acc_complete_send_hid_event, err %d\n", req->status);
366                 return;
367         }
368
369         hid_report_raw_event(hid->hid, HID_INPUT_REPORT, req->buf, length, 1);
370 }
371
372 static int acc_hid_parse(struct hid_device *hid)
373 {
374         struct acc_hid_dev *hdev = hid->driver_data;
375
376         hid_parse_report(hid, hdev->report_desc, hdev->report_desc_len);
377         return 0;
378 }
379
380 static int acc_hid_start(struct hid_device *hid)
381 {
382         return 0;
383 }
384
385 static void acc_hid_stop(struct hid_device *hid)
386 {
387 }
388
389 static int acc_hid_open(struct hid_device *hid)
390 {
391         return 0;
392 }
393
394 static void acc_hid_close(struct hid_device *hid)
395 {
396 }
397
398 static struct hid_ll_driver acc_hid_ll_driver = {
399         .parse = acc_hid_parse,
400         .start = acc_hid_start,
401         .stop = acc_hid_stop,
402         .open = acc_hid_open,
403         .close = acc_hid_close,
404 };
405
406 static struct acc_hid_dev *acc_hid_new(struct acc_dev *dev,
407                 int id, int desc_len)
408 {
409         struct acc_hid_dev *hdev;
410
411         hdev = kzalloc(sizeof(*hdev), GFP_ATOMIC);
412         if (!hdev)
413                 return NULL;
414         hdev->report_desc = kzalloc(desc_len, GFP_ATOMIC);
415         if (!hdev->report_desc) {
416                 kfree(hdev);
417                 return NULL;
418         }
419         hdev->dev = dev;
420         hdev->id = id;
421         hdev->report_desc_len = desc_len;
422
423         return hdev;
424 }
425
426 static struct acc_hid_dev *acc_hid_get(struct list_head *list, int id)
427 {
428         struct acc_hid_dev *hid;
429
430         list_for_each_entry(hid, list, list) {
431                 if (hid->id == id)
432                         return hid;
433         }
434         return NULL;
435 }
436
437 static int acc_register_hid(struct acc_dev *dev, int id, int desc_length)
438 {
439         struct acc_hid_dev *hid;
440         unsigned long flags;
441
442         /* report descriptor length must be > 0 */
443         if (desc_length <= 0)
444                 return -EINVAL;
445
446         spin_lock_irqsave(&dev->lock, flags);
447         /* replace HID if one already exists with this ID */
448         hid = acc_hid_get(&dev->hid_list, id);
449         if (!hid)
450                 hid = acc_hid_get(&dev->new_hid_list, id);
451         if (hid)
452                 list_move(&hid->list, &dev->dead_hid_list);
453
454         hid = acc_hid_new(dev, id, desc_length);
455         if (!hid) {
456                 spin_unlock_irqrestore(&dev->lock, flags);
457                 return -ENOMEM;
458         }
459
460         list_add(&hid->list, &dev->new_hid_list);
461         spin_unlock_irqrestore(&dev->lock, flags);
462
463         /* schedule work to register the HID device */
464         schedule_work(&dev->hid_work);
465         return 0;
466 }
467
468 static int acc_unregister_hid(struct acc_dev *dev, int id)
469 {
470         struct acc_hid_dev *hid;
471         unsigned long flags;
472
473         spin_lock_irqsave(&dev->lock, flags);
474         hid = acc_hid_get(&dev->hid_list, id);
475         if (!hid)
476                 hid = acc_hid_get(&dev->new_hid_list, id);
477         if (!hid) {
478                 spin_unlock_irqrestore(&dev->lock, flags);
479                 return -EINVAL;
480         }
481
482         list_move(&hid->list, &dev->dead_hid_list);
483         spin_unlock_irqrestore(&dev->lock, flags);
484
485         schedule_work(&dev->hid_work);
486         return 0;
487 }
488
489 static int create_bulk_endpoints(struct acc_dev *dev,
490                                 struct usb_endpoint_descriptor *in_desc,
491                                 struct usb_endpoint_descriptor *out_desc)
492 {
493         struct usb_composite_dev *cdev = dev->cdev;
494         struct usb_request *req;
495         struct usb_ep *ep;
496         int i;
497
498         DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
499
500         ep = usb_ep_autoconfig(cdev->gadget, in_desc);
501         if (!ep) {
502                 DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
503                 return -ENODEV;
504         }
505         DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
506         ep->driver_data = dev;          /* claim the endpoint */
507         dev->ep_in = ep;
508
509         ep = usb_ep_autoconfig(cdev->gadget, out_desc);
510         if (!ep) {
511                 DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
512                 return -ENODEV;
513         }
514         DBG(cdev, "usb_ep_autoconfig for ep_out got %s\n", ep->name);
515         ep->driver_data = dev;          /* claim the endpoint */
516         dev->ep_out = ep;
517
518         ep = usb_ep_autoconfig(cdev->gadget, out_desc);
519         if (!ep) {
520                 DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
521                 return -ENODEV;
522         }
523         DBG(cdev, "usb_ep_autoconfig for ep_out got %s\n", ep->name);
524         ep->driver_data = dev;          /* claim the endpoint */
525         dev->ep_out = ep;
526
527         /* now allocate requests for our endpoints */
528         for (i = 0; i < TX_REQ_MAX; i++) {
529                 req = acc_request_new(dev->ep_in, BULK_BUFFER_SIZE);
530                 if (!req)
531                         goto fail;
532                 req->complete = acc_complete_in;
533                 req_put(dev, &dev->tx_idle, req);
534         }
535         for (i = 0; i < RX_REQ_MAX; i++) {
536                 req = acc_request_new(dev->ep_out, BULK_BUFFER_SIZE);
537                 if (!req)
538                         goto fail;
539                 req->complete = acc_complete_out;
540                 dev->rx_req[i] = req;
541         }
542
543         return 0;
544
545 fail:
546         pr_err("acc_bind() could not allocate requests\n");
547         while ((req = req_get(dev, &dev->tx_idle)))
548                 acc_request_free(req, dev->ep_in);
549         for (i = 0; i < RX_REQ_MAX; i++)
550                 acc_request_free(dev->rx_req[i], dev->ep_out);
551         return -1;
552 }
553
554 static ssize_t acc_read(struct file *fp, char __user *buf,
555         size_t count, loff_t *pos)
556 {
557         struct acc_dev *dev = fp->private_data;
558         struct usb_request *req;
559         ssize_t r = count;
560         unsigned xfer;
561         int ret = 0;
562
563         pr_debug("acc_read(%zu)\n", count);
564
565         if (dev->disconnected) {
566                 pr_debug("acc_read disconnected");
567                 return -ENODEV;
568         }
569
570         if (count > BULK_BUFFER_SIZE)
571                 count = BULK_BUFFER_SIZE;
572
573         /* we will block until we're online */
574         pr_debug("acc_read: waiting for online\n");
575         ret = wait_event_interruptible(dev->read_wq, dev->online);
576         if (ret < 0) {
577                 r = ret;
578                 goto done;
579         }
580
581         if (dev->rx_done) {
582                 // last req cancelled. try to get it.
583                 req = dev->rx_req[0];
584                 goto copy_data;
585         }
586
587 requeue_req:
588         /* queue a request */
589         req = dev->rx_req[0];
590         req->length = count;
591         dev->rx_done = 0;
592         ret = usb_ep_queue(dev->ep_out, req, GFP_KERNEL);
593         if (ret < 0) {
594                 r = -EIO;
595                 goto done;
596         } else {
597                 pr_debug("rx %p queue\n", req);
598         }
599
600         /* wait for a request to complete */
601         ret = wait_event_interruptible(dev->read_wq, dev->rx_done);
602         if (ret < 0) {
603                 r = ret;
604                 ret = usb_ep_dequeue(dev->ep_out, req);
605                 if (ret != 0) {
606                         // cancel failed. There can be a data already received.
607                         // it will be retrieved in the next read.
608                         pr_debug("acc_read: cancelling failed %d", ret);
609                 }
610                 goto done;
611         }
612
613 copy_data:
614         dev->rx_done = 0;
615         if (dev->online) {
616                 /* If we got a 0-len packet, throw it back and try again. */
617                 if (req->actual == 0)
618                         goto requeue_req;
619
620                 pr_debug("rx %p %u\n", req, req->actual);
621                 xfer = (req->actual < count) ? req->actual : count;
622                 r = xfer;
623                 if (copy_to_user(buf, req->buf, xfer))
624                         r = -EFAULT;
625         } else
626                 r = -EIO;
627
628 done:
629         pr_debug("acc_read returning %zd\n", r);
630         return r;
631 }
632
633 static ssize_t acc_write(struct file *fp, const char __user *buf,
634         size_t count, loff_t *pos)
635 {
636         struct acc_dev *dev = fp->private_data;
637         struct usb_request *req = 0;
638         ssize_t r = count;
639         unsigned xfer;
640         int ret;
641
642         pr_debug("acc_write(%zu)\n", count);
643
644         if (!dev->online || dev->disconnected) {
645                 pr_debug("acc_write disconnected or not online");
646                 return -ENODEV;
647         }
648
649         while (count > 0) {
650                 if (!dev->online) {
651                         pr_debug("acc_write dev->error\n");
652                         r = -EIO;
653                         break;
654                 }
655
656                 /* get an idle tx request to use */
657                 req = 0;
658                 ret = wait_event_interruptible(dev->write_wq,
659                         ((req = req_get(dev, &dev->tx_idle)) || !dev->online));
660                 if (!req) {
661                         r = ret;
662                         break;
663                 }
664
665                 if (count > BULK_BUFFER_SIZE)
666                         xfer = BULK_BUFFER_SIZE;
667                 else
668                         xfer = count;
669                 if (copy_from_user(req->buf, buf, xfer)) {
670                         r = -EFAULT;
671                         break;
672                 }
673
674                 req->length = xfer;
675                 ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
676                 if (ret < 0) {
677                         pr_debug("acc_write: xfer error %d\n", ret);
678                         r = -EIO;
679                         break;
680                 }
681
682                 buf += xfer;
683                 count -= xfer;
684
685                 /* zero this so we don't try to free it on error exit */
686                 req = 0;
687         }
688
689         if (req)
690                 req_put(dev, &dev->tx_idle, req);
691
692         pr_debug("acc_write returning %zd\n", r);
693         return r;
694 }
695
696 static long acc_ioctl(struct file *fp, unsigned code, unsigned long value)
697 {
698         struct acc_dev *dev = fp->private_data;
699         char *src = NULL;
700         int ret;
701
702         switch (code) {
703         case ACCESSORY_GET_STRING_MANUFACTURER:
704                 src = dev->manufacturer;
705                 break;
706         case ACCESSORY_GET_STRING_MODEL:
707                 src = dev->model;
708                 break;
709         case ACCESSORY_GET_STRING_DESCRIPTION:
710                 src = dev->description;
711                 break;
712         case ACCESSORY_GET_STRING_VERSION:
713                 src = dev->version;
714                 break;
715         case ACCESSORY_GET_STRING_URI:
716                 src = dev->uri;
717                 break;
718         case ACCESSORY_GET_STRING_SERIAL:
719                 src = dev->serial;
720                 break;
721         case ACCESSORY_IS_START_REQUESTED:
722                 return dev->start_requested;
723         case ACCESSORY_GET_AUDIO_MODE:
724                 return dev->audio_mode;
725         }
726         if (!src)
727                 return -EINVAL;
728
729         ret = strlen(src) + 1;
730         if (copy_to_user((void __user *)value, src, ret))
731                 ret = -EFAULT;
732         return ret;
733 }
734
735 static int acc_open(struct inode *ip, struct file *fp)
736 {
737         printk(KERN_INFO "acc_open\n");
738         if (atomic_xchg(&_acc_dev->open_excl, 1))
739                 return -EBUSY;
740
741         _acc_dev->disconnected = 0;
742         fp->private_data = _acc_dev;
743         return 0;
744 }
745
746 static int acc_release(struct inode *ip, struct file *fp)
747 {
748         printk(KERN_INFO "acc_release\n");
749
750         WARN_ON(!atomic_xchg(&_acc_dev->open_excl, 0));
751         _acc_dev->disconnected = 0;
752         return 0;
753 }
754
755 /* file operations for /dev/usb_accessory */
756 static const struct file_operations acc_fops = {
757         .owner = THIS_MODULE,
758         .read = acc_read,
759         .write = acc_write,
760         .unlocked_ioctl = acc_ioctl,
761         .open = acc_open,
762         .release = acc_release,
763 };
764
765 static int acc_hid_probe(struct hid_device *hdev,
766                 const struct hid_device_id *id)
767 {
768         int ret;
769
770         ret = hid_parse(hdev);
771         if (ret)
772                 return ret;
773         return hid_hw_start(hdev, HID_CONNECT_DEFAULT);
774 }
775
776 static struct miscdevice acc_device = {
777         .minor = MISC_DYNAMIC_MINOR,
778         .name = "usb_accessory",
779         .fops = &acc_fops,
780 };
781
782 static const struct hid_device_id acc_hid_table[] = {
783         { HID_USB_DEVICE(HID_ANY_ID, HID_ANY_ID) },
784         { }
785 };
786
787 static struct hid_driver acc_hid_driver = {
788         .name = "USB accessory",
789         .id_table = acc_hid_table,
790         .probe = acc_hid_probe,
791 };
792
793 static int acc_ctrlrequest(struct usb_composite_dev *cdev,
794                                 const struct usb_ctrlrequest *ctrl)
795 {
796         struct acc_dev  *dev = _acc_dev;
797         int     value = -EOPNOTSUPP;
798         struct acc_hid_dev *hid;
799         int offset;
800         u8 b_requestType = ctrl->bRequestType;
801         u8 b_request = ctrl->bRequest;
802         u16     w_index = le16_to_cpu(ctrl->wIndex);
803         u16     w_value = le16_to_cpu(ctrl->wValue);
804         u16     w_length = le16_to_cpu(ctrl->wLength);
805         unsigned long flags;
806
807 /*
808         printk(KERN_INFO "acc_ctrlrequest "
809                         "%02x.%02x v%04x i%04x l%u\n",
810                         b_requestType, b_request,
811                         w_value, w_index, w_length);
812 */
813
814         if (b_requestType == (USB_DIR_OUT | USB_TYPE_VENDOR)) {
815                 if (b_request == ACCESSORY_START) {
816                         dev->start_requested = 1;
817                         schedule_delayed_work(
818                                 &dev->start_work, msecs_to_jiffies(10));
819                         value = 0;
820                 } else if (b_request == ACCESSORY_SEND_STRING) {
821                         dev->string_index = w_index;
822                         cdev->gadget->ep0->driver_data = dev;
823                         cdev->req->complete = acc_complete_set_string;
824                         value = w_length;
825                 } else if (b_request == ACCESSORY_SET_AUDIO_MODE &&
826                                 w_index == 0 && w_length == 0) {
827                         dev->audio_mode = w_value;
828                         value = 0;
829                 } else if (b_request == ACCESSORY_REGISTER_HID) {
830                         value = acc_register_hid(dev, w_value, w_index);
831                 } else if (b_request == ACCESSORY_UNREGISTER_HID) {
832                         value = acc_unregister_hid(dev, w_value);
833                 } else if (b_request == ACCESSORY_SET_HID_REPORT_DESC) {
834                         spin_lock_irqsave(&dev->lock, flags);
835                         hid = acc_hid_get(&dev->new_hid_list, w_value);
836                         spin_unlock_irqrestore(&dev->lock, flags);
837                         if (!hid) {
838                                 value = -EINVAL;
839                                 goto err;
840                         }
841                         offset = w_index;
842                         if (offset != hid->report_desc_offset
843                                 || offset + w_length > hid->report_desc_len) {
844                                 value = -EINVAL;
845                                 goto err;
846                         }
847                         cdev->req->context = hid;
848                         cdev->req->complete = acc_complete_set_hid_report_desc;
849                         value = w_length;
850                 } else if (b_request == ACCESSORY_SEND_HID_EVENT) {
851                         spin_lock_irqsave(&dev->lock, flags);
852                         hid = acc_hid_get(&dev->hid_list, w_value);
853                         spin_unlock_irqrestore(&dev->lock, flags);
854                         if (!hid) {
855                                 value = -EINVAL;
856                                 goto err;
857                         }
858                         cdev->req->context = hid;
859                         cdev->req->complete = acc_complete_send_hid_event;
860                         value = w_length;
861                 }
862         } else if (b_requestType == (USB_DIR_IN | USB_TYPE_VENDOR)) {
863                 if (b_request == ACCESSORY_GET_PROTOCOL) {
864                         *((u16 *)cdev->req->buf) = PROTOCOL_VERSION;
865                         value = sizeof(u16);
866
867                         /* clear any string left over from a previous session */
868                         memset(dev->manufacturer, 0, sizeof(dev->manufacturer));
869                         memset(dev->model, 0, sizeof(dev->model));
870                         memset(dev->description, 0, sizeof(dev->description));
871                         memset(dev->version, 0, sizeof(dev->version));
872                         memset(dev->uri, 0, sizeof(dev->uri));
873                         memset(dev->serial, 0, sizeof(dev->serial));
874                         dev->start_requested = 0;
875                         dev->audio_mode = 0;
876                 }
877         }
878
879         if (value >= 0) {
880                 cdev->req->zero = 0;
881                 cdev->req->length = value;
882                 value = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
883                 if (value < 0)
884                         ERROR(cdev, "%s setup response queue error\n",
885                                 __func__);
886         }
887
888 err:
889         if (value == -EOPNOTSUPP)
890                 VDBG(cdev,
891                         "unknown class-specific control req "
892                         "%02x.%02x v%04x i%04x l%u\n",
893                         ctrl->bRequestType, ctrl->bRequest,
894                         w_value, w_index, w_length);
895         return value;
896 }
897
898 static int
899 acc_function_bind(struct usb_configuration *c, struct usb_function *f)
900 {
901         struct usb_composite_dev *cdev = c->cdev;
902         struct acc_dev  *dev = func_to_dev(f);
903         int                     id;
904         int                     ret;
905
906         DBG(cdev, "acc_function_bind dev: %p\n", dev);
907
908         ret = hid_register_driver(&acc_hid_driver);
909         if (ret)
910                 return ret;
911
912         dev->start_requested = 0;
913
914         /* allocate interface ID(s) */
915         id = usb_interface_id(c, f);
916         if (id < 0)
917                 return id;
918         acc_interface_desc.bInterfaceNumber = id;
919
920         /* allocate endpoints */
921         ret = create_bulk_endpoints(dev, &acc_fullspeed_in_desc,
922                         &acc_fullspeed_out_desc);
923         if (ret)
924                 return ret;
925
926         /* support high speed hardware */
927         if (gadget_is_dualspeed(c->cdev->gadget)) {
928                 acc_highspeed_in_desc.bEndpointAddress =
929                         acc_fullspeed_in_desc.bEndpointAddress;
930                 acc_highspeed_out_desc.bEndpointAddress =
931                         acc_fullspeed_out_desc.bEndpointAddress;
932         }
933
934         DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
935                         gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
936                         f->name, dev->ep_in->name, dev->ep_out->name);
937         return 0;
938 }
939
940 static void
941 kill_all_hid_devices(struct acc_dev *dev)
942 {
943         struct acc_hid_dev *hid;
944         struct list_head *entry, *temp;
945         unsigned long flags;
946
947         spin_lock_irqsave(&dev->lock, flags);
948         list_for_each_safe(entry, temp, &dev->hid_list) {
949                 hid = list_entry(entry, struct acc_hid_dev, list);
950                 list_del(&hid->list);
951                 list_add(&hid->list, &dev->dead_hid_list);
952         }
953         list_for_each_safe(entry, temp, &dev->new_hid_list) {
954                 hid = list_entry(entry, struct acc_hid_dev, list);
955                 list_del(&hid->list);
956                 list_add(&hid->list, &dev->dead_hid_list);
957         }
958         spin_unlock_irqrestore(&dev->lock, flags);
959
960         schedule_work(&dev->hid_work);
961 }
962
963 static void
964 acc_hid_unbind(struct acc_dev *dev)
965 {
966         hid_unregister_driver(&acc_hid_driver);
967         kill_all_hid_devices(dev);
968 }
969
970 static void
971 acc_function_unbind(struct usb_configuration *c, struct usb_function *f)
972 {
973         struct acc_dev  *dev = func_to_dev(f);
974         struct usb_request *req;
975         int i;
976
977         while ((req = req_get(dev, &dev->tx_idle)))
978                 acc_request_free(req, dev->ep_in);
979         for (i = 0; i < RX_REQ_MAX; i++)
980                 acc_request_free(dev->rx_req[i], dev->ep_out);
981
982         acc_hid_unbind(dev);
983 }
984
985 static void acc_start_work(struct work_struct *data)
986 {
987         char *envp[2] = { "ACCESSORY=START", NULL };
988         kobject_uevent_env(&acc_device.this_device->kobj, KOBJ_CHANGE, envp);
989 }
990
991 static int acc_hid_init(struct acc_hid_dev *hdev)
992 {
993         struct hid_device *hid;
994         int ret;
995
996         hid = hid_allocate_device();
997         if (IS_ERR(hid))
998                 return PTR_ERR(hid);
999
1000         hid->ll_driver = &acc_hid_ll_driver;
1001         hid->dev.parent = acc_device.this_device;
1002
1003         hid->bus = BUS_USB;
1004         hid->vendor = HID_ANY_ID;
1005         hid->product = HID_ANY_ID;
1006         hid->driver_data = hdev;
1007         ret = hid_add_device(hid);
1008         if (ret) {
1009                 pr_err("can't add hid device: %d\n", ret);
1010                 hid_destroy_device(hid);
1011                 return ret;
1012         }
1013
1014         hdev->hid = hid;
1015         return 0;
1016 }
1017
1018 static void acc_hid_delete(struct acc_hid_dev *hid)
1019 {
1020         kfree(hid->report_desc);
1021         kfree(hid);
1022 }
1023
1024 static void acc_hid_work(struct work_struct *data)
1025 {
1026         struct acc_dev *dev = _acc_dev;
1027         struct list_head        *entry, *temp;
1028         struct acc_hid_dev *hid;
1029         struct list_head        new_list, dead_list;
1030         unsigned long flags;
1031
1032         INIT_LIST_HEAD(&new_list);
1033
1034         spin_lock_irqsave(&dev->lock, flags);
1035
1036         /* copy hids that are ready for initialization to new_list */
1037         list_for_each_safe(entry, temp, &dev->new_hid_list) {
1038                 hid = list_entry(entry, struct acc_hid_dev, list);
1039                 if (hid->report_desc_offset == hid->report_desc_len)
1040                         list_move(&hid->list, &new_list);
1041         }
1042
1043         if (list_empty(&dev->dead_hid_list)) {
1044                 INIT_LIST_HEAD(&dead_list);
1045         } else {
1046                 /* move all of dev->dead_hid_list to dead_list */
1047                 dead_list.prev = dev->dead_hid_list.prev;
1048                 dead_list.next = dev->dead_hid_list.next;
1049                 dead_list.next->prev = &dead_list;
1050                 dead_list.prev->next = &dead_list;
1051                 INIT_LIST_HEAD(&dev->dead_hid_list);
1052         }
1053
1054         spin_unlock_irqrestore(&dev->lock, flags);
1055
1056         /* register new HID devices */
1057         list_for_each_safe(entry, temp, &new_list) {
1058                 hid = list_entry(entry, struct acc_hid_dev, list);
1059                 if (acc_hid_init(hid)) {
1060                         pr_err("can't add HID device %p\n", hid);
1061                         acc_hid_delete(hid);
1062                 } else {
1063                         spin_lock_irqsave(&dev->lock, flags);
1064                         list_move(&hid->list, &dev->hid_list);
1065                         spin_unlock_irqrestore(&dev->lock, flags);
1066                 }
1067         }
1068
1069         /* remove dead HID devices */
1070         list_for_each_safe(entry, temp, &dead_list) {
1071                 hid = list_entry(entry, struct acc_hid_dev, list);
1072                 list_del(&hid->list);
1073                 if (hid->hid)
1074                         hid_destroy_device(hid->hid);
1075                 acc_hid_delete(hid);
1076         }
1077 }
1078
1079 static int acc_function_set_alt(struct usb_function *f,
1080                 unsigned intf, unsigned alt)
1081 {
1082         struct acc_dev  *dev = func_to_dev(f);
1083         struct usb_composite_dev *cdev = f->config->cdev;
1084         int ret;
1085
1086         DBG(cdev, "acc_function_set_alt intf: %d alt: %d\n", intf, alt);
1087
1088         ret = config_ep_by_speed(cdev->gadget, f, dev->ep_in);
1089         if (ret)
1090                 return ret;
1091
1092         ret = usb_ep_enable(dev->ep_in);
1093         if (ret)
1094                 return ret;
1095
1096         ret = config_ep_by_speed(cdev->gadget, f, dev->ep_out);
1097         if (ret)
1098                 return ret;
1099
1100         ret = usb_ep_enable(dev->ep_out);
1101         if (ret) {
1102                 usb_ep_disable(dev->ep_in);
1103                 return ret;
1104         }
1105
1106         dev->online = 1;
1107
1108         /* readers may be blocked waiting for us to go online */
1109         wake_up(&dev->read_wq);
1110         return 0;
1111 }
1112
1113 static void acc_function_disable(struct usb_function *f)
1114 {
1115         struct acc_dev  *dev = func_to_dev(f);
1116         struct usb_composite_dev        *cdev = dev->cdev;
1117
1118         DBG(cdev, "acc_function_disable\n");
1119         acc_set_disconnected(dev);
1120         usb_ep_disable(dev->ep_in);
1121         usb_ep_disable(dev->ep_out);
1122
1123         /* readers may be blocked waiting for us to go online */
1124         wake_up(&dev->read_wq);
1125
1126         VDBG(cdev, "%s disabled\n", dev->function.name);
1127 }
1128
1129 static int acc_bind_config(struct usb_configuration *c)
1130 {
1131         struct acc_dev *dev = _acc_dev;
1132         int ret;
1133
1134         printk(KERN_INFO "acc_bind_config\n");
1135
1136         /* allocate a string ID for our interface */
1137         if (acc_string_defs[INTERFACE_STRING_INDEX].id == 0) {
1138                 ret = usb_string_id(c->cdev);
1139                 if (ret < 0)
1140                         return ret;
1141                 acc_string_defs[INTERFACE_STRING_INDEX].id = ret;
1142                 acc_interface_desc.iInterface = ret;
1143         }
1144
1145         dev->cdev = c->cdev;
1146         dev->function.name = "accessory";
1147         dev->function.strings = acc_strings,
1148         dev->function.fs_descriptors = fs_acc_descs;
1149         dev->function.hs_descriptors = hs_acc_descs;
1150         dev->function.bind = acc_function_bind;
1151         dev->function.unbind = acc_function_unbind;
1152         dev->function.set_alt = acc_function_set_alt;
1153         dev->function.disable = acc_function_disable;
1154
1155         return usb_add_function(c, &dev->function);
1156 }
1157
1158 static int acc_setup(void)
1159 {
1160         struct acc_dev *dev;
1161         int ret;
1162
1163         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1164         if (!dev)
1165                 return -ENOMEM;
1166
1167         spin_lock_init(&dev->lock);
1168         init_waitqueue_head(&dev->read_wq);
1169         init_waitqueue_head(&dev->write_wq);
1170         atomic_set(&dev->open_excl, 0);
1171         INIT_LIST_HEAD(&dev->tx_idle);
1172         INIT_LIST_HEAD(&dev->hid_list);
1173         INIT_LIST_HEAD(&dev->new_hid_list);
1174         INIT_LIST_HEAD(&dev->dead_hid_list);
1175         INIT_DELAYED_WORK(&dev->start_work, acc_start_work);
1176         INIT_WORK(&dev->hid_work, acc_hid_work);
1177
1178         /* _acc_dev must be set before calling usb_gadget_register_driver */
1179         _acc_dev = dev;
1180
1181         ret = misc_register(&acc_device);
1182         if (ret)
1183                 goto err;
1184
1185         return 0;
1186
1187 err:
1188         kfree(dev);
1189         pr_err("USB accessory gadget driver failed to initialize\n");
1190         return ret;
1191 }
1192
1193 static void acc_disconnect(void)
1194 {
1195         /* unregister all HID devices if USB is disconnected */
1196         kill_all_hid_devices(_acc_dev);
1197 }
1198
1199 static void acc_cleanup(void)
1200 {
1201         misc_deregister(&acc_device);
1202         kfree(_acc_dev);
1203         _acc_dev = NULL;
1204 }