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