xref: /freebsd/sys/dev/usb/usb_device.c (revision d2b2128a286a00ee53d79cb88b4e59bf42525cf9)
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <dev/usb/usb_mfunc.h>
28 #include <dev/usb/usb_error.h>
29 #include <dev/usb/usb.h>
30 #include <dev/usb/usb_ioctl.h>
31 #include "usbdevs.h"
32 
33 #define	USB_DEBUG_VAR usb2_debug
34 
35 #include <dev/usb/usb_core.h>
36 #include <dev/usb/usb_debug.h>
37 #include <dev/usb/usb_process.h>
38 #include <dev/usb/usb_device.h>
39 #include <dev/usb/usb_busdma.h>
40 #include <dev/usb/usb_transfer.h>
41 #include <dev/usb/usb_parse.h>
42 #include <dev/usb/usb_request.h>
43 #include <dev/usb/usb_dynamic.h>
44 #include <dev/usb/usb_hub.h>
45 #include <dev/usb/usb_util.h>
46 #include <dev/usb/usb_mbuf.h>
47 #include <dev/usb/usb_msctest.h>
48 #if USB_HAVE_UGEN
49 #include <dev/usb/usb_dev.h>
50 #include <dev/usb/usb_generic.h>
51 #endif
52 
53 #include <dev/usb/quirk/usb_quirk.h>
54 
55 #include <dev/usb/usb_controller.h>
56 #include <dev/usb/usb_bus.h>
57 
58 /* function prototypes */
59 
60 static void	usb2_fill_pipe_data(struct usb2_device *, uint8_t,
61 		    struct usb2_endpoint_descriptor *, struct usb2_pipe *);
62 static void	usb2_free_pipe_data(struct usb2_device *, uint8_t, uint8_t);
63 static void	usb2_free_iface_data(struct usb2_device *);
64 static void	usb2_detach_device_sub(struct usb2_device *, device_t *,
65 		    uint8_t);
66 static uint8_t	usb2_probe_and_attach_sub(struct usb2_device *,
67 		    struct usb2_attach_arg *);
68 static void	usb2_init_attach_arg(struct usb2_device *,
69 		    struct usb2_attach_arg *);
70 static void	usb2_suspend_resume_sub(struct usb2_device *, device_t,
71 		    uint8_t);
72 static void	usb2_clear_stall_proc(struct usb2_proc_msg *_pm);
73 #if USB_HAVE_STRINGS
74 static void	usb2_check_strings(struct usb2_device *);
75 #endif
76 static usb2_error_t usb2_fill_iface_data(struct usb2_device *, uint8_t,
77 		    uint8_t);
78 #if USB_HAVE_UGEN
79 static void	usb2_notify_addq(const char *type, struct usb2_device *);
80 static void	usb2_fifo_free_wrap(struct usb2_device *, uint8_t, uint8_t);
81 static struct cdev *usb2_make_dev(struct usb2_device *, int, int);
82 static void	usb2_cdev_create(struct usb2_device *);
83 static void	usb2_cdev_free(struct usb2_device *);
84 static void	usb2_cdev_cleanup(void *);
85 #endif
86 
87 /* This variable is global to allow easy access to it: */
88 
89 int	usb2_template = 0;
90 
91 SYSCTL_INT(_hw_usb2, OID_AUTO, template, CTLFLAG_RW,
92     &usb2_template, 0, "Selected USB device side template");
93 
94 
95 /*------------------------------------------------------------------------*
96  *	usb2_get_pipe_by_addr
97  *
98  * This function searches for an USB pipe by endpoint address and
99  * direction.
100  *
101  * Returns:
102  * NULL: Failure
103  * Else: Success
104  *------------------------------------------------------------------------*/
105 struct usb2_pipe *
106 usb2_get_pipe_by_addr(struct usb2_device *udev, uint8_t ea_val)
107 {
108 	struct usb2_pipe *pipe = udev->pipes;
109 	struct usb2_pipe *pipe_end = udev->pipes + USB_EP_MAX;
110 	enum {
111 		EA_MASK = (UE_DIR_IN | UE_DIR_OUT | UE_ADDR),
112 	};
113 
114 	/*
115 	 * According to the USB specification not all bits are used
116 	 * for the endpoint address. Keep defined bits only:
117 	 */
118 	ea_val &= EA_MASK;
119 
120 	/*
121 	 * Iterate accross all the USB pipes searching for a match
122 	 * based on the endpoint address:
123 	 */
124 	for (; pipe != pipe_end; pipe++) {
125 
126 		if (pipe->edesc == NULL) {
127 			continue;
128 		}
129 		/* do the mask and check the value */
130 		if ((pipe->edesc->bEndpointAddress & EA_MASK) == ea_val) {
131 			goto found;
132 		}
133 	}
134 
135 	/*
136 	 * The default pipe is always present and is checked separately:
137 	 */
138 	if ((udev->default_pipe.edesc) &&
139 	    ((udev->default_pipe.edesc->bEndpointAddress & EA_MASK) == ea_val)) {
140 		pipe = &udev->default_pipe;
141 		goto found;
142 	}
143 	return (NULL);
144 
145 found:
146 	return (pipe);
147 }
148 
149 /*------------------------------------------------------------------------*
150  *	usb2_get_pipe
151  *
152  * This function searches for an USB pipe based on the information
153  * given by the passed "struct usb2_config" pointer.
154  *
155  * Return values:
156  * NULL: No match.
157  * Else: Pointer to "struct usb2_pipe".
158  *------------------------------------------------------------------------*/
159 struct usb2_pipe *
160 usb2_get_pipe(struct usb2_device *udev, uint8_t iface_index,
161     const struct usb2_config *setup)
162 {
163 	struct usb2_pipe *pipe = udev->pipes;
164 	struct usb2_pipe *pipe_end = udev->pipes + USB_EP_MAX;
165 	uint8_t index = setup->ep_index;
166 	uint8_t ea_mask;
167 	uint8_t ea_val;
168 	uint8_t type_mask;
169 	uint8_t type_val;
170 
171 	DPRINTFN(10, "udev=%p iface_index=%d address=0x%x "
172 	    "type=0x%x dir=0x%x index=%d\n",
173 	    udev, iface_index, setup->endpoint,
174 	    setup->type, setup->direction, setup->ep_index);
175 
176 	/* setup expected endpoint direction mask and value */
177 
178 	if (setup->direction == UE_DIR_ANY) {
179 		/* match any endpoint direction */
180 		ea_mask = 0;
181 		ea_val = 0;
182 	} else {
183 		/* match the given endpoint direction */
184 		ea_mask = (UE_DIR_IN | UE_DIR_OUT);
185 		ea_val = (setup->direction & (UE_DIR_IN | UE_DIR_OUT));
186 	}
187 
188 	/* setup expected endpoint address */
189 
190 	if (setup->endpoint == UE_ADDR_ANY) {
191 		/* match any endpoint address */
192 	} else {
193 		/* match the given endpoint address */
194 		ea_mask |= UE_ADDR;
195 		ea_val |= (setup->endpoint & UE_ADDR);
196 	}
197 
198 	/* setup expected endpoint type */
199 
200 	if (setup->type == UE_BULK_INTR) {
201 		/* this will match BULK and INTERRUPT endpoints */
202 		type_mask = 2;
203 		type_val = 2;
204 	} else if (setup->type == UE_TYPE_ANY) {
205 		/* match any endpoint type */
206 		type_mask = 0;
207 		type_val = 0;
208 	} else {
209 		/* match the given endpoint type */
210 		type_mask = UE_XFERTYPE;
211 		type_val = (setup->type & UE_XFERTYPE);
212 	}
213 
214 	/*
215 	 * Iterate accross all the USB pipes searching for a match
216 	 * based on the endpoint address. Note that we are searching
217 	 * the pipes from the beginning of the "udev->pipes" array.
218 	 */
219 	for (; pipe != pipe_end; pipe++) {
220 
221 		if ((pipe->edesc == NULL) ||
222 		    (pipe->iface_index != iface_index)) {
223 			continue;
224 		}
225 		/* do the masks and check the values */
226 
227 		if (((pipe->edesc->bEndpointAddress & ea_mask) == ea_val) &&
228 		    ((pipe->edesc->bmAttributes & type_mask) == type_val)) {
229 			if (!index--) {
230 				goto found;
231 			}
232 		}
233 	}
234 
235 	/*
236 	 * Match against default pipe last, so that "any pipe", "any
237 	 * address" and "any direction" returns the first pipe of the
238 	 * interface. "iface_index" and "direction" is ignored:
239 	 */
240 	if ((udev->default_pipe.edesc) &&
241 	    ((udev->default_pipe.edesc->bEndpointAddress & ea_mask) == ea_val) &&
242 	    ((udev->default_pipe.edesc->bmAttributes & type_mask) == type_val) &&
243 	    (!index)) {
244 		pipe = &udev->default_pipe;
245 		goto found;
246 	}
247 	return (NULL);
248 
249 found:
250 	return (pipe);
251 }
252 
253 /*------------------------------------------------------------------------*
254  *	usb2_interface_count
255  *
256  * This function stores the number of USB interfaces excluding
257  * alternate settings, which the USB config descriptor reports into
258  * the unsigned 8-bit integer pointed to by "count".
259  *
260  * Returns:
261  *    0: Success
262  * Else: Failure
263  *------------------------------------------------------------------------*/
264 usb2_error_t
265 usb2_interface_count(struct usb2_device *udev, uint8_t *count)
266 {
267 	if (udev->cdesc == NULL) {
268 		*count = 0;
269 		return (USB_ERR_NOT_CONFIGURED);
270 	}
271 	*count = udev->cdesc->bNumInterface;
272 	return (USB_ERR_NORMAL_COMPLETION);
273 }
274 
275 
276 /*------------------------------------------------------------------------*
277  *	usb2_fill_pipe_data
278  *
279  * This function will initialise the USB pipe structure pointed to by
280  * the "pipe" argument.
281  *------------------------------------------------------------------------*/
282 static void
283 usb2_fill_pipe_data(struct usb2_device *udev, uint8_t iface_index,
284     struct usb2_endpoint_descriptor *edesc, struct usb2_pipe *pipe)
285 {
286 
287 	bzero(pipe, sizeof(*pipe));
288 
289 	(udev->bus->methods->pipe_init) (udev, edesc, pipe);
290 
291 	if (pipe->methods == NULL) {
292 		/* the pipe is invalid: just return */
293 		return;
294 	}
295 	/* initialise USB pipe structure */
296 	pipe->edesc = edesc;
297 	pipe->iface_index = iface_index;
298 	TAILQ_INIT(&pipe->pipe_q.head);
299 	pipe->pipe_q.command = &usb2_pipe_start;
300 
301 	/* clear stall, if any */
302 	if (udev->bus->methods->clear_stall) {
303 		USB_BUS_LOCK(udev->bus);
304 		(udev->bus->methods->clear_stall) (udev, pipe);
305 		USB_BUS_UNLOCK(udev->bus);
306 	}
307 }
308 
309 /*------------------------------------------------------------------------*
310  *	usb2_free_pipe_data
311  *
312  * This function will free USB pipe data for the given interface
313  * index. Hence we do not have any dynamic allocations we simply clear
314  * "pipe->edesc" to indicate that the USB pipe structure can be
315  * reused. The pipes belonging to the given interface should not be in
316  * use when this function is called and no check is performed to
317  * prevent this.
318  *------------------------------------------------------------------------*/
319 static void
320 usb2_free_pipe_data(struct usb2_device *udev,
321     uint8_t iface_index, uint8_t iface_mask)
322 {
323 	struct usb2_pipe *pipe = udev->pipes;
324 	struct usb2_pipe *pipe_end = udev->pipes + USB_EP_MAX;
325 
326 	while (pipe != pipe_end) {
327 		if ((pipe->iface_index & iface_mask) == iface_index) {
328 			/* free pipe */
329 			pipe->edesc = NULL;
330 		}
331 		pipe++;
332 	}
333 }
334 
335 /*------------------------------------------------------------------------*
336  *	usb2_pipe_foreach
337  *
338  * This function will iterate all the USB endpoints except the control
339  * endpoint. This function is NULL safe.
340  *
341  * Return values:
342  * NULL: End of USB pipes
343  * Else: Pointer to next USB pipe
344  *------------------------------------------------------------------------*/
345 struct usb2_pipe *
346 usb2_pipe_foreach(struct usb2_device *udev, struct usb2_pipe *pipe)
347 {
348 	struct usb2_pipe *pipe_end = udev->pipes + USB_EP_MAX;
349 
350 	/* be NULL safe */
351 	if (udev == NULL)
352 		return (NULL);
353 
354 	/* get next pipe */
355 	if (pipe == NULL)
356 		pipe = udev->pipes;
357 	else
358 		pipe++;
359 
360 	/* find next allocated pipe */
361 	while (pipe != pipe_end) {
362 		if (pipe->edesc != NULL)
363 			return (pipe);
364 		pipe++;
365 	}
366 	return (NULL);
367 }
368 
369 /*------------------------------------------------------------------------*
370  *	usb2_fill_iface_data
371  *
372  * This function will fill in interface data and allocate USB pipes
373  * for all the endpoints that belong to the given interface. This
374  * function is typically called when setting the configuration or when
375  * setting an alternate interface.
376  *------------------------------------------------------------------------*/
377 static usb2_error_t
378 usb2_fill_iface_data(struct usb2_device *udev,
379     uint8_t iface_index, uint8_t alt_index)
380 {
381 	struct usb2_interface *iface = usb2_get_iface(udev, iface_index);
382 	struct usb2_pipe *pipe;
383 	struct usb2_pipe *pipe_end;
384 	struct usb2_interface_descriptor *id;
385 	struct usb2_endpoint_descriptor *ed = NULL;
386 	struct usb2_descriptor *desc;
387 	uint8_t nendpt;
388 
389 	if (iface == NULL) {
390 		return (USB_ERR_INVAL);
391 	}
392 	DPRINTFN(5, "iface_index=%d alt_index=%d\n",
393 	    iface_index, alt_index);
394 
395 	sx_assert(udev->default_sx + 1, SA_LOCKED);
396 
397 	pipe = udev->pipes;
398 	pipe_end = udev->pipes + USB_EP_MAX;
399 
400 	/*
401 	 * Check if any USB pipes on the given USB interface are in
402 	 * use:
403 	 */
404 	while (pipe != pipe_end) {
405 		if ((pipe->edesc != NULL) &&
406 		    (pipe->iface_index == iface_index) &&
407 		    (pipe->refcount != 0)) {
408 			return (USB_ERR_IN_USE);
409 		}
410 		pipe++;
411 	}
412 
413 	pipe = &udev->pipes[0];
414 
415 	id = usb2_find_idesc(udev->cdesc, iface_index, alt_index);
416 	if (id == NULL) {
417 		return (USB_ERR_INVAL);
418 	}
419 	/*
420 	 * Free old pipes after we know that an interface descriptor exists,
421 	 * if any.
422 	 */
423 	usb2_free_pipe_data(udev, iface_index, 0 - 1);
424 
425 	/* Setup USB interface structure */
426 	iface->idesc = id;
427 	iface->alt_index = alt_index;
428 	iface->parent_iface_index = USB_IFACE_INDEX_ANY;
429 
430 	nendpt = id->bNumEndpoints;
431 	DPRINTFN(5, "found idesc nendpt=%d\n", nendpt);
432 
433 	desc = (void *)id;
434 
435 	while (nendpt--) {
436 		DPRINTFN(11, "endpt=%d\n", nendpt);
437 
438 		while ((desc = usb2_desc_foreach(udev->cdesc, desc))) {
439 			if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
440 			    (desc->bLength >= sizeof(*ed))) {
441 				goto found;
442 			}
443 			if (desc->bDescriptorType == UDESC_INTERFACE) {
444 				break;
445 			}
446 		}
447 		goto error;
448 
449 found:
450 		ed = (void *)desc;
451 
452 		/* find a free pipe */
453 		while (pipe != pipe_end) {
454 			if (pipe->edesc == NULL) {
455 				/* pipe is free */
456 				usb2_fill_pipe_data(udev, iface_index, ed, pipe);
457 				break;
458 			}
459 			pipe++;
460 		}
461 	}
462 	return (USB_ERR_NORMAL_COMPLETION);
463 
464 error:
465 	/* passed end, or bad desc */
466 	DPRINTFN(0, "%s: bad descriptor(s), addr=%d!\n",
467 	    __FUNCTION__, udev->address);
468 
469 	/* free old pipes if any */
470 	usb2_free_pipe_data(udev, iface_index, 0 - 1);
471 	return (USB_ERR_INVAL);
472 }
473 
474 /*------------------------------------------------------------------------*
475  *	usb2_free_iface_data
476  *
477  * This function will free all USB interfaces and USB pipes belonging
478  * to an USB device.
479  *------------------------------------------------------------------------*/
480 static void
481 usb2_free_iface_data(struct usb2_device *udev)
482 {
483 	struct usb2_interface *iface = udev->ifaces;
484 	struct usb2_interface *iface_end = udev->ifaces + USB_IFACE_MAX;
485 
486 	/* mtx_assert() */
487 
488 #if USB_HAVE_COMPAT_LINUX
489 	/* free Linux compat device, if any */
490 	if (udev->linux_dev) {
491 		usb_linux_free_device(udev->linux_dev);
492 		udev->linux_dev = NULL;
493 	}
494 #endif
495 	/* free all pipes, if any */
496 	usb2_free_pipe_data(udev, 0, 0);
497 
498 	/* free all interfaces, if any */
499 	while (iface != iface_end) {
500 		iface->idesc = NULL;
501 		iface->alt_index = 0;
502 		iface->parent_iface_index = USB_IFACE_INDEX_ANY;
503 		iface++;
504 	}
505 
506 	/* free "cdesc" after "ifaces", if any */
507 	if (udev->cdesc) {
508 		free(udev->cdesc, M_USB);
509 		udev->cdesc = NULL;
510 	}
511 	/* set unconfigured state */
512 	udev->curr_config_no = USB_UNCONFIG_NO;
513 	udev->curr_config_index = USB_UNCONFIG_INDEX;
514 }
515 
516 /*------------------------------------------------------------------------*
517  *	usb2_set_config_index
518  *
519  * This function selects configuration by index, independent of the
520  * actual configuration number. This function should not be used by
521  * USB drivers.
522  *
523  * Returns:
524  *    0: Success
525  * Else: Failure
526  *------------------------------------------------------------------------*/
527 usb2_error_t
528 usb2_set_config_index(struct usb2_device *udev, uint8_t index)
529 {
530 	struct usb2_status ds;
531 	struct usb2_hub_descriptor hd;
532 	struct usb2_config_descriptor *cdp;
533 	uint16_t power;
534 	uint16_t max_power;
535 	uint8_t nifc;
536 	uint8_t selfpowered;
537 	uint8_t do_unlock;
538 	usb2_error_t err;
539 
540 	DPRINTFN(6, "udev=%p index=%d\n", udev, index);
541 
542 	/* automatic locking */
543 	if (sx_xlocked(udev->default_sx + 1)) {
544 		do_unlock = 0;
545 	} else {
546 		do_unlock = 1;
547 		sx_xlock(udev->default_sx + 1);
548 	}
549 
550 	/* detach all interface drivers */
551 	usb2_detach_device(udev, USB_IFACE_INDEX_ANY, 1);
552 
553 #if USB_HAVE_UGEN
554 	/* free all FIFOs except control endpoint FIFOs */
555 	usb2_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, 0);
556 
557 	/* free all configuration data structures */
558 	usb2_cdev_free(udev);
559 #endif
560 	usb2_free_iface_data(udev);
561 
562 	if (index == USB_UNCONFIG_INDEX) {
563 		/*
564 		 * Leave unallocated when unconfiguring the
565 		 * device. "usb2_free_iface_data()" will also reset
566 		 * the current config number and index.
567 		 */
568 		err = usb2_req_set_config(udev, NULL, USB_UNCONFIG_NO);
569 		goto done;
570 	}
571 	/* get the full config descriptor */
572 	err = usb2_req_get_config_desc_full(udev,
573 	    NULL, &cdp, M_USB, index);
574 	if (err) {
575 		goto done;
576 	}
577 	/* set the new config descriptor */
578 
579 	udev->cdesc = cdp;
580 
581 	if (cdp->bNumInterface > USB_IFACE_MAX) {
582 		DPRINTFN(0, "too many interfaces: %d\n", cdp->bNumInterface);
583 		cdp->bNumInterface = USB_IFACE_MAX;
584 	}
585 	/* Figure out if the device is self or bus powered. */
586 	selfpowered = 0;
587 	if ((!udev->flags.uq_bus_powered) &&
588 	    (cdp->bmAttributes & UC_SELF_POWERED) &&
589 	    (udev->flags.usb2_mode == USB_MODE_HOST)) {
590 		/* May be self powered. */
591 		if (cdp->bmAttributes & UC_BUS_POWERED) {
592 			/* Must ask device. */
593 			if (udev->flags.uq_power_claim) {
594 				/*
595 				 * HUB claims to be self powered, but isn't.
596 				 * It seems that the power status can be
597 				 * determined by the HUB characteristics.
598 				 */
599 				err = usb2_req_get_hub_descriptor
600 				    (udev, NULL, &hd, 1);
601 				if (err) {
602 					DPRINTFN(0, "could not read "
603 					    "HUB descriptor: %s\n",
604 					    usb2_errstr(err));
605 
606 				} else if (UGETW(hd.wHubCharacteristics) &
607 				    UHD_PWR_INDIVIDUAL) {
608 					selfpowered = 1;
609 				}
610 				DPRINTF("characteristics=0x%04x\n",
611 				    UGETW(hd.wHubCharacteristics));
612 			} else {
613 				err = usb2_req_get_device_status
614 				    (udev, NULL, &ds);
615 				if (err) {
616 					DPRINTFN(0, "could not read "
617 					    "device status: %s\n",
618 					    usb2_errstr(err));
619 				} else if (UGETW(ds.wStatus) & UDS_SELF_POWERED) {
620 					selfpowered = 1;
621 				}
622 				DPRINTF("status=0x%04x \n",
623 				    UGETW(ds.wStatus));
624 			}
625 		} else
626 			selfpowered = 1;
627 	}
628 	DPRINTF("udev=%p cdesc=%p (addr %d) cno=%d attr=0x%02x, "
629 	    "selfpowered=%d, power=%d\n",
630 	    udev, cdp,
631 	    udev->address, cdp->bConfigurationValue, cdp->bmAttributes,
632 	    selfpowered, cdp->bMaxPower * 2);
633 
634 	/* Check if we have enough power. */
635 	power = cdp->bMaxPower * 2;
636 
637 	if (udev->parent_hub) {
638 		max_power = udev->parent_hub->hub->portpower;
639 	} else {
640 		max_power = USB_MAX_POWER;
641 	}
642 
643 	if (power > max_power) {
644 		DPRINTFN(0, "power exceeded %d > %d\n", power, max_power);
645 		err = USB_ERR_NO_POWER;
646 		goto done;
647 	}
648 	/* Only update "self_powered" in USB Host Mode */
649 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
650 		udev->flags.self_powered = selfpowered;
651 	}
652 	udev->power = power;
653 	udev->curr_config_no = cdp->bConfigurationValue;
654 	udev->curr_config_index = index;
655 
656 	/* Set the actual configuration value. */
657 	err = usb2_req_set_config(udev, NULL, cdp->bConfigurationValue);
658 	if (err) {
659 		goto done;
660 	}
661 	/* Allocate and fill interface data. */
662 	nifc = cdp->bNumInterface;
663 	while (nifc--) {
664 		err = usb2_fill_iface_data(udev, nifc, 0);
665 		if (err) {
666 			goto done;
667 		}
668 	}
669 #if USB_HAVE_UGEN
670 	/* create device nodes for each endpoint */
671 	usb2_cdev_create(udev);
672 #endif
673 
674 done:
675 	DPRINTF("error=%s\n", usb2_errstr(err));
676 	if (err) {
677 #if USB_HAVE_UGEN
678 		usb2_cdev_free(udev);
679 #endif
680 		usb2_free_iface_data(udev);
681 	}
682 	if (do_unlock) {
683 		sx_unlock(udev->default_sx + 1);
684 	}
685 	return (err);
686 }
687 
688 /*------------------------------------------------------------------------*
689  *	usb2_set_alt_interface_index
690  *
691  * This function will select an alternate interface index for the
692  * given interface index. The interface should not be in use when this
693  * function is called. That means there should not be any open USB
694  * transfers. Else an error is returned. If the alternate setting is
695  * already set this function will simply return success. This function
696  * is called in Host mode and Device mode!
697  *
698  * Returns:
699  *    0: Success
700  * Else: Failure
701  *------------------------------------------------------------------------*/
702 usb2_error_t
703 usb2_set_alt_interface_index(struct usb2_device *udev,
704     uint8_t iface_index, uint8_t alt_index)
705 {
706 	struct usb2_interface *iface = usb2_get_iface(udev, iface_index);
707 	usb2_error_t err;
708 	uint8_t do_unlock;
709 
710 	/* automatic locking */
711 	if (sx_xlocked(udev->default_sx + 1)) {
712 		do_unlock = 0;
713 	} else {
714 		do_unlock = 1;
715 		sx_xlock(udev->default_sx + 1);
716 	}
717 	if (iface == NULL) {
718 		err = USB_ERR_INVAL;
719 		goto done;
720 	}
721 	if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
722 		usb2_detach_device(udev, iface_index, 1);
723 	} else {
724 		if (iface->alt_index == alt_index) {
725 			/*
726 			 * Optimise away duplicate setting of
727 			 * alternate setting in USB Host Mode!
728 			 */
729 			err = 0;
730 			goto done;
731 		}
732 	}
733 #if USB_HAVE_UGEN
734 	/*
735 	 * Free all generic FIFOs for this interface, except control
736 	 * endpoint FIFOs:
737 	 */
738 	usb2_fifo_free_wrap(udev, iface_index, 0);
739 #endif
740 	err = usb2_fill_iface_data(udev, iface_index, alt_index);
741 	if (err) {
742 		goto done;
743 	}
744 	err = usb2_req_set_alt_interface_no(udev, NULL, iface_index,
745 	    iface->idesc->bAlternateSetting);
746 
747 done:
748 	if (do_unlock) {
749 		sx_unlock(udev->default_sx + 1);
750 	}
751 	return (err);
752 }
753 
754 /*------------------------------------------------------------------------*
755  *	usb2_set_endpoint_stall
756  *
757  * This function is used to make a BULK or INTERRUPT endpoint
758  * send STALL tokens.
759  *
760  * Returns:
761  *    0: Success
762  * Else: Failure
763  *------------------------------------------------------------------------*/
764 usb2_error_t
765 usb2_set_endpoint_stall(struct usb2_device *udev, struct usb2_pipe *pipe,
766     uint8_t do_stall)
767 {
768 	struct usb2_xfer *xfer;
769 	uint8_t et;
770 	uint8_t was_stalled;
771 
772 	if (pipe == NULL) {
773 		/* nothing to do */
774 		DPRINTF("Cannot find endpoint\n");
775 		/*
776 		 * Pretend that the clear or set stall request is
777 		 * successful else some USB host stacks can do
778 		 * strange things, especially when a control endpoint
779 		 * stalls.
780 		 */
781 		return (0);
782 	}
783 	et = (pipe->edesc->bmAttributes & UE_XFERTYPE);
784 
785 	if ((et != UE_BULK) &&
786 	    (et != UE_INTERRUPT)) {
787 		/*
788 	         * Should not stall control
789 	         * nor isochronous endpoints.
790 	         */
791 		DPRINTF("Invalid endpoint\n");
792 		return (0);
793 	}
794 	USB_BUS_LOCK(udev->bus);
795 
796 	/* store current stall state */
797 	was_stalled = pipe->is_stalled;
798 
799 	/* check for no change */
800 	if (was_stalled && do_stall) {
801 		/* if the pipe is already stalled do nothing */
802 		USB_BUS_UNLOCK(udev->bus);
803 		DPRINTF("No change\n");
804 		return (0);
805 	}
806 	/* set stalled state */
807 	pipe->is_stalled = 1;
808 
809 	if (do_stall || (!was_stalled)) {
810 		if (!was_stalled) {
811 			/* lookup the current USB transfer, if any */
812 			xfer = pipe->pipe_q.curr;
813 		} else {
814 			xfer = NULL;
815 		}
816 
817 		/*
818 		 * If "xfer" is non-NULL the "set_stall" method will
819 		 * complete the USB transfer like in case of a timeout
820 		 * setting the error code "USB_ERR_STALLED".
821 		 */
822 		(udev->bus->methods->set_stall) (udev, xfer, pipe);
823 	}
824 	if (!do_stall) {
825 		pipe->toggle_next = 0;	/* reset data toggle */
826 		pipe->is_stalled = 0;	/* clear stalled state */
827 
828 		(udev->bus->methods->clear_stall) (udev, pipe);
829 
830 		/* start up the current or next transfer, if any */
831 		usb2_command_wrapper(&pipe->pipe_q, pipe->pipe_q.curr);
832 	}
833 	USB_BUS_UNLOCK(udev->bus);
834 	return (0);
835 }
836 
837 /*------------------------------------------------------------------------*
838  *	usb2_reset_iface_endpoints - used in USB device side mode
839  *------------------------------------------------------------------------*/
840 usb2_error_t
841 usb2_reset_iface_endpoints(struct usb2_device *udev, uint8_t iface_index)
842 {
843 	struct usb2_pipe *pipe;
844 	struct usb2_pipe *pipe_end;
845 	usb2_error_t err;
846 
847 	pipe = udev->pipes;
848 	pipe_end = udev->pipes + USB_EP_MAX;
849 
850 	for (; pipe != pipe_end; pipe++) {
851 
852 		if ((pipe->edesc == NULL) ||
853 		    (pipe->iface_index != iface_index)) {
854 			continue;
855 		}
856 		/* simulate a clear stall from the peer */
857 		err = usb2_set_endpoint_stall(udev, pipe, 0);
858 		if (err) {
859 			/* just ignore */
860 		}
861 	}
862 	return (0);
863 }
864 
865 /*------------------------------------------------------------------------*
866  *	usb2_detach_device_sub
867  *
868  * This function will try to detach an USB device. If it fails a panic
869  * will result.
870  *------------------------------------------------------------------------*/
871 static void
872 usb2_detach_device_sub(struct usb2_device *udev, device_t *ppdev,
873     uint8_t free_subdev)
874 {
875 	device_t dev;
876 	int err;
877 
878 	if (!free_subdev) {
879 
880 		*ppdev = NULL;
881 
882 	} else if (*ppdev) {
883 
884 		/*
885 		 * NOTE: It is important to clear "*ppdev" before deleting
886 		 * the child due to some device methods being called late
887 		 * during the delete process !
888 		 */
889 		dev = *ppdev;
890 		*ppdev = NULL;
891 
892 		device_printf(dev, "at %s, port %d, addr %d "
893 		    "(disconnected)\n",
894 		    device_get_nameunit(udev->parent_dev),
895 		    udev->port_no, udev->address);
896 
897 		if (device_is_attached(dev)) {
898 			if (udev->flags.suspended) {
899 				err = DEVICE_RESUME(dev);
900 				if (err) {
901 					device_printf(dev, "Resume failed!\n");
902 				}
903 			}
904 			if (device_detach(dev)) {
905 				goto error;
906 			}
907 		}
908 		if (device_delete_child(udev->parent_dev, dev)) {
909 			goto error;
910 		}
911 	}
912 	return;
913 
914 error:
915 	/* Detach is not allowed to fail in the USB world */
916 	panic("An USB driver would not detach!\n");
917 }
918 
919 /*------------------------------------------------------------------------*
920  *	usb2_detach_device
921  *
922  * The following function will detach the matching interfaces.
923  * This function is NULL safe.
924  *------------------------------------------------------------------------*/
925 void
926 usb2_detach_device(struct usb2_device *udev, uint8_t iface_index,
927     uint8_t free_subdev)
928 {
929 	struct usb2_interface *iface;
930 	uint8_t i;
931 	uint8_t do_unlock;
932 
933 	if (udev == NULL) {
934 		/* nothing to do */
935 		return;
936 	}
937 	DPRINTFN(4, "udev=%p\n", udev);
938 
939 	/* automatic locking */
940 	if (sx_xlocked(udev->default_sx + 1)) {
941 		do_unlock = 0;
942 	} else {
943 		do_unlock = 1;
944 		sx_xlock(udev->default_sx + 1);
945 	}
946 
947 	/*
948 	 * First detach the child to give the child's detach routine a
949 	 * chance to detach the sub-devices in the correct order.
950 	 * Then delete the child using "device_delete_child()" which
951 	 * will detach all sub-devices from the bottom and upwards!
952 	 */
953 	if (iface_index != USB_IFACE_INDEX_ANY) {
954 		i = iface_index;
955 		iface_index = i + 1;
956 	} else {
957 		i = 0;
958 		iface_index = USB_IFACE_MAX;
959 	}
960 
961 	/* do the detach */
962 
963 	for (; i != iface_index; i++) {
964 
965 		iface = usb2_get_iface(udev, i);
966 		if (iface == NULL) {
967 			/* looks like the end of the USB interfaces */
968 			break;
969 		}
970 		usb2_detach_device_sub(udev, &iface->subdev, free_subdev);
971 	}
972 
973 	if (do_unlock) {
974 		sx_unlock(udev->default_sx + 1);
975 	}
976 }
977 
978 /*------------------------------------------------------------------------*
979  *	usb2_probe_and_attach_sub
980  *
981  * Returns:
982  *    0: Success
983  * Else: Failure
984  *------------------------------------------------------------------------*/
985 static uint8_t
986 usb2_probe_and_attach_sub(struct usb2_device *udev,
987     struct usb2_attach_arg *uaa)
988 {
989 	struct usb2_interface *iface;
990 	device_t dev;
991 	int err;
992 
993 	iface = uaa->iface;
994 	if (iface->parent_iface_index != USB_IFACE_INDEX_ANY) {
995 		/* leave interface alone */
996 		return (0);
997 	}
998 	dev = iface->subdev;
999 	if (dev) {
1000 
1001 		/* clean up after module unload */
1002 
1003 		if (device_is_attached(dev)) {
1004 			/* already a device there */
1005 			return (0);
1006 		}
1007 		/* clear "iface->subdev" as early as possible */
1008 
1009 		iface->subdev = NULL;
1010 
1011 		if (device_delete_child(udev->parent_dev, dev)) {
1012 
1013 			/*
1014 			 * Panic here, else one can get a double call
1015 			 * to device_detach().  USB devices should
1016 			 * never fail on detach!
1017 			 */
1018 			panic("device_delete_child() failed!\n");
1019 		}
1020 	}
1021 	if (uaa->temp_dev == NULL) {
1022 
1023 		/* create a new child */
1024 		uaa->temp_dev = device_add_child(udev->parent_dev, NULL, -1);
1025 		if (uaa->temp_dev == NULL) {
1026 			device_printf(udev->parent_dev,
1027 			    "Device creation failed!\n");
1028 			return (1);	/* failure */
1029 		}
1030 		device_set_ivars(uaa->temp_dev, uaa);
1031 		device_quiet(uaa->temp_dev);
1032 	}
1033 	/*
1034 	 * Set "subdev" before probe and attach so that "devd" gets
1035 	 * the information it needs.
1036 	 */
1037 	iface->subdev = uaa->temp_dev;
1038 
1039 	if (device_probe_and_attach(iface->subdev) == 0) {
1040 		/*
1041 		 * The USB attach arguments are only available during probe
1042 		 * and attach !
1043 		 */
1044 		uaa->temp_dev = NULL;
1045 		device_set_ivars(iface->subdev, NULL);
1046 
1047 		if (udev->flags.suspended) {
1048 			err = DEVICE_SUSPEND(iface->subdev);
1049 			device_printf(iface->subdev, "Suspend failed\n");
1050 		}
1051 		return (0);		/* success */
1052 	} else {
1053 		/* No USB driver found */
1054 		iface->subdev = NULL;
1055 	}
1056 	return (1);			/* failure */
1057 }
1058 
1059 /*------------------------------------------------------------------------*
1060  *	usb2_set_parent_iface
1061  *
1062  * Using this function will lock the alternate interface setting on an
1063  * interface. It is typically used for multi interface drivers. In USB
1064  * device side mode it is assumed that the alternate interfaces all
1065  * have the same endpoint descriptors. The default parent index value
1066  * is "USB_IFACE_INDEX_ANY". Then the alternate setting value is not
1067  * locked.
1068  *------------------------------------------------------------------------*/
1069 void
1070 usb2_set_parent_iface(struct usb2_device *udev, uint8_t iface_index,
1071     uint8_t parent_index)
1072 {
1073 	struct usb2_interface *iface;
1074 
1075 	iface = usb2_get_iface(udev, iface_index);
1076 	if (iface) {
1077 		iface->parent_iface_index = parent_index;
1078 	}
1079 }
1080 
1081 static void
1082 usb2_init_attach_arg(struct usb2_device *udev,
1083     struct usb2_attach_arg *uaa)
1084 {
1085 	bzero(uaa, sizeof(*uaa));
1086 
1087 	uaa->device = udev;
1088 	uaa->usb2_mode = udev->flags.usb2_mode;
1089 	uaa->port = udev->port_no;
1090 
1091 	uaa->info.idVendor = UGETW(udev->ddesc.idVendor);
1092 	uaa->info.idProduct = UGETW(udev->ddesc.idProduct);
1093 	uaa->info.bcdDevice = UGETW(udev->ddesc.bcdDevice);
1094 	uaa->info.bDeviceClass = udev->ddesc.bDeviceClass;
1095 	uaa->info.bDeviceSubClass = udev->ddesc.bDeviceSubClass;
1096 	uaa->info.bDeviceProtocol = udev->ddesc.bDeviceProtocol;
1097 	uaa->info.bConfigIndex = udev->curr_config_index;
1098 	uaa->info.bConfigNum = udev->curr_config_no;
1099 }
1100 
1101 /*------------------------------------------------------------------------*
1102  *	usb2_probe_and_attach
1103  *
1104  * This function is called from "uhub_explore_sub()",
1105  * "usb2_handle_set_config()" and "usb2_handle_request()".
1106  *
1107  * Returns:
1108  *    0: Success
1109  * Else: A control transfer failed
1110  *------------------------------------------------------------------------*/
1111 usb2_error_t
1112 usb2_probe_and_attach(struct usb2_device *udev, uint8_t iface_index)
1113 {
1114 	struct usb2_attach_arg uaa;
1115 	struct usb2_interface *iface;
1116 	uint8_t i;
1117 	uint8_t j;
1118 	uint8_t do_unlock;
1119 
1120 	if (udev == NULL) {
1121 		DPRINTF("udev == NULL\n");
1122 		return (USB_ERR_INVAL);
1123 	}
1124 	/* automatic locking */
1125 	if (sx_xlocked(udev->default_sx + 1)) {
1126 		do_unlock = 0;
1127 	} else {
1128 		do_unlock = 1;
1129 		sx_xlock(udev->default_sx + 1);
1130 	}
1131 
1132 	if (udev->curr_config_index == USB_UNCONFIG_INDEX) {
1133 		/* do nothing - no configuration has been set */
1134 		goto done;
1135 	}
1136 	/* setup USB attach arguments */
1137 
1138 	usb2_init_attach_arg(udev, &uaa);
1139 
1140 	/* Check if only one interface should be probed: */
1141 	if (iface_index != USB_IFACE_INDEX_ANY) {
1142 		i = iface_index;
1143 		j = i + 1;
1144 	} else {
1145 		i = 0;
1146 		j = USB_IFACE_MAX;
1147 	}
1148 
1149 	/* Do the probe and attach */
1150 	for (; i != j; i++) {
1151 
1152 		iface = usb2_get_iface(udev, i);
1153 		if (iface == NULL) {
1154 			/*
1155 			 * Looks like the end of the USB
1156 			 * interfaces !
1157 			 */
1158 			DPRINTFN(2, "end of interfaces "
1159 			    "at %u\n", i);
1160 			break;
1161 		}
1162 		if (iface->idesc == NULL) {
1163 			/* no interface descriptor */
1164 			continue;
1165 		}
1166 		uaa.iface = iface;
1167 
1168 		uaa.info.bInterfaceClass =
1169 		    iface->idesc->bInterfaceClass;
1170 		uaa.info.bInterfaceSubClass =
1171 		    iface->idesc->bInterfaceSubClass;
1172 		uaa.info.bInterfaceProtocol =
1173 		    iface->idesc->bInterfaceProtocol;
1174 		uaa.info.bIfaceIndex = i;
1175 		uaa.info.bIfaceNum =
1176 		    iface->idesc->bInterfaceNumber;
1177 		uaa.use_generic = 0;
1178 
1179 		DPRINTFN(2, "iclass=%u/%u/%u iindex=%u/%u\n",
1180 		    uaa.info.bInterfaceClass,
1181 		    uaa.info.bInterfaceSubClass,
1182 		    uaa.info.bInterfaceProtocol,
1183 		    uaa.info.bIfaceIndex,
1184 		    uaa.info.bIfaceNum);
1185 
1186 		/* try specific interface drivers first */
1187 
1188 		if (usb2_probe_and_attach_sub(udev, &uaa)) {
1189 			/* ignore */
1190 		}
1191 		/* try generic interface drivers last */
1192 
1193 		uaa.use_generic = 1;
1194 
1195 		if (usb2_probe_and_attach_sub(udev, &uaa)) {
1196 			/* ignore */
1197 		}
1198 	}
1199 
1200 	if (uaa.temp_dev) {
1201 		/* remove the last created child; it is unused */
1202 
1203 		if (device_delete_child(udev->parent_dev, uaa.temp_dev)) {
1204 			DPRINTFN(0, "device delete child failed!\n");
1205 		}
1206 	}
1207 done:
1208 	if (do_unlock) {
1209 		sx_unlock(udev->default_sx + 1);
1210 	}
1211 	return (0);
1212 }
1213 
1214 /*------------------------------------------------------------------------*
1215  *	usb2_suspend_resume_sub
1216  *
1217  * This function is called when the suspend or resume methods should
1218  * be executed on an USB device.
1219  *------------------------------------------------------------------------*/
1220 static void
1221 usb2_suspend_resume_sub(struct usb2_device *udev, device_t dev, uint8_t do_suspend)
1222 {
1223 	int err;
1224 
1225 	if (dev == NULL) {
1226 		return;
1227 	}
1228 	if (!device_is_attached(dev)) {
1229 		return;
1230 	}
1231 	if (do_suspend) {
1232 		err = DEVICE_SUSPEND(dev);
1233 	} else {
1234 		err = DEVICE_RESUME(dev);
1235 	}
1236 	if (err) {
1237 		device_printf(dev, "%s failed!\n",
1238 		    do_suspend ? "Suspend" : "Resume");
1239 	}
1240 }
1241 
1242 /*------------------------------------------------------------------------*
1243  *	usb2_suspend_resume
1244  *
1245  * The following function will suspend or resume the USB device.
1246  *
1247  * Returns:
1248  *    0: Success
1249  * Else: Failure
1250  *------------------------------------------------------------------------*/
1251 usb2_error_t
1252 usb2_suspend_resume(struct usb2_device *udev, uint8_t do_suspend)
1253 {
1254 	struct usb2_interface *iface;
1255 	uint8_t i;
1256 
1257 	if (udev == NULL) {
1258 		/* nothing to do */
1259 		return (0);
1260 	}
1261 	DPRINTFN(4, "udev=%p do_suspend=%d\n", udev, do_suspend);
1262 
1263 	sx_assert(udev->default_sx + 1, SA_LOCKED);
1264 
1265 	USB_BUS_LOCK(udev->bus);
1266 	/* filter the suspend events */
1267 	if (udev->flags.suspended == do_suspend) {
1268 		USB_BUS_UNLOCK(udev->bus);
1269 		/* nothing to do */
1270 		return (0);
1271 	}
1272 	udev->flags.suspended = do_suspend;
1273 	USB_BUS_UNLOCK(udev->bus);
1274 
1275 	/* do the suspend or resume */
1276 
1277 	for (i = 0; i != USB_IFACE_MAX; i++) {
1278 
1279 		iface = usb2_get_iface(udev, i);
1280 		if (iface == NULL) {
1281 			/* looks like the end of the USB interfaces */
1282 			break;
1283 		}
1284 		usb2_suspend_resume_sub(udev, iface->subdev, do_suspend);
1285 	}
1286 	return (0);
1287 }
1288 
1289 /*------------------------------------------------------------------------*
1290  *      usb2_clear_stall_proc
1291  *
1292  * This function performs generic USB clear stall operations.
1293  *------------------------------------------------------------------------*/
1294 static void
1295 usb2_clear_stall_proc(struct usb2_proc_msg *_pm)
1296 {
1297 	struct usb2_clear_stall_msg *pm = (void *)_pm;
1298 	struct usb2_device *udev = pm->udev;
1299 
1300 	/* Change lock */
1301 	USB_BUS_UNLOCK(udev->bus);
1302 	mtx_lock(udev->default_mtx);
1303 
1304 	/* Start clear stall callback */
1305 	usb2_transfer_start(udev->default_xfer[1]);
1306 
1307 	/* Change lock */
1308 	mtx_unlock(udev->default_mtx);
1309 	USB_BUS_LOCK(udev->bus);
1310 }
1311 
1312 /*------------------------------------------------------------------------*
1313  *	usb2_alloc_device
1314  *
1315  * This function allocates a new USB device. This function is called
1316  * when a new device has been put in the powered state, but not yet in
1317  * the addressed state. Get initial descriptor, set the address, get
1318  * full descriptor and get strings.
1319  *
1320  * Return values:
1321  *    0: Failure
1322  * Else: Success
1323  *------------------------------------------------------------------------*/
1324 struct usb2_device *
1325 usb2_alloc_device(device_t parent_dev, struct usb2_bus *bus,
1326     struct usb2_device *parent_hub, uint8_t depth,
1327     uint8_t port_index, uint8_t port_no, uint8_t speed, uint8_t usb2_mode)
1328 {
1329 	struct usb2_attach_arg uaa;
1330 	struct usb2_device *udev;
1331 	struct usb2_device *adev;
1332 	struct usb2_device *hub;
1333 	uint8_t *scratch_ptr;
1334 	uint32_t scratch_size;
1335 	usb2_error_t err;
1336 	uint8_t device_index;
1337 
1338 	DPRINTF("parent_dev=%p, bus=%p, parent_hub=%p, depth=%u, "
1339 	    "port_index=%u, port_no=%u, speed=%u, usb2_mode=%u\n",
1340 	    parent_dev, bus, parent_hub, depth, port_index, port_no,
1341 	    speed, usb2_mode);
1342 
1343 	/*
1344 	 * Find an unused device index. In USB Host mode this is the
1345 	 * same as the device address.
1346 	 *
1347 	 * Device index zero is not used and device index 1 should
1348 	 * always be the root hub.
1349 	 */
1350 	for (device_index = USB_ROOT_HUB_ADDR;
1351 	    (device_index != bus->devices_max) &&
1352 	    (bus->devices[device_index] != NULL);
1353 	    device_index++) /* nop */;
1354 
1355 	if (device_index == bus->devices_max) {
1356 		device_printf(bus->bdev,
1357 		    "No free USB device index for new device!\n");
1358 		return (NULL);
1359 	}
1360 
1361 	if (depth > 0x10) {
1362 		device_printf(bus->bdev,
1363 		    "Invalid device depth!\n");
1364 		return (NULL);
1365 	}
1366 	udev = malloc(sizeof(*udev), M_USB, M_WAITOK | M_ZERO);
1367 	if (udev == NULL) {
1368 		return (NULL);
1369 	}
1370 	/* initialise our SX-lock */
1371 	sx_init(udev->default_sx, "0123456789ABCDEF - USB device SX lock" + depth);
1372 
1373 	/* initialise our SX-lock */
1374 	sx_init(udev->default_sx + 1, "0123456789ABCDEF - USB config SX lock" + depth);
1375 
1376 	usb2_cv_init(udev->default_cv, "WCTRL");
1377 	usb2_cv_init(udev->default_cv + 1, "UGONE");
1378 
1379 	/* initialise our mutex */
1380 	mtx_init(udev->default_mtx, "USB device mutex", NULL, MTX_DEF);
1381 
1382 	/* initialise generic clear stall */
1383 	udev->cs_msg[0].hdr.pm_callback = &usb2_clear_stall_proc;
1384 	udev->cs_msg[0].udev = udev;
1385 	udev->cs_msg[1].hdr.pm_callback = &usb2_clear_stall_proc;
1386 	udev->cs_msg[1].udev = udev;
1387 
1388 	/* initialise some USB device fields */
1389 	udev->parent_hub = parent_hub;
1390 	udev->parent_dev = parent_dev;
1391 	udev->port_index = port_index;
1392 	udev->port_no = port_no;
1393 	udev->depth = depth;
1394 	udev->bus = bus;
1395 	udev->address = USB_START_ADDR;	/* default value */
1396 	udev->plugtime = (usb2_ticks_t)ticks;
1397 	/*
1398 	 * We need to force the power mode to "on" because there are plenty
1399 	 * of USB devices out there that do not work very well with
1400 	 * automatic suspend and resume!
1401 	 */
1402 	udev->power_mode = USB_POWER_MODE_ON;
1403 	udev->pwr_save.last_xfer_time = ticks;
1404 
1405 	/* we are not ready yet */
1406 	udev->refcount = 1;
1407 
1408 	/* set up default endpoint descriptor */
1409 	udev->default_ep_desc.bLength = sizeof(udev->default_ep_desc);
1410 	udev->default_ep_desc.bDescriptorType = UDESC_ENDPOINT;
1411 	udev->default_ep_desc.bEndpointAddress = USB_CONTROL_ENDPOINT;
1412 	udev->default_ep_desc.bmAttributes = UE_CONTROL;
1413 	udev->default_ep_desc.wMaxPacketSize[0] = USB_MAX_IPACKET;
1414 	udev->default_ep_desc.wMaxPacketSize[1] = 0;
1415 	udev->default_ep_desc.bInterval = 0;
1416 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1417 
1418 	udev->speed = speed;
1419 	udev->flags.usb2_mode = usb2_mode;
1420 
1421 	/* speed combination should be checked by the parent HUB */
1422 
1423 	hub = udev->parent_hub;
1424 
1425 	/* search for our High Speed USB HUB, if any */
1426 
1427 	adev = udev;
1428 	hub = udev->parent_hub;
1429 
1430 	while (hub) {
1431 		if (hub->speed == USB_SPEED_HIGH) {
1432 			udev->hs_hub_addr = hub->address;
1433 			udev->hs_port_no = adev->port_no;
1434 			break;
1435 		}
1436 		adev = hub;
1437 		hub = hub->parent_hub;
1438 	}
1439 
1440 	/* init the default pipe */
1441 	usb2_fill_pipe_data(udev, 0,
1442 	    &udev->default_ep_desc,
1443 	    &udev->default_pipe);
1444 
1445 	/* set device index */
1446 	udev->device_index = device_index;
1447 
1448 #if USB_HAVE_UGEN
1449 	/* Create ugen name */
1450 	snprintf(udev->ugen_name, sizeof(udev->ugen_name),
1451 	    USB_GENERIC_NAME "%u.%u", device_get_unit(bus->bdev),
1452 	    device_index);
1453 	LIST_INIT(&udev->pd_list);
1454 
1455 	/* Create the control endpoint device */
1456 	udev->default_dev = usb2_make_dev(udev, 0, FREAD|FWRITE);
1457 
1458 	/* Create a link from /dev/ugenX.X to the default endpoint */
1459 	make_dev_alias(udev->default_dev, udev->ugen_name);
1460 #endif
1461 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
1462 
1463 		err = usb2_req_set_address(udev, NULL, device_index);
1464 
1465 		/* This is the new USB device address from now on */
1466 
1467 		udev->address = device_index;
1468 
1469 		/*
1470 		 * We ignore any set-address errors, hence there are
1471 		 * buggy USB devices out there that actually receive
1472 		 * the SETUP PID, but manage to set the address before
1473 		 * the STATUS stage is ACK'ed. If the device responds
1474 		 * to the subsequent get-descriptor at the new
1475 		 * address, then we know that the set-address command
1476 		 * was successful.
1477 		 */
1478 		if (err) {
1479 			DPRINTFN(0, "set address %d failed "
1480 			    "(ignored)\n", udev->address);
1481 		}
1482 		/* allow device time to set new address */
1483 		usb2_pause_mtx(NULL,
1484 		    USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1485 	} else {
1486 		/* We are not self powered */
1487 		udev->flags.self_powered = 0;
1488 
1489 		/* Set unconfigured state */
1490 		udev->curr_config_no = USB_UNCONFIG_NO;
1491 		udev->curr_config_index = USB_UNCONFIG_INDEX;
1492 
1493 		/* Setup USB descriptors */
1494 		err = (usb2_temp_setup_by_index_p) (udev, usb2_template);
1495 		if (err) {
1496 			DPRINTFN(0, "setting up USB template failed maybe the USB "
1497 			    "template module has not been loaded\n");
1498 			goto done;
1499 		}
1500 	}
1501 
1502 	/*
1503 	 * Get the first 8 bytes of the device descriptor !
1504 	 *
1505 	 * NOTE: "usb2_do_request" will check the device descriptor
1506 	 * next time we do a request to see if the maximum packet size
1507 	 * changed! The 8 first bytes of the device descriptor
1508 	 * contains the maximum packet size to use on control endpoint
1509 	 * 0. If this value is different from "USB_MAX_IPACKET" a new
1510 	 * USB control request will be setup!
1511 	 */
1512 	err = usb2_req_get_desc(udev, NULL, NULL, &udev->ddesc,
1513 	    USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1514 	if (err) {
1515 		DPRINTFN(0, "getting device descriptor "
1516 		    "at addr %d failed!\n", udev->address);
1517 		/* XXX try to re-enumerate the device */
1518 		err = usb2_req_re_enumerate(udev, NULL);
1519 		if (err) {
1520 			goto done;
1521 		}
1522 	}
1523 	DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
1524 	    "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1525 	    udev->address, UGETW(udev->ddesc.bcdUSB),
1526 	    udev->ddesc.bDeviceClass,
1527 	    udev->ddesc.bDeviceSubClass,
1528 	    udev->ddesc.bDeviceProtocol,
1529 	    udev->ddesc.bMaxPacketSize,
1530 	    udev->ddesc.bLength,
1531 	    udev->speed);
1532 
1533 	/* get the full device descriptor */
1534 	err = usb2_req_get_device_desc(udev, NULL, &udev->ddesc);
1535 	if (err) {
1536 		DPRINTF("addr=%d, getting full desc failed\n",
1537 		    udev->address);
1538 		goto done;
1539 	}
1540 	/*
1541 	 * Setup temporary USB attach args so that we can figure out some
1542 	 * basic quirks for this device.
1543 	 */
1544 	usb2_init_attach_arg(udev, &uaa);
1545 
1546 	if (usb2_test_quirk(&uaa, UQ_BUS_POWERED)) {
1547 		udev->flags.uq_bus_powered = 1;
1548 	}
1549 	if (usb2_test_quirk(&uaa, UQ_POWER_CLAIM)) {
1550 		udev->flags.uq_power_claim = 1;
1551 	}
1552 	if (usb2_test_quirk(&uaa, UQ_NO_STRINGS)) {
1553 		udev->flags.no_strings = 1;
1554 	}
1555 	/*
1556 	 * Workaround for buggy USB devices.
1557 	 *
1558 	 * It appears that some string-less USB chips will crash and
1559 	 * disappear if any attempts are made to read any string
1560 	 * descriptors.
1561 	 *
1562 	 * Try to detect such chips by checking the strings in the USB
1563 	 * device descriptor. If no strings are present there we
1564 	 * simply disable all USB strings.
1565 	 */
1566 	scratch_ptr = udev->bus->scratch[0].data;
1567 	scratch_size = sizeof(udev->bus->scratch[0].data);
1568 
1569 	if (udev->ddesc.iManufacturer ||
1570 	    udev->ddesc.iProduct ||
1571 	    udev->ddesc.iSerialNumber) {
1572 		/* read out the language ID string */
1573 		err = usb2_req_get_string_desc(udev, NULL,
1574 		    (char *)scratch_ptr, 4, scratch_size,
1575 		    USB_LANGUAGE_TABLE);
1576 	} else {
1577 		err = USB_ERR_INVAL;
1578 	}
1579 
1580 	if (err || (scratch_ptr[0] < 4)) {
1581 		udev->flags.no_strings = 1;
1582 	} else {
1583 		/* pick the first language as the default */
1584 		udev->langid = UGETW(scratch_ptr + 2);
1585 	}
1586 
1587 	/* assume 100mA bus powered for now. Changed when configured. */
1588 	udev->power = USB_MIN_POWER;
1589 
1590 #if USB_HAVE_STRINGS
1591 	/* get serial number string */
1592 	err = usb2_req_get_string_any
1593 	    (udev, NULL, (char *)scratch_ptr,
1594 	    scratch_size, udev->ddesc.iSerialNumber);
1595 
1596 	strlcpy(udev->serial, (char *)scratch_ptr, sizeof(udev->serial));
1597 
1598 	/* get manufacturer string */
1599 	err = usb2_req_get_string_any
1600 	    (udev, NULL, (char *)scratch_ptr,
1601 	    scratch_size, udev->ddesc.iManufacturer);
1602 
1603 	strlcpy(udev->manufacturer, (char *)scratch_ptr, sizeof(udev->manufacturer));
1604 
1605 	/* get product string */
1606 	err = usb2_req_get_string_any
1607 	    (udev, NULL, (char *)scratch_ptr,
1608 	    scratch_size, udev->ddesc.iProduct);
1609 
1610 	strlcpy(udev->product, (char *)scratch_ptr, sizeof(udev->product));
1611 
1612 	/* finish up all the strings */
1613 	usb2_check_strings(udev);
1614 #endif
1615 
1616 	if (udev->flags.usb2_mode == USB_MODE_HOST) {
1617 		uint8_t config_index;
1618 		uint8_t config_quirk;
1619 		uint8_t set_config_failed = 0;
1620 
1621 		/*
1622 		 * Most USB devices should attach to config index 0 by
1623 		 * default
1624 		 */
1625 		if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_0)) {
1626 			config_index = 0;
1627 			config_quirk = 1;
1628 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_1)) {
1629 			config_index = 1;
1630 			config_quirk = 1;
1631 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_2)) {
1632 			config_index = 2;
1633 			config_quirk = 1;
1634 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_3)) {
1635 			config_index = 3;
1636 			config_quirk = 1;
1637 		} else if (usb2_test_quirk(&uaa, UQ_CFG_INDEX_4)) {
1638 			config_index = 4;
1639 			config_quirk = 1;
1640 		} else {
1641 			config_index = 0;
1642 			config_quirk = 0;
1643 		}
1644 
1645 repeat_set_config:
1646 
1647 		DPRINTF("setting config %u\n", config_index);
1648 
1649 		/* get the USB device configured */
1650 		sx_xlock(udev->default_sx + 1);
1651 		err = usb2_set_config_index(udev, config_index);
1652 		sx_unlock(udev->default_sx + 1);
1653 		if (err) {
1654 			if (udev->ddesc.bNumConfigurations != 0) {
1655 				if (!set_config_failed) {
1656 					set_config_failed = 1;
1657 					/* XXX try to re-enumerate the device */
1658 					err = usb2_req_re_enumerate(
1659 					    udev, NULL);
1660 					if (err == 0)
1661 					    goto repeat_set_config;
1662 				}
1663 				DPRINTFN(0, "Failure selecting "
1664 				    "configuration index %u: %s, port %u, "
1665 				    "addr %u (ignored)\n",
1666 				    config_index, usb2_errstr(err), udev->port_no,
1667 				    udev->address);
1668 			}
1669 			/*
1670 			 * Some USB devices do not have any
1671 			 * configurations. Ignore any set config
1672 			 * failures!
1673 			 */
1674 			err = 0;
1675 		} else if (config_quirk) {
1676 			/* user quirk selects configuration index */
1677 		} else if ((config_index + 1) < udev->ddesc.bNumConfigurations) {
1678 
1679 			if ((udev->cdesc->bNumInterface < 2) &&
1680 			    (usb2_get_no_endpoints(udev->cdesc) == 0)) {
1681 				DPRINTFN(0, "Found no endpoints "
1682 				    "(trying next config)!\n");
1683 				config_index++;
1684 				goto repeat_set_config;
1685 			}
1686 			if (config_index == 0) {
1687 				/*
1688 				 * Try to figure out if we have an
1689 				 * auto-install disk there:
1690 				 */
1691 				if (usb2_test_autoinstall(udev, 0, 0) == 0) {
1692 					DPRINTFN(0, "Found possible auto-install "
1693 					    "disk (trying next config)\n");
1694 					config_index++;
1695 					goto repeat_set_config;
1696 				}
1697 			}
1698 		} else if (usb2_test_huawei_autoinst_p(udev, &uaa) == 0) {
1699 			DPRINTFN(0, "Found Huawei auto-install disk!\n");
1700 			err = USB_ERR_STALLED;	/* fake an error */
1701 		}
1702 	} else {
1703 		err = 0;		/* set success */
1704 	}
1705 
1706 	DPRINTF("new dev (addr %d), udev=%p, parent_hub=%p\n",
1707 	    udev->address, udev, udev->parent_hub);
1708 
1709 	/* register our device - we are ready */
1710 	usb2_bus_port_set_device(bus, parent_hub ?
1711 	    parent_hub->hub->ports + port_index : NULL, udev, device_index);
1712 
1713 #if USB_HAVE_UGEN
1714 	/* Symlink the ugen device name */
1715 	udev->ugen_symlink = usb2_alloc_symlink(udev->ugen_name);
1716 
1717 	/* Announce device */
1718 #if USB_HAVE_STRINGS
1719 	printf("%s: <%s> at %s\n", udev->ugen_name, udev->manufacturer,
1720 	    device_get_nameunit(udev->bus->bdev));
1721 #endif
1722 	usb2_notify_addq("+", udev);
1723 #endif
1724 done:
1725 	if (err) {
1726 		/* free device  */
1727 		usb2_free_device(udev);
1728 		udev = NULL;
1729 	}
1730 	return (udev);
1731 }
1732 
1733 #if USB_HAVE_UGEN
1734 static struct cdev *
1735 usb2_make_dev(struct usb2_device *udev, int ep, int mode)
1736 {
1737 	struct usb2_fs_privdata* pd;
1738 	char devname[20];
1739 
1740 	/* Store information to locate ourselves again later */
1741 	pd = malloc(sizeof(struct usb2_fs_privdata), M_USBDEV,
1742 	    M_WAITOK | M_ZERO);
1743 	pd->bus_index = device_get_unit(udev->bus->bdev);
1744 	pd->dev_index = udev->device_index;
1745 	pd->ep_addr = ep;
1746 	pd->mode = mode;
1747 
1748 	/* Now, create the device itself */
1749 	snprintf(devname, sizeof(devname), "%u.%u.%u",
1750 	    pd->bus_index, pd->dev_index, pd->ep_addr);
1751 	pd->cdev = make_dev(&usb2_devsw, 0, UID_ROOT,
1752 	    GID_OPERATOR, 0600, USB_DEVICE_DIR "/%s", devname);
1753 	pd->cdev->si_drv1 = pd;
1754 
1755 	return (pd->cdev);
1756 }
1757 
1758 static void
1759 usb2_cdev_create(struct usb2_device *udev)
1760 {
1761 	struct usb2_config_descriptor *cd;
1762 	struct usb2_endpoint_descriptor *ed;
1763 	struct usb2_descriptor *desc;
1764 	struct usb2_fs_privdata* pd;
1765 	struct cdev *dev;
1766 	int inmode, outmode, inmask, outmask, mode;
1767 	uint8_t ep;
1768 
1769 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("stale cdev entries"));
1770 
1771 	DPRINTFN(2, "Creating device nodes\n");
1772 
1773 	if (usb2_get_mode(udev) == USB_MODE_DEVICE) {
1774 		inmode = FWRITE;
1775 		outmode = FREAD;
1776 	} else {		 /* USB_MODE_HOST */
1777 		inmode = FREAD;
1778 		outmode = FWRITE;
1779 	}
1780 
1781 	inmask = 0;
1782 	outmask = 0;
1783 	desc = NULL;
1784 
1785 	/*
1786 	 * Collect all used endpoint numbers instead of just
1787 	 * generating 16 static endpoints.
1788 	 */
1789 	cd = usb2_get_config_descriptor(udev);
1790 	while ((desc = usb2_desc_foreach(cd, desc))) {
1791 		/* filter out all endpoint descriptors */
1792 		if ((desc->bDescriptorType == UDESC_ENDPOINT) &&
1793 		    (desc->bLength >= sizeof(*ed))) {
1794 			ed = (struct usb2_endpoint_descriptor *)desc;
1795 
1796 			/* update masks */
1797 			ep = ed->bEndpointAddress;
1798 			if (UE_GET_DIR(ep)  == UE_DIR_OUT)
1799 				outmask |= 1 << UE_GET_ADDR(ep);
1800 			else
1801 				inmask |= 1 << UE_GET_ADDR(ep);
1802 		}
1803 	}
1804 
1805 	/* Create all available endpoints except EP0 */
1806 	for (ep = 1; ep < 16; ep++) {
1807 		mode = inmask & (1 << ep) ? inmode : 0;
1808 		mode |= outmask & (1 << ep) ? outmode : 0;
1809 		if (mode == 0)
1810 			continue;	/* no IN or OUT endpoint */
1811 
1812 		dev = usb2_make_dev(udev, ep, mode);
1813 		pd = dev->si_drv1;
1814 		LIST_INSERT_HEAD(&udev->pd_list, pd, pd_next);
1815 	}
1816 }
1817 
1818 static void
1819 usb2_cdev_free(struct usb2_device *udev)
1820 {
1821 	struct usb2_fs_privdata* pd;
1822 
1823 	DPRINTFN(2, "Freeing device nodes\n");
1824 
1825 	while ((pd = LIST_FIRST(&udev->pd_list)) != NULL) {
1826 		KASSERT(pd->cdev->si_drv1 == pd, ("privdata corrupt"));
1827 
1828 		destroy_dev_sched_cb(pd->cdev, usb2_cdev_cleanup, pd);
1829 		pd->cdev = NULL;
1830 		LIST_REMOVE(pd, pd_next);
1831 	}
1832 }
1833 
1834 static void
1835 usb2_cdev_cleanup(void* arg)
1836 {
1837 	free(arg, M_USBDEV);
1838 }
1839 #endif
1840 
1841 /*------------------------------------------------------------------------*
1842  *	usb2_free_device
1843  *
1844  * This function is NULL safe and will free an USB device.
1845  *------------------------------------------------------------------------*/
1846 void
1847 usb2_free_device(struct usb2_device *udev)
1848 {
1849 	struct usb2_bus *bus = udev->bus;;
1850 
1851 	DPRINTFN(4, "udev=%p port=%d\n", udev, udev->port_no);
1852 
1853 #if USB_HAVE_UGEN
1854 	usb2_notify_addq("-", udev);
1855 
1856 #if USB_HAVE_STRINGS
1857 	printf("%s: <%s> at %s (disconnected)\n", udev->ugen_name,
1858 	    udev->manufacturer, device_get_nameunit(bus->bdev));
1859 #endif
1860 
1861 	/* Destroy UGEN symlink, if any */
1862 	if (udev->ugen_symlink) {
1863 		usb2_free_symlink(udev->ugen_symlink);
1864 		udev->ugen_symlink = NULL;
1865 	}
1866 #endif
1867 	/*
1868 	 * Unregister our device first which will prevent any further
1869 	 * references:
1870 	 */
1871 	usb2_bus_port_set_device(bus, udev->parent_hub ?
1872 	    udev->parent_hub->hub->ports + udev->port_index : NULL,
1873 	    NULL, USB_ROOT_HUB_ADDR);
1874 
1875 #if USB_HAVE_UGEN
1876 	/* wait for all pending references to go away: */
1877 	mtx_lock(&usb2_ref_lock);
1878 	udev->refcount--;
1879 	while (udev->refcount != 0) {
1880 		usb2_cv_wait(udev->default_cv + 1, &usb2_ref_lock);
1881 	}
1882 	mtx_unlock(&usb2_ref_lock);
1883 #endif
1884 
1885 	if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
1886 		/* stop receiving any control transfers (Device Side Mode) */
1887 		usb2_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1888 	}
1889 #if USB_HAVE_UGEN
1890 	/* free all FIFOs */
1891 	usb2_fifo_free_wrap(udev, USB_IFACE_INDEX_ANY, 1);
1892 
1893 	/*
1894 	 * Free all interface related data and FIFOs, if any.
1895 	 */
1896 	usb2_cdev_free(udev);
1897 #endif
1898 	usb2_free_iface_data(udev);
1899 #if USB_HAVE_UGEN
1900 	destroy_dev_sched_cb(udev->default_dev, usb2_cdev_cleanup,
1901 	    udev->default_dev->si_drv1);
1902 #endif
1903 
1904 	/* unsetup any leftover default USB transfers */
1905 	usb2_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
1906 
1907 	/* template unsetup, if any */
1908 	(usb2_temp_unsetup_p) (udev);
1909 
1910 	/*
1911 	 * Make sure that our clear-stall messages are not queued
1912 	 * anywhere:
1913 	 */
1914 	USB_BUS_LOCK(udev->bus);
1915 	usb2_proc_mwait(&udev->bus->non_giant_callback_proc,
1916 	    &udev->cs_msg[0], &udev->cs_msg[1]);
1917 	USB_BUS_UNLOCK(udev->bus);
1918 
1919 	sx_destroy(udev->default_sx);
1920 	sx_destroy(udev->default_sx + 1);
1921 
1922 	usb2_cv_destroy(udev->default_cv);
1923 	usb2_cv_destroy(udev->default_cv + 1);
1924 
1925 	mtx_destroy(udev->default_mtx);
1926 #if USB_HAVE_UGEN
1927 	KASSERT(LIST_FIRST(&udev->pd_list) == NULL, ("leaked cdev entries"));
1928 #endif
1929 
1930 	/* free device */
1931 	free(udev, M_USB);
1932 }
1933 
1934 /*------------------------------------------------------------------------*
1935  *	usb2_get_iface
1936  *
1937  * This function is the safe way to get the USB interface structure
1938  * pointer by interface index.
1939  *
1940  * Return values:
1941  *   NULL: Interface not present.
1942  *   Else: Pointer to USB interface structure.
1943  *------------------------------------------------------------------------*/
1944 struct usb2_interface *
1945 usb2_get_iface(struct usb2_device *udev, uint8_t iface_index)
1946 {
1947 	struct usb2_interface *iface = udev->ifaces + iface_index;
1948 
1949 	if ((iface < udev->ifaces) ||
1950 	    (iface_index >= USB_IFACE_MAX) ||
1951 	    (udev->cdesc == NULL) ||
1952 	    (iface_index >= udev->cdesc->bNumInterface)) {
1953 		return (NULL);
1954 	}
1955 	return (iface);
1956 }
1957 
1958 /*------------------------------------------------------------------------*
1959  *	usb2_find_descriptor
1960  *
1961  * This function will lookup the first descriptor that matches the
1962  * criteria given by the arguments "type" and "subtype". Descriptors
1963  * will only be searched within the interface having the index
1964  * "iface_index".  If the "id" argument points to an USB descriptor,
1965  * it will be skipped before the search is started. This allows
1966  * searching for multiple descriptors using the same criteria. Else
1967  * the search is started after the interface descriptor.
1968  *
1969  * Return values:
1970  *   NULL: End of descriptors
1971  *   Else: A descriptor matching the criteria
1972  *------------------------------------------------------------------------*/
1973 void   *
1974 usb2_find_descriptor(struct usb2_device *udev, void *id, uint8_t iface_index,
1975     uint8_t type, uint8_t type_mask,
1976     uint8_t subtype, uint8_t subtype_mask)
1977 {
1978 	struct usb2_descriptor *desc;
1979 	struct usb2_config_descriptor *cd;
1980 	struct usb2_interface *iface;
1981 
1982 	cd = usb2_get_config_descriptor(udev);
1983 	if (cd == NULL) {
1984 		return (NULL);
1985 	}
1986 	if (id == NULL) {
1987 		iface = usb2_get_iface(udev, iface_index);
1988 		if (iface == NULL) {
1989 			return (NULL);
1990 		}
1991 		id = usb2_get_interface_descriptor(iface);
1992 		if (id == NULL) {
1993 			return (NULL);
1994 		}
1995 	}
1996 	desc = (void *)id;
1997 
1998 	while ((desc = usb2_desc_foreach(cd, desc))) {
1999 
2000 		if (desc->bDescriptorType == UDESC_INTERFACE) {
2001 			break;
2002 		}
2003 		if (((desc->bDescriptorType & type_mask) == type) &&
2004 		    ((desc->bDescriptorSubtype & subtype_mask) == subtype)) {
2005 			return (desc);
2006 		}
2007 	}
2008 	return (NULL);
2009 }
2010 
2011 /*------------------------------------------------------------------------*
2012  *	usb2_devinfo
2013  *
2014  * This function will dump information from the device descriptor
2015  * belonging to the USB device pointed to by "udev", to the string
2016  * pointed to by "dst_ptr" having a maximum length of "dst_len" bytes
2017  * including the terminating zero.
2018  *------------------------------------------------------------------------*/
2019 void
2020 usb2_devinfo(struct usb2_device *udev, char *dst_ptr, uint16_t dst_len)
2021 {
2022 	struct usb2_device_descriptor *udd = &udev->ddesc;
2023 	uint16_t bcdDevice;
2024 	uint16_t bcdUSB;
2025 
2026 	bcdUSB = UGETW(udd->bcdUSB);
2027 	bcdDevice = UGETW(udd->bcdDevice);
2028 
2029 	if (udd->bDeviceClass != 0xFF) {
2030 		snprintf(dst_ptr, dst_len, "%s %s, class %d/%d, rev %x.%02x/"
2031 		    "%x.%02x, addr %d",
2032 #if USB_HAVE_STRINGS
2033 		    udev->manufacturer, udev->product,
2034 #else
2035 		    "-", "-",
2036 #endif
2037 		    udd->bDeviceClass, udd->bDeviceSubClass,
2038 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2039 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2040 		    udev->address);
2041 	} else {
2042 		snprintf(dst_ptr, dst_len, "%s %s, rev %x.%02x/"
2043 		    "%x.%02x, addr %d",
2044 #if USB_HAVE_STRINGS
2045 		    udev->manufacturer, udev->product,
2046 #else
2047 		    "-", "-",
2048 #endif
2049 		    (bcdUSB >> 8), bcdUSB & 0xFF,
2050 		    (bcdDevice >> 8), bcdDevice & 0xFF,
2051 		    udev->address);
2052 	}
2053 }
2054 
2055 #if USB_HAVE_STRINGS
2056 #if USB_VERBOSE
2057 /*
2058  * Descriptions of of known vendors and devices ("products").
2059  */
2060 struct usb_knowndev {
2061 	uint16_t vendor;
2062 	uint16_t product;
2063 	uint32_t flags;
2064 	const char *vendorname;
2065 	const char *productname;
2066 };
2067 
2068 #define	USB_KNOWNDEV_NOPROD	0x01	/* match on vendor only */
2069 
2070 #include "usbdevs.h"
2071 #include "usbdevs_data.h"
2072 #endif					/* USB_VERBOSE */
2073 
2074 /*------------------------------------------------------------------------*
2075  *	usb2_check_strings
2076  *
2077  * This function checks the manufacturer and product strings and will
2078  * fill in defaults for missing strings.
2079  *------------------------------------------------------------------------*/
2080 static void
2081 usb2_check_strings(struct usb2_device *udev)
2082 {
2083 	struct usb2_device_descriptor *udd = &udev->ddesc;
2084 	const char *vendor;
2085 	const char *product;
2086 
2087 #if USB_VERBOSE
2088 	const struct usb_knowndev *kdp;
2089 
2090 #endif
2091 	uint16_t vendor_id;
2092 	uint16_t product_id;
2093 
2094 	usb2_trim_spaces(udev->manufacturer);
2095 	usb2_trim_spaces(udev->product);
2096 
2097 	if (udev->manufacturer[0]) {
2098 		vendor = udev->manufacturer;
2099 	} else {
2100 		vendor = NULL;
2101 	}
2102 
2103 	if (udev->product[0]) {
2104 		product = udev->product;
2105 	} else {
2106 		product = NULL;
2107 	}
2108 
2109 	vendor_id = UGETW(udd->idVendor);
2110 	product_id = UGETW(udd->idProduct);
2111 
2112 #if USB_VERBOSE
2113 	if (vendor == NULL || product == NULL) {
2114 
2115 		for (kdp = usb_knowndevs;
2116 		    kdp->vendorname != NULL;
2117 		    kdp++) {
2118 			if (kdp->vendor == vendor_id &&
2119 			    (kdp->product == product_id ||
2120 			    (kdp->flags & USB_KNOWNDEV_NOPROD) != 0))
2121 				break;
2122 		}
2123 		if (kdp->vendorname != NULL) {
2124 			if (vendor == NULL)
2125 				vendor = kdp->vendorname;
2126 			if (product == NULL)
2127 				product = (kdp->flags & USB_KNOWNDEV_NOPROD) == 0 ?
2128 				    kdp->productname : NULL;
2129 		}
2130 	}
2131 #endif
2132 	if (vendor && *vendor) {
2133 		if (udev->manufacturer != vendor) {
2134 			strlcpy(udev->manufacturer, vendor,
2135 			    sizeof(udev->manufacturer));
2136 		}
2137 	} else {
2138 		snprintf(udev->manufacturer,
2139 		    sizeof(udev->manufacturer), "vendor 0x%04x", vendor_id);
2140 	}
2141 
2142 	if (product && *product) {
2143 		if (udev->product != product) {
2144 			strlcpy(udev->product, product,
2145 			    sizeof(udev->product));
2146 		}
2147 	} else {
2148 		snprintf(udev->product,
2149 		    sizeof(udev->product), "product 0x%04x", product_id);
2150 	}
2151 }
2152 #endif
2153 
2154 /*
2155  * Returns:
2156  * See: USB_MODE_XXX
2157  */
2158 uint8_t
2159 usb2_get_mode(struct usb2_device *udev)
2160 {
2161 	return (udev->flags.usb2_mode);
2162 }
2163 
2164 /*
2165  * Returns:
2166  * See: USB_SPEED_XXX
2167  */
2168 uint8_t
2169 usb2_get_speed(struct usb2_device *udev)
2170 {
2171 	return (udev->speed);
2172 }
2173 
2174 uint32_t
2175 usb2_get_isoc_fps(struct usb2_device *udev)
2176 {
2177 	;				/* indent fix */
2178 	switch (udev->speed) {
2179 	case USB_SPEED_LOW:
2180 	case USB_SPEED_FULL:
2181 		return (1000);
2182 	default:
2183 		return (8000);
2184 	}
2185 }
2186 
2187 struct usb2_device_descriptor *
2188 usb2_get_device_descriptor(struct usb2_device *udev)
2189 {
2190 	if (udev == NULL)
2191 		return (NULL);		/* be NULL safe */
2192 	return (&udev->ddesc);
2193 }
2194 
2195 struct usb2_config_descriptor *
2196 usb2_get_config_descriptor(struct usb2_device *udev)
2197 {
2198 	if (udev == NULL)
2199 		return (NULL);		/* be NULL safe */
2200 	return (udev->cdesc);
2201 }
2202 
2203 /*------------------------------------------------------------------------*
2204  *	usb2_test_quirk - test a device for a given quirk
2205  *
2206  * Return values:
2207  * 0: The USB device does not have the given quirk.
2208  * Else: The USB device has the given quirk.
2209  *------------------------------------------------------------------------*/
2210 uint8_t
2211 usb2_test_quirk(const struct usb2_attach_arg *uaa, uint16_t quirk)
2212 {
2213 	uint8_t found;
2214 
2215 	found = (usb2_test_quirk_p) (&uaa->info, quirk);
2216 	return (found);
2217 }
2218 
2219 struct usb2_interface_descriptor *
2220 usb2_get_interface_descriptor(struct usb2_interface *iface)
2221 {
2222 	if (iface == NULL)
2223 		return (NULL);		/* be NULL safe */
2224 	return (iface->idesc);
2225 }
2226 
2227 uint8_t
2228 usb2_get_interface_altindex(struct usb2_interface *iface)
2229 {
2230 	return (iface->alt_index);
2231 }
2232 
2233 uint8_t
2234 usb2_get_bus_index(struct usb2_device *udev)
2235 {
2236 	return ((uint8_t)device_get_unit(udev->bus->bdev));
2237 }
2238 
2239 uint8_t
2240 usb2_get_device_index(struct usb2_device *udev)
2241 {
2242 	return (udev->device_index);
2243 }
2244 
2245 #if USB_HAVE_UGEN
2246 /*------------------------------------------------------------------------*
2247  *	usb2_notify_addq
2248  *
2249  * This function will generate events for dev.
2250  *------------------------------------------------------------------------*/
2251 static void
2252 usb2_notify_addq(const char *type, struct usb2_device *udev)
2253 {
2254 	char *data = NULL;
2255 	struct malloc_type *mt;
2256 
2257 	mtx_lock(&malloc_mtx);
2258 	mt = malloc_desc2type("bus");	/* XXX M_BUS */
2259 	mtx_unlock(&malloc_mtx);
2260 	if (mt == NULL)
2261 		return;
2262 
2263 	data = malloc(512, mt, M_NOWAIT);
2264 	if (data == NULL)
2265 		return;
2266 
2267 	/* String it all together. */
2268 	snprintf(data, 1024,
2269 	    "%s"
2270 	    "%s "
2271 	    "vendor=0x%04x "
2272 	    "product=0x%04x "
2273 	    "devclass=0x%02x "
2274 	    "devsubclass=0x%02x "
2275 	    "sernum=\"%s\" "
2276 	    "at "
2277 	    "port=%u "
2278 	    "on "
2279 	    "%s\n",
2280 	    type,
2281 	    udev->ugen_name,
2282 	    UGETW(udev->ddesc.idVendor),
2283 	    UGETW(udev->ddesc.idProduct),
2284 	    udev->ddesc.bDeviceClass,
2285 	    udev->ddesc.bDeviceSubClass,
2286 #if USB_HAVE_STRINGS
2287 	    udev->serial,
2288 #else
2289 	    "",
2290 #endif
2291 	    udev->port_no,
2292 	    udev->parent_hub != NULL ?
2293 		udev->parent_hub->ugen_name :
2294 		device_get_nameunit(device_get_parent(udev->bus->bdev)));
2295 
2296 	devctl_queue_data(data);
2297 }
2298 
2299 /*------------------------------------------------------------------------*
2300  *	usb2_fifo_free_wrap
2301  *
2302  * This function will free the FIFOs.
2303  *
2304  * Flag values, if "iface_index" is equal to "USB_IFACE_INDEX_ANY".
2305  * 0: Free all FIFOs except generic control endpoints.
2306  * 1: Free all FIFOs.
2307  *
2308  * Flag values, if "iface_index" is not equal to "USB_IFACE_INDEX_ANY".
2309  * Not used.
2310  *------------------------------------------------------------------------*/
2311 static void
2312 usb2_fifo_free_wrap(struct usb2_device *udev,
2313     uint8_t iface_index, uint8_t flag)
2314 {
2315 	struct usb2_fifo *f;
2316 	uint16_t i;
2317 
2318 	/*
2319 	 * Free any USB FIFOs on the given interface:
2320 	 */
2321 	for (i = 0; i != USB_FIFO_MAX; i++) {
2322 		f = udev->fifo[i];
2323 		if (f == NULL) {
2324 			continue;
2325 		}
2326 		/* Check if the interface index matches */
2327 		if (iface_index == f->iface_index) {
2328 			if (f->methods != &usb2_ugen_methods) {
2329 				/*
2330 				 * Don't free any non-generic FIFOs in
2331 				 * this case.
2332 				 */
2333 				continue;
2334 			}
2335 			if ((f->dev_ep_index == 0) &&
2336 			    (f->fs_xfer == NULL)) {
2337 				/* no need to free this FIFO */
2338 				continue;
2339 			}
2340 		} else if (iface_index == USB_IFACE_INDEX_ANY) {
2341 			if ((f->methods == &usb2_ugen_methods) &&
2342 			    (f->dev_ep_index == 0) && (flag == 0) &&
2343 			    (f->fs_xfer == NULL)) {
2344 				/* no need to free this FIFO */
2345 				continue;
2346 			}
2347 		} else {
2348 			/* no need to free this FIFO */
2349 			continue;
2350 		}
2351 		/* free this FIFO */
2352 		usb2_fifo_free(f);
2353 	}
2354 }
2355 #endif
2356 
2357 /*------------------------------------------------------------------------*
2358  *	usb2_peer_can_wakeup
2359  *
2360  * Return values:
2361  * 0: Peer cannot do resume signalling.
2362  * Else: Peer can do resume signalling.
2363  *------------------------------------------------------------------------*/
2364 uint8_t
2365 usb2_peer_can_wakeup(struct usb2_device *udev)
2366 {
2367 	const struct usb2_config_descriptor *cdp;
2368 
2369 	cdp = udev->cdesc;
2370 	if ((cdp != NULL) && (udev->flags.usb2_mode == USB_MODE_HOST)) {
2371 		return (cdp->bmAttributes & UC_REMOTE_WAKEUP);
2372 	}
2373 	return (0);			/* not supported */
2374 }
2375