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