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