[go: nahoru, domu]

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
58struct 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
72struct 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
129static 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
139static 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
147static 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
155static 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
162static 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
169static 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
176static 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
183static struct usb_string acc_string_defs[] = {
184	[INTERFACE_STRING_INDEX].s	= "Android Accessory Interface",
185	{  },	/* end of list */
186};
187
188static struct usb_gadget_strings acc_string_table = {
189	.language		= 0x0409,	/* en-US */
190	.strings		= acc_string_defs,
191};
192
193static 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() */
199static struct acc_dev *_acc_dev;
200
201struct acc_instance {
202	struct usb_function_instance func_inst;
203	const char *name;
204};
205
206static inline struct acc_dev *func_to_dev(struct usb_function *f)
207{
208	return container_of(f, struct acc_dev, function);
209}
210
211static 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
227static 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 */
236static 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 */
247static 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
263static void acc_set_disconnected(struct acc_dev *dev)
264{
265	dev->online = 0;
266	dev->disconnected = 1;
267}
268
269static 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
283static 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
296static 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
344static 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
367static 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
381static 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
389static int acc_hid_start(struct hid_device *hid)
390{
391	return 0;
392}
393
394static void acc_hid_stop(struct hid_device *hid)
395{
396}
397
398static int acc_hid_open(struct hid_device *hid)
399{
400	return 0;
401}
402
403static void acc_hid_close(struct hid_device *hid)
404{
405}
406
407static 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
415static 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
435static 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
446static 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
477static 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
498static 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
554fail:
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
563static 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
596requeue_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
622copy_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
637done:
638	pr_debug("acc_read returning %zd\n", r);
639	return r;
640}
641
642static 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
712static 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
751static 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
762static 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 */
772static 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
781static 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
792static struct miscdevice acc_device = {
793	.minor = MISC_DYNAMIC_MINOR,
794	.name = "usb_accessory",
795	.fops = &acc_fops,
796};
797
798static const struct hid_device_id acc_hid_table[] = {
799	{ HID_USB_DEVICE(HID_ANY_ID, HID_ANY_ID) },
800	{ }
801};
802
803static struct hid_driver acc_hid_driver = {
804	.name = "USB accessory",
805	.id_table = acc_hid_table,
806	.probe = acc_hid_probe,
807};
808
809int 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
904err:
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}
913EXPORT_SYMBOL_GPL(acc_ctrlrequest);
914
915static 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
968static int
969acc_function_bind(struct usb_configuration *c, struct usb_function *f) {
970	return __acc_function_bind(c, f, false);
971}
972
973static int
974acc_function_bind_configfs(struct usb_configuration *c,
975			struct usb_function *f) {
976	return __acc_function_bind(c, f, true);
977}
978
979static void
980kill_all_hid_devices(struct acc_dev *dev)
981{
982	struct acc_hid_dev *hid;
983	struct list_head *entry, *temp;
984	unsigned long flags;
985
986	/* do nothing if usb accessory device doesn't exist */
987	if (!dev)
988		return;
989
990	spin_lock_irqsave(&dev->lock, flags);
991	list_for_each_safe(entry, temp, &dev->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	list_for_each_safe(entry, temp, &dev->new_hid_list) {
997		hid = list_entry(entry, struct acc_hid_dev, list);
998		list_del(&hid->list);
999		list_add(&hid->list, &dev->dead_hid_list);
1000	}
1001	spin_unlock_irqrestore(&dev->lock, flags);
1002
1003	schedule_work(&dev->hid_work);
1004}
1005
1006static void
1007acc_hid_unbind(struct acc_dev *dev)
1008{
1009	hid_unregister_driver(&acc_hid_driver);
1010	kill_all_hid_devices(dev);
1011}
1012
1013static void
1014acc_function_unbind(struct usb_configuration *c, struct usb_function *f)
1015{
1016	struct acc_dev	*dev = func_to_dev(f);
1017	struct usb_request *req;
1018	int i;
1019
1020	while ((req = req_get(dev, &dev->tx_idle)))
1021		acc_request_free(req, dev->ep_in);
1022	for (i = 0; i < RX_REQ_MAX; i++)
1023		acc_request_free(dev->rx_req[i], dev->ep_out);
1024
1025	acc_hid_unbind(dev);
1026}
1027
1028static void acc_start_work(struct work_struct *data)
1029{
1030	char *envp[2] = { "ACCESSORY=START", NULL };
1031	kobject_uevent_env(&acc_device.this_device->kobj, KOBJ_CHANGE, envp);
1032}
1033
1034static int acc_hid_init(struct acc_hid_dev *hdev)
1035{
1036	struct hid_device *hid;
1037	int ret;
1038
1039	hid = hid_allocate_device();
1040	if (IS_ERR(hid))
1041		return PTR_ERR(hid);
1042
1043	hid->ll_driver = &acc_hid_ll_driver;
1044	hid->dev.parent = acc_device.this_device;
1045
1046	hid->bus = BUS_USB;
1047	hid->vendor = HID_ANY_ID;
1048	hid->product = HID_ANY_ID;
1049	hid->driver_data = hdev;
1050	ret = hid_add_device(hid);
1051	if (ret) {
1052		pr_err("can't add hid device: %d\n", ret);
1053		hid_destroy_device(hid);
1054		return ret;
1055	}
1056
1057	hdev->hid = hid;
1058	return 0;
1059}
1060
1061static void acc_hid_delete(struct acc_hid_dev *hid)
1062{
1063	kfree(hid->report_desc);
1064	kfree(hid);
1065}
1066
1067static void acc_hid_work(struct work_struct *data)
1068{
1069	struct acc_dev *dev = _acc_dev;
1070	struct list_head	*entry, *temp;
1071	struct acc_hid_dev *hid;
1072	struct list_head	new_list, dead_list;
1073	unsigned long flags;
1074
1075	INIT_LIST_HEAD(&new_list);
1076
1077	spin_lock_irqsave(&dev->lock, flags);
1078
1079	/* copy hids that are ready for initialization to new_list */
1080	list_for_each_safe(entry, temp, &dev->new_hid_list) {
1081		hid = list_entry(entry, struct acc_hid_dev, list);
1082		if (hid->report_desc_offset == hid->report_desc_len)
1083			list_move(&hid->list, &new_list);
1084	}
1085
1086	if (list_empty(&dev->dead_hid_list)) {
1087		INIT_LIST_HEAD(&dead_list);
1088	} else {
1089		/* move all of dev->dead_hid_list to dead_list */
1090		dead_list.prev = dev->dead_hid_list.prev;
1091		dead_list.next = dev->dead_hid_list.next;
1092		dead_list.next->prev = &dead_list;
1093		dead_list.prev->next = &dead_list;
1094		INIT_LIST_HEAD(&dev->dead_hid_list);
1095	}
1096
1097	spin_unlock_irqrestore(&dev->lock, flags);
1098
1099	/* register new HID devices */
1100	list_for_each_safe(entry, temp, &new_list) {
1101		hid = list_entry(entry, struct acc_hid_dev, list);
1102		if (acc_hid_init(hid)) {
1103			pr_err("can't add HID device %p\n", hid);
1104			acc_hid_delete(hid);
1105		} else {
1106			spin_lock_irqsave(&dev->lock, flags);
1107			list_move(&hid->list, &dev->hid_list);
1108			spin_unlock_irqrestore(&dev->lock, flags);
1109		}
1110	}
1111
1112	/* remove dead HID devices */
1113	list_for_each_safe(entry, temp, &dead_list) {
1114		hid = list_entry(entry, struct acc_hid_dev, list);
1115		list_del(&hid->list);
1116		if (hid->hid)
1117			hid_destroy_device(hid->hid);
1118		acc_hid_delete(hid);
1119	}
1120}
1121
1122static int acc_function_set_alt(struct usb_function *f,
1123		unsigned intf, unsigned alt)
1124{
1125	struct acc_dev	*dev = func_to_dev(f);
1126	struct usb_composite_dev *cdev = f->config->cdev;
1127	int ret;
1128
1129	DBG(cdev, "acc_function_set_alt intf: %d alt: %d\n", intf, alt);
1130
1131	ret = config_ep_by_speed(cdev->gadget, f, dev->ep_in);
1132	if (ret)
1133		return ret;
1134
1135	ret = usb_ep_enable(dev->ep_in);
1136	if (ret)
1137		return ret;
1138
1139	ret = config_ep_by_speed(cdev->gadget, f, dev->ep_out);
1140	if (ret)
1141		return ret;
1142
1143	ret = usb_ep_enable(dev->ep_out);
1144	if (ret) {
1145		usb_ep_disable(dev->ep_in);
1146		return ret;
1147	}
1148
1149	dev->online = 1;
1150
1151	/* readers may be blocked waiting for us to go online */
1152	wake_up(&dev->read_wq);
1153	return 0;
1154}
1155
1156static void acc_function_disable(struct usb_function *f)
1157{
1158	struct acc_dev	*dev = func_to_dev(f);
1159	struct usb_composite_dev	*cdev = dev->cdev;
1160
1161	DBG(cdev, "acc_function_disable\n");
1162	acc_set_disconnected(dev);
1163	usb_ep_disable(dev->ep_in);
1164	usb_ep_disable(dev->ep_out);
1165
1166	/* readers may be blocked waiting for us to go online */
1167	wake_up(&dev->read_wq);
1168
1169	VDBG(cdev, "%s disabled\n", dev->function.name);
1170}
1171
1172static int acc_bind_config(struct usb_configuration *c)
1173{
1174	struct acc_dev *dev = _acc_dev;
1175	int ret;
1176
1177	printk(KERN_INFO "acc_bind_config\n");
1178
1179	/* allocate a string ID for our interface */
1180	if (acc_string_defs[INTERFACE_STRING_INDEX].id == 0) {
1181		ret = usb_string_id(c->cdev);
1182		if (ret < 0)
1183			return ret;
1184		acc_string_defs[INTERFACE_STRING_INDEX].id = ret;
1185		acc_interface_desc.iInterface = ret;
1186	}
1187
1188	dev->cdev = c->cdev;
1189	dev->function.name = "accessory";
1190	dev->function.strings = acc_strings,
1191	dev->function.fs_descriptors = fs_acc_descs;
1192	dev->function.hs_descriptors = hs_acc_descs;
1193	dev->function.bind = acc_function_bind;
1194	dev->function.unbind = acc_function_unbind;
1195	dev->function.set_alt = acc_function_set_alt;
1196	dev->function.disable = acc_function_disable;
1197
1198	return usb_add_function(c, &dev->function);
1199}
1200
1201static int acc_setup(void)
1202{
1203	struct acc_dev *dev;
1204	int ret;
1205
1206	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1207	if (!dev)
1208		return -ENOMEM;
1209
1210	spin_lock_init(&dev->lock);
1211	init_waitqueue_head(&dev->read_wq);
1212	init_waitqueue_head(&dev->write_wq);
1213	atomic_set(&dev->open_excl, 0);
1214	INIT_LIST_HEAD(&dev->tx_idle);
1215	INIT_LIST_HEAD(&dev->hid_list);
1216	INIT_LIST_HEAD(&dev->new_hid_list);
1217	INIT_LIST_HEAD(&dev->dead_hid_list);
1218	INIT_DELAYED_WORK(&dev->start_work, acc_start_work);
1219	INIT_WORK(&dev->hid_work, acc_hid_work);
1220
1221	/* _acc_dev must be set before calling usb_gadget_register_driver */
1222	_acc_dev = dev;
1223
1224	ret = misc_register(&acc_device);
1225	if (ret)
1226		goto err;
1227
1228	return 0;
1229
1230err:
1231	kfree(dev);
1232	pr_err("USB accessory gadget driver failed to initialize\n");
1233	return ret;
1234}
1235
1236void acc_disconnect(void)
1237{
1238	/* unregister all HID devices if USB is disconnected */
1239	kill_all_hid_devices(_acc_dev);
1240}
1241EXPORT_SYMBOL_GPL(acc_disconnect);
1242
1243static void acc_cleanup(void)
1244{
1245	misc_deregister(&acc_device);
1246	kfree(_acc_dev);
1247	_acc_dev = NULL;
1248}
1249static struct acc_instance *to_acc_instance(struct config_item *item)
1250{
1251	return container_of(to_config_group(item), struct acc_instance,
1252		func_inst.group);
1253}
1254
1255static void acc_attr_release(struct config_item *item)
1256{
1257	struct acc_instance *fi_acc = to_acc_instance(item);
1258
1259	usb_put_function_instance(&fi_acc->func_inst);
1260}
1261
1262static struct configfs_item_operations acc_item_ops = {
1263	.release        = acc_attr_release,
1264};
1265
1266static struct config_item_type acc_func_type = {
1267	.ct_item_ops    = &acc_item_ops,
1268	.ct_owner       = THIS_MODULE,
1269};
1270
1271static struct acc_instance *to_fi_acc(struct usb_function_instance *fi)
1272{
1273	return container_of(fi, struct acc_instance, func_inst);
1274}
1275
1276static int acc_set_inst_name(struct usb_function_instance *fi, const char *name)
1277{
1278	struct acc_instance *fi_acc;
1279	char *ptr;
1280	int name_len;
1281
1282	name_len = strlen(name) + 1;
1283	if (name_len > MAX_INST_NAME_LEN)
1284		return -ENAMETOOLONG;
1285
1286	ptr = kstrndup(name, name_len, GFP_KERNEL);
1287	if (!ptr)
1288		return -ENOMEM;
1289
1290	fi_acc = to_fi_acc(fi);
1291	fi_acc->name = ptr;
1292	return 0;
1293}
1294
1295static void acc_free_inst(struct usb_function_instance *fi)
1296{
1297	struct acc_instance *fi_acc;
1298
1299	fi_acc = to_fi_acc(fi);
1300	kfree(fi_acc->name);
1301	acc_cleanup();
1302}
1303
1304static struct usb_function_instance *acc_alloc_inst(void)
1305{
1306	struct acc_instance *fi_acc;
1307	struct acc_dev *dev;
1308	int err;
1309
1310	fi_acc = kzalloc(sizeof(*fi_acc), GFP_KERNEL);
1311	if (!fi_acc)
1312		return ERR_PTR(-ENOMEM);
1313	fi_acc->func_inst.set_inst_name = acc_set_inst_name;
1314	fi_acc->func_inst.free_func_inst = acc_free_inst;
1315
1316	err = acc_setup();
1317	if (err) {
1318		kfree(fi_acc);
1319		pr_err("Error setting ACCESSORY\n");
1320		return ERR_PTR(err);
1321	}
1322
1323	config_group_init_type_name(&fi_acc->func_inst.group,
1324					"", &acc_func_type);
1325	dev = _acc_dev;
1326	return  &fi_acc->func_inst;
1327}
1328
1329static void acc_free(struct usb_function *f)
1330{
1331/*NO-OP: no function specific resource allocation in mtp_alloc*/
1332}
1333
1334int acc_ctrlrequest_configfs(struct usb_function *f,
1335			const struct usb_ctrlrequest *ctrl) {
1336	if (f->config != NULL && f->config->cdev != NULL)
1337		return acc_ctrlrequest(f->config->cdev, ctrl);
1338	else
1339		return -1;
1340}
1341
1342static struct usb_function *acc_alloc(struct usb_function_instance *fi)
1343{
1344	struct acc_dev *dev = _acc_dev;
1345
1346	pr_info("acc_alloc\n");
1347
1348	dev->function.name = "accessory";
1349	dev->function.strings = acc_strings,
1350	dev->function.fs_descriptors = fs_acc_descs;
1351	dev->function.hs_descriptors = hs_acc_descs;
1352	dev->function.bind = acc_function_bind_configfs;
1353	dev->function.unbind = acc_function_unbind;
1354	dev->function.set_alt = acc_function_set_alt;
1355	dev->function.disable = acc_function_disable;
1356	dev->function.free_func = acc_free;
1357	dev->function.setup = acc_ctrlrequest_configfs;
1358
1359	return &dev->function;
1360}
1361DECLARE_USB_FUNCTION_INIT(accessory, acc_alloc_inst, acc_alloc);
1362MODULE_LICENSE("GPL");
1363