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