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