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