3 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
27 #include <sys/stdint.h>
28 #include <sys/stddef.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/types.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
35 #include <sys/linker_set.h>
36 #include <sys/module.h>
38 #include <sys/mutex.h>
39 #include <sys/condvar.h>
40 #include <sys/sysctl.h>
42 #include <sys/unistd.h>
43 #include <sys/callout.h>
44 #include <sys/malloc.h>
47 #include <sys/fcntl.h>
49 #include <dev/usb/usb.h>
50 #include <dev/usb/usbdi.h>
51 #include <dev/usb/usbdi_util.h>
52 #include <dev/usb/usb_ioctl.h>
55 #define USB_DEBUG_VAR usb_debug
57 #include <dev/usb/usb_core.h>
58 #include <dev/usb/usb_debug.h>
59 #include <dev/usb/usb_process.h>
60 #include <dev/usb/usb_device.h>
61 #include <dev/usb/usb_busdma.h>
62 #include <dev/usb/usb_transfer.h>
63 #include <dev/usb/usb_request.h>
64 #include <dev/usb/usb_dynamic.h>
65 #include <dev/usb/usb_hub.h>
66 #include <dev/usb/usb_util.h>
67 #include <dev/usb/usb_msctest.h>
69 #include <dev/usb/usb_dev.h>
70 #include <dev/usb/usb_generic.h>
73 #include <dev/usb/quirk/usb_quirk.h>
75 #include <dev/usb/usb_controller.h>
76 #include <dev/usb/usb_bus.h>
78 /* function prototypes */
80 static void usb_init_endpoint(struct usb_device *, uint8_t,
81 struct usb_endpoint_descriptor *, struct usb_endpoint *);
82 static void usb_unconfigure(struct usb_device *, uint8_t);
83 static void usb_detach_device(struct usb_device *, uint8_t, uint8_t);
84 static void usb_detach_device_sub(struct usb_device *, device_t *,
86 static uint8_t usb_probe_and_attach_sub(struct usb_device *,
87 struct usb_attach_arg *);
88 static void usb_init_attach_arg(struct usb_device *,
89 struct usb_attach_arg *);
90 static void usb_suspend_resume_sub(struct usb_device *, device_t,
92 static void usbd_clear_stall_proc(struct usb_proc_msg *_pm);
93 usb_error_t usb_config_parse(struct usb_device *, uint8_t, uint8_t);
94 static void usbd_set_device_strings(struct usb_device *);
96 static void usb_notify_addq(const char *type, struct usb_device *);
97 static void usb_fifo_free_wrap(struct usb_device *, uint8_t, uint8_t);
98 static struct cdev *usb_make_dev(struct usb_device *, int, int);
99 static void usb_cdev_create(struct usb_device *);
100 static void usb_cdev_free(struct usb_device *);
101 static void usb_cdev_cleanup(void *);
104 /* This variable is global to allow easy access to it: */
106 int usb_template = 0;
108 SYSCTL_INT(_hw_usb, OID_AUTO, template, CTLFLAG_RW,
109 &usb_template, 0, "Selected USB device side template");
111 static const char* statestr[USB_STATE_MAX] = {
112 [USB_STATE_DETACHED] = "DETACHED",
113 [USB_STATE_ATTACHED] = "ATTACHED",
114 [USB_STATE_POWERED] = "POWERED",
115 [USB_STATE_ADDRESSED] = "ADDRESSED",
116 [USB_STATE_CONFIGURED] = "CONFIGURED",
120 usb_statestr(enum usb_dev_state state)
122 return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
125 /*------------------------------------------------------------------------*
126 * usbd_get_ep_by_addr
128 * This function searches for an USB ep by endpoint address and
134 *------------------------------------------------------------------------*/
135 struct usb_endpoint *
136 usbd_get_ep_by_addr(struct usb_device *udev, uint8_t ea_val)
138 struct usb_endpoint *ep = udev->endpoints;
139 struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
141 EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
145 * According to the USB specification not all bits are used
146 * for the endpoint address. Keep defined bits only:
151 * Iterate accross all the USB endpoints searching for a match
152 * based on the endpoint address:
154 for (; ep != ep_end; ep++) {
156 if (ep->edesc == NULL) {
159 /* do the mask and check the value */
160 if ((ep->edesc->bEndpointAddress & EA_MASK) == ea_val) {
166 * The default endpoint is always present and is checked separately:
168 if ((udev->default_ep.edesc) &&
169 ((udev->default_ep.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
170 ep = &udev->default_ep;
179 /*------------------------------------------------------------------------*
182 * This function searches for an USB endpoint based on the information
183 * given by the passed "struct usb_config" pointer.
187 * Else: Pointer to "struct usb_endpoint".
188 *------------------------------------------------------------------------*/
189 struct usb_endpoint *
190 usbd_get_endpoint(struct usb_device *udev, uint8_t iface_index,
191 const struct usb_config *setup)
193 struct usb_endpoint *ep = udev->endpoints;
194 struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
195 uint8_t index = setup->ep_index;
201 DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
202 "type=0x%x dir=0x%x index=%d\n",
203 udev, iface_index, setup->endpoint,
204 setup->type, setup->direction, setup->ep_index);
208 if (setup->usb_mode != USB_MODE_DUAL &&
209 udev->flags.usb_mode != setup->usb_mode) {
210 /* wrong mode - no endpoint */
214 /* setup expected endpoint direction mask and value */
216 if (setup->direction == UE_DIR_RX) {
217 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
218 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
219 UE_DIR_OUT : UE_DIR_IN;
220 } else if (setup->direction == UE_DIR_TX) {
221 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
222 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
223 UE_DIR_IN : UE_DIR_OUT;
224 } else if (setup->direction == UE_DIR_ANY) {
225 /* match any endpoint direction */
229 /* match the given endpoint direction */
230 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
231 ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
234 /* setup expected endpoint address */
236 if (setup->endpoint == UE_ADDR_ANY) {
237 /* match any endpoint address */
239 /* match the given endpoint address */
241 ea_val |= (setup->endpoint & UE_ADDR);
244 /* setup expected endpoint type */
246 if (setup->type == UE_BULK_INTR) {
247 /* this will match BULK and INTERRUPT endpoints */
250 } else if (setup->type == UE_TYPE_ANY) {
251 /* match any endpoint type */
255 /* match the given endpoint type */
256 type_mask = UE_XFERTYPE;
257 type_val = (setup->type & UE_XFERTYPE);
261 * Iterate accross all the USB endpoints searching for a match
262 * based on the endpoint address. Note that we are searching
263 * the endpoints from the beginning of the "udev->endpoints" array.
265 for (; ep != ep_end; ep++) {
267 if ((ep->edesc == NULL) ||
268 (ep->iface_index != iface_index)) {
271 /* do the masks and check the values */
273 if (((ep->edesc->bEndpointAddress & ea_mask) == ea_val) &&
274 ((ep->edesc->bmAttributes & type_mask) == type_val)) {
282 * Match against default endpoint last, so that "any endpoint", "any
283 * address" and "any direction" returns the first endpoint of the
284 * interface. "iface_index" and "direction" is ignored:
286 if ((udev->default_ep.edesc) &&
287 ((udev->default_ep.edesc->bEndpointAddress & ea_mask) == ea_val) &&
288 ((udev->default_ep.edesc->bmAttributes & type_mask) == type_val) &&
290 ep = &udev->default_ep;
299 /*------------------------------------------------------------------------*
300 * usbd_interface_count
302 * This function stores the number of USB interfaces excluding
303 * alternate settings, which the USB config descriptor reports into
304 * the unsigned 8-bit integer pointed to by "count".
309 *------------------------------------------------------------------------*/
311 usbd_interface_count(struct usb_device *udev, uint8_t *count)
313 if (udev->cdesc == NULL) {
315 return (USB_ERR_NOT_CONFIGURED);
317 *count = udev->ifaces_max;
318 return (USB_ERR_NORMAL_COMPLETION);
322 /*------------------------------------------------------------------------*
325 * This function will initialise the USB endpoint structure pointed to by
326 * the "endpoint" argument. The structure pointed to by "endpoint" must be
327 * zeroed before calling this function.
328 *------------------------------------------------------------------------*/
330 usb_init_endpoint(struct usb_device *udev, uint8_t iface_index,
331 struct usb_endpoint_descriptor *edesc, struct usb_endpoint *ep)
333 struct usb_bus_methods *methods;
335 methods = udev->bus->methods;
337 (methods->endpoint_init) (udev, edesc, ep);
339 /* initialise USB endpoint structure */
341 ep->iface_index = iface_index;
342 TAILQ_INIT(&ep->endpoint_q.head);
343 ep->endpoint_q.command = &usbd_pipe_start;
345 /* the pipe is not supported by the hardware */
346 if (ep->methods == NULL)
349 /* clear stall, if any */
350 if (methods->clear_stall != NULL) {
351 USB_BUS_LOCK(udev->bus);
352 (methods->clear_stall) (udev, ep);
353 USB_BUS_UNLOCK(udev->bus);
357 /*-----------------------------------------------------------------------*
358 * usb_endpoint_foreach
360 * This function will iterate all the USB endpoints except the control
361 * endpoint. This function is NULL safe.
364 * NULL: End of USB endpoints
365 * Else: Pointer to next USB endpoint
366 *------------------------------------------------------------------------*/
367 struct usb_endpoint *
368 usb_endpoint_foreach(struct usb_device *udev, struct usb_endpoint *ep)
370 struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
376 /* get next endpoint */
378 ep = udev->endpoints;
382 /* find next allocated ep */
383 while (ep != ep_end) {
384 if (ep->edesc != NULL)
391 /*------------------------------------------------------------------------*
394 * This function will free all USB interfaces and USB endpoints belonging
397 * Flag values, see "USB_UNCFG_FLAG_XXX".
398 *------------------------------------------------------------------------*/
400 usb_unconfigure(struct usb_device *udev, uint8_t flag)
404 /* automatic locking */
405 if (usbd_enum_is_locked(udev)) {
409 usbd_enum_lock(udev);
412 /* detach all interface drivers */
413 usb_detach_device(udev, USB_IFACE_INDEX_ANY, flag);
416 /* free all FIFOs except control endpoint FIFOs */
417 usb_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, flag);
420 * Free all cdev's, if any.
425 #if USB_HAVE_COMPAT_LINUX
426 /* free Linux compat device, if any */
427 if (udev->linux_endpoint_start) {
428 usb_linux_free_device(udev);
429 udev->linux_endpoint_start = NULL;
433 usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_FREE);
435 /* free "cdesc" after "ifaces" and "endpoints", if any */
436 if (udev->cdesc != NULL) {
437 if (udev->flags.usb_mode != USB_MODE_DEVICE)
438 free(udev->cdesc, M_USB);
441 /* set unconfigured state */
442 udev->curr_config_no = USB_UNCONFIG_NO;
443 udev->curr_config_index = USB_UNCONFIG_INDEX;
446 usbd_enum_unlock(udev);
449 /*------------------------------------------------------------------------*
450 * usbd_set_config_index
452 * This function selects configuration by index, independent of the
453 * actual configuration number. This function should not be used by
459 *------------------------------------------------------------------------*/
461 usbd_set_config_index(struct usb_device *udev, uint8_t index)
463 struct usb_status ds;
464 struct usb_config_descriptor *cdp;
471 DPRINTFN(6, "udev=%p index=%d\n", udev, index);
473 /* automatic locking */
474 if (usbd_enum_is_locked(udev)) {
478 usbd_enum_lock(udev);
481 usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_SUBDEV);
483 if (index == USB_UNCONFIG_INDEX) {
485 * Leave unallocated when unconfiguring the
486 * device. "usb_unconfigure()" will also reset
487 * the current config number and index.
489 err = usbd_req_set_config(udev, NULL, USB_UNCONFIG_NO);
490 if (udev->state == USB_STATE_CONFIGURED)
491 usb_set_device_state(udev, USB_STATE_ADDRESSED);
494 /* get the full config descriptor */
495 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
496 /* save some memory */
497 err = usbd_req_get_descriptor_ptr(udev, &cdp,
498 (UDESC_CONFIG << 8) | index);
501 err = usbd_req_get_config_desc_full(udev,
502 NULL, &cdp, M_USB, index);
507 /* set the new config descriptor */
511 /* Figure out if the device is self or bus powered. */
513 if ((!udev->flags.uq_bus_powered) &&
514 (cdp->bmAttributes & UC_SELF_POWERED) &&
515 (udev->flags.usb_mode == USB_MODE_HOST)) {
516 /* May be self powered. */
517 if (cdp->bmAttributes & UC_BUS_POWERED) {
518 /* Must ask device. */
519 err = usbd_req_get_device_status(udev, NULL, &ds);
521 DPRINTFN(0, "could not read "
522 "device status: %s\n",
524 } else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
527 DPRINTF("status=0x%04x \n",
532 DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
533 "selfpowered=%d, power=%d\n",
535 udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
536 selfpowered, cdp->bMaxPower * 2);
538 /* Check if we have enough power. */
539 power = cdp->bMaxPower * 2;
541 if (udev->parent_hub) {
542 max_power = udev->parent_hub->hub->portpower;
544 max_power = USB_MAX_POWER;
547 if (power > max_power) {
548 DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
549 err = USB_ERR_NO_POWER;
552 /* Only update "self_powered" in USB Host Mode */
553 if (udev->flags.usb_mode == USB_MODE_HOST) {
554 udev->flags.self_powered = selfpowered;
557 udev->curr_config_no = cdp->bConfigurationValue;
558 udev->curr_config_index = index;
559 usb_set_device_state(udev, USB_STATE_CONFIGURED);
561 /* Set the actual configuration value. */
562 err = usbd_req_set_config(udev, NULL, cdp->bConfigurationValue);
567 err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_ALLOC);
572 err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_INIT);
578 /* create device nodes for each endpoint */
579 usb_cdev_create(udev);
583 DPRINTF("error=%s\n", usbd_errstr(err));
585 usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_SUBDEV);
588 usbd_enum_unlock(udev);
592 /*------------------------------------------------------------------------*
595 * This function will allocate and free USB interfaces and USB endpoints,
596 * parse the USB configuration structure and initialise the USB endpoints
597 * and interfaces. If "iface_index" is not equal to
598 * "USB_IFACE_INDEX_ANY" then the "cmd" parameter is the
599 * alternate_setting to be selected for the given interface. Else the
600 * "cmd" parameter is defined by "USB_CFG_XXX". "iface_index" can be
601 * "USB_IFACE_INDEX_ANY" or a valid USB interface index. This function
602 * is typically called when setting the configuration or when setting
603 * an alternate interface.
608 *------------------------------------------------------------------------*/
610 usb_config_parse(struct usb_device *udev, uint8_t iface_index, uint8_t cmd)
612 struct usb_idesc_parse_state ips;
613 struct usb_interface_descriptor *id;
614 struct usb_endpoint_descriptor *ed;
615 struct usb_interface *iface;
616 struct usb_endpoint *ep;
624 if (iface_index != USB_IFACE_INDEX_ANY) {
625 /* parameter overload */
635 DPRINTFN(5, "iface_index=%d cmd=%d\n",
638 if (cmd == USB_CFG_FREE)
641 if (cmd == USB_CFG_INIT) {
642 sx_assert(udev->default_sx + 1, SA_LOCKED);
644 /* check for in-use endpoints */
646 ep = udev->endpoints;
647 ep_max = udev->endpoints_max;
649 /* look for matching endpoints */
650 if ((iface_index == USB_IFACE_INDEX_ANY) ||
651 (iface_index == ep->iface_index)) {
652 if (ep->refcount != 0) {
654 * This typically indicates a
655 * more serious error.
657 err = USB_ERR_IN_USE;
660 memset(ep, 0, sizeof(*ep));
661 /* make sure we don't zero the endpoint again */
662 ep->iface_index = USB_IFACE_INDEX_ANY;
672 memset(&ips, 0, sizeof(ips));
677 while ((id = usb_idesc_foreach(udev->cdesc, &ips))) {
679 /* check for interface overflow */
680 if (ips.iface_index == USB_IFACE_MAX)
683 iface = udev->ifaces + ips.iface_index;
685 /* check for specific interface match */
687 if (cmd == USB_CFG_INIT) {
688 if ((iface_index != USB_IFACE_INDEX_ANY) &&
689 (iface_index != ips.iface_index)) {
690 /* wrong interface */
692 } else if (alt_index != ips.iface_index_alt) {
693 /* wrong alternate setting */
696 /* initialise interface */
702 /* check for new interface */
703 if (ips.iface_index_alt == 0) {
704 /* update current number of endpoints */
709 /* setup the USB interface structure */
711 /* default setting */
712 iface->parent_iface_index = USB_IFACE_INDEX_ANY;
713 /* set alternate index */
714 iface->alt_index = alt_index;
717 DPRINTFN(5, "found idesc nendpt=%d\n", id->bNumEndpoints);
719 ed = (struct usb_endpoint_descriptor *)id;
723 /* iterate all the endpoint descriptors */
724 while ((ed = usb_edesc_foreach(udev->cdesc, ed))) {
726 if (temp == USB_EP_MAX)
729 ep = udev->endpoints + temp;
732 usb_init_endpoint(udev,
733 ips.iface_index, ed, ep);
738 /* find maximum number of endpoints */
743 id = (struct usb_interface_descriptor *)ed;
747 /* NOTE: It is valid to have no interfaces and no endpoints! */
749 if (cmd == USB_CFG_ALLOC) {
750 udev->ifaces_max = ips.iface_index;
752 if (udev->ifaces_max != 0) {
753 udev->ifaces = malloc(sizeof(*iface) * udev->ifaces_max,
754 M_USB, M_WAITOK | M_ZERO);
755 if (udev->ifaces == NULL) {
761 udev->endpoints = malloc(sizeof(*ep) * ep_max,
762 M_USB, M_WAITOK | M_ZERO);
763 if (udev->endpoints == NULL) {
768 udev->endpoints = NULL;
770 USB_BUS_LOCK(udev->bus);
771 udev->endpoints_max = ep_max;
772 /* reset any ongoing clear-stall */
773 udev->ep_curr = NULL;
774 USB_BUS_UNLOCK(udev->bus);
779 if (cmd == USB_CFG_ALLOC) {
781 USB_BUS_LOCK(udev->bus);
782 udev->endpoints_max = 0;
783 /* reset any ongoing clear-stall */
784 udev->ep_curr = NULL;
785 USB_BUS_UNLOCK(udev->bus);
788 if (udev->ifaces != NULL)
789 free(udev->ifaces, M_USB);
790 if (udev->endpoints != NULL)
791 free(udev->endpoints, M_USB);
794 udev->endpoints = NULL;
795 udev->ifaces_max = 0;
801 /*------------------------------------------------------------------------*
802 * usbd_set_alt_interface_index
804 * This function will select an alternate interface index for the
805 * given interface index. The interface should not be in use when this
806 * function is called. That means there should not be any open USB
807 * transfers. Else an error is returned. If the alternate setting is
808 * already set this function will simply return success. This function
809 * is called in Host mode and Device mode!
814 *------------------------------------------------------------------------*/
816 usbd_set_alt_interface_index(struct usb_device *udev,
817 uint8_t iface_index, uint8_t alt_index)
819 struct usb_interface *iface = usbd_get_iface(udev, iface_index);
823 /* automatic locking */
824 if (usbd_enum_is_locked(udev)) {
828 usbd_enum_lock(udev);
834 if (iface->alt_index == alt_index) {
836 * Optimise away duplicate setting of
837 * alternate setting in USB Host Mode!
844 * Free all generic FIFOs for this interface, except control
847 usb_fifo_free_wrap(udev, iface_index, 0);
850 err = usb_config_parse(udev, iface_index, alt_index);
854 if (iface->alt_index != alt_index) {
855 /* the alternate setting does not exist */
860 err = usbd_req_set_alt_interface_no(udev, NULL, iface_index,
861 iface->idesc->bAlternateSetting);
865 usbd_enum_unlock(udev);
870 /*------------------------------------------------------------------------*
871 * usbd_set_endpoint_stall
873 * This function is used to make a BULK or INTERRUPT endpoint
879 *------------------------------------------------------------------------*/
881 usbd_set_endpoint_stall(struct usb_device *udev, struct usb_endpoint *ep,
884 struct usb_xfer *xfer;
890 DPRINTF("Cannot find endpoint\n");
892 * Pretend that the clear or set stall request is
893 * successful else some USB host stacks can do
894 * strange things, especially when a control endpoint
899 et = (ep->edesc->bmAttributes & UE_XFERTYPE);
901 if ((et != UE_BULK) &&
902 (et != UE_INTERRUPT)) {
904 * Should not stall control
905 * nor isochronous endpoints.
907 DPRINTF("Invalid endpoint\n");
910 USB_BUS_LOCK(udev->bus);
912 /* store current stall state */
913 was_stalled = ep->is_stalled;
915 /* check for no change */
916 if (was_stalled && do_stall) {
917 /* if the endpoint is already stalled do nothing */
918 USB_BUS_UNLOCK(udev->bus);
919 DPRINTF("No change\n");
922 /* set stalled state */
925 if (do_stall || (!was_stalled)) {
927 /* lookup the current USB transfer, if any */
928 xfer = ep->endpoint_q.curr;
934 * If "xfer" is non-NULL the "set_stall" method will
935 * complete the USB transfer like in case of a timeout
936 * setting the error code "USB_ERR_STALLED".
938 (udev->bus->methods->set_stall) (udev, xfer, ep, &do_stall);
941 ep->toggle_next = 0; /* reset data toggle */
942 ep->is_stalled = 0; /* clear stalled state */
944 (udev->bus->methods->clear_stall) (udev, ep);
946 /* start up the current or next transfer, if any */
947 usb_command_wrapper(&ep->endpoint_q, ep->endpoint_q.curr);
949 USB_BUS_UNLOCK(udev->bus);
953 /*------------------------------------------------------------------------*
954 * usb_reset_iface_endpoints - used in USB device side mode
955 *------------------------------------------------------------------------*/
957 usb_reset_iface_endpoints(struct usb_device *udev, uint8_t iface_index)
959 struct usb_endpoint *ep;
960 struct usb_endpoint *ep_end;
962 ep = udev->endpoints;
963 ep_end = udev->endpoints + udev->endpoints_max;
965 for (; ep != ep_end; ep++) {
967 if ((ep->edesc == NULL) ||
968 (ep->iface_index != iface_index)) {
971 /* simulate a clear stall from the peer */
972 usbd_set_endpoint_stall(udev, ep, 0);
977 /*------------------------------------------------------------------------*
978 * usb_detach_device_sub
980 * This function will try to detach an USB device. If it fails a panic
983 * Flag values, see "USB_UNCFG_FLAG_XXX".
984 *------------------------------------------------------------------------*/
986 usb_detach_device_sub(struct usb_device *udev, device_t *ppdev,
992 if (!(flag & USB_UNCFG_FLAG_FREE_SUBDEV)) {
999 * NOTE: It is important to clear "*ppdev" before deleting
1000 * the child due to some device methods being called late
1001 * during the delete process !
1006 device_printf(dev, "at %s, port %d, addr %d "
1008 device_get_nameunit(udev->parent_dev),
1009 udev->port_no, udev->address);
1011 if (device_is_attached(dev)) {
1012 if (udev->flags.peer_suspended) {
1013 err = DEVICE_RESUME(dev);
1015 device_printf(dev, "Resume failed!\n");
1018 if (device_detach(dev)) {
1022 if (device_delete_child(udev->parent_dev, dev)) {
1029 /* Detach is not allowed to fail in the USB world */
1030 panic("An USB driver would not detach!\n");
1033 /*------------------------------------------------------------------------*
1036 * The following function will detach the matching interfaces.
1037 * This function is NULL safe.
1039 * Flag values, see "USB_UNCFG_FLAG_XXX".
1040 *------------------------------------------------------------------------*/
1042 usb_detach_device(struct usb_device *udev, uint8_t iface_index,
1045 struct usb_interface *iface;
1052 DPRINTFN(4, "udev=%p\n", udev);
1054 sx_assert(udev->default_sx + 1, SA_LOCKED);
1057 * First detach the child to give the child's detach routine a
1058 * chance to detach the sub-devices in the correct order.
1059 * Then delete the child using "device_delete_child()" which
1060 * will detach all sub-devices from the bottom and upwards!
1062 if (iface_index != USB_IFACE_INDEX_ANY) {
1064 iface_index = i + 1;
1067 iface_index = USB_IFACE_MAX;
1072 for (; i != iface_index; i++) {
1074 iface = usbd_get_iface(udev, i);
1075 if (iface == NULL) {
1076 /* looks like the end of the USB interfaces */
1079 usb_detach_device_sub(udev, &iface->subdev, flag);
1083 /*------------------------------------------------------------------------*
1084 * usb_probe_and_attach_sub
1089 *------------------------------------------------------------------------*/
1091 usb_probe_and_attach_sub(struct usb_device *udev,
1092 struct usb_attach_arg *uaa)
1094 struct usb_interface *iface;
1099 if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
1100 /* leave interface alone */
1103 dev = iface->subdev;
1106 /* clean up after module unload */
1108 if (device_is_attached(dev)) {
1109 /* already a device there */
1112 /* clear "iface->subdev" as early as possible */
1114 iface->subdev = NULL;
1116 if (device_delete_child(udev->parent_dev, dev)) {
1119 * Panic here, else one can get a double call
1120 * to device_detach(). USB devices should
1121 * never fail on detach!
1123 panic("device_delete_child() failed!\n");
1126 if (uaa->temp_dev == NULL) {
1128 /* create a new child */
1129 uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1130 if (uaa->temp_dev == NULL) {
1131 device_printf(udev->parent_dev,
1132 "Device creation failed!\n");
1133 return (1); /* failure */
1135 device_set_ivars(uaa->temp_dev, uaa);
1136 device_quiet(uaa->temp_dev);
1139 * Set "subdev" before probe and attach so that "devd" gets
1140 * the information it needs.
1142 iface->subdev = uaa->temp_dev;
1144 if (device_probe_and_attach(iface->subdev) == 0) {
1146 * The USB attach arguments are only available during probe
1149 uaa->temp_dev = NULL;
1150 device_set_ivars(iface->subdev, NULL);
1152 if (udev->flags.peer_suspended) {
1153 err = DEVICE_SUSPEND(iface->subdev);
1155 device_printf(iface->subdev, "Suspend failed\n");
1157 return (0); /* success */
1159 /* No USB driver found */
1160 iface->subdev = NULL;
1162 return (1); /* failure */
1165 /*------------------------------------------------------------------------*
1166 * usbd_set_parent_iface
1168 * Using this function will lock the alternate interface setting on an
1169 * interface. It is typically used for multi interface drivers. In USB
1170 * device side mode it is assumed that the alternate interfaces all
1171 * have the same endpoint descriptors. The default parent index value
1172 * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1174 *------------------------------------------------------------------------*/
1176 usbd_set_parent_iface(struct usb_device *udev, uint8_t iface_index,
1177 uint8_t parent_index)
1179 struct usb_interface *iface;
1181 iface = usbd_get_iface(udev, iface_index);
1183 iface->parent_iface_index = parent_index;
1188 usb_init_attach_arg(struct usb_device *udev,
1189 struct usb_attach_arg *uaa)
1191 bzero(uaa, sizeof(*uaa));
1194 uaa->usb_mode = udev->flags.usb_mode;
1195 uaa->port = udev->port_no;
1197 uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1198 uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1199 uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1200 uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1201 uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1202 uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1203 uaa->info.bConfigIndex = udev->curr_config_index;
1204 uaa->info.bConfigNum = udev->curr_config_no;
1207 /*------------------------------------------------------------------------*
1208 * usb_probe_and_attach
1210 * This function is called from "uhub_explore_sub()",
1211 * "usb_handle_set_config()" and "usb_handle_request()".
1215 * Else: A control transfer failed
1216 *------------------------------------------------------------------------*/
1218 usb_probe_and_attach(struct usb_device *udev, uint8_t iface_index)
1220 struct usb_attach_arg uaa;
1221 struct usb_interface *iface;
1227 DPRINTF("udev == NULL\n");
1228 return (USB_ERR_INVAL);
1230 /* automatic locking */
1231 if (usbd_enum_is_locked(udev)) {
1235 usbd_enum_lock(udev);
1238 if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1239 /* do nothing - no configuration has been set */
1242 /* setup USB attach arguments */
1244 usb_init_attach_arg(udev, &uaa);
1246 /* Check if only one interface should be probed: */
1247 if (iface_index != USB_IFACE_INDEX_ANY) {
1255 /* Do the probe and attach */
1256 for (; i != j; i++) {
1258 iface = usbd_get_iface(udev, i);
1259 if (iface == NULL) {
1261 * Looks like the end of the USB
1264 DPRINTFN(2, "end of interfaces "
1268 if (iface->idesc == NULL) {
1269 /* no interface descriptor */
1274 uaa.info.bInterfaceClass =
1275 iface->idesc->bInterfaceClass;
1276 uaa.info.bInterfaceSubClass =
1277 iface->idesc->bInterfaceSubClass;
1278 uaa.info.bInterfaceProtocol =
1279 iface->idesc->bInterfaceProtocol;
1280 uaa.info.bIfaceIndex = i;
1281 uaa.info.bIfaceNum =
1282 iface->idesc->bInterfaceNumber;
1283 uaa.use_generic = 0;
1284 uaa.driver_info = 0; /* reset driver_info */
1286 DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1287 uaa.info.bInterfaceClass,
1288 uaa.info.bInterfaceSubClass,
1289 uaa.info.bInterfaceProtocol,
1290 uaa.info.bIfaceIndex,
1291 uaa.info.bIfaceNum);
1293 /* try specific interface drivers first */
1295 if (usb_probe_and_attach_sub(udev, &uaa)) {
1298 /* try generic interface drivers last */
1300 uaa.use_generic = 1;
1301 uaa.driver_info = 0; /* reset driver_info */
1303 if (usb_probe_and_attach_sub(udev, &uaa)) {
1309 /* remove the last created child; it is unused */
1311 if (device_delete_child(udev->parent_dev, uaa.temp_dev)) {
1312 DPRINTFN(0, "device delete child failed!\n");
1317 usbd_enum_unlock(udev);
1322 /*------------------------------------------------------------------------*
1323 * usb_suspend_resume_sub
1325 * This function is called when the suspend or resume methods should
1326 * be executed on an USB device.
1327 *------------------------------------------------------------------------*/
1329 usb_suspend_resume_sub(struct usb_device *udev, device_t dev, uint8_t do_suspend)
1336 if (!device_is_attached(dev)) {
1340 err = DEVICE_SUSPEND(dev);
1342 err = DEVICE_RESUME(dev);
1345 device_printf(dev, "%s failed!\n",
1346 do_suspend ? "Suspend" : "Resume");
1350 /*------------------------------------------------------------------------*
1351 * usb_suspend_resume
1353 * The following function will suspend or resume the USB device.
1358 *------------------------------------------------------------------------*/
1360 usb_suspend_resume(struct usb_device *udev, uint8_t do_suspend)
1362 struct usb_interface *iface;
1369 DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1371 sx_assert(udev->default_sx + 1, SA_LOCKED);
1373 USB_BUS_LOCK(udev->bus);
1374 /* filter the suspend events */
1375 if (udev->flags.peer_suspended == do_suspend) {
1376 USB_BUS_UNLOCK(udev->bus);
1380 udev->flags.peer_suspended = do_suspend;
1381 USB_BUS_UNLOCK(udev->bus);
1383 /* do the suspend or resume */
1385 for (i = 0; i != USB_IFACE_MAX; i++) {
1387 iface = usbd_get_iface(udev, i);
1388 if (iface == NULL) {
1389 /* looks like the end of the USB interfaces */
1392 usb_suspend_resume_sub(udev, iface->subdev, do_suspend);
1397 /*------------------------------------------------------------------------*
1398 * usbd_clear_stall_proc
1400 * This function performs generic USB clear stall operations.
1401 *------------------------------------------------------------------------*/
1403 usbd_clear_stall_proc(struct usb_proc_msg *_pm)
1405 struct usb_clear_stall_msg *pm = (void *)_pm;
1406 struct usb_device *udev = pm->udev;
1409 USB_BUS_UNLOCK(udev->bus);
1410 mtx_lock(udev->default_mtx);
1412 /* Start clear stall callback */
1413 usbd_transfer_start(udev->default_xfer[1]);
1416 mtx_unlock(udev->default_mtx);
1417 USB_BUS_LOCK(udev->bus);
1420 /*------------------------------------------------------------------------*
1423 * This function allocates a new USB device. This function is called
1424 * when a new device has been put in the powered state, but not yet in
1425 * the addressed state. Get initial descriptor, set the address, get
1426 * full descriptor and get strings.
1431 *------------------------------------------------------------------------*/
1433 usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
1434 struct usb_device *parent_hub, uint8_t depth, uint8_t port_index,
1435 uint8_t port_no, enum usb_dev_speed speed, enum usb_hc_mode mode)
1437 struct usb_attach_arg uaa;
1438 struct usb_device *udev;
1439 struct usb_device *adev;
1440 struct usb_device *hub;
1441 uint8_t *scratch_ptr;
1442 uint32_t scratch_size;
1444 uint8_t device_index;
1446 DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1447 "port_index=%u, port_no=%u, speed=%u, usb_mode=%u\n",
1448 parent_dev, bus, parent_hub, depth, port_index, port_no,
1452 * Find an unused device index. In USB Host mode this is the
1453 * same as the device address.
1455 * Device index zero is not used and device index 1 should
1456 * always be the root hub.
1458 for (device_index = USB_ROOT_HUB_ADDR;
1459 (device_index != bus->devices_max) &&
1460 (bus->devices[device_index] != NULL);
1461 device_index++) /* nop */;
1463 if (device_index == bus->devices_max) {
1464 device_printf(bus->bdev,
1465 "No free USB device index for new device!\n");
1470 device_printf(bus->bdev,
1471 "Invalid device depth!\n");
1474 udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1478 /* initialise our SX-lock */
1479 sx_init(udev->default_sx, "0123456789ABCDEF - USB device SX lock" + depth);
1481 /* initialise our SX-lock */
1482 sx_init(udev->default_sx + 1, "0123456789ABCDEF - USB config SX lock" + depth);
1484 cv_init(udev->default_cv, "WCTRL");
1485 cv_init(udev->default_cv + 1, "UGONE");
1487 /* initialise our mutex */
1488 mtx_init(udev->default_mtx, "USB device mutex", NULL, MTX_DEF);
1490 /* initialise generic clear stall */
1491 udev->cs_msg[0].hdr.pm_callback = &usbd_clear_stall_proc;
1492 udev->cs_msg[0].udev = udev;
1493 udev->cs_msg[1].hdr.pm_callback = &usbd_clear_stall_proc;
1494 udev->cs_msg[1].udev = udev;
1496 /* initialise some USB device fields */
1497 udev->parent_hub = parent_hub;
1498 udev->parent_dev = parent_dev;
1499 udev->port_index = port_index;
1500 udev->port_no = port_no;
1501 udev->depth = depth;
1503 udev->address = USB_START_ADDR; /* default value */
1504 udev->plugtime = (usb_ticks_t)ticks;
1505 usb_set_device_state(udev, USB_STATE_POWERED);
1507 * We need to force the power mode to "on" because there are plenty
1508 * of USB devices out there that do not work very well with
1509 * automatic suspend and resume!
1511 udev->power_mode = USB_POWER_MODE_ON;
1512 udev->pwr_save.last_xfer_time = ticks;
1513 /* we are not ready yet */
1516 /* set up default endpoint descriptor */
1517 udev->default_ep_desc.bLength = sizeof(udev->default_ep_desc);
1518 udev->default_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1519 udev->default_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1520 udev->default_ep_desc.bmAttributes = UE_CONTROL;
1521 udev->default_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1522 udev->default_ep_desc.wMaxPacketSize[1] = 0;
1523 udev->default_ep_desc.bInterval = 0;
1524 udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1526 udev->speed = speed;
1527 udev->flags.usb_mode = mode;
1529 /* search for our High Speed USB HUB, if any */
1532 hub = udev->parent_hub;
1535 if (hub->speed == USB_SPEED_HIGH) {
1536 udev->hs_hub_addr = hub->address;
1537 udev->parent_hs_hub = hub;
1538 udev->hs_port_no = adev->port_no;
1542 hub = hub->parent_hub;
1545 /* init the default endpoint */
1546 usb_init_endpoint(udev, 0,
1547 &udev->default_ep_desc,
1550 /* set device index */
1551 udev->device_index = device_index;
1554 /* Create ugen name */
1555 snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1556 USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1558 LIST_INIT(&udev->pd_list);
1560 /* Create the control endpoint device */
1561 udev->default_dev = usb_make_dev(udev, 0, FREAD|FWRITE);
1563 /* Create a link from /dev/ugenX.X to the default endpoint */
1564 make_dev_alias(udev->default_dev, udev->ugen_name);
1566 if (udev->flags.usb_mode == USB_MODE_HOST) {
1568 err = usbd_req_set_address(udev, NULL, device_index);
1570 /* This is the new USB device address from now on */
1572 udev->address = device_index;
1575 * We ignore any set-address errors, hence there are
1576 * buggy USB devices out there that actually receive
1577 * the SETUP PID, but manage to set the address before
1578 * the STATUS stage is ACK'ed. If the device responds
1579 * to the subsequent get-descriptor at the new
1580 * address, then we know that the set-address command
1584 DPRINTFN(0, "set address %d failed "
1585 "(%s, ignored)\n", udev->address,
1588 /* allow device time to set new address */
1590 USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1592 /* We are not self powered */
1593 udev->flags.self_powered = 0;
1595 /* Set unconfigured state */
1596 udev->curr_config_no = USB_UNCONFIG_NO;
1597 udev->curr_config_index = USB_UNCONFIG_INDEX;
1599 /* Setup USB descriptors */
1600 err = (usb_temp_setup_by_index_p) (udev, usb_template);
1602 DPRINTFN(0, "setting up USB template failed maybe the USB "
1603 "template module has not been loaded\n");
1607 usb_set_device_state(udev, USB_STATE_ADDRESSED);
1610 * Get the first 8 bytes of the device descriptor !
1612 * NOTE: "usbd_do_request" will check the device descriptor
1613 * next time we do a request to see if the maximum packet size
1614 * changed! The 8 first bytes of the device descriptor
1615 * contains the maximum packet size to use on control endpoint
1616 * 0. If this value is different from "USB_MAX_IPACKET" a new
1617 * USB control request will be setup!
1619 err = usbd_req_get_desc(udev, NULL, NULL, &udev->ddesc,
1620 USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1622 DPRINTFN(0, "getting device descriptor "
1623 "at addr %d failed, %s!\n", udev->address,
1625 /* XXX try to re-enumerate the device */
1626 err = usbd_req_re_enumerate(udev, NULL);
1631 DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
1632 "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1633 udev->address, UGETW(udev->ddesc.bcdUSB),
1634 udev->ddesc.bDeviceClass,
1635 udev->ddesc.bDeviceSubClass,
1636 udev->ddesc.bDeviceProtocol,
1637 udev->ddesc.bMaxPacketSize,
1638 udev->ddesc.bLength,
1641 /* get the full device descriptor */
1642 err = usbd_req_get_device_desc(udev, NULL, &udev->ddesc);
1644 DPRINTF("addr=%d, getting full desc failed\n",
1649 * Setup temporary USB attach args so that we can figure out some
1650 * basic quirks for this device.
1652 usb_init_attach_arg(udev, &uaa);
1654 if (usb_test_quirk(&uaa, UQ_BUS_POWERED)) {
1655 udev->flags.uq_bus_powered = 1;
1657 if (usb_test_quirk(&uaa, UQ_NO_STRINGS)) {
1658 udev->flags.no_strings = 1;
1661 * Workaround for buggy USB devices.
1663 * It appears that some string-less USB chips will crash and
1664 * disappear if any attempts are made to read any string
1667 * Try to detect such chips by checking the strings in the USB
1668 * device descriptor. If no strings are present there we
1669 * simply disable all USB strings.
1671 scratch_ptr = udev->bus->scratch[0].data;
1672 scratch_size = sizeof(udev->bus->scratch[0].data);
1674 if (udev->ddesc.iManufacturer ||
1675 udev->ddesc.iProduct ||
1676 udev->ddesc.iSerialNumber) {
1677 /* read out the language ID string */
1678 err = usbd_req_get_string_desc(udev, NULL,
1679 (char *)scratch_ptr, 4, scratch_size,
1680 USB_LANGUAGE_TABLE);
1682 err = USB_ERR_INVAL;
1685 if (err || (scratch_ptr[0] < 4)) {
1686 udev->flags.no_strings = 1;
1688 /* pick the first language as the default */
1689 udev->langid = UGETW(scratch_ptr + 2);
1692 /* assume 100mA bus powered for now. Changed when configured. */
1693 udev->power = USB_MIN_POWER;
1694 /* fetch the vendor and product strings from the device */
1695 usbd_set_device_strings(udev);
1697 if (udev->flags.usb_mode == USB_MODE_HOST) {
1698 uint8_t config_index;
1699 uint8_t config_quirk;
1700 uint8_t set_config_failed = 0;
1703 * Most USB devices should attach to config index 0 by
1706 if (usb_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1709 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1712 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1715 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1718 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1728 DPRINTF("setting config %u\n", config_index);
1730 /* get the USB device configured */
1731 err = usbd_set_config_index(udev, config_index);
1733 if (udev->ddesc.bNumConfigurations != 0) {
1734 if (!set_config_failed) {
1735 set_config_failed = 1;
1736 /* XXX try to re-enumerate the device */
1737 err = usbd_req_re_enumerate(
1740 goto repeat_set_config;
1742 DPRINTFN(0, "Failure selecting "
1743 "configuration index %u: %s, port %u, "
1744 "addr %u (ignored)\n",
1745 config_index, usbd_errstr(err), udev->port_no,
1749 * Some USB devices do not have any
1750 * configurations. Ignore any set config
1754 } else if (config_quirk) {
1755 /* user quirk selects configuration index */
1756 } else if ((config_index + 1) < udev->ddesc.bNumConfigurations) {
1758 if ((udev->cdesc->bNumInterface < 2) &&
1759 (usbd_get_no_descriptors(udev->cdesc,
1760 UDESC_ENDPOINT) == 0)) {
1761 DPRINTFN(0, "Found no endpoints "
1762 "(trying next config)!\n");
1764 goto repeat_set_config;
1766 if (config_index == 0) {
1768 * Try to figure out if we have an
1769 * auto-install disk there:
1771 if (usb_test_autoinstall(udev, 0, 0) == 0) {
1772 DPRINTFN(0, "Found possible auto-install "
1773 "disk (trying next config)\n");
1775 goto repeat_set_config;
1778 } else if (usb_test_huawei_autoinst_p(udev, &uaa) == 0) {
1779 DPRINTFN(0, "Found Huawei auto-install disk!\n");
1780 /* leave device unconfigured */
1781 usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_SUBDEV);
1784 err = 0; /* set success */
1787 DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1788 udev->address, udev, udev->parent_hub);
1790 /* register our device - we are ready */
1791 usb_bus_port_set_device(bus, parent_hub ?
1792 parent_hub->hub->ports + port_index : NULL, udev, device_index);
1795 /* Symlink the ugen device name */
1796 udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
1798 /* Announce device */
1799 printf("%s: <%s> at %s\n", udev->ugen_name, udev->manufacturer,
1800 device_get_nameunit(udev->bus->bdev));
1802 usb_notify_addq("+", udev);
1807 usb_free_device(udev,
1808 USB_UNCFG_FLAG_FREE_SUBDEV |
1809 USB_UNCFG_FLAG_FREE_EP0);
1816 static struct cdev *
1817 usb_make_dev(struct usb_device *udev, int ep, int mode)
1819 struct usb_fs_privdata* pd;
1822 /* Store information to locate ourselves again later */
1823 pd = malloc(sizeof(struct usb_fs_privdata), M_USBDEV,
1825 pd->bus_index = device_get_unit(udev->bus->bdev);
1826 pd->dev_index = udev->device_index;
1830 /* Now, create the device itself */
1831 snprintf(devname, sizeof(devname), "%u.%u.%u",
1832 pd->bus_index, pd->dev_index, pd->ep_addr);
1833 pd->cdev = make_dev(&usb_devsw, 0, UID_ROOT,
1834 GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1835 pd->cdev->si_drv1 = pd;
1841 usb_cdev_create(struct usb_device *udev)
1843 struct usb_config_descriptor *cd;
1844 struct usb_endpoint_descriptor *ed;
1845 struct usb_descriptor *desc;
1846 struct usb_fs_privdata* pd;
1848 int inmode, outmode, inmask, outmask, mode;
1851 KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1853 DPRINTFN(2, "Creating device nodes\n");
1855 if (usbd_get_mode(udev) == USB_MODE_DEVICE) {
1858 } else { /* USB_MODE_HOST */
1868 * Collect all used endpoint numbers instead of just
1869 * generating 16 static endpoints.
1871 cd = usbd_get_config_descriptor(udev);
1872 while ((desc = usb_desc_foreach(cd, desc))) {
1873 /* filter out all endpoint descriptors */
1874 if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1875 (desc->bLength >= sizeof(*ed))) {
1876 ed = (struct usb_endpoint_descriptor *)desc;
1879 ep = ed->bEndpointAddress;
1880 if (UE_GET_DIR(ep) == UE_DIR_OUT)
1881 outmask |= 1 << UE_GET_ADDR(ep);
1883 inmask |= 1 << UE_GET_ADDR(ep);
1887 /* Create all available endpoints except EP0 */
1888 for (ep = 1; ep < 16; ep++) {
1889 mode = inmask & (1 << ep) ? inmode : 0;
1890 mode |= outmask & (1 << ep) ? outmode : 0;
1892 continue; /* no IN or OUT endpoint */
1894 dev = usb_make_dev(udev, ep, mode);
1896 LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1901 usb_cdev_free(struct usb_device *udev)
1903 struct usb_fs_privdata* pd;
1906 DPRINTFN(2, "Freeing device nodes\n");
1908 while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1909 KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1913 LIST_REMOVE(pd, pd_next);
1915 destroy_dev_sched_cb(pcdev, usb_cdev_cleanup, pd);
1920 usb_cdev_cleanup(void* arg)
1922 free(arg, M_USBDEV);
1926 /*------------------------------------------------------------------------*
1929 * This function is NULL safe and will free an USB device.
1931 * Flag values, see "USB_UNCFG_FLAG_XXX".
1932 *------------------------------------------------------------------------*/
1934 usb_free_device(struct usb_device *udev, uint8_t flag)
1936 struct usb_bus *bus;
1939 return; /* already freed */
1941 DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
1944 usb_set_device_state(udev, USB_STATE_DETACHED);
1947 usb_notify_addq("-", udev);
1949 printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
1950 udev->manufacturer, device_get_nameunit(bus->bdev));
1952 /* Destroy UGEN symlink, if any */
1953 if (udev->ugen_symlink) {
1954 usb_free_symlink(udev->ugen_symlink);
1955 udev->ugen_symlink = NULL;
1959 * Unregister our device first which will prevent any further
1962 usb_bus_port_set_device(bus, udev->parent_hub ?
1963 udev->parent_hub->hub->ports + udev->port_index : NULL,
1964 NULL, USB_ROOT_HUB_ADDR);
1967 /* wait for all pending references to go away: */
1968 mtx_lock(&usb_ref_lock);
1970 while (udev->refcount != 0) {
1971 cv_wait(udev->default_cv + 1, &usb_ref_lock);
1973 mtx_unlock(&usb_ref_lock);
1975 destroy_dev_sched_cb(udev->default_dev, usb_cdev_cleanup,
1976 udev->default_dev->si_drv1);
1979 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
1980 /* stop receiving any control transfers (Device Side Mode) */
1981 usbd_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1984 /* the following will get the device unconfigured in software */
1985 usb_unconfigure(udev, flag);
1987 /* unsetup any leftover default USB transfers */
1988 usbd_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1990 /* template unsetup, if any */
1991 (usb_temp_unsetup_p) (udev);
1994 * Make sure that our clear-stall messages are not queued
1997 USB_BUS_LOCK(udev->bus);
1998 usb_proc_mwait(&udev->bus->non_giant_callback_proc,
1999 &udev->cs_msg[0], &udev->cs_msg[1]);
2000 USB_BUS_UNLOCK(udev->bus);
2002 sx_destroy(udev->default_sx);
2003 sx_destroy(udev->default_sx + 1);
2005 cv_destroy(udev->default_cv);
2006 cv_destroy(udev->default_cv + 1);
2008 mtx_destroy(udev->default_mtx);
2010 KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2014 free(udev->serial, M_USB);
2015 free(udev->manufacturer, M_USB);
2016 free(udev->product, M_USB);
2020 /*------------------------------------------------------------------------*
2023 * This function is the safe way to get the USB interface structure
2024 * pointer by interface index.
2027 * NULL: Interface not present.
2028 * Else: Pointer to USB interface structure.
2029 *------------------------------------------------------------------------*/
2030 struct usb_interface *
2031 usbd_get_iface(struct usb_device *udev, uint8_t iface_index)
2033 struct usb_interface *iface = udev->ifaces + iface_index;
2035 if (iface_index >= udev->ifaces_max)
2040 /*------------------------------------------------------------------------*
2041 * usbd_find_descriptor
2043 * This function will lookup the first descriptor that matches the
2044 * criteria given by the arguments "type" and "subtype". Descriptors
2045 * will only be searched within the interface having the index
2046 * "iface_index". If the "id" argument points to an USB descriptor,
2047 * it will be skipped before the search is started. This allows
2048 * searching for multiple descriptors using the same criteria. Else
2049 * the search is started after the interface descriptor.
2052 * NULL: End of descriptors
2053 * Else: A descriptor matching the criteria
2054 *------------------------------------------------------------------------*/
2056 usbd_find_descriptor(struct usb_device *udev, void *id, uint8_t iface_index,
2057 uint8_t type, uint8_t type_mask,
2058 uint8_t subtype, uint8_t subtype_mask)
2060 struct usb_descriptor *desc;
2061 struct usb_config_descriptor *cd;
2062 struct usb_interface *iface;
2064 cd = usbd_get_config_descriptor(udev);
2069 iface = usbd_get_iface(udev, iface_index);
2070 if (iface == NULL) {
2073 id = usbd_get_interface_descriptor(iface);
2080 while ((desc = usb_desc_foreach(cd, desc))) {
2082 if (desc->bDescriptorType == UDESC_INTERFACE) {
2085 if (((desc->bDescriptorType & type_mask) == type) &&
2086 ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2093 /*------------------------------------------------------------------------*
2096 * This function will dump information from the device descriptor
2097 * belonging to the USB device pointed to by "udev", to the string
2098 * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2099 * including the terminating zero.
2100 *------------------------------------------------------------------------*/
2102 usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
2104 struct usb_device_descriptor *udd = &udev->ddesc;
2108 bcdUSB = UGETW(udd->bcdUSB);
2109 bcdDevice = UGETW(udd->bcdDevice);
2111 if (udd->bDeviceClass != 0xFF) {
2112 snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2114 udev->manufacturer, udev->product,
2115 udd->bDeviceClass, udd->bDeviceSubClass,
2116 (bcdUSB >> 8), bcdUSB & 0xFF,
2117 (bcdDevice >> 8), bcdDevice & 0xFF,
2120 snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2122 udev->manufacturer, udev->product,
2123 (bcdUSB >> 8), bcdUSB & 0xFF,
2124 (bcdDevice >> 8), bcdDevice & 0xFF,
2131 * Descriptions of of known vendors and devices ("products").
2133 struct usb_knowndev {
2137 const char *vendorname;
2138 const char *productname;
2141 #define USB_KNOWNDEV_NOPROD 0x01 /* match on vendor only */
2143 #include "usbdevs.h"
2144 #include "usbdevs_data.h"
2145 #endif /* USB_VERBOSE */
2148 usbd_set_device_strings(struct usb_device *udev)
2150 struct usb_device_descriptor *udd = &udev->ddesc;
2152 const struct usb_knowndev *kdp;
2156 uint16_t product_id;
2158 vendor_id = UGETW(udd->idVendor);
2159 product_id = UGETW(udd->idProduct);
2161 /* get serial number string */
2162 bzero(temp, sizeof(temp));
2163 usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2164 udev->ddesc.iSerialNumber);
2165 udev->serial = strdup(temp, M_USB);
2167 /* get manufacturer string */
2168 bzero(temp, sizeof(temp));
2169 usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2170 udev->ddesc.iManufacturer);
2171 usb_trim_spaces(temp);
2172 if (temp[0] != '\0')
2173 udev->manufacturer = strdup(temp, M_USB);
2175 /* get product string */
2176 bzero(temp, sizeof(temp));
2177 usbd_req_get_string_any(udev, NULL, temp, sizeof(temp),
2178 udev->ddesc.iProduct);
2179 usb_trim_spaces(temp);
2180 if (temp[0] != '\0')
2181 udev->product = strdup(temp, M_USB);
2184 if (udev->manufacturer == NULL || udev->product == NULL) {
2185 for (kdp = usb_knowndevs; kdp->vendorname != NULL; kdp++) {
2186 if (kdp->vendor == vendor_id &&
2187 (kdp->product == product_id ||
2188 (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2191 if (kdp->vendorname != NULL) {
2192 /* XXX should use pointer to knowndevs string */
2193 if (udev->manufacturer == NULL) {
2194 udev->manufacturer = strdup(kdp->vendorname,
2197 if (udev->product == NULL &&
2198 (kdp->flags & USB_KNOWNDEV_NOPROD) == 0) {
2199 udev->product = strdup(kdp->productname,
2205 /* Provide default strings if none were found */
2206 if (udev->manufacturer == NULL) {
2207 snprintf(temp, sizeof(temp), "vendor 0x%04x", vendor_id);
2208 udev->manufacturer = strdup(temp, M_USB);
2210 if (udev->product == NULL) {
2211 snprintf(temp, sizeof(temp), "product 0x%04x", product_id);
2212 udev->product = strdup(temp, M_USB);
2221 usbd_get_mode(struct usb_device *udev)
2223 return (udev->flags.usb_mode);
2228 * See: USB_SPEED_XXX
2231 usbd_get_speed(struct usb_device *udev)
2233 return (udev->speed);
2237 usbd_get_isoc_fps(struct usb_device *udev)
2240 switch (udev->speed) {
2242 case USB_SPEED_FULL:
2249 struct usb_device_descriptor *
2250 usbd_get_device_descriptor(struct usb_device *udev)
2253 return (NULL); /* be NULL safe */
2254 return (&udev->ddesc);
2257 struct usb_config_descriptor *
2258 usbd_get_config_descriptor(struct usb_device *udev)
2261 return (NULL); /* be NULL safe */
2262 return (udev->cdesc);
2265 /*------------------------------------------------------------------------*
2266 * usb_test_quirk - test a device for a given quirk
2269 * 0: The USB device does not have the given quirk.
2270 * Else: The USB device has the given quirk.
2271 *------------------------------------------------------------------------*/
2273 usb_test_quirk(const struct usb_attach_arg *uaa, uint16_t quirk)
2277 found = (usb_test_quirk_p) (&uaa->info, quirk);
2281 struct usb_interface_descriptor *
2282 usbd_get_interface_descriptor(struct usb_interface *iface)
2285 return (NULL); /* be NULL safe */
2286 return (iface->idesc);
2290 usbd_get_interface_altindex(struct usb_interface *iface)
2292 return (iface->alt_index);
2296 usbd_get_bus_index(struct usb_device *udev)
2298 return ((uint8_t)device_get_unit(udev->bus->bdev));
2302 usbd_get_device_index(struct usb_device *udev)
2304 return (udev->device_index);
2308 /*------------------------------------------------------------------------*
2311 * This function will generate events for dev.
2312 *------------------------------------------------------------------------*/
2314 usb_notify_addq(const char *type, struct usb_device *udev)
2317 struct malloc_type *mt;
2319 mtx_lock(&malloc_mtx);
2320 mt = malloc_desc2type("bus"); /* XXX M_BUS */
2321 mtx_unlock(&malloc_mtx);
2325 data = malloc(512, mt, M_NOWAIT);
2329 /* String it all together. */
2330 snprintf(data, 1024,
2336 "devsubclass=0x%02x "
2345 UGETW(udev->ddesc.idVendor),
2346 UGETW(udev->ddesc.idProduct),
2347 udev->ddesc.bDeviceClass,
2348 udev->ddesc.bDeviceSubClass,
2350 UGETW(udev->ddesc.bcdDevice),
2352 udev->parent_hub != NULL ?
2353 udev->parent_hub->ugen_name :
2354 device_get_nameunit(device_get_parent(udev->bus->bdev)));
2356 devctl_queue_data(data);
2359 /*------------------------------------------------------------------------*
2360 * usb_fifo_free_wrap
2362 * This function will free the FIFOs.
2364 * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2365 * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2366 * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2367 * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2368 * control endpoint FIFOs. If "iface_index" is not set to
2369 * "USB_IFACE_INDEX_ANY" the flag has no effect.
2370 *------------------------------------------------------------------------*/
2372 usb_fifo_free_wrap(struct usb_device *udev,
2373 uint8_t iface_index, uint8_t flag)
2379 * Free any USB FIFOs on the given interface:
2381 for (i = 0; i != USB_FIFO_MAX; i++) {
2386 /* Check if the interface index matches */
2387 if (iface_index == f->iface_index) {
2388 if (f->methods != &usb_ugen_methods) {
2390 * Don't free any non-generic FIFOs in
2395 if ((f->dev_ep_index == 0) &&
2396 (f->fs_xfer == NULL)) {
2397 /* no need to free this FIFO */
2400 } else if (iface_index == USB_IFACE_INDEX_ANY) {
2401 if ((f->methods == &usb_ugen_methods) &&
2402 (f->dev_ep_index == 0) &&
2403 (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2404 (f->fs_xfer == NULL)) {
2405 /* no need to free this FIFO */
2409 /* no need to free this FIFO */
2412 /* free this FIFO */
2418 /*------------------------------------------------------------------------*
2419 * usb_peer_can_wakeup
2422 * 0: Peer cannot do resume signalling.
2423 * Else: Peer can do resume signalling.
2424 *------------------------------------------------------------------------*/
2426 usb_peer_can_wakeup(struct usb_device *udev)
2428 const struct usb_config_descriptor *cdp;
2431 if ((cdp != NULL) && (udev->flags.usb_mode == USB_MODE_HOST)) {
2432 return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2434 return (0); /* not supported */
2438 usb_set_device_state(struct usb_device *udev, enum usb_dev_state state)
2441 KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2443 DPRINTF("udev %p state %s -> %s\n", udev,
2444 usb_statestr(udev->state), usb_statestr(state));
2445 udev->state = state;
2449 usbd_device_attached(struct usb_device *udev)
2451 return (udev->state > USB_STATE_DETACHED);
2454 /* The following function locks enumerating the given USB device. */
2457 usbd_enum_lock(struct usb_device *udev)
2459 sx_xlock(udev->default_sx + 1);
2461 * NEWBUS LOCK NOTE: We should check if any parent SX locks
2462 * are locked before locking Giant. Else the lock can be
2463 * locked multiple times.
2468 /* The following function unlocks enumerating the given USB device. */
2471 usbd_enum_unlock(struct usb_device *udev)
2474 sx_xunlock(udev->default_sx + 1);
2478 * The following function checks the enumerating lock for the given
2483 usbd_enum_is_locked(struct usb_device *udev)
2485 return (sx_xlocked(udev->default_sx + 1));