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