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