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