xref: /freebsd/sys/dev/usb/usb_device.c (revision f4f8f02054f3abb6ceb84aefcdecc78d5c8b462f)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <dev/usb/usb_mfunc.h>
28 #include <dev/usb/usb_error.h>
29 #include <dev/usb/usb.h>
30 #include <dev/usb/usb_ioctl.h>
31 #include "usbdevs.h"
32 
33 #define	USB_DEBUG_VAR usb2_debug
34 
35 #include <dev/usb/usb_core.h>
36 #include <dev/usb/usb_debug.h>
37 #include <dev/usb/usb_process.h>
38 #include <dev/usb/usb_device.h>
39 #include <dev/usb/usb_busdma.h>
40 #include <dev/usb/usb_transfer.h>
41 #include <dev/usb/usb_parse.h>
42 #include <dev/usb/usb_request.h>
43 #include <dev/usb/usb_dynamic.h>
44 #include <dev/usb/usb_hub.h>
45 #include <dev/usb/usb_util.h>
46 #include <dev/usb/usb_mbuf.h>
47 #include <dev/usb/usb_msctest.h>
48 #if USB_HAVE_UGEN
49 #include <dev/usb/usb_dev.h>
50 #include <dev/usb/usb_generic.h>
51 #endif
52 
53 #include <dev/usb/quirk/usb_quirk.h>
54 
55 #include <dev/usb/usb_controller.h>
56 #include <dev/usb/usb_bus.h>
57 
58 /* function prototypes  */
59 
60 static void	usb2_init_pipe(struct usb2_device *, uint8_t,
61 		    struct usb2_endpoint_descriptor *, struct usb2_pipe *);
62 static void	usb2_unconfigure(struct usb2_device *, uint8_t);
63 static void	usb2_detach_device(struct usb2_device *, uint8_t, uint8_t);
64 static void	usb2_detach_device_sub(struct usb2_device *, device_t *,
65 		    uint8_t);
66 static uint8_t	usb2_probe_and_attach_sub(struct usb2_device *,
67 		    struct usb2_attach_arg *);
68 static void	usb2_init_attach_arg(struct usb2_device *,
69 		    struct usb2_attach_arg *);
70 static void	usb2_suspend_resume_sub(struct usb2_device *, device_t,
71 		    uint8_t);
72 static void	usb2_clear_stall_proc(struct usb2_proc_msg *_pm);
73 usb2_error_t	usb2_config_parse(struct usb2_device *, uint8_t, uint8_t);
74 #if USB_HAVE_STRINGS
75 static void	usb2_check_strings(struct usb2_device *);
76 #endif
77 #if USB_HAVE_UGEN
78 static void	usb2_notify_addq(const char *type, struct usb2_device *);
79 static void	usb2_fifo_free_wrap(struct usb2_device *, uint8_t, uint8_t);
80 static struct cdev *usb2_make_dev(struct usb2_device *, int, int);
81 static void	usb2_cdev_create(struct usb2_device *);
82 static void	usb2_cdev_free(struct usb2_device *);
83 static void	usb2_cdev_cleanup(void *);
84 #endif
85 
86 /* This variable is global to allow easy access to it: */
87 
88 int	usb2_template = 0;
89 
90 SYSCTL_INT(_hw_usb2, OID_AUTO, template, CTLFLAG_RW,
91     &usb2_template, 0, "Selected USB device side template");
92 
93 static const char* statestr[USB_STATE_MAX] = {
94 	[USB_STATE_DETACHED]	= "DETACHED",
95 	[USB_STATE_ATTACHED]	= "ATTACHED",
96 	[USB_STATE_POWERED]	= "POWERED",
97 	[USB_STATE_ADDRESSED]	= "ADDRESSED",
98 	[USB_STATE_CONFIGURED]	= "CONFIGURED",
99 };
100 
101 const char *
102 usb2_statestr(enum usb2_dev_state state)
103 {
104 	return ((state < USB_STATE_MAX) ? statestr[state] : "UNKNOWN");
105 }
106 
107 /*------------------------------------------------------------------------*
108  *	usb2_get_pipe_by_addr
109  *
110  * This function searches for an USB pipe by endpoint address and
111  * direction.
112  *
113  * Returns:
114  * NULL: Failure
115  * Else: Success
116  *------------------------------------------------------------------------*/
117 struct usb2_pipe *
118 usb2_get_pipe_by_addr(struct usb2_device *udev, uint8_t ea_val)
119 {
120 	struct usb2_pipe *pipe = udev->pipes;
121 	struct usb2_pipe *pipe_end = udev->pipes + udev->pipes_max;
122 	enum {
123 		EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
124 	};
125 
126 	/*
127 	 * According to the USB specification not all bits are used
128 	 * for the endpoint address. Keep defined bits only:
129 	 */
130 	ea_val &= EA_MASK;
131 
132 	/*
133 	 * Iterate accross all the USB pipes searching for a match
134 	 * based on the endpoint address:
135 	 */
136 	for (; pipe != pipe_end; pipe++) {
137 
138 		if (pipe->edesc == NULL) {
139 			continue;
140 		}
141 		/* do the mask and check the value */
142 		if ((pipe->edesc->bEndpointAddress & EA_MASK) == ea_val) {
143 			goto found;
144 		}
145 	}
146 
147 	/*
148 	 * The default pipe is always present and is checked separately:
149 	 */
150 	if ((udev->default_pipe.edesc) &&
151 	    ((udev->default_pipe.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
152 		pipe = &udev->default_pipe;
153 		goto found;
154 	}
155 	return (NULL);
156 
157 found:
158 	return (pipe);
159 }
160 
161 /*------------------------------------------------------------------------*
162  *	usb2_get_pipe
163  *
164  * This function searches for an USB pipe based on the information
165  * given by the passed "struct usb2_config" pointer.
166  *
167  * Return values:
168  * NULL: No match.
169  * Else: Pointer to "struct usb2_pipe".
170  *------------------------------------------------------------------------*/
171 struct usb2_pipe *
172 usb2_get_pipe(struct usb2_device *udev, uint8_t iface_index,
173     const struct usb2_config *setup)
174 {
175 	struct usb2_pipe *pipe = udev->pipes;
176 	struct usb2_pipe *pipe_end = udev->pipes + udev->pipes_max;
177 	uint8_t index = setup->ep_index;
178 	uint8_t ea_mask;
179 	uint8_t ea_val;
180 	uint8_t type_mask;
181 	uint8_t type_val;
182 
183 	DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
184 	    "type=0x%x dir=0x%x index=%d\n",
185 	    udev, iface_index, setup->endpoint,
186 	    setup->type, setup->direction, setup->ep_index);
187 
188 	/* check USB mode */
189 
190 	if ((setup->usb_mode != USB_MODE_MAX) &&
191 	    (udev->flags.usb2_mode != setup->usb_mode)) {
192 		/* wrong mode - no pipe */
193 		return (NULL);
194 	}
195 
196 	/* setup expected endpoint direction mask and value */
197 
198 	if (setup->direction == UE_DIR_RX) {
199 		ea_mask = (UE_DIR_IN | UE_DIR_OUT);
200 		ea_val = (udev->flags.usb2_mode == USB_MODE_DEVICE) ?
201 		    UE_DIR_OUT : UE_DIR_IN;
202 	} else if (setup->direction == UE_DIR_TX) {
203 		ea_mask = (UE_DIR_IN | UE_DIR_OUT);
204 		ea_val = (udev->flags.usb2_mode == USB_MODE_DEVICE) ?
205 		    UE_DIR_IN : UE_DIR_OUT;
206 	} else if (setup->direction == UE_DIR_ANY) {
207 		/* match any endpoint direction */
208 		ea_mask = 0;
209 		ea_val = 0;
210 	} else {
211 		/* match the given endpoint direction */
212 		ea_mask = (UE_DIR_IN | UE_DIR_OUT);
213 		ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
214 	}
215 
216 	/* setup expected endpoint address */
217 
218 	if (setup->endpoint == UE_ADDR_ANY) {
219 		/* match any endpoint address */
220 	} else {
221 		/* match the given endpoint address */
222 		ea_mask |= UE_ADDR;
223 		ea_val |= (setup->endpoint & UE_ADDR);
224 	}
225 
226 	/* setup expected endpoint type */
227 
228 	if (setup->type == UE_BULK_INTR) {
229 		/* this will match BULK and INTERRUPT endpoints */
230 		type_mask = 2;
231 		type_val = 2;
232 	} else if (setup->type == UE_TYPE_ANY) {
233 		/* match any endpoint type */
234 		type_mask = 0;
235 		type_val = 0;
236 	} else {
237 		/* match the given endpoint type */
238 		type_mask = UE_XFERTYPE;
239 		type_val = (setup->type & UE_XFERTYPE);
240 	}
241 
242 	/*
243 	 * Iterate accross all the USB pipes searching for a match
244 	 * based on the endpoint address. Note that we are searching
245 	 * the pipes from the beginning of the "udev->pipes" array.
246 	 */
247 	for (; pipe != pipe_end; pipe++) {
248 
249 		if ((pipe->edesc == NULL) ||
250 		    (pipe->iface_index != iface_index)) {
251 			continue;
252 		}
253 		/* do the masks and check the values */
254 
255 		if (((pipe->edesc->bEndpointAddress & ea_mask) == ea_val) &&
256 		    ((pipe->edesc->bmAttributes & type_mask) == type_val)) {
257 			if (!index--) {
258 				goto found;
259 			}
260 		}
261 	}
262 
263 	/*
264 	 * Match against default pipe last, so that "any pipe", "any
265 	 * address" and "any direction" returns the first pipe of the
266 	 * interface. "iface_index" and "direction" is ignored:
267 	 */
268 	if ((udev->default_pipe.edesc) &&
269 	    ((udev->default_pipe.edesc->bEndpointAddress & ea_mask) == ea_val) &&
270 	    ((udev->default_pipe.edesc->bmAttributes & type_mask) == type_val) &&
271 	    (!index)) {
272 		pipe = &udev->default_pipe;
273 		goto found;
274 	}
275 	return (NULL);
276 
277 found:
278 	return (pipe);
279 }
280 
281 /*------------------------------------------------------------------------*
282  *	usb2_interface_count
283  *
284  * This function stores the number of USB interfaces excluding
285  * alternate settings, which the USB config descriptor reports into
286  * the unsigned 8-bit integer pointed to by "count".
287  *
288  * Returns:
289  *    0: Success
290  * Else: Failure
291  *------------------------------------------------------------------------*/
292 usb2_error_t
293 usb2_interface_count(struct usb2_device *udev, uint8_t *count)
294 {
295 	if (udev->cdesc == NULL) {
296 		*count = 0;
297 		return (USB_ERR_NOT_CONFIGURED);
298 	}
299 	*count = udev->ifaces_max;
300 	return (USB_ERR_NORMAL_COMPLETION);
301 }
302 
303 
304 /*------------------------------------------------------------------------*
305  *	usb2_init_pipe
306  *
307  * This function will initialise the USB pipe structure pointed to by
308  * the "pipe" argument. The structure pointed to by "pipe" must be
309  * zeroed before calling this function.
310  *------------------------------------------------------------------------*/
311 static void
312 usb2_init_pipe(struct usb2_device *udev, uint8_t iface_index,
313     struct usb2_endpoint_descriptor *edesc, struct usb2_pipe *pipe)
314 {
315 	struct usb2_bus_methods *methods;
316 
317 	methods = udev->bus->methods;
318 
319 	(methods->pipe_init) (udev, edesc, pipe);
320 
321 	/* initialise USB pipe structure */
322 	pipe->edesc = edesc;
323 	pipe->iface_index = iface_index;
324 	TAILQ_INIT(&pipe->pipe_q.head);
325 	pipe->pipe_q.command = &usb2_pipe_start;
326 
327 	/* the pipe is not supported by the hardware */
328  	if (pipe->methods == NULL)
329 		return;
330 
331 	/* clear stall, if any */
332 	if (methods->clear_stall != NULL) {
333 		USB_BUS_LOCK(udev->bus);
334 		(methods->clear_stall) (udev, pipe);
335 		USB_BUS_UNLOCK(udev->bus);
336 	}
337 }
338 
339 /*-----------------------------------------------------------------------*
340  *	usb2_pipe_foreach
341  *
342  * This function will iterate all the USB endpoints except the control
343  * endpoint. This function is NULL safe.
344  *
345  * Return values:
346  * NULL: End of USB pipes
347  * Else: Pointer to next USB pipe
348  *------------------------------------------------------------------------*/
349 struct usb2_pipe *
350 usb2_pipe_foreach(struct usb2_device *udev, struct usb2_pipe *pipe)
351 {
352 	struct usb2_pipe *pipe_end = udev->pipes + udev->pipes_max;
353 
354 	/* be NULL safe */
355 	if (udev == NULL)
356 		return (NULL);
357 
358 	/* get next pipe */
359 	if (pipe == NULL)
360 		pipe = udev->pipes;
361 	else
362 		pipe++;
363 
364 	/* find next allocated pipe */
365 	while (pipe != pipe_end) {
366 		if (pipe->edesc != NULL)
367 			return (pipe);
368 		pipe++;
369 	}
370 	return (NULL);
371 }
372 
373 /*------------------------------------------------------------------------*
374  *	usb2_unconfigure
375  *
376  * This function will free all USB interfaces and USB pipes belonging
377  * to an USB device.
378  *
379  * Flag values, see "USB_UNCFG_FLAG_XXX".
380  *------------------------------------------------------------------------*/
381 static void
382 usb2_unconfigure(struct usb2_device *udev, uint8_t flag)
383 {
384 	uint8_t do_unlock;
385 
386 	/* automatic locking */
387 	if (sx_xlocked(udev->default_sx + 1)) {
388 		do_unlock = 0;
389 	} else {
390 		do_unlock = 1;
391 		sx_xlock(udev->default_sx + 1);
392 	}
393 
394 	/* detach all interface drivers */
395 	usb2_detach_device(udev, USB_IFACE_INDEX_ANY, flag);
396 
397 #if USB_HAVE_UGEN
398 	/* free all FIFOs except control endpoint FIFOs */
399 	usb2_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, flag);
400 
401 	/*
402 	 * Free all cdev's, if any.
403 	 */
404 	usb2_cdev_free(udev);
405 #endif
406 
407 #if USB_HAVE_COMPAT_LINUX
408 	/* free Linux compat device, if any */
409 	if (udev->linux_dev) {
410 		usb_linux_free_device(udev->linux_dev);
411 		udev->linux_dev = NULL;
412 	}
413 #endif
414 
415 	usb2_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_FREE);
416 
417 	/* free "cdesc" after "ifaces" and "pipes", if any */
418 	if (udev->cdesc != NULL) {
419 		if (udev->flags.usb2_mode != USB_MODE_DEVICE)
420 			free(udev->cdesc, M_USB);
421 		udev->cdesc = NULL;
422 	}
423 	/* set unconfigured state */
424 	udev->curr_config_no = USB_UNCONFIG_NO;
425 	udev->curr_config_index = USB_UNCONFIG_INDEX;
426 
427 	if (do_unlock) {
428 		sx_unlock(udev->default_sx + 1);
429 	}
430 }
431 
432 /*------------------------------------------------------------------------*
433  *	usb2_set_config_index
434  *
435  * This function selects configuration by index, independent of the
436  * actual configuration number. This function should not be used by
437  * USB drivers.
438  *
439  * Returns:
440  *    0: Success
441  * Else: Failure
442  *------------------------------------------------------------------------*/
443 usb2_error_t
444 usb2_set_config_index(struct usb2_device *udev, uint8_t index)
445 {
446 	struct usb2_status ds;
447 	struct usb2_config_descriptor *cdp;
448 	uint16_t power;
449 	uint16_t max_power;
450 	uint8_t selfpowered;
451 	uint8_t do_unlock;
452 	usb2_error_t err;
453 
454 	DPRINTFN(6, "udev=%p index=%d\n", udev, index);
455 
456 	/* automatic locking */
457 	if (sx_xlocked(udev->default_sx + 1)) {
458 		do_unlock = 0;
459 	} else {
460 		do_unlock = 1;
461 		sx_xlock(udev->default_sx + 1);
462 	}
463 
464 	usb2_unconfigure(udev, USB_UNCFG_FLAG_FREE_SUBDEV);
465 
466 	if (index == USB_UNCONFIG_INDEX) {
467 		/*
468 		 * Leave unallocated when unconfiguring the
469 		 * device. "usb2_unconfigure()" will also reset
470 		 * the current config number and index.
471 		 */
472 		err = usb2_req_set_config(udev, NULL, USB_UNCONFIG_NO);
473 		if (udev->state == USB_STATE_CONFIGURED)
474 			usb2_set_device_state(udev, USB_STATE_ADDRESSED);
475 		goto done;
476 	}
477 	/* get the full config descriptor */
478 	if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
479 		/* save some memory */
480 		err = usb2_req_get_descriptor_ptr(udev, &cdp,
481 		    (UDESC_CONFIG << 8) | index);
482 	} else {
483 		/* normal request */
484 		err = usb2_req_get_config_desc_full(udev,
485 		    NULL, &cdp, M_USB, index);
486 	}
487 	if (err) {
488 		goto done;
489 	}
490 	/* set the new config descriptor */
491 
492 	udev->cdesc = cdp;
493 
494 	/* Figure out if the device is self or bus powered. */
495 	selfpowered = 0;
496 	if ((!udev->flags.uq_bus_powered) &&
497 	    (cdp->bmAttributes & UC_SELF_POWERED) &&
498 	    (udev->flags.usb2_mode == USB_MODE_HOST)) {
499 		/* May be self powered. */
500 		if (cdp->bmAttributes & UC_BUS_POWERED) {
501 			/* Must ask device. */
502 			err = usb2_req_get_device_status(udev, NULL, &ds);
503 			if (err) {
504 				DPRINTFN(0, "could not read "
505 				    "device status: %s\n",
506 				    usb2_errstr(err));
507 			} else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
508 				selfpowered = 1;
509 			}
510 			DPRINTF("status=0x%04x \n",
511 				UGETW(ds.wStatus));
512 		} else
513 			selfpowered = 1;
514 	}
515 	DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
516 	    "selfpowered=%d, power=%d\n",
517 	    udev, cdp,
518 	    udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
519 	    selfpowered, cdp->bMaxPower * 2);
520 
521 	/* Check if we have enough power. */
522 	power = cdp->bMaxPower * 2;
523 
524 	if (udev->parent_hub) {
525 		max_power = udev->parent_hub->hub->portpower;
526 	} else {
527 		max_power = USB_MAX_POWER;
528 	}
529 
530 	if (power > max_power) {
531 		DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
532 		err = USB_ERR_NO_POWER;
533 		goto done;
534 	}
535 	/* Only update "self_powered" in USB Host Mode */
536 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
537 		udev->flags.self_powered = selfpowered;
538 	}
539 	udev->power = power;
540 	udev->curr_config_no = cdp->bConfigurationValue;
541 	udev->curr_config_index = index;
542 	usb2_set_device_state(udev, USB_STATE_CONFIGURED);
543 
544 	/* Set the actual configuration value. */
545 	err = usb2_req_set_config(udev, NULL, cdp->bConfigurationValue);
546 	if (err) {
547 		goto done;
548 	}
549 
550 	err = usb2_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_ALLOC);
551 	if (err) {
552 		goto done;
553 	}
554 
555 	err = usb2_config_parse(udev, USB_IFACE_INDEX_ANY, USB_CFG_INIT);
556 	if (err) {
557 		goto done;
558 	}
559 
560 #if USB_HAVE_UGEN
561 	/* create device nodes for each endpoint */
562 	usb2_cdev_create(udev);
563 #endif
564 
565 done:
566 	DPRINTF("error=%s\n", usb2_errstr(err));
567 	if (err) {
568 		usb2_unconfigure(udev, USB_UNCFG_FLAG_FREE_SUBDEV);
569 	}
570 	if (do_unlock) {
571 		sx_unlock(udev->default_sx + 1);
572 	}
573 	return (err);
574 }
575 
576 /*------------------------------------------------------------------------*
577  *	usb2_config_parse
578  *
579  * This function will allocate and free USB interfaces and USB pipes,
580  * parse the USB configuration structure and initialise the USB pipes
581  * and interfaces. If "iface_index" is not equal to
582  * "USB_IFACE_INDEX_ANY" then the "cmd" parameter is the
583  * alternate_setting to be selected for the given interface. Else the
584  * "cmd" parameter is defined by "USB_CFG_XXX". "iface_index" can be
585  * "USB_IFACE_INDEX_ANY" or a valid USB interface index. This function
586  * is typically called when setting the configuration or when setting
587  * an alternate interface.
588  *
589  * Returns:
590  *    0: Success
591  * Else: Failure
592  *------------------------------------------------------------------------*/
593 usb2_error_t
594 usb2_config_parse(struct usb2_device *udev, uint8_t iface_index, uint8_t cmd)
595 {
596 	struct usb2_idesc_parse_state ips;
597 	struct usb2_interface_descriptor *id;
598 	struct usb2_endpoint_descriptor *ed;
599 	struct usb2_interface *iface;
600 	struct usb2_pipe *pipe;
601 	usb2_error_t err;
602 	uint8_t ep_curr;
603 	uint8_t ep_max;
604 	uint8_t temp;
605 	uint8_t do_init;
606 	uint8_t alt_index;
607 
608 	if (iface_index != USB_IFACE_INDEX_ANY) {
609 		/* parameter overload */
610 		alt_index = cmd;
611 		cmd = USB_CFG_INIT;
612 	} else {
613 		/* not used */
614 		alt_index = 0;
615 	}
616 
617 	err = 0;
618 
619 	DPRINTFN(5, "iface_index=%d cmd=%d\n",
620 	    iface_index, cmd);
621 
622 	if (cmd == USB_CFG_FREE)
623 		goto cleanup;
624 
625 	if (cmd == USB_CFG_INIT) {
626 		sx_assert(udev->default_sx + 1, SA_LOCKED);
627 
628 		/* check for in-use pipes */
629 
630 		pipe = udev->pipes;
631 		ep_max = udev->pipes_max;
632 		while (ep_max--) {
633 			/* look for matching pipes */
634 			if ((iface_index == USB_IFACE_INDEX_ANY) ||
635 			    (iface_index == pipe->iface_index)) {
636 				if (pipe->refcount != 0) {
637 					/*
638 					 * This typically indicates a
639 					 * more serious error.
640 					 */
641 					err = USB_ERR_IN_USE;
642 				} else {
643 					/* reset pipe */
644 					memset(pipe, 0, sizeof(*pipe));
645 					/* make sure we don't zero the pipe again */
646 					pipe->iface_index = USB_IFACE_INDEX_ANY;
647 				}
648 			}
649 			pipe++;
650 		}
651 
652 		if (err)
653 			return (err);
654 	}
655 
656 	memset(&ips, 0, sizeof(ips));
657 
658 	ep_curr = 0;
659 	ep_max = 0;
660 
661 	while ((id = usb2_idesc_foreach(udev->cdesc, &ips))) {
662 
663 		/* check for interface overflow */
664 		if (ips.iface_index == USB_IFACE_MAX)
665 			break;			/* crazy */
666 
667 		iface = udev->ifaces + ips.iface_index;
668 
669 		/* check for specific interface match */
670 
671 		if (cmd == USB_CFG_INIT) {
672 			if ((iface_index != USB_IFACE_INDEX_ANY) &&
673 			    (iface_index != ips.iface_index)) {
674 				/* wrong interface */
675 				do_init = 0;
676 			} else if (alt_index != ips.iface_index_alt) {
677 				/* wrong alternate setting */
678 				do_init = 0;
679 			} else {
680 				/* initialise interface */
681 				do_init = 1;
682 			}
683 		} else
684 			do_init = 0;
685 
686 		/* check for new interface */
687 		if (ips.iface_index_alt == 0) {
688 			/* update current number of endpoints */
689 			ep_curr = ep_max;
690 		}
691 		/* check for init */
692 		if (do_init) {
693 			/* setup the USB interface structure */
694 			iface->idesc = id;
695 			/* default setting */
696 			iface->parent_iface_index = USB_IFACE_INDEX_ANY;
697 			/* set alternate index */
698 			iface->alt_index = alt_index;
699 		}
700 
701 		DPRINTFN(5, "found idesc nendpt=%d\n", id->bNumEndpoints);
702 
703 		ed = (struct usb2_endpoint_descriptor *)id;
704 
705 		temp = ep_curr;
706 
707 		/* iterate all the endpoint descriptors */
708 		while ((ed = usb2_edesc_foreach(udev->cdesc, ed))) {
709 
710 			if (temp == USB_EP_MAX)
711 				break;			/* crazy */
712 
713 			pipe = udev->pipes + temp;
714 
715 			if (do_init) {
716 				usb2_init_pipe(udev,
717 				    ips.iface_index, ed, pipe);
718 			}
719 
720 			temp ++;
721 
722 			/* find maximum number of endpoints */
723 			if (ep_max < temp)
724 				ep_max = temp;
725 
726 			/* optimalisation */
727 			id = (struct usb2_interface_descriptor *)ed;
728 		}
729 	}
730 
731 	/* NOTE: It is valid to have no interfaces and no endpoints! */
732 
733 	if (cmd == USB_CFG_ALLOC) {
734 		udev->ifaces_max = ips.iface_index;
735 		udev->ifaces = NULL;
736 		if (udev->ifaces_max != 0) {
737 			udev->ifaces = malloc(sizeof(*iface) * udev->ifaces_max,
738 			        M_USB, M_WAITOK | M_ZERO);
739 			if (udev->ifaces == NULL) {
740 				err = USB_ERR_NOMEM;
741 				goto done;
742 			}
743 		}
744 		if (ep_max != 0) {
745 			udev->pipes = malloc(sizeof(*pipe) * ep_max,
746 			        M_USB, M_WAITOK | M_ZERO);
747 			if (udev->pipes == NULL) {
748 				err = USB_ERR_NOMEM;
749 				goto done;
750 			}
751 		} else {
752 			udev->pipes = NULL;
753 		}
754 		USB_BUS_LOCK(udev->bus);
755 		udev->pipes_max = ep_max;
756 		/* reset any ongoing clear-stall */
757 		udev->pipe_curr = NULL;
758 		USB_BUS_UNLOCK(udev->bus);
759 	}
760 
761 done:
762 	if (err) {
763 		if (cmd == USB_CFG_ALLOC) {
764 cleanup:
765 			USB_BUS_LOCK(udev->bus);
766 			udev->pipes_max = 0;
767 			/* reset any ongoing clear-stall */
768 			udev->pipe_curr = NULL;
769 			USB_BUS_UNLOCK(udev->bus);
770 
771 			/* cleanup */
772 			if (udev->ifaces != NULL)
773 				free(udev->ifaces, M_USB);
774 			if (udev->pipes != NULL)
775 				free(udev->pipes, M_USB);
776 
777 			udev->ifaces = NULL;
778 			udev->pipes = NULL;
779 			udev->ifaces_max = 0;
780 		}
781 	}
782 	return (err);
783 }
784 
785 /*------------------------------------------------------------------------*
786  *	usb2_set_alt_interface_index
787  *
788  * This function will select an alternate interface index for the
789  * given interface index. The interface should not be in use when this
790  * function is called. That means there should not be any open USB
791  * transfers. Else an error is returned. If the alternate setting is
792  * already set this function will simply return success. This function
793  * is called in Host mode and Device mode!
794  *
795  * Returns:
796  *    0: Success
797  * Else: Failure
798  *------------------------------------------------------------------------*/
799 usb2_error_t
800 usb2_set_alt_interface_index(struct usb2_device *udev,
801     uint8_t iface_index, uint8_t alt_index)
802 {
803 	struct usb2_interface *iface = usb2_get_iface(udev, iface_index);
804 	usb2_error_t err;
805 	uint8_t do_unlock;
806 
807 	/* automatic locking */
808 	if (sx_xlocked(udev->default_sx + 1)) {
809 		do_unlock = 0;
810 	} else {
811 		do_unlock = 1;
812 		sx_xlock(udev->default_sx + 1);
813 	}
814 	if (iface == NULL) {
815 		err = USB_ERR_INVAL;
816 		goto done;
817 	}
818 	if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
819 		usb2_detach_device(udev, iface_index,
820 		    USB_UNCFG_FLAG_FREE_SUBDEV);
821 	} else {
822 		if (iface->alt_index == alt_index) {
823 			/*
824 			 * Optimise away duplicate setting of
825 			 * alternate setting in USB Host Mode!
826 			 */
827 			err = 0;
828 			goto done;
829 		}
830 	}
831 #if USB_HAVE_UGEN
832 	/*
833 	 * Free all generic FIFOs for this interface, except control
834 	 * endpoint FIFOs:
835 	 */
836 	usb2_fifo_free_wrap(udev, iface_index, 0);
837 #endif
838 
839 	err = usb2_config_parse(udev, iface_index, alt_index);
840 	if (err) {
841 		goto done;
842 	}
843 	err = usb2_req_set_alt_interface_no(udev, NULL, iface_index,
844 	    iface->idesc->bAlternateSetting);
845 
846 done:
847 	if (do_unlock) {
848 		sx_unlock(udev->default_sx + 1);
849 	}
850 	return (err);
851 }
852 
853 /*------------------------------------------------------------------------*
854  *	usb2_set_endpoint_stall
855  *
856  * This function is used to make a BULK or INTERRUPT endpoint
857  * send STALL tokens.
858  *
859  * Returns:
860  *    0: Success
861  * Else: Failure
862  *------------------------------------------------------------------------*/
863 usb2_error_t
864 usb2_set_endpoint_stall(struct usb2_device *udev, struct usb2_pipe *pipe,
865     uint8_t do_stall)
866 {
867 	struct usb2_xfer *xfer;
868 	uint8_t et;
869 	uint8_t was_stalled;
870 
871 	if (pipe == NULL) {
872 		/* nothing to do */
873 		DPRINTF("Cannot find endpoint\n");
874 		/*
875 		 * Pretend that the clear or set stall request is
876 		 * successful else some USB host stacks can do
877 		 * strange things, especially when a control endpoint
878 		 * stalls.
879 		 */
880 		return (0);
881 	}
882 	et = (pipe->edesc->bmAttributes & UE_XFERTYPE);
883 
884 	if ((et != UE_BULK) &&
885 	    (et != UE_INTERRUPT)) {
886 		/*
887 	         * Should not stall control
888 	         * nor isochronous endpoints.
889 	         */
890 		DPRINTF("Invalid endpoint\n");
891 		return (0);
892 	}
893 	USB_BUS_LOCK(udev->bus);
894 
895 	/* store current stall state */
896 	was_stalled = pipe->is_stalled;
897 
898 	/* check for no change */
899 	if (was_stalled && do_stall) {
900 		/* if the pipe is already stalled do nothing */
901 		USB_BUS_UNLOCK(udev->bus);
902 		DPRINTF("No change\n");
903 		return (0);
904 	}
905 	/* set stalled state */
906 	pipe->is_stalled = 1;
907 
908 	if (do_stall || (!was_stalled)) {
909 		if (!was_stalled) {
910 			/* lookup the current USB transfer, if any */
911 			xfer = pipe->pipe_q.curr;
912 		} else {
913 			xfer = NULL;
914 		}
915 
916 		/*
917 		 * If "xfer" is non-NULL the "set_stall" method will
918 		 * complete the USB transfer like in case of a timeout
919 		 * setting the error code "USB_ERR_STALLED".
920 		 */
921 		(udev->bus->methods->set_stall) (udev, xfer, pipe);
922 	}
923 	if (!do_stall) {
924 		pipe->toggle_next = 0;	/* reset data toggle */
925 		pipe->is_stalled = 0;	/* clear stalled state */
926 
927 		(udev->bus->methods->clear_stall) (udev, pipe);
928 
929 		/* start up the current or next transfer, if any */
930 		usb2_command_wrapper(&pipe->pipe_q, pipe->pipe_q.curr);
931 	}
932 	USB_BUS_UNLOCK(udev->bus);
933 	return (0);
934 }
935 
936 /*------------------------------------------------------------------------*
937  *	usb2_reset_iface_endpoints - used in USB device side mode
938  *------------------------------------------------------------------------*/
939 usb2_error_t
940 usb2_reset_iface_endpoints(struct usb2_device *udev, uint8_t iface_index)
941 {
942 	struct usb2_pipe *pipe;
943 	struct usb2_pipe *pipe_end;
944 	usb2_error_t err;
945 
946 	pipe = udev->pipes;
947 	pipe_end = udev->pipes + udev->pipes_max;
948 
949 	for (; pipe != pipe_end; pipe++) {
950 
951 		if ((pipe->edesc == NULL) ||
952 		    (pipe->iface_index != iface_index)) {
953 			continue;
954 		}
955 		/* simulate a clear stall from the peer */
956 		err = usb2_set_endpoint_stall(udev, pipe, 0);
957 		if (err) {
958 			/* just ignore */
959 		}
960 	}
961 	return (0);
962 }
963 
964 /*------------------------------------------------------------------------*
965  *	usb2_detach_device_sub
966  *
967  * This function will try to detach an USB device. If it fails a panic
968  * will result.
969  *
970  * Flag values, see "USB_UNCFG_FLAG_XXX".
971  *------------------------------------------------------------------------*/
972 static void
973 usb2_detach_device_sub(struct usb2_device *udev, device_t *ppdev,
974     uint8_t flag)
975 {
976 	device_t dev;
977 	int err;
978 
979 	if (!(flag & USB_UNCFG_FLAG_FREE_SUBDEV)) {
980 
981 		*ppdev = NULL;
982 
983 	} else if (*ppdev) {
984 
985 		/*
986 		 * NOTE: It is important to clear "*ppdev" before deleting
987 		 * the child due to some device methods being called late
988 		 * during the delete process !
989 		 */
990 		dev = *ppdev;
991 		*ppdev = NULL;
992 
993 		device_printf(dev, "at %s, port %d, addr %d "
994 		    "(disconnected)\n",
995 		    device_get_nameunit(udev->parent_dev),
996 		    udev->port_no, udev->address);
997 
998 		if (device_is_attached(dev)) {
999 			if (udev->flags.peer_suspended) {
1000 				err = DEVICE_RESUME(dev);
1001 				if (err) {
1002 					device_printf(dev, "Resume failed!\n");
1003 				}
1004 			}
1005 			if (device_detach(dev)) {
1006 				goto error;
1007 			}
1008 		}
1009 		if (device_delete_child(udev->parent_dev, dev)) {
1010 			goto error;
1011 		}
1012 	}
1013 	return;
1014 
1015 error:
1016 	/* Detach is not allowed to fail in the USB world */
1017 	panic("An USB driver would not detach!\n");
1018 }
1019 
1020 /*------------------------------------------------------------------------*
1021  *	usb2_detach_device
1022  *
1023  * The following function will detach the matching interfaces.
1024  * This function is NULL safe.
1025  *
1026  * Flag values, see "USB_UNCFG_FLAG_XXX".
1027  *------------------------------------------------------------------------*/
1028 void
1029 usb2_detach_device(struct usb2_device *udev, uint8_t iface_index,
1030     uint8_t flag)
1031 {
1032 	struct usb2_interface *iface;
1033 	uint8_t i;
1034 
1035 	if (udev == NULL) {
1036 		/* nothing to do */
1037 		return;
1038 	}
1039 	DPRINTFN(4, "udev=%p\n", udev);
1040 
1041 	sx_assert(udev->default_sx + 1, SA_LOCKED);
1042 
1043 	/*
1044 	 * First detach the child to give the child's detach routine a
1045 	 * chance to detach the sub-devices in the correct order.
1046 	 * Then delete the child using "device_delete_child()" which
1047 	 * will detach all sub-devices from the bottom and upwards!
1048 	 */
1049 	if (iface_index != USB_IFACE_INDEX_ANY) {
1050 		i = iface_index;
1051 		iface_index = i + 1;
1052 	} else {
1053 		i = 0;
1054 		iface_index = USB_IFACE_MAX;
1055 	}
1056 
1057 	/* do the detach */
1058 
1059 	for (; i != iface_index; i++) {
1060 
1061 		iface = usb2_get_iface(udev, i);
1062 		if (iface == NULL) {
1063 			/* looks like the end of the USB interfaces */
1064 			break;
1065 		}
1066 		usb2_detach_device_sub(udev, &iface->subdev, flag);
1067 	}
1068 }
1069 
1070 /*------------------------------------------------------------------------*
1071  *	usb2_probe_and_attach_sub
1072  *
1073  * Returns:
1074  *    0: Success
1075  * Else: Failure
1076  *------------------------------------------------------------------------*/
1077 static uint8_t
1078 usb2_probe_and_attach_sub(struct usb2_device *udev,
1079     struct usb2_attach_arg *uaa)
1080 {
1081 	struct usb2_interface *iface;
1082 	device_t dev;
1083 	int err;
1084 
1085 	iface = uaa->iface;
1086 	if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
1087 		/* leave interface alone */
1088 		return (0);
1089 	}
1090 	dev = iface->subdev;
1091 	if (dev) {
1092 
1093 		/* clean up after module unload */
1094 
1095 		if (device_is_attached(dev)) {
1096 			/* already a device there */
1097 			return (0);
1098 		}
1099 		/* clear "iface->subdev" as early as possible */
1100 
1101 		iface->subdev = NULL;
1102 
1103 		if (device_delete_child(udev->parent_dev, dev)) {
1104 
1105 			/*
1106 			 * Panic here, else one can get a double call
1107 			 * to device_detach().  USB devices should
1108 			 * never fail on detach!
1109 			 */
1110 			panic("device_delete_child() failed!\n");
1111 		}
1112 	}
1113 	if (uaa->temp_dev == NULL) {
1114 
1115 		/* create a new child */
1116 		uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1117 		if (uaa->temp_dev == NULL) {
1118 			device_printf(udev->parent_dev,
1119 			    "Device creation failed!\n");
1120 			return (1);	/* failure */
1121 		}
1122 		device_set_ivars(uaa->temp_dev, uaa);
1123 		device_quiet(uaa->temp_dev);
1124 	}
1125 	/*
1126 	 * Set "subdev" before probe and attach so that "devd" gets
1127 	 * the information it needs.
1128 	 */
1129 	iface->subdev = uaa->temp_dev;
1130 
1131 	if (device_probe_and_attach(iface->subdev) == 0) {
1132 		/*
1133 		 * The USB attach arguments are only available during probe
1134 		 * and attach !
1135 		 */
1136 		uaa->temp_dev = NULL;
1137 		device_set_ivars(iface->subdev, NULL);
1138 
1139 		if (udev->flags.peer_suspended) {
1140 			err = DEVICE_SUSPEND(iface->subdev);
1141 			if (err)
1142 				device_printf(iface->subdev, "Suspend failed\n");
1143 		}
1144 		return (0);		/* success */
1145 	} else {
1146 		/* No USB driver found */
1147 		iface->subdev = NULL;
1148 	}
1149 	return (1);			/* failure */
1150 }
1151 
1152 /*------------------------------------------------------------------------*
1153  *	usb2_set_parent_iface
1154  *
1155  * Using this function will lock the alternate interface setting on an
1156  * interface. It is typically used for multi interface drivers. In USB
1157  * device side mode it is assumed that the alternate interfaces all
1158  * have the same endpoint descriptors. The default parent index value
1159  * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1160  * locked.
1161  *------------------------------------------------------------------------*/
1162 void
1163 usb2_set_parent_iface(struct usb2_device *udev, uint8_t iface_index,
1164     uint8_t parent_index)
1165 {
1166 	struct usb2_interface *iface;
1167 
1168 	iface = usb2_get_iface(udev, iface_index);
1169 	if (iface) {
1170 		iface->parent_iface_index = parent_index;
1171 	}
1172 }
1173 
1174 static void
1175 usb2_init_attach_arg(struct usb2_device *udev,
1176     struct usb2_attach_arg *uaa)
1177 {
1178 	bzero(uaa, sizeof(*uaa));
1179 
1180 	uaa->device = udev;
1181 	uaa->usb2_mode = udev->flags.usb2_mode;
1182 	uaa->port = udev->port_no;
1183 
1184 	uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1185 	uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1186 	uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1187 	uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1188 	uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1189 	uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1190 	uaa->info.bConfigIndex = udev->curr_config_index;
1191 	uaa->info.bConfigNum = udev->curr_config_no;
1192 }
1193 
1194 /*------------------------------------------------------------------------*
1195  *	usb2_probe_and_attach
1196  *
1197  * This function is called from "uhub_explore_sub()",
1198  * "usb2_handle_set_config()" and "usb2_handle_request()".
1199  *
1200  * Returns:
1201  *    0: Success
1202  * Else: A control transfer failed
1203  *------------------------------------------------------------------------*/
1204 usb2_error_t
1205 usb2_probe_and_attach(struct usb2_device *udev, uint8_t iface_index)
1206 {
1207 	struct usb2_attach_arg uaa;
1208 	struct usb2_interface *iface;
1209 	uint8_t i;
1210 	uint8_t j;
1211 	uint8_t do_unlock;
1212 
1213 	if (udev == NULL) {
1214 		DPRINTF("udev == NULL\n");
1215 		return (USB_ERR_INVAL);
1216 	}
1217 	/* automatic locking */
1218 	if (sx_xlocked(udev->default_sx + 1)) {
1219 		do_unlock = 0;
1220 	} else {
1221 		do_unlock = 1;
1222 		sx_xlock(udev->default_sx + 1);
1223 	}
1224 
1225 	if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1226 		/* do nothing - no configuration has been set */
1227 		goto done;
1228 	}
1229 	/* setup USB attach arguments */
1230 
1231 	usb2_init_attach_arg(udev, &uaa);
1232 
1233 	/* Check if only one interface should be probed: */
1234 	if (iface_index != USB_IFACE_INDEX_ANY) {
1235 		i = iface_index;
1236 		j = i + 1;
1237 	} else {
1238 		i = 0;
1239 		j = USB_IFACE_MAX;
1240 	}
1241 
1242 	/* Do the probe and attach */
1243 	for (; i != j; i++) {
1244 
1245 		iface = usb2_get_iface(udev, i);
1246 		if (iface == NULL) {
1247 			/*
1248 			 * Looks like the end of the USB
1249 			 * interfaces !
1250 			 */
1251 			DPRINTFN(2, "end of interfaces "
1252 			    "at %u\n", i);
1253 			break;
1254 		}
1255 		if (iface->idesc == NULL) {
1256 			/* no interface descriptor */
1257 			continue;
1258 		}
1259 		uaa.iface = iface;
1260 
1261 		uaa.info.bInterfaceClass =
1262 		    iface->idesc->bInterfaceClass;
1263 		uaa.info.bInterfaceSubClass =
1264 		    iface->idesc->bInterfaceSubClass;
1265 		uaa.info.bInterfaceProtocol =
1266 		    iface->idesc->bInterfaceProtocol;
1267 		uaa.info.bIfaceIndex = i;
1268 		uaa.info.bIfaceNum =
1269 		    iface->idesc->bInterfaceNumber;
1270 		uaa.use_generic = 0;
1271 
1272 		DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1273 		    uaa.info.bInterfaceClass,
1274 		    uaa.info.bInterfaceSubClass,
1275 		    uaa.info.bInterfaceProtocol,
1276 		    uaa.info.bIfaceIndex,
1277 		    uaa.info.bIfaceNum);
1278 
1279 		/* try specific interface drivers first */
1280 
1281 		if (usb2_probe_and_attach_sub(udev, &uaa)) {
1282 			/* ignore */
1283 		}
1284 		/* try generic interface drivers last */
1285 
1286 		uaa.use_generic = 1;
1287 
1288 		if (usb2_probe_and_attach_sub(udev, &uaa)) {
1289 			/* ignore */
1290 		}
1291 	}
1292 
1293 	if (uaa.temp_dev) {
1294 		/* remove the last created child; it is unused */
1295 
1296 		if (device_delete_child(udev->parent_dev, uaa.temp_dev)) {
1297 			DPRINTFN(0, "device delete child failed!\n");
1298 		}
1299 	}
1300 done:
1301 	if (do_unlock) {
1302 		sx_unlock(udev->default_sx + 1);
1303 	}
1304 	return (0);
1305 }
1306 
1307 /*------------------------------------------------------------------------*
1308  *	usb2_suspend_resume_sub
1309  *
1310  * This function is called when the suspend or resume methods should
1311  * be executed on an USB device.
1312  *------------------------------------------------------------------------*/
1313 static void
1314 usb2_suspend_resume_sub(struct usb2_device *udev, device_t dev, uint8_t do_suspend)
1315 {
1316 	int err;
1317 
1318 	if (dev == NULL) {
1319 		return;
1320 	}
1321 	if (!device_is_attached(dev)) {
1322 		return;
1323 	}
1324 	if (do_suspend) {
1325 		err = DEVICE_SUSPEND(dev);
1326 	} else {
1327 		err = DEVICE_RESUME(dev);
1328 	}
1329 	if (err) {
1330 		device_printf(dev, "%s failed!\n",
1331 		    do_suspend ? "Suspend" : "Resume");
1332 	}
1333 }
1334 
1335 /*------------------------------------------------------------------------*
1336  *	usb2_suspend_resume
1337  *
1338  * The following function will suspend or resume the USB device.
1339  *
1340  * Returns:
1341  *    0: Success
1342  * Else: Failure
1343  *------------------------------------------------------------------------*/
1344 usb2_error_t
1345 usb2_suspend_resume(struct usb2_device *udev, uint8_t do_suspend)
1346 {
1347 	struct usb2_interface *iface;
1348 	uint8_t i;
1349 
1350 	if (udev == NULL) {
1351 		/* nothing to do */
1352 		return (0);
1353 	}
1354 	DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1355 
1356 	sx_assert(udev->default_sx + 1, SA_LOCKED);
1357 
1358 	USB_BUS_LOCK(udev->bus);
1359 	/* filter the suspend events */
1360 	if (udev->flags.peer_suspended == do_suspend) {
1361 		USB_BUS_UNLOCK(udev->bus);
1362 		/* nothing to do */
1363 		return (0);
1364 	}
1365 	udev->flags.peer_suspended = do_suspend;
1366 	USB_BUS_UNLOCK(udev->bus);
1367 
1368 	/* do the suspend or resume */
1369 
1370 	for (i = 0; i != USB_IFACE_MAX; i++) {
1371 
1372 		iface = usb2_get_iface(udev, i);
1373 		if (iface == NULL) {
1374 			/* looks like the end of the USB interfaces */
1375 			break;
1376 		}
1377 		usb2_suspend_resume_sub(udev, iface->subdev, do_suspend);
1378 	}
1379 	return (0);
1380 }
1381 
1382 /*------------------------------------------------------------------------*
1383  *      usb2_clear_stall_proc
1384  *
1385  * This function performs generic USB clear stall operations.
1386  *------------------------------------------------------------------------*/
1387 static void
1388 usb2_clear_stall_proc(struct usb2_proc_msg *_pm)
1389 {
1390 	struct usb2_clear_stall_msg *pm = (void *)_pm;
1391 	struct usb2_device *udev = pm->udev;
1392 
1393 	/* Change lock */
1394 	USB_BUS_UNLOCK(udev->bus);
1395 	mtx_lock(udev->default_mtx);
1396 
1397 	/* Start clear stall callback */
1398 	usb2_transfer_start(udev->default_xfer[1]);
1399 
1400 	/* Change lock */
1401 	mtx_unlock(udev->default_mtx);
1402 	USB_BUS_LOCK(udev->bus);
1403 }
1404 
1405 /*------------------------------------------------------------------------*
1406  *	usb2_alloc_device
1407  *
1408  * This function allocates a new USB device. This function is called
1409  * when a new device has been put in the powered state, but not yet in
1410  * the addressed state. Get initial descriptor, set the address, get
1411  * full descriptor and get strings.
1412  *
1413  * Return values:
1414  *    0: Failure
1415  * Else: Success
1416  *------------------------------------------------------------------------*/
1417 struct usb2_device *
1418 usb2_alloc_device(device_t parent_dev, struct usb2_bus *bus,
1419     struct usb2_device *parent_hub, uint8_t depth,
1420     uint8_t port_index, uint8_t port_no, uint8_t speed, uint8_t usb2_mode)
1421 {
1422 	struct usb2_attach_arg uaa;
1423 	struct usb2_device *udev;
1424 	struct usb2_device *adev;
1425 	struct usb2_device *hub;
1426 	uint8_t *scratch_ptr;
1427 	uint32_t scratch_size;
1428 	usb2_error_t err;
1429 	uint8_t device_index;
1430 
1431 	DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1432 	    "port_index=%u, port_no=%u, speed=%u, usb2_mode=%u\n",
1433 	    parent_dev, bus, parent_hub, depth, port_index, port_no,
1434 	    speed, usb2_mode);
1435 
1436 	/*
1437 	 * Find an unused device index. In USB Host mode this is the
1438 	 * same as the device address.
1439 	 *
1440 	 * Device index zero is not used and device index 1 should
1441 	 * always be the root hub.
1442 	 */
1443 	for (device_index = USB_ROOT_HUB_ADDR;
1444 	    (device_index != bus->devices_max) &&
1445 	    (bus->devices[device_index] != NULL);
1446 	    device_index++) /* nop */;
1447 
1448 	if (device_index == bus->devices_max) {
1449 		device_printf(bus->bdev,
1450 		    "No free USB device index for new device!\n");
1451 		return (NULL);
1452 	}
1453 
1454 	if (depth > 0x10) {
1455 		device_printf(bus->bdev,
1456 		    "Invalid device depth!\n");
1457 		return (NULL);
1458 	}
1459 	udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1460 	if (udev == NULL) {
1461 		return (NULL);
1462 	}
1463 	/* initialise our SX-lock */
1464 	sx_init(udev->default_sx, "0123456789ABCDEF - USB device SX lock" + depth);
1465 
1466 	/* initialise our SX-lock */
1467 	sx_init(udev->default_sx + 1, "0123456789ABCDEF - USB config SX lock" + depth);
1468 
1469 	usb2_cv_init(udev->default_cv, "WCTRL");
1470 	usb2_cv_init(udev->default_cv + 1, "UGONE");
1471 
1472 	/* initialise our mutex */
1473 	mtx_init(udev->default_mtx, "USB device mutex", NULL, MTX_DEF);
1474 
1475 	/* initialise generic clear stall */
1476 	udev->cs_msg[0].hdr.pm_callback = &usb2_clear_stall_proc;
1477 	udev->cs_msg[0].udev = udev;
1478 	udev->cs_msg[1].hdr.pm_callback = &usb2_clear_stall_proc;
1479 	udev->cs_msg[1].udev = udev;
1480 
1481 	/* initialise some USB device fields */
1482 	udev->parent_hub = parent_hub;
1483 	udev->parent_dev = parent_dev;
1484 	udev->port_index = port_index;
1485 	udev->port_no = port_no;
1486 	udev->depth = depth;
1487 	udev->bus = bus;
1488 	udev->address = USB_START_ADDR;	/* default value */
1489 	udev->plugtime = (usb2_ticks_t)ticks;
1490 	usb2_set_device_state(udev, USB_STATE_POWERED);
1491 	/*
1492 	 * We need to force the power mode to "on" because there are plenty
1493 	 * of USB devices out there that do not work very well with
1494 	 * automatic suspend and resume!
1495 	 */
1496 	udev->power_mode = USB_POWER_MODE_ON;
1497 	udev->pwr_save.last_xfer_time = ticks;
1498 	/* we are not ready yet */
1499 	udev->refcount = 1;
1500 
1501 	/* set up default endpoint descriptor */
1502 	udev->default_ep_desc.bLength = sizeof(udev->default_ep_desc);
1503 	udev->default_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1504 	udev->default_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1505 	udev->default_ep_desc.bmAttributes = UE_CONTROL;
1506 	udev->default_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1507 	udev->default_ep_desc.wMaxPacketSize[1] = 0;
1508 	udev->default_ep_desc.bInterval = 0;
1509 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1510 
1511 	udev->speed = speed;
1512 	udev->flags.usb2_mode = usb2_mode;
1513 
1514 	/* search for our High Speed USB HUB, if any */
1515 
1516 	adev = udev;
1517 	hub = udev->parent_hub;
1518 
1519 	while (hub) {
1520 		if (hub->speed == USB_SPEED_HIGH) {
1521 			udev->hs_hub_addr = hub->address;
1522 			udev->parent_hs_hub = hub;
1523 			udev->hs_port_no = adev->port_no;
1524 			break;
1525 		}
1526 		adev = hub;
1527 		hub = hub->parent_hub;
1528 	}
1529 
1530 	/* init the default pipe */
1531 	usb2_init_pipe(udev, 0,
1532 	    &udev->default_ep_desc,
1533 	    &udev->default_pipe);
1534 
1535 	/* set device index */
1536 	udev->device_index = device_index;
1537 
1538 #if USB_HAVE_UGEN
1539 	/* Create ugen name */
1540 	snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1541 	    USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1542 	    device_index);
1543 	LIST_INIT(&udev->pd_list);
1544 
1545 	/* Create the control endpoint device */
1546 	udev->default_dev = usb2_make_dev(udev, 0, FREAD|FWRITE);
1547 
1548 	/* Create a link from /dev/ugenX.X to the default endpoint */
1549 	make_dev_alias(udev->default_dev, udev->ugen_name);
1550 #endif
1551 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
1552 
1553 		err = usb2_req_set_address(udev, NULL, device_index);
1554 
1555 		/* This is the new USB device address from now on */
1556 
1557 		udev->address = device_index;
1558 
1559 		/*
1560 		 * We ignore any set-address errors, hence there are
1561 		 * buggy USB devices out there that actually receive
1562 		 * the SETUP PID, but manage to set the address before
1563 		 * the STATUS stage is ACK'ed. If the device responds
1564 		 * to the subsequent get-descriptor at the new
1565 		 * address, then we know that the set-address command
1566 		 * was successful.
1567 		 */
1568 		if (err) {
1569 			DPRINTFN(0, "set address %d failed "
1570 			    "(%s, ignored)\n", udev->address,
1571 			    usb2_errstr(err));
1572 		}
1573 		/* allow device time to set new address */
1574 		usb2_pause_mtx(NULL,
1575 		    USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1576 	} else {
1577 		/* We are not self powered */
1578 		udev->flags.self_powered = 0;
1579 
1580 		/* Set unconfigured state */
1581 		udev->curr_config_no = USB_UNCONFIG_NO;
1582 		udev->curr_config_index = USB_UNCONFIG_INDEX;
1583 
1584 		/* Setup USB descriptors */
1585 		err = (usb2_temp_setup_by_index_p) (udev, usb2_template);
1586 		if (err) {
1587 			DPRINTFN(0, "setting up USB template failed maybe the USB "
1588 			    "template module has not been loaded\n");
1589 			goto done;
1590 		}
1591 	}
1592 	usb2_set_device_state(udev, USB_STATE_ADDRESSED);
1593 
1594 	/*
1595 	 * Get the first 8 bytes of the device descriptor !
1596 	 *
1597 	 * NOTE: "usb2_do_request" will check the device descriptor
1598 	 * next time we do a request to see if the maximum packet size
1599 	 * changed! The 8 first bytes of the device descriptor
1600 	 * contains the maximum packet size to use on control endpoint
1601 	 * 0. If this value is different from "USB_MAX_IPACKET" a new
1602 	 * USB control request will be setup!
1603 	 */
1604 	err = usb2_req_get_desc(udev, NULL, NULL, &udev->ddesc,
1605 	    USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1606 	if (err) {
1607 		DPRINTFN(0, "getting device descriptor "
1608 		    "at addr %d failed, %s!\n", udev->address,
1609 		    usb2_errstr(err));
1610 		/* XXX try to re-enumerate the device */
1611 		err = usb2_req_re_enumerate(udev, NULL);
1612 		if (err) {
1613 			goto done;
1614 		}
1615 	}
1616 	DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
1617 	    "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1618 	    udev->address, UGETW(udev->ddesc.bcdUSB),
1619 	    udev->ddesc.bDeviceClass,
1620 	    udev->ddesc.bDeviceSubClass,
1621 	    udev->ddesc.bDeviceProtocol,
1622 	    udev->ddesc.bMaxPacketSize,
1623 	    udev->ddesc.bLength,
1624 	    udev->speed);
1625 
1626 	/* get the full device descriptor */
1627 	err = usb2_req_get_device_desc(udev, NULL, &udev->ddesc);
1628 	if (err) {
1629 		DPRINTF("addr=%d, getting full desc failed\n",
1630 		    udev->address);
1631 		goto done;
1632 	}
1633 	/*
1634 	 * Setup temporary USB attach args so that we can figure out some
1635 	 * basic quirks for this device.
1636 	 */
1637 	usb2_init_attach_arg(udev, &uaa);
1638 
1639 	if (usb2_test_quirk(&uaa, UQ_BUS_POWERED)) {
1640 		udev->flags.uq_bus_powered = 1;
1641 	}
1642 	if (usb2_test_quirk(&uaa, UQ_NO_STRINGS)) {
1643 		udev->flags.no_strings = 1;
1644 	}
1645 	/*
1646 	 * Workaround for buggy USB devices.
1647 	 *
1648 	 * It appears that some string-less USB chips will crash and
1649 	 * disappear if any attempts are made to read any string
1650 	 * descriptors.
1651 	 *
1652 	 * Try to detect such chips by checking the strings in the USB
1653 	 * device descriptor. If no strings are present there we
1654 	 * simply disable all USB strings.
1655 	 */
1656 	scratch_ptr = udev->bus->scratch[0].data;
1657 	scratch_size = sizeof(udev->bus->scratch[0].data);
1658 
1659 	if (udev->ddesc.iManufacturer ||
1660 	    udev->ddesc.iProduct ||
1661 	    udev->ddesc.iSerialNumber) {
1662 		/* read out the language ID string */
1663 		err = usb2_req_get_string_desc(udev, NULL,
1664 		    (char *)scratch_ptr, 4, scratch_size,
1665 		    USB_LANGUAGE_TABLE);
1666 	} else {
1667 		err = USB_ERR_INVAL;
1668 	}
1669 
1670 	if (err || (scratch_ptr[0] < 4)) {
1671 		udev->flags.no_strings = 1;
1672 	} else {
1673 		/* pick the first language as the default */
1674 		udev->langid = UGETW(scratch_ptr + 2);
1675 	}
1676 
1677 	/* assume 100mA bus powered for now. Changed when configured. */
1678 	udev->power = USB_MIN_POWER;
1679 
1680 #if USB_HAVE_STRINGS
1681 	/* get serial number string */
1682 	err = usb2_req_get_string_any
1683 	    (udev, NULL, (char *)scratch_ptr,
1684 	    scratch_size, udev->ddesc.iSerialNumber);
1685 
1686 	strlcpy(udev->serial, (char *)scratch_ptr, sizeof(udev->serial));
1687 
1688 	/* get manufacturer string */
1689 	err = usb2_req_get_string_any
1690 	    (udev, NULL, (char *)scratch_ptr,
1691 	    scratch_size, udev->ddesc.iManufacturer);
1692 
1693 	strlcpy(udev->manufacturer, (char *)scratch_ptr, sizeof(udev->manufacturer));
1694 
1695 	/* get product string */
1696 	err = usb2_req_get_string_any
1697 	    (udev, NULL, (char *)scratch_ptr,
1698 	    scratch_size, udev->ddesc.iProduct);
1699 
1700 	strlcpy(udev->product, (char *)scratch_ptr, sizeof(udev->product));
1701 
1702 	/* finish up all the strings */
1703 	usb2_check_strings(udev);
1704 #endif
1705 
1706 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
1707 		uint8_t config_index;
1708 		uint8_t config_quirk;
1709 		uint8_t set_config_failed = 0;
1710 
1711 		/*
1712 		 * Most USB devices should attach to config index 0 by
1713 		 * default
1714 		 */
1715 		if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1716 			config_index = 0;
1717 			config_quirk = 1;
1718 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1719 			config_index = 1;
1720 			config_quirk = 1;
1721 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1722 			config_index = 2;
1723 			config_quirk = 1;
1724 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1725 			config_index = 3;
1726 			config_quirk = 1;
1727 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1728 			config_index = 4;
1729 			config_quirk = 1;
1730 		} else {
1731 			config_index = 0;
1732 			config_quirk = 0;
1733 		}
1734 
1735 repeat_set_config:
1736 
1737 		DPRINTF("setting config %u\n", config_index);
1738 
1739 		/* get the USB device configured */
1740 		err = usb2_set_config_index(udev, config_index);
1741 		if (err) {
1742 			if (udev->ddesc.bNumConfigurations != 0) {
1743 				if (!set_config_failed) {
1744 					set_config_failed = 1;
1745 					/* XXX try to re-enumerate the device */
1746 					err = usb2_req_re_enumerate(
1747 					    udev, NULL);
1748 					if (err == 0)
1749 					    goto repeat_set_config;
1750 				}
1751 				DPRINTFN(0, "Failure selecting "
1752 				    "configuration index %u: %s, port %u, "
1753 				    "addr %u (ignored)\n",
1754 				    config_index, usb2_errstr(err), udev->port_no,
1755 				    udev->address);
1756 			}
1757 			/*
1758 			 * Some USB devices do not have any
1759 			 * configurations. Ignore any set config
1760 			 * failures!
1761 			 */
1762 			err = 0;
1763 		} else if (config_quirk) {
1764 			/* user quirk selects configuration index */
1765 		} else if ((config_index + 1) < udev->ddesc.bNumConfigurations) {
1766 
1767 			if ((udev->cdesc->bNumInterface < 2) &&
1768 			    (usb2_get_no_descriptors(udev->cdesc,
1769 			    UDESC_ENDPOINT) == 0)) {
1770 				DPRINTFN(0, "Found no endpoints "
1771 				    "(trying next config)!\n");
1772 				config_index++;
1773 				goto repeat_set_config;
1774 			}
1775 			if (config_index == 0) {
1776 				/*
1777 				 * Try to figure out if we have an
1778 				 * auto-install disk there:
1779 				 */
1780 				if (usb2_test_autoinstall(udev, 0, 0) == 0) {
1781 					DPRINTFN(0, "Found possible auto-install "
1782 					    "disk (trying next config)\n");
1783 					config_index++;
1784 					goto repeat_set_config;
1785 				}
1786 			}
1787 		} else if (usb2_test_huawei_autoinst_p(udev, &uaa) == 0) {
1788 			DPRINTFN(0, "Found Huawei auto-install disk!\n");
1789 			err = USB_ERR_STALLED;	/* fake an error */
1790 		}
1791 	} else {
1792 		err = 0;		/* set success */
1793 	}
1794 
1795 	DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1796 	    udev->address, udev, udev->parent_hub);
1797 
1798 	/* register our device - we are ready */
1799 	usb2_bus_port_set_device(bus, parent_hub ?
1800 	    parent_hub->hub->ports + port_index : NULL, udev, device_index);
1801 
1802 #if USB_HAVE_UGEN
1803 	/* Symlink the ugen device name */
1804 	udev->ugen_symlink = usb2_alloc_symlink(udev->ugen_name);
1805 
1806 	/* Announce device */
1807 	printf("%s: <%s> at %s\n", udev->ugen_name, udev->manufacturer,
1808 	    device_get_nameunit(udev->bus->bdev));
1809 
1810 	usb2_notify_addq("+", udev);
1811 #endif
1812 done:
1813 	if (err) {
1814 		/* free device  */
1815 		usb2_free_device(udev,
1816 		    USB_UNCFG_FLAG_FREE_SUBDEV |
1817 		    USB_UNCFG_FLAG_FREE_EP0);
1818 		udev = NULL;
1819 	}
1820 	return (udev);
1821 }
1822 
1823 #if USB_HAVE_UGEN
1824 static struct cdev *
1825 usb2_make_dev(struct usb2_device *udev, int ep, int mode)
1826 {
1827 	struct usb2_fs_privdata* pd;
1828 	char devname[20];
1829 
1830 	/* Store information to locate ourselves again later */
1831 	pd = malloc(sizeof(struct usb2_fs_privdata), M_USBDEV,
1832 	    M_WAITOK | M_ZERO);
1833 	pd->bus_index = device_get_unit(udev->bus->bdev);
1834 	pd->dev_index = udev->device_index;
1835 	pd->ep_addr = ep;
1836 	pd->mode = mode;
1837 
1838 	/* Now, create the device itself */
1839 	snprintf(devname, sizeof(devname), "%u.%u.%u",
1840 	    pd->bus_index, pd->dev_index, pd->ep_addr);
1841 	pd->cdev = make_dev(&usb2_devsw, 0, UID_ROOT,
1842 	    GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1843 	pd->cdev->si_drv1 = pd;
1844 
1845 	return (pd->cdev);
1846 }
1847 
1848 static void
1849 usb2_cdev_create(struct usb2_device *udev)
1850 {
1851 	struct usb2_config_descriptor *cd;
1852 	struct usb2_endpoint_descriptor *ed;
1853 	struct usb2_descriptor *desc;
1854 	struct usb2_fs_privdata* pd;
1855 	struct cdev *dev;
1856 	int inmode, outmode, inmask, outmask, mode;
1857 	uint8_t ep;
1858 
1859 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1860 
1861 	DPRINTFN(2, "Creating device nodes\n");
1862 
1863 	if (usb2_get_mode(udev) == USB_MODE_DEVICE) {
1864 		inmode = FWRITE;
1865 		outmode = FREAD;
1866 	} else {		 /* USB_MODE_HOST */
1867 		inmode = FREAD;
1868 		outmode = FWRITE;
1869 	}
1870 
1871 	inmask = 0;
1872 	outmask = 0;
1873 	desc = NULL;
1874 
1875 	/*
1876 	 * Collect all used endpoint numbers instead of just
1877 	 * generating 16 static endpoints.
1878 	 */
1879 	cd = usb2_get_config_descriptor(udev);
1880 	while ((desc = usb2_desc_foreach(cd, desc))) {
1881 		/* filter out all endpoint descriptors */
1882 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1883 		    (desc->bLength >= sizeof(*ed))) {
1884 			ed = (struct usb2_endpoint_descriptor *)desc;
1885 
1886 			/* update masks */
1887 			ep = ed->bEndpointAddress;
1888 			if (UE_GET_DIR(ep)  == UE_DIR_OUT)
1889 				outmask |= 1 << UE_GET_ADDR(ep);
1890 			else
1891 				inmask |= 1 << UE_GET_ADDR(ep);
1892 		}
1893 	}
1894 
1895 	/* Create all available endpoints except EP0 */
1896 	for (ep = 1; ep < 16; ep++) {
1897 		mode = inmask & (1 << ep) ? inmode : 0;
1898 		mode |= outmask & (1 << ep) ? outmode : 0;
1899 		if (mode == 0)
1900 			continue;	/* no IN or OUT endpoint */
1901 
1902 		dev = usb2_make_dev(udev, ep, mode);
1903 		pd = dev->si_drv1;
1904 		LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1905 	}
1906 }
1907 
1908 static void
1909 usb2_cdev_free(struct usb2_device *udev)
1910 {
1911 	struct usb2_fs_privdata* pd;
1912 
1913 	DPRINTFN(2, "Freeing device nodes\n");
1914 
1915 	while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1916 		KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1917 
1918 		destroy_dev_sched_cb(pd->cdev, usb2_cdev_cleanup, pd);
1919 		pd->cdev = NULL;
1920 		LIST_REMOVE(pd, pd_next);
1921 	}
1922 }
1923 
1924 static void
1925 usb2_cdev_cleanup(void* arg)
1926 {
1927 	free(arg, M_USBDEV);
1928 }
1929 #endif
1930 
1931 /*------------------------------------------------------------------------*
1932  *	usb2_free_device
1933  *
1934  * This function is NULL safe and will free an USB device.
1935  *
1936  * Flag values, see "USB_UNCFG_FLAG_XXX".
1937  *------------------------------------------------------------------------*/
1938 void
1939 usb2_free_device(struct usb2_device *udev, uint8_t flag)
1940 {
1941 	struct usb2_bus *bus;
1942 
1943 	if (udev == NULL)
1944 		return;		/* already freed */
1945 
1946 	DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
1947 
1948 	bus = udev->bus;
1949 	usb2_set_device_state(udev, USB_STATE_DETACHED);
1950 
1951 #if USB_HAVE_UGEN
1952 	usb2_notify_addq("-", udev);
1953 
1954 	printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
1955 	    udev->manufacturer, device_get_nameunit(bus->bdev));
1956 
1957 	/* Destroy UGEN symlink, if any */
1958 	if (udev->ugen_symlink) {
1959 		usb2_free_symlink(udev->ugen_symlink);
1960 		udev->ugen_symlink = NULL;
1961 	}
1962 #endif
1963 	/*
1964 	 * Unregister our device first which will prevent any further
1965 	 * references:
1966 	 */
1967 	usb2_bus_port_set_device(bus, udev->parent_hub ?
1968 	    udev->parent_hub->hub->ports + udev->port_index : NULL,
1969 	    NULL, USB_ROOT_HUB_ADDR);
1970 
1971 #if USB_HAVE_UGEN
1972 	/* wait for all pending references to go away: */
1973 	mtx_lock(&usb2_ref_lock);
1974 	udev->refcount--;
1975 	while (udev->refcount != 0) {
1976 		usb2_cv_wait(udev->default_cv + 1, &usb2_ref_lock);
1977 	}
1978 	mtx_unlock(&usb2_ref_lock);
1979 
1980 	destroy_dev_sched_cb(udev->default_dev, usb2_cdev_cleanup,
1981 	    udev->default_dev->si_drv1);
1982 #endif
1983 
1984 	if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
1985 		/* stop receiving any control transfers (Device Side Mode) */
1986 		usb2_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1987 	}
1988 
1989 	/* the following will get the device unconfigured in software */
1990 	usb2_unconfigure(udev, flag);
1991 
1992 	/* unsetup any leftover default USB transfers */
1993 	usb2_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1994 
1995 	/* template unsetup, if any */
1996 	(usb2_temp_unsetup_p) (udev);
1997 
1998 	/*
1999 	 * Make sure that our clear-stall messages are not queued
2000 	 * anywhere:
2001 	 */
2002 	USB_BUS_LOCK(udev->bus);
2003 	usb2_proc_mwait(&udev->bus->non_giant_callback_proc,
2004 	    &udev->cs_msg[0], &udev->cs_msg[1]);
2005 	USB_BUS_UNLOCK(udev->bus);
2006 
2007 	sx_destroy(udev->default_sx);
2008 	sx_destroy(udev->default_sx + 1);
2009 
2010 	usb2_cv_destroy(udev->default_cv);
2011 	usb2_cv_destroy(udev->default_cv + 1);
2012 
2013 	mtx_destroy(udev->default_mtx);
2014 #if USB_HAVE_UGEN
2015 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2016 #endif
2017 
2018 	/* free device */
2019 	free(udev, M_USB);
2020 }
2021 
2022 /*------------------------------------------------------------------------*
2023  *	usb2_get_iface
2024  *
2025  * This function is the safe way to get the USB interface structure
2026  * pointer by interface index.
2027  *
2028  * Return values:
2029  *   NULL: Interface not present.
2030  *   Else: Pointer to USB interface structure.
2031  *------------------------------------------------------------------------*/
2032 struct usb2_interface *
2033 usb2_get_iface(struct usb2_device *udev, uint8_t iface_index)
2034 {
2035 	struct usb2_interface *iface = udev->ifaces + iface_index;
2036 
2037 	if (iface_index >= udev->ifaces_max)
2038 		return (NULL);
2039 	return (iface);
2040 }
2041 
2042 /*------------------------------------------------------------------------*
2043  *	usb2_find_descriptor
2044  *
2045  * This function will lookup the first descriptor that matches the
2046  * criteria given by the arguments "type" and "subtype". Descriptors
2047  * will only be searched within the interface having the index
2048  * "iface_index".  If the "id" argument points to an USB descriptor,
2049  * it will be skipped before the search is started. This allows
2050  * searching for multiple descriptors using the same criteria. Else
2051  * the search is started after the interface descriptor.
2052  *
2053  * Return values:
2054  *   NULL: End of descriptors
2055  *   Else: A descriptor matching the criteria
2056  *------------------------------------------------------------------------*/
2057 void   *
2058 usb2_find_descriptor(struct usb2_device *udev, void *id, uint8_t iface_index,
2059     uint8_t type, uint8_t type_mask,
2060     uint8_t subtype, uint8_t subtype_mask)
2061 {
2062 	struct usb2_descriptor *desc;
2063 	struct usb2_config_descriptor *cd;
2064 	struct usb2_interface *iface;
2065 
2066 	cd = usb2_get_config_descriptor(udev);
2067 	if (cd == NULL) {
2068 		return (NULL);
2069 	}
2070 	if (id == NULL) {
2071 		iface = usb2_get_iface(udev, iface_index);
2072 		if (iface == NULL) {
2073 			return (NULL);
2074 		}
2075 		id = usb2_get_interface_descriptor(iface);
2076 		if (id == NULL) {
2077 			return (NULL);
2078 		}
2079 	}
2080 	desc = (void *)id;
2081 
2082 	while ((desc = usb2_desc_foreach(cd, desc))) {
2083 
2084 		if (desc->bDescriptorType == UDESC_INTERFACE) {
2085 			break;
2086 		}
2087 		if (((desc->bDescriptorType & type_mask) == type) &&
2088 		    ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2089 			return (desc);
2090 		}
2091 	}
2092 	return (NULL);
2093 }
2094 
2095 /*------------------------------------------------------------------------*
2096  *	usb2_devinfo
2097  *
2098  * This function will dump information from the device descriptor
2099  * belonging to the USB device pointed to by "udev", to the string
2100  * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2101  * including the terminating zero.
2102  *------------------------------------------------------------------------*/
2103 void
2104 usb2_devinfo(struct usb2_device *udev, char *dst_ptr, uint16_t dst_len)
2105 {
2106 	struct usb2_device_descriptor *udd = &udev->ddesc;
2107 	uint16_t bcdDevice;
2108 	uint16_t bcdUSB;
2109 
2110 	bcdUSB = UGETW(udd->bcdUSB);
2111 	bcdDevice = UGETW(udd->bcdDevice);
2112 
2113 	if (udd->bDeviceClass != 0xFF) {
2114 		snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2115 		    "%x.%02x, addr %d",
2116 #if USB_HAVE_STRINGS
2117 		    udev->manufacturer, udev->product,
2118 #else
2119 		    "-", "-",
2120 #endif
2121 		    udd->bDeviceClass, udd->bDeviceSubClass,
2122 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2123 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2124 		    udev->address);
2125 	} else {
2126 		snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2127 		    "%x.%02x, addr %d",
2128 #if USB_HAVE_STRINGS
2129 		    udev->manufacturer, udev->product,
2130 #else
2131 		    "-", "-",
2132 #endif
2133 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2134 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2135 		    udev->address);
2136 	}
2137 }
2138 
2139 #if USB_HAVE_STRINGS
2140 #if USB_VERBOSE
2141 /*
2142  * Descriptions of of known vendors and devices ("products").
2143  */
2144 struct usb_knowndev {
2145 	uint16_t vendor;
2146 	uint16_t product;
2147 	uint32_t flags;
2148 	const char *vendorname;
2149 	const char *productname;
2150 };
2151 
2152 #define	USB_KNOWNDEV_NOPROD	0x01	/* match on vendor only */
2153 
2154 #include "usbdevs.h"
2155 #include "usbdevs_data.h"
2156 #endif					/* USB_VERBOSE */
2157 
2158 /*------------------------------------------------------------------------*
2159  *	usb2_check_strings
2160  *
2161  * This function checks the manufacturer and product strings and will
2162  * fill in defaults for missing strings.
2163  *------------------------------------------------------------------------*/
2164 static void
2165 usb2_check_strings(struct usb2_device *udev)
2166 {
2167 	struct usb2_device_descriptor *udd = &udev->ddesc;
2168 	const char *vendor;
2169 	const char *product;
2170 
2171 #if USB_VERBOSE
2172 	const struct usb_knowndev *kdp;
2173 
2174 #endif
2175 	uint16_t vendor_id;
2176 	uint16_t product_id;
2177 
2178 	usb2_trim_spaces(udev->manufacturer);
2179 	usb2_trim_spaces(udev->product);
2180 
2181 	if (udev->manufacturer[0]) {
2182 		vendor = udev->manufacturer;
2183 	} else {
2184 		vendor = NULL;
2185 	}
2186 
2187 	if (udev->product[0]) {
2188 		product = udev->product;
2189 	} else {
2190 		product = NULL;
2191 	}
2192 
2193 	vendor_id = UGETW(udd->idVendor);
2194 	product_id = UGETW(udd->idProduct);
2195 
2196 #if USB_VERBOSE
2197 	if (vendor == NULL || product == NULL) {
2198 
2199 		for (kdp = usb_knowndevs;
2200 		    kdp->vendorname != NULL;
2201 		    kdp++) {
2202 			if (kdp->vendor == vendor_id &&
2203 			    (kdp->product == product_id ||
2204 			    (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2205 				break;
2206 		}
2207 		if (kdp->vendorname != NULL) {
2208 			if (vendor == NULL)
2209 				vendor = kdp->vendorname;
2210 			if (product == NULL)
2211 				product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
2212 				    kdp->productname : NULL;
2213 		}
2214 	}
2215 #endif
2216 	if (vendor && *vendor) {
2217 		if (udev->manufacturer != vendor) {
2218 			strlcpy(udev->manufacturer, vendor,
2219 			    sizeof(udev->manufacturer));
2220 		}
2221 	} else {
2222 		snprintf(udev->manufacturer,
2223 		    sizeof(udev->manufacturer), "vendor 0x%04x", vendor_id);
2224 	}
2225 
2226 	if (product && *product) {
2227 		if (udev->product != product) {
2228 			strlcpy(udev->product, product,
2229 			    sizeof(udev->product));
2230 		}
2231 	} else {
2232 		snprintf(udev->product,
2233 		    sizeof(udev->product), "product 0x%04x", product_id);
2234 	}
2235 }
2236 #endif
2237 
2238 /*
2239  * Returns:
2240  * See: USB_MODE_XXX
2241  */
2242 uint8_t
2243 usb2_get_mode(struct usb2_device *udev)
2244 {
2245 	return (udev->flags.usb2_mode);
2246 }
2247 
2248 /*
2249  * Returns:
2250  * See: USB_SPEED_XXX
2251  */
2252 uint8_t
2253 usb2_get_speed(struct usb2_device *udev)
2254 {
2255 	return (udev->speed);
2256 }
2257 
2258 uint32_t
2259 usb2_get_isoc_fps(struct usb2_device *udev)
2260 {
2261 	;				/* indent fix */
2262 	switch (udev->speed) {
2263 	case USB_SPEED_LOW:
2264 	case USB_SPEED_FULL:
2265 		return (1000);
2266 	default:
2267 		return (8000);
2268 	}
2269 }
2270 
2271 struct usb2_device_descriptor *
2272 usb2_get_device_descriptor(struct usb2_device *udev)
2273 {
2274 	if (udev == NULL)
2275 		return (NULL);		/* be NULL safe */
2276 	return (&udev->ddesc);
2277 }
2278 
2279 struct usb2_config_descriptor *
2280 usb2_get_config_descriptor(struct usb2_device *udev)
2281 {
2282 	if (udev == NULL)
2283 		return (NULL);		/* be NULL safe */
2284 	return (udev->cdesc);
2285 }
2286 
2287 /*------------------------------------------------------------------------*
2288  *	usb2_test_quirk - test a device for a given quirk
2289  *
2290  * Return values:
2291  * 0: The USB device does not have the given quirk.
2292  * Else: The USB device has the given quirk.
2293  *------------------------------------------------------------------------*/
2294 uint8_t
2295 usb2_test_quirk(const struct usb2_attach_arg *uaa, uint16_t quirk)
2296 {
2297 	uint8_t found;
2298 
2299 	found = (usb2_test_quirk_p) (&uaa->info, quirk);
2300 	return (found);
2301 }
2302 
2303 struct usb2_interface_descriptor *
2304 usb2_get_interface_descriptor(struct usb2_interface *iface)
2305 {
2306 	if (iface == NULL)
2307 		return (NULL);		/* be NULL safe */
2308 	return (iface->idesc);
2309 }
2310 
2311 uint8_t
2312 usb2_get_interface_altindex(struct usb2_interface *iface)
2313 {
2314 	return (iface->alt_index);
2315 }
2316 
2317 uint8_t
2318 usb2_get_bus_index(struct usb2_device *udev)
2319 {
2320 	return ((uint8_t)device_get_unit(udev->bus->bdev));
2321 }
2322 
2323 uint8_t
2324 usb2_get_device_index(struct usb2_device *udev)
2325 {
2326 	return (udev->device_index);
2327 }
2328 
2329 #if USB_HAVE_UGEN
2330 /*------------------------------------------------------------------------*
2331  *	usb2_notify_addq
2332  *
2333  * This function will generate events for dev.
2334  *------------------------------------------------------------------------*/
2335 static void
2336 usb2_notify_addq(const char *type, struct usb2_device *udev)
2337 {
2338 	char *data = NULL;
2339 	struct malloc_type *mt;
2340 
2341 	mtx_lock(&malloc_mtx);
2342 	mt = malloc_desc2type("bus");	/* XXX M_BUS */
2343 	mtx_unlock(&malloc_mtx);
2344 	if (mt == NULL)
2345 		return;
2346 
2347 	data = malloc(512, mt, M_NOWAIT);
2348 	if (data == NULL)
2349 		return;
2350 
2351 	/* String it all together. */
2352 	snprintf(data, 1024,
2353 	    "%s"
2354 	    "%s "
2355 	    "vendor=0x%04x "
2356 	    "product=0x%04x "
2357 	    "devclass=0x%02x "
2358 	    "devsubclass=0x%02x "
2359 	    "sernum=\"%s\" "
2360 	    "at "
2361 	    "port=%u "
2362 	    "on "
2363 	    "%s\n",
2364 	    type,
2365 	    udev->ugen_name,
2366 	    UGETW(udev->ddesc.idVendor),
2367 	    UGETW(udev->ddesc.idProduct),
2368 	    udev->ddesc.bDeviceClass,
2369 	    udev->ddesc.bDeviceSubClass,
2370 #if USB_HAVE_STRINGS
2371 	    udev->serial,
2372 #else
2373 	    "",
2374 #endif
2375 	    udev->port_no,
2376 	    udev->parent_hub != NULL ?
2377 		udev->parent_hub->ugen_name :
2378 		device_get_nameunit(device_get_parent(udev->bus->bdev)));
2379 
2380 	devctl_queue_data(data);
2381 }
2382 
2383 /*------------------------------------------------------------------------*
2384  *	usb2_fifo_free_wrap
2385  *
2386  * This function will free the FIFOs.
2387  *
2388  * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2389  * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2390  * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2391  * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2392  * control endpoint FIFOs. If "iface_index" is not set to
2393  * "USB_IFACE_INDEX_ANY" the flag has no effect.
2394  *------------------------------------------------------------------------*/
2395 static void
2396 usb2_fifo_free_wrap(struct usb2_device *udev,
2397     uint8_t iface_index, uint8_t flag)
2398 {
2399 	struct usb2_fifo *f;
2400 	uint16_t i;
2401 
2402 	/*
2403 	 * Free any USB FIFOs on the given interface:
2404 	 */
2405 	for (i = 0; i != USB_FIFO_MAX; i++) {
2406 		f = udev->fifo[i];
2407 		if (f == NULL) {
2408 			continue;
2409 		}
2410 		/* Check if the interface index matches */
2411 		if (iface_index == f->iface_index) {
2412 			if (f->methods != &usb2_ugen_methods) {
2413 				/*
2414 				 * Don't free any non-generic FIFOs in
2415 				 * this case.
2416 				 */
2417 				continue;
2418 			}
2419 			if ((f->dev_ep_index == 0) &&
2420 			    (f->fs_xfer == NULL)) {
2421 				/* no need to free this FIFO */
2422 				continue;
2423 			}
2424 		} else if (iface_index == USB_IFACE_INDEX_ANY) {
2425 			if ((f->methods == &usb2_ugen_methods) &&
2426 			    (f->dev_ep_index == 0) &&
2427 			    (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2428 			    (f->fs_xfer == NULL)) {
2429 				/* no need to free this FIFO */
2430 				continue;
2431 			}
2432 		} else {
2433 			/* no need to free this FIFO */
2434 			continue;
2435 		}
2436 		/* free this FIFO */
2437 		usb2_fifo_free(f);
2438 	}
2439 }
2440 #endif
2441 
2442 /*------------------------------------------------------------------------*
2443  *	usb2_peer_can_wakeup
2444  *
2445  * Return values:
2446  * 0: Peer cannot do resume signalling.
2447  * Else: Peer can do resume signalling.
2448  *------------------------------------------------------------------------*/
2449 uint8_t
2450 usb2_peer_can_wakeup(struct usb2_device *udev)
2451 {
2452 	const struct usb2_config_descriptor *cdp;
2453 
2454 	cdp = udev->cdesc;
2455 	if ((cdp != NULL) && (udev->flags.usb2_mode == USB_MODE_HOST)) {
2456 		return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2457 	}
2458 	return (0);			/* not supported */
2459 }
2460 
2461 void
2462 usb2_set_device_state(struct usb2_device *udev, enum usb2_dev_state state)
2463 {
2464 
2465 	KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2466 
2467 	DPRINTF("udev %p state %s -> %s\n", udev,
2468 	    usb2_statestr(udev->state), usb2_statestr(state));
2469 	udev->state = state;
2470 }
2471 
2472 uint8_t
2473 usb2_device_attached(struct usb2_device *udev)
2474 {
2475 	return (udev->state > USB_STATE_DETACHED);
2476 }
2477