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