Home | History | Annotate | Line # | Download | only in usb
uhidev.c revision 1.82
      1 /*	$NetBSD: uhidev.c,v 1.82 2022/02/09 18:09:48 jakllsch Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2001, 2012 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Lennart Augustsson (lennart (at) augustsson.net) at
      9  * Carlstedt Research & Technology and Matthew R. Green (mrg (at) eterna.com.au).
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * HID spec: http://www.usb.org/developers/devclass_docs/HID1_11.pdf
     35  */
     36 
     37 #include <sys/cdefs.h>
     38 __KERNEL_RCSID(0, "$NetBSD: uhidev.c,v 1.82 2022/02/09 18:09:48 jakllsch Exp $");
     39 
     40 #ifdef _KERNEL_OPT
     41 #include "opt_usb.h"
     42 #endif
     43 
     44 #include <sys/param.h>
     45 #include <sys/types.h>
     46 
     47 #include <sys/conf.h>
     48 #include <sys/device.h>
     49 #include <sys/ioctl.h>
     50 #include <sys/kernel.h>
     51 #include <sys/kmem.h>
     52 #include <sys/lwp.h>
     53 #include <sys/rndsource.h>
     54 #include <sys/signalvar.h>
     55 #include <sys/systm.h>
     56 
     57 #include <dev/usb/usb.h>
     58 #include <dev/usb/usbhid.h>
     59 
     60 #include <dev/usb/usbdevs.h>
     61 #include <dev/usb/usbdi.h>
     62 #include <dev/usb/usbdi_util.h>
     63 #include <dev/usb/usb_quirks.h>
     64 
     65 #include <dev/usb/uhidev.h>
     66 #include <dev/hid/hid.h>
     67 
     68 /* Report descriptor for broken Wacom Graphire */
     69 #include <dev/usb/ugraphire_rdesc.h>
     70 /* Report descriptor for game controllers in "XInput" mode */
     71 #include <dev/usb/xinput_rdesc.h>
     72 /* Report descriptor for Xbox One controllers */
     73 #include <dev/usb/x1input_rdesc.h>
     74 
     75 #include "locators.h"
     76 
     77 #ifdef UHIDEV_DEBUG
     78 #define DPRINTF(x)	if (uhidevdebug) printf x
     79 #define DPRINTFN(n,x)	if (uhidevdebug>(n)) printf x
     80 int	uhidevdebug = 0;
     81 #else
     82 #define DPRINTF(x)
     83 #define DPRINTFN(n,x)
     84 #endif
     85 
     86 Static void uhidev_intr(struct usbd_xfer *, void *, usbd_status);
     87 
     88 Static int uhidev_maxrepid(void *, int);
     89 Static int uhidevprint(void *, const char *);
     90 
     91 static int uhidev_match(device_t, cfdata_t, void *);
     92 static void uhidev_attach(device_t, device_t, void *);
     93 static void uhidev_childdet(device_t, device_t);
     94 static int uhidev_detach(device_t, int);
     95 static int uhidev_activate(device_t, enum devact);
     96 
     97 CFATTACH_DECL2_NEW(uhidev, sizeof(struct uhidev_softc), uhidev_match,
     98     uhidev_attach, uhidev_detach, uhidev_activate, NULL, uhidev_childdet);
     99 
    100 static int
    101 uhidev_match(device_t parent, cfdata_t match, void *aux)
    102 {
    103 	struct usbif_attach_arg *uiaa = aux;
    104 
    105 	/* Game controllers in "XInput" mode */
    106 	if (USBIF_IS_XINPUT(uiaa))
    107 		return UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO;
    108 	/* Xbox One controllers */
    109 	if (USBIF_IS_X1INPUT(uiaa) && uiaa->uiaa_ifaceno == 0)
    110 		return UMATCH_IFACECLASS_IFACESUBCLASS_IFACEPROTO;
    111 
    112 	if (uiaa->uiaa_class != UICLASS_HID)
    113 		return UMATCH_NONE;
    114 	if (usbd_get_quirks(uiaa->uiaa_device)->uq_flags & UQ_HID_IGNORE)
    115 		return UMATCH_NONE;
    116 	return UMATCH_IFACECLASS_GENERIC;
    117 }
    118 
    119 static void
    120 uhidev_attach(device_t parent, device_t self, void *aux)
    121 {
    122 	struct uhidev_softc *sc = device_private(self);
    123 	struct usbif_attach_arg *uiaa = aux;
    124 	struct usbd_interface *iface = uiaa->uiaa_iface;
    125 	usb_interface_descriptor_t *id;
    126 	usb_endpoint_descriptor_t *ed;
    127 	struct uhidev_attach_arg uha;
    128 	device_t dev;
    129 	struct uhidev *csc;
    130 	int maxinpktsize, size, nrepid, repid, repsz;
    131 	int *repsizes;
    132 	int i;
    133 	void *desc;
    134 	const void *descptr;
    135 	usbd_status err;
    136 	char *devinfop;
    137 	int locs[UHIDBUSCF_NLOCS];
    138 
    139 	sc->sc_dev = self;
    140 	sc->sc_udev = uiaa->uiaa_device;
    141 	sc->sc_iface = iface;
    142 
    143 	aprint_naive("\n");
    144 	aprint_normal("\n");
    145 
    146 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
    147 	cv_init(&sc->sc_cv, "uhidev");
    148 	sc->sc_writelock = NULL;
    149 	sc->sc_configlock = NULL;
    150 
    151 	id = usbd_get_interface_descriptor(iface);
    152 
    153 	devinfop = usbd_devinfo_alloc(uiaa->uiaa_device, 0);
    154 	aprint_normal_dev(self, "%s, iclass %d/%d\n",
    155 	       devinfop, id->bInterfaceClass, id->bInterfaceSubClass);
    156 	usbd_devinfo_free(devinfop);
    157 
    158 	if (!pmf_device_register(self, NULL, NULL))
    159 		aprint_error_dev(self, "couldn't establish power handler\n");
    160 
    161 	if (uiaa->uiaa_vendor == USB_VENDOR_WACOM) {
    162 		if (uiaa->uiaa_product == USB_PRODUCT_WACOM_XD0912U) {
    163 		/*
    164 		 * Wacom Intuos2 (XD-0912-U) requires longer idle time to
    165 		 * initialize the device with 0x0202.
    166 		 */
    167 			DELAY(500000);
    168 		}
    169 	}
    170 	(void)usbd_set_idle(iface, 0, 0);
    171 
    172 #if 0
    173 	/*
    174 	 * HID 1.11 says we should do this, but the device firmware is
    175 	 * supposed to come up in Report Protocol after reset anyway, and
    176 	 * apparently explicitly requesting it confuses some devices.
    177 	 */
    178 	if ((usbd_get_quirks(sc->sc_udev)->uq_flags & UQ_NO_SET_PROTO) == 0 &&
    179 	    id->bInterfaceSubClass == UISUBCLASS_BOOT)
    180 		(void)usbd_set_protocol(iface, 1);
    181 #endif
    182 
    183 	maxinpktsize = 0;
    184 	sc->sc_iep_addr = sc->sc_oep_addr = -1;
    185 	for (i = 0; i < id->bNumEndpoints; i++) {
    186 		ed = usbd_interface2endpoint_descriptor(iface, i);
    187 		if (ed == NULL) {
    188 			aprint_error_dev(self,
    189 			    "could not read endpoint descriptor\n");
    190 			sc->sc_dying = 1;
    191 			return;
    192 		}
    193 
    194 		DPRINTFN(10,("uhidev_attach: bLength=%d bDescriptorType=%d "
    195 		    "bEndpointAddress=%d-%s bmAttributes=%d wMaxPacketSize=%d"
    196 		    " bInterval=%d\n",
    197 		    ed->bLength, ed->bDescriptorType,
    198 		    ed->bEndpointAddress & UE_ADDR,
    199 		    UE_GET_DIR(ed->bEndpointAddress)==UE_DIR_IN? "in" : "out",
    200 		    ed->bmAttributes & UE_XFERTYPE,
    201 		    UGETW(ed->wMaxPacketSize), ed->bInterval));
    202 
    203 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN &&
    204 		    (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
    205 			maxinpktsize = UGETW(ed->wMaxPacketSize);
    206 			sc->sc_iep_addr = ed->bEndpointAddress;
    207 		} else if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT &&
    208 		    (ed->bmAttributes & UE_XFERTYPE) == UE_INTERRUPT) {
    209 			sc->sc_oep_addr = ed->bEndpointAddress;
    210 		} else {
    211 			aprint_verbose_dev(self, "endpoint %d: ignored\n", i);
    212 		}
    213 	}
    214 
    215 	/*
    216 	 * Check that we found an input interrupt endpoint. The output interrupt
    217 	 * endpoint is optional
    218 	 */
    219 	if (sc->sc_iep_addr == -1) {
    220 		aprint_error_dev(self, "no input interrupt endpoint\n");
    221 		sc->sc_dying = 1;
    222 		return;
    223 	}
    224 
    225 	/* XXX need to extend this */
    226 	descptr = NULL;
    227 	if (uiaa->uiaa_vendor == USB_VENDOR_WACOM) {
    228 		static uByte reportbuf[3];
    229 
    230 		/* The report descriptor for the Wacom Graphire is broken. */
    231 		switch (uiaa->uiaa_product) {
    232 		case USB_PRODUCT_WACOM_GRAPHIRE3_4X5:
    233 		case USB_PRODUCT_WACOM_GRAPHIRE3_6X8:
    234 		case USB_PRODUCT_WACOM_GRAPHIRE4_4X5: /* The 6x8 too? */
    235 			/*
    236 			 * The Graphire3 needs 0x0202 to be written to
    237 			 * feature report ID 2 before it'll start
    238 			 * returning digitizer data.
    239 			 */
    240 			reportbuf[0] = 0x02;
    241 			reportbuf[1] = 0x02;
    242 			usbd_set_report(uiaa->uiaa_iface, UHID_FEATURE_REPORT, 2,
    243 			    &reportbuf, 2);
    244 
    245 			size = sizeof(uhid_graphire3_4x5_report_descr);
    246 			descptr = uhid_graphire3_4x5_report_descr;
    247 			break;
    248 		case USB_PRODUCT_WACOM_GRAPHIRE:
    249 		case USB_PRODUCT_WACOM_GRAPHIRE2:
    250 		case USB_PRODUCT_WACOM_XD0912U:
    251 		case USB_PRODUCT_WACOM_CTH690K0:
    252 			reportbuf[0] = 0x02;
    253 			reportbuf[1] = 0x02;
    254 			usbd_set_report(uiaa->uiaa_iface, UHID_FEATURE_REPORT, 2,
    255 			    &reportbuf, 2);
    256 			break;
    257 		default:
    258 			/* Keep descriptor */
    259 			break;
    260 		}
    261 	}
    262 	if (USBIF_IS_XINPUT(uiaa)) {
    263 		size = sizeof(uhid_xinput_report_descr);
    264 		descptr = uhid_xinput_report_descr;
    265 	}
    266 	if (USBIF_IS_X1INPUT(uiaa)) {
    267 		sc->sc_flags |= UHIDEV_F_XB1;
    268 		size = sizeof(uhid_x1input_report_descr);
    269 		descptr = uhid_x1input_report_descr;
    270 	}
    271 
    272 	if (descptr) {
    273 		desc = kmem_alloc(size, KM_SLEEP);
    274 		err = USBD_NORMAL_COMPLETION;
    275 		memcpy(desc, descptr, size);
    276 	} else {
    277 		desc = NULL;
    278 		err = usbd_read_report_desc(uiaa->uiaa_iface, &desc, &size);
    279 	}
    280 	if (err) {
    281 		aprint_error_dev(self, "no report descriptor\n");
    282 		sc->sc_dying = 1;
    283 		return;
    284 	}
    285 
    286 	if (uiaa->uiaa_vendor == USB_VENDOR_HOSIDEN &&
    287 	    uiaa->uiaa_product == USB_PRODUCT_HOSIDEN_PPP) {
    288 		static uByte reportbuf[] = { 1 };
    289 		/*
    290 		 *  This device was sold by Konami with its ParaParaParadise
    291 		 *  game for PlayStation2.  It needs to be "turned on"
    292 		 *  before it will send any reports.
    293 		 */
    294 
    295 		usbd_set_report(uiaa->uiaa_iface, UHID_FEATURE_REPORT, 0,
    296 		    &reportbuf, sizeof(reportbuf));
    297 	}
    298 
    299 	if (uiaa->uiaa_vendor == USB_VENDOR_LOGITECH &&
    300 	    uiaa->uiaa_product == USB_PRODUCT_LOGITECH_CBT44 && size == 0xb1) {
    301 		uint8_t *data = desc;
    302 		/*
    303 		 * This device has a odd USAGE_MINIMUM value that would
    304 		 * cause the multimedia keys to have their usage number
    305 		 * shifted up one usage.  Adjust so the usages are sane.
    306 		 */
    307 
    308 		if (data[0x56] == 0x19 && data[0x57] == 0x01 &&
    309 		    data[0x58] == 0x2a && data[0x59] == 0x8c)
    310 			data[0x57] = 0x00;
    311 	}
    312 
    313 	/*
    314 	 * Enable the Six Axis and DualShock 3 controllers.
    315 	 * See http://ps3.jim.sh/sixaxis/usb/
    316 	 */
    317 	if (uiaa->uiaa_vendor == USB_VENDOR_SONY &&
    318 	    uiaa->uiaa_product == USB_PRODUCT_SONY_PS3CONTROLLER) {
    319 		usb_device_request_t req;
    320 		char data[17];
    321 		int actlen;
    322 
    323 		req.bmRequestType = UT_READ_CLASS_INTERFACE;
    324 		req.bRequest = 1;
    325 		USETW(req.wValue, 0x3f2);
    326 		USETW(req.wIndex, 0);
    327 		USETW(req.wLength, sizeof(data));
    328 
    329 		usbd_do_request_flags(sc->sc_udev, &req, data,
    330 			USBD_SHORT_XFER_OK, &actlen, USBD_DEFAULT_TIMEOUT);
    331 	}
    332 
    333 	sc->sc_repdesc = desc;
    334 	sc->sc_repdesc_size = size;
    335 
    336 	uha.uiaa = uiaa;
    337 	nrepid = uhidev_maxrepid(desc, size);
    338 	if (nrepid < 0)
    339 		return;
    340 	if (nrepid > 0)
    341 		aprint_normal_dev(self, "%d report ids\n", nrepid);
    342 	nrepid++;
    343 	repsizes = kmem_alloc(nrepid * sizeof(*repsizes), KM_SLEEP);
    344 	sc->sc_subdevs = kmem_zalloc(nrepid * sizeof(sc->sc_subdevs[0]),
    345 	    KM_SLEEP);
    346 
    347 	/* Just request max packet size for the interrupt pipe */
    348 	sc->sc_isize = maxinpktsize;
    349 	sc->sc_nrepid = nrepid;
    350 
    351 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, sc->sc_dev);
    352 
    353 	for (repid = 0; repid < nrepid; repid++) {
    354 		repsz = hid_report_size(desc, size, hid_input, repid);
    355 		DPRINTF(("uhidev_match: repid=%d, repsz=%d\n", repid, repsz));
    356 		repsizes[repid] = repsz;
    357 	}
    358 
    359 	DPRINTF(("uhidev_attach: isize=%d\n", sc->sc_isize));
    360 
    361 	uha.parent = sc;
    362 	for (repid = 0; repid < nrepid; repid++) {
    363 		DPRINTF(("uhidev_match: try repid=%d\n", repid));
    364 		if (hid_report_size(desc, size, hid_input, repid) == 0 &&
    365 		    hid_report_size(desc, size, hid_output, repid) == 0 &&
    366 		    hid_report_size(desc, size, hid_feature, repid) == 0) {
    367 			;	/* already NULL in sc->sc_subdevs[repid] */
    368 		} else {
    369 			uha.reportid = repid;
    370 			locs[UHIDBUSCF_REPORTID] = repid;
    371 
    372 			dev = config_found(self, &uha, uhidevprint,
    373 			    CFARGS(.submatch = config_stdsubmatch,
    374 				   .locators = locs));
    375 			sc->sc_subdevs[repid] = dev;
    376 			if (dev != NULL) {
    377 				csc = device_private(dev);
    378 				csc->sc_in_rep_size = repsizes[repid];
    379 #ifdef DIAGNOSTIC
    380 				DPRINTF(("uhidev_match: repid=%d dev=%p\n",
    381 					 repid, dev));
    382 				if (csc->sc_intr == NULL) {
    383 					kmem_free(repsizes,
    384 					    nrepid * sizeof(*repsizes));
    385 					aprint_error_dev(self,
    386 					    "sc_intr == NULL\n");
    387 					return;
    388 				}
    389 #endif
    390 				rnd_attach_source(&csc->rnd_source,
    391 						  device_xname(dev),
    392 						  RND_TYPE_TTY,
    393 						  RND_FLAG_DEFAULT);
    394 			}
    395 		}
    396 	}
    397 	kmem_free(repsizes, nrepid * sizeof(*repsizes));
    398 
    399 	return;
    400 }
    401 
    402 int
    403 uhidev_maxrepid(void *buf, int len)
    404 {
    405 	struct hid_data *d;
    406 	struct hid_item h;
    407 	int maxid;
    408 
    409 	maxid = -1;
    410 	h.report_ID = 0;
    411 	for (d = hid_start_parse(buf, len, hid_none); hid_get_item(d, &h); )
    412 		if ((int)h.report_ID > maxid)
    413 			maxid = h.report_ID;
    414 	hid_end_parse(d);
    415 	return maxid;
    416 }
    417 
    418 int
    419 uhidevprint(void *aux, const char *pnp)
    420 {
    421 	struct uhidev_attach_arg *uha = aux;
    422 
    423 	if (pnp)
    424 		aprint_normal("uhid at %s", pnp);
    425 	if (uha->reportid != 0)
    426 		aprint_normal(" reportid %d", uha->reportid);
    427 	return UNCONF;
    428 }
    429 
    430 static int
    431 uhidev_activate(device_t self, enum devact act)
    432 {
    433 	struct uhidev_softc *sc = device_private(self);
    434 
    435 	switch (act) {
    436 	case DVACT_DEACTIVATE:
    437 		sc->sc_dying = 1;
    438 		return 0;
    439 	default:
    440 		return EOPNOTSUPP;
    441 	}
    442 }
    443 
    444 static void
    445 uhidev_childdet(device_t self, device_t child)
    446 {
    447 	int i;
    448 	struct uhidev_softc *sc = device_private(self);
    449 
    450 	for (i = 0; i < sc->sc_nrepid; i++) {
    451 		if (sc->sc_subdevs[i] == child)
    452 			break;
    453 	}
    454 	KASSERT(i < sc->sc_nrepid);
    455 	sc->sc_subdevs[i] = NULL;
    456 }
    457 
    458 static int
    459 uhidev_detach(device_t self, int flags)
    460 {
    461 	struct uhidev_softc *sc = device_private(self);
    462 	int i, rv;
    463 	struct uhidev *csc;
    464 
    465 	DPRINTF(("uhidev_detach: sc=%p flags=%d\n", sc, flags));
    466 
    467 	/* Notify that we are going away.  */
    468 	mutex_enter(&sc->sc_lock);
    469 	sc->sc_dying = 1;
    470 	cv_broadcast(&sc->sc_cv);
    471 	mutex_exit(&sc->sc_lock);
    472 
    473 	/*
    474 	 * Try to detach all our children.  If anything fails, bail.
    475 	 * Failure can happen if this is from drvctl -d; of course, if
    476 	 * this is a USB device being yanked, flags will have
    477 	 * DETACH_FORCE and the children will not have the option of
    478 	 * refusing detachment.
    479 	 */
    480 	for (i = 0; i < sc->sc_nrepid; i++) {
    481 		if (sc->sc_subdevs[i] == NULL)
    482 			continue;
    483 		/*
    484 		 * XXX rnd_detach_source should go in uhidev_childdet,
    485 		 * but the struct krndsource lives in the child's
    486 		 * softc, which is gone by the time of childdet.  The
    487 		 * parent uhidev_softc should be changed to allocate
    488 		 * the struct krndsource, not the child.
    489 		 */
    490 		csc = device_private(sc->sc_subdevs[i]);
    491 		rnd_detach_source(&csc->rnd_source);
    492 		rv = config_detach(sc->sc_subdevs[i], flags);
    493 		if (rv) {
    494 			rnd_attach_source(&csc->rnd_source,
    495 			    device_xname(sc->sc_dev),
    496 			    RND_TYPE_TTY, RND_FLAG_DEFAULT);
    497 			mutex_enter(&sc->sc_lock);
    498 			sc->sc_dying = 0;
    499 			mutex_exit(&sc->sc_lock);
    500 			return rv;
    501 		}
    502 	}
    503 
    504 	KASSERTMSG(sc->sc_refcnt == 0,
    505 	    "%s: %d refs remain", device_xname(sc->sc_dev), sc->sc_refcnt);
    506 	KASSERT(sc->sc_opipe == NULL);
    507 	KASSERT(sc->sc_ipipe == NULL);
    508 	KASSERT(sc->sc_ibuf == NULL);
    509 
    510 	if (sc->sc_repdesc != NULL) {
    511 		kmem_free(sc->sc_repdesc, sc->sc_repdesc_size);
    512 		sc->sc_repdesc = NULL;
    513 	}
    514 	if (sc->sc_subdevs != NULL) {
    515 		int nrepid = sc->sc_nrepid;
    516 		kmem_free(sc->sc_subdevs, nrepid * sizeof(sc->sc_subdevs[0]));
    517 		sc->sc_subdevs = NULL;
    518 	}
    519 
    520 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, sc->sc_dev);
    521 
    522 	pmf_device_deregister(self);
    523 	KASSERT(sc->sc_configlock == NULL);
    524 	KASSERT(sc->sc_writelock == NULL);
    525 	cv_destroy(&sc->sc_cv);
    526 	mutex_destroy(&sc->sc_lock);
    527 
    528 	return rv;
    529 }
    530 
    531 void
    532 uhidev_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
    533 {
    534 	struct uhidev_softc *sc = addr;
    535 	device_t cdev;
    536 	struct uhidev *scd;
    537 	u_char *p;
    538 	u_int rep;
    539 	uint32_t cc;
    540 
    541 	usbd_get_xfer_status(xfer, NULL, NULL, &cc, NULL);
    542 
    543 #ifdef UHIDEV_DEBUG
    544 	if (uhidevdebug > 5) {
    545 		uint32_t i;
    546 
    547 		DPRINTF(("uhidev_intr: status=%d cc=%d\n", status, cc));
    548 		DPRINTF(("uhidev_intr: data ="));
    549 		for (i = 0; i < cc; i++)
    550 			DPRINTF((" %02x", sc->sc_ibuf[i]));
    551 		DPRINTF(("\n"));
    552 	}
    553 #endif
    554 
    555 	if (status == USBD_CANCELLED)
    556 		return;
    557 
    558 	if (status != USBD_NORMAL_COMPLETION) {
    559 		DPRINTF(("%s: interrupt status=%d\n", device_xname(sc->sc_dev),
    560 			 status));
    561 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
    562 		return;
    563 	}
    564 
    565 	p = sc->sc_ibuf;
    566 	if (sc->sc_nrepid != 1)
    567 		rep = *p++, cc--;
    568 	else
    569 		rep = 0;
    570 	if (rep >= sc->sc_nrepid) {
    571 		printf("uhidev_intr: bad repid %d\n", rep);
    572 		return;
    573 	}
    574 	cdev = sc->sc_subdevs[rep];
    575 	if (!cdev)
    576 		return;
    577 	scd = device_private(cdev);
    578 	DPRINTFN(5,("uhidev_intr: rep=%d, scd=%p state=%#x\n",
    579 		    rep, scd, scd ? scd->sc_state : 0));
    580 	if (!(scd->sc_state & UHIDEV_OPEN))
    581 		return;
    582 #ifdef UHIDEV_DEBUG
    583 	if (scd->sc_in_rep_size != cc) {
    584 		DPRINTF(("%s: expected %d bytes, got %d\n",
    585 		       device_xname(sc->sc_dev), scd->sc_in_rep_size, cc));
    586 	}
    587 #endif
    588 	if (cc == 0) {
    589 		DPRINTF(("%s: 0-length input ignored\n",
    590 			device_xname(sc->sc_dev)));
    591 		return;
    592 	}
    593 	rnd_add_uint32(&scd->rnd_source, (uintptr_t)(sc->sc_ibuf));
    594 	scd->sc_intr(scd, p, cc);
    595 }
    596 
    597 void
    598 uhidev_get_report_desc(struct uhidev_softc *sc, void **desc, int *size)
    599 {
    600 	*desc = sc->sc_repdesc;
    601 	*size = sc->sc_repdesc_size;
    602 }
    603 
    604 static int
    605 uhidev_config_enter(struct uhidev_softc *sc)
    606 {
    607 	int error;
    608 
    609 	KASSERT(mutex_owned(&sc->sc_lock));
    610 
    611 	for (;;) {
    612 		if (sc->sc_dying)
    613 			return ENXIO;
    614 		if (sc->sc_configlock == NULL)
    615 			break;
    616 		error = cv_wait_sig(&sc->sc_cv, &sc->sc_lock);
    617 		if (error)
    618 			return error;
    619 	}
    620 
    621 	sc->sc_configlock = curlwp;
    622 	return 0;
    623 }
    624 
    625 static void
    626 uhidev_config_enter_nointr(struct uhidev_softc *sc)
    627 {
    628 
    629 	KASSERT(mutex_owned(&sc->sc_lock));
    630 
    631 	while (sc->sc_configlock)
    632 		cv_wait(&sc->sc_cv, &sc->sc_lock);
    633 	sc->sc_configlock = curlwp;
    634 }
    635 
    636 static void
    637 uhidev_config_exit(struct uhidev_softc *sc)
    638 {
    639 
    640 	KASSERT(mutex_owned(&sc->sc_lock));
    641 	KASSERTMSG(sc->sc_configlock == curlwp, "%s: migrated from %p to %p",
    642 	    device_xname(sc->sc_dev), curlwp, sc->sc_configlock);
    643 
    644 	sc->sc_configlock = NULL;
    645 	cv_broadcast(&sc->sc_cv);
    646 }
    647 
    648 /*
    649  * uhidev_open_pipes(sc)
    650  *
    651  *	Ensure the pipes of the softc are open.  Caller must hold
    652  *	sc_lock, which may be released and reacquired.
    653  */
    654 static int
    655 uhidev_open_pipes(struct uhidev_softc *sc)
    656 {
    657 	usbd_status err;
    658 	int error;
    659 
    660 	KASSERT(mutex_owned(&sc->sc_lock));
    661 
    662 	/* If the device is dying, refuse.  */
    663 	if (sc->sc_dying)
    664 		return ENXIO;
    665 
    666 	/*
    667 	 * If the pipes are already open, just increment the reference
    668 	 * count, or fail if it would overflow.
    669 	 */
    670 	if (sc->sc_refcnt) {
    671 		if (sc->sc_refcnt == INT_MAX)
    672 			return EBUSY;
    673 		sc->sc_refcnt++;
    674 		return 0;
    675 	}
    676 
    677 	/*
    678 	 * If there's no input data to prepare, don't bother with the
    679 	 * pipes.  We assume any device that does output also does
    680 	 * input; if you have a device where this is wrong, then
    681 	 * uhidev_write will fail gracefully (it checks sc->sc_opipe),
    682 	 * and you can use that device to test the changes needed to
    683 	 * open the output pipe here.
    684 	 */
    685 	if (sc->sc_isize == 0)
    686 		return 0;
    687 
    688 	/*
    689 	 * Lock the configuration and release sc_lock we may sleep to
    690 	 * allocate.  If someone else got in first, we're done;
    691 	 * otherwise open the pipes.
    692 	 */
    693 	error = uhidev_config_enter(sc);
    694 	if (error)
    695 		goto out;
    696 	if (sc->sc_refcnt) {
    697 		if (sc->sc_refcnt == INT_MAX) {
    698 			error = EBUSY;
    699 		} else {
    700 			sc->sc_refcnt++;
    701 			error = 0;
    702 		}
    703 		goto out0;
    704 	}
    705 	mutex_exit(&sc->sc_lock);
    706 
    707 	/* Allocate an input buffer.  */
    708 	sc->sc_ibuf = kmem_alloc(sc->sc_isize, KM_SLEEP);
    709 
    710 	/* Set up input interrupt pipe. */
    711 	DPRINTF(("%s: isize=%d, ep=0x%02x\n", __func__, sc->sc_isize,
    712 		 sc->sc_iep_addr));
    713 
    714 	err = usbd_open_pipe_intr(sc->sc_iface, sc->sc_iep_addr,
    715 		  USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_ibuf,
    716 		  sc->sc_isize, uhidev_intr, USBD_DEFAULT_INTERVAL);
    717 	if (err != USBD_NORMAL_COMPLETION) {
    718 		DPRINTF(("uhidopen: usbd_open_pipe_intr failed, "
    719 		    "error=%d\n", err));
    720 		error = EIO;
    721 		goto out1;
    722 	}
    723 
    724 	/*
    725 	 * Set up output interrupt pipe if an output interrupt endpoint
    726 	 * exists.
    727 	 */
    728 	if (sc->sc_oep_addr != -1) {
    729 		DPRINTF(("uhidev_open: oep=0x%02x\n", sc->sc_oep_addr));
    730 
    731 		err = usbd_open_pipe(sc->sc_iface, sc->sc_oep_addr,
    732 		    0, &sc->sc_opipe);
    733 
    734 		if (err != USBD_NORMAL_COMPLETION) {
    735 			DPRINTF(("uhidev_open: usbd_open_pipe failed, "
    736 			    "error=%d\n", err));
    737 			error = EIO;
    738 			goto out2;
    739 		}
    740 		DPRINTF(("uhidev_open: sc->sc_opipe=%p\n", sc->sc_opipe));
    741 
    742 		error = usbd_create_xfer(sc->sc_opipe, UHIDEV_OSIZE, 0, 0,
    743 		    &sc->sc_oxfer);
    744 		if (error) {
    745 			DPRINTF(("uhidev_open: couldn't allocate an xfer\n"));
    746 			goto out3;
    747 		}
    748 
    749 		if (sc->sc_flags & UHIDEV_F_XB1) {
    750 			uint8_t init_data[] = { 0x05, 0x20 };
    751 			int init_data_len = sizeof(init_data);
    752 			err = usbd_intr_transfer(sc->sc_oxfer, sc->sc_opipe, 0,
    753 			    USBD_NO_TIMEOUT, init_data, &init_data_len);
    754 			if (err != USBD_NORMAL_COMPLETION) {
    755 				DPRINTF(("uhidev_open: xb1 init failed, "
    756 				    "error=%d\n", err));
    757 				error = EIO;
    758 				goto out4;
    759 			}
    760 		}
    761 	}
    762 
    763 	/* Success!  */
    764 	mutex_enter(&sc->sc_lock);
    765 	KASSERTMSG(sc->sc_refcnt == 0, "%d refs spuriously acquired",
    766 	    sc->sc_refcnt);
    767 	sc->sc_refcnt++;
    768 	goto out0;
    769 
    770 out4:	if (sc->sc_oxfer) {
    771 		usbd_abort_pipe(sc->sc_opipe);
    772 		usbd_destroy_xfer(sc->sc_oxfer);
    773 		sc->sc_oxfer = NULL;
    774 	}
    775 out3:	if (sc->sc_opipe) {
    776 		usbd_close_pipe(sc->sc_opipe);
    777 		sc->sc_opipe = NULL;
    778 	}
    779 out2:	if (sc->sc_ipipe) {
    780 		usbd_abort_pipe(sc->sc_ipipe);
    781 		usbd_close_pipe(sc->sc_ipipe);
    782 		sc->sc_ipipe = NULL;
    783 	}
    784 out1:	kmem_free(sc->sc_ibuf, sc->sc_isize);
    785 	sc->sc_ibuf = NULL;
    786 	mutex_enter(&sc->sc_lock);
    787 out0:	KASSERT(mutex_owned(&sc->sc_lock));
    788 	uhidev_config_exit(sc);
    789 out:	KASSERT(mutex_owned(&sc->sc_lock));
    790 	return error;
    791 }
    792 
    793 static void
    794 uhidev_close_pipes(struct uhidev_softc *sc)
    795 {
    796 
    797 	KASSERT(mutex_owned(&sc->sc_lock));
    798 	KASSERTMSG(sc->sc_refcnt > 0, "%s: refcnt fouled: %d",
    799 	    device_xname(sc->sc_dev), sc->sc_refcnt);
    800 
    801 	/* If this isn't the last reference, just decrement.  */
    802 	if (sc->sc_refcnt > 1) {
    803 		sc->sc_refcnt--;
    804 		return;
    805 	}
    806 
    807 	/*
    808 	 * Lock the configuration and release sc_lock so we may sleep
    809 	 * to free memory.  We're not waiting for anyone to allocate or
    810 	 * free anything.
    811 	 */
    812 	uhidev_config_enter_nointr(sc);
    813 
    814 	/*
    815 	 * If someone else acquired a reference while we were waiting
    816 	 * for the config lock, nothing more for us to do.
    817 	 */
    818 	if (sc->sc_refcnt > 1) {
    819 		sc->sc_refcnt--;
    820 		uhidev_config_exit(sc);
    821 		return;
    822 	}
    823 
    824 	/*
    825 	 * We're the last reference and committed to closing the pipes.
    826 	 * Decrement the reference count before we release the lock --
    827 	 * access to the pipes is allowed as long as the reference
    828 	 * count is positive, so this forces all new opens to wait
    829 	 * until the config lock is released.
    830 	 */
    831 	KASSERTMSG(sc->sc_refcnt == 1, "%s: refcnt fouled: %d",
    832 	    device_xname(sc->sc_dev), sc->sc_refcnt);
    833 	sc->sc_refcnt--;
    834 	mutex_exit(&sc->sc_lock);
    835 
    836 	if (sc->sc_oxfer) {
    837 		usbd_abort_pipe(sc->sc_opipe);
    838 		usbd_destroy_xfer(sc->sc_oxfer);
    839 		sc->sc_oxfer = NULL;
    840 	}
    841 	if (sc->sc_opipe) {
    842 		usbd_close_pipe(sc->sc_opipe);
    843 		sc->sc_opipe = NULL;
    844 	}
    845 	if (sc->sc_ipipe) {
    846 		usbd_abort_pipe(sc->sc_ipipe);
    847 		usbd_close_pipe(sc->sc_ipipe);
    848 		sc->sc_ipipe = NULL;
    849 	}
    850 	kmem_free(sc->sc_ibuf, sc->sc_isize);
    851 	sc->sc_ibuf = NULL;
    852 
    853 	mutex_enter(&sc->sc_lock);
    854 	uhidev_config_exit(sc);
    855 	KASSERTMSG(sc->sc_refcnt == 0, "%s: refcnt fouled: %d",
    856 	    device_xname(sc->sc_dev), sc->sc_refcnt);
    857 }
    858 
    859 int
    860 uhidev_open(struct uhidev *scd)
    861 {
    862 	struct uhidev_softc *sc = scd->sc_parent;
    863 	int error;
    864 
    865 	mutex_enter(&sc->sc_lock);
    866 
    867 	DPRINTF(("uhidev_open(%s, report %d = %s): state=%x refcnt=%d\n",
    868 		device_xname(sc->sc_dev),
    869 		scd->sc_report_id,
    870 		device_xname(scd->sc_dev),
    871 		scd->sc_state,
    872 		sc->sc_refcnt));
    873 
    874 	/* Mark the report id open.  This is an exclusive lock.  */
    875 	if (scd->sc_state & UHIDEV_OPEN) {
    876 		error = EBUSY;
    877 		goto fail0;
    878 	}
    879 	scd->sc_state |= UHIDEV_OPEN;
    880 
    881 	/* Open the pipes which are shared by all report ids.  */
    882 	error = uhidev_open_pipes(sc);
    883 	if (error)
    884 		goto fail1;
    885 
    886 	mutex_exit(&sc->sc_lock);
    887 
    888 	/* Success!  */
    889 	return 0;
    890 
    891 fail2: __unused
    892 	uhidev_close_pipes(sc);
    893 fail1:	KASSERTMSG(scd->sc_state & UHIDEV_OPEN,
    894 	    "%s: report id %d: closed while opening",
    895 	    device_xname(sc->sc_dev), scd->sc_report_id);
    896 	scd->sc_state &= ~UHIDEV_OPEN;
    897 fail0:	mutex_exit(&sc->sc_lock);
    898 	return error;
    899 }
    900 
    901 void
    902 uhidev_stop(struct uhidev *scd)
    903 {
    904 	struct uhidev_softc *sc = scd->sc_parent;
    905 	bool abort = false;
    906 
    907 	mutex_enter(&sc->sc_lock);
    908 	if (sc->sc_writereportid == scd->sc_report_id)
    909 		abort = true;
    910 	mutex_exit(&sc->sc_lock);
    911 
    912 	if (abort && sc->sc_opipe)
    913 		usbd_abort_pipe(sc->sc_opipe);
    914 }
    915 
    916 void
    917 uhidev_close(struct uhidev *scd)
    918 {
    919 	struct uhidev_softc *sc = scd->sc_parent;
    920 
    921 	mutex_enter(&sc->sc_lock);
    922 
    923 	DPRINTF(("uhidev_close(%s, report %d = %s): state=%x refcnt=%d\n",
    924 		device_xname(sc->sc_dev),
    925 		scd->sc_report_id,
    926 		device_xname(scd->sc_dev),
    927 		scd->sc_state,
    928 		sc->sc_refcnt));
    929 
    930 	KASSERTMSG(scd->sc_state & UHIDEV_OPEN,
    931 	    "%s: report id %d: unpaired close",
    932 	    device_xname(sc->sc_dev), scd->sc_report_id);
    933 	uhidev_close_pipes(sc);
    934 	KASSERTMSG(scd->sc_state & UHIDEV_OPEN,
    935 	    "%s: report id %d: closed while closing",
    936 	    device_xname(sc->sc_dev), scd->sc_report_id);
    937 	scd->sc_state &= ~UHIDEV_OPEN;
    938 
    939 	mutex_exit(&sc->sc_lock);
    940 }
    941 
    942 usbd_status
    943 uhidev_set_report(struct uhidev *scd, int type, void *data, int len)
    944 {
    945 	char *buf;
    946 	usbd_status retstat;
    947 
    948 	if (scd->sc_report_id == 0)
    949 		return usbd_set_report(scd->sc_parent->sc_iface, type,
    950 				       scd->sc_report_id, data, len);
    951 
    952 	buf = kmem_alloc(len + 1, KM_SLEEP);
    953 	buf[0] = scd->sc_report_id;
    954 	memcpy(buf+1, data, len);
    955 
    956 	retstat = usbd_set_report(scd->sc_parent->sc_iface, type,
    957 				  scd->sc_report_id, buf, len + 1);
    958 
    959 	kmem_free(buf, len + 1);
    960 
    961 	return retstat;
    962 }
    963 
    964 usbd_status
    965 uhidev_get_report(struct uhidev *scd, int type, void *data, int len)
    966 {
    967 	return usbd_get_report(scd->sc_parent->sc_iface, type,
    968 			       scd->sc_report_id, data, len);
    969 }
    970 
    971 usbd_status
    972 uhidev_write(struct uhidev_softc *sc, void *data, int len)
    973 {
    974 	usbd_status err;
    975 
    976 	DPRINTF(("uhidev_write: data=%p, len=%d\n", data, len));
    977 
    978 	if (sc->sc_opipe == NULL)
    979 		return USBD_INVAL;
    980 
    981 	mutex_enter(&sc->sc_lock);
    982 	KASSERT(sc->sc_refcnt);
    983 	for (;;) {
    984 		if (sc->sc_dying) {
    985 			err = USBD_IOERROR;
    986 			goto out;
    987 		}
    988 		if (sc->sc_writelock == NULL)
    989 			break;
    990 		if (cv_wait_sig(&sc->sc_cv, &sc->sc_lock)) {
    991 			err = USBD_INTERRUPTED;
    992 			goto out;
    993 		}
    994 	}
    995 	sc->sc_writelock = curlwp;
    996 	mutex_exit(&sc->sc_lock);
    997 
    998 #ifdef UHIDEV_DEBUG
    999 	if (uhidevdebug > 50) {
   1000 
   1001 		uint32_t i;
   1002 		uint8_t *d = data;
   1003 
   1004 		DPRINTF(("uhidev_write: data ="));
   1005 		for (i = 0; i < len; i++)
   1006 			DPRINTF((" %02x", d[i]));
   1007 		DPRINTF(("\n"));
   1008 	}
   1009 #endif
   1010 	err = usbd_intr_transfer(sc->sc_oxfer, sc->sc_opipe, 0,
   1011 	    USBD_NO_TIMEOUT, data, &len);
   1012 
   1013 	mutex_enter(&sc->sc_lock);
   1014 	KASSERT(sc->sc_refcnt);
   1015 	KASSERTMSG(sc->sc_writelock == curlwp, "%s: migrated from %p to %p",
   1016 	    device_xname(sc->sc_dev), curlwp, sc->sc_writelock);
   1017 	sc->sc_writelock = NULL;
   1018 	cv_broadcast(&sc->sc_cv);
   1019 out:	mutex_exit(&sc->sc_lock);
   1020 	return err;
   1021 }
   1022