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