• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Gadget Function Driver for Android USB accessories
4  *
5  * Copyright (C) 2011 Google, Inc.
6  * Author: Mike Lockwood <lockwood@android.com>
7  *
8  * This software is licensed under the terms of the GNU General Public
9  * License version 2, as published by the Free Software Foundation, and
10  * may be copied, distributed, and modified under those terms.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  */
18 
19 /* #define DEBUG */
20 /* #define VERBOSE_DEBUG */
21 
22 #include <linux/module.h>
23 #include <linux/init.h>
24 #include <linux/poll.h>
25 #include <linux/delay.h>
26 #include <linux/wait.h>
27 #include <linux/err.h>
28 #include <linux/interrupt.h>
29 #include <linux/kthread.h>
30 #include <linux/freezer.h>
31 #include <linux/kref.h>
32 #include <linux/kernel.h>
33 
34 #include <linux/types.h>
35 #include <linux/file.h>
36 #include <linux/device.h>
37 #include <linux/miscdevice.h>
38 
39 #include <linux/hid.h>
40 #include <linux/hiddev.h>
41 #include <linux/usb.h>
42 #include <linux/usb/ch9.h>
43 #include <linux/usb/f_accessory.h>
44 
45 #include <linux/configfs.h>
46 #include <linux/usb/composite.h>
47 
48 #define MAX_INST_NAME_LEN        40
49 #define BULK_BUFFER_SIZE    16384
50 #define ACC_STRING_SIZE     256
51 
52 #define PROTOCOL_VERSION    2
53 
54 /* String IDs */
55 #define INTERFACE_STRING_INDEX	0
56 
57 /* number of tx and rx requests to allocate */
58 #define TX_REQ_MAX 4
59 #define RX_REQ_MAX 2
60 
61 struct acc_hid_dev {
62 	struct list_head	list;
63 	struct hid_device *hid;
64 	struct acc_dev *dev;
65 	/* accessory defined ID */
66 	int id;
67 	/* HID report descriptor */
68 	u8 *report_desc;
69 	/* length of HID report descriptor */
70 	int report_desc_len;
71 	/* number of bytes of report_desc we have received so far */
72 	int report_desc_offset;
73 };
74 
75 struct acc_dev {
76 	struct usb_function function;
77 	struct usb_composite_dev *cdev;
78 	spinlock_t lock;
79 	struct acc_dev_ref *ref;
80 
81 	struct usb_ep *ep_in;
82 	struct usb_ep *ep_out;
83 
84 	/* online indicates state of function_set_alt & function_unbind
85 	 * set to 1 when we connect
86 	 */
87 	int online;
88 
89 	/* disconnected indicates state of open & release
90 	 * Set to 1 when we disconnect.
91 	 * Not cleared until our file is closed.
92 	 */
93 	int disconnected;
94 
95 	/* strings sent by the host */
96 	char manufacturer[ACC_STRING_SIZE];
97 	char model[ACC_STRING_SIZE];
98 	char description[ACC_STRING_SIZE];
99 	char version[ACC_STRING_SIZE];
100 	char uri[ACC_STRING_SIZE];
101 	char serial[ACC_STRING_SIZE];
102 
103 	/* for acc_complete_set_string */
104 	int string_index;
105 
106 	/* set to 1 if we have a pending start request */
107 	int start_requested;
108 
109 	int audio_mode;
110 
111 	/* synchronize access to our device file */
112 	atomic_t open_excl;
113 
114 	struct list_head tx_idle;
115 
116 	wait_queue_head_t read_wq;
117 	wait_queue_head_t write_wq;
118 	struct usb_request *rx_req[RX_REQ_MAX];
119 	int rx_done;
120 
121 	/* delayed work for handling ACCESSORY_START */
122 	struct delayed_work start_work;
123 
124 	/* work for handling ACCESSORY GET PROTOCOL */
125 	struct work_struct getprotocol_work;
126 
127 	/* work for handling ACCESSORY SEND STRING */
128 	struct work_struct sendstring_work;
129 
130 	/* worker for registering and unregistering hid devices */
131 	struct work_struct hid_work;
132 
133 	/* list of active HID devices */
134 	struct list_head	hid_list;
135 
136 	/* list of new HID devices to register */
137 	struct list_head	new_hid_list;
138 
139 	/* list of dead HID devices to unregister */
140 	struct list_head	dead_hid_list;
141 };
142 
143 static struct usb_interface_descriptor acc_interface_desc = {
144 	.bLength                = USB_DT_INTERFACE_SIZE,
145 	.bDescriptorType        = USB_DT_INTERFACE,
146 	.bInterfaceNumber       = 0,
147 	.bNumEndpoints          = 2,
148 	.bInterfaceClass        = USB_CLASS_VENDOR_SPEC,
149 	.bInterfaceSubClass     = USB_SUBCLASS_VENDOR_SPEC,
150 	.bInterfaceProtocol     = 0,
151 };
152 
153 static struct usb_endpoint_descriptor acc_superspeedplus_in_desc = {
154 	.bLength                = USB_DT_ENDPOINT_SIZE,
155 	.bDescriptorType        = USB_DT_ENDPOINT,
156 	.bEndpointAddress       = USB_DIR_IN,
157 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
158 	.wMaxPacketSize         = cpu_to_le16(1024),
159 };
160 
161 static struct usb_endpoint_descriptor acc_superspeedplus_out_desc = {
162 	.bLength                = USB_DT_ENDPOINT_SIZE,
163 	.bDescriptorType        = USB_DT_ENDPOINT,
164 	.bEndpointAddress       = USB_DIR_OUT,
165 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
166 	.wMaxPacketSize         = cpu_to_le16(1024),
167 };
168 
169 static struct usb_ss_ep_comp_descriptor acc_superspeedplus_comp_desc = {
170 	.bLength                = sizeof(acc_superspeedplus_comp_desc),
171 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
172 
173 	/* the following 2 values can be tweaked if necessary */
174 	/* .bMaxBurst =         0, */
175 	/* .bmAttributes =      0, */
176 };
177 
178 static struct usb_endpoint_descriptor acc_superspeed_in_desc = {
179 	.bLength                = USB_DT_ENDPOINT_SIZE,
180 	.bDescriptorType        = USB_DT_ENDPOINT,
181 	.bEndpointAddress       = USB_DIR_IN,
182 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
183 	.wMaxPacketSize         = cpu_to_le16(1024),
184 };
185 
186 static struct usb_endpoint_descriptor acc_superspeed_out_desc = {
187 	.bLength                = USB_DT_ENDPOINT_SIZE,
188 	.bDescriptorType        = USB_DT_ENDPOINT,
189 	.bEndpointAddress       = USB_DIR_OUT,
190 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
191 	.wMaxPacketSize         = cpu_to_le16(1024),
192 };
193 
194 static struct usb_ss_ep_comp_descriptor acc_superspeed_comp_desc = {
195 	.bLength                = sizeof(acc_superspeed_comp_desc),
196 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
197 
198 	/* the following 2 values can be tweaked if necessary */
199 	/* .bMaxBurst =         0, */
200 	/* .bmAttributes =      0, */
201 };
202 
203 static struct usb_endpoint_descriptor acc_highspeed_in_desc = {
204 	.bLength                = USB_DT_ENDPOINT_SIZE,
205 	.bDescriptorType        = USB_DT_ENDPOINT,
206 	.bEndpointAddress       = USB_DIR_IN,
207 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
208 	.wMaxPacketSize         = cpu_to_le16(512),
209 };
210 
211 static struct usb_endpoint_descriptor acc_highspeed_out_desc = {
212 	.bLength                = USB_DT_ENDPOINT_SIZE,
213 	.bDescriptorType        = USB_DT_ENDPOINT,
214 	.bEndpointAddress       = USB_DIR_OUT,
215 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
216 	.wMaxPacketSize         = cpu_to_le16(512),
217 };
218 
219 static struct usb_endpoint_descriptor acc_fullspeed_in_desc = {
220 	.bLength                = USB_DT_ENDPOINT_SIZE,
221 	.bDescriptorType        = USB_DT_ENDPOINT,
222 	.bEndpointAddress       = USB_DIR_IN,
223 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
224 };
225 
226 static struct usb_endpoint_descriptor acc_fullspeed_out_desc = {
227 	.bLength                = USB_DT_ENDPOINT_SIZE,
228 	.bDescriptorType        = USB_DT_ENDPOINT,
229 	.bEndpointAddress       = USB_DIR_OUT,
230 	.bmAttributes           = USB_ENDPOINT_XFER_BULK,
231 };
232 
233 static struct usb_descriptor_header *fs_acc_descs[] = {
234 	(struct usb_descriptor_header *) &acc_interface_desc,
235 	(struct usb_descriptor_header *) &acc_fullspeed_in_desc,
236 	(struct usb_descriptor_header *) &acc_fullspeed_out_desc,
237 	NULL,
238 };
239 
240 static struct usb_descriptor_header *hs_acc_descs[] = {
241 	(struct usb_descriptor_header *) &acc_interface_desc,
242 	(struct usb_descriptor_header *) &acc_highspeed_in_desc,
243 	(struct usb_descriptor_header *) &acc_highspeed_out_desc,
244 	NULL,
245 };
246 
247 static struct usb_descriptor_header *ss_acc_descs[] = {
248 	(struct usb_descriptor_header *) &acc_interface_desc,
249 	(struct usb_descriptor_header *) &acc_superspeed_in_desc,
250 	(struct usb_descriptor_header *) &acc_superspeed_comp_desc,
251 	(struct usb_descriptor_header *) &acc_superspeed_out_desc,
252 	(struct usb_descriptor_header *) &acc_superspeed_comp_desc,
253 	NULL,
254 };
255 
256 static struct usb_descriptor_header *ssp_acc_descs[] = {
257 	(struct usb_descriptor_header *) &acc_interface_desc,
258 	(struct usb_descriptor_header *) &acc_superspeedplus_in_desc,
259 	(struct usb_descriptor_header *) &acc_superspeedplus_comp_desc,
260 	(struct usb_descriptor_header *) &acc_superspeedplus_out_desc,
261 	(struct usb_descriptor_header *) &acc_superspeedplus_comp_desc,
262 	NULL,
263 };
264 
265 static struct usb_string acc_string_defs[] = {
266 	[INTERFACE_STRING_INDEX].s	= "Android Accessory Interface",
267 	{  },	/* end of list */
268 };
269 
270 static struct usb_gadget_strings acc_string_table = {
271 	.language		= 0x0409,	/* en-US */
272 	.strings		= acc_string_defs,
273 };
274 
275 static struct usb_gadget_strings *acc_strings[] = {
276 	&acc_string_table,
277 	NULL,
278 };
279 
280 struct acc_dev_ref {
281 	struct kref	kref;
282 	struct acc_dev	*acc_dev;
283 };
284 
285 static struct acc_dev_ref _acc_dev_ref = {
286 	.kref = KREF_INIT(0),
287 };
288 
289 struct acc_instance {
290 	struct usb_function_instance func_inst;
291 	const char *name;
292 };
293 
get_acc_dev(void)294 static struct acc_dev *get_acc_dev(void)
295 {
296 	struct acc_dev_ref *ref = &_acc_dev_ref;
297 
298 	return kref_get_unless_zero(&ref->kref) ? ref->acc_dev : NULL;
299 }
300 
__put_acc_dev(struct kref * kref)301 static void __put_acc_dev(struct kref *kref)
302 {
303 	struct acc_dev_ref *ref = container_of(kref, struct acc_dev_ref, kref);
304 	struct acc_dev *dev = ref->acc_dev;
305 
306 	/* Cancel any async work */
307 	cancel_delayed_work_sync(&dev->start_work);
308 	cancel_work_sync(&dev->getprotocol_work);
309 	cancel_work_sync(&dev->sendstring_work);
310 	cancel_work_sync(&dev->hid_work);
311 
312 	ref->acc_dev = NULL;
313 	kfree(dev);
314 }
315 
put_acc_dev(struct acc_dev * dev)316 static void put_acc_dev(struct acc_dev *dev)
317 {
318 	struct acc_dev_ref *ref = dev->ref;
319 
320 	WARN_ON(ref->acc_dev != dev);
321 	kref_put(&ref->kref, __put_acc_dev);
322 }
323 
func_to_dev(struct usb_function * f)324 static inline struct acc_dev *func_to_dev(struct usb_function *f)
325 {
326 	return container_of(f, struct acc_dev, function);
327 }
328 
acc_request_new(struct usb_ep * ep,int buffer_size)329 static struct usb_request *acc_request_new(struct usb_ep *ep, int buffer_size)
330 {
331 	struct usb_request *req = usb_ep_alloc_request(ep, GFP_KERNEL);
332 
333 	if (!req)
334 		return NULL;
335 
336 	/* now allocate buffers for the requests */
337 	req->buf = kmalloc(buffer_size, GFP_KERNEL);
338 	if (!req->buf) {
339 		usb_ep_free_request(ep, req);
340 		return NULL;
341 	}
342 
343 	return req;
344 }
345 
acc_request_free(struct usb_request * req,struct usb_ep * ep)346 static void acc_request_free(struct usb_request *req, struct usb_ep *ep)
347 {
348 	if (req) {
349 		kfree(req->buf);
350 		usb_ep_free_request(ep, req);
351 	}
352 }
353 
354 /* add a request to the tail of a list */
req_put(struct acc_dev * dev,struct list_head * head,struct usb_request * req)355 static void req_put(struct acc_dev *dev, struct list_head *head,
356 		struct usb_request *req)
357 {
358 	unsigned long flags;
359 
360 	spin_lock_irqsave(&dev->lock, flags);
361 	list_add_tail(&req->list, head);
362 	spin_unlock_irqrestore(&dev->lock, flags);
363 }
364 
365 /* remove a request from the head of a list */
req_get(struct acc_dev * dev,struct list_head * head)366 static struct usb_request *req_get(struct acc_dev *dev, struct list_head *head)
367 {
368 	unsigned long flags;
369 	struct usb_request *req;
370 
371 	spin_lock_irqsave(&dev->lock, flags);
372 	if (list_empty(head)) {
373 		req = 0;
374 	} else {
375 		req = list_first_entry(head, struct usb_request, list);
376 		list_del(&req->list);
377 	}
378 	spin_unlock_irqrestore(&dev->lock, flags);
379 	return req;
380 }
381 
acc_set_disconnected(struct acc_dev * dev)382 static void acc_set_disconnected(struct acc_dev *dev)
383 {
384 	dev->disconnected = 1;
385 }
386 
acc_complete_in(struct usb_ep * ep,struct usb_request * req)387 static void acc_complete_in(struct usb_ep *ep, struct usb_request *req)
388 {
389 	struct acc_dev *dev = get_acc_dev();
390 
391 	if (!dev)
392 		return;
393 
394 	if (req->status == -ESHUTDOWN) {
395 		pr_debug("acc_complete_in set disconnected");
396 		acc_set_disconnected(dev);
397 	}
398 
399 	req_put(dev, &dev->tx_idle, req);
400 
401 	wake_up(&dev->write_wq);
402 	put_acc_dev(dev);
403 }
404 
acc_complete_out(struct usb_ep * ep,struct usb_request * req)405 static void acc_complete_out(struct usb_ep *ep, struct usb_request *req)
406 {
407 	struct acc_dev *dev = get_acc_dev();
408 
409 	if (!dev)
410 		return;
411 
412 	dev->rx_done = 1;
413 	if (req->status == -ESHUTDOWN) {
414 		pr_debug("acc_complete_out set disconnected");
415 		acc_set_disconnected(dev);
416 	}
417 
418 	wake_up(&dev->read_wq);
419 	put_acc_dev(dev);
420 }
421 
acc_complete_set_string(struct usb_ep * ep,struct usb_request * req)422 static void acc_complete_set_string(struct usb_ep *ep, struct usb_request *req)
423 {
424 	struct acc_dev	*dev = ep->driver_data;
425 	char *string_dest = NULL;
426 	int length = req->actual;
427 
428 	if (req->status != 0) {
429 		pr_err("acc_complete_set_string, err %d\n", req->status);
430 		return;
431 	}
432 
433 	switch (dev->string_index) {
434 	case ACCESSORY_STRING_MANUFACTURER:
435 		string_dest = dev->manufacturer;
436 		break;
437 	case ACCESSORY_STRING_MODEL:
438 		string_dest = dev->model;
439 		break;
440 	case ACCESSORY_STRING_DESCRIPTION:
441 		string_dest = dev->description;
442 		break;
443 	case ACCESSORY_STRING_VERSION:
444 		string_dest = dev->version;
445 		break;
446 	case ACCESSORY_STRING_URI:
447 		string_dest = dev->uri;
448 		break;
449 	case ACCESSORY_STRING_SERIAL:
450 		string_dest = dev->serial;
451 		break;
452 	}
453 	if (string_dest) {
454 		unsigned long flags;
455 
456 		if (length >= ACC_STRING_SIZE)
457 			length = ACC_STRING_SIZE - 1;
458 
459 		spin_lock_irqsave(&dev->lock, flags);
460 		memcpy(string_dest, req->buf, length);
461 		/* ensure zero termination */
462 		string_dest[length] = 0;
463 		spin_unlock_irqrestore(&dev->lock, flags);
464 	} else {
465 		pr_err("unknown accessory string index %d\n",
466 			dev->string_index);
467 	}
468 }
469 
acc_complete_set_hid_report_desc(struct usb_ep * ep,struct usb_request * req)470 static void acc_complete_set_hid_report_desc(struct usb_ep *ep,
471 		struct usb_request *req)
472 {
473 	struct acc_hid_dev *hid = req->context;
474 	struct acc_dev *dev = hid->dev;
475 	int length = req->actual;
476 
477 	if (req->status != 0) {
478 		pr_err("acc_complete_set_hid_report_desc, err %d\n",
479 			req->status);
480 		return;
481 	}
482 
483 	memcpy(hid->report_desc + hid->report_desc_offset, req->buf, length);
484 	hid->report_desc_offset += length;
485 	if (hid->report_desc_offset == hid->report_desc_len) {
486 		/* After we have received the entire report descriptor
487 		 * we schedule work to initialize the HID device
488 		 */
489 		schedule_work(&dev->hid_work);
490 	}
491 }
492 
acc_complete_send_hid_event(struct usb_ep * ep,struct usb_request * req)493 static void acc_complete_send_hid_event(struct usb_ep *ep,
494 		struct usb_request *req)
495 {
496 	struct acc_hid_dev *hid = req->context;
497 	int length = req->actual;
498 
499 	if (req->status != 0) {
500 		pr_err("acc_complete_send_hid_event, err %d\n", req->status);
501 		return;
502 	}
503 
504 	hid_report_raw_event(hid->hid, HID_INPUT_REPORT, req->buf, length, 1);
505 }
506 
acc_hid_parse(struct hid_device * hid)507 static int acc_hid_parse(struct hid_device *hid)
508 {
509 	struct acc_hid_dev *hdev = hid->driver_data;
510 
511 	hid_parse_report(hid, hdev->report_desc, hdev->report_desc_len);
512 	return 0;
513 }
514 
acc_hid_start(struct hid_device * hid)515 static int acc_hid_start(struct hid_device *hid)
516 {
517 	return 0;
518 }
519 
acc_hid_stop(struct hid_device * hid)520 static void acc_hid_stop(struct hid_device *hid)
521 {
522 }
523 
acc_hid_open(struct hid_device * hid)524 static int acc_hid_open(struct hid_device *hid)
525 {
526 	return 0;
527 }
528 
acc_hid_close(struct hid_device * hid)529 static void acc_hid_close(struct hid_device *hid)
530 {
531 }
532 
acc_hid_raw_request(struct hid_device * hid,unsigned char reportnum,__u8 * buf,size_t len,unsigned char rtype,int reqtype)533 static int acc_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
534 	__u8 *buf, size_t len, unsigned char rtype, int reqtype)
535 {
536 	return 0;
537 }
538 
539 static struct hid_ll_driver acc_hid_ll_driver = {
540 	.parse = acc_hid_parse,
541 	.start = acc_hid_start,
542 	.stop = acc_hid_stop,
543 	.open = acc_hid_open,
544 	.close = acc_hid_close,
545 	.raw_request = acc_hid_raw_request,
546 };
547 
acc_hid_new(struct acc_dev * dev,int id,int desc_len)548 static struct acc_hid_dev *acc_hid_new(struct acc_dev *dev,
549 		int id, int desc_len)
550 {
551 	struct acc_hid_dev *hdev;
552 
553 	hdev = kzalloc(sizeof(*hdev), GFP_ATOMIC);
554 	if (!hdev)
555 		return NULL;
556 	hdev->report_desc = kzalloc(desc_len, GFP_ATOMIC);
557 	if (!hdev->report_desc) {
558 		kfree(hdev);
559 		return NULL;
560 	}
561 	hdev->dev = dev;
562 	hdev->id = id;
563 	hdev->report_desc_len = desc_len;
564 
565 	return hdev;
566 }
567 
acc_hid_get(struct list_head * list,int id)568 static struct acc_hid_dev *acc_hid_get(struct list_head *list, int id)
569 {
570 	struct acc_hid_dev *hid;
571 
572 	list_for_each_entry(hid, list, list) {
573 		if (hid->id == id)
574 			return hid;
575 	}
576 	return NULL;
577 }
578 
acc_register_hid(struct acc_dev * dev,int id,int desc_length)579 static int acc_register_hid(struct acc_dev *dev, int id, int desc_length)
580 {
581 	struct acc_hid_dev *hid;
582 	unsigned long flags;
583 
584 	/* report descriptor length must be > 0 */
585 	if (desc_length <= 0)
586 		return -EINVAL;
587 
588 	spin_lock_irqsave(&dev->lock, flags);
589 	/* replace HID if one already exists with this ID */
590 	hid = acc_hid_get(&dev->hid_list, id);
591 	if (!hid)
592 		hid = acc_hid_get(&dev->new_hid_list, id);
593 	if (hid)
594 		list_move(&hid->list, &dev->dead_hid_list);
595 
596 	hid = acc_hid_new(dev, id, desc_length);
597 	if (!hid) {
598 		spin_unlock_irqrestore(&dev->lock, flags);
599 		return -ENOMEM;
600 	}
601 
602 	list_add(&hid->list, &dev->new_hid_list);
603 	spin_unlock_irqrestore(&dev->lock, flags);
604 
605 	/* schedule work to register the HID device */
606 	schedule_work(&dev->hid_work);
607 	return 0;
608 }
609 
acc_unregister_hid(struct acc_dev * dev,int id)610 static int acc_unregister_hid(struct acc_dev *dev, int id)
611 {
612 	struct acc_hid_dev *hid;
613 	unsigned long flags;
614 
615 	spin_lock_irqsave(&dev->lock, flags);
616 	hid = acc_hid_get(&dev->hid_list, id);
617 	if (!hid)
618 		hid = acc_hid_get(&dev->new_hid_list, id);
619 	if (!hid) {
620 		spin_unlock_irqrestore(&dev->lock, flags);
621 		return -EINVAL;
622 	}
623 
624 	list_move(&hid->list, &dev->dead_hid_list);
625 	spin_unlock_irqrestore(&dev->lock, flags);
626 
627 	schedule_work(&dev->hid_work);
628 	return 0;
629 }
630 
create_bulk_endpoints(struct acc_dev * dev,struct usb_endpoint_descriptor * in_desc,struct usb_endpoint_descriptor * out_desc)631 static int create_bulk_endpoints(struct acc_dev *dev,
632 				struct usb_endpoint_descriptor *in_desc,
633 				struct usb_endpoint_descriptor *out_desc)
634 {
635 	struct usb_composite_dev *cdev = dev->cdev;
636 	struct usb_request *req;
637 	struct usb_ep *ep;
638 	int i;
639 
640 	DBG(cdev, "create_bulk_endpoints dev: %p\n", dev);
641 
642 	ep = usb_ep_autoconfig(cdev->gadget, in_desc);
643 	if (!ep) {
644 		DBG(cdev, "usb_ep_autoconfig for ep_in failed\n");
645 		return -ENODEV;
646 	}
647 	DBG(cdev, "usb_ep_autoconfig for ep_in got %s\n", ep->name);
648 	ep->driver_data = dev;		/* claim the endpoint */
649 	dev->ep_in = ep;
650 
651 	ep = usb_ep_autoconfig(cdev->gadget, out_desc);
652 	if (!ep) {
653 		DBG(cdev, "usb_ep_autoconfig for ep_out failed\n");
654 		return -ENODEV;
655 	}
656 	DBG(cdev, "usb_ep_autoconfig for ep_out got %s\n", ep->name);
657 	ep->driver_data = dev;		/* claim the endpoint */
658 	dev->ep_out = ep;
659 
660 	/* now allocate requests for our endpoints */
661 	for (i = 0; i < TX_REQ_MAX; i++) {
662 		req = acc_request_new(dev->ep_in, BULK_BUFFER_SIZE);
663 		if (!req)
664 			goto fail;
665 		req->complete = acc_complete_in;
666 		req_put(dev, &dev->tx_idle, req);
667 	}
668 	for (i = 0; i < RX_REQ_MAX; i++) {
669 		req = acc_request_new(dev->ep_out, BULK_BUFFER_SIZE);
670 		if (!req)
671 			goto fail;
672 		req->complete = acc_complete_out;
673 		dev->rx_req[i] = req;
674 	}
675 
676 	return 0;
677 
678 fail:
679 	pr_err("acc_bind() could not allocate requests\n");
680 	while ((req = req_get(dev, &dev->tx_idle)))
681 		acc_request_free(req, dev->ep_in);
682 	for (i = 0; i < RX_REQ_MAX; i++) {
683 		acc_request_free(dev->rx_req[i], dev->ep_out);
684 		dev->rx_req[i] = NULL;
685 	}
686 
687 	return -1;
688 }
689 
acc_read(struct file * fp,char __user * buf,size_t count,loff_t * pos)690 static ssize_t acc_read(struct file *fp, char __user *buf,
691 	size_t count, loff_t *pos)
692 {
693 	struct acc_dev *dev = fp->private_data;
694 	struct usb_request *req;
695 	ssize_t r = count;
696 	ssize_t data_length;
697 	unsigned xfer;
698 	int ret = 0;
699 
700 	pr_debug("acc_read(%zu)\n", count);
701 
702 	if (dev->disconnected) {
703 		pr_debug("acc_read disconnected");
704 		return -ENODEV;
705 	}
706 
707 	if (count > BULK_BUFFER_SIZE)
708 		count = BULK_BUFFER_SIZE;
709 
710 	/* we will block until we're online */
711 	pr_debug("acc_read: waiting for online\n");
712 	ret = wait_event_interruptible(dev->read_wq, dev->online);
713 	if (ret < 0) {
714 		r = ret;
715 		goto done;
716 	}
717 
718 	if (!dev->rx_req[0]) {
719 		pr_warn("acc_read: USB request already handled/freed");
720 		r = -EINVAL;
721 		goto done;
722 	}
723 
724 	/*
725 	 * Calculate the data length by considering termination character.
726 	 * Then compansite the difference of rounding up to
727 	 * integer multiple of maxpacket size.
728 	 */
729 	data_length = count;
730 	data_length += dev->ep_out->maxpacket - 1;
731 	data_length -= data_length % dev->ep_out->maxpacket;
732 
733 	if (dev->rx_done) {
734 		// last req cancelled. try to get it.
735 		req = dev->rx_req[0];
736 		goto copy_data;
737 	}
738 
739 requeue_req:
740 	/* queue a request */
741 	req = dev->rx_req[0];
742 	req->length = data_length;
743 	dev->rx_done = 0;
744 	ret = usb_ep_queue(dev->ep_out, req, GFP_KERNEL);
745 	if (ret < 0) {
746 		r = -EIO;
747 		goto done;
748 	} else {
749 		pr_debug("rx %p queue\n", req);
750 	}
751 
752 	/* wait for a request to complete */
753 	ret = wait_event_interruptible(dev->read_wq, dev->rx_done);
754 	if (ret < 0) {
755 		r = ret;
756 		ret = usb_ep_dequeue(dev->ep_out, req);
757 		if (ret != 0) {
758 			// cancel failed. There can be a data already received.
759 			// it will be retrieved in the next read.
760 			pr_debug("acc_read: cancelling failed %d", ret);
761 		}
762 		goto done;
763 	}
764 
765 copy_data:
766 	dev->rx_done = 0;
767 	if (dev->online) {
768 		/* If we got a 0-len packet, throw it back and try again. */
769 		if (req->actual == 0)
770 			goto requeue_req;
771 
772 		pr_debug("rx %p %u\n", req, req->actual);
773 		xfer = (req->actual < count) ? req->actual : count;
774 		r = xfer;
775 		if (copy_to_user(buf, req->buf, xfer))
776 			r = -EFAULT;
777 	} else
778 		r = -EIO;
779 
780 done:
781 	pr_debug("acc_read returning %zd\n", r);
782 	return r;
783 }
784 
acc_write(struct file * fp,const char __user * buf,size_t count,loff_t * pos)785 static ssize_t acc_write(struct file *fp, const char __user *buf,
786 	size_t count, loff_t *pos)
787 {
788 	struct acc_dev *dev = fp->private_data;
789 	struct usb_request *req = 0;
790 	ssize_t r = count;
791 	unsigned xfer;
792 	int ret;
793 
794 	pr_debug("acc_write(%zu)\n", count);
795 
796 	if (!dev->online || dev->disconnected) {
797 		pr_debug("acc_write disconnected or not online");
798 		return -ENODEV;
799 	}
800 
801 	while (count > 0) {
802 		/* get an idle tx request to use */
803 		req = 0;
804 		ret = wait_event_interruptible(dev->write_wq,
805 			((req = req_get(dev, &dev->tx_idle)) || !dev->online));
806 		if (!dev->online || dev->disconnected) {
807 			pr_debug("acc_write dev->error\n");
808 			r = -EIO;
809 			break;
810 		}
811 
812 		if (!req) {
813 			r = ret;
814 			break;
815 		}
816 
817 		if (count > BULK_BUFFER_SIZE) {
818 			xfer = BULK_BUFFER_SIZE;
819 			/* ZLP, They will be more TX requests so not yet. */
820 			req->zero = 0;
821 		} else {
822 			xfer = count;
823 			/* If the data length is a multple of the
824 			 * maxpacket size then send a zero length packet(ZLP).
825 			*/
826 			req->zero = ((xfer % dev->ep_in->maxpacket) == 0);
827 		}
828 		if (copy_from_user(req->buf, buf, xfer)) {
829 			r = -EFAULT;
830 			break;
831 		}
832 
833 		req->length = xfer;
834 		ret = usb_ep_queue(dev->ep_in, req, GFP_KERNEL);
835 		if (ret < 0) {
836 			pr_debug("acc_write: xfer error %d\n", ret);
837 			r = -EIO;
838 			break;
839 		}
840 
841 		buf += xfer;
842 		count -= xfer;
843 
844 		/* zero this so we don't try to free it on error exit */
845 		req = 0;
846 	}
847 
848 	if (req)
849 		req_put(dev, &dev->tx_idle, req);
850 
851 	pr_debug("acc_write returning %zd\n", r);
852 	return r;
853 }
854 
acc_ioctl(struct file * fp,unsigned code,unsigned long value)855 static long acc_ioctl(struct file *fp, unsigned code, unsigned long value)
856 {
857 	struct acc_dev *dev = fp->private_data;
858 	char *src = NULL;
859 	int ret;
860 
861 	switch (code) {
862 	case ACCESSORY_GET_STRING_MANUFACTURER:
863 		src = dev->manufacturer;
864 		break;
865 	case ACCESSORY_GET_STRING_MODEL:
866 		src = dev->model;
867 		break;
868 	case ACCESSORY_GET_STRING_DESCRIPTION:
869 		src = dev->description;
870 		break;
871 	case ACCESSORY_GET_STRING_VERSION:
872 		src = dev->version;
873 		break;
874 	case ACCESSORY_GET_STRING_URI:
875 		src = dev->uri;
876 		break;
877 	case ACCESSORY_GET_STRING_SERIAL:
878 		src = dev->serial;
879 		break;
880 	case ACCESSORY_IS_START_REQUESTED:
881 		return dev->start_requested;
882 	case ACCESSORY_GET_AUDIO_MODE:
883 		return dev->audio_mode;
884 	}
885 	if (!src)
886 		return -EINVAL;
887 
888 	ret = strlen(src) + 1;
889 	if (copy_to_user((void __user *)value, src, ret))
890 		ret = -EFAULT;
891 	return ret;
892 }
893 
acc_open(struct inode * ip,struct file * fp)894 static int acc_open(struct inode *ip, struct file *fp)
895 {
896 	struct acc_dev *dev = get_acc_dev();
897 
898 	if (!dev)
899 		return -ENODEV;
900 
901 	if (atomic_xchg(&dev->open_excl, 1)) {
902 		put_acc_dev(dev);
903 		return -EBUSY;
904 	}
905 
906 	dev->disconnected = 0;
907 	fp->private_data = dev;
908 	return 0;
909 }
910 
acc_release(struct inode * ip,struct file * fp)911 static int acc_release(struct inode *ip, struct file *fp)
912 {
913 	struct acc_dev *dev = fp->private_data;
914 
915 	if (!dev)
916 		return -ENOENT;
917 
918 	/* indicate that we are disconnected
919 	 * still could be online so don't touch online flag
920 	 */
921 	dev->disconnected = 1;
922 
923 	fp->private_data = NULL;
924 	WARN_ON(!atomic_xchg(&dev->open_excl, 0));
925 	put_acc_dev(dev);
926 	return 0;
927 }
928 
929 /* file operations for /dev/usb_accessory */
930 static const struct file_operations acc_fops = {
931 	.owner = THIS_MODULE,
932 	.read = acc_read,
933 	.write = acc_write,
934 	.unlocked_ioctl = acc_ioctl,
935 	.compat_ioctl = acc_ioctl,
936 	.open = acc_open,
937 	.release = acc_release,
938 };
939 
acc_hid_probe(struct hid_device * hdev,const struct hid_device_id * id)940 static int acc_hid_probe(struct hid_device *hdev,
941 		const struct hid_device_id *id)
942 {
943 	int ret;
944 
945 	ret = hid_parse(hdev);
946 	if (ret)
947 		return ret;
948 	return hid_hw_start(hdev, HID_CONNECT_DEFAULT);
949 }
950 
951 static struct miscdevice acc_device = {
952 	.minor = MISC_DYNAMIC_MINOR,
953 	.name = "usb_accessory",
954 	.fops = &acc_fops,
955 };
956 
957 static const struct hid_device_id acc_hid_table[] = {
958 	{ HID_USB_DEVICE(HID_ANY_ID, HID_ANY_ID) },
959 	{ }
960 };
961 
962 static struct hid_driver acc_hid_driver = {
963 	.name = "USB accessory",
964 	.id_table = acc_hid_table,
965 	.probe = acc_hid_probe,
966 };
967 
acc_complete_setup_noop(struct usb_ep * ep,struct usb_request * req)968 static void acc_complete_setup_noop(struct usb_ep *ep, struct usb_request *req)
969 {
970 	/*
971 	 * Default no-op function when nothing needs to be done for the
972 	 * setup request
973 	 */
974 }
975 
acc_ctrlrequest(struct usb_composite_dev * cdev,const struct usb_ctrlrequest * ctrl)976 int acc_ctrlrequest(struct usb_composite_dev *cdev,
977 				const struct usb_ctrlrequest *ctrl)
978 {
979 	struct acc_dev	*dev = get_acc_dev();
980 	int	value = -EOPNOTSUPP;
981 	struct acc_hid_dev *hid;
982 	int offset;
983 	u8 b_requestType = ctrl->bRequestType;
984 	u8 b_request = ctrl->bRequest;
985 	u16	w_index = le16_to_cpu(ctrl->wIndex);
986 	u16	w_value = le16_to_cpu(ctrl->wValue);
987 	u16	w_length = le16_to_cpu(ctrl->wLength);
988 	unsigned long flags;
989 
990 	/*
991 	 * If instance is not created which is the case in power off charging
992 	 * mode, dev will be NULL. Hence return error if it is the case.
993 	 */
994 	if (!dev)
995 		return -ENODEV;
996 
997 	if (b_requestType == (USB_DIR_OUT | USB_TYPE_VENDOR)) {
998 		if (b_request == ACCESSORY_START) {
999 			dev->start_requested = 1;
1000 			schedule_delayed_work(
1001 				&dev->start_work, msecs_to_jiffies(10));
1002 			value = 0;
1003 			cdev->req->complete = acc_complete_setup_noop;
1004 		} else if (b_request == ACCESSORY_SEND_STRING) {
1005 			schedule_work(&dev->sendstring_work);
1006 			dev->string_index = w_index;
1007 			cdev->gadget->ep0->driver_data = dev;
1008 			cdev->req->complete = acc_complete_set_string;
1009 			value = w_length;
1010 		} else if (b_request == ACCESSORY_SET_AUDIO_MODE &&
1011 				w_index == 0 && w_length == 0) {
1012 			dev->audio_mode = w_value;
1013 			cdev->req->complete = acc_complete_setup_noop;
1014 			value = 0;
1015 		} else if (b_request == ACCESSORY_REGISTER_HID) {
1016 			cdev->req->complete = acc_complete_setup_noop;
1017 			value = acc_register_hid(dev, w_value, w_index);
1018 		} else if (b_request == ACCESSORY_UNREGISTER_HID) {
1019 			cdev->req->complete = acc_complete_setup_noop;
1020 			value = acc_unregister_hid(dev, w_value);
1021 		} else if (b_request == ACCESSORY_SET_HID_REPORT_DESC) {
1022 			spin_lock_irqsave(&dev->lock, flags);
1023 			hid = acc_hid_get(&dev->new_hid_list, w_value);
1024 			spin_unlock_irqrestore(&dev->lock, flags);
1025 			if (!hid) {
1026 				value = -EINVAL;
1027 				goto err;
1028 			}
1029 			offset = w_index;
1030 			if (offset != hid->report_desc_offset
1031 				|| offset + w_length > hid->report_desc_len) {
1032 				value = -EINVAL;
1033 				goto err;
1034 			}
1035 			cdev->req->context = hid;
1036 			cdev->req->complete = acc_complete_set_hid_report_desc;
1037 			value = w_length;
1038 		} else if (b_request == ACCESSORY_SEND_HID_EVENT) {
1039 			spin_lock_irqsave(&dev->lock, flags);
1040 			hid = acc_hid_get(&dev->hid_list, w_value);
1041 			spin_unlock_irqrestore(&dev->lock, flags);
1042 			if (!hid) {
1043 				value = -EINVAL;
1044 				goto err;
1045 			}
1046 			cdev->req->context = hid;
1047 			cdev->req->complete = acc_complete_send_hid_event;
1048 			value = w_length;
1049 		}
1050 	} else if (b_requestType == (USB_DIR_IN | USB_TYPE_VENDOR)) {
1051 		if (b_request == ACCESSORY_GET_PROTOCOL) {
1052 			schedule_work(&dev->getprotocol_work);
1053 			*((u16 *)cdev->req->buf) = PROTOCOL_VERSION;
1054 			value = sizeof(u16);
1055 			cdev->req->complete = acc_complete_setup_noop;
1056 			/* clear any string left over from a previous session */
1057 			memset(dev->manufacturer, 0, sizeof(dev->manufacturer));
1058 			memset(dev->model, 0, sizeof(dev->model));
1059 			memset(dev->description, 0, sizeof(dev->description));
1060 			memset(dev->version, 0, sizeof(dev->version));
1061 			memset(dev->uri, 0, sizeof(dev->uri));
1062 			memset(dev->serial, 0, sizeof(dev->serial));
1063 			dev->start_requested = 0;
1064 			dev->audio_mode = 0;
1065 		}
1066 	}
1067 
1068 	if (value >= 0) {
1069 		cdev->req->zero = 0;
1070 		cdev->req->length = value;
1071 		value = usb_ep_queue(cdev->gadget->ep0, cdev->req, GFP_ATOMIC);
1072 		if (value < 0)
1073 			ERROR(cdev, "%s setup response queue error\n",
1074 				__func__);
1075 	}
1076 
1077 err:
1078 	if (value == -EOPNOTSUPP)
1079 		VDBG(cdev,
1080 			"unknown class-specific control req "
1081 			"%02x.%02x v%04x i%04x l%u\n",
1082 			ctrl->bRequestType, ctrl->bRequest,
1083 			w_value, w_index, w_length);
1084 	put_acc_dev(dev);
1085 	return value;
1086 }
1087 EXPORT_SYMBOL_GPL(acc_ctrlrequest);
1088 
acc_ctrlrequest_composite(struct usb_composite_dev * cdev,const struct usb_ctrlrequest * ctrl)1089 int acc_ctrlrequest_composite(struct usb_composite_dev *cdev,
1090 			      const struct usb_ctrlrequest *ctrl)
1091 {
1092 	u16 w_length = le16_to_cpu(ctrl->wLength);
1093 
1094 	if (w_length > USB_COMP_EP0_BUFSIZ) {
1095 		if (ctrl->bRequestType & USB_DIR_IN) {
1096 			/* Cast away the const, we are going to overwrite on purpose. */
1097 			__le16 *temp = (__le16 *)&ctrl->wLength;
1098 
1099 			*temp = cpu_to_le16(USB_COMP_EP0_BUFSIZ);
1100 			w_length = USB_COMP_EP0_BUFSIZ;
1101 		} else {
1102 			return -EINVAL;
1103 		}
1104 	}
1105 	return acc_ctrlrequest(cdev, ctrl);
1106 }
1107 EXPORT_SYMBOL_GPL(acc_ctrlrequest_composite);
1108 
1109 static int
__acc_function_bind(struct usb_configuration * c,struct usb_function * f,bool configfs)1110 __acc_function_bind(struct usb_configuration *c,
1111 			struct usb_function *f, bool configfs)
1112 {
1113 	struct usb_composite_dev *cdev = c->cdev;
1114 	struct usb_string *us;
1115 	struct acc_dev	*dev = func_to_dev(f);
1116 	int			id;
1117 	int			ret;
1118 
1119 	DBG(cdev, "acc_function_bind dev: %p\n", dev);
1120 
1121 	if (configfs) {
1122 		us = usb_gstrings_attach(cdev, acc_strings, ARRAY_SIZE(acc_string_defs));
1123 		if (IS_ERR(us))
1124 			return PTR_ERR(us);
1125 		ret = us[INTERFACE_STRING_INDEX].id;
1126 		acc_interface_desc.iInterface = ret;
1127 		dev->cdev = c->cdev;
1128 	}
1129 	ret = hid_register_driver(&acc_hid_driver);
1130 	if (ret)
1131 		return ret;
1132 
1133 	dev->start_requested = 0;
1134 
1135 	/* allocate interface ID(s) */
1136 	id = usb_interface_id(c, f);
1137 	if (id < 0)
1138 		return id;
1139 	acc_interface_desc.bInterfaceNumber = id;
1140 
1141 	/* allocate endpoints */
1142 	ret = create_bulk_endpoints(dev, &acc_fullspeed_in_desc,
1143 			&acc_fullspeed_out_desc);
1144 	if (ret)
1145 		return ret;
1146 
1147 	/* support high speed hardware */
1148 	acc_highspeed_in_desc.bEndpointAddress =
1149 		acc_fullspeed_in_desc.bEndpointAddress;
1150 	acc_highspeed_out_desc.bEndpointAddress =
1151 		acc_fullspeed_out_desc.bEndpointAddress;
1152 
1153 	/* support super speed hardware */
1154 	acc_superspeed_in_desc.bEndpointAddress =
1155 		acc_fullspeed_in_desc.bEndpointAddress;
1156 	acc_superspeed_out_desc.bEndpointAddress =
1157 		acc_fullspeed_out_desc.bEndpointAddress;
1158 
1159 	/* support super speed plus hardware */
1160 	acc_superspeedplus_in_desc.bEndpointAddress =
1161 		acc_fullspeed_in_desc.bEndpointAddress;
1162 	acc_superspeedplus_out_desc.bEndpointAddress =
1163 		acc_fullspeed_out_desc.bEndpointAddress;
1164 
1165 	DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
1166 			gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1167 			f->name, dev->ep_in->name, dev->ep_out->name);
1168 	return 0;
1169 }
1170 
1171 static int
acc_function_bind_configfs(struct usb_configuration * c,struct usb_function * f)1172 acc_function_bind_configfs(struct usb_configuration *c,
1173 			struct usb_function *f) {
1174 	return __acc_function_bind(c, f, true);
1175 }
1176 
1177 static void
kill_all_hid_devices(struct acc_dev * dev)1178 kill_all_hid_devices(struct acc_dev *dev)
1179 {
1180 	struct acc_hid_dev *hid;
1181 	struct list_head *entry, *temp;
1182 	unsigned long flags;
1183 
1184 	spin_lock_irqsave(&dev->lock, flags);
1185 	list_for_each_safe(entry, temp, &dev->hid_list) {
1186 		hid = list_entry(entry, struct acc_hid_dev, list);
1187 		list_del(&hid->list);
1188 		list_add(&hid->list, &dev->dead_hid_list);
1189 	}
1190 	list_for_each_safe(entry, temp, &dev->new_hid_list) {
1191 		hid = list_entry(entry, struct acc_hid_dev, list);
1192 		list_del(&hid->list);
1193 		list_add(&hid->list, &dev->dead_hid_list);
1194 	}
1195 	spin_unlock_irqrestore(&dev->lock, flags);
1196 
1197 	schedule_work(&dev->hid_work);
1198 }
1199 
1200 static void
acc_hid_unbind(struct acc_dev * dev)1201 acc_hid_unbind(struct acc_dev *dev)
1202 {
1203 	hid_unregister_driver(&acc_hid_driver);
1204 	kill_all_hid_devices(dev);
1205 }
1206 
1207 static void
acc_function_unbind(struct usb_configuration * c,struct usb_function * f)1208 acc_function_unbind(struct usb_configuration *c, struct usb_function *f)
1209 {
1210 	struct acc_dev	*dev = func_to_dev(f);
1211 	struct usb_request *req;
1212 	int i;
1213 
1214 	dev->online = 0;		/* clear online flag */
1215 	wake_up(&dev->read_wq);		/* unblock reads on closure */
1216 	wake_up(&dev->write_wq);	/* likewise for writes */
1217 
1218 	while ((req = req_get(dev, &dev->tx_idle)))
1219 		acc_request_free(req, dev->ep_in);
1220 	for (i = 0; i < RX_REQ_MAX; i++) {
1221 		acc_request_free(dev->rx_req[i], dev->ep_out);
1222 		dev->rx_req[i] = NULL;
1223 	}
1224 
1225 	acc_hid_unbind(dev);
1226 }
1227 
acc_getprotocol_work(struct work_struct * data)1228 static void acc_getprotocol_work(struct work_struct *data)
1229 {
1230 	char *envp[2] = { "ACCESSORY=GETPROTOCOL", NULL };
1231 
1232 	kobject_uevent_env(&acc_device.this_device->kobj, KOBJ_CHANGE, envp);
1233 }
1234 
acc_sendstring_work(struct work_struct * data)1235 static void acc_sendstring_work(struct work_struct *data)
1236 {
1237 	char *envp[2] = { "ACCESSORY=SENDSTRING", NULL };
1238 
1239 	kobject_uevent_env(&acc_device.this_device->kobj, KOBJ_CHANGE, envp);
1240 }
1241 
acc_start_work(struct work_struct * data)1242 static void acc_start_work(struct work_struct *data)
1243 {
1244 	char *envp[2] = { "ACCESSORY=START", NULL };
1245 
1246 	kobject_uevent_env(&acc_device.this_device->kobj, KOBJ_CHANGE, envp);
1247 }
1248 
acc_hid_init(struct acc_hid_dev * hdev)1249 static int acc_hid_init(struct acc_hid_dev *hdev)
1250 {
1251 	struct hid_device *hid;
1252 	int ret;
1253 
1254 	hid = hid_allocate_device();
1255 	if (IS_ERR(hid))
1256 		return PTR_ERR(hid);
1257 
1258 	hid->ll_driver = &acc_hid_ll_driver;
1259 	hid->dev.parent = acc_device.this_device;
1260 
1261 	hid->bus = BUS_USB;
1262 	hid->vendor = HID_ANY_ID;
1263 	hid->product = HID_ANY_ID;
1264 	hid->driver_data = hdev;
1265 	ret = hid_add_device(hid);
1266 	if (ret) {
1267 		pr_err("can't add hid device: %d\n", ret);
1268 		hid_destroy_device(hid);
1269 		return ret;
1270 	}
1271 
1272 	hdev->hid = hid;
1273 	return 0;
1274 }
1275 
acc_hid_delete(struct acc_hid_dev * hid)1276 static void acc_hid_delete(struct acc_hid_dev *hid)
1277 {
1278 	kfree(hid->report_desc);
1279 	kfree(hid);
1280 }
1281 
acc_hid_work(struct work_struct * data)1282 static void acc_hid_work(struct work_struct *data)
1283 {
1284 	struct acc_dev *dev = get_acc_dev();
1285 	struct list_head	*entry, *temp;
1286 	struct acc_hid_dev *hid;
1287 	struct list_head	new_list, dead_list;
1288 	unsigned long flags;
1289 
1290 	if (!dev)
1291 		return;
1292 
1293 	INIT_LIST_HEAD(&new_list);
1294 
1295 	spin_lock_irqsave(&dev->lock, flags);
1296 
1297 	/* copy hids that are ready for initialization to new_list */
1298 	list_for_each_safe(entry, temp, &dev->new_hid_list) {
1299 		hid = list_entry(entry, struct acc_hid_dev, list);
1300 		if (hid->report_desc_offset == hid->report_desc_len)
1301 			list_move(&hid->list, &new_list);
1302 	}
1303 
1304 	if (list_empty(&dev->dead_hid_list)) {
1305 		INIT_LIST_HEAD(&dead_list);
1306 	} else {
1307 		/* move all of dev->dead_hid_list to dead_list */
1308 		dead_list.prev = dev->dead_hid_list.prev;
1309 		dead_list.next = dev->dead_hid_list.next;
1310 		dead_list.next->prev = &dead_list;
1311 		dead_list.prev->next = &dead_list;
1312 		INIT_LIST_HEAD(&dev->dead_hid_list);
1313 	}
1314 
1315 	spin_unlock_irqrestore(&dev->lock, flags);
1316 
1317 	/* register new HID devices */
1318 	list_for_each_safe(entry, temp, &new_list) {
1319 		hid = list_entry(entry, struct acc_hid_dev, list);
1320 		if (acc_hid_init(hid)) {
1321 			pr_err("can't add HID device %p\n", hid);
1322 			acc_hid_delete(hid);
1323 		} else {
1324 			spin_lock_irqsave(&dev->lock, flags);
1325 			list_move(&hid->list, &dev->hid_list);
1326 			spin_unlock_irqrestore(&dev->lock, flags);
1327 		}
1328 	}
1329 
1330 	/* remove dead HID devices */
1331 	list_for_each_safe(entry, temp, &dead_list) {
1332 		hid = list_entry(entry, struct acc_hid_dev, list);
1333 		list_del(&hid->list);
1334 		if (hid->hid)
1335 			hid_destroy_device(hid->hid);
1336 		acc_hid_delete(hid);
1337 	}
1338 
1339 	put_acc_dev(dev);
1340 }
1341 
acc_function_set_alt(struct usb_function * f,unsigned intf,unsigned alt)1342 static int acc_function_set_alt(struct usb_function *f,
1343 		unsigned intf, unsigned alt)
1344 {
1345 	struct acc_dev	*dev = func_to_dev(f);
1346 	struct usb_composite_dev *cdev = f->config->cdev;
1347 	int ret;
1348 
1349 	DBG(cdev, "acc_function_set_alt intf: %d alt: %d\n", intf, alt);
1350 
1351 	ret = config_ep_by_speed(cdev->gadget, f, dev->ep_in);
1352 	if (ret)
1353 		return ret;
1354 
1355 	ret = usb_ep_enable(dev->ep_in);
1356 	if (ret)
1357 		return ret;
1358 
1359 	ret = config_ep_by_speed(cdev->gadget, f, dev->ep_out);
1360 	if (ret)
1361 		return ret;
1362 
1363 	ret = usb_ep_enable(dev->ep_out);
1364 	if (ret) {
1365 		usb_ep_disable(dev->ep_in);
1366 		return ret;
1367 	}
1368 
1369 	dev->online = 1;
1370 	dev->disconnected = 0; /* if online then not disconnected */
1371 
1372 	/* readers may be blocked waiting for us to go online */
1373 	wake_up(&dev->read_wq);
1374 	return 0;
1375 }
1376 
acc_function_disable(struct usb_function * f)1377 static void acc_function_disable(struct usb_function *f)
1378 {
1379 	struct acc_dev	*dev = func_to_dev(f);
1380 	struct usb_composite_dev	*cdev = dev->cdev;
1381 
1382 	DBG(cdev, "acc_function_disable\n");
1383 	acc_set_disconnected(dev); /* this now only sets disconnected */
1384 	dev->online = 0; /* so now need to clear online flag here too */
1385 	usb_ep_disable(dev->ep_in);
1386 	usb_ep_disable(dev->ep_out);
1387 
1388 	/* readers may be blocked waiting for us to go online */
1389 	wake_up(&dev->read_wq);
1390 
1391 	VDBG(cdev, "%s disabled\n", dev->function.name);
1392 }
1393 
acc_setup(void)1394 static int acc_setup(void)
1395 {
1396 	struct acc_dev_ref *ref = &_acc_dev_ref;
1397 	struct acc_dev *dev;
1398 	int ret;
1399 
1400 	if (kref_read(&ref->kref))
1401 		return -EBUSY;
1402 
1403 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1404 	if (!dev)
1405 		return -ENOMEM;
1406 
1407 	spin_lock_init(&dev->lock);
1408 	init_waitqueue_head(&dev->read_wq);
1409 	init_waitqueue_head(&dev->write_wq);
1410 	atomic_set(&dev->open_excl, 0);
1411 	INIT_LIST_HEAD(&dev->tx_idle);
1412 	INIT_LIST_HEAD(&dev->hid_list);
1413 	INIT_LIST_HEAD(&dev->new_hid_list);
1414 	INIT_LIST_HEAD(&dev->dead_hid_list);
1415 	INIT_DELAYED_WORK(&dev->start_work, acc_start_work);
1416 	INIT_WORK(&dev->hid_work, acc_hid_work);
1417 	INIT_WORK(&dev->getprotocol_work, acc_getprotocol_work);
1418 	INIT_WORK(&dev->sendstring_work, acc_sendstring_work);
1419 
1420 	dev->ref = ref;
1421 	if (cmpxchg_relaxed(&ref->acc_dev, NULL, dev)) {
1422 		ret = -EBUSY;
1423 		goto err_free_dev;
1424 	}
1425 
1426 	ret = misc_register(&acc_device);
1427 	if (ret)
1428 		goto err_zap_ptr;
1429 
1430 	kref_init(&ref->kref);
1431 	return 0;
1432 
1433 err_zap_ptr:
1434 	ref->acc_dev = NULL;
1435 err_free_dev:
1436 	kfree(dev);
1437 	pr_err("USB accessory gadget driver failed to initialize\n");
1438 	return ret;
1439 }
1440 
acc_disconnect(void)1441 void acc_disconnect(void)
1442 {
1443 	struct acc_dev *dev = get_acc_dev();
1444 
1445 	if (!dev)
1446 		return;
1447 
1448 	/* unregister all HID devices if USB is disconnected */
1449 	kill_all_hid_devices(dev);
1450 	put_acc_dev(dev);
1451 }
1452 EXPORT_SYMBOL_GPL(acc_disconnect);
1453 
acc_cleanup(void)1454 static void acc_cleanup(void)
1455 {
1456 	struct acc_dev *dev = get_acc_dev();
1457 
1458 	misc_deregister(&acc_device);
1459 	put_acc_dev(dev);
1460 	put_acc_dev(dev); /* Pairs with kref_init() in acc_setup() */
1461 }
to_acc_instance(struct config_item * item)1462 static struct acc_instance *to_acc_instance(struct config_item *item)
1463 {
1464 	return container_of(to_config_group(item), struct acc_instance,
1465 		func_inst.group);
1466 }
1467 
acc_attr_release(struct config_item * item)1468 static void acc_attr_release(struct config_item *item)
1469 {
1470 	struct acc_instance *fi_acc = to_acc_instance(item);
1471 
1472 	usb_put_function_instance(&fi_acc->func_inst);
1473 }
1474 
1475 static struct configfs_item_operations acc_item_ops = {
1476 	.release        = acc_attr_release,
1477 };
1478 
1479 static struct config_item_type acc_func_type = {
1480 	.ct_item_ops    = &acc_item_ops,
1481 	.ct_owner       = THIS_MODULE,
1482 };
1483 
to_fi_acc(struct usb_function_instance * fi)1484 static struct acc_instance *to_fi_acc(struct usb_function_instance *fi)
1485 {
1486 	return container_of(fi, struct acc_instance, func_inst);
1487 }
1488 
acc_set_inst_name(struct usb_function_instance * fi,const char * name)1489 static int acc_set_inst_name(struct usb_function_instance *fi, const char *name)
1490 {
1491 	struct acc_instance *fi_acc;
1492 	char *ptr;
1493 	int name_len;
1494 
1495 	name_len = strlen(name) + 1;
1496 	if (name_len > MAX_INST_NAME_LEN)
1497 		return -ENAMETOOLONG;
1498 
1499 	ptr = kstrndup(name, name_len, GFP_KERNEL);
1500 	if (!ptr)
1501 		return -ENOMEM;
1502 
1503 	fi_acc = to_fi_acc(fi);
1504 	fi_acc->name = ptr;
1505 	return 0;
1506 }
1507 
acc_free_inst(struct usb_function_instance * fi)1508 static void acc_free_inst(struct usb_function_instance *fi)
1509 {
1510 	struct acc_instance *fi_acc;
1511 
1512 	fi_acc = to_fi_acc(fi);
1513 	kfree(fi_acc->name);
1514 	acc_cleanup();
1515 }
1516 
acc_alloc_inst(void)1517 static struct usb_function_instance *acc_alloc_inst(void)
1518 {
1519 	struct acc_instance *fi_acc;
1520 	int err;
1521 
1522 	fi_acc = kzalloc(sizeof(*fi_acc), GFP_KERNEL);
1523 	if (!fi_acc)
1524 		return ERR_PTR(-ENOMEM);
1525 	fi_acc->func_inst.set_inst_name = acc_set_inst_name;
1526 	fi_acc->func_inst.free_func_inst = acc_free_inst;
1527 
1528 	err = acc_setup();
1529 	if (err) {
1530 		kfree(fi_acc);
1531 		return ERR_PTR(err);
1532 	}
1533 
1534 	config_group_init_type_name(&fi_acc->func_inst.group,
1535 					"", &acc_func_type);
1536 	return  &fi_acc->func_inst;
1537 }
1538 
acc_free(struct usb_function * f)1539 static void acc_free(struct usb_function *f)
1540 {
1541 	struct acc_dev *dev = func_to_dev(f);
1542 
1543 	put_acc_dev(dev);
1544 }
1545 
acc_ctrlrequest_configfs(struct usb_function * f,const struct usb_ctrlrequest * ctrl)1546 int acc_ctrlrequest_configfs(struct usb_function *f,
1547 			const struct usb_ctrlrequest *ctrl) {
1548 	if (f->config != NULL && f->config->cdev != NULL)
1549 		return acc_ctrlrequest(f->config->cdev, ctrl);
1550 	else
1551 		return -1;
1552 }
1553 
acc_alloc(struct usb_function_instance * fi)1554 static struct usb_function *acc_alloc(struct usb_function_instance *fi)
1555 {
1556 	struct acc_dev *dev = get_acc_dev();
1557 
1558 	dev->function.name = "accessory";
1559 	dev->function.strings = acc_strings,
1560 	dev->function.fs_descriptors = fs_acc_descs;
1561 	dev->function.hs_descriptors = hs_acc_descs;
1562 	dev->function.ss_descriptors = ss_acc_descs;
1563 	dev->function.ssp_descriptors = ssp_acc_descs;
1564 	dev->function.bind = acc_function_bind_configfs;
1565 	dev->function.unbind = acc_function_unbind;
1566 	dev->function.set_alt = acc_function_set_alt;
1567 	dev->function.disable = acc_function_disable;
1568 	dev->function.free_func = acc_free;
1569 	dev->function.setup = acc_ctrlrequest_configfs;
1570 
1571 	return &dev->function;
1572 }
1573 DECLARE_USB_FUNCTION_INIT(accessory, acc_alloc_inst, acc_alloc);
1574 MODULE_LICENSE("GPL");
1575