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