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