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