]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - sys/dev/usb/usb_request.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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 #include <sys/stdint.h>
30 #include <sys/stddef.h>
31 #include <sys/param.h>
32 #include <sys/queue.h>
33 #include <sys/types.h>
34 #include <sys/systm.h>
35 #include <sys/kernel.h>
36 #include <sys/bus.h>
37 #include <sys/linker_set.h>
38 #include <sys/module.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/condvar.h>
42 #include <sys/sysctl.h>
43 #include <sys/sx.h>
44 #include <sys/unistd.h>
45 #include <sys/callout.h>
46 #include <sys/malloc.h>
47 #include <sys/priv.h>
48
49 #include <dev/usb/usb.h>
50 #include <dev/usb/usbdi.h>
51 #include <dev/usb/usbdi_util.h>
52 #include <dev/usb/usb_ioctl.h>
53 #include <dev/usb/usbhid.h>
54
55 #define USB_DEBUG_VAR usb_debug
56
57 #include <dev/usb/usb_core.h>
58 #include <dev/usb/usb_busdma.h>
59 #include <dev/usb/usb_request.h>
60 #include <dev/usb/usb_process.h>
61 #include <dev/usb/usb_transfer.h>
62 #include <dev/usb/usb_debug.h>
63 #include <dev/usb/usb_device.h>
64 #include <dev/usb/usb_util.h>
65 #include <dev/usb/usb_dynamic.h>
66
67 #include <dev/usb/usb_controller.h>
68 #include <dev/usb/usb_bus.h>
69 #include <sys/ctype.h>
70
71 #ifdef USB_DEBUG
72 static int usb_pr_poll_delay = USB_PORT_RESET_DELAY;
73 static int usb_pr_recovery_delay = USB_PORT_RESET_RECOVERY;
74
75 SYSCTL_INT(_hw_usb, OID_AUTO, pr_poll_delay, CTLFLAG_RW,
76     &usb_pr_poll_delay, 0, "USB port reset poll delay in ms");
77 SYSCTL_INT(_hw_usb, OID_AUTO, pr_recovery_delay, CTLFLAG_RW,
78     &usb_pr_recovery_delay, 0, "USB port reset recovery delay in ms");
79
80 #ifdef USB_REQ_DEBUG
81 /* The following structures are used in connection to fault injection. */
82 struct usb_ctrl_debug {
83         int bus_index;          /* target bus */
84         int dev_index;          /* target address */
85         int ds_fail;            /* fail data stage */
86         int ss_fail;            /* fail data stage */
87         int ds_delay;           /* data stage delay in ms */
88         int ss_delay;           /* status stage delay in ms */
89         int bmRequestType_value;
90         int bRequest_value;
91 };
92
93 struct usb_ctrl_debug_bits {
94         uint16_t ds_delay;
95         uint16_t ss_delay;
96         uint8_t ds_fail:1;
97         uint8_t ss_fail:1;
98         uint8_t enabled:1;
99 };
100
101 /* The default is to disable fault injection. */
102
103 static struct usb_ctrl_debug usb_ctrl_debug = {
104         .bus_index = -1,
105         .dev_index = -1,
106         .bmRequestType_value = -1,
107         .bRequest_value = -1,
108 };
109
110 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_bus_fail, CTLFLAG_RW,
111     &usb_ctrl_debug.bus_index, 0, "USB controller index to fail");
112 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_dev_fail, CTLFLAG_RW,
113     &usb_ctrl_debug.dev_index, 0, "USB device address to fail");
114 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_fail, CTLFLAG_RW,
115     &usb_ctrl_debug.ds_fail, 0, "USB fail data stage");
116 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_fail, CTLFLAG_RW,
117     &usb_ctrl_debug.ss_fail, 0, "USB fail status stage");
118 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ds_delay, CTLFLAG_RW,
119     &usb_ctrl_debug.ds_delay, 0, "USB data stage delay in ms");
120 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_ss_delay, CTLFLAG_RW,
121     &usb_ctrl_debug.ss_delay, 0, "USB status stage delay in ms");
122 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rt_fail, CTLFLAG_RW,
123     &usb_ctrl_debug.bmRequestType_value, 0, "USB bmRequestType to fail");
124 SYSCTL_INT(_hw_usb, OID_AUTO, ctrl_rv_fail, CTLFLAG_RW,
125     &usb_ctrl_debug.bRequest_value, 0, "USB bRequest to fail");
126
127 /*------------------------------------------------------------------------*
128  *      usbd_get_debug_bits
129  *
130  * This function is only useful in USB host mode.
131  *------------------------------------------------------------------------*/
132 static void
133 usbd_get_debug_bits(struct usb_device *udev, struct usb_device_request *req,
134     struct usb_ctrl_debug_bits *dbg)
135 {
136         int temp;
137
138         memset(dbg, 0, sizeof(*dbg));
139
140         /* Compute data stage delay */
141
142         temp = usb_ctrl_debug.ds_delay;
143         if (temp < 0)
144                 temp = 0;
145         else if (temp > (16*1024))
146                 temp = (16*1024);
147
148         dbg->ds_delay = temp;
149
150         /* Compute status stage delay */
151
152         temp = usb_ctrl_debug.ss_delay;
153         if (temp < 0)
154                 temp = 0;
155         else if (temp > (16*1024))
156                 temp = (16*1024);
157
158         dbg->ss_delay = temp;
159
160         /* Check if this control request should be failed */
161
162         if (usbd_get_bus_index(udev) != usb_ctrl_debug.bus_index)
163                 return;
164
165         if (usbd_get_device_index(udev) != usb_ctrl_debug.dev_index)
166                 return;
167
168         temp = usb_ctrl_debug.bmRequestType_value;
169
170         if ((temp != req->bmRequestType) && (temp >= 0) && (temp <= 255))
171                 return;
172
173         temp = usb_ctrl_debug.bRequest_value;
174
175         if ((temp != req->bRequest) && (temp >= 0) && (temp <= 255))
176                 return;
177
178         temp = usb_ctrl_debug.ds_fail;
179         if (temp)
180                 dbg->ds_fail = 1;
181
182         temp = usb_ctrl_debug.ss_fail;
183         if (temp)
184                 dbg->ss_fail = 1;
185
186         dbg->enabled = 1;
187 }
188 #endif  /* USB_REQ_DEBUG */
189 #endif  /* USB_DEBUG */
190
191 /*------------------------------------------------------------------------*
192  *      usbd_do_request_callback
193  *
194  * This function is the USB callback for generic USB Host control
195  * transfers.
196  *------------------------------------------------------------------------*/
197 void
198 usbd_do_request_callback(struct usb_xfer *xfer, usb_error_t error)
199 {
200         ;                               /* workaround for a bug in "indent" */
201
202         DPRINTF("st=%u\n", USB_GET_STATE(xfer));
203
204         switch (USB_GET_STATE(xfer)) {
205         case USB_ST_SETUP:
206                 usbd_transfer_submit(xfer);
207                 break;
208         default:
209                 cv_signal(&xfer->xroot->udev->ctrlreq_cv);
210                 break;
211         }
212 }
213
214 /*------------------------------------------------------------------------*
215  *      usb_do_clear_stall_callback
216  *
217  * This function is the USB callback for generic clear stall requests.
218  *------------------------------------------------------------------------*/
219 void
220 usb_do_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
221 {
222         struct usb_device_request req;
223         struct usb_device *udev;
224         struct usb_endpoint *ep;
225         struct usb_endpoint *ep_end;
226         struct usb_endpoint *ep_first;
227         uint8_t to;
228
229         udev = xfer->xroot->udev;
230
231         USB_BUS_LOCK(udev->bus);
232
233         /* round robin endpoint clear stall */
234
235         ep = udev->ep_curr;
236         ep_end = udev->endpoints + udev->endpoints_max;
237         ep_first = udev->endpoints;
238         to = udev->endpoints_max;
239
240         switch (USB_GET_STATE(xfer)) {
241         case USB_ST_TRANSFERRED:
242                 if (ep == NULL)
243                         goto tr_setup;          /* device was unconfigured */
244                 if (ep->edesc &&
245                     ep->is_stalled) {
246                         ep->toggle_next = 0;
247                         ep->is_stalled = 0;
248                         /* start up the current or next transfer, if any */
249                         usb_command_wrapper(&ep->endpoint_q,
250                             ep->endpoint_q.curr);
251                 }
252                 ep++;
253
254         case USB_ST_SETUP:
255 tr_setup:
256                 if (to == 0)
257                         break;                  /* no endpoints - nothing to do */
258                 if ((ep < ep_first) || (ep >= ep_end))
259                         ep = ep_first;  /* endpoint wrapped around */
260                 if (ep->edesc &&
261                     ep->is_stalled) {
262
263                         /* setup a clear-stall packet */
264
265                         req.bmRequestType = UT_WRITE_ENDPOINT;
266                         req.bRequest = UR_CLEAR_FEATURE;
267                         USETW(req.wValue, UF_ENDPOINT_HALT);
268                         req.wIndex[0] = ep->edesc->bEndpointAddress;
269                         req.wIndex[1] = 0;
270                         USETW(req.wLength, 0);
271
272                         /* copy in the transfer */
273
274                         usbd_copy_in(xfer->frbuffers, 0, &req, sizeof(req));
275
276                         /* set length */
277                         usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
278                         xfer->nframes = 1;
279                         USB_BUS_UNLOCK(udev->bus);
280
281                         usbd_transfer_submit(xfer);
282
283                         USB_BUS_LOCK(udev->bus);
284                         break;
285                 }
286                 ep++;
287                 to--;
288                 goto tr_setup;
289
290         default:
291                 if (xfer->error == USB_ERR_CANCELLED) {
292                         break;
293                 }
294                 goto tr_setup;
295         }
296
297         /* store current endpoint */
298         udev->ep_curr = ep;
299         USB_BUS_UNLOCK(udev->bus);
300 }
301
302 static usb_handle_req_t *
303 usbd_get_hr_func(struct usb_device *udev)
304 {
305         /* figure out if there is a Handle Request function */
306         if (udev->flags.usb_mode == USB_MODE_DEVICE)
307                 return (usb_temp_get_desc_p);
308         else if (udev->parent_hub == NULL)
309                 return (udev->bus->methods->roothub_exec);
310         else
311                 return (NULL);
312 }
313
314 /*------------------------------------------------------------------------*
315  *      usbd_do_request_flags and usbd_do_request
316  *
317  * Description of arguments passed to these functions:
318  *
319  * "udev" - this is the "usb_device" structure pointer on which the
320  * request should be performed. It is possible to call this function
321  * in both Host Side mode and Device Side mode.
322  *
323  * "mtx" - if this argument is non-NULL the mutex pointed to by it
324  * will get dropped and picked up during the execution of this
325  * function, hence this function sometimes needs to sleep. If this
326  * argument is NULL it has no effect.
327  *
328  * "req" - this argument must always be non-NULL and points to an
329  * 8-byte structure holding the USB request to be done. The USB
330  * request structure has a bit telling the direction of the USB
331  * request, if it is a read or a write.
332  *
333  * "data" - if the "wLength" part of the structure pointed to by "req"
334  * is non-zero this argument must point to a valid kernel buffer which
335  * can hold at least "wLength" bytes. If "wLength" is zero "data" can
336  * be NULL.
337  *
338  * "flags" - here is a list of valid flags:
339  *
340  *  o USB_SHORT_XFER_OK: allows the data transfer to be shorter than
341  *  specified
342  *
343  *  o USB_DELAY_STATUS_STAGE: allows the status stage to be performed
344  *  at a later point in time. This is tunable by the "hw.usb.ss_delay"
345  *  sysctl. This flag is mostly useful for debugging.
346  *
347  *  o USB_USER_DATA_PTR: treat the "data" pointer like a userland
348  *  pointer.
349  *
350  * "actlen" - if non-NULL the actual transfer length will be stored in
351  * the 16-bit unsigned integer pointed to by "actlen". This
352  * information is mostly useful when the "USB_SHORT_XFER_OK" flag is
353  * used.
354  *
355  * "timeout" - gives the timeout for the control transfer in
356  * milliseconds. A "timeout" value less than 50 milliseconds is
357  * treated like a 50 millisecond timeout. A "timeout" value greater
358  * than 30 seconds is treated like a 30 second timeout. This USB stack
359  * does not allow control requests without a timeout.
360  *
361  * NOTE: This function is thread safe. All calls to
362  * "usbd_do_request_flags" will be serialised by the use of an
363  * internal "sx_lock".
364  *
365  * Returns:
366  *    0: Success
367  * Else: Failure
368  *------------------------------------------------------------------------*/
369 usb_error_t
370 usbd_do_request_flags(struct usb_device *udev, struct mtx *mtx,
371     struct usb_device_request *req, void *data, uint16_t flags,
372     uint16_t *actlen, usb_timeout_t timeout)
373 {
374 #ifdef USB_REQ_DEBUG
375         struct usb_ctrl_debug_bits dbg;
376 #endif
377         usb_handle_req_t *hr_func;
378         struct usb_xfer *xfer;
379         const void *desc;
380         int err = 0;
381         usb_ticks_t start_ticks;
382         usb_ticks_t delta_ticks;
383         usb_ticks_t max_ticks;
384         uint16_t length;
385         uint16_t temp;
386         uint16_t acttemp;
387         uint8_t enum_locked;
388
389         if (timeout < 50) {
390                 /* timeout is too small */
391                 timeout = 50;
392         }
393         if (timeout > 30000) {
394                 /* timeout is too big */
395                 timeout = 30000;
396         }
397         length = UGETW(req->wLength);
398
399         enum_locked = usbd_enum_is_locked(udev);
400
401         DPRINTFN(5, "udev=%p bmRequestType=0x%02x bRequest=0x%02x "
402             "wValue=0x%02x%02x wIndex=0x%02x%02x wLength=0x%02x%02x\n",
403             udev, req->bmRequestType, req->bRequest,
404             req->wValue[1], req->wValue[0],
405             req->wIndex[1], req->wIndex[0],
406             req->wLength[1], req->wLength[0]);
407
408         /* Check if the device is still alive */
409         if (udev->state < USB_STATE_POWERED) {
410                 DPRINTF("usb device has gone\n");
411                 return (USB_ERR_NOT_CONFIGURED);
412         }
413
414         /*
415          * Set "actlen" to a known value in case the caller does not
416          * check the return value:
417          */
418         if (actlen)
419                 *actlen = 0;
420
421 #if (USB_HAVE_USER_IO == 0)
422         if (flags & USB_USER_DATA_PTR)
423                 return (USB_ERR_INVAL);
424 #endif
425         if ((mtx != NULL) && (mtx != &Giant)) {
426                 mtx_unlock(mtx);
427                 mtx_assert(mtx, MA_NOTOWNED);
428         }
429
430         /*
431          * We need to allow suspend and resume at this point, else the
432          * control transfer will timeout if the device is suspended!
433          */
434         if (enum_locked)
435                 usbd_sr_unlock(udev);
436
437         /*
438          * Grab the default sx-lock so that serialisation
439          * is achieved when multiple threads are involved:
440          */
441         sx_xlock(&udev->ctrl_sx);
442
443         hr_func = usbd_get_hr_func(udev);
444
445         if (hr_func != NULL) {
446                 DPRINTF("Handle Request function is set\n");
447
448                 desc = NULL;
449                 temp = 0;
450
451                 if (!(req->bmRequestType & UT_READ)) {
452                         if (length != 0) {
453                                 DPRINTFN(1, "The handle request function "
454                                     "does not support writing data!\n");
455                                 err = USB_ERR_INVAL;
456                                 goto done;
457                         }
458                 }
459
460                 /* The root HUB code needs the BUS lock locked */
461
462                 USB_BUS_LOCK(udev->bus);
463                 err = (hr_func) (udev, req, &desc, &temp);
464                 USB_BUS_UNLOCK(udev->bus);
465
466                 if (err)
467                         goto done;
468
469                 if (length > temp) {
470                         if (!(flags & USB_SHORT_XFER_OK)) {
471                                 err = USB_ERR_SHORT_XFER;
472                                 goto done;
473                         }
474                         length = temp;
475                 }
476                 if (actlen)
477                         *actlen = length;
478
479                 if (length > 0) {
480 #if USB_HAVE_USER_IO
481                         if (flags & USB_USER_DATA_PTR) {
482                                 if (copyout(desc, data, length)) {
483                                         err = USB_ERR_INVAL;
484                                         goto done;
485                                 }
486                         } else
487 #endif
488                                 bcopy(desc, data, length);
489                 }
490                 goto done;              /* success */
491         }
492
493         /*
494          * Setup a new USB transfer or use the existing one, if any:
495          */
496         usbd_ctrl_transfer_setup(udev);
497
498         xfer = udev->ctrl_xfer[0];
499         if (xfer == NULL) {
500                 /* most likely out of memory */
501                 err = USB_ERR_NOMEM;
502                 goto done;
503         }
504
505 #ifdef USB_REQ_DEBUG
506         /* Get debug bits */
507         usbd_get_debug_bits(udev, req, &dbg);
508
509         /* Check for fault injection */
510         if (dbg.enabled)
511                 flags |= USB_DELAY_STATUS_STAGE;
512 #endif
513         USB_XFER_LOCK(xfer);
514
515         if (flags & USB_DELAY_STATUS_STAGE)
516                 xfer->flags.manual_status = 1;
517         else
518                 xfer->flags.manual_status = 0;
519
520         if (flags & USB_SHORT_XFER_OK)
521                 xfer->flags.short_xfer_ok = 1;
522         else
523                 xfer->flags.short_xfer_ok = 0;
524
525         xfer->timeout = timeout;
526
527         start_ticks = ticks;
528
529         max_ticks = USB_MS_TO_TICKS(timeout);
530
531         usbd_copy_in(xfer->frbuffers, 0, req, sizeof(*req));
532
533         usbd_xfer_set_frame_len(xfer, 0, sizeof(*req));
534
535         while (1) {
536                 temp = length;
537                 if (temp > usbd_xfer_max_len(xfer)) {
538                         temp = usbd_xfer_max_len(xfer);
539                 }
540 #ifdef USB_REQ_DEBUG
541                 if (xfer->flags.manual_status) {
542                         if (usbd_xfer_frame_len(xfer, 0) != 0) {
543                                 /* Execute data stage separately */
544                                 temp = 0;
545                         } else if (temp > 0) {
546                                 if (dbg.ds_fail) {
547                                         err = USB_ERR_INVAL;
548                                         break;
549                                 }
550                                 if (dbg.ds_delay > 0) {
551                                         usb_pause_mtx(
552                                             xfer->xroot->xfer_mtx,
553                                             USB_MS_TO_TICKS(dbg.ds_delay));
554                                         /* make sure we don't time out */
555                                         start_ticks = ticks;
556                                 }
557                         }
558                 }
559 #endif
560                 usbd_xfer_set_frame_len(xfer, 1, temp);
561
562                 if (temp > 0) {
563                         if (!(req->bmRequestType & UT_READ)) {
564 #if USB_HAVE_USER_IO
565                                 if (flags & USB_USER_DATA_PTR) {
566                                         USB_XFER_UNLOCK(xfer);
567                                         err = usbd_copy_in_user(xfer->frbuffers + 1,
568                                             0, data, temp);
569                                         USB_XFER_LOCK(xfer);
570                                         if (err) {
571                                                 err = USB_ERR_INVAL;
572                                                 break;
573                                         }
574                                 } else
575 #endif
576                                         usbd_copy_in(xfer->frbuffers + 1,
577                                             0, data, temp);
578                         }
579                         usbd_xfer_set_frames(xfer, 2);
580                 } else {
581                         if (usbd_xfer_frame_len(xfer, 0) == 0) {
582                                 if (xfer->flags.manual_status) {
583 #ifdef USB_REQ_DEBUG
584                                         if (dbg.ss_fail) {
585                                                 err = USB_ERR_INVAL;
586                                                 break;
587                                         }
588                                         if (dbg.ss_delay > 0) {
589                                                 usb_pause_mtx(
590                                                     xfer->xroot->xfer_mtx,
591                                                     USB_MS_TO_TICKS(dbg.ss_delay));
592                                                 /* make sure we don't time out */
593                                                 start_ticks = ticks;
594                                         }
595 #endif
596                                         xfer->flags.manual_status = 0;
597                                 } else {
598                                         break;
599                                 }
600                         }
601                         usbd_xfer_set_frames(xfer, 1);
602                 }
603
604                 usbd_transfer_start(xfer);
605
606                 while (usbd_transfer_pending(xfer)) {
607                         cv_wait(&udev->ctrlreq_cv,
608                             xfer->xroot->xfer_mtx);
609                 }
610
611                 err = xfer->error;
612
613                 if (err) {
614                         break;
615                 }
616
617                 /* get actual length of DATA stage */
618
619                 if (xfer->aframes < 2) {
620                         acttemp = 0;
621                 } else {
622                         acttemp = usbd_xfer_frame_len(xfer, 1);
623                 }
624
625                 /* check for short packet */
626
627                 if (temp > acttemp) {
628                         temp = acttemp;
629                         length = temp;
630                 }
631                 if (temp > 0) {
632                         if (req->bmRequestType & UT_READ) {
633 #if USB_HAVE_USER_IO
634                                 if (flags & USB_USER_DATA_PTR) {
635                                         USB_XFER_UNLOCK(xfer);
636                                         err = usbd_copy_out_user(xfer->frbuffers + 1,
637                                             0, data, temp);
638                                         USB_XFER_LOCK(xfer);
639                                         if (err) {
640                                                 err = USB_ERR_INVAL;
641                                                 break;
642                                         }
643                                 } else
644 #endif
645                                         usbd_copy_out(xfer->frbuffers + 1,
646                                             0, data, temp);
647                         }
648                 }
649                 /*
650                  * Clear "frlengths[0]" so that we don't send the setup
651                  * packet again:
652                  */
653                 usbd_xfer_set_frame_len(xfer, 0, 0);
654
655                 /* update length and data pointer */
656                 length -= temp;
657                 data = USB_ADD_BYTES(data, temp);
658
659                 if (actlen) {
660                         (*actlen) += temp;
661                 }
662                 /* check for timeout */
663
664                 delta_ticks = ticks - start_ticks;
665                 if (delta_ticks > max_ticks) {
666                         if (!err) {
667                                 err = USB_ERR_TIMEOUT;
668                         }
669                 }
670                 if (err) {
671                         break;
672                 }
673         }
674
675         if (err) {
676                 /*
677                  * Make sure that the control endpoint is no longer
678                  * blocked in case of a non-transfer related error:
679                  */
680                 usbd_transfer_stop(xfer);
681         }
682         USB_XFER_UNLOCK(xfer);
683
684 done:
685         sx_xunlock(&udev->ctrl_sx);
686
687         if (enum_locked)
688                 usbd_sr_lock(udev);
689
690         if ((mtx != NULL) && (mtx != &Giant))
691                 mtx_lock(mtx);
692
693         return ((usb_error_t)err);
694 }
695
696 /*------------------------------------------------------------------------*
697  *      usbd_do_request_proc - factored out code
698  *
699  * This function is factored out code. It does basically the same like
700  * usbd_do_request_flags, except it will check the status of the
701  * passed process argument before doing the USB request. If the
702  * process is draining the USB_ERR_IOERROR code will be returned. It
703  * is assumed that the mutex associated with the process is locked
704  * when calling this function.
705  *------------------------------------------------------------------------*/
706 usb_error_t
707 usbd_do_request_proc(struct usb_device *udev, struct usb_process *pproc,
708     struct usb_device_request *req, void *data, uint16_t flags,
709     uint16_t *actlen, usb_timeout_t timeout)
710 {
711         usb_error_t err;
712         uint16_t len;
713
714         /* get request data length */
715         len = UGETW(req->wLength);
716
717         /* check if the device is being detached */
718         if (usb_proc_is_gone(pproc)) {
719                 err = USB_ERR_IOERROR;
720                 goto done;
721         }
722
723         /* forward the USB request */
724         err = usbd_do_request_flags(udev, pproc->up_mtx,
725             req, data, flags, actlen, timeout);
726
727 done:
728         /* on failure we zero the data */
729         /* on short packet we zero the unused data */
730         if ((len != 0) && (req->bmRequestType & UE_DIR_IN)) {
731                 if (err)
732                         memset(data, 0, len);
733                 else if (actlen && *actlen != len)
734                         memset(((uint8_t *)data) + *actlen, 0, len - *actlen);
735         }
736         return (err);
737 }
738
739 /*------------------------------------------------------------------------*
740  *      usbd_req_reset_port
741  *
742  * This function will instruct an USB HUB to perform a reset sequence
743  * on the specified port number.
744  *
745  * Returns:
746  *    0: Success. The USB device should now be at address zero.
747  * Else: Failure. No USB device is present and the USB port should be
748  *       disabled.
749  *------------------------------------------------------------------------*/
750 usb_error_t
751 usbd_req_reset_port(struct usb_device *udev, struct mtx *mtx, uint8_t port)
752 {
753         struct usb_port_status ps;
754         usb_error_t err;
755         uint16_t n;
756
757 #ifdef USB_DEBUG
758         uint16_t pr_poll_delay;
759         uint16_t pr_recovery_delay;
760
761 #endif
762         err = usbd_req_set_port_feature(udev, mtx, port, UHF_PORT_RESET);
763         if (err) {
764                 goto done;
765         }
766 #ifdef USB_DEBUG
767         /* range check input parameters */
768         pr_poll_delay = usb_pr_poll_delay;
769         if (pr_poll_delay < 1) {
770                 pr_poll_delay = 1;
771         } else if (pr_poll_delay > 1000) {
772                 pr_poll_delay = 1000;
773         }
774         pr_recovery_delay = usb_pr_recovery_delay;
775         if (pr_recovery_delay > 1000) {
776                 pr_recovery_delay = 1000;
777         }
778 #endif
779         n = 0;
780         while (1) {
781 #ifdef USB_DEBUG
782                 /* wait for the device to recover from reset */
783                 usb_pause_mtx(mtx, USB_MS_TO_TICKS(pr_poll_delay));
784                 n += pr_poll_delay;
785 #else
786                 /* wait for the device to recover from reset */
787                 usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_PORT_RESET_DELAY));
788                 n += USB_PORT_RESET_DELAY;
789 #endif
790                 err = usbd_req_get_port_status(udev, mtx, &ps, port);
791                 if (err) {
792                         goto done;
793                 }
794                 /* if the device disappeared, just give up */
795                 if (!(UGETW(ps.wPortStatus) & UPS_CURRENT_CONNECT_STATUS)) {
796                         goto done;
797                 }
798                 /* check if reset is complete */
799                 if (UGETW(ps.wPortChange) & UPS_C_PORT_RESET) {
800                         break;
801                 }
802                 /* check for timeout */
803                 if (n > 1000) {
804                         n = 0;
805                         break;
806                 }
807         }
808
809         /* clear port reset first */
810         err = usbd_req_clear_port_feature(
811             udev, mtx, port, UHF_C_PORT_RESET);
812         if (err) {
813                 goto done;
814         }
815         /* check for timeout */
816         if (n == 0) {
817                 err = USB_ERR_TIMEOUT;
818                 goto done;
819         }
820 #ifdef USB_DEBUG
821         /* wait for the device to recover from reset */
822         usb_pause_mtx(mtx, USB_MS_TO_TICKS(pr_recovery_delay));
823 #else
824         /* wait for the device to recover from reset */
825         usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_PORT_RESET_RECOVERY));
826 #endif
827
828 done:
829         DPRINTFN(2, "port %d reset returning error=%s\n",
830             port, usbd_errstr(err));
831         return (err);
832 }
833
834 /*------------------------------------------------------------------------*
835  *      usbd_req_get_desc
836  *
837  * This function can be used to retrieve USB descriptors. It contains
838  * some additional logic like zeroing of missing descriptor bytes and
839  * retrying an USB descriptor in case of failure. The "min_len"
840  * argument specifies the minimum descriptor length. The "max_len"
841  * argument specifies the maximum descriptor length. If the real
842  * descriptor length is less than the minimum length the missing
843  * byte(s) will be zeroed. The type field, the second byte of the USB
844  * descriptor, will get forced to the correct type. If the "actlen"
845  * pointer is non-NULL, the actual length of the transfer will get
846  * stored in the 16-bit unsigned integer which it is pointing to. The
847  * first byte of the descriptor will not get updated. If the "actlen"
848  * pointer is NULL the first byte of the descriptor will get updated
849  * to reflect the actual length instead. If "min_len" is not equal to
850  * "max_len" then this function will try to retrive the beginning of
851  * the descriptor and base the maximum length on the first byte of the
852  * descriptor.
853  *
854  * Returns:
855  *    0: Success
856  * Else: Failure
857  *------------------------------------------------------------------------*/
858 usb_error_t
859 usbd_req_get_desc(struct usb_device *udev,
860     struct mtx *mtx, uint16_t *actlen, void *desc,
861     uint16_t min_len, uint16_t max_len,
862     uint16_t id, uint8_t type, uint8_t index,
863     uint8_t retries)
864 {
865         struct usb_device_request req;
866         uint8_t *buf;
867         usb_error_t err;
868
869         DPRINTFN(4, "id=%d, type=%d, index=%d, max_len=%d\n",
870             id, type, index, max_len);
871
872         req.bmRequestType = UT_READ_DEVICE;
873         req.bRequest = UR_GET_DESCRIPTOR;
874         USETW2(req.wValue, type, index);
875         USETW(req.wIndex, id);
876
877         while (1) {
878
879                 if ((min_len < 2) || (max_len < 2)) {
880                         err = USB_ERR_INVAL;
881                         goto done;
882                 }
883                 USETW(req.wLength, min_len);
884
885                 err = usbd_do_request_flags(udev, mtx, &req,
886                     desc, 0, NULL, 1000);
887
888                 if (err) {
889                         if (!retries) {
890                                 goto done;
891                         }
892                         retries--;
893
894                         usb_pause_mtx(mtx, hz / 5);
895
896                         continue;
897                 }
898                 buf = desc;
899
900                 if (min_len == max_len) {
901
902                         /* enforce correct length */
903                         if ((buf[0] > min_len) && (actlen == NULL))
904                                 buf[0] = min_len;
905
906                         /* enforce correct type */
907                         buf[1] = type;
908
909                         goto done;
910                 }
911                 /* range check */
912
913                 if (max_len > buf[0]) {
914                         max_len = buf[0];
915                 }
916                 /* zero minimum data */
917
918                 while (min_len > max_len) {
919                         min_len--;
920                         buf[min_len] = 0;
921                 }
922
923                 /* set new minimum length */
924
925                 min_len = max_len;
926         }
927 done:
928         if (actlen != NULL) {
929                 if (err)
930                         *actlen = 0;
931                 else
932                         *actlen = min_len;
933         }
934         return (err);
935 }
936
937 /*------------------------------------------------------------------------*
938  *      usbd_req_get_string_any
939  *
940  * This function will return the string given by "string_index"
941  * using the first language ID. The maximum length "len" includes
942  * the terminating zero. The "len" argument should be twice as
943  * big pluss 2 bytes, compared with the actual maximum string length !
944  *
945  * Returns:
946  *    0: Success
947  * Else: Failure
948  *------------------------------------------------------------------------*/
949 usb_error_t
950 usbd_req_get_string_any(struct usb_device *udev, struct mtx *mtx, char *buf,
951     uint16_t len, uint8_t string_index)
952 {
953         char *s;
954         uint8_t *temp;
955         uint16_t i;
956         uint16_t n;
957         uint16_t c;
958         uint8_t swap;
959         usb_error_t err;
960
961         if (len == 0) {
962                 /* should not happen */
963                 return (USB_ERR_NORMAL_COMPLETION);
964         }
965         if (string_index == 0) {
966                 /* this is the language table */
967                 buf[0] = 0;
968                 return (USB_ERR_INVAL);
969         }
970         if (udev->flags.no_strings) {
971                 buf[0] = 0;
972                 return (USB_ERR_STALLED);
973         }
974         err = usbd_req_get_string_desc
975             (udev, mtx, buf, len, udev->langid, string_index);
976         if (err) {
977                 buf[0] = 0;
978                 return (err);
979         }
980         temp = (uint8_t *)buf;
981
982         if (temp[0] < 2) {
983                 /* string length is too short */
984                 buf[0] = 0;
985                 return (USB_ERR_INVAL);
986         }
987         /* reserve one byte for terminating zero */
988         len--;
989
990         /* find maximum length */
991         s = buf;
992         n = (temp[0] / 2) - 1;
993         if (n > len) {
994                 n = len;
995         }
996         /* skip descriptor header */
997         temp += 2;
998
999         /* reset swap state */
1000         swap = 3;
1001
1002         /* convert and filter */
1003         for (i = 0; (i != n); i++) {
1004                 c = UGETW(temp + (2 * i));
1005
1006                 /* convert from Unicode, handle buggy strings */
1007                 if (((c & 0xff00) == 0) && (swap & 1)) {
1008                         /* Little Endian, default */
1009                         *s = c;
1010                         swap = 1;
1011                 } else if (((c & 0x00ff) == 0) && (swap & 2)) {
1012                         /* Big Endian */
1013                         *s = c >> 8;
1014                         swap = 2;
1015                 } else {
1016                         /* silently skip bad character */
1017                         continue;
1018                 }
1019
1020                 /*
1021                  * Filter by default - we don't allow greater and less than
1022                  * signs because they might confuse the dmesg printouts!
1023                  */
1024                 if ((*s == '<') || (*s == '>') || (!isprint(*s))) {
1025                         /* silently skip bad character */
1026                         continue;
1027                 }
1028                 s++;
1029         }
1030         *s = 0;                         /* zero terminate resulting string */
1031         return (USB_ERR_NORMAL_COMPLETION);
1032 }
1033
1034 /*------------------------------------------------------------------------*
1035  *      usbd_req_get_string_desc
1036  *
1037  * If you don't know the language ID, consider using
1038  * "usbd_req_get_string_any()".
1039  *
1040  * Returns:
1041  *    0: Success
1042  * Else: Failure
1043  *------------------------------------------------------------------------*/
1044 usb_error_t
1045 usbd_req_get_string_desc(struct usb_device *udev, struct mtx *mtx, void *sdesc,
1046     uint16_t max_len, uint16_t lang_id,
1047     uint8_t string_index)
1048 {
1049         return (usbd_req_get_desc(udev, mtx, NULL, sdesc, 2, max_len, lang_id,
1050             UDESC_STRING, string_index, 0));
1051 }
1052
1053 /*------------------------------------------------------------------------*
1054  *      usbd_req_get_config_desc_ptr
1055  *
1056  * This function is used in device side mode to retrieve the pointer
1057  * to the generated config descriptor. This saves allocating space for
1058  * an additional config descriptor when setting the configuration.
1059  *
1060  * Returns:
1061  *    0: Success
1062  * Else: Failure
1063  *------------------------------------------------------------------------*/
1064 usb_error_t
1065 usbd_req_get_descriptor_ptr(struct usb_device *udev,
1066     struct usb_config_descriptor **ppcd, uint16_t wValue)
1067 {
1068         struct usb_device_request req;
1069         usb_handle_req_t *hr_func;
1070         const void *ptr;
1071         uint16_t len;
1072         usb_error_t err;
1073
1074         req.bmRequestType = UT_READ_DEVICE;
1075         req.bRequest = UR_GET_DESCRIPTOR;
1076         USETW(req.wValue, wValue);
1077         USETW(req.wIndex, 0);
1078         USETW(req.wLength, 0);
1079
1080         ptr = NULL;
1081         len = 0;
1082
1083         hr_func = usbd_get_hr_func(udev);
1084
1085         if (hr_func == NULL)
1086                 err = USB_ERR_INVAL;
1087         else {
1088                 USB_BUS_LOCK(udev->bus);
1089                 err = (hr_func) (udev, &req, &ptr, &len);
1090                 USB_BUS_UNLOCK(udev->bus);
1091         }
1092
1093         if (err)
1094                 ptr = NULL;
1095         else if (ptr == NULL)
1096                 err = USB_ERR_INVAL;
1097
1098         *ppcd = __DECONST(struct usb_config_descriptor *, ptr);
1099
1100         return (err);
1101 }
1102
1103 /*------------------------------------------------------------------------*
1104  *      usbd_req_get_config_desc
1105  *
1106  * Returns:
1107  *    0: Success
1108  * Else: Failure
1109  *------------------------------------------------------------------------*/
1110 usb_error_t
1111 usbd_req_get_config_desc(struct usb_device *udev, struct mtx *mtx,
1112     struct usb_config_descriptor *d, uint8_t conf_index)
1113 {
1114         usb_error_t err;
1115
1116         DPRINTFN(4, "confidx=%d\n", conf_index);
1117
1118         err = usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
1119             sizeof(*d), 0, UDESC_CONFIG, conf_index, 0);
1120         if (err) {
1121                 goto done;
1122         }
1123         /* Extra sanity checking */
1124         if (UGETW(d->wTotalLength) < sizeof(*d)) {
1125                 err = USB_ERR_INVAL;
1126         }
1127 done:
1128         return (err);
1129 }
1130
1131 /*------------------------------------------------------------------------*
1132  *      usbd_req_get_config_desc_full
1133  *
1134  * This function gets the complete USB configuration descriptor and
1135  * ensures that "wTotalLength" is correct.
1136  *
1137  * Returns:
1138  *    0: Success
1139  * Else: Failure
1140  *------------------------------------------------------------------------*/
1141 usb_error_t
1142 usbd_req_get_config_desc_full(struct usb_device *udev, struct mtx *mtx,
1143     struct usb_config_descriptor **ppcd, struct malloc_type *mtype,
1144     uint8_t index)
1145 {
1146         struct usb_config_descriptor cd;
1147         struct usb_config_descriptor *cdesc;
1148         uint16_t len;
1149         usb_error_t err;
1150
1151         DPRINTFN(4, "index=%d\n", index);
1152
1153         *ppcd = NULL;
1154
1155         err = usbd_req_get_config_desc(udev, mtx, &cd, index);
1156         if (err) {
1157                 return (err);
1158         }
1159         /* get full descriptor */
1160         len = UGETW(cd.wTotalLength);
1161         if (len < sizeof(*cdesc)) {
1162                 /* corrupt descriptor */
1163                 return (USB_ERR_INVAL);
1164         }
1165         cdesc = malloc(len, mtype, M_WAITOK);
1166         if (cdesc == NULL) {
1167                 return (USB_ERR_NOMEM);
1168         }
1169         err = usbd_req_get_desc(udev, mtx, NULL, cdesc, len, len, 0,
1170             UDESC_CONFIG, index, 3);
1171         if (err) {
1172                 free(cdesc, mtype);
1173                 return (err);
1174         }
1175         /* make sure that the device is not fooling us: */
1176         USETW(cdesc->wTotalLength, len);
1177
1178         *ppcd = cdesc;
1179
1180         return (0);                     /* success */
1181 }
1182
1183 /*------------------------------------------------------------------------*
1184  *      usbd_req_get_device_desc
1185  *
1186  * Returns:
1187  *    0: Success
1188  * Else: Failure
1189  *------------------------------------------------------------------------*/
1190 usb_error_t
1191 usbd_req_get_device_desc(struct usb_device *udev, struct mtx *mtx,
1192     struct usb_device_descriptor *d)
1193 {
1194         DPRINTFN(4, "\n");
1195         return (usbd_req_get_desc(udev, mtx, NULL, d, sizeof(*d),
1196             sizeof(*d), 0, UDESC_DEVICE, 0, 3));
1197 }
1198
1199 /*------------------------------------------------------------------------*
1200  *      usbd_req_get_alt_interface_no
1201  *
1202  * Returns:
1203  *    0: Success
1204  * Else: Failure
1205  *------------------------------------------------------------------------*/
1206 usb_error_t
1207 usbd_req_get_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1208     uint8_t *alt_iface_no, uint8_t iface_index)
1209 {
1210         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1211         struct usb_device_request req;
1212
1213         if ((iface == NULL) || (iface->idesc == NULL))
1214                 return (USB_ERR_INVAL);
1215
1216         req.bmRequestType = UT_READ_INTERFACE;
1217         req.bRequest = UR_GET_INTERFACE;
1218         USETW(req.wValue, 0);
1219         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1220         req.wIndex[1] = 0;
1221         USETW(req.wLength, 1);
1222         return (usbd_do_request(udev, mtx, &req, alt_iface_no));
1223 }
1224
1225 /*------------------------------------------------------------------------*
1226  *      usbd_req_set_alt_interface_no
1227  *
1228  * Returns:
1229  *    0: Success
1230  * Else: Failure
1231  *------------------------------------------------------------------------*/
1232 usb_error_t
1233 usbd_req_set_alt_interface_no(struct usb_device *udev, struct mtx *mtx,
1234     uint8_t iface_index, uint8_t alt_no)
1235 {
1236         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1237         struct usb_device_request req;
1238
1239         if ((iface == NULL) || (iface->idesc == NULL))
1240                 return (USB_ERR_INVAL);
1241
1242         req.bmRequestType = UT_WRITE_INTERFACE;
1243         req.bRequest = UR_SET_INTERFACE;
1244         req.wValue[0] = alt_no;
1245         req.wValue[1] = 0;
1246         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1247         req.wIndex[1] = 0;
1248         USETW(req.wLength, 0);
1249         return (usbd_do_request(udev, mtx, &req, 0));
1250 }
1251
1252 /*------------------------------------------------------------------------*
1253  *      usbd_req_get_device_status
1254  *
1255  * Returns:
1256  *    0: Success
1257  * Else: Failure
1258  *------------------------------------------------------------------------*/
1259 usb_error_t
1260 usbd_req_get_device_status(struct usb_device *udev, struct mtx *mtx,
1261     struct usb_status *st)
1262 {
1263         struct usb_device_request req;
1264
1265         req.bmRequestType = UT_READ_DEVICE;
1266         req.bRequest = UR_GET_STATUS;
1267         USETW(req.wValue, 0);
1268         USETW(req.wIndex, 0);
1269         USETW(req.wLength, sizeof(*st));
1270         return (usbd_do_request(udev, mtx, &req, st));
1271 }
1272
1273 /*------------------------------------------------------------------------*
1274  *      usbd_req_get_hub_descriptor
1275  *
1276  * Returns:
1277  *    0: Success
1278  * Else: Failure
1279  *------------------------------------------------------------------------*/
1280 usb_error_t
1281 usbd_req_get_hub_descriptor(struct usb_device *udev, struct mtx *mtx,
1282     struct usb_hub_descriptor *hd, uint8_t nports)
1283 {
1284         struct usb_device_request req;
1285         uint16_t len = (nports + 7 + (8 * 8)) / 8;
1286
1287         req.bmRequestType = UT_READ_CLASS_DEVICE;
1288         req.bRequest = UR_GET_DESCRIPTOR;
1289         USETW2(req.wValue, UDESC_HUB, 0);
1290         USETW(req.wIndex, 0);
1291         USETW(req.wLength, len);
1292         return (usbd_do_request(udev, mtx, &req, hd));
1293 }
1294
1295 /*------------------------------------------------------------------------*
1296  *      usbd_req_get_hub_status
1297  *
1298  * Returns:
1299  *    0: Success
1300  * Else: Failure
1301  *------------------------------------------------------------------------*/
1302 usb_error_t
1303 usbd_req_get_hub_status(struct usb_device *udev, struct mtx *mtx,
1304     struct usb_hub_status *st)
1305 {
1306         struct usb_device_request req;
1307
1308         req.bmRequestType = UT_READ_CLASS_DEVICE;
1309         req.bRequest = UR_GET_STATUS;
1310         USETW(req.wValue, 0);
1311         USETW(req.wIndex, 0);
1312         USETW(req.wLength, sizeof(struct usb_hub_status));
1313         return (usbd_do_request(udev, mtx, &req, st));
1314 }
1315
1316 /*------------------------------------------------------------------------*
1317  *      usbd_req_set_address
1318  *
1319  * This function is used to set the address for an USB device. After
1320  * port reset the USB device will respond at address zero.
1321  *
1322  * Returns:
1323  *    0: Success
1324  * Else: Failure
1325  *------------------------------------------------------------------------*/
1326 usb_error_t
1327 usbd_req_set_address(struct usb_device *udev, struct mtx *mtx, uint16_t addr)
1328 {
1329         struct usb_device_request req;
1330
1331         DPRINTFN(6, "setting device address=%d\n", addr);
1332
1333         req.bmRequestType = UT_WRITE_DEVICE;
1334         req.bRequest = UR_SET_ADDRESS;
1335         USETW(req.wValue, addr);
1336         USETW(req.wIndex, 0);
1337         USETW(req.wLength, 0);
1338
1339         /* Setting the address should not take more than 1 second ! */
1340         return (usbd_do_request_flags(udev, mtx, &req, NULL,
1341             USB_DELAY_STATUS_STAGE, NULL, 1000));
1342 }
1343
1344 /*------------------------------------------------------------------------*
1345  *      usbd_req_get_port_status
1346  *
1347  * Returns:
1348  *    0: Success
1349  * Else: Failure
1350  *------------------------------------------------------------------------*/
1351 usb_error_t
1352 usbd_req_get_port_status(struct usb_device *udev, struct mtx *mtx,
1353     struct usb_port_status *ps, uint8_t port)
1354 {
1355         struct usb_device_request req;
1356
1357         req.bmRequestType = UT_READ_CLASS_OTHER;
1358         req.bRequest = UR_GET_STATUS;
1359         USETW(req.wValue, 0);
1360         req.wIndex[0] = port;
1361         req.wIndex[1] = 0;
1362         USETW(req.wLength, sizeof *ps);
1363         return (usbd_do_request(udev, mtx, &req, ps));
1364 }
1365
1366 /*------------------------------------------------------------------------*
1367  *      usbd_req_clear_hub_feature
1368  *
1369  * Returns:
1370  *    0: Success
1371  * Else: Failure
1372  *------------------------------------------------------------------------*/
1373 usb_error_t
1374 usbd_req_clear_hub_feature(struct usb_device *udev, struct mtx *mtx,
1375     uint16_t sel)
1376 {
1377         struct usb_device_request req;
1378
1379         req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1380         req.bRequest = UR_CLEAR_FEATURE;
1381         USETW(req.wValue, sel);
1382         USETW(req.wIndex, 0);
1383         USETW(req.wLength, 0);
1384         return (usbd_do_request(udev, mtx, &req, 0));
1385 }
1386
1387 /*------------------------------------------------------------------------*
1388  *      usbd_req_set_hub_feature
1389  *
1390  * Returns:
1391  *    0: Success
1392  * Else: Failure
1393  *------------------------------------------------------------------------*/
1394 usb_error_t
1395 usbd_req_set_hub_feature(struct usb_device *udev, struct mtx *mtx,
1396     uint16_t sel)
1397 {
1398         struct usb_device_request req;
1399
1400         req.bmRequestType = UT_WRITE_CLASS_DEVICE;
1401         req.bRequest = UR_SET_FEATURE;
1402         USETW(req.wValue, sel);
1403         USETW(req.wIndex, 0);
1404         USETW(req.wLength, 0);
1405         return (usbd_do_request(udev, mtx, &req, 0));
1406 }
1407
1408 /*------------------------------------------------------------------------*
1409  *      usbd_req_clear_port_feature
1410  *
1411  * Returns:
1412  *    0: Success
1413  * Else: Failure
1414  *------------------------------------------------------------------------*/
1415 usb_error_t
1416 usbd_req_clear_port_feature(struct usb_device *udev, struct mtx *mtx,
1417     uint8_t port, uint16_t sel)
1418 {
1419         struct usb_device_request req;
1420
1421         req.bmRequestType = UT_WRITE_CLASS_OTHER;
1422         req.bRequest = UR_CLEAR_FEATURE;
1423         USETW(req.wValue, sel);
1424         req.wIndex[0] = port;
1425         req.wIndex[1] = 0;
1426         USETW(req.wLength, 0);
1427         return (usbd_do_request(udev, mtx, &req, 0));
1428 }
1429
1430 /*------------------------------------------------------------------------*
1431  *      usbd_req_set_port_feature
1432  *
1433  * Returns:
1434  *    0: Success
1435  * Else: Failure
1436  *------------------------------------------------------------------------*/
1437 usb_error_t
1438 usbd_req_set_port_feature(struct usb_device *udev, struct mtx *mtx,
1439     uint8_t port, uint16_t sel)
1440 {
1441         struct usb_device_request req;
1442
1443         req.bmRequestType = UT_WRITE_CLASS_OTHER;
1444         req.bRequest = UR_SET_FEATURE;
1445         USETW(req.wValue, sel);
1446         req.wIndex[0] = port;
1447         req.wIndex[1] = 0;
1448         USETW(req.wLength, 0);
1449         return (usbd_do_request(udev, mtx, &req, 0));
1450 }
1451
1452 /*------------------------------------------------------------------------*
1453  *      usbd_req_set_protocol
1454  *
1455  * Returns:
1456  *    0: Success
1457  * Else: Failure
1458  *------------------------------------------------------------------------*/
1459 usb_error_t
1460 usbd_req_set_protocol(struct usb_device *udev, struct mtx *mtx,
1461     uint8_t iface_index, uint16_t report)
1462 {
1463         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1464         struct usb_device_request req;
1465
1466         if ((iface == NULL) || (iface->idesc == NULL)) {
1467                 return (USB_ERR_INVAL);
1468         }
1469         DPRINTFN(5, "iface=%p, report=%d, endpt=%d\n",
1470             iface, report, iface->idesc->bInterfaceNumber);
1471
1472         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1473         req.bRequest = UR_SET_PROTOCOL;
1474         USETW(req.wValue, report);
1475         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1476         req.wIndex[1] = 0;
1477         USETW(req.wLength, 0);
1478         return (usbd_do_request(udev, mtx, &req, 0));
1479 }
1480
1481 /*------------------------------------------------------------------------*
1482  *      usbd_req_set_report
1483  *
1484  * Returns:
1485  *    0: Success
1486  * Else: Failure
1487  *------------------------------------------------------------------------*/
1488 usb_error_t
1489 usbd_req_set_report(struct usb_device *udev, struct mtx *mtx, void *data, uint16_t len,
1490     uint8_t iface_index, uint8_t type, uint8_t id)
1491 {
1492         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1493         struct usb_device_request req;
1494
1495         if ((iface == NULL) || (iface->idesc == NULL)) {
1496                 return (USB_ERR_INVAL);
1497         }
1498         DPRINTFN(5, "len=%d\n", len);
1499
1500         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1501         req.bRequest = UR_SET_REPORT;
1502         USETW2(req.wValue, type, id);
1503         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1504         req.wIndex[1] = 0;
1505         USETW(req.wLength, len);
1506         return (usbd_do_request(udev, mtx, &req, data));
1507 }
1508
1509 /*------------------------------------------------------------------------*
1510  *      usbd_req_get_report
1511  *
1512  * Returns:
1513  *    0: Success
1514  * Else: Failure
1515  *------------------------------------------------------------------------*/
1516 usb_error_t
1517 usbd_req_get_report(struct usb_device *udev, struct mtx *mtx, void *data,
1518     uint16_t len, uint8_t iface_index, uint8_t type, uint8_t id)
1519 {
1520         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1521         struct usb_device_request req;
1522
1523         if ((iface == NULL) || (iface->idesc == NULL) || (id == 0)) {
1524                 return (USB_ERR_INVAL);
1525         }
1526         DPRINTFN(5, "len=%d\n", len);
1527
1528         req.bmRequestType = UT_READ_CLASS_INTERFACE;
1529         req.bRequest = UR_GET_REPORT;
1530         USETW2(req.wValue, type, id);
1531         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1532         req.wIndex[1] = 0;
1533         USETW(req.wLength, len);
1534         return (usbd_do_request(udev, mtx, &req, data));
1535 }
1536
1537 /*------------------------------------------------------------------------*
1538  *      usbd_req_set_idle
1539  *
1540  * Returns:
1541  *    0: Success
1542  * Else: Failure
1543  *------------------------------------------------------------------------*/
1544 usb_error_t
1545 usbd_req_set_idle(struct usb_device *udev, struct mtx *mtx,
1546     uint8_t iface_index, uint8_t duration, uint8_t id)
1547 {
1548         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1549         struct usb_device_request req;
1550
1551         if ((iface == NULL) || (iface->idesc == NULL)) {
1552                 return (USB_ERR_INVAL);
1553         }
1554         DPRINTFN(5, "%d %d\n", duration, id);
1555
1556         req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
1557         req.bRequest = UR_SET_IDLE;
1558         USETW2(req.wValue, duration, id);
1559         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1560         req.wIndex[1] = 0;
1561         USETW(req.wLength, 0);
1562         return (usbd_do_request(udev, mtx, &req, 0));
1563 }
1564
1565 /*------------------------------------------------------------------------*
1566  *      usbd_req_get_report_descriptor
1567  *
1568  * Returns:
1569  *    0: Success
1570  * Else: Failure
1571  *------------------------------------------------------------------------*/
1572 usb_error_t
1573 usbd_req_get_report_descriptor(struct usb_device *udev, struct mtx *mtx,
1574     void *d, uint16_t size, uint8_t iface_index)
1575 {
1576         struct usb_interface *iface = usbd_get_iface(udev, iface_index);
1577         struct usb_device_request req;
1578
1579         if ((iface == NULL) || (iface->idesc == NULL)) {
1580                 return (USB_ERR_INVAL);
1581         }
1582         req.bmRequestType = UT_READ_INTERFACE;
1583         req.bRequest = UR_GET_DESCRIPTOR;
1584         USETW2(req.wValue, UDESC_REPORT, 0);    /* report id should be 0 */
1585         req.wIndex[0] = iface->idesc->bInterfaceNumber;
1586         req.wIndex[1] = 0;
1587         USETW(req.wLength, size);
1588         return (usbd_do_request(udev, mtx, &req, d));
1589 }
1590
1591 /*------------------------------------------------------------------------*
1592  *      usbd_req_set_config
1593  *
1594  * This function is used to select the current configuration number in
1595  * both USB device side mode and USB host side mode. When setting the
1596  * configuration the function of the interfaces can change.
1597  *
1598  * Returns:
1599  *    0: Success
1600  * Else: Failure
1601  *------------------------------------------------------------------------*/
1602 usb_error_t
1603 usbd_req_set_config(struct usb_device *udev, struct mtx *mtx, uint8_t conf)
1604 {
1605         struct usb_device_request req;
1606
1607         DPRINTF("setting config %d\n", conf);
1608
1609         /* do "set configuration" request */
1610
1611         req.bmRequestType = UT_WRITE_DEVICE;
1612         req.bRequest = UR_SET_CONFIG;
1613         req.wValue[0] = conf;
1614         req.wValue[1] = 0;
1615         USETW(req.wIndex, 0);
1616         USETW(req.wLength, 0);
1617         return (usbd_do_request(udev, mtx, &req, 0));
1618 }
1619
1620 /*------------------------------------------------------------------------*
1621  *      usbd_req_get_config
1622  *
1623  * Returns:
1624  *    0: Success
1625  * Else: Failure
1626  *------------------------------------------------------------------------*/
1627 usb_error_t
1628 usbd_req_get_config(struct usb_device *udev, struct mtx *mtx, uint8_t *pconf)
1629 {
1630         struct usb_device_request req;
1631
1632         req.bmRequestType = UT_READ_DEVICE;
1633         req.bRequest = UR_GET_CONFIG;
1634         USETW(req.wValue, 0);
1635         USETW(req.wIndex, 0);
1636         USETW(req.wLength, 1);
1637         return (usbd_do_request(udev, mtx, &req, pconf));
1638 }
1639
1640 /*------------------------------------------------------------------------*
1641  *      usbd_req_re_enumerate
1642  *
1643  * NOTE: After this function returns the hardware is in the
1644  * unconfigured state! The application is responsible for setting a
1645  * new configuration.
1646  *
1647  * Returns:
1648  *    0: Success
1649  * Else: Failure
1650  *------------------------------------------------------------------------*/
1651 usb_error_t
1652 usbd_req_re_enumerate(struct usb_device *udev, struct mtx *mtx)
1653 {
1654         struct usb_device *parent_hub;
1655         usb_error_t err;
1656         uint8_t old_addr;
1657         uint8_t do_retry = 1;
1658
1659         if (udev->flags.usb_mode != USB_MODE_HOST) {
1660                 return (USB_ERR_INVAL);
1661         }
1662         old_addr = udev->address;
1663         parent_hub = udev->parent_hub;
1664         if (parent_hub == NULL) {
1665                 return (USB_ERR_INVAL);
1666         }
1667 retry:
1668         err = usbd_req_reset_port(parent_hub, mtx, udev->port_no);
1669         if (err) {
1670                 DPRINTFN(0, "addr=%d, port reset failed, %s\n", 
1671                     old_addr, usbd_errstr(err));
1672                 goto done;
1673         }
1674         /*
1675          * After that the port has been reset our device should be at
1676          * address zero:
1677          */
1678         udev->address = USB_START_ADDR;
1679
1680         /* reset "bMaxPacketSize" */
1681         udev->ddesc.bMaxPacketSize = USB_MAX_IPACKET;
1682
1683         /*
1684          * Restore device address:
1685          */
1686         err = usbd_req_set_address(udev, mtx, old_addr);
1687         if (err) {
1688                 /* XXX ignore any errors! */
1689                 DPRINTFN(0, "addr=%d, set address failed! (%s, ignored)\n",
1690                     old_addr, usbd_errstr(err));
1691         }
1692         /* restore device address */
1693         udev->address = old_addr;
1694
1695         /* allow device time to set new address */
1696         usb_pause_mtx(mtx, USB_MS_TO_TICKS(USB_SET_ADDRESS_SETTLE));
1697
1698         /* get the device descriptor */
1699         err = usbd_req_get_desc(udev, mtx, NULL, &udev->ddesc,
1700             USB_MAX_IPACKET, USB_MAX_IPACKET, 0, UDESC_DEVICE, 0, 0);
1701         if (err) {
1702                 DPRINTFN(0, "getting device descriptor "
1703                     "at addr %d failed, %s\n", udev->address,
1704                     usbd_errstr(err));
1705                 goto done;
1706         }
1707         /* get the full device descriptor */
1708         err = usbd_req_get_device_desc(udev, mtx, &udev->ddesc);
1709         if (err) {
1710                 DPRINTFN(0, "addr=%d, getting device "
1711                     "descriptor failed, %s\n", old_addr, 
1712                     usbd_errstr(err));
1713                 goto done;
1714         }
1715 done:
1716         if (err && do_retry) {
1717                 /* give the USB firmware some time to load */
1718                 usb_pause_mtx(mtx, hz / 2);
1719                 /* no more retries after this retry */
1720                 do_retry = 0;
1721                 /* try again */
1722                 goto retry;
1723         }
1724         /* restore address */
1725         udev->address = old_addr;
1726         return (err);
1727 }
1728
1729 /*------------------------------------------------------------------------*
1730  *      usbd_req_clear_device_feature
1731  *
1732  * Returns:
1733  *    0: Success
1734  * Else: Failure
1735  *------------------------------------------------------------------------*/
1736 usb_error_t
1737 usbd_req_clear_device_feature(struct usb_device *udev, struct mtx *mtx,
1738     uint16_t sel)
1739 {
1740         struct usb_device_request req;
1741
1742         req.bmRequestType = UT_WRITE_DEVICE;
1743         req.bRequest = UR_CLEAR_FEATURE;
1744         USETW(req.wValue, sel);
1745         USETW(req.wIndex, 0);
1746         USETW(req.wLength, 0);
1747         return (usbd_do_request(udev, mtx, &req, 0));
1748 }
1749
1750 /*------------------------------------------------------------------------*
1751  *      usbd_req_set_device_feature
1752  *
1753  * Returns:
1754  *    0: Success
1755  * Else: Failure
1756  *------------------------------------------------------------------------*/
1757 usb_error_t
1758 usbd_req_set_device_feature(struct usb_device *udev, struct mtx *mtx,
1759     uint16_t sel)
1760 {
1761         struct usb_device_request req;
1762
1763         req.bmRequestType = UT_WRITE_DEVICE;
1764         req.bRequest = UR_SET_FEATURE;
1765         USETW(req.wValue, sel);
1766         USETW(req.wIndex, 0);
1767         USETW(req.wLength, 0);
1768         return (usbd_do_request(udev, mtx, &req, 0));
1769 }