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 #ifdef USB_GLOBAL_INCLUDE_FILE
28 #include USB_GLOBAL_INCLUDE_FILE
30 #include <sys/stdint.h>
31 #include <sys/stddef.h>
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
38 #include <sys/module.h>
40 #include <sys/mutex.h>
41 #include <sys/condvar.h>
42 #include <sys/sysctl.h>
44 #include <sys/unistd.h>
45 #include <sys/callout.h>
46 #include <sys/malloc.h>
50 #include <dev/usb/usb.h>
51 #include <dev/usb/usbdi.h>
52 #include <dev/usb/usbdi_util.h>
54 #define USB_DEBUG_VAR usb_debug
56 #include <dev/usb/usb_core.h>
57 #include <dev/usb/usb_busdma.h>
58 #include <dev/usb/usb_process.h>
59 #include <dev/usb/usb_transfer.h>
60 #include <dev/usb/usb_device.h>
61 #include <dev/usb/usb_debug.h>
62 #include <dev/usb/usb_util.h>
64 #include <dev/usb/usb_controller.h>
65 #include <dev/usb/usb_bus.h>
66 #include <dev/usb/usb_pf.h>
67 #endif /* USB_GLOBAL_INCLUDE_FILE */
69 struct usb_std_packet_size {
71 uint16_t min; /* inclusive */
72 uint16_t max; /* inclusive */
78 static usb_callback_t usb_request_callback;
80 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
82 /* This transfer is used for generic control endpoint transfers */
86 .endpoint = 0x00, /* Control endpoint */
87 .direction = UE_DIR_ANY,
88 .bufsize = USB_EP0_BUFSIZE, /* bytes */
89 .flags = {.proxy_buffer = 1,},
90 .callback = &usb_request_callback,
91 .usb_mode = USB_MODE_DUAL, /* both modes */
94 /* This transfer is used for generic clear stall only */
98 .endpoint = 0x00, /* Control pipe */
99 .direction = UE_DIR_ANY,
100 .bufsize = sizeof(struct usb_device_request),
101 .callback = &usb_do_clear_stall_callback,
102 .timeout = 1000, /* 1 second */
103 .interval = 50, /* 50ms */
104 .usb_mode = USB_MODE_HOST,
108 /* function prototypes */
110 static void usbd_update_max_frame_size(struct usb_xfer *);
111 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
112 static void usbd_control_transfer_init(struct usb_xfer *);
113 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
114 static void usb_callback_proc(struct usb_proc_msg *);
115 static void usbd_callback_ss_done_defer(struct usb_xfer *);
116 static void usbd_callback_wrapper(struct usb_xfer_queue *);
117 static void usbd_transfer_start_cb(void *);
118 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
119 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
120 uint8_t type, enum usb_dev_speed speed);
122 /*------------------------------------------------------------------------*
123 * usb_request_callback
124 *------------------------------------------------------------------------*/
126 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
128 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
129 usb_handle_request_callback(xfer, error);
131 usbd_do_request_callback(xfer, error);
134 /*------------------------------------------------------------------------*
135 * usbd_update_max_frame_size
137 * This function updates the maximum frame size, hence high speed USB
138 * can transfer multiple consecutive packets.
139 *------------------------------------------------------------------------*/
141 usbd_update_max_frame_size(struct usb_xfer *xfer)
143 /* compute maximum frame size */
144 /* this computation should not overflow 16-bit */
145 /* max = 15 * 1024 */
147 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
150 /*------------------------------------------------------------------------*
153 * The following function is called when we need to
154 * synchronize with DMA hardware.
157 * 0: no DMA delay required
158 * Else: milliseconds of DMA delay
159 *------------------------------------------------------------------------*/
161 usbd_get_dma_delay(struct usb_device *udev)
163 struct usb_bus_methods *mtod;
166 mtod = udev->bus->methods;
169 if (mtod->get_dma_delay) {
170 (mtod->get_dma_delay) (udev, &temp);
172 * Round up and convert to milliseconds. Note that we use
173 * 1024 milliseconds per second. to save a division.
181 /*------------------------------------------------------------------------*
182 * usbd_transfer_setup_sub_malloc
184 * This function will allocate one or more DMA'able memory chunks
185 * according to "size", "align" and "count" arguments. "ppc" is
186 * pointed to a linear array of USB page caches afterwards.
188 * If the "align" argument is equal to "1" a non-contiguous allocation
189 * can happen. Else if the "align" argument is greater than "1", the
190 * allocation will always be contiguous in memory.
195 *------------------------------------------------------------------------*/
198 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
199 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
202 struct usb_page_cache *pc;
213 USB_ASSERT(align > 0, ("Invalid alignment, 0x%08x\n",
215 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
218 return (0); /* nothing to allocate */
221 * Make sure that the size is aligned properly.
223 size = -((-size) & (-align));
226 * Try multi-allocation chunks to reduce the number of DMA
227 * allocations, hence DMA allocations are slow.
230 /* special case - non-cached multi page DMA memory */
232 n_dma_pg = (2 + (size / USB_PAGE_SIZE));
234 } else if (size >= USB_PAGE_SIZE) {
239 /* compute number of objects per page */
240 n_obj = (USB_PAGE_SIZE / size);
242 * Compute number of DMA chunks, rounded up
245 n_dma_pc = ((count + n_obj - 1) / n_obj);
250 * DMA memory is allocated once, but mapped twice. That's why
251 * there is one list for auto-free and another list for
252 * non-auto-free which only holds the mapping and not the
255 if (parm->buf == NULL) {
256 /* reserve memory (auto-free) */
257 parm->dma_page_ptr += n_dma_pc * n_dma_pg;
258 parm->dma_page_cache_ptr += n_dma_pc;
260 /* reserve memory (no-auto-free) */
261 parm->dma_page_ptr += count * n_dma_pg;
262 parm->xfer_page_cache_ptr += count;
265 for (x = 0; x != n_dma_pc; x++) {
266 /* need to initialize the page cache */
267 parm->dma_page_cache_ptr[x].tag_parent =
268 &parm->curr_xfer->xroot->dma_parent_tag;
270 for (x = 0; x != count; x++) {
271 /* need to initialize the page cache */
272 parm->xfer_page_cache_ptr[x].tag_parent =
273 &parm->curr_xfer->xroot->dma_parent_tag;
277 *ppc = parm->xfer_page_cache_ptr;
279 r = count; /* set remainder count */
280 z = n_obj * size; /* set allocation size */
281 pc = parm->xfer_page_cache_ptr;
282 pg = parm->dma_page_ptr;
284 for (x = 0; x != n_dma_pc; x++) {
287 /* compute last remainder */
291 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
293 return (1); /* failure */
295 /* Set beginning of current buffer */
296 buf = parm->dma_page_cache_ptr->buffer;
297 /* Make room for one DMA page cache and one page */
298 parm->dma_page_cache_ptr++;
301 for (y = 0; (y != n_obj); y++, r--, pc++, pg += n_dma_pg) {
303 /* Load sub-chunk into DMA */
304 if (usb_pc_dmamap_create(pc, size)) {
305 return (1); /* failure */
307 pc->buffer = USB_ADD_BYTES(buf, y * size);
310 mtx_lock(pc->tag_parent->mtx);
311 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
312 mtx_unlock(pc->tag_parent->mtx);
313 return (1); /* failure */
315 mtx_unlock(pc->tag_parent->mtx);
319 parm->xfer_page_cache_ptr = pc;
320 parm->dma_page_ptr = pg;
325 /*------------------------------------------------------------------------*
326 * usbd_transfer_setup_sub - transfer setup subroutine
328 * This function must be called from the "xfer_setup" callback of the
329 * USB Host or Device controller driver when setting up an USB
330 * transfer. This function will setup correct packet sizes, buffer
331 * sizes, flags and more, that are stored in the "usb_xfer"
333 *------------------------------------------------------------------------*/
335 usbd_transfer_setup_sub(struct usb_setup_params *parm)
341 struct usb_xfer *xfer = parm->curr_xfer;
342 const struct usb_config *setup = parm->curr_setup;
343 struct usb_endpoint_ss_comp_descriptor *ecomp;
344 struct usb_endpoint_descriptor *edesc;
345 struct usb_std_packet_size std_size;
346 usb_frcount_t n_frlengths;
347 usb_frcount_t n_frbuffers;
354 * Sanity check. The following parameters must be initialized before
355 * calling this function.
357 if ((parm->hc_max_packet_size == 0) ||
358 (parm->hc_max_packet_count == 0) ||
359 (parm->hc_max_frame_size == 0)) {
360 parm->err = USB_ERR_INVAL;
363 edesc = xfer->endpoint->edesc;
364 ecomp = xfer->endpoint->ecomp;
366 type = (edesc->bmAttributes & UE_XFERTYPE);
368 xfer->flags = setup->flags;
369 xfer->nframes = setup->frames;
370 xfer->timeout = setup->timeout;
371 xfer->callback = setup->callback;
372 xfer->interval = setup->interval;
373 xfer->endpointno = edesc->bEndpointAddress;
374 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
375 xfer->max_packet_count = 1;
376 /* make a shadow copy: */
377 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
379 parm->bufsize = setup->bufsize;
381 switch (parm->speed) {
386 xfer->max_packet_count +=
387 (xfer->max_packet_size >> 11) & 3;
389 /* check for invalid max packet count */
390 if (xfer->max_packet_count > 3)
391 xfer->max_packet_count = 3;
396 xfer->max_packet_size &= 0x7FF;
398 case USB_SPEED_SUPER:
399 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
402 xfer->max_packet_count += ecomp->bMaxBurst;
404 if ((xfer->max_packet_count == 0) ||
405 (xfer->max_packet_count > 16))
406 xfer->max_packet_count = 16;
410 xfer->max_packet_count = 1;
416 mult = UE_GET_SS_ISO_MULT(
417 ecomp->bmAttributes) + 1;
421 xfer->max_packet_count *= mult;
427 xfer->max_packet_size &= 0x7FF;
432 /* range check "max_packet_count" */
434 if (xfer->max_packet_count > parm->hc_max_packet_count) {
435 xfer->max_packet_count = parm->hc_max_packet_count;
438 /* store max packet size value before filtering */
440 maxp_old = xfer->max_packet_size;
442 /* filter "wMaxPacketSize" according to HC capabilities */
444 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
445 (xfer->max_packet_size == 0)) {
446 xfer->max_packet_size = parm->hc_max_packet_size;
448 /* filter "wMaxPacketSize" according to standard sizes */
450 usbd_get_std_packet_size(&std_size, type, parm->speed);
452 if (std_size.range.min || std_size.range.max) {
454 if (xfer->max_packet_size < std_size.range.min) {
455 xfer->max_packet_size = std_size.range.min;
457 if (xfer->max_packet_size > std_size.range.max) {
458 xfer->max_packet_size = std_size.range.max;
462 if (xfer->max_packet_size >= std_size.fixed[3]) {
463 xfer->max_packet_size = std_size.fixed[3];
464 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
465 xfer->max_packet_size = std_size.fixed[2];
466 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
467 xfer->max_packet_size = std_size.fixed[1];
469 /* only one possibility left */
470 xfer->max_packet_size = std_size.fixed[0];
475 * Check if the max packet size was outside its allowed range
476 * and clamped to a valid value:
478 if (maxp_old != xfer->max_packet_size)
479 xfer->flags_int.maxp_was_clamped = 1;
481 /* compute "max_frame_size" */
483 usbd_update_max_frame_size(xfer);
485 /* check interrupt interval and transfer pre-delay */
487 if (type == UE_ISOCHRONOUS) {
489 uint16_t frame_limit;
491 xfer->interval = 0; /* not used, must be zero */
492 xfer->flags_int.isochronous_xfr = 1; /* set flag */
494 if (xfer->timeout == 0) {
496 * set a default timeout in
497 * case something goes wrong!
499 xfer->timeout = 1000 / 4;
501 switch (parm->speed) {
504 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
508 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
509 xfer->fps_shift = edesc->bInterval;
510 if (xfer->fps_shift > 0)
512 if (xfer->fps_shift > 3)
514 if (xfer->flags.pre_scale_frames != 0)
515 xfer->nframes <<= (3 - xfer->fps_shift);
519 if (xfer->nframes > frame_limit) {
521 * this is not going to work
524 parm->err = USB_ERR_INVAL;
527 if (xfer->nframes == 0) {
529 * this is not a valid value
531 parm->err = USB_ERR_ZERO_NFRAMES;
537 * If a value is specified use that else check the
538 * endpoint descriptor!
540 if (type == UE_INTERRUPT) {
544 if (xfer->interval == 0) {
546 xfer->interval = edesc->bInterval;
548 switch (parm->speed) {
554 if (xfer->interval < 4)
556 else if (xfer->interval > 16)
557 xfer->interval = (1 << (16 - 4));
560 (1 << (xfer->interval - 4));
565 if (xfer->interval == 0) {
567 * One millisecond is the smallest
568 * interval we support:
576 while ((temp != 0) && (temp < xfer->interval)) {
581 switch (parm->speed) {
586 xfer->fps_shift += 3;
593 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
594 * to be equal to zero when setting up USB transfers, hence
595 * this leads to alot of extra code in the USB kernel.
598 if ((xfer->max_frame_size == 0) ||
599 (xfer->max_packet_size == 0)) {
603 if ((parm->bufsize <= MIN_PKT) &&
604 (type != UE_CONTROL) &&
608 xfer->max_packet_size = MIN_PKT;
609 xfer->max_packet_count = 1;
610 parm->bufsize = 0; /* automatic setup length */
611 usbd_update_max_frame_size(xfer);
614 parm->err = USB_ERR_ZERO_MAXP;
623 * check if we should setup a default
627 if (parm->bufsize == 0) {
629 parm->bufsize = xfer->max_frame_size;
631 if (type == UE_ISOCHRONOUS) {
632 parm->bufsize *= xfer->nframes;
636 * check if we are about to setup a proxy
640 if (xfer->flags.proxy_buffer) {
642 /* round bufsize up */
644 parm->bufsize += (xfer->max_frame_size - 1);
646 if (parm->bufsize < xfer->max_frame_size) {
647 /* length wrapped around */
648 parm->err = USB_ERR_INVAL;
651 /* subtract remainder */
653 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
655 /* add length of USB device request structure, if any */
657 if (type == UE_CONTROL) {
658 parm->bufsize += REQ_SIZE; /* SETUP message */
661 xfer->max_data_length = parm->bufsize;
663 /* Setup "n_frlengths" and "n_frbuffers" */
665 if (type == UE_ISOCHRONOUS) {
666 n_frlengths = xfer->nframes;
670 if (type == UE_CONTROL) {
671 xfer->flags_int.control_xfr = 1;
672 if (xfer->nframes == 0) {
673 if (parm->bufsize <= REQ_SIZE) {
675 * there will never be any data
684 if (xfer->nframes == 0) {
689 n_frlengths = xfer->nframes;
690 n_frbuffers = xfer->nframes;
694 * check if we have room for the
695 * USB device request structure:
698 if (type == UE_CONTROL) {
700 if (xfer->max_data_length < REQ_SIZE) {
701 /* length wrapped around or too small bufsize */
702 parm->err = USB_ERR_INVAL;
705 xfer->max_data_length -= REQ_SIZE;
708 * Setup "frlengths" and shadow "frlengths" for keeping the
709 * initial frame lengths when a USB transfer is complete. This
710 * information is useful when computing isochronous offsets.
712 xfer->frlengths = parm->xfer_length_ptr;
713 parm->xfer_length_ptr += 2 * n_frlengths;
715 /* setup "frbuffers" */
716 xfer->frbuffers = parm->xfer_page_cache_ptr;
717 parm->xfer_page_cache_ptr += n_frbuffers;
719 /* initialize max frame count */
720 xfer->max_frame_count = xfer->nframes;
723 * check if we need to setup
727 if (!xfer->flags.ext_buffer) {
729 struct usb_page_search page_info;
730 struct usb_page_cache *pc;
732 if (usbd_transfer_setup_sub_malloc(parm,
733 &pc, parm->bufsize, 1, 1)) {
734 parm->err = USB_ERR_NOMEM;
735 } else if (parm->buf != NULL) {
737 usbd_get_page(pc, 0, &page_info);
739 xfer->local_buffer = page_info.buffer;
741 usbd_xfer_set_frame_offset(xfer, 0, 0);
743 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
744 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
749 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
751 if (parm->buf != NULL) {
753 USB_ADD_BYTES(parm->buf, parm->size[0]);
755 usbd_xfer_set_frame_offset(xfer, 0, 0);
757 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
758 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
761 parm->size[0] += parm->bufsize;
763 /* align data again */
764 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
768 * Compute maximum buffer size
771 if (parm->bufsize_max < parm->bufsize) {
772 parm->bufsize_max = parm->bufsize;
775 if (xfer->flags_int.bdma_enable) {
777 * Setup "dma_page_ptr".
779 * Proof for formula below:
781 * Assume there are three USB frames having length "a", "b" and
782 * "c". These USB frames will at maximum need "z"
783 * "usb_page" structures. "z" is given by:
785 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
786 * ((c / USB_PAGE_SIZE) + 2);
788 * Constraining "a", "b" and "c" like this:
790 * (a + b + c) <= parm->bufsize
794 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
796 * Here is the general formula:
798 xfer->dma_page_ptr = parm->dma_page_ptr;
799 parm->dma_page_ptr += (2 * n_frbuffers);
800 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
804 /* correct maximum data length */
805 xfer->max_data_length = 0;
807 /* subtract USB frame remainder from "hc_max_frame_size" */
809 xfer->max_hc_frame_size =
810 (parm->hc_max_frame_size -
811 (parm->hc_max_frame_size % xfer->max_frame_size));
813 if (xfer->max_hc_frame_size == 0) {
814 parm->err = USB_ERR_INVAL;
818 /* initialize frame buffers */
821 for (x = 0; x != n_frbuffers; x++) {
822 xfer->frbuffers[x].tag_parent =
823 &xfer->xroot->dma_parent_tag;
825 if (xfer->flags_int.bdma_enable &&
826 (parm->bufsize_max > 0)) {
828 if (usb_pc_dmamap_create(
830 parm->bufsize_max)) {
831 parm->err = USB_ERR_NOMEM;
841 * Set some dummy values so that we avoid division by zero:
843 xfer->max_hc_frame_size = 1;
844 xfer->max_frame_size = 1;
845 xfer->max_packet_size = 1;
846 xfer->max_data_length = 0;
848 xfer->max_frame_count = 0;
852 /*------------------------------------------------------------------------*
853 * usbd_transfer_setup - setup an array of USB transfers
855 * NOTE: You must always call "usbd_transfer_unsetup" after calling
856 * "usbd_transfer_setup" if success was returned.
858 * The idea is that the USB device driver should pre-allocate all its
859 * transfers by one call to this function.
864 *------------------------------------------------------------------------*/
866 usbd_transfer_setup(struct usb_device *udev,
867 const uint8_t *ifaces, struct usb_xfer **ppxfer,
868 const struct usb_config *setup_start, uint16_t n_setup,
869 void *priv_sc, struct mtx *xfer_mtx)
871 const struct usb_config *setup_end = setup_start + n_setup;
872 const struct usb_config *setup;
873 struct usb_setup_params *parm;
874 struct usb_endpoint *ep;
875 struct usb_xfer_root *info;
876 struct usb_xfer *xfer;
878 usb_error_t error = 0;
883 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
884 "usbd_transfer_setup can sleep!");
886 /* do some checking first */
889 DPRINTFN(6, "setup array has zero length!\n");
890 return (USB_ERR_INVAL);
893 DPRINTFN(6, "ifaces array is NULL!\n");
894 return (USB_ERR_INVAL);
896 if (xfer_mtx == NULL) {
897 DPRINTFN(6, "using global lock\n");
901 /* more sanity checks */
903 for (setup = setup_start, n = 0;
904 setup != setup_end; setup++, n++) {
905 if (setup->bufsize == (usb_frlength_t)-1) {
906 error = USB_ERR_BAD_BUFSIZE;
907 DPRINTF("invalid bufsize\n");
909 if (setup->callback == NULL) {
910 error = USB_ERR_NO_CALLBACK;
911 DPRINTF("no callback\n");
919 /* Protect scratch area */
920 do_unlock = usbd_enum_lock(udev);
925 parm = &udev->scratch.xfer_setup[0].parm;
926 memset(parm, 0, sizeof(*parm));
929 parm->speed = usbd_get_speed(udev);
930 parm->hc_max_packet_count = 1;
932 if (parm->speed >= USB_SPEED_MAX) {
933 parm->err = USB_ERR_INVAL;
936 /* setup all transfers */
942 * Initialize the "usb_xfer_root" structure,
943 * which is common for all our USB transfers.
945 info = USB_ADD_BYTES(buf, 0);
947 info->memory_base = buf;
948 info->memory_size = parm->size[0];
951 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
952 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
954 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
955 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
957 cv_init(&info->cv_drain, "WDRAIN");
959 info->xfer_mtx = xfer_mtx;
961 usb_dma_tag_setup(&info->dma_parent_tag,
962 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
963 xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
967 info->bus = udev->bus;
970 TAILQ_INIT(&info->done_q.head);
971 info->done_q.command = &usbd_callback_wrapper;
973 TAILQ_INIT(&info->dma_q.head);
974 info->dma_q.command = &usb_bdma_work_loop;
976 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
977 info->done_m[0].xroot = info;
978 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
979 info->done_m[1].xroot = info;
982 * In device side mode control endpoint
983 * requests need to run from a separate
984 * context, else there is a chance of
987 if (setup_start == usb_control_ep_cfg)
989 USB_BUS_CONTROL_XFER_PROC(udev->bus);
990 else if (xfer_mtx == &Giant)
992 USB_BUS_GIANT_PROC(udev->bus);
995 USB_BUS_NON_GIANT_PROC(udev->bus);
1001 parm->size[0] += sizeof(info[0]);
1003 for (setup = setup_start, n = 0;
1004 setup != setup_end; setup++, n++) {
1006 /* skip USB transfers without callbacks: */
1007 if (setup->callback == NULL) {
1010 /* see if there is a matching endpoint */
1011 ep = usbd_get_endpoint(udev,
1012 ifaces[setup->if_index], setup);
1015 * Check that the USB PIPE is valid and that
1016 * the endpoint mode is proper.
1018 * Make sure we don't allocate a streams
1019 * transfer when such a combination is not
1022 if ((ep == NULL) || (ep->methods == NULL) ||
1023 ((ep->ep_mode != USB_EP_MODE_STREAMS) &&
1024 (ep->ep_mode != USB_EP_MODE_DEFAULT)) ||
1025 (setup->stream_id != 0 &&
1026 (setup->stream_id >= USB_MAX_EP_STREAMS ||
1027 (ep->ep_mode != USB_EP_MODE_STREAMS)))) {
1028 if (setup->flags.no_pipe_ok)
1030 if ((setup->usb_mode != USB_MODE_DUAL) &&
1031 (setup->usb_mode != udev->flags.usb_mode))
1033 parm->err = USB_ERR_NO_PIPE;
1037 /* align data properly */
1038 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1040 /* store current setup pointer */
1041 parm->curr_setup = setup;
1045 * Common initialization of the
1046 * "usb_xfer" structure.
1048 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1049 xfer->address = udev->address;
1050 xfer->priv_sc = priv_sc;
1053 usb_callout_init_mtx(&xfer->timeout_handle,
1054 &udev->bus->bus_mtx, 0);
1057 * Setup a dummy xfer, hence we are
1058 * writing to the "usb_xfer"
1059 * structure pointed to by "xfer"
1060 * before we have allocated any
1063 xfer = &udev->scratch.xfer_setup[0].dummy;
1064 memset(xfer, 0, sizeof(*xfer));
1068 /* set transfer endpoint pointer */
1069 xfer->endpoint = ep;
1071 /* set transfer stream ID */
1072 xfer->stream_id = setup->stream_id;
1074 parm->size[0] += sizeof(xfer[0]);
1075 parm->methods = xfer->endpoint->methods;
1076 parm->curr_xfer = xfer;
1079 * Call the Host or Device controller transfer
1082 (udev->bus->methods->xfer_setup) (parm);
1084 /* check for error */
1090 * Increment the endpoint refcount. This
1091 * basically prevents setting a new
1092 * configuration and alternate setting
1093 * when USB transfers are in use on
1094 * the given interface. Search the USB
1095 * code for "endpoint->refcount_alloc" if you
1096 * want more information.
1098 USB_BUS_LOCK(info->bus);
1099 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1100 parm->err = USB_ERR_INVAL;
1102 xfer->endpoint->refcount_alloc++;
1104 if (xfer->endpoint->refcount_alloc == 0)
1105 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1106 USB_BUS_UNLOCK(info->bus);
1109 * Whenever we set ppxfer[] then we
1110 * also need to increment the
1113 info->setup_refcount++;
1116 * Transfer is successfully setup and
1122 /* check for error */
1127 if (buf != NULL || parm->err != 0)
1130 /* if no transfers, nothing to do */
1134 /* align data properly */
1135 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1137 /* store offset temporarily */
1138 parm->size[1] = parm->size[0];
1141 * The number of DMA tags required depends on
1142 * the number of endpoints. The current estimate
1143 * for maximum number of DMA tags per endpoint
1145 * 1) for loading memory
1146 * 2) for allocating memory
1147 * 3) for fixing memory [UHCI]
1149 parm->dma_tag_max += 3 * MIN(n_setup, USB_EP_MAX);
1152 * DMA tags for QH, TD, Data and more.
1154 parm->dma_tag_max += 8;
1156 parm->dma_tag_p += parm->dma_tag_max;
1158 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1161 /* align data properly */
1162 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1164 /* store offset temporarily */
1165 parm->size[3] = parm->size[0];
1167 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1170 /* align data properly */
1171 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1173 /* store offset temporarily */
1174 parm->size[4] = parm->size[0];
1176 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1179 /* store end offset temporarily */
1180 parm->size[5] = parm->size[0];
1182 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1185 /* store end offset temporarily */
1187 parm->size[2] = parm->size[0];
1189 /* align data properly */
1190 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1192 parm->size[6] = parm->size[0];
1194 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1197 /* align data properly */
1198 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1200 /* allocate zeroed memory */
1201 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1204 parm->err = USB_ERR_NOMEM;
1205 DPRINTFN(0, "cannot allocate memory block for "
1206 "configuration (%d bytes)\n",
1210 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1211 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1212 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1213 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1214 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1219 if (info->setup_refcount == 0) {
1221 * "usbd_transfer_unsetup_sub" will unlock
1222 * the bus mutex before returning !
1224 USB_BUS_LOCK(info->bus);
1226 /* something went wrong */
1227 usbd_transfer_unsetup_sub(info, 0);
1231 /* check if any errors happened */
1233 usbd_transfer_unsetup(ppxfer, n_setup);
1238 usbd_enum_unlock(udev);
1243 /*------------------------------------------------------------------------*
1244 * usbd_transfer_unsetup_sub - factored out code
1245 *------------------------------------------------------------------------*/
1247 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1250 struct usb_page_cache *pc;
1253 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1255 /* wait for any outstanding DMA operations */
1259 temp = usbd_get_dma_delay(info->udev);
1261 usb_pause_mtx(&info->bus->bus_mtx,
1262 USB_MS_TO_TICKS(temp));
1266 /* make sure that our done messages are not queued anywhere */
1267 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1269 USB_BUS_UNLOCK(info->bus);
1272 /* free DMA'able memory, if any */
1273 pc = info->dma_page_cache_start;
1274 while (pc != info->dma_page_cache_end) {
1275 usb_pc_free_mem(pc);
1279 /* free DMA maps in all "xfer->frbuffers" */
1280 pc = info->xfer_page_cache_start;
1281 while (pc != info->xfer_page_cache_end) {
1282 usb_pc_dmamap_destroy(pc);
1286 /* free all DMA tags */
1287 usb_dma_tag_unsetup(&info->dma_parent_tag);
1290 cv_destroy(&info->cv_drain);
1293 * free the "memory_base" last, hence the "info" structure is
1294 * contained within the "memory_base"!
1296 free(info->memory_base, M_USB);
1299 /*------------------------------------------------------------------------*
1300 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1302 * NOTE: All USB transfers in progress will get called back passing
1303 * the error code "USB_ERR_CANCELLED" before this function
1305 *------------------------------------------------------------------------*/
1307 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1309 struct usb_xfer *xfer;
1310 struct usb_xfer_root *info;
1311 uint8_t needs_delay = 0;
1313 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1314 "usbd_transfer_unsetup can sleep!");
1317 xfer = pxfer[n_setup];
1324 USB_XFER_LOCK(xfer);
1325 USB_BUS_LOCK(info->bus);
1328 * HINT: when you start/stop a transfer, it might be a
1329 * good idea to directly use the "pxfer[]" structure:
1331 * usbd_transfer_start(sc->pxfer[0]);
1332 * usbd_transfer_stop(sc->pxfer[0]);
1334 * That way, if your code has many parts that will not
1335 * stop running under the same lock, in other words
1336 * "xfer_mtx", the usbd_transfer_start and
1337 * usbd_transfer_stop functions will simply return
1338 * when they detect a NULL pointer argument.
1340 * To avoid any races we clear the "pxfer[]" pointer
1341 * while holding the private mutex of the driver:
1343 pxfer[n_setup] = NULL;
1345 USB_BUS_UNLOCK(info->bus);
1346 USB_XFER_UNLOCK(xfer);
1348 usbd_transfer_drain(xfer);
1351 if (xfer->flags_int.bdma_enable)
1355 * NOTE: default endpoint does not have an
1356 * interface, even if endpoint->iface_index == 0
1358 USB_BUS_LOCK(info->bus);
1359 xfer->endpoint->refcount_alloc--;
1360 USB_BUS_UNLOCK(info->bus);
1362 usb_callout_drain(&xfer->timeout_handle);
1364 USB_BUS_LOCK(info->bus);
1366 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1367 "reference count\n"));
1369 info->setup_refcount--;
1371 if (info->setup_refcount == 0) {
1372 usbd_transfer_unsetup_sub(info,
1375 USB_BUS_UNLOCK(info->bus);
1380 /*------------------------------------------------------------------------*
1381 * usbd_control_transfer_init - factored out code
1383 * In USB Device Mode we have to wait for the SETUP packet which
1384 * containst the "struct usb_device_request" structure, before we can
1385 * transfer any data. In USB Host Mode we already have the SETUP
1386 * packet at the moment the USB transfer is started. This leads us to
1387 * having to setup the USB transfer at two different places in
1388 * time. This function just contains factored out control transfer
1389 * initialisation code, so that we don't duplicate the code.
1390 *------------------------------------------------------------------------*/
1392 usbd_control_transfer_init(struct usb_xfer *xfer)
1394 struct usb_device_request req;
1396 /* copy out the USB request header */
1398 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1400 /* setup remainder */
1402 xfer->flags_int.control_rem = UGETW(req.wLength);
1404 /* copy direction to endpoint variable */
1406 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1408 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1411 /*------------------------------------------------------------------------*
1412 * usbd_control_transfer_did_data
1414 * This function returns non-zero if a control endpoint has
1415 * transferred the first DATA packet after the SETUP packet.
1416 * Else it returns zero.
1417 *------------------------------------------------------------------------*/
1419 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1421 struct usb_device_request req;
1423 /* SETUP packet is not yet sent */
1424 if (xfer->flags_int.control_hdr != 0)
1427 /* copy out the USB request header */
1428 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1430 /* compare remainder to the initial value */
1431 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1434 /*------------------------------------------------------------------------*
1435 * usbd_setup_ctrl_transfer
1437 * This function handles initialisation of control transfers. Control
1438 * transfers are special in that regard that they can both transmit
1444 *------------------------------------------------------------------------*/
1446 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1450 /* Check for control endpoint stall */
1451 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1452 /* the control transfer is no longer active */
1453 xfer->flags_int.control_stall = 1;
1454 xfer->flags_int.control_act = 0;
1456 /* don't stall control transfer by default */
1457 xfer->flags_int.control_stall = 0;
1460 /* Check for invalid number of frames */
1461 if (xfer->nframes > 2) {
1463 * If you need to split a control transfer, you
1464 * have to do one part at a time. Only with
1465 * non-control transfers you can do multiple
1468 DPRINTFN(0, "Too many frames: %u\n",
1469 (unsigned int)xfer->nframes);
1474 * Check if there is a control
1475 * transfer in progress:
1477 if (xfer->flags_int.control_act) {
1479 if (xfer->flags_int.control_hdr) {
1481 /* clear send header flag */
1483 xfer->flags_int.control_hdr = 0;
1485 /* setup control transfer */
1486 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1487 usbd_control_transfer_init(xfer);
1490 /* get data length */
1496 /* the size of the SETUP structure is hardcoded ! */
1498 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1499 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1500 xfer->frlengths[0], sizeof(struct
1501 usb_device_request));
1504 /* check USB mode */
1505 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1507 /* check number of frames */
1508 if (xfer->nframes != 1) {
1510 * We need to receive the setup
1511 * message first so that we know the
1514 DPRINTF("Misconfigured transfer\n");
1518 * Set a dummy "control_rem" value. This
1519 * variable will be overwritten later by a
1520 * call to "usbd_control_transfer_init()" !
1522 xfer->flags_int.control_rem = 0xFFFF;
1525 /* setup "endpoint" and "control_rem" */
1527 usbd_control_transfer_init(xfer);
1530 /* set transfer-header flag */
1532 xfer->flags_int.control_hdr = 1;
1534 /* get data length */
1536 len = (xfer->sumlen - sizeof(struct usb_device_request));
1539 /* update did data flag */
1541 xfer->flags_int.control_did_data =
1542 usbd_control_transfer_did_data(xfer);
1544 /* check if there is a length mismatch */
1546 if (len > xfer->flags_int.control_rem) {
1547 DPRINTFN(0, "Length (%d) greater than "
1548 "remaining length (%d)\n", len,
1549 xfer->flags_int.control_rem);
1552 /* check if we are doing a short transfer */
1554 if (xfer->flags.force_short_xfer) {
1555 xfer->flags_int.control_rem = 0;
1557 if ((len != xfer->max_data_length) &&
1558 (len != xfer->flags_int.control_rem) &&
1559 (xfer->nframes != 1)) {
1560 DPRINTFN(0, "Short control transfer without "
1561 "force_short_xfer set\n");
1564 xfer->flags_int.control_rem -= len;
1567 /* the status part is executed when "control_act" is 0 */
1569 if ((xfer->flags_int.control_rem > 0) ||
1570 (xfer->flags.manual_status)) {
1571 /* don't execute the STATUS stage yet */
1572 xfer->flags_int.control_act = 1;
1575 if ((!xfer->flags_int.control_hdr) &&
1576 (xfer->nframes == 1)) {
1578 * This is not a valid operation!
1580 DPRINTFN(0, "Invalid parameter "
1585 /* time to execute the STATUS stage */
1586 xfer->flags_int.control_act = 0;
1588 return (0); /* success */
1591 return (1); /* failure */
1594 /*------------------------------------------------------------------------*
1595 * usbd_transfer_submit - start USB hardware for the given transfer
1597 * This function should only be called from the USB callback.
1598 *------------------------------------------------------------------------*/
1600 usbd_transfer_submit(struct usb_xfer *xfer)
1602 struct usb_xfer_root *info;
1603 struct usb_bus *bus;
1609 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1610 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1614 if (USB_DEBUG_VAR > 0) {
1617 usb_dump_endpoint(xfer->endpoint);
1619 USB_BUS_UNLOCK(bus);
1623 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1624 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1626 /* Only open the USB transfer once! */
1627 if (!xfer->flags_int.open) {
1628 xfer->flags_int.open = 1;
1633 (xfer->endpoint->methods->open) (xfer);
1634 USB_BUS_UNLOCK(bus);
1636 /* set "transferring" flag */
1637 xfer->flags_int.transferring = 1;
1640 /* increment power reference */
1641 usbd_transfer_power_ref(xfer, 1);
1644 * Check if the transfer is waiting on a queue, most
1645 * frequently the "done_q":
1647 if (xfer->wait_queue) {
1649 usbd_transfer_dequeue(xfer);
1650 USB_BUS_UNLOCK(bus);
1652 /* clear "did_dma_delay" flag */
1653 xfer->flags_int.did_dma_delay = 0;
1655 /* clear "did_close" flag */
1656 xfer->flags_int.did_close = 0;
1659 /* clear "bdma_setup" flag */
1660 xfer->flags_int.bdma_setup = 0;
1662 /* by default we cannot cancel any USB transfer immediately */
1663 xfer->flags_int.can_cancel_immed = 0;
1665 /* clear lengths and frame counts by default */
1670 /* clear any previous errors */
1673 /* Check if the device is still alive */
1674 if (info->udev->state < USB_STATE_POWERED) {
1677 * Must return cancelled error code else
1678 * device drivers can hang.
1680 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1681 USB_BUS_UNLOCK(bus);
1686 if (xfer->nframes == 0) {
1687 if (xfer->flags.stall_pipe) {
1689 * Special case - want to stall without transferring
1692 DPRINTF("xfer=%p nframes=0: stall "
1693 "or clear stall!\n", xfer);
1695 xfer->flags_int.can_cancel_immed = 1;
1696 /* start the transfer */
1697 usb_command_wrapper(&xfer->endpoint->
1698 endpoint_q[xfer->stream_id], xfer);
1699 USB_BUS_UNLOCK(bus);
1703 usbd_transfer_done(xfer, USB_ERR_INVAL);
1704 USB_BUS_UNLOCK(bus);
1707 /* compute some variables */
1709 for (x = 0; x != xfer->nframes; x++) {
1710 /* make a copy of the frlenghts[] */
1711 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1712 /* compute total transfer length */
1713 xfer->sumlen += xfer->frlengths[x];
1714 if (xfer->sumlen < xfer->frlengths[x]) {
1715 /* length wrapped around */
1717 usbd_transfer_done(xfer, USB_ERR_INVAL);
1718 USB_BUS_UNLOCK(bus);
1723 /* clear some internal flags */
1725 xfer->flags_int.short_xfer_ok = 0;
1726 xfer->flags_int.short_frames_ok = 0;
1728 /* check if this is a control transfer */
1730 if (xfer->flags_int.control_xfr) {
1732 if (usbd_setup_ctrl_transfer(xfer)) {
1734 usbd_transfer_done(xfer, USB_ERR_STALLED);
1735 USB_BUS_UNLOCK(bus);
1740 * Setup filtered version of some transfer flags,
1741 * in case of data read direction
1743 if (USB_GET_DATA_ISREAD(xfer)) {
1745 if (xfer->flags.short_frames_ok) {
1746 xfer->flags_int.short_xfer_ok = 1;
1747 xfer->flags_int.short_frames_ok = 1;
1748 } else if (xfer->flags.short_xfer_ok) {
1749 xfer->flags_int.short_xfer_ok = 1;
1751 /* check for control transfer */
1752 if (xfer->flags_int.control_xfr) {
1754 * 1) Control transfers do not support
1755 * reception of multiple short USB
1756 * frames in host mode and device side
1757 * mode, with exception of:
1759 * 2) Due to sometimes buggy device
1760 * side firmware we need to do a
1761 * STATUS stage in case of short
1762 * control transfers in USB host mode.
1763 * The STATUS stage then becomes the
1764 * "alt_next" to the DATA stage.
1766 xfer->flags_int.short_frames_ok = 1;
1771 * Check if BUS-DMA support is enabled and try to load virtual
1772 * buffers into DMA, if any:
1775 if (xfer->flags_int.bdma_enable) {
1776 /* insert the USB transfer last in the BUS-DMA queue */
1777 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1782 * Enter the USB transfer into the Host Controller or
1783 * Device Controller schedule:
1785 usbd_pipe_enter(xfer);
1788 /*------------------------------------------------------------------------*
1789 * usbd_pipe_enter - factored out code
1790 *------------------------------------------------------------------------*/
1792 usbd_pipe_enter(struct usb_xfer *xfer)
1794 struct usb_endpoint *ep;
1796 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1798 USB_BUS_LOCK(xfer->xroot->bus);
1800 ep = xfer->endpoint;
1804 /* the transfer can now be cancelled */
1805 xfer->flags_int.can_cancel_immed = 1;
1807 /* enter the transfer */
1808 (ep->methods->enter) (xfer);
1810 /* check for transfer error */
1812 /* some error has happened */
1813 usbd_transfer_done(xfer, 0);
1814 USB_BUS_UNLOCK(xfer->xroot->bus);
1818 /* start the transfer */
1819 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1820 USB_BUS_UNLOCK(xfer->xroot->bus);
1823 /*------------------------------------------------------------------------*
1824 * usbd_transfer_start - start an USB transfer
1826 * NOTE: Calling this function more than one time will only
1827 * result in a single transfer start, until the USB transfer
1829 *------------------------------------------------------------------------*/
1831 usbd_transfer_start(struct usb_xfer *xfer)
1834 /* transfer is gone */
1837 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1839 /* mark the USB transfer started */
1841 if (!xfer->flags_int.started) {
1842 /* lock the BUS lock to avoid races updating flags_int */
1843 USB_BUS_LOCK(xfer->xroot->bus);
1844 xfer->flags_int.started = 1;
1845 USB_BUS_UNLOCK(xfer->xroot->bus);
1847 /* check if the USB transfer callback is already transferring */
1849 if (xfer->flags_int.transferring) {
1852 USB_BUS_LOCK(xfer->xroot->bus);
1853 /* call the USB transfer callback */
1854 usbd_callback_ss_done_defer(xfer);
1855 USB_BUS_UNLOCK(xfer->xroot->bus);
1858 /*------------------------------------------------------------------------*
1859 * usbd_transfer_stop - stop an USB transfer
1861 * NOTE: Calling this function more than one time will only
1862 * result in a single transfer stop.
1863 * NOTE: When this function returns it is not safe to free nor
1864 * reuse any DMA buffers. See "usbd_transfer_drain()".
1865 *------------------------------------------------------------------------*/
1867 usbd_transfer_stop(struct usb_xfer *xfer)
1869 struct usb_endpoint *ep;
1872 /* transfer is gone */
1875 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1877 /* check if the USB transfer was ever opened */
1879 if (!xfer->flags_int.open) {
1880 if (xfer->flags_int.started) {
1881 /* nothing to do except clearing the "started" flag */
1882 /* lock the BUS lock to avoid races updating flags_int */
1883 USB_BUS_LOCK(xfer->xroot->bus);
1884 xfer->flags_int.started = 0;
1885 USB_BUS_UNLOCK(xfer->xroot->bus);
1889 /* try to stop the current USB transfer */
1891 USB_BUS_LOCK(xfer->xroot->bus);
1892 /* override any previous error */
1893 xfer->error = USB_ERR_CANCELLED;
1896 * Clear "open" and "started" when both private and USB lock
1897 * is locked so that we don't get a race updating "flags_int"
1899 xfer->flags_int.open = 0;
1900 xfer->flags_int.started = 0;
1903 * Check if we can cancel the USB transfer immediately.
1905 if (xfer->flags_int.transferring) {
1906 if (xfer->flags_int.can_cancel_immed &&
1907 (!xfer->flags_int.did_close)) {
1910 * The following will lead to an USB_ERR_CANCELLED
1911 * error code being passed to the USB callback.
1913 (xfer->endpoint->methods->close) (xfer);
1914 /* only close once */
1915 xfer->flags_int.did_close = 1;
1917 /* need to wait for the next done callback */
1922 /* close here and now */
1923 (xfer->endpoint->methods->close) (xfer);
1926 * Any additional DMA delay is done by
1927 * "usbd_transfer_unsetup()".
1931 * Special case. Check if we need to restart a blocked
1934 ep = xfer->endpoint;
1937 * If the current USB transfer is completing we need
1938 * to start the next one:
1940 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
1941 usb_command_wrapper(
1942 &ep->endpoint_q[xfer->stream_id], NULL);
1946 USB_BUS_UNLOCK(xfer->xroot->bus);
1949 /*------------------------------------------------------------------------*
1950 * usbd_transfer_pending
1952 * This function will check if an USB transfer is pending which is a
1953 * little bit complicated!
1956 * 1: Pending: The USB transfer will receive a callback in the future.
1957 *------------------------------------------------------------------------*/
1959 usbd_transfer_pending(struct usb_xfer *xfer)
1961 struct usb_xfer_root *info;
1962 struct usb_xfer_queue *pq;
1965 /* transfer is gone */
1968 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1970 if (xfer->flags_int.transferring) {
1974 USB_BUS_LOCK(xfer->xroot->bus);
1975 if (xfer->wait_queue) {
1976 /* we are waiting on a queue somewhere */
1977 USB_BUS_UNLOCK(xfer->xroot->bus);
1983 if (pq->curr == xfer) {
1984 /* we are currently scheduled for callback */
1985 USB_BUS_UNLOCK(xfer->xroot->bus);
1988 /* we are not pending */
1989 USB_BUS_UNLOCK(xfer->xroot->bus);
1993 /*------------------------------------------------------------------------*
1994 * usbd_transfer_drain
1996 * This function will stop the USB transfer and wait for any
1997 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1998 * are loaded into DMA can safely be freed or reused after that this
1999 * function has returned.
2000 *------------------------------------------------------------------------*/
2002 usbd_transfer_drain(struct usb_xfer *xfer)
2004 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2005 "usbd_transfer_drain can sleep!");
2008 /* transfer is gone */
2011 if (xfer->xroot->xfer_mtx != &Giant) {
2012 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2014 USB_XFER_LOCK(xfer);
2016 usbd_transfer_stop(xfer);
2018 while (usbd_transfer_pending(xfer) ||
2019 xfer->flags_int.doing_callback) {
2022 * It is allowed that the callback can drop its
2023 * transfer mutex. In that case checking only
2024 * "usbd_transfer_pending()" is not enough to tell if
2025 * the USB transfer is fully drained. We also need to
2026 * check the internal "doing_callback" flag.
2028 xfer->flags_int.draining = 1;
2031 * Wait until the current outstanding USB
2032 * transfer is complete !
2034 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2036 USB_XFER_UNLOCK(xfer);
2039 struct usb_page_cache *
2040 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2042 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2044 return (&xfer->frbuffers[frindex]);
2048 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2050 struct usb_page_search page_info;
2052 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2054 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2055 return (page_info.buffer);
2058 /*------------------------------------------------------------------------*
2059 * usbd_xfer_get_fps_shift
2061 * The following function is only useful for isochronous transfers. It
2062 * returns how many times the frame execution rate has been shifted
2068 *------------------------------------------------------------------------*/
2070 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2072 return (xfer->fps_shift);
2076 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2078 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2080 return (xfer->frlengths[frindex]);
2083 /*------------------------------------------------------------------------*
2084 * usbd_xfer_set_frame_data
2086 * This function sets the pointer of the buffer that should
2087 * loaded directly into DMA for the given USB frame. Passing "ptr"
2088 * equal to NULL while the corresponding "frlength" is greater
2089 * than zero gives undefined results!
2090 *------------------------------------------------------------------------*/
2092 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2093 void *ptr, usb_frlength_t len)
2095 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2097 /* set virtual address to load and length */
2098 xfer->frbuffers[frindex].buffer = ptr;
2099 usbd_xfer_set_frame_len(xfer, frindex, len);
2103 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2104 void **ptr, int *len)
2106 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2109 *ptr = xfer->frbuffers[frindex].buffer;
2111 *len = xfer->frlengths[frindex];
2114 /*------------------------------------------------------------------------*
2115 * usbd_xfer_old_frame_length
2117 * This function returns the framelength of the given frame at the
2118 * time the transfer was submitted. This function can be used to
2119 * compute the starting data pointer of the next isochronous frame
2120 * when an isochronous transfer has completed.
2121 *------------------------------------------------------------------------*/
2123 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2125 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2127 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2131 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2135 *actlen = xfer->actlen;
2137 *sumlen = xfer->sumlen;
2138 if (aframes != NULL)
2139 *aframes = xfer->aframes;
2140 if (nframes != NULL)
2141 *nframes = xfer->nframes;
2144 /*------------------------------------------------------------------------*
2145 * usbd_xfer_set_frame_offset
2147 * This function sets the frame data buffer offset relative to the beginning
2148 * of the USB DMA buffer allocated for this USB transfer.
2149 *------------------------------------------------------------------------*/
2151 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2152 usb_frcount_t frindex)
2154 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2155 "when the USB buffer is external\n"));
2156 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2158 /* set virtual address to load */
2159 xfer->frbuffers[frindex].buffer =
2160 USB_ADD_BYTES(xfer->local_buffer, offset);
2164 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2170 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2176 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2182 usbd_xfer_max_frames(struct usb_xfer *xfer)
2184 return (xfer->max_frame_count);
2188 usbd_xfer_max_len(struct usb_xfer *xfer)
2190 return (xfer->max_data_length);
2194 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2196 return (xfer->max_frame_size);
2200 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2203 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2205 xfer->frlengths[frindex] = len;
2208 /*------------------------------------------------------------------------*
2209 * usb_callback_proc - factored out code
2211 * This function performs USB callbacks.
2212 *------------------------------------------------------------------------*/
2214 usb_callback_proc(struct usb_proc_msg *_pm)
2216 struct usb_done_msg *pm = (void *)_pm;
2217 struct usb_xfer_root *info = pm->xroot;
2219 /* Change locking order */
2220 USB_BUS_UNLOCK(info->bus);
2223 * We exploit the fact that the mutex is the same for all
2224 * callbacks that will be called from this thread:
2226 mtx_lock(info->xfer_mtx);
2227 USB_BUS_LOCK(info->bus);
2229 /* Continue where we lost track */
2230 usb_command_wrapper(&info->done_q,
2233 mtx_unlock(info->xfer_mtx);
2236 /*------------------------------------------------------------------------*
2237 * usbd_callback_ss_done_defer
2239 * This function will defer the start, stop and done callback to the
2241 *------------------------------------------------------------------------*/
2243 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2245 struct usb_xfer_root *info = xfer->xroot;
2246 struct usb_xfer_queue *pq = &info->done_q;
2248 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2250 if (pq->curr != xfer) {
2251 usbd_transfer_enqueue(pq, xfer);
2253 if (!pq->recurse_1) {
2256 * We have to postpone the callback due to the fact we
2257 * will have a Lock Order Reversal, LOR, if we try to
2260 if (usb_proc_msignal(info->done_p,
2261 &info->done_m[0], &info->done_m[1])) {
2265 /* clear second recurse flag */
2272 /*------------------------------------------------------------------------*
2273 * usbd_callback_wrapper
2275 * This is a wrapper for USB callbacks. This wrapper does some
2276 * auto-magic things like figuring out if we can call the callback
2277 * directly from the current context or if we need to wakeup the
2278 * interrupt process.
2279 *------------------------------------------------------------------------*/
2281 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2283 struct usb_xfer *xfer = pq->curr;
2284 struct usb_xfer_root *info = xfer->xroot;
2286 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2287 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2289 * Cases that end up here:
2291 * 5) HW interrupt done callback or other source.
2293 DPRINTFN(3, "case 5\n");
2296 * We have to postpone the callback due to the fact we
2297 * will have a Lock Order Reversal, LOR, if we try to
2300 if (usb_proc_msignal(info->done_p,
2301 &info->done_m[0], &info->done_m[1])) {
2307 * Cases that end up here:
2309 * 1) We are starting a transfer
2310 * 2) We are prematurely calling back a transfer
2311 * 3) We are stopping a transfer
2312 * 4) We are doing an ordinary callback
2314 DPRINTFN(3, "case 1-4\n");
2315 /* get next USB transfer in the queue */
2316 info->done_q.curr = NULL;
2318 /* set flag in case of drain */
2319 xfer->flags_int.doing_callback = 1;
2321 USB_BUS_UNLOCK(info->bus);
2322 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2324 /* set correct USB state for callback */
2325 if (!xfer->flags_int.transferring) {
2326 xfer->usb_state = USB_ST_SETUP;
2327 if (!xfer->flags_int.started) {
2328 /* we got stopped before we even got started */
2329 USB_BUS_LOCK(info->bus);
2334 if (usbd_callback_wrapper_sub(xfer)) {
2335 /* the callback has been deferred */
2336 USB_BUS_LOCK(info->bus);
2340 /* decrement power reference */
2341 usbd_transfer_power_ref(xfer, -1);
2343 xfer->flags_int.transferring = 0;
2346 xfer->usb_state = USB_ST_ERROR;
2348 /* set transferred state */
2349 xfer->usb_state = USB_ST_TRANSFERRED;
2351 /* sync DMA memory, if any */
2352 if (xfer->flags_int.bdma_enable &&
2353 (!xfer->flags_int.bdma_no_post_sync)) {
2354 usb_bdma_post_sync(xfer);
2361 if (xfer->usb_state != USB_ST_SETUP)
2362 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2364 /* call processing routine */
2365 (xfer->callback) (xfer, xfer->error);
2367 /* pickup the USB mutex again */
2368 USB_BUS_LOCK(info->bus);
2371 * Check if we got started after that we got cancelled, but
2372 * before we managed to do the callback.
2374 if ((!xfer->flags_int.open) &&
2375 (xfer->flags_int.started) &&
2376 (xfer->usb_state == USB_ST_ERROR)) {
2377 /* clear flag in case of drain */
2378 xfer->flags_int.doing_callback = 0;
2379 /* try to loop, but not recursivly */
2380 usb_command_wrapper(&info->done_q, xfer);
2385 /* clear flag in case of drain */
2386 xfer->flags_int.doing_callback = 0;
2389 * Check if we are draining.
2391 if (xfer->flags_int.draining &&
2392 (!xfer->flags_int.transferring)) {
2393 /* "usbd_transfer_drain()" is waiting for end of transfer */
2394 xfer->flags_int.draining = 0;
2395 cv_broadcast(&info->cv_drain);
2398 /* do the next callback, if any */
2399 usb_command_wrapper(&info->done_q,
2403 /*------------------------------------------------------------------------*
2404 * usb_dma_delay_done_cb
2406 * This function is called when the DMA delay has been exectuded, and
2407 * will make sure that the callback is called to complete the USB
2408 * transfer. This code path is ususally only used when there is an USB
2409 * error like USB_ERR_CANCELLED.
2410 *------------------------------------------------------------------------*/
2412 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2414 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2416 DPRINTFN(3, "Completed %p\n", xfer);
2418 /* queue callback for execution, again */
2419 usbd_transfer_done(xfer, 0);
2422 /*------------------------------------------------------------------------*
2423 * usbd_transfer_dequeue
2425 * - This function is used to remove an USB transfer from a USB
2428 * - This function can be called multiple times in a row.
2429 *------------------------------------------------------------------------*/
2431 usbd_transfer_dequeue(struct usb_xfer *xfer)
2433 struct usb_xfer_queue *pq;
2435 pq = xfer->wait_queue;
2437 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2438 xfer->wait_queue = NULL;
2442 /*------------------------------------------------------------------------*
2443 * usbd_transfer_enqueue
2445 * - This function is used to insert an USB transfer into a USB *
2448 * - This function can be called multiple times in a row.
2449 *------------------------------------------------------------------------*/
2451 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2454 * Insert the USB transfer into the queue, if it is not
2455 * already on a USB transfer queue:
2457 if (xfer->wait_queue == NULL) {
2458 xfer->wait_queue = pq;
2459 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2463 /*------------------------------------------------------------------------*
2464 * usbd_transfer_done
2466 * - This function is used to remove an USB transfer from the busdma,
2467 * pipe or interrupt queue.
2469 * - This function is used to queue the USB transfer on the done
2472 * - This function is used to stop any USB transfer timeouts.
2473 *------------------------------------------------------------------------*/
2475 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2477 struct usb_xfer_root *info = xfer->xroot;
2479 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2481 DPRINTF("err=%s\n", usbd_errstr(error));
2484 * If we are not transferring then just return.
2485 * This can happen during transfer cancel.
2487 if (!xfer->flags_int.transferring) {
2488 DPRINTF("not transferring\n");
2489 /* end of control transfer, if any */
2490 xfer->flags_int.control_act = 0;
2493 /* only set transfer error, if not already set */
2494 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2495 xfer->error = error;
2497 /* stop any callouts */
2498 usb_callout_stop(&xfer->timeout_handle);
2501 * If we are waiting on a queue, just remove the USB transfer
2502 * from the queue, if any. We should have the required locks
2503 * locked to do the remove when this function is called.
2505 usbd_transfer_dequeue(xfer);
2508 if (mtx_owned(info->xfer_mtx)) {
2509 struct usb_xfer_queue *pq;
2512 * If the private USB lock is not locked, then we assume
2513 * that the BUS-DMA load stage has been passed:
2517 if (pq->curr == xfer) {
2518 /* start the next BUS-DMA load, if any */
2519 usb_command_wrapper(pq, NULL);
2523 /* keep some statistics */
2525 info->bus->stats_err.uds_requests
2526 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2528 info->bus->stats_ok.uds_requests
2529 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2532 /* call the USB transfer callback */
2533 usbd_callback_ss_done_defer(xfer);
2536 /*------------------------------------------------------------------------*
2537 * usbd_transfer_start_cb
2539 * This function is called to start the USB transfer when
2540 * "xfer->interval" is greater than zero, and and the endpoint type is
2542 *------------------------------------------------------------------------*/
2544 usbd_transfer_start_cb(void *arg)
2546 struct usb_xfer *xfer = arg;
2547 struct usb_endpoint *ep = xfer->endpoint;
2549 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2554 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2557 /* the transfer can now be cancelled */
2558 xfer->flags_int.can_cancel_immed = 1;
2560 /* start USB transfer, if no error */
2561 if (xfer->error == 0)
2562 (ep->methods->start) (xfer);
2564 /* check for transfer error */
2566 /* some error has happened */
2567 usbd_transfer_done(xfer, 0);
2571 /*------------------------------------------------------------------------*
2572 * usbd_xfer_set_stall
2574 * This function is used to set the stall flag outside the
2575 * callback. This function is NULL safe.
2576 *------------------------------------------------------------------------*/
2578 usbd_xfer_set_stall(struct usb_xfer *xfer)
2584 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2586 /* avoid any races by locking the USB mutex */
2587 USB_BUS_LOCK(xfer->xroot->bus);
2588 xfer->flags.stall_pipe = 1;
2589 USB_BUS_UNLOCK(xfer->xroot->bus);
2593 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2595 return (xfer->endpoint->is_stalled);
2598 /*------------------------------------------------------------------------*
2599 * usbd_transfer_clear_stall
2601 * This function is used to clear the stall flag outside the
2602 * callback. This function is NULL safe.
2603 *------------------------------------------------------------------------*/
2605 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2611 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2613 /* avoid any races by locking the USB mutex */
2614 USB_BUS_LOCK(xfer->xroot->bus);
2616 xfer->flags.stall_pipe = 0;
2618 USB_BUS_UNLOCK(xfer->xroot->bus);
2621 /*------------------------------------------------------------------------*
2624 * This function is used to add an USB transfer to the pipe transfer list.
2625 *------------------------------------------------------------------------*/
2627 usbd_pipe_start(struct usb_xfer_queue *pq)
2629 struct usb_endpoint *ep;
2630 struct usb_xfer *xfer;
2634 ep = xfer->endpoint;
2636 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2639 * If the endpoint is already stalled we do nothing !
2641 if (ep->is_stalled) {
2645 * Check if we are supposed to stall the endpoint:
2647 if (xfer->flags.stall_pipe) {
2648 struct usb_device *udev;
2649 struct usb_xfer_root *info;
2651 /* clear stall command */
2652 xfer->flags.stall_pipe = 0;
2654 /* get pointer to USB device */
2659 * Only stall BULK and INTERRUPT endpoints.
2661 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2662 if ((type == UE_BULK) ||
2663 (type == UE_INTERRUPT)) {
2668 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2669 (udev->bus->methods->set_stall) (
2670 udev, ep, &did_stall);
2671 } else if (udev->ctrl_xfer[1]) {
2672 info = udev->ctrl_xfer[1]->xroot;
2674 USB_BUS_NON_GIANT_PROC(info->bus),
2675 &udev->cs_msg[0], &udev->cs_msg[1]);
2677 /* should not happen */
2678 DPRINTFN(0, "No stall handler\n");
2681 * Check if we should stall. Some USB hardware
2682 * handles set- and clear-stall in hardware.
2686 * The transfer will be continued when
2687 * the clear-stall control endpoint
2688 * message is received.
2693 } else if (type == UE_ISOCHRONOUS) {
2696 * Make sure any FIFO overflow or other FIFO
2697 * error conditions go away by resetting the
2698 * endpoint FIFO through the clear stall
2701 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2702 (udev->bus->methods->clear_stall) (udev, ep);
2706 /* Set or clear stall complete - special case */
2707 if (xfer->nframes == 0) {
2708 /* we are complete */
2710 usbd_transfer_done(xfer, 0);
2716 * 1) Start the first transfer queued.
2718 * 2) Re-start the current USB transfer.
2721 * Check if there should be any
2722 * pre transfer start delay:
2724 if (xfer->interval > 0) {
2725 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2726 if ((type == UE_BULK) ||
2727 (type == UE_CONTROL)) {
2728 usbd_transfer_timeout_ms(xfer,
2729 &usbd_transfer_start_cb,
2737 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2739 /* the transfer can now be cancelled */
2740 xfer->flags_int.can_cancel_immed = 1;
2742 /* start USB transfer, if no error */
2743 if (xfer->error == 0)
2744 (ep->methods->start) (xfer);
2746 /* check for transfer error */
2748 /* some error has happened */
2749 usbd_transfer_done(xfer, 0);
2753 /*------------------------------------------------------------------------*
2754 * usbd_transfer_timeout_ms
2756 * This function is used to setup a timeout on the given USB
2757 * transfer. If the timeout has been deferred the callback given by
2758 * "cb" will get called after "ms" milliseconds.
2759 *------------------------------------------------------------------------*/
2761 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2762 void (*cb) (void *arg), usb_timeout_t ms)
2764 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2767 usb_callout_reset(&xfer->timeout_handle,
2768 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2771 /*------------------------------------------------------------------------*
2772 * usbd_callback_wrapper_sub
2774 * - This function will update variables in an USB transfer after
2775 * that the USB transfer is complete.
2777 * - This function is used to start the next USB transfer on the
2778 * ep transfer queue, if any.
2780 * NOTE: In some special cases the USB transfer will not be removed from
2781 * the pipe queue, but remain first. To enforce USB transfer removal call
2782 * this function passing the error code "USB_ERR_CANCELLED".
2786 * Else: The callback has been deferred.
2787 *------------------------------------------------------------------------*/
2789 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2791 struct usb_endpoint *ep;
2792 struct usb_bus *bus;
2795 bus = xfer->xroot->bus;
2797 if ((!xfer->flags_int.open) &&
2798 (!xfer->flags_int.did_close)) {
2801 (xfer->endpoint->methods->close) (xfer);
2802 USB_BUS_UNLOCK(bus);
2803 /* only close once */
2804 xfer->flags_int.did_close = 1;
2805 return (1); /* wait for new callback */
2808 * If we have a non-hardware induced error we
2809 * need to do the DMA delay!
2811 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2812 (xfer->error == USB_ERR_CANCELLED ||
2813 xfer->error == USB_ERR_TIMEOUT ||
2814 bus->methods->start_dma_delay != NULL)) {
2818 /* only delay once */
2819 xfer->flags_int.did_dma_delay = 1;
2821 /* we can not cancel this delay */
2822 xfer->flags_int.can_cancel_immed = 0;
2824 temp = usbd_get_dma_delay(xfer->xroot->udev);
2826 DPRINTFN(3, "DMA delay, %u ms, "
2827 "on %p\n", temp, xfer);
2832 * Some hardware solutions have dedicated
2833 * events when it is safe to free DMA'ed
2834 * memory. For the other hardware platforms we
2835 * use a static delay.
2837 if (bus->methods->start_dma_delay != NULL) {
2838 (bus->methods->start_dma_delay) (xfer);
2840 usbd_transfer_timeout_ms(xfer,
2841 (void (*)(void *))&usb_dma_delay_done_cb,
2844 USB_BUS_UNLOCK(bus);
2845 return (1); /* wait for new callback */
2848 /* check actual number of frames */
2849 if (xfer->aframes > xfer->nframes) {
2850 if (xfer->error == 0) {
2851 panic("%s: actual number of frames, %d, is "
2852 "greater than initial number of frames, %d\n",
2853 __FUNCTION__, xfer->aframes, xfer->nframes);
2855 /* just set some valid value */
2856 xfer->aframes = xfer->nframes;
2859 /* compute actual length */
2862 for (x = 0; x != xfer->aframes; x++) {
2863 xfer->actlen += xfer->frlengths[x];
2867 * Frames that were not transferred get zero actual length in
2868 * case the USB device driver does not check the actual number
2869 * of frames transferred, "xfer->aframes":
2871 for (; x < xfer->nframes; x++) {
2872 usbd_xfer_set_frame_len(xfer, x, 0);
2875 /* check actual length */
2876 if (xfer->actlen > xfer->sumlen) {
2877 if (xfer->error == 0) {
2878 panic("%s: actual length, %d, is greater than "
2879 "initial length, %d\n",
2880 __FUNCTION__, xfer->actlen, xfer->sumlen);
2882 /* just set some valid value */
2883 xfer->actlen = xfer->sumlen;
2886 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2887 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2888 xfer->aframes, xfer->nframes);
2891 /* end of control transfer, if any */
2892 xfer->flags_int.control_act = 0;
2894 #if USB_HAVE_TT_SUPPORT
2895 switch (xfer->error) {
2896 case USB_ERR_NORMAL_COMPLETION:
2897 case USB_ERR_SHORT_XFER:
2898 case USB_ERR_STALLED:
2899 case USB_ERR_CANCELLED:
2903 /* try to reset the TT, if any */
2905 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2906 USB_BUS_UNLOCK(bus);
2910 /* check if we should block the execution queue */
2911 if ((xfer->error != USB_ERR_CANCELLED) &&
2912 (xfer->flags.pipe_bof)) {
2913 DPRINTFN(2, "xfer=%p: Block On Failure "
2914 "on endpoint=%p\n", xfer, xfer->endpoint);
2918 /* check for short transfers */
2919 if (xfer->actlen < xfer->sumlen) {
2921 /* end of control transfer, if any */
2922 xfer->flags_int.control_act = 0;
2924 if (!xfer->flags_int.short_xfer_ok) {
2925 xfer->error = USB_ERR_SHORT_XFER;
2926 if (xfer->flags.pipe_bof) {
2927 DPRINTFN(2, "xfer=%p: Block On Failure on "
2928 "Short Transfer on endpoint %p.\n",
2929 xfer, xfer->endpoint);
2935 * Check if we are in the middle of a
2938 if (xfer->flags_int.control_act) {
2939 DPRINTFN(5, "xfer=%p: Control transfer "
2940 "active on endpoint=%p\n", xfer, xfer->endpoint);
2946 ep = xfer->endpoint;
2949 * If the current USB transfer is completing we need to start the
2953 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2954 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
2956 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
2957 TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
2958 /* there is another USB transfer waiting */
2960 /* this is the last USB transfer */
2961 /* clear isochronous sync flag */
2962 xfer->endpoint->is_synced = 0;
2965 USB_BUS_UNLOCK(bus);
2970 /*------------------------------------------------------------------------*
2971 * usb_command_wrapper
2973 * This function is used to execute commands non-recursivly on an USB
2975 *------------------------------------------------------------------------*/
2977 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2981 * If the transfer is not already processing,
2984 if (pq->curr != xfer) {
2985 usbd_transfer_enqueue(pq, xfer);
2986 if (pq->curr != NULL) {
2987 /* something is already processing */
2988 DPRINTFN(6, "busy %p\n", pq->curr);
2993 /* Get next element in queue */
2997 if (!pq->recurse_1) {
3001 /* set both recurse flags */
3005 if (pq->curr == NULL) {
3006 xfer = TAILQ_FIRST(&pq->head);
3008 TAILQ_REMOVE(&pq->head, xfer,
3010 xfer->wait_queue = NULL;
3016 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3018 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3020 } while (!pq->recurse_2);
3022 /* clear first recurse flag */
3026 /* clear second recurse flag */
3031 /*------------------------------------------------------------------------*
3032 * usbd_ctrl_transfer_setup
3034 * This function is used to setup the default USB control endpoint
3036 *------------------------------------------------------------------------*/
3038 usbd_ctrl_transfer_setup(struct usb_device *udev)
3040 struct usb_xfer *xfer;
3042 uint8_t iface_index;
3044 /* check for root HUB */
3045 if (udev->parent_hub == NULL)
3049 xfer = udev->ctrl_xfer[0];
3051 USB_XFER_LOCK(xfer);
3053 ((xfer->address == udev->address) &&
3054 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3055 udev->ddesc.bMaxPacketSize));
3056 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3059 * NOTE: checking "xfer->address" and
3060 * starting the USB transfer must be
3063 usbd_transfer_start(xfer);
3066 USB_XFER_UNLOCK(xfer);
3073 * All parameters are exactly the same like before.
3079 * Update wMaxPacketSize for the default control endpoint:
3081 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3082 udev->ddesc.bMaxPacketSize;
3085 * Unsetup any existing USB transfer:
3087 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3090 * Reset clear stall error counter.
3092 udev->clear_stall_errors = 0;
3095 * Try to setup a new USB transfer for the
3096 * default control endpoint:
3099 if (usbd_transfer_setup(udev, &iface_index,
3100 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3101 &udev->device_mtx)) {
3102 DPRINTFN(0, "could not setup default "
3109 /*------------------------------------------------------------------------*
3110 * usbd_clear_data_toggle - factored out code
3112 * NOTE: the intention of this function is not to reset the hardware
3114 *------------------------------------------------------------------------*/
3116 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3118 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3120 /* check that we have a valid case */
3121 if (udev->flags.usb_mode == USB_MODE_HOST &&
3122 udev->parent_hub != NULL &&
3123 udev->bus->methods->clear_stall != NULL &&
3124 ep->methods != NULL) {
3125 (udev->bus->methods->clear_stall) (udev, ep);
3129 /*------------------------------------------------------------------------*
3130 * usbd_clear_data_toggle - factored out code
3132 * NOTE: the intention of this function is not to reset the hardware
3133 * data toggle on the USB device side.
3134 *------------------------------------------------------------------------*/
3136 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3138 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3140 USB_BUS_LOCK(udev->bus);
3141 ep->toggle_next = 0;
3142 /* some hardware needs a callback to clear the data toggle */
3143 usbd_clear_stall_locked(udev, ep);
3144 USB_BUS_UNLOCK(udev->bus);
3147 /*------------------------------------------------------------------------*
3148 * usbd_clear_stall_callback - factored out clear stall callback
3151 * xfer1: Clear Stall Control Transfer
3152 * xfer2: Stalled USB Transfer
3154 * This function is NULL safe.
3160 * Clear stall config example:
3162 * static const struct usb_config my_clearstall = {
3163 * .type = UE_CONTROL,
3165 * .direction = UE_DIR_ANY,
3166 * .interval = 50, //50 milliseconds
3167 * .bufsize = sizeof(struct usb_device_request),
3168 * .timeout = 1000, //1.000 seconds
3169 * .callback = &my_clear_stall_callback, // **
3170 * .usb_mode = USB_MODE_HOST,
3173 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3174 * passing the correct parameters.
3175 *------------------------------------------------------------------------*/
3177 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3178 struct usb_xfer *xfer2)
3180 struct usb_device_request req;
3182 if (xfer2 == NULL) {
3183 /* looks like we are tearing down */
3184 DPRINTF("NULL input parameter\n");
3187 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3188 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3190 switch (USB_GET_STATE(xfer1)) {
3194 * pre-clear the data toggle to DATA0 ("umass.c" and
3195 * "ata-usb.c" depends on this)
3198 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3200 /* setup a clear-stall packet */
3202 req.bmRequestType = UT_WRITE_ENDPOINT;
3203 req.bRequest = UR_CLEAR_FEATURE;
3204 USETW(req.wValue, UF_ENDPOINT_HALT);
3205 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3207 USETW(req.wLength, 0);
3210 * "usbd_transfer_setup_sub()" will ensure that
3211 * we have sufficient room in the buffer for
3212 * the request structure!
3215 /* copy in the transfer */
3217 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3220 xfer1->frlengths[0] = sizeof(req);
3223 usbd_transfer_submit(xfer1);
3226 case USB_ST_TRANSFERRED:
3229 default: /* Error */
3230 if (xfer1->error == USB_ERR_CANCELLED) {
3235 return (1); /* Clear Stall Finished */
3238 /*------------------------------------------------------------------------*
3239 * usbd_transfer_poll
3241 * The following function gets called from the USB keyboard driver and
3242 * UMASS when the system has paniced.
3244 * NOTE: It is currently not possible to resume normal operation on
3245 * the USB controller which has been polled, due to clearing of the
3246 * "up_dsleep" and "up_msleep" flags.
3247 *------------------------------------------------------------------------*/
3249 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3251 struct usb_xfer *xfer;
3252 struct usb_xfer_root *xroot;
3253 struct usb_device *udev;
3254 struct usb_proc_msg *pm;
3259 for (n = 0; n != max; n++) {
3260 /* Extra checks to avoid panic */
3263 continue; /* no USB transfer */
3264 xroot = xfer->xroot;
3266 continue; /* no USB root */
3269 continue; /* no USB device */
3270 if (udev->bus == NULL)
3271 continue; /* no BUS structure */
3272 if (udev->bus->methods == NULL)
3273 continue; /* no BUS methods */
3274 if (udev->bus->methods->xfer_poll == NULL)
3275 continue; /* no poll method */
3277 /* make sure that the BUS mutex is not locked */
3279 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3280 mtx_unlock(&xroot->udev->bus->bus_mtx);
3284 /* make sure that the transfer mutex is not locked */
3286 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3287 mtx_unlock(xroot->xfer_mtx);
3291 /* Make sure cv_signal() and cv_broadcast() is not called */
3292 USB_BUS_CONTROL_XFER_PROC(udev->bus)->up_msleep = 0;
3293 USB_BUS_EXPLORE_PROC(udev->bus)->up_msleep = 0;
3294 USB_BUS_GIANT_PROC(udev->bus)->up_msleep = 0;
3295 USB_BUS_NON_GIANT_PROC(udev->bus)->up_msleep = 0;
3297 /* poll USB hardware */
3298 (udev->bus->methods->xfer_poll) (udev->bus);
3300 USB_BUS_LOCK(xroot->bus);
3302 /* check for clear stall */
3303 if (udev->ctrl_xfer[1] != NULL) {
3305 /* poll clear stall start */
3306 pm = &udev->cs_msg[0].hdr;
3307 (pm->pm_callback) (pm);
3308 /* poll clear stall done thread */
3309 pm = &udev->ctrl_xfer[1]->
3310 xroot->done_m[0].hdr;
3311 (pm->pm_callback) (pm);
3314 /* poll done thread */
3315 pm = &xroot->done_m[0].hdr;
3316 (pm->pm_callback) (pm);
3318 USB_BUS_UNLOCK(xroot->bus);
3320 /* restore transfer mutex */
3322 mtx_lock(xroot->xfer_mtx);
3324 /* restore BUS mutex */
3326 mtx_lock(&xroot->udev->bus->bus_mtx);
3331 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3332 uint8_t type, enum usb_dev_speed speed)
3334 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3335 [USB_SPEED_LOW] = 8,
3336 [USB_SPEED_FULL] = 64,
3337 [USB_SPEED_HIGH] = 1024,
3338 [USB_SPEED_VARIABLE] = 1024,
3339 [USB_SPEED_SUPER] = 1024,
3342 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3343 [USB_SPEED_LOW] = 0, /* invalid */
3344 [USB_SPEED_FULL] = 1023,
3345 [USB_SPEED_HIGH] = 1024,
3346 [USB_SPEED_VARIABLE] = 3584,
3347 [USB_SPEED_SUPER] = 1024,
3350 static const uint16_t control_min[USB_SPEED_MAX] = {
3351 [USB_SPEED_LOW] = 8,
3352 [USB_SPEED_FULL] = 8,
3353 [USB_SPEED_HIGH] = 64,
3354 [USB_SPEED_VARIABLE] = 512,
3355 [USB_SPEED_SUPER] = 512,
3358 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3359 [USB_SPEED_LOW] = 8,
3360 [USB_SPEED_FULL] = 8,
3361 [USB_SPEED_HIGH] = 512,
3362 [USB_SPEED_VARIABLE] = 512,
3363 [USB_SPEED_SUPER] = 1024,
3368 memset(ptr, 0, sizeof(*ptr));
3372 ptr->range.max = intr_range_max[speed];
3374 case UE_ISOCHRONOUS:
3375 ptr->range.max = isoc_range_max[speed];
3378 if (type == UE_BULK)
3379 temp = bulk_min[speed];
3380 else /* UE_CONTROL */
3381 temp = control_min[speed];
3383 /* default is fixed */
3384 ptr->fixed[0] = temp;
3385 ptr->fixed[1] = temp;
3386 ptr->fixed[2] = temp;
3387 ptr->fixed[3] = temp;
3389 if (speed == USB_SPEED_FULL) {
3390 /* multiple sizes */
3395 if ((speed == USB_SPEED_VARIABLE) &&
3396 (type == UE_BULK)) {
3397 /* multiple sizes */
3398 ptr->fixed[2] = 1024;
3399 ptr->fixed[3] = 1536;
3406 usbd_xfer_softc(struct usb_xfer *xfer)
3408 return (xfer->priv_sc);
3412 usbd_xfer_get_priv(struct usb_xfer *xfer)
3414 return (xfer->priv_fifo);
3418 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3420 xfer->priv_fifo = ptr;
3424 usbd_xfer_state(struct usb_xfer *xfer)
3426 return (xfer->usb_state);
3430 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3433 case USB_FORCE_SHORT_XFER:
3434 xfer->flags.force_short_xfer = 1;
3436 case USB_SHORT_XFER_OK:
3437 xfer->flags.short_xfer_ok = 1;
3439 case USB_MULTI_SHORT_OK:
3440 xfer->flags.short_frames_ok = 1;
3442 case USB_MANUAL_STATUS:
3443 xfer->flags.manual_status = 1;
3449 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3452 case USB_FORCE_SHORT_XFER:
3453 xfer->flags.force_short_xfer = 0;
3455 case USB_SHORT_XFER_OK:
3456 xfer->flags.short_xfer_ok = 0;
3458 case USB_MULTI_SHORT_OK:
3459 xfer->flags.short_frames_ok = 0;
3461 case USB_MANUAL_STATUS:
3462 xfer->flags.manual_status = 0;
3468 * The following function returns in milliseconds when the isochronous
3469 * transfer was completed by the hardware. The returned value wraps
3470 * around 65536 milliseconds.
3473 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3475 return (xfer->isoc_time_complete);
3479 * The following function returns non-zero if the max packet size
3480 * field was clamped to a valid value. Else it returns zero.
3483 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3485 return (xfer->flags_int.maxp_was_clamped);