Home | History | Annotate | Line # | Download | only in usb
uhub.c revision 1.152
      1 /*	$NetBSD: uhub.c,v 1.152 2021/06/13 14:46:07 riastradh 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.152 2021/06/13 14:46:07 riastradh 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 	config_pending_incr(self);
    273 
    274 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    275 
    276 	sc->sc_dev = self;
    277 	sc->sc_hub = dev;
    278 	sc->sc_proto = uaa->uaa_proto;
    279 
    280 	devinfop = usbd_devinfo_alloc(dev, 1);
    281 	aprint_naive("\n");
    282 	aprint_normal(": %s\n", devinfop);
    283 	usbd_devinfo_free(devinfop);
    284 
    285 	if (dev->ud_depth > 0 && UHUB_IS_HIGH_SPEED(sc)) {
    286 		aprint_normal_dev(self, "%s transaction translator%s\n",
    287 		       UHUB_IS_SINGLE_TT(sc) ? "single" : "multiple",
    288 		       UHUB_IS_SINGLE_TT(sc) ? "" : "s");
    289 	}
    290 
    291 	err = usbd_set_config_index(dev, 0, 1);
    292 	if (err) {
    293 		DPRINTF("configuration failed, sc %#jx error %jd",
    294 		    (uintptr_t)sc, err, 0, 0);
    295 		goto bad2;
    296 	}
    297 
    298 	if (dev->ud_depth > USB_HUB_MAX_DEPTH) {
    299 		aprint_error_dev(self,
    300 		    "hub depth (%d) exceeded, hub ignored\n",
    301 		    USB_HUB_MAX_DEPTH);
    302 		goto bad2;
    303 	}
    304 
    305 	/* Get hub descriptor. */
    306 	memset(&hubdesc, 0, sizeof(hubdesc));
    307 	err = usbd_get_hub_desc(dev, &hubdesc, dev->ud_speed);
    308 	nports = hubdesc.bNbrPorts;
    309 	if (err) {
    310 		DPRINTF("getting hub descriptor failed, uhub%jd error %jd",
    311 		    device_unit(self), err, 0, 0);
    312 		goto bad2;
    313 	}
    314 
    315 	for (nremov = 0, port = 1; port <= nports; port++)
    316 		if (!UHD_NOT_REMOV(&hubdesc, port))
    317 			nremov++;
    318 	aprint_verbose_dev(self, "%d port%s with %d removable, %s powered\n",
    319 	    nports, nports != 1 ? "s" : "", nremov,
    320 	    dev->ud_selfpowered ? "self" : "bus");
    321 
    322 	if (nports == 0) {
    323 		aprint_debug_dev(self, "no ports, hub ignored\n");
    324 		goto bad;
    325 	}
    326 
    327 	hub = kmem_alloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
    328 	    KM_SLEEP);
    329 	dev->ud_hub = hub;
    330 	dev->ud_hub->uh_hubsoftc = sc;
    331 	hub->uh_explore = uhub_explore;
    332 	hub->uh_hubdesc = hubdesc;
    333 
    334 	if (USB_IS_SS(dev->ud_speed) && dev->ud_depth != 0) {
    335 		aprint_debug_dev(self, "setting hub depth %u\n",
    336 		    dev->ud_depth - 1);
    337 		err = usbd_set_hub_depth(dev, dev->ud_depth - 1);
    338 		if (err) {
    339 			aprint_error_dev(self, "can't set depth\n");
    340 			goto bad;
    341 		}
    342 	}
    343 
    344 	/* Set up interrupt pipe. */
    345 	err = usbd_device2interface_handle(dev, 0, &iface);
    346 	if (err) {
    347 		aprint_error_dev(self, "no interface handle\n");
    348 		goto bad;
    349 	}
    350 
    351 	if (UHUB_IS_HIGH_SPEED(sc) && !UHUB_IS_SINGLE_TT(sc)) {
    352 		err = usbd_set_interface(iface, 1);
    353 		if (err)
    354 			aprint_error_dev(self, "can't enable multiple TTs\n");
    355 	}
    356 
    357 	ed = usbd_interface2endpoint_descriptor(iface, 0);
    358 	if (ed == NULL) {
    359 		aprint_error_dev(self, "no endpoint descriptor\n");
    360 		goto bad;
    361 	}
    362 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
    363 		aprint_error_dev(self, "bad interrupt endpoint\n");
    364 		goto bad;
    365 	}
    366 
    367 	sc->sc_statuslen = (nports + 1 + 7) / 8;
    368 	sc->sc_statusbuf = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
    369 	sc->sc_statuspend = kmem_zalloc(sc->sc_statuslen, KM_SLEEP);
    370 	sc->sc_status = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
    371 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
    372 	cv_init(&sc->sc_cv, "uhubex");
    373 
    374 	/* force initial scan */
    375 	memset(sc->sc_status, 0xff, sc->sc_statuslen);
    376 	sc->sc_explorepending = true;
    377 
    378 	err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
    379 		  USBD_SHORT_XFER_OK|USBD_MPSAFE, &sc->sc_ipipe, sc,
    380 		  sc->sc_statusbuf, sc->sc_statuslen,
    381 		  uhub_intr, USBD_DEFAULT_INTERVAL);
    382 	if (err) {
    383 		aprint_error_dev(self, "cannot open interrupt pipe\n");
    384 		goto bad;
    385 	}
    386 
    387 	/* Wait with power off for a while. */
    388 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
    389 
    390 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, dev, sc->sc_dev);
    391 
    392 	/*
    393 	 * To have the best chance of success we do things in the exact same
    394 	 * order as Windows 98.  This should not be necessary, but some
    395 	 * devices do not follow the USB specs to the letter.
    396 	 *
    397 	 * These are the events on the bus when a hub is attached:
    398 	 *  Get device and config descriptors (see attach code)
    399 	 *  Get hub descriptor (see above)
    400 	 *  For all ports
    401 	 *     turn on power
    402 	 *     wait for power to become stable
    403 	 * (all below happens in explore code)
    404 	 *  For all ports
    405 	 *     clear C_PORT_CONNECTION
    406 	 *  For all ports
    407 	 *     get port status
    408 	 *     if device connected
    409 	 *        wait 100 ms
    410 	 *        turn on reset
    411 	 *        wait
    412 	 *        clear C_PORT_RESET
    413 	 *        get port status
    414 	 *        proceed with device attachment
    415 	 */
    416 
    417 	if (UHUB_IS_HIGH_SPEED(sc) && nports > 0) {
    418 		tts = kmem_alloc((UHUB_IS_SINGLE_TT(sc) ? 1 : nports) *
    419 			     sizeof(struct usbd_tt), KM_SLEEP);
    420 	}
    421 	/* Set up data structures */
    422 	for (p = 1; p <= nports; p++) {
    423 		struct usbd_port *up = &hub->uh_ports[p - 1];
    424 		up->up_dev = NULL;
    425 		up->up_parent = dev;
    426 		up->up_portno = p;
    427 		if (dev->ud_selfpowered)
    428 			/* Self powered hub, give ports maximum current. */
    429 			up->up_power = USB_MAX_POWER;
    430 		else
    431 			up->up_power = USB_MIN_POWER;
    432 		up->up_restartcnt = 0;
    433 		up->up_reattach = 0;
    434 		if (UHUB_IS_HIGH_SPEED(sc)) {
    435 			up->up_tt = &tts[UHUB_IS_SINGLE_TT(sc) ? 0 : p - 1];
    436 			up->up_tt->utt_hub = hub;
    437 		} else {
    438 			up->up_tt = NULL;
    439 		}
    440 	}
    441 
    442 	/* XXX should check for none, individual, or ganged power? */
    443 
    444 	pwrdly = dev->ud_hub->uh_hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR
    445 	    + USB_EXTRA_POWER_UP_TIME;
    446 	for (port = 1; port <= nports; port++) {
    447 		/* Turn the power on. */
    448 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
    449 		if (err)
    450 			aprint_error_dev(self, "port %d power on failed, %s\n",
    451 			    port, usbd_errstr(err));
    452 		DPRINTF("uhub%jd turn on port %jd power", device_unit(self),
    453 		    port, 0, 0);
    454 	}
    455 
    456 	/* Wait for stable power if we are not a root hub */
    457 	if (dev->ud_powersrc->up_parent != NULL)
    458 		usbd_delay_ms(dev, pwrdly);
    459 
    460 	/* The usual exploration will finish the setup. */
    461 	sc->sc_running = true;
    462 	sc->sc_first_explore = true;
    463 
    464 	if (!pmf_device_register(self, NULL, NULL))
    465 		aprint_error_dev(self, "couldn't establish power handler\n");
    466 
    467 	return;
    468 
    469  bad:
    470 	if (sc->sc_status)
    471 		kmem_free(sc->sc_status, sc->sc_statuslen);
    472 	if (sc->sc_statuspend)
    473 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
    474 	if (sc->sc_statusbuf)
    475 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
    476 	if (hub)
    477 		kmem_free(hub,
    478 		    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
    479 	dev->ud_hub = NULL;
    480  bad2:
    481 	config_pending_decr(self);
    482 }
    483 
    484 usbd_status
    485 uhub_explore(struct usbd_device *dev)
    486 {
    487 	usb_hub_descriptor_t *hd = &dev->ud_hub->uh_hubdesc;
    488 	struct uhub_softc *sc = dev->ud_hub->uh_hubsoftc;
    489 	struct usbd_port *up;
    490 	struct usbd_device *subdev;
    491 	usbd_status err;
    492 	int speed;
    493 	int port;
    494 	int change, status, reconnect, rescan;
    495 
    496 	UHUBHIST_FUNC();
    497 	UHUBHIST_CALLARGS("uhub%jd dev=%#jx addr=%jd speed=%ju",
    498 	    device_unit(sc->sc_dev), (uintptr_t)dev, dev->ud_addr,
    499 	    dev->ud_speed);
    500 
    501 	KASSERT(KERNEL_LOCKED_P());
    502 
    503 	if (!sc->sc_running)
    504 		return USBD_NOT_STARTED;
    505 
    506 	/* Ignore hubs that are too deep. */
    507 	if (dev->ud_depth > USB_HUB_MAX_DEPTH)
    508 		return USBD_TOO_DEEP;
    509 
    510 	/* Process rescan if requested.  */
    511 	mutex_enter(&sc->sc_lock);
    512 	rescan = sc->sc_rescan;
    513 	sc->sc_rescan = false;
    514 	mutex_exit(&sc->sc_lock);
    515 	if (rescan) {
    516 		for (port = 1; port <= hd->bNbrPorts; port++) {
    517 			subdev = dev->ud_hub->uh_ports[port - 1].up_dev;
    518 			if (subdev == NULL)
    519 				continue;
    520 			usbd_reattach_device(sc->sc_dev, subdev, port, NULL);
    521 		}
    522 	}
    523 
    524 	if (PORTSTAT_ISSET(sc, 0)) { /* hub status change */
    525 		usb_hub_status_t hs;
    526 
    527 		err = usbd_get_hub_status(dev, &hs);
    528 		if (err) {
    529 			DPRINTF("uhub%jd get hub status failed, err %jd",
    530 			    device_unit(sc->sc_dev), err, 0, 0);
    531 		} else {
    532 			/* just acknowledge */
    533 			status = UGETW(hs.wHubStatus);
    534 			change = UGETW(hs.wHubChange);
    535 			DPRINTF("uhub%jd s/c=%jx/%jx", device_unit(sc->sc_dev),
    536 			    status, change, 0);
    537 
    538 			if (change & UHS_LOCAL_POWER)
    539 				usbd_clear_hub_feature(dev,
    540 						       UHF_C_HUB_LOCAL_POWER);
    541 			if (change & UHS_OVER_CURRENT)
    542 				usbd_clear_hub_feature(dev,
    543 						       UHF_C_HUB_OVER_CURRENT);
    544 		}
    545 	}
    546 
    547 	for (port = 1; port <= hd->bNbrPorts; port++) {
    548 		up = &dev->ud_hub->uh_ports[port - 1];
    549 
    550 		/* reattach is needed after firmware upload */
    551 		reconnect = up->up_reattach;
    552 		up->up_reattach = 0;
    553 
    554 		status = change = 0;
    555 
    556 		/* don't check if no change summary notification */
    557 		if (PORTSTAT_ISSET(sc, port) || reconnect) {
    558 			err = usbd_get_port_status(dev, port, &up->up_status);
    559 			if (err) {
    560 				DPRINTF("uhub%jd get port stat failed, err %jd",
    561 				    device_unit(sc->sc_dev), err, 0, 0);
    562 				continue;
    563 			}
    564 			status = UGETW(up->up_status.wPortStatus);
    565 			change = UGETW(up->up_status.wPortChange);
    566 
    567 			DPRINTF("uhub%jd port %jd: s/c=%jx/%jx",
    568 			    device_unit(sc->sc_dev), port, status, change);
    569 		}
    570 		if (!change && !reconnect) {
    571 			/* No status change, just do recursive explore. */
    572 			if (up->up_dev != NULL && up->up_dev->ud_hub != NULL)
    573 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    574 			continue;
    575 		}
    576 
    577 		if (change & UPS_C_PORT_ENABLED) {
    578 			DPRINTF("uhub%jd port %jd C_PORT_ENABLED",
    579 			    device_unit(sc->sc_dev), port, 0, 0);
    580 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
    581 			if (change & UPS_C_CONNECT_STATUS) {
    582 				/* Ignore the port error if the device
    583 				   vanished. */
    584 			} else if (status & UPS_PORT_ENABLED) {
    585 				aprint_error_dev(sc->sc_dev,
    586 				    "illegal enable change, port %d\n", port);
    587 			} else {
    588 				/* Port error condition. */
    589 				if (up->up_restartcnt) /* no message first time */
    590 					aprint_error_dev(sc->sc_dev,
    591 					    "port error, restarting port %d\n",
    592 					    port);
    593 
    594 				if (up->up_restartcnt++ < USBD_RESTART_MAX)
    595 					goto disco;
    596 				else
    597 					aprint_error_dev(sc->sc_dev,
    598 					    "port error, giving up port %d\n",
    599 					    port);
    600 			}
    601 		}
    602 		if (change & UPS_C_PORT_RESET) {
    603 			/*
    604 			 * some xHCs set PortResetChange instead of CSC
    605 			 * when port is reset.
    606 			 */
    607 			if ((status & UPS_CURRENT_CONNECT_STATUS) != 0) {
    608 				change |= UPS_C_CONNECT_STATUS;
    609 			}
    610 			usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    611 		}
    612 		if (change & UPS_C_BH_PORT_RESET) {
    613 			/*
    614 			 * some xHCs set WarmResetChange instead of CSC
    615 			 * when port is reset.
    616 			 */
    617 			if ((status & UPS_CURRENT_CONNECT_STATUS) != 0) {
    618 				change |= UPS_C_CONNECT_STATUS;
    619 			}
    620 			usbd_clear_port_feature(dev, port,
    621 			    UHF_C_BH_PORT_RESET);
    622 		}
    623 		if (change & UPS_C_PORT_LINK_STATE)
    624 			usbd_clear_port_feature(dev, port,
    625 			    UHF_C_PORT_LINK_STATE);
    626 		if (change & UPS_C_PORT_CONFIG_ERROR)
    627 			usbd_clear_port_feature(dev, port,
    628 			    UHF_C_PORT_CONFIG_ERROR);
    629 
    630 		/* XXX handle overcurrent and resume events! */
    631 
    632 		if (!reconnect && !(change & UPS_C_CONNECT_STATUS)) {
    633 			/* No status change, just do recursive explore. */
    634 			if (up->up_dev != NULL && up->up_dev->ud_hub != NULL)
    635 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    636 			continue;
    637 		}
    638 
    639 		/* We have a connect status change, handle it. */
    640 
    641 		DPRINTF("uhub%jd status change port %jd",
    642 		    device_unit(sc->sc_dev), port, 0, 0);
    643 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
    644 		/*
    645 		 * If there is already a device on the port the change status
    646 		 * must mean that is has disconnected.  Looking at the
    647 		 * current connect status is not enough to figure this out
    648 		 * since a new unit may have been connected before we handle
    649 		 * the disconnect.
    650 		 */
    651 	disco:
    652 		if (up->up_dev != NULL) {
    653 			/* Disconnected */
    654 			DPRINTF("uhub%jd device addr=%jd disappeared on "
    655 			    "port %jd",
    656 			    device_unit(sc->sc_dev), up->up_dev->ud_addr, port,
    657 			    0);
    658 
    659 			usb_disconnect_port(up, sc->sc_dev, DETACH_FORCE);
    660 			usbd_clear_port_feature(dev, port,
    661 						UHF_C_PORT_CONNECTION);
    662 		}
    663 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
    664 			/* Nothing connected, just ignore it. */
    665 			DPRINTFN(3, "uhub%jd port %jd !CURRENT_CONNECT_STATUS",
    666 			    device_unit(sc->sc_dev), port, 0, 0);
    667 			usb_disconnect_port(up, sc->sc_dev, DETACH_FORCE);
    668 			usbd_clear_port_feature(dev, port,
    669 						UHF_C_PORT_CONNECTION);
    670 			continue;
    671 		}
    672 
    673 		/* Connected */
    674 		DPRINTF("unit %jd dev->speed=%ju dev->depth=%ju",
    675 		    device_unit(sc->sc_dev), dev->ud_speed, dev->ud_depth, 0);
    676 
    677 		/* Wait for maximum device power up time. */
    678 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
    679 
    680 		/* Reset port, which implies enabling it. */
    681 		if (usbd_reset_port(dev, port, &up->up_status)) {
    682 			aprint_error_dev(sc->sc_dev,
    683 			    "port %d reset failed\n", port);
    684 			continue;
    685 		}
    686 #if 0
    687 		/* Get port status again, it might have changed during reset */
    688 		err = usbd_get_port_status(dev, port, &up->up_status);
    689 		if (err) {
    690 			DPRINTF("uhub%jd port %jd get port status failed, "
    691 			    "err %jd", device_unit(sc->sc_dev), port, err, 0);
    692 			continue;
    693 		}
    694 #endif
    695 		/*
    696 		 * Use the port status from the reset to check for the device
    697 		 * disappearing, the port enable status, and the port speed
    698 		 */
    699 		status = UGETW(up->up_status.wPortStatus);
    700 		change = UGETW(up->up_status.wPortChange);
    701 		DPRINTF("uhub%jd port %jd after reset: s/c=%jx/%jx",
    702 		    device_unit(sc->sc_dev), port, status, change);
    703 
    704 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
    705 			/* Nothing connected, just ignore it. */
    706 #ifdef DIAGNOSTIC
    707 			aprint_debug_dev(sc->sc_dev,
    708 			    "port %d, device disappeared after reset\n", port);
    709 #endif
    710 			continue;
    711 		}
    712 		if (!(status & UPS_PORT_ENABLED)) {
    713 			/* Not allowed send/receive packet. */
    714 #ifdef DIAGNOSTIC
    715 			printf("%s: port %d, device not enabled\n",
    716 			       device_xname(sc->sc_dev), port);
    717 #endif
    718 			continue;
    719 		}
    720 		/* port reset may cause Warm Reset Change, drop it. */
    721 		if (change & UPS_C_BH_PORT_RESET)
    722 			usbd_clear_port_feature(dev, port,
    723 			    UHF_C_BH_PORT_RESET);
    724 
    725 		/*
    726 		 * Figure out device speed from power bit of port status.
    727 		 *  USB 2.0 ch 11.24.2.7.1
    728 		 *  USB 3.1 ch 10.16.2.6.1
    729 		 */
    730 		int sts = status;
    731 		if ((sts & UPS_PORT_POWER) == 0)
    732 			sts &= ~UPS_PORT_POWER_SS;
    733 
    734 		if (sts & UPS_HIGH_SPEED)
    735 			speed = USB_SPEED_HIGH;
    736 		else if (sts & UPS_LOW_SPEED)
    737 			speed = USB_SPEED_LOW;
    738 		else {
    739 			/*
    740 			 * If there is no power bit set, it is certainly
    741 			 * a Super Speed device, so use the speed of its
    742 			 * parent hub.
    743 			 */
    744 			if (sts & UPS_PORT_POWER)
    745 				speed = USB_SPEED_FULL;
    746 			else
    747 				speed = dev->ud_speed;
    748 		}
    749 
    750 		/*
    751 		 * Reduce the speed, otherwise we won't setup the proper
    752 		 * transfer methods.
    753 		 */
    754 		if (speed > dev->ud_speed)
    755 			speed = dev->ud_speed;
    756 
    757 		DPRINTF("uhub%jd speed %ju", device_unit(sc->sc_dev), speed, 0,
    758 		    0);
    759 
    760 		/*
    761 		 * To check whether port has power,
    762 		 *  check UPS_PORT_POWER_SS bit if port speed is SS, and
    763 		 *  check UPS_PORT_POWER bit if port speed is HS/FS/LS.
    764 		 */
    765 		if (USB_IS_SS(speed)) {
    766 			/* SS hub port */
    767 			if (!(status & UPS_PORT_POWER_SS))
    768 				aprint_normal_dev(sc->sc_dev,
    769 				    "strange, connected port %d has no power\n",
    770 				    port);
    771 		} else {
    772 			/* HS/FS/LS hub port */
    773 			if (!(status & UPS_PORT_POWER))
    774 				aprint_normal_dev(sc->sc_dev,
    775 				    "strange, connected port %d has no power\n",
    776 				    port);
    777 		}
    778 
    779 		if (dev->ud_bus->ub_hctype == USBHCTYPE_VHCI) {
    780 			kcov_remote_enter(KCOV_REMOTE_VHCI,
    781 			    KCOV_REMOTE_VHCI_ID(dev->ud_bus->ub_busnum, port));
    782 		}
    783 
    784 		/* Get device info and set its address. */
    785 		err = usbd_new_device(sc->sc_dev, dev->ud_bus,
    786 			  dev->ud_depth + 1, speed, port, up);
    787 
    788 		if (dev->ud_bus->ub_hctype == USBHCTYPE_VHCI) {
    789 			kcov_remote_leave(KCOV_REMOTE_VHCI,
    790 			    KCOV_REMOTE_VHCI_ID(dev->ud_bus->ub_busnum, port));
    791 		}
    792 
    793 		/* XXX retry a few times? */
    794 		if (err) {
    795 			DPRINTF("uhub%jd: usbd_new_device failed, error %jd",
    796 			    device_unit(sc->sc_dev), err, 0, 0);
    797 			/* Avoid addressing problems by disabling. */
    798 			/* usbd_reset_port(dev, port, &up->status); */
    799 
    800 			/*
    801 			 * The unit refused to accept a new address, or had
    802 			 * some other serious problem.  Since we cannot leave
    803 			 * at 0 we have to disable the port instead.
    804 			 */
    805 			aprint_error_dev(sc->sc_dev,
    806 			    "device problem, disabling port %d\n", port);
    807 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
    808 		} else {
    809 			/* The port set up succeeded, reset error count. */
    810 			up->up_restartcnt = 0;
    811 
    812 			if (up->up_dev->ud_hub)
    813 				up->up_dev->ud_hub->uh_explore(up->up_dev);
    814 		}
    815 	}
    816 	mutex_enter(&sc->sc_lock);
    817 	sc->sc_explorepending = false;
    818 	for (int i = 0; i < sc->sc_statuslen; i++) {
    819 		if (sc->sc_statuspend[i] != 0) {
    820 			memcpy(sc->sc_status, sc->sc_statuspend,
    821 			    sc->sc_statuslen);
    822 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
    823 			usb_needs_explore(sc->sc_hub);
    824 			break;
    825 		}
    826 	}
    827 	mutex_exit(&sc->sc_lock);
    828 	if (sc->sc_first_explore) {
    829 		config_pending_decr(sc->sc_dev);
    830 		sc->sc_first_explore = false;
    831 	}
    832 
    833 	return USBD_NORMAL_COMPLETION;
    834 }
    835 
    836 /*
    837  * Called from process context when the hub is gone.
    838  * Detach all devices on active ports.
    839  */
    840 static int
    841 uhub_detach(device_t self, int flags)
    842 {
    843 	struct uhub_softc *sc = device_private(self);
    844 	struct usbd_hub *hub = sc->sc_hub->ud_hub;
    845 	struct usbd_port *rup;
    846 	int nports, port, rc;
    847 
    848 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
    849 
    850 	DPRINTF("uhub%jd flags=%jd", device_unit(self), flags, 0, 0);
    851 
    852 	if (hub == NULL)		/* Must be partially working */
    853 		return 0;
    854 
    855 	/* XXXSMP usb */
    856 	KERNEL_LOCK(1, curlwp);
    857 
    858 	nports = hub->uh_hubdesc.bNbrPorts;
    859 	for (port = 1; port <= nports; port++) {
    860 		rup = &hub->uh_ports[port - 1];
    861 		if (rup->up_dev == NULL)
    862 			continue;
    863 		if ((rc = usb_disconnect_port(rup, self, flags)) != 0) {
    864 			/* XXXSMP usb */
    865 			KERNEL_UNLOCK_ONE(curlwp);
    866 
    867 			return rc;
    868 		}
    869 	}
    870 
    871 	pmf_device_deregister(self);
    872 	usbd_abort_pipe(sc->sc_ipipe);
    873 	usbd_close_pipe(sc->sc_ipipe);
    874 
    875 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_hub, sc->sc_dev);
    876 
    877 	if (hub->uh_ports[0].up_tt)
    878 		kmem_free(hub->uh_ports[0].up_tt,
    879 		    (UHUB_IS_SINGLE_TT(sc) ? 1 : nports) *
    880 		    sizeof(struct usbd_tt));
    881 	kmem_free(hub,
    882 	    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
    883 	sc->sc_hub->ud_hub = NULL;
    884 	if (sc->sc_status)
    885 		kmem_free(sc->sc_status, sc->sc_statuslen);
    886 	if (sc->sc_statuspend)
    887 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
    888 	if (sc->sc_statusbuf)
    889 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
    890 
    891 	cv_destroy(&sc->sc_cv);
    892 	mutex_destroy(&sc->sc_lock);
    893 
    894 	/* XXXSMP usb */
    895 	KERNEL_UNLOCK_ONE(curlwp);
    896 
    897 	return 0;
    898 }
    899 
    900 static int
    901 uhub_rescan(device_t self, const char *ifattr, const int *locators)
    902 {
    903 	struct uhub_softc *sc = device_private(self);
    904 
    905 	UHUBHIST_FUNC();
    906 	UHUBHIST_CALLARGS("uhub%jd", device_unit(sc->sc_dev), 0, 0, 0);
    907 
    908 	KASSERT(KERNEL_LOCKED_P());
    909 
    910 	/* Trigger bus exploration.  */
    911 	/* XXX locators */
    912 	mutex_enter(&sc->sc_lock);
    913 	sc->sc_rescan = true;
    914 	mutex_exit(&sc->sc_lock);
    915 	usb_needs_explore(sc->sc_hub);
    916 
    917 	return 0;
    918 }
    919 
    920 /* Called when a device has been detached from it */
    921 static void
    922 uhub_childdet(device_t self, device_t child)
    923 {
    924 	struct uhub_softc *sc = device_private(self);
    925 	struct usbd_device *devhub = sc->sc_hub;
    926 	struct usbd_device *dev;
    927 	int nports;
    928 	int port;
    929 	int i;
    930 
    931 	KASSERT(KERNEL_LOCKED_P());
    932 
    933 	if (!devhub->ud_hub)
    934 		/* should never happen; children are only created after init */
    935 		panic("hub not fully initialised, but child deleted?");
    936 
    937 	nports = devhub->ud_hub->uh_hubdesc.bNbrPorts;
    938 	for (port = 1; port <= nports; port++) {
    939 		dev = devhub->ud_hub->uh_ports[port - 1].up_dev;
    940 		if (!dev || dev->ud_subdevlen == 0)
    941 			continue;
    942 		for (i = 0; i < dev->ud_subdevlen; i++) {
    943 			if (dev->ud_subdevs[i] == child) {
    944 				dev->ud_subdevs[i] = NULL;
    945 				dev->ud_nifaces_claimed--;
    946 			}
    947 		}
    948 		if (dev->ud_nifaces_claimed == 0) {
    949 			kmem_free(dev->ud_subdevs,
    950 			    dev->ud_subdevlen * sizeof(device_t));
    951 			dev->ud_subdevs = NULL;
    952 			dev->ud_subdevlen = 0;
    953 		}
    954 	}
    955 }
    956 
    957 
    958 /*
    959  * Hub interrupt.
    960  * This an indication that some port has changed status.
    961  * Notify the bus event handler thread that we need
    962  * to be explored again.
    963  */
    964 void
    965 uhub_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
    966 {
    967 	struct uhub_softc *sc = addr;
    968 
    969 	UHUBHIST_FUNC(); UHUBHIST_CALLARGS("called! uhub%jd status=%jx",
    970 	    device_unit(sc->sc_dev), status, 0, 0);
    971 
    972 	if (status == USBD_STALLED)
    973 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
    974 	else if (status == USBD_NORMAL_COMPLETION) {
    975 
    976 		mutex_enter(&sc->sc_lock);
    977 
    978 		DPRINTFN(5, "uhub%jd: explore pending %jd",
    979 		    device_unit(sc->sc_dev), sc->sc_explorepending, 0, 0);
    980 
    981 		/* merge port bitmap into pending interrupts list */
    982 		for (size_t i = 0; i < sc->sc_statuslen; i++) {
    983 			sc->sc_statuspend[i] |= sc->sc_statusbuf[i];
    984 
    985 			DPRINTFN(5, "uhub%jd: pending/new ports "
    986 			    "[%jd] %#jx/%#jx", device_unit(sc->sc_dev),
    987 			    i, sc->sc_statuspend[i], sc->sc_statusbuf[i]);
    988 		}
    989 
    990 		if (!sc->sc_explorepending) {
    991 			sc->sc_explorepending = true;
    992 
    993 			memcpy(sc->sc_status, sc->sc_statuspend,
    994 			    sc->sc_statuslen);
    995 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
    996 
    997 			for (size_t i = 0; i < sc->sc_statuslen; i++) {
    998 				DPRINTFN(5, "uhub%jd: exploring ports "
    999 				    "[%jd] %#jx", device_unit(sc->sc_dev),
   1000 				    i, sc->sc_status[i], 0);
   1001 			}
   1002 
   1003 			usb_needs_explore(sc->sc_hub);
   1004 		}
   1005 		mutex_exit(&sc->sc_lock);
   1006 	}
   1007 }
   1008