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