xref: /freebsd/sys/dev/usb/usb_device.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
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.driver_info = 0;	/* reset driver_info */
1338 
1339 		DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1340 		    uaa.info.bInterfaceClass,
1341 		    uaa.info.bInterfaceSubClass,
1342 		    uaa.info.bInterfaceProtocol,
1343 		    uaa.info.bIfaceIndex,
1344 		    uaa.info.bIfaceNum);
1345 
1346 		if (usb_probe_and_attach_sub(udev, &uaa)) {
1347 			/* ignore */
1348 		}
1349 	}
1350 
1351 	if (uaa.temp_dev) {
1352 		/* remove the last created child; it is unused */
1353 
1354 		if (device_delete_child(udev->parent_dev, uaa.temp_dev)) {
1355 			DPRINTFN(0, "device delete child failed\n");
1356 		}
1357 	}
1358 done:
1359 	if (do_unlock)
1360 		usbd_enum_unlock(udev);
1361 
1362 	return (0);
1363 }
1364 
1365 /*------------------------------------------------------------------------*
1366  *	usb_suspend_resume_sub
1367  *
1368  * This function is called when the suspend or resume methods should
1369  * be executed on an USB device.
1370  *------------------------------------------------------------------------*/
1371 static void
1372 usb_suspend_resume_sub(struct usb_device *udev, device_t dev, uint8_t do_suspend)
1373 {
1374 	int err;
1375 
1376 	if (dev == NULL) {
1377 		return;
1378 	}
1379 	if (!device_is_attached(dev)) {
1380 		return;
1381 	}
1382 	if (do_suspend) {
1383 		err = DEVICE_SUSPEND(dev);
1384 	} else {
1385 		err = DEVICE_RESUME(dev);
1386 	}
1387 	if (err) {
1388 		device_printf(dev, "%s failed\n",
1389 		    do_suspend ? "Suspend" : "Resume");
1390 	}
1391 }
1392 
1393 /*------------------------------------------------------------------------*
1394  *	usb_suspend_resume
1395  *
1396  * The following function will suspend or resume the USB device.
1397  *
1398  * Returns:
1399  *    0: Success
1400  * Else: Failure
1401  *------------------------------------------------------------------------*/
1402 usb_error_t
1403 usb_suspend_resume(struct usb_device *udev, uint8_t do_suspend)
1404 {
1405 	struct usb_interface *iface;
1406 	uint8_t i;
1407 
1408 	if (udev == NULL) {
1409 		/* nothing to do */
1410 		return (0);
1411 	}
1412 	DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1413 
1414 	sx_assert(&udev->sr_sx, SA_LOCKED);
1415 
1416 	USB_BUS_LOCK(udev->bus);
1417 	/* filter the suspend events */
1418 	if (udev->flags.peer_suspended == do_suspend) {
1419 		USB_BUS_UNLOCK(udev->bus);
1420 		/* nothing to do */
1421 		return (0);
1422 	}
1423 	udev->flags.peer_suspended = do_suspend;
1424 	USB_BUS_UNLOCK(udev->bus);
1425 
1426 	/* do the suspend or resume */
1427 
1428 	for (i = 0; i != USB_IFACE_MAX; i++) {
1429 
1430 		iface = usbd_get_iface(udev, i);
1431 		if (iface == NULL) {
1432 			/* looks like the end of the USB interfaces */
1433 			break;
1434 		}
1435 		usb_suspend_resume_sub(udev, iface->subdev, do_suspend);
1436 	}
1437 	return (0);
1438 }
1439 
1440 /*------------------------------------------------------------------------*
1441  *      usbd_clear_stall_proc
1442  *
1443  * This function performs generic USB clear stall operations.
1444  *------------------------------------------------------------------------*/
1445 static void
1446 usbd_clear_stall_proc(struct usb_proc_msg *_pm)
1447 {
1448 	struct usb_clear_stall_msg *pm = (void *)_pm;
1449 	struct usb_device *udev = pm->udev;
1450 
1451 	/* Change lock */
1452 	USB_BUS_UNLOCK(udev->bus);
1453 	mtx_lock(&udev->device_mtx);
1454 
1455 	/* Start clear stall callback */
1456 	usbd_transfer_start(udev->ctrl_xfer[1]);
1457 
1458 	/* Change lock */
1459 	mtx_unlock(&udev->device_mtx);
1460 	USB_BUS_LOCK(udev->bus);
1461 }
1462 
1463 /*------------------------------------------------------------------------*
1464  *	usb_alloc_device
1465  *
1466  * This function allocates a new USB device. This function is called
1467  * when a new device has been put in the powered state, but not yet in
1468  * the addressed state. Get initial descriptor, set the address, get
1469  * full descriptor and get strings.
1470  *
1471  * Return values:
1472  *    0: Failure
1473  * Else: Success
1474  *------------------------------------------------------------------------*/
1475 struct usb_device *
1476 usb_alloc_device(device_t parent_dev, struct usb_bus *bus,
1477     struct usb_device *parent_hub, uint8_t depth, uint8_t port_index,
1478     uint8_t port_no, enum usb_dev_speed speed, enum usb_hc_mode mode)
1479 {
1480 	struct usb_attach_arg uaa;
1481 	struct usb_device *udev;
1482 	struct usb_device *adev;
1483 	struct usb_device *hub;
1484 	uint8_t *scratch_ptr;
1485 	size_t scratch_size;
1486 	usb_error_t err;
1487 	uint8_t device_index;
1488 	uint8_t config_index;
1489 	uint8_t config_quirk;
1490 	uint8_t set_config_failed;
1491 
1492 	DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1493 	    "port_index=%u, port_no=%u, speed=%u, usb_mode=%u\n",
1494 	    parent_dev, bus, parent_hub, depth, port_index, port_no,
1495 	    speed, mode);
1496 
1497 	/*
1498 	 * Find an unused device index. In USB Host mode this is the
1499 	 * same as the device address.
1500 	 *
1501 	 * Device index zero is not used and device index 1 should
1502 	 * always be the root hub.
1503 	 */
1504 	for (device_index = USB_ROOT_HUB_ADDR;
1505 	    (device_index != bus->devices_max) &&
1506 	    (bus->devices[device_index] != NULL);
1507 	    device_index++) /* nop */;
1508 
1509 	if (device_index == bus->devices_max) {
1510 		device_printf(bus->bdev,
1511 		    "No free USB device index for new device\n");
1512 		return (NULL);
1513 	}
1514 
1515 	if (depth > 0x10) {
1516 		device_printf(bus->bdev,
1517 		    "Invalid device depth\n");
1518 		return (NULL);
1519 	}
1520 	udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1521 	if (udev == NULL) {
1522 		return (NULL);
1523 	}
1524 	/* initialise our SX-lock */
1525 	sx_init_flags(&udev->ctrl_sx, "USB device SX lock", SX_DUPOK);
1526 
1527 	/* initialise our SX-lock */
1528 	sx_init_flags(&udev->enum_sx, "USB config SX lock", SX_DUPOK);
1529 	sx_init_flags(&udev->sr_sx, "USB suspend and resume SX lock", SX_DUPOK);
1530 
1531 	cv_init(&udev->ctrlreq_cv, "WCTRL");
1532 	cv_init(&udev->ref_cv, "UGONE");
1533 
1534 	/* initialise our mutex */
1535 	mtx_init(&udev->device_mtx, "USB device mutex", NULL, MTX_DEF);
1536 
1537 	/* initialise generic clear stall */
1538 	udev->cs_msg[0].hdr.pm_callback = &usbd_clear_stall_proc;
1539 	udev->cs_msg[0].udev = udev;
1540 	udev->cs_msg[1].hdr.pm_callback = &usbd_clear_stall_proc;
1541 	udev->cs_msg[1].udev = udev;
1542 
1543 	/* initialise some USB device fields */
1544 	udev->parent_hub = parent_hub;
1545 	udev->parent_dev = parent_dev;
1546 	udev->port_index = port_index;
1547 	udev->port_no = port_no;
1548 	udev->depth = depth;
1549 	udev->bus = bus;
1550 	udev->address = USB_START_ADDR;	/* default value */
1551 	udev->plugtime = (usb_ticks_t)ticks;
1552 	/*
1553 	 * We need to force the power mode to "on" because there are plenty
1554 	 * of USB devices out there that do not work very well with
1555 	 * automatic suspend and resume!
1556 	 */
1557 	udev->power_mode = usbd_filter_power_mode(udev, USB_POWER_MODE_ON);
1558 	udev->pwr_save.last_xfer_time = ticks;
1559 	/* we are not ready yet */
1560 	udev->refcount = 1;
1561 
1562 	/* set up default endpoint descriptor */
1563 	udev->ctrl_ep_desc.bLength = sizeof(udev->ctrl_ep_desc);
1564 	udev->ctrl_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1565 	udev->ctrl_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1566 	udev->ctrl_ep_desc.bmAttributes = UE_CONTROL;
1567 	udev->ctrl_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1568 	udev->ctrl_ep_desc.wMaxPacketSize[1] = 0;
1569 	udev->ctrl_ep_desc.bInterval = 0;
1570 
1571 	/* set up default endpoint companion descriptor */
1572 	udev->ctrl_ep_comp_desc.bLength = sizeof(udev->ctrl_ep_comp_desc);
1573 	udev->ctrl_ep_comp_desc.bDescriptorType = UDESC_ENDPOINT_SS_COMP;
1574 
1575 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1576 
1577 	udev->speed = speed;
1578 	udev->flags.usb_mode = mode;
1579 
1580 	/* search for our High Speed USB HUB, if any */
1581 
1582 	adev = udev;
1583 	hub = udev->parent_hub;
1584 
1585 	while (hub) {
1586 		if (hub->speed == USB_SPEED_HIGH) {
1587 			udev->hs_hub_addr = hub->address;
1588 			udev->parent_hs_hub = hub;
1589 			udev->hs_port_no = adev->port_no;
1590 			break;
1591 		}
1592 		adev = hub;
1593 		hub = hub->parent_hub;
1594 	}
1595 
1596 	/* init the default endpoint */
1597 	usb_init_endpoint(udev, 0,
1598 	    &udev->ctrl_ep_desc,
1599 	    &udev->ctrl_ep_comp_desc,
1600 	    &udev->ctrl_ep);
1601 
1602 	/* set device index */
1603 	udev->device_index = device_index;
1604 
1605 #if USB_HAVE_UGEN
1606 	/* Create ugen name */
1607 	snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1608 	    USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1609 	    device_index);
1610 	LIST_INIT(&udev->pd_list);
1611 
1612 	/* Create the control endpoint device */
1613 	udev->ctrl_dev = usb_make_dev(udev, 0, FREAD|FWRITE);
1614 
1615 	/* Create a link from /dev/ugenX.X to the default endpoint */
1616 	make_dev_alias(udev->ctrl_dev, "%s", udev->ugen_name);
1617 #endif
1618 	/* Initialise device */
1619 	if (bus->methods->device_init != NULL) {
1620 		err = (bus->methods->device_init) (udev);
1621 		if (err != 0) {
1622 			DPRINTFN(0, "device init %d failed "
1623 			    "(%s, ignored)\n", device_index,
1624 			    usbd_errstr(err));
1625 			goto done;
1626 		}
1627 	}
1628 	/* set powered device state after device init is complete */
1629 	usb_set_device_state(udev, USB_STATE_POWERED);
1630 
1631 	if (udev->flags.usb_mode == USB_MODE_HOST) {
1632 
1633 		err = usbd_req_set_address(udev, NULL, device_index);
1634 
1635 		/*
1636 		 * This is the new USB device address from now on, if
1637 		 * the set address request didn't set it already.
1638 		 */
1639 		if (udev->address == USB_START_ADDR)
1640 			udev->address = device_index;
1641 
1642 		/*
1643 		 * We ignore any set-address errors, hence there are
1644 		 * buggy USB devices out there that actually receive
1645 		 * the SETUP PID, but manage to set the address before
1646 		 * the STATUS stage is ACK'ed. If the device responds
1647 		 * to the subsequent get-descriptor at the new
1648 		 * address, then we know that the set-address command
1649 		 * was successful.
1650 		 */
1651 		if (err) {
1652 			DPRINTFN(0, "set address %d failed "
1653 			    "(%s, ignored)\n", udev->address,
1654 			    usbd_errstr(err));
1655 		}
1656 	} else {
1657 		/* We are not self powered */
1658 		udev->flags.self_powered = 0;
1659 
1660 		/* Set unconfigured state */
1661 		udev->curr_config_no = USB_UNCONFIG_NO;
1662 		udev->curr_config_index = USB_UNCONFIG_INDEX;
1663 
1664 		/* Setup USB descriptors */
1665 		err = (usb_temp_setup_by_index_p) (udev, usb_template);
1666 		if (err) {
1667 			DPRINTFN(0, "setting up USB template failed maybe the USB "
1668 			    "template module has not been loaded\n");
1669 			goto done;
1670 		}
1671 	}
1672 	usb_set_device_state(udev, USB_STATE_ADDRESSED);
1673 
1674 	/* setup the device descriptor and the initial "wMaxPacketSize" */
1675 	err = usbd_setup_device_desc(udev, NULL);
1676 
1677 	if (err != 0) {
1678 		/* XXX try to re-enumerate the device */
1679 		err = usbd_req_re_enumerate(udev, NULL);
1680 		if (err)
1681 			goto done;
1682 	}
1683 
1684 	/*
1685 	 * Setup temporary USB attach args so that we can figure out some
1686 	 * basic quirks for this device.
1687 	 */
1688 	usb_init_attach_arg(udev, &uaa);
1689 
1690 	if (usb_test_quirk(&uaa, UQ_BUS_POWERED)) {
1691 		udev->flags.uq_bus_powered = 1;
1692 	}
1693 	if (usb_test_quirk(&uaa, UQ_NO_STRINGS)) {
1694 		udev->flags.no_strings = 1;
1695 	}
1696 	/*
1697 	 * Workaround for buggy USB devices.
1698 	 *
1699 	 * It appears that some string-less USB chips will crash and
1700 	 * disappear if any attempts are made to read any string
1701 	 * descriptors.
1702 	 *
1703 	 * Try to detect such chips by checking the strings in the USB
1704 	 * device descriptor. If no strings are present there we
1705 	 * simply disable all USB strings.
1706 	 */
1707 	scratch_ptr = udev->bus->scratch[0].data;
1708 	scratch_size = sizeof(udev->bus->scratch[0].data);
1709 
1710 	if (udev->ddesc.iManufacturer ||
1711 	    udev->ddesc.iProduct ||
1712 	    udev->ddesc.iSerialNumber) {
1713 		/* read out the language ID string */
1714 		err = usbd_req_get_string_desc(udev, NULL,
1715 		    (char *)scratch_ptr, 4, 0, USB_LANGUAGE_TABLE);
1716 	} else {
1717 		err = USB_ERR_INVAL;
1718 	}
1719 
1720 	if (err || (scratch_ptr[0] < 4)) {
1721 		udev->flags.no_strings = 1;
1722 	} else {
1723 		uint16_t langid;
1724 		uint16_t pref;
1725 		uint16_t mask;
1726 		uint8_t x;
1727 
1728 		/* load preferred value and mask */
1729 		pref = usb_lang_id;
1730 		mask = usb_lang_mask;
1731 
1732 		/* align length correctly */
1733 		scratch_ptr[0] &= ~1;
1734 
1735 		/* fix compiler warning */
1736 		langid = 0;
1737 
1738 		/* search for preferred language */
1739 		for (x = 2; (x < scratch_ptr[0]); x += 2) {
1740 			langid = UGETW(scratch_ptr + x);
1741 			if ((langid & mask) == pref)
1742 				break;
1743 		}
1744 		if (x >= scratch_ptr[0]) {
1745 			/* pick the first language as the default */
1746 			DPRINTFN(1, "Using first language\n");
1747 			langid = UGETW(scratch_ptr + 2);
1748 		}
1749 
1750 		DPRINTFN(1, "Language selected: 0x%04x\n", langid);
1751 		udev->langid = langid;
1752 	}
1753 
1754 	/* assume 100mA bus powered for now. Changed when configured. */
1755 	udev->power = USB_MIN_POWER;
1756 	/* fetch the vendor and product strings from the device */
1757 	usbd_set_device_strings(udev);
1758 
1759 	if (udev->flags.usb_mode == USB_MODE_DEVICE) {
1760 		/* USB device mode setup is complete */
1761 		err = 0;
1762 		goto config_done;
1763 	}
1764 
1765 	/*
1766 	 * Most USB devices should attach to config index 0 by
1767 	 * default
1768 	 */
1769 	if (usb_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1770 		config_index = 0;
1771 		config_quirk = 1;
1772 	} else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1773 		config_index = 1;
1774 		config_quirk = 1;
1775 	} else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1776 		config_index = 2;
1777 		config_quirk = 1;
1778 	} else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1779 		config_index = 3;
1780 		config_quirk = 1;
1781 	} else if (usb_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1782 		config_index = 4;
1783 		config_quirk = 1;
1784 	} else {
1785 		config_index = 0;
1786 		config_quirk = 0;
1787 	}
1788 
1789 	set_config_failed = 0;
1790 repeat_set_config:
1791 
1792 	DPRINTF("setting config %u\n", config_index);
1793 
1794 	/* get the USB device configured */
1795 	err = usbd_set_config_index(udev, config_index);
1796 	if (err) {
1797 		if (udev->ddesc.bNumConfigurations != 0) {
1798 			if (!set_config_failed) {
1799 				set_config_failed = 1;
1800 				/* XXX try to re-enumerate the device */
1801 				err = usbd_req_re_enumerate(udev, NULL);
1802 				if (err == 0)
1803 					goto repeat_set_config;
1804 			}
1805 			DPRINTFN(0, "Failure selecting configuration index %u:"
1806 			    "%s, port %u, addr %u (ignored)\n",
1807 			    config_index, usbd_errstr(err), udev->port_no,
1808 			    udev->address);
1809 		}
1810 		/*
1811 		 * Some USB devices do not have any configurations. Ignore any
1812 		 * set config failures!
1813 		 */
1814 		err = 0;
1815 		goto config_done;
1816 	}
1817 	if (!config_quirk && config_index + 1 < udev->ddesc.bNumConfigurations) {
1818 		if ((udev->cdesc->bNumInterface < 2) &&
1819 		    usbd_get_no_descriptors(udev->cdesc, UDESC_ENDPOINT) == 0) {
1820 			DPRINTFN(0, "Found no endpoints, trying next config\n");
1821 			config_index++;
1822 			goto repeat_set_config;
1823 		}
1824 		if (config_index == 0) {
1825 			/*
1826 			 * Try to figure out if we have an
1827 			 * auto-install disk there:
1828 			 */
1829 			if (usb_iface_is_cdrom(udev, 0)) {
1830 				DPRINTFN(0, "Found possible auto-install "
1831 				    "disk (trying next config)\n");
1832 				config_index++;
1833 				goto repeat_set_config;
1834 			}
1835 		}
1836 	}
1837 	EVENTHANDLER_INVOKE(usb_dev_configured, udev, &uaa);
1838 	if (uaa.dev_state != UAA_DEV_READY) {
1839 		/* leave device unconfigured */
1840 		usb_unconfigure(udev, 0);
1841 	}
1842 
1843 config_done:
1844 	DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1845 	    udev->address, udev, udev->parent_hub);
1846 
1847 	/* register our device - we are ready */
1848 	usb_bus_port_set_device(bus, parent_hub ?
1849 	    parent_hub->hub->ports + port_index : NULL, udev, device_index);
1850 
1851 #if USB_HAVE_UGEN
1852 	/* Symlink the ugen device name */
1853 	udev->ugen_symlink = usb_alloc_symlink(udev->ugen_name);
1854 
1855 	/* Announce device */
1856 	printf("%s: <%s> at %s\n", udev->ugen_name,
1857 	    usb_get_manufacturer(udev),
1858 	    device_get_nameunit(udev->bus->bdev));
1859 #endif
1860 
1861 #if USB_HAVE_DEVCTL
1862 	usb_notify_addq("ATTACH", udev);
1863 #endif
1864 done:
1865 	if (err) {
1866 		/*
1867 		 * Free USB device and all subdevices, if any.
1868 		 */
1869 		usb_free_device(udev, 0);
1870 		udev = NULL;
1871 	}
1872 	return (udev);
1873 }
1874 
1875 #if USB_HAVE_UGEN
1876 static struct cdev *
1877 usb_make_dev(struct usb_device *udev, int ep, int mode)
1878 {
1879 	struct usb_fs_privdata* pd;
1880 	char devname[20];
1881 
1882 	/* Store information to locate ourselves again later */
1883 	pd = malloc(sizeof(struct usb_fs_privdata), M_USBDEV,
1884 	    M_WAITOK | M_ZERO);
1885 	pd->bus_index = device_get_unit(udev->bus->bdev);
1886 	pd->dev_index = udev->device_index;
1887 	pd->ep_addr = ep;
1888 	pd->mode = mode;
1889 
1890 	/* Now, create the device itself */
1891 	snprintf(devname, sizeof(devname), "%u.%u.%u",
1892 	    pd->bus_index, pd->dev_index, pd->ep_addr);
1893 	pd->cdev = make_dev(&usb_devsw, 0, UID_ROOT,
1894 	    GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1895 	pd->cdev->si_drv1 = pd;
1896 
1897 	return (pd->cdev);
1898 }
1899 
1900 static void
1901 usb_cdev_create(struct usb_device *udev)
1902 {
1903 	struct usb_config_descriptor *cd;
1904 	struct usb_endpoint_descriptor *ed;
1905 	struct usb_descriptor *desc;
1906 	struct usb_fs_privdata* pd;
1907 	struct cdev *dev;
1908 	int inmode, outmode, inmask, outmask, mode;
1909 	uint8_t ep;
1910 
1911 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1912 
1913 	DPRINTFN(2, "Creating device nodes\n");
1914 
1915 	if (usbd_get_mode(udev) == USB_MODE_DEVICE) {
1916 		inmode = FWRITE;
1917 		outmode = FREAD;
1918 	} else {		 /* USB_MODE_HOST */
1919 		inmode = FREAD;
1920 		outmode = FWRITE;
1921 	}
1922 
1923 	inmask = 0;
1924 	outmask = 0;
1925 	desc = NULL;
1926 
1927 	/*
1928 	 * Collect all used endpoint numbers instead of just
1929 	 * generating 16 static endpoints.
1930 	 */
1931 	cd = usbd_get_config_descriptor(udev);
1932 	while ((desc = usb_desc_foreach(cd, desc))) {
1933 		/* filter out all endpoint descriptors */
1934 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1935 		    (desc->bLength >= sizeof(*ed))) {
1936 			ed = (struct usb_endpoint_descriptor *)desc;
1937 
1938 			/* update masks */
1939 			ep = ed->bEndpointAddress;
1940 			if (UE_GET_DIR(ep)  == UE_DIR_OUT)
1941 				outmask |= 1 << UE_GET_ADDR(ep);
1942 			else
1943 				inmask |= 1 << UE_GET_ADDR(ep);
1944 		}
1945 	}
1946 
1947 	/* Create all available endpoints except EP0 */
1948 	for (ep = 1; ep < 16; ep++) {
1949 		mode = inmask & (1 << ep) ? inmode : 0;
1950 		mode |= outmask & (1 << ep) ? outmode : 0;
1951 		if (mode == 0)
1952 			continue;	/* no IN or OUT endpoint */
1953 
1954 		dev = usb_make_dev(udev, ep, mode);
1955 		pd = dev->si_drv1;
1956 		LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1957 	}
1958 }
1959 
1960 static void
1961 usb_cdev_free(struct usb_device *udev)
1962 {
1963 	struct usb_fs_privdata* pd;
1964 	struct cdev* pcdev;
1965 
1966 	DPRINTFN(2, "Freeing device nodes\n");
1967 
1968 	while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1969 		KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1970 
1971 		pcdev = pd->cdev;
1972 		pd->cdev = NULL;
1973 		LIST_REMOVE(pd, pd_next);
1974 		if (pcdev != NULL)
1975 			destroy_dev_sched_cb(pcdev, usb_cdev_cleanup, pd);
1976 	}
1977 }
1978 
1979 static void
1980 usb_cdev_cleanup(void* arg)
1981 {
1982 	free(arg, M_USBDEV);
1983 }
1984 #endif
1985 
1986 /*------------------------------------------------------------------------*
1987  *	usb_free_device
1988  *
1989  * This function is NULL safe and will free an USB device and its
1990  * children devices, if any.
1991  *
1992  * Flag values: Reserved, set to zero.
1993  *------------------------------------------------------------------------*/
1994 void
1995 usb_free_device(struct usb_device *udev, uint8_t flag)
1996 {
1997 	struct usb_bus *bus;
1998 
1999 	if (udev == NULL)
2000 		return;		/* already freed */
2001 
2002 	DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
2003 
2004 	bus = udev->bus;
2005 	usb_set_device_state(udev, USB_STATE_DETACHED);
2006 
2007 #if USB_HAVE_DEVCTL
2008 	usb_notify_addq("DETACH", udev);
2009 #endif
2010 
2011 #if USB_HAVE_UGEN
2012 	printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
2013 	    usb_get_manufacturer(udev), device_get_nameunit(bus->bdev));
2014 
2015 	/* Destroy UGEN symlink, if any */
2016 	if (udev->ugen_symlink) {
2017 		usb_free_symlink(udev->ugen_symlink);
2018 		udev->ugen_symlink = NULL;
2019 	}
2020 #endif
2021 	/*
2022 	 * Unregister our device first which will prevent any further
2023 	 * references:
2024 	 */
2025 	usb_bus_port_set_device(bus, udev->parent_hub ?
2026 	    udev->parent_hub->hub->ports + udev->port_index : NULL,
2027 	    NULL, USB_ROOT_HUB_ADDR);
2028 
2029 #if USB_HAVE_UGEN
2030 	/* wait for all pending references to go away: */
2031 	mtx_lock(&usb_ref_lock);
2032 	udev->refcount--;
2033 	while (udev->refcount != 0) {
2034 		cv_wait(&udev->ref_cv, &usb_ref_lock);
2035 	}
2036 	mtx_unlock(&usb_ref_lock);
2037 
2038 	destroy_dev_sched_cb(udev->ctrl_dev, usb_cdev_cleanup,
2039 	    udev->ctrl_dev->si_drv1);
2040 #endif
2041 
2042 	if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2043 		/* stop receiving any control transfers (Device Side Mode) */
2044 		usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2045 	}
2046 
2047 	/* the following will get the device unconfigured in software */
2048 	usb_unconfigure(udev, USB_UNCFG_FLAG_FREE_EP0);
2049 
2050 	/* unsetup any leftover default USB transfers */
2051 	usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2052 
2053 	/* template unsetup, if any */
2054 	(usb_temp_unsetup_p) (udev);
2055 
2056 	/*
2057 	 * Make sure that our clear-stall messages are not queued
2058 	 * anywhere:
2059 	 */
2060 	USB_BUS_LOCK(udev->bus);
2061 	usb_proc_mwait(&udev->bus->non_giant_callback_proc,
2062 	    &udev->cs_msg[0], &udev->cs_msg[1]);
2063 	USB_BUS_UNLOCK(udev->bus);
2064 
2065 	sx_destroy(&udev->ctrl_sx);
2066 	sx_destroy(&udev->enum_sx);
2067 	sx_destroy(&udev->sr_sx);
2068 
2069 	cv_destroy(&udev->ctrlreq_cv);
2070 	cv_destroy(&udev->ref_cv);
2071 
2072 	mtx_destroy(&udev->device_mtx);
2073 #if USB_HAVE_UGEN
2074 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
2075 #endif
2076 
2077 	/* Uninitialise device */
2078 	if (bus->methods->device_uninit != NULL)
2079 		(bus->methods->device_uninit) (udev);
2080 
2081 	/* free device */
2082 	free(udev->serial, M_USB);
2083 	free(udev->manufacturer, M_USB);
2084 	free(udev->product, M_USB);
2085 	free(udev, M_USB);
2086 }
2087 
2088 /*------------------------------------------------------------------------*
2089  *	usbd_get_iface
2090  *
2091  * This function is the safe way to get the USB interface structure
2092  * pointer by interface index.
2093  *
2094  * Return values:
2095  *   NULL: Interface not present.
2096  *   Else: Pointer to USB interface structure.
2097  *------------------------------------------------------------------------*/
2098 struct usb_interface *
2099 usbd_get_iface(struct usb_device *udev, uint8_t iface_index)
2100 {
2101 	struct usb_interface *iface = udev->ifaces + iface_index;
2102 
2103 	if (iface_index >= udev->ifaces_max)
2104 		return (NULL);
2105 	return (iface);
2106 }
2107 
2108 /*------------------------------------------------------------------------*
2109  *	usbd_find_descriptor
2110  *
2111  * This function will lookup the first descriptor that matches the
2112  * criteria given by the arguments "type" and "subtype". Descriptors
2113  * will only be searched within the interface having the index
2114  * "iface_index".  If the "id" argument points to an USB descriptor,
2115  * it will be skipped before the search is started. This allows
2116  * searching for multiple descriptors using the same criteria. Else
2117  * the search is started after the interface descriptor.
2118  *
2119  * Return values:
2120  *   NULL: End of descriptors
2121  *   Else: A descriptor matching the criteria
2122  *------------------------------------------------------------------------*/
2123 void   *
2124 usbd_find_descriptor(struct usb_device *udev, void *id, uint8_t iface_index,
2125     uint8_t type, uint8_t type_mask,
2126     uint8_t subtype, uint8_t subtype_mask)
2127 {
2128 	struct usb_descriptor *desc;
2129 	struct usb_config_descriptor *cd;
2130 	struct usb_interface *iface;
2131 
2132 	cd = usbd_get_config_descriptor(udev);
2133 	if (cd == NULL) {
2134 		return (NULL);
2135 	}
2136 	if (id == NULL) {
2137 		iface = usbd_get_iface(udev, iface_index);
2138 		if (iface == NULL) {
2139 			return (NULL);
2140 		}
2141 		id = usbd_get_interface_descriptor(iface);
2142 		if (id == NULL) {
2143 			return (NULL);
2144 		}
2145 	}
2146 	desc = (void *)id;
2147 
2148 	while ((desc = usb_desc_foreach(cd, desc))) {
2149 
2150 		if (desc->bDescriptorType == UDESC_INTERFACE) {
2151 			break;
2152 		}
2153 		if (((desc->bDescriptorType & type_mask) == type) &&
2154 		    ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2155 			return (desc);
2156 		}
2157 	}
2158 	return (NULL);
2159 }
2160 
2161 /*------------------------------------------------------------------------*
2162  *	usb_devinfo
2163  *
2164  * This function will dump information from the device descriptor
2165  * belonging to the USB device pointed to by "udev", to the string
2166  * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2167  * including the terminating zero.
2168  *------------------------------------------------------------------------*/
2169 void
2170 usb_devinfo(struct usb_device *udev, char *dst_ptr, uint16_t dst_len)
2171 {
2172 	struct usb_device_descriptor *udd = &udev->ddesc;
2173 	uint16_t bcdDevice;
2174 	uint16_t bcdUSB;
2175 
2176 	bcdUSB = UGETW(udd->bcdUSB);
2177 	bcdDevice = UGETW(udd->bcdDevice);
2178 
2179 	if (udd->bDeviceClass != 0xFF) {
2180 		snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2181 		    "%x.%02x, addr %d",
2182 		    usb_get_manufacturer(udev),
2183 		    usb_get_product(udev),
2184 		    udd->bDeviceClass, udd->bDeviceSubClass,
2185 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2186 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2187 		    udev->address);
2188 	} else {
2189 		snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2190 		    "%x.%02x, addr %d",
2191 		    usb_get_manufacturer(udev),
2192 		    usb_get_product(udev),
2193 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2194 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2195 		    udev->address);
2196 	}
2197 }
2198 
2199 #ifdef USB_VERBOSE
2200 /*
2201  * Descriptions of of known vendors and devices ("products").
2202  */
2203 struct usb_knowndev {
2204 	uint16_t vendor;
2205 	uint16_t product;
2206 	uint32_t flags;
2207 	const char *vendorname;
2208 	const char *productname;
2209 };
2210 
2211 #define	USB_KNOWNDEV_NOPROD	0x01	/* match on vendor only */
2212 
2213 #include "usbdevs.h"
2214 #include "usbdevs_data.h"
2215 #endif					/* USB_VERBOSE */
2216 
2217 static void
2218 usbd_set_device_strings(struct usb_device *udev)
2219 {
2220 	struct usb_device_descriptor *udd = &udev->ddesc;
2221 #ifdef USB_VERBOSE
2222 	const struct usb_knowndev *kdp;
2223 #endif
2224 	char *temp_ptr;
2225 	size_t temp_size;
2226 	uint16_t vendor_id;
2227 	uint16_t product_id;
2228 
2229 	temp_ptr = (char *)udev->bus->scratch[0].data;
2230 	temp_size = sizeof(udev->bus->scratch[0].data);
2231 
2232 	vendor_id = UGETW(udd->idVendor);
2233 	product_id = UGETW(udd->idProduct);
2234 
2235 	/* get serial number string */
2236 	usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2237 	    udev->ddesc.iSerialNumber);
2238 	udev->serial = strdup(temp_ptr, M_USB);
2239 
2240 	/* get manufacturer string */
2241 	usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2242 	    udev->ddesc.iManufacturer);
2243 	usb_trim_spaces(temp_ptr);
2244 	if (temp_ptr[0] != '\0')
2245 		udev->manufacturer = strdup(temp_ptr, M_USB);
2246 
2247 	/* get product string */
2248 	usbd_req_get_string_any(udev, NULL, temp_ptr, temp_size,
2249 	    udev->ddesc.iProduct);
2250 	usb_trim_spaces(temp_ptr);
2251 	if (temp_ptr[0] != '\0')
2252 		udev->product = strdup(temp_ptr, M_USB);
2253 
2254 #ifdef USB_VERBOSE
2255 	if (udev->manufacturer == NULL || udev->product == NULL) {
2256 		for (kdp = usb_knowndevs; kdp->vendorname != NULL; kdp++) {
2257 			if (kdp->vendor == vendor_id &&
2258 			    (kdp->product == product_id ||
2259 			    (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2260 				break;
2261 		}
2262 		if (kdp->vendorname != NULL) {
2263 			/* XXX should use pointer to knowndevs string */
2264 			if (udev->manufacturer == NULL) {
2265 				udev->manufacturer = strdup(kdp->vendorname,
2266 				    M_USB);
2267 			}
2268 			if (udev->product == NULL &&
2269 			    (kdp->flags & USB_KNOWNDEV_NOPROD) == 0) {
2270 				udev->product = strdup(kdp->productname,
2271 				    M_USB);
2272 			}
2273 		}
2274 	}
2275 #endif
2276 	/* Provide default strings if none were found */
2277 	if (udev->manufacturer == NULL) {
2278 		snprintf(temp_ptr, temp_size, "vendor 0x%04x", vendor_id);
2279 		udev->manufacturer = strdup(temp_ptr, M_USB);
2280 	}
2281 	if (udev->product == NULL) {
2282 		snprintf(temp_ptr, temp_size, "product 0x%04x", product_id);
2283 		udev->product = strdup(temp_ptr, M_USB);
2284 	}
2285 }
2286 
2287 /*
2288  * Returns:
2289  * See: USB_MODE_XXX
2290  */
2291 enum usb_hc_mode
2292 usbd_get_mode(struct usb_device *udev)
2293 {
2294 	return (udev->flags.usb_mode);
2295 }
2296 
2297 /*
2298  * Returns:
2299  * See: USB_SPEED_XXX
2300  */
2301 enum usb_dev_speed
2302 usbd_get_speed(struct usb_device *udev)
2303 {
2304 	return (udev->speed);
2305 }
2306 
2307 uint32_t
2308 usbd_get_isoc_fps(struct usb_device *udev)
2309 {
2310 	;				/* indent fix */
2311 	switch (udev->speed) {
2312 	case USB_SPEED_LOW:
2313 	case USB_SPEED_FULL:
2314 		return (1000);
2315 	default:
2316 		return (8000);
2317 	}
2318 }
2319 
2320 struct usb_device_descriptor *
2321 usbd_get_device_descriptor(struct usb_device *udev)
2322 {
2323 	if (udev == NULL)
2324 		return (NULL);		/* be NULL safe */
2325 	return (&udev->ddesc);
2326 }
2327 
2328 struct usb_config_descriptor *
2329 usbd_get_config_descriptor(struct usb_device *udev)
2330 {
2331 	if (udev == NULL)
2332 		return (NULL);		/* be NULL safe */
2333 	return (udev->cdesc);
2334 }
2335 
2336 /*------------------------------------------------------------------------*
2337  *	usb_test_quirk - test a device for a given quirk
2338  *
2339  * Return values:
2340  * 0: The USB device does not have the given quirk.
2341  * Else: The USB device has the given quirk.
2342  *------------------------------------------------------------------------*/
2343 uint8_t
2344 usb_test_quirk(const struct usb_attach_arg *uaa, uint16_t quirk)
2345 {
2346 	uint8_t found;
2347 
2348 	found = (usb_test_quirk_p) (&uaa->info, quirk);
2349 	return (found);
2350 }
2351 
2352 struct usb_interface_descriptor *
2353 usbd_get_interface_descriptor(struct usb_interface *iface)
2354 {
2355 	if (iface == NULL)
2356 		return (NULL);		/* be NULL safe */
2357 	return (iface->idesc);
2358 }
2359 
2360 uint8_t
2361 usbd_get_interface_altindex(struct usb_interface *iface)
2362 {
2363 	return (iface->alt_index);
2364 }
2365 
2366 uint8_t
2367 usbd_get_bus_index(struct usb_device *udev)
2368 {
2369 	return ((uint8_t)device_get_unit(udev->bus->bdev));
2370 }
2371 
2372 uint8_t
2373 usbd_get_device_index(struct usb_device *udev)
2374 {
2375 	return (udev->device_index);
2376 }
2377 
2378 #if USB_HAVE_DEVCTL
2379 static void
2380 usb_notify_addq(const char *type, struct usb_device *udev)
2381 {
2382 	struct usb_interface *iface;
2383 	struct sbuf *sb;
2384 	int i;
2385 
2386 	/* announce the device */
2387 	sb = sbuf_new_auto();
2388 	sbuf_printf(sb,
2389 #if USB_HAVE_UGEN
2390 	    "ugen=%s "
2391 	    "cdev=%s "
2392 #endif
2393 	    "vendor=0x%04x "
2394 	    "product=0x%04x "
2395 	    "devclass=0x%02x "
2396 	    "devsubclass=0x%02x "
2397 	    "sernum=\"%s\" "
2398 	    "release=0x%04x "
2399 	    "mode=%s "
2400 	    "port=%u "
2401 #if USB_HAVE_UGEN
2402 	    "parent=%s"
2403 #endif
2404 	    "",
2405 #if USB_HAVE_UGEN
2406 	    udev->ugen_name,
2407 	    udev->ugen_name,
2408 #endif
2409 	    UGETW(udev->ddesc.idVendor),
2410 	    UGETW(udev->ddesc.idProduct),
2411 	    udev->ddesc.bDeviceClass,
2412 	    udev->ddesc.bDeviceSubClass,
2413 	    usb_get_serial(udev),
2414 	    UGETW(udev->ddesc.bcdDevice),
2415 	    (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2416 	    udev->port_no
2417 #if USB_HAVE_UGEN
2418 	    , udev->parent_hub != NULL ?
2419 		udev->parent_hub->ugen_name :
2420 		device_get_nameunit(device_get_parent(udev->bus->bdev))
2421 #endif
2422 	    );
2423 	sbuf_finish(sb);
2424 	devctl_notify("USB", "DEVICE", type, sbuf_data(sb));
2425 	sbuf_delete(sb);
2426 
2427 	/* announce each interface */
2428 	for (i = 0; i < USB_IFACE_MAX; i++) {
2429 		iface = usbd_get_iface(udev, i);
2430 		if (iface == NULL)
2431 			break;		/* end of interfaces */
2432 		if (iface->idesc == NULL)
2433 			continue;	/* no interface descriptor */
2434 
2435 		sb = sbuf_new_auto();
2436 		sbuf_printf(sb,
2437 #if USB_HAVE_UGEN
2438 		    "ugen=%s "
2439 		    "cdev=%s "
2440 #endif
2441 		    "vendor=0x%04x "
2442 		    "product=0x%04x "
2443 		    "devclass=0x%02x "
2444 		    "devsubclass=0x%02x "
2445 		    "sernum=\"%s\" "
2446 		    "release=0x%04x "
2447 		    "mode=%s "
2448 		    "interface=%d "
2449 		    "endpoints=%d "
2450 		    "intclass=0x%02x "
2451 		    "intsubclass=0x%02x "
2452 		    "intprotocol=0x%02x",
2453 #if USB_HAVE_UGEN
2454 		    udev->ugen_name,
2455 		    udev->ugen_name,
2456 #endif
2457 		    UGETW(udev->ddesc.idVendor),
2458 		    UGETW(udev->ddesc.idProduct),
2459 		    udev->ddesc.bDeviceClass,
2460 		    udev->ddesc.bDeviceSubClass,
2461 		    usb_get_serial(udev),
2462 		    UGETW(udev->ddesc.bcdDevice),
2463 		    (udev->flags.usb_mode == USB_MODE_HOST) ? "host" : "device",
2464 		    iface->idesc->bInterfaceNumber,
2465 		    iface->idesc->bNumEndpoints,
2466 		    iface->idesc->bInterfaceClass,
2467 		    iface->idesc->bInterfaceSubClass,
2468 		    iface->idesc->bInterfaceProtocol);
2469 		sbuf_finish(sb);
2470 		devctl_notify("USB", "INTERFACE", type, sbuf_data(sb));
2471 		sbuf_delete(sb);
2472 	}
2473 }
2474 #endif
2475 
2476 #if USB_HAVE_UGEN
2477 /*------------------------------------------------------------------------*
2478  *	usb_fifo_free_wrap
2479  *
2480  * This function will free the FIFOs.
2481  *
2482  * Description of "flag" argument: If the USB_UNCFG_FLAG_FREE_EP0 flag
2483  * is set and "iface_index" is set to "USB_IFACE_INDEX_ANY", we free
2484  * all FIFOs. If the USB_UNCFG_FLAG_FREE_EP0 flag is not set and
2485  * "iface_index" is set to "USB_IFACE_INDEX_ANY", we free all non
2486  * control endpoint FIFOs. If "iface_index" is not set to
2487  * "USB_IFACE_INDEX_ANY" the flag has no effect.
2488  *------------------------------------------------------------------------*/
2489 static void
2490 usb_fifo_free_wrap(struct usb_device *udev,
2491     uint8_t iface_index, uint8_t flag)
2492 {
2493 	struct usb_fifo *f;
2494 	uint16_t i;
2495 
2496 	/*
2497 	 * Free any USB FIFOs on the given interface:
2498 	 */
2499 	for (i = 0; i != USB_FIFO_MAX; i++) {
2500 		f = udev->fifo[i];
2501 		if (f == NULL) {
2502 			continue;
2503 		}
2504 		/* Check if the interface index matches */
2505 		if (iface_index == f->iface_index) {
2506 			if (f->methods != &usb_ugen_methods) {
2507 				/*
2508 				 * Don't free any non-generic FIFOs in
2509 				 * this case.
2510 				 */
2511 				continue;
2512 			}
2513 			if ((f->dev_ep_index == 0) &&
2514 			    (f->fs_xfer == NULL)) {
2515 				/* no need to free this FIFO */
2516 				continue;
2517 			}
2518 		} else if (iface_index == USB_IFACE_INDEX_ANY) {
2519 			if ((f->methods == &usb_ugen_methods) &&
2520 			    (f->dev_ep_index == 0) &&
2521 			    (!(flag & USB_UNCFG_FLAG_FREE_EP0)) &&
2522 			    (f->fs_xfer == NULL)) {
2523 				/* no need to free this FIFO */
2524 				continue;
2525 			}
2526 		} else {
2527 			/* no need to free this FIFO */
2528 			continue;
2529 		}
2530 		/* free this FIFO */
2531 		usb_fifo_free(f);
2532 	}
2533 }
2534 #endif
2535 
2536 /*------------------------------------------------------------------------*
2537  *	usb_peer_can_wakeup
2538  *
2539  * Return values:
2540  * 0: Peer cannot do resume signalling.
2541  * Else: Peer can do resume signalling.
2542  *------------------------------------------------------------------------*/
2543 uint8_t
2544 usb_peer_can_wakeup(struct usb_device *udev)
2545 {
2546 	const struct usb_config_descriptor *cdp;
2547 
2548 	cdp = udev->cdesc;
2549 	if ((cdp != NULL) && (udev->flags.usb_mode == USB_MODE_HOST)) {
2550 		return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2551 	}
2552 	return (0);			/* not supported */
2553 }
2554 
2555 void
2556 usb_set_device_state(struct usb_device *udev, enum usb_dev_state state)
2557 {
2558 
2559 	KASSERT(state < USB_STATE_MAX, ("invalid udev state"));
2560 
2561 	DPRINTF("udev %p state %s -> %s\n", udev,
2562 	    usb_statestr(udev->state), usb_statestr(state));
2563 	udev->state = state;
2564 
2565 	if (udev->bus->methods->device_state_change != NULL)
2566 		(udev->bus->methods->device_state_change) (udev);
2567 }
2568 
2569 enum usb_dev_state
2570 usb_get_device_state(struct usb_device *udev)
2571 {
2572 	if (udev == NULL)
2573 		return (USB_STATE_DETACHED);
2574 	return (udev->state);
2575 }
2576 
2577 uint8_t
2578 usbd_device_attached(struct usb_device *udev)
2579 {
2580 	return (udev->state > USB_STATE_DETACHED);
2581 }
2582 
2583 /* The following function locks enumerating the given USB device. */
2584 
2585 void
2586 usbd_enum_lock(struct usb_device *udev)
2587 {
2588 	sx_xlock(&udev->enum_sx);
2589 	sx_xlock(&udev->sr_sx);
2590 	/*
2591 	 * NEWBUS LOCK NOTE: We should check if any parent SX locks
2592 	 * are locked before locking Giant. Else the lock can be
2593 	 * locked multiple times.
2594 	 */
2595 	mtx_lock(&Giant);
2596 }
2597 
2598 /* The following function unlocks enumerating the given USB device. */
2599 
2600 void
2601 usbd_enum_unlock(struct usb_device *udev)
2602 {
2603 	mtx_unlock(&Giant);
2604 	sx_xunlock(&udev->enum_sx);
2605 	sx_xunlock(&udev->sr_sx);
2606 }
2607 
2608 /* The following function locks suspend and resume. */
2609 
2610 void
2611 usbd_sr_lock(struct usb_device *udev)
2612 {
2613 	sx_xlock(&udev->sr_sx);
2614 	/*
2615 	 * NEWBUS LOCK NOTE: We should check if any parent SX locks
2616 	 * are locked before locking Giant. Else the lock can be
2617 	 * locked multiple times.
2618 	 */
2619 	mtx_lock(&Giant);
2620 }
2621 
2622 /* The following function unlocks suspend and resume. */
2623 
2624 void
2625 usbd_sr_unlock(struct usb_device *udev)
2626 {
2627 	mtx_unlock(&Giant);
2628 	sx_xunlock(&udev->sr_sx);
2629 }
2630 
2631 /*
2632  * The following function checks the enumerating lock for the given
2633  * USB device.
2634  */
2635 
2636 uint8_t
2637 usbd_enum_is_locked(struct usb_device *udev)
2638 {
2639 	return (sx_xlocked(&udev->enum_sx));
2640 }
2641 
2642 /*
2643  * The following function is used to set the per-interface specific
2644  * plug and play information. The string referred to by the pnpinfo
2645  * argument can safely be freed after calling this function. The
2646  * pnpinfo of an interface will be reset at device detach or when
2647  * passing a NULL argument to this function. This function
2648  * returns zero on success, else a USB_ERR_XXX failure code.
2649  */
2650 
2651 usb_error_t
2652 usbd_set_pnpinfo(struct usb_device *udev, uint8_t iface_index, const char *pnpinfo)
2653 {
2654 	struct usb_interface *iface;
2655 
2656 	iface = usbd_get_iface(udev, iface_index);
2657 	if (iface == NULL)
2658 		return (USB_ERR_INVAL);
2659 
2660 	if (iface->pnpinfo != NULL) {
2661 		free(iface->pnpinfo, M_USBDEV);
2662 		iface->pnpinfo = NULL;
2663 	}
2664 
2665 	if (pnpinfo == NULL || pnpinfo[0] == 0)
2666 		return (0);		/* success */
2667 
2668 	iface->pnpinfo = strdup(pnpinfo, M_USBDEV);
2669 	if (iface->pnpinfo == NULL)
2670 		return (USB_ERR_NOMEM);
2671 
2672 	return (0);			/* success */
2673 }
2674 
2675