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