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