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