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