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