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