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