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