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