The Design and Implementation of the FreeBSD Operating System, Second Edition
Now available: The Design and Implementation of the FreeBSD Operating System (Second Edition)


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]

FreeBSD/Linux Kernel Cross Reference
sys/dev/usb/usb_device.c

Version: -  FREEBSD  -  FREEBSD-13-STABLE  -  FREEBSD-13-0  -  FREEBSD-12-STABLE  -  FREEBSD-12-0  -  FREEBSD-11-STABLE  -  FREEBSD-11-0  -  FREEBSD-10-STABLE  -  FREEBSD-10-0  -  FREEBSD-9-STABLE  -  FREEBSD-9-0  -  FREEBSD-8-STABLE  -  FREEBSD-8-0  -  FREEBSD-7-STABLE  -  FREEBSD-7-0  -  FREEBSD-6-STABLE  -  FREEBSD-6-0  -  FREEBSD-5-STABLE  -  FREEBSD-5-0  -  FREEBSD-4-STABLE  -  FREEBSD-3-STABLE  -  FREEBSD22  -  l41  -  OPENBSD  -  linux-2.6  -  MK84  -  PLAN9  -  xnu-8792 
SearchContext: -  none  -  3  -  10 

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

Cache object: d19cab3b97897ec7acd1c5c7fecba689


[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ] [ list types ] [ track identifier ]


This page is part of the FreeBSD/Linux Linux Kernel Cross-Reference, and was automatically generated using a modified version of the LXR engine.