xref: /freebsd/sys/dev/usb/usb_request.c (revision 1f474190)
1 /* $FreeBSD$ */
2 /*-
3  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4  *
5  * Copyright (c) 1998 The NetBSD Foundation, Inc. All rights reserved.
6  * Copyright (c) 1998 Lennart Augustsson. All rights reserved.
7  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #ifdef USB_GLOBAL_INCLUDE_FILE
32 #include USB_GLOBAL_INCLUDE_FILE
33 #else
34 #include <sys/stdint.h>
35 #include <sys/stddef.h>
36 #include <sys/param.h>
37 #include <sys/queue.h>
38 #include <sys/types.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/module.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/condvar.h>
46 #include <sys/sysctl.h>
47 #include <sys/sx.h>
48 #include <sys/unistd.h>
49 #include <sys/callout.h>
50 #include <sys/malloc.h>
51 #include <sys/priv.h>
52 
53 #include <dev/usb/usb.h>
54 #include <dev/usb/usbdi.h>
55 #include <dev/usb/usbdi_util.h>
56 #include <dev/usb/usbhid.h>
57 
58 #define	USB_DEBUG_VAR usb_debug
59 
60 #include <dev/usb/usb_core.h>
61 #include <dev/usb/usb_busdma.h>
62 #include <dev/usb/usb_request.h>
63 #include <dev/usb/usb_process.h>
64 #include <dev/usb/usb_transfer.h>
65 #include <dev/usb/usb_debug.h>
66 #include <dev/usb/usb_device.h>
67 #include <dev/usb/usb_util.h>
68 #include <dev/usb/usb_dynamic.h>
69 
70 #include <dev/usb/usb_controller.h>
71 #include <dev/usb/usb_bus.h>
72 #include <sys/ctype.h>
73 #endif			/* USB_GLOBAL_INCLUDE_FILE */
74 
75 static int usb_no_cs_fail;
76 
77 SYSCTL_INT(_hw_usb, OID_AUTO, no_cs_fail, CTLFLAG_RWTUN,
78     &usb_no_cs_fail, 0, "USB clear stall failures are ignored, if set");
79 
80 static int usb_full_ddesc;
81 
82 SYSCTL_INT(_hw_usb, OID_AUTO, full_ddesc, CTLFLAG_RWTUN,
83     &usb_full_ddesc, 0, "USB always read complete device descriptor, if set");
84 
85 #ifdef USB_DEBUG
86 #ifdef USB_REQ_DEBUG
87 /* The following structures are used in connection to fault injection. */
88 struct usb_ctrl_debug {
89 	int bus_index;		/* target bus */
90 	int dev_index;		/* target address */
91 	int ds_fail;		/* fail data stage */
92 	int ss_fail;		/* fail status stage */
93 	int ds_delay;		/* data stage delay in ms */
94 	int ss_delay;		/* status stage delay in ms */
95 	int bmRequestType_value;
96 	int bRequest_value;
97 };
98 
99 struct usb_ctrl_debug_bits {
100 	uint16_t ds_delay;
101 	uint16_t ss_delay;
102 	uint8_t ds_fail:1;
103 	uint8_t ss_fail:1;
104 	uint8_t enabled:1;
105 };
106 
107 /* The default is to disable fault injection. */
108 
109 static struct usb_ctrl_debug usb_ctrl_debug = {
110 	.bus_index = -1,
111 	.dev_index = -1,
112 	.bmRequestType_value = -1,
113 	.bRequest_value = -1,
114 };
115 
116 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_bus_fail, CTLFLAG_RWTUN,
117     &usb_ctrl_debug.bus_index, 0, "USB controller index to fail");
118 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_dev_fail, CTLFLAG_RWTUN,
119     &usb_ctrl_debug.dev_index, 0, "USB device address to fail");
120 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_fail, CTLFLAG_RWTUN,
121     &usb_ctrl_debug.ds_fail, 0, "USB fail data stage");
122 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_fail, CTLFLAG_RWTUN,
123     &usb_ctrl_debug.ss_fail, 0, "USB fail status stage");
124 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_delay, CTLFLAG_RWTUN,
125     &usb_ctrl_debug.ds_delay, 0, "USB data stage delay in ms");
126 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_delay, CTLFLAG_RWTUN,
127     &usb_ctrl_debug.ss_delay, 0, "USB status stage delay in ms");
128 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rt_fail, CTLFLAG_RWTUN,
129     &usb_ctrl_debug.bmRequestType_value, 0, "USB bmRequestType to fail");
130 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rv_fail, CTLFLAG_RWTUN,
131     &usb_ctrl_debug.bRequest_value, 0, "USB bRequest to fail");
132 
133 /*------------------------------------------------------------------------*
134  *	usbd_get_debug_bits
135  *
136  * This function is only useful in USB host mode.
137  *------------------------------------------------------------------------*/
138 static void
139 usbd_get_debug_bits(struct usb_device *udev, struct usb_device_request *req,
140     struct usb_ctrl_debug_bits *dbg)
141 {
142 	int temp;
143 
144 	memset(dbg, 0, sizeof(*dbg));
145 
146 	/* Compute data stage delay */
147 
148 	temp = usb_ctrl_debug.ds_delay;
149 	if (temp < 0)
150 		temp = 0;
151 	else if (temp > (16*1024))
152 		temp = (16*1024);
153 
154 	dbg->ds_delay = temp;
155 
156 	/* Compute status stage delay */
157 
158 	temp = usb_ctrl_debug.ss_delay;
159 	if (temp < 0)
160 		temp = 0;
161 	else if (temp > (16*1024))
162 		temp = (16*1024);
163 
164 	dbg->ss_delay = temp;
165 
166 	/* Check if this control request should be failed */
167 
168 	if (usbd_get_bus_index(udev) != usb_ctrl_debug.bus_index)
169 		return;
170 
171 	if (usbd_get_device_index(udev) != usb_ctrl_debug.dev_index)
172 		return;
173 
174 	temp = usb_ctrl_debug.bmRequestType_value;
175 
176 	if ((temp != req->bmRequestType) && (temp >= 0) && (temp <= 255))
177 		return;
178 
179 	temp = usb_ctrl_debug.bRequest_value;
180 
181 	if ((temp != req->bRequest) && (temp >= 0) && (temp <= 255))
182 		return;
183 
184 	temp = usb_ctrl_debug.ds_fail;
185 	if (temp)
186 		dbg->ds_fail = 1;
187 
188 	temp = usb_ctrl_debug.ss_fail;
189 	if (temp)
190 		dbg->ss_fail = 1;
191 
192 	dbg->enabled = 1;
193 }
194 #endif	/* USB_REQ_DEBUG */
195 #endif	/* USB_DEBUG */
196 
197 /*------------------------------------------------------------------------*
198  *	usbd_do_request_callback
199  *
200  * This function is the USB callback for generic USB Host control
201  * transfers.
202  *------------------------------------------------------------------------*/
203 void
204 usbd_do_request_callback(struct usb_xfer *xfer, usb_error_t error)
205 {
206 	;				/* workaround for a bug in "indent" */
207 
208 	DPRINTF("st=%u\n", USB_GET_STATE(xfer));
209 
210 	switch (USB_GET_STATE(xfer)) {
211 	case USB_ST_SETUP:
212 		usbd_transfer_submit(xfer);
213 		break;
214 	default:
215 		cv_signal(&xfer->xroot->udev->ctrlreq_cv);
216 		break;
217 	}
218 }
219 
220 /*------------------------------------------------------------------------*
221  *	usb_do_clear_stall_callback
222  *
223  * This function is the USB callback for generic clear stall requests.
224  *------------------------------------------------------------------------*/
225 void
226 usb_do_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
227 {
228 	struct usb_device_request req;
229 	struct usb_device *udev;
230 	struct usb_endpoint *ep;
231 	struct usb_endpoint *ep_end;
232 	struct usb_endpoint *ep_first;
233 	usb_stream_t x;
234 	uint8_t to;
235 
236 	udev = xfer->xroot->udev;
237 
238 	USB_BUS_LOCK(udev->bus);
239 
240 	/* round robin endpoint clear stall */
241 
242 	ep = udev->ep_curr;
243 	ep_end = udev->endpoints + udev->endpoints_max;
244 	ep_first = udev->endpoints;
245 	to = udev->endpoints_max;
246 
247 	switch (USB_GET_STATE(xfer)) {
248 	case USB_ST_TRANSFERRED:
249 tr_transferred:
250 		/* reset error counter */
251 		udev->clear_stall_errors = 0;
252 
253 		if (ep == NULL)
254 			goto tr_setup;		/* device was unconfigured */
255 		if (ep->edesc &&
256 		    ep->is_stalled) {
257 			ep->toggle_next = 0;
258 			ep->is_stalled = 0;
259 			/* some hardware needs a callback to clear the data toggle */
260 			usbd_clear_stall_locked(udev, ep);
261 			for (x = 0; x != USB_MAX_EP_STREAMS; x++) {
262 				/* start the current or next transfer, if any */
263 				usb_command_wrapper(&ep->endpoint_q[x],
264 				    ep->endpoint_q[x].curr);
265 			}
266 		}
267 		ep++;
268 
269 	case USB_ST_SETUP:
270 tr_setup:
271 		if (to == 0)
272 			break;			/* no endpoints - nothing to do */
273 		if ((ep < ep_first) || (ep >= ep_end))
274 			ep = ep_first;	/* endpoint wrapped around */
275 		if (ep->edesc &&
276 		    ep->is_stalled) {
277 			/* setup a clear-stall packet */
278 
279 			req.bmRequestType = UT_WRITE_ENDPOINT;
280 			req.bRequest = UR_CLEAR_FEATURE;
281 			USETW(req.wValue, UF_ENDPOINT_HALT);
282 			req.wIndex[0] = ep->edesc->bEndpointAddress;
283 			req.wIndex[1] = 0;
284 			USETW(req.wLength, 0);
285 
286 			/* copy in the transfer */
287 
288 			usbd_copy_in(xfer->frbuffers, 0, &req, sizeof(req));
289 
290 			/* set length */
291 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
292 			xfer->nframes = 1;
293 			USB_BUS_UNLOCK(udev->bus);
294 
295 			usbd_transfer_submit(xfer);
296 
297 			USB_BUS_LOCK(udev->bus);
298 			break;
299 		}
300 		ep++;
301 		to--;
302 		goto tr_setup;
303 
304 	default:
305 		if (error == USB_ERR_CANCELLED)
306 			break;
307 
308 		DPRINTF("Clear stall failed.\n");
309 
310 		/*
311 		 * Some VMs like VirtualBox always return failure on
312 		 * clear-stall which we sometimes should just ignore.
313 		 */
314 		if (usb_no_cs_fail)
315 			goto tr_transferred;
316 		if (udev->clear_stall_errors == USB_CS_RESET_LIMIT)
317 			goto tr_setup;
318 
319 		if (error == USB_ERR_TIMEOUT) {
320 			udev->clear_stall_errors = USB_CS_RESET_LIMIT;
321 			DPRINTF("Trying to re-enumerate.\n");
322 			usbd_start_re_enumerate(udev);
323 		} else {
324 			udev->clear_stall_errors++;
325 			if (udev->clear_stall_errors == USB_CS_RESET_LIMIT) {
326 				DPRINTF("Trying to re-enumerate.\n");
327 				usbd_start_re_enumerate(udev);
328 			}
329 		}
330 		goto tr_setup;
331 	}
332 
333 	/* store current endpoint */
334 	udev->ep_curr = ep;
335 	USB_BUS_UNLOCK(udev->bus);
336 }
337 
338 static usb_handle_req_t *
339 usbd_get_hr_func(struct usb_device *udev)
340 {
341 	/* figure out if there is a Handle Request function */
342 	if (udev->flags.usb_mode == USB_MODE_DEVICE)
343 		return (usb_temp_get_desc_p);
344 	else if (udev->parent_hub == NULL)
345 		return (udev->bus->methods->roothub_exec);
346 	else
347 		return (NULL);
348 }
349 
350 /*------------------------------------------------------------------------*
351  *	usbd_do_request_flags and usbd_do_request
352  *
353  * Description of arguments passed to these functions:
354  *
355  * "udev" - this is the "usb_device" structure pointer on which the
356  * request should be performed. It is possible to call this function
357  * in both Host Side mode and Device Side mode.
358  *
359  * "mtx" - if this argument is non-NULL the mutex pointed to by it
360  * will get dropped and picked up during the execution of this
361  * function, hence this function sometimes needs to sleep. If this
362  * argument is NULL it has no effect.
363  *
364  * "req" - this argument must always be non-NULL and points to an
365  * 8-byte structure holding the USB request to be done. The USB
366  * request structure has a bit telling the direction of the USB
367  * request, if it is a read or a write.
368  *
369  * "data" - if the "wLength" part of the structure pointed to by "req"
370  * is non-zero this argument must point to a valid kernel buffer which
371  * can hold at least "wLength" bytes. If "wLength" is zero "data" can
372  * be NULL.
373  *
374  * "flags" - here is a list of valid flags:
375  *
376  *  o USB_SHORT_XFER_OK: allows the data transfer to be shorter than
377  *  specified
378  *
379  *  o USB_DELAY_STATUS_STAGE: allows the status stage to be performed
380  *  at a later point in time. This is tunable by the "hw.usb.ss_delay"
381  *  sysctl. This flag is mostly useful for debugging.
382  *
383  *  o USB_USER_DATA_PTR: treat the "data" pointer like a userland
384  *  pointer.
385  *
386  * "actlen" - if non-NULL the actual transfer length will be stored in
387  * the 16-bit unsigned integer pointed to by "actlen". This
388  * information is mostly useful when the "USB_SHORT_XFER_OK" flag is
389  * used.
390  *
391  * "timeout" - gives the timeout for the control transfer in
392  * milliseconds. A "timeout" value less than 50 milliseconds is
393  * treated like a 50 millisecond timeout. A "timeout" value greater
394  * than 30 seconds is treated like a 30 second timeout. This USB stack
395  * does not allow control requests without a timeout.
396  *
397  * NOTE: This function is thread safe. All calls to "usbd_do_request_flags"
398  * will be serialized by the use of the USB device enumeration lock.
399  *
400  * Returns:
401  *    0: Success
402  * Else: Failure
403  *------------------------------------------------------------------------*/
404 usb_error_t
405 usbd_do_request_flags(struct usb_device *udev, struct mtx *mtx,
406     struct usb_device_request *req, void *data, uint16_t flags,
407     uint16_t *actlen, usb_timeout_t timeout)
408 {
409 #ifdef USB_REQ_DEBUG
410 	struct usb_ctrl_debug_bits dbg;
411 #endif
412 	usb_handle_req_t *hr_func;
413 	struct usb_xfer *xfer;
414 	const void *desc;
415 	int err = 0;
416 	usb_ticks_t start_ticks;
417 	usb_ticks_t delta_ticks;
418 	usb_ticks_t max_ticks;
419 	uint16_t length;
420 	uint16_t temp;
421 	uint16_t acttemp;
422 	uint8_t do_unlock;
423 
424 	if (timeout < 50) {
425 		/* timeout is too small */
426 		timeout = 50;
427 	}
428 	if (timeout > 30000) {
429 		/* timeout is too big */
430 		timeout = 30000;
431 	}
432 	length = UGETW(req->wLength);
433 
434 	DPRINTFN(5, "udev=%p bmRequestType=0x%02x bRequest=0x%02x "
435 	    "wValue=0x%02x%02x wIndex=0x%02x%02x wLength=0x%02x%02x\n",
436 	    udev, req->bmRequestType, req->bRequest,
437 	    req->wValue[1], req->wValue[0],
438 	    req->wIndex[1], req->wIndex[0],
439 	    req->wLength[1], req->wLength[0]);
440 
441 	/* Check if the device is still alive */
442 	if (udev->state < USB_STATE_POWERED) {
443 		DPRINTF("usb device has gone\n");
444 		return (USB_ERR_NOT_CONFIGURED);
445 	}
446 
447 	/*
448 	 * Set "actlen" to a known value in case the caller does not
449 	 * check the return value:
450 	 */
451 	if (actlen)
452 		*actlen = 0;
453 
454 #if (USB_HAVE_USER_IO == 0)
455 	if (flags & USB_USER_DATA_PTR)
456 		return (USB_ERR_INVAL);
457 #endif
458 	if ((mtx != NULL) && (mtx != &Giant)) {
459 		USB_MTX_UNLOCK(mtx);
460 		USB_MTX_ASSERT(mtx, MA_NOTOWNED);
461 	}
462 
463 	/*
464 	 * Serialize access to this function:
465 	 */
466 	do_unlock = usbd_ctrl_lock(udev);
467 
468 	hr_func = usbd_get_hr_func(udev);
469 
470 	if (hr_func != NULL) {
471 		DPRINTF("Handle Request function is set\n");
472 
473 		desc = NULL;
474 		temp = 0;
475 
476 		if (!(req->bmRequestType & UT_READ)) {
477 			if (length != 0) {
478 				DPRINTFN(1, "The handle request function "
479 				    "does not support writing data!\n");
480 				err = USB_ERR_INVAL;
481 				goto done;
482 			}
483 		}
484 
485 		/* The root HUB code needs the BUS lock locked */
486 
487 		USB_BUS_LOCK(udev->bus);
488 		err = (hr_func) (udev, req, &desc, &temp);
489 		USB_BUS_UNLOCK(udev->bus);
490 
491 		if (err)
492 			goto done;
493 
494 		if (length > temp) {
495 			if (!(flags & USB_SHORT_XFER_OK)) {
496 				err = USB_ERR_SHORT_XFER;
497 				goto done;
498 			}
499 			length = temp;
500 		}
501 		if (actlen)
502 			*actlen = length;
503 
504 		if (length > 0) {
505 #if USB_HAVE_USER_IO
506 			if (flags & USB_USER_DATA_PTR) {
507 				if (copyout(desc, data, length)) {
508 					err = USB_ERR_INVAL;
509 					goto done;
510 				}
511 			} else
512 #endif
513 				memcpy(data, desc, length);
514 		}
515 		goto done;		/* success */
516 	}
517 
518 	/*
519 	 * Setup a new USB transfer or use the existing one, if any:
520 	 */
521 	usbd_ctrl_transfer_setup(udev);
522 
523 	xfer = udev->ctrl_xfer[0];
524 	if (xfer == NULL) {
525 		/* most likely out of memory */
526 		err = USB_ERR_NOMEM;
527 		goto done;
528 	}
529 
530 #ifdef USB_REQ_DEBUG
531 	/* Get debug bits */
532 	usbd_get_debug_bits(udev, req, &dbg);
533 
534 	/* Check for fault injection */
535 	if (dbg.enabled)
536 		flags |= USB_DELAY_STATUS_STAGE;
537 #endif
538 	USB_XFER_LOCK(xfer);
539 
540 	if (flags & USB_DELAY_STATUS_STAGE)
541 		xfer->flags.manual_status = 1;
542 	else
543 		xfer->flags.manual_status = 0;
544 
545 	if (flags & USB_SHORT_XFER_OK)
546 		xfer->flags.short_xfer_ok = 1;
547 	else
548 		xfer->flags.short_xfer_ok = 0;
549 
550 	xfer->timeout = timeout;
551 
552 	start_ticks = ticks;
553 
554 	max_ticks = USB_MS_TO_TICKS(timeout);
555 
556 	usbd_copy_in(xfer->frbuffers, 0, req, sizeof(*req));
557 
558 	usbd_xfer_set_frame_len(xfer, 0, sizeof(*req));
559 
560 	while (1) {
561 		temp = length;
562 		if (temp > usbd_xfer_max_len(xfer)) {
563 			temp = usbd_xfer_max_len(xfer);
564 		}
565 #ifdef USB_REQ_DEBUG
566 		if (xfer->flags.manual_status) {
567 			if (usbd_xfer_frame_len(xfer, 0) != 0) {
568 				/* Execute data stage separately */
569 				temp = 0;
570 			} else if (temp > 0) {
571 				if (dbg.ds_fail) {
572 					err = USB_ERR_INVAL;
573 					break;
574 				}
575 				if (dbg.ds_delay > 0) {
576 					usb_pause_mtx(
577 					    xfer->xroot->xfer_mtx,
578 				            USB_MS_TO_TICKS(dbg.ds_delay));
579 					/* make sure we don't time out */
580 					start_ticks = ticks;
581 				}
582 			}
583 		}
584 #endif
585 		usbd_xfer_set_frame_len(xfer, 1, temp);
586 
587 		if (temp > 0) {
588 			if (!(req->bmRequestType & UT_READ)) {
589 #if USB_HAVE_USER_IO
590 				if (flags & USB_USER_DATA_PTR) {
591 					USB_XFER_UNLOCK(xfer);
592 					err = usbd_copy_in_user(xfer->frbuffers + 1,
593 					    0, data, temp);
594 					USB_XFER_LOCK(xfer);
595 					if (err) {
596 						err = USB_ERR_INVAL;
597 						break;
598 					}
599 				} else
600 #endif
601 					usbd_copy_in(xfer->frbuffers + 1,
602 					    0, data, temp);
603 			}
604 			usbd_xfer_set_frames(xfer, 2);
605 		} else {
606 			if (usbd_xfer_frame_len(xfer, 0) == 0) {
607 				if (xfer->flags.manual_status) {
608 #ifdef USB_REQ_DEBUG
609 					if (dbg.ss_fail) {
610 						err = USB_ERR_INVAL;
611 						break;
612 					}
613 					if (dbg.ss_delay > 0) {
614 						usb_pause_mtx(
615 						    xfer->xroot->xfer_mtx,
616 						    USB_MS_TO_TICKS(dbg.ss_delay));
617 						/* make sure we don't time out */
618 						start_ticks = ticks;
619 					}
620 #endif
621 					xfer->flags.manual_status = 0;
622 				} else {
623 					break;
624 				}
625 			}
626 			usbd_xfer_set_frames(xfer, 1);
627 		}
628 
629 		usbd_transfer_start(xfer);
630 
631 		while (usbd_transfer_pending(xfer)) {
632 			cv_wait(&udev->ctrlreq_cv,
633 			    xfer->xroot->xfer_mtx);
634 		}
635 
636 		err = xfer->error;
637 
638 		if (err) {
639 			break;
640 		}
641 
642 		/* get actual length of DATA stage */
643 
644 		if (xfer->aframes < 2) {
645 			acttemp = 0;
646 		} else {
647 			acttemp = usbd_xfer_frame_len(xfer, 1);
648 		}
649 
650 		/* check for short packet */
651 
652 		if (temp > acttemp) {
653 			temp = acttemp;
654 			length = temp;
655 		}
656 		if (temp > 0) {
657 			if (req->bmRequestType & UT_READ) {
658 #if USB_HAVE_USER_IO
659 				if (flags & USB_USER_DATA_PTR) {
660 					USB_XFER_UNLOCK(xfer);
661 					err = usbd_copy_out_user(xfer->frbuffers + 1,
662 					    0, data, temp);
663 					USB_XFER_LOCK(xfer);
664 					if (err) {
665 						err = USB_ERR_INVAL;
666 						break;
667 					}
668 				} else
669 #endif
670 					usbd_copy_out(xfer->frbuffers + 1,
671 					    0, data, temp);
672 			}
673 		}
674 		/*
675 		 * Clear "frlengths[0]" so that we don't send the setup
676 		 * packet again:
677 		 */
678 		usbd_xfer_set_frame_len(xfer, 0, 0);
679 
680 		/* update length and data pointer */
681 		length -= temp;
682 		data = USB_ADD_BYTES(data, temp);
683 
684 		if (actlen) {
685 			(*actlen) += temp;
686 		}
687 		/* check for timeout */
688 
689 		delta_ticks = ticks - start_ticks;
690 		if (delta_ticks > max_ticks) {
691 			if (!err) {
692 				err = USB_ERR_TIMEOUT;
693 			}
694 		}
695 		if (err) {
696 			break;
697 		}
698 	}
699 
700 	if (err) {
701 		/*
702 		 * Make sure that the control endpoint is no longer
703 		 * blocked in case of a non-transfer related error:
704 		 */
705 		usbd_transfer_stop(xfer);
706 	}
707 	USB_XFER_UNLOCK(xfer);
708 
709 done:
710 	if (do_unlock)
711 		usbd_ctrl_unlock(udev);
712 
713 	if ((mtx != NULL) && (mtx != &Giant))
714 		USB_MTX_LOCK(mtx);
715 
716 	switch (err) {
717 	case USB_ERR_NORMAL_COMPLETION:
718 	case USB_ERR_SHORT_XFER:
719 	case USB_ERR_STALLED:
720 	case USB_ERR_CANCELLED:
721 		break;
722 	default:
723 		DPRINTF("error=%s - waiting a bit for TT cleanup\n",
724 		    usbd_errstr(err));
725 		usb_pause_mtx(mtx, hz / 16);
726 		break;
727 	}
728 	return ((usb_error_t)err);
729 }
730 
731 /*------------------------------------------------------------------------*
732  *	usbd_do_request_proc - factored out code
733  *
734  * This function is factored out code. It does basically the same like
735  * usbd_do_request_flags, except it will check the status of the
736  * passed process argument before doing the USB request. If the
737  * process is draining the USB_ERR_IOERROR code will be returned. It
738  * is assumed that the mutex associated with the process is locked
739  * when calling this function.
740  *------------------------------------------------------------------------*/
741 usb_error_t
742 usbd_do_request_proc(struct usb_device *udev, struct usb_process *pproc,
743     struct usb_device_request *req, void *data, uint16_t flags,
744     uint16_t *actlen, usb_timeout_t timeout)
745 {
746 	usb_error_t err;
747 	uint16_t len;
748 
749 	/* get request data length */
750 	len = UGETW(req->wLength);
751 
752 	/* check if the device is being detached */
753 	if (usb_proc_is_gone(pproc)) {
754 		err = USB_ERR_IOERROR;
755 		goto done;
756 	}
757 
758 	/* forward the USB request */
759 	err = usbd_do_request_flags(udev, pproc->up_mtx,
760 	    req, data, flags, actlen, timeout);
761 
762 done:
763 	/* on failure we zero the data */
764 	/* on short packet we zero the unused data */
765 	if ((len != 0) && (req->bmRequestType & UE_DIR_IN)) {
766 		if (err)
767 			memset(data, 0, len);
768 		else if (actlen && *actlen != len)
769 			memset(((uint8_t *)data) + *actlen, 0, len - *actlen);
770 	}
771 	return (err);
772 }
773 
774 /*------------------------------------------------------------------------*
775  *	usbd_req_reset_port
776  *
777  * This function will instruct a USB HUB to perform a reset sequence
778  * on the specified port number.
779  *
780  * Returns:
781  *    0: Success. The USB device should now be at address zero.
782  * Else: Failure. No USB device is present and the USB port should be
783  *       disabled.
784  *------------------------------------------------------------------------*/
785 usb_error_t
786 usbd_req_reset_port(struct usb_device *udev, struct mtx *mtx, uint8_t port)
787 {
788 	struct usb_port_status ps;
789 	usb_error_t err;
790 	uint16_t n;
791 	uint16_t status;
792 	uint16_t change;
793 
794 	DPRINTF("\n");
795 
796 	/* clear any leftover port reset changes first */
797 	usbd_req_clear_port_feature(
798 	    udev, mtx, port, UHF_C_PORT_RESET);
799 
800 	/* assert port reset on the given port */
801 	err = usbd_req_set_port_feature(
802 	    udev, mtx, port, UHF_PORT_RESET);
803 
804 	/* check for errors */
805 	if (err)
806 		goto done;
807 	n = 0;
808 	while (1) {
809 		/* wait for the device to recover from reset */
810 		usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_delay));
811 		n += usb_port_reset_delay;
812 		err = usbd_req_get_port_status(udev, mtx, &ps, port);
813 		if (err)
814 			goto done;
815 
816 		status = UGETW(ps.wPortStatus);
817 		change = UGETW(ps.wPortChange);
818 
819 		/* if the device disappeared, just give up */
820 		if (!(status & UPS_CURRENT_CONNECT_STATUS))
821 			goto done;
822 
823 		/* check if reset is complete */
824 		if (change & UPS_C_PORT_RESET)
825 			break;
826 
827 		/*
828 		 * Some Virtual Machines like VirtualBox 4.x fail to
829 		 * generate a port reset change event. Check if reset
830 		 * is no longer asserted.
831 		 */
832 		if (!(status & UPS_RESET))
833 			break;
834 
835 		/* check for timeout */
836 		if (n > 1000) {
837 			n = 0;
838 			break;
839 		}
840 	}
841 
842 	/* clear port reset first */
843 	err = usbd_req_clear_port_feature(
844 	    udev, mtx, port, UHF_C_PORT_RESET);
845 	if (err)
846 		goto done;
847 
848 	/* check for timeout */
849 	if (n == 0) {
850 		err = USB_ERR_TIMEOUT;
851 		goto done;
852 	}
853 	/* wait for the device to recover from reset */
854 	usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_recovery));
855 
856 done:
857 	DPRINTFN(2, "port %d reset returning error=%s\n",
858 	    port, usbd_errstr(err));
859 	return (err);
860 }
861 
862 /*------------------------------------------------------------------------*
863  *	usbd_req_warm_reset_port
864  *
865  * This function will instruct an USB HUB to perform a warm reset
866  * sequence on the specified port number. This kind of reset is not
867  * mandatory for LOW-, FULL- and HIGH-speed USB HUBs and is targeted
868  * for SUPER-speed USB HUBs.
869  *
870  * Returns:
871  *    0: Success. The USB device should now be available again.
872  * Else: Failure. No USB device is present and the USB port should be
873  *       disabled.
874  *------------------------------------------------------------------------*/
875 usb_error_t
876 usbd_req_warm_reset_port(struct usb_device *udev, struct mtx *mtx,
877     uint8_t port)
878 {
879 	struct usb_port_status ps;
880 	usb_error_t err;
881 	uint16_t n;
882 	uint16_t status;
883 	uint16_t change;
884 
885 	DPRINTF("\n");
886 
887 	err = usbd_req_get_port_status(udev, mtx, &ps, port);
888 	if (err)
889 		goto done;
890 
891 	status = UGETW(ps.wPortStatus);
892 
893 	switch (UPS_PORT_LINK_STATE_GET(status)) {
894 	case UPS_PORT_LS_U3:
895 	case UPS_PORT_LS_COMP_MODE:
896 	case UPS_PORT_LS_LOOPBACK:
897 	case UPS_PORT_LS_SS_INA:
898 		break;
899 	default:
900 		DPRINTF("Wrong state for warm reset\n");
901 		return (0);
902 	}
903 
904 	/* clear any leftover warm port reset changes first */
905 	usbd_req_clear_port_feature(udev, mtx,
906 	    port, UHF_C_BH_PORT_RESET);
907 
908 	/* set warm port reset */
909 	err = usbd_req_set_port_feature(udev, mtx,
910 	    port, UHF_BH_PORT_RESET);
911 	if (err)
912 		goto done;
913 
914 	n = 0;
915 	while (1) {
916 		/* wait for the device to recover from reset */
917 		usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_delay));
918 		n += usb_port_reset_delay;
919 		err = usbd_req_get_port_status(udev, mtx, &ps, port);
920 		if (err)
921 			goto done;
922 
923 		status = UGETW(ps.wPortStatus);
924 		change = UGETW(ps.wPortChange);
925 
926 		/* if the device disappeared, just give up */
927 		if (!(status & UPS_CURRENT_CONNECT_STATUS))
928 			goto done;
929 
930 		/* check if reset is complete */
931 		if (change & UPS_C_BH_PORT_RESET)
932 			break;
933 
934 		/* check for timeout */
935 		if (n > 1000) {
936 			n = 0;
937 			break;
938 		}
939 	}
940 
941 	/* clear port reset first */
942 	err = usbd_req_clear_port_feature(
943 	    udev, mtx, port, UHF_C_BH_PORT_RESET);
944 	if (err)
945 		goto done;
946 
947 	/* check for timeout */
948 	if (n == 0) {
949 		err = USB_ERR_TIMEOUT;
950 		goto done;
951 	}
952 	/* wait for the device to recover from reset */
953 	usb_pause_mtx(mtx, USB_MS_TO_TICKS(usb_port_reset_recovery));
954 
955 done:
956 	DPRINTFN(2, "port %d warm reset returning error=%s\n",
957 	    port, usbd_errstr(err));
958 	return (err);
959 }
960 
961 /*------------------------------------------------------------------------*
962  *	usbd_req_get_desc
963  *
964  * This function can be used to retrieve USB descriptors. It contains
965  * some additional logic like zeroing of missing descriptor bytes and
966  * retrying an USB descriptor in case of failure. The "min_len"
967  * argument specifies the minimum descriptor length. The "max_len"
968  * argument specifies the maximum descriptor length. If the real
969  * descriptor length is less than the minimum length the missing
970  * byte(s) will be zeroed. The type field, the second byte of the USB
971  * descriptor, will get forced to the correct type. If the "actlen"
972  * pointer is non-NULL, the actual length of the transfer will get
973  * stored in the 16-bit unsigned integer which it is pointing to. The
974  * first byte of the descriptor will not get updated. If the "actlen"
975  * pointer is NULL the first byte of the descriptor will get updated
976  * to reflect the actual length instead. If "min_len" is not equal to
977  * "max_len" then this function will try to retrive the beginning of
978  * the descriptor and base the maximum length on the first byte of the
979  * descriptor.
980  *
981  * Returns:
982  *    0: Success
983  * Else: Failure
984  *------------------------------------------------------------------------*/
985 usb_error_t
986 usbd_req_get_desc(struct usb_device *udev,
987     struct mtx *mtx, uint16_t *actlen, void *desc,
988     uint16_t min_len, uint16_t max_len,
989     uint16_t id, uint8_t type, uint8_t index,
990     uint8_t retries)
991 {
992 	struct usb_device_request req;
993 	uint8_t *buf = desc;
994 	usb_error_t err;
995 
996 	DPRINTFN(4, "id=%d, type=%d, index=%d, max_len=%d\n",
997 	    id, type, index, max_len);
998 
999 	req.bmRequestType = UT_READ_DEVICE;
1000 	req.bRequest = UR_GET_DESCRIPTOR;
1001 	USETW2(req.wValue, type, index);
1002 	USETW(req.wIndex, id);
1003 
1004 	while (1) {
1005 		if ((min_len < 2) || (max_len < 2)) {
1006 			err = USB_ERR_INVAL;
1007 			goto done;
1008 		}
1009 		USETW(req.wLength, min_len);
1010 
1011 		err = usbd_do_request_flags(udev, mtx, &req,
1012 		    desc, 0, NULL, 1000 /* ms */);
1013 
1014 		if (err != 0 && err != USB_ERR_TIMEOUT &&
1015 		    min_len != max_len) {
1016 			/* clear descriptor data */
1017 			memset(desc, 0, max_len);
1018 
1019 			/* try to read full descriptor length */
1020 			USETW(req.wLength, max_len);
1021 
1022 			err = usbd_do_request_flags(udev, mtx, &req,
1023 			    desc, USB_SHORT_XFER_OK, NULL, 1000 /* ms */);
1024 
1025 			if (err == 0) {
1026 				/* verify length */
1027 				if (buf[0] > max_len)
1028 					buf[0] = max_len;
1029 				else if (buf[0] < 2)
1030 					err = USB_ERR_INVAL;
1031 
1032 				min_len = buf[0];
1033 
1034 				/* enforce descriptor type */
1035 				buf[1] = type;
1036 				goto done;
1037 			}
1038 		}
1039 
1040 		if (err) {
1041 			if (!retries) {
1042 				goto done;
1043 			}
1044 			retries--;
1045 
1046 			usb_pause_mtx(mtx, hz / 5);
1047 
1048 			continue;
1049 		}
1050 
1051 		if (min_len == max_len) {
1052 			/* enforce correct length */
1053 			if ((buf[0] > min_len) && (actlen == NULL))
1054 				buf[0] = min_len;
1055 
1056 			/* enforce correct type */
1057 			buf[1] = type;
1058 
1059 			goto done;
1060 		}
1061 		/* range check */
1062 
1063 		if (max_len > buf[0]) {
1064 			max_len = buf[0];
1065 		}
1066 		/* zero minimum data */
1067 
1068 		while (min_len > max_len) {
1069 			min_len--;
1070 			buf[min_len] = 0;
1071 		}
1072 
1073 		/* set new minimum length */
1074 
1075 		min_len = max_len;
1076 	}
1077 done:
1078 	if (actlen != NULL) {
1079 		if (err)
1080 			*actlen = 0;
1081 		else
1082 			*actlen = min_len;
1083 	}
1084 	return (err);
1085 }
1086 
1087 /*------------------------------------------------------------------------*
1088  *	usbd_req_get_string_any
1089  *
1090  * This function will return the string given by "string_index"
1091  * using the first language ID. The maximum length "len" includes
1092  * the terminating zero. The "len" argument should be twice as
1093  * big pluss 2 bytes, compared with the actual maximum string length !
1094  *
1095  * Returns:
1096  *    0: Success
1097  * Else: Failure
1098  *------------------------------------------------------------------------*/
1099 usb_error_t
1100 usbd_req_get_string_any(struct usb_device *udev, struct mtx *mtx, char *buf,
1101     uint16_t len, uint8_t string_index)
1102 {
1103 	char *s;
1104 	uint8_t *temp;
1105 	uint16_t i;
1106 	uint16_t n;
1107 	uint16_t c;
1108 	uint8_t swap;
1109 	usb_error_t err;
1110 
1111 	if (len == 0) {
1112 		/* should not happen */
1113 		return (USB_ERR_NORMAL_COMPLETION);
1114 	}
1115 	if (string_index == 0) {
1116 		/* this is the language table */
1117 		buf[0] = 0;
1118 		return (USB_ERR_INVAL);
1119 	}
1120 	if (udev->flags.no_strings) {
1121 		buf[0] = 0;
1122 		return (USB_ERR_STALLED);
1123 	}
1124 	err = usbd_req_get_string_desc
1125 	    (udev, mtx, buf, len, udev->langid, string_index);
1126 	if (err) {
1127 		buf[0] = 0;
1128 		return (err);
1129 	}
1130 	temp = (uint8_t *)buf;
1131 
1132 	if (temp[0] < 2) {
1133 		/* string length is too short */
1134 		buf[0] = 0;
1135 		return (USB_ERR_INVAL);
1136 	}
1137 	/* reserve one byte for terminating zero */
1138 	len--;
1139 
1140 	/* find maximum length */
1141 	s = buf;
1142 	n = (temp[0] / 2) - 1;
1143 	if (n > len) {
1144 		n = len;
1145 	}
1146 	/* skip descriptor header */
1147 	temp += 2;
1148 
1149 	/* reset swap state */
1150 	swap = 3;
1151 
1152 	/* convert and filter */
1153 	for (i = 0; (i != n); i++) {
1154 		c = UGETW(temp + (2 * i));
1155 
1156 		/* convert from Unicode, handle buggy strings */
1157 		if (((c & 0xff00) == 0) && (swap & 1)) {
1158 			/* Little Endian, default */
1159 			*s = c;
1160 			swap = 1;
1161 		} else if (((c & 0x00ff) == 0) && (swap & 2)) {
1162 			/* Big Endian */
1163 			*s = c >> 8;
1164 			swap = 2;
1165 		} else {
1166 			/* silently skip bad character */
1167 			continue;
1168 		}
1169 
1170 		/*
1171 		 * Filter by default - We only allow alphanumerical
1172 		 * and a few more to avoid any problems with scripts
1173 		 * and daemons.
1174 		 */
1175 		if (isalpha(*s) ||
1176 		    isdigit(*s) ||
1177 		    *s == '-' ||
1178 		    *s == '+' ||
1179 		    *s == ' ' ||
1180 		    *s == '.' ||
1181 		    *s == ',' ||
1182 		    *s == ':' ||
1183 		    *s == '/' ||
1184 		    *s == '(' ||
1185 		    *s == ')') {
1186 			/* allowed */
1187 			s++;
1188 		}
1189 		/* silently skip bad character */
1190 	}
1191 	*s = 0;				/* zero terminate resulting string */
1192 	return (USB_ERR_NORMAL_COMPLETION);
1193 }
1194 
1195 /*------------------------------------------------------------------------*
1196  *	usbd_req_get_string_desc
1197  *
1198  * If you don't know the language ID, consider using
1199  * "usbd_req_get_string_any()".
1200  *
1201  * Returns:
1202  *    0: Success
1203  * Else: Failure
1204  *------------------------------------------------------------------------*/
1205 usb_error_t
1206 usbd_req_get_string_desc(struct usb_device *udev, struct mtx *mtx, void *sdesc,
1207     uint16_t max_len, uint16_t lang_id,
1208     uint8_t string_index)
1209 {
1210 	return (usbd_req_get_desc(udev, mtx, NULL, sdesc, 2, max_len, lang_id,
1211 	    UDESC_STRING, string_index, 0));
1212 }
1213 
1214 /*------------------------------------------------------------------------*
1215  *	usbd_req_get_config_desc_ptr
1216  *
1217  * This function is used in device side mode to retrieve the pointer
1218  * to the generated config descriptor. This saves allocating space for
1219  * an additional config descriptor when setting the configuration.
1220  *
1221  * Returns:
1222  *    0: Success
1223  * Else: Failure
1224  *------------------------------------------------------------------------*/
1225 usb_error_t
1226 usbd_req_get_descriptor_ptr(struct usb_device *udev,
1227     struct usb_config_descriptor **ppcd, uint16_t wValue)
1228 {
1229 	struct usb_device_request req;
1230 	usb_handle_req_t *hr_func;
1231 	const void *ptr;
1232 	uint16_t len;
1233 	usb_error_t err;
1234 
1235 	req.bmRequestType = UT_READ_DEVICE;
1236 	req.bRequest = UR_GET_DESCRIPTOR;
1237 	USETW(req.wValue, wValue);
1238 	USETW(req.wIndex, 0);
1239 	USETW(req.wLength, 0);
1240 
1241 	ptr = NULL;
1242 	len = 0;
1243 
1244 	hr_func = usbd_get_hr_func(udev);
1245 
1246 	if (hr_func == NULL)
1247 		err = USB_ERR_INVAL;
1248 	else {
1249 		USB_BUS_LOCK(udev->bus);
1250 		err = (hr_func) (udev, &req, &ptr, &len);
1251 		USB_BUS_UNLOCK(udev->bus);
1252 	}
1253 
1254 	if (err)
1255 		ptr = NULL;
1256 	else if (ptr == NULL)
1257 		err = USB_ERR_INVAL;
1258 
1259 	*ppcd = __DECONST(struct usb_config_descriptor *, ptr);
1260 
1261 	return (err);
1262 }
1263 
1264 /*------------------------------------------------------------------------*
1265  *	usbd_req_get_config_desc
1266  *
1267  * Returns:
1268  *    0: Success
1269  * Else: Failure
1270  *------------------------------------------------------------------------*/
1271 usb_error_t
1272 usbd_req_get_config_desc(struct usb_device *udev, struct mtx *mtx,
1273     struct usb_config_descriptor *d, uint8_t conf_index)
1274 {
1275 	usb_error_t err;
1276 
1277 	DPRINTFN(4, "confidx=%d\n", conf_index);
1278 
1279 	err = usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
1280 	    sizeof(*d), 0, UDESC_CONFIG, conf_index, 0);
1281 	if (err) {
1282 		goto done;
1283 	}
1284 	/* Extra sanity checking */
1285 	if (UGETW(d->wTotalLength) < (uint16_t)sizeof(*d)) {
1286 		err = USB_ERR_INVAL;
1287 	}
1288 done:
1289 	return (err);
1290 }
1291 
1292 /*------------------------------------------------------------------------*
1293  *	usbd_alloc_config_desc
1294  *
1295  * This function is used to allocate a zeroed configuration
1296  * descriptor.
1297  *
1298  * Returns:
1299  * NULL: Failure
1300  * Else: Success
1301  *------------------------------------------------------------------------*/
1302 void *
1303 usbd_alloc_config_desc(struct usb_device *udev, uint32_t size)
1304 {
1305 	if (size > USB_CONFIG_MAX) {
1306 		DPRINTF("Configuration descriptor too big\n");
1307 		return (NULL);
1308 	}
1309 #if (USB_HAVE_FIXED_CONFIG == 0)
1310 	return (malloc(size, M_USBDEV, M_ZERO | M_WAITOK));
1311 #else
1312 	memset(udev->config_data, 0, sizeof(udev->config_data));
1313 	return (udev->config_data);
1314 #endif
1315 }
1316 
1317 /*------------------------------------------------------------------------*
1318  *	usbd_alloc_config_desc
1319  *
1320  * This function is used to free a configuration descriptor.
1321  *------------------------------------------------------------------------*/
1322 void
1323 usbd_free_config_desc(struct usb_device *udev, void *ptr)
1324 {
1325 #if (USB_HAVE_FIXED_CONFIG == 0)
1326 	free(ptr, M_USBDEV);
1327 #endif
1328 }
1329 
1330 /*------------------------------------------------------------------------*
1331  *	usbd_req_get_config_desc_full
1332  *
1333  * This function gets the complete USB configuration descriptor and
1334  * ensures that "wTotalLength" is correct. The returned configuration
1335  * descriptor is freed by calling "usbd_free_config_desc()".
1336  *
1337  * Returns:
1338  *    0: Success
1339  * Else: Failure
1340  *------------------------------------------------------------------------*/
1341 usb_error_t
1342 usbd_req_get_config_desc_full(struct usb_device *udev, struct mtx *mtx,
1343     struct usb_config_descriptor **ppcd, uint8_t index)
1344 {
1345 	struct usb_config_descriptor cd;
1346 	struct usb_config_descriptor *cdesc;
1347 	uint32_t len;
1348 	usb_error_t err;
1349 
1350 	DPRINTFN(4, "index=%d\n", index);
1351 
1352 	*ppcd = NULL;
1353 
1354 	err = usbd_req_get_config_desc(udev, mtx, &cd, index);
1355 	if (err)
1356 		return (err);
1357 
1358 	/* get full descriptor */
1359 	len = UGETW(cd.wTotalLength);
1360 	if (len < (uint32_t)sizeof(*cdesc)) {
1361 		/* corrupt descriptor */
1362 		return (USB_ERR_INVAL);
1363 	} else if (len > USB_CONFIG_MAX) {
1364 		DPRINTF("Configuration descriptor was truncated\n");
1365 		len = USB_CONFIG_MAX;
1366 	}
1367 	cdesc = usbd_alloc_config_desc(udev, len);
1368 	if (cdesc == NULL)
1369 		return (USB_ERR_NOMEM);
1370 	err = usbd_req_get_desc(udev, mtx, NULL, cdesc, len, len, 0,
1371 	    UDESC_CONFIG, index, 3);
1372 	if (err) {
1373 		usbd_free_config_desc(udev, cdesc);
1374 		return (err);
1375 	}
1376 	/* make sure that the device is not fooling us: */
1377 	USETW(cdesc->wTotalLength, len);
1378 
1379 	*ppcd = cdesc;
1380 
1381 	return (0);			/* success */
1382 }
1383 
1384 /*------------------------------------------------------------------------*
1385  *	usbd_req_get_device_desc
1386  *
1387  * Returns:
1388  *    0: Success
1389  * Else: Failure
1390  *------------------------------------------------------------------------*/
1391 usb_error_t
1392 usbd_req_get_device_desc(struct usb_device *udev, struct mtx *mtx,
1393     struct usb_device_descriptor *d)
1394 {
1395 	DPRINTFN(4, "\n");
1396 	return (usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
1397 	    sizeof(*d), 0, UDESC_DEVICE, 0, 3));
1398 }
1399 
1400 /*------------------------------------------------------------------------*
1401  *	usbd_req_get_alt_interface_no
1402  *
1403  * Returns:
1404  *    0: Success
1405  * Else: Failure
1406  *------------------------------------------------------------------------*/
1407 usb_error_t
1408 usbd_req_get_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1409     uint8_t *alt_iface_no, uint8_t iface_index)
1410 {
1411 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1412 	struct usb_device_request req;
1413 
1414 	if ((iface == NULL) || (iface->idesc == NULL))
1415 		return (USB_ERR_INVAL);
1416 
1417 	req.bmRequestType = UT_READ_INTERFACE;
1418 	req.bRequest = UR_GET_INTERFACE;
1419 	USETW(req.wValue, 0);
1420 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1421 	req.wIndex[1] = 0;
1422 	USETW(req.wLength, 1);
1423 	return (usbd_do_request(udev, mtx, &req, alt_iface_no));
1424 }
1425 
1426 /*------------------------------------------------------------------------*
1427  *	usbd_req_set_alt_interface_no
1428  *
1429  * Returns:
1430  *    0: Success
1431  * Else: Failure
1432  *------------------------------------------------------------------------*/
1433 usb_error_t
1434 usbd_req_set_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1435     uint8_t iface_index, uint8_t alt_no)
1436 {
1437 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1438 	struct usb_device_request req;
1439 
1440 	if ((iface == NULL) || (iface->idesc == NULL))
1441 		return (USB_ERR_INVAL);
1442 
1443 	req.bmRequestType = UT_WRITE_INTERFACE;
1444 	req.bRequest = UR_SET_INTERFACE;
1445 	req.wValue[0] = alt_no;
1446 	req.wValue[1] = 0;
1447 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1448 	req.wIndex[1] = 0;
1449 	USETW(req.wLength, 0);
1450 	return (usbd_do_request(udev, mtx, &req, 0));
1451 }
1452 
1453 /*------------------------------------------------------------------------*
1454  *	usbd_req_get_device_status
1455  *
1456  * Returns:
1457  *    0: Success
1458  * Else: Failure
1459  *------------------------------------------------------------------------*/
1460 usb_error_t
1461 usbd_req_get_device_status(struct usb_device *udev, struct mtx *mtx,
1462     struct usb_status *st)
1463 {
1464 	struct usb_device_request req;
1465 
1466 	req.bmRequestType = UT_READ_DEVICE;
1467 	req.bRequest = UR_GET_STATUS;
1468 	USETW(req.wValue, 0);
1469 	USETW(req.wIndex, 0);
1470 	USETW(req.wLength, sizeof(*st));
1471 	return (usbd_do_request(udev, mtx, &req, st));
1472 }
1473 
1474 /*------------------------------------------------------------------------*
1475  *	usbd_req_get_hub_descriptor
1476  *
1477  * Returns:
1478  *    0: Success
1479  * Else: Failure
1480  *------------------------------------------------------------------------*/
1481 usb_error_t
1482 usbd_req_get_hub_descriptor(struct usb_device *udev, struct mtx *mtx,
1483     struct usb_hub_descriptor *hd, uint8_t nports)
1484 {
1485 	struct usb_device_request req;
1486 	uint16_t len = (nports + 7 + (8 * 8)) / 8;
1487 
1488 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1489 	req.bRequest = UR_GET_DESCRIPTOR;
1490 	USETW2(req.wValue, UDESC_HUB, 0);
1491 	USETW(req.wIndex, 0);
1492 	USETW(req.wLength, len);
1493 	return (usbd_do_request(udev, mtx, &req, hd));
1494 }
1495 
1496 /*------------------------------------------------------------------------*
1497  *	usbd_req_get_ss_hub_descriptor
1498  *
1499  * Returns:
1500  *    0: Success
1501  * Else: Failure
1502  *------------------------------------------------------------------------*/
1503 usb_error_t
1504 usbd_req_get_ss_hub_descriptor(struct usb_device *udev, struct mtx *mtx,
1505     struct usb_hub_ss_descriptor *hd, uint8_t nports)
1506 {
1507 	struct usb_device_request req;
1508 	uint16_t len = sizeof(*hd) - 32 + 1 + ((nports + 7) / 8);
1509 
1510 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1511 	req.bRequest = UR_GET_DESCRIPTOR;
1512 	USETW2(req.wValue, UDESC_SS_HUB, 0);
1513 	USETW(req.wIndex, 0);
1514 	USETW(req.wLength, len);
1515 	return (usbd_do_request(udev, mtx, &req, hd));
1516 }
1517 
1518 /*------------------------------------------------------------------------*
1519  *	usbd_req_get_hub_status
1520  *
1521  * Returns:
1522  *    0: Success
1523  * Else: Failure
1524  *------------------------------------------------------------------------*/
1525 usb_error_t
1526 usbd_req_get_hub_status(struct usb_device *udev, struct mtx *mtx,
1527     struct usb_hub_status *st)
1528 {
1529 	struct usb_device_request req;
1530 
1531 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1532 	req.bRequest = UR_GET_STATUS;
1533 	USETW(req.wValue, 0);
1534 	USETW(req.wIndex, 0);
1535 	USETW(req.wLength, sizeof(struct usb_hub_status));
1536 	return (usbd_do_request(udev, mtx, &req, st));
1537 }
1538 
1539 /*------------------------------------------------------------------------*
1540  *	usbd_req_set_address
1541  *
1542  * This function is used to set the address for an USB device. After
1543  * port reset the USB device will respond at address zero.
1544  *
1545  * Returns:
1546  *    0: Success
1547  * Else: Failure
1548  *------------------------------------------------------------------------*/
1549 usb_error_t
1550 usbd_req_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t addr)
1551 {
1552 	struct usb_device_request req;
1553 	usb_error_t err;
1554 
1555 	DPRINTFN(6, "setting device address=%d\n", addr);
1556 
1557 	req.bmRequestType = UT_WRITE_DEVICE;
1558 	req.bRequest = UR_SET_ADDRESS;
1559 	USETW(req.wValue, addr);
1560 	USETW(req.wIndex, 0);
1561 	USETW(req.wLength, 0);
1562 
1563 	err = USB_ERR_INVAL;
1564 
1565 	/* check if USB controller handles set address */
1566 	if (udev->bus->methods->set_address != NULL)
1567 		err = (udev->bus->methods->set_address) (udev, mtx, addr);
1568 
1569 	if (err != USB_ERR_INVAL)
1570 		goto done;
1571 
1572 	/* Setting the address should not take more than 1 second ! */
1573 	err = usbd_do_request_flags(udev, mtx, &req, NULL,
1574 	    USB_DELAY_STATUS_STAGE, NULL, 1000);
1575 
1576 done:
1577 	/* allow device time to set new address */
1578 	usb_pause_mtx(mtx,
1579 	    USB_MS_TO_TICKS(usb_set_address_settle));
1580 
1581 	return (err);
1582 }
1583 
1584 /*------------------------------------------------------------------------*
1585  *	usbd_req_get_port_status
1586  *
1587  * Returns:
1588  *    0: Success
1589  * Else: Failure
1590  *------------------------------------------------------------------------*/
1591 usb_error_t
1592 usbd_req_get_port_status(struct usb_device *udev, struct mtx *mtx,
1593     struct usb_port_status *ps, uint8_t port)
1594 {
1595 	struct usb_device_request req;
1596 
1597 	req.bmRequestType = UT_READ_CLASS_OTHER;
1598 	req.bRequest = UR_GET_STATUS;
1599 	USETW(req.wValue, 0);
1600 	req.wIndex[0] = port;
1601 	req.wIndex[1] = 0;
1602 	USETW(req.wLength, sizeof(*ps));
1603 
1604 	return (usbd_do_request_flags(udev, mtx, &req, ps, 0, NULL, 1000));
1605 }
1606 
1607 /*------------------------------------------------------------------------*
1608  *	usbd_req_clear_hub_feature
1609  *
1610  * Returns:
1611  *    0: Success
1612  * Else: Failure
1613  *------------------------------------------------------------------------*/
1614 usb_error_t
1615 usbd_req_clear_hub_feature(struct usb_device *udev, struct mtx *mtx,
1616     uint16_t sel)
1617 {
1618 	struct usb_device_request req;
1619 
1620 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1621 	req.bRequest = UR_CLEAR_FEATURE;
1622 	USETW(req.wValue, sel);
1623 	USETW(req.wIndex, 0);
1624 	USETW(req.wLength, 0);
1625 	return (usbd_do_request(udev, mtx, &req, 0));
1626 }
1627 
1628 /*------------------------------------------------------------------------*
1629  *	usbd_req_set_hub_feature
1630  *
1631  * Returns:
1632  *    0: Success
1633  * Else: Failure
1634  *------------------------------------------------------------------------*/
1635 usb_error_t
1636 usbd_req_set_hub_feature(struct usb_device *udev, struct mtx *mtx,
1637     uint16_t sel)
1638 {
1639 	struct usb_device_request req;
1640 
1641 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1642 	req.bRequest = UR_SET_FEATURE;
1643 	USETW(req.wValue, sel);
1644 	USETW(req.wIndex, 0);
1645 	USETW(req.wLength, 0);
1646 	return (usbd_do_request(udev, mtx, &req, 0));
1647 }
1648 
1649 /*------------------------------------------------------------------------*
1650  *	usbd_req_set_hub_u1_timeout
1651  *
1652  * Returns:
1653  *    0: Success
1654  * Else: Failure
1655  *------------------------------------------------------------------------*/
1656 usb_error_t
1657 usbd_req_set_hub_u1_timeout(struct usb_device *udev, struct mtx *mtx,
1658     uint8_t port, uint8_t timeout)
1659 {
1660 	struct usb_device_request req;
1661 
1662 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1663 	req.bRequest = UR_SET_FEATURE;
1664 	USETW(req.wValue, UHF_PORT_U1_TIMEOUT);
1665 	req.wIndex[0] = port;
1666 	req.wIndex[1] = timeout;
1667 	USETW(req.wLength, 0);
1668 	return (usbd_do_request(udev, mtx, &req, 0));
1669 }
1670 
1671 /*------------------------------------------------------------------------*
1672  *	usbd_req_set_hub_u2_timeout
1673  *
1674  * Returns:
1675  *    0: Success
1676  * Else: Failure
1677  *------------------------------------------------------------------------*/
1678 usb_error_t
1679 usbd_req_set_hub_u2_timeout(struct usb_device *udev, struct mtx *mtx,
1680     uint8_t port, uint8_t timeout)
1681 {
1682 	struct usb_device_request req;
1683 
1684 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1685 	req.bRequest = UR_SET_FEATURE;
1686 	USETW(req.wValue, UHF_PORT_U2_TIMEOUT);
1687 	req.wIndex[0] = port;
1688 	req.wIndex[1] = timeout;
1689 	USETW(req.wLength, 0);
1690 	return (usbd_do_request(udev, mtx, &req, 0));
1691 }
1692 
1693 /*------------------------------------------------------------------------*
1694  *	usbd_req_set_hub_depth
1695  *
1696  * Returns:
1697  *    0: Success
1698  * Else: Failure
1699  *------------------------------------------------------------------------*/
1700 usb_error_t
1701 usbd_req_set_hub_depth(struct usb_device *udev, struct mtx *mtx,
1702     uint16_t depth)
1703 {
1704 	struct usb_device_request req;
1705 
1706 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1707 	req.bRequest = UR_SET_HUB_DEPTH;
1708 	USETW(req.wValue, depth);
1709 	USETW(req.wIndex, 0);
1710 	USETW(req.wLength, 0);
1711 	return (usbd_do_request(udev, mtx, &req, 0));
1712 }
1713 
1714 /*------------------------------------------------------------------------*
1715  *	usbd_req_clear_port_feature
1716  *
1717  * Returns:
1718  *    0: Success
1719  * Else: Failure
1720  *------------------------------------------------------------------------*/
1721 usb_error_t
1722 usbd_req_clear_port_feature(struct usb_device *udev, struct mtx *mtx,
1723     uint8_t port, uint16_t sel)
1724 {
1725 	struct usb_device_request req;
1726 
1727 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1728 	req.bRequest = UR_CLEAR_FEATURE;
1729 	USETW(req.wValue, sel);
1730 	req.wIndex[0] = port;
1731 	req.wIndex[1] = 0;
1732 	USETW(req.wLength, 0);
1733 	return (usbd_do_request(udev, mtx, &req, 0));
1734 }
1735 
1736 /*------------------------------------------------------------------------*
1737  *	usbd_req_set_port_feature
1738  *
1739  * Returns:
1740  *    0: Success
1741  * Else: Failure
1742  *------------------------------------------------------------------------*/
1743 usb_error_t
1744 usbd_req_set_port_feature(struct usb_device *udev, struct mtx *mtx,
1745     uint8_t port, uint16_t sel)
1746 {
1747 	struct usb_device_request req;
1748 
1749 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1750 	req.bRequest = UR_SET_FEATURE;
1751 	USETW(req.wValue, sel);
1752 	req.wIndex[0] = port;
1753 	req.wIndex[1] = 0;
1754 	USETW(req.wLength, 0);
1755 	return (usbd_do_request(udev, mtx, &req, 0));
1756 }
1757 
1758 /*------------------------------------------------------------------------*
1759  *	usbd_req_set_protocol
1760  *
1761  * Returns:
1762  *    0: Success
1763  * Else: Failure
1764  *------------------------------------------------------------------------*/
1765 usb_error_t
1766 usbd_req_set_protocol(struct usb_device *udev, struct mtx *mtx,
1767     uint8_t iface_index, uint16_t report)
1768 {
1769 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1770 	struct usb_device_request req;
1771 
1772 	if ((iface == NULL) || (iface->idesc == NULL)) {
1773 		return (USB_ERR_INVAL);
1774 	}
1775 	DPRINTFN(5, "iface=%p, report=%d, endpt=%d\n",
1776 	    iface, report, iface->idesc->bInterfaceNumber);
1777 
1778 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1779 	req.bRequest = UR_SET_PROTOCOL;
1780 	USETW(req.wValue, report);
1781 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1782 	req.wIndex[1] = 0;
1783 	USETW(req.wLength, 0);
1784 	return (usbd_do_request(udev, mtx, &req, 0));
1785 }
1786 
1787 /*------------------------------------------------------------------------*
1788  *	usbd_req_set_report
1789  *
1790  * Returns:
1791  *    0: Success
1792  * Else: Failure
1793  *------------------------------------------------------------------------*/
1794 usb_error_t
1795 usbd_req_set_report(struct usb_device *udev, struct mtx *mtx, void *data, uint16_t len,
1796     uint8_t iface_index, uint8_t type, uint8_t id)
1797 {
1798 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1799 	struct usb_device_request req;
1800 
1801 	if ((iface == NULL) || (iface->idesc == NULL)) {
1802 		return (USB_ERR_INVAL);
1803 	}
1804 	DPRINTFN(5, "len=%d\n", len);
1805 
1806 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1807 	req.bRequest = UR_SET_REPORT;
1808 	USETW2(req.wValue, type, id);
1809 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1810 	req.wIndex[1] = 0;
1811 	USETW(req.wLength, len);
1812 	return (usbd_do_request(udev, mtx, &req, data));
1813 }
1814 
1815 /*------------------------------------------------------------------------*
1816  *	usbd_req_get_report
1817  *
1818  * Returns:
1819  *    0: Success
1820  * Else: Failure
1821  *------------------------------------------------------------------------*/
1822 usb_error_t
1823 usbd_req_get_report(struct usb_device *udev, struct mtx *mtx, void *data,
1824     uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id)
1825 {
1826 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1827 	struct usb_device_request req;
1828 
1829 	if ((iface == NULL) || (iface->idesc == NULL)) {
1830 		return (USB_ERR_INVAL);
1831 	}
1832 	DPRINTFN(5, "len=%d\n", len);
1833 
1834 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1835 	req.bRequest = UR_GET_REPORT;
1836 	USETW2(req.wValue, type, id);
1837 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1838 	req.wIndex[1] = 0;
1839 	USETW(req.wLength, len);
1840 	return (usbd_do_request(udev, mtx, &req, data));
1841 }
1842 
1843 /*------------------------------------------------------------------------*
1844  *	usbd_req_set_idle
1845  *
1846  * Returns:
1847  *    0: Success
1848  * Else: Failure
1849  *------------------------------------------------------------------------*/
1850 usb_error_t
1851 usbd_req_set_idle(struct usb_device *udev, struct mtx *mtx,
1852     uint8_t iface_index, uint8_t duration, uint8_t id)
1853 {
1854 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1855 	struct usb_device_request req;
1856 
1857 	if ((iface == NULL) || (iface->idesc == NULL)) {
1858 		return (USB_ERR_INVAL);
1859 	}
1860 	DPRINTFN(5, "%d %d\n", duration, id);
1861 
1862 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1863 	req.bRequest = UR_SET_IDLE;
1864 	USETW2(req.wValue, duration, id);
1865 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1866 	req.wIndex[1] = 0;
1867 	USETW(req.wLength, 0);
1868 	return (usbd_do_request(udev, mtx, &req, 0));
1869 }
1870 
1871 /*------------------------------------------------------------------------*
1872  *	usbd_req_get_report_descriptor
1873  *
1874  * Returns:
1875  *    0: Success
1876  * Else: Failure
1877  *------------------------------------------------------------------------*/
1878 usb_error_t
1879 usbd_req_get_report_descriptor(struct usb_device *udev, struct mtx *mtx,
1880     void *d, uint16_t size, uint8_t iface_index)
1881 {
1882 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1883 	struct usb_device_request req;
1884 
1885 	if ((iface == NULL) || (iface->idesc == NULL)) {
1886 		return (USB_ERR_INVAL);
1887 	}
1888 	req.bmRequestType = UT_READ_INTERFACE;
1889 	req.bRequest = UR_GET_DESCRIPTOR;
1890 	USETW2(req.wValue, UDESC_REPORT, 0);	/* report id should be 0 */
1891 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1892 	req.wIndex[1] = 0;
1893 	USETW(req.wLength, size);
1894 	return (usbd_do_request(udev, mtx, &req, d));
1895 }
1896 
1897 /*------------------------------------------------------------------------*
1898  *	usbd_req_set_config
1899  *
1900  * This function is used to select the current configuration number in
1901  * both USB device side mode and USB host side mode. When setting the
1902  * configuration the function of the interfaces can change.
1903  *
1904  * Returns:
1905  *    0: Success
1906  * Else: Failure
1907  *------------------------------------------------------------------------*/
1908 usb_error_t
1909 usbd_req_set_config(struct usb_device *udev, struct mtx *mtx, uint8_t conf)
1910 {
1911 	struct usb_device_request req;
1912 
1913 	DPRINTF("setting config %d\n", conf);
1914 
1915 	/* do "set configuration" request */
1916 
1917 	req.bmRequestType = UT_WRITE_DEVICE;
1918 	req.bRequest = UR_SET_CONFIG;
1919 	req.wValue[0] = conf;
1920 	req.wValue[1] = 0;
1921 	USETW(req.wIndex, 0);
1922 	USETW(req.wLength, 0);
1923 	return (usbd_do_request(udev, mtx, &req, 0));
1924 }
1925 
1926 /*------------------------------------------------------------------------*
1927  *	usbd_req_get_config
1928  *
1929  * Returns:
1930  *    0: Success
1931  * Else: Failure
1932  *------------------------------------------------------------------------*/
1933 usb_error_t
1934 usbd_req_get_config(struct usb_device *udev, struct mtx *mtx, uint8_t *pconf)
1935 {
1936 	struct usb_device_request req;
1937 
1938 	req.bmRequestType = UT_READ_DEVICE;
1939 	req.bRequest = UR_GET_CONFIG;
1940 	USETW(req.wValue, 0);
1941 	USETW(req.wIndex, 0);
1942 	USETW(req.wLength, 1);
1943 	return (usbd_do_request(udev, mtx, &req, pconf));
1944 }
1945 
1946 /*------------------------------------------------------------------------*
1947  *	usbd_setup_device_desc
1948  *------------------------------------------------------------------------*/
1949 usb_error_t
1950 usbd_setup_device_desc(struct usb_device *udev, struct mtx *mtx)
1951 {
1952 	usb_error_t err;
1953 
1954 	/*
1955 	 * Get the first 8 bytes of the device descriptor !
1956 	 *
1957 	 * NOTE: "usbd_do_request()" will check the device descriptor
1958 	 * next time we do a request to see if the maximum packet size
1959 	 * changed! The 8 first bytes of the device descriptor
1960 	 * contains the maximum packet size to use on control endpoint
1961 	 * 0. If this value is different from "USB_MAX_IPACKET" a new
1962 	 * USB control request will be setup!
1963 	 */
1964 	switch (udev->speed) {
1965 	case USB_SPEED_FULL:
1966 		if (usb_full_ddesc != 0) {
1967 			/* get full device descriptor */
1968 			err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1969 			if (err == 0)
1970 				break;
1971 		}
1972 
1973 		/* get partial device descriptor, some devices crash on this */
1974 		err = usbd_req_get_desc(udev, mtx, NULL, &udev->ddesc,
1975 		    USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1976 		if (err != 0) {
1977 			DPRINTF("Trying fallback for getting the USB device descriptor\n");
1978 			/* try 8 bytes bMaxPacketSize */
1979 			udev->ddesc.bMaxPacketSize = 8;
1980 			/* get full device descriptor */
1981 			err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1982 			if (err == 0)
1983 				break;
1984 			/* try 16 bytes bMaxPacketSize */
1985 			udev->ddesc.bMaxPacketSize = 16;
1986 			/* get full device descriptor */
1987 			err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1988 			if (err == 0)
1989 				break;
1990 			/* try 32/64 bytes bMaxPacketSize */
1991 			udev->ddesc.bMaxPacketSize = 32;
1992 		}
1993 		/* get the full device descriptor */
1994 		err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1995 		break;
1996 
1997 	default:
1998 		DPRINTF("Minimum bMaxPacketSize is large enough "
1999 		    "to hold the complete device descriptor or "
2000 		    "only one bMaxPacketSize choice\n");
2001 
2002 		/* get the full device descriptor */
2003 		err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
2004 
2005 		/* try one more time, if error */
2006 		if (err != 0)
2007 			err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
2008 		break;
2009 	}
2010 
2011 	if (err != 0) {
2012 		DPRINTFN(0, "getting device descriptor "
2013 		    "at addr %d failed, %s\n", udev->address,
2014 		    usbd_errstr(err));
2015 		return (err);
2016 	}
2017 
2018 	DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
2019 	    "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
2020 	    udev->address, UGETW(udev->ddesc.bcdUSB),
2021 	    udev->ddesc.bDeviceClass,
2022 	    udev->ddesc.bDeviceSubClass,
2023 	    udev->ddesc.bDeviceProtocol,
2024 	    udev->ddesc.bMaxPacketSize,
2025 	    udev->ddesc.bLength,
2026 	    udev->speed);
2027 
2028 	return (err);
2029 }
2030 
2031 /*------------------------------------------------------------------------*
2032  *	usbd_req_re_enumerate
2033  *
2034  * NOTE: After this function returns the hardware is in the
2035  * unconfigured state! The application is responsible for setting a
2036  * new configuration.
2037  *
2038  * Returns:
2039  *    0: Success
2040  * Else: Failure
2041  *------------------------------------------------------------------------*/
2042 usb_error_t
2043 usbd_req_re_enumerate(struct usb_device *udev, struct mtx *mtx)
2044 {
2045 	struct usb_device *parent_hub;
2046 	usb_error_t err;
2047 	uint8_t old_addr;
2048 	uint8_t do_retry = 1;
2049 
2050 	if (udev->flags.usb_mode != USB_MODE_HOST) {
2051 		return (USB_ERR_INVAL);
2052 	}
2053 	old_addr = udev->address;
2054 	parent_hub = udev->parent_hub;
2055 	if (parent_hub == NULL) {
2056 		return (USB_ERR_INVAL);
2057 	}
2058 retry:
2059 #if USB_HAVE_TT_SUPPORT
2060 	/*
2061 	 * Try to reset the High Speed parent HUB of a LOW- or FULL-
2062 	 * speed device, if any.
2063 	 */
2064 	if (udev->parent_hs_hub != NULL &&
2065 	    udev->speed != USB_SPEED_HIGH) {
2066 		DPRINTF("Trying to reset parent High Speed TT.\n");
2067 		if (udev->parent_hs_hub == parent_hub &&
2068 		    (uhub_count_active_host_ports(parent_hub, USB_SPEED_LOW) +
2069 		     uhub_count_active_host_ports(parent_hub, USB_SPEED_FULL)) == 1) {
2070 			/* we can reset the whole TT */
2071 			err = usbd_req_reset_tt(parent_hub, NULL,
2072 			    udev->hs_port_no);
2073 		} else {
2074 			/* only reset a particular device and endpoint */
2075 			err = usbd_req_clear_tt_buffer(udev->parent_hs_hub, NULL,
2076 			    udev->hs_port_no, old_addr, UE_CONTROL, 0);
2077 		}
2078 		if (err) {
2079 			DPRINTF("Resetting parent High "
2080 			    "Speed TT failed (%s).\n",
2081 			    usbd_errstr(err));
2082 		}
2083 	}
2084 #endif
2085 	/* Try to warm reset first */
2086 	if (parent_hub->speed == USB_SPEED_SUPER)
2087 		usbd_req_warm_reset_port(parent_hub, mtx, udev->port_no);
2088 
2089 	/* Try to reset the parent HUB port. */
2090 	err = usbd_req_reset_port(parent_hub, mtx, udev->port_no);
2091 	if (err) {
2092 		DPRINTFN(0, "addr=%d, port reset failed, %s\n",
2093 		    old_addr, usbd_errstr(err));
2094 		goto done;
2095 	}
2096 
2097 	/*
2098 	 * After that the port has been reset our device should be at
2099 	 * address zero:
2100 	 */
2101 	udev->address = USB_START_ADDR;
2102 
2103 	/* reset "bMaxPacketSize" */
2104 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
2105 
2106 	/* reset USB state */
2107 	usb_set_device_state(udev, USB_STATE_POWERED);
2108 
2109 	/*
2110 	 * Restore device address:
2111 	 */
2112 	err = usbd_req_set_address(udev, mtx, old_addr);
2113 	if (err) {
2114 		/* XXX ignore any errors! */
2115 		DPRINTFN(0, "addr=%d, set address failed! (%s, ignored)\n",
2116 		    old_addr, usbd_errstr(err));
2117 	}
2118 	/*
2119 	 * Restore device address, if the controller driver did not
2120 	 * set a new one:
2121 	 */
2122 	if (udev->address == USB_START_ADDR)
2123 		udev->address = old_addr;
2124 
2125 	/* setup the device descriptor and the initial "wMaxPacketSize" */
2126 	err = usbd_setup_device_desc(udev, mtx);
2127 
2128 done:
2129 	if (err && do_retry) {
2130 		/* give the USB firmware some time to load */
2131 		usb_pause_mtx(mtx, hz / 2);
2132 		/* no more retries after this retry */
2133 		do_retry = 0;
2134 		/* try again */
2135 		goto retry;
2136 	}
2137 	/* restore address */
2138 	if (udev->address == USB_START_ADDR)
2139 		udev->address = old_addr;
2140 	/* update state, if successful */
2141 	if (err == 0)
2142 		usb_set_device_state(udev, USB_STATE_ADDRESSED);
2143 	return (err);
2144 }
2145 
2146 /*------------------------------------------------------------------------*
2147  *	usbd_req_clear_device_feature
2148  *
2149  * Returns:
2150  *    0: Success
2151  * Else: Failure
2152  *------------------------------------------------------------------------*/
2153 usb_error_t
2154 usbd_req_clear_device_feature(struct usb_device *udev, struct mtx *mtx,
2155     uint16_t sel)
2156 {
2157 	struct usb_device_request req;
2158 
2159 	req.bmRequestType = UT_WRITE_DEVICE;
2160 	req.bRequest = UR_CLEAR_FEATURE;
2161 	USETW(req.wValue, sel);
2162 	USETW(req.wIndex, 0);
2163 	USETW(req.wLength, 0);
2164 	return (usbd_do_request(udev, mtx, &req, 0));
2165 }
2166 
2167 /*------------------------------------------------------------------------*
2168  *	usbd_req_set_device_feature
2169  *
2170  * Returns:
2171  *    0: Success
2172  * Else: Failure
2173  *------------------------------------------------------------------------*/
2174 usb_error_t
2175 usbd_req_set_device_feature(struct usb_device *udev, struct mtx *mtx,
2176     uint16_t sel)
2177 {
2178 	struct usb_device_request req;
2179 
2180 	req.bmRequestType = UT_WRITE_DEVICE;
2181 	req.bRequest = UR_SET_FEATURE;
2182 	USETW(req.wValue, sel);
2183 	USETW(req.wIndex, 0);
2184 	USETW(req.wLength, 0);
2185 	return (usbd_do_request(udev, mtx, &req, 0));
2186 }
2187 
2188 /*------------------------------------------------------------------------*
2189  *	usbd_req_reset_tt
2190  *
2191  * Returns:
2192  *    0: Success
2193  * Else: Failure
2194  *------------------------------------------------------------------------*/
2195 usb_error_t
2196 usbd_req_reset_tt(struct usb_device *udev, struct mtx *mtx,
2197     uint8_t port)
2198 {
2199 	struct usb_device_request req;
2200 
2201 	/* For single TT HUBs the port should be 1 */
2202 
2203 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
2204 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
2205 		port = 1;
2206 
2207 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2208 	req.bRequest = UR_RESET_TT;
2209 	USETW(req.wValue, 0);
2210 	req.wIndex[0] = port;
2211 	req.wIndex[1] = 0;
2212 	USETW(req.wLength, 0);
2213 	return (usbd_do_request(udev, mtx, &req, 0));
2214 }
2215 
2216 /*------------------------------------------------------------------------*
2217  *	usbd_req_clear_tt_buffer
2218  *
2219  * For single TT HUBs the port should be 1.
2220  *
2221  * Returns:
2222  *    0: Success
2223  * Else: Failure
2224  *------------------------------------------------------------------------*/
2225 usb_error_t
2226 usbd_req_clear_tt_buffer(struct usb_device *udev, struct mtx *mtx,
2227     uint8_t port, uint8_t addr, uint8_t type, uint8_t endpoint)
2228 {
2229 	struct usb_device_request req;
2230 	uint16_t wValue;
2231 
2232 	/* For single TT HUBs the port should be 1 */
2233 
2234 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
2235 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
2236 		port = 1;
2237 
2238 	wValue = (endpoint & 0xF) | ((addr & 0x7F) << 4) |
2239 	    ((endpoint & 0x80) << 8) | ((type & 3) << 12);
2240 
2241 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2242 	req.bRequest = UR_CLEAR_TT_BUFFER;
2243 	USETW(req.wValue, wValue);
2244 	req.wIndex[0] = port;
2245 	req.wIndex[1] = 0;
2246 	USETW(req.wLength, 0);
2247 	return (usbd_do_request(udev, mtx, &req, 0));
2248 }
2249 
2250 /*------------------------------------------------------------------------*
2251  *	usbd_req_set_port_link_state
2252  *
2253  * USB 3.0 specific request
2254  *
2255  * Returns:
2256  *    0: Success
2257  * Else: Failure
2258  *------------------------------------------------------------------------*/
2259 usb_error_t
2260 usbd_req_set_port_link_state(struct usb_device *udev, struct mtx *mtx,
2261     uint8_t port, uint8_t link_state)
2262 {
2263 	struct usb_device_request req;
2264 
2265 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2266 	req.bRequest = UR_SET_FEATURE;
2267 	USETW(req.wValue, UHF_PORT_LINK_STATE);
2268 	req.wIndex[0] = port;
2269 	req.wIndex[1] = link_state;
2270 	USETW(req.wLength, 0);
2271 	return (usbd_do_request(udev, mtx, &req, 0));
2272 }
2273 
2274 /*------------------------------------------------------------------------*
2275  *		usbd_req_set_lpm_info
2276  *
2277  * USB 2.0 specific request for Link Power Management.
2278  *
2279  * Returns:
2280  * 0:				Success
2281  * USB_ERR_PENDING_REQUESTS:	NYET
2282  * USB_ERR_TIMEOUT:		TIMEOUT
2283  * USB_ERR_STALL:		STALL
2284  * Else:			Failure
2285  *------------------------------------------------------------------------*/
2286 usb_error_t
2287 usbd_req_set_lpm_info(struct usb_device *udev, struct mtx *mtx,
2288     uint8_t port, uint8_t besl, uint8_t addr, uint8_t rwe)
2289 {
2290 	struct usb_device_request req;
2291 	usb_error_t err;
2292 	uint8_t buf[1];
2293 
2294 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2295 	req.bRequest = UR_SET_AND_TEST;
2296 	USETW(req.wValue, UHF_PORT_L1);
2297 	req.wIndex[0] = (port & 0xF) | ((besl & 0xF) << 4);
2298 	req.wIndex[1] = (addr & 0x7F) | (rwe ? 0x80 : 0x00);
2299 	USETW(req.wLength, sizeof(buf));
2300 
2301 	/* set default value in case of short transfer */
2302 	buf[0] = 0x00;
2303 
2304 	err = usbd_do_request(udev, mtx, &req, buf);
2305 	if (err)
2306 		return (err);
2307 
2308 	switch (buf[0]) {
2309 	case 0x00:	/* SUCCESS */
2310 		break;
2311 	case 0x10:	/* NYET */
2312 		err = USB_ERR_PENDING_REQUESTS;
2313 		break;
2314 	case 0x11:	/* TIMEOUT */
2315 		err = USB_ERR_TIMEOUT;
2316 		break;
2317 	case 0x30:	/* STALL */
2318 		err = USB_ERR_STALLED;
2319 		break;
2320 	default:	/* reserved */
2321 		err = USB_ERR_IOERROR;
2322 		break;
2323 	}
2324 	return (err);
2325 }
2326