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