xref: /netbsd-src/sys/dev/usb/uhub.c (revision 8450a7c42673d65e3b1f6560d3b6ecd317a6cbe8)
1 /*	$NetBSD: uhub.c,v 1.134 2016/09/13 07:30:32 skrll Exp $	*/
2 /*	$FreeBSD: src/sys/dev/usb/uhub.c,v 1.18 1999/11/17 22:33:43 n_hibma Exp $	*/
3 /*	$OpenBSD: uhub.c,v 1.86 2015/06/29 18:27:40 mpi Exp $ */
4 
5 /*
6  * Copyright (c) 1998, 2004 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Lennart Augustsson (lennart@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.134 2016/09/13 07:30:32 skrll Exp $");
41 
42 #include <sys/param.h>
43 
44 #include <sys/bus.h>
45 #include <sys/device.h>
46 #include <sys/kernel.h>
47 #include <sys/kmem.h>
48 #include <sys/proc.h>
49 #include <sys/sysctl.h>
50 #include <sys/systm.h>
51 
52 
53 #include <dev/usb/usb.h>
54 #include <dev/usb/usbdi.h>
55 #include <dev/usb/usbdi_util.h>
56 #include <dev/usb/usbdivar.h>
57 #include <dev/usb/usbhist.h>
58 
59 #ifdef USB_DEBUG
60 #ifndef UHUB_DEBUG
61 #define uhubdebug 0
62 #else
63 static int uhubdebug = 0;
64 
65 SYSCTL_SETUP(sysctl_hw_uhub_setup, "sysctl hw.uhub setup")
66 {
67 	int err;
68 	const struct sysctlnode *rnode;
69 	const struct sysctlnode *cnode;
70 
71 	err = sysctl_createv(clog, 0, NULL, &rnode,
72 	    CTLFLAG_PERMANENT, CTLTYPE_NODE, "uhub",
73 	    SYSCTL_DESCR("uhub global controls"),
74 	    NULL, 0, NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
75 
76 	if (err)
77 		goto fail;
78 
79 	/* control debugging printfs */
80 	err = sysctl_createv(clog, 0, &rnode, &cnode,
81 	    CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_INT,
82 	    "debug", SYSCTL_DESCR("Enable debugging output"),
83 	    NULL, 0, &uhubdebug, sizeof(uhubdebug), CTL_CREATE, CTL_EOL);
84 	if (err)
85 		goto fail;
86 
87 	return;
88 fail:
89 	aprint_error("%s: sysctl_createv failed (err = %d)\n", __func__, err);
90 }
91 
92 #endif /* UHUB_DEBUG */
93 #endif /* USB_DEBUG */
94 
95 #define DPRINTF(FMT,A,B,C,D)	USBHIST_LOGN(uhubdebug,1,FMT,A,B,C,D)
96 #define DPRINTFN(N,FMT,A,B,C,D)	USBHIST_LOGN(uhubdebug,N,FMT,A,B,C,D)
97 #define UHUBHIST_FUNC() USBHIST_FUNC()
98 #define UHUBHIST_CALLED(name) USBHIST_CALLED(uhubdebug)
99 
100 struct uhub_softc {
101 	device_t		 sc_dev;	/* base device */
102 	struct usbd_device	*sc_hub;	/* USB device */
103 	int			 sc_proto;	/* device protocol */
104 	struct usbd_pipe	*sc_ipipe;	/* interrupt pipe */
105 
106 	kmutex_t		 sc_lock;
107 
108 	uint8_t			*sc_statusbuf;
109 	uint8_t			*sc_statuspend;
110 	uint8_t			*sc_status;
111 	size_t			 sc_statuslen;
112 	int			 sc_explorepending;
113 
114 	u_char			 sc_running;
115 };
116 
117 #define UHUB_IS_HIGH_SPEED(sc) \
118     ((sc)->sc_proto == UDPROTO_HSHUBSTT || (sc)->sc_proto == UDPROTO_HSHUBMTT)
119 #define UHUB_IS_SINGLE_TT(sc) ((sc)->sc_proto == UDPROTO_HSHUBSTT)
120 
121 #define PORTSTAT_ISSET(sc, port) \
122 	((sc)->sc_status[(port) / 8] & (1 << ((port) % 8)))
123 
124 Static usbd_status uhub_explore(struct usbd_device *);
125 Static void uhub_intr(struct usbd_xfer *, void *, usbd_status);
126 
127 
128 /*
129  * We need two attachment points:
130  * hub to usb and hub to hub
131  * Every other driver only connects to hubs
132  */
133 
134 int uhub_match(device_t, cfdata_t, void *);
135 void uhub_attach(device_t, device_t, void *);
136 int uhub_rescan(device_t, const char *, const int *);
137 void uhub_childdet(device_t, device_t);
138 int uhub_detach(device_t, int);
139 extern struct cfdriver uhub_cd;
140 CFATTACH_DECL3_NEW(uhub, sizeof(struct uhub_softc), uhub_match,
141     uhub_attach, uhub_detach, NULL, uhub_rescan, uhub_childdet,
142     DVF_DETACH_SHUTDOWN);
143 CFATTACH_DECL2_NEW(uroothub, sizeof(struct uhub_softc), uhub_match,
144     uhub_attach, uhub_detach, NULL, uhub_rescan, uhub_childdet);
145 
146 /*
147  * Setting this to 1 makes sure than an uhub attaches even at higher
148  * priority than ugen when ugen_override is set to 1.  This allows to
149  * probe the whole USB bus and attach functions with ugen.
150  */
151 int uhub_ubermatch = 0;
152 
153 static usbd_status
154 usbd_get_hub_desc(struct usbd_device *dev, usb_hub_descriptor_t *hd, int speed)
155 {
156 	usb_device_request_t req;
157 	usbd_status err;
158 	int nports;
159 
160 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
161 
162 	/* don't issue UDESC_HUB to SS hub, or it would stall */
163 	if (dev->ud_depth != 0 && USB_IS_SS(dev->ud_speed)) {
164 		usb_hub_ss_descriptor_t hssd;
165 		int rmvlen;
166 
167 		memset(&hssd, 0, sizeof(hssd));
168 		req.bmRequestType = UT_READ_CLASS_DEVICE;
169 		req.bRequest = UR_GET_DESCRIPTOR;
170 		USETW2(req.wValue, UDESC_SS_HUB, 0);
171 		USETW(req.wIndex, 0);
172 		USETW(req.wLength, USB_HUB_SS_DESCRIPTOR_SIZE);
173 		DPRINTFN(1, "getting sshub descriptor", 0, 0, 0, 0);
174 		err = usbd_do_request(dev, &req, &hssd);
175 		nports = hssd.bNbrPorts;
176 		if (dev->ud_depth != 0 && nports > UHD_SS_NPORTS_MAX) {
177 			DPRINTF("num of ports %d exceeds maxports %d",
178 			    nports, UHD_SS_NPORTS_MAX, 0, 0);
179 			nports = hd->bNbrPorts = UHD_SS_NPORTS_MAX;
180 		}
181 		rmvlen = (nports + 7) / 8;
182 		hd->bDescLength = USB_HUB_DESCRIPTOR_SIZE +
183 		    (rmvlen > 1 ? rmvlen : 1) - 1;
184 		memcpy(hd->DeviceRemovable, hssd.DeviceRemovable, rmvlen);
185 		hd->bDescriptorType		= hssd.bDescriptorType;
186 		hd->bNbrPorts			= hssd.bNbrPorts;
187 		hd->wHubCharacteristics[0]	= hssd.wHubCharacteristics[0];
188 		hd->wHubCharacteristics[1]	= hssd.wHubCharacteristics[1];
189 		hd->bPwrOn2PwrGood		= hssd.bPwrOn2PwrGood;
190 		hd->bHubContrCurrent		= hssd.bHubContrCurrent;
191 	} else {
192 		req.bmRequestType = UT_READ_CLASS_DEVICE;
193 		req.bRequest = UR_GET_DESCRIPTOR;
194 		USETW2(req.wValue, UDESC_HUB, 0);
195 		USETW(req.wIndex, 0);
196 		USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
197 		DPRINTFN(1, "getting hub descriptor", 0, 0, 0, 0);
198 		err = usbd_do_request(dev, &req, hd);
199 		nports = hd->bNbrPorts;
200 		if (!err && nports > 7) {
201 			USETW(req.wLength,
202 			    USB_HUB_DESCRIPTOR_SIZE + (nports+1) / 8);
203 			err = usbd_do_request(dev, &req, hd);
204 		}
205 	}
206 
207 	return err;
208 }
209 
210 static usbd_status
211 usbd_set_hub_depth(struct usbd_device *dev, int depth)
212 {
213 	usb_device_request_t req;
214 
215 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
216 	req.bRequest = UR_SET_HUB_DEPTH;
217 	USETW(req.wValue, depth);
218 	USETW(req.wIndex, 0);
219 	USETW(req.wLength, 0);
220 	return usbd_do_request(dev, &req, 0);
221 }
222 
223 int
224 uhub_match(device_t parent, cfdata_t match, void *aux)
225 {
226 	struct usb_attach_arg *uaa = aux;
227 	int matchvalue;
228 
229 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
230 
231 	if (uhub_ubermatch)
232 		matchvalue = UMATCH_HIGHEST+1;
233 	else
234 		matchvalue = UMATCH_DEVCLASS_DEVSUBCLASS;
235 
236 	DPRINTFN(5, "uaa=%p", uaa, 0, 0, 0);
237 	/*
238 	 * The subclass for hubs seems to be 0 for some and 1 for others,
239 	 * so we just ignore the subclass.
240 	 */
241 	if (uaa->uaa_class == UDCLASS_HUB)
242 		return matchvalue;
243 	return UMATCH_NONE;
244 }
245 
246 void
247 uhub_attach(device_t parent, device_t self, void *aux)
248 {
249 	struct uhub_softc *sc = device_private(self);
250 	struct usb_attach_arg *uaa = aux;
251 	struct usbd_device *dev = uaa->uaa_device;
252 	char *devinfop;
253 	usbd_status err;
254 	struct usbd_hub *hub = NULL;
255 	usb_hub_descriptor_t hubdesc;
256 	int p, port, nports, nremov, pwrdly;
257 	struct usbd_interface *iface;
258 	usb_endpoint_descriptor_t *ed;
259 	struct usbd_tt *tts = NULL;
260 
261 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
262 
263 	sc->sc_dev = self;
264 	sc->sc_hub = dev;
265 	sc->sc_proto = uaa->uaa_proto;
266 
267 	devinfop = usbd_devinfo_alloc(dev, 1);
268 	aprint_naive("\n");
269 	aprint_normal(": %s\n", devinfop);
270 	usbd_devinfo_free(devinfop);
271 
272 	if (dev->ud_depth > 0 && UHUB_IS_HIGH_SPEED(sc)) {
273 		aprint_normal_dev(self, "%s transaction translator%s\n",
274 		       UHUB_IS_SINGLE_TT(sc) ? "single" : "multiple",
275 		       UHUB_IS_SINGLE_TT(sc) ? "" : "s");
276 	}
277 
278 	err = usbd_set_config_index(dev, 0, 1);
279 	if (err) {
280 		DPRINTF("configuration failed, sc %p error %d", sc, err, 0, 0);
281 		return;
282 	}
283 
284 	if (dev->ud_depth > USB_HUB_MAX_DEPTH) {
285 		aprint_error_dev(self,
286 		    "hub depth (%d) exceeded, hub ignored\n",
287 		    USB_HUB_MAX_DEPTH);
288 		return;
289 	}
290 
291 	/* Get hub descriptor. */
292 	memset(&hubdesc, 0, sizeof(hubdesc));
293 	err = usbd_get_hub_desc(dev, &hubdesc, dev->ud_speed);
294 	nports = hubdesc.bNbrPorts;
295 	if (err) {
296 		DPRINTF("getting hub descriptor failed, uhub%d error %d",
297 		    device_unit(self), err, 0, 0);
298 		return;
299 	}
300 
301 	for (nremov = 0, port = 1; port <= nports; port++)
302 		if (!UHD_NOT_REMOV(&hubdesc, port))
303 			nremov++;
304 	aprint_verbose_dev(self, "%d port%s with %d removable, %s powered\n",
305 	    nports, nports != 1 ? "s" : "", nremov,
306 	    dev->ud_selfpowered ? "self" : "bus");
307 
308 	if (nports == 0) {
309 		aprint_debug_dev(self, "no ports, hub ignored\n");
310 		goto bad;
311 	}
312 
313 	hub = kmem_alloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
314 	    KM_SLEEP);
315 	if (hub == NULL)
316 		return;
317 	dev->ud_hub = hub;
318 	dev->ud_hub->uh_hubsoftc = sc;
319 	hub->uh_explore = uhub_explore;
320 	hub->uh_hubdesc = hubdesc;
321 
322 	if (USB_IS_SS(dev->ud_speed) && dev->ud_depth != 0) {
323 		aprint_debug_dev(self, "setting hub depth %u\n",
324 		    dev->ud_depth - 1);
325 		err = usbd_set_hub_depth(dev, dev->ud_depth - 1);
326 		if (err) {
327 			aprint_error_dev(self, "can't set depth\n");
328 			goto bad;
329 		}
330 	}
331 
332 	/* Set up interrupt pipe. */
333 	err = usbd_device2interface_handle(dev, 0, &iface);
334 	if (err) {
335 		aprint_error_dev(self, "no interface handle\n");
336 		goto bad;
337 	}
338 
339 	if (UHUB_IS_HIGH_SPEED(sc) && !UHUB_IS_SINGLE_TT(sc)) {
340 		err = usbd_set_interface(iface, 1);
341 		if (err)
342 			aprint_error_dev(self, "can't enable multiple TTs\n");
343 	}
344 
345 	ed = usbd_interface2endpoint_descriptor(iface, 0);
346 	if (ed == NULL) {
347 		aprint_error_dev(self, "no endpoint descriptor\n");
348 		goto bad;
349 	}
350 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
351 		aprint_error_dev(self, "bad interrupt endpoint\n");
352 		goto bad;
353 	}
354 
355 	sc->sc_statuslen = (nports + 1 + 7) / 8;
356 	sc->sc_statusbuf = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
357 	if (!sc->sc_statusbuf)
358 		goto bad;
359 	sc->sc_statuspend = kmem_zalloc(sc->sc_statuslen, KM_SLEEP);
360 	if (!sc->sc_statuspend)
361 		goto bad;
362 	sc->sc_status = kmem_alloc(sc->sc_statuslen, KM_SLEEP);
363 	if (!sc->sc_status)
364 		goto bad;
365 
366 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_SOFTUSB);
367 	memset(sc->sc_statuspend, 0, sc->sc_statuslen);
368 
369 	/* force initial scan */
370 	memset(sc->sc_status, 0xff, sc->sc_statuslen);
371 	sc->sc_explorepending = 1;
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 		if (!tts)
416 			goto bad;
417 	}
418 	/* Set up data structures */
419 	for (p = 0; p < nports; p++) {
420 		struct usbd_port *up = &hub->uh_ports[p];
421 		up->up_dev = NULL;
422 		up->up_parent = dev;
423 		up->up_portno = p + 1;
424 		if (dev->ud_selfpowered)
425 			/* Self powered hub, give ports maximum current. */
426 			up->up_power = USB_MAX_POWER;
427 		else
428 			up->up_power = USB_MIN_POWER;
429 		up->up_restartcnt = 0;
430 		up->up_reattach = 0;
431 		if (UHUB_IS_HIGH_SPEED(sc)) {
432 			up->up_tt = &tts[UHUB_IS_SINGLE_TT(sc) ? 0 : p];
433 			up->up_tt->utt_hub = hub;
434 		} else {
435 			up->up_tt = NULL;
436 		}
437 	}
438 
439 	/* XXX should check for none, individual, or ganged power? */
440 
441 	pwrdly = dev->ud_hub->uh_hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR
442 	    + USB_EXTRA_POWER_UP_TIME;
443 	for (port = 1; port <= nports; port++) {
444 		/* Turn the power on. */
445 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
446 		if (err)
447 			aprint_error_dev(self, "port %d power on failed, %s\n",
448 			    port, usbd_errstr(err));
449 		DPRINTF("uhub%d turn on port %d power", device_unit(self),
450 		    port, 0, 0);
451 	}
452 
453 	/* Wait for stable power if we are not a root hub */
454 	if (dev->ud_powersrc->up_parent != NULL)
455 		usbd_delay_ms(dev, pwrdly);
456 
457 	/* The usual exploration will finish the setup. */
458 
459 	sc->sc_running = 1;
460 
461 	if (!pmf_device_register(self, NULL, NULL))
462 		aprint_error_dev(self, "couldn't establish power handler\n");
463 
464 	return;
465 
466  bad:
467 	if (sc->sc_status)
468 		kmem_free(sc->sc_status, sc->sc_statuslen);
469 	if (sc->sc_statuspend)
470 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
471 	if (sc->sc_statusbuf)
472 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
473 	if (hub)
474 		kmem_free(hub,
475 		    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
476 	dev->ud_hub = NULL;
477 	return;
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(); UHUBHIST_CALLED();
492 
493 	DPRINTFN(10, "uhub%d dev=%p addr=%d speed=%u",
494 	    device_unit(sc->sc_dev), dev, dev->ud_addr, 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%d get hub status failed, err %d",
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%d s/c=%x/%x", 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%d get port stat failed, err %d",
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%d port %d: s/c=%x/%x",
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%d port %d 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%d status change port %d", device_unit(sc->sc_dev),
621 		    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%d device addr=%d disappeared on port %d",
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%d port %d !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 %d dev->speed=%u dev->depth=%u",
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%d port %d get port status failed, "
669 			    "err %d", 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%d port %d after reset: s/c=%x/%x",
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%d speed %u", 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 		/* Get device info and set its address. */
758 		err = usbd_new_device(sc->sc_dev, dev->ud_bus,
759 			  dev->ud_depth + 1, speed, port, up);
760 		/* XXX retry a few times? */
761 		if (err) {
762 			DPRINTF("usbd_new_device failed, error %d", err, 0, 0,
763 			    0);
764 			/* Avoid addressing problems by disabling. */
765 			/* usbd_reset_port(dev, port, &up->status); */
766 
767 			/*
768 			 * The unit refused to accept a new address, or had
769 			 * some other serious problem.  Since we cannot leave
770 			 * at 0 we have to disable the port instead.
771 			 */
772 			aprint_error_dev(sc->sc_dev,
773 			    "device problem, disabling port %d\n", port);
774 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
775 		} else {
776 			/* The port set up succeeded, reset error count. */
777 			up->up_restartcnt = 0;
778 
779 			if (up->up_dev->ud_hub)
780 				up->up_dev->ud_hub->uh_explore(up->up_dev);
781 		}
782 	}
783 	mutex_enter(&sc->sc_lock);
784 	sc->sc_explorepending = 0;
785 	for (int i = 0; i < sc->sc_statuslen; i++) {
786 		if (sc->sc_statuspend[i] != 0) {
787 			memcpy(sc->sc_status, sc->sc_statuspend,
788 			    sc->sc_statuslen);
789 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
790 			usb_needs_explore(sc->sc_hub);
791 			break;
792 		}
793 	}
794 	mutex_exit(&sc->sc_lock);
795 
796 	return USBD_NORMAL_COMPLETION;
797 }
798 
799 /*
800  * Called from process context when the hub is gone.
801  * Detach all devices on active ports.
802  */
803 int
804 uhub_detach(device_t self, int flags)
805 {
806 	struct uhub_softc *sc = device_private(self);
807 	struct usbd_hub *hub = sc->sc_hub->ud_hub;
808 	struct usbd_port *rup;
809 	int nports, port, rc;
810 
811 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
812 
813 	DPRINTF("uhub%d flags=%d", device_unit(self), flags, 0, 0);
814 
815 	if (hub == NULL)		/* Must be partially working */
816 		return 0;
817 
818 	/* XXXSMP usb */
819 	KERNEL_LOCK(1, curlwp);
820 
821 	nports = hub->uh_hubdesc.bNbrPorts;
822 	for (port = 0; port < nports; port++) {
823 		rup = &hub->uh_ports[port];
824 		if (rup->up_dev == NULL)
825 			continue;
826 		if ((rc = usb_disconnect_port(rup, self, flags)) != 0) {
827 			/* XXXSMP usb */
828 			KERNEL_UNLOCK_ONE(curlwp);
829 
830 			return rc;
831 		}
832 	}
833 
834 	pmf_device_deregister(self);
835 	usbd_abort_pipe(sc->sc_ipipe);
836 	usbd_close_pipe(sc->sc_ipipe);
837 
838 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_hub, sc->sc_dev);
839 
840 	if (hub->uh_ports[0].up_tt)
841 		kmem_free(hub->uh_ports[0].up_tt,
842 		    (UHUB_IS_SINGLE_TT(sc) ? 1 : nports) *
843 		    sizeof(struct usbd_tt));
844 	kmem_free(hub,
845 	    sizeof(*hub) + (nports-1) * sizeof(struct usbd_port));
846 	sc->sc_hub->ud_hub = NULL;
847 	if (sc->sc_status)
848 		kmem_free(sc->sc_status, sc->sc_statuslen);
849 	if (sc->sc_statuspend)
850 		kmem_free(sc->sc_statuspend, sc->sc_statuslen);
851 	if (sc->sc_statusbuf)
852 		kmem_free(sc->sc_statusbuf, sc->sc_statuslen);
853 
854 	mutex_destroy(&sc->sc_lock);
855 
856 	/* XXXSMP usb */
857 	KERNEL_UNLOCK_ONE(curlwp);
858 
859 	return 0;
860 }
861 
862 int
863 uhub_rescan(device_t self, const char *ifattr, const int *locators)
864 {
865 	struct uhub_softc *sc = device_private(self);
866 	struct usbd_hub *hub = sc->sc_hub->ud_hub;
867 	struct usbd_device *dev;
868 	int port;
869 
870 	for (port = 0; port < hub->uh_hubdesc.bNbrPorts; port++) {
871 		dev = hub->uh_ports[port].up_dev;
872 		if (dev == NULL)
873 			continue;
874 		usbd_reattach_device(sc->sc_dev, dev, port, locators);
875 	}
876 	return 0;
877 }
878 
879 /* Called when a device has been detached from it */
880 void
881 uhub_childdet(device_t self, device_t child)
882 {
883 	struct uhub_softc *sc = device_private(self);
884 	struct usbd_device *devhub = sc->sc_hub;
885 	struct usbd_device *dev;
886 	int nports;
887 	int port;
888 	int i;
889 
890 	if (!devhub->ud_hub)
891 		/* should never happen; children are only created after init */
892 		panic("hub not fully initialised, but child deleted?");
893 
894 	nports = devhub->ud_hub->uh_hubdesc.bNbrPorts;
895 	for (port = 0; port < nports; port++) {
896 		dev = devhub->ud_hub->uh_ports[port].up_dev;
897 		if (!dev || dev->ud_subdevlen == 0)
898 			continue;
899 		for (i = 0; i < dev->ud_subdevlen; i++) {
900 			if (dev->ud_subdevs[i] == child) {
901 				dev->ud_subdevs[i] = NULL;
902 				dev->ud_nifaces_claimed--;
903 			}
904 		}
905 		if (dev->ud_nifaces_claimed == 0) {
906 			kmem_free(dev->ud_subdevs,
907 			    dev->ud_subdevlen * sizeof(device_t));
908 			dev->ud_subdevs = NULL;
909 			dev->ud_subdevlen = 0;
910 		}
911 	}
912 }
913 
914 
915 /*
916  * Hub interrupt.
917  * This an indication that some port has changed status.
918  * Notify the bus event handler thread that we need
919  * to be explored again.
920  */
921 void
922 uhub_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
923 {
924 	struct uhub_softc *sc = addr;
925 
926 	UHUBHIST_FUNC(); UHUBHIST_CALLED();
927 
928 	DPRINTFN(5, "uhub%d", device_unit(sc->sc_dev), 0, 0, 0);
929 
930 	if (status == USBD_STALLED)
931 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
932 	else if (status == USBD_NORMAL_COMPLETION) {
933 
934 		mutex_enter(&sc->sc_lock);
935 
936 		DPRINTFN(5, "uhub%d: explore pending %d",
937 		    device_unit(sc->sc_dev), sc->sc_explorepending, 0, 0);
938 
939 		/* merge port bitmap into pending interrupts list */
940 		for (size_t i = 0; i < sc->sc_statuslen; i++) {
941 			sc->sc_statuspend[i] |= sc->sc_statusbuf[i];
942 
943 			DPRINTFN(5, "uhub%d: pending/new ports "
944 			    "[%d] %#x/%#x", device_unit(sc->sc_dev),
945 			    i, sc->sc_statuspend[i], sc->sc_statusbuf[i]);
946 		}
947 
948 		if (!sc->sc_explorepending) {
949 			sc->sc_explorepending = 1;
950 
951 			memcpy(sc->sc_status, sc->sc_statuspend,
952 			    sc->sc_statuslen);
953 			memset(sc->sc_statuspend, 0, sc->sc_statuslen);
954 
955 			for (size_t i = 0; i < sc->sc_statuslen; i++) {
956 				DPRINTFN(5, "uhub%d: exploring ports "
957 				    "[%d] %#x", device_unit(sc->sc_dev),
958 				    i, sc->sc_status[i], 0);
959 			}
960 
961 			usb_needs_explore(sc->sc_hub);
962 		}
963 		mutex_exit(&sc->sc_lock);
964 	}
965 }
966