xref: /openbsd-src/sys/dev/usb/uhub.c (revision 992bf2de34964da0d872d895bce4e55821232acf)
1 /*	$OpenBSD: uhub.c,v 1.2 1999/08/16 22:08:49 fgsch Exp $	*/
2 /*	$NetBSD: uhub.c,v 1.18 1999/06/30 06:44:23 augustss Exp $	*/
3 
4 /*
5  * Copyright (c) 1998 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Lennart Augustsson (augustss@carlstedt.se) at
10  * Carlstedt Research & Technology.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *        This product includes software developed by the NetBSD
23  *        Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 /*
42  * USB spec: http://www.usb.org/cgi-usb/mailmerge.cgi/home/usb/docs/developers/cgiform.tpl
43  */
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/malloc.h>
49 #if defined(__NetBSD__) || defined(__OpenBSD__)
50 #include <sys/device.h>
51 #elif defined(__FreeBSD__)
52 #include <sys/module.h>
53 #include <sys/bus.h>
54 #endif
55 #include <sys/proc.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 
62 #ifdef USB_DEBUG
63 #define DPRINTF(x)	if (usbdebug) logprintf x
64 #define DPRINTFN(n,x)	if (usbdebug>(n)) logprintf x
65 extern int	usbdebug;
66 extern char 	*usbd_error_strs[];
67 #else
68 #define DPRINTF(x)
69 #define DPRINTFN(n,x)
70 #endif
71 
72 struct uhub_softc {
73 	bdevice			sc_dev;		/* base device */
74 	usbd_device_handle	sc_hub;		/* USB device */
75 	usbd_pipe_handle	sc_ipipe;	/* interrupt pipe */
76 	u_int8_t		sc_status[1];	/* XXX more ports */
77 	u_char			sc_running;
78 };
79 
80 usbd_status uhub_init_port __P((struct usbd_port *));
81 void uhub_disconnect_port __P((struct usbd_port *up));
82 usbd_status uhub_explore __P((usbd_device_handle hub));
83 void uhub_intr __P((usbd_request_handle, usbd_private_handle, usbd_status));
84 
85 USB_DECLARE_DRIVER_NAME(usb, uhub);
86 
87 #if defined(__NetBSD__) || defined(__OpenBSD__)
88 struct cfattach uhub_uhub_ca = {
89 	sizeof(struct uhub_softc), uhub_match, uhub_attach,
90 	uhub_detach, uhub_activate
91 };
92 #endif
93 
94 USB_MATCH(uhub)
95 {
96 	USB_MATCH_START(uhub, uaa);
97 	usb_device_descriptor_t *dd = usbd_get_device_descriptor(uaa->device);
98 
99 	DPRINTFN(5,("uhub_match, dd=%p\n", dd));
100 	/*
101 	 * The subclass for hubs seems to be 0 for some and 1 for others,
102 	 * so we just ignore the subclass.
103 	 */
104 	if (uaa->iface == 0 && dd->bDeviceClass == UCLASS_HUB)
105 		return (UMATCH_DEVCLASS_DEVSUBCLASS);
106 	return (UMATCH_NONE);
107 }
108 
109 USB_ATTACH(uhub)
110 {
111 	USB_ATTACH_START(uhub, sc, uaa);
112 	usbd_device_handle dev = uaa->device;
113 	char devinfo[1024];
114 	usbd_status r;
115 	struct usbd_hub *hub;
116 	usb_device_request_t req;
117 	usb_hub_descriptor_t hubdesc;
118 	int p, port, nports, nremov;
119 	usbd_interface_handle iface;
120 	usb_endpoint_descriptor_t *ed;
121 
122 	DPRINTFN(1,("uhub_attach\n"));
123 	sc->sc_hub = dev;
124 	usbd_devinfo(dev, 1, devinfo);
125 	USB_ATTACH_SETUP;
126 	printf("%s: %s\n", USBDEVNAME(sc->sc_dev), devinfo);
127 
128 	r = usbd_set_config_index(dev, 0, 1);
129 	if (r != USBD_NORMAL_COMPLETION) {
130 		DPRINTF(("%s: configuration failed, error=%d(%s)\n",
131 			 USBDEVNAME(sc->sc_dev), r, usbd_error_strs[r]));
132 		USB_ATTACH_ERROR_RETURN;
133 	}
134 
135 	if (dev->depth > USB_HUB_MAX_DEPTH) {
136 		printf("%s: hub depth (%d) exceeded, hub ignored\n",
137 		       USBDEVNAME(sc->sc_dev), USB_HUB_MAX_DEPTH);
138 		USB_ATTACH_ERROR_RETURN;
139 	}
140 
141 	/* Get hub descriptor. */
142 	req.bmRequestType = UT_READ_CLASS_DEVICE;
143 	req.bRequest = UR_GET_DESCRIPTOR;
144 	USETW(req.wValue, 0);
145 	USETW(req.wIndex, 0);
146 	USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
147 	DPRINTFN(1,("usb_init_hub: getting hub descriptor\n"));
148 	r = usbd_do_request(dev, &req, &hubdesc);
149 	nports = hubdesc.bNbrPorts;
150 	if (r == USBD_NORMAL_COMPLETION && nports > 7) {
151 		USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE + (nports+1) / 8);
152 		r = usbd_do_request(dev, &req, &hubdesc);
153 	}
154 	if (r != USBD_NORMAL_COMPLETION) {
155 		DPRINTF(("%s: getting hub descriptor failed, error=%d(%s)\n",
156 			 USBDEVNAME(sc->sc_dev), r, usbd_error_strs[r]));
157 		USB_ATTACH_ERROR_RETURN;
158 	}
159 
160 	for (nremov = 0, port = 1; port <= nports; port++)
161 		if (!UHD_NOT_REMOV(&hubdesc, port))
162 			nremov++;
163 	printf("%s: %d port%s with %d removable, %s powered\n",
164 	       USBDEVNAME(sc->sc_dev), nports, nports != 1 ? "s" : "",
165 	       nremov, dev->self_powered ? "self" : "bus");
166 
167 
168 	hub = malloc(sizeof(*hub) + (nports-1) * sizeof(struct usbd_port),
169 		     M_USBDEV, M_NOWAIT);
170 	if (hub == 0)
171 		USB_ATTACH_ERROR_RETURN;
172 	dev->hub = hub;
173 	dev->hub->hubsoftc = sc;
174 	hub->explore = uhub_explore;
175 	hub->hubdesc = hubdesc;
176 
177 	DPRINTFN(1,("usbhub_init_hub: selfpowered=%d, parent=%p, "
178 		    "parent->selfpowered=%d\n",
179 		 dev->self_powered, dev->powersrc->parent,
180 		 dev->powersrc->parent ?
181 		 dev->powersrc->parent->self_powered : 0));
182 	if (!dev->self_powered && dev->powersrc->parent &&
183 	    !dev->powersrc->parent->self_powered) {
184 		printf("%s: bus powered hub connected to bus powered hub, "
185 		       "ignored\n",
186 		       USBDEVNAME(sc->sc_dev));
187 		goto bad;
188 	}
189 
190 	/* Set up interrupt pipe. */
191 	r = usbd_device2interface_handle(dev, 0, &iface);
192 	if (r != USBD_NORMAL_COMPLETION) {
193 		printf("%s: no interface handle\n", USBDEVNAME(sc->sc_dev));
194 		goto bad;
195 	}
196 	ed = usbd_interface2endpoint_descriptor(iface, 0);
197 	if (ed == 0) {
198 		printf("%s: no endpoint descriptor\n", USBDEVNAME(sc->sc_dev));
199 		goto bad;
200 	}
201 	if ((ed->bmAttributes & UE_XFERTYPE) != UE_INTERRUPT) {
202 		printf("%s: bad interrupt endpoint\n", USBDEVNAME(sc->sc_dev));
203 		goto bad;
204 	}
205 
206 	r = usbd_open_pipe_intr(iface, ed->bEndpointAddress,USBD_SHORT_XFER_OK,
207 				&sc->sc_ipipe, sc, sc->sc_status,
208 				sizeof(sc->sc_status),
209 				uhub_intr);
210 	if (r != USBD_NORMAL_COMPLETION) {
211 		printf("%s: cannot open interrupt pipe\n",
212 		       USBDEVNAME(sc->sc_dev));
213 		goto bad;
214 	}
215 
216 	/* Wait with power off for a while. */
217 	usbd_delay_ms(dev, USB_POWER_DOWN_TIME);
218 
219 	for (p = 0; p < nports; p++) {
220 		struct usbd_port *up = &hub->ports[p];
221 		up->device = 0;
222 		up->parent = dev;
223 		up->portno = p+1;
224 		r = uhub_init_port(up);
225 		if (r != USBD_NORMAL_COMPLETION)
226 			printf("%s: init of port %d failed\n",
227 			       USBDEVNAME(sc->sc_dev), up->portno);
228 	}
229 	sc->sc_running = 1;
230 
231 	USB_ATTACH_SUCCESS_RETURN;
232 
233  bad:
234 	free(hub, M_USBDEV);
235 	dev->hub = 0;
236 	USB_ATTACH_ERROR_RETURN;
237 }
238 
239 usbd_status
240 uhub_init_port(up)
241 	struct usbd_port *up;
242 {
243 	int port = up->portno;
244 	usbd_device_handle dev = up->parent;
245 	usbd_status r;
246 	u_int16_t pstatus;
247 
248 	r = usbd_get_port_status(dev, port, &up->status);
249 	if (r != USBD_NORMAL_COMPLETION)
250 		return (r);
251 	pstatus = UGETW(up->status.wPortStatus);
252 	DPRINTF(("usbd_init_port: adding hub port=%d status=0x%04x "
253 		 "change=0x%04x\n",
254 		 port, pstatus, UGETW(up->status.wPortChange)));
255 	if ((pstatus & UPS_PORT_POWER) == 0) {
256 		/* Port lacks power, turn it on */
257 
258 		/* First let the device go through a good power cycle, */
259 		usbd_delay_ms(dev, USB_PORT_POWER_DOWN_TIME);
260 
261 #if 0
262 usbd_clear_hub_feature(dev, UHF_C_HUB_OVER_CURRENT);
263 usbd_clear_port_feature(dev, port, UHF_C_PORT_OVER_CURRENT);
264 #endif
265 
266 		/* then turn the power on. */
267 		r = usbd_set_port_feature(dev, port, UHF_PORT_POWER);
268 		if (r != USBD_NORMAL_COMPLETION)
269 			return (r);
270 		DPRINTF(("usb_init_port: turn on port %d power status=0x%04x "
271 			 "change=0x%04x\n",
272 			 port, UGETW(up->status.wPortStatus),
273 			 UGETW(up->status.wPortChange)));
274 		/* Wait for stable power. */
275 		usbd_delay_ms(dev, dev->hub->hubdesc.bPwrOn2PwrGood *
276 			           UHD_PWRON_FACTOR);
277 		/* Get the port status again. */
278 		r = usbd_get_port_status(dev, port, &up->status);
279 		if (r != USBD_NORMAL_COMPLETION)
280 			return (r);
281 		DPRINTF(("usb_init_port: after power on status=0x%04x "
282 			 "change=0x%04x\n",
283 			 UGETW(up->status.wPortStatus),
284 			 UGETW(up->status.wPortChange)));
285 
286 #if 0
287 usbd_clear_hub_feature(dev, UHF_C_HUB_OVER_CURRENT);
288 usbd_clear_port_feature(dev, port, UHF_C_PORT_OVER_CURRENT);
289 usbd_get_port_status(dev, port, &up->status);
290 #endif
291 
292 		pstatus = UGETW(up->status.wPortStatus);
293 		if ((pstatus & UPS_PORT_POWER) == 0)
294 			printf("%s: port %d did not power up\n",
295  USBDEVNAME(((struct uhub_softc *)dev->hub->hubsoftc)->sc_dev), port);
296 
297 	}
298 	if (dev->self_powered)
299 		/* Self powered hub, give ports maximum current. */
300 		up->power = USB_MAX_POWER;
301 	else
302 		up->power = USB_MIN_POWER;
303 	return (USBD_NORMAL_COMPLETION);
304 }
305 
306 usbd_status
307 uhub_explore(dev)
308 	usbd_device_handle dev;
309 {
310 	usb_hub_descriptor_t *hd = &dev->hub->hubdesc;
311 	struct uhub_softc *sc = dev->hub->hubsoftc;
312 	struct usbd_port *up;
313 	usbd_status r;
314 	int port;
315 	int change, status;
316 
317 	DPRINTFN(10, ("uhub_explore dev=%p addr=%d\n", dev, dev->address));
318 
319 	if (!sc->sc_running)
320 		return (USBD_NOT_STARTED);
321 
322 	/* Ignore hubs that are too deep. */
323 	if (dev->depth > USB_HUB_MAX_DEPTH)
324 		return (USBD_TOO_DEEP);
325 
326 	for(port = 1; port <= hd->bNbrPorts; port++) {
327 		up = &dev->hub->ports[port-1];
328 		r = usbd_get_port_status(dev, port, &up->status);
329 		if (r != USBD_NORMAL_COMPLETION) {
330 			DPRINTF(("uhub_explore: get port status failed, "
331 				 "error=%d(%s)\n",
332 				 r, usbd_error_strs[r]));
333 			continue;
334 		}
335 		status = UGETW(up->status.wPortStatus);
336 		change = UGETW(up->status.wPortChange);
337 		DPRINTFN(5, ("uhub_explore: port %d status 0x%04x 0x%04x\n",
338 			     port, status, change));
339 		if (change & UPS_C_PORT_ENABLED) {
340 			usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
341 			if (status & UPS_PORT_ENABLED) {
342 				printf("%s: illegal enable change, port %d\n",
343 				       USBDEVNAME(sc->sc_dev), port);
344 			} else {
345 				/* Port error condition. */
346 				if (up->restartcnt++ < USBD_RESTART_MAX) {
347 					printf("%s: port error, restarting "
348 					       "port %d\n",
349 					       USBDEVNAME(sc->sc_dev), port);
350 					goto disco;
351 				} else {
352 					printf("%s: port error, giving up "
353 					       "port %d\n",
354 					       USBDEVNAME(sc->sc_dev), port);
355 				}
356 			}
357 		}
358 		if (!(change & UPS_C_CONNECT_STATUS)) {
359 			/* No status change, just do recursive explore. */
360 			if (up->device && up->device->hub)
361 				up->device->hub->explore(up->device);
362 			continue;
363 		}
364 		DPRINTF(("uhub_explore: status change hub=%d port=%d\n",
365 			 dev->address, port));
366 		usbd_clear_port_feature(dev, port, UHF_C_PORT_CONNECTION);
367 		usbd_clear_port_feature(dev, port, UHF_C_PORT_ENABLE);
368 		/*
369 		 * If there is already a device on the port the change status
370 		 * must mean that is has disconnected.  Looking at the
371 		 * current connect status is not enough to figure this out
372 		 * since a new unit may have been connected before we handle
373 		 * the disconnect.
374 		 */
375 	disco:
376 		if (up->device) {
377 			/* Disconnected */
378 			DPRINTF(("uhub_explore: device %d disappeared "
379 				 "on port %d\n",
380 				 up->device->address, port));
381 			uhub_disconnect_port(up);
382 			usbd_clear_port_feature(dev, port,
383 						UHF_C_PORT_CONNECTION);
384 		}
385 		if (!(status & UPS_CURRENT_CONNECT_STATUS))
386 			continue;
387 
388 		/* Connected */
389 		up->restartcnt = 0;
390 
391 		/* Wait for maximum device power up time. */
392 		usbd_delay_ms(dev, USB_PORT_POWERUP_DELAY);
393 
394 		/* Reset port, which implies enabling it. */
395 		if (usbd_reset_port(dev, port, &up->status) !=
396 		    USBD_NORMAL_COMPLETION)
397 			continue;
398 
399 		/* Get device info and set its address. */
400 		r = usbd_new_device(&sc->sc_dev, dev->bus,
401 				    dev->depth + 1, status & UPS_LOW_SPEED,
402 				    port, up);
403 		/* XXX retry a few times? */
404 		if (r != USBD_NORMAL_COMPLETION) {
405 			DPRINTFN(-1,("uhub_explore: usb_new_device failed, "
406 				     "error=%d(%s)\n", r, usbd_error_strs[r]));
407 			/* Avoid addressing problems by disabling. */
408 			/* usbd_reset_port(dev, port, &up->status); */
409 /* XXX
410  * What should we do.  The device may or may not be at its
411  * assigned address.  In any case we'd like to ignore it.
412  * Maybe the port should be disabled until the device is
413  * disconnected.
414  */
415 			if (r == USBD_SET_ADDR_FAILED || 1) {/* XXX */
416 				/* The unit refused to accept a new
417 				 * address, and since we cannot leave
418 				 * at 0 we have to disable the port
419 				 * instead. */
420 				printf("%s: device problem, disabling "
421 				       "port %d\n",
422 				       USBDEVNAME(sc->sc_dev), port);
423 				usbd_clear_port_feature(dev, port,
424 							UHF_PORT_ENABLE);
425 				/* Make sure we don't try to restart it. */
426 				up->restartcnt = USBD_RESTART_MAX;
427 			}
428 		} else {
429 			if (up->device->hub)
430 				up->device->hub->explore(up->device);
431 		}
432 	}
433 	return (USBD_NORMAL_COMPLETION);
434 }
435 
436 /*
437  * The general mechanism for detaching drivers works as follows: Each
438  * driver is responsible for maintaining a reference count on the
439  * number of outstanding references to its softc (e.g.  from
440  * processing hanging in a read or write).  The detach method of the
441  * driver decrements this counter and flags in the softc that the
442  * driver is dying and then wakes any sleepers.  It then sleeps on the
443  * softc.  Each place that can sleep must maintain the reference
444  * count.  When the reference count drops to -1 (0 is the normal value
445  * of the reference count) the a wakeup on the softc is performed
446  * signaling to the detach waiter that all references are gone.
447  */
448 
449 /*
450  * Called from process context when we discover that a port has
451  * been disconnected.
452  */
453 void
454 uhub_disconnect_port(up)
455 	struct usbd_port *up;
456 {
457 	usbd_device_handle dev = up->device;
458 	char *hubname;
459 	int i;
460 
461 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
462 		    up, dev, up->portno));
463 
464 	if (!dev->cdesc) {
465 		/* Partially attached device, just drop it. */
466 		dev->bus->devices[dev->address] = 0;
467 		up->device = 0;
468 		return;
469 	}
470 
471 	hubname = USBDEVNAME(*up->parent->subdevs[0]);
472 	for (i = 0; dev->subdevs[i]; i++) {
473 		printf("%s: at %s port %d (addr %d) disconnected\n",
474 		       USBDEVNAME(*dev->subdevs[i]), hubname,
475 		       up->portno, dev->address);
476 		config_detach(dev->subdevs[i], DETACH_FORCE);
477 	}
478 
479 	dev->bus->devices[dev->address] = 0;
480 	up->device = 0;
481 	usb_free_device(dev);
482 
483 #if defined(__FreeBSD__)
484       device_delete_child(
485 	  device_get_parent(((struct softc *)dev->softc)->sc_dev),
486 	  ((struct softc *)dev->softc)->sc_dev);
487 #endif
488 }
489 
490 int
491 uhub_activate(self, act)
492 	struct device *self;
493 	enum devact act;
494 {
495 	return (0);
496 }
497 
498 /*
499  * Called from process context when the hub is gone.
500  * Detach all devices on active ports.
501  */
502 int
503 uhub_detach(self, flags)
504 	struct device *self;
505 	int flags;
506 {
507 	struct uhub_softc *sc = (struct uhub_softc *)self;
508 	usbd_device_handle dev = sc->sc_hub;
509 	struct usbd_port *rup;
510 	int p, nports;
511 
512 	DPRINTF(("uhub_detach: sc=%p flags=%d\n", sc, flags));
513 
514 	if (!dev->hub) {
515 		/* Must be partially working */
516 		return (0);
517 	}
518 
519 	usbd_abort_pipe(sc->sc_ipipe);
520 	usbd_close_pipe(sc->sc_ipipe);
521 
522 	nports = dev->hub->hubdesc.bNbrPorts;
523 	for(p = 0; p < nports; p++) {
524 		rup = &dev->hub->ports[p];
525 		if (rup->device)
526 			uhub_disconnect_port(rup);
527 	}
528 
529 	free(dev->hub, M_USBDEV);
530 	dev->hub = 0;
531 
532 	return (0);
533 }
534 
535 /*
536  * Hub interrupt.
537  * This an indication that some port has changed status.
538  * Notify the bus event handler thread that we need
539  * to be explored again.
540  */
541 void
542 uhub_intr(reqh, addr, status)
543 	usbd_request_handle reqh;
544 	usbd_private_handle addr;
545 	usbd_status status;
546 {
547 	struct uhub_softc *sc = addr;
548 
549 	DPRINTFN(5,("uhub_intr: sc=%p\n", sc));
550 	if (status != USBD_NORMAL_COMPLETION)
551 		usbd_clear_endpoint_stall_async(sc->sc_ipipe);
552 
553 	usb_needs_explore(sc->sc_hub->bus);
554 }
555 
556 #if defined(__FreeBSD__)
557 DRIVER_MODULE(uhub, usb, uhubroot_driver, uhubroot_devclass, 0, 0);
558 DRIVER_MODULE(uhub, uhub, uhub_driver, uhub_devclass, usbd_driver_load, 0);
559 #endif
560