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