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