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