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