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