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