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