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