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