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