xref: /openbsd-src/sys/dev/usb/uhub.c (revision b803619633b47e09895c24f4cfb35d50a3052141)
1 /*	$OpenBSD: uhub.c,v 1.82 2015/01/02 11:58:32 mpi 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 		ttthink = UGETW(hd.hs.wHubCharacteristics) & UHD_TT_THINK;
171 		if (!err && nports > 7)
172 			usbd_get_hub_descriptor(dev, &hd.hs, nports);
173 	}
174 
175 	if (err) {
176 		DPRINTF("%s: getting hub descriptor failed, error=%s\n",
177 			 sc->sc_dev.dv_xname, usbd_errstr(err));
178 		return;
179 	}
180 
181 #ifdef UHUB_DEBUG
182 	for (nremov = 0, port = 1; port <= nports; port++) {
183 		if (dev->speed == USB_SPEED_SUPER) {
184 			if (!UHD_NOT_REMOV(&hd.ss, port))
185 				nremov++;
186 		} else {
187 			if (!UHD_NOT_REMOV(&hd.hs, port))
188 				nremov++;
189 		}
190 	}
191 
192 	printf("%s: %d port%s with %d removable, %s powered",
193 	       sc->sc_dev.dv_xname, nports, nports != 1 ? "s" : "",
194 	       nremov, dev->self_powered ? "self" : "bus");
195 
196 	if (dev->depth > 0 && UHUB_IS_HIGH_SPEED(sc)) {
197 		printf(", %s transaction translator%s",
198 		    UHUB_IS_SINGLE_TT(sc) ? "single" : "multiple",
199 		    UHUB_IS_SINGLE_TT(sc) ? "" : "s");
200 	}
201 
202 	printf("\n");
203 #endif
204 
205 	if (nports == 0) {
206 		printf("%s: no ports, hub ignored\n", sc->sc_dev.dv_xname);
207 		goto bad;
208 	}
209 
210 	hub = malloc(sizeof(*hub), M_USBDEV, M_NOWAIT);
211 	if (hub == NULL)
212 		return;
213 	hub->ports = mallocarray(nports, sizeof(struct usbd_port),
214 	    M_USBDEV, M_NOWAIT);
215 	if (hub->ports == NULL) {
216 		free(hub, M_USBDEV, 0);
217 		return;
218 	}
219 	dev->hub = hub;
220 	dev->hub->hubsoftc = sc;
221 	hub->explore = uhub_explore;
222 	hub->nports = nports;
223 	hub->powerdelay = powerdelay;
224 	hub->ttthink = ttthink >> 5;
225 
226 	if (!dev->self_powered && dev->powersrc->parent != NULL &&
227 	    !dev->powersrc->parent->self_powered) {
228 		printf("%s: bus powered hub connected to bus powered hub, "
229 		       "ignored\n", sc->sc_dev.dv_xname);
230 		goto bad;
231 	}
232 
233 	/* Set up interrupt pipe. */
234 	err = usbd_device2interface_handle(dev, 0, &iface);
235 	if (err) {
236 		printf("%s: no interface handle\n", sc->sc_dev.dv_xname);
237 		goto bad;
238 	}
239 	ed = usbd_interface2endpoint_descriptor(iface, 0);
240 	if (ed == NULL) {
241 		printf("%s: no endpoint descriptor\n", sc->sc_dev.dv_xname);
242 		goto bad;
243 	}
244 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
245 		printf("%s: bad interrupt endpoint\n", sc->sc_dev.dv_xname);
246 		goto bad;
247 	}
248 
249 	sc->sc_statuslen = (nports + 1 + 7) / 8;
250 	sc->sc_statusbuf = malloc(sc->sc_statuslen, M_USBDEV, M_NOWAIT);
251 	if (!sc->sc_statusbuf)
252 		goto bad;
253 
254 	err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
255 		  USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_statusbuf,
256 		  sc->sc_statuslen, uhub_intr, UHUB_INTR_INTERVAL);
257 	if (err) {
258 		printf("%s: cannot open interrupt pipe\n",
259 		       sc->sc_dev.dv_xname);
260 		goto bad;
261 	}
262 
263 	/* Wait with power off for a while. */
264 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
265 
266 	/*
267 	 * To have the best chance of success we do things in the exact same
268 	 * order as Windoze98.  This should not be necessary, but some
269 	 * devices do not follow the USB specs to the letter.
270 	 *
271 	 * These are the events on the bus when a hub is attached:
272 	 *  Get device and config descriptors (see attach code)
273 	 *  Get hub descriptor (see above)
274 	 *  For all ports
275 	 *     turn on power
276 	 *     wait for power to become stable
277 	 * (all below happens in explore code)
278 	 *  For all ports
279 	 *     clear C_PORT_CONNECTION
280 	 *  For all ports
281 	 *     get port status
282 	 *     if device connected
283 	 *        wait 100 ms
284 	 *        turn on reset
285 	 *        wait
286 	 *        clear C_PORT_RESET
287 	 *        get port status
288 	 *        proceed with device attachment
289 	 */
290 
291 	if (UHUB_IS_HIGH_SPEED(sc)) {
292 		tts = mallocarray((UHUB_IS_SINGLE_TT(sc) ? 1 : nports),
293 		    sizeof (struct usbd_tt), M_USBDEV, M_NOWAIT);
294 		if (!tts)
295 			goto bad;
296 	}
297 	/* Set up data structures */
298 	for (p = 0; p < nports; p++) {
299 		struct usbd_port *up = &hub->ports[p];
300 		up->device = NULL;
301 		up->parent = dev;
302 		up->portno = p+1;
303 		if (dev->self_powered)
304 			/* Self powered hub, give ports maximum current. */
305 			up->power = USB_MAX_POWER;
306 		else
307 			up->power = USB_MIN_POWER;
308 		up->restartcnt = 0;
309 		up->reattach = 0;
310 		if (UHUB_IS_HIGH_SPEED(sc)) {
311 			up->tt = &tts[UHUB_IS_SINGLE_TT(sc) ? 0 : p];
312 			up->tt->hub = hub;
313 		} else {
314 			up->tt = NULL;
315 		}
316 	}
317 
318 	for (port = 1; port <= nports; port++) {
319 		/* Turn the power on. */
320 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
321 		if (err)
322 			printf("%s: port %d power on failed, %s\n",
323 			       sc->sc_dev.dv_xname, port,
324 			       usbd_errstr(err));
325 	}
326 
327 	/* Wait for stable power. */
328         if (dev->powersrc->parent != NULL)
329 		usbd_delay_ms(dev, powerdelay + USB_EXTRA_POWER_UP_TIME);
330 
331 	/* The usual exploration will finish the setup. */
332 
333 	sc->sc_running = 1;
334 
335 	return;
336 
337  bad:
338 	if (sc->sc_statusbuf)
339 		free(sc->sc_statusbuf, M_USBDEV, 0);
340 	if (hub) {
341 		if (hub->ports)
342 			free(hub->ports, M_USBDEV, 0);
343 		free(hub, M_USBDEV, 0);
344 	}
345 	dev->hub = NULL;
346 }
347 
348 int
349 uhub_explore(struct usbd_device *dev)
350 {
351 	struct uhub_softc *sc = dev->hub->hubsoftc;
352 	struct usbd_port *up;
353 	usbd_status err;
354 	int speed;
355 	int port;
356 	int change, status, reconnect;
357 
358 	if (usbd_is_dying(dev))
359 		return (EIO);
360 
361 	if (!sc->sc_running)
362 		return (ENXIO);
363 
364 	/* Ignore hubs that are too deep. */
365 	if (dev->depth > USB_HUB_MAX_DEPTH)
366 		return (EOPNOTSUPP);
367 
368 	for (port = 1; port <= dev->hub->nports; port++) {
369 		up = &dev->hub->ports[port-1];
370 		err = usbd_get_port_status(dev, port, &up->status);
371 		if (err) {
372 			DPRINTF("%s: get port %d status failed, error=%s\n",
373 			    sc->sc_dev.dv_xname, port, usbd_errstr(err));
374 			continue;
375 		}
376 		status = UGETW(up->status.wPortStatus);
377 		change = UGETW(up->status.wPortChange);
378 		reconnect = up->reattach;
379 		up->reattach = 0;
380 		DPRINTF("%s: port %d status=0x%04x change=0x%04x\n",
381 		    sc->sc_dev.dv_xname, port, status, change);
382 		if (change & UPS_C_PORT_ENABLED) {
383 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
384 			if (change & UPS_C_CONNECT_STATUS) {
385 				/* Ignore the port error if the device
386 				   vanished. */
387 			} else if (status & UPS_PORT_ENABLED) {
388 				printf("%s: illegal enable change, port %d\n",
389 				       sc->sc_dev.dv_xname, port);
390 			} else {
391 				/* Port error condition. */
392 				if (up->restartcnt) /* no message first time */
393 					printf("%s: port error, restarting "
394 					       "port %d\n",
395 					       sc->sc_dev.dv_xname, port);
396 
397 				if (up->restartcnt++ < USBD_RESTART_MAX)
398 					goto disco;
399 				else
400 					printf("%s: port error, giving up "
401 					       "port %d\n",
402 					       sc->sc_dev.dv_xname, port);
403 			}
404 		}
405 		if (!reconnect && !(change & UPS_C_CONNECT_STATUS)) {
406 			/* No status change, just do recursive explore. */
407 			if (up->device != NULL && up->device->hub != NULL)
408 				up->device->hub->explore(up->device);
409 			continue;
410 		}
411 
412 		/* We have a connect status change, handle it. */
413 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
414 		/*
415 		 * If there is already a device on the port the change status
416 		 * must mean that is has disconnected.  Looking at the
417 		 * current connect status is not enough to figure this out
418 		 * since a new unit may have been connected before we handle
419 		 * the disconnect.
420 		 */
421 	disco:
422 		if (up->device != NULL) {
423 			/* Disconnected */
424 			usbd_detach(up->device, &sc->sc_dev);
425 			up->device = NULL;
426 			usbd_clear_port_feature(dev, port,
427 						UHF_C_PORT_CONNECTION);
428 		}
429 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
430 			/* Nothing connected, just ignore it. */
431 			continue;
432 		}
433 
434 		/* Connected */
435 		if (!(status & (UPS_PORT_POWER|UPS_PORT_POWER_SS))) {
436 			printf("%s: connected port %d has no power\n",
437 			       sc->sc_dev.dv_xname, port);
438 			continue;
439 		}
440 
441 		/* Wait for maximum device power up time. */
442 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
443 
444 		/* Reset port, which implies enabling it. */
445 		if (usbd_reset_port(dev, port)) {
446 			printf("%s: port %d reset failed\n",
447 			       sc->sc_dev.dv_xname, port);
448 			continue;
449 		}
450 		/* Get port status again, it might have changed during reset */
451 		err = usbd_get_port_status(dev, port, &up->status);
452 		if (err) {
453 			DPRINTF("%s: get port %d status failed, error=%s\n",
454 			    sc->sc_dev.dv_xname, port, usbd_errstr(err));
455 			continue;
456 		}
457 		status = UGETW(up->status.wPortStatus);
458 		change = UGETW(up->status.wPortChange);
459 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
460 			/* Nothing connected, just ignore it. */
461 			DPRINTF("%s: port %d, device disappeared after reset\n",
462 			    sc->sc_dev.dv_xname, port);
463 			continue;
464 		}
465 
466 		/*
467 		 * Figure out device speed.  This is a bit tricky because
468 		 * UPS_PORT_POWER_SS and UPS_LOW_SPEED share the same bit.
469 		 */
470 		if ((status & UPS_PORT_POWER) == 0)
471 			status &= ~UPS_PORT_POWER_SS;
472 
473 		if (status & UPS_SUPER_SPEED)
474 			speed = USB_SPEED_SUPER;
475 		else if (status & UPS_HIGH_SPEED)
476 			speed = USB_SPEED_HIGH;
477 		else if (status & UPS_LOW_SPEED)
478 			speed = USB_SPEED_LOW;
479 		else {
480 			/*
481 			 * If there is no power bit set, it is certainly
482 			 * a Super Speed device, so use the speed of its
483 			 * parent hub.
484 			 */
485 			if (status & UPS_PORT_POWER)
486 				speed = USB_SPEED_FULL;
487 			else
488 				speed = sc->sc_hub->speed;
489 		}
490 
491 		/*
492 		 * Reduce the speed, otherwise we won't setup the proper
493 		 * transfer methods.
494 		 */
495 		if (speed > sc->sc_hub->speed)
496 			speed = sc->sc_hub->speed;
497 
498 		/* Get device info and set its address. */
499 		err = usbd_new_device(&sc->sc_dev, dev->bus,
500 			  dev->depth + 1, speed, port, up);
501 		/* XXX retry a few times? */
502 		if (err) {
503 			DPRINTF("%s: usbd_new_device failed, error=%s\n",
504 			    sc->sc_dev.dv_xname, usbd_errstr(err));
505 			/* Avoid addressing problems by disabling. */
506 			/* usbd_reset_port(dev, port, &up->status); */
507 
508 			/*
509 			 * The unit refused to accept a new address, or had
510 			 * some other serious problem.  Since we cannot leave
511 			 * at 0 we have to disable the port instead.
512 			 */
513 			printf("%s: device problem, disabling port %d\n",
514 			       sc->sc_dev.dv_xname, port);
515 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
516 		} else {
517 			/* The port set up succeeded, reset error count. */
518 			up->restartcnt = 0;
519 
520 			if (up->device->hub)
521 				up->device->hub->explore(up->device);
522 		}
523 	}
524 
525 	return (0);
526 }
527 
528 /*
529  * Called from process context when the hub is gone.
530  * Detach all devices on active ports.
531  */
532 int
533 uhub_detach(struct device *self, int flags)
534 {
535 	struct uhub_softc *sc = (struct uhub_softc *)self;
536 	struct usbd_hub *hub = sc->sc_hub->hub;
537 	struct usbd_port *rup;
538 	int port;
539 
540 	if (hub == NULL)		/* Must be partially working */
541 		return (0);
542 
543 	usbd_abort_pipe(sc->sc_ipipe);
544 	usbd_close_pipe(sc->sc_ipipe);
545 
546 	for (port = 0; port < hub->nports; port++) {
547 		rup = &hub->ports[port];
548 		if (rup->device != NULL) {
549 			usbd_detach(rup->device, self);
550 			rup->device = NULL;
551 		}
552 	}
553 
554 	if (hub->ports[0].tt)
555 		free(hub->ports[0].tt, M_USBDEV, 0);
556 	if (sc->sc_statusbuf)
557 		free(sc->sc_statusbuf, M_USBDEV, 0);
558 	if (hub->ports)
559 		free(hub->ports, M_USBDEV, 0);
560 	free(hub, M_USBDEV, 0);
561 	sc->sc_hub->hub = NULL;
562 
563 	return (0);
564 }
565 
566 /*
567  * This is an indication that some port has changed status.  Remember
568  * the ports that need attention and notify the USB task thread that
569  * we need to be explored again.
570  */
571 void
572 uhub_intr(struct usbd_xfer *xfer, void *addr, usbd_status status)
573 {
574 	struct uhub_softc *sc = addr;
575 
576 	if (usbd_is_dying(sc->sc_hub))
577 		return;
578 
579 	DPRINTF("%s: intr status=%d\n", sc->sc_dev.dv_xname, status);
580 
581 	if (status == USBD_STALLED)
582 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
583 	else if (status == USBD_NORMAL_COMPLETION)
584 		usb_needs_explore(sc->sc_hub, 0);
585 }
586