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