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