f_hid.c 29.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * f_hid.c -- USB HID function driver
 *
 * Copyright (C) 2010 Fabien Chouteau <fabien.chouteau@barco.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/hid.h>
15
#include <linux/idr.h>
16 17 18 19 20
#include <linux/cdev.h>
#include <linux/mutex.h>
#include <linux/poll.h>
#include <linux/uaccess.h>
#include <linux/wait.h>
21
#include <linux/sched.h>
22 23
#include <linux/usb/g_hid.h>

24
#include "u_f.h"
25 26 27
#include "u_hid.h"

#define HIDG_MINORS	4
28

29 30
static int major, minors;
static struct class *hidg_class;
31 32
static DEFINE_IDA(hidg_ida);
static DEFINE_MUTEX(hidg_ida_lock); /* protects access to hidg_ida */
33 34 35 36

/*-------------------------------------------------------------------------*/
/*                            HID gadget struct                            */

37 38 39 40 41 42
struct f_hidg_req_list {
	struct usb_request	*req;
	unsigned int		pos;
	struct list_head 	list;
};

43 44 45 46
struct f_hidg {
	/* configuration */
	unsigned char			bInterfaceSubClass;
	unsigned char			bInterfaceProtocol;
47
	unsigned char			protocol;
48 49 50 51 52
	unsigned short			report_desc_length;
	char				*report_desc;
	unsigned short			report_length;

	/* recv report */
53
	struct list_head		completed_out_req;
54
	spinlock_t			read_spinlock;
55
	wait_queue_head_t		read_queue;
56
	unsigned int			qlen;
57 58

	/* send report */
59
	spinlock_t			write_spinlock;
60 61 62 63 64 65 66
	bool				write_pending;
	wait_queue_head_t		write_queue;
	struct usb_request		*req;

	int				minor;
	struct cdev			cdev;
	struct usb_function		func;
67

68
	struct usb_ep			*in_ep;
69
	struct usb_ep			*out_ep;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
};

static inline struct f_hidg *func_to_hidg(struct usb_function *f)
{
	return container_of(f, struct f_hidg, func);
}

/*-------------------------------------------------------------------------*/
/*                           Static descriptors                            */

static struct usb_interface_descriptor hidg_interface_desc = {
	.bLength		= sizeof hidg_interface_desc,
	.bDescriptorType	= USB_DT_INTERFACE,
	/* .bInterfaceNumber	= DYNAMIC */
	.bAlternateSetting	= 0,
85
	.bNumEndpoints		= 2,
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
	.bInterfaceClass	= USB_CLASS_HID,
	/* .bInterfaceSubClass	= DYNAMIC */
	/* .bInterfaceProtocol	= DYNAMIC */
	/* .iInterface		= DYNAMIC */
};

static struct hid_descriptor hidg_desc = {
	.bLength			= sizeof hidg_desc,
	.bDescriptorType		= HID_DT_HID,
	.bcdHID				= 0x0101,
	.bCountryCode			= 0x00,
	.bNumDescriptors		= 0x1,
	/*.desc[0].bDescriptorType	= DYNAMIC */
	/*.desc[0].wDescriptorLenght	= DYNAMIC */
};

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
/* Super-Speed Support */

static struct usb_endpoint_descriptor hidg_ss_in_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_IN,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 4, /* FIXME: Add this field in the
				      * HID gadget configuration?
				      * (struct hidg_func_descriptor)
				      */
};

static struct usb_ss_ep_comp_descriptor hidg_ss_in_comp_desc = {
	.bLength                = sizeof(hidg_ss_in_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,

	/* .bMaxBurst           = 0, */
	/* .bmAttributes        = 0, */
	/* .wBytesPerInterval   = DYNAMIC */
};

static struct usb_endpoint_descriptor hidg_ss_out_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_OUT,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 4, /* FIXME: Add this field in the
				      * HID gadget configuration?
				      * (struct hidg_func_descriptor)
				      */
};

static struct usb_ss_ep_comp_descriptor hidg_ss_out_comp_desc = {
	.bLength                = sizeof(hidg_ss_out_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,

	/* .bMaxBurst           = 0, */
	/* .bmAttributes        = 0, */
	/* .wBytesPerInterval   = DYNAMIC */
};

static struct usb_descriptor_header *hidg_ss_descriptors[] = {
	(struct usb_descriptor_header *)&hidg_interface_desc,
	(struct usb_descriptor_header *)&hidg_desc,
	(struct usb_descriptor_header *)&hidg_ss_in_ep_desc,
	(struct usb_descriptor_header *)&hidg_ss_in_comp_desc,
	(struct usb_descriptor_header *)&hidg_ss_out_ep_desc,
	(struct usb_descriptor_header *)&hidg_ss_out_comp_desc,
	NULL,
};

156 157 158 159 160 161 162 163 164 165 166 167 168 169
/* High-Speed Support */

static struct usb_endpoint_descriptor hidg_hs_in_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_IN,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 4, /* FIXME: Add this field in the
				      * HID gadget configuration?
				      * (struct hidg_func_descriptor)
				      */
};

170 171 172 173 174 175 176 177 178 179 180 181
static struct usb_endpoint_descriptor hidg_hs_out_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_OUT,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 4, /* FIXME: Add this field in the
				      * HID gadget configuration?
				      * (struct hidg_func_descriptor)
				      */
};

182 183 184 185
static struct usb_descriptor_header *hidg_hs_descriptors[] = {
	(struct usb_descriptor_header *)&hidg_interface_desc,
	(struct usb_descriptor_header *)&hidg_desc,
	(struct usb_descriptor_header *)&hidg_hs_in_ep_desc,
186
	(struct usb_descriptor_header *)&hidg_hs_out_ep_desc,
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
	NULL,
};

/* Full-Speed Support */

static struct usb_endpoint_descriptor hidg_fs_in_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_IN,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 10, /* FIXME: Add this field in the
				       * HID gadget configuration?
				       * (struct hidg_func_descriptor)
				       */
};

204 205 206 207 208 209 210 211 212 213 214 215
static struct usb_endpoint_descriptor hidg_fs_out_ep_desc = {
	.bLength		= USB_DT_ENDPOINT_SIZE,
	.bDescriptorType	= USB_DT_ENDPOINT,
	.bEndpointAddress	= USB_DIR_OUT,
	.bmAttributes		= USB_ENDPOINT_XFER_INT,
	/*.wMaxPacketSize	= DYNAMIC */
	.bInterval		= 10, /* FIXME: Add this field in the
				       * HID gadget configuration?
				       * (struct hidg_func_descriptor)
				       */
};

216 217 218 219
static struct usb_descriptor_header *hidg_fs_descriptors[] = {
	(struct usb_descriptor_header *)&hidg_interface_desc,
	(struct usb_descriptor_header *)&hidg_desc,
	(struct usb_descriptor_header *)&hidg_fs_in_ep_desc,
220
	(struct usb_descriptor_header *)&hidg_fs_out_ep_desc,
221 222 223
	NULL,
};

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
/*-------------------------------------------------------------------------*/
/*                                 Strings                                 */

#define CT_FUNC_HID_IDX	0

static struct usb_string ct_func_string_defs[] = {
	[CT_FUNC_HID_IDX].s	= "HID Interface",
	{},			/* end of list */
};

static struct usb_gadget_strings ct_func_string_table = {
	.language	= 0x0409,	/* en-US */
	.strings	= ct_func_string_defs,
};

static struct usb_gadget_strings *ct_func_strings[] = {
	&ct_func_string_table,
	NULL,
};

244 245 246 247 248 249
/*-------------------------------------------------------------------------*/
/*                              Char Device                                */

static ssize_t f_hidg_read(struct file *file, char __user *buffer,
			size_t count, loff_t *ptr)
{
250 251 252 253 254
	struct f_hidg *hidg = file->private_data;
	struct f_hidg_req_list *list;
	struct usb_request *req;
	unsigned long flags;
	int ret;
255 256 257 258 259 260 261

	if (!count)
		return 0;

	if (!access_ok(VERIFY_WRITE, buffer, count))
		return -EFAULT;

262
	spin_lock_irqsave(&hidg->read_spinlock, flags);
263

264
#define READ_COND (!list_empty(&hidg->completed_out_req))
265

266
	/* wait for at least one buffer to complete */
267
	while (!READ_COND) {
268
		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
269 270 271 272 273 274
		if (file->f_flags & O_NONBLOCK)
			return -EAGAIN;

		if (wait_event_interruptible(hidg->read_queue, READ_COND))
			return -ERESTARTSYS;

275
		spin_lock_irqsave(&hidg->read_spinlock, flags);
276 277
	}

278 279 280
	/* pick the first one */
	list = list_first_entry(&hidg->completed_out_req,
				struct f_hidg_req_list, list);
281 282 283 284 285 286 287

	/*
	 * Remove this from list to protect it from beign free()
	 * while host disables our function
	 */
	list_del(&list->list);

288 289
	req = list->req;
	count = min_t(unsigned int, count, req->actual - list->pos);
290
	spin_unlock_irqrestore(&hidg->read_spinlock, flags);
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	/* copy to user outside spinlock */
	count -= copy_to_user(buffer, req->buf + list->pos, count);
	list->pos += count;

	/*
	 * if this request is completely handled and transfered to
	 * userspace, remove its entry from the list and requeue it
	 * again. Otherwise, we will revisit it again upon the next
	 * call, taking into account its current read position.
	 */
	if (list->pos == req->actual) {
		kfree(list);

		req->length = hidg->report_length;
		ret = usb_ep_queue(hidg->out_ep, req, GFP_KERNEL);
307 308
		if (ret < 0) {
			free_ep_req(hidg->out_ep, req);
309
			return ret;
310 311
		}
	} else {
312
		spin_lock_irqsave(&hidg->read_spinlock, flags);
313
		list_add(&list->list, &hidg->completed_out_req);
314
		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
315 316

		wake_up(&hidg->read_queue);
317
	}
318 319 320 321 322 323 324

	return count;
}

static void f_hidg_req_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct f_hidg *hidg = (struct f_hidg *)ep->driver_data;
325
	unsigned long flags;
326 327 328 329 330 331

	if (req->status != 0) {
		ERROR(hidg->func.config->cdev,
			"End Point Request ERROR: %d\n", req->status);
	}

332
	spin_lock_irqsave(&hidg->write_spinlock, flags);
333
	hidg->write_pending = 0;
334
	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
335 336 337 338 339 340
	wake_up(&hidg->write_queue);
}

static ssize_t f_hidg_write(struct file *file, const char __user *buffer,
			    size_t count, loff_t *offp)
{
341
	struct f_hidg *hidg  = file->private_data;
342
	struct usb_request *req;
343
	unsigned long flags;
344 345 346 347 348
	ssize_t status = -ENOMEM;

	if (!access_ok(VERIFY_READ, buffer, count))
		return -EFAULT;

349
	spin_lock_irqsave(&hidg->write_spinlock, flags);
350 351

#define WRITE_COND (!hidg->write_pending)
352
try_again:
353 354
	/* write queue */
	while (!WRITE_COND) {
355
		spin_unlock_irqrestore(&hidg->write_spinlock, flags);
356 357 358 359 360 361 362
		if (file->f_flags & O_NONBLOCK)
			return -EAGAIN;

		if (wait_event_interruptible_exclusive(
				hidg->write_queue, WRITE_COND))
			return -ERESTARTSYS;

363
		spin_lock_irqsave(&hidg->write_spinlock, flags);
364 365
	}

366
	hidg->write_pending = 1;
367
	req = hidg->req;
368
	count  = min_t(unsigned, count, hidg->report_length);
369 370

	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
371
	status = copy_from_user(req->buf, buffer, count);
372 373 374 375

	if (status != 0) {
		ERROR(hidg->func.config->cdev,
			"copy_from_user error\n");
376 377
		status = -EINVAL;
		goto release_write_pending;
378 379
	}

380 381
	spin_lock_irqsave(&hidg->write_spinlock, flags);

382
	/* when our function has been disabled by host */
383
	if (!hidg->req) {
384
		free_ep_req(hidg->in_ep, req);
385 386 387 388 389 390 391 392 393 394 395 396
		/*
		 * TODO
		 * Should we fail with error here?
		 */
		goto try_again;
	}

	req->status   = 0;
	req->zero     = 0;
	req->length   = count;
	req->complete = f_hidg_req_complete;
	req->context  = hidg;
397

398
	status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);
399 400 401
	if (status < 0) {
		ERROR(hidg->func.config->cdev,
			"usb_ep_queue error on int endpoint %zd\n", status);
402
		goto release_write_pending_unlocked;
403 404 405
	} else {
		status = count;
	}
406
	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
407

408 409 410
	return status;
release_write_pending:
	spin_lock_irqsave(&hidg->write_spinlock, flags);
411
release_write_pending_unlocked:
412 413 414 415
	hidg->write_pending = 0;
	spin_unlock_irqrestore(&hidg->write_spinlock, flags);

	wake_up(&hidg->write_queue);
416 417 418 419 420 421

	return status;
}

static unsigned int f_hidg_poll(struct file *file, poll_table *wait)
{
422
	struct f_hidg	*hidg  = file->private_data;
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	unsigned int	ret = 0;

	poll_wait(file, &hidg->read_queue, wait);
	poll_wait(file, &hidg->write_queue, wait);

	if (WRITE_COND)
		ret |= POLLOUT | POLLWRNORM;

	if (READ_COND)
		ret |= POLLIN | POLLRDNORM;

	return ret;
}

#undef WRITE_COND
#undef READ_COND

static int f_hidg_release(struct inode *inode, struct file *fd)
{
	fd->private_data = NULL;
	return 0;
}

static int f_hidg_open(struct inode *inode, struct file *fd)
{
	struct f_hidg *hidg =
		container_of(inode->i_cdev, struct f_hidg, cdev);

	fd->private_data = hidg;

	return 0;
}

/*-------------------------------------------------------------------------*/
/*                                usb_function                             */

459 460
static inline struct usb_request *hidg_alloc_ep_req(struct usb_ep *ep,
						    unsigned length)
461
{
462
	return alloc_ep_req(ep, length);
463
}
464

465 466 467
static void hidg_set_report_complete(struct usb_ep *ep, struct usb_request *req)
{
	struct f_hidg *hidg = (struct f_hidg *) req->context;
468
	struct usb_composite_dev *cdev = hidg->func.config->cdev;
469 470
	struct f_hidg_req_list *req_list;
	unsigned long flags;
471

472 473 474 475 476 477 478
	switch (req->status) {
	case 0:
		req_list = kzalloc(sizeof(*req_list), GFP_ATOMIC);
		if (!req_list) {
			ERROR(cdev, "Unable to allocate mem for req_list\n");
			goto free_req;
		}
479

480
		req_list->req = req;
481

482
		spin_lock_irqsave(&hidg->read_spinlock, flags);
483
		list_add_tail(&req_list->list, &hidg->completed_out_req);
484
		spin_unlock_irqrestore(&hidg->read_spinlock, flags);
485

486 487 488 489 490 491 492 493 494 495 496 497
		wake_up(&hidg->read_queue);
		break;
	default:
		ERROR(cdev, "Set report failed %d\n", req->status);
		/* FALLTHROUGH */
	case -ECONNABORTED:		/* hardware forced ep reset */
	case -ECONNRESET:		/* request dequeued */
	case -ESHUTDOWN:		/* disconnect from host */
free_req:
		free_ep_req(ep, req);
		return;
	}
498 499 500 501 502 503 504 505 506 507 508 509 510 511
}

static int hidg_setup(struct usb_function *f,
		const struct usb_ctrlrequest *ctrl)
{
	struct f_hidg			*hidg = func_to_hidg(f);
	struct usb_composite_dev	*cdev = f->config->cdev;
	struct usb_request		*req  = cdev->req;
	int status = 0;
	__u16 value, length;

	value	= __le16_to_cpu(ctrl->wValue);
	length	= __le16_to_cpu(ctrl->wLength);

512 513 514
	VDBG(cdev,
	     "%s crtl_request : bRequestType:0x%x bRequest:0x%x Value:0x%x\n",
	     __func__, ctrl->bRequestType, ctrl->bRequest, value);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

	switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
		  | HID_REQ_GET_REPORT):
		VDBG(cdev, "get_report\n");

		/* send an empty report */
		length = min_t(unsigned, length, hidg->report_length);
		memset(req->buf, 0x0, length);

		goto respond;
		break;

	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
		  | HID_REQ_GET_PROTOCOL):
		VDBG(cdev, "get_protocol\n");
531 532 533
		length = min_t(unsigned int, length, 1);
		((u8 *) req->buf)[0] = hidg->protocol;
		goto respond;
534 535 536 537
		break;

	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
		  | HID_REQ_SET_REPORT):
538
		VDBG(cdev, "set_report | wLength=%d\n", ctrl->wLength);
539
		goto stall;
540 541 542 543 544
		break;

	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
		  | HID_REQ_SET_PROTOCOL):
		VDBG(cdev, "set_protocol\n");
545 546 547 548 549 550 551 552 553 554 555
		if (value > HID_REPORT_PROTOCOL)
			goto stall;
		length = 0;
		/*
		 * We assume that programs implementing the Boot protocol
		 * are also compatible with the Report Protocol
		 */
		if (hidg->bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
			hidg->protocol = value;
			goto respond;
		}
556 557 558 559 560 561
		goto stall;
		break;

	case ((USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE) << 8
		  | USB_REQ_GET_DESCRIPTOR):
		switch (value >> 8) {
562
		case HID_DT_HID:
563 564 565
		{
			struct hid_descriptor hidg_desc_copy = hidg_desc;

566
			VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: HID\n");
567 568 569 570
			hidg_desc_copy.desc[0].bDescriptorType = HID_DT_REPORT;
			hidg_desc_copy.desc[0].wDescriptorLength =
				cpu_to_le16(hidg->report_desc_length);

571
			length = min_t(unsigned short, length,
572 573
						   hidg_desc_copy.bLength);
			memcpy(req->buf, &hidg_desc_copy, length);
574 575
			goto respond;
			break;
576
		}
577 578 579 580 581 582 583 584 585
		case HID_DT_REPORT:
			VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: REPORT\n");
			length = min_t(unsigned short, length,
						   hidg->report_desc_length);
			memcpy(req->buf, hidg->report_desc, length);
			goto respond;
			break;

		default:
M
Masanari Iida 已提交
586
			VDBG(cdev, "Unknown descriptor request 0x%x\n",
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
				 value >> 8);
			goto stall;
			break;
		}
		break;

	default:
		VDBG(cdev, "Unknown request 0x%x\n",
			 ctrl->bRequest);
		goto stall;
		break;
	}

stall:
	return -EOPNOTSUPP;

respond:
	req->zero = 0;
	req->length = length;
	status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
	if (status < 0)
		ERROR(cdev, "usb_ep_queue error on ep0 %d\n", value);
	return status;
}

static void hidg_disable(struct usb_function *f)
{
	struct f_hidg *hidg = func_to_hidg(f);
615
	struct f_hidg_req_list *list, *next;
616
	unsigned long flags;
617 618

	usb_ep_disable(hidg->in_ep);
619 620
	usb_ep_disable(hidg->out_ep);

621
	spin_lock_irqsave(&hidg->read_spinlock, flags);
622
	list_for_each_entry_safe(list, next, &hidg->completed_out_req, list) {
623
		free_ep_req(hidg->out_ep, list->req);
624 625 626
		list_del(&list->list);
		kfree(list);
	}
627
	spin_unlock_irqrestore(&hidg->read_spinlock, flags);
628 629 630 631 632 633 634 635 636

	spin_lock_irqsave(&hidg->write_spinlock, flags);
	if (!hidg->write_pending) {
		free_ep_req(hidg->in_ep, hidg->req);
		hidg->write_pending = 1;
	}

	hidg->req = NULL;
	spin_unlock_irqrestore(&hidg->write_spinlock, flags);
637 638 639 640 641 642
}

static int hidg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
{
	struct usb_composite_dev		*cdev = f->config->cdev;
	struct f_hidg				*hidg = func_to_hidg(f);
643 644
	struct usb_request			*req_in = NULL;
	unsigned long				flags;
645
	int i, status = 0;
646 647 648 649 650

	VDBG(cdev, "hidg_set_alt intf:%d alt:%d\n", intf, alt);

	if (hidg->in_ep != NULL) {
		/* restart endpoint */
651
		usb_ep_disable(hidg->in_ep);
652

653 654 655 656 657 658
		status = config_ep_by_speed(f->config->cdev->gadget, f,
					    hidg->in_ep);
		if (status) {
			ERROR(cdev, "config_ep_by_speed FAILED!\n");
			goto fail;
		}
659
		status = usb_ep_enable(hidg->in_ep);
660
		if (status < 0) {
661
			ERROR(cdev, "Enable IN endpoint FAILED!\n");
662 663 664
			goto fail;
		}
		hidg->in_ep->driver_data = hidg;
665 666 667 668 669 670

		req_in = hidg_alloc_ep_req(hidg->in_ep, hidg->report_length);
		if (!req_in) {
			status = -ENOMEM;
			goto disable_ep_in;
		}
671
	}
672 673 674 675


	if (hidg->out_ep != NULL) {
		/* restart endpoint */
676
		usb_ep_disable(hidg->out_ep);
677 678 679 680 681

		status = config_ep_by_speed(f->config->cdev->gadget, f,
					    hidg->out_ep);
		if (status) {
			ERROR(cdev, "config_ep_by_speed FAILED!\n");
682
			goto free_req_in;
683 684 685
		}
		status = usb_ep_enable(hidg->out_ep);
		if (status < 0) {
686
			ERROR(cdev, "Enable OUT endpoint FAILED!\n");
687
			goto free_req_in;
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
		}
		hidg->out_ep->driver_data = hidg;

		/*
		 * allocate a bunch of read buffers and queue them all at once.
		 */
		for (i = 0; i < hidg->qlen && status == 0; i++) {
			struct usb_request *req =
					hidg_alloc_ep_req(hidg->out_ep,
							  hidg->report_length);
			if (req) {
				req->complete = hidg_set_report_complete;
				req->context  = hidg;
				status = usb_ep_queue(hidg->out_ep, req,
						      GFP_ATOMIC);
703
				if (status) {
704 705
					ERROR(cdev, "%s queue req --> %d\n",
						hidg->out_ep->name, status);
706 707
					free_ep_req(hidg->out_ep, req);
				}
708 709
			} else {
				status = -ENOMEM;
710
				goto disable_out_ep;
711 712 713 714
			}
		}
	}

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	if (hidg->in_ep != NULL) {
		spin_lock_irqsave(&hidg->write_spinlock, flags);
		hidg->req = req_in;
		hidg->write_pending = 0;
		spin_unlock_irqrestore(&hidg->write_spinlock, flags);

		wake_up(&hidg->write_queue);
	}
	return 0;
disable_out_ep:
	usb_ep_disable(hidg->out_ep);
free_req_in:
	if (req_in)
		free_ep_req(hidg->in_ep, req_in);

disable_ep_in:
	if (hidg->in_ep)
		usb_ep_disable(hidg->in_ep);

734 735 736 737
fail:
	return status;
}

738
static const struct file_operations f_hidg_fops = {
739 740 741 742 743 744
	.owner		= THIS_MODULE,
	.open		= f_hidg_open,
	.release	= f_hidg_release,
	.write		= f_hidg_write,
	.read		= f_hidg_read,
	.poll		= f_hidg_poll,
745
	.llseek		= noop_llseek,
746 747
};

748
static int hidg_bind(struct usb_configuration *c, struct usb_function *f)
749 750 751
{
	struct usb_ep		*ep;
	struct f_hidg		*hidg = func_to_hidg(f);
752
	struct usb_string	*us;
753
	struct device		*device;
754 755 756
	int			status;
	dev_t			dev;

757
	/* maybe allocate device-global string IDs, and patch descriptors */
758 759 760 761 762
	us = usb_gstrings_attach(c->cdev, ct_func_strings,
				 ARRAY_SIZE(ct_func_string_defs));
	if (IS_ERR(us))
		return PTR_ERR(us);
	hidg_interface_desc.iInterface = us[CT_FUNC_HID_IDX].id;
763

764 765 766 767 768 769 770 771 772 773 774 775 776
	/* allocate instance-specific interface IDs, and patch descriptors */
	status = usb_interface_id(c, f);
	if (status < 0)
		goto fail;
	hidg_interface_desc.bInterfaceNumber = status;

	/* allocate instance-specific endpoints */
	status = -ENODEV;
	ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_in_ep_desc);
	if (!ep)
		goto fail;
	hidg->in_ep = ep;

777 778 779 780 781
	ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_out_ep_desc);
	if (!ep)
		goto fail;
	hidg->out_ep = ep;

782 783 784
	/* set descriptor dynamic values */
	hidg_interface_desc.bInterfaceSubClass = hidg->bInterfaceSubClass;
	hidg_interface_desc.bInterfaceProtocol = hidg->bInterfaceProtocol;
785
	hidg->protocol = HID_REPORT_PROTOCOL;
786 787 788
	hidg_ss_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
	hidg_ss_in_comp_desc.wBytesPerInterval =
				cpu_to_le16(hidg->report_length);
789 790
	hidg_hs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
	hidg_fs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
791 792 793
	hidg_ss_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
	hidg_ss_out_comp_desc.wBytesPerInterval =
				cpu_to_le16(hidg->report_length);
794 795
	hidg_hs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
	hidg_fs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
796 797 798 799
	/*
	 * We can use hidg_desc struct here but we should not relay
	 * that its content won't change after returning from this function.
	 */
800 801 802 803
	hidg_desc.desc[0].bDescriptorType = HID_DT_REPORT;
	hidg_desc.desc[0].wDescriptorLength =
		cpu_to_le16(hidg->report_desc_length);

804 805 806 807
	hidg_hs_in_ep_desc.bEndpointAddress =
		hidg_fs_in_ep_desc.bEndpointAddress;
	hidg_hs_out_ep_desc.bEndpointAddress =
		hidg_fs_out_ep_desc.bEndpointAddress;
808

809 810 811 812 813
	hidg_ss_in_ep_desc.bEndpointAddress =
		hidg_fs_in_ep_desc.bEndpointAddress;
	hidg_ss_out_ep_desc.bEndpointAddress =
		hidg_fs_out_ep_desc.bEndpointAddress;

814
	status = usb_assign_descriptors(f, hidg_fs_descriptors,
815
			hidg_hs_descriptors, hidg_ss_descriptors, NULL);
816 817
	if (status)
		goto fail;
818

819
	spin_lock_init(&hidg->write_spinlock);
820 821
	hidg->write_pending = 1;
	hidg->req = NULL;
822
	spin_lock_init(&hidg->read_spinlock);
823 824
	init_waitqueue_head(&hidg->write_queue);
	init_waitqueue_head(&hidg->read_queue);
825
	INIT_LIST_HEAD(&hidg->completed_out_req);
826 827 828 829 830 831

	/* create char device */
	cdev_init(&hidg->cdev, &f_hidg_fops);
	dev = MKDEV(major, hidg->minor);
	status = cdev_add(&hidg->cdev, dev, 1);
	if (status)
832
		goto fail_free_descs;
833

834 835 836 837 838 839
	device = device_create(hidg_class, NULL, dev, NULL,
			       "%s%d", "hidg", hidg->minor);
	if (IS_ERR(device)) {
		status = PTR_ERR(device);
		goto del;
	}
840 841

	return 0;
842 843
del:
	cdev_del(&hidg->cdev);
844 845
fail_free_descs:
	usb_free_all_descriptors(f);
846 847
fail:
	ERROR(f->config->cdev, "hidg_bind FAILED\n");
848 849
	if (hidg->req != NULL)
		free_ep_req(hidg->in_ep, hidg->req);
850 851 852 853

	return status;
}

854
static inline int hidg_get_minor(void)
855
{
856
	int ret;
857

858
	ret = ida_simple_get(&hidg_ida, 0, 0, GFP_KERNEL);
859 860 861 862
	if (ret >= HIDG_MINORS) {
		ida_simple_remove(&hidg_ida, ret);
		ret = -ENODEV;
	}
863

864 865
	return ret;
}
866

867 868 869 870
static inline struct f_hid_opts *to_f_hid_opts(struct config_item *item)
{
	return container_of(to_config_group(item), struct f_hid_opts,
			    func_inst.group);
871 872
}

873 874 875
static void hid_attr_release(struct config_item *item)
{
	struct f_hid_opts *opts = to_f_hid_opts(item);
876

877 878
	usb_put_function_instance(&opts->func_inst);
}
879

880 881
static struct configfs_item_operations hidg_item_ops = {
	.release	= hid_attr_release,
882 883
};

884
#define F_HID_OPT(name, prec, limit)					\
885
static ssize_t f_hid_opts_##name##_show(struct config_item *item, char *page)\
886
{									\
887
	struct f_hid_opts *opts = to_f_hid_opts(item);			\
888 889 890 891 892 893 894 895 896
	int result;							\
									\
	mutex_lock(&opts->lock);					\
	result = sprintf(page, "%d\n", opts->name);			\
	mutex_unlock(&opts->lock);					\
									\
	return result;							\
}									\
									\
897
static ssize_t f_hid_opts_##name##_store(struct config_item *item,	\
898 899
					 const char *page, size_t len)	\
{									\
900
	struct f_hid_opts *opts = to_f_hid_opts(item);			\
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
	int ret;							\
	u##prec num;							\
									\
	mutex_lock(&opts->lock);					\
	if (opts->refcnt) {						\
		ret = -EBUSY;						\
		goto end;						\
	}								\
									\
	ret = kstrtou##prec(page, 0, &num);				\
	if (ret)							\
		goto end;						\
									\
	if (num > limit) {						\
		ret = -EINVAL;						\
		goto end;						\
	}								\
	opts->name = num;						\
	ret = len;							\
									\
end:									\
	mutex_unlock(&opts->lock);					\
	return ret;							\
}									\
									\
926
CONFIGFS_ATTR(f_hid_opts_, name)
927 928 929

F_HID_OPT(subclass, 8, 255);
F_HID_OPT(protocol, 8, 255);
930
F_HID_OPT(report_length, 16, 65535);
931

932
static ssize_t f_hid_opts_report_desc_show(struct config_item *item, char *page)
933
{
934
	struct f_hid_opts *opts = to_f_hid_opts(item);
935 936 937 938 939 940 941 942 943 944
	int result;

	mutex_lock(&opts->lock);
	result = opts->report_desc_length;
	memcpy(page, opts->report_desc, opts->report_desc_length);
	mutex_unlock(&opts->lock);

	return result;
}

945
static ssize_t f_hid_opts_report_desc_store(struct config_item *item,
946 947
					    const char *page, size_t len)
{
948
	struct f_hid_opts *opts = to_f_hid_opts(item);
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
	int ret = -EBUSY;
	char *d;

	mutex_lock(&opts->lock);

	if (opts->refcnt)
		goto end;
	if (len > PAGE_SIZE) {
		ret = -ENOSPC;
		goto end;
	}
	d = kmemdup(page, len, GFP_KERNEL);
	if (!d) {
		ret = -ENOMEM;
		goto end;
	}
	kfree(opts->report_desc);
	opts->report_desc = d;
	opts->report_desc_length = len;
	opts->report_desc_alloc = true;
	ret = len;
end:
	mutex_unlock(&opts->lock);
	return ret;
}

975
CONFIGFS_ATTR(f_hid_opts_, report_desc);
976

977 978 979 980 981 982 983 984 985
static ssize_t f_hid_opts_dev_show(struct config_item *item, char *page)
{
	struct f_hid_opts *opts = to_f_hid_opts(item);

	return sprintf(page, "%d:%d\n", major, opts->minor);
}

CONFIGFS_ATTR_RO(f_hid_opts_, dev);

986
static struct configfs_attribute *hid_attrs[] = {
987 988 989 990
	&f_hid_opts_attr_subclass,
	&f_hid_opts_attr_protocol,
	&f_hid_opts_attr_report_length,
	&f_hid_opts_attr_report_desc,
991
	&f_hid_opts_attr_dev,
992 993 994
	NULL,
};

995 996 997 998 999
static struct config_item_type hid_func_type = {
	.ct_item_ops	= &hidg_item_ops,
	.ct_attrs	= hid_attrs,
	.ct_owner	= THIS_MODULE,
};
1000

1001
static inline void hidg_put_minor(int minor)
1002
{
1003 1004
	ida_simple_remove(&hidg_ida, minor);
}
1005

1006 1007 1008
static void hidg_free_inst(struct usb_function_instance *f)
{
	struct f_hid_opts *opts;
1009

1010 1011 1012 1013 1014
	opts = container_of(f, struct f_hid_opts, func_inst);

	mutex_lock(&hidg_ida_lock);

	hidg_put_minor(opts->minor);
M
Matthew Wilcox 已提交
1015
	if (ida_is_empty(&hidg_ida))
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
		ghid_cleanup();

	mutex_unlock(&hidg_ida_lock);

	if (opts->report_desc_alloc)
		kfree(opts->report_desc);

	kfree(opts);
}

static struct usb_function_instance *hidg_alloc_inst(void)
{
	struct f_hid_opts *opts;
	struct usb_function_instance *ret;
	int status = 0;

	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
	if (!opts)
		return ERR_PTR(-ENOMEM);
1035
	mutex_init(&opts->lock);
1036 1037 1038 1039 1040
	opts->func_inst.free_func_inst = hidg_free_inst;
	ret = &opts->func_inst;

	mutex_lock(&hidg_ida_lock);

M
Matthew Wilcox 已提交
1041
	if (ida_is_empty(&hidg_ida)) {
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
		status = ghid_setup(NULL, HIDG_MINORS);
		if (status)  {
			ret = ERR_PTR(status);
			kfree(opts);
			goto unlock;
		}
	}

	opts->minor = hidg_get_minor();
	if (opts->minor < 0) {
		ret = ERR_PTR(opts->minor);
		kfree(opts);
M
Matthew Wilcox 已提交
1054
		if (ida_is_empty(&hidg_ida))
1055
			ghid_cleanup();
1056
		goto unlock;
1057
	}
1058
	config_group_init_type_name(&opts->func_inst.group, "", &hid_func_type);
1059 1060 1061 1062 1063 1064 1065 1066 1067

unlock:
	mutex_unlock(&hidg_ida_lock);
	return ret;
}

static void hidg_free(struct usb_function *f)
{
	struct f_hidg *hidg;
1068
	struct f_hid_opts *opts;
1069 1070

	hidg = func_to_hidg(f);
1071
	opts = container_of(f->fi, struct f_hid_opts, func_inst);
1072 1073
	kfree(hidg->report_desc);
	kfree(hidg);
1074 1075 1076
	mutex_lock(&opts->lock);
	--opts->refcnt;
	mutex_unlock(&opts->lock);
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
}

static void hidg_unbind(struct usb_configuration *c, struct usb_function *f)
{
	struct f_hidg *hidg = func_to_hidg(f);

	device_destroy(hidg_class, MKDEV(major, hidg->minor));
	cdev_del(&hidg->cdev);

	usb_free_all_descriptors(f);
}

1089
static struct usb_function *hidg_alloc(struct usb_function_instance *fi)
1090 1091 1092
{
	struct f_hidg *hidg;
	struct f_hid_opts *opts;
1093 1094

	/* allocate and initialize one new instance */
1095
	hidg = kzalloc(sizeof(*hidg), GFP_KERNEL);
1096
	if (!hidg)
1097 1098 1099 1100
		return ERR_PTR(-ENOMEM);

	opts = container_of(fi, struct f_hid_opts, func_inst);

1101 1102 1103
	mutex_lock(&opts->lock);
	++opts->refcnt;

1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
	hidg->minor = opts->minor;
	hidg->bInterfaceSubClass = opts->subclass;
	hidg->bInterfaceProtocol = opts->protocol;
	hidg->report_length = opts->report_length;
	hidg->report_desc_length = opts->report_desc_length;
	if (opts->report_desc) {
		hidg->report_desc = kmemdup(opts->report_desc,
					    opts->report_desc_length,
					    GFP_KERNEL);
		if (!hidg->report_desc) {
			kfree(hidg);
1115
			mutex_unlock(&opts->lock);
1116 1117
			return ERR_PTR(-ENOMEM);
		}
1118 1119
	}

1120 1121
	mutex_unlock(&opts->lock);

1122 1123 1124 1125 1126 1127
	hidg->func.name    = "hid";
	hidg->func.bind    = hidg_bind;
	hidg->func.unbind  = hidg_unbind;
	hidg->func.set_alt = hidg_set_alt;
	hidg->func.disable = hidg_disable;
	hidg->func.setup   = hidg_setup;
1128
	hidg->func.free_func = hidg_free;
1129

1130 1131 1132
	/* this could me made configurable at some point */
	hidg->qlen	   = 4;

1133
	return &hidg->func;
1134 1135
}

1136 1137 1138 1139 1140
DECLARE_USB_FUNCTION_INIT(hid, hidg_alloc_inst, hidg_alloc);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Fabien Chouteau");

int ghid_setup(struct usb_gadget *g, int count)
1141 1142 1143 1144 1145
{
	int status;
	dev_t dev;

	hidg_class = class_create(THIS_MODULE, "hidg");
1146
	if (IS_ERR(hidg_class)) {
1147
		status = PTR_ERR(hidg_class);
1148
		hidg_class = NULL;
1149
		return status;
1150
	}
1151 1152

	status = alloc_chrdev_region(&dev, 0, count, "hidg");
1153 1154 1155 1156
	if (status) {
		class_destroy(hidg_class);
		hidg_class = NULL;
		return status;
1157 1158
	}

1159 1160 1161 1162
	major = MAJOR(dev);
	minors = count;

	return 0;
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
}

void ghid_cleanup(void)
{
	if (major) {
		unregister_chrdev_region(MKDEV(major, 0), minors);
		major = minors = 0;
	}

	class_destroy(hidg_class);
	hidg_class = NULL;
}