]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/usb_subr.c
This commit was generated by cvs2svn to compensate for changes in r170331,
[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
853         /* First try with device specific drivers. */
854         DPRINTF(("usbd_probe_and_attach: trying device specific drivers\n"));
855
856         dev->ifacenums = NULL;
857         dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
858         if (dev->subdevs == NULL) {
859                 free(devinfo, M_USB);
860                 return (USBD_NOMEM);
861         }
862         dev->subdevs[0] = bdev;
863         dev->subdevs[1] = 0;
864         *uaap = uaa;
865         usbd_devinfo(dev, 1, devinfo);
866         device_set_desc_copy(bdev, devinfo);
867         dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
868         if (dv) {
869                 free(devinfo, M_USB);
870                 return (USBD_NORMAL_COMPLETION);
871         }
872         /*
873          * Free subdevs so we can reallocate it larger for the number of
874          * interfaces 
875          */
876         tmpdv = dev->subdevs;
877         dev->subdevs = NULL;
878         free(tmpdv, M_USB);
879         DPRINTF(("usbd_probe_and_attach: no device specific driver found\n"));
880
881         DPRINTF(("usbd_probe_and_attach: looping over %d configurations\n",
882                  dd->bNumConfigurations));
883         /* Next try with interface drivers. */
884         for (confi = 0; confi < dd->bNumConfigurations; confi++) {
885                 DPRINTFN(1,("usbd_probe_and_attach: trying config idx=%d\n",
886                             confi));
887                 err = usbd_set_config_index(dev, confi, 1);
888                 if (err) {
889 #ifdef USB_DEBUG
890                         DPRINTF(("%s: port %d, set config at addr %d failed, "
891                                  "error=%s\n", device_get_nameunit(parent), port,
892                                  addr, usbd_errstr(err)));
893 #else
894                         printf("%s: port %d, set config at addr %d failed\n",
895                                device_get_nameunit(parent), port, addr);
896 #endif
897                         free(devinfo, M_USB);
898                         return (err);
899                 }
900                 nifaces = dev->cdesc->bNumInterface;
901                 uaa.configno = dev->cdesc->bConfigurationValue;
902                 for (i = 0; i < nifaces; i++)
903                         ifaces[i] = &dev->ifaces[i];
904                 uaa.ifaces = ifaces;
905                 uaa.nifaces = nifaces;
906                 dev->subdevs = malloc((nifaces+1) * sizeof dv, M_USB,M_NOWAIT);
907                 if (dev->subdevs == NULL) {
908                         free(devinfo, M_USB);
909                         return (USBD_NOMEM);
910                 }
911                 dev->ifacenums = malloc((nifaces) * sizeof(*dev->ifacenums),
912                     M_USB,M_NOWAIT);
913                 if (dev->ifacenums == NULL) {
914                         free(devinfo, M_USB);
915                         return (USBD_NOMEM);
916                 }
917
918                 found = 0;
919                 for (i = 0; i < nifaces; i++) {
920                         if (ifaces[i] == NULL)
921                                 continue; /* interface already claimed */
922                         uaa.iface = ifaces[i];
923                         uaa.ifaceno = ifaces[i]->idesc->bInterfaceNumber;
924                         dev->subdevs[found] = bdev;
925                         dev->subdevs[found + 1] = 0;
926                         dev->ifacenums[found] = i;
927                         *uaap = uaa;
928                         usbd_devinfo(dev, 1, devinfo);
929                         device_set_desc_copy(bdev, devinfo);
930                         dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print,
931                                            usbd_submatch);
932                         if (dv != NULL) {
933                                 ifaces[i] = 0; /* consumed */
934                                 found++;
935                                 /* create another child for the next iface */
936                                 bdev = device_add_child(parent, NULL, -1);
937                                 if (!bdev) {
938                                         device_printf(parent,
939                                             "Device add failed\n");
940                                         free(devinfo, M_USB);
941                                         return (USBD_NORMAL_COMPLETION);
942                                 }
943                                 uaap = malloc(sizeof(uaa), M_USB, M_NOWAIT);
944                                 if (uaap == NULL) {
945                                         free(devinfo, M_USB);
946                                         return (USBD_NOMEM);
947                                 }
948                                 device_set_ivars(bdev, uaap);
949                         } else {
950                                 dev->subdevs[found] = 0;
951                         }
952                 }
953                 if (found != 0) {
954                         /* remove the last created child.  It is unused */
955                         free(uaap, M_USB);
956                         free(devinfo, M_USB);
957                         device_delete_child(parent, bdev);
958                         /* free(uaap, M_USB); */ /* May be needed? xxx */
959                         return (USBD_NORMAL_COMPLETION);
960                 }
961                 tmpdv = dev->subdevs;
962                 dev->subdevs = NULL;
963                 free(tmpdv, M_USB);
964                 free(dev->ifacenums, M_USB);
965                 dev->ifacenums = NULL;
966         }
967         /* No interfaces were attached in any of the configurations. */
968
969         if (dd->bNumConfigurations > 1) /* don't change if only 1 config */
970                 usbd_set_config_index(dev, 0, 0);
971
972         DPRINTF(("usbd_probe_and_attach: no interface drivers found\n"));
973
974         /* Finally try the generic driver. */
975         uaa.iface = NULL;
976         uaa.usegeneric = 1;
977         uaa.configno = UHUB_UNK_CONFIGURATION;
978         uaa.ifaceno = UHUB_UNK_INTERFACE;
979         dev->subdevs = malloc(2 * sizeof dv, M_USB, M_NOWAIT);
980         if (dev->subdevs == 0) {
981                 free(devinfo, M_USB);
982                 return (USBD_NOMEM);
983         }
984         dev->subdevs[0] = bdev;
985         dev->subdevs[1] = 0;
986         *uaap = uaa;
987         usbd_devinfo(dev, 1, devinfo);
988         device_set_desc_copy(bdev, devinfo);
989         free(devinfo, M_USB);
990         dv = USB_DO_ATTACH(dev, bdev, parent, &uaa, usbd_print, usbd_submatch);
991         if (dv != NULL)
992                 return (USBD_NORMAL_COMPLETION);
993
994         /*
995          * The generic attach failed, but leave the device as it is.
996          * We just did not find any drivers, that's all.  The device is
997          * fully operational and not harming anyone.
998          */
999         DPRINTF(("usbd_probe_and_attach: generic attach failed\n"));
1000         return (USBD_NORMAL_COMPLETION);
1001 }
1002
1003
1004 /*
1005  * Called when a new device has been put in the powered state,
1006  * but not yet in the addressed state.
1007  * Get initial descriptor, set the address, get full descriptor,
1008  * and attach a driver.
1009  */
1010 usbd_status
1011 usbd_new_device(device_t parent, usbd_bus_handle bus, int depth,
1012                 int speed, int port, struct usbd_port *up)
1013 {
1014         usbd_device_handle dev, adev;
1015         struct usbd_device *hub;
1016         usb_device_descriptor_t *dd;
1017         usb_port_status_t ps;
1018         usbd_status err;
1019         int addr;
1020         int i;
1021         int p;
1022
1023         DPRINTF(("usbd_new_device bus=%p port=%d depth=%d speed=%d\n",
1024                  bus, port, depth, speed));
1025         addr = usbd_getnewaddr(bus);
1026         if (addr < 0) {
1027                 printf("%s: No free USB addresses, new device ignored.\n",
1028                        device_get_nameunit(bus->bdev));
1029                 return (USBD_NO_ADDR);
1030         }
1031
1032         dev = malloc(sizeof *dev, M_USB, M_NOWAIT|M_ZERO);
1033         if (dev == NULL)
1034                 return (USBD_NOMEM);
1035
1036         dev->bus = bus;
1037
1038         /* Set up default endpoint handle. */
1039         dev->def_ep.edesc = &dev->def_ep_desc;
1040
1041         /* Set up default endpoint descriptor. */
1042         dev->def_ep_desc.bLength = USB_ENDPOINT_DESCRIPTOR_SIZE;
1043         dev->def_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1044         dev->def_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1045         dev->def_ep_desc.bmAttributes = UE_CONTROL;
1046         USETW(dev->def_ep_desc.wMaxPacketSize, USB_MAX_IPACKET);
1047         dev->def_ep_desc.bInterval = 0;
1048
1049         dev->quirks = &usbd_no_quirk;
1050         dev->address = USB_START_ADDR;
1051         dev->ddesc.bMaxPacketSize = 0;
1052         dev->depth = depth;
1053         dev->powersrc = up;
1054         dev->myhub = up->parent;
1055
1056         up->device = dev;
1057
1058         /* Locate port on upstream high speed hub */
1059         for (adev = dev, hub = up->parent;
1060              hub != NULL && hub->speed != USB_SPEED_HIGH;
1061              adev = hub, hub = hub->myhub)
1062                 ;
1063         if (hub) {
1064                 for (p = 0; p < hub->hub->hubdesc.bNbrPorts; p++) {
1065                         if (hub->hub->ports[p].device == adev) {
1066                                 dev->myhsport = &hub->hub->ports[p];
1067                                 goto found;
1068                         }
1069                 }
1070                 panic("usbd_new_device: cannot find HS port\n");
1071         found:
1072                 DPRINTFN(1,("usbd_new_device: high speed port %d\n", p));
1073         } else {
1074                 dev->myhsport = NULL;
1075         }
1076         dev->speed = speed;
1077         dev->langid = USBD_NOLANG;
1078         dev->cookie.cookie = ++usb_cookie_no;
1079
1080         /* Establish the default pipe. */
1081         err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1082                               &dev->default_pipe);
1083         if (err) {
1084                 usbd_remove_device(dev, up);
1085                 return (err);
1086         }
1087
1088         dd = &dev->ddesc;
1089         /* Try a few times in case the device is slow (i.e. outside specs.) */
1090         DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
1091         for (i = 0; i < 15; i++) {
1092                 /* Get the first 8 bytes of the device descriptor. */
1093                 err = usbd_get_desc(dev, UDESC_DEVICE, 0, USB_MAX_IPACKET, dd);
1094                 if (!err)
1095                         break;
1096                 usbd_delay_ms(dev, 200);
1097                 if ((i & 3) == 3) {
1098                         DPRINTFN(-1,("usb_new_device: set address %d "
1099                             "failed - trying a port reset\n", addr));
1100                         usbd_reset_port(up->parent, port, &ps);
1101                 }
1102
1103         }
1104         if (err) {
1105                 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting first desc "
1106                               "failed\n", addr));
1107                 usbd_remove_device(dev, up);
1108                 return (err);
1109         }
1110
1111         if (speed == USB_SPEED_HIGH) {
1112                 /* Max packet size must be 64 (sec 5.5.3). */
1113                 if (dd->bMaxPacketSize != USB_2_MAX_CTRL_PACKET) {
1114 #ifdef DIAGNOSTIC
1115                         printf("usbd_new_device: addr=%d bad max packet size\n",
1116                                addr);
1117 #endif
1118                         dd->bMaxPacketSize = USB_2_MAX_CTRL_PACKET;
1119                 }
1120         }
1121
1122         DPRINTF(("usbd_new_device: adding unit addr=%d, rev=%02x, class=%d, "
1123                  "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1124                  addr,UGETW(dd->bcdUSB), dd->bDeviceClass, dd->bDeviceSubClass,
1125                  dd->bDeviceProtocol, dd->bMaxPacketSize, dd->bLength,
1126                  dev->speed));
1127
1128         if (dd->bDescriptorType != UDESC_DEVICE) {
1129                 /* Illegal device descriptor */
1130                 DPRINTFN(-1,("usbd_new_device: illegal descriptor %d\n",
1131                              dd->bDescriptorType));
1132                 usbd_remove_device(dev, up);
1133                 return (USBD_INVAL);
1134         }
1135
1136         if (dd->bLength < USB_DEVICE_DESCRIPTOR_SIZE) {
1137                 DPRINTFN(-1,("usbd_new_device: bad length %d\n", dd->bLength));
1138                 usbd_remove_device(dev, up);
1139                 return (USBD_INVAL);
1140         }
1141
1142         USETW(dev->def_ep_desc.wMaxPacketSize, dd->bMaxPacketSize);
1143
1144         /* Re-establish the default pipe with the new max packet size. */
1145         usbd_kill_pipe(dev->default_pipe);
1146         err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1147             &dev->default_pipe);
1148         if (err) {
1149                 usbd_remove_device(dev, up);
1150                 return (err);
1151         }
1152
1153         err = usbd_reload_device_desc(dev);
1154         if (err) {
1155                 DPRINTFN(-1, ("usbd_new_device: addr=%d, getting full desc "
1156                               "failed\n", addr));
1157                 usbd_remove_device(dev, up);
1158                 return (err);
1159         }
1160
1161         /* Set the address */
1162         DPRINTFN(5,("usbd_new_device: setting device address=%d\n", addr));
1163         err = usbd_set_address(dev, addr);
1164         if (err) {
1165                 DPRINTFN(-1,("usb_new_device: set address %d failed\n", addr));
1166                 err = USBD_SET_ADDR_FAILED;
1167                 usbd_remove_device(dev, up);
1168                 return (err);
1169         }
1170
1171         /* Allow device time to set new address */
1172         usbd_delay_ms(dev, USB_SET_ADDRESS_SETTLE);
1173         dev->address = addr;    /* New device address now */
1174         bus->devices[addr] = dev;
1175
1176         /* Re-establish the default pipe with the new address. */
1177         usbd_kill_pipe(dev->default_pipe);
1178         err = usbd_setup_pipe(dev, 0, &dev->def_ep, USBD_DEFAULT_INTERVAL,
1179             &dev->default_pipe);
1180         if (err) {
1181                 usbd_remove_device(dev, up);
1182                 return (err);
1183         }
1184
1185         /* Assume 100mA bus powered for now. Changed when configured. */
1186         dev->power = USB_MIN_POWER;
1187         dev->self_powered = 0;
1188
1189         DPRINTF(("usbd_new_device: new dev (addr %d), dev=%p, parent=%p\n",
1190                  addr, dev, parent));
1191
1192         err = usbd_probe_and_attach(parent, dev, port, addr);
1193         if (err) {
1194                 usbd_remove_device(dev, up);
1195                 return (err);
1196         }
1197
1198         usbd_add_dev_event(USB_EVENT_DEVICE_ATTACH, dev);
1199
1200         return (USBD_NORMAL_COMPLETION);
1201 }
1202
1203 usbd_status
1204 usbd_reload_device_desc(usbd_device_handle dev)
1205 {
1206         usbd_status err;
1207         int i;
1208
1209         /* Get the full device descriptor. */
1210         for (i = 0; i < 3; ++i) {
1211                 err = usbd_get_device_desc(dev, &dev->ddesc);
1212                 if (!err)
1213                         break;
1214                 usbd_delay_ms(dev, 200);
1215         }
1216         if (err)
1217                 return (err);
1218
1219         /* Figure out what's wrong with this device. */
1220         dev->quirks = usbd_find_quirk(&dev->ddesc);
1221
1222         return (USBD_NORMAL_COMPLETION);
1223 }
1224
1225 void
1226 usbd_remove_device(usbd_device_handle dev, struct usbd_port *up)
1227 {
1228         DPRINTF(("usbd_remove_device: %p\n", dev));
1229
1230         if (dev->default_pipe != NULL)
1231                 usbd_kill_pipe(dev->default_pipe);
1232         up->device = NULL;
1233         dev->bus->devices[dev->address] = NULL;
1234
1235         free(dev, M_USB);
1236 }
1237
1238 void
1239 usbd_fill_deviceinfo(usbd_device_handle dev, struct usb_device_info *di,
1240                      int usedev)
1241 {
1242         struct usbd_port *p;
1243         int i, err, s;
1244
1245         di->udi_bus = device_get_unit(dev->bus->bdev);
1246         di->udi_addr = dev->address;
1247         di->udi_cookie = dev->cookie;
1248         usbd_devinfo_vp(dev, di->udi_vendor, di->udi_product, usedev);
1249         usbd_printBCD(di->udi_release, UGETW(dev->ddesc.bcdDevice));
1250         di->udi_vendorNo = UGETW(dev->ddesc.idVendor);
1251         di->udi_productNo = UGETW(dev->ddesc.idProduct);
1252         di->udi_releaseNo = UGETW(dev->ddesc.bcdDevice);
1253         di->udi_class = dev->ddesc.bDeviceClass;
1254         di->udi_subclass = dev->ddesc.bDeviceSubClass;
1255         di->udi_protocol = dev->ddesc.bDeviceProtocol;
1256         di->udi_config = dev->config;
1257         di->udi_power = dev->self_powered ? 0 : dev->power;
1258         di->udi_speed = dev->speed;
1259
1260         if (dev->subdevs != NULL) {
1261                 for (i = 0; dev->subdevs[i] && i < USB_MAX_DEVNAMES; i++) {
1262                         if (device_is_attached(dev->subdevs[i]))
1263                                 strlcpy(di->udi_devnames[i],
1264                                     device_get_nameunit(dev->subdevs[i]),
1265                                     USB_MAX_DEVNAMELEN);
1266                         else
1267                                 di->udi_devnames[i][0] = 0;
1268                 }
1269         } else {
1270                 i = 0;
1271         }
1272         for (/*i is set */; i < USB_MAX_DEVNAMES; i++)
1273                 di->udi_devnames[i][0] = 0;                 /* empty */
1274
1275         if (dev->hub) {
1276                 for (i = 0;
1277                      i < sizeof(di->udi_ports) / sizeof(di->udi_ports[0]) &&
1278                              i < dev->hub->hubdesc.bNbrPorts;
1279                      i++) {
1280                         p = &dev->hub->ports[i];
1281                         if (p->device)
1282                                 err = p->device->address;
1283                         else {
1284                                 s = UGETW(p->status.wPortStatus);
1285                                 if (s & UPS_PORT_ENABLED)
1286                                         err = USB_PORT_ENABLED;
1287                                 else if (s & UPS_SUSPEND)
1288                                         err = USB_PORT_SUSPENDED;
1289                                 else if (s & UPS_PORT_POWER)
1290                                         err = USB_PORT_POWERED;
1291                                 else
1292                                         err = USB_PORT_DISABLED;
1293                         }
1294                         di->udi_ports[i] = err;
1295                 }
1296                 di->udi_nports = dev->hub->hubdesc.bNbrPorts;
1297         } else
1298                 di->udi_nports = 0;
1299 }
1300
1301 void
1302 usb_free_device(usbd_device_handle dev)
1303 {
1304         int ifcidx, nifc;
1305
1306         if (dev->default_pipe != NULL)
1307                 usbd_kill_pipe(dev->default_pipe);
1308         if (dev->ifaces != NULL) {
1309                 nifc = dev->cdesc->bNumInterface;
1310                 for (ifcidx = 0; ifcidx < nifc; ifcidx++)
1311                         usbd_free_iface_data(dev, ifcidx);
1312                 free(dev->ifaces, M_USB);
1313         }
1314         if (dev->cdesc != NULL)
1315                 free(dev->cdesc, M_USB);
1316         if (dev->subdevs != NULL)
1317                 free(dev->subdevs, M_USB);
1318         if (dev->ifacenums != NULL)
1319                 free(dev->ifacenums, M_USB);
1320         free(dev, M_USB);
1321 }
1322
1323 /*
1324  * The general mechanism for detaching drivers works as follows: Each
1325  * driver is responsible for maintaining a reference count on the
1326  * number of outstanding references to its softc (e.g.  from
1327  * processing hanging in a read or write).  The detach method of the
1328  * driver decrements this counter and flags in the softc that the
1329  * driver is dying and then wakes any sleepers.  It then sleeps on the
1330  * softc.  Each place that can sleep must maintain the reference
1331  * count.  When the reference count drops to -1 (0 is the normal value
1332  * of the reference count) the a wakeup on the softc is performed
1333  * signaling to the detach waiter that all references are gone.
1334  */
1335
1336 /*
1337  * Called from process context when we discover that a port has
1338  * been disconnected.
1339  */
1340 void
1341 usb_disconnect_port(struct usbd_port *up, device_t parent)
1342 {
1343         usbd_device_handle dev = up->device;
1344         const char *hubname = device_get_nameunit(parent);
1345         int i;
1346
1347         DPRINTFN(3,("uhub_disconnect: up=%p dev=%p port=%d\n",
1348                     up, dev, up->portno));
1349
1350 #ifdef DIAGNOSTIC
1351         if (dev == NULL) {
1352                 printf("usb_disconnect_port: no device\n");
1353                 return;
1354         }
1355 #endif
1356
1357         if (dev->subdevs != NULL) {
1358                 DPRINTFN(3,("usb_disconnect_port: disconnect subdevs\n"));
1359                 for (i = 0; dev->subdevs[i]; i++) {
1360                         printf("%s: at %s", device_get_nameunit(dev->subdevs[i]),
1361                                hubname);
1362                         if (up->portno != 0)
1363                                 printf(" port %d", up->portno);
1364                         printf(" (addr %d) disconnected\n", dev->address);
1365                         config_detach(dev->subdevs[i], DETACH_FORCE);
1366                         dev->subdevs[i] = NULL;
1367                 }
1368         }
1369
1370         usbd_add_dev_event(USB_EVENT_DEVICE_DETACH, dev);
1371         dev->bus->devices[dev->address] = NULL;
1372         up->device = NULL;
1373         usb_free_device(dev);
1374 }