xref: /openbsd-src/sys/dev/usb/uhidev.c (revision 42ac1f71ddfc8f2b1ea1555399aa1e1ffc2faced)
1 /*	$OpenBSD: uhidev.c,v 1.107 2022/03/21 12:18:52 thfr Exp $	*/
2 /*	$NetBSD: uhidev.c,v 1.14 2003/03/11 16:44:00 augustss Exp $	*/
3 
4 /*
5  * Copyright (c) 2001 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (lennart@augustsson.net) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  */
33 
34 /*
35  * HID spec: https://www.usb.org/sites/default/files/hid1_11.pdf
36  */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/malloc.h>
42 #include <sys/signalvar.h>
43 #include <sys/device.h>
44 #include <sys/ioctl.h>
45 #include <sys/conf.h>
46 
47 #include <machine/bus.h>
48 
49 #include <dev/usb/usb.h>
50 #include <dev/usb/usbhid.h>
51 
52 #include <dev/usb/usbdevs.h>
53 #include <dev/usb/usbdi.h>
54 #include <dev/usb/usbdi_util.h>
55 #include <dev/usb/usbdivar.h>
56 #include <dev/usb/usb_mem.h>
57 #include <dev/usb/usb_quirks.h>
58 
59 #include <dev/usb/uhidev.h>
60 
61 #ifndef SMALL_KERNEL
62 /* Replacement report descriptors for devices shipped with broken ones */
63 #include <dev/usb/uhid_rdesc.h>
64 int uhidev_use_rdesc(struct uhidev_softc *, usb_interface_descriptor_t *,
65 		int, int, void **, int *);
66 #define UISUBCLASS_XBOX360_CONTROLLER	0x5d
67 #define UIPROTO_XBOX360_GAMEPAD		0x01
68 #define UISUBCLASS_XBOXONE_CONTROLLER	0x47
69 #define UIPROTO_XBOXONE_GAMEPAD		0xd0
70 #endif /* !SMALL_KERNEL */
71 
72 #define DEVNAME(sc)		((sc)->sc_dev.dv_xname)
73 
74 #ifdef UHIDEV_DEBUG
75 #define DPRINTF(x)	do { if (uhidevdebug) printf x; } while (0)
76 #define DPRINTFN(n,x)	do { if (uhidevdebug>(n)) printf x; } while (0)
77 int	uhidevdebug = 0;
78 #else
79 #define DPRINTF(x)
80 #define DPRINTFN(n,x)
81 #endif
82 
83 struct uhidev_async_info {
84 	void (*callback)(void *priv, int id, void *data, int len);
85 	void *priv;
86 	void *data;
87 	int id;
88 };
89 
90 void uhidev_intr(struct usbd_xfer *, void *, usbd_status);
91 
92 int uhidev_maxrepid(void *buf, int len);
93 int uhidevprint(void *aux, const char *pnp);
94 
95 int uhidev_match(struct device *, void *, void *);
96 void uhidev_attach(struct device *, struct device *, void *);
97 int uhidev_detach(struct device *, int);
98 int uhidev_activate(struct device *, int);
99 
100 void uhidev_get_report_async_cb(struct usbd_xfer *, void *, usbd_status);
101 void uhidev_set_report_async_cb(struct usbd_xfer *, void *, usbd_status);
102 
103 struct cfdriver uhidev_cd = {
104 	NULL, "uhidev", DV_DULL
105 };
106 
107 const struct cfattach uhidev_ca = {
108 	sizeof(struct uhidev_softc), uhidev_match, uhidev_attach,
109 	uhidev_detach, uhidev_activate,
110 };
111 
112 int
113 uhidev_match(struct device *parent, void *match, void *aux)
114 {
115 	struct usb_attach_arg *uaa = aux;
116 	usb_interface_descriptor_t *id;
117 
118 	if (uaa->iface == NULL)
119 		return (UMATCH_NONE);
120 	id = usbd_get_interface_descriptor(uaa->iface);
121 	if (id == NULL)
122 		return (UMATCH_NONE);
123 #ifndef SMALL_KERNEL
124 	if (id->bInterfaceClass == UICLASS_VENDOR &&
125 	    id->bInterfaceSubClass == UISUBCLASS_XBOX360_CONTROLLER &&
126 	    id->bInterfaceProtocol == UIPROTO_XBOX360_GAMEPAD)
127 		return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
128 	if (id->bInterfaceClass == UICLASS_VENDOR &&
129 	    id->bInterfaceSubClass == UISUBCLASS_XBOXONE_CONTROLLER &&
130 	    id->bInterfaceProtocol == UIPROTO_XBOXONE_GAMEPAD) {
131 		return (UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO);
132 	}
133 #endif /* !SMALL_KERNEL */
134 	if (id->bInterfaceClass != UICLASS_HID)
135 		return (UMATCH_NONE);
136 	if (usbd_get_quirks(uaa->device)->uq_flags & UQ_BAD_HID)
137 		return (UMATCH_NONE);
138 
139 	return (UMATCH_IFACECLASS_GENERIC);
140 }
141 
142 void
143 uhidev_attach(struct device *parent, struct device *self, void *aux)
144 {
145 	struct uhidev_softc *sc = (struct uhidev_softc *)self;
146 	struct usb_attach_arg *uaa = aux;
147 	usb_interface_descriptor_t *id;
148 	usb_endpoint_descriptor_t *ed;
149 	struct uhidev_attach_arg uha;
150 	int nrepid, repid, repsz;
151 	int i;
152 	void *desc = NULL;
153 	int size = 0;
154 	struct device *dev;
155 
156 	sc->sc_udev = uaa->device;
157 	sc->sc_iface = uaa->iface;
158 	sc->sc_ifaceno = uaa->ifaceno;
159 	id = usbd_get_interface_descriptor(sc->sc_iface);
160 
161 	sc->sc_iep_addr = sc->sc_oep_addr = -1;
162 	for (i = 0; i < id->bNumEndpoints; i++) {
163 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
164 		if (ed == NULL) {
165 			printf("%s: could not read endpoint descriptor\n",
166 			    DEVNAME(sc));
167 			return;
168 		}
169 
170 		DPRINTFN(10,("uhidev_attach: bLength=%d bDescriptorType=%d "
171 		    "bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d"
172 		    " bInterval=%d\n",
173 		    ed->bLength, ed->bDescriptorType,
174 		    ed->bEndpointAddress & UE_ADDR,
175 		    UE_GET_DIR(ed->bEndpointAddress)==UE_DIR_IN? "in" : "out",
176 		    UE_GET_XFERTYPE(ed->bmAttributes),
177 		    UGETW(ed->wMaxPacketSize), ed->bInterval));
178 
179 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
180 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
181 			sc->sc_iep_addr = ed->bEndpointAddress;
182 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
183 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_INTERRUPT) {
184 			sc->sc_oep_addr = ed->bEndpointAddress;
185 		} else {
186 			printf("%s: unexpected endpoint\n", DEVNAME(sc));
187 			return;
188 		}
189 	}
190 
191 	/*
192 	 * Check that we found an input interrupt endpoint.
193 	 * The output interrupt endpoint is optional
194 	 */
195 	if (sc->sc_iep_addr == -1) {
196 		printf("%s: no input interrupt endpoint\n", DEVNAME(sc));
197 		return;
198 	}
199 
200 #ifndef SMALL_KERNEL
201 	if (uhidev_use_rdesc(sc, id, uaa->vendor, uaa->product, &desc, &size))
202 		return;
203 #endif /* !SMALL_KERNEL */
204 
205 	if (desc == NULL) {
206 		struct usb_hid_descriptor *hid;
207 
208 		hid = usbd_get_hid_descriptor(sc->sc_udev, id);
209 		if (hid == NULL) {
210 			printf("%s: no HID descriptor\n", DEVNAME(sc));
211 			return;
212 		}
213 		size = UGETW(hid->descrs[0].wDescriptorLength);
214 		desc = malloc(size, M_USBDEV, M_NOWAIT);
215 		if (desc == NULL) {
216 			printf("%s: no memory\n", DEVNAME(sc));
217 			return;
218 		}
219 		if (usbd_get_report_descriptor(sc->sc_udev, sc->sc_ifaceno,
220 		    desc, size)) {
221 			printf("%s: no report descriptor\n", DEVNAME(sc));
222 			free(desc, M_USBDEV, size);
223 			return;
224 		}
225 	}
226 
227 	sc->sc_repdesc = desc;
228 	sc->sc_repdesc_size = size;
229 
230 	nrepid = uhidev_maxrepid(desc, size);
231 	if (nrepid < 0)
232 		return;
233 	printf("%s: iclass %d/%d", DEVNAME(sc), id->bInterfaceClass,
234 	    id->bInterfaceSubClass);
235 	if (nrepid > 0)
236 		printf(", %d report id%s", nrepid, nrepid > 1 ? "s" : "");
237 	printf("\n");
238 	nrepid++;
239 	sc->sc_subdevs = mallocarray(nrepid, sizeof(struct uhidev *),
240 	    M_USBDEV, M_NOWAIT | M_ZERO);
241 	if (sc->sc_subdevs == NULL) {
242 		printf("%s: no memory\n", DEVNAME(sc));
243 		return;
244 	}
245 	sc->sc_nrepid = nrepid;
246 	sc->sc_isize = 0;
247 
248 	for (repid = 0; repid < nrepid; repid++) {
249 		repsz = hid_report_size(desc, size, hid_input, repid);
250 		DPRINTF(("uhidev_match: repid=%d, repsz=%d\n", repid, repsz));
251 		if (repsz > sc->sc_isize)
252 			sc->sc_isize = repsz;
253 	}
254 	sc->sc_isize += (nrepid != 1);	/* one byte for the report ID */
255 	DPRINTF(("uhidev_attach: isize=%d\n", sc->sc_isize));
256 
257 	uha.uaa = uaa;
258 	uha.parent = sc;
259 	uha.reportid = 0;
260 	uha.nreports = nrepid;
261 	uha.claimed = malloc(nrepid, M_TEMP, M_WAITOK|M_ZERO);
262 
263 	/* Look for a driver claiming multiple report IDs first. */
264 	dev = config_found_sm(self, &uha, NULL, NULL);
265 	if (dev != NULL) {
266 		int nclaimed = 0;
267 
268 		for (repid = 0; repid < nrepid; repid++) {
269 			if (!uha.claimed[repid])
270 				continue;
271 
272 			nclaimed++;
273 			/*
274 			 * Could already be assigned by uhidev_set_report_dev().
275 			 */
276 			if (sc->sc_subdevs[repid] == NULL)
277 				sc->sc_subdevs[repid] = (struct uhidev *)dev;
278 		}
279 		KASSERTMSG(nclaimed > 0, "%s did not claim any report ids",
280 		    dev->dv_xname);
281 	}
282 
283 	free(uha.claimed, M_TEMP, nrepid);
284 	uha.claimed = NULL;
285 
286 	for (repid = 0; repid < nrepid; repid++) {
287 		DPRINTF(("%s: try repid=%d\n", __func__, repid));
288 		if (hid_report_size(desc, size, hid_input, repid) == 0 &&
289 		    hid_report_size(desc, size, hid_output, repid) == 0 &&
290 		    hid_report_size(desc, size, hid_feature, repid) == 0)
291 			continue;
292 
293 		/* Could already be assigned by uhidev_set_report_dev(). */
294 		if (sc->sc_subdevs[repid] != NULL)
295 			continue;
296 
297 		uha.reportid = repid;
298 		dev = config_found_sm(self, &uha, uhidevprint, NULL);
299 		sc->sc_subdevs[repid] = (struct uhidev *)dev;
300 	}
301 }
302 
303 #ifndef SMALL_KERNEL
304 int
305 uhidev_use_rdesc(struct uhidev_softc *sc, usb_interface_descriptor_t *id,
306 		int vendor, int product, void **descp, int *sizep)
307 {
308 	static uByte reportbuf[] = {2, 2};
309 	const void *descptr = NULL;
310 	void *desc;
311 	int size;
312 
313 	if (vendor == USB_VENDOR_WACOM) {
314 		/* The report descriptor for the Wacom Graphire is broken. */
315 		switch (product) {
316 		case USB_PRODUCT_WACOM_GRAPHIRE:
317 			size = sizeof(uhid_graphire_report_descr);
318 			descptr = uhid_graphire_report_descr;
319 			break;
320 		case USB_PRODUCT_WACOM_GRAPHIRE3_4X5:
321 		case USB_PRODUCT_WACOM_GRAPHIRE4_4X5:
322 			uhidev_set_report(sc, UHID_FEATURE_REPORT,
323 			    2, &reportbuf, sizeof(reportbuf));
324 			size = sizeof(uhid_graphire3_4x5_report_descr);
325 			descptr = uhid_graphire3_4x5_report_descr;
326 			break;
327 		default:
328 			break;
329 		}
330 	} else if ((id->bInterfaceClass == UICLASS_VENDOR &&
331 		   id->bInterfaceSubClass == UISUBCLASS_XBOX360_CONTROLLER &&
332 		   id->bInterfaceProtocol == UIPROTO_XBOX360_GAMEPAD)) {
333 		/* The Xbox 360 gamepad has no report descriptor. */
334 		size = sizeof(uhid_xb360gp_report_descr);
335 		descptr = uhid_xb360gp_report_descr;
336 	} else if ((id->bInterfaceClass == UICLASS_VENDOR &&
337 		    id->bInterfaceSubClass == UISUBCLASS_XBOXONE_CONTROLLER &&
338 		    id->bInterfaceProtocol == UIPROTO_XBOXONE_GAMEPAD)) {
339 		sc->sc_flags |= UHIDEV_F_XB1;
340 		/* The Xbox One gamepad has no report descriptor. */
341 		size = sizeof(uhid_xbonegp_report_descr);
342 		descptr = uhid_xbonegp_report_descr;
343 	}
344 
345 	if (descptr) {
346 		desc = malloc(size, M_USBDEV, M_NOWAIT);
347 		if (desc == NULL)
348 			return (ENOMEM);
349 
350 		memcpy(desc, descptr, size);
351 
352 		*descp = desc;
353 		*sizep = size;
354 	}
355 
356 	return (0);
357 }
358 #endif /* !SMALL_KERNEL */
359 
360 int
361 uhidev_maxrepid(void *buf, int len)
362 {
363 	struct hid_data *d;
364 	struct hid_item h;
365 	int maxid;
366 
367 	maxid = -1;
368 	h.report_ID = 0;
369 	for (d = hid_start_parse(buf, len, hid_none); hid_get_item(d, &h); )
370 		if (h.report_ID > maxid)
371 			maxid = h.report_ID;
372 	hid_end_parse(d);
373 	return (maxid);
374 }
375 
376 int
377 uhidevprint(void *aux, const char *pnp)
378 {
379 	struct uhidev_attach_arg *uha = aux;
380 
381 	if (pnp)
382 		printf("uhid at %s", pnp);
383 	if (uha->reportid != 0)
384 		printf(" reportid %d", uha->reportid);
385 	return (UNCONF);
386 }
387 
388 int
389 uhidev_activate(struct device *self, int act)
390 {
391 	struct uhidev_softc *sc = (struct uhidev_softc *)self;
392 	int i, j, already, rv = 0, r;
393 
394 	switch (act) {
395 	case DVACT_DEACTIVATE:
396 		for (i = 0; i < sc->sc_nrepid; i++) {
397 			if (sc->sc_subdevs[i] == NULL)
398 				continue;
399 
400 			/*
401 			 * Only notify devices attached to multiple report ids
402 			 * once.
403 			 */
404 			for (already = 0, j = 0; j < i; j++) {
405 				if (sc->sc_subdevs[i] == sc->sc_subdevs[j]) {
406 					already = 1;
407 					break;
408 				}
409 			}
410 
411 			if (!already) {
412 				r = config_deactivate(
413 				    &sc->sc_subdevs[i]->sc_dev);
414 				if (r && r != EOPNOTSUPP)
415 					rv = r;
416 			}
417 		}
418 		usbd_deactivate(sc->sc_udev);
419 		break;
420 	}
421 	return (rv);
422 }
423 
424 int
425 uhidev_detach(struct device *self, int flags)
426 {
427 	struct uhidev_softc *sc = (struct uhidev_softc *)self;
428 	int i, j, rv = 0;
429 
430 	DPRINTF(("uhidev_detach: sc=%p flags=%d\n", sc, flags));
431 
432 	if (sc->sc_opipe != NULL) {
433 		usbd_close_pipe(sc->sc_opipe);
434 		sc->sc_opipe = NULL;
435 	}
436 
437 	if (sc->sc_ipipe != NULL) {
438 		usbd_close_pipe(sc->sc_ipipe);
439 		sc->sc_ipipe = NULL;
440 	}
441 
442 	if (sc->sc_repdesc != NULL)
443 		free(sc->sc_repdesc, M_USBDEV, sc->sc_repdesc_size);
444 
445 	for (i = 0; i < sc->sc_nrepid; i++) {
446 		if (sc->sc_subdevs[i] == NULL)
447 			continue;
448 
449 		rv |= config_detach(&sc->sc_subdevs[i]->sc_dev, flags);
450 
451 		/*
452 		 * Nullify without detaching any other instances of this device
453 		 * found on other report ids.
454 		 */
455 		for (j = i + 1; j < sc->sc_nrepid; j++) {
456 			if (sc->sc_subdevs[i] == sc->sc_subdevs[j])
457 				sc->sc_subdevs[j] = NULL;
458 		}
459 
460 		sc->sc_subdevs[i] = NULL;
461 	}
462 	free(sc->sc_subdevs, M_USBDEV, sc->sc_nrepid * sizeof(struct uhidev *));
463 
464 	return (rv);
465 }
466 
467 void
468 uhidev_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
469 {
470 	struct uhidev_softc *sc = addr;
471 	struct uhidev *scd;
472 	u_char *p;
473 	u_int rep;
474 	u_int32_t cc;
475 
476 	if (usbd_is_dying(sc->sc_udev))
477 		return;
478 
479 	usbd_get_xfer_status(xfer, NULL, NULL, &cc, NULL);
480 
481 #ifdef UHIDEV_DEBUG
482 	if (uhidevdebug > 5) {
483 		u_int32_t i;
484 
485 		DPRINTF(("uhidev_intr: status=%d cc=%d\n", status, cc));
486 		DPRINTF(("uhidev_intr: data ="));
487 		for (i = 0; i < cc; i++)
488 			DPRINTF((" %02x", sc->sc_ibuf[i]));
489 		DPRINTF(("\n"));
490 	}
491 #endif
492 
493 	if (status == USBD_CANCELLED || status == USBD_IOERROR)
494 		return;
495 
496 	if (status != USBD_NORMAL_COMPLETION) {
497 		DPRINTF(("%s: interrupt status=%d\n", DEVNAME(sc), status));
498 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
499 		return;
500 	}
501 
502 	p = sc->sc_ibuf;
503 	if (sc->sc_nrepid != 1)
504 		rep = *p++, cc--;
505 	else
506 		rep = 0;
507 	if (rep >= sc->sc_nrepid) {
508 		printf("uhidev_intr: bad repid %d\n", rep);
509 		return;
510 	}
511 	scd = sc->sc_subdevs[rep];
512 	DPRINTFN(5,("uhidev_intr: rep=%d, scd=%p state=0x%x\n",
513 		    rep, scd, scd ? scd->sc_state : 0));
514 	if (scd == NULL || !(scd->sc_state & UHIDEV_OPEN))
515 		return;
516 
517 	scd->sc_intr(scd, p, cc);
518 }
519 
520 void
521 uhidev_get_report_desc(struct uhidev_softc *sc, void **desc, int *size)
522 {
523 	*desc = sc->sc_repdesc;
524 	*size = sc->sc_repdesc_size;
525 }
526 
527 int
528 uhidev_open(struct uhidev *scd)
529 {
530 	struct uhidev_softc *sc = scd->sc_parent;
531 	usbd_status err;
532 	int error;
533 
534 	DPRINTF(("uhidev_open: open pipe, state=%d refcnt=%d\n",
535 		 scd->sc_state, sc->sc_refcnt));
536 
537 	if (scd->sc_state & UHIDEV_OPEN)
538 		return (EBUSY);
539 	scd->sc_state |= UHIDEV_OPEN;
540 	if (sc->sc_refcnt++)
541 		return (0);
542 
543 	if (sc->sc_isize == 0)
544 		return (0);
545 
546 	sc->sc_ibuf = malloc(sc->sc_isize, M_USBDEV, M_WAITOK);
547 
548 	/* Set up input interrupt pipe. */
549 	DPRINTF(("uhidev_open: isize=%d, ep=0x%02x\n", sc->sc_isize,
550 	    sc->sc_iep_addr));
551 
552 	err = usbd_open_pipe_intr(sc->sc_iface, sc->sc_iep_addr,
553 		  USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_ibuf,
554 		  sc->sc_isize, uhidev_intr, USBD_DEFAULT_INTERVAL);
555 	if (err != USBD_NORMAL_COMPLETION) {
556 		DPRINTF(("uhidopen: usbd_open_pipe_intr failed, "
557 		    "error=%d\n", err));
558 		error = EIO;
559 		goto out1;
560 	}
561 
562 	DPRINTF(("uhidev_open: sc->sc_ipipe=%p\n", sc->sc_ipipe));
563 
564 	sc->sc_ixfer = usbd_alloc_xfer(sc->sc_udev);
565 	if (sc->sc_ixfer == NULL) {
566 		DPRINTF(("uhidev_open: couldn't allocate an xfer\n"));
567 		error = ENOMEM;
568 		goto out1; // xxxx
569 	}
570 
571 	/*
572 	 * Set up output interrupt pipe if an output interrupt endpoint
573 	 * exists.
574 	 */
575 	if (sc->sc_oep_addr != -1) {
576 		DPRINTF(("uhidev_open: oep=0x%02x\n", sc->sc_oep_addr));
577 
578 		err = usbd_open_pipe(sc->sc_iface, sc->sc_oep_addr,
579 		    0, &sc->sc_opipe);
580 		if (err != USBD_NORMAL_COMPLETION) {
581 			DPRINTF(("uhidev_open: usbd_open_pipe failed, "
582 			    "error=%d\n", err));
583 			error = EIO;
584 			goto out2;
585 		}
586 
587 		DPRINTF(("uhidev_open: sc->sc_opipe=%p\n", sc->sc_opipe));
588 
589 		sc->sc_oxfer = usbd_alloc_xfer(sc->sc_udev);
590 		if (sc->sc_oxfer == NULL) {
591 			DPRINTF(("uhidev_open: couldn't allocate an xfer\n"));
592 			error = ENOMEM;
593 			goto out3;
594 		}
595 
596 		sc->sc_owxfer = usbd_alloc_xfer(sc->sc_udev);
597 		if (sc->sc_owxfer == NULL) {
598 			DPRINTF(("uhidev_open: couldn't allocate owxfer\n"));
599 			error = ENOMEM;
600 			goto out3;
601 		}
602 
603 #ifndef SMALL_KERNEL
604 		/* XBox One controller initialization */
605 		if (sc->sc_flags & UHIDEV_F_XB1) {
606 			uint8_t init_data[] = { 0x05, 0x20, 0x00, 0x01, 0x00 };
607 			size_t init_data_len = sizeof(init_data);
608 			usbd_setup_xfer(sc->sc_oxfer, sc->sc_opipe, 0,
609 			    init_data, init_data_len,
610 			    USBD_SYNCHRONOUS | USBD_CATCH, USBD_NO_TIMEOUT,
611 			    NULL);
612 			err = usbd_transfer(sc->sc_oxfer);
613 			if (err != USBD_NORMAL_COMPLETION) {
614 				DPRINTF(("uhidev_open: xb1 init failed, "
615 				"error=%d\n", err));
616 				error = EIO;
617 				goto out3;
618 			}
619 		}
620 #endif /* !SMALL_KERNEL */
621 	}
622 
623 	return (0);
624 
625 out3:
626 	/* Abort output pipe */
627 	usbd_close_pipe(sc->sc_opipe);
628 out2:
629 	/* Abort input pipe */
630 	usbd_close_pipe(sc->sc_ipipe);
631 out1:
632 	DPRINTF(("uhidev_open: failed in someway"));
633 	free(sc->sc_ibuf, M_USBDEV, sc->sc_isize);
634 	sc->sc_ibuf = NULL;
635 	scd->sc_state &= ~UHIDEV_OPEN;
636 	sc->sc_refcnt = 0;
637 	sc->sc_ipipe = NULL;
638 	sc->sc_opipe = NULL;
639 	if (sc->sc_oxfer != NULL) {
640 		usbd_free_xfer(sc->sc_oxfer);
641 		sc->sc_oxfer = NULL;
642 	}
643 	if (sc->sc_owxfer != NULL) {
644 		usbd_free_xfer(sc->sc_owxfer);
645 		sc->sc_owxfer = NULL;
646 	}
647 	if (sc->sc_ixfer != NULL) {
648 		usbd_free_xfer(sc->sc_ixfer);
649 		sc->sc_ixfer = NULL;
650 	}
651 	return (error);
652 }
653 
654 void
655 uhidev_close(struct uhidev *scd)
656 {
657 	struct uhidev_softc *sc = scd->sc_parent;
658 
659 	if (!(scd->sc_state & UHIDEV_OPEN))
660 		return;
661 	scd->sc_state &= ~UHIDEV_OPEN;
662 	if (--sc->sc_refcnt)
663 		return;
664 	DPRINTF(("uhidev_close: close pipe\n"));
665 
666 	/* Disable interrupts. */
667 	if (sc->sc_opipe != NULL) {
668 		usbd_close_pipe(sc->sc_opipe);
669 		sc->sc_opipe = NULL;
670 	}
671 
672 	if (sc->sc_ipipe != NULL) {
673 		usbd_close_pipe(sc->sc_ipipe);
674 		sc->sc_ipipe = NULL;
675 	}
676 
677 	if (sc->sc_oxfer != NULL) {
678 		usbd_free_xfer(sc->sc_oxfer);
679 		sc->sc_oxfer = NULL;
680 	}
681 
682 	if (sc->sc_owxfer != NULL) {
683 		usbd_free_xfer(sc->sc_owxfer);
684 		sc->sc_owxfer = NULL;
685 	}
686 
687 	if (sc->sc_ixfer != NULL) {
688 		usbd_free_xfer(sc->sc_ixfer);
689 		sc->sc_ixfer = NULL;
690 	}
691 
692 	if (sc->sc_ibuf != NULL) {
693 		free(sc->sc_ibuf, M_USBDEV, sc->sc_isize);
694 		sc->sc_ibuf = NULL;
695 	}
696 }
697 
698 int
699 uhidev_report_type_conv(int hid_type_id)
700 {
701 	switch (hid_type_id) {
702 	case hid_input:
703 		return UHID_INPUT_REPORT;
704 	case hid_output:
705 		return UHID_OUTPUT_REPORT;
706 	case hid_feature:
707 		return UHID_FEATURE_REPORT;
708 	default:
709 		return -1;
710 	}
711 }
712 
713 int
714 uhidev_set_report(struct uhidev_softc *sc, int type, int id, void *data,
715     int len)
716 {
717 	usb_device_request_t req;
718 	char *buf = data;
719 	int actlen = len;
720 
721 	/* Prepend the reportID. */
722 	if (id > 0) {
723 		len++;
724 		buf = malloc(len, M_TEMP, M_WAITOK);
725 		buf[0] = id;
726 		memcpy(buf + 1, data, len - 1);
727 	}
728 
729 	if (sc->sc_opipe != NULL) {
730 		usbd_setup_xfer(sc->sc_owxfer, sc->sc_opipe, 0, buf, len,
731 		    USBD_SYNCHRONOUS | USBD_CATCH, 0, NULL);
732 		if (usbd_transfer(sc->sc_owxfer)) {
733 			usbd_clear_endpoint_stall(sc->sc_opipe);
734 			actlen = -1;
735 		}
736 	} else {
737 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
738 		req.bRequest = UR_SET_REPORT;
739 		USETW2(req.wValue, type, id);
740 		USETW(req.wIndex, sc->sc_ifaceno);
741 		USETW(req.wLength, len);
742 
743 		if (usbd_do_request(sc->sc_udev, &req, buf))
744 			actlen = -1;
745 	}
746 
747 	if (id > 0)
748 		free(buf, M_TEMP, len);
749 
750 	return (actlen);
751 }
752 
753 void
754 uhidev_set_report_async_cb(struct usbd_xfer *xfer, void *priv, usbd_status err)
755 {
756 	struct uhidev_softc *sc = priv;
757 
758 	if (err == USBD_STALLED)
759 		usbd_clear_endpoint_stall_async(sc->sc_opipe);
760 	usbd_free_xfer(xfer);
761 }
762 
763 int
764 uhidev_set_report_async(struct uhidev_softc *sc, int type, int id, void *data,
765     int len)
766 {
767 	struct usbd_xfer *xfer;
768 	usb_device_request_t req;
769 	int actlen = len;
770 	char *buf;
771 
772 	xfer = usbd_alloc_xfer(sc->sc_udev);
773 	if (xfer == NULL)
774 		return (-1);
775 
776 	if (id > 0)
777 		len++;
778 
779 	buf = usbd_alloc_buffer(xfer, len);
780 	if (buf == NULL) {
781 		usbd_free_xfer(xfer);
782 		return (-1);
783 	}
784 
785 	/* Prepend the reportID. */
786 	if (id > 0) {
787 		buf[0] = id;
788 		memcpy(buf + 1, data, len - 1);
789 	} else {
790 		memcpy(buf, data, len);
791 	}
792 
793 	if (sc->sc_opipe != NULL) {
794 		usbd_setup_xfer(xfer, sc->sc_opipe, sc, buf, len,
795 		    USBD_NO_COPY, USBD_DEFAULT_TIMEOUT,
796 		    uhidev_set_report_async_cb);
797 		if (usbd_transfer(xfer)) {
798 			usbd_clear_endpoint_stall_async(sc->sc_opipe);
799 			actlen = -1;
800 		}
801 	} else {
802 		req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
803 		req.bRequest = UR_SET_REPORT;
804 		USETW2(req.wValue, type, id);
805 		USETW(req.wIndex, sc->sc_ifaceno);
806 		USETW(req.wLength, len);
807 		if (usbd_request_async(xfer, &req, NULL, NULL))
808 			actlen = -1;
809 	}
810 
811 	return (actlen);
812 }
813 
814 int
815 uhidev_get_report(struct uhidev_softc *sc, int type, int id, void *data,
816     int len)
817 {
818 	usb_device_request_t req;
819 	char *buf = data;
820 	usbd_status err;
821 	int actlen;
822 
823 	if (id > 0) {
824 		len++;
825 		buf = malloc(len, M_TEMP, M_WAITOK|M_ZERO);
826 	}
827 
828 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
829 	req.bRequest = UR_GET_REPORT;
830 	USETW2(req.wValue, type, id);
831 	USETW(req.wIndex, sc->sc_ifaceno);
832 	USETW(req.wLength, len);
833 
834 	err = usbd_do_request_flags(sc->sc_udev, &req, buf, 0, &actlen,
835 	    USBD_DEFAULT_TIMEOUT);
836 	if (err != USBD_NORMAL_COMPLETION && err != USBD_SHORT_XFER)
837 		actlen = -1;
838 
839 	/* Skip the reportID. */
840 	if (id > 0) {
841 		memcpy(data, buf + 1, len - 1);
842 		free(buf, M_TEMP, len);
843 	}
844 
845 	return (actlen);
846 }
847 
848 void
849 uhidev_get_report_async_cb(struct usbd_xfer *xfer, void *priv, usbd_status err)
850 {
851 	struct uhidev_async_info *info = priv;
852 	char *buf;
853 	int len = -1;
854 
855 	if (!usbd_is_dying(xfer->pipe->device)) {
856 		if (err == USBD_NORMAL_COMPLETION || err == USBD_SHORT_XFER) {
857 			len = xfer->actlen;
858 			buf = KERNADDR(&xfer->dmabuf, 0);
859 			if (info->id > 0) {
860 				len--;
861 				memcpy(info->data, buf + 1, len);
862 			} else {
863 				memcpy(info->data, buf, len);
864 			}
865 		}
866 		info->callback(info->priv, info->id, info->data, len);
867 	}
868 	free(info, M_TEMP, sizeof(*info));
869 	usbd_free_xfer(xfer);
870 }
871 
872 int
873 uhidev_get_report_async(struct uhidev_softc *sc, int type, int id, void *data,
874     int len, void *priv, void (*callback)(void *, int, void *, int))
875 {
876 	struct usbd_xfer *xfer;
877 	usb_device_request_t req;
878 	struct uhidev_async_info *info;
879 	int actlen = len;
880 	char *buf;
881 
882 	xfer = usbd_alloc_xfer(sc->sc_udev);
883 	if (xfer == NULL)
884 		return (-1);
885 
886 	if (id > 0)
887 		len++;
888 
889 	buf = usbd_alloc_buffer(xfer, len);
890 	if (buf == NULL) {
891 		usbd_free_xfer(xfer);
892 		return (-1);
893 	}
894 
895 	info = malloc(sizeof(*info), M_TEMP, M_NOWAIT);
896 	if (info == NULL) {
897 		usbd_free_xfer(xfer);
898 		return (-1);
899 	}
900 
901 	info->callback = callback;
902 	info->priv = priv;
903 	info->data = data;
904 	info->id = id;
905 
906 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
907 	req.bRequest = UR_GET_REPORT;
908 	USETW2(req.wValue, type, id);
909 	USETW(req.wIndex, sc->sc_ifaceno);
910 	USETW(req.wLength, len);
911 
912 	if (usbd_request_async(xfer, &req, info, uhidev_get_report_async_cb)) {
913 		free(info, M_TEMP, sizeof(*info));
914 		actlen = -1;
915 	}
916 
917 	return (actlen);
918 }
919 
920 usbd_status
921 uhidev_write(struct uhidev_softc *sc, void *data, int len)
922 {
923 	usbd_status error;
924 
925 	DPRINTF(("uhidev_write: data=%p, len=%d\n", data, len));
926 
927 	if (sc->sc_opipe == NULL)
928 		return USBD_INVAL;
929 
930 #ifdef UHIDEV_DEBUG
931 	if (uhidevdebug > 50) {
932 
933 		u_int32_t i;
934 		u_int8_t *d = data;
935 
936 		DPRINTF(("uhidev_write: data ="));
937 		for (i = 0; i < len; i++)
938 			DPRINTF((" %02x", d[i]));
939 		DPRINTF(("\n"));
940 	}
941 #endif
942 	usbd_setup_xfer(sc->sc_owxfer, sc->sc_opipe, 0, data, len,
943 	    USBD_SYNCHRONOUS | USBD_CATCH, 0, NULL);
944 	error = usbd_transfer(sc->sc_owxfer);
945 	if (error)
946 		usbd_clear_endpoint_stall(sc->sc_opipe);
947 
948 	return (error);
949 }
950 
951 int
952 uhidev_ioctl(struct uhidev *sc, u_long cmd, caddr_t addr, int flag,
953     struct proc *p)
954 {
955 	struct usb_ctl_report_desc *rd;
956 	struct usb_ctl_report *re;
957 	int size;
958 	void *desc;
959 
960 	switch (cmd) {
961 	case USB_GET_REPORT_DESC:
962 		uhidev_get_report_desc(sc->sc_parent, &desc, &size);
963 		rd = (struct usb_ctl_report_desc *)addr;
964 		size = min(size, sizeof rd->ucrd_data);
965 		rd->ucrd_size = size;
966 		memcpy(rd->ucrd_data, desc, size);
967 		break;
968 	case USB_GET_REPORT:
969 		re = (struct usb_ctl_report *)addr;
970 		switch (re->ucr_report) {
971 		case UHID_INPUT_REPORT:
972 			size = sc->sc_isize;
973 			break;
974 		case UHID_OUTPUT_REPORT:
975 			size = sc->sc_osize;
976 			break;
977 		case UHID_FEATURE_REPORT:
978 			size = sc->sc_fsize;
979 			break;
980 		default:
981 			return EINVAL;
982 		}
983 		if (uhidev_get_report(sc->sc_parent, re->ucr_report,
984 		    sc->sc_report_id, re->ucr_data, size) != size)
985 			return EIO;
986 		break;
987 	case USB_SET_REPORT:
988 		re = (struct usb_ctl_report *)addr;
989 		switch (re->ucr_report) {
990 		case UHID_INPUT_REPORT:
991 			size = sc->sc_isize;
992 			break;
993 		case UHID_OUTPUT_REPORT:
994 			size = sc->sc_osize;
995 			break;
996 		case UHID_FEATURE_REPORT:
997 			size = sc->sc_fsize;
998 			break;
999 		default:
1000 			return EINVAL;
1001 		}
1002 		if (uhidev_set_report(sc->sc_parent, re->ucr_report,
1003 		    sc->sc_report_id, re->ucr_data, size) != size)
1004 			return EIO;
1005 		break;
1006 	case USB_GET_REPORT_ID:
1007 		*(int *)addr = sc->sc_report_id;
1008 		break;
1009 	default:
1010 		return -1;
1011 	}
1012 	return 0;
1013 }
1014 
1015 int
1016 uhidev_set_report_dev(struct uhidev_softc *sc, struct uhidev *dev, int repid)
1017 {
1018 	if ((dev->sc_state & UHIDEV_OPEN) == 0)
1019 		return ENODEV;
1020 	if (repid >= sc->sc_nrepid)
1021 		return EINVAL;
1022 
1023 	sc->sc_subdevs[repid] = dev;
1024 	return 0;
1025 }
1026