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