xref: /openbmc/linux/drivers/hid/usbhid/hid-core.c (revision b8d312aa)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  USB HID support for Linux
4  *
5  *  Copyright (c) 1999 Andreas Gal
6  *  Copyright (c) 2000-2005 Vojtech Pavlik <vojtech@suse.cz>
7  *  Copyright (c) 2005 Michael Haboustak <mike-@cinci.rr.com> for Concept2, Inc
8  *  Copyright (c) 2007-2008 Oliver Neukum
9  *  Copyright (c) 2006-2010 Jiri Kosina
10  */
11 
12 /*
13  */
14 
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/init.h>
18 #include <linux/kernel.h>
19 #include <linux/list.h>
20 #include <linux/mm.h>
21 #include <linux/mutex.h>
22 #include <linux/spinlock.h>
23 #include <asm/unaligned.h>
24 #include <asm/byteorder.h>
25 #include <linux/input.h>
26 #include <linux/wait.h>
27 #include <linux/workqueue.h>
28 #include <linux/string.h>
29 
30 #include <linux/usb.h>
31 
32 #include <linux/hid.h>
33 #include <linux/hiddev.h>
34 #include <linux/hid-debug.h>
35 #include <linux/hidraw.h>
36 #include "usbhid.h"
37 
38 /*
39  * Version Information
40  */
41 
42 #define DRIVER_DESC "USB HID core driver"
43 
44 /*
45  * Module parameters.
46  */
47 
48 static unsigned int hid_mousepoll_interval;
49 module_param_named(mousepoll, hid_mousepoll_interval, uint, 0644);
50 MODULE_PARM_DESC(mousepoll, "Polling interval of mice");
51 
52 static unsigned int hid_jspoll_interval;
53 module_param_named(jspoll, hid_jspoll_interval, uint, 0644);
54 MODULE_PARM_DESC(jspoll, "Polling interval of joysticks");
55 
56 static unsigned int hid_kbpoll_interval;
57 module_param_named(kbpoll, hid_kbpoll_interval, uint, 0644);
58 MODULE_PARM_DESC(kbpoll, "Polling interval of keyboards");
59 
60 static unsigned int ignoreled;
61 module_param_named(ignoreled, ignoreled, uint, 0644);
62 MODULE_PARM_DESC(ignoreled, "Autosuspend with active leds");
63 
64 /* Quirks specified at module load time */
65 static char *quirks_param[MAX_USBHID_BOOT_QUIRKS];
66 module_param_array_named(quirks, quirks_param, charp, NULL, 0444);
67 MODULE_PARM_DESC(quirks, "Add/modify USB HID quirks by specifying "
68 		" quirks=vendorID:productID:quirks"
69 		" where vendorID, productID, and quirks are all in"
70 		" 0x-prefixed hex");
71 /*
72  * Input submission and I/O error handler.
73  */
74 static void hid_io_error(struct hid_device *hid);
75 static int hid_submit_out(struct hid_device *hid);
76 static int hid_submit_ctrl(struct hid_device *hid);
77 static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid);
78 
79 /* Start up the input URB */
80 static int hid_start_in(struct hid_device *hid)
81 {
82 	unsigned long flags;
83 	int rc = 0;
84 	struct usbhid_device *usbhid = hid->driver_data;
85 
86 	spin_lock_irqsave(&usbhid->lock, flags);
87 	if (test_bit(HID_IN_POLLING, &usbhid->iofl) &&
88 	    !test_bit(HID_DISCONNECTED, &usbhid->iofl) &&
89 	    !test_bit(HID_SUSPENDED, &usbhid->iofl) &&
90 	    !test_and_set_bit(HID_IN_RUNNING, &usbhid->iofl)) {
91 		rc = usb_submit_urb(usbhid->urbin, GFP_ATOMIC);
92 		if (rc != 0) {
93 			clear_bit(HID_IN_RUNNING, &usbhid->iofl);
94 			if (rc == -ENOSPC)
95 				set_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
96 		} else {
97 			clear_bit(HID_NO_BANDWIDTH, &usbhid->iofl);
98 		}
99 	}
100 	spin_unlock_irqrestore(&usbhid->lock, flags);
101 	return rc;
102 }
103 
104 /* I/O retry timer routine */
105 static void hid_retry_timeout(struct timer_list *t)
106 {
107 	struct usbhid_device *usbhid = from_timer(usbhid, t, io_retry);
108 	struct hid_device *hid = usbhid->hid;
109 
110 	dev_dbg(&usbhid->intf->dev, "retrying intr urb\n");
111 	if (hid_start_in(hid))
112 		hid_io_error(hid);
113 }
114 
115 /* Workqueue routine to reset the device or clear a halt */
116 static void hid_reset(struct work_struct *work)
117 {
118 	struct usbhid_device *usbhid =
119 		container_of(work, struct usbhid_device, reset_work);
120 	struct hid_device *hid = usbhid->hid;
121 	int rc;
122 
123 	if (test_bit(HID_CLEAR_HALT, &usbhid->iofl)) {
124 		dev_dbg(&usbhid->intf->dev, "clear halt\n");
125 		rc = usb_clear_halt(hid_to_usb_dev(hid), usbhid->urbin->pipe);
126 		clear_bit(HID_CLEAR_HALT, &usbhid->iofl);
127 		if (rc == 0) {
128 			hid_start_in(hid);
129 		} else {
130 			dev_dbg(&usbhid->intf->dev,
131 					"clear-halt failed: %d\n", rc);
132 			set_bit(HID_RESET_PENDING, &usbhid->iofl);
133 		}
134 	}
135 
136 	if (test_bit(HID_RESET_PENDING, &usbhid->iofl)) {
137 		dev_dbg(&usbhid->intf->dev, "resetting device\n");
138 		usb_queue_reset_device(usbhid->intf);
139 	}
140 }
141 
142 /* Main I/O error handler */
143 static void hid_io_error(struct hid_device *hid)
144 {
145 	unsigned long flags;
146 	struct usbhid_device *usbhid = hid->driver_data;
147 
148 	spin_lock_irqsave(&usbhid->lock, flags);
149 
150 	/* Stop when disconnected */
151 	if (test_bit(HID_DISCONNECTED, &usbhid->iofl))
152 		goto done;
153 
154 	/* If it has been a while since the last error, we'll assume
155 	 * this a brand new error and reset the retry timeout. */
156 	if (time_after(jiffies, usbhid->stop_retry + HZ/2))
157 		usbhid->retry_delay = 0;
158 
159 	/* When an error occurs, retry at increasing intervals */
160 	if (usbhid->retry_delay == 0) {
161 		usbhid->retry_delay = 13;	/* Then 26, 52, 104, 104, ... */
162 		usbhid->stop_retry = jiffies + msecs_to_jiffies(1000);
163 	} else if (usbhid->retry_delay < 100)
164 		usbhid->retry_delay *= 2;
165 
166 	if (time_after(jiffies, usbhid->stop_retry)) {
167 
168 		/* Retries failed, so do a port reset unless we lack bandwidth*/
169 		if (!test_bit(HID_NO_BANDWIDTH, &usbhid->iofl)
170 		     && !test_and_set_bit(HID_RESET_PENDING, &usbhid->iofl)) {
171 
172 			schedule_work(&usbhid->reset_work);
173 			goto done;
174 		}
175 	}
176 
177 	mod_timer(&usbhid->io_retry,
178 			jiffies + msecs_to_jiffies(usbhid->retry_delay));
179 done:
180 	spin_unlock_irqrestore(&usbhid->lock, flags);
181 }
182 
183 static void usbhid_mark_busy(struct usbhid_device *usbhid)
184 {
185 	struct usb_interface *intf = usbhid->intf;
186 
187 	usb_mark_last_busy(interface_to_usbdev(intf));
188 }
189 
190 static int usbhid_restart_out_queue(struct usbhid_device *usbhid)
191 {
192 	struct hid_device *hid = usb_get_intfdata(usbhid->intf);
193 	int kicked;
194 	int r;
195 
196 	if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
197 			test_bit(HID_SUSPENDED, &usbhid->iofl))
198 		return 0;
199 
200 	if ((kicked = (usbhid->outhead != usbhid->outtail))) {
201 		hid_dbg(hid, "Kicking head %d tail %d", usbhid->outhead, usbhid->outtail);
202 
203 		/* Try to wake up from autosuspend... */
204 		r = usb_autopm_get_interface_async(usbhid->intf);
205 		if (r < 0)
206 			return r;
207 
208 		/*
209 		 * If still suspended, don't submit.  Submission will
210 		 * occur if/when resume drains the queue.
211 		 */
212 		if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
213 			usb_autopm_put_interface_no_suspend(usbhid->intf);
214 			return r;
215 		}
216 
217 		/* Asynchronously flush queue. */
218 		set_bit(HID_OUT_RUNNING, &usbhid->iofl);
219 		if (hid_submit_out(hid)) {
220 			clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
221 			usb_autopm_put_interface_async(usbhid->intf);
222 		}
223 		wake_up(&usbhid->wait);
224 	}
225 	return kicked;
226 }
227 
228 static int usbhid_restart_ctrl_queue(struct usbhid_device *usbhid)
229 {
230 	struct hid_device *hid = usb_get_intfdata(usbhid->intf);
231 	int kicked;
232 	int r;
233 
234 	WARN_ON(hid == NULL);
235 	if (!hid || test_bit(HID_RESET_PENDING, &usbhid->iofl) ||
236 			test_bit(HID_SUSPENDED, &usbhid->iofl))
237 		return 0;
238 
239 	if ((kicked = (usbhid->ctrlhead != usbhid->ctrltail))) {
240 		hid_dbg(hid, "Kicking head %d tail %d", usbhid->ctrlhead, usbhid->ctrltail);
241 
242 		/* Try to wake up from autosuspend... */
243 		r = usb_autopm_get_interface_async(usbhid->intf);
244 		if (r < 0)
245 			return r;
246 
247 		/*
248 		 * If still suspended, don't submit.  Submission will
249 		 * occur if/when resume drains the queue.
250 		 */
251 		if (test_bit(HID_SUSPENDED, &usbhid->iofl)) {
252 			usb_autopm_put_interface_no_suspend(usbhid->intf);
253 			return r;
254 		}
255 
256 		/* Asynchronously flush queue. */
257 		set_bit(HID_CTRL_RUNNING, &usbhid->iofl);
258 		if (hid_submit_ctrl(hid)) {
259 			clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
260 			usb_autopm_put_interface_async(usbhid->intf);
261 		}
262 		wake_up(&usbhid->wait);
263 	}
264 	return kicked;
265 }
266 
267 /*
268  * Input interrupt completion handler.
269  */
270 
271 static void hid_irq_in(struct urb *urb)
272 {
273 	struct hid_device	*hid = urb->context;
274 	struct usbhid_device	*usbhid = hid->driver_data;
275 	int			status;
276 
277 	switch (urb->status) {
278 	case 0:			/* success */
279 		usbhid->retry_delay = 0;
280 		if (!test_bit(HID_OPENED, &usbhid->iofl))
281 			break;
282 		usbhid_mark_busy(usbhid);
283 		if (!test_bit(HID_RESUME_RUNNING, &usbhid->iofl)) {
284 			hid_input_report(urb->context, HID_INPUT_REPORT,
285 					 urb->transfer_buffer,
286 					 urb->actual_length, 1);
287 			/*
288 			 * autosuspend refused while keys are pressed
289 			 * because most keyboards don't wake up when
290 			 * a key is released
291 			 */
292 			if (hid_check_keys_pressed(hid))
293 				set_bit(HID_KEYS_PRESSED, &usbhid->iofl);
294 			else
295 				clear_bit(HID_KEYS_PRESSED, &usbhid->iofl);
296 		}
297 		break;
298 	case -EPIPE:		/* stall */
299 		usbhid_mark_busy(usbhid);
300 		clear_bit(HID_IN_RUNNING, &usbhid->iofl);
301 		set_bit(HID_CLEAR_HALT, &usbhid->iofl);
302 		schedule_work(&usbhid->reset_work);
303 		return;
304 	case -ECONNRESET:	/* unlink */
305 	case -ENOENT:
306 	case -ESHUTDOWN:	/* unplug */
307 		clear_bit(HID_IN_RUNNING, &usbhid->iofl);
308 		return;
309 	case -EILSEQ:		/* protocol error or unplug */
310 	case -EPROTO:		/* protocol error or unplug */
311 	case -ETIME:		/* protocol error or unplug */
312 	case -ETIMEDOUT:	/* Should never happen, but... */
313 		usbhid_mark_busy(usbhid);
314 		clear_bit(HID_IN_RUNNING, &usbhid->iofl);
315 		hid_io_error(hid);
316 		return;
317 	default:		/* error */
318 		hid_warn(urb->dev, "input irq status %d received\n",
319 			 urb->status);
320 	}
321 
322 	status = usb_submit_urb(urb, GFP_ATOMIC);
323 	if (status) {
324 		clear_bit(HID_IN_RUNNING, &usbhid->iofl);
325 		if (status != -EPERM) {
326 			hid_err(hid, "can't resubmit intr, %s-%s/input%d, status %d\n",
327 				hid_to_usb_dev(hid)->bus->bus_name,
328 				hid_to_usb_dev(hid)->devpath,
329 				usbhid->ifnum, status);
330 			hid_io_error(hid);
331 		}
332 	}
333 }
334 
335 static int hid_submit_out(struct hid_device *hid)
336 {
337 	struct hid_report *report;
338 	char *raw_report;
339 	struct usbhid_device *usbhid = hid->driver_data;
340 	int r;
341 
342 	report = usbhid->out[usbhid->outtail].report;
343 	raw_report = usbhid->out[usbhid->outtail].raw_report;
344 
345 	usbhid->urbout->transfer_buffer_length = hid_report_len(report);
346 	usbhid->urbout->dev = hid_to_usb_dev(hid);
347 	if (raw_report) {
348 		memcpy(usbhid->outbuf, raw_report,
349 				usbhid->urbout->transfer_buffer_length);
350 		kfree(raw_report);
351 		usbhid->out[usbhid->outtail].raw_report = NULL;
352 	}
353 
354 	dbg_hid("submitting out urb\n");
355 
356 	r = usb_submit_urb(usbhid->urbout, GFP_ATOMIC);
357 	if (r < 0) {
358 		hid_err(hid, "usb_submit_urb(out) failed: %d\n", r);
359 		return r;
360 	}
361 	usbhid->last_out = jiffies;
362 	return 0;
363 }
364 
365 static int hid_submit_ctrl(struct hid_device *hid)
366 {
367 	struct hid_report *report;
368 	unsigned char dir;
369 	char *raw_report;
370 	int len, r;
371 	struct usbhid_device *usbhid = hid->driver_data;
372 
373 	report = usbhid->ctrl[usbhid->ctrltail].report;
374 	raw_report = usbhid->ctrl[usbhid->ctrltail].raw_report;
375 	dir = usbhid->ctrl[usbhid->ctrltail].dir;
376 
377 	len = ((report->size - 1) >> 3) + 1 + (report->id > 0);
378 	if (dir == USB_DIR_OUT) {
379 		usbhid->urbctrl->pipe = usb_sndctrlpipe(hid_to_usb_dev(hid), 0);
380 		usbhid->urbctrl->transfer_buffer_length = len;
381 		if (raw_report) {
382 			memcpy(usbhid->ctrlbuf, raw_report, len);
383 			kfree(raw_report);
384 			usbhid->ctrl[usbhid->ctrltail].raw_report = NULL;
385 		}
386 	} else {
387 		int maxpacket, padlen;
388 
389 		usbhid->urbctrl->pipe = usb_rcvctrlpipe(hid_to_usb_dev(hid), 0);
390 		maxpacket = usb_maxpacket(hid_to_usb_dev(hid),
391 					  usbhid->urbctrl->pipe, 0);
392 		if (maxpacket > 0) {
393 			padlen = DIV_ROUND_UP(len, maxpacket);
394 			padlen *= maxpacket;
395 			if (padlen > usbhid->bufsize)
396 				padlen = usbhid->bufsize;
397 		} else
398 			padlen = 0;
399 		usbhid->urbctrl->transfer_buffer_length = padlen;
400 	}
401 	usbhid->urbctrl->dev = hid_to_usb_dev(hid);
402 
403 	usbhid->cr->bRequestType = USB_TYPE_CLASS | USB_RECIP_INTERFACE | dir;
404 	usbhid->cr->bRequest = (dir == USB_DIR_OUT) ? HID_REQ_SET_REPORT :
405 						      HID_REQ_GET_REPORT;
406 	usbhid->cr->wValue = cpu_to_le16(((report->type + 1) << 8) |
407 					 report->id);
408 	usbhid->cr->wIndex = cpu_to_le16(usbhid->ifnum);
409 	usbhid->cr->wLength = cpu_to_le16(len);
410 
411 	dbg_hid("submitting ctrl urb: %s wValue=0x%04x wIndex=0x%04x wLength=%u\n",
412 		usbhid->cr->bRequest == HID_REQ_SET_REPORT ? "Set_Report" :
413 							     "Get_Report",
414 		usbhid->cr->wValue, usbhid->cr->wIndex, usbhid->cr->wLength);
415 
416 	r = usb_submit_urb(usbhid->urbctrl, GFP_ATOMIC);
417 	if (r < 0) {
418 		hid_err(hid, "usb_submit_urb(ctrl) failed: %d\n", r);
419 		return r;
420 	}
421 	usbhid->last_ctrl = jiffies;
422 	return 0;
423 }
424 
425 /*
426  * Output interrupt completion handler.
427  */
428 
429 static void hid_irq_out(struct urb *urb)
430 {
431 	struct hid_device *hid = urb->context;
432 	struct usbhid_device *usbhid = hid->driver_data;
433 	unsigned long flags;
434 	int unplug = 0;
435 
436 	switch (urb->status) {
437 	case 0:			/* success */
438 		break;
439 	case -ESHUTDOWN:	/* unplug */
440 		unplug = 1;
441 	case -EILSEQ:		/* protocol error or unplug */
442 	case -EPROTO:		/* protocol error or unplug */
443 	case -ECONNRESET:	/* unlink */
444 	case -ENOENT:
445 		break;
446 	default:		/* error */
447 		hid_warn(urb->dev, "output irq status %d received\n",
448 			 urb->status);
449 	}
450 
451 	spin_lock_irqsave(&usbhid->lock, flags);
452 
453 	if (unplug) {
454 		usbhid->outtail = usbhid->outhead;
455 	} else {
456 		usbhid->outtail = (usbhid->outtail + 1) & (HID_OUTPUT_FIFO_SIZE - 1);
457 
458 		if (usbhid->outhead != usbhid->outtail &&
459 				hid_submit_out(hid) == 0) {
460 			/* Successfully submitted next urb in queue */
461 			spin_unlock_irqrestore(&usbhid->lock, flags);
462 			return;
463 		}
464 	}
465 
466 	clear_bit(HID_OUT_RUNNING, &usbhid->iofl);
467 	spin_unlock_irqrestore(&usbhid->lock, flags);
468 	usb_autopm_put_interface_async(usbhid->intf);
469 	wake_up(&usbhid->wait);
470 }
471 
472 /*
473  * Control pipe completion handler.
474  */
475 
476 static void hid_ctrl(struct urb *urb)
477 {
478 	struct hid_device *hid = urb->context;
479 	struct usbhid_device *usbhid = hid->driver_data;
480 	unsigned long flags;
481 	int unplug = 0, status = urb->status;
482 
483 	switch (status) {
484 	case 0:			/* success */
485 		if (usbhid->ctrl[usbhid->ctrltail].dir == USB_DIR_IN)
486 			hid_input_report(urb->context,
487 				usbhid->ctrl[usbhid->ctrltail].report->type,
488 				urb->transfer_buffer, urb->actual_length, 0);
489 		break;
490 	case -ESHUTDOWN:	/* unplug */
491 		unplug = 1;
492 	case -EILSEQ:		/* protocol error or unplug */
493 	case -EPROTO:		/* protocol error or unplug */
494 	case -ECONNRESET:	/* unlink */
495 	case -ENOENT:
496 	case -EPIPE:		/* report not available */
497 		break;
498 	default:		/* error */
499 		hid_warn(urb->dev, "ctrl urb status %d received\n", status);
500 	}
501 
502 	spin_lock_irqsave(&usbhid->lock, flags);
503 
504 	if (unplug) {
505 		usbhid->ctrltail = usbhid->ctrlhead;
506 	} else {
507 		usbhid->ctrltail = (usbhid->ctrltail + 1) & (HID_CONTROL_FIFO_SIZE - 1);
508 
509 		if (usbhid->ctrlhead != usbhid->ctrltail &&
510 				hid_submit_ctrl(hid) == 0) {
511 			/* Successfully submitted next urb in queue */
512 			spin_unlock_irqrestore(&usbhid->lock, flags);
513 			return;
514 		}
515 	}
516 
517 	clear_bit(HID_CTRL_RUNNING, &usbhid->iofl);
518 	spin_unlock_irqrestore(&usbhid->lock, flags);
519 	usb_autopm_put_interface_async(usbhid->intf);
520 	wake_up(&usbhid->wait);
521 }
522 
523 static void __usbhid_submit_report(struct hid_device *hid, struct hid_report *report,
524 				   unsigned char dir)
525 {
526 	int head;
527 	struct usbhid_device *usbhid = hid->driver_data;
528 
529 	if (((hid->quirks & HID_QUIRK_NOGET) && dir == USB_DIR_IN) ||
530 		test_bit(HID_DISCONNECTED, &usbhid->iofl))
531 		return;
532 
533 	if (usbhid->urbout && dir == USB_DIR_OUT && report->type == HID_OUTPUT_REPORT) {
534 		if ((head = (usbhid->outhead + 1) & (HID_OUTPUT_FIFO_SIZE - 1)) == usbhid->outtail) {
535 			hid_warn(hid, "output queue full\n");
536 			return;
537 		}
538 
539 		usbhid->out[usbhid->outhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
540 		if (!usbhid->out[usbhid->outhead].raw_report) {
541 			hid_warn(hid, "output queueing failed\n");
542 			return;
543 		}
544 		hid_output_report(report, usbhid->out[usbhid->outhead].raw_report);
545 		usbhid->out[usbhid->outhead].report = report;
546 		usbhid->outhead = head;
547 
548 		/* If the queue isn't running, restart it */
549 		if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl)) {
550 			usbhid_restart_out_queue(usbhid);
551 
552 		/* Otherwise see if an earlier request has timed out */
553 		} else if (time_after(jiffies, usbhid->last_out + HZ * 5)) {
554 
555 			/* Prevent autosuspend following the unlink */
556 			usb_autopm_get_interface_no_resume(usbhid->intf);
557 
558 			/*
559 			 * Prevent resubmission in case the URB completes
560 			 * before we can unlink it.  We don't want to cancel
561 			 * the wrong transfer!
562 			 */
563 			usb_block_urb(usbhid->urbout);
564 
565 			/* Drop lock to avoid deadlock if the callback runs */
566 			spin_unlock(&usbhid->lock);
567 
568 			usb_unlink_urb(usbhid->urbout);
569 			spin_lock(&usbhid->lock);
570 			usb_unblock_urb(usbhid->urbout);
571 
572 			/* Unlink might have stopped the queue */
573 			if (!test_bit(HID_OUT_RUNNING, &usbhid->iofl))
574 				usbhid_restart_out_queue(usbhid);
575 
576 			/* Now we can allow autosuspend again */
577 			usb_autopm_put_interface_async(usbhid->intf);
578 		}
579 		return;
580 	}
581 
582 	if ((head = (usbhid->ctrlhead + 1) & (HID_CONTROL_FIFO_SIZE - 1)) == usbhid->ctrltail) {
583 		hid_warn(hid, "control queue full\n");
584 		return;
585 	}
586 
587 	if (dir == USB_DIR_OUT) {
588 		usbhid->ctrl[usbhid->ctrlhead].raw_report = hid_alloc_report_buf(report, GFP_ATOMIC);
589 		if (!usbhid->ctrl[usbhid->ctrlhead].raw_report) {
590 			hid_warn(hid, "control queueing failed\n");
591 			return;
592 		}
593 		hid_output_report(report, usbhid->ctrl[usbhid->ctrlhead].raw_report);
594 	}
595 	usbhid->ctrl[usbhid->ctrlhead].report = report;
596 	usbhid->ctrl[usbhid->ctrlhead].dir = dir;
597 	usbhid->ctrlhead = head;
598 
599 	/* If the queue isn't running, restart it */
600 	if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl)) {
601 		usbhid_restart_ctrl_queue(usbhid);
602 
603 	/* Otherwise see if an earlier request has timed out */
604 	} else if (time_after(jiffies, usbhid->last_ctrl + HZ * 5)) {
605 
606 		/* Prevent autosuspend following the unlink */
607 		usb_autopm_get_interface_no_resume(usbhid->intf);
608 
609 		/*
610 		 * Prevent resubmission in case the URB completes
611 		 * before we can unlink it.  We don't want to cancel
612 		 * the wrong transfer!
613 		 */
614 		usb_block_urb(usbhid->urbctrl);
615 
616 		/* Drop lock to avoid deadlock if the callback runs */
617 		spin_unlock(&usbhid->lock);
618 
619 		usb_unlink_urb(usbhid->urbctrl);
620 		spin_lock(&usbhid->lock);
621 		usb_unblock_urb(usbhid->urbctrl);
622 
623 		/* Unlink might have stopped the queue */
624 		if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
625 			usbhid_restart_ctrl_queue(usbhid);
626 
627 		/* Now we can allow autosuspend again */
628 		usb_autopm_put_interface_async(usbhid->intf);
629 	}
630 }
631 
632 static void usbhid_submit_report(struct hid_device *hid, struct hid_report *report, unsigned char dir)
633 {
634 	struct usbhid_device *usbhid = hid->driver_data;
635 	unsigned long flags;
636 
637 	spin_lock_irqsave(&usbhid->lock, flags);
638 	__usbhid_submit_report(hid, report, dir);
639 	spin_unlock_irqrestore(&usbhid->lock, flags);
640 }
641 
642 static int usbhid_wait_io(struct hid_device *hid)
643 {
644 	struct usbhid_device *usbhid = hid->driver_data;
645 
646 	if (!wait_event_timeout(usbhid->wait,
647 				(!test_bit(HID_CTRL_RUNNING, &usbhid->iofl) &&
648 				!test_bit(HID_OUT_RUNNING, &usbhid->iofl)),
649 					10*HZ)) {
650 		dbg_hid("timeout waiting for ctrl or out queue to clear\n");
651 		return -1;
652 	}
653 
654 	return 0;
655 }
656 
657 static int hid_set_idle(struct usb_device *dev, int ifnum, int report, int idle)
658 {
659 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
660 		HID_REQ_SET_IDLE, USB_TYPE_CLASS | USB_RECIP_INTERFACE, (idle << 8) | report,
661 		ifnum, NULL, 0, USB_CTRL_SET_TIMEOUT);
662 }
663 
664 static int hid_get_class_descriptor(struct usb_device *dev, int ifnum,
665 		unsigned char type, void *buf, int size)
666 {
667 	int result, retries = 4;
668 
669 	memset(buf, 0, size);
670 
671 	do {
672 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
673 				USB_REQ_GET_DESCRIPTOR, USB_RECIP_INTERFACE | USB_DIR_IN,
674 				(type << 8), ifnum, buf, size, USB_CTRL_GET_TIMEOUT);
675 		retries--;
676 	} while (result < size && retries);
677 	return result;
678 }
679 
680 static int usbhid_open(struct hid_device *hid)
681 {
682 	struct usbhid_device *usbhid = hid->driver_data;
683 	int res;
684 
685 	set_bit(HID_OPENED, &usbhid->iofl);
686 
687 	if (hid->quirks & HID_QUIRK_ALWAYS_POLL)
688 		return 0;
689 
690 	res = usb_autopm_get_interface(usbhid->intf);
691 	/* the device must be awake to reliably request remote wakeup */
692 	if (res < 0) {
693 		clear_bit(HID_OPENED, &usbhid->iofl);
694 		return -EIO;
695 	}
696 
697 	usbhid->intf->needs_remote_wakeup = 1;
698 
699 	set_bit(HID_RESUME_RUNNING, &usbhid->iofl);
700 	set_bit(HID_IN_POLLING, &usbhid->iofl);
701 
702 	res = hid_start_in(hid);
703 	if (res) {
704 		if (res != -ENOSPC) {
705 			hid_io_error(hid);
706 			res = 0;
707 		} else {
708 			/* no use opening if resources are insufficient */
709 			res = -EBUSY;
710 			clear_bit(HID_OPENED, &usbhid->iofl);
711 			clear_bit(HID_IN_POLLING, &usbhid->iofl);
712 			usbhid->intf->needs_remote_wakeup = 0;
713 		}
714 	}
715 
716 	usb_autopm_put_interface(usbhid->intf);
717 
718 	/*
719 	 * In case events are generated while nobody was listening,
720 	 * some are released when the device is re-opened.
721 	 * Wait 50 msec for the queue to empty before allowing events
722 	 * to go through hid.
723 	 */
724 	if (res == 0)
725 		msleep(50);
726 
727 	clear_bit(HID_RESUME_RUNNING, &usbhid->iofl);
728 	return res;
729 }
730 
731 static void usbhid_close(struct hid_device *hid)
732 {
733 	struct usbhid_device *usbhid = hid->driver_data;
734 
735 	/*
736 	 * Make sure we don't restart data acquisition due to
737 	 * a resumption we no longer care about by avoiding racing
738 	 * with hid_start_in().
739 	 */
740 	spin_lock_irq(&usbhid->lock);
741 	clear_bit(HID_OPENED, &usbhid->iofl);
742 	if (!(hid->quirks & HID_QUIRK_ALWAYS_POLL))
743 		clear_bit(HID_IN_POLLING, &usbhid->iofl);
744 	spin_unlock_irq(&usbhid->lock);
745 
746 	if (hid->quirks & HID_QUIRK_ALWAYS_POLL)
747 		return;
748 
749 	hid_cancel_delayed_stuff(usbhid);
750 	usb_kill_urb(usbhid->urbin);
751 	usbhid->intf->needs_remote_wakeup = 0;
752 }
753 
754 /*
755  * Initialize all reports
756  */
757 
758 void usbhid_init_reports(struct hid_device *hid)
759 {
760 	struct hid_report *report;
761 	struct usbhid_device *usbhid = hid->driver_data;
762 	struct hid_report_enum *report_enum;
763 	int err, ret;
764 
765 	report_enum = &hid->report_enum[HID_INPUT_REPORT];
766 	list_for_each_entry(report, &report_enum->report_list, list)
767 		usbhid_submit_report(hid, report, USB_DIR_IN);
768 
769 	report_enum = &hid->report_enum[HID_FEATURE_REPORT];
770 	list_for_each_entry(report, &report_enum->report_list, list)
771 		usbhid_submit_report(hid, report, USB_DIR_IN);
772 
773 	err = 0;
774 	ret = usbhid_wait_io(hid);
775 	while (ret) {
776 		err |= ret;
777 		if (test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
778 			usb_kill_urb(usbhid->urbctrl);
779 		if (test_bit(HID_OUT_RUNNING, &usbhid->iofl))
780 			usb_kill_urb(usbhid->urbout);
781 		ret = usbhid_wait_io(hid);
782 	}
783 
784 	if (err)
785 		hid_warn(hid, "timeout initializing reports\n");
786 }
787 
788 /*
789  * Reset LEDs which BIOS might have left on. For now, just NumLock (0x01).
790  */
791 static int hid_find_field_early(struct hid_device *hid, unsigned int page,
792     unsigned int hid_code, struct hid_field **pfield)
793 {
794 	struct hid_report *report;
795 	struct hid_field *field;
796 	struct hid_usage *usage;
797 	int i, j;
798 
799 	list_for_each_entry(report, &hid->report_enum[HID_OUTPUT_REPORT].report_list, list) {
800 		for (i = 0; i < report->maxfield; i++) {
801 			field = report->field[i];
802 			for (j = 0; j < field->maxusage; j++) {
803 				usage = &field->usage[j];
804 				if ((usage->hid & HID_USAGE_PAGE) == page &&
805 				    (usage->hid & 0xFFFF) == hid_code) {
806 					*pfield = field;
807 					return j;
808 				}
809 			}
810 		}
811 	}
812 	return -1;
813 }
814 
815 static void usbhid_set_leds(struct hid_device *hid)
816 {
817 	struct hid_field *field;
818 	int offset;
819 
820 	if ((offset = hid_find_field_early(hid, HID_UP_LED, 0x01, &field)) != -1) {
821 		hid_set_field(field, offset, 0);
822 		usbhid_submit_report(hid, field->report, USB_DIR_OUT);
823 	}
824 }
825 
826 /*
827  * Traverse the supplied list of reports and find the longest
828  */
829 static void hid_find_max_report(struct hid_device *hid, unsigned int type,
830 		unsigned int *max)
831 {
832 	struct hid_report *report;
833 	unsigned int size;
834 
835 	list_for_each_entry(report, &hid->report_enum[type].report_list, list) {
836 		size = ((report->size - 1) >> 3) + 1 + hid->report_enum[type].numbered;
837 		if (*max < size)
838 			*max = size;
839 	}
840 }
841 
842 static int hid_alloc_buffers(struct usb_device *dev, struct hid_device *hid)
843 {
844 	struct usbhid_device *usbhid = hid->driver_data;
845 
846 	usbhid->inbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
847 			&usbhid->inbuf_dma);
848 	usbhid->outbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
849 			&usbhid->outbuf_dma);
850 	usbhid->cr = kmalloc(sizeof(*usbhid->cr), GFP_KERNEL);
851 	usbhid->ctrlbuf = usb_alloc_coherent(dev, usbhid->bufsize, GFP_KERNEL,
852 			&usbhid->ctrlbuf_dma);
853 	if (!usbhid->inbuf || !usbhid->outbuf || !usbhid->cr ||
854 			!usbhid->ctrlbuf)
855 		return -1;
856 
857 	return 0;
858 }
859 
860 static int usbhid_get_raw_report(struct hid_device *hid,
861 		unsigned char report_number, __u8 *buf, size_t count,
862 		unsigned char report_type)
863 {
864 	struct usbhid_device *usbhid = hid->driver_data;
865 	struct usb_device *dev = hid_to_usb_dev(hid);
866 	struct usb_interface *intf = usbhid->intf;
867 	struct usb_host_interface *interface = intf->cur_altsetting;
868 	int skipped_report_id = 0;
869 	int ret;
870 
871 	/* Byte 0 is the report number. Report data starts at byte 1.*/
872 	buf[0] = report_number;
873 	if (report_number == 0x0) {
874 		/* Offset the return buffer by 1, so that the report ID
875 		   will remain in byte 0. */
876 		buf++;
877 		count--;
878 		skipped_report_id = 1;
879 	}
880 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
881 		HID_REQ_GET_REPORT,
882 		USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
883 		((report_type + 1) << 8) | report_number,
884 		interface->desc.bInterfaceNumber, buf, count,
885 		USB_CTRL_SET_TIMEOUT);
886 
887 	/* count also the report id */
888 	if (ret > 0 && skipped_report_id)
889 		ret++;
890 
891 	return ret;
892 }
893 
894 static int usbhid_set_raw_report(struct hid_device *hid, unsigned int reportnum,
895 				 __u8 *buf, size_t count, unsigned char rtype)
896 {
897 	struct usbhid_device *usbhid = hid->driver_data;
898 	struct usb_device *dev = hid_to_usb_dev(hid);
899 	struct usb_interface *intf = usbhid->intf;
900 	struct usb_host_interface *interface = intf->cur_altsetting;
901 	int ret, skipped_report_id = 0;
902 
903 	/* Byte 0 is the report number. Report data starts at byte 1.*/
904 	if ((rtype == HID_OUTPUT_REPORT) &&
905 	    (hid->quirks & HID_QUIRK_SKIP_OUTPUT_REPORT_ID))
906 		buf[0] = 0;
907 	else
908 		buf[0] = reportnum;
909 
910 	if (buf[0] == 0x0) {
911 		/* Don't send the Report ID */
912 		buf++;
913 		count--;
914 		skipped_report_id = 1;
915 	}
916 
917 	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
918 			HID_REQ_SET_REPORT,
919 			USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
920 			((rtype + 1) << 8) | reportnum,
921 			interface->desc.bInterfaceNumber, buf, count,
922 			USB_CTRL_SET_TIMEOUT);
923 	/* count also the report id, if this was a numbered report. */
924 	if (ret > 0 && skipped_report_id)
925 		ret++;
926 
927 	return ret;
928 }
929 
930 static int usbhid_output_report(struct hid_device *hid, __u8 *buf, size_t count)
931 {
932 	struct usbhid_device *usbhid = hid->driver_data;
933 	struct usb_device *dev = hid_to_usb_dev(hid);
934 	int actual_length, skipped_report_id = 0, ret;
935 
936 	if (!usbhid->urbout)
937 		return -ENOSYS;
938 
939 	if (buf[0] == 0x0) {
940 		/* Don't send the Report ID */
941 		buf++;
942 		count--;
943 		skipped_report_id = 1;
944 	}
945 
946 	ret = usb_interrupt_msg(dev, usbhid->urbout->pipe,
947 				buf, count, &actual_length,
948 				USB_CTRL_SET_TIMEOUT);
949 	/* return the number of bytes transferred */
950 	if (ret == 0) {
951 		ret = actual_length;
952 		/* count also the report id */
953 		if (skipped_report_id)
954 			ret++;
955 	}
956 
957 	return ret;
958 }
959 
960 static void hid_free_buffers(struct usb_device *dev, struct hid_device *hid)
961 {
962 	struct usbhid_device *usbhid = hid->driver_data;
963 
964 	usb_free_coherent(dev, usbhid->bufsize, usbhid->inbuf, usbhid->inbuf_dma);
965 	usb_free_coherent(dev, usbhid->bufsize, usbhid->outbuf, usbhid->outbuf_dma);
966 	kfree(usbhid->cr);
967 	usb_free_coherent(dev, usbhid->bufsize, usbhid->ctrlbuf, usbhid->ctrlbuf_dma);
968 }
969 
970 static int usbhid_parse(struct hid_device *hid)
971 {
972 	struct usb_interface *intf = to_usb_interface(hid->dev.parent);
973 	struct usb_host_interface *interface = intf->cur_altsetting;
974 	struct usb_device *dev = interface_to_usbdev (intf);
975 	struct hid_descriptor *hdesc;
976 	u32 quirks = 0;
977 	unsigned int rsize = 0;
978 	char *rdesc;
979 	int ret, n;
980 	int num_descriptors;
981 	size_t offset = offsetof(struct hid_descriptor, desc);
982 
983 	quirks = hid_lookup_quirk(hid);
984 
985 	if (quirks & HID_QUIRK_IGNORE)
986 		return -ENODEV;
987 
988 	/* Many keyboards and mice don't like to be polled for reports,
989 	 * so we will always set the HID_QUIRK_NOGET flag for them. */
990 	if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
991 		if (interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_KEYBOARD ||
992 			interface->desc.bInterfaceProtocol == USB_INTERFACE_PROTOCOL_MOUSE)
993 				quirks |= HID_QUIRK_NOGET;
994 	}
995 
996 	if (usb_get_extra_descriptor(interface, HID_DT_HID, &hdesc) &&
997 	    (!interface->desc.bNumEndpoints ||
998 	     usb_get_extra_descriptor(&interface->endpoint[0], HID_DT_HID, &hdesc))) {
999 		dbg_hid("class descriptor not present\n");
1000 		return -ENODEV;
1001 	}
1002 
1003 	if (hdesc->bLength < sizeof(struct hid_descriptor)) {
1004 		dbg_hid("hid descriptor is too short\n");
1005 		return -EINVAL;
1006 	}
1007 
1008 	hid->version = le16_to_cpu(hdesc->bcdHID);
1009 	hid->country = hdesc->bCountryCode;
1010 
1011 	num_descriptors = min_t(int, hdesc->bNumDescriptors,
1012 	       (hdesc->bLength - offset) / sizeof(struct hid_class_descriptor));
1013 
1014 	for (n = 0; n < num_descriptors; n++)
1015 		if (hdesc->desc[n].bDescriptorType == HID_DT_REPORT)
1016 			rsize = le16_to_cpu(hdesc->desc[n].wDescriptorLength);
1017 
1018 	if (!rsize || rsize > HID_MAX_DESCRIPTOR_SIZE) {
1019 		dbg_hid("weird size of report descriptor (%u)\n", rsize);
1020 		return -EINVAL;
1021 	}
1022 
1023 	rdesc = kmalloc(rsize, GFP_KERNEL);
1024 	if (!rdesc)
1025 		return -ENOMEM;
1026 
1027 	hid_set_idle(dev, interface->desc.bInterfaceNumber, 0, 0);
1028 
1029 	ret = hid_get_class_descriptor(dev, interface->desc.bInterfaceNumber,
1030 			HID_DT_REPORT, rdesc, rsize);
1031 	if (ret < 0) {
1032 		dbg_hid("reading report descriptor failed\n");
1033 		kfree(rdesc);
1034 		goto err;
1035 	}
1036 
1037 	ret = hid_parse_report(hid, rdesc, rsize);
1038 	kfree(rdesc);
1039 	if (ret) {
1040 		dbg_hid("parsing report descriptor failed\n");
1041 		goto err;
1042 	}
1043 
1044 	hid->quirks |= quirks;
1045 
1046 	return 0;
1047 err:
1048 	return ret;
1049 }
1050 
1051 static int usbhid_start(struct hid_device *hid)
1052 {
1053 	struct usb_interface *intf = to_usb_interface(hid->dev.parent);
1054 	struct usb_host_interface *interface = intf->cur_altsetting;
1055 	struct usb_device *dev = interface_to_usbdev(intf);
1056 	struct usbhid_device *usbhid = hid->driver_data;
1057 	unsigned int n, insize = 0;
1058 	int ret;
1059 
1060 	clear_bit(HID_DISCONNECTED, &usbhid->iofl);
1061 
1062 	usbhid->bufsize = HID_MIN_BUFFER_SIZE;
1063 	hid_find_max_report(hid, HID_INPUT_REPORT, &usbhid->bufsize);
1064 	hid_find_max_report(hid, HID_OUTPUT_REPORT, &usbhid->bufsize);
1065 	hid_find_max_report(hid, HID_FEATURE_REPORT, &usbhid->bufsize);
1066 
1067 	if (usbhid->bufsize > HID_MAX_BUFFER_SIZE)
1068 		usbhid->bufsize = HID_MAX_BUFFER_SIZE;
1069 
1070 	hid_find_max_report(hid, HID_INPUT_REPORT, &insize);
1071 
1072 	if (insize > HID_MAX_BUFFER_SIZE)
1073 		insize = HID_MAX_BUFFER_SIZE;
1074 
1075 	if (hid_alloc_buffers(dev, hid)) {
1076 		ret = -ENOMEM;
1077 		goto fail;
1078 	}
1079 
1080 	for (n = 0; n < interface->desc.bNumEndpoints; n++) {
1081 		struct usb_endpoint_descriptor *endpoint;
1082 		int pipe;
1083 		int interval;
1084 
1085 		endpoint = &interface->endpoint[n].desc;
1086 		if (!usb_endpoint_xfer_int(endpoint))
1087 			continue;
1088 
1089 		interval = endpoint->bInterval;
1090 
1091 		/* Some vendors give fullspeed interval on highspeed devides */
1092 		if (hid->quirks & HID_QUIRK_FULLSPEED_INTERVAL &&
1093 		    dev->speed == USB_SPEED_HIGH) {
1094 			interval = fls(endpoint->bInterval*8);
1095 			pr_info("%s: Fixing fullspeed to highspeed interval: %d -> %d\n",
1096 				hid->name, endpoint->bInterval, interval);
1097 		}
1098 
1099 		/* Change the polling interval of mice, joysticks
1100 		 * and keyboards.
1101 		 */
1102 		switch (hid->collection->usage) {
1103 		case HID_GD_MOUSE:
1104 			if (hid_mousepoll_interval > 0)
1105 				interval = hid_mousepoll_interval;
1106 			break;
1107 		case HID_GD_JOYSTICK:
1108 			if (hid_jspoll_interval > 0)
1109 				interval = hid_jspoll_interval;
1110 			break;
1111 		case HID_GD_KEYBOARD:
1112 			if (hid_kbpoll_interval > 0)
1113 				interval = hid_kbpoll_interval;
1114 			break;
1115 		}
1116 
1117 		ret = -ENOMEM;
1118 		if (usb_endpoint_dir_in(endpoint)) {
1119 			if (usbhid->urbin)
1120 				continue;
1121 			if (!(usbhid->urbin = usb_alloc_urb(0, GFP_KERNEL)))
1122 				goto fail;
1123 			pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
1124 			usb_fill_int_urb(usbhid->urbin, dev, pipe, usbhid->inbuf, insize,
1125 					 hid_irq_in, hid, interval);
1126 			usbhid->urbin->transfer_dma = usbhid->inbuf_dma;
1127 			usbhid->urbin->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1128 		} else {
1129 			if (usbhid->urbout)
1130 				continue;
1131 			if (!(usbhid->urbout = usb_alloc_urb(0, GFP_KERNEL)))
1132 				goto fail;
1133 			pipe = usb_sndintpipe(dev, endpoint->bEndpointAddress);
1134 			usb_fill_int_urb(usbhid->urbout, dev, pipe, usbhid->outbuf, 0,
1135 					 hid_irq_out, hid, interval);
1136 			usbhid->urbout->transfer_dma = usbhid->outbuf_dma;
1137 			usbhid->urbout->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1138 		}
1139 	}
1140 
1141 	usbhid->urbctrl = usb_alloc_urb(0, GFP_KERNEL);
1142 	if (!usbhid->urbctrl) {
1143 		ret = -ENOMEM;
1144 		goto fail;
1145 	}
1146 
1147 	usb_fill_control_urb(usbhid->urbctrl, dev, 0, (void *) usbhid->cr,
1148 			     usbhid->ctrlbuf, 1, hid_ctrl, hid);
1149 	usbhid->urbctrl->transfer_dma = usbhid->ctrlbuf_dma;
1150 	usbhid->urbctrl->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1151 
1152 	set_bit(HID_STARTED, &usbhid->iofl);
1153 
1154 	if (hid->quirks & HID_QUIRK_ALWAYS_POLL) {
1155 		ret = usb_autopm_get_interface(usbhid->intf);
1156 		if (ret)
1157 			goto fail;
1158 		set_bit(HID_IN_POLLING, &usbhid->iofl);
1159 		usbhid->intf->needs_remote_wakeup = 1;
1160 		ret = hid_start_in(hid);
1161 		if (ret) {
1162 			dev_err(&hid->dev,
1163 				"failed to start in urb: %d\n", ret);
1164 		}
1165 		usb_autopm_put_interface(usbhid->intf);
1166 	}
1167 
1168 	/* Some keyboards don't work until their LEDs have been set.
1169 	 * Since BIOSes do set the LEDs, it must be safe for any device
1170 	 * that supports the keyboard boot protocol.
1171 	 * In addition, enable remote wakeup by default for all keyboard
1172 	 * devices supporting the boot protocol.
1173 	 */
1174 	if (interface->desc.bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT &&
1175 			interface->desc.bInterfaceProtocol ==
1176 				USB_INTERFACE_PROTOCOL_KEYBOARD) {
1177 		usbhid_set_leds(hid);
1178 		device_set_wakeup_enable(&dev->dev, 1);
1179 	}
1180 	return 0;
1181 
1182 fail:
1183 	usb_free_urb(usbhid->urbin);
1184 	usb_free_urb(usbhid->urbout);
1185 	usb_free_urb(usbhid->urbctrl);
1186 	usbhid->urbin = NULL;
1187 	usbhid->urbout = NULL;
1188 	usbhid->urbctrl = NULL;
1189 	hid_free_buffers(dev, hid);
1190 	return ret;
1191 }
1192 
1193 static void usbhid_stop(struct hid_device *hid)
1194 {
1195 	struct usbhid_device *usbhid = hid->driver_data;
1196 
1197 	if (WARN_ON(!usbhid))
1198 		return;
1199 
1200 	if (hid->quirks & HID_QUIRK_ALWAYS_POLL) {
1201 		clear_bit(HID_IN_POLLING, &usbhid->iofl);
1202 		usbhid->intf->needs_remote_wakeup = 0;
1203 	}
1204 
1205 	clear_bit(HID_STARTED, &usbhid->iofl);
1206 	spin_lock_irq(&usbhid->lock);	/* Sync with error and led handlers */
1207 	set_bit(HID_DISCONNECTED, &usbhid->iofl);
1208 	spin_unlock_irq(&usbhid->lock);
1209 	usb_kill_urb(usbhid->urbin);
1210 	usb_kill_urb(usbhid->urbout);
1211 	usb_kill_urb(usbhid->urbctrl);
1212 
1213 	hid_cancel_delayed_stuff(usbhid);
1214 
1215 	hid->claimed = 0;
1216 
1217 	usb_free_urb(usbhid->urbin);
1218 	usb_free_urb(usbhid->urbctrl);
1219 	usb_free_urb(usbhid->urbout);
1220 	usbhid->urbin = NULL; /* don't mess up next start */
1221 	usbhid->urbctrl = NULL;
1222 	usbhid->urbout = NULL;
1223 
1224 	hid_free_buffers(hid_to_usb_dev(hid), hid);
1225 }
1226 
1227 static int usbhid_power(struct hid_device *hid, int lvl)
1228 {
1229 	struct usbhid_device *usbhid = hid->driver_data;
1230 	int r = 0;
1231 
1232 	switch (lvl) {
1233 	case PM_HINT_FULLON:
1234 		r = usb_autopm_get_interface(usbhid->intf);
1235 		break;
1236 
1237 	case PM_HINT_NORMAL:
1238 		usb_autopm_put_interface(usbhid->intf);
1239 		break;
1240 	}
1241 
1242 	return r;
1243 }
1244 
1245 static void usbhid_request(struct hid_device *hid, struct hid_report *rep, int reqtype)
1246 {
1247 	switch (reqtype) {
1248 	case HID_REQ_GET_REPORT:
1249 		usbhid_submit_report(hid, rep, USB_DIR_IN);
1250 		break;
1251 	case HID_REQ_SET_REPORT:
1252 		usbhid_submit_report(hid, rep, USB_DIR_OUT);
1253 		break;
1254 	}
1255 }
1256 
1257 static int usbhid_raw_request(struct hid_device *hid, unsigned char reportnum,
1258 			      __u8 *buf, size_t len, unsigned char rtype,
1259 			      int reqtype)
1260 {
1261 	switch (reqtype) {
1262 	case HID_REQ_GET_REPORT:
1263 		return usbhid_get_raw_report(hid, reportnum, buf, len, rtype);
1264 	case HID_REQ_SET_REPORT:
1265 		return usbhid_set_raw_report(hid, reportnum, buf, len, rtype);
1266 	default:
1267 		return -EIO;
1268 	}
1269 }
1270 
1271 static int usbhid_idle(struct hid_device *hid, int report, int idle,
1272 		int reqtype)
1273 {
1274 	struct usb_device *dev = hid_to_usb_dev(hid);
1275 	struct usb_interface *intf = to_usb_interface(hid->dev.parent);
1276 	struct usb_host_interface *interface = intf->cur_altsetting;
1277 	int ifnum = interface->desc.bInterfaceNumber;
1278 
1279 	if (reqtype != HID_REQ_SET_IDLE)
1280 		return -EINVAL;
1281 
1282 	return hid_set_idle(dev, ifnum, report, idle);
1283 }
1284 
1285 struct hid_ll_driver usb_hid_driver = {
1286 	.parse = usbhid_parse,
1287 	.start = usbhid_start,
1288 	.stop = usbhid_stop,
1289 	.open = usbhid_open,
1290 	.close = usbhid_close,
1291 	.power = usbhid_power,
1292 	.request = usbhid_request,
1293 	.wait = usbhid_wait_io,
1294 	.raw_request = usbhid_raw_request,
1295 	.output_report = usbhid_output_report,
1296 	.idle = usbhid_idle,
1297 };
1298 EXPORT_SYMBOL_GPL(usb_hid_driver);
1299 
1300 static int usbhid_probe(struct usb_interface *intf, const struct usb_device_id *id)
1301 {
1302 	struct usb_host_interface *interface = intf->cur_altsetting;
1303 	struct usb_device *dev = interface_to_usbdev(intf);
1304 	struct usbhid_device *usbhid;
1305 	struct hid_device *hid;
1306 	unsigned int n, has_in = 0;
1307 	size_t len;
1308 	int ret;
1309 
1310 	dbg_hid("HID probe called for ifnum %d\n",
1311 			intf->altsetting->desc.bInterfaceNumber);
1312 
1313 	for (n = 0; n < interface->desc.bNumEndpoints; n++)
1314 		if (usb_endpoint_is_int_in(&interface->endpoint[n].desc))
1315 			has_in++;
1316 	if (!has_in) {
1317 		hid_err(intf, "couldn't find an input interrupt endpoint\n");
1318 		return -ENODEV;
1319 	}
1320 
1321 	hid = hid_allocate_device();
1322 	if (IS_ERR(hid))
1323 		return PTR_ERR(hid);
1324 
1325 	usb_set_intfdata(intf, hid);
1326 	hid->ll_driver = &usb_hid_driver;
1327 	hid->ff_init = hid_pidff_init;
1328 #ifdef CONFIG_USB_HIDDEV
1329 	hid->hiddev_connect = hiddev_connect;
1330 	hid->hiddev_disconnect = hiddev_disconnect;
1331 	hid->hiddev_hid_event = hiddev_hid_event;
1332 	hid->hiddev_report_event = hiddev_report_event;
1333 #endif
1334 	hid->dev.parent = &intf->dev;
1335 	hid->bus = BUS_USB;
1336 	hid->vendor = le16_to_cpu(dev->descriptor.idVendor);
1337 	hid->product = le16_to_cpu(dev->descriptor.idProduct);
1338 	hid->version = le16_to_cpu(dev->descriptor.bcdDevice);
1339 	hid->name[0] = 0;
1340 	if (intf->cur_altsetting->desc.bInterfaceProtocol ==
1341 			USB_INTERFACE_PROTOCOL_MOUSE)
1342 		hid->type = HID_TYPE_USBMOUSE;
1343 	else if (intf->cur_altsetting->desc.bInterfaceProtocol == 0)
1344 		hid->type = HID_TYPE_USBNONE;
1345 
1346 	if (dev->manufacturer)
1347 		strlcpy(hid->name, dev->manufacturer, sizeof(hid->name));
1348 
1349 	if (dev->product) {
1350 		if (dev->manufacturer)
1351 			strlcat(hid->name, " ", sizeof(hid->name));
1352 		strlcat(hid->name, dev->product, sizeof(hid->name));
1353 	}
1354 
1355 	if (!strlen(hid->name))
1356 		snprintf(hid->name, sizeof(hid->name), "HID %04x:%04x",
1357 			 le16_to_cpu(dev->descriptor.idVendor),
1358 			 le16_to_cpu(dev->descriptor.idProduct));
1359 
1360 	usb_make_path(dev, hid->phys, sizeof(hid->phys));
1361 	strlcat(hid->phys, "/input", sizeof(hid->phys));
1362 	len = strlen(hid->phys);
1363 	if (len < sizeof(hid->phys) - 1)
1364 		snprintf(hid->phys + len, sizeof(hid->phys) - len,
1365 			 "%d", intf->altsetting[0].desc.bInterfaceNumber);
1366 
1367 	if (usb_string(dev, dev->descriptor.iSerialNumber, hid->uniq, 64) <= 0)
1368 		hid->uniq[0] = 0;
1369 
1370 	usbhid = kzalloc(sizeof(*usbhid), GFP_KERNEL);
1371 	if (usbhid == NULL) {
1372 		ret = -ENOMEM;
1373 		goto err;
1374 	}
1375 
1376 	hid->driver_data = usbhid;
1377 	usbhid->hid = hid;
1378 	usbhid->intf = intf;
1379 	usbhid->ifnum = interface->desc.bInterfaceNumber;
1380 
1381 	init_waitqueue_head(&usbhid->wait);
1382 	INIT_WORK(&usbhid->reset_work, hid_reset);
1383 	timer_setup(&usbhid->io_retry, hid_retry_timeout, 0);
1384 	spin_lock_init(&usbhid->lock);
1385 
1386 	ret = hid_add_device(hid);
1387 	if (ret) {
1388 		if (ret != -ENODEV)
1389 			hid_err(intf, "can't add hid device: %d\n", ret);
1390 		goto err_free;
1391 	}
1392 
1393 	return 0;
1394 err_free:
1395 	kfree(usbhid);
1396 err:
1397 	hid_destroy_device(hid);
1398 	return ret;
1399 }
1400 
1401 static void usbhid_disconnect(struct usb_interface *intf)
1402 {
1403 	struct hid_device *hid = usb_get_intfdata(intf);
1404 	struct usbhid_device *usbhid;
1405 
1406 	if (WARN_ON(!hid))
1407 		return;
1408 
1409 	usbhid = hid->driver_data;
1410 	spin_lock_irq(&usbhid->lock);	/* Sync with error and led handlers */
1411 	set_bit(HID_DISCONNECTED, &usbhid->iofl);
1412 	spin_unlock_irq(&usbhid->lock);
1413 	hid_destroy_device(hid);
1414 	kfree(usbhid);
1415 }
1416 
1417 static void hid_cancel_delayed_stuff(struct usbhid_device *usbhid)
1418 {
1419 	del_timer_sync(&usbhid->io_retry);
1420 	cancel_work_sync(&usbhid->reset_work);
1421 }
1422 
1423 static void hid_cease_io(struct usbhid_device *usbhid)
1424 {
1425 	del_timer_sync(&usbhid->io_retry);
1426 	usb_kill_urb(usbhid->urbin);
1427 	usb_kill_urb(usbhid->urbctrl);
1428 	usb_kill_urb(usbhid->urbout);
1429 }
1430 
1431 static void hid_restart_io(struct hid_device *hid)
1432 {
1433 	struct usbhid_device *usbhid = hid->driver_data;
1434 	int clear_halt = test_bit(HID_CLEAR_HALT, &usbhid->iofl);
1435 	int reset_pending = test_bit(HID_RESET_PENDING, &usbhid->iofl);
1436 
1437 	spin_lock_irq(&usbhid->lock);
1438 	clear_bit(HID_SUSPENDED, &usbhid->iofl);
1439 	usbhid_mark_busy(usbhid);
1440 
1441 	if (clear_halt || reset_pending)
1442 		schedule_work(&usbhid->reset_work);
1443 	usbhid->retry_delay = 0;
1444 	spin_unlock_irq(&usbhid->lock);
1445 
1446 	if (reset_pending || !test_bit(HID_STARTED, &usbhid->iofl))
1447 		return;
1448 
1449 	if (!clear_halt) {
1450 		if (hid_start_in(hid) < 0)
1451 			hid_io_error(hid);
1452 	}
1453 
1454 	spin_lock_irq(&usbhid->lock);
1455 	if (usbhid->urbout && !test_bit(HID_OUT_RUNNING, &usbhid->iofl))
1456 		usbhid_restart_out_queue(usbhid);
1457 	if (!test_bit(HID_CTRL_RUNNING, &usbhid->iofl))
1458 		usbhid_restart_ctrl_queue(usbhid);
1459 	spin_unlock_irq(&usbhid->lock);
1460 }
1461 
1462 /* Treat USB reset pretty much the same as suspend/resume */
1463 static int hid_pre_reset(struct usb_interface *intf)
1464 {
1465 	struct hid_device *hid = usb_get_intfdata(intf);
1466 	struct usbhid_device *usbhid = hid->driver_data;
1467 
1468 	spin_lock_irq(&usbhid->lock);
1469 	set_bit(HID_RESET_PENDING, &usbhid->iofl);
1470 	spin_unlock_irq(&usbhid->lock);
1471 	hid_cease_io(usbhid);
1472 
1473 	return 0;
1474 }
1475 
1476 /* Same routine used for post_reset and reset_resume */
1477 static int hid_post_reset(struct usb_interface *intf)
1478 {
1479 	struct usb_device *dev = interface_to_usbdev (intf);
1480 	struct hid_device *hid = usb_get_intfdata(intf);
1481 	struct usbhid_device *usbhid = hid->driver_data;
1482 	struct usb_host_interface *interface = intf->cur_altsetting;
1483 	int status;
1484 	char *rdesc;
1485 
1486 	/* Fetch and examine the HID report descriptor. If this
1487 	 * has changed, then rebind. Since usbcore's check of the
1488 	 * configuration descriptors passed, we already know that
1489 	 * the size of the HID report descriptor has not changed.
1490 	 */
1491 	rdesc = kmalloc(hid->dev_rsize, GFP_KERNEL);
1492 	if (!rdesc)
1493 		return -ENOMEM;
1494 
1495 	status = hid_get_class_descriptor(dev,
1496 				interface->desc.bInterfaceNumber,
1497 				HID_DT_REPORT, rdesc, hid->dev_rsize);
1498 	if (status < 0) {
1499 		dbg_hid("reading report descriptor failed (post_reset)\n");
1500 		kfree(rdesc);
1501 		return status;
1502 	}
1503 	status = memcmp(rdesc, hid->dev_rdesc, hid->dev_rsize);
1504 	kfree(rdesc);
1505 	if (status != 0) {
1506 		dbg_hid("report descriptor changed\n");
1507 		return -EPERM;
1508 	}
1509 
1510 	/* No need to do another reset or clear a halted endpoint */
1511 	spin_lock_irq(&usbhid->lock);
1512 	clear_bit(HID_RESET_PENDING, &usbhid->iofl);
1513 	clear_bit(HID_CLEAR_HALT, &usbhid->iofl);
1514 	spin_unlock_irq(&usbhid->lock);
1515 	hid_set_idle(dev, intf->cur_altsetting->desc.bInterfaceNumber, 0, 0);
1516 
1517 	hid_restart_io(hid);
1518 
1519 	return 0;
1520 }
1521 
1522 #ifdef CONFIG_PM
1523 static int hid_resume_common(struct hid_device *hid, bool driver_suspended)
1524 {
1525 	int status = 0;
1526 
1527 	hid_restart_io(hid);
1528 	if (driver_suspended && hid->driver && hid->driver->resume)
1529 		status = hid->driver->resume(hid);
1530 	return status;
1531 }
1532 
1533 static int hid_suspend(struct usb_interface *intf, pm_message_t message)
1534 {
1535 	struct hid_device *hid = usb_get_intfdata(intf);
1536 	struct usbhid_device *usbhid = hid->driver_data;
1537 	int status = 0;
1538 	bool driver_suspended = false;
1539 	unsigned int ledcount;
1540 
1541 	if (PMSG_IS_AUTO(message)) {
1542 		ledcount = hidinput_count_leds(hid);
1543 		spin_lock_irq(&usbhid->lock);	/* Sync with error handler */
1544 		if (!test_bit(HID_RESET_PENDING, &usbhid->iofl)
1545 		    && !test_bit(HID_CLEAR_HALT, &usbhid->iofl)
1546 		    && !test_bit(HID_OUT_RUNNING, &usbhid->iofl)
1547 		    && !test_bit(HID_CTRL_RUNNING, &usbhid->iofl)
1548 		    && !test_bit(HID_KEYS_PRESSED, &usbhid->iofl)
1549 		    && (!ledcount || ignoreled))
1550 		{
1551 			set_bit(HID_SUSPENDED, &usbhid->iofl);
1552 			spin_unlock_irq(&usbhid->lock);
1553 			if (hid->driver && hid->driver->suspend) {
1554 				status = hid->driver->suspend(hid, message);
1555 				if (status < 0)
1556 					goto failed;
1557 			}
1558 			driver_suspended = true;
1559 		} else {
1560 			usbhid_mark_busy(usbhid);
1561 			spin_unlock_irq(&usbhid->lock);
1562 			return -EBUSY;
1563 		}
1564 
1565 	} else {
1566 		/* TODO: resume() might need to handle suspend failure */
1567 		if (hid->driver && hid->driver->suspend)
1568 			status = hid->driver->suspend(hid, message);
1569 		driver_suspended = true;
1570 		spin_lock_irq(&usbhid->lock);
1571 		set_bit(HID_SUSPENDED, &usbhid->iofl);
1572 		spin_unlock_irq(&usbhid->lock);
1573 		if (usbhid_wait_io(hid) < 0)
1574 			status = -EIO;
1575 	}
1576 
1577 	hid_cancel_delayed_stuff(usbhid);
1578 	hid_cease_io(usbhid);
1579 
1580 	if (PMSG_IS_AUTO(message) && test_bit(HID_KEYS_PRESSED, &usbhid->iofl)) {
1581 		/* lost race against keypresses */
1582 		status = -EBUSY;
1583 		goto failed;
1584 	}
1585 	dev_dbg(&intf->dev, "suspend\n");
1586 	return status;
1587 
1588  failed:
1589 	hid_resume_common(hid, driver_suspended);
1590 	return status;
1591 }
1592 
1593 static int hid_resume(struct usb_interface *intf)
1594 {
1595 	struct hid_device *hid = usb_get_intfdata (intf);
1596 	int status;
1597 
1598 	status = hid_resume_common(hid, true);
1599 	dev_dbg(&intf->dev, "resume status %d\n", status);
1600 	return 0;
1601 }
1602 
1603 static int hid_reset_resume(struct usb_interface *intf)
1604 {
1605 	struct hid_device *hid = usb_get_intfdata(intf);
1606 	int status;
1607 
1608 	status = hid_post_reset(intf);
1609 	if (status >= 0 && hid->driver && hid->driver->reset_resume) {
1610 		int ret = hid->driver->reset_resume(hid);
1611 		if (ret < 0)
1612 			status = ret;
1613 	}
1614 	return status;
1615 }
1616 
1617 #endif /* CONFIG_PM */
1618 
1619 static const struct usb_device_id hid_usb_ids[] = {
1620 	{ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
1621 		.bInterfaceClass = USB_INTERFACE_CLASS_HID },
1622 	{ }						/* Terminating entry */
1623 };
1624 
1625 MODULE_DEVICE_TABLE (usb, hid_usb_ids);
1626 
1627 static struct usb_driver hid_driver = {
1628 	.name =		"usbhid",
1629 	.probe =	usbhid_probe,
1630 	.disconnect =	usbhid_disconnect,
1631 #ifdef CONFIG_PM
1632 	.suspend =	hid_suspend,
1633 	.resume =	hid_resume,
1634 	.reset_resume =	hid_reset_resume,
1635 #endif
1636 	.pre_reset =	hid_pre_reset,
1637 	.post_reset =	hid_post_reset,
1638 	.id_table =	hid_usb_ids,
1639 	.supports_autosuspend = 1,
1640 };
1641 
1642 struct usb_interface *usbhid_find_interface(int minor)
1643 {
1644 	return usb_find_interface(&hid_driver, minor);
1645 }
1646 
1647 static int __init hid_init(void)
1648 {
1649 	int retval = -ENOMEM;
1650 
1651 	retval = hid_quirks_init(quirks_param, BUS_USB, MAX_USBHID_BOOT_QUIRKS);
1652 	if (retval)
1653 		goto usbhid_quirks_init_fail;
1654 	retval = usb_register(&hid_driver);
1655 	if (retval)
1656 		goto usb_register_fail;
1657 	pr_info(KBUILD_MODNAME ": " DRIVER_DESC "\n");
1658 
1659 	return 0;
1660 usb_register_fail:
1661 	hid_quirks_exit(BUS_USB);
1662 usbhid_quirks_init_fail:
1663 	return retval;
1664 }
1665 
1666 static void __exit hid_exit(void)
1667 {
1668 	usb_deregister(&hid_driver);
1669 	hid_quirks_exit(BUS_USB);
1670 }
1671 
1672 module_init(hid_init);
1673 module_exit(hid_exit);
1674 
1675 MODULE_AUTHOR("Andreas Gal");
1676 MODULE_AUTHOR("Vojtech Pavlik");
1677 MODULE_AUTHOR("Jiri Kosina");
1678 MODULE_DESCRIPTION(DRIVER_DESC);
1679 MODULE_LICENSE("GPL");
1680