xref: /openbsd-src/sys/dev/usb/uhub.c (revision 82426cf3b279940ef76b217706b0c03228290c05)
1 /*	$OpenBSD: uhub.c,v 1.10 2000/07/04 11:44:23 fgsch Exp $ */
2 /*	$NetBSD: uhub.c,v 1.41 2000/03/27 12:33:56 augustss 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  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *        This product includes software developed by the NetBSD
24  *        Foundation, Inc. and its contributors.
25  * 4. Neither the name of The NetBSD Foundation nor the names of its
26  *    contributors may be used to endorse or promote products derived
27  *    from this software without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39  * POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 /*
43  * USB spec: http://www.usb.org/developers/docs.htm
44  */
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/malloc.h>
50 #if defined(__NetBSD__) || defined(__OpenBSD__)
51 #include <sys/device.h>
52 #include <sys/proc.h>
53 #elif defined(__FreeBSD__)
54 #include <sys/module.h>
55 #include <sys/bus.h>
56 #include "bus_if.h"
57 #endif
58 
59 #include <machine/bus.h>
60 
61 #include <dev/usb/usb.h>
62 #include <dev/usb/usbdi.h>
63 #include <dev/usb/usbdi_util.h>
64 #include <dev/usb/usbdivar.h>
65 
66 #define UHUB_INTR_INTERVAL 255	/* ms */
67 
68 #ifdef UHUB_DEBUG
69 #define DPRINTF(x)	if (uhubdebug) logprintf x
70 #define DPRINTFN(n,x)	if (uhubdebug>(n)) logprintf x
71 int	uhubdebug;
72 #else
73 #define DPRINTF(x)
74 #define DPRINTFN(n,x)
75 #endif
76 
77 struct uhub_softc {
78 	USBBASEDEVICE		sc_dev;		/* base device */
79 	usbd_device_handle	sc_hub;		/* USB device */
80 	usbd_pipe_handle	sc_ipipe;	/* interrupt pipe */
81 	u_int8_t		sc_status[1];	/* XXX more ports */
82 	u_char			sc_running;
83 };
84 
85 Static usbd_status uhub_explore __P((usbd_device_handle hub));
86 Static void uhub_intr __P((usbd_xfer_handle, usbd_private_handle,usbd_status));
87 
88 #if defined(__FreeBSD__)
89 Static bus_child_detached_t uhub_child_detached;
90 #endif
91 
92 
93 /*
94  * We need two attachment points:
95  * hub to usb and hub to hub
96  * Every other driver only connects to hubs
97  */
98 
99 #if defined(__NetBSD__) || defined(__OpenBSD__)
100 USB_DECLARE_DRIVER(uhub);
101 
102 /* Create the driver instance for the hub connected to hub case */
103 struct cfattach uhub_uhub_ca = {
104 	sizeof(struct uhub_softc), uhub_match, uhub_attach,
105 	uhub_detach, uhub_activate
106 };
107 #elif defined(__FreeBSD__)
108 USB_DECLARE_DRIVER_INIT(uhub,
109 			DEVMETHOD(bus_child_detached, uhub_child_detached));
110 
111 /* Create the driver instance for the hub connected to usb case. */
112 devclass_t uhubroot_devclass;
113 
114 Static device_method_t uhubroot_methods[] = {
115 	DEVMETHOD(device_probe, uhub_match),
116 	DEVMETHOD(device_attach, uhub_attach),
117 
118 	/* detach is not allowed for a root hub */
119 	{0,0}
120 };
121 
122 Static	driver_t uhubroot_driver = {
123 	"uhub",
124 	uhubroot_methods,
125 	sizeof(struct uhub_softc)
126 };
127 #endif
128 
129 USB_MATCH(uhub)
130 {
131 	USB_MATCH_START(uhub, uaa);
132 	usb_device_descriptor_t *dd = usbd_get_device_descriptor(uaa->device);
133 
134 	DPRINTFN(5,("uhub_match, dd=%p\n", dd));
135 	/*
136 	 * The subclass for hubs seems to be 0 for some and 1 for others,
137 	 * so we just ignore the subclass.
138 	 */
139 	if (uaa->iface == NULL && dd->bDeviceClass == UDCLASS_HUB)
140 		return (UMATCH_DEVCLASS_DEVSUBCLASS);
141 	return (UMATCH_NONE);
142 }
143 
144 USB_ATTACH(uhub)
145 {
146 	USB_ATTACH_START(uhub, sc, uaa);
147 	usbd_device_handle dev = uaa->device;
148 	char devinfo[1024];
149 	usbd_status err;
150 	struct usbd_hub *hub;
151 	usb_device_request_t req;
152 	usb_hub_descriptor_t hubdesc;
153 	int p, port, nports, nremov, pwrdly;
154 	usbd_interface_handle iface;
155 	usb_endpoint_descriptor_t *ed;
156 
157 	DPRINTFN(1,("uhub_attach\n"));
158 	sc->sc_hub = dev;
159 	usbd_devinfo(dev, 1, devinfo);
160 	USB_ATTACH_SETUP;
161 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
162 
163 	err = usbd_set_config_index(dev, 0, 1);
164 	if (err) {
165 		DPRINTF(("%s: configuration failed, error=%s\n",
166 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
167 		USB_ATTACH_ERROR_RETURN;
168 	}
169 
170 	if (dev->depth > USB_HUB_MAX_DEPTH) {
171 		printf("%s: hub depth (%d) exceeded, hub ignored\n",
172 		       USBDEVNAME(sc->sc_dev), USB_HUB_MAX_DEPTH);
173 		USB_ATTACH_ERROR_RETURN;
174 	}
175 
176 	/* Get hub descriptor. */
177 	req.bmRequestType = UT_READ_CLASS_DEVICE;
178 	req.bRequest = UR_GET_DESCRIPTOR;
179 	USETW(req.wValue, 0);
180 	USETW(req.wIndex, 0);
181 	USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
182 	DPRINTFN(1,("usb_init_hub: getting hub descriptor\n"));
183 	err = usbd_do_request(dev, &req, &hubdesc);
184 	nports = hubdesc.bNbrPorts;
185 	if (!err && nports > 7) {
186 		USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE + (nports+1) / 8);
187 		err = usbd_do_request(dev, &req, &hubdesc);
188 	}
189 	if (err) {
190 		DPRINTF(("%s: getting hub descriptor failed, error=%s\n",
191 			 USBDEVNAME(sc->sc_dev), usbd_errstr(err)));
192 		USB_ATTACH_ERROR_RETURN;
193 	}
194 
195 	for (nremov = 0, port = 1; port <= nports; port++)
196 		if (!UHD_NOT_REMOV(&hubdesc, port))
197 			nremov++;
198 	printf("%s: %d port%s with %d removable, %s powered\n",
199 	       USBDEVNAME(sc->sc_dev), nports, nports != 1 ? "s" : "",
200 	       nremov, dev->self_powered ? "self" : "bus");
201 
202 	hub = malloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
203 		     M_USBDEV, M_NOWAIT);
204 	if (hub == NULL)
205 		USB_ATTACH_ERROR_RETURN;
206 	dev->hub = hub;
207 	dev->hub->hubsoftc = sc;
208 	hub->explore = uhub_explore;
209 	hub->hubdesc = hubdesc;
210 
211 	DPRINTFN(1,("usbhub_init_hub: selfpowered=%d, parent=%p, "
212 		    "parent->selfpowered=%d\n",
213 		 dev->self_powered, dev->powersrc->parent,
214 		 dev->powersrc->parent ?
215 		 dev->powersrc->parent->self_powered : 0));
216 
217 	if (!dev->self_powered && dev->powersrc->parent != NULL &&
218 	    !dev->powersrc->parent->self_powered) {
219 		printf("%s: bus powered hub connected to bus powered hub, "
220 		       "ignored\n", USBDEVNAME(sc->sc_dev));
221 		goto bad;
222 	}
223 
224 	/* Set up interrupt pipe. */
225 	err = usbd_device2interface_handle(dev, 0, &iface);
226 	if (err) {
227 		printf("%s: no interface handle\n", USBDEVNAME(sc->sc_dev));
228 		goto bad;
229 	}
230 	ed = usbd_interface2endpoint_descriptor(iface, 0);
231 	if (ed == NULL) {
232 		printf("%s: no endpoint descriptor\n", USBDEVNAME(sc->sc_dev));
233 		goto bad;
234 	}
235 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
236 		printf("%s: bad interrupt endpoint\n", USBDEVNAME(sc->sc_dev));
237 		goto bad;
238 	}
239 
240 	err = usbd_open_pipe_intr(iface, ed->bEndpointAddress,
241 		  USBD_SHORT_XFER_OK, &sc->sc_ipipe, sc, sc->sc_status,
242 		  sizeof(sc->sc_status), uhub_intr, UHUB_INTR_INTERVAL);
243 	if (err) {
244 		printf("%s: cannot open interrupt pipe\n",
245 		       USBDEVNAME(sc->sc_dev));
246 		goto bad;
247 	}
248 
249 	/* Wait with power off for a while. */
250 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
251 
252 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, dev, USBDEV(sc->sc_dev));
253 
254 	/*
255 	 * To have the best chance of success we do things in the exact same
256 	 * order as Windoze98.  This should not be necessary, but some
257 	 * devices do not follow the USB specs to the letter.
258 	 *
259 	 * These are the events on the bus when a hub is attached:
260 	 *  Get device and config descriptors (see attach code)
261 	 *  Get hub descriptor (see above)
262 	 *  For all ports
263 	 *     turn on power
264 	 *     wait for power to become stable
265 	 * (all below happens in explore code)
266 	 *  For all ports
267 	 *     clear C_PORT_CONNECTION
268 	 *  For all ports
269 	 *     get port status
270 	 *     if device connected
271 	 *        turn on reset
272 	 *        wait
273 	 *        clear C_PORT_RESET
274 	 *        get port status
275 	 *        proceed with device attachment
276 	 */
277 
278 	/* Set up data structures */
279 	for (p = 0; p < nports; p++) {
280 		struct usbd_port *up = &hub->ports[p];
281 		up->device = 0;
282 		up->parent = dev;
283 		up->portno = p+1;
284 		if (dev->self_powered)
285 			/* Self powered hub, give ports maximum current. */
286 			up->power = USB_MAX_POWER;
287 		else
288 			up->power = USB_MIN_POWER;
289 	}
290 
291 	/* XXX should check for none, individual, or ganged power? */
292 
293 	pwrdly = dev->hub->hubdesc.bPwrOn2PwrGood * UHD_PWRON_FACTOR
294 	    + USB_EXTRA_POWER_UP_TIME;
295 	for (port = 1; port <= nports; port++) {
296 		/* Turn the power on. */
297 		err = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
298 		if (err)
299 			printf("%s: port %d power on failed, %s\n",
300 			       USBDEVNAME(sc->sc_dev), port,
301 			       usbd_errstr(err));
302 		DPRINTF(("usb_init_port: turn on port %d power\n", port));
303 		/* Wait for stable power. */
304 		usbd_delay_ms(dev, pwrdly);
305 	}
306 
307 	/* The usual exploration will finish the setup. */
308 
309 	sc->sc_running = 1;
310 
311 	USB_ATTACH_SUCCESS_RETURN;
312 
313  bad:
314 	free(hub, M_USBDEV);
315 	dev->hub = 0;
316 	USB_ATTACH_ERROR_RETURN;
317 }
318 
319 usbd_status
320 uhub_explore(dev)
321 	usbd_device_handle dev;
322 {
323 	usb_hub_descriptor_t *hd = &dev->hub->hubdesc;
324 	struct uhub_softc *sc = dev->hub->hubsoftc;
325 	struct usbd_port *up;
326 	usbd_status err;
327 	int port;
328 	int change, status;
329 
330 	DPRINTFN(10, ("uhub_explore dev=%p addr=%d\n", dev, dev->address));
331 
332 	if (!sc->sc_running)
333 		return (USBD_NOT_STARTED);
334 
335 	/* Ignore hubs that are too deep. */
336 	if (dev->depth > USB_HUB_MAX_DEPTH)
337 		return (USBD_TOO_DEEP);
338 
339 	for(port = 1; port <= hd->bNbrPorts; port++) {
340 		up = &dev->hub->ports[port-1];
341 		err = usbd_get_port_status(dev, port, &up->status);
342 		if (err) {
343 			DPRINTF(("uhub_explore: get port status failed, "
344 				 "error=%s\n", usbd_errstr(err)));
345 			continue;
346 		}
347 		status = UGETW(up->status.wPortStatus);
348 		change = UGETW(up->status.wPortChange);
349 		DPRINTFN(3,("uhub_explore: port %d status 0x%04x 0x%04x\n",
350 			    port, status, change));
351 		if (change & UPS_C_PORT_ENABLED) {
352 			DPRINTF(("uhub_explore: C_PORT_ENABLED\n"));
353 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
354 			if (status & UPS_PORT_ENABLED) {
355 				printf("%s: illegal enable change, port %d\n",
356 				       USBDEVNAME(sc->sc_dev), port);
357 			} else {
358 				/* Port error condition. */
359 				if (up->restartcnt++ < USBD_RESTART_MAX) {
360 					printf("%s: port error, restarting "
361 					       "port %d\n",
362 					       USBDEVNAME(sc->sc_dev), port);
363 					goto disco;
364 				} else {
365 					printf("%s: port error, giving up "
366 					       "port %d\n",
367 					       USBDEVNAME(sc->sc_dev), port);
368 				}
369 			}
370 		}
371 		if (!(change & UPS_C_CONNECT_STATUS)) {
372 			DPRINTFN(3,("uhub_explore: port=%d !C_CONNECT_"
373 				    "STATUS\n", port));
374 			/* No status change, just do recursive explore. */
375 			if (up->device && up->device->hub)
376 				up->device->hub->explore(up->device);
377 			continue;
378 		}
379 
380 		/* We have a connect status change, handle it. */
381 
382 		DPRINTF(("uhub_explore: status change hub=%d port=%d\n",
383 			 dev->address, port));
384 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
385 		/*usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);*/
386 		/*
387 		 * If there is already a device on the port the change status
388 		 * must mean that is has disconnected.  Looking at the
389 		 * current connect status is not enough to figure this out
390 		 * since a new unit may have been connected before we handle
391 		 * the disconnect.
392 		 */
393 	disco:
394 		if (up->device != NULL) {
395 			/* Disconnected */
396 			DPRINTF(("uhub_explore: device addr=%d disappeared "
397 				 "on port %d\n", up->device->address, port));
398 			usb_disconnect_port(up, USBDEV(sc->sc_dev));
399 			usbd_clear_port_feature(dev, port,
400 						UHF_C_PORT_CONNECTION);
401 		}
402 		if (!(status & UPS_CURRENT_CONNECT_STATUS)) {
403 			/* Nothing connected, just ignore it. */
404 			DPRINTFN(3,("uhub_explore: port=%d !CURRENT_CONNECT"
405 				    "_STATUS\n", port));
406 			continue;
407 		}
408 
409 		/* Connected */
410 
411 		if (!(status & UPS_PORT_POWER))
412 			printf("%s: strange, connected port %d has no power\n",
413 			       USBDEVNAME(sc->sc_dev), port);
414 
415 		up->restartcnt = 0;
416 
417 		/* Wait for maximum device power up time. */
418 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
419 
420 		/* Reset port, which implies enabling it. */
421 		if (usbd_reset_port(dev, port, &up->status)) {
422 			printf("uhub_explore: port=%d reset failed\n",
423 				 port);
424 			continue;
425 		}
426 
427 		/* Get device info and set its address. */
428 		err = usbd_new_device(USBDEV(sc->sc_dev), dev->bus,
429 			  dev->depth + 1, status & UPS_LOW_SPEED,
430 			  port, up);
431 		/* XXX retry a few times? */
432 		if (err) {
433 			DPRINTFN(-1,("uhub_explore: usb_new_device failed, "
434 				     "error=%s\n", usbd_errstr(err)));
435 			/* Avoid addressing problems by disabling. */
436 			/* usbd_reset_port(dev, port, &up->status); */
437 
438 			/*
439 			 * The unit refused to accept a new address, or had
440 			 * some other serious problem.  Since we cannot leave
441 			 * at 0 we have to disable the port instead.
442 			 */
443 			printf("%s: device problem, disabling port %d\n",
444 			       USBDEVNAME(sc->sc_dev), port);
445 			usbd_clear_port_feature(dev, port, UHF_PORT_ENABLE);
446 			/* Make sure we don't try to restart it infinitely. */
447 			up->restartcnt = USBD_RESTART_MAX;
448 		} else {
449 			if (up->device->hub)
450 				up->device->hub->explore(up->device);
451 		}
452 	}
453 	return (USBD_NORMAL_COMPLETION);
454 }
455 
456 #if defined(__NetBSD__) || defined(__OpenBSD__)
457 int
458 uhub_activate(self, act)
459 	device_ptr_t self;
460 	enum devact act;
461 {
462 	struct uhub_softc *sc = (struct uhub_softc *)self;
463 	struct usbd_hub *hub = sc->sc_hub->hub;
464 	usbd_device_handle dev;
465 	int nports, port, i;
466 
467 	switch (act) {
468 	case DVACT_ACTIVATE:
469 		return (EOPNOTSUPP);
470 		break;
471 
472 	case DVACT_DEACTIVATE:
473 		if (hub == NULL) /* malfunctioning hub */
474 			break;
475 		nports = hub->hubdesc.bNbrPorts;
476 		for(port = 0; port < nports; port++) {
477 			dev = hub->ports[port].device;
478 			if (dev != NULL) {
479 				for (i = 0; dev->subdevs[i]; i++)
480 					config_deactivate(dev->subdevs[i]);
481 			}
482 		}
483 		break;
484 	}
485 	return (0);
486 }
487 #endif
488 
489 /*
490  * Called from process context when the hub is gone.
491  * Detach all devices on active ports.
492  */
493 USB_DETACH(uhub)
494 {
495 	USB_DETACH_START(uhub, sc);
496 	struct usbd_hub *hub = sc->sc_hub->hub;
497 	struct usbd_port *rup;
498 	int port, nports;
499 
500 #if defined(__NetBSD__) || defined(__OpenBSD__)
501 	DPRINTF(("uhub_detach: sc=%p flags=%d\n", sc, flags));
502 #elif defined(__FreeBSD__)
503 	DPRINTF(("uhub_detach: sc=%port\n", sc));
504 #endif
505 
506 	if (hub == NULL)		/* Must be partially working */
507 		return (0);
508 
509 	usbd_abort_pipe(sc->sc_ipipe);
510 	usbd_close_pipe(sc->sc_ipipe);
511 
512 	nports = hub->hubdesc.bNbrPorts;
513 	for(port = 0; port < nports; port++) {
514 		rup = &hub->ports[port];
515 		if (rup->device)
516 			usb_disconnect_port(rup, self);
517 	}
518 
519 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_hub,
520 			   USBDEV(sc->sc_dev));
521 
522 	free(hub, M_USBDEV);
523 	sc->sc_hub->hub = NULL;
524 
525 	return (0);
526 }
527 
528 #if defined(__FreeBSD__)
529 /* Called when a device has been detached from it */
530 Static void
531 uhub_child_detached(self, child)
532        device_t self;
533        device_t child;
534 {
535        struct uhub_softc *sc = device_get_softc(self);
536        usbd_device_handle devhub = sc->sc_hub;
537        usbd_device_handle dev;
538        int nports;
539        int port;
540        int i;
541 
542        if (!devhub->hub)
543                /* should never happen; children are only created after init */
544                panic("hub not fully initialised, but child deleted?");
545 
546        nports = devhub->hub->hubdesc.bNbrPorts;
547        for (port = 0; port < nports; port++) {
548                dev = devhub->hub->ports[port].device;
549                if (dev && dev->subdevs) {
550                        for (i = 0; dev->subdevs[i]; i++) {
551                                if (dev->subdevs[i] == child) {
552                                        dev->subdevs[i] = NULL;
553                                        return;
554                                }
555                        }
556                }
557        }
558 }
559 #endif
560 
561 
562 /*
563  * Hub interrupt.
564  * This an indication that some port has changed status.
565  * Notify the bus event handler thread that we need
566  * to be explored again.
567  */
568 void
569 uhub_intr(xfer, addr, status)
570 	usbd_xfer_handle xfer;
571 	usbd_private_handle addr;
572 	usbd_status status;
573 {
574 	struct uhub_softc *sc = addr;
575 
576 	DPRINTFN(5,("uhub_intr: sc=%p\n", sc));
577 	if (status != USBD_NORMAL_COMPLETION)
578 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
579 
580 	usb_needs_explore(sc->sc_hub->bus);
581 }
582 
583 #if defined(__FreeBSD__)
584 DRIVER_MODULE(uhub, usb, uhubroot_driver, uhubroot_devclass, 0, 0);
585 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, usbd_driver_load, 0);
586 #endif
587