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