3 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/stdint.h>
28 #include <sys/stddef.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/types.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
35 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/sysctl.h>
41 #include <sys/unistd.h>
42 #include <sys/callout.h>
43 #include <sys/malloc.h>
46 #include <dev/usb/usb.h>
47 #include <dev/usb/usbdi.h>
48 #include <dev/usb/usbdi_util.h>
50 #define USB_DEBUG_VAR usb_debug
52 #include <dev/usb/usb_core.h>
53 #include <dev/usb/usb_busdma.h>
54 #include <dev/usb/usb_process.h>
55 #include <dev/usb/usb_transfer.h>
56 #include <dev/usb/usb_device.h>
57 #include <dev/usb/usb_debug.h>
58 #include <dev/usb/usb_util.h>
60 #include <dev/usb/usb_controller.h>
61 #include <dev/usb/usb_bus.h>
63 struct usb_std_packet_size {
65 uint16_t min; /* inclusive */
66 uint16_t max; /* inclusive */
72 static usb_callback_t usb_request_callback;
74 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
76 /* This transfer is used for generic control endpoint transfers */
80 .endpoint = 0x00, /* Control endpoint */
81 .direction = UE_DIR_ANY,
82 .bufsize = USB_EP0_BUFSIZE, /* bytes */
83 .flags = {.proxy_buffer = 1,},
84 .callback = &usb_request_callback,
85 .usb_mode = USB_MODE_DUAL, /* both modes */
88 /* This transfer is used for generic clear stall only */
92 .endpoint = 0x00, /* Control pipe */
93 .direction = UE_DIR_ANY,
94 .bufsize = sizeof(struct usb_device_request),
95 .callback = &usb_do_clear_stall_callback,
96 .timeout = 1000, /* 1 second */
97 .interval = 50, /* 50ms */
98 .usb_mode = USB_MODE_HOST,
102 /* function prototypes */
104 static void usbd_update_max_frame_size(struct usb_xfer *);
105 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
106 static void usbd_control_transfer_init(struct usb_xfer *);
107 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
108 static void usb_callback_proc(struct usb_proc_msg *);
109 static void usbd_callback_ss_done_defer(struct usb_xfer *);
110 static void usbd_callback_wrapper(struct usb_xfer_queue *);
111 static void usbd_transfer_start_cb(void *);
112 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
113 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
114 uint8_t type, enum usb_dev_speed speed);
116 /*------------------------------------------------------------------------*
117 * usb_request_callback
118 *------------------------------------------------------------------------*/
120 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
122 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
123 usb_handle_request_callback(xfer, error);
125 usbd_do_request_callback(xfer, error);
128 /*------------------------------------------------------------------------*
129 * usbd_update_max_frame_size
131 * This function updates the maximum frame size, hence high speed USB
132 * can transfer multiple consecutive packets.
133 *------------------------------------------------------------------------*/
135 usbd_update_max_frame_size(struct usb_xfer *xfer)
137 /* compute maximum frame size */
138 /* this computation should not overflow 16-bit */
139 /* max = 15 * 1024 */
141 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
144 /*------------------------------------------------------------------------*
147 * The following function is called when we need to
148 * synchronize with DMA hardware.
151 * 0: no DMA delay required
152 * Else: milliseconds of DMA delay
153 *------------------------------------------------------------------------*/
155 usbd_get_dma_delay(struct usb_device *udev)
157 struct usb_bus_methods *mtod;
160 mtod = udev->bus->methods;
163 if (mtod->get_dma_delay) {
164 (mtod->get_dma_delay) (udev, &temp);
166 * Round up and convert to milliseconds. Note that we use
167 * 1024 milliseconds per second. to save a division.
175 /*------------------------------------------------------------------------*
176 * usbd_transfer_setup_sub_malloc
178 * This function will allocate one or more DMA'able memory chunks
179 * according to "size", "align" and "count" arguments. "ppc" is
180 * pointed to a linear array of USB page caches afterwards.
185 *------------------------------------------------------------------------*/
188 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
189 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
192 struct usb_page_cache *pc;
202 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
204 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
207 return (0); /* nothing to allocate */
210 * Make sure that the size is aligned properly.
212 size = -((-size) & (-align));
215 * Try multi-allocation chunks to reduce the number of DMA
216 * allocations, hence DMA allocations are slow.
218 if (size >= PAGE_SIZE) {
222 /* compute number of objects per page */
223 n_obj = (PAGE_SIZE / size);
225 * Compute number of DMA chunks, rounded up
228 n_dma_pc = ((count + n_obj - 1) / n_obj);
231 if (parm->buf == NULL) {
233 parm->dma_page_ptr += n_dma_pc;
234 parm->dma_page_cache_ptr += n_dma_pc;
235 parm->dma_page_ptr += count;
236 parm->xfer_page_cache_ptr += count;
239 for (x = 0; x != n_dma_pc; x++) {
240 /* need to initialize the page cache */
241 parm->dma_page_cache_ptr[x].tag_parent =
242 &parm->curr_xfer->xroot->dma_parent_tag;
244 for (x = 0; x != count; x++) {
245 /* need to initialize the page cache */
246 parm->xfer_page_cache_ptr[x].tag_parent =
247 &parm->curr_xfer->xroot->dma_parent_tag;
251 *ppc = parm->xfer_page_cache_ptr;
253 r = count; /* set remainder count */
254 z = n_obj * size; /* set allocation size */
255 pc = parm->xfer_page_cache_ptr;
256 pg = parm->dma_page_ptr;
258 for (x = 0; x != n_dma_pc; x++) {
261 /* compute last remainder */
265 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
267 return (1); /* failure */
269 /* Set beginning of current buffer */
270 buf = parm->dma_page_cache_ptr->buffer;
271 /* Make room for one DMA page cache and one page */
272 parm->dma_page_cache_ptr++;
275 for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
277 /* Load sub-chunk into DMA */
278 if (usb_pc_dmamap_create(pc, size)) {
279 return (1); /* failure */
281 pc->buffer = USB_ADD_BYTES(buf, y * size);
284 mtx_lock(pc->tag_parent->mtx);
285 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
286 mtx_unlock(pc->tag_parent->mtx);
287 return (1); /* failure */
289 mtx_unlock(pc->tag_parent->mtx);
293 parm->xfer_page_cache_ptr = pc;
294 parm->dma_page_ptr = pg;
299 /*------------------------------------------------------------------------*
300 * usbd_transfer_setup_sub - transfer setup subroutine
302 * This function must be called from the "xfer_setup" callback of the
303 * USB Host or Device controller driver when setting up an USB
304 * transfer. This function will setup correct packet sizes, buffer
305 * sizes, flags and more, that are stored in the "usb_xfer"
307 *------------------------------------------------------------------------*/
309 usbd_transfer_setup_sub(struct usb_setup_params *parm)
315 struct usb_xfer *xfer = parm->curr_xfer;
316 const struct usb_config *setup = parm->curr_setup;
317 struct usb_endpoint_ss_comp_descriptor *ecomp;
318 struct usb_endpoint_descriptor *edesc;
319 struct usb_std_packet_size std_size;
320 usb_frcount_t n_frlengths;
321 usb_frcount_t n_frbuffers;
327 * Sanity check. The following parameters must be initialized before
328 * calling this function.
330 if ((parm->hc_max_packet_size == 0) ||
331 (parm->hc_max_packet_count == 0) ||
332 (parm->hc_max_frame_size == 0)) {
333 parm->err = USB_ERR_INVAL;
336 edesc = xfer->endpoint->edesc;
337 ecomp = xfer->endpoint->ecomp;
339 type = (edesc->bmAttributes & UE_XFERTYPE);
341 xfer->flags = setup->flags;
342 xfer->nframes = setup->frames;
343 xfer->timeout = setup->timeout;
344 xfer->callback = setup->callback;
345 xfer->interval = setup->interval;
346 xfer->endpointno = edesc->bEndpointAddress;
347 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
348 xfer->max_packet_count = 1;
349 /* make a shadow copy: */
350 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
352 parm->bufsize = setup->bufsize;
354 switch (parm->speed) {
359 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
361 /* check for invalid max packet count */
362 if (xfer->max_packet_count > 3)
363 xfer->max_packet_count = 3;
368 xfer->max_packet_size &= 0x7FF;
370 case USB_SPEED_SUPER:
371 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
374 xfer->max_packet_count += ecomp->bMaxBurst;
376 if ((xfer->max_packet_count == 0) ||
377 (xfer->max_packet_count > 16))
378 xfer->max_packet_count = 16;
382 xfer->max_packet_count = 1;
388 mult = (ecomp->bmAttributes & 3) + 1;
392 xfer->max_packet_count *= mult;
398 xfer->max_packet_size &= 0x7FF;
403 /* range check "max_packet_count" */
405 if (xfer->max_packet_count > parm->hc_max_packet_count) {
406 xfer->max_packet_count = parm->hc_max_packet_count;
408 /* filter "wMaxPacketSize" according to HC capabilities */
410 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
411 (xfer->max_packet_size == 0)) {
412 xfer->max_packet_size = parm->hc_max_packet_size;
414 /* filter "wMaxPacketSize" according to standard sizes */
416 usbd_get_std_packet_size(&std_size, type, parm->speed);
418 if (std_size.range.min || std_size.range.max) {
420 if (xfer->max_packet_size < std_size.range.min) {
421 xfer->max_packet_size = std_size.range.min;
423 if (xfer->max_packet_size > std_size.range.max) {
424 xfer->max_packet_size = std_size.range.max;
428 if (xfer->max_packet_size >= std_size.fixed[3]) {
429 xfer->max_packet_size = std_size.fixed[3];
430 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
431 xfer->max_packet_size = std_size.fixed[2];
432 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
433 xfer->max_packet_size = std_size.fixed[1];
435 /* only one possibility left */
436 xfer->max_packet_size = std_size.fixed[0];
440 /* compute "max_frame_size" */
442 usbd_update_max_frame_size(xfer);
444 /* check interrupt interval and transfer pre-delay */
446 if (type == UE_ISOCHRONOUS) {
448 uint16_t frame_limit;
450 xfer->interval = 0; /* not used, must be zero */
451 xfer->flags_int.isochronous_xfr = 1; /* set flag */
453 if (xfer->timeout == 0) {
455 * set a default timeout in
456 * case something goes wrong!
458 xfer->timeout = 1000 / 4;
460 switch (parm->speed) {
463 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
467 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
468 xfer->fps_shift = edesc->bInterval;
469 if (xfer->fps_shift > 0)
471 if (xfer->fps_shift > 3)
473 if (xfer->flags.pre_scale_frames != 0)
474 xfer->nframes <<= (3 - xfer->fps_shift);
478 if (xfer->nframes > frame_limit) {
480 * this is not going to work
483 parm->err = USB_ERR_INVAL;
486 if (xfer->nframes == 0) {
488 * this is not a valid value
490 parm->err = USB_ERR_ZERO_NFRAMES;
496 * If a value is specified use that else check the
497 * endpoint descriptor!
499 if (type == UE_INTERRUPT) {
503 if (xfer->interval == 0) {
505 xfer->interval = edesc->bInterval;
507 switch (parm->speed) {
513 if (xfer->interval < 4)
515 else if (xfer->interval > 16)
516 xfer->interval = (1 << (16 - 4));
519 (1 << (xfer->interval - 4));
524 if (xfer->interval == 0) {
526 * One millisecond is the smallest
527 * interval we support:
535 while ((temp != 0) && (temp < xfer->interval)) {
540 switch (parm->speed) {
545 xfer->fps_shift += 3;
552 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
553 * to be equal to zero when setting up USB transfers, hence
554 * this leads to alot of extra code in the USB kernel.
557 if ((xfer->max_frame_size == 0) ||
558 (xfer->max_packet_size == 0)) {
562 if ((parm->bufsize <= MIN_PKT) &&
563 (type != UE_CONTROL) &&
567 xfer->max_packet_size = MIN_PKT;
568 xfer->max_packet_count = 1;
569 parm->bufsize = 0; /* automatic setup length */
570 usbd_update_max_frame_size(xfer);
573 parm->err = USB_ERR_ZERO_MAXP;
582 * check if we should setup a default
586 if (parm->bufsize == 0) {
588 parm->bufsize = xfer->max_frame_size;
590 if (type == UE_ISOCHRONOUS) {
591 parm->bufsize *= xfer->nframes;
595 * check if we are about to setup a proxy
599 if (xfer->flags.proxy_buffer) {
601 /* round bufsize up */
603 parm->bufsize += (xfer->max_frame_size - 1);
605 if (parm->bufsize < xfer->max_frame_size) {
606 /* length wrapped around */
607 parm->err = USB_ERR_INVAL;
610 /* subtract remainder */
612 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
614 /* add length of USB device request structure, if any */
616 if (type == UE_CONTROL) {
617 parm->bufsize += REQ_SIZE; /* SETUP message */
620 xfer->max_data_length = parm->bufsize;
622 /* Setup "n_frlengths" and "n_frbuffers" */
624 if (type == UE_ISOCHRONOUS) {
625 n_frlengths = xfer->nframes;
629 if (type == UE_CONTROL) {
630 xfer->flags_int.control_xfr = 1;
631 if (xfer->nframes == 0) {
632 if (parm->bufsize <= REQ_SIZE) {
634 * there will never be any data
643 if (xfer->nframes == 0) {
648 n_frlengths = xfer->nframes;
649 n_frbuffers = xfer->nframes;
653 * check if we have room for the
654 * USB device request structure:
657 if (type == UE_CONTROL) {
659 if (xfer->max_data_length < REQ_SIZE) {
660 /* length wrapped around or too small bufsize */
661 parm->err = USB_ERR_INVAL;
664 xfer->max_data_length -= REQ_SIZE;
666 /* setup "frlengths" */
667 xfer->frlengths = parm->xfer_length_ptr;
668 parm->xfer_length_ptr += n_frlengths;
670 /* setup "frbuffers" */
671 xfer->frbuffers = parm->xfer_page_cache_ptr;
672 parm->xfer_page_cache_ptr += n_frbuffers;
674 /* initialize max frame count */
675 xfer->max_frame_count = xfer->nframes;
678 * check if we need to setup
682 if (!xfer->flags.ext_buffer) {
685 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
690 USB_ADD_BYTES(parm->buf, parm->size[0]);
692 usbd_xfer_set_frame_offset(xfer, 0, 0);
694 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
695 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
698 parm->size[0] += parm->bufsize;
700 /* align data again */
701 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
704 * Compute maximum buffer size
707 if (parm->bufsize_max < parm->bufsize) {
708 parm->bufsize_max = parm->bufsize;
711 if (xfer->flags_int.bdma_enable) {
713 * Setup "dma_page_ptr".
715 * Proof for formula below:
717 * Assume there are three USB frames having length "a", "b" and
718 * "c". These USB frames will at maximum need "z"
719 * "usb_page" structures. "z" is given by:
721 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
722 * ((c / USB_PAGE_SIZE) + 2);
724 * Constraining "a", "b" and "c" like this:
726 * (a + b + c) <= parm->bufsize
730 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
732 * Here is the general formula:
734 xfer->dma_page_ptr = parm->dma_page_ptr;
735 parm->dma_page_ptr += (2 * n_frbuffers);
736 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
740 /* correct maximum data length */
741 xfer->max_data_length = 0;
743 /* subtract USB frame remainder from "hc_max_frame_size" */
745 xfer->max_hc_frame_size =
746 (parm->hc_max_frame_size -
747 (parm->hc_max_frame_size % xfer->max_frame_size));
749 if (xfer->max_hc_frame_size == 0) {
750 parm->err = USB_ERR_INVAL;
754 /* initialize frame buffers */
757 for (x = 0; x != n_frbuffers; x++) {
758 xfer->frbuffers[x].tag_parent =
759 &xfer->xroot->dma_parent_tag;
761 if (xfer->flags_int.bdma_enable &&
762 (parm->bufsize_max > 0)) {
764 if (usb_pc_dmamap_create(
766 parm->bufsize_max)) {
767 parm->err = USB_ERR_NOMEM;
777 * Set some dummy values so that we avoid division by zero:
779 xfer->max_hc_frame_size = 1;
780 xfer->max_frame_size = 1;
781 xfer->max_packet_size = 1;
782 xfer->max_data_length = 0;
784 xfer->max_frame_count = 0;
788 /*------------------------------------------------------------------------*
789 * usbd_transfer_setup - setup an array of USB transfers
791 * NOTE: You must always call "usbd_transfer_unsetup" after calling
792 * "usbd_transfer_setup" if success was returned.
794 * The idea is that the USB device driver should pre-allocate all its
795 * transfers by one call to this function.
800 *------------------------------------------------------------------------*/
802 usbd_transfer_setup(struct usb_device *udev,
803 const uint8_t *ifaces, struct usb_xfer **ppxfer,
804 const struct usb_config *setup_start, uint16_t n_setup,
805 void *priv_sc, struct mtx *xfer_mtx)
807 struct usb_xfer dummy;
808 struct usb_setup_params parm;
809 const struct usb_config *setup_end = setup_start + n_setup;
810 const struct usb_config *setup;
811 struct usb_endpoint *ep;
812 struct usb_xfer_root *info;
813 struct usb_xfer *xfer;
822 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
823 "usbd_transfer_setup can sleep!");
825 /* do some checking first */
828 DPRINTFN(6, "setup array has zero length!\n");
829 return (USB_ERR_INVAL);
832 DPRINTFN(6, "ifaces array is NULL!\n");
833 return (USB_ERR_INVAL);
835 if (xfer_mtx == NULL) {
836 DPRINTFN(6, "using global lock\n");
840 for (setup = setup_start, n = 0;
841 setup != setup_end; setup++, n++) {
842 if (setup->bufsize == (usb_frlength_t)-1) {
843 parm.err = USB_ERR_BAD_BUFSIZE;
844 DPRINTF("invalid bufsize\n");
846 if (setup->callback == NULL) {
847 parm.err = USB_ERR_NO_CALLBACK;
848 DPRINTF("no callback\n");
856 bzero(&parm, sizeof(parm));
859 parm.speed = usbd_get_speed(udev);
860 parm.hc_max_packet_count = 1;
862 if (parm.speed >= USB_SPEED_MAX) {
863 parm.err = USB_ERR_INVAL;
866 /* setup all transfers */
872 * Initialize the "usb_xfer_root" structure,
873 * which is common for all our USB transfers.
875 info = USB_ADD_BYTES(buf, 0);
877 info->memory_base = buf;
878 info->memory_size = parm.size[0];
881 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
882 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
884 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
885 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
887 cv_init(&info->cv_drain, "WDRAIN");
889 info->xfer_mtx = xfer_mtx;
891 usb_dma_tag_setup(&info->dma_parent_tag,
892 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
893 xfer_mtx, &usb_bdma_done_event, 32, parm.dma_tag_max);
896 info->bus = udev->bus;
899 TAILQ_INIT(&info->done_q.head);
900 info->done_q.command = &usbd_callback_wrapper;
902 TAILQ_INIT(&info->dma_q.head);
903 info->dma_q.command = &usb_bdma_work_loop;
905 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
906 info->done_m[0].xroot = info;
907 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
908 info->done_m[1].xroot = info;
911 * In device side mode control endpoint
912 * requests need to run from a separate
913 * context, else there is a chance of
916 if (setup_start == usb_control_ep_cfg)
918 &udev->bus->control_xfer_proc;
919 else if (xfer_mtx == &Giant)
921 &udev->bus->giant_callback_proc;
924 &udev->bus->non_giant_callback_proc;
930 parm.size[0] += sizeof(info[0]);
932 for (setup = setup_start, n = 0;
933 setup != setup_end; setup++, n++) {
935 /* skip USB transfers without callbacks: */
936 if (setup->callback == NULL) {
939 /* see if there is a matching endpoint */
940 ep = usbd_get_endpoint(udev,
941 ifaces[setup->if_index], setup);
943 if ((ep == NULL) || (ep->methods == NULL)) {
944 if (setup->flags.no_pipe_ok)
946 if ((setup->usb_mode != USB_MODE_DUAL) &&
947 (setup->usb_mode != udev->flags.usb_mode))
949 parm.err = USB_ERR_NO_PIPE;
953 /* align data properly */
954 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
956 /* store current setup pointer */
957 parm.curr_setup = setup;
961 * Common initialization of the
962 * "usb_xfer" structure.
964 xfer = USB_ADD_BYTES(buf, parm.size[0]);
965 xfer->address = udev->address;
966 xfer->priv_sc = priv_sc;
969 usb_callout_init_mtx(&xfer->timeout_handle,
970 &udev->bus->bus_mtx, 0);
973 * Setup a dummy xfer, hence we are
974 * writing to the "usb_xfer"
975 * structure pointed to by "xfer"
976 * before we have allocated any
980 bzero(&dummy, sizeof(dummy));
984 /* set transfer endpoint pointer */
987 parm.size[0] += sizeof(xfer[0]);
988 parm.methods = xfer->endpoint->methods;
989 parm.curr_xfer = xfer;
992 * Call the Host or Device controller transfer
995 (udev->bus->methods->xfer_setup) (&parm);
997 /* check for error */
1003 * Increment the endpoint refcount. This
1004 * basically prevents setting a new
1005 * configuration and alternate setting
1006 * when USB transfers are in use on
1007 * the given interface. Search the USB
1008 * code for "endpoint->refcount_alloc" if you
1009 * want more information.
1011 USB_BUS_LOCK(info->bus);
1012 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1013 parm.err = USB_ERR_INVAL;
1015 xfer->endpoint->refcount_alloc++;
1017 if (xfer->endpoint->refcount_alloc == 0)
1018 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1019 USB_BUS_UNLOCK(info->bus);
1022 * Whenever we set ppxfer[] then we
1023 * also need to increment the
1026 info->setup_refcount++;
1029 * Transfer is successfully setup and
1035 /* check for error */
1040 if (buf || parm.err) {
1043 if (refcount == 0) {
1044 /* no transfers - nothing to do ! */
1047 /* align data properly */
1048 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1050 /* store offset temporarily */
1051 parm.size[1] = parm.size[0];
1054 * The number of DMA tags required depends on
1055 * the number of endpoints. The current estimate
1056 * for maximum number of DMA tags per endpoint
1059 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1062 * DMA tags for QH, TD, Data and more.
1064 parm.dma_tag_max += 8;
1066 parm.dma_tag_p += parm.dma_tag_max;
1068 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1071 /* align data properly */
1072 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1074 /* store offset temporarily */
1075 parm.size[3] = parm.size[0];
1077 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1080 /* align data properly */
1081 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1083 /* store offset temporarily */
1084 parm.size[4] = parm.size[0];
1086 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1089 /* store end offset temporarily */
1090 parm.size[5] = parm.size[0];
1092 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1095 /* store end offset temporarily */
1097 parm.size[2] = parm.size[0];
1099 /* align data properly */
1100 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1102 parm.size[6] = parm.size[0];
1104 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1107 /* align data properly */
1108 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1110 /* allocate zeroed memory */
1111 buf = malloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1114 parm.err = USB_ERR_NOMEM;
1115 DPRINTFN(0, "cannot allocate memory block for "
1116 "configuration (%d bytes)\n",
1120 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1121 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1122 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1123 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1124 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1129 if (info->setup_refcount == 0) {
1131 * "usbd_transfer_unsetup_sub" will unlock
1132 * the bus mutex before returning !
1134 USB_BUS_LOCK(info->bus);
1136 /* something went wrong */
1137 usbd_transfer_unsetup_sub(info, 0);
1141 usbd_transfer_unsetup(ppxfer, n_setup);
1146 /*------------------------------------------------------------------------*
1147 * usbd_transfer_unsetup_sub - factored out code
1148 *------------------------------------------------------------------------*/
1150 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1153 struct usb_page_cache *pc;
1156 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1158 /* wait for any outstanding DMA operations */
1162 temp = usbd_get_dma_delay(info->udev);
1164 usb_pause_mtx(&info->bus->bus_mtx,
1165 USB_MS_TO_TICKS(temp));
1169 /* make sure that our done messages are not queued anywhere */
1170 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1172 USB_BUS_UNLOCK(info->bus);
1175 /* free DMA'able memory, if any */
1176 pc = info->dma_page_cache_start;
1177 while (pc != info->dma_page_cache_end) {
1178 usb_pc_free_mem(pc);
1182 /* free DMA maps in all "xfer->frbuffers" */
1183 pc = info->xfer_page_cache_start;
1184 while (pc != info->xfer_page_cache_end) {
1185 usb_pc_dmamap_destroy(pc);
1189 /* free all DMA tags */
1190 usb_dma_tag_unsetup(&info->dma_parent_tag);
1193 cv_destroy(&info->cv_drain);
1196 * free the "memory_base" last, hence the "info" structure is
1197 * contained within the "memory_base"!
1199 free(info->memory_base, M_USB);
1202 /*------------------------------------------------------------------------*
1203 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1205 * NOTE: All USB transfers in progress will get called back passing
1206 * the error code "USB_ERR_CANCELLED" before this function
1208 *------------------------------------------------------------------------*/
1210 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1212 struct usb_xfer *xfer;
1213 struct usb_xfer_root *info;
1214 uint8_t needs_delay = 0;
1216 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1217 "usbd_transfer_unsetup can sleep!");
1220 xfer = pxfer[n_setup];
1227 USB_XFER_LOCK(xfer);
1228 USB_BUS_LOCK(info->bus);
1231 * HINT: when you start/stop a transfer, it might be a
1232 * good idea to directly use the "pxfer[]" structure:
1234 * usbd_transfer_start(sc->pxfer[0]);
1235 * usbd_transfer_stop(sc->pxfer[0]);
1237 * That way, if your code has many parts that will not
1238 * stop running under the same lock, in other words
1239 * "xfer_mtx", the usbd_transfer_start and
1240 * usbd_transfer_stop functions will simply return
1241 * when they detect a NULL pointer argument.
1243 * To avoid any races we clear the "pxfer[]" pointer
1244 * while holding the private mutex of the driver:
1246 pxfer[n_setup] = NULL;
1248 USB_BUS_UNLOCK(info->bus);
1249 USB_XFER_UNLOCK(xfer);
1251 usbd_transfer_drain(xfer);
1254 if (xfer->flags_int.bdma_enable)
1258 * NOTE: default endpoint does not have an
1259 * interface, even if endpoint->iface_index == 0
1261 USB_BUS_LOCK(info->bus);
1262 xfer->endpoint->refcount_alloc--;
1263 USB_BUS_UNLOCK(info->bus);
1265 usb_callout_drain(&xfer->timeout_handle);
1267 USB_BUS_LOCK(info->bus);
1269 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1270 "reference count\n"));
1272 info->setup_refcount--;
1274 if (info->setup_refcount == 0) {
1275 usbd_transfer_unsetup_sub(info,
1278 USB_BUS_UNLOCK(info->bus);
1283 /*------------------------------------------------------------------------*
1284 * usbd_control_transfer_init - factored out code
1286 * In USB Device Mode we have to wait for the SETUP packet which
1287 * containst the "struct usb_device_request" structure, before we can
1288 * transfer any data. In USB Host Mode we already have the SETUP
1289 * packet at the moment the USB transfer is started. This leads us to
1290 * having to setup the USB transfer at two different places in
1291 * time. This function just contains factored out control transfer
1292 * initialisation code, so that we don't duplicate the code.
1293 *------------------------------------------------------------------------*/
1295 usbd_control_transfer_init(struct usb_xfer *xfer)
1297 struct usb_device_request req;
1299 /* copy out the USB request header */
1301 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1303 /* setup remainder */
1305 xfer->flags_int.control_rem = UGETW(req.wLength);
1307 /* copy direction to endpoint variable */
1309 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1311 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1314 /*------------------------------------------------------------------------*
1315 * usbd_setup_ctrl_transfer
1317 * This function handles initialisation of control transfers. Control
1318 * transfers are special in that regard that they can both transmit
1324 *------------------------------------------------------------------------*/
1326 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1330 /* Check for control endpoint stall */
1331 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1332 /* the control transfer is no longer active */
1333 xfer->flags_int.control_stall = 1;
1334 xfer->flags_int.control_act = 0;
1336 /* don't stall control transfer by default */
1337 xfer->flags_int.control_stall = 0;
1340 /* Check for invalid number of frames */
1341 if (xfer->nframes > 2) {
1343 * If you need to split a control transfer, you
1344 * have to do one part at a time. Only with
1345 * non-control transfers you can do multiple
1348 DPRINTFN(0, "Too many frames: %u\n",
1349 (unsigned int)xfer->nframes);
1354 * Check if there is a control
1355 * transfer in progress:
1357 if (xfer->flags_int.control_act) {
1359 if (xfer->flags_int.control_hdr) {
1361 /* clear send header flag */
1363 xfer->flags_int.control_hdr = 0;
1365 /* setup control transfer */
1366 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1367 usbd_control_transfer_init(xfer);
1370 /* get data length */
1376 /* the size of the SETUP structure is hardcoded ! */
1378 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1379 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1380 xfer->frlengths[0], sizeof(struct
1381 usb_device_request));
1384 /* check USB mode */
1385 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1387 /* check number of frames */
1388 if (xfer->nframes != 1) {
1390 * We need to receive the setup
1391 * message first so that we know the
1394 DPRINTF("Misconfigured transfer\n");
1398 * Set a dummy "control_rem" value. This
1399 * variable will be overwritten later by a
1400 * call to "usbd_control_transfer_init()" !
1402 xfer->flags_int.control_rem = 0xFFFF;
1405 /* setup "endpoint" and "control_rem" */
1407 usbd_control_transfer_init(xfer);
1410 /* set transfer-header flag */
1412 xfer->flags_int.control_hdr = 1;
1414 /* get data length */
1416 len = (xfer->sumlen - sizeof(struct usb_device_request));
1419 /* check if there is a length mismatch */
1421 if (len > xfer->flags_int.control_rem) {
1422 DPRINTFN(0, "Length (%d) greater than "
1423 "remaining length (%d)\n", len,
1424 xfer->flags_int.control_rem);
1427 /* check if we are doing a short transfer */
1429 if (xfer->flags.force_short_xfer) {
1430 xfer->flags_int.control_rem = 0;
1432 if ((len != xfer->max_data_length) &&
1433 (len != xfer->flags_int.control_rem) &&
1434 (xfer->nframes != 1)) {
1435 DPRINTFN(0, "Short control transfer without "
1436 "force_short_xfer set\n");
1439 xfer->flags_int.control_rem -= len;
1442 /* the status part is executed when "control_act" is 0 */
1444 if ((xfer->flags_int.control_rem > 0) ||
1445 (xfer->flags.manual_status)) {
1446 /* don't execute the STATUS stage yet */
1447 xfer->flags_int.control_act = 1;
1450 if ((!xfer->flags_int.control_hdr) &&
1451 (xfer->nframes == 1)) {
1453 * This is not a valid operation!
1455 DPRINTFN(0, "Invalid parameter "
1460 /* time to execute the STATUS stage */
1461 xfer->flags_int.control_act = 0;
1463 return (0); /* success */
1466 return (1); /* failure */
1469 /*------------------------------------------------------------------------*
1470 * usbd_transfer_submit - start USB hardware for the given transfer
1472 * This function should only be called from the USB callback.
1473 *------------------------------------------------------------------------*/
1475 usbd_transfer_submit(struct usb_xfer *xfer)
1477 struct usb_xfer_root *info;
1478 struct usb_bus *bus;
1484 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1485 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1489 if (USB_DEBUG_VAR > 0) {
1492 usb_dump_endpoint(xfer->endpoint);
1494 USB_BUS_UNLOCK(bus);
1498 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1499 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1501 /* Only open the USB transfer once! */
1502 if (!xfer->flags_int.open) {
1503 xfer->flags_int.open = 1;
1508 (xfer->endpoint->methods->open) (xfer);
1509 USB_BUS_UNLOCK(bus);
1511 /* set "transferring" flag */
1512 xfer->flags_int.transferring = 1;
1515 /* increment power reference */
1516 usbd_transfer_power_ref(xfer, 1);
1519 * Check if the transfer is waiting on a queue, most
1520 * frequently the "done_q":
1522 if (xfer->wait_queue) {
1524 usbd_transfer_dequeue(xfer);
1525 USB_BUS_UNLOCK(bus);
1527 /* clear "did_dma_delay" flag */
1528 xfer->flags_int.did_dma_delay = 0;
1530 /* clear "did_close" flag */
1531 xfer->flags_int.did_close = 0;
1534 /* clear "bdma_setup" flag */
1535 xfer->flags_int.bdma_setup = 0;
1537 /* by default we cannot cancel any USB transfer immediately */
1538 xfer->flags_int.can_cancel_immed = 0;
1540 /* clear lengths and frame counts by default */
1545 /* clear any previous errors */
1548 /* Check if the device is still alive */
1549 if (info->udev->state < USB_STATE_POWERED) {
1552 * Must return cancelled error code else
1553 * device drivers can hang.
1555 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1556 USB_BUS_UNLOCK(bus);
1561 if (xfer->nframes == 0) {
1562 if (xfer->flags.stall_pipe) {
1564 * Special case - want to stall without transferring
1567 DPRINTF("xfer=%p nframes=0: stall "
1568 "or clear stall!\n", xfer);
1570 xfer->flags_int.can_cancel_immed = 1;
1571 /* start the transfer */
1572 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1573 USB_BUS_UNLOCK(bus);
1577 usbd_transfer_done(xfer, USB_ERR_INVAL);
1578 USB_BUS_UNLOCK(bus);
1581 /* compute total transfer length */
1583 for (x = 0; x != xfer->nframes; x++) {
1584 xfer->sumlen += xfer->frlengths[x];
1585 if (xfer->sumlen < xfer->frlengths[x]) {
1586 /* length wrapped around */
1588 usbd_transfer_done(xfer, USB_ERR_INVAL);
1589 USB_BUS_UNLOCK(bus);
1594 /* clear some internal flags */
1596 xfer->flags_int.short_xfer_ok = 0;
1597 xfer->flags_int.short_frames_ok = 0;
1599 /* check if this is a control transfer */
1601 if (xfer->flags_int.control_xfr) {
1603 if (usbd_setup_ctrl_transfer(xfer)) {
1605 usbd_transfer_done(xfer, USB_ERR_STALLED);
1606 USB_BUS_UNLOCK(bus);
1611 * Setup filtered version of some transfer flags,
1612 * in case of data read direction
1614 if (USB_GET_DATA_ISREAD(xfer)) {
1616 if (xfer->flags.short_frames_ok) {
1617 xfer->flags_int.short_xfer_ok = 1;
1618 xfer->flags_int.short_frames_ok = 1;
1619 } else if (xfer->flags.short_xfer_ok) {
1620 xfer->flags_int.short_xfer_ok = 1;
1622 /* check for control transfer */
1623 if (xfer->flags_int.control_xfr) {
1625 * 1) Control transfers do not support
1626 * reception of multiple short USB
1627 * frames in host mode and device side
1628 * mode, with exception of:
1630 * 2) Due to sometimes buggy device
1631 * side firmware we need to do a
1632 * STATUS stage in case of short
1633 * control transfers in USB host mode.
1634 * The STATUS stage then becomes the
1635 * "alt_next" to the DATA stage.
1637 xfer->flags_int.short_frames_ok = 1;
1642 * Check if BUS-DMA support is enabled and try to load virtual
1643 * buffers into DMA, if any:
1646 if (xfer->flags_int.bdma_enable) {
1647 /* insert the USB transfer last in the BUS-DMA queue */
1648 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1653 * Enter the USB transfer into the Host Controller or
1654 * Device Controller schedule:
1656 usbd_pipe_enter(xfer);
1659 /*------------------------------------------------------------------------*
1660 * usbd_pipe_enter - factored out code
1661 *------------------------------------------------------------------------*/
1663 usbd_pipe_enter(struct usb_xfer *xfer)
1665 struct usb_endpoint *ep;
1667 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1669 USB_BUS_LOCK(xfer->xroot->bus);
1671 ep = xfer->endpoint;
1675 /* enter the transfer */
1676 (ep->methods->enter) (xfer);
1678 xfer->flags_int.can_cancel_immed = 1;
1680 /* check for transfer error */
1682 /* some error has happened */
1683 usbd_transfer_done(xfer, 0);
1684 USB_BUS_UNLOCK(xfer->xroot->bus);
1688 /* start the transfer */
1689 usb_command_wrapper(&ep->endpoint_q, xfer);
1690 USB_BUS_UNLOCK(xfer->xroot->bus);
1693 /*------------------------------------------------------------------------*
1694 * usbd_transfer_start - start an USB transfer
1696 * NOTE: Calling this function more than one time will only
1697 * result in a single transfer start, until the USB transfer
1699 *------------------------------------------------------------------------*/
1701 usbd_transfer_start(struct usb_xfer *xfer)
1704 /* transfer is gone */
1707 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1709 /* mark the USB transfer started */
1711 if (!xfer->flags_int.started) {
1712 /* lock the BUS lock to avoid races updating flags_int */
1713 USB_BUS_LOCK(xfer->xroot->bus);
1714 xfer->flags_int.started = 1;
1715 USB_BUS_UNLOCK(xfer->xroot->bus);
1717 /* check if the USB transfer callback is already transferring */
1719 if (xfer->flags_int.transferring) {
1722 USB_BUS_LOCK(xfer->xroot->bus);
1723 /* call the USB transfer callback */
1724 usbd_callback_ss_done_defer(xfer);
1725 USB_BUS_UNLOCK(xfer->xroot->bus);
1728 /*------------------------------------------------------------------------*
1729 * usbd_transfer_stop - stop an USB transfer
1731 * NOTE: Calling this function more than one time will only
1732 * result in a single transfer stop.
1733 * NOTE: When this function returns it is not safe to free nor
1734 * reuse any DMA buffers. See "usbd_transfer_drain()".
1735 *------------------------------------------------------------------------*/
1737 usbd_transfer_stop(struct usb_xfer *xfer)
1739 struct usb_endpoint *ep;
1742 /* transfer is gone */
1745 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1747 /* check if the USB transfer was ever opened */
1749 if (!xfer->flags_int.open) {
1750 if (xfer->flags_int.started) {
1751 /* nothing to do except clearing the "started" flag */
1752 /* lock the BUS lock to avoid races updating flags_int */
1753 USB_BUS_LOCK(xfer->xroot->bus);
1754 xfer->flags_int.started = 0;
1755 USB_BUS_UNLOCK(xfer->xroot->bus);
1759 /* try to stop the current USB transfer */
1761 USB_BUS_LOCK(xfer->xroot->bus);
1762 /* override any previous error */
1763 xfer->error = USB_ERR_CANCELLED;
1766 * Clear "open" and "started" when both private and USB lock
1767 * is locked so that we don't get a race updating "flags_int"
1769 xfer->flags_int.open = 0;
1770 xfer->flags_int.started = 0;
1773 * Check if we can cancel the USB transfer immediately.
1775 if (xfer->flags_int.transferring) {
1776 if (xfer->flags_int.can_cancel_immed &&
1777 (!xfer->flags_int.did_close)) {
1780 * The following will lead to an USB_ERR_CANCELLED
1781 * error code being passed to the USB callback.
1783 (xfer->endpoint->methods->close) (xfer);
1784 /* only close once */
1785 xfer->flags_int.did_close = 1;
1787 /* need to wait for the next done callback */
1792 /* close here and now */
1793 (xfer->endpoint->methods->close) (xfer);
1796 * Any additional DMA delay is done by
1797 * "usbd_transfer_unsetup()".
1801 * Special case. Check if we need to restart a blocked
1804 ep = xfer->endpoint;
1807 * If the current USB transfer is completing we need
1808 * to start the next one:
1810 if (ep->endpoint_q.curr == xfer) {
1811 usb_command_wrapper(&ep->endpoint_q, NULL);
1815 USB_BUS_UNLOCK(xfer->xroot->bus);
1818 /*------------------------------------------------------------------------*
1819 * usbd_transfer_pending
1821 * This function will check if an USB transfer is pending which is a
1822 * little bit complicated!
1825 * 1: Pending: The USB transfer will receive a callback in the future.
1826 *------------------------------------------------------------------------*/
1828 usbd_transfer_pending(struct usb_xfer *xfer)
1830 struct usb_xfer_root *info;
1831 struct usb_xfer_queue *pq;
1834 /* transfer is gone */
1837 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1839 if (xfer->flags_int.transferring) {
1843 USB_BUS_LOCK(xfer->xroot->bus);
1844 if (xfer->wait_queue) {
1845 /* we are waiting on a queue somewhere */
1846 USB_BUS_UNLOCK(xfer->xroot->bus);
1852 if (pq->curr == xfer) {
1853 /* we are currently scheduled for callback */
1854 USB_BUS_UNLOCK(xfer->xroot->bus);
1857 /* we are not pending */
1858 USB_BUS_UNLOCK(xfer->xroot->bus);
1862 /*------------------------------------------------------------------------*
1863 * usbd_transfer_drain
1865 * This function will stop the USB transfer and wait for any
1866 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1867 * are loaded into DMA can safely be freed or reused after that this
1868 * function has returned.
1869 *------------------------------------------------------------------------*/
1871 usbd_transfer_drain(struct usb_xfer *xfer)
1873 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1874 "usbd_transfer_drain can sleep!");
1877 /* transfer is gone */
1880 if (xfer->xroot->xfer_mtx != &Giant) {
1881 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1883 USB_XFER_LOCK(xfer);
1885 usbd_transfer_stop(xfer);
1887 while (usbd_transfer_pending(xfer) ||
1888 xfer->flags_int.doing_callback) {
1891 * It is allowed that the callback can drop its
1892 * transfer mutex. In that case checking only
1893 * "usbd_transfer_pending()" is not enough to tell if
1894 * the USB transfer is fully drained. We also need to
1895 * check the internal "doing_callback" flag.
1897 xfer->flags_int.draining = 1;
1900 * Wait until the current outstanding USB
1901 * transfer is complete !
1903 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1905 USB_XFER_UNLOCK(xfer);
1908 struct usb_page_cache *
1909 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1911 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1913 return (&xfer->frbuffers[frindex]);
1916 /*------------------------------------------------------------------------*
1917 * usbd_xfer_get_fps_shift
1919 * The following function is only useful for isochronous transfers. It
1920 * returns how many times the frame execution rate has been shifted
1926 *------------------------------------------------------------------------*/
1928 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1930 return (xfer->fps_shift);
1934 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1936 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1938 return (xfer->frlengths[frindex]);
1941 /*------------------------------------------------------------------------*
1942 * usbd_xfer_set_frame_data
1944 * This function sets the pointer of the buffer that should
1945 * loaded directly into DMA for the given USB frame. Passing "ptr"
1946 * equal to NULL while the corresponding "frlength" is greater
1947 * than zero gives undefined results!
1948 *------------------------------------------------------------------------*/
1950 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1951 void *ptr, usb_frlength_t len)
1953 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1955 /* set virtual address to load and length */
1956 xfer->frbuffers[frindex].buffer = ptr;
1957 usbd_xfer_set_frame_len(xfer, frindex, len);
1961 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1962 void **ptr, int *len)
1964 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1967 *ptr = xfer->frbuffers[frindex].buffer;
1969 *len = xfer->frlengths[frindex];
1973 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
1977 *actlen = xfer->actlen;
1979 *sumlen = xfer->sumlen;
1980 if (aframes != NULL)
1981 *aframes = xfer->aframes;
1982 if (nframes != NULL)
1983 *nframes = xfer->nframes;
1986 /*------------------------------------------------------------------------*
1987 * usbd_xfer_set_frame_offset
1989 * This function sets the frame data buffer offset relative to the beginning
1990 * of the USB DMA buffer allocated for this USB transfer.
1991 *------------------------------------------------------------------------*/
1993 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
1994 usb_frcount_t frindex)
1996 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
1997 "when the USB buffer is external\n"));
1998 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2000 /* set virtual address to load */
2001 xfer->frbuffers[frindex].buffer =
2002 USB_ADD_BYTES(xfer->local_buffer, offset);
2006 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2012 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2018 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2024 usbd_xfer_max_frames(struct usb_xfer *xfer)
2026 return (xfer->max_frame_count);
2030 usbd_xfer_max_len(struct usb_xfer *xfer)
2032 return (xfer->max_data_length);
2036 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2038 return (xfer->max_frame_size);
2042 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2045 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2047 xfer->frlengths[frindex] = len;
2050 /*------------------------------------------------------------------------*
2051 * usb_callback_proc - factored out code
2053 * This function performs USB callbacks.
2054 *------------------------------------------------------------------------*/
2056 usb_callback_proc(struct usb_proc_msg *_pm)
2058 struct usb_done_msg *pm = (void *)_pm;
2059 struct usb_xfer_root *info = pm->xroot;
2061 /* Change locking order */
2062 USB_BUS_UNLOCK(info->bus);
2065 * We exploit the fact that the mutex is the same for all
2066 * callbacks that will be called from this thread:
2068 mtx_lock(info->xfer_mtx);
2069 USB_BUS_LOCK(info->bus);
2071 /* Continue where we lost track */
2072 usb_command_wrapper(&info->done_q,
2075 mtx_unlock(info->xfer_mtx);
2078 /*------------------------------------------------------------------------*
2079 * usbd_callback_ss_done_defer
2081 * This function will defer the start, stop and done callback to the
2083 *------------------------------------------------------------------------*/
2085 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2087 struct usb_xfer_root *info = xfer->xroot;
2088 struct usb_xfer_queue *pq = &info->done_q;
2090 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2092 if (pq->curr != xfer) {
2093 usbd_transfer_enqueue(pq, xfer);
2095 if (!pq->recurse_1) {
2098 * We have to postpone the callback due to the fact we
2099 * will have a Lock Order Reversal, LOR, if we try to
2102 if (usb_proc_msignal(info->done_p,
2103 &info->done_m[0], &info->done_m[1])) {
2107 /* clear second recurse flag */
2114 /*------------------------------------------------------------------------*
2115 * usbd_callback_wrapper
2117 * This is a wrapper for USB callbacks. This wrapper does some
2118 * auto-magic things like figuring out if we can call the callback
2119 * directly from the current context or if we need to wakeup the
2120 * interrupt process.
2121 *------------------------------------------------------------------------*/
2123 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2125 struct usb_xfer *xfer = pq->curr;
2126 struct usb_xfer_root *info = xfer->xroot;
2128 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2129 if (!mtx_owned(info->xfer_mtx)) {
2131 * Cases that end up here:
2133 * 5) HW interrupt done callback or other source.
2135 DPRINTFN(3, "case 5\n");
2138 * We have to postpone the callback due to the fact we
2139 * will have a Lock Order Reversal, LOR, if we try to
2142 if (usb_proc_msignal(info->done_p,
2143 &info->done_m[0], &info->done_m[1])) {
2149 * Cases that end up here:
2151 * 1) We are starting a transfer
2152 * 2) We are prematurely calling back a transfer
2153 * 3) We are stopping a transfer
2154 * 4) We are doing an ordinary callback
2156 DPRINTFN(3, "case 1-4\n");
2157 /* get next USB transfer in the queue */
2158 info->done_q.curr = NULL;
2160 /* set flag in case of drain */
2161 xfer->flags_int.doing_callback = 1;
2163 USB_BUS_UNLOCK(info->bus);
2164 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2166 /* set correct USB state for callback */
2167 if (!xfer->flags_int.transferring) {
2168 xfer->usb_state = USB_ST_SETUP;
2169 if (!xfer->flags_int.started) {
2170 /* we got stopped before we even got started */
2171 USB_BUS_LOCK(info->bus);
2176 if (usbd_callback_wrapper_sub(xfer)) {
2177 /* the callback has been deferred */
2178 USB_BUS_LOCK(info->bus);
2182 /* decrement power reference */
2183 usbd_transfer_power_ref(xfer, -1);
2185 xfer->flags_int.transferring = 0;
2188 xfer->usb_state = USB_ST_ERROR;
2190 /* set transferred state */
2191 xfer->usb_state = USB_ST_TRANSFERRED;
2193 /* sync DMA memory, if any */
2194 if (xfer->flags_int.bdma_enable &&
2195 (!xfer->flags_int.bdma_no_post_sync)) {
2196 usb_bdma_post_sync(xfer);
2202 /* call processing routine */
2203 (xfer->callback) (xfer, xfer->error);
2205 /* pickup the USB mutex again */
2206 USB_BUS_LOCK(info->bus);
2209 * Check if we got started after that we got cancelled, but
2210 * before we managed to do the callback.
2212 if ((!xfer->flags_int.open) &&
2213 (xfer->flags_int.started) &&
2214 (xfer->usb_state == USB_ST_ERROR)) {
2215 /* clear flag in case of drain */
2216 xfer->flags_int.doing_callback = 0;
2217 /* try to loop, but not recursivly */
2218 usb_command_wrapper(&info->done_q, xfer);
2223 /* clear flag in case of drain */
2224 xfer->flags_int.doing_callback = 0;
2227 * Check if we are draining.
2229 if (xfer->flags_int.draining &&
2230 (!xfer->flags_int.transferring)) {
2231 /* "usbd_transfer_drain()" is waiting for end of transfer */
2232 xfer->flags_int.draining = 0;
2233 cv_broadcast(&info->cv_drain);
2236 /* do the next callback, if any */
2237 usb_command_wrapper(&info->done_q,
2241 /*------------------------------------------------------------------------*
2242 * usb_dma_delay_done_cb
2244 * This function is called when the DMA delay has been exectuded, and
2245 * will make sure that the callback is called to complete the USB
2246 * transfer. This code path is ususally only used when there is an USB
2247 * error like USB_ERR_CANCELLED.
2248 *------------------------------------------------------------------------*/
2250 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2252 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2254 DPRINTFN(3, "Completed %p\n", xfer);
2256 /* queue callback for execution, again */
2257 usbd_transfer_done(xfer, 0);
2260 /*------------------------------------------------------------------------*
2261 * usbd_transfer_dequeue
2263 * - This function is used to remove an USB transfer from a USB
2266 * - This function can be called multiple times in a row.
2267 *------------------------------------------------------------------------*/
2269 usbd_transfer_dequeue(struct usb_xfer *xfer)
2271 struct usb_xfer_queue *pq;
2273 pq = xfer->wait_queue;
2275 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2276 xfer->wait_queue = NULL;
2280 /*------------------------------------------------------------------------*
2281 * usbd_transfer_enqueue
2283 * - This function is used to insert an USB transfer into a USB *
2286 * - This function can be called multiple times in a row.
2287 *------------------------------------------------------------------------*/
2289 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2292 * Insert the USB transfer into the queue, if it is not
2293 * already on a USB transfer queue:
2295 if (xfer->wait_queue == NULL) {
2296 xfer->wait_queue = pq;
2297 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2301 /*------------------------------------------------------------------------*
2302 * usbd_transfer_done
2304 * - This function is used to remove an USB transfer from the busdma,
2305 * pipe or interrupt queue.
2307 * - This function is used to queue the USB transfer on the done
2310 * - This function is used to stop any USB transfer timeouts.
2311 *------------------------------------------------------------------------*/
2313 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2315 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2317 DPRINTF("err=%s\n", usbd_errstr(error));
2320 * If we are not transferring then just return.
2321 * This can happen during transfer cancel.
2323 if (!xfer->flags_int.transferring) {
2324 DPRINTF("not transferring\n");
2325 /* end of control transfer, if any */
2326 xfer->flags_int.control_act = 0;
2329 /* only set transfer error if not already set */
2331 xfer->error = error;
2333 /* stop any callouts */
2334 usb_callout_stop(&xfer->timeout_handle);
2337 * If we are waiting on a queue, just remove the USB transfer
2338 * from the queue, if any. We should have the required locks
2339 * locked to do the remove when this function is called.
2341 usbd_transfer_dequeue(xfer);
2344 if (mtx_owned(xfer->xroot->xfer_mtx)) {
2345 struct usb_xfer_queue *pq;
2348 * If the private USB lock is not locked, then we assume
2349 * that the BUS-DMA load stage has been passed:
2351 pq = &xfer->xroot->dma_q;
2353 if (pq->curr == xfer) {
2354 /* start the next BUS-DMA load, if any */
2355 usb_command_wrapper(pq, NULL);
2359 /* keep some statistics */
2361 xfer->xroot->bus->stats_err.uds_requests
2362 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2364 xfer->xroot->bus->stats_ok.uds_requests
2365 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2368 /* call the USB transfer callback */
2369 usbd_callback_ss_done_defer(xfer);
2372 /*------------------------------------------------------------------------*
2373 * usbd_transfer_start_cb
2375 * This function is called to start the USB transfer when
2376 * "xfer->interval" is greater than zero, and and the endpoint type is
2378 *------------------------------------------------------------------------*/
2380 usbd_transfer_start_cb(void *arg)
2382 struct usb_xfer *xfer = arg;
2383 struct usb_endpoint *ep = xfer->endpoint;
2385 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2389 /* start the transfer */
2390 (ep->methods->start) (xfer);
2392 xfer->flags_int.can_cancel_immed = 1;
2394 /* check for error */
2396 /* some error has happened */
2397 usbd_transfer_done(xfer, 0);
2401 /*------------------------------------------------------------------------*
2402 * usbd_xfer_set_stall
2404 * This function is used to set the stall flag outside the
2405 * callback. This function is NULL safe.
2406 *------------------------------------------------------------------------*/
2408 usbd_xfer_set_stall(struct usb_xfer *xfer)
2414 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2416 /* avoid any races by locking the USB mutex */
2417 USB_BUS_LOCK(xfer->xroot->bus);
2418 xfer->flags.stall_pipe = 1;
2419 USB_BUS_UNLOCK(xfer->xroot->bus);
2423 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2425 return (xfer->endpoint->is_stalled);
2428 /*------------------------------------------------------------------------*
2429 * usbd_transfer_clear_stall
2431 * This function is used to clear the stall flag outside the
2432 * callback. This function is NULL safe.
2433 *------------------------------------------------------------------------*/
2435 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2441 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2443 /* avoid any races by locking the USB mutex */
2444 USB_BUS_LOCK(xfer->xroot->bus);
2446 xfer->flags.stall_pipe = 0;
2448 USB_BUS_UNLOCK(xfer->xroot->bus);
2451 /*------------------------------------------------------------------------*
2454 * This function is used to add an USB transfer to the pipe transfer list.
2455 *------------------------------------------------------------------------*/
2457 usbd_pipe_start(struct usb_xfer_queue *pq)
2459 struct usb_endpoint *ep;
2460 struct usb_xfer *xfer;
2464 ep = xfer->endpoint;
2466 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2469 * If the endpoint is already stalled we do nothing !
2471 if (ep->is_stalled) {
2475 * Check if we are supposed to stall the endpoint:
2477 if (xfer->flags.stall_pipe) {
2478 struct usb_device *udev;
2479 struct usb_xfer_root *info;
2481 /* clear stall command */
2482 xfer->flags.stall_pipe = 0;
2484 /* get pointer to USB device */
2489 * Only stall BULK and INTERRUPT endpoints.
2491 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2492 if ((type == UE_BULK) ||
2493 (type == UE_INTERRUPT)) {
2498 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2499 (udev->bus->methods->set_stall) (
2500 udev, NULL, ep, &did_stall);
2501 } else if (udev->ctrl_xfer[1]) {
2502 info = udev->ctrl_xfer[1]->xroot;
2504 &info->bus->non_giant_callback_proc,
2505 &udev->cs_msg[0], &udev->cs_msg[1]);
2507 /* should not happen */
2508 DPRINTFN(0, "No stall handler\n");
2511 * Check if we should stall. Some USB hardware
2512 * handles set- and clear-stall in hardware.
2516 * The transfer will be continued when
2517 * the clear-stall control endpoint
2518 * message is received.
2523 } else if (type == UE_ISOCHRONOUS) {
2526 * Make sure any FIFO overflow or other FIFO
2527 * error conditions go away by resetting the
2528 * endpoint FIFO through the clear stall
2531 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2532 (udev->bus->methods->clear_stall) (udev, ep);
2536 /* Set or clear stall complete - special case */
2537 if (xfer->nframes == 0) {
2538 /* we are complete */
2540 usbd_transfer_done(xfer, 0);
2546 * 1) Start the first transfer queued.
2548 * 2) Re-start the current USB transfer.
2551 * Check if there should be any
2552 * pre transfer start delay:
2554 if (xfer->interval > 0) {
2555 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2556 if ((type == UE_BULK) ||
2557 (type == UE_CONTROL)) {
2558 usbd_transfer_timeout_ms(xfer,
2559 &usbd_transfer_start_cb,
2566 /* start USB transfer */
2567 (ep->methods->start) (xfer);
2569 xfer->flags_int.can_cancel_immed = 1;
2571 /* check for error */
2573 /* some error has happened */
2574 usbd_transfer_done(xfer, 0);
2578 /*------------------------------------------------------------------------*
2579 * usbd_transfer_timeout_ms
2581 * This function is used to setup a timeout on the given USB
2582 * transfer. If the timeout has been deferred the callback given by
2583 * "cb" will get called after "ms" milliseconds.
2584 *------------------------------------------------------------------------*/
2586 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2587 void (*cb) (void *arg), usb_timeout_t ms)
2589 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2592 usb_callout_reset(&xfer->timeout_handle,
2593 USB_MS_TO_TICKS(ms), cb, xfer);
2596 /*------------------------------------------------------------------------*
2597 * usbd_callback_wrapper_sub
2599 * - This function will update variables in an USB transfer after
2600 * that the USB transfer is complete.
2602 * - This function is used to start the next USB transfer on the
2603 * ep transfer queue, if any.
2605 * NOTE: In some special cases the USB transfer will not be removed from
2606 * the pipe queue, but remain first. To enforce USB transfer removal call
2607 * this function passing the error code "USB_ERR_CANCELLED".
2611 * Else: The callback has been deferred.
2612 *------------------------------------------------------------------------*/
2614 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2616 struct usb_endpoint *ep;
2617 struct usb_bus *bus;
2620 bus = xfer->xroot->bus;
2622 if ((!xfer->flags_int.open) &&
2623 (!xfer->flags_int.did_close)) {
2626 (xfer->endpoint->methods->close) (xfer);
2627 USB_BUS_UNLOCK(bus);
2628 /* only close once */
2629 xfer->flags_int.did_close = 1;
2630 return (1); /* wait for new callback */
2633 * If we have a non-hardware induced error we
2634 * need to do the DMA delay!
2636 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2637 (xfer->error == USB_ERR_CANCELLED ||
2638 xfer->error == USB_ERR_TIMEOUT ||
2639 bus->methods->start_dma_delay != NULL)) {
2643 /* only delay once */
2644 xfer->flags_int.did_dma_delay = 1;
2646 /* we can not cancel this delay */
2647 xfer->flags_int.can_cancel_immed = 0;
2649 temp = usbd_get_dma_delay(xfer->xroot->udev);
2651 DPRINTFN(3, "DMA delay, %u ms, "
2652 "on %p\n", temp, xfer);
2657 * Some hardware solutions have dedicated
2658 * events when it is safe to free DMA'ed
2659 * memory. For the other hardware platforms we
2660 * use a static delay.
2662 if (bus->methods->start_dma_delay != NULL) {
2663 (bus->methods->start_dma_delay) (xfer);
2665 usbd_transfer_timeout_ms(xfer,
2666 (void *)&usb_dma_delay_done_cb, temp);
2668 USB_BUS_UNLOCK(bus);
2669 return (1); /* wait for new callback */
2672 /* check actual number of frames */
2673 if (xfer->aframes > xfer->nframes) {
2674 if (xfer->error == 0) {
2675 panic("%s: actual number of frames, %d, is "
2676 "greater than initial number of frames, %d\n",
2677 __FUNCTION__, xfer->aframes, xfer->nframes);
2679 /* just set some valid value */
2680 xfer->aframes = xfer->nframes;
2683 /* compute actual length */
2686 for (x = 0; x != xfer->aframes; x++) {
2687 xfer->actlen += xfer->frlengths[x];
2691 * Frames that were not transferred get zero actual length in
2692 * case the USB device driver does not check the actual number
2693 * of frames transferred, "xfer->aframes":
2695 for (; x < xfer->nframes; x++) {
2696 usbd_xfer_set_frame_len(xfer, x, 0);
2699 /* check actual length */
2700 if (xfer->actlen > xfer->sumlen) {
2701 if (xfer->error == 0) {
2702 panic("%s: actual length, %d, is greater than "
2703 "initial length, %d\n",
2704 __FUNCTION__, xfer->actlen, xfer->sumlen);
2706 /* just set some valid value */
2707 xfer->actlen = xfer->sumlen;
2710 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2711 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2712 xfer->aframes, xfer->nframes);
2715 /* end of control transfer, if any */
2716 xfer->flags_int.control_act = 0;
2718 /* check if we should block the execution queue */
2719 if ((xfer->error != USB_ERR_CANCELLED) &&
2720 (xfer->flags.pipe_bof)) {
2721 DPRINTFN(2, "xfer=%p: Block On Failure "
2722 "on endpoint=%p\n", xfer, xfer->endpoint);
2726 /* check for short transfers */
2727 if (xfer->actlen < xfer->sumlen) {
2729 /* end of control transfer, if any */
2730 xfer->flags_int.control_act = 0;
2732 if (!xfer->flags_int.short_xfer_ok) {
2733 xfer->error = USB_ERR_SHORT_XFER;
2734 if (xfer->flags.pipe_bof) {
2735 DPRINTFN(2, "xfer=%p: Block On Failure on "
2736 "Short Transfer on endpoint %p.\n",
2737 xfer, xfer->endpoint);
2743 * Check if we are in the middle of a
2746 if (xfer->flags_int.control_act) {
2747 DPRINTFN(5, "xfer=%p: Control transfer "
2748 "active on endpoint=%p\n", xfer, xfer->endpoint);
2754 ep = xfer->endpoint;
2757 * If the current USB transfer is completing we need to start the
2761 if (ep->endpoint_q.curr == xfer) {
2762 usb_command_wrapper(&ep->endpoint_q, NULL);
2764 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2765 /* there is another USB transfer waiting */
2767 /* this is the last USB transfer */
2768 /* clear isochronous sync flag */
2769 xfer->endpoint->is_synced = 0;
2772 USB_BUS_UNLOCK(bus);
2777 /*------------------------------------------------------------------------*
2778 * usb_command_wrapper
2780 * This function is used to execute commands non-recursivly on an USB
2782 *------------------------------------------------------------------------*/
2784 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2788 * If the transfer is not already processing,
2791 if (pq->curr != xfer) {
2792 usbd_transfer_enqueue(pq, xfer);
2793 if (pq->curr != NULL) {
2794 /* something is already processing */
2795 DPRINTFN(6, "busy %p\n", pq->curr);
2800 /* Get next element in queue */
2804 if (!pq->recurse_1) {
2808 /* set both recurse flags */
2812 if (pq->curr == NULL) {
2813 xfer = TAILQ_FIRST(&pq->head);
2815 TAILQ_REMOVE(&pq->head, xfer,
2817 xfer->wait_queue = NULL;
2823 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2825 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2827 } while (!pq->recurse_2);
2829 /* clear first recurse flag */
2833 /* clear second recurse flag */
2838 /*------------------------------------------------------------------------*
2839 * usbd_ctrl_transfer_setup
2841 * This function is used to setup the default USB control endpoint
2843 *------------------------------------------------------------------------*/
2845 usbd_ctrl_transfer_setup(struct usb_device *udev)
2847 struct usb_xfer *xfer;
2849 uint8_t iface_index;
2851 /* check for root HUB */
2852 if (udev->parent_hub == NULL)
2856 xfer = udev->ctrl_xfer[0];
2858 USB_XFER_LOCK(xfer);
2860 ((xfer->address == udev->address) &&
2861 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2862 udev->ddesc.bMaxPacketSize));
2863 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2866 * NOTE: checking "xfer->address" and
2867 * starting the USB transfer must be
2870 usbd_transfer_start(xfer);
2873 USB_XFER_UNLOCK(xfer);
2880 * All parameters are exactly the same like before.
2886 * Update wMaxPacketSize for the default control endpoint:
2888 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2889 udev->ddesc.bMaxPacketSize;
2892 * Unsetup any existing USB transfer:
2894 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2897 * Try to setup a new USB transfer for the
2898 * default control endpoint:
2901 if (usbd_transfer_setup(udev, &iface_index,
2902 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2903 &udev->device_mtx)) {
2904 DPRINTFN(0, "could not setup default "
2911 /*------------------------------------------------------------------------*
2912 * usbd_clear_data_toggle - factored out code
2914 * NOTE: the intention of this function is not to reset the hardware
2916 *------------------------------------------------------------------------*/
2918 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2920 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
2922 /* check that we have a valid case */
2923 if (udev->flags.usb_mode == USB_MODE_HOST &&
2924 udev->parent_hub != NULL &&
2925 udev->bus->methods->clear_stall != NULL &&
2926 ep->methods != NULL) {
2927 (udev->bus->methods->clear_stall) (udev, ep);
2931 /*------------------------------------------------------------------------*
2932 * usbd_clear_data_toggle - factored out code
2934 * NOTE: the intention of this function is not to reset the hardware
2935 * data toggle on the USB device side.
2936 *------------------------------------------------------------------------*/
2938 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2940 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2942 USB_BUS_LOCK(udev->bus);
2943 ep->toggle_next = 0;
2944 /* some hardware needs a callback to clear the data toggle */
2945 usbd_clear_stall_locked(udev, ep);
2946 USB_BUS_UNLOCK(udev->bus);
2949 /*------------------------------------------------------------------------*
2950 * usbd_clear_stall_callback - factored out clear stall callback
2953 * xfer1: Clear Stall Control Transfer
2954 * xfer2: Stalled USB Transfer
2956 * This function is NULL safe.
2962 * Clear stall config example:
2964 * static const struct usb_config my_clearstall = {
2965 * .type = UE_CONTROL,
2967 * .direction = UE_DIR_ANY,
2968 * .interval = 50, //50 milliseconds
2969 * .bufsize = sizeof(struct usb_device_request),
2970 * .timeout = 1000, //1.000 seconds
2971 * .callback = &my_clear_stall_callback, // **
2972 * .usb_mode = USB_MODE_HOST,
2975 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
2976 * passing the correct parameters.
2977 *------------------------------------------------------------------------*/
2979 usbd_clear_stall_callback(struct usb_xfer *xfer1,
2980 struct usb_xfer *xfer2)
2982 struct usb_device_request req;
2984 if (xfer2 == NULL) {
2985 /* looks like we are tearing down */
2986 DPRINTF("NULL input parameter\n");
2989 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
2990 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
2992 switch (USB_GET_STATE(xfer1)) {
2996 * pre-clear the data toggle to DATA0 ("umass.c" and
2997 * "ata-usb.c" depends on this)
3000 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3002 /* setup a clear-stall packet */
3004 req.bmRequestType = UT_WRITE_ENDPOINT;
3005 req.bRequest = UR_CLEAR_FEATURE;
3006 USETW(req.wValue, UF_ENDPOINT_HALT);
3007 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3009 USETW(req.wLength, 0);
3012 * "usbd_transfer_setup_sub()" will ensure that
3013 * we have sufficient room in the buffer for
3014 * the request structure!
3017 /* copy in the transfer */
3019 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3022 xfer1->frlengths[0] = sizeof(req);
3025 usbd_transfer_submit(xfer1);
3028 case USB_ST_TRANSFERRED:
3031 default: /* Error */
3032 if (xfer1->error == USB_ERR_CANCELLED) {
3037 return (1); /* Clear Stall Finished */
3040 /*------------------------------------------------------------------------*
3041 * usbd_transfer_poll
3043 * The following function gets called from the USB keyboard driver and
3044 * UMASS when the system has paniced.
3046 * NOTE: It is currently not possible to resume normal operation on
3047 * the USB controller which has been polled, due to clearing of the
3048 * "up_dsleep" and "up_msleep" flags.
3049 *------------------------------------------------------------------------*/
3051 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3053 struct usb_xfer *xfer;
3054 struct usb_xfer_root *xroot;
3055 struct usb_device *udev;
3056 struct usb_proc_msg *pm;
3061 for (n = 0; n != max; n++) {
3062 /* Extra checks to avoid panic */
3065 continue; /* no USB transfer */
3066 xroot = xfer->xroot;
3068 continue; /* no USB root */
3071 continue; /* no USB device */
3072 if (udev->bus == NULL)
3073 continue; /* no BUS structure */
3074 if (udev->bus->methods == NULL)
3075 continue; /* no BUS methods */
3076 if (udev->bus->methods->xfer_poll == NULL)
3077 continue; /* no poll method */
3079 /* make sure that the BUS mutex is not locked */
3081 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3082 mtx_unlock(&xroot->udev->bus->bus_mtx);
3086 /* make sure that the transfer mutex is not locked */
3088 while (mtx_owned(xroot->xfer_mtx)) {
3089 mtx_unlock(xroot->xfer_mtx);
3093 /* Make sure cv_signal() and cv_broadcast() is not called */
3094 udev->bus->control_xfer_proc.up_msleep = 0;
3095 udev->bus->explore_proc.up_msleep = 0;
3096 udev->bus->giant_callback_proc.up_msleep = 0;
3097 udev->bus->non_giant_callback_proc.up_msleep = 0;
3099 /* poll USB hardware */
3100 (udev->bus->methods->xfer_poll) (udev->bus);
3102 USB_BUS_LOCK(xroot->bus);
3104 /* check for clear stall */
3105 if (udev->ctrl_xfer[1] != NULL) {
3107 /* poll clear stall start */
3108 pm = &udev->cs_msg[0].hdr;
3109 (pm->pm_callback) (pm);
3110 /* poll clear stall done thread */
3111 pm = &udev->ctrl_xfer[1]->
3112 xroot->done_m[0].hdr;
3113 (pm->pm_callback) (pm);
3116 /* poll done thread */
3117 pm = &xroot->done_m[0].hdr;
3118 (pm->pm_callback) (pm);
3120 USB_BUS_UNLOCK(xroot->bus);
3122 /* restore transfer mutex */
3124 mtx_lock(xroot->xfer_mtx);
3126 /* restore BUS mutex */
3128 mtx_lock(&xroot->udev->bus->bus_mtx);
3133 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3134 uint8_t type, enum usb_dev_speed speed)
3136 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3137 [USB_SPEED_LOW] = 8,
3138 [USB_SPEED_FULL] = 64,
3139 [USB_SPEED_HIGH] = 1024,
3140 [USB_SPEED_VARIABLE] = 1024,
3141 [USB_SPEED_SUPER] = 1024,
3144 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3145 [USB_SPEED_LOW] = 0, /* invalid */
3146 [USB_SPEED_FULL] = 1023,
3147 [USB_SPEED_HIGH] = 1024,
3148 [USB_SPEED_VARIABLE] = 3584,
3149 [USB_SPEED_SUPER] = 1024,
3152 static const uint16_t control_min[USB_SPEED_MAX] = {
3153 [USB_SPEED_LOW] = 8,
3154 [USB_SPEED_FULL] = 8,
3155 [USB_SPEED_HIGH] = 64,
3156 [USB_SPEED_VARIABLE] = 512,
3157 [USB_SPEED_SUPER] = 512,
3160 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3161 [USB_SPEED_LOW] = 8,
3162 [USB_SPEED_FULL] = 8,
3163 [USB_SPEED_HIGH] = 512,
3164 [USB_SPEED_VARIABLE] = 512,
3165 [USB_SPEED_SUPER] = 1024,
3170 memset(ptr, 0, sizeof(*ptr));
3174 ptr->range.max = intr_range_max[speed];
3176 case UE_ISOCHRONOUS:
3177 ptr->range.max = isoc_range_max[speed];
3180 if (type == UE_BULK)
3181 temp = bulk_min[speed];
3182 else /* UE_CONTROL */
3183 temp = control_min[speed];
3185 /* default is fixed */
3186 ptr->fixed[0] = temp;
3187 ptr->fixed[1] = temp;
3188 ptr->fixed[2] = temp;
3189 ptr->fixed[3] = temp;
3191 if (speed == USB_SPEED_FULL) {
3192 /* multiple sizes */
3197 if ((speed == USB_SPEED_VARIABLE) &&
3198 (type == UE_BULK)) {
3199 /* multiple sizes */
3200 ptr->fixed[2] = 1024;
3201 ptr->fixed[3] = 1536;
3208 usbd_xfer_softc(struct usb_xfer *xfer)
3210 return (xfer->priv_sc);
3214 usbd_xfer_get_priv(struct usb_xfer *xfer)
3216 return (xfer->priv_fifo);
3220 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3222 xfer->priv_fifo = ptr;
3226 usbd_xfer_state(struct usb_xfer *xfer)
3228 return (xfer->usb_state);
3232 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3235 case USB_FORCE_SHORT_XFER:
3236 xfer->flags.force_short_xfer = 1;
3238 case USB_SHORT_XFER_OK:
3239 xfer->flags.short_xfer_ok = 1;
3241 case USB_MULTI_SHORT_OK:
3242 xfer->flags.short_frames_ok = 1;
3244 case USB_MANUAL_STATUS:
3245 xfer->flags.manual_status = 1;
3251 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3254 case USB_FORCE_SHORT_XFER:
3255 xfer->flags.force_short_xfer = 0;
3257 case USB_SHORT_XFER_OK:
3258 xfer->flags.short_xfer_ok = 0;
3260 case USB_MULTI_SHORT_OK:
3261 xfer->flags.short_frames_ok = 0;
3263 case USB_MANUAL_STATUS:
3264 xfer->flags.manual_status = 0;
3270 * The following function returns in milliseconds when the isochronous
3271 * transfer was completed by the hardware. The returned value wraps
3272 * around 65536 milliseconds.
3275 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3277 return (xfer->isoc_time_complete);