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