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