xref: /freebsd/sys/dev/hid/hidbus.c (revision 535af610)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2019-2020 Vladimir Kondratyev <wulf@FreeBSD.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>
32 #include <sys/bus.h>
33 #include <sys/ck.h>
34 #include <sys/epoch.h>
35 #include <sys/kdb.h>
36 #include <sys/kernel.h>
37 #include <sys/libkern.h>
38 #include <sys/lock.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/mutex.h>
42 #include <sys/proc.h>
43 #include <sys/sbuf.h>
44 #include <sys/sx.h>
45 #include <sys/systm.h>
46 
47 #define	HID_DEBUG_VAR	hid_debug
48 #include <dev/hid/hid.h>
49 #include <dev/hid/hidbus.h>
50 #include <dev/hid/hidquirk.h>
51 
52 #include "hid_if.h"
53 
54 #define	INPUT_EPOCH	global_epoch_preempt
55 #define	HID_RSIZE_MAX	1024
56 
57 static hid_intr_t	hidbus_intr;
58 
59 static device_probe_t	hidbus_probe;
60 static device_attach_t	hidbus_attach;
61 static device_detach_t	hidbus_detach;
62 
63 struct hidbus_ivars {
64 	int32_t				usage;
65 	uint8_t				index;
66 	uint32_t			flags;
67 	uintptr_t			driver_info;    /* for internal use */
68 	struct mtx			*mtx;		/* child intr mtx */
69 	hid_intr_t			*intr_handler;	/* executed under mtx*/
70 	void				*intr_ctx;
71 	unsigned int			refcnt;		/* protected by mtx */
72 	struct epoch_context		epoch_ctx;
73 	CK_STAILQ_ENTRY(hidbus_ivars)	link;
74 };
75 
76 struct hidbus_softc {
77 	device_t			dev;
78 	struct sx			sx;
79 	struct mtx			mtx;
80 
81 	bool				nowrite;
82 
83 	struct hid_rdesc_info		rdesc;
84 	bool				overloaded;
85 	int				nest;	/* Child attach nesting lvl */
86 	int				nauto;	/* Number of autochildren */
87 
88 	CK_STAILQ_HEAD(, hidbus_ivars)	tlcs;
89 };
90 
91 static int
92 hidbus_fill_rdesc_info(struct hid_rdesc_info *hri, const void *data,
93     hid_size_t len)
94 {
95 	int error = 0;
96 
97 	hri->data = __DECONST(void *, data);
98 	hri->len = len;
99 
100 	/*
101 	 * If report descriptor is not available yet, set maximal
102 	 * report sizes high enough to allow hidraw to work.
103 	 */
104 	hri->isize = len == 0 ? HID_RSIZE_MAX :
105 	    hid_report_size_max(data, len, hid_input, &hri->iid);
106 	hri->osize = len == 0 ? HID_RSIZE_MAX :
107 	    hid_report_size_max(data, len, hid_output, &hri->oid);
108 	hri->fsize = len == 0 ? HID_RSIZE_MAX :
109 	    hid_report_size_max(data, len, hid_feature, &hri->fid);
110 
111 	if (hri->isize > HID_RSIZE_MAX) {
112 		DPRINTF("input size is too large, %u bytes (truncating)\n",
113 		    hri->isize);
114 		hri->isize = HID_RSIZE_MAX;
115 		error = EOVERFLOW;
116 	}
117 	if (hri->osize > HID_RSIZE_MAX) {
118 		DPRINTF("output size is too large, %u bytes (truncating)\n",
119 		    hri->osize);
120 		hri->osize = HID_RSIZE_MAX;
121 		error = EOVERFLOW;
122 	}
123 	if (hri->fsize > HID_RSIZE_MAX) {
124 		DPRINTF("feature size is too large, %u bytes (truncating)\n",
125 		    hri->fsize);
126 		hri->fsize = HID_RSIZE_MAX;
127 		error = EOVERFLOW;
128 	}
129 
130 	return (error);
131 }
132 
133 int
134 hidbus_locate(const void *desc, hid_size_t size, int32_t u, enum hid_kind k,
135     uint8_t tlc_index, uint8_t index, struct hid_location *loc,
136     uint32_t *flags, uint8_t *id, struct hid_absinfo *ai)
137 {
138 	struct hid_data *d;
139 	struct hid_item h;
140 	int i;
141 
142 	d = hid_start_parse(desc, size, 1 << k);
143 	HIDBUS_FOREACH_ITEM(d, &h, tlc_index) {
144 		for (i = 0; i < h.nusages; i++) {
145 			if (h.kind == k && h.usages[i] == u) {
146 				if (index--)
147 					break;
148 				if (loc != NULL)
149 					*loc = h.loc;
150 				if (flags != NULL)
151 					*flags = h.flags;
152 				if (id != NULL)
153 					*id = h.report_ID;
154 				if (ai != NULL && (h.flags&HIO_RELATIVE) == 0)
155 					*ai = (struct hid_absinfo) {
156 					    .max = h.logical_maximum,
157 					    .min = h.logical_minimum,
158 					    .res = hid_item_resolution(&h),
159 					};
160 				hid_end_parse(d);
161 				return (1);
162 			}
163 		}
164 	}
165 	if (loc != NULL)
166 		loc->size = 0;
167 	if (flags != NULL)
168 		*flags = 0;
169 	if (id != NULL)
170 		*id = 0;
171 	hid_end_parse(d);
172 	return (0);
173 }
174 
175 bool
176 hidbus_is_collection(const void *desc, hid_size_t size, int32_t usage,
177     uint8_t tlc_index)
178 {
179 	struct hid_data *d;
180 	struct hid_item h;
181 	bool ret = false;
182 
183 	d = hid_start_parse(desc, size, 0);
184 	HIDBUS_FOREACH_ITEM(d, &h, tlc_index) {
185 		if (h.kind == hid_collection && h.usage == usage) {
186 			ret = true;
187 			break;
188 		}
189 	}
190 	hid_end_parse(d);
191 	return (ret);
192 }
193 
194 static device_t
195 hidbus_add_child(device_t dev, u_int order, const char *name, int unit)
196 {
197 	struct hidbus_softc *sc = device_get_softc(dev);
198 	struct hidbus_ivars *tlc;
199 	device_t child;
200 
201 	child = device_add_child_ordered(dev, order, name, unit);
202 	if (child == NULL)
203 			return (child);
204 
205 	tlc = malloc(sizeof(struct hidbus_ivars), M_DEVBUF, M_WAITOK | M_ZERO);
206 	tlc->mtx = &sc->mtx;
207 	device_set_ivars(child, tlc);
208 	sx_xlock(&sc->sx);
209 	CK_STAILQ_INSERT_TAIL(&sc->tlcs, tlc, link);
210 	sx_unlock(&sc->sx);
211 
212 	return (child);
213 }
214 
215 static int
216 hidbus_enumerate_children(device_t dev, const void* data, hid_size_t len)
217 {
218 	struct hidbus_softc *sc = device_get_softc(dev);
219 	struct hid_data *hd;
220 	struct hid_item hi;
221 	device_t child;
222 	uint8_t index = 0;
223 
224 	if (data == NULL || len == 0)
225 		return (ENXIO);
226 
227 	/* Add a child for each top level collection */
228 	hd = hid_start_parse(data, len, 1 << hid_input);
229 	while (hid_get_item(hd, &hi)) {
230 		if (hi.kind != hid_collection || hi.collevel != 1)
231 			continue;
232 		child = BUS_ADD_CHILD(dev, 0, NULL, -1);
233 		if (child == NULL) {
234 			device_printf(dev, "Could not add HID device\n");
235 			continue;
236 		}
237 		hidbus_set_index(child, index);
238 		hidbus_set_usage(child, hi.usage);
239 		hidbus_set_flags(child, HIDBUS_FLAG_AUTOCHILD);
240 		index++;
241 		DPRINTF("Add child TLC: 0x%04x:0x%04x\n",
242 		    HID_GET_USAGE_PAGE(hi.usage), HID_GET_USAGE(hi.usage));
243 	}
244 	hid_end_parse(hd);
245 
246 	if (index == 0)
247 		return (ENXIO);
248 
249 	sc->nauto = index;
250 
251 	return (0);
252 }
253 
254 static int
255 hidbus_attach_children(device_t dev)
256 {
257 	struct hidbus_softc *sc = device_get_softc(dev);
258 	int error;
259 
260 	HID_INTR_SETUP(device_get_parent(dev), dev, hidbus_intr, sc,
261 	    &sc->rdesc);
262 
263 	error = hidbus_enumerate_children(dev, sc->rdesc.data, sc->rdesc.len);
264 	if (error != 0)
265 		DPRINTF("failed to enumerate children: error %d\n", error);
266 
267 	/*
268 	 * hidbus_attach_children() can recurse through device_identify->
269 	 * hid_set_report_descr() call sequence. Do not perform children
270 	 * attach twice in that case.
271 	 */
272 	sc->nest++;
273 	bus_generic_probe(dev);
274 	sc->nest--;
275 	if (sc->nest != 0)
276 		return (0);
277 
278 	if (hid_is_keyboard(sc->rdesc.data, sc->rdesc.len) != 0)
279 		error = bus_generic_attach(dev);
280 	else
281 		error = bus_delayed_attach_children(dev);
282 	if (error != 0)
283 		device_printf(dev, "failed to attach child: error %d\n", error);
284 
285 	return (error);
286 }
287 
288 static int
289 hidbus_detach_children(device_t dev)
290 {
291 	device_t *children, bus;
292 	bool is_bus;
293 	int i, error;
294 
295 	error = 0;
296 
297 	is_bus = device_get_devclass(dev) == devclass_find("hidbus");
298 	bus = is_bus ? dev : device_get_parent(dev);
299 
300 	KASSERT(device_get_devclass(bus) == devclass_find("hidbus"),
301 	    ("Device is not hidbus or it's child"));
302 
303 	if (is_bus) {
304 		/* If hidbus is passed, delete all children. */
305 		bus_generic_detach(bus);
306 		device_delete_children(bus);
307 	} else {
308 		/*
309 		 * If hidbus child is passed, delete all hidbus children
310 		 * except caller. Deleting the caller may result in deadlock.
311 		 */
312 		error = device_get_children(bus, &children, &i);
313 		if (error != 0)
314 			return (error);
315 		while (i-- > 0) {
316 			if (children[i] == dev)
317 				continue;
318 			DPRINTF("Delete child. index=%d (%s)\n",
319 			    hidbus_get_index(children[i]),
320 			    device_get_nameunit(children[i]));
321 			error = device_delete_child(bus, children[i]);
322 			if (error) {
323 				DPRINTF("Failed deleting %s\n",
324 				    device_get_nameunit(children[i]));
325 				break;
326 			}
327 		}
328 		free(children, M_TEMP);
329 	}
330 
331 	HID_INTR_UNSETUP(device_get_parent(bus), bus);
332 
333 	return (error);
334 }
335 
336 static int
337 hidbus_probe(device_t dev)
338 {
339 
340 	device_set_desc(dev, "HID bus");
341 
342 	/* Allow other subclasses to override this driver. */
343 	return (BUS_PROBE_GENERIC);
344 }
345 
346 static int
347 hidbus_attach(device_t dev)
348 {
349 	struct hidbus_softc *sc = device_get_softc(dev);
350 	struct hid_device_info *devinfo = device_get_ivars(dev);
351 	void *d_ptr = NULL;
352 	hid_size_t d_len;
353 	int error;
354 
355 	sc->dev = dev;
356 	CK_STAILQ_INIT(&sc->tlcs);
357 	mtx_init(&sc->mtx, "hidbus ivar lock", NULL, MTX_DEF);
358 	sx_init(&sc->sx, "hidbus ivar list lock");
359 
360 	/*
361 	 * Ignore error. It is possible for non-HID device e.g. XBox360 gamepad
362 	 * to emulate HID through overloading of report descriptor.
363 	 */
364 	d_len = devinfo->rdescsize;
365 	if (d_len != 0) {
366 		d_ptr = malloc(d_len, M_DEVBUF, M_ZERO | M_WAITOK);
367 		error = hid_get_rdesc(dev, d_ptr, d_len);
368 		if (error != 0) {
369 			free(d_ptr, M_DEVBUF);
370 			d_len = 0;
371 			d_ptr = NULL;
372 		}
373 	}
374 
375 	hidbus_fill_rdesc_info(&sc->rdesc, d_ptr, d_len);
376 
377 	sc->nowrite = hid_test_quirk(devinfo, HQ_NOWRITE);
378 
379 	error = hidbus_attach_children(dev);
380 	if (error != 0) {
381 		hidbus_detach(dev);
382 		return (ENXIO);
383 	}
384 
385 	return (0);
386 }
387 
388 static int
389 hidbus_detach(device_t dev)
390 {
391 	struct hidbus_softc *sc = device_get_softc(dev);
392 
393 	hidbus_detach_children(dev);
394 	sx_destroy(&sc->sx);
395 	mtx_destroy(&sc->mtx);
396 	free(sc->rdesc.data, M_DEVBUF);
397 
398 	return (0);
399 }
400 
401 static void
402 hidbus_child_detached(device_t bus, device_t child)
403 {
404 	struct hidbus_softc *sc = device_get_softc(bus);
405 	struct hidbus_ivars *tlc = device_get_ivars(child);
406 
407 	KASSERT(tlc->refcnt == 0, ("Child device is running"));
408 	tlc->mtx = &sc->mtx;
409 	tlc->intr_handler = NULL;
410 	tlc->flags &= ~HIDBUS_FLAG_CAN_POLL;
411 }
412 
413 /*
414  * Epoch callback indicating tlc is safe to destroy
415  */
416 static void
417 hidbus_ivar_dtor(epoch_context_t ctx)
418 {
419 	struct hidbus_ivars *tlc;
420 
421 	tlc = __containerof(ctx, struct hidbus_ivars, epoch_ctx);
422 	free(tlc, M_DEVBUF);
423 }
424 
425 static void
426 hidbus_child_deleted(device_t bus, device_t child)
427 {
428 	struct hidbus_softc *sc = device_get_softc(bus);
429 	struct hidbus_ivars *tlc = device_get_ivars(child);
430 
431 	sx_xlock(&sc->sx);
432 	KASSERT(tlc->refcnt == 0, ("Child device is running"));
433 	CK_STAILQ_REMOVE(&sc->tlcs, tlc, hidbus_ivars, link);
434 	sx_unlock(&sc->sx);
435 	epoch_call(INPUT_EPOCH, hidbus_ivar_dtor, &tlc->epoch_ctx);
436 }
437 
438 static int
439 hidbus_read_ivar(device_t bus, device_t child, int which, uintptr_t *result)
440 {
441 	struct hidbus_softc *sc = device_get_softc(bus);
442 	struct hidbus_ivars *tlc = device_get_ivars(child);
443 
444 	switch (which) {
445 	case HIDBUS_IVAR_INDEX:
446 		*result = tlc->index;
447 		break;
448 	case HIDBUS_IVAR_USAGE:
449 		*result = tlc->usage;
450 		break;
451 	case HIDBUS_IVAR_FLAGS:
452 		*result = tlc->flags;
453 		break;
454 	case HIDBUS_IVAR_DRIVER_INFO:
455 		*result = tlc->driver_info;
456 		break;
457 	case HIDBUS_IVAR_LOCK:
458 		*result = (uintptr_t)(tlc->mtx == &sc->mtx ? NULL : tlc->mtx);
459 		break;
460 	default:
461 		return (EINVAL);
462 	}
463 	return (0);
464 }
465 
466 static int
467 hidbus_write_ivar(device_t bus, device_t child, int which, uintptr_t value)
468 {
469 	struct hidbus_softc *sc = device_get_softc(bus);
470 	struct hidbus_ivars *tlc = device_get_ivars(child);
471 
472 	switch (which) {
473 	case HIDBUS_IVAR_INDEX:
474 		tlc->index = value;
475 		break;
476 	case HIDBUS_IVAR_USAGE:
477 		tlc->usage = value;
478 		break;
479 	case HIDBUS_IVAR_FLAGS:
480 		tlc->flags = value;
481 		if ((value & HIDBUS_FLAG_CAN_POLL) != 0)
482 			HID_INTR_SETUP(
483 			    device_get_parent(bus), bus, NULL, NULL, NULL);
484 		break;
485 	case HIDBUS_IVAR_DRIVER_INFO:
486 		tlc->driver_info = value;
487 		break;
488 	case HIDBUS_IVAR_LOCK:
489 		tlc->mtx = (struct mtx *)value == NULL ?
490 		    &sc->mtx : (struct mtx *)value;
491 		break;
492 	default:
493 		return (EINVAL);
494 	}
495 	return (0);
496 }
497 
498 /* Location hint for devctl(8) */
499 static int
500 hidbus_child_location(device_t bus, device_t child, struct sbuf *sb)
501 {
502 	struct hidbus_ivars *tlc = device_get_ivars(child);
503 
504 	sbuf_printf(sb, "index=%hhu", tlc->index);
505         return (0);
506 }
507 
508 /* PnP information for devctl(8) */
509 static int
510 hidbus_child_pnpinfo(device_t bus, device_t child, struct sbuf *sb)
511 {
512 	struct hidbus_ivars *tlc = device_get_ivars(child);
513 	struct hid_device_info *devinfo = device_get_ivars(bus);
514 
515 	sbuf_printf(sb, "page=0x%04x usage=0x%04x bus=0x%02hx "
516 	    "vendor=0x%04hx product=0x%04hx version=0x%04hx%s%s",
517 	    HID_GET_USAGE_PAGE(tlc->usage), HID_GET_USAGE(tlc->usage),
518 	    devinfo->idBus, devinfo->idVendor, devinfo->idProduct,
519 	    devinfo->idVersion, devinfo->idPnP[0] == '\0' ? "" : " _HID=",
520 	    devinfo->idPnP[0] == '\0' ? "" : devinfo->idPnP);
521 	return (0);
522 }
523 
524 void
525 hidbus_set_desc(device_t child, const char *suffix)
526 {
527 	device_t bus = device_get_parent(child);
528 	struct hidbus_softc *sc = device_get_softc(bus);
529 	struct hid_device_info *devinfo = device_get_ivars(bus);
530 	struct hidbus_ivars *tlc = device_get_ivars(child);
531 	char buf[80];
532 
533 	/* Do not add NULL suffix or if device name already contains it. */
534 	if (suffix != NULL && strcasestr(devinfo->name, suffix) == NULL &&
535 	    (sc->nauto > 1 || (tlc->flags & HIDBUS_FLAG_AUTOCHILD) == 0)) {
536 		snprintf(buf, sizeof(buf), "%s %s", devinfo->name, suffix);
537 		device_set_desc_copy(child, buf);
538 	} else
539 		device_set_desc(child, devinfo->name);
540 }
541 
542 device_t
543 hidbus_find_child(device_t bus, int32_t usage)
544 {
545 	device_t *children, child;
546 	int ccount, i;
547 
548 	bus_topo_assert();
549 
550 	/* Get a list of all hidbus children */
551 	if (device_get_children(bus, &children, &ccount) != 0)
552 		return (NULL);
553 
554 	/* Scan through to find required TLC */
555 	for (i = 0, child = NULL; i < ccount; i++) {
556 		if (hidbus_get_usage(children[i]) == usage) {
557 			child = children[i];
558 			break;
559 		}
560 	}
561 	free(children, M_TEMP);
562 
563 	return (child);
564 }
565 
566 void
567 hidbus_intr(void *context, void *buf, hid_size_t len)
568 {
569 	struct hidbus_softc *sc = context;
570 	struct hidbus_ivars *tlc;
571 	struct epoch_tracker et;
572 
573 	/*
574 	 * Broadcast input report to all subscribers.
575 	 * TODO: Add check for input report ID.
576 	 *
577 	 * Relock mutex on every TLC item as we can't hold any locks over whole
578 	 * TLC list here due to LOR with open()/close() handlers.
579 	 */
580 	if (!HID_IN_POLLING_MODE())
581 		epoch_enter_preempt(INPUT_EPOCH, &et);
582 	CK_STAILQ_FOREACH(tlc, &sc->tlcs, link) {
583 		if (tlc->refcnt == 0 || tlc->intr_handler == NULL)
584 			continue;
585 		if (HID_IN_POLLING_MODE()) {
586 			if ((tlc->flags & HIDBUS_FLAG_CAN_POLL) != 0)
587 				tlc->intr_handler(tlc->intr_ctx, buf, len);
588 		} else {
589 			mtx_lock(tlc->mtx);
590 			tlc->intr_handler(tlc->intr_ctx, buf, len);
591 			mtx_unlock(tlc->mtx);
592 		}
593 	}
594 	if (!HID_IN_POLLING_MODE())
595 		epoch_exit_preempt(INPUT_EPOCH, &et);
596 }
597 
598 void
599 hidbus_set_intr(device_t child, hid_intr_t *handler, void *context)
600 {
601 	struct hidbus_ivars *tlc = device_get_ivars(child);
602 
603 	tlc->intr_handler = handler;
604 	tlc->intr_ctx = context;
605 }
606 
607 static int
608 hidbus_intr_start(device_t bus, device_t child)
609 {
610 	MPASS(bus = device_get_parent(child));
611 	struct hidbus_softc *sc = device_get_softc(bus);
612 	struct hidbus_ivars *ivar = device_get_ivars(child);
613 	struct hidbus_ivars *tlc;
614 	bool refcnted = false;
615 	int error;
616 
617 	if (sx_xlock_sig(&sc->sx) != 0)
618 		return (EINTR);
619 	CK_STAILQ_FOREACH(tlc, &sc->tlcs, link) {
620 		refcnted |= (tlc->refcnt != 0);
621 		if (tlc == ivar) {
622 			mtx_lock(tlc->mtx);
623 			++tlc->refcnt;
624 			mtx_unlock(tlc->mtx);
625 		}
626 	}
627 	error = refcnted ? 0 : hid_intr_start(bus);
628 	sx_unlock(&sc->sx);
629 
630 	return (error);
631 }
632 
633 static int
634 hidbus_intr_stop(device_t bus, device_t child)
635 {
636 	MPASS(bus = device_get_parent(child));
637 	struct hidbus_softc *sc = device_get_softc(bus);
638 	struct hidbus_ivars *ivar = device_get_ivars(child);
639 	struct hidbus_ivars *tlc;
640 	bool refcnted = false;
641 	int error;
642 
643 	if (sx_xlock_sig(&sc->sx) != 0)
644 		return (EINTR);
645 	CK_STAILQ_FOREACH(tlc, &sc->tlcs, link) {
646 		if (tlc == ivar) {
647 			mtx_lock(tlc->mtx);
648 			MPASS(tlc->refcnt != 0);
649 			--tlc->refcnt;
650 			mtx_unlock(tlc->mtx);
651 		}
652 		refcnted |= (tlc->refcnt != 0);
653 	}
654 	error = refcnted ? 0 : hid_intr_stop(bus);
655 	sx_unlock(&sc->sx);
656 
657 	return (error);
658 }
659 
660 static void
661 hidbus_intr_poll(device_t bus, device_t child __unused)
662 {
663 	hid_intr_poll(bus);
664 }
665 
666 struct hid_rdesc_info *
667 hidbus_get_rdesc_info(device_t child)
668 {
669 	device_t bus = device_get_parent(child);
670 	struct hidbus_softc *sc = device_get_softc(bus);
671 
672 	return (&sc->rdesc);
673 }
674 
675 /*
676  * HID interface.
677  *
678  * Hidbus as well as any hidbus child can be passed as first arg.
679  */
680 
681 /* Read cached report descriptor */
682 int
683 hid_get_report_descr(device_t dev, void **data, hid_size_t *len)
684 {
685 	device_t bus;
686 	struct hidbus_softc *sc;
687 
688 	bus = device_get_devclass(dev) == devclass_find("hidbus") ?
689 	    dev : device_get_parent(dev);
690 	sc = device_get_softc(bus);
691 
692 	/*
693 	 * Do not send request to a transport backend.
694 	 * Use cached report descriptor instead of it.
695 	 */
696 	if (sc->rdesc.data == NULL || sc->rdesc.len == 0)
697 		return (ENXIO);
698 
699 	if (data != NULL)
700 		*data = sc->rdesc.data;
701 	if (len != NULL)
702 		*len = sc->rdesc.len;
703 
704 	return (0);
705 }
706 
707 /*
708  * Replace cached report descriptor with top level driver provided one.
709  *
710  * It deletes all hidbus children except caller and enumerates them again after
711  * new descriptor has been registered. Currently it can not be called from
712  * autoenumerated (by report's TLC) child device context as it results in child
713  * duplication. To overcome this limitation hid_set_report_descr() should be
714  * called from device_identify driver's handler with hidbus itself passed as
715  * 'device_t dev' parameter.
716  */
717 int
718 hid_set_report_descr(device_t dev, const void *data, hid_size_t len)
719 {
720 	struct hid_rdesc_info rdesc;
721 	device_t bus;
722 	struct hidbus_softc *sc;
723 	bool is_bus;
724 	int error;
725 
726 	bus_topo_assert();
727 
728 	is_bus = device_get_devclass(dev) == devclass_find("hidbus");
729 	bus = is_bus ? dev : device_get_parent(dev);
730 	sc = device_get_softc(bus);
731 
732 	/*
733 	 * Do not overload already overloaded report descriptor in
734 	 * device_identify handler. It causes infinite recursion loop.
735 	 */
736 	if (is_bus && sc->overloaded)
737 		return(0);
738 
739 	DPRINTFN(5, "len=%d\n", len);
740 	DPRINTFN(5, "data = %*D\n", len, data, " ");
741 
742 	error = hidbus_fill_rdesc_info(&rdesc, data, len);
743 	if (error != 0)
744 		return (error);
745 
746 	error = hidbus_detach_children(dev);
747 	if (error != 0)
748 		return(error);
749 
750 	/* Make private copy to handle a case of dynamicaly allocated data. */
751 	rdesc.data = malloc(len, M_DEVBUF, M_ZERO | M_WAITOK);
752 	bcopy(data, rdesc.data, len);
753 	sc->overloaded = true;
754 	free(sc->rdesc.data, M_DEVBUF);
755 	bcopy(&rdesc, &sc->rdesc, sizeof(struct hid_rdesc_info));
756 
757 	error = hidbus_attach_children(bus);
758 
759 	return (error);
760 }
761 
762 static int
763 hidbus_get_rdesc(device_t dev, device_t child __unused, void *data,
764     hid_size_t len)
765 {
766 	return (hid_get_rdesc(dev, data, len));
767 }
768 
769 static int
770 hidbus_read(device_t dev, device_t child __unused, void *data,
771     hid_size_t maxlen, hid_size_t *actlen)
772 {
773 	return (hid_read(dev, data, maxlen, actlen));
774 }
775 
776 static int
777 hidbus_write(device_t dev, device_t child __unused, const void *data,
778     hid_size_t len)
779 {
780 	struct hidbus_softc *sc;
781 	uint8_t id;
782 
783 	sc = device_get_softc(dev);
784 	/*
785 	 * Output interrupt endpoint is often optional. If HID device
786 	 * does not provide it, send reports via control pipe.
787 	 */
788 	if (sc->nowrite) {
789 		/* try to extract the ID byte */
790 		id = (sc->rdesc.oid & (len > 0)) ? *(const uint8_t*)data : 0;
791 		return (hid_set_report(dev, data, len, HID_OUTPUT_REPORT, id));
792 	}
793 
794 	return (hid_write(dev, data, len));
795 }
796 
797 static int
798 hidbus_get_report(device_t dev, device_t child __unused, void *data,
799     hid_size_t maxlen, hid_size_t *actlen, uint8_t type, uint8_t id)
800 {
801 	return (hid_get_report(dev, data, maxlen, actlen, type, id));
802 }
803 
804 static int
805 hidbus_set_report(device_t dev, device_t child __unused, const void *data,
806     hid_size_t len, uint8_t type, uint8_t id)
807 {
808 	return (hid_set_report(dev, data, len, type, id));
809 }
810 
811 static int
812 hidbus_set_idle(device_t dev, device_t child __unused, uint16_t duration,
813     uint8_t id)
814 {
815 	return (hid_set_idle(dev, duration, id));
816 }
817 
818 static int
819 hidbus_set_protocol(device_t dev, device_t child __unused, uint16_t protocol)
820 {
821 	return (hid_set_protocol(dev, protocol));
822 }
823 
824 static int
825 hidbus_ioctl(device_t dev, device_t child __unused, unsigned long cmd,
826     uintptr_t data)
827 {
828 	return (hid_ioctl(dev, cmd, data));
829 }
830 
831 /*------------------------------------------------------------------------*
832  *	hidbus_lookup_id
833  *
834  * This functions takes an array of "struct hid_device_id" and tries
835  * to match the entries with the information in "struct hid_device_info".
836  *
837  * Return values:
838  * NULL: No match found.
839  * Else: Pointer to matching entry.
840  *------------------------------------------------------------------------*/
841 const struct hid_device_id *
842 hidbus_lookup_id(device_t dev, const struct hid_device_id *id, int nitems_id)
843 {
844 	const struct hid_device_id *id_end;
845 	const struct hid_device_info *info;
846 	int32_t usage;
847 	bool is_child;
848 
849 	if (id == NULL) {
850 		goto done;
851 	}
852 
853 	id_end = id + nitems_id;
854 	info = hid_get_device_info(dev);
855 	is_child = device_get_devclass(dev) != devclass_find("hidbus");
856 	if (is_child)
857 		usage = hidbus_get_usage(dev);
858 
859 	/*
860 	 * Keep on matching array entries until we find a match or
861 	 * until we reach the end of the matching array:
862 	 */
863 	for (; id != id_end; id++) {
864 
865 		if (is_child && (id->match_flag_page) &&
866 		    (id->page != HID_GET_USAGE_PAGE(usage))) {
867 			continue;
868 		}
869 		if (is_child && (id->match_flag_usage) &&
870 		    (id->usage != HID_GET_USAGE(usage))) {
871 			continue;
872 		}
873 		if ((id->match_flag_bus) &&
874 		    (id->idBus != info->idBus)) {
875 			continue;
876 		}
877 		if ((id->match_flag_vendor) &&
878 		    (id->idVendor != info->idVendor)) {
879 			continue;
880 		}
881 		if ((id->match_flag_product) &&
882 		    (id->idProduct != info->idProduct)) {
883 			continue;
884 		}
885 		if ((id->match_flag_ver_lo) &&
886 		    (id->idVersion_lo > info->idVersion)) {
887 			continue;
888 		}
889 		if ((id->match_flag_ver_hi) &&
890 		    (id->idVersion_hi < info->idVersion)) {
891 			continue;
892 		}
893 		if (id->match_flag_pnp &&
894 		    strncmp(id->idPnP, info->idPnP, HID_PNP_ID_SIZE) != 0) {
895 			continue;
896 		}
897 		/* We found a match! */
898 		return (id);
899 	}
900 
901 done:
902 	return (NULL);
903 }
904 
905 /*------------------------------------------------------------------------*
906  *	hidbus_lookup_driver_info - factored out code
907  *
908  * Return values:
909  *    0: Success
910  * Else: Failure
911  *------------------------------------------------------------------------*/
912 int
913 hidbus_lookup_driver_info(device_t child, const struct hid_device_id *id,
914     int nitems_id)
915 {
916 
917 	id = hidbus_lookup_id(child, id, nitems_id);
918 	if (id) {
919 		/* copy driver info */
920 		hidbus_set_driver_info(child, id->driver_info);
921 		return (0);
922 	}
923 	return (ENXIO);
924 }
925 
926 const struct hid_device_info *
927 hid_get_device_info(device_t dev)
928 {
929 	device_t bus;
930 
931 	bus = device_get_devclass(dev) == devclass_find("hidbus") ?
932 	    dev : device_get_parent(dev);
933 
934 	return (device_get_ivars(bus));
935 }
936 
937 static device_method_t hidbus_methods[] = {
938 	/* device interface */
939 	DEVMETHOD(device_probe,		hidbus_probe),
940 	DEVMETHOD(device_attach,	hidbus_attach),
941 	DEVMETHOD(device_detach,	hidbus_detach),
942 	DEVMETHOD(device_suspend,	bus_generic_suspend),
943 	DEVMETHOD(device_resume,	bus_generic_resume),
944 
945 	/* bus interface */
946 	DEVMETHOD(bus_add_child,	hidbus_add_child),
947 	DEVMETHOD(bus_child_detached,	hidbus_child_detached),
948 	DEVMETHOD(bus_child_deleted,	hidbus_child_deleted),
949 	DEVMETHOD(bus_read_ivar,	hidbus_read_ivar),
950 	DEVMETHOD(bus_write_ivar,	hidbus_write_ivar),
951 	DEVMETHOD(bus_child_pnpinfo,	hidbus_child_pnpinfo),
952 	DEVMETHOD(bus_child_location,	hidbus_child_location),
953 
954 	/* hid interface */
955 	DEVMETHOD(hid_intr_start,	hidbus_intr_start),
956 	DEVMETHOD(hid_intr_stop,	hidbus_intr_stop),
957 	DEVMETHOD(hid_intr_poll,	hidbus_intr_poll),
958 	DEVMETHOD(hid_get_rdesc,	hidbus_get_rdesc),
959 	DEVMETHOD(hid_read,		hidbus_read),
960 	DEVMETHOD(hid_write,		hidbus_write),
961 	DEVMETHOD(hid_get_report,	hidbus_get_report),
962 	DEVMETHOD(hid_set_report,	hidbus_set_report),
963 	DEVMETHOD(hid_set_idle,		hidbus_set_idle),
964 	DEVMETHOD(hid_set_protocol,	hidbus_set_protocol),
965 	DEVMETHOD(hid_ioctl,		hidbus_ioctl),
966 
967 	DEVMETHOD_END
968 };
969 
970 driver_t hidbus_driver = {
971 	"hidbus",
972 	hidbus_methods,
973 	sizeof(struct hidbus_softc),
974 };
975 
976 MODULE_DEPEND(hidbus, hid, 1, 1, 1);
977 MODULE_VERSION(hidbus, 1);
978 DRIVER_MODULE(hidbus, hvhid, hidbus_driver, 0, 0);
979 DRIVER_MODULE(hidbus, iichid, hidbus_driver, 0, 0);
980 DRIVER_MODULE(hidbus, usbhid, hidbus_driver, 0, 0);
981