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