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