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