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