Linux Audio

Check our new training course

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