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