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