xref: /dragonfly/sys/bus/u4b/usb_request.c (revision 07a2f99c)
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 	err = usbd_req_get_desc(udev, lock, NULL, cdesc, len, len, 0,
1362 	    UDESC_CONFIG, index, 3);
1363 	if (err) {
1364 		kfree(cdesc, mtype);
1365 		return (err);
1366 	}
1367 	/* make sure that the device is not fooling us: */
1368 	USETW(cdesc->wTotalLength, len);
1369 
1370 	*ppcd = cdesc;
1371 
1372 	return (0);			/* success */
1373 }
1374 
1375 /*------------------------------------------------------------------------*
1376  *	usbd_req_get_device_desc
1377  *
1378  * Returns:
1379  *    0: Success
1380  * Else: Failure
1381  *------------------------------------------------------------------------*/
1382 usb_error_t
1383 usbd_req_get_device_desc(struct usb_device *udev, struct lock *lock,
1384     struct usb_device_descriptor *d)
1385 {
1386 	DPRINTFN(4, "\n");
1387 	return (usbd_req_get_desc(udev, lock, NULL, d, sizeof(*d),
1388 	    sizeof(*d), 0, UDESC_DEVICE, 0, 3));
1389 }
1390 
1391 /*------------------------------------------------------------------------*
1392  *	usbd_req_get_alt_interface_no
1393  *
1394  * Returns:
1395  *    0: Success
1396  * Else: Failure
1397  *------------------------------------------------------------------------*/
1398 usb_error_t
1399 usbd_req_get_alt_interface_no(struct usb_device *udev, struct lock *lock,
1400     uint8_t *alt_iface_no, uint8_t iface_index)
1401 {
1402 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1403 	struct usb_device_request req;
1404 
1405 	if ((iface == NULL) || (iface->idesc == NULL))
1406 		return (USB_ERR_INVAL);
1407 
1408 	req.bmRequestType = UT_READ_INTERFACE;
1409 	req.bRequest = UR_GET_INTERFACE;
1410 	USETW(req.wValue, 0);
1411 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1412 	req.wIndex[1] = 0;
1413 	USETW(req.wLength, 1);
1414 	return (usbd_do_request(udev, lock, &req, alt_iface_no));
1415 }
1416 
1417 /*------------------------------------------------------------------------*
1418  *	usbd_req_set_alt_interface_no
1419  *
1420  * Returns:
1421  *    0: Success
1422  * Else: Failure
1423  *------------------------------------------------------------------------*/
1424 usb_error_t
1425 usbd_req_set_alt_interface_no(struct usb_device *udev, struct lock *lock,
1426     uint8_t iface_index, uint8_t alt_no)
1427 {
1428 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1429 	struct usb_device_request req;
1430 
1431 	if ((iface == NULL) || (iface->idesc == NULL))
1432 		return (USB_ERR_INVAL);
1433 
1434 	req.bmRequestType = UT_WRITE_INTERFACE;
1435 	req.bRequest = UR_SET_INTERFACE;
1436 	req.wValue[0] = alt_no;
1437 	req.wValue[1] = 0;
1438 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1439 	req.wIndex[1] = 0;
1440 	USETW(req.wLength, 0);
1441 	return (usbd_do_request(udev, lock, &req, 0));
1442 }
1443 
1444 /*------------------------------------------------------------------------*
1445  *	usbd_req_get_device_status
1446  *
1447  * Returns:
1448  *    0: Success
1449  * Else: Failure
1450  *------------------------------------------------------------------------*/
1451 usb_error_t
1452 usbd_req_get_device_status(struct usb_device *udev, struct lock *lock,
1453     struct usb_status *st)
1454 {
1455 	struct usb_device_request req;
1456 
1457 	req.bmRequestType = UT_READ_DEVICE;
1458 	req.bRequest = UR_GET_STATUS;
1459 	USETW(req.wValue, 0);
1460 	USETW(req.wIndex, 0);
1461 	USETW(req.wLength, sizeof(*st));
1462 	return (usbd_do_request(udev, lock, &req, st));
1463 }
1464 
1465 /*------------------------------------------------------------------------*
1466  *	usbd_req_get_hub_descriptor
1467  *
1468  * Returns:
1469  *    0: Success
1470  * Else: Failure
1471  *------------------------------------------------------------------------*/
1472 usb_error_t
1473 usbd_req_get_hub_descriptor(struct usb_device *udev, struct lock *lock,
1474     struct usb_hub_descriptor *hd, uint8_t nports)
1475 {
1476 	struct usb_device_request req;
1477 	uint16_t len = (nports + 7 + (8 * 8)) / 8;
1478 
1479 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1480 	req.bRequest = UR_GET_DESCRIPTOR;
1481 	USETW2(req.wValue, UDESC_HUB, 0);
1482 	USETW(req.wIndex, 0);
1483 	USETW(req.wLength, len);
1484 	return (usbd_do_request(udev, lock, &req, hd));
1485 }
1486 
1487 /*------------------------------------------------------------------------*
1488  *	usbd_req_get_ss_hub_descriptor
1489  *
1490  * Returns:
1491  *    0: Success
1492  * Else: Failure
1493  *------------------------------------------------------------------------*/
1494 usb_error_t
1495 usbd_req_get_ss_hub_descriptor(struct usb_device *udev, struct lock *lock,
1496     struct usb_hub_ss_descriptor *hd, uint8_t nports)
1497 {
1498 	struct usb_device_request req;
1499 	uint16_t len = sizeof(*hd) - 32 + 1 + ((nports + 7) / 8);
1500 
1501 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1502 	req.bRequest = UR_GET_DESCRIPTOR;
1503 	USETW2(req.wValue, UDESC_SS_HUB, 0);
1504 	USETW(req.wIndex, 0);
1505 	USETW(req.wLength, len);
1506 	return (usbd_do_request(udev, lock, &req, hd));
1507 }
1508 
1509 /*------------------------------------------------------------------------*
1510  *	usbd_req_get_hub_status
1511  *
1512  * Returns:
1513  *    0: Success
1514  * Else: Failure
1515  *------------------------------------------------------------------------*/
1516 usb_error_t
1517 usbd_req_get_hub_status(struct usb_device *udev, struct lock *lock,
1518     struct usb_hub_status *st)
1519 {
1520 	struct usb_device_request req;
1521 
1522 	req.bmRequestType = UT_READ_CLASS_DEVICE;
1523 	req.bRequest = UR_GET_STATUS;
1524 	USETW(req.wValue, 0);
1525 	USETW(req.wIndex, 0);
1526 	USETW(req.wLength, sizeof(struct usb_hub_status));
1527 	return (usbd_do_request(udev, lock, &req, st));
1528 }
1529 
1530 /*------------------------------------------------------------------------*
1531  *	usbd_req_set_address
1532  *
1533  * This function is used to set the address for an USB device. After
1534  * port reset the USB device will respond at address zero.
1535  *
1536  * Returns:
1537  *    0: Success
1538  * Else: Failure
1539  *------------------------------------------------------------------------*/
1540 usb_error_t
1541 usbd_req_set_address(struct usb_device *udev, struct lock *lock, uint16_t addr)
1542 {
1543 	struct usb_device_request req;
1544 	usb_error_t err;
1545 
1546 	DPRINTFN(6, "setting device address=%d\n", addr);
1547 
1548 	req.bmRequestType = UT_WRITE_DEVICE;
1549 	req.bRequest = UR_SET_ADDRESS;
1550 	USETW(req.wValue, addr);
1551 	USETW(req.wIndex, 0);
1552 	USETW(req.wLength, 0);
1553 
1554 	err = USB_ERR_INVAL;
1555 
1556 	/* check if USB controller handles set address */
1557 	if (udev->bus->methods->set_address != NULL)
1558 		err = (udev->bus->methods->set_address) (udev, lock, addr);
1559 
1560 	if (err != USB_ERR_INVAL)
1561 		goto done;
1562 
1563 	/* Setting the address should not take more than 1 second ! */
1564 	err = usbd_do_request_flags(udev, lock, &req, NULL,
1565 	    USB_DELAY_STATUS_STAGE, NULL, 1000);
1566 
1567 done:
1568 	/* allow device time to set new address */
1569 	usb_pause_mtx(lock,
1570 	    USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1571 
1572 	return (err);
1573 }
1574 
1575 /*------------------------------------------------------------------------*
1576  *	usbd_req_get_port_status
1577  *
1578  * Returns:
1579  *    0: Success
1580  * Else: Failure
1581  *------------------------------------------------------------------------*/
1582 usb_error_t
1583 usbd_req_get_port_status(struct usb_device *udev, struct lock *lock,
1584     struct usb_port_status *ps, uint8_t port)
1585 {
1586 	struct usb_device_request req;
1587 
1588 	req.bmRequestType = UT_READ_CLASS_OTHER;
1589 	req.bRequest = UR_GET_STATUS;
1590 	USETW(req.wValue, 0);
1591 	req.wIndex[0] = port;
1592 	req.wIndex[1] = 0;
1593 	USETW(req.wLength, sizeof *ps);
1594 	return (usbd_do_request(udev, lock, &req, ps));
1595 }
1596 
1597 /*------------------------------------------------------------------------*
1598  *	usbd_req_clear_hub_feature
1599  *
1600  * Returns:
1601  *    0: Success
1602  * Else: Failure
1603  *------------------------------------------------------------------------*/
1604 usb_error_t
1605 usbd_req_clear_hub_feature(struct usb_device *udev, struct lock *lock,
1606     uint16_t sel)
1607 {
1608 	struct usb_device_request req;
1609 
1610 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1611 	req.bRequest = UR_CLEAR_FEATURE;
1612 	USETW(req.wValue, sel);
1613 	USETW(req.wIndex, 0);
1614 	USETW(req.wLength, 0);
1615 	return (usbd_do_request(udev, lock, &req, 0));
1616 }
1617 
1618 /*------------------------------------------------------------------------*
1619  *	usbd_req_set_hub_feature
1620  *
1621  * Returns:
1622  *    0: Success
1623  * Else: Failure
1624  *------------------------------------------------------------------------*/
1625 usb_error_t
1626 usbd_req_set_hub_feature(struct usb_device *udev, struct lock *lock,
1627     uint16_t sel)
1628 {
1629 	struct usb_device_request req;
1630 
1631 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1632 	req.bRequest = UR_SET_FEATURE;
1633 	USETW(req.wValue, sel);
1634 	USETW(req.wIndex, 0);
1635 	USETW(req.wLength, 0);
1636 	return (usbd_do_request(udev, lock, &req, 0));
1637 }
1638 
1639 /*------------------------------------------------------------------------*
1640  *	usbd_req_set_hub_u1_timeout
1641  *
1642  * Returns:
1643  *    0: Success
1644  * Else: Failure
1645  *------------------------------------------------------------------------*/
1646 usb_error_t
1647 usbd_req_set_hub_u1_timeout(struct usb_device *udev, struct lock *lock,
1648     uint8_t port, uint8_t timeout)
1649 {
1650 	struct usb_device_request req;
1651 
1652 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1653 	req.bRequest = UR_SET_FEATURE;
1654 	USETW(req.wValue, UHF_PORT_U1_TIMEOUT);
1655 	req.wIndex[0] = port;
1656 	req.wIndex[1] = timeout;
1657 	USETW(req.wLength, 0);
1658 	return (usbd_do_request(udev, lock, &req, 0));
1659 }
1660 
1661 /*------------------------------------------------------------------------*
1662  *	usbd_req_set_hub_u2_timeout
1663  *
1664  * Returns:
1665  *    0: Success
1666  * Else: Failure
1667  *------------------------------------------------------------------------*/
1668 usb_error_t
1669 usbd_req_set_hub_u2_timeout(struct usb_device *udev, struct lock *lock,
1670     uint8_t port, uint8_t timeout)
1671 {
1672 	struct usb_device_request req;
1673 
1674 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1675 	req.bRequest = UR_SET_FEATURE;
1676 	USETW(req.wValue, UHF_PORT_U2_TIMEOUT);
1677 	req.wIndex[0] = port;
1678 	req.wIndex[1] = timeout;
1679 	USETW(req.wLength, 0);
1680 	return (usbd_do_request(udev, lock, &req, 0));
1681 }
1682 
1683 /*------------------------------------------------------------------------*
1684  *	usbd_req_set_hub_depth
1685  *
1686  * Returns:
1687  *    0: Success
1688  * Else: Failure
1689  *------------------------------------------------------------------------*/
1690 usb_error_t
1691 usbd_req_set_hub_depth(struct usb_device *udev, struct lock *lock,
1692     uint16_t depth)
1693 {
1694 	struct usb_device_request req;
1695 
1696 	req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1697 	req.bRequest = UR_SET_HUB_DEPTH;
1698 	USETW(req.wValue, depth);
1699 	USETW(req.wIndex, 0);
1700 	USETW(req.wLength, 0);
1701 	return (usbd_do_request(udev, lock, &req, 0));
1702 }
1703 
1704 /*------------------------------------------------------------------------*
1705  *	usbd_req_clear_port_feature
1706  *
1707  * Returns:
1708  *    0: Success
1709  * Else: Failure
1710  *------------------------------------------------------------------------*/
1711 usb_error_t
1712 usbd_req_clear_port_feature(struct usb_device *udev, struct lock *lock,
1713     uint8_t port, uint16_t sel)
1714 {
1715 	struct usb_device_request req;
1716 
1717 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1718 	req.bRequest = UR_CLEAR_FEATURE;
1719 	USETW(req.wValue, sel);
1720 	req.wIndex[0] = port;
1721 	req.wIndex[1] = 0;
1722 	USETW(req.wLength, 0);
1723 	return (usbd_do_request(udev, lock, &req, 0));
1724 }
1725 
1726 /*------------------------------------------------------------------------*
1727  *	usbd_req_set_port_feature
1728  *
1729  * Returns:
1730  *    0: Success
1731  * Else: Failure
1732  *------------------------------------------------------------------------*/
1733 usb_error_t
1734 usbd_req_set_port_feature(struct usb_device *udev, struct lock *lock,
1735     uint8_t port, uint16_t sel)
1736 {
1737 	struct usb_device_request req;
1738 
1739 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
1740 	req.bRequest = UR_SET_FEATURE;
1741 	USETW(req.wValue, sel);
1742 	req.wIndex[0] = port;
1743 	req.wIndex[1] = 0;
1744 	USETW(req.wLength, 0);
1745 	return (usbd_do_request(udev, lock, &req, 0));
1746 }
1747 
1748 /*------------------------------------------------------------------------*
1749  *	usbd_req_set_protocol
1750  *
1751  * Returns:
1752  *    0: Success
1753  * Else: Failure
1754  *------------------------------------------------------------------------*/
1755 usb_error_t
1756 usbd_req_set_protocol(struct usb_device *udev, struct lock *lock,
1757     uint8_t iface_index, uint16_t report)
1758 {
1759 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1760 	struct usb_device_request req;
1761 
1762 	if ((iface == NULL) || (iface->idesc == NULL)) {
1763 		return (USB_ERR_INVAL);
1764 	}
1765 	DPRINTFN(5, "iface=%p, report=%d, endpt=%d\n",
1766 	    iface, report, iface->idesc->bInterfaceNumber);
1767 
1768 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1769 	req.bRequest = UR_SET_PROTOCOL;
1770 	USETW(req.wValue, report);
1771 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1772 	req.wIndex[1] = 0;
1773 	USETW(req.wLength, 0);
1774 	return (usbd_do_request(udev, lock, &req, 0));
1775 }
1776 
1777 /*------------------------------------------------------------------------*
1778  *	usbd_req_set_report
1779  *
1780  * Returns:
1781  *    0: Success
1782  * Else: Failure
1783  *------------------------------------------------------------------------*/
1784 usb_error_t
1785 usbd_req_set_report(struct usb_device *udev, struct lock *lock, void *data, uint16_t len,
1786     uint8_t iface_index, uint8_t type, uint8_t id)
1787 {
1788 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1789 	struct usb_device_request req;
1790 
1791 	if ((iface == NULL) || (iface->idesc == NULL)) {
1792 		return (USB_ERR_INVAL);
1793 	}
1794 	DPRINTFN(5, "len=%d\n", len);
1795 
1796 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1797 	req.bRequest = UR_SET_REPORT;
1798 	USETW2(req.wValue, type, id);
1799 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1800 	req.wIndex[1] = 0;
1801 	USETW(req.wLength, len);
1802 	return (usbd_do_request(udev, lock, &req, data));
1803 }
1804 
1805 /*------------------------------------------------------------------------*
1806  *	usbd_req_get_report
1807  *
1808  * Returns:
1809  *    0: Success
1810  * Else: Failure
1811  *------------------------------------------------------------------------*/
1812 usb_error_t
1813 usbd_req_get_report(struct usb_device *udev, struct lock *lock, void *data,
1814     uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id)
1815 {
1816 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1817 	struct usb_device_request req;
1818 
1819 	if ((iface == NULL) || (iface->idesc == NULL)) {
1820 		return (USB_ERR_INVAL);
1821 	}
1822 	DPRINTFN(5, "len=%d\n", len);
1823 
1824 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
1825 	req.bRequest = UR_GET_REPORT;
1826 	USETW2(req.wValue, type, id);
1827 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1828 	req.wIndex[1] = 0;
1829 	USETW(req.wLength, len);
1830 	return (usbd_do_request(udev, lock, &req, data));
1831 }
1832 
1833 /*------------------------------------------------------------------------*
1834  *	usbd_req_set_idle
1835  *
1836  * Returns:
1837  *    0: Success
1838  * Else: Failure
1839  *------------------------------------------------------------------------*/
1840 usb_error_t
1841 usbd_req_set_idle(struct usb_device *udev, struct lock *lock,
1842     uint8_t iface_index, uint8_t duration, uint8_t id)
1843 {
1844 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1845 	struct usb_device_request req;
1846 
1847 	if ((iface == NULL) || (iface->idesc == NULL)) {
1848 		return (USB_ERR_INVAL);
1849 	}
1850 	DPRINTFN(5, "%d %d\n", duration, id);
1851 
1852 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1853 	req.bRequest = UR_SET_IDLE;
1854 	USETW2(req.wValue, duration, id);
1855 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1856 	req.wIndex[1] = 0;
1857 	USETW(req.wLength, 0);
1858 	return (usbd_do_request(udev, lock, &req, 0));
1859 }
1860 
1861 /*------------------------------------------------------------------------*
1862  *	usbd_req_get_report_descriptor
1863  *
1864  * Returns:
1865  *    0: Success
1866  * Else: Failure
1867  *------------------------------------------------------------------------*/
1868 usb_error_t
1869 usbd_req_get_report_descriptor(struct usb_device *udev, struct lock *lock,
1870     void *d, uint16_t size, uint8_t iface_index)
1871 {
1872 	struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1873 	struct usb_device_request req;
1874 
1875 	if ((iface == NULL) || (iface->idesc == NULL)) {
1876 		return (USB_ERR_INVAL);
1877 	}
1878 	req.bmRequestType = UT_READ_INTERFACE;
1879 	req.bRequest = UR_GET_DESCRIPTOR;
1880 	USETW2(req.wValue, UDESC_REPORT, 0);	/* report id should be 0 */
1881 	req.wIndex[0] = iface->idesc->bInterfaceNumber;
1882 	req.wIndex[1] = 0;
1883 	USETW(req.wLength, size);
1884 	return (usbd_do_request(udev, lock, &req, d));
1885 }
1886 
1887 /*------------------------------------------------------------------------*
1888  *	usbd_req_set_config
1889  *
1890  * This function is used to select the current configuration number in
1891  * both USB device side mode and USB host side mode. When setting the
1892  * configuration the function of the interfaces can change.
1893  *
1894  * Returns:
1895  *    0: Success
1896  * Else: Failure
1897  *------------------------------------------------------------------------*/
1898 usb_error_t
1899 usbd_req_set_config(struct usb_device *udev, struct lock *lock, uint8_t conf)
1900 {
1901 	struct usb_device_request req;
1902 
1903 	DPRINTF("setting config %d\n", conf);
1904 
1905 	/* do "set configuration" request */
1906 
1907 	req.bmRequestType = UT_WRITE_DEVICE;
1908 	req.bRequest = UR_SET_CONFIG;
1909 	req.wValue[0] = conf;
1910 	req.wValue[1] = 0;
1911 	USETW(req.wIndex, 0);
1912 	USETW(req.wLength, 0);
1913 	return (usbd_do_request(udev, lock, &req, 0));
1914 }
1915 
1916 /*------------------------------------------------------------------------*
1917  *	usbd_req_get_config
1918  *
1919  * Returns:
1920  *    0: Success
1921  * Else: Failure
1922  *------------------------------------------------------------------------*/
1923 usb_error_t
1924 usbd_req_get_config(struct usb_device *udev, struct lock *lock, uint8_t *pconf)
1925 {
1926 	struct usb_device_request req;
1927 
1928 	req.bmRequestType = UT_READ_DEVICE;
1929 	req.bRequest = UR_GET_CONFIG;
1930 	USETW(req.wValue, 0);
1931 	USETW(req.wIndex, 0);
1932 	USETW(req.wLength, 1);
1933 	return (usbd_do_request(udev, lock, &req, pconf));
1934 }
1935 
1936 /*------------------------------------------------------------------------*
1937  *	usbd_setup_device_desc
1938  *------------------------------------------------------------------------*/
1939 usb_error_t
1940 usbd_setup_device_desc(struct usb_device *udev, struct lock *lock)
1941 {
1942 	usb_error_t err;
1943 
1944 	/*
1945 	 * Get the first 8 bytes of the device descriptor !
1946 	 *
1947 	 * NOTE: "usbd_do_request()" will check the device descriptor
1948 	 * next time we do a request to see if the maximum packet size
1949 	 * changed! The 8 first bytes of the device descriptor
1950 	 * contains the maximum packet size to use on control endpoint
1951 	 * 0. If this value is different from "USB_MAX_IPACKET" a new
1952 	 * USB control request will be setup!
1953 	 */
1954 	switch (udev->speed) {
1955 	case USB_SPEED_FULL:
1956 	case USB_SPEED_LOW:
1957 		err = usbd_req_get_desc(udev, lock, NULL, &udev->ddesc,
1958 		    USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1959 		if (err != 0) {
1960 			DPRINTFN(0, "getting device descriptor "
1961 			    "at addr %d failed, %s\n", udev->address,
1962 			    usbd_errstr(err));
1963 			return (err);
1964 		}
1965 		break;
1966 	default:
1967 		DPRINTF("Minimum MaxPacketSize is large enough "
1968 		    "to hold the complete device descriptor\n");
1969 		break;
1970 	}
1971 
1972 	/* get the full device descriptor */
1973 	err = usbd_req_get_device_desc(udev, lock, &udev->ddesc);
1974 
1975 	/* try one more time, if error */
1976 	if (err)
1977 		err = usbd_req_get_device_desc(udev, lock, &udev->ddesc);
1978 
1979 	if (err) {
1980 		DPRINTF("addr=%d, getting full desc failed\n",
1981 		    udev->address);
1982 		return (err);
1983 	}
1984 
1985 	DPRINTF("adding unit addr=%d, rev=%02x, class=%d, "
1986 	    "subclass=%d, protocol=%d, maxpacket=%d, len=%d, speed=%d\n",
1987 	    udev->address, UGETW(udev->ddesc.bcdUSB),
1988 	    udev->ddesc.bDeviceClass,
1989 	    udev->ddesc.bDeviceSubClass,
1990 	    udev->ddesc.bDeviceProtocol,
1991 	    udev->ddesc.bMaxPacketSize,
1992 	    udev->ddesc.bLength,
1993 	    udev->speed);
1994 
1995 	return (err);
1996 }
1997 
1998 /*------------------------------------------------------------------------*
1999  *	usbd_req_re_enumerate
2000  *
2001  * NOTE: After this function returns the hardware is in the
2002  * unconfigured state! The application is responsible for setting a
2003  * new configuration.
2004  *
2005  * Returns:
2006  *    0: Success
2007  * Else: Failure
2008  *------------------------------------------------------------------------*/
2009 usb_error_t
2010 usbd_req_re_enumerate(struct usb_device *udev, struct lock *lock)
2011 {
2012 	struct usb_device *parent_hub;
2013 	usb_error_t err;
2014 	uint8_t old_addr;
2015 	uint8_t do_retry = 1;
2016 
2017 	if (udev->flags.usb_mode != USB_MODE_HOST) {
2018 		return (USB_ERR_INVAL);
2019 	}
2020 	old_addr = udev->address;
2021 	parent_hub = udev->parent_hub;
2022 	if (parent_hub == NULL) {
2023 		return (USB_ERR_INVAL);
2024 	}
2025 retry:
2026 	/*
2027 	 * Try to reset the High Speed parent HUB of a LOW- or FULL-
2028 	 * speed device, if any.
2029 	 */
2030 	if (udev->parent_hs_hub != NULL &&
2031 	    udev->speed != USB_SPEED_HIGH) {
2032 		DPRINTF("Trying to reset parent High Speed TT.\n");
2033 		err = usbd_req_reset_tt(udev->parent_hs_hub, NULL,
2034 		    udev->hs_port_no);
2035 		if (err) {
2036 			DPRINTF("Resetting parent High "
2037 			    "Speed TT failed (%s).\n",
2038 			    usbd_errstr(err));
2039 		}
2040 	}
2041 
2042 	/* Try to warm reset first */
2043 	if (parent_hub->speed == USB_SPEED_SUPER)
2044 		usbd_req_warm_reset_port(parent_hub, lock, udev->port_no);
2045 
2046 	/* Try to reset the parent HUB port. */
2047 	err = usbd_req_reset_port(parent_hub, lock, udev->port_no);
2048 	if (err) {
2049 		DPRINTFN(0, "addr=%d, port reset failed, %s\n",
2050 		    old_addr, usbd_errstr(err));
2051 		goto done;
2052 	}
2053 
2054 	/*
2055 	 * After that the port has been reset our device should be at
2056 	 * address zero:
2057 	 */
2058 	udev->address = USB_START_ADDR;
2059 
2060 	/* reset "bMaxPacketSize" */
2061 	udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
2062 
2063 	/* reset USB state */
2064 	usb_set_device_state(udev, USB_STATE_POWERED);
2065 
2066 	/*
2067 	 * Restore device address:
2068 	 */
2069 	err = usbd_req_set_address(udev, lock, old_addr);
2070 	if (err) {
2071 		/* XXX ignore any errors! */
2072 		DPRINTFN(0, "addr=%d, set address failed! (%s, ignored)\n",
2073 		    old_addr, usbd_errstr(err));
2074 	}
2075 	/*
2076 	 * Restore device address, if the controller driver did not
2077 	 * set a new one:
2078 	 */
2079 	if (udev->address == USB_START_ADDR)
2080 		udev->address = old_addr;
2081 
2082 	/* setup the device descriptor and the initial "wMaxPacketSize" */
2083 	err = usbd_setup_device_desc(udev, lock);
2084 
2085 done:
2086 	if (err && do_retry) {
2087 		/* give the USB firmware some time to load */
2088 		usb_pause_mtx(lock, hz / 2);
2089 		/* no more retries after this retry */
2090 		do_retry = 0;
2091 		/* try again */
2092 		goto retry;
2093 	}
2094 	/* restore address */
2095 	if (udev->address == USB_START_ADDR)
2096 		udev->address = old_addr;
2097 	/* update state, if successful */
2098 	if (err == 0)
2099 		usb_set_device_state(udev, USB_STATE_ADDRESSED);
2100 	return (err);
2101 }
2102 
2103 /*------------------------------------------------------------------------*
2104  *	usbd_req_clear_device_feature
2105  *
2106  * Returns:
2107  *    0: Success
2108  * Else: Failure
2109  *------------------------------------------------------------------------*/
2110 usb_error_t
2111 usbd_req_clear_device_feature(struct usb_device *udev, struct lock *lock,
2112     uint16_t sel)
2113 {
2114 	struct usb_device_request req;
2115 
2116 	req.bmRequestType = UT_WRITE_DEVICE;
2117 	req.bRequest = UR_CLEAR_FEATURE;
2118 	USETW(req.wValue, sel);
2119 	USETW(req.wIndex, 0);
2120 	USETW(req.wLength, 0);
2121 	return (usbd_do_request(udev, lock, &req, 0));
2122 }
2123 
2124 /*------------------------------------------------------------------------*
2125  *	usbd_req_set_device_feature
2126  *
2127  * Returns:
2128  *    0: Success
2129  * Else: Failure
2130  *------------------------------------------------------------------------*/
2131 usb_error_t
2132 usbd_req_set_device_feature(struct usb_device *udev, struct lock *lock,
2133     uint16_t sel)
2134 {
2135 	struct usb_device_request req;
2136 
2137 	req.bmRequestType = UT_WRITE_DEVICE;
2138 	req.bRequest = UR_SET_FEATURE;
2139 	USETW(req.wValue, sel);
2140 	USETW(req.wIndex, 0);
2141 	USETW(req.wLength, 0);
2142 	return (usbd_do_request(udev, lock, &req, 0));
2143 }
2144 
2145 /*------------------------------------------------------------------------*
2146  *	usbd_req_reset_tt
2147  *
2148  * Returns:
2149  *    0: Success
2150  * Else: Failure
2151  *------------------------------------------------------------------------*/
2152 usb_error_t
2153 usbd_req_reset_tt(struct usb_device *udev, struct lock *lock,
2154     uint8_t port)
2155 {
2156 	struct usb_device_request req;
2157 
2158 	/* For single TT HUBs the port should be 1 */
2159 
2160 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
2161 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
2162 		port = 1;
2163 
2164 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2165 	req.bRequest = UR_RESET_TT;
2166 	USETW(req.wValue, 0);
2167 	req.wIndex[0] = port;
2168 	req.wIndex[1] = 0;
2169 	USETW(req.wLength, 0);
2170 	return (usbd_do_request(udev, lock, &req, 0));
2171 }
2172 
2173 /*------------------------------------------------------------------------*
2174  *	usbd_req_clear_tt_buffer
2175  *
2176  * For single TT HUBs the port should be 1.
2177  *
2178  * Returns:
2179  *    0: Success
2180  * Else: Failure
2181  *------------------------------------------------------------------------*/
2182 usb_error_t
2183 usbd_req_clear_tt_buffer(struct usb_device *udev, struct lock *lock,
2184     uint8_t port, uint8_t addr, uint8_t type, uint8_t endpoint)
2185 {
2186 	struct usb_device_request req;
2187 	uint16_t wValue;
2188 
2189 	/* For single TT HUBs the port should be 1 */
2190 
2191 	if (udev->ddesc.bDeviceClass == UDCLASS_HUB &&
2192 	    udev->ddesc.bDeviceProtocol == UDPROTO_HSHUBSTT)
2193 		port = 1;
2194 
2195 	wValue = (endpoint & 0xF) | ((addr & 0x7F) << 4) |
2196 	    ((endpoint & 0x80) << 8) | ((type & 3) << 12);
2197 
2198 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2199 	req.bRequest = UR_CLEAR_TT_BUFFER;
2200 	USETW(req.wValue, wValue);
2201 	req.wIndex[0] = port;
2202 	req.wIndex[1] = 0;
2203 	USETW(req.wLength, 0);
2204 	return (usbd_do_request(udev, lock, &req, 0));
2205 }
2206 
2207 /*------------------------------------------------------------------------*
2208  *	usbd_req_set_port_link_state
2209  *
2210  * USB 3.0 specific request
2211  *
2212  * Returns:
2213  *    0: Success
2214  * Else: Failure
2215  *------------------------------------------------------------------------*/
2216 usb_error_t
2217 usbd_req_set_port_link_state(struct usb_device *udev, struct lock *lock,
2218     uint8_t port, uint8_t link_state)
2219 {
2220 	struct usb_device_request req;
2221 
2222 	req.bmRequestType = UT_WRITE_CLASS_OTHER;
2223 	req.bRequest = UR_SET_FEATURE;
2224 	USETW(req.wValue, UHF_PORT_LINK_STATE);
2225 	req.wIndex[0] = port;
2226 	req.wIndex[1] = link_state;
2227 	USETW(req.wLength, 0);
2228 	return (usbd_do_request(udev, lock, &req, 0));
2229 }
2230