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