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