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