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