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