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