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