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