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