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