xref: /netbsd-src/sys/dev/usb/usb_subr.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: usb_subr.c,v 1.131 2005/11/23 08:54:48 augustss 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.131 2005/11/23 08:54:48 augustss 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[USB_MAX_ENCODED_STRING_LEN];
264 	char product[USB_MAX_ENCODED_STRING_LEN];
265 	int bcdDevice, bcdUSB;
266 	char *ep;
267 
268 	ep = cp + l;
269 
270 	usbd_devinfo_vp(dev, vendor, product, 1);
271 	cp += snprintf(cp, ep - cp, "%s %s", vendor, product);
272 	if (showclass)
273 		cp += snprintf(cp, ep - cp, ", class %d/%d",
274 		    udd->bDeviceClass, udd->bDeviceSubClass);
275 	bcdUSB = UGETW(udd->bcdUSB);
276 	bcdDevice = UGETW(udd->bcdDevice);
277 	cp += snprintf(cp, ep - cp, ", rev ");
278 	cp += usbd_printBCD(cp, ep - cp, bcdUSB);
279 	*cp++ = '/';
280 	cp += usbd_printBCD(cp, ep - cp, bcdDevice);
281 	cp += snprintf(cp, ep - cp, ", addr %d", dev->address);
282 	*cp = 0;
283 }
284 
285 char *
286 usbd_devinfo_alloc(usbd_device_handle dev, int showclass)
287 {
288 	char *devinfop;
289 
290 	devinfop = malloc(DEVINFOSIZE, M_TEMP, M_WAITOK);
291 	usbd_devinfo(dev, showclass, devinfop, DEVINFOSIZE);
292 	return devinfop;
293 }
294 
295 void
296 usbd_devinfo_free(char *devinfop)
297 {
298 	free(devinfop, M_TEMP);
299 }
300 
301 /* Delay for a certain number of ms */
302 void
303 usb_delay_ms(usbd_bus_handle bus, u_int ms)
304 {
305 	/* Wait at least two clock ticks so we know the time has passed. */
306 	if (bus->use_polling || cold)
307 		delay((ms+1) * 1000);
308 	else
309 		tsleep(&ms, PRIBIO, "usbdly", (ms*hz+999)/1000 + 1);
310 }
311 
312 /* Delay given a device handle. */
313 void
314 usbd_delay_ms(usbd_device_handle dev, u_int ms)
315 {
316 	usb_delay_ms(dev->bus, ms);
317 }
318 
319 usbd_status
320 usbd_reset_port(usbd_device_handle dev, int port, usb_port_status_t *ps)
321 {
322 	usb_device_request_t req;
323 	usbd_status err;
324 	int n;
325 
326 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
327 	req.bRequest = UR_SET_FEATURE;
328 	USETW(req.wValue, UHF_PORT_RESET);
329 	USETW(req.wIndex, port);
330 	USETW(req.wLength, 0);
331 	err = usbd_do_request(dev, &req, 0);
332 	DPRINTFN(1,("usbd_reset_port: port %d reset done, error=%s\n",
333 		    port, usbd_errstr(err)));
334 	if (err)
335 		return (err);
336 	n = 10;
337 	do {
338 		/* Wait for device to recover from reset. */
339 		usbd_delay_ms(dev, USB_PORT_RESET_DELAY);
340 		err = usbd_get_port_status(dev, port, ps);
341 		if (err) {
342 			DPRINTF(("usbd_reset_port: get status failed %d\n",
343 				 err));
344 			return (err);
345 		}
346 		/* If the device disappeared, just give up. */
347 		if (!(UGETW(ps->wPortStatus) & UPS_CURRENT_CONNECT_STATUS))
348 			return (USBD_NORMAL_COMPLETION);
349 	} while ((UGETW(ps->wPortChange) & UPS_C_PORT_RESET) == 0 && --n > 0);
350 	if (n == 0)
351 		return (USBD_TIMEOUT);
352 	err = usbd_clear_port_feature(dev, port, UHF_C_PORT_RESET);
353 #ifdef USB_DEBUG
354 	if (err)
355 		DPRINTF(("usbd_reset_port: clear port feature failed %d\n",
356 			 err));
357 #endif
358 
359 	/* Wait for the device to recover from reset. */
360 	usbd_delay_ms(dev, USB_PORT_RESET_RECOVERY);
361 	return (err);
362 }
363 
364 usb_interface_descriptor_t *
365 usbd_find_idesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx)
366 {
367 	char *p = (char *)cd;
368 	char *end = p + UGETW(cd->wTotalLength);
369 	usb_interface_descriptor_t *d;
370 	int curidx, lastidx, curaidx = 0;
371 
372 	for (curidx = lastidx = -1; p < end; ) {
373 		d = (usb_interface_descriptor_t *)p;
374 		DPRINTFN(4,("usbd_find_idesc: idx=%d(%d) altidx=%d(%d) len=%d "
375 			    "type=%d\n",
376 			    ifaceidx, curidx, altidx, curaidx,
377 			    d->bLength, d->bDescriptorType));
378 		if (d->bLength == 0) /* bad descriptor */
379 			break;
380 		p += d->bLength;
381 		if (p <= end && d->bDescriptorType == UDESC_INTERFACE) {
382 			if (d->bInterfaceNumber != lastidx) {
383 				lastidx = d->bInterfaceNumber;
384 				curidx++;
385 				curaidx = 0;
386 			} else
387 				curaidx++;
388 			if (ifaceidx == curidx && altidx == curaidx)
389 				return (d);
390 		}
391 	}
392 	return (NULL);
393 }
394 
395 usb_endpoint_descriptor_t *
396 usbd_find_edesc(usb_config_descriptor_t *cd, int ifaceidx, int altidx,
397 		int endptidx)
398 {
399 	char *p = (char *)cd;
400 	char *end = p + UGETW(cd->wTotalLength);
401 	usb_interface_descriptor_t *d;
402 	usb_endpoint_descriptor_t *e;
403 	int curidx;
404 
405 	d = usbd_find_idesc(cd, ifaceidx, altidx);
406 	if (d == NULL)
407 		return (NULL);
408 	if (endptidx >= d->bNumEndpoints) /* quick exit */
409 		return (NULL);
410 
411 	curidx = -1;
412 	for (p = (char *)d + d->bLength; p < end; ) {
413 		e = (usb_endpoint_descriptor_t *)p;
414 		if (e->bLength == 0) /* bad descriptor */
415 			break;
416 		p += e->bLength;
417 		if (p <= end && e->bDescriptorType == UDESC_INTERFACE)
418 			return (NULL);
419 		if (p <= end && e->bDescriptorType == UDESC_ENDPOINT) {
420 			curidx++;
421 			if (curidx == endptidx)
422 				return (e);
423 		}
424 	}
425 	return (NULL);
426 }
427 
428 usbd_status
429 usbd_fill_iface_data(usbd_device_handle dev, int ifaceidx, int altidx)
430 {
431 	usbd_interface_handle ifc = &dev->ifaces[ifaceidx];
432 	usb_interface_descriptor_t *idesc;
433 	char *p, *end;
434 	int endpt, nendpt;
435 
436 	DPRINTFN(4,("usbd_fill_iface_data: ifaceidx=%d altidx=%d\n",
437 		    ifaceidx, altidx));
438 	idesc = usbd_find_idesc(dev->cdesc, ifaceidx, altidx);
439 	if (idesc == NULL)
440 		return (USBD_INVAL);
441 	ifc->device = dev;
442 	ifc->idesc = idesc;
443 	ifc->index = ifaceidx;
444 	ifc->altindex = altidx;
445 	nendpt = ifc->idesc->bNumEndpoints;
446 	DPRINTFN(4,("usbd_fill_iface_data: found idesc nendpt=%d\n", nendpt));
447 	if (nendpt != 0) {
448 		ifc->endpoints = malloc(nendpt * sizeof(struct usbd_endpoint),
449 					M_USB, M_NOWAIT);
450 		if (ifc->endpoints == NULL)
451 			return (USBD_NOMEM);
452 	} else
453 		ifc->endpoints = NULL;
454 	ifc->priv = NULL;
455 	p = (char *)ifc->idesc + ifc->idesc->bLength;
456 	end = (char *)dev->cdesc + UGETW(dev->cdesc->wTotalLength);
457 #define ed ((usb_endpoint_descriptor_t *)p)
458 	for (endpt = 0; endpt < nendpt; endpt++) {
459 		DPRINTFN(10,("usbd_fill_iface_data: endpt=%d\n", endpt));
460 		for (; p < end; p += ed->bLength) {
461 			DPRINTFN(10,("usbd_fill_iface_data: p=%p end=%p "
462 				     "len=%d type=%d\n",
463 				 p, end, ed->bLength, ed->bDescriptorType));
464 			if (p + ed->bLength <= end && ed->bLength != 0 &&
465 			    ed->bDescriptorType == UDESC_ENDPOINT)
466 				goto found;
467 			if (ed->bLength == 0 ||
468 			    ed->bDescriptorType == UDESC_INTERFACE)
469 				break;
470 		}
471 		/* passed end, or bad desc */
472 		printf("usbd_fill_iface_data: bad descriptor(s): %s\n",
473 		       ed->bLength == 0 ? "0 length" :
474 		       ed->bDescriptorType == UDESC_INTERFACE ? "iface desc":
475 		       "out of data");
476 		goto bad;
477 	found:
478 		ifc->endpoints[endpt].edesc = ed;
479 		if (dev->speed == USB_SPEED_HIGH) {
480 			u_int mps;
481 			/* Control and bulk endpoints have max packet limits. */
482 			switch (UE_GET_XFERTYPE(ed->bmAttributes)) {
483 			case UE_CONTROL:
484 				mps = USB_2_MAX_CTRL_PACKET;
485 				goto check;
486 			case UE_BULK:
487 				mps = USB_2_MAX_BULK_PACKET;
488 			check:
489 				if (UGETW(ed->wMaxPacketSize) != mps) {
490 					USETW(ed->wMaxPacketSize, mps);
491 #ifdef DIAGNOSTIC
492 					printf("usbd_fill_iface_data: bad max "
493 					       "packet size\n");
494 #endif
495 				}
496 				break;
497 			default:
498 				break;
499 			}
500 		}
501 		ifc->endpoints[endpt].refcnt = 0;
502 		p += ed->bLength;
503 	}
504 #undef ed
505 	LIST_INIT(&ifc->pipes);
506 	return (USBD_NORMAL_COMPLETION);
507 
508  bad:
509 	if (ifc->endpoints != NULL) {
510 		free(ifc->endpoints, M_USB);
511 		ifc->endpoints = NULL;
512 	}
513 	return (USBD_INVAL);
514 }
515 
516 void
517 usbd_free_iface_data(usbd_device_handle dev, int ifcno)
518 {
519 	usbd_interface_handle ifc = &dev->ifaces[ifcno];
520 	if (ifc->endpoints)
521 		free(ifc->endpoints, M_USB);
522 }
523 
524 Static usbd_status
525 usbd_set_config(usbd_device_handle dev, int conf)
526 {
527 	usb_device_request_t req;
528 
529 	req.bmRequestType = UT_WRITE_DEVICE;
530 	req.bRequest = UR_SET_CONFIG;
531 	USETW(req.wValue, conf);
532 	USETW(req.wIndex, 0);
533 	USETW(req.wLength, 0);
534 	return (usbd_do_request(dev, &req, 0));
535 }
536 
537 usbd_status
538 usbd_set_config_no(usbd_device_handle dev, int no, int msg)
539 {
540 	int index;
541 	usb_config_descriptor_t cd;
542 	usbd_status err;
543 
544 	if (no == USB_UNCONFIG_NO)
545 		return (usbd_set_config_index(dev, USB_UNCONFIG_INDEX, msg));
546 
547 	DPRINTFN(5,("usbd_set_config_no: %d\n", no));
548 	/* Figure out what config index to use. */
549 	for (index = 0; index < dev->ddesc.bNumConfigurations; index++) {
550 		err = usbd_get_config_desc(dev, index, &cd);
551 		if (err)
552 			return (err);
553 		if (cd.bConfigurationValue == no)
554 			return (usbd_set_config_index(dev, index, msg));
555 	}
556 	return (USBD_INVAL);
557 }
558 
559 usbd_status
560 usbd_set_config_index(usbd_device_handle dev, int index, int msg)
561 {
562 	usb_status_t ds;
563 	usb_config_descriptor_t cd, *cdp;
564 	usbd_status err;
565 	int i, ifcidx, nifc, len, selfpowered, power;
566 
567 	DPRINTFN(5,("usbd_set_config_index: dev=%p index=%d\n", dev, index));
568 
569 	/* XXX check that all interfaces are idle */
570 	if (dev->config != USB_UNCONFIG_NO) {
571 		DPRINTF(("usbd_set_config_index: free old config\n"));
572 		/* Free all configuration data structures. */
573 		nifc = dev->cdesc->bNumInterface;
574 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
575 			usbd_free_iface_data(dev, ifcidx);
576 		free(dev->ifaces, M_USB);
577 		free(dev->cdesc, M_USB);
578 		dev->ifaces = NULL;
579 		dev->cdesc = NULL;
580 		dev->config = USB_UNCONFIG_NO;
581 	}
582 
583 	if (index == USB_UNCONFIG_INDEX) {
584 		/* We are unconfiguring the device, so leave unallocated. */
585 		DPRINTF(("usbd_set_config_index: set config 0\n"));
586 		err = usbd_set_config(dev, USB_UNCONFIG_NO);
587 		if (err)
588 			DPRINTF(("usbd_set_config_index: setting config=0 "
589 				 "failed, error=%s\n", usbd_errstr(err)));
590 		return (err);
591 	}
592 
593 	/* Get the short descriptor. */
594 	err = usbd_get_config_desc(dev, index, &cd);
595 	if (err)
596 		return (err);
597 	len = UGETW(cd.wTotalLength);
598 	cdp = malloc(len, M_USB, M_NOWAIT);
599 	if (cdp == NULL)
600 		return (USBD_NOMEM);
601 
602 	/* Get the full descriptor.  Try a few times for slow devices. */
603 	for (i = 0; i < 3; i++) {
604 		err = usbd_get_desc(dev, UDESC_CONFIG, index, len, cdp);
605 		if (!err)
606 			break;
607 		usbd_delay_ms(dev, 200);
608 	}
609 	if (err)
610 		goto bad;
611 
612 	if (cdp->bDescriptorType != UDESC_CONFIG) {
613 		DPRINTFN(-1,("usbd_set_config_index: bad desc %d\n",
614 			     cdp->bDescriptorType));
615 		err = USBD_INVAL;
616 		goto bad;
617 	}
618 
619 	/* Figure out if the device is self or bus powered. */
620 	selfpowered = 0;
621 	if (!(dev->quirks->uq_flags & UQ_BUS_POWERED) &&
622 	    (cdp->bmAttributes & UC_SELF_POWERED)) {
623 		/* May be self powered. */
624 		if (cdp->bmAttributes & UC_BUS_POWERED) {
625 			/* Must ask device. */
626 			if (dev->quirks->uq_flags & UQ_POWER_CLAIM) {
627 				/*
628 				 * Hub claims to be self powered, but isn't.
629 				 * It seems that the power status can be
630 				 * determined by the hub characteristics.
631 				 */
632 				usb_hub_descriptor_t hd;
633 				usb_device_request_t req;
634 				req.bmRequestType = UT_READ_CLASS_DEVICE;
635 				req.bRequest = UR_GET_DESCRIPTOR;
636 				USETW(req.wValue, 0);
637 				USETW(req.wIndex, 0);
638 				USETW(req.wLength, USB_HUB_DESCRIPTOR_SIZE);
639 				err = usbd_do_request(dev, &req, &hd);
640 				if (!err &&
641 				    (UGETW(hd.wHubCharacteristics) &
642 				     UHD_PWR_INDIVIDUAL))
643 					selfpowered = 1;
644 				DPRINTF(("usbd_set_config_index: charac=0x%04x"
645 				    ", error=%s\n",
646 				    UGETW(hd.wHubCharacteristics),
647 				    usbd_errstr(err)));
648 			} else {
649 				err = usbd_get_device_status(dev, &ds);
650 				if (!err &&
651 				    (UGETW(ds.wStatus) & UDS_SELF_POWERED))
652 					selfpowered = 1;
653 				DPRINTF(("usbd_set_config_index: status=0x%04x"
654 				    ", error=%s\n",
655 				    UGETW(ds.wStatus), usbd_errstr(err)));
656 			}
657 		} else
658 			selfpowered = 1;
659 	}
660 	DPRINTF(("usbd_set_config_index: (addr %d) cno=%d attr=0x%02x, "
661 		 "selfpowered=%d, power=%d\n",
662 		 cdp->bConfigurationValue, dev->address, cdp->bmAttributes,
663 		 selfpowered, cdp->bMaxPower * 2));
664 
665 	/* Check if we have enough power. */
666 #ifdef USB_DEBUG
667 	if (dev->powersrc == NULL) {
668 		DPRINTF(("usbd_set_config_index: No power source?\n"));
669 		return (USBD_IOERROR);
670 	}
671 #endif
672 	power = cdp->bMaxPower * 2;
673 	if (power > dev->powersrc->power) {
674 		DPRINTF(("power exceeded %d %d\n", power,dev->powersrc->power));
675 		/* XXX print nicer message. */
676 		if (msg)
677 			printf("%s: device addr %d (config %d) exceeds power "
678 				 "budget, %d mA > %d mA\n",
679 			       USBDEVNAME(dev->bus->bdev), dev->address,
680 			       cdp->bConfigurationValue,
681 			       power, dev->powersrc->power);
682 		err = USBD_NO_POWER;
683 		goto bad;
684 	}
685 	dev->power = power;
686 	dev->self_powered = selfpowered;
687 
688 	/* Set the actual configuration value. */
689 	DPRINTF(("usbd_set_config_index: set config %d\n",
690 		 cdp->bConfigurationValue));
691 	err = usbd_set_config(dev, cdp->bConfigurationValue);
692 	if (err) {
693 		DPRINTF(("usbd_set_config_index: setting config=%d failed, "
694 			 "error=%s\n",
695 			 cdp->bConfigurationValue, usbd_errstr(err)));
696 		goto bad;
697 	}
698 
699 	/* Allocate and fill interface data. */
700 	nifc = cdp->bNumInterface;
701 	dev->ifaces = malloc(nifc * sizeof(struct usbd_interface),
702 			     M_USB, M_NOWAIT);
703 	if (dev->ifaces == NULL) {
704 		err = USBD_NOMEM;
705 		goto bad;
706 	}
707 	DPRINTFN(5,("usbd_set_config_index: dev=%p cdesc=%p\n", dev, cdp));
708 	dev->cdesc = cdp;
709 	dev->config = cdp->bConfigurationValue;
710 	for (ifcidx = 0; ifcidx < nifc; ifcidx++) {
711 		err = usbd_fill_iface_data(dev, ifcidx, 0);
712 		if (err) {
713 			while (--ifcidx >= 0)
714 				usbd_free_iface_data(dev, ifcidx);
715 			goto bad;
716 		}
717 	}
718 
719 	return (USBD_NORMAL_COMPLETION);
720 
721  bad:
722 	free(cdp, M_USB);
723 	return (err);
724 }
725 
726 /* XXX add function for alternate settings */
727 
728 usbd_status
729 usbd_setup_pipe(usbd_device_handle dev, usbd_interface_handle iface,
730 		struct usbd_endpoint *ep, int ival, usbd_pipe_handle *pipe)
731 {
732 	usbd_pipe_handle p;
733 	usbd_status err;
734 
735 	DPRINTFN(1,("usbd_setup_pipe: dev=%p iface=%p ep=%p pipe=%p\n",
736 		    dev, iface, ep, pipe));
737 	p = malloc(dev->bus->pipe_size, M_USB, M_NOWAIT);
738 	if (p == NULL)
739 		return (USBD_NOMEM);
740 	p->device = dev;
741 	p->iface = iface;
742 	p->endpoint = ep;
743 	ep->refcnt++;
744 	p->refcnt = 1;
745 	p->intrxfer = 0;
746 	p->running = 0;
747 	p->aborting = 0;
748 	p->repeat = 0;
749 	p->interval = ival;
750 	SIMPLEQ_INIT(&p->queue);
751 	err = dev->bus->methods->open_pipe(p);
752 	if (err) {
753 		DPRINTFN(-1,("usbd_setup_pipe: endpoint=0x%x failed, error="
754 			 "%s\n",
755 			 ep->edesc->bEndpointAddress, usbd_errstr(err)));
756 		free(p, M_USB);
757 		return (err);
758 	}
759 	*pipe = p;
760 	return (USBD_NORMAL_COMPLETION);
761 }
762 
763 /* Abort the device control pipe. */
764 void
765 usbd_kill_pipe(usbd_pipe_handle pipe)
766 {
767 	usbd_abort_pipe(pipe);
768 	pipe->methods->close(pipe);
769 	pipe->endpoint->refcnt--;
770 	free(pipe, M_USB);
771 }
772 
773 int
774 usbd_getnewaddr(usbd_bus_handle bus)
775 {
776 	int addr;
777 
778 	for (addr = 1; addr < USB_MAX_DEVICES; addr++)
779 		if (bus->devices[addr] == 0)
780 			return (addr);
781 	return (-1);
782 }
783 
784 
785 usbd_status
786 usbd_probe_and_attach(device_ptr_t parent, usbd_device_handle dev,
787 		      int port, int addr)
788 {
789 	struct usb_attach_arg uaa;
790 	usb_device_descriptor_t *dd = &dev->ddesc;
791 	int found, i, confi, nifaces;
792 	usbd_status err;
793 	device_ptr_t dv;
794 	usbd_interface_handle ifaces[256]; /* 256 is the absolute max */
795 
796 #if defined(__FreeBSD__)
797 	/*
798 	 * XXX uaa is a static var. Not a problem as it _should_ be used only
799 	 * during probe and attach. Should be changed however.
800 	 */
801 	device_t bdev;
802 	bdev = device_add_child(parent, NULL, -1, &uaa);
803 	if (!bdev) {
804 	    printf("%s: Device creation failed\n", USBDEVNAME(dev->bus->bdev));
805 	    return (USBD_INVAL);
806 	}
807 	device_quiet(bdev);
808 #endif
809 
810 	uaa.device = dev;
811 	uaa.iface = NULL;
812 	uaa.ifaces = NULL;
813 	uaa.nifaces = 0;
814 	uaa.usegeneric = 0;
815 	uaa.port = port;
816 	uaa.configno = UHUB_UNK_CONFIGURATION;
817 	uaa.ifaceno = UHUB_UNK_INTERFACE;
818 	uaa.vendor = UGETW(dd->idVendor);
819 	uaa.product = UGETW(dd->idProduct);
820 	uaa.release = UGETW(dd->bcdDevice);
821 
822 	/* First try with device specific drivers. */
823 	DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
824 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
825 	if (dv) {
826 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
827 		if (dev->subdevs == NULL)
828 			return (USBD_NOMEM);
829 		dev->subdevs[0] = dv;
830 		dev->subdevs[1] = 0;
831 		return (USBD_NORMAL_COMPLETION);
832 	}
833 
834 	DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
835 
836 	DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
837 		 dd->bNumConfigurations));
838 	/* Next try with interface drivers. */
839 	for (confi = 0; confi < dd->bNumConfigurations; confi++) {
840 		DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
841 			    confi));
842 		err = usbd_set_config_index(dev, confi, 1);
843 		if (err) {
844 #ifdef USB_DEBUG
845 			DPRINTF(("%s: port %d, set config at addr %d failed, "
846 				 "error=%s\n", USBDEVPTRNAME(parent), port,
847 				 addr, usbd_errstr(err)));
848 #else
849 			printf("%s: port %d, set config at addr %d failed\n",
850 			       USBDEVPTRNAME(parent), port, addr);
851 #endif
852 #if defined(__FreeBSD__)
853 			device_delete_child(parent, bdev);
854 #endif
855 
856  			return (err);
857 		}
858 		nifaces = dev->cdesc->bNumInterface;
859 		uaa.configno = dev->cdesc->bConfigurationValue;
860 		for (i = 0; i < nifaces; i++)
861 			ifaces[i] = &dev->ifaces[i];
862 		uaa.ifaces = ifaces;
863 		uaa.nifaces = nifaces;
864 		dev->subdevs = malloc((nifaces+1) * sizeof dv, M_USB,M_NOWAIT);
865 		if (dev->subdevs == NULL) {
866 #if defined(__FreeBSD__)
867 			device_delete_child(parent, bdev);
868 #endif
869 			return (USBD_NOMEM);
870 		}
871 
872 		found = 0;
873 		for (i = 0; i < nifaces; i++) {
874 			if (ifaces[i] == NULL)
875 				continue; /* interface already claimed */
876 			uaa.iface = ifaces[i];
877 			uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
878 			dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
879 					   usbd_submatch);
880 			if (dv != NULL) {
881 				dev->subdevs[found++] = dv;
882 				dev->subdevs[found] = 0;
883 				ifaces[i] = 0; /* consumed */
884 
885 #if defined(__FreeBSD__)
886 				/* create another child for the next iface */
887 				bdev = device_add_child(parent, NULL, -1,&uaa);
888 				if (!bdev) {
889 					printf("%s: Device creation failed\n",
890 					USBDEVNAME(dev->bus->bdev));
891 					return (USBD_NORMAL_COMPLETION);
892 				}
893 				device_quiet(bdev);
894 #endif
895 			}
896 		}
897 		if (found != 0) {
898 #if defined(__FreeBSD__)
899 			/* remove the last created child again; it is unused */
900 			device_delete_child(parent, bdev);
901 #endif
902 			return (USBD_NORMAL_COMPLETION);
903 		}
904 		free(dev->subdevs, M_USB);
905 		dev->subdevs = 0;
906 	}
907 	/* No interfaces were attached in any of the configurations. */
908 
909 	if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
910 		usbd_set_config_index(dev, 0, 0);
911 
912 	DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
913 
914 	/* Finally try the generic driver. */
915 	uaa.iface = NULL;
916 	uaa.usegeneric = 1;
917 	uaa.configno = UHUB_UNK_CONFIGURATION;
918 	uaa.ifaceno = UHUB_UNK_INTERFACE;
919 	dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
920 	if (dv != NULL) {
921 		dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
922 		if (dev->subdevs == 0)
923 			return (USBD_NOMEM);
924 		dev->subdevs[0] = dv;
925 		dev->subdevs[1] = 0;
926 		return (USBD_NORMAL_COMPLETION);
927 	}
928 
929 	/*
930 	 * The generic attach failed, but leave the device as it is.
931 	 * We just did not find any drivers, that's all.  The device is
932 	 * fully operational and not harming anyone.
933 	 */
934 	DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
935 #if defined(__FreeBSD__)
936 	device_delete_child(parent, bdev);
937 #endif
938  	return (USBD_NORMAL_COMPLETION);
939 }
940 
941 
942 /*
943  * Called when a new device has been put in the powered state,
944  * but not yet in the addressed state.
945  * Get initial descriptor, set the address, get full descriptor,
946  * and attach a driver.
947  */
948 usbd_status
949 usbd_new_device(device_ptr_t parent, usbd_bus_handle bus, int depth,
950 		int speed, int port, struct usbd_port *up)
951 {
952 	usbd_device_handle dev, adev;
953 	struct usbd_device *hub;
954 	usb_device_descriptor_t *dd;
955 	usb_port_status_t ps;
956 	usbd_status err;
957 	int addr;
958 	int i;
959 	int p;
960 
961 	DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
962 		 bus, port, depth, speed));
963 	addr = usbd_getnewaddr(bus);
964 	if (addr < 0) {
965 		printf("%s: No free USB addresses, new device ignored.\n",
966 		       USBDEVNAME(bus->bdev));
967 		return (USBD_NO_ADDR);
968 	}
969 
970 	dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
971 	if (dev == NULL)
972 		return (USBD_NOMEM);
973 
974 	dev->bus = bus;
975 
976 	/* Set up default endpoint handle. */
977 	dev->def_ep.edesc = &dev->def_ep_desc;
978 
979 	/* Set up default endpoint descriptor. */
980 	dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
981 	dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
982 	dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
983 	dev->def_ep_desc.bmAttributes = UE_CONTROL;
984 	USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
985 	dev->def_ep_desc.bInterval = 0;
986 
987 	dev->quirks = &usbd_no_quirk;
988 	dev->address = USB_START_ADDR;
989 	dev->ddesc.bMaxPacketSize = 0;
990 	dev->depth = depth;
991 	dev->powersrc = up;
992 	dev->myhub = up->parent;
993 
994 	up->device = dev;
995 
996 	/* Locate port on upstream high speed hub */
997 	for (adev = dev, hub = up->parent;
998 	     hub != NULL && hub->speed != USB_SPEED_HIGH;
999 	     adev = hub, hub = hub->myhub)
1000 		;
1001 	if (hub) {
1002 		for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
1003 			if (hub->hub->ports[p].device == adev) {
1004 				dev->myhsport = &hub->hub->ports[p];
1005 				goto found;
1006 			}
1007 		}
1008 		panic("usbd_new_device: cannot find HS port\n");
1009 	found:
1010 		DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
1011 	} else {
1012 		dev->myhsport = NULL;
1013 	}
1014 	dev->speed = speed;
1015 	dev->langid = USBD_NOLANG;
1016 	dev->cookie.cookie = ++usb_cookie_no;
1017 
1018 	/* Establish the default pipe. */
1019 	err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1020 			      &dev->default_pipe);
1021 	if (err) {
1022 		usbd_remove_device(dev, up);
1023 		return (err);
1024 	}
1025 
1026 	/* Set the address.  Do this early; some devices need that. */
1027 	err = usbd_set_address(dev, addr);
1028 	DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
1029 	if (err) {
1030 		DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
1031 		err = USBD_SET_ADDR_FAILED;
1032 		usbd_remove_device(dev, up);
1033 		return (err);
1034 	}
1035 	/* Allow device time to set new address */
1036 	usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1037 	dev->address = addr;	/* New device address now */
1038 	bus->devices[addr] = dev;
1039 
1040 	dd = &dev->ddesc;
1041 	/* Try a few times in case the device is slow (i.e. outside specs.) */
1042 	for (i = 0; i < 10; i++) {
1043 		/* Get the first 8 bytes of the device descriptor. */
1044 		err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1045 		if (!err)
1046 			break;
1047 		usbd_delay_ms(dev, 200);
1048 		if ((i & 3) == 3)
1049 			usbd_reset_port(up->parent, port, &ps);
1050 	}
1051 	if (err) {
1052 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1053 			      "failed\n", addr));
1054 		usbd_remove_device(dev, up);
1055 		return (err);
1056 	}
1057 
1058 	if (speed == USB_SPEED_HIGH) {
1059 		/* Max packet size must be 64 (sec 5.5.3). */
1060 		if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1061 #ifdef DIAGNOSTIC
1062 			printf("usbd_new_device: addr=%d bad max packet size\n",
1063 			       addr);
1064 #endif
1065 			dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1066 		}
1067 	}
1068 
1069 	DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1070 		 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1071 		 addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1072 		 dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1073 		 dev->speed));
1074 
1075 	if (dd->bDescriptorType != UDESC_DEVICE) {
1076 		/* Illegal device descriptor */
1077 		DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1078 			     dd->bDescriptorType));
1079 		usbd_remove_device(dev, up);
1080 		return (USBD_INVAL);
1081 	}
1082 
1083 	if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1084 		DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1085 		usbd_remove_device(dev, up);
1086 		return (USBD_INVAL);
1087 	}
1088 
1089 	USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1090 
1091 	err = usbd_reload_device_desc(dev);
1092 	if (err) {
1093 		DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1094 			      "failed\n", addr));
1095 		usbd_remove_device(dev, up);
1096 		return (err);
1097 	}
1098 
1099 	/* Assume 100mA bus powered for now. Changed when configured. */
1100 	dev->power = USB_MIN_POWER;
1101 	dev->self_powered = 0;
1102 
1103 	DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1104 		 addr, dev, parent));
1105 
1106 	usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1107 
1108 	err = usbd_probe_and_attach(parent, dev, port, addr);
1109 	if (err) {
1110 		usbd_remove_device(dev, up);
1111 		return (err);
1112   	}
1113 
1114   	return (USBD_NORMAL_COMPLETION);
1115 }
1116 
1117 usbd_status
1118 usbd_reload_device_desc(usbd_device_handle dev)
1119 {
1120 	usbd_status err;
1121 
1122 	/* Get the full device descriptor. */
1123 	err = usbd_get_device_desc(dev, &dev->ddesc);
1124 	if (err)
1125 		return (err);
1126 
1127 	/* Figure out what's wrong with this device. */
1128 	dev->quirks = usbd_find_quirk(&dev->ddesc);
1129 
1130 	return (USBD_NORMAL_COMPLETION);
1131 }
1132 
1133 void
1134 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1135 {
1136 	DPRINTF(("usbd_remove_device: %p\n", dev));
1137 
1138 	if (dev->default_pipe != NULL)
1139 		usbd_kill_pipe(dev->default_pipe);
1140 	up->device = NULL;
1141 	dev->bus->devices[dev->address] = NULL;
1142 
1143 	free(dev, M_USB);
1144 }
1145 
1146 #if defined(__NetBSD__) || defined(__OpenBSD__)
1147 int
1148 usbd_print(void *aux, const char *pnp)
1149 {
1150 	struct usb_attach_arg *uaa = aux;
1151 	char devinfo[1024];
1152 
1153 	DPRINTFN(15, ("usbd_print dev=%p\n", uaa->device));
1154 	if (pnp) {
1155 		if (!uaa->usegeneric)
1156 			return (QUIET);
1157 		usbd_devinfo(uaa->device, 1, devinfo, sizeof(devinfo));
1158 		aprint_normal("%s, %s", devinfo, pnp);
1159 	}
1160 	if (uaa->port != 0)
1161 		aprint_normal(" port %d", uaa->port);
1162 	if (uaa->configno != UHUB_UNK_CONFIGURATION)
1163 		aprint_normal(" configuration %d", uaa->configno);
1164 	if (uaa->ifaceno != UHUB_UNK_INTERFACE)
1165 		aprint_normal(" interface %d", uaa->ifaceno);
1166 #if 0
1167 	/*
1168 	 * It gets very crowded with these locators on the attach line.
1169 	 * They are not really needed since they are printed in the clear
1170 	 * by each driver.
1171 	 */
1172 	if (uaa->vendor != UHUB_UNK_VENDOR)
1173 		aprint_normal(" vendor 0x%04x", uaa->vendor);
1174 	if (uaa->product != UHUB_UNK_PRODUCT)
1175 		aprint_normal(" product 0x%04x", uaa->product);
1176 	if (uaa->release != UHUB_UNK_RELEASE)
1177 		aprint_normal(" release 0x%04x", uaa->release);
1178 #endif
1179 	return (UNCONF);
1180 }
1181 
1182 #if defined(__NetBSD__)
1183 int
1184 usbd_submatch(struct device *parent, struct cfdata *cf,
1185 	      const int *ldesc, void *aux)
1186 {
1187 #elif defined(__OpenBSD__)
1188 int
1189 usbd_submatch(struct device *parent, void *match, void *aux)
1190 {
1191 	struct cfdata *cf = match;
1192 #endif
1193 	struct usb_attach_arg *uaa = aux;
1194 
1195 	DPRINTFN(5,("usbd_submatch port=%d,%d configno=%d,%d "
1196 	    "ifaceno=%d,%d vendor=%d,%d product=%d,%d release=%d,%d\n",
1197 	    uaa->port, cf->uhubcf_port,
1198 	    uaa->configno, cf->uhubcf_configuration,
1199 	    uaa->ifaceno, cf->uhubcf_interface,
1200 	    uaa->vendor, cf->uhubcf_vendor,
1201 	    uaa->product, cf->uhubcf_product,
1202 	    uaa->release, cf->uhubcf_release));
1203 	if (uaa->port != 0 &&	/* root hub has port 0, it should match */
1204 	    ((cf->uhubcf_port != UHUB_UNK_PORT &&
1205 	      cf->uhubcf_port != uaa->port) ||
1206 	     (uaa->configno != UHUB_UNK_CONFIGURATION &&
1207 	      cf->uhubcf_configuration != UHUB_UNK_CONFIGURATION &&
1208 	      cf->uhubcf_configuration != uaa->configno) ||
1209 	     (uaa->ifaceno != UHUB_UNK_INTERFACE &&
1210 	      cf->uhubcf_interface != UHUB_UNK_INTERFACE &&
1211 	      cf->uhubcf_interface != uaa->ifaceno) ||
1212 	     (uaa->vendor != UHUB_UNK_VENDOR &&
1213 	      cf->uhubcf_vendor != UHUB_UNK_VENDOR &&
1214 	      cf->uhubcf_vendor != uaa->vendor) ||
1215 	     (uaa->product != UHUB_UNK_PRODUCT &&
1216 	      cf->uhubcf_product != UHUB_UNK_PRODUCT &&
1217 	      cf->uhubcf_product != uaa->product) ||
1218 	     (uaa->release != UHUB_UNK_RELEASE &&
1219 	      cf->uhubcf_release != UHUB_UNK_RELEASE &&
1220 	      cf->uhubcf_release != uaa->release)
1221 	     )
1222 	   )
1223 		return 0;
1224 	return (config_match(parent, cf, aux));
1225 }
1226 
1227 #endif
1228 
1229 void
1230 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1231 		     int usedev)
1232 {
1233 	struct usbd_port *p;
1234 	int i, err, s;
1235 
1236 	di->udi_bus = USBDEVUNIT(dev->bus->bdev);
1237 	di->udi_addr = dev->address;
1238 	di->udi_cookie = dev->cookie;
1239 	usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev);
1240 	usbd_printBCD(di->udi_release, sizeof(di->udi_release),
1241 	    UGETW(dev->ddesc.bcdDevice));
1242 	di->udi_serial[0] = 0;
1243 	if (usedev)
1244 		(void)usbd_get_string(dev, dev->ddesc.iSerialNumber,
1245 				      di->udi_serial);
1246 	di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1247 	di->udi_productNo = UGETW(dev->ddesc.idProduct);
1248 	di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1249 	di->udi_class = dev->ddesc.bDeviceClass;
1250 	di->udi_subclass = dev->ddesc.bDeviceSubClass;
1251 	di->udi_protocol = dev->ddesc.bDeviceProtocol;
1252 	di->udi_config = dev->config;
1253 	di->udi_power = dev->self_powered ? 0 : dev->power;
1254 	di->udi_speed = dev->speed;
1255 
1256 	if (dev->subdevs != NULL) {
1257 		for (i = 0; dev->subdevs[i] &&
1258 			     i < USB_MAX_DEVNAMES; i++) {
1259 			strncpy(di->udi_devnames[i], USBDEVPTRNAME(dev->subdevs[i]),
1260 				USB_MAX_DEVNAMELEN);
1261 			di->udi_devnames[i][USB_MAX_DEVNAMELEN-1] = '\0';
1262                 }
1263         } else {
1264                 i = 0;
1265         }
1266         for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1267                 di->udi_devnames[i][0] = 0;                 /* empty */
1268 
1269 	if (dev->hub) {
1270 		for (i = 0;
1271 		     i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1272 			     i < dev->hub->hubdesc.bNbrPorts;
1273 		     i++) {
1274 			p = &dev->hub->ports[i];
1275 			if (p->device)
1276 				err = p->device->address;
1277 			else {
1278 				s = UGETW(p->status.wPortStatus);
1279 				if (s & UPS_PORT_ENABLED)
1280 					err = USB_PORT_ENABLED;
1281 				else if (s & UPS_SUSPEND)
1282 					err = USB_PORT_SUSPENDED;
1283 				else if (s & UPS_PORT_POWER)
1284 					err = USB_PORT_POWERED;
1285 				else
1286 					err = USB_PORT_DISABLED;
1287 			}
1288 			di->udi_ports[i] = err;
1289 		}
1290 		di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1291 	} else
1292 		di->udi_nports = 0;
1293 }
1294 
1295 void
1296 usb_free_device(usbd_device_handle dev)
1297 {
1298 	int ifcidx, nifc;
1299 
1300 	if (dev->default_pipe != NULL)
1301 		usbd_kill_pipe(dev->default_pipe);
1302 	if (dev->ifaces != NULL) {
1303 		nifc = dev->cdesc->bNumInterface;
1304 		for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1305 			usbd_free_iface_data(dev, ifcidx);
1306 		free(dev->ifaces, M_USB);
1307 	}
1308 	if (dev->cdesc != NULL)
1309 		free(dev->cdesc, M_USB);
1310 	if (dev->subdevs != NULL)
1311 		free(dev->subdevs, M_USB);
1312 	free(dev, M_USB);
1313 }
1314 
1315 /*
1316  * The general mechanism for detaching drivers works as follows: Each
1317  * driver is responsible for maintaining a reference count on the
1318  * number of outstanding references to its softc (e.g.  from
1319  * processing hanging in a read or write).  The detach method of the
1320  * driver decrements this counter and flags in the softc that the
1321  * driver is dying and then wakes any sleepers.  It then sleeps on the
1322  * softc.  Each place that can sleep must maintain the reference
1323  * count.  When the reference count drops to -1 (0 is the normal value
1324  * of the reference count) the a wakeup on the softc is performed
1325  * signaling to the detach waiter that all references are gone.
1326  */
1327 
1328 /*
1329  * Called from process context when we discover that a port has
1330  * been disconnected.
1331  */
1332 void
1333 usb_disconnect_port(struct usbd_port *up, device_ptr_t parent)
1334 {
1335 	usbd_device_handle dev = up->device;
1336 	char *hubname = USBDEVPTRNAME(parent);
1337 	int i;
1338 
1339 	DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1340 		    up, dev, up->portno));
1341 
1342 #ifdef DIAGNOSTIC
1343 	if (dev == NULL) {
1344 		printf("usb_disconnect_port: no device\n");
1345 		return;
1346 	}
1347 #endif
1348 
1349 	if (dev->subdevs != NULL) {
1350 		DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1351 		for (i = 0; dev->subdevs[i]; i++) {
1352 			printf("%s: at %s", USBDEVPTRNAME(dev->subdevs[i]),
1353 			       hubname);
1354 			if (up->portno != 0)
1355 				printf(" port %d", up->portno);
1356 			printf(" (addr %d) disconnected\n", dev->address);
1357 			config_detach(dev->subdevs[i], DETACH_FORCE);
1358 			dev->subdevs[i] = 0;
1359 		}
1360 	}
1361 
1362 	usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1363 	dev->bus->devices[dev->address] = NULL;
1364 	up->device = NULL;
1365 	usb_free_device(dev);
1366 }
1367 
1368 #ifdef __OpenBSD__
1369 void *usb_realloc(void *p, u_int size, int pool, int flags)
1370 {
1371 	void *q;
1372 
1373 	q = malloc(size, pool, flags);
1374 	if (q == NULL)
1375 		return (NULL);
1376 	bcopy(p, q, size);
1377 	free(p, pool);
1378 	return (q);
1379 }
1380 #endif
1381