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_setup_ctrl_transfer
1414 * This function handles initialisation of control transfers. Control
1415 * transfers are special in that regard that they can both transmit
1421 *------------------------------------------------------------------------*/
1423 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1427 /* Check for control endpoint stall */
1428 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1429 /* the control transfer is no longer active */
1430 xfer->flags_int.control_stall = 1;
1431 xfer->flags_int.control_act = 0;
1433 /* don't stall control transfer by default */
1434 xfer->flags_int.control_stall = 0;
1437 /* Check for invalid number of frames */
1438 if (xfer->nframes > 2) {
1440 * If you need to split a control transfer, you
1441 * have to do one part at a time. Only with
1442 * non-control transfers you can do multiple
1445 DPRINTFN(0, "Too many frames: %u\n",
1446 (unsigned int)xfer->nframes);
1451 * Check if there is a control
1452 * transfer in progress:
1454 if (xfer->flags_int.control_act) {
1456 if (xfer->flags_int.control_hdr) {
1458 /* clear send header flag */
1460 xfer->flags_int.control_hdr = 0;
1462 /* setup control transfer */
1463 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1464 usbd_control_transfer_init(xfer);
1467 /* get data length */
1473 /* the size of the SETUP structure is hardcoded ! */
1475 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1476 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1477 xfer->frlengths[0], sizeof(struct
1478 usb_device_request));
1481 /* check USB mode */
1482 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1484 /* check number of frames */
1485 if (xfer->nframes != 1) {
1487 * We need to receive the setup
1488 * message first so that we know the
1491 DPRINTF("Misconfigured transfer\n");
1495 * Set a dummy "control_rem" value. This
1496 * variable will be overwritten later by a
1497 * call to "usbd_control_transfer_init()" !
1499 xfer->flags_int.control_rem = 0xFFFF;
1502 /* setup "endpoint" and "control_rem" */
1504 usbd_control_transfer_init(xfer);
1507 /* set transfer-header flag */
1509 xfer->flags_int.control_hdr = 1;
1511 /* get data length */
1513 len = (xfer->sumlen - sizeof(struct usb_device_request));
1516 /* check if there is a length mismatch */
1518 if (len > xfer->flags_int.control_rem) {
1519 DPRINTFN(0, "Length (%d) greater than "
1520 "remaining length (%d)\n", len,
1521 xfer->flags_int.control_rem);
1524 /* check if we are doing a short transfer */
1526 if (xfer->flags.force_short_xfer) {
1527 xfer->flags_int.control_rem = 0;
1529 if ((len != xfer->max_data_length) &&
1530 (len != xfer->flags_int.control_rem) &&
1531 (xfer->nframes != 1)) {
1532 DPRINTFN(0, "Short control transfer without "
1533 "force_short_xfer set\n");
1536 xfer->flags_int.control_rem -= len;
1539 /* the status part is executed when "control_act" is 0 */
1541 if ((xfer->flags_int.control_rem > 0) ||
1542 (xfer->flags.manual_status)) {
1543 /* don't execute the STATUS stage yet */
1544 xfer->flags_int.control_act = 1;
1547 if ((!xfer->flags_int.control_hdr) &&
1548 (xfer->nframes == 1)) {
1550 * This is not a valid operation!
1552 DPRINTFN(0, "Invalid parameter "
1557 /* time to execute the STATUS stage */
1558 xfer->flags_int.control_act = 0;
1560 return (0); /* success */
1563 return (1); /* failure */
1566 /*------------------------------------------------------------------------*
1567 * usbd_transfer_submit - start USB hardware for the given transfer
1569 * This function should only be called from the USB callback.
1570 *------------------------------------------------------------------------*/
1572 usbd_transfer_submit(struct usb_xfer *xfer)
1574 struct usb_xfer_root *info;
1575 struct usb_bus *bus;
1581 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1582 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1586 if (USB_DEBUG_VAR > 0) {
1589 usb_dump_endpoint(xfer->endpoint);
1591 USB_BUS_UNLOCK(bus);
1595 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1596 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1598 /* Only open the USB transfer once! */
1599 if (!xfer->flags_int.open) {
1600 xfer->flags_int.open = 1;
1605 (xfer->endpoint->methods->open) (xfer);
1606 USB_BUS_UNLOCK(bus);
1608 /* set "transferring" flag */
1609 xfer->flags_int.transferring = 1;
1612 /* increment power reference */
1613 usbd_transfer_power_ref(xfer, 1);
1616 * Check if the transfer is waiting on a queue, most
1617 * frequently the "done_q":
1619 if (xfer->wait_queue) {
1621 usbd_transfer_dequeue(xfer);
1622 USB_BUS_UNLOCK(bus);
1624 /* clear "did_dma_delay" flag */
1625 xfer->flags_int.did_dma_delay = 0;
1627 /* clear "did_close" flag */
1628 xfer->flags_int.did_close = 0;
1631 /* clear "bdma_setup" flag */
1632 xfer->flags_int.bdma_setup = 0;
1634 /* by default we cannot cancel any USB transfer immediately */
1635 xfer->flags_int.can_cancel_immed = 0;
1637 /* clear lengths and frame counts by default */
1642 /* clear any previous errors */
1645 /* Check if the device is still alive */
1646 if (info->udev->state < USB_STATE_POWERED) {
1649 * Must return cancelled error code else
1650 * device drivers can hang.
1652 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1653 USB_BUS_UNLOCK(bus);
1658 if (xfer->nframes == 0) {
1659 if (xfer->flags.stall_pipe) {
1661 * Special case - want to stall without transferring
1664 DPRINTF("xfer=%p nframes=0: stall "
1665 "or clear stall!\n", xfer);
1667 xfer->flags_int.can_cancel_immed = 1;
1668 /* start the transfer */
1669 usb_command_wrapper(&xfer->endpoint->
1670 endpoint_q[xfer->stream_id], xfer);
1671 USB_BUS_UNLOCK(bus);
1675 usbd_transfer_done(xfer, USB_ERR_INVAL);
1676 USB_BUS_UNLOCK(bus);
1679 /* compute some variables */
1681 for (x = 0; x != xfer->nframes; x++) {
1682 /* make a copy of the frlenghts[] */
1683 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1684 /* compute total transfer length */
1685 xfer->sumlen += xfer->frlengths[x];
1686 if (xfer->sumlen < xfer->frlengths[x]) {
1687 /* length wrapped around */
1689 usbd_transfer_done(xfer, USB_ERR_INVAL);
1690 USB_BUS_UNLOCK(bus);
1695 /* clear some internal flags */
1697 xfer->flags_int.short_xfer_ok = 0;
1698 xfer->flags_int.short_frames_ok = 0;
1700 /* check if this is a control transfer */
1702 if (xfer->flags_int.control_xfr) {
1704 if (usbd_setup_ctrl_transfer(xfer)) {
1706 usbd_transfer_done(xfer, USB_ERR_STALLED);
1707 USB_BUS_UNLOCK(bus);
1712 * Setup filtered version of some transfer flags,
1713 * in case of data read direction
1715 if (USB_GET_DATA_ISREAD(xfer)) {
1717 if (xfer->flags.short_frames_ok) {
1718 xfer->flags_int.short_xfer_ok = 1;
1719 xfer->flags_int.short_frames_ok = 1;
1720 } else if (xfer->flags.short_xfer_ok) {
1721 xfer->flags_int.short_xfer_ok = 1;
1723 /* check for control transfer */
1724 if (xfer->flags_int.control_xfr) {
1726 * 1) Control transfers do not support
1727 * reception of multiple short USB
1728 * frames in host mode and device side
1729 * mode, with exception of:
1731 * 2) Due to sometimes buggy device
1732 * side firmware we need to do a
1733 * STATUS stage in case of short
1734 * control transfers in USB host mode.
1735 * The STATUS stage then becomes the
1736 * "alt_next" to the DATA stage.
1738 xfer->flags_int.short_frames_ok = 1;
1743 * Check if BUS-DMA support is enabled and try to load virtual
1744 * buffers into DMA, if any:
1747 if (xfer->flags_int.bdma_enable) {
1748 /* insert the USB transfer last in the BUS-DMA queue */
1749 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1754 * Enter the USB transfer into the Host Controller or
1755 * Device Controller schedule:
1757 usbd_pipe_enter(xfer);
1760 /*------------------------------------------------------------------------*
1761 * usbd_pipe_enter - factored out code
1762 *------------------------------------------------------------------------*/
1764 usbd_pipe_enter(struct usb_xfer *xfer)
1766 struct usb_endpoint *ep;
1768 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1770 USB_BUS_LOCK(xfer->xroot->bus);
1772 ep = xfer->endpoint;
1776 /* the transfer can now be cancelled */
1777 xfer->flags_int.can_cancel_immed = 1;
1779 /* enter the transfer */
1780 (ep->methods->enter) (xfer);
1782 /* check for transfer error */
1784 /* some error has happened */
1785 usbd_transfer_done(xfer, 0);
1786 USB_BUS_UNLOCK(xfer->xroot->bus);
1790 /* start the transfer */
1791 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1792 USB_BUS_UNLOCK(xfer->xroot->bus);
1795 /*------------------------------------------------------------------------*
1796 * usbd_transfer_start - start an USB transfer
1798 * NOTE: Calling this function more than one time will only
1799 * result in a single transfer start, until the USB transfer
1801 *------------------------------------------------------------------------*/
1803 usbd_transfer_start(struct usb_xfer *xfer)
1806 /* transfer is gone */
1809 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1811 /* mark the USB transfer started */
1813 if (!xfer->flags_int.started) {
1814 /* lock the BUS lock to avoid races updating flags_int */
1815 USB_BUS_LOCK(xfer->xroot->bus);
1816 xfer->flags_int.started = 1;
1817 USB_BUS_UNLOCK(xfer->xroot->bus);
1819 /* check if the USB transfer callback is already transferring */
1821 if (xfer->flags_int.transferring) {
1824 USB_BUS_LOCK(xfer->xroot->bus);
1825 /* call the USB transfer callback */
1826 usbd_callback_ss_done_defer(xfer);
1827 USB_BUS_UNLOCK(xfer->xroot->bus);
1830 /*------------------------------------------------------------------------*
1831 * usbd_transfer_stop - stop an USB transfer
1833 * NOTE: Calling this function more than one time will only
1834 * result in a single transfer stop.
1835 * NOTE: When this function returns it is not safe to free nor
1836 * reuse any DMA buffers. See "usbd_transfer_drain()".
1837 *------------------------------------------------------------------------*/
1839 usbd_transfer_stop(struct usb_xfer *xfer)
1841 struct usb_endpoint *ep;
1844 /* transfer is gone */
1847 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1849 /* check if the USB transfer was ever opened */
1851 if (!xfer->flags_int.open) {
1852 if (xfer->flags_int.started) {
1853 /* nothing to do except clearing the "started" flag */
1854 /* lock the BUS lock to avoid races updating flags_int */
1855 USB_BUS_LOCK(xfer->xroot->bus);
1856 xfer->flags_int.started = 0;
1857 USB_BUS_UNLOCK(xfer->xroot->bus);
1861 /* try to stop the current USB transfer */
1863 USB_BUS_LOCK(xfer->xroot->bus);
1864 /* override any previous error */
1865 xfer->error = USB_ERR_CANCELLED;
1868 * Clear "open" and "started" when both private and USB lock
1869 * is locked so that we don't get a race updating "flags_int"
1871 xfer->flags_int.open = 0;
1872 xfer->flags_int.started = 0;
1875 * Check if we can cancel the USB transfer immediately.
1877 if (xfer->flags_int.transferring) {
1878 if (xfer->flags_int.can_cancel_immed &&
1879 (!xfer->flags_int.did_close)) {
1882 * The following will lead to an USB_ERR_CANCELLED
1883 * error code being passed to the USB callback.
1885 (xfer->endpoint->methods->close) (xfer);
1886 /* only close once */
1887 xfer->flags_int.did_close = 1;
1889 /* need to wait for the next done callback */
1894 /* close here and now */
1895 (xfer->endpoint->methods->close) (xfer);
1898 * Any additional DMA delay is done by
1899 * "usbd_transfer_unsetup()".
1903 * Special case. Check if we need to restart a blocked
1906 ep = xfer->endpoint;
1909 * If the current USB transfer is completing we need
1910 * to start the next one:
1912 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
1913 usb_command_wrapper(
1914 &ep->endpoint_q[xfer->stream_id], NULL);
1918 USB_BUS_UNLOCK(xfer->xroot->bus);
1921 /*------------------------------------------------------------------------*
1922 * usbd_transfer_pending
1924 * This function will check if an USB transfer is pending which is a
1925 * little bit complicated!
1928 * 1: Pending: The USB transfer will receive a callback in the future.
1929 *------------------------------------------------------------------------*/
1931 usbd_transfer_pending(struct usb_xfer *xfer)
1933 struct usb_xfer_root *info;
1934 struct usb_xfer_queue *pq;
1937 /* transfer is gone */
1940 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1942 if (xfer->flags_int.transferring) {
1946 USB_BUS_LOCK(xfer->xroot->bus);
1947 if (xfer->wait_queue) {
1948 /* we are waiting on a queue somewhere */
1949 USB_BUS_UNLOCK(xfer->xroot->bus);
1955 if (pq->curr == xfer) {
1956 /* we are currently scheduled for callback */
1957 USB_BUS_UNLOCK(xfer->xroot->bus);
1960 /* we are not pending */
1961 USB_BUS_UNLOCK(xfer->xroot->bus);
1965 /*------------------------------------------------------------------------*
1966 * usbd_transfer_drain
1968 * This function will stop the USB transfer and wait for any
1969 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1970 * are loaded into DMA can safely be freed or reused after that this
1971 * function has returned.
1972 *------------------------------------------------------------------------*/
1974 usbd_transfer_drain(struct usb_xfer *xfer)
1976 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1977 "usbd_transfer_drain can sleep!");
1980 /* transfer is gone */
1983 if (xfer->xroot->xfer_mtx != &Giant) {
1984 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1986 USB_XFER_LOCK(xfer);
1988 usbd_transfer_stop(xfer);
1990 while (usbd_transfer_pending(xfer) ||
1991 xfer->flags_int.doing_callback) {
1994 * It is allowed that the callback can drop its
1995 * transfer mutex. In that case checking only
1996 * "usbd_transfer_pending()" is not enough to tell if
1997 * the USB transfer is fully drained. We also need to
1998 * check the internal "doing_callback" flag.
2000 xfer->flags_int.draining = 1;
2003 * Wait until the current outstanding USB
2004 * transfer is complete !
2006 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2008 USB_XFER_UNLOCK(xfer);
2011 struct usb_page_cache *
2012 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2014 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2016 return (&xfer->frbuffers[frindex]);
2020 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2022 struct usb_page_search page_info;
2024 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2026 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2027 return (page_info.buffer);
2030 /*------------------------------------------------------------------------*
2031 * usbd_xfer_get_fps_shift
2033 * The following function is only useful for isochronous transfers. It
2034 * returns how many times the frame execution rate has been shifted
2040 *------------------------------------------------------------------------*/
2042 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2044 return (xfer->fps_shift);
2048 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2050 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2052 return (xfer->frlengths[frindex]);
2055 /*------------------------------------------------------------------------*
2056 * usbd_xfer_set_frame_data
2058 * This function sets the pointer of the buffer that should
2059 * loaded directly into DMA for the given USB frame. Passing "ptr"
2060 * equal to NULL while the corresponding "frlength" is greater
2061 * than zero gives undefined results!
2062 *------------------------------------------------------------------------*/
2064 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2065 void *ptr, usb_frlength_t len)
2067 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2069 /* set virtual address to load and length */
2070 xfer->frbuffers[frindex].buffer = ptr;
2071 usbd_xfer_set_frame_len(xfer, frindex, len);
2075 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2076 void **ptr, int *len)
2078 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2081 *ptr = xfer->frbuffers[frindex].buffer;
2083 *len = xfer->frlengths[frindex];
2086 /*------------------------------------------------------------------------*
2087 * usbd_xfer_old_frame_length
2089 * This function returns the framelength of the given frame at the
2090 * time the transfer was submitted. This function can be used to
2091 * compute the starting data pointer of the next isochronous frame
2092 * when an isochronous transfer has completed.
2093 *------------------------------------------------------------------------*/
2095 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2097 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2099 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2103 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2107 *actlen = xfer->actlen;
2109 *sumlen = xfer->sumlen;
2110 if (aframes != NULL)
2111 *aframes = xfer->aframes;
2112 if (nframes != NULL)
2113 *nframes = xfer->nframes;
2116 /*------------------------------------------------------------------------*
2117 * usbd_xfer_set_frame_offset
2119 * This function sets the frame data buffer offset relative to the beginning
2120 * of the USB DMA buffer allocated for this USB transfer.
2121 *------------------------------------------------------------------------*/
2123 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2124 usb_frcount_t frindex)
2126 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2127 "when the USB buffer is external\n"));
2128 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2130 /* set virtual address to load */
2131 xfer->frbuffers[frindex].buffer =
2132 USB_ADD_BYTES(xfer->local_buffer, offset);
2136 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2142 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2148 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2154 usbd_xfer_max_frames(struct usb_xfer *xfer)
2156 return (xfer->max_frame_count);
2160 usbd_xfer_max_len(struct usb_xfer *xfer)
2162 return (xfer->max_data_length);
2166 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2168 return (xfer->max_frame_size);
2172 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2175 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2177 xfer->frlengths[frindex] = len;
2180 /*------------------------------------------------------------------------*
2181 * usb_callback_proc - factored out code
2183 * This function performs USB callbacks.
2184 *------------------------------------------------------------------------*/
2186 usb_callback_proc(struct usb_proc_msg *_pm)
2188 struct usb_done_msg *pm = (void *)_pm;
2189 struct usb_xfer_root *info = pm->xroot;
2191 /* Change locking order */
2192 USB_BUS_UNLOCK(info->bus);
2195 * We exploit the fact that the mutex is the same for all
2196 * callbacks that will be called from this thread:
2198 mtx_lock(info->xfer_mtx);
2199 USB_BUS_LOCK(info->bus);
2201 /* Continue where we lost track */
2202 usb_command_wrapper(&info->done_q,
2205 mtx_unlock(info->xfer_mtx);
2208 /*------------------------------------------------------------------------*
2209 * usbd_callback_ss_done_defer
2211 * This function will defer the start, stop and done callback to the
2213 *------------------------------------------------------------------------*/
2215 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2217 struct usb_xfer_root *info = xfer->xroot;
2218 struct usb_xfer_queue *pq = &info->done_q;
2220 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2222 if (pq->curr != xfer) {
2223 usbd_transfer_enqueue(pq, xfer);
2225 if (!pq->recurse_1) {
2228 * We have to postpone the callback due to the fact we
2229 * will have a Lock Order Reversal, LOR, if we try to
2232 if (usb_proc_msignal(info->done_p,
2233 &info->done_m[0], &info->done_m[1])) {
2237 /* clear second recurse flag */
2244 /*------------------------------------------------------------------------*
2245 * usbd_callback_wrapper
2247 * This is a wrapper for USB callbacks. This wrapper does some
2248 * auto-magic things like figuring out if we can call the callback
2249 * directly from the current context or if we need to wakeup the
2250 * interrupt process.
2251 *------------------------------------------------------------------------*/
2253 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2255 struct usb_xfer *xfer = pq->curr;
2256 struct usb_xfer_root *info = xfer->xroot;
2258 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2259 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2261 * Cases that end up here:
2263 * 5) HW interrupt done callback or other source.
2265 DPRINTFN(3, "case 5\n");
2268 * We have to postpone the callback due to the fact we
2269 * will have a Lock Order Reversal, LOR, if we try to
2272 if (usb_proc_msignal(info->done_p,
2273 &info->done_m[0], &info->done_m[1])) {
2279 * Cases that end up here:
2281 * 1) We are starting a transfer
2282 * 2) We are prematurely calling back a transfer
2283 * 3) We are stopping a transfer
2284 * 4) We are doing an ordinary callback
2286 DPRINTFN(3, "case 1-4\n");
2287 /* get next USB transfer in the queue */
2288 info->done_q.curr = NULL;
2290 /* set flag in case of drain */
2291 xfer->flags_int.doing_callback = 1;
2293 USB_BUS_UNLOCK(info->bus);
2294 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2296 /* set correct USB state for callback */
2297 if (!xfer->flags_int.transferring) {
2298 xfer->usb_state = USB_ST_SETUP;
2299 if (!xfer->flags_int.started) {
2300 /* we got stopped before we even got started */
2301 USB_BUS_LOCK(info->bus);
2306 if (usbd_callback_wrapper_sub(xfer)) {
2307 /* the callback has been deferred */
2308 USB_BUS_LOCK(info->bus);
2312 /* decrement power reference */
2313 usbd_transfer_power_ref(xfer, -1);
2315 xfer->flags_int.transferring = 0;
2318 xfer->usb_state = USB_ST_ERROR;
2320 /* set transferred state */
2321 xfer->usb_state = USB_ST_TRANSFERRED;
2323 /* sync DMA memory, if any */
2324 if (xfer->flags_int.bdma_enable &&
2325 (!xfer->flags_int.bdma_no_post_sync)) {
2326 usb_bdma_post_sync(xfer);
2333 if (xfer->usb_state != USB_ST_SETUP)
2334 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2336 /* call processing routine */
2337 (xfer->callback) (xfer, xfer->error);
2339 /* pickup the USB mutex again */
2340 USB_BUS_LOCK(info->bus);
2343 * Check if we got started after that we got cancelled, but
2344 * before we managed to do the callback.
2346 if ((!xfer->flags_int.open) &&
2347 (xfer->flags_int.started) &&
2348 (xfer->usb_state == USB_ST_ERROR)) {
2349 /* clear flag in case of drain */
2350 xfer->flags_int.doing_callback = 0;
2351 /* try to loop, but not recursivly */
2352 usb_command_wrapper(&info->done_q, xfer);
2357 /* clear flag in case of drain */
2358 xfer->flags_int.doing_callback = 0;
2361 * Check if we are draining.
2363 if (xfer->flags_int.draining &&
2364 (!xfer->flags_int.transferring)) {
2365 /* "usbd_transfer_drain()" is waiting for end of transfer */
2366 xfer->flags_int.draining = 0;
2367 cv_broadcast(&info->cv_drain);
2370 /* do the next callback, if any */
2371 usb_command_wrapper(&info->done_q,
2375 /*------------------------------------------------------------------------*
2376 * usb_dma_delay_done_cb
2378 * This function is called when the DMA delay has been exectuded, and
2379 * will make sure that the callback is called to complete the USB
2380 * transfer. This code path is ususally only used when there is an USB
2381 * error like USB_ERR_CANCELLED.
2382 *------------------------------------------------------------------------*/
2384 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2386 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2388 DPRINTFN(3, "Completed %p\n", xfer);
2390 /* queue callback for execution, again */
2391 usbd_transfer_done(xfer, 0);
2394 /*------------------------------------------------------------------------*
2395 * usbd_transfer_dequeue
2397 * - This function is used to remove an USB transfer from a USB
2400 * - This function can be called multiple times in a row.
2401 *------------------------------------------------------------------------*/
2403 usbd_transfer_dequeue(struct usb_xfer *xfer)
2405 struct usb_xfer_queue *pq;
2407 pq = xfer->wait_queue;
2409 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2410 xfer->wait_queue = NULL;
2414 /*------------------------------------------------------------------------*
2415 * usbd_transfer_enqueue
2417 * - This function is used to insert an USB transfer into a USB *
2420 * - This function can be called multiple times in a row.
2421 *------------------------------------------------------------------------*/
2423 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2426 * Insert the USB transfer into the queue, if it is not
2427 * already on a USB transfer queue:
2429 if (xfer->wait_queue == NULL) {
2430 xfer->wait_queue = pq;
2431 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2435 /*------------------------------------------------------------------------*
2436 * usbd_transfer_done
2438 * - This function is used to remove an USB transfer from the busdma,
2439 * pipe or interrupt queue.
2441 * - This function is used to queue the USB transfer on the done
2444 * - This function is used to stop any USB transfer timeouts.
2445 *------------------------------------------------------------------------*/
2447 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2449 struct usb_xfer_root *info = xfer->xroot;
2451 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2453 DPRINTF("err=%s\n", usbd_errstr(error));
2456 * If we are not transferring then just return.
2457 * This can happen during transfer cancel.
2459 if (!xfer->flags_int.transferring) {
2460 DPRINTF("not transferring\n");
2461 /* end of control transfer, if any */
2462 xfer->flags_int.control_act = 0;
2465 /* only set transfer error, if not already set */
2466 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2467 xfer->error = error;
2469 /* stop any callouts */
2470 usb_callout_stop(&xfer->timeout_handle);
2473 * If we are waiting on a queue, just remove the USB transfer
2474 * from the queue, if any. We should have the required locks
2475 * locked to do the remove when this function is called.
2477 usbd_transfer_dequeue(xfer);
2480 if (mtx_owned(info->xfer_mtx)) {
2481 struct usb_xfer_queue *pq;
2484 * If the private USB lock is not locked, then we assume
2485 * that the BUS-DMA load stage has been passed:
2489 if (pq->curr == xfer) {
2490 /* start the next BUS-DMA load, if any */
2491 usb_command_wrapper(pq, NULL);
2495 /* keep some statistics */
2497 info->bus->stats_err.uds_requests
2498 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2500 info->bus->stats_ok.uds_requests
2501 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2504 /* call the USB transfer callback */
2505 usbd_callback_ss_done_defer(xfer);
2508 /*------------------------------------------------------------------------*
2509 * usbd_transfer_start_cb
2511 * This function is called to start the USB transfer when
2512 * "xfer->interval" is greater than zero, and and the endpoint type is
2514 *------------------------------------------------------------------------*/
2516 usbd_transfer_start_cb(void *arg)
2518 struct usb_xfer *xfer = arg;
2519 struct usb_endpoint *ep = xfer->endpoint;
2521 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2526 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2529 /* the transfer can now be cancelled */
2530 xfer->flags_int.can_cancel_immed = 1;
2532 /* start USB transfer, if no error */
2533 if (xfer->error == 0)
2534 (ep->methods->start) (xfer);
2536 /* check for transfer error */
2538 /* some error has happened */
2539 usbd_transfer_done(xfer, 0);
2543 /*------------------------------------------------------------------------*
2544 * usbd_xfer_set_stall
2546 * This function is used to set the stall flag outside the
2547 * callback. This function is NULL safe.
2548 *------------------------------------------------------------------------*/
2550 usbd_xfer_set_stall(struct usb_xfer *xfer)
2556 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2558 /* avoid any races by locking the USB mutex */
2559 USB_BUS_LOCK(xfer->xroot->bus);
2560 xfer->flags.stall_pipe = 1;
2561 USB_BUS_UNLOCK(xfer->xroot->bus);
2565 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2567 return (xfer->endpoint->is_stalled);
2570 /*------------------------------------------------------------------------*
2571 * usbd_transfer_clear_stall
2573 * This function is used to clear the stall flag outside the
2574 * callback. This function is NULL safe.
2575 *------------------------------------------------------------------------*/
2577 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2583 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2585 /* avoid any races by locking the USB mutex */
2586 USB_BUS_LOCK(xfer->xroot->bus);
2588 xfer->flags.stall_pipe = 0;
2590 USB_BUS_UNLOCK(xfer->xroot->bus);
2593 /*------------------------------------------------------------------------*
2596 * This function is used to add an USB transfer to the pipe transfer list.
2597 *------------------------------------------------------------------------*/
2599 usbd_pipe_start(struct usb_xfer_queue *pq)
2601 struct usb_endpoint *ep;
2602 struct usb_xfer *xfer;
2606 ep = xfer->endpoint;
2608 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2611 * If the endpoint is already stalled we do nothing !
2613 if (ep->is_stalled) {
2617 * Check if we are supposed to stall the endpoint:
2619 if (xfer->flags.stall_pipe) {
2620 struct usb_device *udev;
2621 struct usb_xfer_root *info;
2623 /* clear stall command */
2624 xfer->flags.stall_pipe = 0;
2626 /* get pointer to USB device */
2631 * Only stall BULK and INTERRUPT endpoints.
2633 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2634 if ((type == UE_BULK) ||
2635 (type == UE_INTERRUPT)) {
2640 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2641 (udev->bus->methods->set_stall) (
2642 udev, ep, &did_stall);
2643 } else if (udev->ctrl_xfer[1]) {
2644 info = udev->ctrl_xfer[1]->xroot;
2646 USB_BUS_NON_GIANT_PROC(info->bus),
2647 &udev->cs_msg[0], &udev->cs_msg[1]);
2649 /* should not happen */
2650 DPRINTFN(0, "No stall handler\n");
2653 * Check if we should stall. Some USB hardware
2654 * handles set- and clear-stall in hardware.
2658 * The transfer will be continued when
2659 * the clear-stall control endpoint
2660 * message is received.
2665 } else if (type == UE_ISOCHRONOUS) {
2668 * Make sure any FIFO overflow or other FIFO
2669 * error conditions go away by resetting the
2670 * endpoint FIFO through the clear stall
2673 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2674 (udev->bus->methods->clear_stall) (udev, ep);
2678 /* Set or clear stall complete - special case */
2679 if (xfer->nframes == 0) {
2680 /* we are complete */
2682 usbd_transfer_done(xfer, 0);
2688 * 1) Start the first transfer queued.
2690 * 2) Re-start the current USB transfer.
2693 * Check if there should be any
2694 * pre transfer start delay:
2696 if (xfer->interval > 0) {
2697 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2698 if ((type == UE_BULK) ||
2699 (type == UE_CONTROL)) {
2700 usbd_transfer_timeout_ms(xfer,
2701 &usbd_transfer_start_cb,
2709 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2711 /* the transfer can now be cancelled */
2712 xfer->flags_int.can_cancel_immed = 1;
2714 /* start USB transfer, if no error */
2715 if (xfer->error == 0)
2716 (ep->methods->start) (xfer);
2718 /* check for transfer error */
2720 /* some error has happened */
2721 usbd_transfer_done(xfer, 0);
2725 /*------------------------------------------------------------------------*
2726 * usbd_transfer_timeout_ms
2728 * This function is used to setup a timeout on the given USB
2729 * transfer. If the timeout has been deferred the callback given by
2730 * "cb" will get called after "ms" milliseconds.
2731 *------------------------------------------------------------------------*/
2733 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2734 void (*cb) (void *arg), usb_timeout_t ms)
2736 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2739 usb_callout_reset(&xfer->timeout_handle,
2740 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2743 /*------------------------------------------------------------------------*
2744 * usbd_callback_wrapper_sub
2746 * - This function will update variables in an USB transfer after
2747 * that the USB transfer is complete.
2749 * - This function is used to start the next USB transfer on the
2750 * ep transfer queue, if any.
2752 * NOTE: In some special cases the USB transfer will not be removed from
2753 * the pipe queue, but remain first. To enforce USB transfer removal call
2754 * this function passing the error code "USB_ERR_CANCELLED".
2758 * Else: The callback has been deferred.
2759 *------------------------------------------------------------------------*/
2761 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2763 struct usb_endpoint *ep;
2764 struct usb_bus *bus;
2767 bus = xfer->xroot->bus;
2769 if ((!xfer->flags_int.open) &&
2770 (!xfer->flags_int.did_close)) {
2773 (xfer->endpoint->methods->close) (xfer);
2774 USB_BUS_UNLOCK(bus);
2775 /* only close once */
2776 xfer->flags_int.did_close = 1;
2777 return (1); /* wait for new callback */
2780 * If we have a non-hardware induced error we
2781 * need to do the DMA delay!
2783 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2784 (xfer->error == USB_ERR_CANCELLED ||
2785 xfer->error == USB_ERR_TIMEOUT ||
2786 bus->methods->start_dma_delay != NULL)) {
2790 /* only delay once */
2791 xfer->flags_int.did_dma_delay = 1;
2793 /* we can not cancel this delay */
2794 xfer->flags_int.can_cancel_immed = 0;
2796 temp = usbd_get_dma_delay(xfer->xroot->udev);
2798 DPRINTFN(3, "DMA delay, %u ms, "
2799 "on %p\n", temp, xfer);
2804 * Some hardware solutions have dedicated
2805 * events when it is safe to free DMA'ed
2806 * memory. For the other hardware platforms we
2807 * use a static delay.
2809 if (bus->methods->start_dma_delay != NULL) {
2810 (bus->methods->start_dma_delay) (xfer);
2812 usbd_transfer_timeout_ms(xfer,
2813 (void (*)(void *))&usb_dma_delay_done_cb,
2816 USB_BUS_UNLOCK(bus);
2817 return (1); /* wait for new callback */
2820 /* check actual number of frames */
2821 if (xfer->aframes > xfer->nframes) {
2822 if (xfer->error == 0) {
2823 panic("%s: actual number of frames, %d, is "
2824 "greater than initial number of frames, %d\n",
2825 __FUNCTION__, xfer->aframes, xfer->nframes);
2827 /* just set some valid value */
2828 xfer->aframes = xfer->nframes;
2831 /* compute actual length */
2834 for (x = 0; x != xfer->aframes; x++) {
2835 xfer->actlen += xfer->frlengths[x];
2839 * Frames that were not transferred get zero actual length in
2840 * case the USB device driver does not check the actual number
2841 * of frames transferred, "xfer->aframes":
2843 for (; x < xfer->nframes; x++) {
2844 usbd_xfer_set_frame_len(xfer, x, 0);
2847 /* check actual length */
2848 if (xfer->actlen > xfer->sumlen) {
2849 if (xfer->error == 0) {
2850 panic("%s: actual length, %d, is greater than "
2851 "initial length, %d\n",
2852 __FUNCTION__, xfer->actlen, xfer->sumlen);
2854 /* just set some valid value */
2855 xfer->actlen = xfer->sumlen;
2858 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2859 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2860 xfer->aframes, xfer->nframes);
2863 /* end of control transfer, if any */
2864 xfer->flags_int.control_act = 0;
2866 #if USB_HAVE_TT_SUPPORT
2867 switch (xfer->error) {
2868 case USB_ERR_NORMAL_COMPLETION:
2869 case USB_ERR_SHORT_XFER:
2870 case USB_ERR_STALLED:
2871 case USB_ERR_CANCELLED:
2875 /* try to reset the TT, if any */
2877 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2878 USB_BUS_UNLOCK(bus);
2882 /* check if we should block the execution queue */
2883 if ((xfer->error != USB_ERR_CANCELLED) &&
2884 (xfer->flags.pipe_bof)) {
2885 DPRINTFN(2, "xfer=%p: Block On Failure "
2886 "on endpoint=%p\n", xfer, xfer->endpoint);
2890 /* check for short transfers */
2891 if (xfer->actlen < xfer->sumlen) {
2893 /* end of control transfer, if any */
2894 xfer->flags_int.control_act = 0;
2896 if (!xfer->flags_int.short_xfer_ok) {
2897 xfer->error = USB_ERR_SHORT_XFER;
2898 if (xfer->flags.pipe_bof) {
2899 DPRINTFN(2, "xfer=%p: Block On Failure on "
2900 "Short Transfer on endpoint %p.\n",
2901 xfer, xfer->endpoint);
2907 * Check if we are in the middle of a
2910 if (xfer->flags_int.control_act) {
2911 DPRINTFN(5, "xfer=%p: Control transfer "
2912 "active on endpoint=%p\n", xfer, xfer->endpoint);
2918 ep = xfer->endpoint;
2921 * If the current USB transfer is completing we need to start the
2925 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2926 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
2928 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
2929 TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
2930 /* there is another USB transfer waiting */
2932 /* this is the last USB transfer */
2933 /* clear isochronous sync flag */
2934 xfer->endpoint->is_synced = 0;
2937 USB_BUS_UNLOCK(bus);
2942 /*------------------------------------------------------------------------*
2943 * usb_command_wrapper
2945 * This function is used to execute commands non-recursivly on an USB
2947 *------------------------------------------------------------------------*/
2949 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2953 * If the transfer is not already processing,
2956 if (pq->curr != xfer) {
2957 usbd_transfer_enqueue(pq, xfer);
2958 if (pq->curr != NULL) {
2959 /* something is already processing */
2960 DPRINTFN(6, "busy %p\n", pq->curr);
2965 /* Get next element in queue */
2969 if (!pq->recurse_1) {
2973 /* set both recurse flags */
2977 if (pq->curr == NULL) {
2978 xfer = TAILQ_FIRST(&pq->head);
2980 TAILQ_REMOVE(&pq->head, xfer,
2982 xfer->wait_queue = NULL;
2988 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2990 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2992 } while (!pq->recurse_2);
2994 /* clear first recurse flag */
2998 /* clear second recurse flag */
3003 /*------------------------------------------------------------------------*
3004 * usbd_ctrl_transfer_setup
3006 * This function is used to setup the default USB control endpoint
3008 *------------------------------------------------------------------------*/
3010 usbd_ctrl_transfer_setup(struct usb_device *udev)
3012 struct usb_xfer *xfer;
3014 uint8_t iface_index;
3016 /* check for root HUB */
3017 if (udev->parent_hub == NULL)
3021 xfer = udev->ctrl_xfer[0];
3023 USB_XFER_LOCK(xfer);
3025 ((xfer->address == udev->address) &&
3026 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3027 udev->ddesc.bMaxPacketSize));
3028 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3031 * NOTE: checking "xfer->address" and
3032 * starting the USB transfer must be
3035 usbd_transfer_start(xfer);
3038 USB_XFER_UNLOCK(xfer);
3045 * All parameters are exactly the same like before.
3051 * Update wMaxPacketSize for the default control endpoint:
3053 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3054 udev->ddesc.bMaxPacketSize;
3057 * Unsetup any existing USB transfer:
3059 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3062 * Reset clear stall error counter.
3064 udev->clear_stall_errors = 0;
3067 * Try to setup a new USB transfer for the
3068 * default control endpoint:
3071 if (usbd_transfer_setup(udev, &iface_index,
3072 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3073 &udev->device_mtx)) {
3074 DPRINTFN(0, "could not setup default "
3081 /*------------------------------------------------------------------------*
3082 * usbd_clear_data_toggle - factored out code
3084 * NOTE: the intention of this function is not to reset the hardware
3086 *------------------------------------------------------------------------*/
3088 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3090 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3092 /* check that we have a valid case */
3093 if (udev->flags.usb_mode == USB_MODE_HOST &&
3094 udev->parent_hub != NULL &&
3095 udev->bus->methods->clear_stall != NULL &&
3096 ep->methods != NULL) {
3097 (udev->bus->methods->clear_stall) (udev, ep);
3101 /*------------------------------------------------------------------------*
3102 * usbd_clear_data_toggle - factored out code
3104 * NOTE: the intention of this function is not to reset the hardware
3105 * data toggle on the USB device side.
3106 *------------------------------------------------------------------------*/
3108 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3110 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3112 USB_BUS_LOCK(udev->bus);
3113 ep->toggle_next = 0;
3114 /* some hardware needs a callback to clear the data toggle */
3115 usbd_clear_stall_locked(udev, ep);
3116 USB_BUS_UNLOCK(udev->bus);
3119 /*------------------------------------------------------------------------*
3120 * usbd_clear_stall_callback - factored out clear stall callback
3123 * xfer1: Clear Stall Control Transfer
3124 * xfer2: Stalled USB Transfer
3126 * This function is NULL safe.
3132 * Clear stall config example:
3134 * static const struct usb_config my_clearstall = {
3135 * .type = UE_CONTROL,
3137 * .direction = UE_DIR_ANY,
3138 * .interval = 50, //50 milliseconds
3139 * .bufsize = sizeof(struct usb_device_request),
3140 * .timeout = 1000, //1.000 seconds
3141 * .callback = &my_clear_stall_callback, // **
3142 * .usb_mode = USB_MODE_HOST,
3145 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3146 * passing the correct parameters.
3147 *------------------------------------------------------------------------*/
3149 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3150 struct usb_xfer *xfer2)
3152 struct usb_device_request req;
3154 if (xfer2 == NULL) {
3155 /* looks like we are tearing down */
3156 DPRINTF("NULL input parameter\n");
3159 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3160 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3162 switch (USB_GET_STATE(xfer1)) {
3166 * pre-clear the data toggle to DATA0 ("umass.c" and
3167 * "ata-usb.c" depends on this)
3170 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3172 /* setup a clear-stall packet */
3174 req.bmRequestType = UT_WRITE_ENDPOINT;
3175 req.bRequest = UR_CLEAR_FEATURE;
3176 USETW(req.wValue, UF_ENDPOINT_HALT);
3177 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3179 USETW(req.wLength, 0);
3182 * "usbd_transfer_setup_sub()" will ensure that
3183 * we have sufficient room in the buffer for
3184 * the request structure!
3187 /* copy in the transfer */
3189 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3192 xfer1->frlengths[0] = sizeof(req);
3195 usbd_transfer_submit(xfer1);
3198 case USB_ST_TRANSFERRED:
3201 default: /* Error */
3202 if (xfer1->error == USB_ERR_CANCELLED) {
3207 return (1); /* Clear Stall Finished */
3210 /*------------------------------------------------------------------------*
3211 * usbd_transfer_poll
3213 * The following function gets called from the USB keyboard driver and
3214 * UMASS when the system has paniced.
3216 * NOTE: It is currently not possible to resume normal operation on
3217 * the USB controller which has been polled, due to clearing of the
3218 * "up_dsleep" and "up_msleep" flags.
3219 *------------------------------------------------------------------------*/
3221 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3223 struct usb_xfer *xfer;
3224 struct usb_xfer_root *xroot;
3225 struct usb_device *udev;
3226 struct usb_proc_msg *pm;
3231 for (n = 0; n != max; n++) {
3232 /* Extra checks to avoid panic */
3235 continue; /* no USB transfer */
3236 xroot = xfer->xroot;
3238 continue; /* no USB root */
3241 continue; /* no USB device */
3242 if (udev->bus == NULL)
3243 continue; /* no BUS structure */
3244 if (udev->bus->methods == NULL)
3245 continue; /* no BUS methods */
3246 if (udev->bus->methods->xfer_poll == NULL)
3247 continue; /* no poll method */
3249 /* make sure that the BUS mutex is not locked */
3251 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3252 mtx_unlock(&xroot->udev->bus->bus_mtx);
3256 /* make sure that the transfer mutex is not locked */
3258 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3259 mtx_unlock(xroot->xfer_mtx);
3263 /* Make sure cv_signal() and cv_broadcast() is not called */
3264 USB_BUS_CONTROL_XFER_PROC(udev->bus)->up_msleep = 0;
3265 USB_BUS_EXPLORE_PROC(udev->bus)->up_msleep = 0;
3266 USB_BUS_GIANT_PROC(udev->bus)->up_msleep = 0;
3267 USB_BUS_NON_GIANT_PROC(udev->bus)->up_msleep = 0;
3269 /* poll USB hardware */
3270 (udev->bus->methods->xfer_poll) (udev->bus);
3272 USB_BUS_LOCK(xroot->bus);
3274 /* check for clear stall */
3275 if (udev->ctrl_xfer[1] != NULL) {
3277 /* poll clear stall start */
3278 pm = &udev->cs_msg[0].hdr;
3279 (pm->pm_callback) (pm);
3280 /* poll clear stall done thread */
3281 pm = &udev->ctrl_xfer[1]->
3282 xroot->done_m[0].hdr;
3283 (pm->pm_callback) (pm);
3286 /* poll done thread */
3287 pm = &xroot->done_m[0].hdr;
3288 (pm->pm_callback) (pm);
3290 USB_BUS_UNLOCK(xroot->bus);
3292 /* restore transfer mutex */
3294 mtx_lock(xroot->xfer_mtx);
3296 /* restore BUS mutex */
3298 mtx_lock(&xroot->udev->bus->bus_mtx);
3303 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3304 uint8_t type, enum usb_dev_speed speed)
3306 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3307 [USB_SPEED_LOW] = 8,
3308 [USB_SPEED_FULL] = 64,
3309 [USB_SPEED_HIGH] = 1024,
3310 [USB_SPEED_VARIABLE] = 1024,
3311 [USB_SPEED_SUPER] = 1024,
3314 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3315 [USB_SPEED_LOW] = 0, /* invalid */
3316 [USB_SPEED_FULL] = 1023,
3317 [USB_SPEED_HIGH] = 1024,
3318 [USB_SPEED_VARIABLE] = 3584,
3319 [USB_SPEED_SUPER] = 1024,
3322 static const uint16_t control_min[USB_SPEED_MAX] = {
3323 [USB_SPEED_LOW] = 8,
3324 [USB_SPEED_FULL] = 8,
3325 [USB_SPEED_HIGH] = 64,
3326 [USB_SPEED_VARIABLE] = 512,
3327 [USB_SPEED_SUPER] = 512,
3330 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3331 [USB_SPEED_LOW] = 8,
3332 [USB_SPEED_FULL] = 8,
3333 [USB_SPEED_HIGH] = 512,
3334 [USB_SPEED_VARIABLE] = 512,
3335 [USB_SPEED_SUPER] = 1024,
3340 memset(ptr, 0, sizeof(*ptr));
3344 ptr->range.max = intr_range_max[speed];
3346 case UE_ISOCHRONOUS:
3347 ptr->range.max = isoc_range_max[speed];
3350 if (type == UE_BULK)
3351 temp = bulk_min[speed];
3352 else /* UE_CONTROL */
3353 temp = control_min[speed];
3355 /* default is fixed */
3356 ptr->fixed[0] = temp;
3357 ptr->fixed[1] = temp;
3358 ptr->fixed[2] = temp;
3359 ptr->fixed[3] = temp;
3361 if (speed == USB_SPEED_FULL) {
3362 /* multiple sizes */
3367 if ((speed == USB_SPEED_VARIABLE) &&
3368 (type == UE_BULK)) {
3369 /* multiple sizes */
3370 ptr->fixed[2] = 1024;
3371 ptr->fixed[3] = 1536;
3378 usbd_xfer_softc(struct usb_xfer *xfer)
3380 return (xfer->priv_sc);
3384 usbd_xfer_get_priv(struct usb_xfer *xfer)
3386 return (xfer->priv_fifo);
3390 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3392 xfer->priv_fifo = ptr;
3396 usbd_xfer_state(struct usb_xfer *xfer)
3398 return (xfer->usb_state);
3402 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3405 case USB_FORCE_SHORT_XFER:
3406 xfer->flags.force_short_xfer = 1;
3408 case USB_SHORT_XFER_OK:
3409 xfer->flags.short_xfer_ok = 1;
3411 case USB_MULTI_SHORT_OK:
3412 xfer->flags.short_frames_ok = 1;
3414 case USB_MANUAL_STATUS:
3415 xfer->flags.manual_status = 1;
3421 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3424 case USB_FORCE_SHORT_XFER:
3425 xfer->flags.force_short_xfer = 0;
3427 case USB_SHORT_XFER_OK:
3428 xfer->flags.short_xfer_ok = 0;
3430 case USB_MULTI_SHORT_OK:
3431 xfer->flags.short_frames_ok = 0;
3433 case USB_MANUAL_STATUS:
3434 xfer->flags.manual_status = 0;
3440 * The following function returns in milliseconds when the isochronous
3441 * transfer was completed by the hardware. The returned value wraps
3442 * around 65536 milliseconds.
3445 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3447 return (xfer->isoc_time_complete);
3451 * The following function returns non-zero if the max packet size
3452 * field was clamped to a valid value. Else it returns zero.
3455 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3457 return (xfer->flags_int.maxp_was_clamped);