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