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