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