xref: /openbsd-src/sys/dev/usb/uhub.c (revision 0f0d0f957e83845b9ea328181972c6df85dc75c5)
1 /*	$OpenBSD: uhub.c,v 1.81 2014/12/09 07:05:06 doug Exp $ */
2 /*	$NetBSD: uhub.c,v 1.64 2003/02/08 03:32:51 ichiro Exp $	*/
3 /*	$FreeBSD: src/sys/dev/usb/uhub.c,v 1.18 1999/11/17 22:33:43 n_hibma Exp $	*/
4 
5 /*
6  * Copyright (c) 1998 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 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
38 #include <sys/malloc.h>
39 #include <sys/device.h>
40 
41 #include <machine/bus.h>
42 
43 #include <dev/usb/usb.h>
44 #include <dev/usb/usbdi.h>
45 #include <dev/usb/usbdi_util.h>
46 #include <dev/usb/usbdivar.h>
47 
48 #define UHUB_INTR_INTERVAL 255	/* ms */
49 
50 #ifdef UHUB_DEBUG
51 #define DPRINTF(x...)	do { printf(x); } while (0)
52 #else
53 #define DPRINTF(x...)
54 #endif
55 
56 struct uhub_softc {
57 	struct device		sc_dev;		/* base device */
58 	struct usbd_device	*sc_hub;	/* USB device */
59 	struct usbd_pipe	*sc_ipipe;	/* interrupt pipe */
60 	u_int8_t		*sc_statusbuf;	/* per port status buffer */
61 	size_t			sc_statuslen;	/* status bufferlen */
62 	u_char			sc_running;
63 };
64 #define UHUB_PROTO(sc) ((sc)->sc_hub->ddesc.bDeviceProtocol)
65 #define UHUB_IS_HIGH_SPEED(sc) (UHUB_PROTO(sc) != UDPROTO_FSHUB)
66 #define UHUB_IS_SINGLE_TT(sc) (UHUB_PROTO(sc) == UDPROTO_HSHUBSTT)
67 
68 int uhub_explore(struct usbd_device *hub);
69 void uhub_intr(struct usbd_xfer *, void *, usbd_status);
70 
71 /*
72  * We need two attachment points:
73  * hub to usb and hub to hub
74  * Every other driver only connects to hubs
75  */
76 
77 int uhub_match(struct device *, void *, void *);
78 void uhub_attach(struct device *, struct device *, void *);
79 int uhub_detach(struct device *, int);
80 
81 struct cfdriver uhub_cd = {
82 	NULL, "uhub", DV_DULL
83 };
84 
85 const struct cfattach uhub_ca = {
86 	sizeof(struct uhub_softc), uhub_match, uhub_attach,  uhub_detach
87 };
88 
89 const struct cfattach uhub_uhub_ca = {
90 	sizeof(struct uhub_softc), uhub_match, uhub_attach,  uhub_detach
91 };
92 
93 int
94 uhub_match(struct device *parent, void *match, void *aux)
95 {
96 	struct usb_attach_arg *uaa = aux;
97 	usb_device_descriptor_t *dd = usbd_get_device_descriptor(uaa->device);
98 
99 	/*
100 	 * The subclass for hubs seems to be 0 for some and 1 for others,
101 	 * so we just ignore the subclass.
102 	 */
103 	if (uaa->iface == NULL && dd->bDeviceClass == UDCLASS_HUB)
104 		return (UMATCH_DEVCLASS_DEVSUBCLASS);
105 	return (UMATCH_NONE);
106 }
107 
108 void
109 uhub_attach(struct device *parent, struct device *self, void *aux)
110 {
111 	struct uhub_softc *sc = (struct uhub_softc *)self;
112 	struct usb_attach_arg *uaa = aux;
113 	struct usbd_device *dev = uaa->device;
114 	struct usbd_hub *hub = NULL;
115 	union {
116 		usb_hub_descriptor_t	hs;
117 		usb_hub_ss_descriptor_t	ss;
118 	} hd;
119 	int p, port, nports, powerdelay;
120 	struct usbd_interface *iface;
121 	usb_endpoint_descriptor_t *ed;
122 	struct usbd_tt *tts = NULL;
123 	uint8_t ttthink = 0;
124 	usbd_status err;
125 #ifdef UHUB_DEBUG
126 	int nremov;
127 #endif
128 
129 	sc->sc_hub = dev;
130 
131 	err = usbd_set_config_index(dev, 0, 1);
132 	if (err) {
133 		DPRINTF("%s: configuration failed, error=%s\n",
134 			 sc->sc_dev.dv_xname, usbd_errstr(err));
135 		return;
136 	}
137 
138 	if (dev->depth > USB_HUB_MAX_DEPTH) {
139 		printf("%s: hub depth (%d) exceeded, hub ignored\n",
140 		       sc->sc_dev.dv_xname, USB_HUB_MAX_DEPTH);
141 		return;
142 	}
143 
144 	/*
145 	 * Super-Speed hubs need to know their depth to be able to
146 	 * parse the bits of the route-string that correspond to
147 	 * their downstream port number.
148 	 *
149 	 * This does no apply to root hubs.
150 	 */
151 	if (dev->depth != 0 && dev->speed == USB_SPEED_SUPER) {
152 		if (usbd_set_hub_depth(dev, dev->depth - 1)) {
153 			printf("%s: unable to set HUB depth\n",
154 			    sc->sc_dev.dv_xname);
155 			return;
156 		}
157 	}
158 
159 	/* Get hub descriptor. */
160 	if (dev->speed == USB_SPEED_SUPER) {
161 		err = usbd_get_hub_ss_descriptor(dev, &hd.ss, 1);
162 		nports = hd.ss.bNbrPorts;
163 		powerdelay = (hd.ss.bPwrOn2PwrGood * UHD_PWRON_FACTOR);
164 		if (!err && nports > 7)
165 			usbd_get_hub_ss_descriptor(dev, &hd.ss, nports);
166 	} else {
167 		err = usbd_get_hub_descriptor(dev, &hd.hs, 1);
168 		nports = hd.hs.bNbrPorts;
169 		powerdelay = (hd.hs.bPwrOn2PwrGood * UHD_PWRON_FACTOR);
170 		if (!err && nports > 7)
171 			usbd_get_hub_descriptor(dev, &hd.hs, nports);
172 	}
173 
174 	if (err) {
175 		DPRINTF("%s: getting hub descriptor failed, error=%s\n",
176 			 sc->sc_dev.dv_xname, usbd_errstr(err));
177 		return;
178 	}
179 
180 #ifdef UHUB_DEBUG
181 	for (nremov = 0, port = 1; port <= nports; port++) {
182 		if (dev->speed == USB_SPEED_SUPER) {
183 			if (!UHD_NOT_REMOV(&hd.ss, port))
184 				nremov++;
185 		} else {
186 			if (!UHD_NOT_REMOV(&hd.hs, port))
187 				nremov++;
188 		}
189 	}
190 
191 	printf("%s: %d port%s with %d removable, %s powered",
192 	       sc->sc_dev.dv_xname, nports, nports != 1 ? "s" : "",
193 	       nremov, dev->self_powered ? "self" : "bus");
194 
195 	if (dev->depth > 0 && UHUB_IS_HIGH_SPEED(sc)) {
196 		printf(", %s transaction translator%s",
197 		    UHUB_IS_SINGLE_TT(sc) ? "single" : "multiple",
198 		    UHUB_IS_SINGLE_TT(sc) ? "" : "s");
199 	}
200 
201 	printf("\n");
202 #endif
203 
204 	if (nports == 0) {
205 		printf("%s: no ports, hub ignored\n", sc->sc_dev.dv_xname);
206 		goto bad;
207 	}
208 
209 	hub = malloc(sizeof(*hub), M_USBDEV, M_NOWAIT);
210 	if (hub == NULL)
211 		return;
212 	hub->ports = mallocarray(nports, sizeof(struct usbd_port),
213 	    M_USBDEV, M_NOWAIT);
214 	if (hub->ports == NULL) {
215 		free(hub, M_USBDEV, 0);
216 		return;
217 	}
218 	dev->hub = hub;
219 	dev->hub->hubsoftc = sc;
220 	hub->explore = uhub_explore;
221 	hub->nports = nports;
222 	hub->powerdelay = powerdelay;
223 	hub->ttthink = ttthink;
224 
225 	if (!dev->self_powered && dev->powersrc->parent != NULL &&
226 	    !dev->powersrc->parent->self_powered) {
227 		printf("%s: bus powered hub connected to bus powered hub, "
228 		       "ignored\n", sc->sc_dev.dv_xname);
229 		goto bad;
230 	}
231 
232 	/* Set up interrupt pipe. */
233 	err = usbd_device2interface_handle(dev, 0, &iface);
234 	if (err) {
235 		printf("%s: no interface handle\n", sc->sc_dev.dv_xname);
236 		goto bad;
237 	}
238 	ed = usbd_interface2endpoint_descriptor(iface, 0);
239 	if (ed == NULL) {
240 		printf("%s: no endpoint descriptor\n", sc->sc_dev.dv_xname);
241 		goto bad;
242 	}
243 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
244 		printf("%s: bad interrupt endpoint\n", sc->sc_dev.dv_xname);
245 		goto bad;
246 	}
247 
248 	sc->sc_statuslen = (nports + 1 + 7) / 8;
249 	sc->sc_statusbuf = malloc(sc->sc_statuslen, M_USBDEV, M_NOWAIT);
250 	if (!sc->sc_statusbuf)
251 		goto bad;
252 
253 	err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
254 		  USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_statusbuf,
255 		  sc->sc_statuslen, uhub_intr, UHUB_INTR_INTERVAL);
256 	if (err) {
257 		printf("%s: cannot open interrupt pipe\n",
258 		       sc->sc_dev.dv_xname);
259 		goto bad;
260 	}
261 
262 	/* Wait with power off for a while. */
263 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
264 
265 	/*
266 	 * To have the best chance of success we do things in the exact same
267 	 * order as Windoze98.  This should not be necessary, but some
268 	 * devices do not follow the USB specs to the letter.
269 	 *
270 	 * These are the events on the bus when a hub is attached:
271 	 *  Get device and config descriptors (see attach code)
272 	 *  Get hub descriptor (see above)
273 	 *  For all ports
274 	 *     turn on power
275 	 *     wait for power to become stable
276 	 * (all below happens in explore code)
277 	 *  For all ports
278 	 *     clear C_PORT_CONNECTION
279 	 *  For all ports
280 	 *     get port status
281 	 *     if device connected
282 	 *        wait 100 ms
283 	 *        turn on reset
284 	 *        wait
285 	 *        clear C_PORT_RESET
286 	 *        get port status
287 	 *        proceed with device attachment
288 	 */
289 
290 	if (UHUB_IS_HIGH_SPEED(sc)) {
291 		tts = mallocarray((UHUB_IS_SINGLE_TT(sc) ? 1 : nports),
292 		    sizeof (struct usbd_tt), M_USBDEV, M_NOWAIT);
293 		if (!tts)
294 			goto bad;
295 	}
296 	/* Set up data structures */
297 	for (p = 0; p < nports; p++) {
298 		struct usbd_port *up = &hub->ports[p];
299 		up->device = NULL;
300 		up->parent = dev;
301 		up->portno = p+1;
302 		if (dev->self_powered)
303 			/* Self powered hub, give ports maximum current. */
304 			up->power = USB_MAX_POWER;
305 		else
306 			up->power = USB_MIN_POWER;
307 		up->restartcnt = 0;
308 		up->reattach = 0;
309 		if (UHUB_IS_HIGH_SPEED(sc)) {
310 			up->tt = &tts[UHUB_IS_SINGLE_TT(sc) ? 0 : p];
311 			up->tt->hub = hub;
312 		} else {
313 			up->tt = NULL;
314 		}
315 	}
316 
317 	for (port = 1; port <= nports; port++) {
318 		/* Turn the power on. */
319 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
320 		if (err)
321 			printf("%s: port %d power on failed, %s\n",
322 			       sc->sc_dev.dv_xname, port,
323 			       usbd_errstr(err));
324 	}
325 
326 	/* Wait for stable power. */
327         if (dev->powersrc->parent != NULL)
328 		usbd_delay_ms(dev, powerdelay + USB_EXTRA_POWER_UP_TIME);
329 
330 	/* The usual exploration will finish the setup. */
331 
332 	sc->sc_running = 1;
333 
334 	return;
335 
336  bad:
337 	if (sc->sc_statusbuf)
338 		free(sc->sc_statusbuf, M_USBDEV, 0);
339 	if (hub) {
340 		if (hub->ports)
341 			free(hub->ports, M_USBDEV, 0);
342 		free(hub, M_USBDEV, 0);
343 	}
344 	dev->hub = NULL;
345 }
346 
347 int
348 uhub_explore(struct usbd_device *dev)
349 {
350 	struct uhub_softc *sc = dev->hub->hubsoftc;
351 	struct usbd_port *up;
352 	usbd_status err;
353 	int speed;
354 	int port;
355 	int change, status, reconnect;
356 
357 	if (usbd_is_dying(dev))
358 		return (EIO);
359 
360 	if (!sc->sc_running)
361 		return (ENXIO);
362 
363 	/* Ignore hubs that are too deep. */
364 	if (dev->depth > USB_HUB_MAX_DEPTH)
365 		return (EOPNOTSUPP);
366 
367 	for (port = 1; port <= dev->hub->nports; port++) {
368 		up = &dev->hub->ports[port-1];
369 		err = usbd_get_port_status(dev, port, &up->status);
370 		if (err) {
371 			DPRINTF("%s: get port %d status failed, error=%s\n",
372 			    sc->sc_dev.dv_xname, port, usbd_errstr(err));
373 			continue;
374 		}
375 		status = UGETW(up->status.wPortStatus);
376 		change = UGETW(up->status.wPortChange);
377 		reconnect = up->reattach;
378 		up->reattach = 0;
379 		DPRINTF("%s: port %d status=0x%04x change=0x%04x\n",
380 		    sc->sc_dev.dv_xname, port, status, change);
381 		if (change & UPS_C_PORT_ENABLED) {
382 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
383 			if (change & UPS_C_CONNECT_STATUS) {
384 				/* Ignore the port error if the device
385 				   vanished. */
386 			} else if (status & UPS_PORT_ENABLED) {
387 				printf("%s: illegal enable change, port %d\n",
388 				       sc->sc_dev.dv_xname, port);
389 			} else {
390 				/* Port error condition. */
391 				if (up->restartcnt) /* no message first time */
392 					printf("%s: port error, restarting "
393 					       "port %d\n",
394 					       sc->sc_dev.dv_xname, port);
395 
396 				if (up->restartcnt++ < USBD_RESTART_MAX)
397 					goto disco;
398 				else
399 					printf("%s: port error, giving up "
400 					       "port %d\n",
401 					       sc->sc_dev.dv_xname, port);
402 			}
403 		}
404 		if (!reconnect && !(change & UPS_C_CONNECT_STATUS)) {
405 			/* No status change, just do recursive explore. */
406 			if (up->device != NULL && up->device->hub != NULL)
407 				up->device->hub->explore(up->device);
408 			continue;
409 		}
410 
411 		/* We have a connect status change, handle it. */
412 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
413 		/*
414 		 * If there is already a device on the port the change status
415 		 * must mean that is has disconnected.  Looking at the
416 		 * current connect status is not enough to figure this out
417 		 * since a new unit may have been connected before we handle
418 		 * the disconnect.
419 		 */
420 	disco:
421 		if (up->device != NULL) {
422 			/* Disconnected */
423 			usbd_detach(up->device, &sc->sc_dev);
424 			up->device = NULL;
425 			usbd_clear_port_feature(dev, port,
426 						UHF_C_PORT_CONNECTION);
427 		}
428 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
429 			/* Nothing connected, just ignore it. */
430 			continue;
431 		}
432 
433 		/* Connected */
434 		if (!(status & (UPS_PORT_POWER|UPS_PORT_POWER_SS))) {
435 			printf("%s: connected port %d has no power\n",
436 			       sc->sc_dev.dv_xname, port);
437 			continue;
438 		}
439 
440 		/* Wait for maximum device power up time. */
441 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
442 
443 		/* Reset port, which implies enabling it. */
444 		if (usbd_reset_port(dev, port)) {
445 			printf("%s: port %d reset failed\n",
446 			       sc->sc_dev.dv_xname, port);
447 			continue;
448 		}
449 		/* Get port status again, it might have changed during reset */
450 		err = usbd_get_port_status(dev, port, &up->status);
451 		if (err) {
452 			DPRINTF("%s: get port %d status failed, error=%s\n",
453 			    sc->sc_dev.dv_xname, port, usbd_errstr(err));
454 			continue;
455 		}
456 		status = UGETW(up->status.wPortStatus);
457 		change = UGETW(up->status.wPortChange);
458 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
459 			/* Nothing connected, just ignore it. */
460 			DPRINTF("%s: port %d, device disappeared after reset\n",
461 			    sc->sc_dev.dv_xname, port);
462 			continue;
463 		}
464 
465 		/*
466 		 * Figure out device speed.  This is a bit tricky because
467 		 * UPS_PORT_POWER_SS and UPS_LOW_SPEED share the same bit.
468 		 */
469 		if ((status & UPS_PORT_POWER) == 0)
470 			status &= ~UPS_PORT_POWER_SS;
471 
472 		if (status & UPS_SUPER_SPEED)
473 			speed = USB_SPEED_SUPER;
474 		else if (status & UPS_HIGH_SPEED)
475 			speed = USB_SPEED_HIGH;
476 		else if (status & UPS_LOW_SPEED)
477 			speed = USB_SPEED_LOW;
478 		else {
479 			/*
480 			 * If there is no power bit set, it is certainly
481 			 * a Super Speed device, so use the speed of its
482 			 * parent hub.
483 			 */
484 			if (status & UPS_PORT_POWER)
485 				speed = USB_SPEED_FULL;
486 			else
487 				speed = sc->sc_hub->speed;
488 		}
489 
490 		/*
491 		 * Reduce the speed, otherwise we won't setup the proper
492 		 * transfer methods.
493 		 */
494 		if (speed > sc->sc_hub->speed)
495 			speed = sc->sc_hub->speed;
496 
497 		/* Get device info and set its address. */
498 		err = usbd_new_device(&sc->sc_dev, dev->bus,
499 			  dev->depth + 1, speed, port, up);
500 		/* XXX retry a few times? */
501 		if (err) {
502 			DPRINTF("%s: usbd_new_device failed, error=%s\n",
503 			    sc->sc_dev.dv_xname, usbd_errstr(err));
504 			/* Avoid addressing problems by disabling. */
505 			/* usbd_reset_port(dev, port, &up->status); */
506 
507 			/*
508 			 * The unit refused to accept a new address, or had
509 			 * some other serious problem.  Since we cannot leave
510 			 * at 0 we have to disable the port instead.
511 			 */
512 			printf("%s: device problem, disabling port %d\n",
513 			       sc->sc_dev.dv_xname, port);
514 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
515 		} else {
516 			/* The port set up succeeded, reset error count. */
517 			up->restartcnt = 0;
518 
519 			if (up->device->hub)
520 				up->device->hub->explore(up->device);
521 		}
522 	}
523 
524 	return (0);
525 }
526 
527 /*
528  * Called from process context when the hub is gone.
529  * Detach all devices on active ports.
530  */
531 int
532 uhub_detach(struct device *self, int flags)
533 {
534 	struct uhub_softc *sc = (struct uhub_softc *)self;
535 	struct usbd_hub *hub = sc->sc_hub->hub;
536 	struct usbd_port *rup;
537 	int port;
538 
539 	if (hub == NULL)		/* Must be partially working */
540 		return (0);
541 
542 	usbd_abort_pipe(sc->sc_ipipe);
543 	usbd_close_pipe(sc->sc_ipipe);
544 
545 	for (port = 0; port < hub->nports; port++) {
546 		rup = &hub->ports[port];
547 		if (rup->device != NULL) {
548 			usbd_detach(rup->device, self);
549 			rup->device = NULL;
550 		}
551 	}
552 
553 	if (hub->ports[0].tt)
554 		free(hub->ports[0].tt, M_USBDEV, 0);
555 	if (sc->sc_statusbuf)
556 		free(sc->sc_statusbuf, M_USBDEV, 0);
557 	if (hub->ports)
558 		free(hub->ports, M_USBDEV, 0);
559 	free(hub, M_USBDEV, 0);
560 	sc->sc_hub->hub = NULL;
561 
562 	return (0);
563 }
564 
565 /*
566  * This is an indication that some port has changed status.  Remember
567  * the ports that need attention and notify the USB task thread that
568  * we need to be explored again.
569  */
570 void
571 uhub_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
572 {
573 	struct uhub_softc *sc = addr;
574 
575 	if (usbd_is_dying(sc->sc_hub))
576 		return;
577 
578 	DPRINTF("%s: intr status=%d\n", sc->sc_dev.dv_xname, status);
579 
580 	if (status == USBD_STALLED)
581 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
582 	else if (status == USBD_NORMAL_COMPLETION)
583 		usb_needs_explore(sc->sc_hub, 0);
584 }
585