]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/dev/usb/usb_device.c
MFC r197558
[FreeBSD/stable/8.git] / sys / dev / usb / usb_device.c
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/stdint.h>
28 #include <sys/stddef.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/types.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/bus.h>
35 #include <sys/linker_set.h>
36 #include <sys/module.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/condvar.h>
40 #include <sys/sysctl.h>
41 #include <sys/sx.h>
42 #include <sys/unistd.h>
43 #include <sys/callout.h>
44 #include <sys/malloc.h>
45 #include <sys/priv.h>
46 #include <sys/conf.h>
47 #include <sys/fcntl.h>
48
49 #include <dev/usb/usb.h>
50 #include <dev/usb/usbdi.h>
51 #include <dev/usb/usbdi_util.h>
52 #include <dev/usb/usb_ioctl.h>
53 #include "usbdevs.h"
54
55 #define USB_DEBUG_VAR usb_debug
56
57 #include <dev/usb/usb_core.h>
58 #include <dev/usb/usb_debug.h>
59 #include <dev/usb/usb_process.h>
60 #include <dev/usb/usb_device.h>
61 #include <dev/usb/usb_busdma.h>
62 #include <dev/usb/usb_transfer.h>
63 #include <dev/usb/usb_request.h>
64 #include <dev/usb/usb_dynamic.h>
65 #include <dev/usb/usb_hub.h>
66 #include <dev/usb/usb_util.h>
67 #include <dev/usb/usb_msctest.h>
68 #if USB_HAVE_UGEN
69 #include <dev/usb/usb_dev.h>
70 #include <dev/usb/usb_generic.h>
71 #endif
72
73 #include <dev/usb/quirk/usb_quirk.h>
74
75 #include <dev/usb/usb_controller.h>
76 #include <dev/usb/usb_bus.h>
77
78 /* function prototypes  */
79
80 static void     usb_init_endpoint(struct usb_device *, uint8_t,
81                     struct usb_endpoint_descriptor *, struct usb_endpoint *);
82 static void     usb_unconfigure(struct usb_device *, uint8_t);
83 static void     usb_detach_device(struct usb_device *, uint8_t, uint8_t);
84 static void     usb_detach_device_sub(struct usb_device *, device_t *,
85                     uint8_t);
86 static uint8_t  usb_probe_and_attach_sub(struct usb_device *,
87                     struct usb_attach_arg *);
88 static void     usb_init_attach_arg(struct usb_device *,
89                     struct usb_attach_arg *);
90 static void     usb_suspend_resume_sub(struct usb_device *, device_t,
91                     uint8_t);
92 static void     usbd_clear_stall_proc(struct usb_proc_msg *_pm);
93 usb_error_t     usb_config_parse(struct usb_device *, uint8_t, uint8_t);
94 static void     usbd_set_device_strings(struct usb_device *);
95 #if USB_HAVE_UGEN
96 static void     usb_notify_addq(const char *type, struct usb_device *);
97 static void     usb_fifo_free_wrap(struct usb_device *, uint8_t, uint8_t);
98 static struct cdev *usb_make_dev(struct usb_device *, int, int);
99 static void     usb_cdev_create(struct usb_device *);
100 static void     usb_cdev_free(struct usb_device *);
101 static void     usb_cdev_cleanup(void *);
102 #endif
103
104 /* This variable is global to allow easy access to it: */
105
106 int     usb_template = 0;
107
108 SYSCTL_INT(_hw_usb, OID_AUTO, template, CTLFLAG_RW,
109     &usb_template, 0, "Selected USB device side template");
110
111 static const char* statestr[USB_STATE_MAX] = {
112         [USB_STATE_DETACHED]    = "DETACHED",
113         [USB_STATE_ATTACHED]    = "ATTACHED",
114         [USB_STATE_POWERED]     = "POWERED",
115         [USB_STATE_ADDRESSED]   = "ADDRESSED",
116         [USB_STATE_CONFIGURED]  = "CONFIGURED",
117 };
118
119 const char *
120 usb_statestr(enum usb_dev_state state)
121 {
122         return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
123 }
124
125 /*------------------------------------------------------------------------*
126  *      usbd_get_ep_by_addr
127  *
128  * This function searches for an USB ep by endpoint address and
129  * direction.
130  *
131  * Returns:
132  * NULL: Failure
133  * Else: Success
134  *------------------------------------------------------------------------*/
135 struct usb_endpoint *
136 usbd_get_ep_by_addr(struct usb_device *udev, uint8_t ea_val)
137 {
138         struct usb_endpoint *ep = udev->endpoints;
139         struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
140         enum {
141                 EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
142         };
143
144         /*
145          * According to the USB specification not all bits are used
146          * for the endpoint address. Keep defined bits only:
147          */
148         ea_val &= EA_MASK;
149
150         /*
151          * Iterate accross all the USB endpoints searching for a match
152          * based on the endpoint address:
153          */
154         for (; ep != ep_end; ep++) {
155
156                 if (ep->edesc == NULL) {
157                         continue;
158                 }
159                 /* do the mask and check the value */
160                 if ((ep->edesc->bEndpointAddress & EA_MASK) == ea_val) {
161                         goto found;
162                 }
163         }
164
165         /*
166          * The default endpoint is always present and is checked separately:
167          */
168         if ((udev->default_ep.edesc) &&
169             ((udev->default_ep.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
170                 ep = &udev->default_ep;
171                 goto found;
172         }
173         return (NULL);
174
175 found:
176         return (ep);
177 }
178
179 /*------------------------------------------------------------------------*
180  *      usbd_get_endpoint
181  *
182  * This function searches for an USB endpoint based on the information
183  * given by the passed "struct usb_config" pointer.
184  *
185  * Return values:
186  * NULL: No match.
187  * Else: Pointer to "struct usb_endpoint".
188  *------------------------------------------------------------------------*/
189 struct usb_endpoint *
190 usbd_get_endpoint(struct usb_device *udev, uint8_t iface_index,
191     const struct usb_config *setup)
192 {
193         struct usb_endpoint *ep = udev->endpoints;
194         struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
195         uint8_t index = setup->ep_index;
196         uint8_t ea_mask;
197         uint8_t ea_val;
198         uint8_t type_mask;
199         uint8_t type_val;
200
201         DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
202             "type=0x%x dir=0x%x index=%d\n",
203             udev, iface_index, setup->endpoint,
204             setup->type, setup->direction, setup->ep_index);
205
206         /* check USB mode */
207
208         if (setup->usb_mode != USB_MODE_DUAL &&
209             udev->flags.usb_mode != setup->usb_mode) {
210                 /* wrong mode - no endpoint */
211                 return (NULL);
212         }
213
214         /* setup expected endpoint direction mask and value */
215
216         if (setup->direction == UE_DIR_RX) {
217                 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
218                 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
219                     UE_DIR_OUT : UE_DIR_IN;
220         } else if (setup->direction == UE_DIR_TX) {
221                 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
222                 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
223                     UE_DIR_IN : UE_DIR_OUT;
224         } else if (setup->direction == UE_DIR_ANY) {
225                 /* match any endpoint direction */
226                 ea_mask = 0;
227                 ea_val = 0;
228         } else {
229                 /* match the given endpoint direction */
230                 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
231                 ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
232         }
233
234         /* setup expected endpoint address */
235
236         if (setup->endpoint == UE_ADDR_ANY) {
237                 /* match any endpoint address */
238         } else {
239                 /* match the given endpoint address */
240                 ea_mask |= UE_ADDR;
241                 ea_val |= (setup->endpoint & UE_ADDR);
242         }
243
244         /* setup expected endpoint type */
245
246         if (setup->type == UE_BULK_INTR) {
247                 /* this will match BULK and INTERRUPT endpoints */
248                 type_mask = 2;
249                 type_val = 2;
250         } else if (setup->type == UE_TYPE_ANY) {
251                 /* match any endpoint type */
252                 type_mask = 0;
253                 type_val = 0;
254         } else {
255                 /* match the given endpoint type */
256                 type_mask = UE_XFERTYPE;
257                 type_val = (setup->type & UE_XFERTYPE);
258         }
259
260         /*
261          * Iterate accross all the USB endpoints searching for a match
262          * based on the endpoint address. Note that we are searching
263          * the endpoints from the beginning of the "udev->endpoints" array.
264          */
265         for (; ep != ep_end; ep++) {
266
267                 if ((ep->edesc == NULL) ||
268                     (ep->iface_index != iface_index)) {
269                         continue;
270                 }
271                 /* do the masks and check the values */
272
273                 if (((ep->edesc->bEndpointAddress & ea_mask) == ea_val) &&
274                     ((ep->edesc->bmAttributes & type_mask) == type_val)) {
275                         if (!index--) {
276                                 goto found;
277                         }
278                 }
279         }
280
281         /*
282          * Match against default endpoint last, so that "any endpoint", "any
283          * address" and "any direction" returns the first endpoint of the
284          * interface. "iface_index" and "direction" is ignored:
285          */
286         if ((udev->default_ep.edesc) &&
287             ((udev->default_ep.edesc->bEndpointAddress & ea_mask) == ea_val) &&
288             ((udev->default_ep.edesc->bmAttributes & type_mask) == type_val) &&
289             (!index)) {
290                 ep = &udev->default_ep;
291                 goto found;
292         }
293         return (NULL);
294
295 found:
296         return (ep);
297 }
298
299 /*------------------------------------------------------------------------*
300  *      usbd_interface_count
301  *
302  * This function stores the number of USB interfaces excluding
303  * alternate settings, which the USB config descriptor reports into
304  * the unsigned 8-bit integer pointed to by "count".
305  *
306  * Returns:
307  *    0: Success
308  * Else: Failure
309  *------------------------------------------------------------------------*/
310 usb_error_t
311 usbd_interface_count(struct usb_device *udev, uint8_t *count)
312 {
313         if (udev->cdesc == NULL) {
314                 *count = 0;
315                 return (USB_ERR_NOT_CONFIGURED);
316         }
317         *count = udev->ifaces_max;
318         return (USB_ERR_NORMAL_COMPLETION);
319 }
320
321
322 /*------------------------------------------------------------------------*
323  *      usb_init_endpoint
324  *
325  * This function will initialise the USB endpoint structure pointed to by
326  * the "endpoint" argument. The structure pointed to by "endpoint" must be
327  * zeroed before calling this function.
328  *------------------------------------------------------------------------*/
329 static void
330 usb_init_endpoint(struct usb_device *udev, uint8_t iface_index,
331     struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep)
332 {
333         struct usb_bus_methods *methods;
334
335         methods = udev->bus->methods;
336
337         (methods->endpoint_init) (udev, edesc, ep);
338
339         /* initialise USB endpoint structure */
340         ep->edesc = edesc;
341         ep->iface_index = iface_index;
342         TAILQ_INIT(&ep->endpoint_q.head);
343         ep->endpoint_q.command = &usbd_pipe_start;
344
345         /* the pipe is not supported by the hardware */
346         if (ep->methods == NULL)
347                 return;
348
349         /* clear stall, if any */
350         if (methods->clear_stall != NULL) {
351                 USB_BUS_LOCK(udev->bus);
352                 (methods->clear_stall) (udev, ep);
353                 USB_BUS_UNLOCK(udev->bus);
354         }
355 }
356
357 /*-----------------------------------------------------------------------*
358  *      usb_endpoint_foreach
359  *
360  * This function will iterate all the USB endpoints except the control
361  * endpoint. This function is NULL safe.
362  *
363  * Return values:
364  * NULL: End of USB endpoints
365  * Else: Pointer to next USB endpoint
366  *------------------------------------------------------------------------*/
367 struct usb_endpoint *
368 usb_endpoint_foreach(struct usb_device *udev, struct usb_endpoint *ep)
369 {
370         struct usb_endpoint *ep_end;
371
372         /* be NULL safe */
373         if (udev == NULL)
374                 return (NULL);
375
376         ep_end = udev->endpoints + udev->endpoints_max;
377
378         /* get next endpoint */
379         if (ep == NULL)
380                 ep = udev->endpoints;
381         else
382                 ep++;
383
384         /* find next allocated ep */
385         while (ep != ep_end) {
386                 if (ep->edesc != NULL)
387                         return (ep);
388                 ep++;
389         }
390         return (NULL);
391 }
392
393 /*------------------------------------------------------------------------*
394  *      usb_unconfigure
395  *
396  * This function will free all USB interfaces and USB endpoints belonging
397  * to an USB device.
398  *
399  * Flag values, see "USB_UNCFG_FLAG_XXX".
400  *------------------------------------------------------------------------*/
401 static void
402 usb_unconfigure(struct usb_device *udev, uint8_t flag)
403 {
404         uint8_t do_unlock;
405
406         /* automatic locking */
407         if (usbd_enum_is_locked(udev)) {
408                 do_unlock = 0;
409         } else {
410                 do_unlock = 1;
411                 usbd_enum_lock(udev);
412         }
413
414         /* detach all interface drivers */
415         usb_detach_device(udev, USB_IFACE_INDEX_ANY, flag);
416
417 #if USB_HAVE_UGEN
418         /* free all FIFOs except control endpoint FIFOs */
419         usb_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, flag);
420
421         /*
422          * Free all cdev's, if any.
423          */
424         usb_cdev_free(udev);
425 #endif
426
427 #if USB_HAVE_COMPAT_LINUX
428         /* free Linux compat device, if any */
429         if (udev->linux_endpoint_start) {
430                 usb_linux_free_device(udev);
431                 udev->linux_endpoint_start = NULL;
432         }
433 #endif
434
435         usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_FREE);
436
437         /* free "cdesc" after "ifaces" and "endpoints", if any */
438         if (udev->cdesc != NULL) {
439                 if (udev->flags.usb_mode != USB_MODE_DEVICE)
440                         free(udev->cdesc, M_USB);
441                 udev->cdesc = NULL;
442         }
443         /* set unconfigured state */
444         udev->curr_config_no = USB_UNCONFIG_NO;
445         udev->curr_config_index = USB_UNCONFIG_INDEX;
446
447         if (do_unlock)
448                 usbd_enum_unlock(udev);
449 }
450
451 /*------------------------------------------------------------------------*
452  *      usbd_set_config_index
453  *
454  * This function selects configuration by index, independent of the
455  * actual configuration number. This function should not be used by
456  * USB drivers.
457  *
458  * Returns:
459  *    0: Success
460  * Else: Failure
461  *------------------------------------------------------------------------*/
462 usb_error_t
463 usbd_set_config_index(struct usb_device *udev, uint8_t index)
464 {
465         struct usb_status ds;
466         struct usb_config_descriptor *cdp;
467         uint16_t power;
468         uint16_t max_power;
469         uint8_t selfpowered;
470         uint8_t do_unlock;
471         usb_error_t err;
472
473         DPRINTFN(6, "udev=%p index=%d\n", udev, index);
474
475         /* automatic locking */
476         if (usbd_enum_is_locked(udev)) {
477                 do_unlock = 0;
478         } else {
479                 do_unlock = 1;
480                 usbd_enum_lock(udev);
481         }
482
483         usb_unconfigure(udev, 0);
484
485         if (index == USB_UNCONFIG_INDEX) {
486                 /*
487                  * Leave unallocated when unconfiguring the
488                  * device. "usb_unconfigure()" will also reset
489                  * the current config number and index.
490                  */
491                 err = usbd_req_set_config(udev, NULL, USB_UNCONFIG_NO);
492                 if (udev->state == USB_STATE_CONFIGURED)
493                         usb_set_device_state(udev, USB_STATE_ADDRESSED);
494                 goto done;
495         }
496         /* get the full config descriptor */
497         if (udev->flags.usb_mode == USB_MODE_DEVICE) {
498                 /* save some memory */
499                 err = usbd_req_get_descriptor_ptr(udev, &cdp, 
500                     (UDESC_CONFIG << 8) | index);
501         } else {
502                 /* normal request */
503                 err = usbd_req_get_config_desc_full(udev,
504                     NULL, &cdp, M_USB, index);
505         }
506         if (err) {
507                 goto done;
508         }
509         /* set the new config descriptor */
510
511         udev->cdesc = cdp;
512
513         /* Figure out if the device is self or bus powered. */
514         selfpowered = 0;
515         if ((!udev->flags.uq_bus_powered) &&
516             (cdp->bmAttributes & UC_SELF_POWERED) &&
517             (udev->flags.usb_mode == USB_MODE_HOST)) {
518                 /* May be self powered. */
519                 if (cdp->bmAttributes & UC_BUS_POWERED) {
520                         /* Must ask device. */
521                         err = usbd_req_get_device_status(udev, NULL, &ds);
522                         if (err) {
523                                 DPRINTFN(0, "could not read "
524                                     "device status: %s\n",
525                                     usbd_errstr(err));
526                         } else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
527                                 selfpowered = 1;
528                         }
529                         DPRINTF("status=0x%04x \n",
530                                 UGETW(ds.wStatus));
531                 } else
532                         selfpowered = 1;
533         }
534         DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
535             "selfpowered=%d, power=%d\n",
536             udev, cdp,
537             udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
538             selfpowered, cdp->bMaxPower * 2);
539
540         /* Check if we have enough power. */
541         power = cdp->bMaxPower * 2;
542
543         if (udev->parent_hub) {
544                 max_power = udev->parent_hub->hub->portpower;
545         } else {
546                 max_power = USB_MAX_POWER;
547         }
548
549         if (power > max_power) {
550                 DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
551                 err = USB_ERR_NO_POWER;
552                 goto done;
553         }
554         /* Only update "self_powered" in USB Host Mode */
555         if (udev->flags.usb_mode == USB_MODE_HOST) {
556                 udev->flags.self_powered = selfpowered;
557         }
558         udev->power = power;
559         udev->curr_config_no = cdp->bConfigurationValue;
560         udev->curr_config_index = index;
561         usb_set_device_state(udev, USB_STATE_CONFIGURED);
562
563         /* Set the actual configuration value. */
564         err = usbd_req_set_config(udev, NULL, cdp->bConfigurationValue);
565         if (err) {
566                 goto done;
567         }
568
569         err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_ALLOC);
570         if (err) {
571                 goto done;
572         }
573
574         err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_INIT);
575         if (err) {
576                 goto done;
577         }
578
579 #if USB_HAVE_UGEN
580         /* create device nodes for each endpoint */
581         usb_cdev_create(udev);
582 #endif
583
584 done:
585         DPRINTF("error=%s\n", usbd_errstr(err));
586         if (err) {
587                 usb_unconfigure(udev, 0);
588         }
589         if (do_unlock)
590                 usbd_enum_unlock(udev);
591         return (err);
592 }
593
594 /*------------------------------------------------------------------------*
595  *      usb_config_parse
596  *
597  * This function will allocate and free USB interfaces and USB endpoints,
598  * parse the USB configuration structure and initialise the USB endpoints
599  * and interfaces. If "iface_index" is not equal to
600  * "USB_IFACE_INDEX_ANY" then the "cmd" parameter is the
601  * alternate_setting to be selected for the given interface. Else the
602  * "cmd" parameter is defined by "USB_CFG_XXX". "iface_index" can be
603  * "USB_IFACE_INDEX_ANY" or a valid USB interface index. This function
604  * is typically called when setting the configuration or when setting
605  * an alternate interface.
606  *
607  * Returns:
608  *    0: Success
609  * Else: Failure
610  *------------------------------------------------------------------------*/
611 usb_error_t
612 usb_config_parse(struct usb_device *udev, uint8_t iface_index, uint8_t cmd)
613 {
614         struct usb_idesc_parse_state ips;
615         struct usb_interface_descriptor *id;
616         struct usb_endpoint_descriptor *ed;
617         struct usb_interface *iface;
618         struct usb_endpoint *ep;
619         usb_error_t err;
620         uint8_t ep_curr;
621         uint8_t ep_max;
622         uint8_t temp;
623         uint8_t do_init;
624         uint8_t alt_index;
625
626         if (iface_index != USB_IFACE_INDEX_ANY) {
627                 /* parameter overload */
628                 alt_index = cmd;
629                 cmd = USB_CFG_INIT;
630         } else {
631                 /* not used */
632                 alt_index = 0;
633         }
634
635         err = 0;
636
637         DPRINTFN(5, "iface_index=%d cmd=%d\n",
638             iface_index, cmd);
639
640         if (cmd == USB_CFG_FREE)
641                 goto cleanup;
642
643         if (cmd == USB_CFG_INIT) {
644                 sx_assert(udev->default_sx + 1, SA_LOCKED);
645
646                 /* check for in-use endpoints */
647
648                 ep = udev->endpoints;
649                 ep_max = udev->endpoints_max;
650                 while (ep_max--) {
651                         /* look for matching endpoints */
652                         if ((iface_index == USB_IFACE_INDEX_ANY) ||
653                             (iface_index == ep->iface_index)) {
654                                 if (ep->refcount != 0) {
655                                         /*
656                                          * This typically indicates a
657                                          * more serious error.
658                                          */
659                                         err = USB_ERR_IN_USE;
660                                 } else {
661                                         /* reset endpoint */
662                                         memset(ep, 0, sizeof(*ep));
663                                         /* make sure we don't zero the endpoint again */
664                                         ep->iface_index = USB_IFACE_INDEX_ANY;
665                                 }
666                         }
667                         ep++;
668                 }
669
670                 if (err)
671                         return (err);
672         }
673
674         memset(&ips, 0, sizeof(ips));
675
676         ep_curr = 0;
677         ep_max = 0;
678
679         while ((id = usb_idesc_foreach(udev->cdesc, &ips))) {
680
681                 /* check for interface overflow */
682                 if (ips.iface_index == USB_IFACE_MAX)
683                         break;                  /* crazy */
684
685                 iface = udev->ifaces + ips.iface_index;
686
687                 /* check for specific interface match */
688
689                 if (cmd == USB_CFG_INIT) {
690                         if ((iface_index != USB_IFACE_INDEX_ANY) && 
691                             (iface_index != ips.iface_index)) {
692                                 /* wrong interface */
693                                 do_init = 0;
694                         } else if (alt_index != ips.iface_index_alt) {
695                                 /* wrong alternate setting */
696                                 do_init = 0;
697                         } else {
698                                 /* initialise interface */
699                                 do_init = 1;
700                         }
701                 } else
702                         do_init = 0;
703
704                 /* check for new interface */
705                 if (ips.iface_index_alt == 0) {
706                         /* update current number of endpoints */
707                         ep_curr = ep_max;
708                 }
709                 /* check for init */
710                 if (do_init) {
711                         /* setup the USB interface structure */
712                         iface->idesc = id;
713                         /* default setting */
714                         iface->parent_iface_index = USB_IFACE_INDEX_ANY;
715                         /* set alternate index */
716                         iface->alt_index = alt_index;
717                 }
718
719                 DPRINTFN(5, "found idesc nendpt=%d\n", id->bNumEndpoints);
720
721                 ed = (struct usb_endpoint_descriptor *)id;
722
723                 temp = ep_curr;
724
725                 /* iterate all the endpoint descriptors */
726                 while ((ed = usb_edesc_foreach(udev->cdesc, ed))) {
727
728                         if (temp == USB_EP_MAX)
729                                 break;                  /* crazy */
730
731                         ep = udev->endpoints + temp;
732
733                         if (do_init) {
734                                 usb_init_endpoint(udev, 
735                                     ips.iface_index, ed, ep);
736                         }
737
738                         temp ++;
739
740                         /* find maximum number of endpoints */
741                         if (ep_max < temp)
742                                 ep_max = temp;
743
744                         /* optimalisation */
745                         id = (struct usb_interface_descriptor *)ed;
746                 }
747         }
748
749         /* NOTE: It is valid to have no interfaces and no endpoints! */
750
751         if (cmd == USB_CFG_ALLOC) {
752                 udev->ifaces_max = ips.iface_index;
753                 udev->ifaces = NULL;
754                 if (udev->ifaces_max != 0) {
755                         udev->ifaces = malloc(sizeof(*iface) * udev->ifaces_max,
756                                 M_USB, M_WAITOK | M_ZERO);
757                         if (udev->ifaces == NULL) {
758                                 err = USB_ERR_NOMEM;
759                                 goto done;
760                         }
761                 }
762                 if (ep_max != 0) {
763                         udev->endpoints = malloc(sizeof(*ep) * ep_max,
764                                 M_USB, M_WAITOK | M_ZERO);
765                         if (udev->endpoints == NULL) {
766                                 err = USB_ERR_NOMEM;
767                                 goto done;
768                         }
769                 } else {
770                         udev->endpoints = NULL;
771                 }
772                 USB_BUS_LOCK(udev->bus);
773                 udev->endpoints_max = ep_max;
774                 /* reset any ongoing clear-stall */
775                 udev->ep_curr = NULL;
776                 USB_BUS_UNLOCK(udev->bus);
777         }
778
779 done:
780         if (err) {
781                 if (cmd == USB_CFG_ALLOC) {
782 cleanup:
783                         USB_BUS_LOCK(udev->bus);
784                         udev->endpoints_max = 0;
785                         /* reset any ongoing clear-stall */
786                         udev->ep_curr = NULL;
787                         USB_BUS_UNLOCK(udev->bus);
788
789                         /* cleanup */
790                         if (udev->ifaces != NULL)
791                                 free(udev->ifaces, M_USB);
792                         if (udev->endpoints != NULL)
793                                 free(udev->endpoints, M_USB);
794
795                         udev->ifaces = NULL;
796                         udev->endpoints = NULL;
797                         udev->ifaces_max = 0;
798                 }
799         }
800         return (err);
801 }
802
803 /*------------------------------------------------------------------------*
804  *      usbd_set_alt_interface_index
805  *
806  * This function will select an alternate interface index for the
807  * given interface index. The interface should not be in use when this
808  * function is called. That means there should not be any open USB
809  * transfers. Else an error is returned. If the alternate setting is
810  * already set this function will simply return success. This function
811  * is called in Host mode and Device mode!
812  *
813  * Returns:
814  *    0: Success
815  * Else: Failure
816  *------------------------------------------------------------------------*/
817 usb_error_t
818 usbd_set_alt_interface_index(struct usb_device *udev,
819     uint8_t iface_index, uint8_t alt_index)
820 {
821         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
822         usb_error_t err;
823         uint8_t do_unlock;
824
825         /* automatic locking */
826         if (usbd_enum_is_locked(udev)) {
827                 do_unlock = 0;
828         } else {
829                 do_unlock = 1;
830                 usbd_enum_lock(udev);
831         }
832         if (iface == NULL) {
833                 err = USB_ERR_INVAL;
834                 goto done;
835         }
836         if (iface->alt_index == alt_index) {
837                 /* 
838                  * Optimise away duplicate setting of
839                  * alternate setting in USB Host Mode!
840                  */
841                 err = 0;
842                 goto done;
843         }
844 #if USB_HAVE_UGEN
845         /*
846          * Free all generic FIFOs for this interface, except control
847          * endpoint FIFOs:
848          */
849         usb_fifo_free_wrap(udev, iface_index, 0);
850 #endif
851
852         err = usb_config_parse(udev, iface_index, alt_index);
853         if (err) {
854                 goto done;
855         }
856         if (iface->alt_index != alt_index) {
857                 /* the alternate setting does not exist */
858                 err = USB_ERR_INVAL;
859                 goto done;
860         }
861
862         err = usbd_req_set_alt_interface_no(udev, NULL, iface_index,
863             iface->idesc->bAlternateSetting);
864
865 done:
866         if (do_unlock)
867                 usbd_enum_unlock(udev);
868
869         return (err);
870 }
871
872 /*------------------------------------------------------------------------*
873  *      usbd_set_endpoint_stall
874  *
875  * This function is used to make a BULK or INTERRUPT endpoint
876  * send STALL tokens.
877  *
878  * Returns:
879  *    0: Success
880  * Else: Failure
881  *------------------------------------------------------------------------*/
882 usb_error_t
883 usbd_set_endpoint_stall(struct usb_device *udev, struct usb_endpoint *ep,
884     uint8_t do_stall)
885 {
886         struct usb_xfer *xfer;
887         uint8_t et;
888         uint8_t was_stalled;
889
890         if (ep == NULL) {
891                 /* nothing to do */
892                 DPRINTF("Cannot find endpoint\n");
893                 /*
894                  * Pretend that the clear or set stall request is
895                  * successful else some USB host stacks can do
896                  * strange things, especially when a control endpoint
897                  * stalls.
898                  */
899                 return (0);
900         }
901         et = (ep->edesc->bmAttributes & UE_XFERTYPE);
902
903         if ((et != UE_BULK) &&
904             (et != UE_INTERRUPT)) {
905                 /*
906                  * Should not stall control
907                  * nor isochronous endpoints.
908                  */
909                 DPRINTF("Invalid endpoint\n");
910                 return (0);
911         }
912         USB_BUS_LOCK(udev->bus);
913
914         /* store current stall state */
915         was_stalled = ep->is_stalled;
916
917         /* check for no change */
918         if (was_stalled && do_stall) {
919                 /* if the endpoint is already stalled do nothing */
920                 USB_BUS_UNLOCK(udev->bus);
921                 DPRINTF("No change\n");
922                 return (0);
923         }
924         /* set stalled state */
925         ep->is_stalled = 1;
926
927         if (do_stall || (!was_stalled)) {
928                 if (!was_stalled) {
929                         /* lookup the current USB transfer, if any */
930                         xfer = ep->endpoint_q.curr;
931                 } else {
932                         xfer = NULL;
933                 }
934
935                 /*
936                  * If "xfer" is non-NULL the "set_stall" method will
937                  * complete the USB transfer like in case of a timeout
938                  * setting the error code "USB_ERR_STALLED".
939                  */
940                 (udev->bus->methods->set_stall) (udev, xfer, ep, &do_stall);
941         }
942         if (!do_stall) {
943                 ep->toggle_next = 0;    /* reset data toggle */
944                 ep->is_stalled = 0;     /* clear stalled state */
945
946                 (udev->bus->methods->clear_stall) (udev, ep);
947
948                 /* start up the current or next transfer, if any */
949                 usb_command_wrapper(&ep->endpoint_q, ep->endpoint_q.curr);
950         }
951         USB_BUS_UNLOCK(udev->bus);
952         return (0);
953 }
954
955 /*------------------------------------------------------------------------*
956  *      usb_reset_iface_endpoints - used in USB device side mode
957  *------------------------------------------------------------------------*/
958 usb_error_t
959 usb_reset_iface_endpoints(struct usb_device *udev, uint8_t iface_index)
960 {
961         struct usb_endpoint *ep;
962         struct usb_endpoint *ep_end;
963
964         ep = udev->endpoints;
965         ep_end = udev->endpoints + udev->endpoints_max;
966
967         for (; ep != ep_end; ep++) {
968
969                 if ((ep->edesc == NULL) ||
970                     (ep->iface_index != iface_index)) {
971                         continue;
972                 }
973                 /* simulate a clear stall from the peer */
974                 usbd_set_endpoint_stall(udev, ep, 0);
975         }
976         return (0);
977 }
978
979 /*------------------------------------------------------------------------*
980  *      usb_detach_device_sub
981  *
982  * This function will try to detach an USB device. If it fails a panic
983  * will result.
984  *
985  * Flag values, see "USB_UNCFG_FLAG_XXX".
986  *------------------------------------------------------------------------*/
987 static void
988 usb_detach_device_sub(struct usb_device *udev, device_t *ppdev,
989     uint8_t flag)
990 {
991         device_t dev;
992         int err;
993
994         dev = *ppdev;
995         if (dev) {
996                 /*
997                  * NOTE: It is important to clear "*ppdev" before deleting
998                  * the child due to some device methods being called late
999                  * during the delete process !
1000                  */
1001                 *ppdev = NULL;
1002
1003                 device_printf(dev, "at %s, port %d, addr %d "
1004                     "(disconnected)\n",
1005                     device_get_nameunit(udev->parent_dev),
1006                     udev->port_no, udev->address);
1007
1008                 if (device_is_attached(dev)) {
1009                         if (udev->flags.peer_suspended) {
1010                                 err = DEVICE_RESUME(dev);
1011                                 if (err) {
1012                                         device_printf(dev, "Resume failed!\n");
1013                                 }
1014                         }
1015                         if (device_detach(dev)) {
1016                                 goto error;
1017                         }
1018                 }
1019                 if (device_delete_child(udev->parent_dev, dev)) {
1020                         goto error;
1021                 }
1022         }
1023         return;
1024
1025 error:
1026         /* Detach is not allowed to fail in the USB world */
1027         panic("An USB driver would not detach!\n");
1028 }
1029
1030 /*------------------------------------------------------------------------*
1031  *      usb_detach_device
1032  *
1033  * The following function will detach the matching interfaces.
1034  * This function is NULL safe.
1035  *
1036  * Flag values, see "USB_UNCFG_FLAG_XXX".
1037  *------------------------------------------------------------------------*/
1038 void
1039 usb_detach_device(struct usb_device *udev, uint8_t iface_index,
1040     uint8_t flag)
1041 {
1042         struct usb_interface *iface;
1043         uint8_t i;
1044
1045         if (udev == NULL) {
1046                 /* nothing to do */
1047                 return;
1048         }
1049         DPRINTFN(4, "udev=%p\n", udev);
1050
1051         sx_assert(udev->default_sx + 1, SA_LOCKED);
1052
1053         /*
1054          * First detach the child to give the child's detach routine a
1055          * chance to detach the sub-devices in the correct order.
1056          * Then delete the child using "device_delete_child()" which
1057          * will detach all sub-devices from the bottom and upwards!
1058          */
1059         if (iface_index != USB_IFACE_INDEX_ANY) {
1060                 i = iface_index;
1061                 iface_index = i + 1;
1062         } else {
1063                 i = 0;
1064                 iface_index = USB_IFACE_MAX;
1065         }
1066
1067         /* do the detach */
1068
1069         for (; i != iface_index; i++) {
1070
1071                 iface = usbd_get_iface(udev, i);
1072                 if (iface == NULL) {
1073                         /* looks like the end of the USB interfaces */
1074                         break;
1075                 }
1076                 usb_detach_device_sub(udev, &iface->subdev, flag);
1077         }
1078 }
1079
1080 /*------------------------------------------------------------------------*
1081  *      usb_probe_and_attach_sub
1082  *
1083  * Returns:
1084  *    0: Success
1085  * Else: Failure
1086  *------------------------------------------------------------------------*/
1087 static uint8_t
1088 usb_probe_and_attach_sub(struct usb_device *udev,
1089     struct usb_attach_arg *uaa)
1090 {
1091         struct usb_interface *iface;
1092         device_t dev;
1093         int err;
1094
1095         iface = uaa->iface;
1096         if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
1097                 /* leave interface alone */
1098                 return (0);
1099         }
1100         dev = iface->subdev;
1101         if (dev) {
1102
1103                 /* clean up after module unload */
1104
1105                 if (device_is_attached(dev)) {
1106                         /* already a device there */
1107                         return (0);
1108                 }
1109                 /* clear "iface->subdev" as early as possible */
1110
1111                 iface->subdev = NULL;
1112
1113                 if (device_delete_child(udev->parent_dev, dev)) {
1114
1115                         /*
1116                          * Panic here, else one can get a double call
1117                          * to device_detach().  USB devices should
1118                          * never fail on detach!
1119                          */
1120                         panic("device_delete_child() failed!\n");
1121                 }
1122         }
1123         if (uaa->temp_dev == NULL) {
1124
1125                 /* create a new child */
1126                 uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1127                 if (uaa->temp_dev == NULL) {
1128                         device_printf(udev->parent_dev,
1129                             "Device creation failed!\n");
1130                         return (1);     /* failure */
1131                 }
1132                 device_set_ivars(uaa->temp_dev, uaa);
1133                 device_quiet(uaa->temp_dev);
1134         }
1135         /*
1136          * Set "subdev" before probe and attach so that "devd" gets
1137          * the information it needs.
1138          */
1139         iface->subdev = uaa->temp_dev;
1140
1141         if (device_probe_and_attach(iface->subdev) == 0) {
1142                 /*
1143                  * The USB attach arguments are only available during probe
1144                  * and attach !
1145                  */
1146                 uaa->temp_dev = NULL;
1147                 device_set_ivars(iface->subdev, NULL);
1148
1149                 if (udev->flags.peer_suspended) {
1150                         err = DEVICE_SUSPEND(iface->subdev);
1151                         if (err)
1152                                 device_printf(iface->subdev, "Suspend failed\n");
1153                 }
1154                 return (0);             /* success */
1155         } else {
1156                 /* No USB driver found */
1157                 iface->subdev = NULL;
1158         }
1159         return (1);                     /* failure */
1160 }
1161
1162 /*------------------------------------------------------------------------*
1163  *      usbd_set_parent_iface
1164  *
1165  * Using this function will lock the alternate interface setting on an
1166  * interface. It is typically used for multi interface drivers. In USB
1167  * device side mode it is assumed that the alternate interfaces all
1168  * have the same endpoint descriptors. The default parent index value
1169  * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1170  * locked.
1171  *------------------------------------------------------------------------*/
1172 void
1173 usbd_set_parent_iface(struct usb_device *udev, uint8_t iface_index,
1174     uint8_t parent_index)
1175 {
1176         struct usb_interface *iface;
1177
1178         iface = usbd_get_iface(udev, iface_index);
1179         if (iface) {
1180                 iface->parent_iface_index = parent_index;
1181         }
1182 }
1183
1184 static void
1185 usb_init_attach_arg(struct usb_device *udev,
1186     struct usb_attach_arg *uaa)
1187 {
1188         bzero(uaa, sizeof(*uaa));
1189
1190         uaa->device = udev;
1191         uaa->usb_mode = udev->flags.usb_mode;
1192         uaa->port = udev->port_no;
1193
1194         uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1195         uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1196         uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1197         uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1198         uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1199         uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1200         uaa->info.bConfigIndex = udev->curr_config_index;
1201         uaa->info.bConfigNum = udev->curr_config_no;
1202 }
1203
1204 /*------------------------------------------------------------------------*
1205  *      usb_probe_and_attach
1206  *
1207  * This function is called from "uhub_explore_sub()",
1208  * "usb_handle_set_config()" and "usb_handle_request()".
1209  *
1210  * Returns:
1211  *    0: Success
1212  * Else: A control transfer failed
1213  *------------------------------------------------------------------------*/
1214 usb_error_t
1215 usb_probe_and_attach(struct usb_device *udev, uint8_t iface_index)
1216 {
1217         struct usb_attach_arg uaa;
1218         struct usb_interface *iface;
1219         uint8_t i;
1220         uint8_t j;
1221         uint8_t do_unlock;
1222
1223         if (udev == NULL) {
1224                 DPRINTF("udev == NULL\n");
1225                 return (USB_ERR_INVAL);
1226         }
1227         /* automatic locking */
1228         if (usbd_enum_is_locked(udev)) {
1229                 do_unlock = 0;
1230         } else {
1231                 do_unlock = 1;
1232                 usbd_enum_lock(udev);
1233         }
1234
1235         if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1236                 /* do nothing - no configuration has been set */
1237                 goto done;
1238         }
1239         /* setup USB attach arguments */
1240
1241         usb_init_attach_arg(udev, &uaa);
1242
1243         /* Check if only one interface should be probed: */
1244         if (iface_index != USB_IFACE_INDEX_ANY) {
1245                 i = iface_index;
1246                 j = i + 1;
1247         } else {
1248                 i = 0;
1249                 j = USB_IFACE_MAX;
1250         }
1251
1252         /* Do the probe and attach */
1253         for (; i != j; i++) {
1254
1255                 iface = usbd_get_iface(udev, i);
1256                 if (iface == NULL) {
1257                         /*
1258                          * Looks like the end of the USB
1259                          * interfaces !
1260                          */
1261                         DPRINTFN(2, "end of interfaces "
1262                             "at %u\n", i);
1263                         break;
1264                 }
1265                 if (iface->idesc == NULL) {
1266                         /* no interface descriptor */
1267                         continue;
1268                 }
1269                 uaa.iface = iface;
1270
1271                 uaa.info.bInterfaceClass =
1272                     iface->idesc->bInterfaceClass;
1273                 uaa.info.bInterfaceSubClass =
1274                     iface->idesc->bInterfaceSubClass;
1275                 uaa.info.bInterfaceProtocol =
1276                     iface->idesc->bInterfaceProtocol;
1277                 uaa.info.bIfaceIndex = i;
1278                 uaa.info.bIfaceNum =
1279                     iface->idesc->bInterfaceNumber;
1280                 uaa.use_generic = 0;
1281                 uaa.driver_info = 0;    /* reset driver_info */
1282
1283                 DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1284                     uaa.info.bInterfaceClass,
1285                     uaa.info.bInterfaceSubClass,
1286                     uaa.info.bInterfaceProtocol,
1287                     uaa.info.bIfaceIndex,
1288                     uaa.info.bIfaceNum);
1289
1290                 /* try specific interface drivers first */
1291
1292                 if (usb_probe_and_attach_sub(udev, &uaa)) {
1293                         /* ignore */
1294                 }
1295                 /* try generic interface drivers last */
1296
1297                 uaa.use_generic = 1;
1298                 uaa.driver_info = 0;    /* reset driver_info */
1299
1300                 if (usb_probe_and_attach_sub(udev, &uaa)) {
1301                         /* ignore */
1302                 }
1303         }
1304
1305         if (uaa.temp_dev) {
1306                 /* remove the last created child; it is unused */
1307
1308                 if (device_delete_child(udev->parent_dev, uaa.temp_dev)) {
1309                         DPRINTFN(0, "device delete child failed!\n");
1310                 }
1311         }
1312 done:
1313         if (do_unlock)
1314                 usbd_enum_unlock(udev);
1315
1316         return (0);
1317 }
1318
1319 /*------------------------------------------------------------------------*
1320  *      usb_suspend_resume_sub
1321  *
1322  * This function is called when the suspend or resume methods should
1323  * be executed on an USB device.
1324  *------------------------------------------------------------------------*/
1325 static void
1326 usb_suspend_resume_sub(struct usb_device *udev, device_t dev, uint8_t do_suspend)
1327 {
1328         int err;
1329
1330         if (dev == NULL) {
1331                 return;
1332         }
1333         if (!device_is_attached(dev)) {
1334                 return;
1335         }
1336         if (do_suspend) {
1337                 err = DEVICE_SUSPEND(dev);
1338         } else {
1339                 err = DEVICE_RESUME(dev);
1340         }
1341         if (err) {
1342                 device_printf(dev, "%s failed!\n",
1343                     do_suspend ? "Suspend" : "Resume");
1344         }
1345 }
1346
1347 /*------------------------------------------------------------------------*
1348  *      usb_suspend_resume
1349  *
1350  * The following function will suspend or resume the USB device.
1351  *
1352  * Returns:
1353  *    0: Success
1354  * Else: Failure
1355  *------------------------------------------------------------------------*/
1356 usb_error_t
1357 usb_suspend_resume(struct usb_device *udev, uint8_t do_suspend)
1358 {
1359         struct usb_interface *iface;
1360         uint8_t i;
1361
1362         if (udev == NULL) {
1363                 /* nothing to do */
1364                 return (0);
1365         }
1366         DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1367
1368         sx_assert(udev->default_sx + 1, SA_LOCKED);
1369
1370         USB_BUS_LOCK(udev->bus);
1371         /* filter the suspend events */
1372         if (udev->flags.peer_suspended == do_suspend) {
1373                 USB_BUS_UNLOCK(udev->bus);
1374                 /* nothing to do */
1375                 return (0);
1376         }
1377         udev->flags.peer_suspended = do_suspend;
1378         USB_BUS_UNLOCK(udev->bus);
1379
1380         /* do the suspend or resume */
1381
1382         for (i = 0; i != USB_IFACE_MAX; i++) {
1383
1384                 iface = usbd_get_iface(udev, i);
1385                 if (iface == NULL) {
1386                         /* looks like the end of the USB interfaces */
1387                         break;
1388                 }
1389                 usb_suspend_resume_sub(udev, iface->subdev, do_suspend);
1390         }
1391         return (0);
1392 }
1393
1394 /*------------------------------------------------------------------------*
1395  *      usbd_clear_stall_proc
1396  *
1397  * This function performs generic USB clear stall operations.
1398  *------------------------------------------------------------------------*/
1399 static void
1400 usbd_clear_stall_proc(struct usb_proc_msg *_pm)
1401 {
1402         struct usb_clear_stall_msg *pm = (void *)_pm;
1403         struct usb_device *udev = pm->udev;
1404
1405         /* Change lock */
1406         USB_BUS_UNLOCK(udev->bus);
1407         mtx_lock(udev->default_mtx);
1408
1409         /* Start clear stall callback */
1410         usbd_transfer_start(udev->default_xfer[1]);
1411
1412         /* Change lock */
1413         mtx_unlock(udev->default_mtx);
1414         USB_BUS_LOCK(udev->bus);
1415 }
1416
1417 /*------------------------------------------------------------------------*
1418  *      usb_alloc_device
1419  *
1420  * This function allocates a new USB device. This function is called
1421  * when a new device has been put in the powered state, but not yet in
1422  * the addressed state. Get initial descriptor, set the address, get
1423  * full descriptor and get strings.
1424  *
1425  * Return values:
1426  *    0: Failure
1427  * Else: Success
1428  *------------------------------------------------------------------------*/
1429 struct usb_device *
1430 usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
1431     struct usb_device *parent_hub, uint8_t depth, uint8_t port_index,
1432     uint8_t port_no, enum usb_dev_speed speed, enum usb_hc_mode mode)
1433 {
1434         struct usb_attach_arg uaa;
1435         struct usb_device *udev;
1436         struct usb_device *adev;
1437         struct usb_device *hub;
1438         uint8_t *scratch_ptr;
1439         uint32_t scratch_size;
1440         usb_error_t err;
1441         uint8_t device_index;
1442
1443         DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1444             "port_index=%u, port_no=%u, speed=%u, usb_mode=%u\n",
1445             parent_dev, bus, parent_hub, depth, port_index, port_no,
1446             speed, mode);
1447
1448         /*
1449          * Find an unused device index. In USB Host mode this is the
1450          * same as the device address.
1451          *
1452          * Device index zero is not used and device index 1 should
1453          * always be the root hub.
1454          */
1455         for (device_index = USB_ROOT_HUB_ADDR;
1456             (device_index != bus->devices_max) &&
1457             (bus->devices[device_index] != NULL);
1458             device_index++) /* nop */;
1459
1460         if (device_index == bus->devices_max) {
1461                 device_printf(bus->bdev,
1462                     "No free USB device index for new device!\n");
1463                 return (NULL);
1464         }
1465
1466         if (depth > 0x10) {
1467                 device_printf(bus->bdev,
1468                     "Invalid device depth!\n");
1469                 return (NULL);
1470         }
1471         udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1472         if (udev == NULL) {
1473                 return (NULL);
1474         }
1475         /* initialise our SX-lock */
1476         sx_init(udev->default_sx, "0123456789ABCDEF - USB device SX lock" + depth);
1477
1478         /* initialise our SX-lock */
1479         sx_init(udev->default_sx + 1, "0123456789ABCDEF - USB config SX lock" + depth);
1480
1481         cv_init(udev->default_cv, "WCTRL");
1482         cv_init(udev->default_cv + 1, "UGONE");
1483
1484         /* initialise our mutex */
1485         mtx_init(udev->default_mtx, "USB device mutex", NULL, MTX_DEF);
1486
1487         /* initialise generic clear stall */
1488         udev->cs_msg[0].hdr.pm_callback = &usbd_clear_stall_proc;
1489         udev->cs_msg[0].udev = udev;
1490         udev->cs_msg[1].hdr.pm_callback = &usbd_clear_stall_proc;
1491         udev->cs_msg[1].udev = udev;
1492
1493         /* initialise some USB device fields */
1494         udev->parent_hub = parent_hub;
1495         udev->parent_dev = parent_dev;
1496         udev->port_index = port_index;
1497         udev->port_no = port_no;
1498         udev->depth = depth;
1499         udev->bus = bus;
1500         udev->address = USB_START_ADDR; /* default value */
1501         udev->plugtime = (usb_ticks_t)ticks;
1502         usb_set_device_state(udev, USB_STATE_POWERED);
1503         /*
1504          * We need to force the power mode to "on" because there are plenty
1505          * of USB devices out there that do not work very well with
1506          * automatic suspend and resume!
1507          */
1508         udev->power_mode = USB_POWER_MODE_ON;
1509         udev->pwr_save.last_xfer_time = ticks;
1510         /* we are not ready yet */
1511         udev->refcount = 1;
1512
1513         /* set up default endpoint descriptor */
1514         udev->default_ep_desc.bLength = sizeof(udev->default_ep_desc);
1515         udev->default_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1516         udev->default_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1517         udev->default_ep_desc.bmAttributes = UE_CONTROL;
1518         udev->default_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1519         udev->default_ep_desc.wMaxPacketSize[1] = 0;
1520         udev->default_ep_desc.bInterval = 0;
1521         udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1522
1523         udev->speed = speed;
1524         udev->flags.usb_mode = mode;
1525
1526         /* search for our High Speed USB HUB, if any */
1527
1528         adev = udev;
1529         hub = udev->parent_hub;
1530
1531         while (hub) {
1532                 if (hub->speed == USB_SPEED_HIGH) {
1533                         udev->hs_hub_addr = hub->address;
1534                         udev->parent_hs_hub = hub;
1535                         udev->hs_port_no = adev->port_no;
1536                         break;
1537                 }
1538                 adev = hub;
1539                 hub = hub->parent_hub;
1540         }
1541
1542         /* init the default endpoint */
1543         usb_init_endpoint(udev, 0,
1544             &udev->default_ep_desc,
1545             &udev->default_ep);
1546
1547         /* set device index */
1548         udev->device_index = device_index;
1549
1550 #if USB_HAVE_UGEN
1551         /* Create ugen name */
1552         snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1553             USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1554             device_index);
1555         LIST_INIT(&udev->pd_list);
1556
1557         /* Create the control endpoint device */
1558         udev->default_dev = usb_make_dev(udev, 0, FREAD|FWRITE);
1559
1560         /* Create a link from /dev/ugenX.X to the default endpoint */
1561         make_dev_alias(udev->default_dev, udev->ugen_name);
1562 #endif
1563         if (udev->flags.usb_mode == USB_MODE_HOST) {
1564
1565                 err = usbd_req_set_address(udev, NULL, device_index);
1566
1567                 /* This is the new USB device address from now on */
1568
1569                 udev->address = device_index;
1570
1571                 /*
1572                  * We ignore any set-address errors, hence there are
1573                  * buggy USB devices out there that actually receive
1574                  * the SETUP PID, but manage to set the address before
1575                  * the STATUS stage is ACK'ed. If the device responds
1576                  * to the subsequent get-descriptor at the new
1577                  * address, then we know that the set-address command
1578                  * was successful.
1579                  */
1580                 if (err) {
1581                         DPRINTFN(0, "set address %d failed "
1582                             "(%s, ignored)\n", udev->address, 
1583                             usbd_errstr(err));
1584                 }
1585                 /* allow device time to set new address */
1586                 usb_pause_mtx(NULL, 
1587                     USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1588         } else {
1589                 /* We are not self powered */
1590                 udev->flags.self_powered = 0;
1591
1592                 /* Set unconfigured state */
1593                 udev->curr_config_no = USB_UNCONFIG_NO;
1594                 udev->curr_config_index = USB_UNCONFIG_INDEX;
1595
1596                 /* Setup USB descriptors */
1597                 err = (usb_temp_setup_by_index_p) (udev, usb_template);
1598                 if (err) {
1599                         DPRINTFN(0, "setting up USB template failed maybe the USB "
1600                             "template module has not been loaded\n");
1601                         goto done;
1602                 }
1603         }
1604         usb_set_device_state(udev, USB_STATE_ADDRESSED);
1605
1606         /*
1607          * Get the first 8 bytes of the device descriptor !
1608          *
1609          * NOTE: "usbd_do_request" will check the device descriptor
1610          * next time we do a request to see if the maximum packet size
1611          * changed! The 8 first bytes of the device descriptor
1612          * contains the maximum packet size to use on control endpoint
1613          * 0. If this value is different from "USB_MAX_IPACKET" a new
1614          * USB control request will be setup!
1615          */
1616         err = usbd_req_get_desc(udev, NULL, NULL, &udev->ddesc,
1617             USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1618         if (err) {
1619                 DPRINTFN(0, "getting device descriptor "
1620                     "at addr %d failed, %s!\n", udev->address,
1621                     usbd_errstr(err));
1622                 /* XXX try to re-enumerate the device */
1623                 err = usbd_req_re_enumerate(udev, NULL);
1624                 if (err) {
1625                         goto done;
1626                 }
1627         }
1628         DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
1629             "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1630             udev->address, UGETW(udev->ddesc.bcdUSB),
1631             udev->ddesc.bDeviceClass,
1632             udev->ddesc.bDeviceSubClass,
1633             udev->ddesc.bDeviceProtocol,
1634             udev->ddesc.bMaxPacketSize,
1635             udev->ddesc.bLength,
1636             udev->speed);
1637
1638         /* get the full device descriptor */
1639         err = usbd_req_get_device_desc(udev, NULL, &udev->ddesc);
1640         if (err) {
1641                 DPRINTF("addr=%d, getting full desc failed\n",
1642                     udev->address);
1643                 goto done;
1644         }
1645         /*
1646          * Setup temporary USB attach args so that we can figure out some
1647          * basic quirks for this device.
1648          */
1649         usb_init_attach_arg(udev, &uaa);
1650
1651         if (usb_test_quirk(&uaa, UQ_BUS_POWERED)) {
1652                 udev->flags.uq_bus_powered = 1;
1653         }
1654         if (usb_test_quirk(&uaa, UQ_NO_STRINGS)) {
1655                 udev->flags.no_strings = 1;
1656         }
1657         /*
1658          * Workaround for buggy USB devices.
1659          *
1660          * It appears that some string-less USB chips will crash and
1661          * disappear if any attempts are made to read any string
1662          * descriptors.
1663          *
1664          * Try to detect such chips by checking the strings in the USB
1665          * device descriptor. If no strings are present there we
1666          * simply disable all USB strings.
1667          */
1668         scratch_ptr = udev->bus->scratch[0].data;
1669         scratch_size = sizeof(udev->bus->scratch[0].data);
1670
1671         if (udev->ddesc.iManufacturer ||
1672             udev->ddesc.iProduct ||
1673             udev->ddesc.iSerialNumber) {
1674                 /* read out the language ID string */
1675                 err = usbd_req_get_string_desc(udev, NULL,
1676                     (char *)scratch_ptr, 4, scratch_size,
1677                     USB_LANGUAGE_TABLE);
1678         } else {
1679                 err = USB_ERR_INVAL;
1680         }
1681
1682         if (err || (scratch_ptr[0] < 4)) {
1683                 udev->flags.no_strings = 1;
1684         } else {
1685                 /* pick the first language as the default */
1686                 udev->langid = UGETW(scratch_ptr + 2);
1687         }
1688
1689         /* assume 100mA bus powered for now. Changed when configured. */
1690         udev->power = USB_MIN_POWER;
1691         /* fetch the vendor and product strings from the device */
1692         usbd_set_device_strings(udev);
1693
1694         if (udev->flags.usb_mode == USB_MODE_HOST) {
1695                 uint8_t config_index;
1696                 uint8_t config_quirk;
1697                 uint8_t set_config_failed = 0;
1698
1699                 /*
1700                  * Most USB devices should attach to config index 0 by
1701                  * default
1702                  */
1703                 if (usb_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1704                         config_index = 0;
1705                         config_quirk = 1;
1706                 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1707                         config_index = 1;
1708                         config_quirk = 1;
1709                 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1710                         config_index = 2;
1711                         config_quirk = 1;
1712                 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1713                         config_index = 3;
1714                         config_quirk = 1;
1715                 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1716                         config_index = 4;
1717                         config_quirk = 1;
1718                 } else {
1719                         config_index = 0;
1720                         config_quirk = 0;
1721                 }
1722
1723 repeat_set_config:
1724
1725                 DPRINTF("setting config %u\n", config_index);
1726
1727                 /* get the USB device configured */
1728                 err = usbd_set_config_index(udev, config_index);
1729                 if (err) {
1730                         if (udev->ddesc.bNumConfigurations != 0) {
1731                                 if (!set_config_failed) {
1732                                         set_config_failed = 1;
1733                                         /* XXX try to re-enumerate the device */
1734                                         err = usbd_req_re_enumerate(
1735                                             udev, NULL);
1736                                         if (err == 0)
1737                                             goto repeat_set_config;
1738                                 }
1739                                 DPRINTFN(0, "Failure selecting "
1740                                     "configuration index %u: %s, port %u, "
1741                                     "addr %u (ignored)\n",
1742                                     config_index, usbd_errstr(err), udev->port_no,
1743                                     udev->address);
1744                         }
1745                         /*
1746                          * Some USB devices do not have any
1747                          * configurations. Ignore any set config
1748                          * failures!
1749                          */
1750                         err = 0;
1751                 } else if (config_quirk) {
1752                         /* user quirk selects configuration index */
1753                 } else if ((config_index + 1) < udev->ddesc.bNumConfigurations) {
1754
1755                         if ((udev->cdesc->bNumInterface < 2) &&
1756                             (usbd_get_no_descriptors(udev->cdesc,
1757                             UDESC_ENDPOINT) == 0)) {
1758                                 DPRINTFN(0, "Found no endpoints "
1759                                     "(trying next config)!\n");
1760                                 config_index++;
1761                                 goto repeat_set_config;
1762                         }
1763                         if (config_index == 0) {
1764                                 /*
1765                                  * Try to figure out if we have an
1766                                  * auto-install disk there:
1767                                  */
1768                                 if (usb_test_autoinstall(udev, 0, 0) == 0) {
1769                                         DPRINTFN(0, "Found possible auto-install "
1770                                             "disk (trying next config)\n");
1771                                         config_index++;
1772                                         goto repeat_set_config;
1773                                 }
1774                         }
1775                 } else if (usb_test_huawei_autoinst_p(udev, &uaa) == 0) {
1776                         DPRINTFN(0, "Found Huawei auto-install disk!\n");
1777                         /* leave device unconfigured */
1778                         usb_unconfigure(udev, 0);
1779                 }
1780         } else {
1781                 err = 0;                /* set success */
1782         }
1783
1784         DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1785             udev->address, udev, udev->parent_hub);
1786
1787         /* register our device - we are ready */
1788         usb_bus_port_set_device(bus, parent_hub ?
1789             parent_hub->hub->ports + port_index : NULL, udev, device_index);
1790
1791 #if USB_HAVE_UGEN
1792         /* Symlink the ugen device name */
1793         udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
1794
1795         /* Announce device */
1796         printf("%s: <%s> at %s\n", udev->ugen_name, udev->manufacturer,
1797             device_get_nameunit(udev->bus->bdev));
1798
1799         usb_notify_addq("+", udev);
1800 #endif
1801 done:
1802         if (err) {
1803                 /*
1804                  * Free USB device and all subdevices, if any.
1805                  */
1806                 usb_free_device(udev, 0);
1807                 udev = NULL;
1808         }
1809         return (udev);
1810 }
1811
1812 #if USB_HAVE_UGEN
1813 static struct cdev *
1814 usb_make_dev(struct usb_device *udev, int ep, int mode)
1815 {
1816         struct usb_fs_privdata* pd;
1817         char devname[20];
1818
1819         /* Store information to locate ourselves again later */
1820         pd = malloc(sizeof(struct usb_fs_privdata), M_USBDEV,
1821             M_WAITOK | M_ZERO);
1822         pd->bus_index = device_get_unit(udev->bus->bdev);
1823         pd->dev_index = udev->device_index;
1824         pd->ep_addr = ep;
1825         pd->mode = mode;
1826
1827         /* Now, create the device itself */
1828         snprintf(devname, sizeof(devname), "%u.%u.%u",
1829             pd->bus_index, pd->dev_index, pd->ep_addr);
1830         pd->cdev = make_dev(&usb_devsw, 0, UID_ROOT,
1831             GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1832         pd->cdev->si_drv1 = pd;
1833
1834         return (pd->cdev);
1835 }
1836
1837 static void
1838 usb_cdev_create(struct usb_device *udev)
1839 {
1840         struct usb_config_descriptor *cd;
1841         struct usb_endpoint_descriptor *ed;
1842         struct usb_descriptor *desc;
1843         struct usb_fs_privdata* pd;
1844         struct cdev *dev;
1845         int inmode, outmode, inmask, outmask, mode;
1846         uint8_t ep;
1847
1848         KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1849
1850         DPRINTFN(2, "Creating device nodes\n");
1851
1852         if (usbd_get_mode(udev) == USB_MODE_DEVICE) {
1853                 inmode = FWRITE;
1854                 outmode = FREAD;
1855         } else {                 /* USB_MODE_HOST */
1856                 inmode = FREAD;
1857                 outmode = FWRITE;
1858         }
1859
1860         inmask = 0;
1861         outmask = 0;
1862         desc = NULL;
1863
1864         /*
1865          * Collect all used endpoint numbers instead of just
1866          * generating 16 static endpoints.
1867          */
1868         cd = usbd_get_config_descriptor(udev);
1869         while ((desc = usb_desc_foreach(cd, desc))) {
1870                 /* filter out all endpoint descriptors */
1871                 if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1872                     (desc->bLength >= sizeof(*ed))) {
1873                         ed = (struct usb_endpoint_descriptor *)desc;
1874
1875                         /* update masks */
1876                         ep = ed->bEndpointAddress;
1877                         if (UE_GET_DIR(ep)  == UE_DIR_OUT)
1878                                 outmask |= 1 << UE_GET_ADDR(ep);
1879                         else
1880                                 inmask |= 1 << UE_GET_ADDR(ep);
1881                 }
1882         }
1883
1884         /* Create all available endpoints except EP0 */
1885         for (ep = 1; ep < 16; ep++) {
1886                 mode = inmask & (1 << ep) ? inmode : 0;
1887                 mode |= outmask & (1 << ep) ? outmode : 0;
1888                 if (mode == 0)
1889                         continue;       /* no IN or OUT endpoint */
1890
1891                 dev = usb_make_dev(udev, ep, mode);
1892                 pd = dev->si_drv1;
1893                 LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1894         }
1895 }
1896
1897 static void
1898 usb_cdev_free(struct usb_device *udev)
1899 {
1900         struct usb_fs_privdata* pd;
1901         struct cdev* pcdev;
1902
1903         DPRINTFN(2, "Freeing device nodes\n");
1904
1905         while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1906                 KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1907
1908                 pcdev = pd->cdev;
1909                 pd->cdev = NULL;
1910                 LIST_REMOVE(pd, pd_next);
1911                 if (pcdev != NULL)
1912                         destroy_dev_sched_cb(pcdev, usb_cdev_cleanup, pd);
1913         }
1914 }
1915
1916 static void
1917 usb_cdev_cleanup(void* arg)
1918 {
1919         free(arg, M_USBDEV);
1920 }
1921 #endif
1922
1923 /*------------------------------------------------------------------------*
1924  *      usb_free_device
1925  *
1926  * This function is NULL safe and will free an USB device and its
1927  * children devices, if any.
1928  *
1929  * Flag values: Reserved, set to zero.
1930  *------------------------------------------------------------------------*/
1931 void
1932 usb_free_device(struct usb_device *udev, uint8_t flag)
1933 {
1934         struct usb_bus *bus;
1935
1936         if (udev == NULL)
1937                 return;         /* already freed */
1938
1939         DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
1940
1941         bus = udev->bus;
1942         usb_set_device_state(udev, USB_STATE_DETACHED);
1943
1944 #if USB_HAVE_UGEN
1945         usb_notify_addq("-", udev);
1946
1947         printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
1948             udev->manufacturer, device_get_nameunit(bus->bdev));
1949
1950         /* Destroy UGEN symlink, if any */
1951         if (udev->ugen_symlink) {
1952                 usb_free_symlink(udev->ugen_symlink);
1953                 udev->ugen_symlink = NULL;
1954         }
1955 #endif
1956         /*
1957          * Unregister our device first which will prevent any further
1958          * references:
1959          */
1960         usb_bus_port_set_device(bus, udev->parent_hub ?
1961             udev->parent_hub->hub->ports + udev->port_index : NULL,
1962             NULL, USB_ROOT_HUB_ADDR);
1963
1964 #if USB_HAVE_UGEN
1965         /* wait for all pending references to go away: */
1966         mtx_lock(&usb_ref_lock);
1967         udev->refcount--;
1968         while (udev->refcount != 0) {
1969                 cv_wait(udev->default_cv + 1, &usb_ref_lock);
1970         }
1971         mtx_unlock(&usb_ref_lock);
1972
1973         destroy_dev_sched_cb(udev->default_dev, usb_cdev_cleanup,
1974             udev->default_dev->si_drv1);
1975 #endif
1976
1977         if (udev->flags.usb_mode == USB_MODE_DEVICE) {
1978                 /* stop receiving any control transfers (Device Side Mode) */
1979                 usbd_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1980         }
1981
1982         /* the following will get the device unconfigured in software */
1983         usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_EP0);
1984
1985         /* unsetup any leftover default USB transfers */
1986         usbd_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1987
1988         /* template unsetup, if any */
1989         (usb_temp_unsetup_p) (udev);
1990
1991         /* 
1992          * Make sure that our clear-stall messages are not queued
1993          * anywhere:
1994          */
1995         USB_BUS_LOCK(udev->bus);
1996         usb_proc_mwait(&udev->bus->non_giant_callback_proc,
1997             &udev->cs_msg[0], &udev->cs_msg[1]);
1998         USB_BUS_UNLOCK(udev->bus);
1999
2000         sx_destroy(udev->default_sx);
2001         sx_destroy(udev->default_sx + 1);
2002
2003         cv_destroy(udev->default_cv);
2004         cv_destroy(udev->default_cv + 1);
2005
2006         mtx_destroy(udev->default_mtx);
2007 #if USB_HAVE_UGEN
2008         KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2009 #endif
2010
2011         /* free device */
2012         free(udev->serial, M_USB);
2013         free(udev->manufacturer, M_USB);
2014         free(udev->product, M_USB);
2015         free(udev, M_USB);
2016 }
2017
2018 /*------------------------------------------------------------------------*
2019  *      usbd_get_iface
2020  *
2021  * This function is the safe way to get the USB interface structure
2022  * pointer by interface index.
2023  *
2024  * Return values:
2025  *   NULL: Interface not present.
2026  *   Else: Pointer to USB interface structure.
2027  *------------------------------------------------------------------------*/
2028 struct usb_interface *
2029 usbd_get_iface(struct usb_device *udev, uint8_t iface_index)
2030 {
2031         struct usb_interface *iface = udev->ifaces + iface_index;
2032
2033         if (iface_index >= udev->ifaces_max)
2034                 return (NULL);
2035         return (iface);
2036 }
2037
2038 /*------------------------------------------------------------------------*
2039  *      usbd_find_descriptor
2040  *
2041  * This function will lookup the first descriptor that matches the
2042  * criteria given by the arguments "type" and "subtype". Descriptors
2043  * will only be searched within the interface having the index
2044  * "iface_index".  If the "id" argument points to an USB descriptor,
2045  * it will be skipped before the search is started. This allows
2046  * searching for multiple descriptors using the same criteria. Else
2047  * the search is started after the interface descriptor.
2048  *
2049  * Return values:
2050  *   NULL: End of descriptors
2051  *   Else: A descriptor matching the criteria
2052  *------------------------------------------------------------------------*/
2053 void   *
2054 usbd_find_descriptor(struct usb_device *udev, void *id, uint8_t iface_index,
2055     uint8_t type, uint8_t type_mask,
2056     uint8_t subtype, uint8_t subtype_mask)
2057 {
2058         struct usb_descriptor *desc;
2059         struct usb_config_descriptor *cd;
2060         struct usb_interface *iface;
2061
2062         cd = usbd_get_config_descriptor(udev);
2063         if (cd == NULL) {
2064                 return (NULL);
2065         }
2066         if (id == NULL) {
2067                 iface = usbd_get_iface(udev, iface_index);
2068                 if (iface == NULL) {
2069                         return (NULL);
2070                 }
2071                 id = usbd_get_interface_descriptor(iface);
2072                 if (id == NULL) {
2073                         return (NULL);
2074                 }
2075         }
2076         desc = (void *)id;
2077
2078         while ((desc = usb_desc_foreach(cd, desc))) {
2079
2080                 if (desc->bDescriptorType == UDESC_INTERFACE) {
2081                         break;
2082                 }
2083                 if (((desc->bDescriptorType & type_mask) == type) &&
2084                     ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2085                         return (desc);
2086                 }
2087         }
2088         return (NULL);
2089 }
2090
2091 /*------------------------------------------------------------------------*
2092  *      usb_devinfo
2093  *
2094  * This function will dump information from the device descriptor
2095  * belonging to the USB device pointed to by "udev", to the string
2096  * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2097  * including the terminating zero.
2098  *------------------------------------------------------------------------*/
2099 void
2100 usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
2101 {
2102         struct usb_device_descriptor *udd = &udev->ddesc;
2103         uint16_t bcdDevice;
2104         uint16_t bcdUSB;
2105
2106         bcdUSB = UGETW(udd->bcdUSB);
2107         bcdDevice = UGETW(udd->bcdDevice);
2108
2109         if (udd->bDeviceClass != 0xFF) {
2110                 snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2111                     "%x.%02x, addr %d",
2112                     udev->manufacturer, udev->product,
2113                     udd->bDeviceClass, udd->bDeviceSubClass,
2114                     (bcdUSB >> 8), bcdUSB & 0xFF,
2115                     (bcdDevice >> 8), bcdDevice & 0xFF,
2116                     udev->address);
2117         } else {
2118                 snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2119                     "%x.%02x, addr %d",
2120                     udev->manufacturer, udev->product,
2121                     (bcdUSB >> 8), bcdUSB & 0xFF,
2122                     (bcdDevice >> 8), bcdDevice & 0xFF,
2123                     udev->address);
2124         }
2125 }
2126
2127 #ifdef USB_VERBOSE
2128 /*
2129  * Descriptions of of known vendors and devices ("products").
2130  */
2131 struct usb_knowndev {
2132         uint16_t vendor;
2133         uint16_t product;
2134         uint32_t flags;
2135         const char *vendorname;
2136         const char *productname;
2137 };
2138
2139 #define USB_KNOWNDEV_NOPROD     0x01    /* match on vendor only */
2140
2141 #include "usbdevs.h"
2142 #include "usbdevs_data.h"
2143 #endif                                  /* USB_VERBOSE */
2144
2145 static void
2146 usbd_set_device_strings(struct usb_device *udev)
2147 {
2148         struct usb_device_descriptor *udd = &udev->ddesc;
2149 #ifdef USB_VERBOSE
2150         const struct usb_knowndev *kdp;
2151 #endif
2152         char temp[64];
2153         uint16_t vendor_id;
2154         uint16_t product_id;
2155
2156         vendor_id = UGETW(udd->idVendor);
2157         product_id = UGETW(udd->idProduct);
2158
2159         /* get serial number string */
2160         bzero(temp, sizeof(temp));
2161         usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2162             udev->ddesc.iSerialNumber);
2163         udev->serial = strdup(temp, M_USB);
2164
2165         /* get manufacturer string */
2166         bzero(temp, sizeof(temp));
2167         usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2168             udev->ddesc.iManufacturer);
2169         usb_trim_spaces(temp);
2170         if (temp[0] != '\0')
2171                 udev->manufacturer = strdup(temp, M_USB);
2172
2173         /* get product string */
2174         bzero(temp, sizeof(temp));
2175         usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2176             udev->ddesc.iProduct);
2177         usb_trim_spaces(temp);
2178         if (temp[0] != '\0')
2179                 udev->product = strdup(temp, M_USB);
2180
2181 #ifdef USB_VERBOSE
2182         if (udev->manufacturer == NULL || udev->product == NULL) {
2183                 for (kdp = usb_knowndevs; kdp->vendorname != NULL; kdp++) {
2184                         if (kdp->vendor == vendor_id &&
2185                             (kdp->product == product_id ||
2186                             (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2187                                 break;
2188                 }
2189                 if (kdp->vendorname != NULL) {
2190                         /* XXX should use pointer to knowndevs string */
2191                         if (udev->manufacturer == NULL) {
2192                                 udev->manufacturer = strdup(kdp->vendorname,
2193                                     M_USB);
2194                         }
2195                         if (udev->product == NULL &&
2196                             (kdp->flags & USB_KNOWNDEV_NOPROD) == 0) {
2197                                 udev->product = strdup(kdp->productname,
2198                                     M_USB);
2199                         }
2200                 }
2201         }
2202 #endif
2203         /* Provide default strings if none were found */
2204         if (udev->manufacturer == NULL) {
2205                 snprintf(temp, sizeof(temp), "vendor 0x%04x", vendor_id);
2206                 udev->manufacturer = strdup(temp, M_USB);
2207         }
2208         if (udev->product == NULL) {
2209                 snprintf(temp, sizeof(temp), "product 0x%04x", product_id);
2210                 udev->product = strdup(temp, M_USB);
2211         }
2212 }
2213
2214 /*
2215  * Returns:
2216  * See: USB_MODE_XXX
2217  */
2218 enum usb_hc_mode
2219 usbd_get_mode(struct usb_device *udev)
2220 {
2221         return (udev->flags.usb_mode);
2222 }
2223
2224 /*
2225  * Returns:
2226  * See: USB_SPEED_XXX
2227  */
2228 enum usb_dev_speed
2229 usbd_get_speed(struct usb_device *udev)
2230 {
2231         return (udev->speed);
2232 }
2233
2234 uint32_t
2235 usbd_get_isoc_fps(struct usb_device *udev)
2236 {
2237         ;                               /* indent fix */
2238         switch (udev->speed) {
2239         case USB_SPEED_LOW:
2240         case USB_SPEED_FULL:
2241                 return (1000);
2242         default:
2243                 return (8000);
2244         }
2245 }
2246
2247 struct usb_device_descriptor *
2248 usbd_get_device_descriptor(struct usb_device *udev)
2249 {
2250         if (udev == NULL)
2251                 return (NULL);          /* be NULL safe */
2252         return (&udev->ddesc);
2253 }
2254
2255 struct usb_config_descriptor *
2256 usbd_get_config_descriptor(struct usb_device *udev)
2257 {
2258         if (udev == NULL)
2259                 return (NULL);          /* be NULL safe */
2260         return (udev->cdesc);
2261 }
2262
2263 /*------------------------------------------------------------------------*
2264  *      usb_test_quirk - test a device for a given quirk
2265  *
2266  * Return values:
2267  * 0: The USB device does not have the given quirk.
2268  * Else: The USB device has the given quirk.
2269  *------------------------------------------------------------------------*/
2270 uint8_t
2271 usb_test_quirk(const struct usb_attach_arg *uaa, uint16_t quirk)
2272 {
2273         uint8_t found;
2274
2275         found = (usb_test_quirk_p) (&uaa->info, quirk);
2276         return (found);
2277 }
2278
2279 struct usb_interface_descriptor *
2280 usbd_get_interface_descriptor(struct usb_interface *iface)
2281 {
2282         if (iface == NULL)
2283                 return (NULL);          /* be NULL safe */
2284         return (iface->idesc);
2285 }
2286
2287 uint8_t
2288 usbd_get_interface_altindex(struct usb_interface *iface)
2289 {
2290         return (iface->alt_index);
2291 }
2292
2293 uint8_t
2294 usbd_get_bus_index(struct usb_device *udev)
2295 {
2296         return ((uint8_t)device_get_unit(udev->bus->bdev));
2297 }
2298
2299 uint8_t
2300 usbd_get_device_index(struct usb_device *udev)
2301 {
2302         return (udev->device_index);
2303 }
2304
2305 #if USB_HAVE_UGEN
2306 /*------------------------------------------------------------------------*
2307  *      usb_notify_addq
2308  *
2309  * This function will generate events for dev.
2310  *------------------------------------------------------------------------*/
2311 static void
2312 usb_notify_addq(const char *type, struct usb_device *udev)
2313 {
2314         char *data = NULL;
2315         struct malloc_type *mt;
2316
2317         mtx_lock(&malloc_mtx);
2318         mt = malloc_desc2type("bus");   /* XXX M_BUS */
2319         mtx_unlock(&malloc_mtx);
2320         if (mt == NULL)
2321                 return;
2322
2323         data = malloc(512, mt, M_NOWAIT);
2324         if (data == NULL)
2325                 return;
2326
2327         /* String it all together. */
2328         snprintf(data, 1024,
2329             "%s"
2330             "%s "
2331             "vendor=0x%04x "
2332             "product=0x%04x "
2333             "devclass=0x%02x "
2334             "devsubclass=0x%02x "
2335             "sernum=\"%s\" "
2336             "release=0x%04x "
2337             "at "
2338             "port=%u "
2339             "on "
2340             "%s\n",
2341             type,
2342             udev->ugen_name,
2343             UGETW(udev->ddesc.idVendor),
2344             UGETW(udev->ddesc.idProduct),
2345             udev->ddesc.bDeviceClass,
2346             udev->ddesc.bDeviceSubClass,
2347             udev->serial,
2348             UGETW(udev->ddesc.bcdDevice),
2349             udev->port_no,
2350             udev->parent_hub != NULL ?
2351                 udev->parent_hub->ugen_name :
2352                 device_get_nameunit(device_get_parent(udev->bus->bdev)));
2353
2354         devctl_queue_data(data);
2355 }
2356
2357 /*------------------------------------------------------------------------*
2358  *      usb_fifo_free_wrap
2359  *
2360  * This function will free the FIFOs.
2361  *
2362  * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2363  * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2364  * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2365  * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2366  * control endpoint FIFOs. If "iface_index" is not set to
2367  * "USB_IFACE_INDEX_ANY" the flag has no effect.
2368  *------------------------------------------------------------------------*/
2369 static void
2370 usb_fifo_free_wrap(struct usb_device *udev,
2371     uint8_t iface_index, uint8_t flag)
2372 {
2373         struct usb_fifo *f;
2374         uint16_t i;
2375
2376         /*
2377          * Free any USB FIFOs on the given interface:
2378          */
2379         for (i = 0; i != USB_FIFO_MAX; i++) {
2380                 f = udev->fifo[i];
2381                 if (f == NULL) {
2382                         continue;
2383                 }
2384                 /* Check if the interface index matches */
2385                 if (iface_index == f->iface_index) {
2386                         if (f->methods != &usb_ugen_methods) {
2387                                 /*
2388                                  * Don't free any non-generic FIFOs in
2389                                  * this case.
2390                                  */
2391                                 continue;
2392                         }
2393                         if ((f->dev_ep_index == 0) &&
2394                             (f->fs_xfer == NULL)) {
2395                                 /* no need to free this FIFO */
2396                                 continue;
2397                         }
2398                 } else if (iface_index == USB_IFACE_INDEX_ANY) {
2399                         if ((f->methods == &usb_ugen_methods) &&
2400                             (f->dev_ep_index == 0) &&
2401                             (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2402                             (f->fs_xfer == NULL)) {
2403                                 /* no need to free this FIFO */
2404                                 continue;
2405                         }
2406                 } else {
2407                         /* no need to free this FIFO */
2408                         continue;
2409                 }
2410                 /* free this FIFO */
2411                 usb_fifo_free(f);
2412         }
2413 }
2414 #endif
2415
2416 /*------------------------------------------------------------------------*
2417  *      usb_peer_can_wakeup
2418  *
2419  * Return values:
2420  * 0: Peer cannot do resume signalling.
2421  * Else: Peer can do resume signalling.
2422  *------------------------------------------------------------------------*/
2423 uint8_t
2424 usb_peer_can_wakeup(struct usb_device *udev)
2425 {
2426         const struct usb_config_descriptor *cdp;
2427
2428         cdp = udev->cdesc;
2429         if ((cdp != NULL) && (udev->flags.usb_mode == USB_MODE_HOST)) {
2430                 return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2431         }
2432         return (0);                     /* not supported */
2433 }
2434
2435 void
2436 usb_set_device_state(struct usb_device *udev, enum usb_dev_state state)
2437 {
2438
2439         KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2440
2441         DPRINTF("udev %p state %s -> %s\n", udev,
2442             usb_statestr(udev->state), usb_statestr(state));
2443         udev->state = state;
2444 }
2445
2446 uint8_t
2447 usbd_device_attached(struct usb_device *udev)
2448 {
2449         return (udev->state > USB_STATE_DETACHED);
2450 }
2451
2452 /* The following function locks enumerating the given USB device. */
2453
2454 void
2455 usbd_enum_lock(struct usb_device *udev)
2456 {
2457         sx_xlock(udev->default_sx + 1);
2458         /* 
2459          * NEWBUS LOCK NOTE: We should check if any parent SX locks
2460          * are locked before locking Giant. Else the lock can be
2461          * locked multiple times.
2462          */
2463         mtx_lock(&Giant);
2464 }
2465
2466 /* The following function unlocks enumerating the given USB device. */
2467
2468 void
2469 usbd_enum_unlock(struct usb_device *udev)
2470 {
2471         mtx_unlock(&Giant);
2472         sx_xunlock(udev->default_sx + 1);
2473 }
2474
2475 /*
2476  * The following function checks the enumerating lock for the given
2477  * USB device.
2478  */
2479
2480 uint8_t
2481 usbd_enum_is_locked(struct usb_device *udev)
2482 {
2483         return (sx_xlocked(udev->default_sx + 1));
2484 }