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