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