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