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