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