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/module.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/sysctl.h>
41 #include <sys/unistd.h>
42 #include <sys/callout.h>
43 #include <sys/malloc.h>
46 #include <sys/fcntl.h>
48 #include <dev/usb/usb.h>
49 #include <dev/usb/usbdi.h>
50 #include <dev/usb/usbdi_util.h>
51 #include <dev/usb/usb_ioctl.h>
59 #define USB_DEBUG_VAR usb_debug
61 #include <dev/usb/usb_core.h>
62 #include <dev/usb/usb_debug.h>
63 #include <dev/usb/usb_process.h>
64 #include <dev/usb/usb_device.h>
65 #include <dev/usb/usb_busdma.h>
66 #include <dev/usb/usb_transfer.h>
67 #include <dev/usb/usb_request.h>
68 #include <dev/usb/usb_dynamic.h>
69 #include <dev/usb/usb_hub.h>
70 #include <dev/usb/usb_util.h>
71 #include <dev/usb/usb_msctest.h>
73 #include <dev/usb/usb_dev.h>
74 #include <dev/usb/usb_generic.h>
77 #include <dev/usb/quirk/usb_quirk.h>
79 #include <dev/usb/usb_controller.h>
80 #include <dev/usb/usb_bus.h>
82 /* function prototypes */
84 static void usb_init_endpoint(struct usb_device *, uint8_t,
85 struct usb_endpoint_descriptor *,
86 struct usb_endpoint_ss_comp_descriptor *,
87 struct usb_endpoint *);
88 static void usb_unconfigure(struct usb_device *, uint8_t);
89 static void usb_detach_device_sub(struct usb_device *, device_t *,
91 static uint8_t usb_probe_and_attach_sub(struct usb_device *,
92 struct usb_attach_arg *);
93 static void usb_init_attach_arg(struct usb_device *,
94 struct usb_attach_arg *);
95 static void usb_suspend_resume_sub(struct usb_device *, device_t,
97 static void usbd_clear_stall_proc(struct usb_proc_msg *_pm);
98 static usb_error_t usb_config_parse(struct usb_device *, uint8_t, uint8_t);
99 static void usbd_set_device_strings(struct usb_device *);
101 static void usb_notify_addq(const char *type, struct usb_device *);
104 static void usb_fifo_free_wrap(struct usb_device *, uint8_t, uint8_t);
105 static struct cdev *usb_make_dev(struct usb_device *, int, int);
106 static void usb_cdev_create(struct usb_device *);
107 static void usb_cdev_free(struct usb_device *);
108 static void usb_cdev_cleanup(void *);
111 /* This variable is global to allow easy access to it: */
113 int usb_template = 0;
115 TUNABLE_INT("hw.usb.usb_template", &usb_template);
116 SYSCTL_INT(_hw_usb, OID_AUTO, template, CTLFLAG_RW,
117 &usb_template, 0, "Selected USB device side template");
119 /* English is default language */
121 static int usb_lang_id = 0x0009;
122 static int usb_lang_mask = 0x00FF;
124 TUNABLE_INT("hw.usb.usb_lang_id", &usb_lang_id);
125 SYSCTL_INT(_hw_usb, OID_AUTO, usb_lang_id, CTLFLAG_RW,
126 &usb_lang_id, 0, "Preferred USB language ID");
128 TUNABLE_INT("hw.usb.usb_lang_mask", &usb_lang_mask);
129 SYSCTL_INT(_hw_usb, OID_AUTO, usb_lang_mask, CTLFLAG_RW,
130 &usb_lang_mask, 0, "Preferred USB language mask");
132 static const char* statestr[USB_STATE_MAX] = {
133 [USB_STATE_DETACHED] = "DETACHED",
134 [USB_STATE_ATTACHED] = "ATTACHED",
135 [USB_STATE_POWERED] = "POWERED",
136 [USB_STATE_ADDRESSED] = "ADDRESSED",
137 [USB_STATE_CONFIGURED] = "CONFIGURED",
141 usb_statestr(enum usb_dev_state state)
143 return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
147 usb_get_manufacturer(struct usb_device *udev)
149 return (udev->manufacturer ? udev->manufacturer : "Unknown");
153 usb_get_product(struct usb_device *udev)
155 return (udev->product ? udev->product : "");
159 usb_get_serial(struct usb_device *udev)
161 return (udev->serial ? udev->serial : "");
164 /*------------------------------------------------------------------------*
165 * usbd_get_ep_by_addr
167 * This function searches for an USB ep by endpoint address and
173 *------------------------------------------------------------------------*/
174 struct usb_endpoint *
175 usbd_get_ep_by_addr(struct usb_device *udev, uint8_t ea_val)
177 struct usb_endpoint *ep = udev->endpoints;
178 struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
180 EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
184 * According to the USB specification not all bits are used
185 * for the endpoint address. Keep defined bits only:
190 * Iterate accross all the USB endpoints searching for a match
191 * based on the endpoint address:
193 for (; ep != ep_end; ep++) {
195 if (ep->edesc == NULL) {
198 /* do the mask and check the value */
199 if ((ep->edesc->bEndpointAddress & EA_MASK) == ea_val) {
205 * The default endpoint is always present and is checked separately:
207 if ((udev->ctrl_ep.edesc) &&
208 ((udev->ctrl_ep.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
218 /*------------------------------------------------------------------------*
221 * This function searches for an USB endpoint based on the information
222 * given by the passed "struct usb_config" pointer.
226 * Else: Pointer to "struct usb_endpoint".
227 *------------------------------------------------------------------------*/
228 struct usb_endpoint *
229 usbd_get_endpoint(struct usb_device *udev, uint8_t iface_index,
230 const struct usb_config *setup)
232 struct usb_endpoint *ep = udev->endpoints;
233 struct usb_endpoint *ep_end = udev->endpoints + udev->endpoints_max;
234 uint8_t index = setup->ep_index;
240 DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
241 "type=0x%x dir=0x%x index=%d\n",
242 udev, iface_index, setup->endpoint,
243 setup->type, setup->direction, setup->ep_index);
247 if (setup->usb_mode != USB_MODE_DUAL &&
248 udev->flags.usb_mode != setup->usb_mode) {
249 /* wrong mode - no endpoint */
253 /* setup expected endpoint direction mask and value */
255 if (setup->direction == UE_DIR_RX) {
256 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
257 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
258 UE_DIR_OUT : UE_DIR_IN;
259 } else if (setup->direction == UE_DIR_TX) {
260 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
261 ea_val = (udev->flags.usb_mode == USB_MODE_DEVICE) ?
262 UE_DIR_IN : UE_DIR_OUT;
263 } else if (setup->direction == UE_DIR_ANY) {
264 /* match any endpoint direction */
268 /* match the given endpoint direction */
269 ea_mask = (UE_DIR_IN | UE_DIR_OUT);
270 ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
273 /* setup expected endpoint address */
275 if (setup->endpoint == UE_ADDR_ANY) {
276 /* match any endpoint address */
278 /* match the given endpoint address */
280 ea_val |= (setup->endpoint & UE_ADDR);
283 /* setup expected endpoint type */
285 if (setup->type == UE_BULK_INTR) {
286 /* this will match BULK and INTERRUPT endpoints */
289 } else if (setup->type == UE_TYPE_ANY) {
290 /* match any endpoint type */
294 /* match the given endpoint type */
295 type_mask = UE_XFERTYPE;
296 type_val = (setup->type & UE_XFERTYPE);
300 * Iterate accross all the USB endpoints searching for a match
301 * based on the endpoint address. Note that we are searching
302 * the endpoints from the beginning of the "udev->endpoints" array.
304 for (; ep != ep_end; ep++) {
306 if ((ep->edesc == NULL) ||
307 (ep->iface_index != iface_index)) {
310 /* do the masks and check the values */
312 if (((ep->edesc->bEndpointAddress & ea_mask) == ea_val) &&
313 ((ep->edesc->bmAttributes & type_mask) == type_val)) {
321 * Match against default endpoint last, so that "any endpoint", "any
322 * address" and "any direction" returns the first endpoint of the
323 * interface. "iface_index" and "direction" is ignored:
325 if ((udev->ctrl_ep.edesc) &&
326 ((udev->ctrl_ep.edesc->bEndpointAddress & ea_mask) == ea_val) &&
327 ((udev->ctrl_ep.edesc->bmAttributes & type_mask) == type_val) &&
338 /*------------------------------------------------------------------------*
339 * usbd_interface_count
341 * This function stores the number of USB interfaces excluding
342 * alternate settings, which the USB config descriptor reports into
343 * the unsigned 8-bit integer pointed to by "count".
348 *------------------------------------------------------------------------*/
350 usbd_interface_count(struct usb_device *udev, uint8_t *count)
352 if (udev->cdesc == NULL) {
354 return (USB_ERR_NOT_CONFIGURED);
356 *count = udev->ifaces_max;
357 return (USB_ERR_NORMAL_COMPLETION);
361 /*------------------------------------------------------------------------*
364 * This function will initialise the USB endpoint structure pointed to by
365 * the "endpoint" argument. The structure pointed to by "endpoint" must be
366 * zeroed before calling this function.
367 *------------------------------------------------------------------------*/
369 usb_init_endpoint(struct usb_device *udev, uint8_t iface_index,
370 struct usb_endpoint_descriptor *edesc,
371 struct usb_endpoint_ss_comp_descriptor *ecomp,
372 struct usb_endpoint *ep)
374 struct usb_bus_methods *methods;
376 methods = udev->bus->methods;
378 (methods->endpoint_init) (udev, edesc, ep);
380 /* initialise USB endpoint structure */
383 ep->iface_index = iface_index;
384 TAILQ_INIT(&ep->endpoint_q.head);
385 ep->endpoint_q.command = &usbd_pipe_start;
387 /* the pipe is not supported by the hardware */
388 if (ep->methods == NULL)
391 /* clear stall, if any */
392 if (methods->clear_stall != NULL) {
393 USB_BUS_LOCK(udev->bus);
394 (methods->clear_stall) (udev, ep);
395 USB_BUS_UNLOCK(udev->bus);
399 /*-----------------------------------------------------------------------*
400 * usb_endpoint_foreach
402 * This function will iterate all the USB endpoints except the control
403 * endpoint. This function is NULL safe.
406 * NULL: End of USB endpoints
407 * Else: Pointer to next USB endpoint
408 *------------------------------------------------------------------------*/
409 struct usb_endpoint *
410 usb_endpoint_foreach(struct usb_device *udev, struct usb_endpoint *ep)
412 struct usb_endpoint *ep_end;
418 ep_end = udev->endpoints + udev->endpoints_max;
420 /* get next endpoint */
422 ep = udev->endpoints;
426 /* find next allocated ep */
427 while (ep != ep_end) {
428 if (ep->edesc != NULL)
435 /*------------------------------------------------------------------------*
438 * This function will free all USB interfaces and USB endpoints belonging
441 * Flag values, see "USB_UNCFG_FLAG_XXX".
442 *------------------------------------------------------------------------*/
444 usb_unconfigure(struct usb_device *udev, uint8_t flag)
448 /* automatic locking */
449 if (usbd_enum_is_locked(udev)) {
453 usbd_enum_lock(udev);
456 /* detach all interface drivers */
457 usb_detach_device(udev, USB_IFACE_INDEX_ANY, flag);
460 /* free all FIFOs except control endpoint FIFOs */
461 usb_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, flag);
464 * Free all cdev's, if any.
469 #if USB_HAVE_COMPAT_LINUX
470 /* free Linux compat device, if any */
471 if (udev->linux_endpoint_start) {
472 usb_linux_free_device(udev);
473 udev->linux_endpoint_start = NULL;
477 usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_FREE);
479 /* free "cdesc" after "ifaces" and "endpoints", if any */
480 if (udev->cdesc != NULL) {
481 if (udev->flags.usb_mode != USB_MODE_DEVICE)
482 free(udev->cdesc, M_USB);
485 /* set unconfigured state */
486 udev->curr_config_no = USB_UNCONFIG_NO;
487 udev->curr_config_index = USB_UNCONFIG_INDEX;
490 usbd_enum_unlock(udev);
493 /*------------------------------------------------------------------------*
494 * usbd_set_config_index
496 * This function selects configuration by index, independent of the
497 * actual configuration number. This function should not be used by
503 *------------------------------------------------------------------------*/
505 usbd_set_config_index(struct usb_device *udev, uint8_t index)
507 struct usb_status ds;
508 struct usb_config_descriptor *cdp;
515 DPRINTFN(6, "udev=%p index=%d\n", udev, index);
517 /* automatic locking */
518 if (usbd_enum_is_locked(udev)) {
522 usbd_enum_lock(udev);
525 usb_unconfigure(udev, 0);
527 if (index == USB_UNCONFIG_INDEX) {
529 * Leave unallocated when unconfiguring the
530 * device. "usb_unconfigure()" will also reset
531 * the current config number and index.
533 err = usbd_req_set_config(udev, NULL, USB_UNCONFIG_NO);
534 if (udev->state == USB_STATE_CONFIGURED)
535 usb_set_device_state(udev, USB_STATE_ADDRESSED);
538 /* get the full config descriptor */
539 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
540 /* save some memory */
541 err = usbd_req_get_descriptor_ptr(udev, &cdp,
542 (UDESC_CONFIG << 8) | index);
545 err = usbd_req_get_config_desc_full(udev,
546 NULL, &cdp, M_USB, index);
551 /* set the new config descriptor */
555 /* Figure out if the device is self or bus powered. */
557 if ((!udev->flags.uq_bus_powered) &&
558 (cdp->bmAttributes & UC_SELF_POWERED) &&
559 (udev->flags.usb_mode == USB_MODE_HOST)) {
560 /* May be self powered. */
561 if (cdp->bmAttributes & UC_BUS_POWERED) {
562 /* Must ask device. */
563 err = usbd_req_get_device_status(udev, NULL, &ds);
565 DPRINTFN(0, "could not read "
566 "device status: %s\n",
568 } else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
571 DPRINTF("status=0x%04x \n",
576 DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
577 "selfpowered=%d, power=%d\n",
579 udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
580 selfpowered, cdp->bMaxPower * 2);
582 /* Check if we have enough power. */
583 power = cdp->bMaxPower * 2;
585 if (udev->parent_hub) {
586 max_power = udev->parent_hub->hub->portpower;
588 max_power = USB_MAX_POWER;
591 if (power > max_power) {
592 DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
593 err = USB_ERR_NO_POWER;
596 /* Only update "self_powered" in USB Host Mode */
597 if (udev->flags.usb_mode == USB_MODE_HOST) {
598 udev->flags.self_powered = selfpowered;
601 udev->curr_config_no = cdp->bConfigurationValue;
602 udev->curr_config_index = index;
603 usb_set_device_state(udev, USB_STATE_CONFIGURED);
605 /* Set the actual configuration value. */
606 err = usbd_req_set_config(udev, NULL, cdp->bConfigurationValue);
611 err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_ALLOC);
616 err = usb_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_INIT);
622 /* create device nodes for each endpoint */
623 usb_cdev_create(udev);
627 DPRINTF("error=%s\n", usbd_errstr(err));
629 usb_unconfigure(udev, 0);
632 usbd_enum_unlock(udev);
636 /*------------------------------------------------------------------------*
639 * This function will allocate and free USB interfaces and USB endpoints,
640 * parse the USB configuration structure and initialise the USB endpoints
641 * and interfaces. If "iface_index" is not equal to
642 * "USB_IFACE_INDEX_ANY" then the "cmd" parameter is the
643 * alternate_setting to be selected for the given interface. Else the
644 * "cmd" parameter is defined by "USB_CFG_XXX". "iface_index" can be
645 * "USB_IFACE_INDEX_ANY" or a valid USB interface index. This function
646 * is typically called when setting the configuration or when setting
647 * an alternate interface.
652 *------------------------------------------------------------------------*/
654 usb_config_parse(struct usb_device *udev, uint8_t iface_index, uint8_t cmd)
656 struct usb_idesc_parse_state ips;
657 struct usb_interface_descriptor *id;
658 struct usb_endpoint_descriptor *ed;
659 struct usb_interface *iface;
660 struct usb_endpoint *ep;
668 if (iface_index != USB_IFACE_INDEX_ANY) {
669 /* parameter overload */
679 DPRINTFN(5, "iface_index=%d cmd=%d\n",
682 if (cmd == USB_CFG_FREE)
685 if (cmd == USB_CFG_INIT) {
686 sx_assert(&udev->enum_sx, SA_LOCKED);
688 /* check for in-use endpoints */
690 ep = udev->endpoints;
691 ep_max = udev->endpoints_max;
693 /* look for matching endpoints */
694 if ((iface_index == USB_IFACE_INDEX_ANY) ||
695 (iface_index == ep->iface_index)) {
696 if (ep->refcount_alloc != 0) {
698 * This typically indicates a
699 * more serious error.
701 err = USB_ERR_IN_USE;
704 memset(ep, 0, sizeof(*ep));
705 /* make sure we don't zero the endpoint again */
706 ep->iface_index = USB_IFACE_INDEX_ANY;
716 memset(&ips, 0, sizeof(ips));
721 while ((id = usb_idesc_foreach(udev->cdesc, &ips))) {
723 /* check for interface overflow */
724 if (ips.iface_index == USB_IFACE_MAX)
727 iface = udev->ifaces + ips.iface_index;
729 /* check for specific interface match */
731 if (cmd == USB_CFG_INIT) {
732 if ((iface_index != USB_IFACE_INDEX_ANY) &&
733 (iface_index != ips.iface_index)) {
734 /* wrong interface */
736 } else if (alt_index != ips.iface_index_alt) {
737 /* wrong alternate setting */
740 /* initialise interface */
746 /* check for new interface */
747 if (ips.iface_index_alt == 0) {
748 /* update current number of endpoints */
753 /* setup the USB interface structure */
755 /* default setting */
756 iface->parent_iface_index = USB_IFACE_INDEX_ANY;
757 /* set alternate index */
758 iface->alt_index = alt_index;
761 DPRINTFN(5, "found idesc nendpt=%d\n", id->bNumEndpoints);
763 ed = (struct usb_endpoint_descriptor *)id;
767 /* iterate all the endpoint descriptors */
768 while ((ed = usb_edesc_foreach(udev->cdesc, ed))) {
770 if (temp == USB_EP_MAX)
773 ep = udev->endpoints + temp;
778 ecomp = usb_ed_comp_foreach(udev->cdesc, (void *)ed);
780 DPRINTFN(5, "Found endpoint companion descriptor\n");
782 usb_init_endpoint(udev,
783 ips.iface_index, ed, ecomp, ep);
788 /* find maximum number of endpoints */
793 id = (struct usb_interface_descriptor *)ed;
797 /* NOTE: It is valid to have no interfaces and no endpoints! */
799 if (cmd == USB_CFG_ALLOC) {
800 udev->ifaces_max = ips.iface_index;
802 if (udev->ifaces_max != 0) {
803 udev->ifaces = malloc(sizeof(*iface) * udev->ifaces_max,
804 M_USB, M_WAITOK | M_ZERO);
805 if (udev->ifaces == NULL) {
811 udev->endpoints = malloc(sizeof(*ep) * ep_max,
812 M_USB, M_WAITOK | M_ZERO);
813 if (udev->endpoints == NULL) {
818 udev->endpoints = NULL;
820 USB_BUS_LOCK(udev->bus);
821 udev->endpoints_max = ep_max;
822 /* reset any ongoing clear-stall */
823 udev->ep_curr = NULL;
824 USB_BUS_UNLOCK(udev->bus);
829 if (cmd == USB_CFG_ALLOC) {
831 USB_BUS_LOCK(udev->bus);
832 udev->endpoints_max = 0;
833 /* reset any ongoing clear-stall */
834 udev->ep_curr = NULL;
835 USB_BUS_UNLOCK(udev->bus);
838 if (udev->ifaces != NULL)
839 free(udev->ifaces, M_USB);
840 if (udev->endpoints != NULL)
841 free(udev->endpoints, M_USB);
844 udev->endpoints = NULL;
845 udev->ifaces_max = 0;
851 /*------------------------------------------------------------------------*
852 * usbd_set_alt_interface_index
854 * This function will select an alternate interface index for the
855 * given interface index. The interface should not be in use when this
856 * function is called. That means there should not be any open USB
857 * transfers. Else an error is returned. If the alternate setting is
858 * already set this function will simply return success. This function
859 * is called in Host mode and Device mode!
864 *------------------------------------------------------------------------*/
866 usbd_set_alt_interface_index(struct usb_device *udev,
867 uint8_t iface_index, uint8_t alt_index)
869 struct usb_interface *iface = usbd_get_iface(udev, iface_index);
873 /* automatic locking */
874 if (usbd_enum_is_locked(udev)) {
878 usbd_enum_lock(udev);
884 if (iface->alt_index == alt_index) {
886 * Optimise away duplicate setting of
887 * alternate setting in USB Host Mode!
894 * Free all generic FIFOs for this interface, except control
897 usb_fifo_free_wrap(udev, iface_index, 0);
900 err = usb_config_parse(udev, iface_index, alt_index);
904 if (iface->alt_index != alt_index) {
905 /* the alternate setting does not exist */
910 err = usbd_req_set_alt_interface_no(udev, NULL, iface_index,
911 iface->idesc->bAlternateSetting);
915 usbd_enum_unlock(udev);
920 /*------------------------------------------------------------------------*
921 * usbd_set_endpoint_stall
923 * This function is used to make a BULK or INTERRUPT endpoint send
924 * STALL tokens in USB device mode.
929 *------------------------------------------------------------------------*/
931 usbd_set_endpoint_stall(struct usb_device *udev, struct usb_endpoint *ep,
934 struct usb_xfer *xfer;
940 DPRINTF("Cannot find endpoint\n");
942 * Pretend that the clear or set stall request is
943 * successful else some USB host stacks can do
944 * strange things, especially when a control endpoint
949 et = (ep->edesc->bmAttributes & UE_XFERTYPE);
951 if ((et != UE_BULK) &&
952 (et != UE_INTERRUPT)) {
954 * Should not stall control
955 * nor isochronous endpoints.
957 DPRINTF("Invalid endpoint\n");
960 USB_BUS_LOCK(udev->bus);
962 /* store current stall state */
963 was_stalled = ep->is_stalled;
965 /* check for no change */
966 if (was_stalled && do_stall) {
967 /* if the endpoint is already stalled do nothing */
968 USB_BUS_UNLOCK(udev->bus);
969 DPRINTF("No change\n");
972 /* set stalled state */
975 if (do_stall || (!was_stalled)) {
977 /* lookup the current USB transfer, if any */
978 xfer = ep->endpoint_q.curr;
984 * If "xfer" is non-NULL the "set_stall" method will
985 * complete the USB transfer like in case of a timeout
986 * setting the error code "USB_ERR_STALLED".
988 (udev->bus->methods->set_stall) (udev, xfer, ep, &do_stall);
991 ep->toggle_next = 0; /* reset data toggle */
992 ep->is_stalled = 0; /* clear stalled state */
994 (udev->bus->methods->clear_stall) (udev, ep);
996 /* start up the current or next transfer, if any */
997 usb_command_wrapper(&ep->endpoint_q, ep->endpoint_q.curr);
999 USB_BUS_UNLOCK(udev->bus);
1003 /*------------------------------------------------------------------------*
1004 * usb_reset_iface_endpoints - used in USB device side mode
1005 *------------------------------------------------------------------------*/
1007 usb_reset_iface_endpoints(struct usb_device *udev, uint8_t iface_index)
1009 struct usb_endpoint *ep;
1010 struct usb_endpoint *ep_end;
1012 ep = udev->endpoints;
1013 ep_end = udev->endpoints + udev->endpoints_max;
1015 for (; ep != ep_end; ep++) {
1017 if ((ep->edesc == NULL) ||
1018 (ep->iface_index != iface_index)) {
1021 /* simulate a clear stall from the peer */
1022 usbd_set_endpoint_stall(udev, ep, 0);
1027 /*------------------------------------------------------------------------*
1028 * usb_detach_device_sub
1030 * This function will try to detach an USB device. If it fails a panic
1033 * Flag values, see "USB_UNCFG_FLAG_XXX".
1034 *------------------------------------------------------------------------*/
1036 usb_detach_device_sub(struct usb_device *udev, device_t *ppdev,
1037 char **ppnpinfo, uint8_t flag)
1046 * NOTE: It is important to clear "*ppdev" before deleting
1047 * the child due to some device methods being called late
1048 * during the delete process !
1052 device_printf(dev, "at %s, port %d, addr %d "
1054 device_get_nameunit(udev->parent_dev),
1055 udev->port_no, udev->address);
1057 if (device_is_attached(dev)) {
1058 if (udev->flags.peer_suspended) {
1059 err = DEVICE_RESUME(dev);
1061 device_printf(dev, "Resume failed\n");
1064 if (device_detach(dev)) {
1068 if (device_delete_child(udev->parent_dev, dev)) {
1073 pnpinfo = *ppnpinfo;
1074 if (pnpinfo != NULL) {
1076 free(pnpinfo, M_USBDEV);
1081 /* Detach is not allowed to fail in the USB world */
1082 panic("usb_detach_device_sub: A USB driver would not detach\n");
1085 /*------------------------------------------------------------------------*
1088 * The following function will detach the matching interfaces.
1089 * This function is NULL safe.
1091 * Flag values, see "USB_UNCFG_FLAG_XXX".
1092 *------------------------------------------------------------------------*/
1094 usb_detach_device(struct usb_device *udev, uint8_t iface_index,
1097 struct usb_interface *iface;
1104 DPRINTFN(4, "udev=%p\n", udev);
1106 sx_assert(&udev->enum_sx, SA_LOCKED);
1109 * First detach the child to give the child's detach routine a
1110 * chance to detach the sub-devices in the correct order.
1111 * Then delete the child using "device_delete_child()" which
1112 * will detach all sub-devices from the bottom and upwards!
1114 if (iface_index != USB_IFACE_INDEX_ANY) {
1116 iface_index = i + 1;
1119 iface_index = USB_IFACE_MAX;
1124 for (; i != iface_index; i++) {
1126 iface = usbd_get_iface(udev, i);
1127 if (iface == NULL) {
1128 /* looks like the end of the USB interfaces */
1131 usb_detach_device_sub(udev, &iface->subdev,
1132 &iface->pnpinfo, flag);
1136 /*------------------------------------------------------------------------*
1137 * usb_probe_and_attach_sub
1142 *------------------------------------------------------------------------*/
1144 usb_probe_and_attach_sub(struct usb_device *udev,
1145 struct usb_attach_arg *uaa)
1147 struct usb_interface *iface;
1152 if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
1153 /* leave interface alone */
1156 dev = iface->subdev;
1159 /* clean up after module unload */
1161 if (device_is_attached(dev)) {
1162 /* already a device there */
1165 /* clear "iface->subdev" as early as possible */
1167 iface->subdev = NULL;
1169 if (device_delete_child(udev->parent_dev, dev)) {
1172 * Panic here, else one can get a double call
1173 * to device_detach(). USB devices should
1174 * never fail on detach!
1176 panic("device_delete_child() failed\n");
1179 if (uaa->temp_dev == NULL) {
1181 /* create a new child */
1182 uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1183 if (uaa->temp_dev == NULL) {
1184 device_printf(udev->parent_dev,
1185 "Device creation failed\n");
1186 return (1); /* failure */
1188 device_set_ivars(uaa->temp_dev, uaa);
1189 device_quiet(uaa->temp_dev);
1192 * Set "subdev" before probe and attach so that "devd" gets
1193 * the information it needs.
1195 iface->subdev = uaa->temp_dev;
1197 if (device_probe_and_attach(iface->subdev) == 0) {
1199 * The USB attach arguments are only available during probe
1202 uaa->temp_dev = NULL;
1203 device_set_ivars(iface->subdev, NULL);
1205 if (udev->flags.peer_suspended) {
1206 err = DEVICE_SUSPEND(iface->subdev);
1208 device_printf(iface->subdev, "Suspend failed\n");
1210 return (0); /* success */
1212 /* No USB driver found */
1213 iface->subdev = NULL;
1215 return (1); /* failure */
1218 /*------------------------------------------------------------------------*
1219 * usbd_set_parent_iface
1221 * Using this function will lock the alternate interface setting on an
1222 * interface. It is typically used for multi interface drivers. In USB
1223 * device side mode it is assumed that the alternate interfaces all
1224 * have the same endpoint descriptors. The default parent index value
1225 * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1227 *------------------------------------------------------------------------*/
1229 usbd_set_parent_iface(struct usb_device *udev, uint8_t iface_index,
1230 uint8_t parent_index)
1232 struct usb_interface *iface;
1234 iface = usbd_get_iface(udev, iface_index);
1236 iface->parent_iface_index = parent_index;
1241 usb_init_attach_arg(struct usb_device *udev,
1242 struct usb_attach_arg *uaa)
1244 bzero(uaa, sizeof(*uaa));
1247 uaa->usb_mode = udev->flags.usb_mode;
1248 uaa->port = udev->port_no;
1249 uaa->dev_state = UAA_DEV_READY;
1251 uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1252 uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1253 uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1254 uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1255 uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1256 uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1257 uaa->info.bConfigIndex = udev->curr_config_index;
1258 uaa->info.bConfigNum = udev->curr_config_no;
1261 /*------------------------------------------------------------------------*
1262 * usb_probe_and_attach
1264 * This function is called from "uhub_explore_sub()",
1265 * "usb_handle_set_config()" and "usb_handle_request()".
1269 * Else: A control transfer failed
1270 *------------------------------------------------------------------------*/
1272 usb_probe_and_attach(struct usb_device *udev, uint8_t iface_index)
1274 struct usb_attach_arg uaa;
1275 struct usb_interface *iface;
1281 DPRINTF("udev == NULL\n");
1282 return (USB_ERR_INVAL);
1284 /* automatic locking */
1285 if (usbd_enum_is_locked(udev)) {
1289 usbd_enum_lock(udev);
1292 if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1293 /* do nothing - no configuration has been set */
1296 /* setup USB attach arguments */
1298 usb_init_attach_arg(udev, &uaa);
1301 * If the whole USB device is targeted, invoke the USB event
1304 if (iface_index == USB_IFACE_INDEX_ANY) {
1306 EVENTHANDLER_INVOKE(usb_dev_configured, udev, &uaa);
1308 if (uaa.dev_state != UAA_DEV_READY) {
1309 /* leave device unconfigured */
1310 usb_unconfigure(udev, 0);
1315 /* Check if only one interface should be probed: */
1316 if (iface_index != USB_IFACE_INDEX_ANY) {
1324 /* Do the probe and attach */
1325 for (; i != j; i++) {
1327 iface = usbd_get_iface(udev, i);
1328 if (iface == NULL) {
1330 * Looks like the end of the USB
1333 DPRINTFN(2, "end of interfaces "
1337 if (iface->idesc == NULL) {
1338 /* no interface descriptor */
1343 uaa.info.bInterfaceClass =
1344 iface->idesc->bInterfaceClass;
1345 uaa.info.bInterfaceSubClass =
1346 iface->idesc->bInterfaceSubClass;
1347 uaa.info.bInterfaceProtocol =
1348 iface->idesc->bInterfaceProtocol;
1349 uaa.info.bIfaceIndex = i;
1350 uaa.info.bIfaceNum =
1351 iface->idesc->bInterfaceNumber;
1352 uaa.driver_info = 0; /* reset driver_info */
1354 DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1355 uaa.info.bInterfaceClass,
1356 uaa.info.bInterfaceSubClass,
1357 uaa.info.bInterfaceProtocol,
1358 uaa.info.bIfaceIndex,
1359 uaa.info.bIfaceNum);
1361 usb_probe_and_attach_sub(udev, &uaa);
1364 * Remove the leftover child, if any, to enforce that
1365 * a new nomatch devd event is generated for the next
1366 * interface if no driver is found:
1368 if (uaa.temp_dev == NULL)
1370 if (device_delete_child(udev->parent_dev, uaa.temp_dev))
1371 DPRINTFN(0, "device delete child failed\n");
1372 uaa.temp_dev = NULL;
1376 usbd_enum_unlock(udev);
1381 /*------------------------------------------------------------------------*
1382 * usb_suspend_resume_sub
1384 * This function is called when the suspend or resume methods should
1385 * be executed on an USB device.
1386 *------------------------------------------------------------------------*/
1388 usb_suspend_resume_sub(struct usb_device *udev, device_t dev, uint8_t do_suspend)
1395 if (!device_is_attached(dev)) {
1399 err = DEVICE_SUSPEND(dev);
1401 err = DEVICE_RESUME(dev);
1404 device_printf(dev, "%s failed\n",
1405 do_suspend ? "Suspend" : "Resume");
1409 /*------------------------------------------------------------------------*
1410 * usb_suspend_resume
1412 * The following function will suspend or resume the USB device.
1417 *------------------------------------------------------------------------*/
1419 usb_suspend_resume(struct usb_device *udev, uint8_t do_suspend)
1421 struct usb_interface *iface;
1428 DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1430 sx_assert(&udev->sr_sx, SA_LOCKED);
1432 USB_BUS_LOCK(udev->bus);
1433 /* filter the suspend events */
1434 if (udev->flags.peer_suspended == do_suspend) {
1435 USB_BUS_UNLOCK(udev->bus);
1439 udev->flags.peer_suspended = do_suspend;
1440 USB_BUS_UNLOCK(udev->bus);
1442 /* do the suspend or resume */
1444 for (i = 0; i != USB_IFACE_MAX; i++) {
1446 iface = usbd_get_iface(udev, i);
1447 if (iface == NULL) {
1448 /* looks like the end of the USB interfaces */
1451 usb_suspend_resume_sub(udev, iface->subdev, do_suspend);
1456 /*------------------------------------------------------------------------*
1457 * usbd_clear_stall_proc
1459 * This function performs generic USB clear stall operations.
1460 *------------------------------------------------------------------------*/
1462 usbd_clear_stall_proc(struct usb_proc_msg *_pm)
1464 struct usb_clear_stall_msg *pm = (void *)_pm;
1465 struct usb_device *udev = pm->udev;
1468 USB_BUS_UNLOCK(udev->bus);
1469 mtx_lock(&udev->device_mtx);
1471 /* Start clear stall callback */
1472 usbd_transfer_start(udev->ctrl_xfer[1]);
1475 mtx_unlock(&udev->device_mtx);
1476 USB_BUS_LOCK(udev->bus);
1479 /*------------------------------------------------------------------------*
1482 * This function allocates a new USB device. This function is called
1483 * when a new device has been put in the powered state, but not yet in
1484 * the addressed state. Get initial descriptor, set the address, get
1485 * full descriptor and get strings.
1490 *------------------------------------------------------------------------*/
1492 usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
1493 struct usb_device *parent_hub, uint8_t depth, uint8_t port_index,
1494 uint8_t port_no, enum usb_dev_speed speed, enum usb_hc_mode mode)
1496 struct usb_attach_arg uaa;
1497 struct usb_device *udev;
1498 struct usb_device *adev;
1499 struct usb_device *hub;
1500 uint8_t *scratch_ptr;
1501 size_t scratch_size;
1503 uint8_t device_index;
1504 uint8_t config_index;
1505 uint8_t config_quirk;
1506 uint8_t set_config_failed;
1508 DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1509 "port_index=%u, port_no=%u, speed=%u, usb_mode=%u\n",
1510 parent_dev, bus, parent_hub, depth, port_index, port_no,
1514 * Find an unused device index. In USB Host mode this is the
1515 * same as the device address.
1517 * Device index zero is not used and device index 1 should
1518 * always be the root hub.
1520 for (device_index = USB_ROOT_HUB_ADDR;
1521 (device_index != bus->devices_max) &&
1522 (bus->devices[device_index] != NULL);
1523 device_index++) /* nop */;
1525 if (device_index == bus->devices_max) {
1526 device_printf(bus->bdev,
1527 "No free USB device index for new device\n");
1532 device_printf(bus->bdev,
1533 "Invalid device depth\n");
1536 udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1540 /* initialise our SX-lock */
1541 sx_init_flags(&udev->ctrl_sx, "USB device SX lock", SX_DUPOK);
1543 /* initialise our SX-lock */
1544 sx_init_flags(&udev->enum_sx, "USB config SX lock", SX_DUPOK);
1545 sx_init_flags(&udev->sr_sx, "USB suspend and resume SX lock", SX_NOWITNESS);
1547 cv_init(&udev->ctrlreq_cv, "WCTRL");
1548 cv_init(&udev->ref_cv, "UGONE");
1550 /* initialise our mutex */
1551 mtx_init(&udev->device_mtx, "USB device mutex", NULL, MTX_DEF);
1553 /* initialise generic clear stall */
1554 udev->cs_msg[0].hdr.pm_callback = &usbd_clear_stall_proc;
1555 udev->cs_msg[0].udev = udev;
1556 udev->cs_msg[1].hdr.pm_callback = &usbd_clear_stall_proc;
1557 udev->cs_msg[1].udev = udev;
1559 /* initialise some USB device fields */
1560 udev->parent_hub = parent_hub;
1561 udev->parent_dev = parent_dev;
1562 udev->port_index = port_index;
1563 udev->port_no = port_no;
1564 udev->depth = depth;
1566 udev->address = USB_START_ADDR; /* default value */
1567 udev->plugtime = (usb_ticks_t)ticks;
1569 * We need to force the power mode to "on" because there are plenty
1570 * of USB devices out there that do not work very well with
1571 * automatic suspend and resume!
1573 udev->power_mode = usbd_filter_power_mode(udev, USB_POWER_MODE_ON);
1574 udev->pwr_save.last_xfer_time = ticks;
1575 /* we are not ready yet */
1578 /* set up default endpoint descriptor */
1579 udev->ctrl_ep_desc.bLength = sizeof(udev->ctrl_ep_desc);
1580 udev->ctrl_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1581 udev->ctrl_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1582 udev->ctrl_ep_desc.bmAttributes = UE_CONTROL;
1583 udev->ctrl_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1584 udev->ctrl_ep_desc.wMaxPacketSize[1] = 0;
1585 udev->ctrl_ep_desc.bInterval = 0;
1587 /* set up default endpoint companion descriptor */
1588 udev->ctrl_ep_comp_desc.bLength = sizeof(udev->ctrl_ep_comp_desc);
1589 udev->ctrl_ep_comp_desc.bDescriptorType = UDESC_ENDPOINT_SS_COMP;
1591 udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1593 udev->speed = speed;
1594 udev->flags.usb_mode = mode;
1596 /* search for our High Speed USB HUB, if any */
1599 hub = udev->parent_hub;
1602 if (hub->speed == USB_SPEED_HIGH) {
1603 udev->hs_hub_addr = hub->address;
1604 udev->parent_hs_hub = hub;
1605 udev->hs_port_no = adev->port_no;
1609 hub = hub->parent_hub;
1612 /* init the default endpoint */
1613 usb_init_endpoint(udev, 0,
1614 &udev->ctrl_ep_desc,
1615 &udev->ctrl_ep_comp_desc,
1618 /* set device index */
1619 udev->device_index = device_index;
1622 /* Create ugen name */
1623 snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1624 USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1626 LIST_INIT(&udev->pd_list);
1628 /* Create the control endpoint device */
1629 udev->ctrl_dev = usb_make_dev(udev, 0, FREAD|FWRITE);
1631 /* Create a link from /dev/ugenX.X to the default endpoint */
1632 make_dev_alias(udev->ctrl_dev, "%s", udev->ugen_name);
1634 /* Initialise device */
1635 if (bus->methods->device_init != NULL) {
1636 err = (bus->methods->device_init) (udev);
1638 DPRINTFN(0, "device init %d failed "
1639 "(%s, ignored)\n", device_index,
1644 /* set powered device state after device init is complete */
1645 usb_set_device_state(udev, USB_STATE_POWERED);
1647 if (udev->flags.usb_mode == USB_MODE_HOST) {
1649 err = usbd_req_set_address(udev, NULL, device_index);
1652 * This is the new USB device address from now on, if
1653 * the set address request didn't set it already.
1655 if (udev->address == USB_START_ADDR)
1656 udev->address = device_index;
1659 * We ignore any set-address errors, hence there are
1660 * buggy USB devices out there that actually receive
1661 * the SETUP PID, but manage to set the address before
1662 * the STATUS stage is ACK'ed. If the device responds
1663 * to the subsequent get-descriptor at the new
1664 * address, then we know that the set-address command
1668 DPRINTFN(0, "set address %d failed "
1669 "(%s, ignored)\n", udev->address,
1673 /* We are not self powered */
1674 udev->flags.self_powered = 0;
1676 /* Set unconfigured state */
1677 udev->curr_config_no = USB_UNCONFIG_NO;
1678 udev->curr_config_index = USB_UNCONFIG_INDEX;
1680 /* Setup USB descriptors */
1681 err = (usb_temp_setup_by_index_p) (udev, usb_template);
1683 DPRINTFN(0, "setting up USB template failed maybe the USB "
1684 "template module has not been loaded\n");
1688 usb_set_device_state(udev, USB_STATE_ADDRESSED);
1690 /* setup the device descriptor and the initial "wMaxPacketSize" */
1691 err = usbd_setup_device_desc(udev, NULL);
1694 /* XXX try to re-enumerate the device */
1695 err = usbd_req_re_enumerate(udev, NULL);
1701 * Setup temporary USB attach args so that we can figure out some
1702 * basic quirks for this device.
1704 usb_init_attach_arg(udev, &uaa);
1706 if (usb_test_quirk(&uaa, UQ_BUS_POWERED)) {
1707 udev->flags.uq_bus_powered = 1;
1709 if (usb_test_quirk(&uaa, UQ_NO_STRINGS)) {
1710 udev->flags.no_strings = 1;
1713 * Workaround for buggy USB devices.
1715 * It appears that some string-less USB chips will crash and
1716 * disappear if any attempts are made to read any string
1719 * Try to detect such chips by checking the strings in the USB
1720 * device descriptor. If no strings are present there we
1721 * simply disable all USB strings.
1723 scratch_ptr = udev->bus->scratch[0].data;
1724 scratch_size = sizeof(udev->bus->scratch[0].data);
1726 if (udev->ddesc.iManufacturer ||
1727 udev->ddesc.iProduct ||
1728 udev->ddesc.iSerialNumber) {
1729 /* read out the language ID string */
1730 err = usbd_req_get_string_desc(udev, NULL,
1731 (char *)scratch_ptr, 4, 0, USB_LANGUAGE_TABLE);
1733 err = USB_ERR_INVAL;
1736 if (err || (scratch_ptr[0] < 4)) {
1737 udev->flags.no_strings = 1;
1744 /* load preferred value and mask */
1746 mask = usb_lang_mask;
1748 /* align length correctly */
1749 scratch_ptr[0] &= ~1;
1751 /* fix compiler warning */
1754 /* search for preferred language */
1755 for (x = 2; (x < scratch_ptr[0]); x += 2) {
1756 langid = UGETW(scratch_ptr + x);
1757 if ((langid & mask) == pref)
1760 if (x >= scratch_ptr[0]) {
1761 /* pick the first language as the default */
1762 DPRINTFN(1, "Using first language\n");
1763 langid = UGETW(scratch_ptr + 2);
1766 DPRINTFN(1, "Language selected: 0x%04x\n", langid);
1767 udev->langid = langid;
1770 /* assume 100mA bus powered for now. Changed when configured. */
1771 udev->power = USB_MIN_POWER;
1772 /* fetch the vendor and product strings from the device */
1773 usbd_set_device_strings(udev);
1775 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
1776 /* USB device mode setup is complete */
1782 * Most USB devices should attach to config index 0 by
1785 if (usb_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1788 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1791 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1794 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1797 } else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1805 set_config_failed = 0;
1808 DPRINTF("setting config %u\n", config_index);
1810 /* get the USB device configured */
1811 err = usbd_set_config_index(udev, config_index);
1813 if (udev->ddesc.bNumConfigurations != 0) {
1814 if (!set_config_failed) {
1815 set_config_failed = 1;
1816 /* XXX try to re-enumerate the device */
1817 err = usbd_req_re_enumerate(udev, NULL);
1819 goto repeat_set_config;
1821 DPRINTFN(0, "Failure selecting configuration index %u:"
1822 "%s, port %u, addr %u (ignored)\n",
1823 config_index, usbd_errstr(err), udev->port_no,
1827 * Some USB devices do not have any configurations. Ignore any
1828 * set config failures!
1833 if (!config_quirk && config_index + 1 < udev->ddesc.bNumConfigurations) {
1834 if ((udev->cdesc->bNumInterface < 2) &&
1835 usbd_get_no_descriptors(udev->cdesc, UDESC_ENDPOINT) == 0) {
1836 DPRINTFN(0, "Found no endpoints, trying next config\n");
1838 goto repeat_set_config;
1840 if (config_index == 0) {
1842 * Try to figure out if we have an
1843 * auto-install disk there:
1845 if (usb_iface_is_cdrom(udev, 0)) {
1846 DPRINTFN(0, "Found possible auto-install "
1847 "disk (trying next config)\n");
1849 goto repeat_set_config;
1855 DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1856 udev->address, udev, udev->parent_hub);
1858 /* register our device - we are ready */
1859 usb_bus_port_set_device(bus, parent_hub ?
1860 parent_hub->hub->ports + port_index : NULL, udev, device_index);
1863 /* Symlink the ugen device name */
1864 udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
1866 /* Announce device */
1867 printf("%s: <%s> at %s\n", udev->ugen_name,
1868 usb_get_manufacturer(udev),
1869 device_get_nameunit(udev->bus->bdev));
1873 usb_notify_addq("ATTACH", udev);
1878 * Free USB device and all subdevices, if any.
1880 usb_free_device(udev, 0);
1887 static struct cdev *
1888 usb_make_dev(struct usb_device *udev, int ep, int mode)
1890 struct usb_fs_privdata* pd;
1893 /* Store information to locate ourselves again later */
1894 pd = malloc(sizeof(struct usb_fs_privdata), M_USBDEV,
1896 pd->bus_index = device_get_unit(udev->bus->bdev);
1897 pd->dev_index = udev->device_index;
1901 /* Now, create the device itself */
1902 snprintf(devname, sizeof(devname), "%u.%u.%u",
1903 pd->bus_index, pd->dev_index, pd->ep_addr);
1904 pd->cdev = make_dev(&usb_devsw, 0, UID_ROOT,
1905 GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1906 pd->cdev->si_drv1 = pd;
1912 usb_cdev_create(struct usb_device *udev)
1914 struct usb_config_descriptor *cd;
1915 struct usb_endpoint_descriptor *ed;
1916 struct usb_descriptor *desc;
1917 struct usb_fs_privdata* pd;
1919 int inmode, outmode, inmask, outmask, mode;
1922 KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1924 DPRINTFN(2, "Creating device nodes\n");
1926 if (usbd_get_mode(udev) == USB_MODE_DEVICE) {
1929 } else { /* USB_MODE_HOST */
1939 * Collect all used endpoint numbers instead of just
1940 * generating 16 static endpoints.
1942 cd = usbd_get_config_descriptor(udev);
1943 while ((desc = usb_desc_foreach(cd, desc))) {
1944 /* filter out all endpoint descriptors */
1945 if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1946 (desc->bLength >= sizeof(*ed))) {
1947 ed = (struct usb_endpoint_descriptor *)desc;
1950 ep = ed->bEndpointAddress;
1951 if (UE_GET_DIR(ep) == UE_DIR_OUT)
1952 outmask |= 1 << UE_GET_ADDR(ep);
1954 inmask |= 1 << UE_GET_ADDR(ep);
1958 /* Create all available endpoints except EP0 */
1959 for (ep = 1; ep < 16; ep++) {
1960 mode = inmask & (1 << ep) ? inmode : 0;
1961 mode |= outmask & (1 << ep) ? outmode : 0;
1963 continue; /* no IN or OUT endpoint */
1965 dev = usb_make_dev(udev, ep, mode);
1967 LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1972 usb_cdev_free(struct usb_device *udev)
1974 struct usb_fs_privdata* pd;
1977 DPRINTFN(2, "Freeing device nodes\n");
1979 while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1980 KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1984 LIST_REMOVE(pd, pd_next);
1986 destroy_dev_sched_cb(pcdev, usb_cdev_cleanup, pd);
1991 usb_cdev_cleanup(void* arg)
1993 free(arg, M_USBDEV);
1997 /*------------------------------------------------------------------------*
2000 * This function is NULL safe and will free an USB device and its
2001 * children devices, if any.
2003 * Flag values: Reserved, set to zero.
2004 *------------------------------------------------------------------------*/
2006 usb_free_device(struct usb_device *udev, uint8_t flag)
2008 struct usb_bus *bus;
2011 return; /* already freed */
2013 DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
2016 usb_set_device_state(udev, USB_STATE_DETACHED);
2019 usb_notify_addq("DETACH", udev);
2023 printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
2024 usb_get_manufacturer(udev), device_get_nameunit(bus->bdev));
2026 /* Destroy UGEN symlink, if any */
2027 if (udev->ugen_symlink) {
2028 usb_free_symlink(udev->ugen_symlink);
2029 udev->ugen_symlink = NULL;
2033 * Unregister our device first which will prevent any further
2036 usb_bus_port_set_device(bus, udev->parent_hub ?
2037 udev->parent_hub->hub->ports + udev->port_index : NULL,
2038 NULL, USB_ROOT_HUB_ADDR);
2041 /* wait for all pending references to go away: */
2042 mtx_lock(&usb_ref_lock);
2044 while (udev->refcount != 0) {
2045 cv_wait(&udev->ref_cv, &usb_ref_lock);
2047 mtx_unlock(&usb_ref_lock);
2049 destroy_dev_sched_cb(udev->ctrl_dev, usb_cdev_cleanup,
2050 udev->ctrl_dev->si_drv1);
2053 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2054 /* stop receiving any control transfers (Device Side Mode) */
2055 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2058 /* the following will get the device unconfigured in software */
2059 usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_EP0);
2061 /* unsetup any leftover default USB transfers */
2062 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2064 /* template unsetup, if any */
2065 (usb_temp_unsetup_p) (udev);
2068 * Make sure that our clear-stall messages are not queued
2071 USB_BUS_LOCK(udev->bus);
2072 usb_proc_mwait(&udev->bus->non_giant_callback_proc,
2073 &udev->cs_msg[0], &udev->cs_msg[1]);
2074 USB_BUS_UNLOCK(udev->bus);
2076 sx_destroy(&udev->ctrl_sx);
2077 sx_destroy(&udev->enum_sx);
2078 sx_destroy(&udev->sr_sx);
2080 cv_destroy(&udev->ctrlreq_cv);
2081 cv_destroy(&udev->ref_cv);
2083 mtx_destroy(&udev->device_mtx);
2085 KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2088 /* Uninitialise device */
2089 if (bus->methods->device_uninit != NULL)
2090 (bus->methods->device_uninit) (udev);
2093 free(udev->serial, M_USB);
2094 free(udev->manufacturer, M_USB);
2095 free(udev->product, M_USB);
2099 /*------------------------------------------------------------------------*
2102 * This function is the safe way to get the USB interface structure
2103 * pointer by interface index.
2106 * NULL: Interface not present.
2107 * Else: Pointer to USB interface structure.
2108 *------------------------------------------------------------------------*/
2109 struct usb_interface *
2110 usbd_get_iface(struct usb_device *udev, uint8_t iface_index)
2112 struct usb_interface *iface = udev->ifaces + iface_index;
2114 if (iface_index >= udev->ifaces_max)
2119 /*------------------------------------------------------------------------*
2120 * usbd_find_descriptor
2122 * This function will lookup the first descriptor that matches the
2123 * criteria given by the arguments "type" and "subtype". Descriptors
2124 * will only be searched within the interface having the index
2125 * "iface_index". If the "id" argument points to an USB descriptor,
2126 * it will be skipped before the search is started. This allows
2127 * searching for multiple descriptors using the same criteria. Else
2128 * the search is started after the interface descriptor.
2131 * NULL: End of descriptors
2132 * Else: A descriptor matching the criteria
2133 *------------------------------------------------------------------------*/
2135 usbd_find_descriptor(struct usb_device *udev, void *id, uint8_t iface_index,
2136 uint8_t type, uint8_t type_mask,
2137 uint8_t subtype, uint8_t subtype_mask)
2139 struct usb_descriptor *desc;
2140 struct usb_config_descriptor *cd;
2141 struct usb_interface *iface;
2143 cd = usbd_get_config_descriptor(udev);
2148 iface = usbd_get_iface(udev, iface_index);
2149 if (iface == NULL) {
2152 id = usbd_get_interface_descriptor(iface);
2159 while ((desc = usb_desc_foreach(cd, desc))) {
2161 if (desc->bDescriptorType == UDESC_INTERFACE) {
2164 if (((desc->bDescriptorType & type_mask) == type) &&
2165 ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2172 /*------------------------------------------------------------------------*
2175 * This function will dump information from the device descriptor
2176 * belonging to the USB device pointed to by "udev", to the string
2177 * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2178 * including the terminating zero.
2179 *------------------------------------------------------------------------*/
2181 usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
2183 struct usb_device_descriptor *udd = &udev->ddesc;
2187 bcdUSB = UGETW(udd->bcdUSB);
2188 bcdDevice = UGETW(udd->bcdDevice);
2190 if (udd->bDeviceClass != 0xFF) {
2191 snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2193 usb_get_manufacturer(udev),
2194 usb_get_product(udev),
2195 udd->bDeviceClass, udd->bDeviceSubClass,
2196 (bcdUSB >> 8), bcdUSB & 0xFF,
2197 (bcdDevice >> 8), bcdDevice & 0xFF,
2200 snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2202 usb_get_manufacturer(udev),
2203 usb_get_product(udev),
2204 (bcdUSB >> 8), bcdUSB & 0xFF,
2205 (bcdDevice >> 8), bcdDevice & 0xFF,
2212 * Descriptions of of known vendors and devices ("products").
2214 struct usb_knowndev {
2218 const char *vendorname;
2219 const char *productname;
2222 #define USB_KNOWNDEV_NOPROD 0x01 /* match on vendor only */
2224 #include "usbdevs.h"
2225 #include "usbdevs_data.h"
2226 #endif /* USB_VERBOSE */
2229 usbd_set_device_strings(struct usb_device *udev)
2231 struct usb_device_descriptor *udd = &udev->ddesc;
2233 const struct usb_knowndev *kdp;
2238 uint16_t product_id;
2240 temp_ptr = (char *)udev->bus->scratch[0].data;
2241 temp_size = sizeof(udev->bus->scratch[0].data);
2243 vendor_id = UGETW(udd->idVendor);
2244 product_id = UGETW(udd->idProduct);
2246 /* get serial number string */
2247 usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2248 udev->ddesc.iSerialNumber);
2249 udev->serial = strdup(temp_ptr, M_USB);
2251 /* get manufacturer string */
2252 usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2253 udev->ddesc.iManufacturer);
2254 usb_trim_spaces(temp_ptr);
2255 if (temp_ptr[0] != '\0')
2256 udev->manufacturer = strdup(temp_ptr, M_USB);
2258 /* get product string */
2259 usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2260 udev->ddesc.iProduct);
2261 usb_trim_spaces(temp_ptr);
2262 if (temp_ptr[0] != '\0')
2263 udev->product = strdup(temp_ptr, M_USB);
2266 if (udev->manufacturer == NULL || udev->product == NULL) {
2267 for (kdp = usb_knowndevs; kdp->vendorname != NULL; kdp++) {
2268 if (kdp->vendor == vendor_id &&
2269 (kdp->product == product_id ||
2270 (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2273 if (kdp->vendorname != NULL) {
2274 /* XXX should use pointer to knowndevs string */
2275 if (udev->manufacturer == NULL) {
2276 udev->manufacturer = strdup(kdp->vendorname,
2279 if (udev->product == NULL &&
2280 (kdp->flags & USB_KNOWNDEV_NOPROD) == 0) {
2281 udev->product = strdup(kdp->productname,
2287 /* Provide default strings if none were found */
2288 if (udev->manufacturer == NULL) {
2289 snprintf(temp_ptr, temp_size, "vendor 0x%04x", vendor_id);
2290 udev->manufacturer = strdup(temp_ptr, M_USB);
2292 if (udev->product == NULL) {
2293 snprintf(temp_ptr, temp_size, "product 0x%04x", product_id);
2294 udev->product = strdup(temp_ptr, M_USB);
2303 usbd_get_mode(struct usb_device *udev)
2305 return (udev->flags.usb_mode);
2310 * See: USB_SPEED_XXX
2313 usbd_get_speed(struct usb_device *udev)
2315 return (udev->speed);
2319 usbd_get_isoc_fps(struct usb_device *udev)
2322 switch (udev->speed) {
2324 case USB_SPEED_FULL:
2331 struct usb_device_descriptor *
2332 usbd_get_device_descriptor(struct usb_device *udev)
2335 return (NULL); /* be NULL safe */
2336 return (&udev->ddesc);
2339 struct usb_config_descriptor *
2340 usbd_get_config_descriptor(struct usb_device *udev)
2343 return (NULL); /* be NULL safe */
2344 return (udev->cdesc);
2347 /*------------------------------------------------------------------------*
2348 * usb_test_quirk - test a device for a given quirk
2351 * 0: The USB device does not have the given quirk.
2352 * Else: The USB device has the given quirk.
2353 *------------------------------------------------------------------------*/
2355 usb_test_quirk(const struct usb_attach_arg *uaa, uint16_t quirk)
2359 found = (usb_test_quirk_p) (&uaa->info, quirk);
2363 struct usb_interface_descriptor *
2364 usbd_get_interface_descriptor(struct usb_interface *iface)
2367 return (NULL); /* be NULL safe */
2368 return (iface->idesc);
2372 usbd_get_interface_altindex(struct usb_interface *iface)
2374 return (iface->alt_index);
2378 usbd_get_bus_index(struct usb_device *udev)
2380 return ((uint8_t)device_get_unit(udev->bus->bdev));
2384 usbd_get_device_index(struct usb_device *udev)
2386 return (udev->device_index);
2390 /*------------------------------------------------------------------------*
2393 * This function will generate events for dev.
2394 *------------------------------------------------------------------------*/
2395 #ifndef BURN_BRIDGES
2397 usb_notify_addq_compat(const char *type, struct usb_device *udev)
2401 struct malloc_type *mt;
2402 const size_t buf_size = 512;
2404 /* Convert notify type */
2405 if (strcmp(type, "ATTACH") == 0)
2407 else if (strcmp(type, "DETACH") == 0)
2412 mtx_lock(&malloc_mtx);
2413 mt = malloc_desc2type("bus"); /* XXX M_BUS */
2414 mtx_unlock(&malloc_mtx);
2418 data = malloc(buf_size, mt, M_NOWAIT);
2422 /* String it all together. */
2423 snprintf(data, buf_size,
2432 "devsubclass=0x%02x "
2444 UGETW(udev->ddesc.idVendor),
2445 UGETW(udev->ddesc.idProduct),
2446 udev->ddesc.bDeviceClass,
2447 udev->ddesc.bDeviceSubClass,
2448 usb_get_serial(udev),
2449 UGETW(udev->ddesc.bcdDevice)
2451 , udev->parent_hub != NULL ?
2452 udev->parent_hub->ugen_name :
2453 device_get_nameunit(device_get_parent(udev->bus->bdev))
2457 devctl_queue_data(data);
2462 usb_notify_addq(const char *type, struct usb_device *udev)
2464 struct usb_interface *iface;
2468 #ifndef BURN_BRIDGES
2469 usb_notify_addq_compat(type, udev);
2472 /* announce the device */
2473 sb = sbuf_new_auto();
2482 "devsubclass=0x%02x "
2495 UGETW(udev->ddesc.idVendor),
2496 UGETW(udev->ddesc.idProduct),
2497 udev->ddesc.bDeviceClass,
2498 udev->ddesc.bDeviceSubClass,
2499 usb_get_serial(udev),
2500 UGETW(udev->ddesc.bcdDevice),
2501 (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2504 , udev->parent_hub != NULL ?
2505 udev->parent_hub->ugen_name :
2506 device_get_nameunit(device_get_parent(udev->bus->bdev))
2510 devctl_notify("USB", "DEVICE", type, sbuf_data(sb));
2513 /* announce each interface */
2514 for (i = 0; i < USB_IFACE_MAX; i++) {
2515 iface = usbd_get_iface(udev, i);
2517 break; /* end of interfaces */
2518 if (iface->idesc == NULL)
2519 continue; /* no interface descriptor */
2521 sb = sbuf_new_auto();
2530 "devsubclass=0x%02x "
2537 "intsubclass=0x%02x "
2538 "intprotocol=0x%02x",
2543 UGETW(udev->ddesc.idVendor),
2544 UGETW(udev->ddesc.idProduct),
2545 udev->ddesc.bDeviceClass,
2546 udev->ddesc.bDeviceSubClass,
2547 usb_get_serial(udev),
2548 UGETW(udev->ddesc.bcdDevice),
2549 (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2550 iface->idesc->bInterfaceNumber,
2551 iface->idesc->bNumEndpoints,
2552 iface->idesc->bInterfaceClass,
2553 iface->idesc->bInterfaceSubClass,
2554 iface->idesc->bInterfaceProtocol);
2556 devctl_notify("USB", "INTERFACE", type, sbuf_data(sb));
2563 /*------------------------------------------------------------------------*
2564 * usb_fifo_free_wrap
2566 * This function will free the FIFOs.
2568 * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2569 * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2570 * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2571 * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2572 * control endpoint FIFOs. If "iface_index" is not set to
2573 * "USB_IFACE_INDEX_ANY" the flag has no effect.
2574 *------------------------------------------------------------------------*/
2576 usb_fifo_free_wrap(struct usb_device *udev,
2577 uint8_t iface_index, uint8_t flag)
2583 * Free any USB FIFOs on the given interface:
2585 for (i = 0; i != USB_FIFO_MAX; i++) {
2590 /* Check if the interface index matches */
2591 if (iface_index == f->iface_index) {
2592 if (f->methods != &usb_ugen_methods) {
2594 * Don't free any non-generic FIFOs in
2599 if ((f->dev_ep_index == 0) &&
2600 (f->fs_xfer == NULL)) {
2601 /* no need to free this FIFO */
2604 } else if (iface_index == USB_IFACE_INDEX_ANY) {
2605 if ((f->methods == &usb_ugen_methods) &&
2606 (f->dev_ep_index == 0) &&
2607 (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2608 (f->fs_xfer == NULL)) {
2609 /* no need to free this FIFO */
2613 /* no need to free this FIFO */
2616 /* free this FIFO */
2622 /*------------------------------------------------------------------------*
2623 * usb_peer_can_wakeup
2626 * 0: Peer cannot do resume signalling.
2627 * Else: Peer can do resume signalling.
2628 *------------------------------------------------------------------------*/
2630 usb_peer_can_wakeup(struct usb_device *udev)
2632 const struct usb_config_descriptor *cdp;
2635 if ((cdp != NULL) && (udev->flags.usb_mode == USB_MODE_HOST)) {
2636 return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2638 return (0); /* not supported */
2642 usb_set_device_state(struct usb_device *udev, enum usb_dev_state state)
2645 KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2647 DPRINTF("udev %p state %s -> %s\n", udev,
2648 usb_statestr(udev->state), usb_statestr(state));
2649 udev->state = state;
2651 if (udev->bus->methods->device_state_change != NULL)
2652 (udev->bus->methods->device_state_change) (udev);
2656 usb_get_device_state(struct usb_device *udev)
2659 return (USB_STATE_DETACHED);
2660 return (udev->state);
2664 usbd_device_attached(struct usb_device *udev)
2666 return (udev->state > USB_STATE_DETACHED);
2669 /* The following function locks enumerating the given USB device. */
2672 usbd_enum_lock(struct usb_device *udev)
2674 sx_xlock(&udev->enum_sx);
2675 sx_xlock(&udev->sr_sx);
2677 * NEWBUS LOCK NOTE: We should check if any parent SX locks
2678 * are locked before locking Giant. Else the lock can be
2679 * locked multiple times.
2684 /* The following function unlocks enumerating the given USB device. */
2687 usbd_enum_unlock(struct usb_device *udev)
2690 sx_xunlock(&udev->enum_sx);
2691 sx_xunlock(&udev->sr_sx);
2694 /* The following function locks suspend and resume. */
2697 usbd_sr_lock(struct usb_device *udev)
2699 sx_xlock(&udev->sr_sx);
2701 * NEWBUS LOCK NOTE: We should check if any parent SX locks
2702 * are locked before locking Giant. Else the lock can be
2703 * locked multiple times.
2708 /* The following function unlocks suspend and resume. */
2711 usbd_sr_unlock(struct usb_device *udev)
2714 sx_xunlock(&udev->sr_sx);
2718 * The following function checks the enumerating lock for the given
2723 usbd_enum_is_locked(struct usb_device *udev)
2725 return (sx_xlocked(&udev->enum_sx));
2729 * The following function is used to set the per-interface specific
2730 * plug and play information. The string referred to by the pnpinfo
2731 * argument can safely be freed after calling this function. The
2732 * pnpinfo of an interface will be reset at device detach or when
2733 * passing a NULL argument to this function. This function
2734 * returns zero on success, else a USB_ERR_XXX failure code.
2738 usbd_set_pnpinfo(struct usb_device *udev, uint8_t iface_index, const char *pnpinfo)
2740 struct usb_interface *iface;
2742 iface = usbd_get_iface(udev, iface_index);
2744 return (USB_ERR_INVAL);
2746 if (iface->pnpinfo != NULL) {
2747 free(iface->pnpinfo, M_USBDEV);
2748 iface->pnpinfo = NULL;
2751 if (pnpinfo == NULL || pnpinfo[0] == 0)
2752 return (0); /* success */
2754 iface->pnpinfo = strdup(pnpinfo, M_USBDEV);
2755 if (iface->pnpinfo == NULL)
2756 return (USB_ERR_NOMEM);
2758 return (0); /* success */