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