xref: /linux/drivers/usb/gadget/function/f_hid.c (revision 5fd54ace4721fc5ce2bb5aef6318fcf17f421460)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_hid.c -- USB HID function driver
4  *
5  * Copyright (C) 2010 Fabien Chouteau <fabien.chouteau@barco.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  */
12 
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/hid.h>
16 #include <linux/idr.h>
17 #include <linux/cdev.h>
18 #include <linux/mutex.h>
19 #include <linux/poll.h>
20 #include <linux/uaccess.h>
21 #include <linux/wait.h>
22 #include <linux/sched.h>
23 #include <linux/usb/g_hid.h>
24 
25 #include "u_f.h"
26 #include "u_hid.h"
27 
28 #define HIDG_MINORS	4
29 
30 static int major, minors;
31 static struct class *hidg_class;
32 static DEFINE_IDA(hidg_ida);
33 static DEFINE_MUTEX(hidg_ida_lock); /* protects access to hidg_ida */
34 
35 /*-------------------------------------------------------------------------*/
36 /*                            HID gadget struct                            */
37 
38 struct f_hidg_req_list {
39 	struct usb_request	*req;
40 	unsigned int		pos;
41 	struct list_head 	list;
42 };
43 
44 struct f_hidg {
45 	/* configuration */
46 	unsigned char			bInterfaceSubClass;
47 	unsigned char			bInterfaceProtocol;
48 	unsigned char			protocol;
49 	unsigned short			report_desc_length;
50 	char				*report_desc;
51 	unsigned short			report_length;
52 
53 	/* recv report */
54 	struct list_head		completed_out_req;
55 	spinlock_t			read_spinlock;
56 	wait_queue_head_t		read_queue;
57 	unsigned int			qlen;
58 
59 	/* send report */
60 	spinlock_t			write_spinlock;
61 	bool				write_pending;
62 	wait_queue_head_t		write_queue;
63 	struct usb_request		*req;
64 
65 	int				minor;
66 	struct cdev			cdev;
67 	struct usb_function		func;
68 
69 	struct usb_ep			*in_ep;
70 	struct usb_ep			*out_ep;
71 };
72 
73 static inline struct f_hidg *func_to_hidg(struct usb_function *f)
74 {
75 	return container_of(f, struct f_hidg, func);
76 }
77 
78 /*-------------------------------------------------------------------------*/
79 /*                           Static descriptors                            */
80 
81 static struct usb_interface_descriptor hidg_interface_desc = {
82 	.bLength		= sizeof hidg_interface_desc,
83 	.bDescriptorType	= USB_DT_INTERFACE,
84 	/* .bInterfaceNumber	= DYNAMIC */
85 	.bAlternateSetting	= 0,
86 	.bNumEndpoints		= 2,
87 	.bInterfaceClass	= USB_CLASS_HID,
88 	/* .bInterfaceSubClass	= DYNAMIC */
89 	/* .bInterfaceProtocol	= DYNAMIC */
90 	/* .iInterface		= DYNAMIC */
91 };
92 
93 static struct hid_descriptor hidg_desc = {
94 	.bLength			= sizeof hidg_desc,
95 	.bDescriptorType		= HID_DT_HID,
96 	.bcdHID				= 0x0101,
97 	.bCountryCode			= 0x00,
98 	.bNumDescriptors		= 0x1,
99 	/*.desc[0].bDescriptorType	= DYNAMIC */
100 	/*.desc[0].wDescriptorLenght	= DYNAMIC */
101 };
102 
103 /* Super-Speed Support */
104 
105 static struct usb_endpoint_descriptor hidg_ss_in_ep_desc = {
106 	.bLength		= USB_DT_ENDPOINT_SIZE,
107 	.bDescriptorType	= USB_DT_ENDPOINT,
108 	.bEndpointAddress	= USB_DIR_IN,
109 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
110 	/*.wMaxPacketSize	= DYNAMIC */
111 	.bInterval		= 4, /* FIXME: Add this field in the
112 				      * HID gadget configuration?
113 				      * (struct hidg_func_descriptor)
114 				      */
115 };
116 
117 static struct usb_ss_ep_comp_descriptor hidg_ss_in_comp_desc = {
118 	.bLength                = sizeof(hidg_ss_in_comp_desc),
119 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
120 
121 	/* .bMaxBurst           = 0, */
122 	/* .bmAttributes        = 0, */
123 	/* .wBytesPerInterval   = DYNAMIC */
124 };
125 
126 static struct usb_endpoint_descriptor hidg_ss_out_ep_desc = {
127 	.bLength		= USB_DT_ENDPOINT_SIZE,
128 	.bDescriptorType	= USB_DT_ENDPOINT,
129 	.bEndpointAddress	= USB_DIR_OUT,
130 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
131 	/*.wMaxPacketSize	= DYNAMIC */
132 	.bInterval		= 4, /* FIXME: Add this field in the
133 				      * HID gadget configuration?
134 				      * (struct hidg_func_descriptor)
135 				      */
136 };
137 
138 static struct usb_ss_ep_comp_descriptor hidg_ss_out_comp_desc = {
139 	.bLength                = sizeof(hidg_ss_out_comp_desc),
140 	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
141 
142 	/* .bMaxBurst           = 0, */
143 	/* .bmAttributes        = 0, */
144 	/* .wBytesPerInterval   = DYNAMIC */
145 };
146 
147 static struct usb_descriptor_header *hidg_ss_descriptors[] = {
148 	(struct usb_descriptor_header *)&hidg_interface_desc,
149 	(struct usb_descriptor_header *)&hidg_desc,
150 	(struct usb_descriptor_header *)&hidg_ss_in_ep_desc,
151 	(struct usb_descriptor_header *)&hidg_ss_in_comp_desc,
152 	(struct usb_descriptor_header *)&hidg_ss_out_ep_desc,
153 	(struct usb_descriptor_header *)&hidg_ss_out_comp_desc,
154 	NULL,
155 };
156 
157 /* High-Speed Support */
158 
159 static struct usb_endpoint_descriptor hidg_hs_in_ep_desc = {
160 	.bLength		= USB_DT_ENDPOINT_SIZE,
161 	.bDescriptorType	= USB_DT_ENDPOINT,
162 	.bEndpointAddress	= USB_DIR_IN,
163 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
164 	/*.wMaxPacketSize	= DYNAMIC */
165 	.bInterval		= 4, /* FIXME: Add this field in the
166 				      * HID gadget configuration?
167 				      * (struct hidg_func_descriptor)
168 				      */
169 };
170 
171 static struct usb_endpoint_descriptor hidg_hs_out_ep_desc = {
172 	.bLength		= USB_DT_ENDPOINT_SIZE,
173 	.bDescriptorType	= USB_DT_ENDPOINT,
174 	.bEndpointAddress	= USB_DIR_OUT,
175 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
176 	/*.wMaxPacketSize	= DYNAMIC */
177 	.bInterval		= 4, /* FIXME: Add this field in the
178 				      * HID gadget configuration?
179 				      * (struct hidg_func_descriptor)
180 				      */
181 };
182 
183 static struct usb_descriptor_header *hidg_hs_descriptors[] = {
184 	(struct usb_descriptor_header *)&hidg_interface_desc,
185 	(struct usb_descriptor_header *)&hidg_desc,
186 	(struct usb_descriptor_header *)&hidg_hs_in_ep_desc,
187 	(struct usb_descriptor_header *)&hidg_hs_out_ep_desc,
188 	NULL,
189 };
190 
191 /* Full-Speed Support */
192 
193 static struct usb_endpoint_descriptor hidg_fs_in_ep_desc = {
194 	.bLength		= USB_DT_ENDPOINT_SIZE,
195 	.bDescriptorType	= USB_DT_ENDPOINT,
196 	.bEndpointAddress	= USB_DIR_IN,
197 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
198 	/*.wMaxPacketSize	= DYNAMIC */
199 	.bInterval		= 10, /* FIXME: Add this field in the
200 				       * HID gadget configuration?
201 				       * (struct hidg_func_descriptor)
202 				       */
203 };
204 
205 static struct usb_endpoint_descriptor hidg_fs_out_ep_desc = {
206 	.bLength		= USB_DT_ENDPOINT_SIZE,
207 	.bDescriptorType	= USB_DT_ENDPOINT,
208 	.bEndpointAddress	= USB_DIR_OUT,
209 	.bmAttributes		= USB_ENDPOINT_XFER_INT,
210 	/*.wMaxPacketSize	= DYNAMIC */
211 	.bInterval		= 10, /* FIXME: Add this field in the
212 				       * HID gadget configuration?
213 				       * (struct hidg_func_descriptor)
214 				       */
215 };
216 
217 static struct usb_descriptor_header *hidg_fs_descriptors[] = {
218 	(struct usb_descriptor_header *)&hidg_interface_desc,
219 	(struct usb_descriptor_header *)&hidg_desc,
220 	(struct usb_descriptor_header *)&hidg_fs_in_ep_desc,
221 	(struct usb_descriptor_header *)&hidg_fs_out_ep_desc,
222 	NULL,
223 };
224 
225 /*-------------------------------------------------------------------------*/
226 /*                                 Strings                                 */
227 
228 #define CT_FUNC_HID_IDX	0
229 
230 static struct usb_string ct_func_string_defs[] = {
231 	[CT_FUNC_HID_IDX].s	= "HID Interface",
232 	{},			/* end of list */
233 };
234 
235 static struct usb_gadget_strings ct_func_string_table = {
236 	.language	= 0x0409,	/* en-US */
237 	.strings	= ct_func_string_defs,
238 };
239 
240 static struct usb_gadget_strings *ct_func_strings[] = {
241 	&ct_func_string_table,
242 	NULL,
243 };
244 
245 /*-------------------------------------------------------------------------*/
246 /*                              Char Device                                */
247 
248 static ssize_t f_hidg_read(struct file *file, char __user *buffer,
249 			size_t count, loff_t *ptr)
250 {
251 	struct f_hidg *hidg = file->private_data;
252 	struct f_hidg_req_list *list;
253 	struct usb_request *req;
254 	unsigned long flags;
255 	int ret;
256 
257 	if (!count)
258 		return 0;
259 
260 	if (!access_ok(VERIFY_WRITE, buffer, count))
261 		return -EFAULT;
262 
263 	spin_lock_irqsave(&hidg->read_spinlock, flags);
264 
265 #define READ_COND (!list_empty(&hidg->completed_out_req))
266 
267 	/* wait for at least one buffer to complete */
268 	while (!READ_COND) {
269 		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
270 		if (file->f_flags & O_NONBLOCK)
271 			return -EAGAIN;
272 
273 		if (wait_event_interruptible(hidg->read_queue, READ_COND))
274 			return -ERESTARTSYS;
275 
276 		spin_lock_irqsave(&hidg->read_spinlock, flags);
277 	}
278 
279 	/* pick the first one */
280 	list = list_first_entry(&hidg->completed_out_req,
281 				struct f_hidg_req_list, list);
282 
283 	/*
284 	 * Remove this from list to protect it from beign free()
285 	 * while host disables our function
286 	 */
287 	list_del(&list->list);
288 
289 	req = list->req;
290 	count = min_t(unsigned int, count, req->actual - list->pos);
291 	spin_unlock_irqrestore(&hidg->read_spinlock, flags);
292 
293 	/* copy to user outside spinlock */
294 	count -= copy_to_user(buffer, req->buf + list->pos, count);
295 	list->pos += count;
296 
297 	/*
298 	 * if this request is completely handled and transfered to
299 	 * userspace, remove its entry from the list and requeue it
300 	 * again. Otherwise, we will revisit it again upon the next
301 	 * call, taking into account its current read position.
302 	 */
303 	if (list->pos == req->actual) {
304 		kfree(list);
305 
306 		req->length = hidg->report_length;
307 		ret = usb_ep_queue(hidg->out_ep, req, GFP_KERNEL);
308 		if (ret < 0) {
309 			free_ep_req(hidg->out_ep, req);
310 			return ret;
311 		}
312 	} else {
313 		spin_lock_irqsave(&hidg->read_spinlock, flags);
314 		list_add(&list->list, &hidg->completed_out_req);
315 		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
316 
317 		wake_up(&hidg->read_queue);
318 	}
319 
320 	return count;
321 }
322 
323 static void f_hidg_req_complete(struct usb_ep *ep, struct usb_request *req)
324 {
325 	struct f_hidg *hidg = (struct f_hidg *)ep->driver_data;
326 	unsigned long flags;
327 
328 	if (req->status != 0) {
329 		ERROR(hidg->func.config->cdev,
330 			"End Point Request ERROR: %d\n", req->status);
331 	}
332 
333 	spin_lock_irqsave(&hidg->write_spinlock, flags);
334 	hidg->write_pending = 0;
335 	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
336 	wake_up(&hidg->write_queue);
337 }
338 
339 static ssize_t f_hidg_write(struct file *file, const char __user *buffer,
340 			    size_t count, loff_t *offp)
341 {
342 	struct f_hidg *hidg  = file->private_data;
343 	struct usb_request *req;
344 	unsigned long flags;
345 	ssize_t status = -ENOMEM;
346 
347 	if (!access_ok(VERIFY_READ, buffer, count))
348 		return -EFAULT;
349 
350 	spin_lock_irqsave(&hidg->write_spinlock, flags);
351 
352 #define WRITE_COND (!hidg->write_pending)
353 try_again:
354 	/* write queue */
355 	while (!WRITE_COND) {
356 		spin_unlock_irqrestore(&hidg->write_spinlock, flags);
357 		if (file->f_flags & O_NONBLOCK)
358 			return -EAGAIN;
359 
360 		if (wait_event_interruptible_exclusive(
361 				hidg->write_queue, WRITE_COND))
362 			return -ERESTARTSYS;
363 
364 		spin_lock_irqsave(&hidg->write_spinlock, flags);
365 	}
366 
367 	hidg->write_pending = 1;
368 	req = hidg->req;
369 	count  = min_t(unsigned, count, hidg->report_length);
370 
371 	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
372 	status = copy_from_user(req->buf, buffer, count);
373 
374 	if (status != 0) {
375 		ERROR(hidg->func.config->cdev,
376 			"copy_from_user error\n");
377 		status = -EINVAL;
378 		goto release_write_pending;
379 	}
380 
381 	spin_lock_irqsave(&hidg->write_spinlock, flags);
382 
383 	/* when our function has been disabled by host */
384 	if (!hidg->req) {
385 		free_ep_req(hidg->in_ep, req);
386 		/*
387 		 * TODO
388 		 * Should we fail with error here?
389 		 */
390 		goto try_again;
391 	}
392 
393 	req->status   = 0;
394 	req->zero     = 0;
395 	req->length   = count;
396 	req->complete = f_hidg_req_complete;
397 	req->context  = hidg;
398 
399 	status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);
400 	if (status < 0) {
401 		ERROR(hidg->func.config->cdev,
402 			"usb_ep_queue error on int endpoint %zd\n", status);
403 		goto release_write_pending_unlocked;
404 	} else {
405 		status = count;
406 	}
407 	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
408 
409 	return status;
410 release_write_pending:
411 	spin_lock_irqsave(&hidg->write_spinlock, flags);
412 release_write_pending_unlocked:
413 	hidg->write_pending = 0;
414 	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
415 
416 	wake_up(&hidg->write_queue);
417 
418 	return status;
419 }
420 
421 static unsigned int f_hidg_poll(struct file *file, poll_table *wait)
422 {
423 	struct f_hidg	*hidg  = file->private_data;
424 	unsigned int	ret = 0;
425 
426 	poll_wait(file, &hidg->read_queue, wait);
427 	poll_wait(file, &hidg->write_queue, wait);
428 
429 	if (WRITE_COND)
430 		ret |= POLLOUT | POLLWRNORM;
431 
432 	if (READ_COND)
433 		ret |= POLLIN | POLLRDNORM;
434 
435 	return ret;
436 }
437 
438 #undef WRITE_COND
439 #undef READ_COND
440 
441 static int f_hidg_release(struct inode *inode, struct file *fd)
442 {
443 	fd->private_data = NULL;
444 	return 0;
445 }
446 
447 static int f_hidg_open(struct inode *inode, struct file *fd)
448 {
449 	struct f_hidg *hidg =
450 		container_of(inode->i_cdev, struct f_hidg, cdev);
451 
452 	fd->private_data = hidg;
453 
454 	return 0;
455 }
456 
457 /*-------------------------------------------------------------------------*/
458 /*                                usb_function                             */
459 
460 static inline struct usb_request *hidg_alloc_ep_req(struct usb_ep *ep,
461 						    unsigned length)
462 {
463 	return alloc_ep_req(ep, length);
464 }
465 
466 static void hidg_set_report_complete(struct usb_ep *ep, struct usb_request *req)
467 {
468 	struct f_hidg *hidg = (struct f_hidg *) req->context;
469 	struct usb_composite_dev *cdev = hidg->func.config->cdev;
470 	struct f_hidg_req_list *req_list;
471 	unsigned long flags;
472 
473 	switch (req->status) {
474 	case 0:
475 		req_list = kzalloc(sizeof(*req_list), GFP_ATOMIC);
476 		if (!req_list) {
477 			ERROR(cdev, "Unable to allocate mem for req_list\n");
478 			goto free_req;
479 		}
480 
481 		req_list->req = req;
482 
483 		spin_lock_irqsave(&hidg->read_spinlock, flags);
484 		list_add_tail(&req_list->list, &hidg->completed_out_req);
485 		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
486 
487 		wake_up(&hidg->read_queue);
488 		break;
489 	default:
490 		ERROR(cdev, "Set report failed %d\n", req->status);
491 		/* FALLTHROUGH */
492 	case -ECONNABORTED:		/* hardware forced ep reset */
493 	case -ECONNRESET:		/* request dequeued */
494 	case -ESHUTDOWN:		/* disconnect from host */
495 free_req:
496 		free_ep_req(ep, req);
497 		return;
498 	}
499 }
500 
501 static int hidg_setup(struct usb_function *f,
502 		const struct usb_ctrlrequest *ctrl)
503 {
504 	struct f_hidg			*hidg = func_to_hidg(f);
505 	struct usb_composite_dev	*cdev = f->config->cdev;
506 	struct usb_request		*req  = cdev->req;
507 	int status = 0;
508 	__u16 value, length;
509 
510 	value	= __le16_to_cpu(ctrl->wValue);
511 	length	= __le16_to_cpu(ctrl->wLength);
512 
513 	VDBG(cdev,
514 	     "%s crtl_request : bRequestType:0x%x bRequest:0x%x Value:0x%x\n",
515 	     __func__, ctrl->bRequestType, ctrl->bRequest, value);
516 
517 	switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
518 	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
519 		  | HID_REQ_GET_REPORT):
520 		VDBG(cdev, "get_report\n");
521 
522 		/* send an empty report */
523 		length = min_t(unsigned, length, hidg->report_length);
524 		memset(req->buf, 0x0, length);
525 
526 		goto respond;
527 		break;
528 
529 	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
530 		  | HID_REQ_GET_PROTOCOL):
531 		VDBG(cdev, "get_protocol\n");
532 		length = min_t(unsigned int, length, 1);
533 		((u8 *) req->buf)[0] = hidg->protocol;
534 		goto respond;
535 		break;
536 
537 	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
538 		  | HID_REQ_SET_REPORT):
539 		VDBG(cdev, "set_report | wLength=%d\n", ctrl->wLength);
540 		goto stall;
541 		break;
542 
543 	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
544 		  | HID_REQ_SET_PROTOCOL):
545 		VDBG(cdev, "set_protocol\n");
546 		if (value > HID_REPORT_PROTOCOL)
547 			goto stall;
548 		length = 0;
549 		/*
550 		 * We assume that programs implementing the Boot protocol
551 		 * are also compatible with the Report Protocol
552 		 */
553 		if (hidg->bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
554 			hidg->protocol = value;
555 			goto respond;
556 		}
557 		goto stall;
558 		break;
559 
560 	case ((USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE) << 8
561 		  | USB_REQ_GET_DESCRIPTOR):
562 		switch (value >> 8) {
563 		case HID_DT_HID:
564 		{
565 			struct hid_descriptor hidg_desc_copy = hidg_desc;
566 
567 			VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: HID\n");
568 			hidg_desc_copy.desc[0].bDescriptorType = HID_DT_REPORT;
569 			hidg_desc_copy.desc[0].wDescriptorLength =
570 				cpu_to_le16(hidg->report_desc_length);
571 
572 			length = min_t(unsigned short, length,
573 						   hidg_desc_copy.bLength);
574 			memcpy(req->buf, &hidg_desc_copy, length);
575 			goto respond;
576 			break;
577 		}
578 		case HID_DT_REPORT:
579 			VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: REPORT\n");
580 			length = min_t(unsigned short, length,
581 						   hidg->report_desc_length);
582 			memcpy(req->buf, hidg->report_desc, length);
583 			goto respond;
584 			break;
585 
586 		default:
587 			VDBG(cdev, "Unknown descriptor request 0x%x\n",
588 				 value >> 8);
589 			goto stall;
590 			break;
591 		}
592 		break;
593 
594 	default:
595 		VDBG(cdev, "Unknown request 0x%x\n",
596 			 ctrl->bRequest);
597 		goto stall;
598 		break;
599 	}
600 
601 stall:
602 	return -EOPNOTSUPP;
603 
604 respond:
605 	req->zero = 0;
606 	req->length = length;
607 	status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
608 	if (status < 0)
609 		ERROR(cdev, "usb_ep_queue error on ep0 %d\n", value);
610 	return status;
611 }
612 
613 static void hidg_disable(struct usb_function *f)
614 {
615 	struct f_hidg *hidg = func_to_hidg(f);
616 	struct f_hidg_req_list *list, *next;
617 	unsigned long flags;
618 
619 	usb_ep_disable(hidg->in_ep);
620 	usb_ep_disable(hidg->out_ep);
621 
622 	spin_lock_irqsave(&hidg->read_spinlock, flags);
623 	list_for_each_entry_safe(list, next, &hidg->completed_out_req, list) {
624 		free_ep_req(hidg->out_ep, list->req);
625 		list_del(&list->list);
626 		kfree(list);
627 	}
628 	spin_unlock_irqrestore(&hidg->read_spinlock, flags);
629 
630 	spin_lock_irqsave(&hidg->write_spinlock, flags);
631 	if (!hidg->write_pending) {
632 		free_ep_req(hidg->in_ep, hidg->req);
633 		hidg->write_pending = 1;
634 	}
635 
636 	hidg->req = NULL;
637 	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
638 }
639 
640 static int hidg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
641 {
642 	struct usb_composite_dev		*cdev = f->config->cdev;
643 	struct f_hidg				*hidg = func_to_hidg(f);
644 	struct usb_request			*req_in = NULL;
645 	unsigned long				flags;
646 	int i, status = 0;
647 
648 	VDBG(cdev, "hidg_set_alt intf:%d alt:%d\n", intf, alt);
649 
650 	if (hidg->in_ep != NULL) {
651 		/* restart endpoint */
652 		usb_ep_disable(hidg->in_ep);
653 
654 		status = config_ep_by_speed(f->config->cdev->gadget, f,
655 					    hidg->in_ep);
656 		if (status) {
657 			ERROR(cdev, "config_ep_by_speed FAILED!\n");
658 			goto fail;
659 		}
660 		status = usb_ep_enable(hidg->in_ep);
661 		if (status < 0) {
662 			ERROR(cdev, "Enable IN endpoint FAILED!\n");
663 			goto fail;
664 		}
665 		hidg->in_ep->driver_data = hidg;
666 
667 		req_in = hidg_alloc_ep_req(hidg->in_ep, hidg->report_length);
668 		if (!req_in) {
669 			status = -ENOMEM;
670 			goto disable_ep_in;
671 		}
672 	}
673 
674 
675 	if (hidg->out_ep != NULL) {
676 		/* restart endpoint */
677 		usb_ep_disable(hidg->out_ep);
678 
679 		status = config_ep_by_speed(f->config->cdev->gadget, f,
680 					    hidg->out_ep);
681 		if (status) {
682 			ERROR(cdev, "config_ep_by_speed FAILED!\n");
683 			goto free_req_in;
684 		}
685 		status = usb_ep_enable(hidg->out_ep);
686 		if (status < 0) {
687 			ERROR(cdev, "Enable OUT endpoint FAILED!\n");
688 			goto free_req_in;
689 		}
690 		hidg->out_ep->driver_data = hidg;
691 
692 		/*
693 		 * allocate a bunch of read buffers and queue them all at once.
694 		 */
695 		for (i = 0; i < hidg->qlen && status == 0; i++) {
696 			struct usb_request *req =
697 					hidg_alloc_ep_req(hidg->out_ep,
698 							  hidg->report_length);
699 			if (req) {
700 				req->complete = hidg_set_report_complete;
701 				req->context  = hidg;
702 				status = usb_ep_queue(hidg->out_ep, req,
703 						      GFP_ATOMIC);
704 				if (status) {
705 					ERROR(cdev, "%s queue req --> %d\n",
706 						hidg->out_ep->name, status);
707 					free_ep_req(hidg->out_ep, req);
708 				}
709 			} else {
710 				status = -ENOMEM;
711 				goto disable_out_ep;
712 			}
713 		}
714 	}
715 
716 	if (hidg->in_ep != NULL) {
717 		spin_lock_irqsave(&hidg->write_spinlock, flags);
718 		hidg->req = req_in;
719 		hidg->write_pending = 0;
720 		spin_unlock_irqrestore(&hidg->write_spinlock, flags);
721 
722 		wake_up(&hidg->write_queue);
723 	}
724 	return 0;
725 disable_out_ep:
726 	usb_ep_disable(hidg->out_ep);
727 free_req_in:
728 	if (req_in)
729 		free_ep_req(hidg->in_ep, req_in);
730 
731 disable_ep_in:
732 	if (hidg->in_ep)
733 		usb_ep_disable(hidg->in_ep);
734 
735 fail:
736 	return status;
737 }
738 
739 static const struct file_operations f_hidg_fops = {
740 	.owner		= THIS_MODULE,
741 	.open		= f_hidg_open,
742 	.release	= f_hidg_release,
743 	.write		= f_hidg_write,
744 	.read		= f_hidg_read,
745 	.poll		= f_hidg_poll,
746 	.llseek		= noop_llseek,
747 };
748 
749 static int hidg_bind(struct usb_configuration *c, struct usb_function *f)
750 {
751 	struct usb_ep		*ep;
752 	struct f_hidg		*hidg = func_to_hidg(f);
753 	struct usb_string	*us;
754 	struct device		*device;
755 	int			status;
756 	dev_t			dev;
757 
758 	/* maybe allocate device-global string IDs, and patch descriptors */
759 	us = usb_gstrings_attach(c->cdev, ct_func_strings,
760 				 ARRAY_SIZE(ct_func_string_defs));
761 	if (IS_ERR(us))
762 		return PTR_ERR(us);
763 	hidg_interface_desc.iInterface = us[CT_FUNC_HID_IDX].id;
764 
765 	/* allocate instance-specific interface IDs, and patch descriptors */
766 	status = usb_interface_id(c, f);
767 	if (status < 0)
768 		goto fail;
769 	hidg_interface_desc.bInterfaceNumber = status;
770 
771 	/* allocate instance-specific endpoints */
772 	status = -ENODEV;
773 	ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_in_ep_desc);
774 	if (!ep)
775 		goto fail;
776 	hidg->in_ep = ep;
777 
778 	ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_out_ep_desc);
779 	if (!ep)
780 		goto fail;
781 	hidg->out_ep = ep;
782 
783 	/* set descriptor dynamic values */
784 	hidg_interface_desc.bInterfaceSubClass = hidg->bInterfaceSubClass;
785 	hidg_interface_desc.bInterfaceProtocol = hidg->bInterfaceProtocol;
786 	hidg->protocol = HID_REPORT_PROTOCOL;
787 	hidg_ss_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
788 	hidg_ss_in_comp_desc.wBytesPerInterval =
789 				cpu_to_le16(hidg->report_length);
790 	hidg_hs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
791 	hidg_fs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
792 	hidg_ss_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
793 	hidg_ss_out_comp_desc.wBytesPerInterval =
794 				cpu_to_le16(hidg->report_length);
795 	hidg_hs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
796 	hidg_fs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
797 	/*
798 	 * We can use hidg_desc struct here but we should not relay
799 	 * that its content won't change after returning from this function.
800 	 */
801 	hidg_desc.desc[0].bDescriptorType = HID_DT_REPORT;
802 	hidg_desc.desc[0].wDescriptorLength =
803 		cpu_to_le16(hidg->report_desc_length);
804 
805 	hidg_hs_in_ep_desc.bEndpointAddress =
806 		hidg_fs_in_ep_desc.bEndpointAddress;
807 	hidg_hs_out_ep_desc.bEndpointAddress =
808 		hidg_fs_out_ep_desc.bEndpointAddress;
809 
810 	hidg_ss_in_ep_desc.bEndpointAddress =
811 		hidg_fs_in_ep_desc.bEndpointAddress;
812 	hidg_ss_out_ep_desc.bEndpointAddress =
813 		hidg_fs_out_ep_desc.bEndpointAddress;
814 
815 	status = usb_assign_descriptors(f, hidg_fs_descriptors,
816 			hidg_hs_descriptors, hidg_ss_descriptors, NULL);
817 	if (status)
818 		goto fail;
819 
820 	spin_lock_init(&hidg->write_spinlock);
821 	hidg->write_pending = 1;
822 	hidg->req = NULL;
823 	spin_lock_init(&hidg->read_spinlock);
824 	init_waitqueue_head(&hidg->write_queue);
825 	init_waitqueue_head(&hidg->read_queue);
826 	INIT_LIST_HEAD(&hidg->completed_out_req);
827 
828 	/* create char device */
829 	cdev_init(&hidg->cdev, &f_hidg_fops);
830 	dev = MKDEV(major, hidg->minor);
831 	status = cdev_add(&hidg->cdev, dev, 1);
832 	if (status)
833 		goto fail_free_descs;
834 
835 	device = device_create(hidg_class, NULL, dev, NULL,
836 			       "%s%d", "hidg", hidg->minor);
837 	if (IS_ERR(device)) {
838 		status = PTR_ERR(device);
839 		goto del;
840 	}
841 
842 	return 0;
843 del:
844 	cdev_del(&hidg->cdev);
845 fail_free_descs:
846 	usb_free_all_descriptors(f);
847 fail:
848 	ERROR(f->config->cdev, "hidg_bind FAILED\n");
849 	if (hidg->req != NULL)
850 		free_ep_req(hidg->in_ep, hidg->req);
851 
852 	return status;
853 }
854 
855 static inline int hidg_get_minor(void)
856 {
857 	int ret;
858 
859 	ret = ida_simple_get(&hidg_ida, 0, 0, GFP_KERNEL);
860 	if (ret >= HIDG_MINORS) {
861 		ida_simple_remove(&hidg_ida, ret);
862 		ret = -ENODEV;
863 	}
864 
865 	return ret;
866 }
867 
868 static inline struct f_hid_opts *to_f_hid_opts(struct config_item *item)
869 {
870 	return container_of(to_config_group(item), struct f_hid_opts,
871 			    func_inst.group);
872 }
873 
874 static void hid_attr_release(struct config_item *item)
875 {
876 	struct f_hid_opts *opts = to_f_hid_opts(item);
877 
878 	usb_put_function_instance(&opts->func_inst);
879 }
880 
881 static struct configfs_item_operations hidg_item_ops = {
882 	.release	= hid_attr_release,
883 };
884 
885 #define F_HID_OPT(name, prec, limit)					\
886 static ssize_t f_hid_opts_##name##_show(struct config_item *item, char *page)\
887 {									\
888 	struct f_hid_opts *opts = to_f_hid_opts(item);			\
889 	int result;							\
890 									\
891 	mutex_lock(&opts->lock);					\
892 	result = sprintf(page, "%d\n", opts->name);			\
893 	mutex_unlock(&opts->lock);					\
894 									\
895 	return result;							\
896 }									\
897 									\
898 static ssize_t f_hid_opts_##name##_store(struct config_item *item,	\
899 					 const char *page, size_t len)	\
900 {									\
901 	struct f_hid_opts *opts = to_f_hid_opts(item);			\
902 	int ret;							\
903 	u##prec num;							\
904 									\
905 	mutex_lock(&opts->lock);					\
906 	if (opts->refcnt) {						\
907 		ret = -EBUSY;						\
908 		goto end;						\
909 	}								\
910 									\
911 	ret = kstrtou##prec(page, 0, &num);				\
912 	if (ret)							\
913 		goto end;						\
914 									\
915 	if (num > limit) {						\
916 		ret = -EINVAL;						\
917 		goto end;						\
918 	}								\
919 	opts->name = num;						\
920 	ret = len;							\
921 									\
922 end:									\
923 	mutex_unlock(&opts->lock);					\
924 	return ret;							\
925 }									\
926 									\
927 CONFIGFS_ATTR(f_hid_opts_, name)
928 
929 F_HID_OPT(subclass, 8, 255);
930 F_HID_OPT(protocol, 8, 255);
931 F_HID_OPT(report_length, 16, 65535);
932 
933 static ssize_t f_hid_opts_report_desc_show(struct config_item *item, char *page)
934 {
935 	struct f_hid_opts *opts = to_f_hid_opts(item);
936 	int result;
937 
938 	mutex_lock(&opts->lock);
939 	result = opts->report_desc_length;
940 	memcpy(page, opts->report_desc, opts->report_desc_length);
941 	mutex_unlock(&opts->lock);
942 
943 	return result;
944 }
945 
946 static ssize_t f_hid_opts_report_desc_store(struct config_item *item,
947 					    const char *page, size_t len)
948 {
949 	struct f_hid_opts *opts = to_f_hid_opts(item);
950 	int ret = -EBUSY;
951 	char *d;
952 
953 	mutex_lock(&opts->lock);
954 
955 	if (opts->refcnt)
956 		goto end;
957 	if (len > PAGE_SIZE) {
958 		ret = -ENOSPC;
959 		goto end;
960 	}
961 	d = kmemdup(page, len, GFP_KERNEL);
962 	if (!d) {
963 		ret = -ENOMEM;
964 		goto end;
965 	}
966 	kfree(opts->report_desc);
967 	opts->report_desc = d;
968 	opts->report_desc_length = len;
969 	opts->report_desc_alloc = true;
970 	ret = len;
971 end:
972 	mutex_unlock(&opts->lock);
973 	return ret;
974 }
975 
976 CONFIGFS_ATTR(f_hid_opts_, report_desc);
977 
978 static ssize_t f_hid_opts_dev_show(struct config_item *item, char *page)
979 {
980 	struct f_hid_opts *opts = to_f_hid_opts(item);
981 
982 	return sprintf(page, "%d:%d\n", major, opts->minor);
983 }
984 
985 CONFIGFS_ATTR_RO(f_hid_opts_, dev);
986 
987 static struct configfs_attribute *hid_attrs[] = {
988 	&f_hid_opts_attr_subclass,
989 	&f_hid_opts_attr_protocol,
990 	&f_hid_opts_attr_report_length,
991 	&f_hid_opts_attr_report_desc,
992 	&f_hid_opts_attr_dev,
993 	NULL,
994 };
995 
996 static struct config_item_type hid_func_type = {
997 	.ct_item_ops	= &hidg_item_ops,
998 	.ct_attrs	= hid_attrs,
999 	.ct_owner	= THIS_MODULE,
1000 };
1001 
1002 static inline void hidg_put_minor(int minor)
1003 {
1004 	ida_simple_remove(&hidg_ida, minor);
1005 }
1006 
1007 static void hidg_free_inst(struct usb_function_instance *f)
1008 {
1009 	struct f_hid_opts *opts;
1010 
1011 	opts = container_of(f, struct f_hid_opts, func_inst);
1012 
1013 	mutex_lock(&hidg_ida_lock);
1014 
1015 	hidg_put_minor(opts->minor);
1016 	if (ida_is_empty(&hidg_ida))
1017 		ghid_cleanup();
1018 
1019 	mutex_unlock(&hidg_ida_lock);
1020 
1021 	if (opts->report_desc_alloc)
1022 		kfree(opts->report_desc);
1023 
1024 	kfree(opts);
1025 }
1026 
1027 static struct usb_function_instance *hidg_alloc_inst(void)
1028 {
1029 	struct f_hid_opts *opts;
1030 	struct usb_function_instance *ret;
1031 	int status = 0;
1032 
1033 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1034 	if (!opts)
1035 		return ERR_PTR(-ENOMEM);
1036 	mutex_init(&opts->lock);
1037 	opts->func_inst.free_func_inst = hidg_free_inst;
1038 	ret = &opts->func_inst;
1039 
1040 	mutex_lock(&hidg_ida_lock);
1041 
1042 	if (ida_is_empty(&hidg_ida)) {
1043 		status = ghid_setup(NULL, HIDG_MINORS);
1044 		if (status)  {
1045 			ret = ERR_PTR(status);
1046 			kfree(opts);
1047 			goto unlock;
1048 		}
1049 	}
1050 
1051 	opts->minor = hidg_get_minor();
1052 	if (opts->minor < 0) {
1053 		ret = ERR_PTR(opts->minor);
1054 		kfree(opts);
1055 		if (ida_is_empty(&hidg_ida))
1056 			ghid_cleanup();
1057 		goto unlock;
1058 	}
1059 	config_group_init_type_name(&opts->func_inst.group, "", &hid_func_type);
1060 
1061 unlock:
1062 	mutex_unlock(&hidg_ida_lock);
1063 	return ret;
1064 }
1065 
1066 static void hidg_free(struct usb_function *f)
1067 {
1068 	struct f_hidg *hidg;
1069 	struct f_hid_opts *opts;
1070 
1071 	hidg = func_to_hidg(f);
1072 	opts = container_of(f->fi, struct f_hid_opts, func_inst);
1073 	kfree(hidg->report_desc);
1074 	kfree(hidg);
1075 	mutex_lock(&opts->lock);
1076 	--opts->refcnt;
1077 	mutex_unlock(&opts->lock);
1078 }
1079 
1080 static void hidg_unbind(struct usb_configuration *c, struct usb_function *f)
1081 {
1082 	struct f_hidg *hidg = func_to_hidg(f);
1083 
1084 	device_destroy(hidg_class, MKDEV(major, hidg->minor));
1085 	cdev_del(&hidg->cdev);
1086 
1087 	usb_free_all_descriptors(f);
1088 }
1089 
1090 static struct usb_function *hidg_alloc(struct usb_function_instance *fi)
1091 {
1092 	struct f_hidg *hidg;
1093 	struct f_hid_opts *opts;
1094 
1095 	/* allocate and initialize one new instance */
1096 	hidg = kzalloc(sizeof(*hidg), GFP_KERNEL);
1097 	if (!hidg)
1098 		return ERR_PTR(-ENOMEM);
1099 
1100 	opts = container_of(fi, struct f_hid_opts, func_inst);
1101 
1102 	mutex_lock(&opts->lock);
1103 	++opts->refcnt;
1104 
1105 	hidg->minor = opts->minor;
1106 	hidg->bInterfaceSubClass = opts->subclass;
1107 	hidg->bInterfaceProtocol = opts->protocol;
1108 	hidg->report_length = opts->report_length;
1109 	hidg->report_desc_length = opts->report_desc_length;
1110 	if (opts->report_desc) {
1111 		hidg->report_desc = kmemdup(opts->report_desc,
1112 					    opts->report_desc_length,
1113 					    GFP_KERNEL);
1114 		if (!hidg->report_desc) {
1115 			kfree(hidg);
1116 			mutex_unlock(&opts->lock);
1117 			return ERR_PTR(-ENOMEM);
1118 		}
1119 	}
1120 
1121 	mutex_unlock(&opts->lock);
1122 
1123 	hidg->func.name    = "hid";
1124 	hidg->func.bind    = hidg_bind;
1125 	hidg->func.unbind  = hidg_unbind;
1126 	hidg->func.set_alt = hidg_set_alt;
1127 	hidg->func.disable = hidg_disable;
1128 	hidg->func.setup   = hidg_setup;
1129 	hidg->func.free_func = hidg_free;
1130 
1131 	/* this could me made configurable at some point */
1132 	hidg->qlen	   = 4;
1133 
1134 	return &hidg->func;
1135 }
1136 
1137 DECLARE_USB_FUNCTION_INIT(hid, hidg_alloc_inst, hidg_alloc);
1138 MODULE_LICENSE("GPL");
1139 MODULE_AUTHOR("Fabien Chouteau");
1140 
1141 int ghid_setup(struct usb_gadget *g, int count)
1142 {
1143 	int status;
1144 	dev_t dev;
1145 
1146 	hidg_class = class_create(THIS_MODULE, "hidg");
1147 	if (IS_ERR(hidg_class)) {
1148 		status = PTR_ERR(hidg_class);
1149 		hidg_class = NULL;
1150 		return status;
1151 	}
1152 
1153 	status = alloc_chrdev_region(&dev, 0, count, "hidg");
1154 	if (status) {
1155 		class_destroy(hidg_class);
1156 		hidg_class = NULL;
1157 		return status;
1158 	}
1159 
1160 	major = MAJOR(dev);
1161 	minors = count;
1162 
1163 	return 0;
1164 }
1165 
1166 void ghid_cleanup(void)
1167 {
1168 	if (major) {
1169 		unregister_chrdev_region(MKDEV(major, 0), minors);
1170 		major = minors = 0;
1171 	}
1172 
1173 	class_destroy(hidg_class);
1174 	hidg_class = NULL;
1175 }
1176