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