Home | History | Annotate | Line # | Download | only in usb
usb_subr.c revision 1.22
      1 /*	$NetBSD: usb_subr.c,v 1.22 1998/12/29 16:02:55 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 (at) 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 #include <sys/param.h>
     41 #include <sys/systm.h>
     42 #include <sys/kernel.h>
     43 #include <sys/malloc.h>
     44 #if defined(__NetBSD__)
     45 #include <sys/device.h>
     46 #elif defined(__FreeBSD__)
     47 #include <sys/module.h>
     48 #include <sys/bus.h>
     49 #endif
     50 #include <sys/proc.h>
     51 #include <sys/select.h>
     52 
     53 #include <dev/usb/usb.h>
     54 
     55 #include <dev/usb/usbdi.h>
     56 #include <dev/usb/usbdi_util.h>
     57 #include <dev/usb/usbdivar.h>
     58 #include <dev/usb/usbdevs.h>
     59 #include <dev/usb/usb_quirks.h>
     60 
     61 #ifdef USB_DEBUG
     62 #define DPRINTF(x)	if (usbdebug) printf x
     63 #define DPRINTFN(n,x)	if (usbdebug>(n)) printf x
     64 extern int usbdebug;
     65 #else
     66 #define DPRINTF(x)
     67 #define DPRINTFN(n,x)
     68 #endif
     69 
     70 static usbd_status	usbd_set_config __P((usbd_device_handle, int));
     71 char *usbd_get_string __P((usbd_device_handle, int, char *));
     72 int usbd_getnewaddr __P((usbd_bus_handle bus));
     73 int usbd_print __P((void *aux, const char *pnp));
     74 #if defined(__NetBSD__)
     75 int usbd_submatch __P((struct device *, struct cfdata *cf, void *));
     76 #endif
     77 usb_interface_descriptor_t *usbd_find_idesc __P((usb_config_descriptor_t *cd,
     78 						 int ifaceidx, int altidx));
     79 void usbd_free_iface_data __P((usbd_device_handle dev, int ifcno));
     80 void usbd_kill_pipe __P((usbd_pipe_handle));
     81 usbd_status usbd_probe_and_attach
     82 	__P((bdevice *parent, usbd_device_handle dev, int port, int addr));
     83 
     84 #ifdef USBVERBOSE
     85 typedef u_int16_t usb_vendor_id_t;
     86 typedef u_int16_t usb_product_id_t;
     87 
     88 /*
     89  * Descriptions of of known vendors and devices ("products").
     90  */
     91 struct usb_knowndev {
     92 	usb_vendor_id_t		vendor;
     93 	usb_product_id_t	product;
     94 	int			flags;
     95 	char			*vendorname, *productname;
     96 };
     97 #define	USB_KNOWNDEV_NOPROD	0x01		/* match on vendor only */
     98 
     99 #include <dev/usb/usbdevs_data.h>
    100 #endif /* USBVERBOSE */
    101 
    102 #ifdef USB_DEBUG
    103 char *usbd_error_strs[] = {
    104 	"NORMAL_COMPLETION",
    105 	"IN_PROGRESS",
    106 	"PENDING_REQUESTS",
    107 	"NOT_STARTED",
    108 	"INVAL",
    109 	"IS_IDLE",
    110 	"NOMEM",
    111 	"CANCELLED",
    112 	"BAD_ADDRESS",
    113 	"IN_USE",
    114 	"INTERFACE_NOT_ACTIVE",
    115 	"NO_ADDR",
    116 	"SET_ADDR_FAILED",
    117 	"NO_POWER",
    118 	"TOO_DEEP",
    119 	"IOERROR",
    120 	"NOT_CONFIGURED",
    121 	"TIMEOUT",
    122 	"SHORT_XFER",
    123 	"STALLED",
    124 	"XXX",
    125 };
    126 #endif
    127 
    128 usbd_status
    129 usbd_get_string_desc(dev, sindex, langid, sdesc)
    130 	usbd_device_handle dev;
    131 	int sindex;
    132 	int langid;
    133 	usb_string_descriptor_t *sdesc;
    134 {
    135 	usb_device_request_t req;
    136 	usbd_status r;
    137 
    138 	req.bmRequestType = UT_READ_DEVICE;
    139 	req.bRequest = UR_GET_DESCRIPTOR;
    140 	USETW2(req.wValue, UDESC_STRING, sindex);
    141 	USETW(req.wIndex, langid);
    142 	USETW(req.wLength, 1);	/* only size byte first */
    143 	r = usbd_do_request(dev, &req, sdesc);
    144 	if (r != USBD_NORMAL_COMPLETION)
    145 		return (r);
    146 	USETW(req.wLength, sdesc->bLength);	/* the whole string */
    147 	return (usbd_do_request(dev, &req, sdesc));
    148 }
    149 
    150 char *
    151 usbd_get_string(dev, si, buf)
    152 	usbd_device_handle dev;
    153 	int si;
    154 	char *buf;
    155 {
    156 	int swap = dev->quirks->uq_flags & UQ_SWAP_UNICODE;
    157 	usb_string_descriptor_t us;
    158 	char *s;
    159 	int i, n;
    160 	u_int16_t c;
    161 	usbd_status r;
    162 
    163 	if (si == 0)
    164 		return (0);
    165 	if (dev->quirks->uq_flags & UQ_NO_STRINGS)
    166 		return (0);
    167 	if (dev->langid == USBD_NOLANG) {
    168 		/* Set up default language */
    169 		r = usbd_get_string_desc(dev, USB_LANGUAGE_TABLE, 0, &us);
    170 		if (r != USBD_NORMAL_COMPLETION || us.bLength < 4) {
    171 			dev->langid = 0; /* Well, just pick English then */
    172 		} else {
    173 			/* Pick the first language as the default. */
    174 			dev->langid = UGETW(us.bString[0]);
    175 		}
    176 	}
    177 	r = usbd_get_string_desc(dev, si, dev->langid, &us);
    178 	if (r != USBD_NORMAL_COMPLETION)
    179 		return (0);
    180 	s = buf;
    181 	n = us.bLength / 2 - 1;
    182 	for (i = 0; i < n; i++) {
    183 		c = UGETW(us.bString[i]);
    184 		/* Convert from Unicode, handle buggy strings. */
    185 		if ((c & 0xff00) == 0)
    186 			*s++ = c;
    187 		else if ((c & 0x00ff) == 0 && swap)
    188 			*s++ = c >> 8;
    189 		else
    190 			*s++ = '?';
    191 	}
    192 	*s++ = 0;
    193 	return buf;
    194 }
    195 
    196 void
    197 usbd_devinfo_vp(dev, v, p)
    198 	usbd_device_handle dev;
    199 	char *v, *p;
    200 {
    201 	usb_device_descriptor_t *udd = &dev->ddesc;
    202 	char *vendor = 0, *product = 0;
    203 #ifdef USBVERBOSE
    204 	struct usb_knowndev *kdp;
    205 #endif
    206 
    207 	vendor = usbd_get_string(dev, udd->iManufacturer, v);
    208 	product = usbd_get_string(dev, udd->iProduct, p);
    209 #ifdef USBVERBOSE
    210 	if (!vendor) {
    211 		for(kdp = usb_knowndevs;
    212 		    kdp->vendorname != NULL;
    213 		    kdp++) {
    214 			if (kdp->vendor == UGETW(udd->idVendor) &&
    215 			    (kdp->product == UGETW(udd->idProduct) ||
    216 			     (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
    217 				break;
    218 		}
    219 		if (kdp->vendorname == NULL)
    220 			vendor = product = NULL;
    221 		else {
    222 			vendor = kdp->vendorname;
    223 			product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
    224 				kdp->productname : NULL;
    225 		}
    226 	}
    227 #endif
    228 	if (vendor)
    229 		strcpy(v, vendor);
    230 	else
    231 		sprintf(v, "vendor 0x%04x", UGETW(udd->idVendor));
    232 	if (product)
    233 		strcpy(p, product);
    234 	else
    235 		sprintf(p, "product 0x%04x", UGETW(udd->idProduct));
    236 }
    237 
    238 int
    239 usbd_printBCD(cp, bcd)
    240 	char *cp;
    241 	int bcd;
    242 {
    243 	return (sprintf(cp, "%x.%02x", bcd >> 8, bcd & 0xff));
    244 }
    245 
    246 void
    247 usbd_devinfo(dev, showclass, cp)
    248 	usbd_device_handle dev;
    249 	int showclass;
    250 	char *cp;
    251 {
    252 	usb_device_descriptor_t *udd = &dev->ddesc;
    253 	char vendor[USB_MAX_STRING_LEN];
    254 	char product[USB_MAX_STRING_LEN];
    255 	int bcdDevice, bcdUSB;
    256 
    257 	usbd_devinfo_vp(dev, vendor, product);
    258 	cp += sprintf(cp, "%s %s", vendor, product);
    259 	if (showclass)
    260 		cp += sprintf(cp, ", class %d/%d",
    261 			      udd->bDeviceClass, udd->bDeviceSubClass);
    262 	bcdUSB = UGETW(udd->bcdUSB);
    263 	bcdDevice = UGETW(udd->bcdDevice);
    264 	cp += sprintf(cp, ", rev ");
    265 	cp += usbd_printBCD(cp, bcdUSB);
    266 	*cp++ = '/';
    267 	cp += usbd_printBCD(cp, bcdDevice);
    268 	cp += sprintf(cp, ", addr %d", dev->address);
    269 	*cp = 0;
    270 }
    271 
    272 /* Delay for a certain number of ms */
    273 void
    274 usbd_delay_ms(bus, ms)
    275 	usbd_bus_handle bus;
    276 	int ms;
    277 {
    278 	/* Wait at least two clock ticks so we know the time has passed. */
    279 	if (bus->use_polling)
    280 		delay((ms+1) * 1000);
    281 	else
    282 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
    283 }
    284 
    285 usbd_status
    286 usbd_reset_port(dev, port, ps)
    287 	usbd_device_handle dev;
    288 	int port;
    289 	usb_port_status_t *ps;
    290 {
    291 	usb_device_request_t req;
    292 	usbd_status r;
    293 	int n;
    294 
    295 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
    296 	req.bRequest = UR_SET_FEATURE;
    297 	USETW(req.wValue, UHF_PORT_RESET);
    298 	USETW(req.wIndex, port);
    299 	USETW(req.wLength, 0);
    300 	r = usbd_do_request(dev, &req, 0);
    301 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%d(%s)\n",
    302 		    port, r, usbd_error_strs[r]));
    303 	if (r != USBD_NORMAL_COMPLETION)
    304 		return (r);
    305 	n = 10;
    306 	do {
    307 		/* Wait for device to recover from reset. */
    308 		usbd_delay_ms(dev->bus, USB_PORT_RESET_DELAY);
    309 		r = usbd_get_port_status(dev, port, ps);
    310 		if (r != USBD_NORMAL_COMPLETION) {
    311 			DPRINTF(("usbd_reset_port: get status failed %d\n",r));
    312 			return (r);
    313 		}
    314 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
    315 	if (n == 0) {
    316 		printf("usbd_reset_port: timeout\n");
    317 		return (USBD_IOERROR);
    318 	}
    319 	r = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
    320 #ifdef USB_DEBUG
    321 	if (r != USBD_NORMAL_COMPLETION)
    322 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",r));
    323 #endif
    324 
    325 	/* Wait for the device to recover from reset. */
    326 	usbd_delay_ms(dev->bus, USB_PORT_RESET_RECOVERY);
    327 	return (r);
    328 }
    329 
    330 usb_interface_descriptor_t *
    331 usbd_find_idesc(cd, ifaceidx, altidx)
    332 	usb_config_descriptor_t *cd;
    333 	int ifaceidx;
    334 	int altidx;
    335 {
    336 	char *p = (char *)cd;
    337 	char *end = p + UGETW(cd->wTotalLength);
    338 	usb_interface_descriptor_t *d;
    339 	int curidx, lastidx, curaidx = 0;
    340 
    341 	for (curidx = lastidx = -1; p < end; ) {
    342 		d = (usb_interface_descriptor_t *)p;
    343 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
    344 			    "type=%d\n",
    345 			    ifaceidx, curidx, altidx, curaidx,
    346 			    d->bLength, d->bDescriptorType));
    347 		if (d->bLength == 0) /* bad descriptor */
    348 			break;
    349 		p += d->bLength;
    350 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
    351 			if (d->bInterfaceNumber != lastidx) {
    352 				lastidx = d->bInterfaceNumber;
    353 				curidx++;
    354 				curaidx = 0;
    355 			} else
    356 				curaidx++;
    357 			if (ifaceidx == curidx && altidx == curaidx)
    358 				return (d);
    359 		}
    360 	}
    361 	return (0);
    362 }
    363 
    364 usb_endpoint_descriptor_t *
    365 usbd_find_edesc(cd, ifaceidx, altidx, endptidx)
    366 	usb_config_descriptor_t *cd;
    367 	int ifaceidx;
    368 	int altidx;
    369 	int endptidx;
    370 {
    371 	char *p = (char *)cd;
    372 	char *end = p + UGETW(cd->wTotalLength);
    373 	usb_interface_descriptor_t *d;
    374 	usb_endpoint_descriptor_t *e;
    375 	int curidx;
    376 
    377 	d = usbd_find_idesc(cd, ifaceidx, altidx);
    378 	if (!d)
    379 		return (0);
    380 	if (endptidx >= d->bNumEndpoints) /* quick exit */
    381 		return (0);
    382 
    383 	curidx = -1;
    384 	for (p = (char *)d + d->bLength; p < end; ) {
    385 		e = (usb_endpoint_descriptor_t *)p;
    386 		if (e->bLength == 0) /* bad descriptor */
    387 			break;
    388 		p += e->bLength;
    389 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
    390 			return (0);
    391 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
    392 			curidx++;
    393 			if (curidx == endptidx)
    394 				return (e);
    395 		}
    396 	}
    397 	return (0);
    398 }
    399 
    400 usbd_status
    401 usbd_fill_iface_data(dev, ifaceidx, altidx)
    402 	usbd_device_handle dev;
    403 	int ifaceidx;
    404 	int altidx;
    405 {
    406 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
    407 	char *p, *end;
    408 	int endpt, nendpt;
    409 	usbd_status r;
    410 
    411 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
    412 		    ifaceidx, altidx));
    413 	ifc->device = dev;
    414 	ifc->idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
    415 	if (ifc->idesc == 0)
    416 		return (USBD_INVAL);
    417 	ifc->index = ifaceidx;
    418 	ifc->altindex = altidx;
    419 	nendpt = ifc->idesc->bNumEndpoints;
    420 	DPRINTFN(10,("usbd_fill_iface_data: found idesc n=%d\n", nendpt));
    421 	if (nendpt != 0) {
    422 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
    423 					M_USB, M_NOWAIT);
    424 		if (ifc->endpoints == 0)
    425 			return (USBD_NOMEM);
    426 	} else
    427 		ifc->endpoints = 0;
    428 	ifc->priv = 0;
    429 	p = (char *)ifc->idesc + ifc->idesc->bLength;
    430 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
    431 #define ed ((usb_endpoint_descriptor_t *)p)
    432 	for (endpt = 0; endpt < nendpt; endpt++) {
    433 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
    434 		for (; p < end; p += ed->bLength) {
    435 			ed = (usb_endpoint_descriptor_t *)p;
    436 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
    437 				     "len=%d type=%d\n",
    438 				 p, end, ed->bLength, ed->bDescriptorType));
    439 			if (p + ed->bLength <= end &&
    440 			    ed->bDescriptorType == UDESC_ENDPOINT)
    441 				break;
    442 			if (ed->bDescriptorType == UDESC_INTERFACE ||
    443 			    ed->bLength == 0) {
    444 				r = USBD_INVAL;
    445 				goto bad;
    446 			}
    447 		}
    448 		ifc->endpoints[endpt].edesc = ed;
    449 		ifc->endpoints[endpt].state = USBD_ENDPOINT_ACTIVE;
    450 		ifc->endpoints[endpt].refcnt = 0;
    451 		ifc->endpoints[endpt].toggle = 0;
    452 	}
    453 #undef ed
    454 	LIST_INIT(&ifc->pipes);
    455 	ifc->state = USBD_INTERFACE_ACTIVE;
    456 	return (USBD_NORMAL_COMPLETION);
    457  bad:
    458 	free(ifc->endpoints, M_USB);
    459 	return (r);
    460 }
    461 
    462 void
    463 usbd_free_iface_data(dev, ifcno)
    464 	usbd_device_handle dev;
    465 	int ifcno;
    466 {
    467 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
    468 	if (ifc->endpoints)
    469 		free(ifc->endpoints, M_USB);
    470 }
    471 
    472 static usbd_status
    473 usbd_set_config(dev, conf)
    474 	usbd_device_handle dev;
    475 	int conf;
    476 {
    477 	usb_device_request_t req;
    478 
    479 	req.bmRequestType = UT_WRITE_DEVICE;
    480 	req.bRequest = UR_SET_CONFIG;
    481 	USETW(req.wValue, conf);
    482 	USETW(req.wIndex, 0);
    483 	USETW(req.wLength, 0);
    484 	return (usbd_do_request(dev, &req, 0));
    485 }
    486 
    487 usbd_status
    488 usbd_set_config_no(dev, no, msg)
    489 	usbd_device_handle dev;
    490 	int no;
    491 	int msg;
    492 {
    493 	int index;
    494 	usb_config_descriptor_t cd;
    495 	usbd_status r;
    496 
    497 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
    498 	/* Figure out what config index to use. */
    499 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
    500 		r = usbd_get_config_desc(dev, index, &cd);
    501 		if (r != USBD_NORMAL_COMPLETION)
    502 			return (r);
    503 		if (cd.bConfigurationValue == no)
    504 			return (usbd_set_config_index(dev, index, msg));
    505 	}
    506 	return (USBD_INVAL);
    507 }
    508 
    509 usbd_status
    510 usbd_set_config_index(dev, index, msg)
    511 	usbd_device_handle dev;
    512 	int index;
    513 	int msg;
    514 {
    515 	usb_status_t ds;
    516 	usb_hub_status_t hs;
    517 	usb_config_descriptor_t cd, *cdp;
    518 	usbd_status r;
    519 	int ifcidx, nifc, len, selfpowered, power;
    520 
    521 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
    522 
    523 	/* XXX check that all interfaces are idle */
    524 	if (dev->config != 0) {
    525 		DPRINTF(("usbd_set_config_index: free old config\n"));
    526 		/* Free all configuration data structures. */
    527 		nifc = dev->cdesc->bNumInterface;
    528 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
    529 			usbd_free_iface_data(dev, ifcidx);
    530 		free(dev->ifaces, M_USB);
    531 		free(dev->cdesc, M_USB);
    532 		dev->ifaces = 0;
    533 		dev->cdesc = 0;
    534 		dev->config = 0;
    535 		dev->state = USBD_DEVICE_ADDRESSED;
    536 	}
    537 
    538 	/* Figure out what config number to use. */
    539 	r = usbd_get_config_desc(dev, index, &cd);
    540 	if (r != USBD_NORMAL_COMPLETION)
    541 		return (r);
    542 	len = UGETW(cd.wTotalLength);
    543 	cdp = malloc(len, M_USB, M_NOWAIT);
    544 	if (cdp == 0)
    545 		return (USBD_NOMEM);
    546 	r = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
    547 	if (r != USBD_NORMAL_COMPLETION)
    548 		goto bad;
    549 	if (cdp->bDescriptorType != UDESC_CONFIG) {
    550 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
    551 			     cdp->bDescriptorType));
    552 		r = USBD_INVAL;
    553 		goto bad;
    554 	}
    555 	selfpowered = 0;
    556 	if (cdp->bmAttributes & UC_SELF_POWERED) {
    557 		/* May be self powered. */
    558 		if (cdp->bmAttributes & UC_BUS_POWERED) {
    559 			/* Must ask device. */
    560 			if (dev->quirks->uq_flags & UQ_HUB_POWER) {
    561 				/* Buggy hub, use hub descriptor. */
    562 				r = usbd_get_hub_status(dev, &hs);
    563 				if (r == USBD_NORMAL_COMPLETION &&
    564 				    !(UGETW(hs.wHubStatus) & UHS_LOCAL_POWER))
    565 					selfpowered = 1;
    566 			} else {
    567 				r = usbd_get_device_status(dev, &ds);
    568 				if (r == USBD_NORMAL_COMPLETION &&
    569 				    (UGETW(ds.wStatus) & UDS_SELF_POWERED))
    570 					selfpowered = 1;
    571 			}
    572 			DPRINTF(("usbd_set_config_index: status=0x%04x, "
    573 				 "error=%d(%s)\n",
    574 				 UGETW(ds.wStatus), r, usbd_error_strs[r]));
    575 		} else
    576 			selfpowered = 1;
    577 	}
    578 	DPRINTF(("usbd_set_config_index: (addr %d) attr=0x%02x, "
    579 		 "selfpowered=%d, power=%d, powerquirk=%x\n",
    580 		 dev->address, cdp->bmAttributes,
    581 		 selfpowered, cdp->bMaxPower * 2,
    582 		 dev->quirks->uq_flags & UQ_HUB_POWER));
    583 #ifdef USB_DEBUG
    584 	if (!dev->powersrc) {
    585 		printf("usbd_set_config_index: No power source?\n");
    586 		return (USBD_IOERROR);
    587 	}
    588 #endif
    589 	power = cdp->bMaxPower * 2;
    590 	if (power > dev->powersrc->power) {
    591 		/* XXX print nicer message. */
    592 		if (msg)
    593 			printf("%s: device addr %d (config %d) exceeds power "
    594 				 "budget, %d mA > %d mA\n",
    595 			       USBDEVNAME(dev->bus->bdev), dev->address,
    596 			       cdp->bConfigurationValue,
    597 			       power, dev->powersrc->power);
    598 		r = USBD_NO_POWER;
    599 		goto bad;
    600 	}
    601 	dev->power = power;
    602 	dev->self_powered = selfpowered;
    603 
    604 	DPRINTF(("usbd_set_config_index: set config %d\n",
    605 		 cdp->bConfigurationValue));
    606 	r = usbd_set_config(dev, cdp->bConfigurationValue);
    607 	if (r != USBD_NORMAL_COMPLETION) {
    608 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
    609 			 "error=%d(%s)\n",
    610 			 cdp->bConfigurationValue, r, usbd_error_strs[r]));
    611 		goto bad;
    612 	}
    613 	DPRINTF(("usbd_set_config_index: setting new config %d\n",
    614 		 cdp->bConfigurationValue));
    615 	nifc = cdp->bNumInterface;
    616 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
    617 			     M_USB, M_NOWAIT);
    618 	if (dev->ifaces == 0) {
    619 		r = USBD_NOMEM;
    620 		goto bad;
    621 	}
    622 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
    623 	dev->cdesc = cdp;
    624 	dev->config = cdp->bConfigurationValue;
    625 	dev->state = USBD_DEVICE_CONFIGURED;
    626 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
    627 		r = usbd_fill_iface_data(dev, ifcidx, 0);
    628 		if (r != USBD_NORMAL_COMPLETION) {
    629 			while (--ifcidx >= 0)
    630 				usbd_free_iface_data(dev, ifcidx);
    631 			goto bad;
    632 		}
    633 	}
    634 
    635 	return (USBD_NORMAL_COMPLETION);
    636 
    637  bad:
    638 	free(cdp, M_USB);
    639 	return (r);
    640 }
    641 
    642 /* XXX add function for alternate settings */
    643 
    644 usbd_status
    645 usbd_setup_pipe(dev, iface, ep, pipe)
    646 	usbd_device_handle dev;
    647 	usbd_interface_handle iface;
    648 	struct usbd_endpoint *ep;
    649 	usbd_pipe_handle *pipe;
    650 {
    651 	usbd_pipe_handle p;
    652 	usbd_status r;
    653 
    654 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
    655 		    dev, iface, ep, pipe));
    656 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
    657 	if (p == 0)
    658 		return (USBD_NOMEM);
    659 	p->device = dev;
    660 	p->iface = iface;
    661 	p->state = USBD_PIPE_ACTIVE;
    662 	p->endpoint = ep;
    663 	ep->refcnt++;
    664 	p->refcnt = 1;
    665 	p->intrreqh = 0;
    666 	p->running = 0;
    667 	SIMPLEQ_INIT(&p->queue);
    668 	r = dev->bus->open_pipe(p);
    669 	if (r != USBD_NORMAL_COMPLETION) {
    670 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error=%d"
    671 			 "(%s)\n",
    672 			 ep->edesc->bEndpointAddress, r, usbd_error_strs[r]));
    673 		free(p, M_USB);
    674 		return (r);
    675 	}
    676 	*pipe = p;
    677 	return (USBD_NORMAL_COMPLETION);
    678 }
    679 
    680 /* Abort the device control pipe. */
    681 void
    682 usbd_kill_pipe(pipe)
    683 	usbd_pipe_handle pipe;
    684 {
    685 	pipe->methods->close(pipe);
    686 	pipe->endpoint->refcnt--;
    687 	free(pipe, M_USB);
    688 }
    689 
    690 int
    691 usbd_getnewaddr(bus)
    692 	usbd_bus_handle bus;
    693 {
    694 	int addr;
    695 
    696 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
    697 		if (bus->devices[addr] == 0)
    698 			return (addr);
    699 	return (-1);
    700 }
    701 
    702 
    703 usbd_status
    704 usbd_probe_and_attach(parent, dev, port, addr)
    705 	bdevice *parent;
    706 	usbd_device_handle dev;
    707 	int port;
    708 	int addr;
    709 {
    710 	struct usb_attach_arg uaa;
    711 	usb_device_descriptor_t *dd = &dev->ddesc;
    712 	int r, found, i, confi, nifaces;
    713 	usbd_interface_handle ifaces[256]; /* 256 is the absolute max */
    714 
    715 #if defined(__FreeBSD__)
    716 /* XXX isn't it bad to build &uaa into a value that has a lifetime
    717    longer than this function call? */
    718 	bdevice bdev;
    719 	bdev = device_add_child(*parent, NULL, -1, &uaa);
    720 	if (bdev) {
    721 	    printf("%s: Device creation failed\n", USBDEVNAME(dev->bus->bdev));
    722 	    return (USBD_INVAL);
    723 	}
    724 #endif
    725 
    726 	uaa.device = dev;
    727 	uaa.iface = 0;
    728 	uaa.ifaces = 0;
    729 	uaa.nifaces = 0;
    730 	uaa.usegeneric = 0;
    731 	uaa.port = port;
    732 	uaa.configno = UHUB_UNK_CONFIGURATION;
    733 	uaa.ifaceno = UHUB_UNK_INTERFACE;
    734 
    735 	/* First try with device specific drivers. */
    736 	if (USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch))
    737 		return (USBD_NORMAL_COMPLETION);
    738 
    739 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
    740 
    741 	/* Next try with interface drivers. */
    742 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
    743 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
    744 			    confi));
    745 		r = usbd_set_config_index(dev, confi, 1);
    746 		if (r != USBD_NORMAL_COMPLETION) {
    747 #ifdef USB_DEBUG
    748 			DPRINTF(("%s: port %d, set config at addr %d failed, "
    749 				 "error=%d(%s)\n", USBDEVNAME(*parent), port,
    750 				 addr, r, usbd_error_strs[r]));
    751 #else
    752 			printf("%s: port %d, set config at addr %d failed\n",
    753 			       USBDEVNAME(*parent), port, addr);
    754 #endif
    755 			return (r);
    756 		}
    757 		nifaces = dev->cdesc->bNumInterface;
    758 		uaa.configno = confi;
    759 		for (i = 0; i < nifaces; i++)
    760 			ifaces[i] = &dev->ifaces[i];
    761 		uaa.ifaces = ifaces;
    762 		uaa.nifaces = nifaces;
    763 		for (found = i = 0; i < nifaces; i++) {
    764 			if (!ifaces[i])
    765 				continue; /* interface already claimed */
    766 			uaa.iface = ifaces[i];
    767 			uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
    768 			if (USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
    769 					  usbd_submatch)) {
    770 				found++;
    771 				ifaces[i] = 0; /* consumed */
    772 			}
    773 		}
    774 		if (found != 0)
    775 			return (USBD_NORMAL_COMPLETION);
    776 	}
    777 	/* No interfaces were attached in any of the configurations. */
    778 	if (dd->bNumConfigurations > 1)/* don't change if only 1 config */
    779 		usbd_set_config_index(dev, 0, 0);
    780 
    781 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
    782 
    783 	/* Finally try the generic driver. */
    784 	uaa.iface = 0;
    785 	uaa.usegeneric = 1;
    786 	uaa.configno = UHUB_UNK_CONFIGURATION;
    787 	uaa.ifaceno = UHUB_UNK_INTERFACE;
    788 	if (USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch))
    789 		return (USBD_NORMAL_COMPLETION);
    790 
    791 	/*
    792 	 * The generic attach failed, but leave the device as it is.
    793 	 * We just did not find any drivers, that's all.  The device is
    794 	 * fully operational and not harming anyone.
    795 	 */
    796 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
    797 	return (USBD_NORMAL_COMPLETION);
    798 }
    799 
    800 
    801 
    802 /*
    803  * Called when a new device has been put in the powered state,
    804  * but not yet in the addressed state.
    805  * Get initial descriptor, set the address, get full descriptor,
    806  * and attach a driver.
    807  */
    808 usbd_status
    809 usbd_new_device(parent, bus, depth, lowspeed, port, up)
    810 	bdevice *parent;
    811 	usbd_bus_handle bus;
    812 	int depth;
    813 	int lowspeed;
    814 	int port;
    815 	struct usbd_port *up;
    816 {
    817 	usbd_device_handle dev;
    818 	usb_device_descriptor_t *dd;
    819 	usbd_status r;
    820 	int addr;
    821 	int i;
    822 
    823 	DPRINTF(("usbd_new_device bus=%p depth=%d lowspeed=%d\n",
    824 		 bus, depth, lowspeed));
    825 	addr = usbd_getnewaddr(bus);
    826 	if (addr < 0) {
    827 		printf("%s: No free USB addresses, new device ignored.\n",
    828 		       USBDEVNAME(bus->bdev));
    829 		return (USBD_NO_ADDR);
    830 	}
    831 
    832 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT);
    833 	if (dev == 0)
    834 		return (USBD_NOMEM);
    835 	memset(dev, 0, sizeof(*dev));
    836 
    837 	dev->bus = bus;
    838 
    839 	/* Set up default endpoint handle. */
    840 	dev->def_ep.edesc = &dev->def_ep_desc;
    841 	dev->def_ep.state = USBD_ENDPOINT_ACTIVE;
    842 
    843 	/* Set up default endpoint descriptor. */
    844 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
    845 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
    846 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
    847 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
    848 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
    849 	dev->def_ep_desc.bInterval = 0;
    850 
    851 	dev->state = USBD_DEVICE_DEFAULT;
    852 	dev->quirks = &usbd_no_quirk;
    853 	dev->address = USB_START_ADDR;
    854 	dev->ddesc.bMaxPacketSize = 0;
    855 	dev->lowspeed = lowspeed != 0;
    856 	dev->depth = depth;
    857 	dev->powersrc = up;
    858 	dev->langid = USBD_NOLANG;
    859 
    860 	/* Establish the the default pipe. */
    861 	r = usbd_setup_pipe(dev, 0, &dev->def_ep, &dev->default_pipe);
    862 	if (r != USBD_NORMAL_COMPLETION) {
    863 		usbd_remove_device(dev, up);
    864 		return (r);
    865 	}
    866 
    867 	up->device = dev;
    868 	dd = &dev->ddesc;
    869 	/* Try a few times in case the device is slow (i.e. outside specs.) */
    870 	for (i = 0; i < 5; i++) {
    871 		/* Get the first 8 bytes of the device descriptor. */
    872 		r = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
    873 		if (r == USBD_NORMAL_COMPLETION)
    874 			break;
    875 		usbd_delay_ms(dev->bus, 200);
    876 	}
    877 	if (r != USBD_NORMAL_COMPLETION) {
    878 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
    879 			      "failed\n",
    880 			      addr));
    881 		usbd_remove_device(dev, up);
    882 		return (r);
    883 	}
    884 
    885 	if (dd->bDescriptorType != UDESC_DEVICE) {
    886 		/* Illegal device descriptor */
    887 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
    888 			     dd->bDescriptorType));
    889 		usbd_remove_device(dev, up);
    890 		return (USBD_INVAL);
    891 	}
    892 
    893 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
    894 		 "subclass=%d, protocol=%d, maxpacket=%d, ls=%d\n",
    895 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
    896 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dev->lowspeed));
    897 
    898 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
    899 
    900 	/* Get the full device descriptor. */
    901 	r = usbd_get_device_desc(dev, dd);
    902 	if (r != USBD_NORMAL_COMPLETION) {
    903 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
    904 			      "failed\n", addr));
    905 		usbd_remove_device(dev, up);
    906 		return (r);
    907 	}
    908 
    909 	/* Figure out what's wrong with this device. */
    910 	dev->quirks = usbd_find_quirk(dd);
    911 
    912 	/* Set the address */
    913 	r = usbd_set_address(dev, addr);
    914 	if (r != USBD_NORMAL_COMPLETION) {
    915 		DPRINTFN(-1,("usb_new_device: set address %d failed\n",addr));
    916 		r = USBD_SET_ADDR_FAILED;
    917 		usbd_remove_device(dev, up);
    918 		return (r);
    919 	}
    920 	/* Allow device time to set new address */
    921 	usbd_delay_ms(dev->bus, USB_SET_ADDRESS_SETTLE);
    922 
    923 	dev->address = addr;	/* New device address now */
    924 	dev->state = USBD_DEVICE_ADDRESSED;
    925 	bus->devices[addr] = dev;
    926 
    927 	/* Assume 100mA bus powered for now. Changed when configured. */
    928 	dev->power = USB_MIN_POWER;
    929 	dev->self_powered = 0;
    930 
    931 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
    932 		 addr, dev, parent));
    933 
    934 	r = usbd_probe_and_attach(parent, dev, port, addr);
    935 	if (r != USBD_NORMAL_COMPLETION) {
    936 		usbd_remove_device(dev, up);
    937 		return (r);
    938   	}
    939 
    940   	return (USBD_NORMAL_COMPLETION);
    941 }
    942 
    943 void
    944 usbd_remove_device(dev, up)
    945 	usbd_device_handle dev;
    946 	struct usbd_port *up;
    947 {
    948 	DPRINTF(("usbd_remove_device: %p\n", dev));
    949 
    950 #if defined(__NetBSD__)
    951 	/* XXX bit of a hack, only for hubs the detach is called
    952 	 *
    953 	 * easiest solution, register a detach method in the softc, call that
    954 	 * one and pass the device struct to it, or the softc. Whatever.
    955 	 */
    956 	/*if (dev->bdev && dev->hub)
    957 	  uhub_detach(dev->hub->hubdata);*/
    958 #elif defined(__FreeBSD__)
    959 	if (dev->bdev)
    960 		device_delete_child(device_get_parent(dev->bdev), dev->bdev);
    961 #endif
    962 
    963 	if (dev->default_pipe)
    964 		usbd_kill_pipe(dev->default_pipe);
    965 	up->device = 0;
    966 	dev->bus->devices[dev->address] = 0;
    967 
    968 	free(dev, M_USB);
    969 }
    970 
    971 #if defined(__NetBSD__)
    972 int
    973 usbd_print(aux, pnp)
    974 	void *aux;
    975 	const char *pnp;
    976 {
    977 	struct usb_attach_arg *uaa = aux;
    978 	char devinfo[1024];
    979 
    980 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
    981 	if (pnp) {
    982 		if (!uaa->usegeneric)
    983 			return (QUIET);
    984 		usbd_devinfo(uaa->device, 1, devinfo);
    985 		printf("%s, %s", devinfo, pnp);
    986 	}
    987 	if (uaa->port != 0)
    988 		printf(" port %d", uaa->port);
    989 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
    990 		printf(" configuration %d", uaa->configno);
    991 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
    992 		printf(" interface %d", uaa->ifaceno);
    993 	return (UNCONF);
    994 }
    995 
    996 int
    997 usbd_submatch(parent, cf, aux)
    998 	struct device *parent;
    999 	struct cfdata *cf;
   1000 	void *aux;
   1001 {
   1002 	struct usb_attach_arg *uaa = aux;
   1003 
   1004 	if ((uaa->port != 0 &&
   1005 	     cf->uhubcf_port != UHUB_UNK_PORT &&
   1006 	     cf->uhubcf_port != uaa->port) ||
   1007 	    (uaa->configno != UHUB_UNK_CONFIGURATION &&
   1008 	     cf->uhubcf_configuration != UHUB_UNK_CONFIGURATION &&
   1009 	     cf->uhubcf_configuration != uaa->configno) ||
   1010 	    (uaa->ifaceno != UHUB_UNK_INTERFACE &&
   1011 	     cf->uhubcf_interface != UHUB_UNK_INTERFACE &&
   1012 	     cf->uhubcf_interface != uaa->ifaceno))
   1013 		return 0;
   1014 	return ((*cf->cf_attach->ca_match)(parent, cf, aux));
   1015 }
   1016 
   1017 #elif defined(__FreeBSD__)
   1018 static void
   1019 usbd_bus_print_child(device_t bus, device_t dev)
   1020 {
   1021 	/* FIXME print the device address and the configuration used
   1022 	 */
   1023 }
   1024 #endif
   1025 
   1026 usbd_status
   1027 usb_insert_transfer(reqh)
   1028 	usbd_request_handle reqh;
   1029 {
   1030 	usbd_pipe_handle pipe = reqh->pipe;
   1031 	usbd_interface_handle iface = pipe->iface;
   1032 
   1033 	if (pipe->state == USBD_PIPE_IDLE ||
   1034 	    (iface && iface->state == USBD_INTERFACE_IDLE))
   1035 		return (USBD_IS_IDLE);
   1036 	SIMPLEQ_INSERT_TAIL(&pipe->queue, reqh, next);
   1037 	if (pipe->state != USBD_PIPE_ACTIVE ||
   1038 	    (iface && iface->state != USBD_INTERFACE_ACTIVE))
   1039 		return (USBD_NOT_STARTED);
   1040 	if (pipe->running)
   1041 		return (USBD_IN_PROGRESS);
   1042 	pipe->running = 1;
   1043 	return (USBD_NORMAL_COMPLETION);
   1044 }
   1045 
   1046 void
   1047 usb_start_next(pipe)
   1048 	usbd_pipe_handle pipe;
   1049 {
   1050 	usbd_request_handle reqh;
   1051 	usbd_status r;
   1052 
   1053 #ifdef DIAGNOSTIC
   1054 	if (SIMPLEQ_FIRST(&pipe->queue) == 0) {
   1055 		printf("usb_start_next: empty\n");
   1056 		return;
   1057 	}
   1058 #endif
   1059 
   1060 	/* First remove remove old */
   1061 	SIMPLEQ_REMOVE_HEAD(&pipe->queue, SIMPLEQ_FIRST(&pipe->queue), next);
   1062 	if (pipe->state != USBD_PIPE_ACTIVE) {
   1063 		pipe->running = 0;
   1064 		return;
   1065 	}
   1066 	reqh = SIMPLEQ_FIRST(&pipe->queue);
   1067 	DPRINTFN(5, ("usb_start_next: start reqh=%p\n", reqh));
   1068 	if (!reqh)
   1069 		pipe->running = 0;
   1070 	else {
   1071 		r = pipe->methods->start(reqh);
   1072 		if (r != USBD_IN_PROGRESS) {
   1073 			printf("usb_start_next: error=%d\n", r);
   1074 			pipe->running = 0;
   1075 			/* XXX do what? */
   1076 		}
   1077 	}
   1078 }
   1079 
   1080 void
   1081 usbd_fill_deviceinfo(dev, di)
   1082 	usbd_device_handle dev;
   1083 	struct usb_device_info *di;
   1084 {
   1085 	struct usbd_port *p;
   1086 	int i, r, s;
   1087 
   1088 	di->config = dev->config;
   1089 	usbd_devinfo_vp(dev, di->vendor, di->product);
   1090 	usbd_printBCD(di->revision, UGETW(dev->ddesc.bcdDevice));
   1091 	di->vendorNo = UGETW(dev->ddesc.idVendor);
   1092 	di->productNo = UGETW(dev->ddesc.idProduct);
   1093 	di->class = dev->ddesc.bDeviceClass;
   1094 	di->power = dev->self_powered ? 0 : dev->power;
   1095 	di->lowspeed = dev->lowspeed;
   1096 	di->addr = dev->address;
   1097 	if (dev->hub) {
   1098 		for (i = 0;
   1099 		     i < sizeof(di->ports) / sizeof(di->ports[0]) &&
   1100 			     i < dev->hub->hubdesc.bNbrPorts;
   1101 		     i++) {
   1102 			p = &dev->hub->ports[i];
   1103 			if (p->device)
   1104 				r = p->device->address;
   1105 			else {
   1106 				s = UGETW(p->status.wPortStatus);
   1107 				if (s & UPS_PORT_ENABLED)
   1108 					r = USB_PORT_ENABLED;
   1109 				else if (s & UPS_SUSPEND)
   1110 					r = USB_PORT_SUSPENDED;
   1111 				else if (s & UPS_PORT_POWER)
   1112 					r = USB_PORT_POWERED;
   1113 				else
   1114 					r = USB_PORT_DISABLED;
   1115 			}
   1116 			di->ports[i] = r;
   1117 		}
   1118 		di->nports = dev->hub->hubdesc.bNbrPorts;
   1119 	} else
   1120 		di->nports = 0;
   1121 }
   1122