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