3 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/stdint.h>
28 #include <sys/stddef.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/types.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
35 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/sysctl.h>
41 #include <sys/unistd.h>
42 #include <sys/callout.h>
43 #include <sys/malloc.h>
47 #include <dev/usb/usb.h>
48 #include <dev/usb/usbdi.h>
49 #include <dev/usb/usbdi_util.h>
51 #define USB_DEBUG_VAR usb_debug
53 #include <dev/usb/usb_core.h>
54 #include <dev/usb/usb_busdma.h>
55 #include <dev/usb/usb_process.h>
56 #include <dev/usb/usb_transfer.h>
57 #include <dev/usb/usb_device.h>
58 #include <dev/usb/usb_debug.h>
59 #include <dev/usb/usb_util.h>
61 #include <dev/usb/usb_controller.h>
62 #include <dev/usb/usb_bus.h>
63 #include <dev/usb/usb_pf.h>
65 struct usb_std_packet_size {
67 uint16_t min; /* inclusive */
68 uint16_t max; /* inclusive */
74 static usb_callback_t usb_request_callback;
76 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
78 /* This transfer is used for generic control endpoint transfers */
82 .endpoint = 0x00, /* Control endpoint */
83 .direction = UE_DIR_ANY,
84 .bufsize = USB_EP0_BUFSIZE, /* bytes */
85 .flags = {.proxy_buffer = 1,},
86 .callback = &usb_request_callback,
87 .usb_mode = USB_MODE_DUAL, /* both modes */
90 /* This transfer is used for generic clear stall only */
94 .endpoint = 0x00, /* Control pipe */
95 .direction = UE_DIR_ANY,
96 .bufsize = sizeof(struct usb_device_request),
97 .callback = &usb_do_clear_stall_callback,
98 .timeout = 1000, /* 1 second */
99 .interval = 50, /* 50ms */
100 .usb_mode = USB_MODE_HOST,
104 /* function prototypes */
106 static void usbd_update_max_frame_size(struct usb_xfer *);
107 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
108 static void usbd_control_transfer_init(struct usb_xfer *);
109 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
110 static void usb_callback_proc(struct usb_proc_msg *);
111 static void usbd_callback_ss_done_defer(struct usb_xfer *);
112 static void usbd_callback_wrapper(struct usb_xfer_queue *);
113 static void usbd_transfer_start_cb(void *);
114 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
115 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
116 uint8_t type, enum usb_dev_speed speed);
118 /*------------------------------------------------------------------------*
119 * usb_request_callback
120 *------------------------------------------------------------------------*/
122 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
124 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
125 usb_handle_request_callback(xfer, error);
127 usbd_do_request_callback(xfer, error);
130 /*------------------------------------------------------------------------*
131 * usbd_update_max_frame_size
133 * This function updates the maximum frame size, hence high speed USB
134 * can transfer multiple consecutive packets.
135 *------------------------------------------------------------------------*/
137 usbd_update_max_frame_size(struct usb_xfer *xfer)
139 /* compute maximum frame size */
140 /* this computation should not overflow 16-bit */
141 /* max = 15 * 1024 */
143 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
146 /*------------------------------------------------------------------------*
149 * The following function is called when we need to
150 * synchronize with DMA hardware.
153 * 0: no DMA delay required
154 * Else: milliseconds of DMA delay
155 *------------------------------------------------------------------------*/
157 usbd_get_dma_delay(struct usb_device *udev)
159 struct usb_bus_methods *mtod;
162 mtod = udev->bus->methods;
165 if (mtod->get_dma_delay) {
166 (mtod->get_dma_delay) (udev, &temp);
168 * Round up and convert to milliseconds. Note that we use
169 * 1024 milliseconds per second. to save a division.
177 /*------------------------------------------------------------------------*
178 * usbd_transfer_setup_sub_malloc
180 * This function will allocate one or more DMA'able memory chunks
181 * according to "size", "align" and "count" arguments. "ppc" is
182 * pointed to a linear array of USB page caches afterwards.
187 *------------------------------------------------------------------------*/
190 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
191 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
194 struct usb_page_cache *pc;
204 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
206 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
209 return (0); /* nothing to allocate */
212 * Make sure that the size is aligned properly.
214 size = -((-size) & (-align));
217 * Try multi-allocation chunks to reduce the number of DMA
218 * allocations, hence DMA allocations are slow.
220 if (size >= USB_PAGE_SIZE) {
224 /* compute number of objects per page */
225 n_obj = (USB_PAGE_SIZE / size);
227 * Compute number of DMA chunks, rounded up
230 n_dma_pc = ((count + n_obj - 1) / n_obj);
233 if (parm->buf == NULL) {
235 parm->dma_page_ptr += n_dma_pc;
236 parm->dma_page_cache_ptr += n_dma_pc;
237 parm->dma_page_ptr += count;
238 parm->xfer_page_cache_ptr += count;
241 for (x = 0; x != n_dma_pc; x++) {
242 /* need to initialize the page cache */
243 parm->dma_page_cache_ptr[x].tag_parent =
244 &parm->curr_xfer->xroot->dma_parent_tag;
246 for (x = 0; x != count; x++) {
247 /* need to initialize the page cache */
248 parm->xfer_page_cache_ptr[x].tag_parent =
249 &parm->curr_xfer->xroot->dma_parent_tag;
253 *ppc = parm->xfer_page_cache_ptr;
255 r = count; /* set remainder count */
256 z = n_obj * size; /* set allocation size */
257 pc = parm->xfer_page_cache_ptr;
258 pg = parm->dma_page_ptr;
260 for (x = 0; x != n_dma_pc; x++) {
263 /* compute last remainder */
267 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
269 return (1); /* failure */
271 /* Set beginning of current buffer */
272 buf = parm->dma_page_cache_ptr->buffer;
273 /* Make room for one DMA page cache and one page */
274 parm->dma_page_cache_ptr++;
277 for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
279 /* Load sub-chunk into DMA */
280 if (usb_pc_dmamap_create(pc, size)) {
281 return (1); /* failure */
283 pc->buffer = USB_ADD_BYTES(buf, y * size);
286 mtx_lock(pc->tag_parent->mtx);
287 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
288 mtx_unlock(pc->tag_parent->mtx);
289 return (1); /* failure */
291 mtx_unlock(pc->tag_parent->mtx);
295 parm->xfer_page_cache_ptr = pc;
296 parm->dma_page_ptr = pg;
301 /*------------------------------------------------------------------------*
302 * usbd_transfer_setup_sub - transfer setup subroutine
304 * This function must be called from the "xfer_setup" callback of the
305 * USB Host or Device controller driver when setting up an USB
306 * transfer. This function will setup correct packet sizes, buffer
307 * sizes, flags and more, that are stored in the "usb_xfer"
309 *------------------------------------------------------------------------*/
311 usbd_transfer_setup_sub(struct usb_setup_params *parm)
317 struct usb_xfer *xfer = parm->curr_xfer;
318 const struct usb_config *setup = parm->curr_setup;
319 struct usb_endpoint_ss_comp_descriptor *ecomp;
320 struct usb_endpoint_descriptor *edesc;
321 struct usb_std_packet_size std_size;
322 usb_frcount_t n_frlengths;
323 usb_frcount_t n_frbuffers;
329 * Sanity check. The following parameters must be initialized before
330 * calling this function.
332 if ((parm->hc_max_packet_size == 0) ||
333 (parm->hc_max_packet_count == 0) ||
334 (parm->hc_max_frame_size == 0)) {
335 parm->err = USB_ERR_INVAL;
338 edesc = xfer->endpoint->edesc;
339 ecomp = xfer->endpoint->ecomp;
341 type = (edesc->bmAttributes & UE_XFERTYPE);
343 xfer->flags = setup->flags;
344 xfer->nframes = setup->frames;
345 xfer->timeout = setup->timeout;
346 xfer->callback = setup->callback;
347 xfer->interval = setup->interval;
348 xfer->endpointno = edesc->bEndpointAddress;
349 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
350 xfer->max_packet_count = 1;
351 /* make a shadow copy: */
352 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
354 parm->bufsize = setup->bufsize;
356 switch (parm->speed) {
361 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
363 /* check for invalid max packet count */
364 if (xfer->max_packet_count > 3)
365 xfer->max_packet_count = 3;
370 xfer->max_packet_size &= 0x7FF;
372 case USB_SPEED_SUPER:
373 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
376 xfer->max_packet_count += ecomp->bMaxBurst;
378 if ((xfer->max_packet_count == 0) ||
379 (xfer->max_packet_count > 16))
380 xfer->max_packet_count = 16;
384 xfer->max_packet_count = 1;
390 mult = (ecomp->bmAttributes & 3) + 1;
394 xfer->max_packet_count *= mult;
400 xfer->max_packet_size &= 0x7FF;
405 /* range check "max_packet_count" */
407 if (xfer->max_packet_count > parm->hc_max_packet_count) {
408 xfer->max_packet_count = parm->hc_max_packet_count;
410 /* filter "wMaxPacketSize" according to HC capabilities */
412 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
413 (xfer->max_packet_size == 0)) {
414 xfer->max_packet_size = parm->hc_max_packet_size;
416 /* filter "wMaxPacketSize" according to standard sizes */
418 usbd_get_std_packet_size(&std_size, type, parm->speed);
420 if (std_size.range.min || std_size.range.max) {
422 if (xfer->max_packet_size < std_size.range.min) {
423 xfer->max_packet_size = std_size.range.min;
425 if (xfer->max_packet_size > std_size.range.max) {
426 xfer->max_packet_size = std_size.range.max;
430 if (xfer->max_packet_size >= std_size.fixed[3]) {
431 xfer->max_packet_size = std_size.fixed[3];
432 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
433 xfer->max_packet_size = std_size.fixed[2];
434 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
435 xfer->max_packet_size = std_size.fixed[1];
437 /* only one possibility left */
438 xfer->max_packet_size = std_size.fixed[0];
442 /* compute "max_frame_size" */
444 usbd_update_max_frame_size(xfer);
446 /* check interrupt interval and transfer pre-delay */
448 if (type == UE_ISOCHRONOUS) {
450 uint16_t frame_limit;
452 xfer->interval = 0; /* not used, must be zero */
453 xfer->flags_int.isochronous_xfr = 1; /* set flag */
455 if (xfer->timeout == 0) {
457 * set a default timeout in
458 * case something goes wrong!
460 xfer->timeout = 1000 / 4;
462 switch (parm->speed) {
465 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
469 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
470 xfer->fps_shift = edesc->bInterval;
471 if (xfer->fps_shift > 0)
473 if (xfer->fps_shift > 3)
475 if (xfer->flags.pre_scale_frames != 0)
476 xfer->nframes <<= (3 - xfer->fps_shift);
480 if (xfer->nframes > frame_limit) {
482 * this is not going to work
485 parm->err = USB_ERR_INVAL;
488 if (xfer->nframes == 0) {
490 * this is not a valid value
492 parm->err = USB_ERR_ZERO_NFRAMES;
498 * If a value is specified use that else check the
499 * endpoint descriptor!
501 if (type == UE_INTERRUPT) {
505 if (xfer->interval == 0) {
507 xfer->interval = edesc->bInterval;
509 switch (parm->speed) {
515 if (xfer->interval < 4)
517 else if (xfer->interval > 16)
518 xfer->interval = (1 << (16 - 4));
521 (1 << (xfer->interval - 4));
526 if (xfer->interval == 0) {
528 * One millisecond is the smallest
529 * interval we support:
537 while ((temp != 0) && (temp < xfer->interval)) {
542 switch (parm->speed) {
547 xfer->fps_shift += 3;
554 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
555 * to be equal to zero when setting up USB transfers, hence
556 * this leads to alot of extra code in the USB kernel.
559 if ((xfer->max_frame_size == 0) ||
560 (xfer->max_packet_size == 0)) {
564 if ((parm->bufsize <= MIN_PKT) &&
565 (type != UE_CONTROL) &&
569 xfer->max_packet_size = MIN_PKT;
570 xfer->max_packet_count = 1;
571 parm->bufsize = 0; /* automatic setup length */
572 usbd_update_max_frame_size(xfer);
575 parm->err = USB_ERR_ZERO_MAXP;
584 * check if we should setup a default
588 if (parm->bufsize == 0) {
590 parm->bufsize = xfer->max_frame_size;
592 if (type == UE_ISOCHRONOUS) {
593 parm->bufsize *= xfer->nframes;
597 * check if we are about to setup a proxy
601 if (xfer->flags.proxy_buffer) {
603 /* round bufsize up */
605 parm->bufsize += (xfer->max_frame_size - 1);
607 if (parm->bufsize < xfer->max_frame_size) {
608 /* length wrapped around */
609 parm->err = USB_ERR_INVAL;
612 /* subtract remainder */
614 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
616 /* add length of USB device request structure, if any */
618 if (type == UE_CONTROL) {
619 parm->bufsize += REQ_SIZE; /* SETUP message */
622 xfer->max_data_length = parm->bufsize;
624 /* Setup "n_frlengths" and "n_frbuffers" */
626 if (type == UE_ISOCHRONOUS) {
627 n_frlengths = xfer->nframes;
631 if (type == UE_CONTROL) {
632 xfer->flags_int.control_xfr = 1;
633 if (xfer->nframes == 0) {
634 if (parm->bufsize <= REQ_SIZE) {
636 * there will never be any data
645 if (xfer->nframes == 0) {
650 n_frlengths = xfer->nframes;
651 n_frbuffers = xfer->nframes;
655 * check if we have room for the
656 * USB device request structure:
659 if (type == UE_CONTROL) {
661 if (xfer->max_data_length < REQ_SIZE) {
662 /* length wrapped around or too small bufsize */
663 parm->err = USB_ERR_INVAL;
666 xfer->max_data_length -= REQ_SIZE;
669 * Setup "frlengths" and shadow "frlengths" for keeping the
670 * initial frame lengths when a USB transfer is complete. This
671 * information is useful when computing isochronous offsets.
673 xfer->frlengths = parm->xfer_length_ptr;
674 parm->xfer_length_ptr += 2 * n_frlengths;
676 /* setup "frbuffers" */
677 xfer->frbuffers = parm->xfer_page_cache_ptr;
678 parm->xfer_page_cache_ptr += n_frbuffers;
680 /* initialize max frame count */
681 xfer->max_frame_count = xfer->nframes;
684 * check if we need to setup
688 if (!xfer->flags.ext_buffer) {
691 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
696 USB_ADD_BYTES(parm->buf, parm->size[0]);
698 usbd_xfer_set_frame_offset(xfer, 0, 0);
700 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
701 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
704 parm->size[0] += parm->bufsize;
706 /* align data again */
707 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
710 * Compute maximum buffer size
713 if (parm->bufsize_max < parm->bufsize) {
714 parm->bufsize_max = parm->bufsize;
717 if (xfer->flags_int.bdma_enable) {
719 * Setup "dma_page_ptr".
721 * Proof for formula below:
723 * Assume there are three USB frames having length "a", "b" and
724 * "c". These USB frames will at maximum need "z"
725 * "usb_page" structures. "z" is given by:
727 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
728 * ((c / USB_PAGE_SIZE) + 2);
730 * Constraining "a", "b" and "c" like this:
732 * (a + b + c) <= parm->bufsize
736 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
738 * Here is the general formula:
740 xfer->dma_page_ptr = parm->dma_page_ptr;
741 parm->dma_page_ptr += (2 * n_frbuffers);
742 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
746 /* correct maximum data length */
747 xfer->max_data_length = 0;
749 /* subtract USB frame remainder from "hc_max_frame_size" */
751 xfer->max_hc_frame_size =
752 (parm->hc_max_frame_size -
753 (parm->hc_max_frame_size % xfer->max_frame_size));
755 if (xfer->max_hc_frame_size == 0) {
756 parm->err = USB_ERR_INVAL;
760 /* initialize frame buffers */
763 for (x = 0; x != n_frbuffers; x++) {
764 xfer->frbuffers[x].tag_parent =
765 &xfer->xroot->dma_parent_tag;
767 if (xfer->flags_int.bdma_enable &&
768 (parm->bufsize_max > 0)) {
770 if (usb_pc_dmamap_create(
772 parm->bufsize_max)) {
773 parm->err = USB_ERR_NOMEM;
783 * Set some dummy values so that we avoid division by zero:
785 xfer->max_hc_frame_size = 1;
786 xfer->max_frame_size = 1;
787 xfer->max_packet_size = 1;
788 xfer->max_data_length = 0;
790 xfer->max_frame_count = 0;
794 /*------------------------------------------------------------------------*
795 * usbd_transfer_setup - setup an array of USB transfers
797 * NOTE: You must always call "usbd_transfer_unsetup" after calling
798 * "usbd_transfer_setup" if success was returned.
800 * The idea is that the USB device driver should pre-allocate all its
801 * transfers by one call to this function.
806 *------------------------------------------------------------------------*/
808 usbd_transfer_setup(struct usb_device *udev,
809 const uint8_t *ifaces, struct usb_xfer **ppxfer,
810 const struct usb_config *setup_start, uint16_t n_setup,
811 void *priv_sc, struct mtx *xfer_mtx)
813 struct usb_xfer dummy;
814 struct usb_setup_params parm;
815 const struct usb_config *setup_end = setup_start + n_setup;
816 const struct usb_config *setup;
817 struct usb_endpoint *ep;
818 struct usb_xfer_root *info;
819 struct usb_xfer *xfer;
828 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
829 "usbd_transfer_setup can sleep!");
831 /* do some checking first */
834 DPRINTFN(6, "setup array has zero length!\n");
835 return (USB_ERR_INVAL);
838 DPRINTFN(6, "ifaces array is NULL!\n");
839 return (USB_ERR_INVAL);
841 if (xfer_mtx == NULL) {
842 DPRINTFN(6, "using global lock\n");
846 for (setup = setup_start, n = 0;
847 setup != setup_end; setup++, n++) {
848 if (setup->bufsize == (usb_frlength_t)-1) {
849 parm.err = USB_ERR_BAD_BUFSIZE;
850 DPRINTF("invalid bufsize\n");
852 if (setup->callback == NULL) {
853 parm.err = USB_ERR_NO_CALLBACK;
854 DPRINTF("no callback\n");
862 memset(&parm, 0, sizeof(parm));
865 parm.speed = usbd_get_speed(udev);
866 parm.hc_max_packet_count = 1;
868 if (parm.speed >= USB_SPEED_MAX) {
869 parm.err = USB_ERR_INVAL;
872 /* setup all transfers */
878 * Initialize the "usb_xfer_root" structure,
879 * which is common for all our USB transfers.
881 info = USB_ADD_BYTES(buf, 0);
883 info->memory_base = buf;
884 info->memory_size = parm.size[0];
887 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
888 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
890 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
891 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
893 cv_init(&info->cv_drain, "WDRAIN");
895 info->xfer_mtx = xfer_mtx;
897 usb_dma_tag_setup(&info->dma_parent_tag,
898 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
899 xfer_mtx, &usb_bdma_done_event, 32, parm.dma_tag_max);
902 info->bus = udev->bus;
905 TAILQ_INIT(&info->done_q.head);
906 info->done_q.command = &usbd_callback_wrapper;
908 TAILQ_INIT(&info->dma_q.head);
909 info->dma_q.command = &usb_bdma_work_loop;
911 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
912 info->done_m[0].xroot = info;
913 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
914 info->done_m[1].xroot = info;
917 * In device side mode control endpoint
918 * requests need to run from a separate
919 * context, else there is a chance of
922 if (setup_start == usb_control_ep_cfg)
924 &udev->bus->control_xfer_proc;
925 else if (xfer_mtx == &Giant)
927 &udev->bus->giant_callback_proc;
930 &udev->bus->non_giant_callback_proc;
936 parm.size[0] += sizeof(info[0]);
938 for (setup = setup_start, n = 0;
939 setup != setup_end; setup++, n++) {
941 /* skip USB transfers without callbacks: */
942 if (setup->callback == NULL) {
945 /* see if there is a matching endpoint */
946 ep = usbd_get_endpoint(udev,
947 ifaces[setup->if_index], setup);
949 if ((ep == NULL) || (ep->methods == NULL)) {
950 if (setup->flags.no_pipe_ok)
952 if ((setup->usb_mode != USB_MODE_DUAL) &&
953 (setup->usb_mode != udev->flags.usb_mode))
955 parm.err = USB_ERR_NO_PIPE;
959 /* align data properly */
960 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
962 /* store current setup pointer */
963 parm.curr_setup = setup;
967 * Common initialization of the
968 * "usb_xfer" structure.
970 xfer = USB_ADD_BYTES(buf, parm.size[0]);
971 xfer->address = udev->address;
972 xfer->priv_sc = priv_sc;
975 usb_callout_init_mtx(&xfer->timeout_handle,
976 &udev->bus->bus_mtx, 0);
979 * Setup a dummy xfer, hence we are
980 * writing to the "usb_xfer"
981 * structure pointed to by "xfer"
982 * before we have allocated any
986 memset(&dummy, 0, sizeof(dummy));
990 /* set transfer endpoint pointer */
993 parm.size[0] += sizeof(xfer[0]);
994 parm.methods = xfer->endpoint->methods;
995 parm.curr_xfer = xfer;
998 * Call the Host or Device controller transfer
1001 (udev->bus->methods->xfer_setup) (&parm);
1003 /* check for error */
1009 * Increment the endpoint refcount. This
1010 * basically prevents setting a new
1011 * configuration and alternate setting
1012 * when USB transfers are in use on
1013 * the given interface. Search the USB
1014 * code for "endpoint->refcount_alloc" if you
1015 * want more information.
1017 USB_BUS_LOCK(info->bus);
1018 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1019 parm.err = USB_ERR_INVAL;
1021 xfer->endpoint->refcount_alloc++;
1023 if (xfer->endpoint->refcount_alloc == 0)
1024 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1025 USB_BUS_UNLOCK(info->bus);
1028 * Whenever we set ppxfer[] then we
1029 * also need to increment the
1032 info->setup_refcount++;
1035 * Transfer is successfully setup and
1041 /* check for error */
1046 if (buf || parm.err) {
1049 if (refcount == 0) {
1050 /* no transfers - nothing to do ! */
1053 /* align data properly */
1054 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1056 /* store offset temporarily */
1057 parm.size[1] = parm.size[0];
1060 * The number of DMA tags required depends on
1061 * the number of endpoints. The current estimate
1062 * for maximum number of DMA tags per endpoint
1065 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1068 * DMA tags for QH, TD, Data and more.
1070 parm.dma_tag_max += 8;
1072 parm.dma_tag_p += parm.dma_tag_max;
1074 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1077 /* align data properly */
1078 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1080 /* store offset temporarily */
1081 parm.size[3] = parm.size[0];
1083 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1086 /* align data properly */
1087 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1089 /* store offset temporarily */
1090 parm.size[4] = parm.size[0];
1092 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1095 /* store end offset temporarily */
1096 parm.size[5] = parm.size[0];
1098 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1101 /* store end offset temporarily */
1103 parm.size[2] = parm.size[0];
1105 /* align data properly */
1106 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1108 parm.size[6] = parm.size[0];
1110 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1113 /* align data properly */
1114 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1116 /* allocate zeroed memory */
1117 buf = malloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1120 parm.err = USB_ERR_NOMEM;
1121 DPRINTFN(0, "cannot allocate memory block for "
1122 "configuration (%d bytes)\n",
1126 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1127 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1128 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1129 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1130 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1135 if (info->setup_refcount == 0) {
1137 * "usbd_transfer_unsetup_sub" will unlock
1138 * the bus mutex before returning !
1140 USB_BUS_LOCK(info->bus);
1142 /* something went wrong */
1143 usbd_transfer_unsetup_sub(info, 0);
1147 usbd_transfer_unsetup(ppxfer, n_setup);
1152 /*------------------------------------------------------------------------*
1153 * usbd_transfer_unsetup_sub - factored out code
1154 *------------------------------------------------------------------------*/
1156 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1159 struct usb_page_cache *pc;
1162 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1164 /* wait for any outstanding DMA operations */
1168 temp = usbd_get_dma_delay(info->udev);
1170 usb_pause_mtx(&info->bus->bus_mtx,
1171 USB_MS_TO_TICKS(temp));
1175 /* make sure that our done messages are not queued anywhere */
1176 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1178 USB_BUS_UNLOCK(info->bus);
1181 /* free DMA'able memory, if any */
1182 pc = info->dma_page_cache_start;
1183 while (pc != info->dma_page_cache_end) {
1184 usb_pc_free_mem(pc);
1188 /* free DMA maps in all "xfer->frbuffers" */
1189 pc = info->xfer_page_cache_start;
1190 while (pc != info->xfer_page_cache_end) {
1191 usb_pc_dmamap_destroy(pc);
1195 /* free all DMA tags */
1196 usb_dma_tag_unsetup(&info->dma_parent_tag);
1199 cv_destroy(&info->cv_drain);
1202 * free the "memory_base" last, hence the "info" structure is
1203 * contained within the "memory_base"!
1205 free(info->memory_base, M_USB);
1208 /*------------------------------------------------------------------------*
1209 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1211 * NOTE: All USB transfers in progress will get called back passing
1212 * the error code "USB_ERR_CANCELLED" before this function
1214 *------------------------------------------------------------------------*/
1216 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1218 struct usb_xfer *xfer;
1219 struct usb_xfer_root *info;
1220 uint8_t needs_delay = 0;
1222 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1223 "usbd_transfer_unsetup can sleep!");
1226 xfer = pxfer[n_setup];
1233 USB_XFER_LOCK(xfer);
1234 USB_BUS_LOCK(info->bus);
1237 * HINT: when you start/stop a transfer, it might be a
1238 * good idea to directly use the "pxfer[]" structure:
1240 * usbd_transfer_start(sc->pxfer[0]);
1241 * usbd_transfer_stop(sc->pxfer[0]);
1243 * That way, if your code has many parts that will not
1244 * stop running under the same lock, in other words
1245 * "xfer_mtx", the usbd_transfer_start and
1246 * usbd_transfer_stop functions will simply return
1247 * when they detect a NULL pointer argument.
1249 * To avoid any races we clear the "pxfer[]" pointer
1250 * while holding the private mutex of the driver:
1252 pxfer[n_setup] = NULL;
1254 USB_BUS_UNLOCK(info->bus);
1255 USB_XFER_UNLOCK(xfer);
1257 usbd_transfer_drain(xfer);
1260 if (xfer->flags_int.bdma_enable)
1264 * NOTE: default endpoint does not have an
1265 * interface, even if endpoint->iface_index == 0
1267 USB_BUS_LOCK(info->bus);
1268 xfer->endpoint->refcount_alloc--;
1269 USB_BUS_UNLOCK(info->bus);
1271 usb_callout_drain(&xfer->timeout_handle);
1273 USB_BUS_LOCK(info->bus);
1275 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1276 "reference count\n"));
1278 info->setup_refcount--;
1280 if (info->setup_refcount == 0) {
1281 usbd_transfer_unsetup_sub(info,
1284 USB_BUS_UNLOCK(info->bus);
1289 /*------------------------------------------------------------------------*
1290 * usbd_control_transfer_init - factored out code
1292 * In USB Device Mode we have to wait for the SETUP packet which
1293 * containst the "struct usb_device_request" structure, before we can
1294 * transfer any data. In USB Host Mode we already have the SETUP
1295 * packet at the moment the USB transfer is started. This leads us to
1296 * having to setup the USB transfer at two different places in
1297 * time. This function just contains factored out control transfer
1298 * initialisation code, so that we don't duplicate the code.
1299 *------------------------------------------------------------------------*/
1301 usbd_control_transfer_init(struct usb_xfer *xfer)
1303 struct usb_device_request req;
1305 /* copy out the USB request header */
1307 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1309 /* setup remainder */
1311 xfer->flags_int.control_rem = UGETW(req.wLength);
1313 /* copy direction to endpoint variable */
1315 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1317 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1320 /*------------------------------------------------------------------------*
1321 * usbd_setup_ctrl_transfer
1323 * This function handles initialisation of control transfers. Control
1324 * transfers are special in that regard that they can both transmit
1330 *------------------------------------------------------------------------*/
1332 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1336 /* Check for control endpoint stall */
1337 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1338 /* the control transfer is no longer active */
1339 xfer->flags_int.control_stall = 1;
1340 xfer->flags_int.control_act = 0;
1342 /* don't stall control transfer by default */
1343 xfer->flags_int.control_stall = 0;
1346 /* Check for invalid number of frames */
1347 if (xfer->nframes > 2) {
1349 * If you need to split a control transfer, you
1350 * have to do one part at a time. Only with
1351 * non-control transfers you can do multiple
1354 DPRINTFN(0, "Too many frames: %u\n",
1355 (unsigned int)xfer->nframes);
1360 * Check if there is a control
1361 * transfer in progress:
1363 if (xfer->flags_int.control_act) {
1365 if (xfer->flags_int.control_hdr) {
1367 /* clear send header flag */
1369 xfer->flags_int.control_hdr = 0;
1371 /* setup control transfer */
1372 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1373 usbd_control_transfer_init(xfer);
1376 /* get data length */
1382 /* the size of the SETUP structure is hardcoded ! */
1384 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1385 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1386 xfer->frlengths[0], sizeof(struct
1387 usb_device_request));
1390 /* check USB mode */
1391 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1393 /* check number of frames */
1394 if (xfer->nframes != 1) {
1396 * We need to receive the setup
1397 * message first so that we know the
1400 DPRINTF("Misconfigured transfer\n");
1404 * Set a dummy "control_rem" value. This
1405 * variable will be overwritten later by a
1406 * call to "usbd_control_transfer_init()" !
1408 xfer->flags_int.control_rem = 0xFFFF;
1411 /* setup "endpoint" and "control_rem" */
1413 usbd_control_transfer_init(xfer);
1416 /* set transfer-header flag */
1418 xfer->flags_int.control_hdr = 1;
1420 /* get data length */
1422 len = (xfer->sumlen - sizeof(struct usb_device_request));
1425 /* check if there is a length mismatch */
1427 if (len > xfer->flags_int.control_rem) {
1428 DPRINTFN(0, "Length (%d) greater than "
1429 "remaining length (%d)\n", len,
1430 xfer->flags_int.control_rem);
1433 /* check if we are doing a short transfer */
1435 if (xfer->flags.force_short_xfer) {
1436 xfer->flags_int.control_rem = 0;
1438 if ((len != xfer->max_data_length) &&
1439 (len != xfer->flags_int.control_rem) &&
1440 (xfer->nframes != 1)) {
1441 DPRINTFN(0, "Short control transfer without "
1442 "force_short_xfer set\n");
1445 xfer->flags_int.control_rem -= len;
1448 /* the status part is executed when "control_act" is 0 */
1450 if ((xfer->flags_int.control_rem > 0) ||
1451 (xfer->flags.manual_status)) {
1452 /* don't execute the STATUS stage yet */
1453 xfer->flags_int.control_act = 1;
1456 if ((!xfer->flags_int.control_hdr) &&
1457 (xfer->nframes == 1)) {
1459 * This is not a valid operation!
1461 DPRINTFN(0, "Invalid parameter "
1466 /* time to execute the STATUS stage */
1467 xfer->flags_int.control_act = 0;
1469 return (0); /* success */
1472 return (1); /* failure */
1475 /*------------------------------------------------------------------------*
1476 * usbd_transfer_submit - start USB hardware for the given transfer
1478 * This function should only be called from the USB callback.
1479 *------------------------------------------------------------------------*/
1481 usbd_transfer_submit(struct usb_xfer *xfer)
1483 struct usb_xfer_root *info;
1484 struct usb_bus *bus;
1490 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1491 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1495 if (USB_DEBUG_VAR > 0) {
1498 usb_dump_endpoint(xfer->endpoint);
1500 USB_BUS_UNLOCK(bus);
1504 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1505 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1507 /* Only open the USB transfer once! */
1508 if (!xfer->flags_int.open) {
1509 xfer->flags_int.open = 1;
1514 (xfer->endpoint->methods->open) (xfer);
1515 USB_BUS_UNLOCK(bus);
1517 /* set "transferring" flag */
1518 xfer->flags_int.transferring = 1;
1521 /* increment power reference */
1522 usbd_transfer_power_ref(xfer, 1);
1525 * Check if the transfer is waiting on a queue, most
1526 * frequently the "done_q":
1528 if (xfer->wait_queue) {
1530 usbd_transfer_dequeue(xfer);
1531 USB_BUS_UNLOCK(bus);
1533 /* clear "did_dma_delay" flag */
1534 xfer->flags_int.did_dma_delay = 0;
1536 /* clear "did_close" flag */
1537 xfer->flags_int.did_close = 0;
1540 /* clear "bdma_setup" flag */
1541 xfer->flags_int.bdma_setup = 0;
1543 /* by default we cannot cancel any USB transfer immediately */
1544 xfer->flags_int.can_cancel_immed = 0;
1546 /* clear lengths and frame counts by default */
1551 /* clear any previous errors */
1554 /* Check if the device is still alive */
1555 if (info->udev->state < USB_STATE_POWERED) {
1558 * Must return cancelled error code else
1559 * device drivers can hang.
1561 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1562 USB_BUS_UNLOCK(bus);
1567 if (xfer->nframes == 0) {
1568 if (xfer->flags.stall_pipe) {
1570 * Special case - want to stall without transferring
1573 DPRINTF("xfer=%p nframes=0: stall "
1574 "or clear stall!\n", xfer);
1576 xfer->flags_int.can_cancel_immed = 1;
1577 /* start the transfer */
1578 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1579 USB_BUS_UNLOCK(bus);
1583 usbd_transfer_done(xfer, USB_ERR_INVAL);
1584 USB_BUS_UNLOCK(bus);
1587 /* compute some variables */
1589 for (x = 0; x != xfer->nframes; x++) {
1590 /* make a copy of the frlenghts[] */
1591 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1592 /* compute total transfer length */
1593 xfer->sumlen += xfer->frlengths[x];
1594 if (xfer->sumlen < xfer->frlengths[x]) {
1595 /* length wrapped around */
1597 usbd_transfer_done(xfer, USB_ERR_INVAL);
1598 USB_BUS_UNLOCK(bus);
1603 /* clear some internal flags */
1605 xfer->flags_int.short_xfer_ok = 0;
1606 xfer->flags_int.short_frames_ok = 0;
1608 /* check if this is a control transfer */
1610 if (xfer->flags_int.control_xfr) {
1612 if (usbd_setup_ctrl_transfer(xfer)) {
1614 usbd_transfer_done(xfer, USB_ERR_STALLED);
1615 USB_BUS_UNLOCK(bus);
1620 * Setup filtered version of some transfer flags,
1621 * in case of data read direction
1623 if (USB_GET_DATA_ISREAD(xfer)) {
1625 if (xfer->flags.short_frames_ok) {
1626 xfer->flags_int.short_xfer_ok = 1;
1627 xfer->flags_int.short_frames_ok = 1;
1628 } else if (xfer->flags.short_xfer_ok) {
1629 xfer->flags_int.short_xfer_ok = 1;
1631 /* check for control transfer */
1632 if (xfer->flags_int.control_xfr) {
1634 * 1) Control transfers do not support
1635 * reception of multiple short USB
1636 * frames in host mode and device side
1637 * mode, with exception of:
1639 * 2) Due to sometimes buggy device
1640 * side firmware we need to do a
1641 * STATUS stage in case of short
1642 * control transfers in USB host mode.
1643 * The STATUS stage then becomes the
1644 * "alt_next" to the DATA stage.
1646 xfer->flags_int.short_frames_ok = 1;
1651 * Check if BUS-DMA support is enabled and try to load virtual
1652 * buffers into DMA, if any:
1655 if (xfer->flags_int.bdma_enable) {
1656 /* insert the USB transfer last in the BUS-DMA queue */
1657 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1662 * Enter the USB transfer into the Host Controller or
1663 * Device Controller schedule:
1665 usbd_pipe_enter(xfer);
1668 /*------------------------------------------------------------------------*
1669 * usbd_pipe_enter - factored out code
1670 *------------------------------------------------------------------------*/
1672 usbd_pipe_enter(struct usb_xfer *xfer)
1674 struct usb_endpoint *ep;
1676 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1678 USB_BUS_LOCK(xfer->xroot->bus);
1680 ep = xfer->endpoint;
1684 /* the transfer can now be cancelled */
1685 xfer->flags_int.can_cancel_immed = 1;
1687 /* enter the transfer */
1688 (ep->methods->enter) (xfer);
1690 /* check for transfer error */
1692 /* some error has happened */
1693 usbd_transfer_done(xfer, 0);
1694 USB_BUS_UNLOCK(xfer->xroot->bus);
1698 /* start the transfer */
1699 usb_command_wrapper(&ep->endpoint_q, xfer);
1700 USB_BUS_UNLOCK(xfer->xroot->bus);
1703 /*------------------------------------------------------------------------*
1704 * usbd_transfer_start - start an USB transfer
1706 * NOTE: Calling this function more than one time will only
1707 * result in a single transfer start, until the USB transfer
1709 *------------------------------------------------------------------------*/
1711 usbd_transfer_start(struct usb_xfer *xfer)
1714 /* transfer is gone */
1717 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1719 /* mark the USB transfer started */
1721 if (!xfer->flags_int.started) {
1722 /* lock the BUS lock to avoid races updating flags_int */
1723 USB_BUS_LOCK(xfer->xroot->bus);
1724 xfer->flags_int.started = 1;
1725 USB_BUS_UNLOCK(xfer->xroot->bus);
1727 /* check if the USB transfer callback is already transferring */
1729 if (xfer->flags_int.transferring) {
1732 USB_BUS_LOCK(xfer->xroot->bus);
1733 /* call the USB transfer callback */
1734 usbd_callback_ss_done_defer(xfer);
1735 USB_BUS_UNLOCK(xfer->xroot->bus);
1738 /*------------------------------------------------------------------------*
1739 * usbd_transfer_stop - stop an USB transfer
1741 * NOTE: Calling this function more than one time will only
1742 * result in a single transfer stop.
1743 * NOTE: When this function returns it is not safe to free nor
1744 * reuse any DMA buffers. See "usbd_transfer_drain()".
1745 *------------------------------------------------------------------------*/
1747 usbd_transfer_stop(struct usb_xfer *xfer)
1749 struct usb_endpoint *ep;
1752 /* transfer is gone */
1755 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1757 /* check if the USB transfer was ever opened */
1759 if (!xfer->flags_int.open) {
1760 if (xfer->flags_int.started) {
1761 /* nothing to do except clearing the "started" flag */
1762 /* lock the BUS lock to avoid races updating flags_int */
1763 USB_BUS_LOCK(xfer->xroot->bus);
1764 xfer->flags_int.started = 0;
1765 USB_BUS_UNLOCK(xfer->xroot->bus);
1769 /* try to stop the current USB transfer */
1771 USB_BUS_LOCK(xfer->xroot->bus);
1772 /* override any previous error */
1773 xfer->error = USB_ERR_CANCELLED;
1776 * Clear "open" and "started" when both private and USB lock
1777 * is locked so that we don't get a race updating "flags_int"
1779 xfer->flags_int.open = 0;
1780 xfer->flags_int.started = 0;
1783 * Check if we can cancel the USB transfer immediately.
1785 if (xfer->flags_int.transferring) {
1786 if (xfer->flags_int.can_cancel_immed &&
1787 (!xfer->flags_int.did_close)) {
1790 * The following will lead to an USB_ERR_CANCELLED
1791 * error code being passed to the USB callback.
1793 (xfer->endpoint->methods->close) (xfer);
1794 /* only close once */
1795 xfer->flags_int.did_close = 1;
1797 /* need to wait for the next done callback */
1802 /* close here and now */
1803 (xfer->endpoint->methods->close) (xfer);
1806 * Any additional DMA delay is done by
1807 * "usbd_transfer_unsetup()".
1811 * Special case. Check if we need to restart a blocked
1814 ep = xfer->endpoint;
1817 * If the current USB transfer is completing we need
1818 * to start the next one:
1820 if (ep->endpoint_q.curr == xfer) {
1821 usb_command_wrapper(&ep->endpoint_q, NULL);
1825 USB_BUS_UNLOCK(xfer->xroot->bus);
1828 /*------------------------------------------------------------------------*
1829 * usbd_transfer_pending
1831 * This function will check if an USB transfer is pending which is a
1832 * little bit complicated!
1835 * 1: Pending: The USB transfer will receive a callback in the future.
1836 *------------------------------------------------------------------------*/
1838 usbd_transfer_pending(struct usb_xfer *xfer)
1840 struct usb_xfer_root *info;
1841 struct usb_xfer_queue *pq;
1844 /* transfer is gone */
1847 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1849 if (xfer->flags_int.transferring) {
1853 USB_BUS_LOCK(xfer->xroot->bus);
1854 if (xfer->wait_queue) {
1855 /* we are waiting on a queue somewhere */
1856 USB_BUS_UNLOCK(xfer->xroot->bus);
1862 if (pq->curr == xfer) {
1863 /* we are currently scheduled for callback */
1864 USB_BUS_UNLOCK(xfer->xroot->bus);
1867 /* we are not pending */
1868 USB_BUS_UNLOCK(xfer->xroot->bus);
1872 /*------------------------------------------------------------------------*
1873 * usbd_transfer_drain
1875 * This function will stop the USB transfer and wait for any
1876 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1877 * are loaded into DMA can safely be freed or reused after that this
1878 * function has returned.
1879 *------------------------------------------------------------------------*/
1881 usbd_transfer_drain(struct usb_xfer *xfer)
1883 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1884 "usbd_transfer_drain can sleep!");
1887 /* transfer is gone */
1890 if (xfer->xroot->xfer_mtx != &Giant) {
1891 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1893 USB_XFER_LOCK(xfer);
1895 usbd_transfer_stop(xfer);
1897 while (usbd_transfer_pending(xfer) ||
1898 xfer->flags_int.doing_callback) {
1901 * It is allowed that the callback can drop its
1902 * transfer mutex. In that case checking only
1903 * "usbd_transfer_pending()" is not enough to tell if
1904 * the USB transfer is fully drained. We also need to
1905 * check the internal "doing_callback" flag.
1907 xfer->flags_int.draining = 1;
1910 * Wait until the current outstanding USB
1911 * transfer is complete !
1913 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1915 USB_XFER_UNLOCK(xfer);
1918 struct usb_page_cache *
1919 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1921 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1923 return (&xfer->frbuffers[frindex]);
1926 /*------------------------------------------------------------------------*
1927 * usbd_xfer_get_fps_shift
1929 * The following function is only useful for isochronous transfers. It
1930 * returns how many times the frame execution rate has been shifted
1936 *------------------------------------------------------------------------*/
1938 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1940 return (xfer->fps_shift);
1944 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1946 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1948 return (xfer->frlengths[frindex]);
1951 /*------------------------------------------------------------------------*
1952 * usbd_xfer_set_frame_data
1954 * This function sets the pointer of the buffer that should
1955 * loaded directly into DMA for the given USB frame. Passing "ptr"
1956 * equal to NULL while the corresponding "frlength" is greater
1957 * than zero gives undefined results!
1958 *------------------------------------------------------------------------*/
1960 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1961 void *ptr, usb_frlength_t len)
1963 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1965 /* set virtual address to load and length */
1966 xfer->frbuffers[frindex].buffer = ptr;
1967 usbd_xfer_set_frame_len(xfer, frindex, len);
1971 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1972 void **ptr, int *len)
1974 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1977 *ptr = xfer->frbuffers[frindex].buffer;
1979 *len = xfer->frlengths[frindex];
1982 /*------------------------------------------------------------------------*
1983 * usbd_xfer_old_frame_length
1985 * This function returns the framelength of the given frame at the
1986 * time the transfer was submitted. This function can be used to
1987 * compute the starting data pointer of the next isochronous frame
1988 * when an isochronous transfer has completed.
1989 *------------------------------------------------------------------------*/
1991 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
1993 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1995 return (xfer->frlengths[frindex + xfer->max_frame_count]);
1999 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2003 *actlen = xfer->actlen;
2005 *sumlen = xfer->sumlen;
2006 if (aframes != NULL)
2007 *aframes = xfer->aframes;
2008 if (nframes != NULL)
2009 *nframes = xfer->nframes;
2012 /*------------------------------------------------------------------------*
2013 * usbd_xfer_set_frame_offset
2015 * This function sets the frame data buffer offset relative to the beginning
2016 * of the USB DMA buffer allocated for this USB transfer.
2017 *------------------------------------------------------------------------*/
2019 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2020 usb_frcount_t frindex)
2022 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2023 "when the USB buffer is external\n"));
2024 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2026 /* set virtual address to load */
2027 xfer->frbuffers[frindex].buffer =
2028 USB_ADD_BYTES(xfer->local_buffer, offset);
2032 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2038 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2044 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2050 usbd_xfer_max_frames(struct usb_xfer *xfer)
2052 return (xfer->max_frame_count);
2056 usbd_xfer_max_len(struct usb_xfer *xfer)
2058 return (xfer->max_data_length);
2062 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2064 return (xfer->max_frame_size);
2068 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2071 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2073 xfer->frlengths[frindex] = len;
2076 /*------------------------------------------------------------------------*
2077 * usb_callback_proc - factored out code
2079 * This function performs USB callbacks.
2080 *------------------------------------------------------------------------*/
2082 usb_callback_proc(struct usb_proc_msg *_pm)
2084 struct usb_done_msg *pm = (void *)_pm;
2085 struct usb_xfer_root *info = pm->xroot;
2087 /* Change locking order */
2088 USB_BUS_UNLOCK(info->bus);
2091 * We exploit the fact that the mutex is the same for all
2092 * callbacks that will be called from this thread:
2094 mtx_lock(info->xfer_mtx);
2095 USB_BUS_LOCK(info->bus);
2097 /* Continue where we lost track */
2098 usb_command_wrapper(&info->done_q,
2101 mtx_unlock(info->xfer_mtx);
2104 /*------------------------------------------------------------------------*
2105 * usbd_callback_ss_done_defer
2107 * This function will defer the start, stop and done callback to the
2109 *------------------------------------------------------------------------*/
2111 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2113 struct usb_xfer_root *info = xfer->xroot;
2114 struct usb_xfer_queue *pq = &info->done_q;
2116 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2118 if (pq->curr != xfer) {
2119 usbd_transfer_enqueue(pq, xfer);
2121 if (!pq->recurse_1) {
2124 * We have to postpone the callback due to the fact we
2125 * will have a Lock Order Reversal, LOR, if we try to
2128 if (usb_proc_msignal(info->done_p,
2129 &info->done_m[0], &info->done_m[1])) {
2133 /* clear second recurse flag */
2140 /*------------------------------------------------------------------------*
2141 * usbd_callback_wrapper
2143 * This is a wrapper for USB callbacks. This wrapper does some
2144 * auto-magic things like figuring out if we can call the callback
2145 * directly from the current context or if we need to wakeup the
2146 * interrupt process.
2147 *------------------------------------------------------------------------*/
2149 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2151 struct usb_xfer *xfer = pq->curr;
2152 struct usb_xfer_root *info = xfer->xroot;
2154 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2155 if (!mtx_owned(info->xfer_mtx)) {
2157 * Cases that end up here:
2159 * 5) HW interrupt done callback or other source.
2161 DPRINTFN(3, "case 5\n");
2164 * We have to postpone the callback due to the fact we
2165 * will have a Lock Order Reversal, LOR, if we try to
2168 if (usb_proc_msignal(info->done_p,
2169 &info->done_m[0], &info->done_m[1])) {
2175 * Cases that end up here:
2177 * 1) We are starting a transfer
2178 * 2) We are prematurely calling back a transfer
2179 * 3) We are stopping a transfer
2180 * 4) We are doing an ordinary callback
2182 DPRINTFN(3, "case 1-4\n");
2183 /* get next USB transfer in the queue */
2184 info->done_q.curr = NULL;
2186 /* set flag in case of drain */
2187 xfer->flags_int.doing_callback = 1;
2189 USB_BUS_UNLOCK(info->bus);
2190 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2192 /* set correct USB state for callback */
2193 if (!xfer->flags_int.transferring) {
2194 xfer->usb_state = USB_ST_SETUP;
2195 if (!xfer->flags_int.started) {
2196 /* we got stopped before we even got started */
2197 USB_BUS_LOCK(info->bus);
2202 if (usbd_callback_wrapper_sub(xfer)) {
2203 /* the callback has been deferred */
2204 USB_BUS_LOCK(info->bus);
2208 /* decrement power reference */
2209 usbd_transfer_power_ref(xfer, -1);
2211 xfer->flags_int.transferring = 0;
2214 xfer->usb_state = USB_ST_ERROR;
2216 /* set transferred state */
2217 xfer->usb_state = USB_ST_TRANSFERRED;
2219 /* sync DMA memory, if any */
2220 if (xfer->flags_int.bdma_enable &&
2221 (!xfer->flags_int.bdma_no_post_sync)) {
2222 usb_bdma_post_sync(xfer);
2229 if (xfer->usb_state != USB_ST_SETUP)
2230 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2232 /* call processing routine */
2233 (xfer->callback) (xfer, xfer->error);
2235 /* pickup the USB mutex again */
2236 USB_BUS_LOCK(info->bus);
2239 * Check if we got started after that we got cancelled, but
2240 * before we managed to do the callback.
2242 if ((!xfer->flags_int.open) &&
2243 (xfer->flags_int.started) &&
2244 (xfer->usb_state == USB_ST_ERROR)) {
2245 /* clear flag in case of drain */
2246 xfer->flags_int.doing_callback = 0;
2247 /* try to loop, but not recursivly */
2248 usb_command_wrapper(&info->done_q, xfer);
2253 /* clear flag in case of drain */
2254 xfer->flags_int.doing_callback = 0;
2257 * Check if we are draining.
2259 if (xfer->flags_int.draining &&
2260 (!xfer->flags_int.transferring)) {
2261 /* "usbd_transfer_drain()" is waiting for end of transfer */
2262 xfer->flags_int.draining = 0;
2263 cv_broadcast(&info->cv_drain);
2266 /* do the next callback, if any */
2267 usb_command_wrapper(&info->done_q,
2271 /*------------------------------------------------------------------------*
2272 * usb_dma_delay_done_cb
2274 * This function is called when the DMA delay has been exectuded, and
2275 * will make sure that the callback is called to complete the USB
2276 * transfer. This code path is ususally only used when there is an USB
2277 * error like USB_ERR_CANCELLED.
2278 *------------------------------------------------------------------------*/
2280 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2282 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2284 DPRINTFN(3, "Completed %p\n", xfer);
2286 /* queue callback for execution, again */
2287 usbd_transfer_done(xfer, 0);
2290 /*------------------------------------------------------------------------*
2291 * usbd_transfer_dequeue
2293 * - This function is used to remove an USB transfer from a USB
2296 * - This function can be called multiple times in a row.
2297 *------------------------------------------------------------------------*/
2299 usbd_transfer_dequeue(struct usb_xfer *xfer)
2301 struct usb_xfer_queue *pq;
2303 pq = xfer->wait_queue;
2305 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2306 xfer->wait_queue = NULL;
2310 /*------------------------------------------------------------------------*
2311 * usbd_transfer_enqueue
2313 * - This function is used to insert an USB transfer into a USB *
2316 * - This function can be called multiple times in a row.
2317 *------------------------------------------------------------------------*/
2319 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2322 * Insert the USB transfer into the queue, if it is not
2323 * already on a USB transfer queue:
2325 if (xfer->wait_queue == NULL) {
2326 xfer->wait_queue = pq;
2327 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2331 /*------------------------------------------------------------------------*
2332 * usbd_transfer_done
2334 * - This function is used to remove an USB transfer from the busdma,
2335 * pipe or interrupt queue.
2337 * - This function is used to queue the USB transfer on the done
2340 * - This function is used to stop any USB transfer timeouts.
2341 *------------------------------------------------------------------------*/
2343 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2345 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2347 DPRINTF("err=%s\n", usbd_errstr(error));
2350 * If we are not transferring then just return.
2351 * This can happen during transfer cancel.
2353 if (!xfer->flags_int.transferring) {
2354 DPRINTF("not transferring\n");
2355 /* end of control transfer, if any */
2356 xfer->flags_int.control_act = 0;
2359 /* only set transfer error if not already set */
2361 xfer->error = error;
2363 /* stop any callouts */
2364 usb_callout_stop(&xfer->timeout_handle);
2367 * If we are waiting on a queue, just remove the USB transfer
2368 * from the queue, if any. We should have the required locks
2369 * locked to do the remove when this function is called.
2371 usbd_transfer_dequeue(xfer);
2374 if (mtx_owned(xfer->xroot->xfer_mtx)) {
2375 struct usb_xfer_queue *pq;
2378 * If the private USB lock is not locked, then we assume
2379 * that the BUS-DMA load stage has been passed:
2381 pq = &xfer->xroot->dma_q;
2383 if (pq->curr == xfer) {
2384 /* start the next BUS-DMA load, if any */
2385 usb_command_wrapper(pq, NULL);
2389 /* keep some statistics */
2391 xfer->xroot->bus->stats_err.uds_requests
2392 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2394 xfer->xroot->bus->stats_ok.uds_requests
2395 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2398 /* call the USB transfer callback */
2399 usbd_callback_ss_done_defer(xfer);
2402 /*------------------------------------------------------------------------*
2403 * usbd_transfer_start_cb
2405 * This function is called to start the USB transfer when
2406 * "xfer->interval" is greater than zero, and and the endpoint type is
2408 *------------------------------------------------------------------------*/
2410 usbd_transfer_start_cb(void *arg)
2412 struct usb_xfer *xfer = arg;
2413 struct usb_endpoint *ep = xfer->endpoint;
2415 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2420 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2423 /* the transfer can now be cancelled */
2424 xfer->flags_int.can_cancel_immed = 1;
2426 /* start USB transfer, if no error */
2427 if (xfer->error == 0)
2428 (ep->methods->start) (xfer);
2430 /* check for transfer error */
2432 /* some error has happened */
2433 usbd_transfer_done(xfer, 0);
2437 /*------------------------------------------------------------------------*
2438 * usbd_xfer_set_stall
2440 * This function is used to set the stall flag outside the
2441 * callback. This function is NULL safe.
2442 *------------------------------------------------------------------------*/
2444 usbd_xfer_set_stall(struct usb_xfer *xfer)
2450 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2452 /* avoid any races by locking the USB mutex */
2453 USB_BUS_LOCK(xfer->xroot->bus);
2454 xfer->flags.stall_pipe = 1;
2455 USB_BUS_UNLOCK(xfer->xroot->bus);
2459 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2461 return (xfer->endpoint->is_stalled);
2464 /*------------------------------------------------------------------------*
2465 * usbd_transfer_clear_stall
2467 * This function is used to clear the stall flag outside the
2468 * callback. This function is NULL safe.
2469 *------------------------------------------------------------------------*/
2471 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2477 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2479 /* avoid any races by locking the USB mutex */
2480 USB_BUS_LOCK(xfer->xroot->bus);
2482 xfer->flags.stall_pipe = 0;
2484 USB_BUS_UNLOCK(xfer->xroot->bus);
2487 /*------------------------------------------------------------------------*
2490 * This function is used to add an USB transfer to the pipe transfer list.
2491 *------------------------------------------------------------------------*/
2493 usbd_pipe_start(struct usb_xfer_queue *pq)
2495 struct usb_endpoint *ep;
2496 struct usb_xfer *xfer;
2500 ep = xfer->endpoint;
2502 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2505 * If the endpoint is already stalled we do nothing !
2507 if (ep->is_stalled) {
2511 * Check if we are supposed to stall the endpoint:
2513 if (xfer->flags.stall_pipe) {
2514 struct usb_device *udev;
2515 struct usb_xfer_root *info;
2517 /* clear stall command */
2518 xfer->flags.stall_pipe = 0;
2520 /* get pointer to USB device */
2525 * Only stall BULK and INTERRUPT endpoints.
2527 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2528 if ((type == UE_BULK) ||
2529 (type == UE_INTERRUPT)) {
2534 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2535 (udev->bus->methods->set_stall) (
2536 udev, NULL, ep, &did_stall);
2537 } else if (udev->ctrl_xfer[1]) {
2538 info = udev->ctrl_xfer[1]->xroot;
2540 &info->bus->non_giant_callback_proc,
2541 &udev->cs_msg[0], &udev->cs_msg[1]);
2543 /* should not happen */
2544 DPRINTFN(0, "No stall handler\n");
2547 * Check if we should stall. Some USB hardware
2548 * handles set- and clear-stall in hardware.
2552 * The transfer will be continued when
2553 * the clear-stall control endpoint
2554 * message is received.
2559 } else if (type == UE_ISOCHRONOUS) {
2562 * Make sure any FIFO overflow or other FIFO
2563 * error conditions go away by resetting the
2564 * endpoint FIFO through the clear stall
2567 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2568 (udev->bus->methods->clear_stall) (udev, ep);
2572 /* Set or clear stall complete - special case */
2573 if (xfer->nframes == 0) {
2574 /* we are complete */
2576 usbd_transfer_done(xfer, 0);
2582 * 1) Start the first transfer queued.
2584 * 2) Re-start the current USB transfer.
2587 * Check if there should be any
2588 * pre transfer start delay:
2590 if (xfer->interval > 0) {
2591 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2592 if ((type == UE_BULK) ||
2593 (type == UE_CONTROL)) {
2594 usbd_transfer_timeout_ms(xfer,
2595 &usbd_transfer_start_cb,
2603 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2605 /* the transfer can now be cancelled */
2606 xfer->flags_int.can_cancel_immed = 1;
2608 /* start USB transfer, if no error */
2609 if (xfer->error == 0)
2610 (ep->methods->start) (xfer);
2612 /* check for transfer error */
2614 /* some error has happened */
2615 usbd_transfer_done(xfer, 0);
2619 /*------------------------------------------------------------------------*
2620 * usbd_transfer_timeout_ms
2622 * This function is used to setup a timeout on the given USB
2623 * transfer. If the timeout has been deferred the callback given by
2624 * "cb" will get called after "ms" milliseconds.
2625 *------------------------------------------------------------------------*/
2627 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2628 void (*cb) (void *arg), usb_timeout_t ms)
2630 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2633 usb_callout_reset(&xfer->timeout_handle,
2634 USB_MS_TO_TICKS(ms), cb, xfer);
2637 /*------------------------------------------------------------------------*
2638 * usbd_callback_wrapper_sub
2640 * - This function will update variables in an USB transfer after
2641 * that the USB transfer is complete.
2643 * - This function is used to start the next USB transfer on the
2644 * ep transfer queue, if any.
2646 * NOTE: In some special cases the USB transfer will not be removed from
2647 * the pipe queue, but remain first. To enforce USB transfer removal call
2648 * this function passing the error code "USB_ERR_CANCELLED".
2652 * Else: The callback has been deferred.
2653 *------------------------------------------------------------------------*/
2655 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2657 struct usb_endpoint *ep;
2658 struct usb_bus *bus;
2661 bus = xfer->xroot->bus;
2663 if ((!xfer->flags_int.open) &&
2664 (!xfer->flags_int.did_close)) {
2667 (xfer->endpoint->methods->close) (xfer);
2668 USB_BUS_UNLOCK(bus);
2669 /* only close once */
2670 xfer->flags_int.did_close = 1;
2671 return (1); /* wait for new callback */
2674 * If we have a non-hardware induced error we
2675 * need to do the DMA delay!
2677 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2678 (xfer->error == USB_ERR_CANCELLED ||
2679 xfer->error == USB_ERR_TIMEOUT ||
2680 bus->methods->start_dma_delay != NULL)) {
2684 /* only delay once */
2685 xfer->flags_int.did_dma_delay = 1;
2687 /* we can not cancel this delay */
2688 xfer->flags_int.can_cancel_immed = 0;
2690 temp = usbd_get_dma_delay(xfer->xroot->udev);
2692 DPRINTFN(3, "DMA delay, %u ms, "
2693 "on %p\n", temp, xfer);
2698 * Some hardware solutions have dedicated
2699 * events when it is safe to free DMA'ed
2700 * memory. For the other hardware platforms we
2701 * use a static delay.
2703 if (bus->methods->start_dma_delay != NULL) {
2704 (bus->methods->start_dma_delay) (xfer);
2706 usbd_transfer_timeout_ms(xfer,
2707 (void (*)(void *))&usb_dma_delay_done_cb,
2710 USB_BUS_UNLOCK(bus);
2711 return (1); /* wait for new callback */
2714 /* check actual number of frames */
2715 if (xfer->aframes > xfer->nframes) {
2716 if (xfer->error == 0) {
2717 panic("%s: actual number of frames, %d, is "
2718 "greater than initial number of frames, %d\n",
2719 __FUNCTION__, xfer->aframes, xfer->nframes);
2721 /* just set some valid value */
2722 xfer->aframes = xfer->nframes;
2725 /* compute actual length */
2728 for (x = 0; x != xfer->aframes; x++) {
2729 xfer->actlen += xfer->frlengths[x];
2733 * Frames that were not transferred get zero actual length in
2734 * case the USB device driver does not check the actual number
2735 * of frames transferred, "xfer->aframes":
2737 for (; x < xfer->nframes; x++) {
2738 usbd_xfer_set_frame_len(xfer, x, 0);
2741 /* check actual length */
2742 if (xfer->actlen > xfer->sumlen) {
2743 if (xfer->error == 0) {
2744 panic("%s: actual length, %d, is greater than "
2745 "initial length, %d\n",
2746 __FUNCTION__, xfer->actlen, xfer->sumlen);
2748 /* just set some valid value */
2749 xfer->actlen = xfer->sumlen;
2752 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2753 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2754 xfer->aframes, xfer->nframes);
2757 /* end of control transfer, if any */
2758 xfer->flags_int.control_act = 0;
2760 /* check if we should block the execution queue */
2761 if ((xfer->error != USB_ERR_CANCELLED) &&
2762 (xfer->flags.pipe_bof)) {
2763 DPRINTFN(2, "xfer=%p: Block On Failure "
2764 "on endpoint=%p\n", xfer, xfer->endpoint);
2768 /* check for short transfers */
2769 if (xfer->actlen < xfer->sumlen) {
2771 /* end of control transfer, if any */
2772 xfer->flags_int.control_act = 0;
2774 if (!xfer->flags_int.short_xfer_ok) {
2775 xfer->error = USB_ERR_SHORT_XFER;
2776 if (xfer->flags.pipe_bof) {
2777 DPRINTFN(2, "xfer=%p: Block On Failure on "
2778 "Short Transfer on endpoint %p.\n",
2779 xfer, xfer->endpoint);
2785 * Check if we are in the middle of a
2788 if (xfer->flags_int.control_act) {
2789 DPRINTFN(5, "xfer=%p: Control transfer "
2790 "active on endpoint=%p\n", xfer, xfer->endpoint);
2796 ep = xfer->endpoint;
2799 * If the current USB transfer is completing we need to start the
2803 if (ep->endpoint_q.curr == xfer) {
2804 usb_command_wrapper(&ep->endpoint_q, NULL);
2806 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2807 /* there is another USB transfer waiting */
2809 /* this is the last USB transfer */
2810 /* clear isochronous sync flag */
2811 xfer->endpoint->is_synced = 0;
2814 USB_BUS_UNLOCK(bus);
2819 /*------------------------------------------------------------------------*
2820 * usb_command_wrapper
2822 * This function is used to execute commands non-recursivly on an USB
2824 *------------------------------------------------------------------------*/
2826 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2830 * If the transfer is not already processing,
2833 if (pq->curr != xfer) {
2834 usbd_transfer_enqueue(pq, xfer);
2835 if (pq->curr != NULL) {
2836 /* something is already processing */
2837 DPRINTFN(6, "busy %p\n", pq->curr);
2842 /* Get next element in queue */
2846 if (!pq->recurse_1) {
2850 /* set both recurse flags */
2854 if (pq->curr == NULL) {
2855 xfer = TAILQ_FIRST(&pq->head);
2857 TAILQ_REMOVE(&pq->head, xfer,
2859 xfer->wait_queue = NULL;
2865 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2867 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2869 } while (!pq->recurse_2);
2871 /* clear first recurse flag */
2875 /* clear second recurse flag */
2880 /*------------------------------------------------------------------------*
2881 * usbd_ctrl_transfer_setup
2883 * This function is used to setup the default USB control endpoint
2885 *------------------------------------------------------------------------*/
2887 usbd_ctrl_transfer_setup(struct usb_device *udev)
2889 struct usb_xfer *xfer;
2891 uint8_t iface_index;
2893 /* check for root HUB */
2894 if (udev->parent_hub == NULL)
2898 xfer = udev->ctrl_xfer[0];
2900 USB_XFER_LOCK(xfer);
2902 ((xfer->address == udev->address) &&
2903 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2904 udev->ddesc.bMaxPacketSize));
2905 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2908 * NOTE: checking "xfer->address" and
2909 * starting the USB transfer must be
2912 usbd_transfer_start(xfer);
2915 USB_XFER_UNLOCK(xfer);
2922 * All parameters are exactly the same like before.
2928 * Update wMaxPacketSize for the default control endpoint:
2930 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2931 udev->ddesc.bMaxPacketSize;
2934 * Unsetup any existing USB transfer:
2936 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2939 * Reset clear stall error counter.
2941 udev->clear_stall_errors = 0;
2944 * Try to setup a new USB transfer for the
2945 * default control endpoint:
2948 if (usbd_transfer_setup(udev, &iface_index,
2949 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2950 &udev->device_mtx)) {
2951 DPRINTFN(0, "could not setup default "
2958 /*------------------------------------------------------------------------*
2959 * usbd_clear_data_toggle - factored out code
2961 * NOTE: the intention of this function is not to reset the hardware
2963 *------------------------------------------------------------------------*/
2965 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2967 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
2969 /* check that we have a valid case */
2970 if (udev->flags.usb_mode == USB_MODE_HOST &&
2971 udev->parent_hub != NULL &&
2972 udev->bus->methods->clear_stall != NULL &&
2973 ep->methods != NULL) {
2974 (udev->bus->methods->clear_stall) (udev, ep);
2978 /*------------------------------------------------------------------------*
2979 * usbd_clear_data_toggle - factored out code
2981 * NOTE: the intention of this function is not to reset the hardware
2982 * data toggle on the USB device side.
2983 *------------------------------------------------------------------------*/
2985 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2987 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2989 USB_BUS_LOCK(udev->bus);
2990 ep->toggle_next = 0;
2991 /* some hardware needs a callback to clear the data toggle */
2992 usbd_clear_stall_locked(udev, ep);
2993 USB_BUS_UNLOCK(udev->bus);
2996 /*------------------------------------------------------------------------*
2997 * usbd_clear_stall_callback - factored out clear stall callback
3000 * xfer1: Clear Stall Control Transfer
3001 * xfer2: Stalled USB Transfer
3003 * This function is NULL safe.
3009 * Clear stall config example:
3011 * static const struct usb_config my_clearstall = {
3012 * .type = UE_CONTROL,
3014 * .direction = UE_DIR_ANY,
3015 * .interval = 50, //50 milliseconds
3016 * .bufsize = sizeof(struct usb_device_request),
3017 * .timeout = 1000, //1.000 seconds
3018 * .callback = &my_clear_stall_callback, // **
3019 * .usb_mode = USB_MODE_HOST,
3022 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3023 * passing the correct parameters.
3024 *------------------------------------------------------------------------*/
3026 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3027 struct usb_xfer *xfer2)
3029 struct usb_device_request req;
3031 if (xfer2 == NULL) {
3032 /* looks like we are tearing down */
3033 DPRINTF("NULL input parameter\n");
3036 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3037 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3039 switch (USB_GET_STATE(xfer1)) {
3043 * pre-clear the data toggle to DATA0 ("umass.c" and
3044 * "ata-usb.c" depends on this)
3047 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3049 /* setup a clear-stall packet */
3051 req.bmRequestType = UT_WRITE_ENDPOINT;
3052 req.bRequest = UR_CLEAR_FEATURE;
3053 USETW(req.wValue, UF_ENDPOINT_HALT);
3054 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3056 USETW(req.wLength, 0);
3059 * "usbd_transfer_setup_sub()" will ensure that
3060 * we have sufficient room in the buffer for
3061 * the request structure!
3064 /* copy in the transfer */
3066 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3069 xfer1->frlengths[0] = sizeof(req);
3072 usbd_transfer_submit(xfer1);
3075 case USB_ST_TRANSFERRED:
3078 default: /* Error */
3079 if (xfer1->error == USB_ERR_CANCELLED) {
3084 return (1); /* Clear Stall Finished */
3087 /*------------------------------------------------------------------------*
3088 * usbd_transfer_poll
3090 * The following function gets called from the USB keyboard driver and
3091 * UMASS when the system has paniced.
3093 * NOTE: It is currently not possible to resume normal operation on
3094 * the USB controller which has been polled, due to clearing of the
3095 * "up_dsleep" and "up_msleep" flags.
3096 *------------------------------------------------------------------------*/
3098 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3100 struct usb_xfer *xfer;
3101 struct usb_xfer_root *xroot;
3102 struct usb_device *udev;
3103 struct usb_proc_msg *pm;
3108 for (n = 0; n != max; n++) {
3109 /* Extra checks to avoid panic */
3112 continue; /* no USB transfer */
3113 xroot = xfer->xroot;
3115 continue; /* no USB root */
3118 continue; /* no USB device */
3119 if (udev->bus == NULL)
3120 continue; /* no BUS structure */
3121 if (udev->bus->methods == NULL)
3122 continue; /* no BUS methods */
3123 if (udev->bus->methods->xfer_poll == NULL)
3124 continue; /* no poll method */
3126 /* make sure that the BUS mutex is not locked */
3128 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3129 mtx_unlock(&xroot->udev->bus->bus_mtx);
3133 /* make sure that the transfer mutex is not locked */
3135 while (mtx_owned(xroot->xfer_mtx)) {
3136 mtx_unlock(xroot->xfer_mtx);
3140 /* Make sure cv_signal() and cv_broadcast() is not called */
3141 udev->bus->control_xfer_proc.up_msleep = 0;
3142 udev->bus->explore_proc.up_msleep = 0;
3143 udev->bus->giant_callback_proc.up_msleep = 0;
3144 udev->bus->non_giant_callback_proc.up_msleep = 0;
3146 /* poll USB hardware */
3147 (udev->bus->methods->xfer_poll) (udev->bus);
3149 USB_BUS_LOCK(xroot->bus);
3151 /* check for clear stall */
3152 if (udev->ctrl_xfer[1] != NULL) {
3154 /* poll clear stall start */
3155 pm = &udev->cs_msg[0].hdr;
3156 (pm->pm_callback) (pm);
3157 /* poll clear stall done thread */
3158 pm = &udev->ctrl_xfer[1]->
3159 xroot->done_m[0].hdr;
3160 (pm->pm_callback) (pm);
3163 /* poll done thread */
3164 pm = &xroot->done_m[0].hdr;
3165 (pm->pm_callback) (pm);
3167 USB_BUS_UNLOCK(xroot->bus);
3169 /* restore transfer mutex */
3171 mtx_lock(xroot->xfer_mtx);
3173 /* restore BUS mutex */
3175 mtx_lock(&xroot->udev->bus->bus_mtx);
3180 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3181 uint8_t type, enum usb_dev_speed speed)
3183 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3184 [USB_SPEED_LOW] = 8,
3185 [USB_SPEED_FULL] = 64,
3186 [USB_SPEED_HIGH] = 1024,
3187 [USB_SPEED_VARIABLE] = 1024,
3188 [USB_SPEED_SUPER] = 1024,
3191 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3192 [USB_SPEED_LOW] = 0, /* invalid */
3193 [USB_SPEED_FULL] = 1023,
3194 [USB_SPEED_HIGH] = 1024,
3195 [USB_SPEED_VARIABLE] = 3584,
3196 [USB_SPEED_SUPER] = 1024,
3199 static const uint16_t control_min[USB_SPEED_MAX] = {
3200 [USB_SPEED_LOW] = 8,
3201 [USB_SPEED_FULL] = 8,
3202 [USB_SPEED_HIGH] = 64,
3203 [USB_SPEED_VARIABLE] = 512,
3204 [USB_SPEED_SUPER] = 512,
3207 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3208 [USB_SPEED_LOW] = 8,
3209 [USB_SPEED_FULL] = 8,
3210 [USB_SPEED_HIGH] = 512,
3211 [USB_SPEED_VARIABLE] = 512,
3212 [USB_SPEED_SUPER] = 1024,
3217 memset(ptr, 0, sizeof(*ptr));
3221 ptr->range.max = intr_range_max[speed];
3223 case UE_ISOCHRONOUS:
3224 ptr->range.max = isoc_range_max[speed];
3227 if (type == UE_BULK)
3228 temp = bulk_min[speed];
3229 else /* UE_CONTROL */
3230 temp = control_min[speed];
3232 /* default is fixed */
3233 ptr->fixed[0] = temp;
3234 ptr->fixed[1] = temp;
3235 ptr->fixed[2] = temp;
3236 ptr->fixed[3] = temp;
3238 if (speed == USB_SPEED_FULL) {
3239 /* multiple sizes */
3244 if ((speed == USB_SPEED_VARIABLE) &&
3245 (type == UE_BULK)) {
3246 /* multiple sizes */
3247 ptr->fixed[2] = 1024;
3248 ptr->fixed[3] = 1536;
3255 usbd_xfer_softc(struct usb_xfer *xfer)
3257 return (xfer->priv_sc);
3261 usbd_xfer_get_priv(struct usb_xfer *xfer)
3263 return (xfer->priv_fifo);
3267 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3269 xfer->priv_fifo = ptr;
3273 usbd_xfer_state(struct usb_xfer *xfer)
3275 return (xfer->usb_state);
3279 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3282 case USB_FORCE_SHORT_XFER:
3283 xfer->flags.force_short_xfer = 1;
3285 case USB_SHORT_XFER_OK:
3286 xfer->flags.short_xfer_ok = 1;
3288 case USB_MULTI_SHORT_OK:
3289 xfer->flags.short_frames_ok = 1;
3291 case USB_MANUAL_STATUS:
3292 xfer->flags.manual_status = 1;
3298 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3301 case USB_FORCE_SHORT_XFER:
3302 xfer->flags.force_short_xfer = 0;
3304 case USB_SHORT_XFER_OK:
3305 xfer->flags.short_xfer_ok = 0;
3307 case USB_MULTI_SHORT_OK:
3308 xfer->flags.short_frames_ok = 0;
3310 case USB_MANUAL_STATUS:
3311 xfer->flags.manual_status = 0;
3317 * The following function returns in milliseconds when the isochronous
3318 * transfer was completed by the hardware. The returned value wraps
3319 * around 65536 milliseconds.
3322 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3324 return (xfer->isoc_time_complete);