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