Home | History | Annotate | Line # | Download | only in usb
uhub.c revision 1.147.6.1
      1 /*	$NetBSD: uhub.c,v 1.147.6.1 2021/06/17 04:46:31 thorpej Exp $	*/
      2 /*	$FreeBSD: src/sys/dev/usb/uhub.c,v 1.18 1999/11/17 22:33:43 n_hibma Exp $	*/
      3 /*	$OpenBSD: uhub.c,v 1.86 2015/06/29 18:27:40 mpi Exp $ */
      4 
      5 /*
      6  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to The NetBSD Foundation
     10  * by Lennart Augustsson (lennart (at) augustsson.net) at
     11  * Carlstedt Research & Technology.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     32  * POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * USB spec: http://www.usb.org/developers/docs/usbspec.zip
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 __KERNEL_RCSID(0, "$NetBSD: uhub.c,v 1.147.6.1 2021/06/17 04:46:31 thorpej Exp $");
     41 
     42 #ifdef _KERNEL_OPT
     43 #include "opt_usb.h"
     44 #endif
     45 
     46 #include <sys/param.h>
     47 
     48 #include <sys/bus.h>
     49 #include <sys/device.h>
     50 #include <sys/kernel.h>
     51 #include <sys/kmem.h>
     52 #include <sys/proc.h>
     53 #include <sys/sysctl.h>
     54 #include <sys/systm.h>
     55 #include <sys/kcov.h>
     56 
     57 #include <dev/usb/usb.h>
     58 #include <dev/usb/usbdi.h>
     59 #include <dev/usb/usbdi_util.h>
     60 #include <dev/usb/usbdivar.h>
     61 #include <dev/usb/usbhist.h>
     62 
     63 #ifdef USB_DEBUG
     64 #ifndef UHUB_DEBUG
     65 #define uhubdebug 0
     66 #else
     67 static int uhubdebug = 0;
     68 
     69 SYSCTL_SETUP(sysctl_hw_uhub_setup, "sysctl hw.uhub setup")
     70 {
     71 	int err;
     72 	const struct sysctlnode *rnode;
     73 	const struct sysctlnode *cnode;
     74 
     75 	err = sysctl_createv(clog, 0, NULL, &rnode,
     76 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "uhub",
     77 	    SYSCTL_DESCR("uhub global controls"),
     78 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
     79 
     80 	if (err)
     81 		goto fail;
     82 
     83 	/* control debugging printfs */
     84 	err = sysctl_createv(clog, 0, &rnode, &cnode,
     85 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
     86 	    "debug", SYSCTL_DESCR("Enable debugging output"),
     87 	    NULL, 0, &uhubdebug, sizeof(uhubdebug), CTL_CREATE, CTL_EOL);
     88 	if (err)
     89 		goto fail;
     90 
     91 	return;
     92 fail:
     93 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
     94 }
     95 
     96 #endif /* UHUB_DEBUG */
     97 #endif /* USB_DEBUG */
     98 
     99 #define DPRINTF(FMT,A,B,C,D)	USBHIST_LOGN(uhubdebug,1,FMT,A,B,C,D)
    100 #define DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(uhubdebug,N,FMT,A,B,C,D)
    101 #define UHUBHIST_FUNC()		USBHIST_FUNC()
    102 #define UHUBHIST_CALLED(name)	USBHIST_CALLED(uhubdebug)
    103 #define UHUBHIST_CALLARGS(FMT,A,B,C,D) \
    104 				USBHIST_CALLARGS(uhubdebug,FMT,A,B,C,D)
    105 
    106 struct uhub_softc {
    107 	device_t		 sc_dev;	/* base device */
    108 	struct usbd_device	*sc_hub;	/* USB device */
    109 	int			 sc_proto;	/* device protocol */
    110 	struct usbd_pipe	*sc_ipipe;	/* interrupt pipe */
    111 
    112 	kmutex_t		 sc_lock;
    113 	kcondvar_t		 sc_cv;
    114 
    115 	uint8_t			*sc_statusbuf;
    116 	uint8_t			*sc_statuspend;
    117 	uint8_t			*sc_status;
    118 	size_t			 sc_statuslen;
    119 	bool			 sc_explorepending;
    120 	bool			 sc_first_explore;
    121 	bool			 sc_running;
    122 	bool			 sc_rescan;
    123 
    124 	struct lwp		*sc_exploring;
    125 };
    126 
    127 #define UHUB_IS_HIGH_SPEED(sc) \
    128     ((sc)->sc_proto == UDPROTO_HSHUBSTT || (sc)->sc_proto == UDPROTO_HSHUBMTT)
    129 #define UHUB_IS_SINGLE_TT(sc) ((sc)->sc_proto == UDPROTO_HSHUBSTT)
    130 
    131 #define PORTSTAT_ISSET(sc, port) \
    132 	((sc)->sc_status[(port) / 8] & (1 << ((port) % 8)))
    133 
    134 Static usbd_status uhub_explore(struct usbd_device *);
    135 Static void uhub_intr(struct usbd_xfer *, void *, usbd_status);
    136 
    137 
    138 /*
    139  * We need two attachment points:
    140  * hub to usb and hub to hub
    141  * Every other driver only connects to hubs
    142  */
    143 
    144 static int uhub_match(device_t, cfdata_t, void *);
    145 static void uhub_attach(device_t, device_t, void *);
    146 static int uhub_rescan(device_t, const char *, const int *);
    147 static void uhub_childdet(device_t, device_t);
    148 static int uhub_detach(device_t, int);
    149 
    150 CFATTACH_DECL3_NEW(uhub, sizeof(struct uhub_softc), uhub_match,
    151     uhub_attach, uhub_detach, NULL, uhub_rescan, uhub_childdet,
    152     DVF_DETACH_SHUTDOWN);
    153 CFATTACH_DECL3_NEW(uroothub, sizeof(struct uhub_softc), uhub_match,
    154     uhub_attach, uhub_detach, NULL, uhub_rescan, uhub_childdet,
    155     DVF_DETACH_SHUTDOWN);
    156 
    157 /*
    158  * Setting this to 1 makes sure than an uhub attaches even at higher
    159  * priority than ugen when ugen_override is set to 1.  This allows to
    160  * probe the whole USB bus and attach functions with ugen.
    161  */
    162 int uhub_ubermatch = 0;
    163 
    164 static usbd_status
    165 usbd_get_hub_desc(struct usbd_device *dev, usb_hub_descriptor_t *hd, int speed)
    166 {
    167 	usb_device_request_t req;
    168 	usbd_status err;
    169 	int nports;
    170 
    171 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    172 
    173 	/* don't issue UDESC_HUB to SS hub, or it would stall */
    174 	if (dev->ud_depth != 0 && USB_IS_SS(dev->ud_speed)) {
    175 		usb_hub_ss_descriptor_t hssd;
    176 		int rmvlen;
    177 
    178 		memset(&hssd, 0, sizeof(hssd));
    179 		req.bmRequestType = UT_READ_CLASS_DEVICE;
    180 		req.bRequest = UR_GET_DESCRIPTOR;
    181 		USETW2(req.wValue, UDESC_SS_HUB, 0);
    182 		USETW(req.wIndex, 0);
    183 		USETW(req.wLength, USB_HUB_SS_DESCRIPTOR_SIZE);
    184 		DPRINTFN(1, "getting sshub descriptor", 0, 0, 0, 0);
    185 		err = usbd_do_request(dev, &req, &hssd);
    186 		nports = hssd.bNbrPorts;
    187 		if (dev->ud_depth != 0 && nports > UHD_SS_NPORTS_MAX) {
    188 			DPRINTF("num of ports %jd exceeds maxports %jd",
    189 			    nports, UHD_SS_NPORTS_MAX, 0, 0);
    190 			nports = hd->bNbrPorts = UHD_SS_NPORTS_MAX;
    191 		}
    192 		rmvlen = (nports + 7) / 8;
    193 		hd->bDescLength = USB_HUB_DESCRIPTOR_SIZE +
    194 		    (rmvlen > 1 ? rmvlen : 1) - 1;
    195 		memcpy(hd->DeviceRemovable, hssd.DeviceRemovable, rmvlen);
    196 		hd->bDescriptorType		= hssd.bDescriptorType;
    197 		hd->bNbrPorts			= hssd.bNbrPorts;
    198 		hd->wHubCharacteristics[0]	= hssd.wHubCharacteristics[0];
    199 		hd->wHubCharacteristics[1]	= hssd.wHubCharacteristics[1];
    200 		hd->bPwrOn2PwrGood		= hssd.bPwrOn2PwrGood;
    201 		hd->bHubContrCurrent		= hssd.bHubContrCurrent;
    202 	} else {
    203 		req.bmRequestType = UT_READ_CLASS_DEVICE;
    204 		req.bRequest = UR_GET_DESCRIPTOR;
    205 		USETW2(req.wValue, UDESC_HUB, 0);
    206 		USETW(req.wIndex, 0);
    207 		USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
    208 		DPRINTFN(1, "getting hub descriptor", 0, 0, 0, 0);
    209 		err = usbd_do_request(dev, &req, hd);
    210 		nports = hd->bNbrPorts;
    211 		if (!err && nports > 7) {
    212 			USETW(req.wLength,
    213 			    USB_HUB_DESCRIPTOR_SIZE + (nports+1) / 8);
    214 			err = usbd_do_request(dev, &req, hd);
    215 		}
    216 	}
    217 
    218 	return err;
    219 }
    220 
    221 static usbd_status
    222 usbd_set_hub_depth(struct usbd_device *dev, int depth)
    223 {
    224 	usb_device_request_t req;
    225 
    226 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
    227 	req.bRequest = UR_SET_HUB_DEPTH;
    228 	USETW(req.wValue, depth);
    229 	USETW(req.wIndex, 0);
    230 	USETW(req.wLength, 0);
    231 	return usbd_do_request(dev, &req, 0);
    232 }
    233 
    234 static int
    235 uhub_match(device_t parent, cfdata_t match, void *aux)
    236 {
    237 	struct usb_attach_arg *uaa = aux;
    238 	int matchvalue;
    239 
    240 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    241 
    242 	if (uhub_ubermatch)
    243 		matchvalue = UMATCH_HIGHEST+1;
    244 	else
    245 		matchvalue = UMATCH_DEVCLASS_DEVSUBCLASS;
    246 
    247 	DPRINTFN(5, "uaa=%#jx", (uintptr_t)uaa, 0, 0, 0);
    248 	/*
    249 	 * The subclass for hubs seems to be 0 for some and 1 for others,
    250 	 * so we just ignore the subclass.
    251 	 */
    252 	if (uaa->uaa_class == UDCLASS_HUB)
    253 		return matchvalue;
    254 	return UMATCH_NONE;
    255 }
    256 
    257 static void
    258 uhub_attach(device_t parent, device_t self, void *aux)
    259 {
    260 	struct uhub_softc *sc = device_private(self);
    261 	struct usb_attach_arg *uaa = aux;
    262 	struct usbd_device *dev = uaa->uaa_device;
    263 	char *devinfop;
    264 	usbd_status err;
    265 	struct usbd_hub *hub = NULL;
    266 	usb_hub_descriptor_t hubdesc;
    267 	int p, port, nports, nremov, pwrdly;
    268 	struct usbd_interface *iface;
    269 	usb_endpoint_descriptor_t *ed;
    270 	struct usbd_tt *tts = NULL;
    271 
    272 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    273 
    274 	KASSERT(usb_in_event_thread(parent));
    275 
    276 	config_pending_incr(self);
    277 
    278 	sc->sc_dev = self;
    279 	sc->sc_hub = dev;
    280 	sc->sc_proto = uaa->uaa_proto;
    281 
    282 	devinfop = usbd_devinfo_alloc(dev, 1);
    283 	aprint_naive("\n");
    284 	aprint_normal(": %s\n", devinfop);
    285 	usbd_devinfo_free(devinfop);
    286 
    287 	if (dev->ud_depth > 0 && UHUB_IS_HIGH_SPEED(sc)) {
    288 		aprint_normal_dev(self, "%s transaction translator%s\n",
    289 		       UHUB_IS_SINGLE_TT(sc) ? "single" : "multiple",
    290 		       UHUB_IS_SINGLE_TT(sc) ? "" : "s");
    291 	}
    292 
    293 	err = usbd_set_config_index(dev, 0, 1);
    294 	if (err) {
    295 		DPRINTF("configuration failed, sc %#jx error %jd",
    296 		    (uintptr_t)sc, err, 0, 0);
    297 		goto bad2;
    298 	}
    299 
    300 	if (dev->ud_depth > USB_HUB_MAX_DEPTH) {
    301 		aprint_error_dev(self,
    302 		    "hub depth (%d) exceeded, hub ignored\n",
    303 		    USB_HUB_MAX_DEPTH);
    304 		goto bad2;
    305 	}
    306 
    307 	/* Get hub descriptor. */
    308 	memset(&hubdesc, 0, sizeof(hubdesc));
    309 	err = usbd_get_hub_desc(dev, &hubdesc, dev->ud_speed);
    310 	nports = hubdesc.bNbrPorts;
    311 	if (err) {
    312 		DPRINTF("getting hub descriptor failed, uhub%jd error %jd",
    313 		    device_unit(self), err, 0, 0);
    314 		goto bad2;
    315 	}
    316 
    317 	for (nremov = 0, port = 1; port <= nports; port++)
    318 		if (!UHD_NOT_REMOV(&hubdesc, port))
    319 			nremov++;
    320 	aprint_verbose_dev(self, "%d port%s with %d removable, %s powered\n",
    321 	    nports, nports != 1 ? "s" : "", nremov,
    322 	    dev->ud_selfpowered ? "self" : "bus");
    323 
    324 	if (nports == 0) {
    325 		aprint_debug_dev(self, "no ports, hub ignored\n");
    326 		goto bad;
    327 	}
    328 
    329 	hub = kmem_alloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
    330 	    KM_SLEEP);
    331 	dev->ud_hub = hub;
    332 	dev->ud_hub->uh_hubsoftc = sc;
    333 	hub->uh_explore = uhub_explore;
    334 	hub->uh_hubdesc = hubdesc;
    335 
    336 	if (USB_IS_SS(dev->ud_speed) && dev->ud_depth != 0) {
    337 		aprint_debug_dev(self, "setting hub depth %u\n",
    338 		    dev->ud_depth - 1);
    339 		err = usbd_set_hub_depth(dev, dev->ud_depth - 1);
    340 		if (err) {
    341 			aprint_error_dev(self, "can't set depth\n");
    342 			goto bad;
    343 		}
    344 	}
    345 
    346 	/* Set up interrupt pipe. */
    347 	err = usbd_device2interface_handle(dev, 0, &iface);
    348 	if (err) {
    349 		aprint_error_dev(self, "no interface handle\n");
    350 		goto bad;
    351 	}
    352 
    353 	if (UHUB_IS_HIGH_SPEED(sc) && !UHUB_IS_SINGLE_TT(sc)) {
    354 		err = usbd_set_interface(iface, 1);
    355 		if (err)
    356 			aprint_error_dev(self, "can't enable multiple TTs\n");
    357 	}
    358 
    359 	ed = usbd_interface2endpoint_descriptor(iface, 0);
    360 	if (ed == NULL) {
    361 		aprint_error_dev(self, "no endpoint descriptor\n");
    362 		goto bad;
    363 	}
    364 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
    365 		aprint_error_dev(self, "bad interrupt endpoint\n");
    366 		goto bad;
    367 	}
    368 
    369 	sc->sc_statuslen = (nports + 1 + 7) / 8;
    370 	sc->sc_statusbuf = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
    371 	sc->sc_statuspend = kmem_zalloc(sc->sc_statuslen, KM_SLEEP);
    372 	sc->sc_status = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
    373 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
    374 	cv_init(&sc->sc_cv, "uhubex");
    375 
    376 	/* force initial scan */
    377 	memset(sc->sc_status, 0xff, sc->sc_statuslen);
    378 	sc->sc_explorepending = true;
    379 
    380 	err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
    381 		  USBD_SHORT_XFER_OK|USBD_MPSAFE, &sc->sc_ipipe, sc,
    382 		  sc->sc_statusbuf, sc->sc_statuslen,
    383 		  uhub_intr, USBD_DEFAULT_INTERVAL);
    384 	if (err) {
    385 		aprint_error_dev(self, "cannot open interrupt pipe\n");
    386 		goto bad;
    387 	}
    388 
    389 	/* Wait with power off for a while. */
    390 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
    391 
    392 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, dev, sc->sc_dev);
    393 
    394 	/*
    395 	 * To have the best chance of success we do things in the exact same
    396 	 * order as Windows 98.  This should not be necessary, but some
    397 	 * devices do not follow the USB specs to the letter.
    398 	 *
    399 	 * These are the events on the bus when a hub is attached:
    400 	 *  Get device and config descriptors (see attach code)
    401 	 *  Get hub descriptor (see above)
    402 	 *  For all ports
    403 	 *     turn on power
    404 	 *     wait for power to become stable
    405 	 * (all below happens in explore code)
    406 	 *  For all ports
    407 	 *     clear C_PORT_CONNECTION
    408 	 *  For all ports
    409 	 *     get port status
    410 	 *     if device connected
    411 	 *        wait 100 ms
    412 	 *        turn on reset
    413 	 *        wait
    414 	 *        clear C_PORT_RESET
    415 	 *        get port status
    416 	 *        proceed with device attachment
    417 	 */
    418 
    419 	if (UHUB_IS_HIGH_SPEED(sc) && nports > 0) {
    420 		tts = kmem_alloc((UHUB_IS_SINGLE_TT(sc) ? 1 : nports) *
    421 			     sizeof(struct usbd_tt), KM_SLEEP);
    422 	}
    423 	/* Set up data structures */
    424 	for (p = 1; p <= nports; p++) {
    425 		struct usbd_port *up = &hub->uh_ports[p - 1];
    426 		up->up_dev = NULL;
    427 		up->up_parent = dev;
    428 		up->up_portno = p;
    429 		if (dev->ud_selfpowered)
    430 			/* Self powered hub, give ports maximum current. */
    431 			up->up_power = USB_MAX_POWER;
    432 		else
    433 			up->up_power = USB_MIN_POWER;
    434 		up->up_restartcnt = 0;
    435 		up->up_reattach = 0;
    436 		if (UHUB_IS_HIGH_SPEED(sc)) {
    437 			up->up_tt = &tts[UHUB_IS_SINGLE_TT(sc) ? 0 : p - 1];
    438 			up->up_tt->utt_hub = hub;
    439 		} else {
    440 			up->up_tt = NULL;
    441 		}
    442 	}
    443 
    444 	/* XXX should check for none, individual, or ganged power? */
    445 
    446 	pwrdly = dev->ud_hub->uh_hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR
    447 	    + USB_EXTRA_POWER_UP_TIME;
    448 	for (port = 1; port <= nports; port++) {
    449 		/* Turn the power on. */
    450 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
    451 		if (err)
    452 			aprint_error_dev(self, "port %d power on failed, %s\n",
    453 			    port, usbd_errstr(err));
    454 		DPRINTF("uhub%jd turn on port %jd power", device_unit(self),
    455 		    port, 0, 0);
    456 	}
    457 
    458 	/* Wait for stable power if we are not a root hub */
    459 	if (dev->ud_powersrc->up_parent != NULL)
    460 		usbd_delay_ms(dev, pwrdly);
    461 
    462 	/* The usual exploration will finish the setup. */
    463 	sc->sc_running = true;
    464 	sc->sc_first_explore = true;
    465 
    466 	if (!pmf_device_register(self, NULL, NULL))
    467 		aprint_error_dev(self, "couldn't establish power handler\n");
    468 
    469 	return;
    470 
    471  bad:
    472 	if (sc->sc_status)
    473 		kmem_free(sc->sc_status, sc->sc_statuslen);
    474 	if (sc->sc_statuspend)
    475 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
    476 	if (sc->sc_statusbuf)
    477 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
    478 	if (hub)
    479 		kmem_free(hub,
    480 		    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
    481 	dev->ud_hub = NULL;
    482  bad2:
    483 	config_pending_decr(self);
    484 }
    485 
    486 usbd_status
    487 uhub_explore(struct usbd_device *dev)
    488 {
    489 	usb_hub_descriptor_t *hd = &dev->ud_hub->uh_hubdesc;
    490 	struct uhub_softc *sc = dev->ud_hub->uh_hubsoftc;
    491 	struct usbd_port *up;
    492 	struct usbd_device *subdev;
    493 	usbd_status err;
    494 	int speed;
    495 	int port;
    496 	int change, status, reconnect, rescan;
    497 
    498 	UHUBHIST_FUNC();
    499 	UHUBHIST_CALLARGS("uhub%jd dev=%#jx addr=%jd speed=%ju",
    500 	    device_unit(sc->sc_dev), (uintptr_t)dev, dev->ud_addr,
    501 	    dev->ud_speed);
    502 
    503 	KASSERT(usb_in_event_thread(sc->sc_dev));
    504 
    505 	if (!sc->sc_running)
    506 		return USBD_NOT_STARTED;
    507 
    508 	/* Ignore hubs that are too deep. */
    509 	if (dev->ud_depth > USB_HUB_MAX_DEPTH)
    510 		return USBD_TOO_DEEP;
    511 
    512 	/* Process rescan if requested.  */
    513 	mutex_enter(&sc->sc_lock);
    514 	rescan = sc->sc_rescan;
    515 	sc->sc_rescan = false;
    516 	mutex_exit(&sc->sc_lock);
    517 	if (rescan) {
    518 		for (port = 1; port <= hd->bNbrPorts; port++) {
    519 			subdev = dev->ud_hub->uh_ports[port - 1].up_dev;
    520 			if (subdev == NULL)
    521 				continue;
    522 			usbd_reattach_device(sc->sc_dev, subdev, port, NULL);
    523 		}
    524 	}
    525 
    526 	if (PORTSTAT_ISSET(sc, 0)) { /* hub status change */
    527 		usb_hub_status_t hs;
    528 
    529 		err = usbd_get_hub_status(dev, &hs);
    530 		if (err) {
    531 			DPRINTF("uhub%jd get hub status failed, err %jd",
    532 			    device_unit(sc->sc_dev), err, 0, 0);
    533 		} else {
    534 			/* just acknowledge */
    535 			status = UGETW(hs.wHubStatus);
    536 			change = UGETW(hs.wHubChange);
    537 			DPRINTF("uhub%jd s/c=%jx/%jx", device_unit(sc->sc_dev),
    538 			    status, change, 0);
    539 
    540 			if (change & UHS_LOCAL_POWER)
    541 				usbd_clear_hub_feature(dev,
    542 						       UHF_C_HUB_LOCAL_POWER);
    543 			if (change & UHS_OVER_CURRENT)
    544 				usbd_clear_hub_feature(dev,
    545 						       UHF_C_HUB_OVER_CURRENT);
    546 		}
    547 	}
    548 
    549 	for (port = 1; port <= hd->bNbrPorts; port++) {
    550 		up = &dev->ud_hub->uh_ports[port - 1];
    551 
    552 		/* reattach is needed after firmware upload */
    553 		reconnect = up->up_reattach;
    554 		up->up_reattach = 0;
    555 
    556 		status = change = 0;
    557 
    558 		/* don't check if no change summary notification */
    559 		if (PORTSTAT_ISSET(sc, port) || reconnect) {
    560 			err = usbd_get_port_status(dev, port, &up->up_status);
    561 			if (err) {
    562 				DPRINTF("uhub%jd get port stat failed, err %jd",
    563 				    device_unit(sc->sc_dev), err, 0, 0);
    564 				continue;
    565 			}
    566 			status = UGETW(up->up_status.wPortStatus);
    567 			change = UGETW(up->up_status.wPortChange);
    568 
    569 			DPRINTF("uhub%jd port %jd: s/c=%jx/%jx",
    570 			    device_unit(sc->sc_dev), port, status, change);
    571 		}
    572 		if (!change && !reconnect) {
    573 			/* No status change, just do recursive explore. */
    574 			if (up->up_dev != NULL && up->up_dev->ud_hub != NULL)
    575 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    576 			continue;
    577 		}
    578 
    579 		if (change & UPS_C_PORT_ENABLED) {
    580 			DPRINTF("uhub%jd port %jd C_PORT_ENABLED",
    581 			    device_unit(sc->sc_dev), port, 0, 0);
    582 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
    583 			if (change & UPS_C_CONNECT_STATUS) {
    584 				/* Ignore the port error if the device
    585 				   vanished. */
    586 			} else if (status & UPS_PORT_ENABLED) {
    587 				aprint_error_dev(sc->sc_dev,
    588 				    "illegal enable change, port %d\n", port);
    589 			} else {
    590 				/* Port error condition. */
    591 				if (up->up_restartcnt) /* no message first time */
    592 					aprint_error_dev(sc->sc_dev,
    593 					    "port error, restarting port %d\n",
    594 					    port);
    595 
    596 				if (up->up_restartcnt++ < USBD_RESTART_MAX)
    597 					goto disco;
    598 				else
    599 					aprint_error_dev(sc->sc_dev,
    600 					    "port error, giving up port %d\n",
    601 					    port);
    602 			}
    603 		}
    604 		if (change & UPS_C_PORT_RESET) {
    605 			/*
    606 			 * some xHCs set PortResetChange instead of CSC
    607 			 * when port is reset.
    608 			 */
    609 			if ((status & UPS_CURRENT_CONNECT_STATUS) != 0) {
    610 				change |= UPS_C_CONNECT_STATUS;
    611 			}
    612 			usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    613 		}
    614 		if (change & UPS_C_BH_PORT_RESET) {
    615 			/*
    616 			 * some xHCs set WarmResetChange instead of CSC
    617 			 * when port is reset.
    618 			 */
    619 			if ((status & UPS_CURRENT_CONNECT_STATUS) != 0) {
    620 				change |= UPS_C_CONNECT_STATUS;
    621 			}
    622 			usbd_clear_port_feature(dev, port,
    623 			    UHF_C_BH_PORT_RESET);
    624 		}
    625 		if (change & UPS_C_PORT_LINK_STATE)
    626 			usbd_clear_port_feature(dev, port,
    627 			    UHF_C_PORT_LINK_STATE);
    628 		if (change & UPS_C_PORT_CONFIG_ERROR)
    629 			usbd_clear_port_feature(dev, port,
    630 			    UHF_C_PORT_CONFIG_ERROR);
    631 
    632 		/* XXX handle overcurrent and resume events! */
    633 
    634 		if (!reconnect && !(change & UPS_C_CONNECT_STATUS)) {
    635 			/* No status change, just do recursive explore. */
    636 			if (up->up_dev != NULL && up->up_dev->ud_hub != NULL)
    637 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    638 			continue;
    639 		}
    640 
    641 		/* We have a connect status change, handle it. */
    642 
    643 		DPRINTF("uhub%jd status change port %jd",
    644 		    device_unit(sc->sc_dev), port, 0, 0);
    645 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
    646 		/*
    647 		 * If there is already a device on the port the change status
    648 		 * must mean that is has disconnected.  Looking at the
    649 		 * current connect status is not enough to figure this out
    650 		 * since a new unit may have been connected before we handle
    651 		 * the disconnect.
    652 		 */
    653 	disco:
    654 		if (up->up_dev != NULL) {
    655 			/* Disconnected */
    656 			DPRINTF("uhub%jd device addr=%jd disappeared on "
    657 			    "port %jd",
    658 			    device_unit(sc->sc_dev), up->up_dev->ud_addr, port,
    659 			    0);
    660 
    661 			usb_disconnect_port(up, sc->sc_dev, DETACH_FORCE);
    662 			usbd_clear_port_feature(dev, port,
    663 						UHF_C_PORT_CONNECTION);
    664 		}
    665 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
    666 			/* Nothing connected, just ignore it. */
    667 			DPRINTFN(3, "uhub%jd port %jd !CURRENT_CONNECT_STATUS",
    668 			    device_unit(sc->sc_dev), port, 0, 0);
    669 			usb_disconnect_port(up, sc->sc_dev, DETACH_FORCE);
    670 			usbd_clear_port_feature(dev, port,
    671 						UHF_C_PORT_CONNECTION);
    672 			continue;
    673 		}
    674 
    675 		/* Connected */
    676 		DPRINTF("unit %jd dev->speed=%ju dev->depth=%ju",
    677 		    device_unit(sc->sc_dev), dev->ud_speed, dev->ud_depth, 0);
    678 
    679 		/* Wait for maximum device power up time. */
    680 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
    681 
    682 		/* Reset port, which implies enabling it. */
    683 		if (usbd_reset_port(dev, port, &up->up_status)) {
    684 			aprint_error_dev(sc->sc_dev,
    685 			    "port %d reset failed\n", port);
    686 			continue;
    687 		}
    688 #if 0
    689 		/* Get port status again, it might have changed during reset */
    690 		err = usbd_get_port_status(dev, port, &up->up_status);
    691 		if (err) {
    692 			DPRINTF("uhub%jd port %jd get port status failed, "
    693 			    "err %jd", device_unit(sc->sc_dev), port, err, 0);
    694 			continue;
    695 		}
    696 #endif
    697 		/*
    698 		 * Use the port status from the reset to check for the device
    699 		 * disappearing, the port enable status, and the port speed
    700 		 */
    701 		status = UGETW(up->up_status.wPortStatus);
    702 		change = UGETW(up->up_status.wPortChange);
    703 		DPRINTF("uhub%jd port %jd after reset: s/c=%jx/%jx",
    704 		    device_unit(sc->sc_dev), port, status, change);
    705 
    706 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
    707 			/* Nothing connected, just ignore it. */
    708 #ifdef DIAGNOSTIC
    709 			aprint_debug_dev(sc->sc_dev,
    710 			    "port %d, device disappeared after reset\n", port);
    711 #endif
    712 			continue;
    713 		}
    714 		if (!(status & UPS_PORT_ENABLED)) {
    715 			/* Not allowed send/receive packet. */
    716 #ifdef DIAGNOSTIC
    717 			printf("%s: port %d, device not enabled\n",
    718 			       device_xname(sc->sc_dev), port);
    719 #endif
    720 			continue;
    721 		}
    722 		/* port reset may cause Warm Reset Change, drop it. */
    723 		if (change & UPS_C_BH_PORT_RESET)
    724 			usbd_clear_port_feature(dev, port,
    725 			    UHF_C_BH_PORT_RESET);
    726 
    727 		/*
    728 		 * Figure out device speed from power bit of port status.
    729 		 *  USB 2.0 ch 11.24.2.7.1
    730 		 *  USB 3.1 ch 10.16.2.6.1
    731 		 */
    732 		int sts = status;
    733 		if ((sts & UPS_PORT_POWER) == 0)
    734 			sts &= ~UPS_PORT_POWER_SS;
    735 
    736 		if (sts & UPS_HIGH_SPEED)
    737 			speed = USB_SPEED_HIGH;
    738 		else if (sts & UPS_LOW_SPEED)
    739 			speed = USB_SPEED_LOW;
    740 		else {
    741 			/*
    742 			 * If there is no power bit set, it is certainly
    743 			 * a Super Speed device, so use the speed of its
    744 			 * parent hub.
    745 			 */
    746 			if (sts & UPS_PORT_POWER)
    747 				speed = USB_SPEED_FULL;
    748 			else
    749 				speed = dev->ud_speed;
    750 		}
    751 
    752 		/*
    753 		 * Reduce the speed, otherwise we won't setup the proper
    754 		 * transfer methods.
    755 		 */
    756 		if (speed > dev->ud_speed)
    757 			speed = dev->ud_speed;
    758 
    759 		DPRINTF("uhub%jd speed %ju", device_unit(sc->sc_dev), speed, 0,
    760 		    0);
    761 
    762 		/*
    763 		 * To check whether port has power,
    764 		 *  check UPS_PORT_POWER_SS bit if port speed is SS, and
    765 		 *  check UPS_PORT_POWER bit if port speed is HS/FS/LS.
    766 		 */
    767 		if (USB_IS_SS(speed)) {
    768 			/* SS hub port */
    769 			if (!(status & UPS_PORT_POWER_SS))
    770 				aprint_normal_dev(sc->sc_dev,
    771 				    "strange, connected port %d has no power\n",
    772 				    port);
    773 		} else {
    774 			/* HS/FS/LS hub port */
    775 			if (!(status & UPS_PORT_POWER))
    776 				aprint_normal_dev(sc->sc_dev,
    777 				    "strange, connected port %d has no power\n",
    778 				    port);
    779 		}
    780 
    781 		if (dev->ud_bus->ub_hctype == USBHCTYPE_VHCI) {
    782 			kcov_remote_enter(KCOV_REMOTE_VHCI,
    783 			    KCOV_REMOTE_VHCI_ID(dev->ud_bus->ub_busnum, port));
    784 		}
    785 
    786 		/* Get device info and set its address. */
    787 		err = usbd_new_device(sc->sc_dev, dev->ud_bus,
    788 			  dev->ud_depth + 1, speed, port, up);
    789 
    790 		if (dev->ud_bus->ub_hctype == USBHCTYPE_VHCI) {
    791 			kcov_remote_leave(KCOV_REMOTE_VHCI,
    792 			    KCOV_REMOTE_VHCI_ID(dev->ud_bus->ub_busnum, port));
    793 		}
    794 
    795 		/* XXX retry a few times? */
    796 		if (err) {
    797 			DPRINTF("uhub%jd: usbd_new_device failed, error %jd",
    798 			    device_unit(sc->sc_dev), err, 0, 0);
    799 			/* Avoid addressing problems by disabling. */
    800 			/* usbd_reset_port(dev, port, &up->status); */
    801 
    802 			/*
    803 			 * The unit refused to accept a new address, or had
    804 			 * some other serious problem.  Since we cannot leave
    805 			 * at 0 we have to disable the port instead.
    806 			 */
    807 			aprint_error_dev(sc->sc_dev,
    808 			    "device problem, disabling port %d\n", port);
    809 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
    810 		} else {
    811 			/* The port set up succeeded, reset error count. */
    812 			up->up_restartcnt = 0;
    813 
    814 			if (up->up_dev->ud_hub)
    815 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    816 		}
    817 	}
    818 	mutex_enter(&sc->sc_lock);
    819 	sc->sc_explorepending = false;
    820 	for (int i = 0; i < sc->sc_statuslen; i++) {
    821 		if (sc->sc_statuspend[i] != 0) {
    822 			memcpy(sc->sc_status, sc->sc_statuspend,
    823 			    sc->sc_statuslen);
    824 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
    825 			usb_needs_explore(sc->sc_hub);
    826 			break;
    827 		}
    828 	}
    829 	mutex_exit(&sc->sc_lock);
    830 	if (sc->sc_first_explore) {
    831 		config_pending_decr(sc->sc_dev);
    832 		sc->sc_first_explore = false;
    833 	}
    834 
    835 	return USBD_NORMAL_COMPLETION;
    836 }
    837 
    838 /*
    839  * Called from process context when the hub is gone.
    840  * Detach all devices on active ports.
    841  */
    842 static int
    843 uhub_detach(device_t self, int flags)
    844 {
    845 	struct uhub_softc *sc = device_private(self);
    846 	struct usbd_hub *hub = sc->sc_hub->ud_hub;
    847 	struct usbd_port *rup;
    848 	int nports, port, rc;
    849 
    850 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    851 
    852 	DPRINTF("uhub%jd flags=%jd", device_unit(self), flags, 0, 0);
    853 
    854 	if (hub == NULL)		/* Must be partially working */
    855 		return 0;
    856 
    857 	/* XXXSMP usb */
    858 	KERNEL_LOCK(1, curlwp);
    859 
    860 	nports = hub->uh_hubdesc.bNbrPorts;
    861 	for (port = 1; port <= nports; port++) {
    862 		rup = &hub->uh_ports[port - 1];
    863 		if (rup->up_dev == NULL)
    864 			continue;
    865 		if ((rc = usb_disconnect_port(rup, self, flags)) != 0) {
    866 			/* XXXSMP usb */
    867 			KERNEL_UNLOCK_ONE(curlwp);
    868 
    869 			return rc;
    870 		}
    871 	}
    872 
    873 	pmf_device_deregister(self);
    874 	usbd_abort_pipe(sc->sc_ipipe);
    875 	usbd_close_pipe(sc->sc_ipipe);
    876 
    877 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_hub, sc->sc_dev);
    878 
    879 	if (hub->uh_ports[0].up_tt)
    880 		kmem_free(hub->uh_ports[0].up_tt,
    881 		    (UHUB_IS_SINGLE_TT(sc) ? 1 : nports) *
    882 		    sizeof(struct usbd_tt));
    883 	kmem_free(hub,
    884 	    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
    885 	sc->sc_hub->ud_hub = NULL;
    886 	if (sc->sc_status)
    887 		kmem_free(sc->sc_status, sc->sc_statuslen);
    888 	if (sc->sc_statuspend)
    889 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
    890 	if (sc->sc_statusbuf)
    891 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
    892 
    893 	cv_destroy(&sc->sc_cv);
    894 	mutex_destroy(&sc->sc_lock);
    895 
    896 	/* XXXSMP usb */
    897 	KERNEL_UNLOCK_ONE(curlwp);
    898 
    899 	return 0;
    900 }
    901 
    902 static int
    903 uhub_rescan(device_t self, const char *ifattr, const int *locators)
    904 {
    905 	struct uhub_softc *sc = device_private(self);
    906 
    907 	UHUBHIST_FUNC();
    908 	UHUBHIST_CALLARGS("uhub%jd", device_unit(sc->sc_dev), 0, 0, 0);
    909 
    910 	KASSERT(KERNEL_LOCKED_P());
    911 
    912 	/* Trigger bus exploration.  */
    913 	/* XXX locators */
    914 	mutex_enter(&sc->sc_lock);
    915 	sc->sc_rescan = true;
    916 	mutex_exit(&sc->sc_lock);
    917 	usb_needs_explore(sc->sc_hub);
    918 
    919 	return 0;
    920 }
    921 
    922 /* Called when a device has been detached from it */
    923 static void
    924 uhub_childdet(device_t self, device_t child)
    925 {
    926 	struct uhub_softc *sc = device_private(self);
    927 	struct usbd_device *devhub = sc->sc_hub;
    928 	struct usbd_device *dev;
    929 	int nports;
    930 	int port;
    931 	int i;
    932 
    933 	KASSERT(KERNEL_LOCKED_P());
    934 
    935 	if (!devhub->ud_hub)
    936 		/* should never happen; children are only created after init */
    937 		panic("hub not fully initialised, but child deleted?");
    938 
    939 	nports = devhub->ud_hub->uh_hubdesc.bNbrPorts;
    940 	for (port = 1; port <= nports; port++) {
    941 		dev = devhub->ud_hub->uh_ports[port - 1].up_dev;
    942 		if (!dev || dev->ud_subdevlen == 0)
    943 			continue;
    944 		for (i = 0; i < dev->ud_subdevlen; i++) {
    945 			if (dev->ud_subdevs[i] == child) {
    946 				dev->ud_subdevs[i] = NULL;
    947 				dev->ud_nifaces_claimed--;
    948 			}
    949 		}
    950 		if (dev->ud_nifaces_claimed == 0) {
    951 			kmem_free(dev->ud_subdevs,
    952 			    dev->ud_subdevlen * sizeof(device_t));
    953 			dev->ud_subdevs = NULL;
    954 			dev->ud_subdevlen = 0;
    955 		}
    956 	}
    957 }
    958 
    959 
    960 /*
    961  * Hub interrupt.
    962  * This an indication that some port has changed status.
    963  * Notify the bus event handler thread that we need
    964  * to be explored again.
    965  */
    966 void
    967 uhub_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
    968 {
    969 	struct uhub_softc *sc = addr;
    970 
    971 	UHUBHIST_FUNC(); UHUBHIST_CALLARGS("called! uhub%jd status=%jx",
    972 	    device_unit(sc->sc_dev), status, 0, 0);
    973 
    974 	if (status == USBD_STALLED)
    975 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
    976 	else if (status == USBD_NORMAL_COMPLETION) {
    977 
    978 		mutex_enter(&sc->sc_lock);
    979 
    980 		DPRINTFN(5, "uhub%jd: explore pending %jd",
    981 		    device_unit(sc->sc_dev), sc->sc_explorepending, 0, 0);
    982 
    983 		/* merge port bitmap into pending interrupts list */
    984 		for (size_t i = 0; i < sc->sc_statuslen; i++) {
    985 			sc->sc_statuspend[i] |= sc->sc_statusbuf[i];
    986 
    987 			DPRINTFN(5, "uhub%jd: pending/new ports "
    988 			    "[%jd] %#jx/%#jx", device_unit(sc->sc_dev),
    989 			    i, sc->sc_statuspend[i], sc->sc_statusbuf[i]);
    990 		}
    991 
    992 		if (!sc->sc_explorepending) {
    993 			sc->sc_explorepending = true;
    994 
    995 			memcpy(sc->sc_status, sc->sc_statuspend,
    996 			    sc->sc_statuslen);
    997 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
    998 
    999 			for (size_t i = 0; i < sc->sc_statuslen; i++) {
   1000 				DPRINTFN(5, "uhub%jd: exploring ports "
   1001 				    "[%jd] %#jx", device_unit(sc->sc_dev),
   1002 				    i, sc->sc_status[i], 0);
   1003 			}
   1004 
   1005 			usb_needs_explore(sc->sc_hub);
   1006 		}
   1007 		mutex_exit(&sc->sc_lock);
   1008 	}
   1009 }
   1010