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