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