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