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