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