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