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