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