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