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/param.h>
29 #include <sys/queue.h>
30 #include <sys/types.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
34 #include <sys/module.h>
36 #include <sys/mutex.h>
37 #include <sys/condvar.h>
38 #include <sys/sysctl.h>
39 #include <sys/unistd.h>
40 #include <sys/callout.h>
41 #include <sys/malloc.h>
45 #include <bus/u4b/usb.h>
46 #include <bus/u4b/usbdi.h>
47 #include <bus/u4b/usbdi_util.h>
49 #define USB_DEBUG_VAR usb_debug
51 #include <bus/u4b/usb_core.h>
52 #include <bus/u4b/usb_busdma.h>
53 #include <bus/u4b/usb_process.h>
54 #include <bus/u4b/usb_transfer.h>
55 #include <bus/u4b/usb_device.h>
56 #include <bus/u4b/usb_debug.h>
57 #include <bus/u4b/usb_util.h>
59 #include <bus/u4b/usb_controller.h>
60 #include <bus/u4b/usb_bus.h>
61 #include <bus/u4b/usb_pf.h>
63 struct usb_std_packet_size {
65 uint16_t min; /* inclusive */
66 uint16_t max; /* inclusive */
72 static usb_callback_t usb_request_callback;
74 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
76 /* This transfer is used for generic control endpoint transfers */
80 .endpoint = 0x00, /* Control endpoint */
81 .direction = UE_DIR_ANY,
82 .bufsize = USB_EP0_BUFSIZE, /* bytes */
83 .flags = {.proxy_buffer = 1,},
84 .callback = &usb_request_callback,
85 .usb_mode = USB_MODE_DUAL, /* both modes */
88 /* This transfer is used for generic clear stall only */
92 .endpoint = 0x00, /* Control pipe */
93 .direction = UE_DIR_ANY,
94 .bufsize = sizeof(struct usb_device_request),
95 .callback = &usb_do_clear_stall_callback,
96 .timeout = 1000, /* 1 second */
97 .interval = 50, /* 50ms */
98 .usb_mode = USB_MODE_HOST,
102 /* function prototypes */
104 static void usbd_update_max_frame_size(struct usb_xfer *);
105 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
106 static void usbd_control_transfer_init(struct usb_xfer *);
107 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
108 static void usb_callback_proc(struct usb_proc_msg *);
109 static void usbd_callback_ss_done_defer(struct usb_xfer *);
110 static void usbd_callback_wrapper(struct usb_xfer_queue *);
111 static void usbd_transfer_start_cb(void *);
112 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
113 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
114 uint8_t type, enum usb_dev_speed speed);
116 /*------------------------------------------------------------------------*
117 * usb_request_callback
118 *------------------------------------------------------------------------*/
120 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
122 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
123 usb_handle_request_callback(xfer, error);
125 usbd_do_request_callback(xfer, error);
128 /*------------------------------------------------------------------------*
129 * usbd_update_max_frame_size
131 * This function updates the maximum frame size, hence high speed USB
132 * can transfer multiple consecutive packets.
133 *------------------------------------------------------------------------*/
135 usbd_update_max_frame_size(struct usb_xfer *xfer)
137 /* compute maximum frame size */
138 /* this computation should not overflow 16-bit */
139 /* max = 15 * 1024 */
141 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
144 /*------------------------------------------------------------------------*
147 * The following function is called when we need to
148 * synchronize with DMA hardware.
151 * 0: no DMA delay required
152 * Else: milliseconds of DMA delay
153 *------------------------------------------------------------------------*/
155 usbd_get_dma_delay(struct usb_device *udev)
157 struct usb_bus_methods *mtod;
160 mtod = udev->bus->methods;
163 if (mtod->get_dma_delay) {
164 (mtod->get_dma_delay) (udev, &temp);
166 * Round up and convert to milliseconds. Note that we use
167 * 1024 milliseconds per second. to save a division.
175 /*------------------------------------------------------------------------*
176 * usbd_transfer_setup_sub_malloc
178 * This function will allocate one or more DMA'able memory chunks
179 * according to "size", "align" and "count" arguments. "ppc" is
180 * pointed to a linear array of USB page caches afterwards.
185 *------------------------------------------------------------------------*/
188 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
189 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
192 struct usb_page_cache *pc;
203 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
205 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 >= PAGE_SIZE) {
224 /* compute number of objects per page */
225 n_obj = (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 lockmgr(pc->tag_parent->lock, LK_EXCLUSIVE);
287 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
288 lockmgr(pc->tag_parent->lock, LK_RELEASE);
289 return (1); /* failure */
291 lockmgr(pc->tag_parent->lock, LK_RELEASE);
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 lock *xfer_lock)
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;
829 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
830 "usbd_transfer_setup can sleep!");
833 /* do some checking first */
836 DPRINTFN(6, "setup array has zero length!\n");
837 return (USB_ERR_INVAL);
840 DPRINTFN(6, "ifaces array is NULL!\n");
841 return (USB_ERR_INVAL);
843 if (xfer_lock == NULL) {
844 panic("xfer without lock!\n");
845 DPRINTFN(6, "using global lock\n");
848 for (setup = setup_start, n = 0;
849 setup != setup_end; setup++, n++) {
850 if (setup->bufsize == (usb_frlength_t)-1) {
851 parm.err = USB_ERR_BAD_BUFSIZE;
852 DPRINTF("invalid bufsize\n");
854 if (setup->callback == NULL) {
855 parm.err = USB_ERR_NO_CALLBACK;
856 DPRINTF("no callback\n");
864 memset(&parm, 0, sizeof(parm));
867 parm.speed = usbd_get_speed(udev);
868 parm.hc_max_packet_count = 1;
870 if (parm.speed >= USB_SPEED_MAX) {
871 parm.err = USB_ERR_INVAL;
874 /* setup all transfers */
880 * Initialize the "usb_xfer_root" structure,
881 * which is common for all our USB transfers.
883 info = USB_ADD_BYTES(buf, 0);
885 info->memory_base = buf;
886 info->memory_size = parm.size[0];
889 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
890 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
892 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
893 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
895 cv_init(&info->cv_drain, "WDRAIN");
897 info->xfer_lock = xfer_lock;
899 usb_dma_tag_setup(&info->dma_parent_tag,
900 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
901 xfer_lock, &usb_bdma_done_event, 32, parm.dma_tag_max);
904 info->bus = udev->bus;
907 TAILQ_INIT(&info->done_q.head);
908 info->done_q.command = &usbd_callback_wrapper;
910 TAILQ_INIT(&info->dma_q.head);
911 info->dma_q.command = &usb_bdma_work_loop;
913 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
914 info->done_m[0].xroot = info;
915 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
916 info->done_m[1].xroot = info;
919 * In device side mode control endpoint
920 * requests need to run from a separate
921 * context, else there is a chance of
924 if (setup_start == usb_control_ep_cfg)
926 &udev->bus->control_xfer_proc;
929 &udev->bus->non_giant_callback_proc;
935 parm.size[0] += sizeof(info[0]);
937 for (setup = setup_start, n = 0;
938 setup != setup_end; setup++, n++) {
940 /* skip USB transfers without callbacks: */
941 if (setup->callback == NULL) {
944 /* see if there is a matching endpoint */
945 ep = usbd_get_endpoint(udev,
946 ifaces[setup->if_index], setup);
948 if ((ep == NULL) || (ep->methods == NULL)) {
949 if (setup->flags.no_pipe_ok)
951 if ((setup->usb_mode != USB_MODE_DUAL) &&
952 (setup->usb_mode != udev->flags.usb_mode))
954 parm.err = USB_ERR_NO_PIPE;
958 /* align data properly */
959 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
961 /* store current setup pointer */
962 parm.curr_setup = setup;
966 * Common initialization of the
967 * "usb_xfer" structure.
969 xfer = USB_ADD_BYTES(buf, parm.size[0]);
970 xfer->address = udev->address;
971 xfer->priv_sc = priv_sc;
974 usb_callout_init_mtx(&xfer->timeout_handle,
975 &udev->bus->bus_lock, 0);
978 * Setup a dummy xfer, hence we are
979 * writing to the "usb_xfer"
980 * structure pointed to by "xfer"
981 * before we have allocated any
985 memset(&dummy, 0, sizeof(dummy));
989 /* set transfer endpoint pointer */
992 parm.size[0] += sizeof(xfer[0]);
993 parm.methods = xfer->endpoint->methods;
994 parm.curr_xfer = xfer;
997 * Call the Host or Device controller transfer
1000 (udev->bus->methods->xfer_setup) (&parm);
1002 /* check for error */
1008 * Increment the endpoint refcount. This
1009 * basically prevents setting a new
1010 * configuration and alternate setting
1011 * when USB transfers are in use on
1012 * the given interface. Search the USB
1013 * code for "endpoint->refcount_alloc" if you
1014 * want more information.
1016 USB_BUS_LOCK(info->bus);
1017 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1018 parm.err = USB_ERR_INVAL;
1020 xfer->endpoint->refcount_alloc++;
1022 if (xfer->endpoint->refcount_alloc == 0)
1023 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1024 USB_BUS_UNLOCK(info->bus);
1027 * Whenever we set ppxfer[] then we
1028 * also need to increment the
1031 info->setup_refcount++;
1034 * Transfer is successfully setup and
1040 /* check for error */
1045 if (buf || parm.err) {
1048 if (refcount == 0) {
1049 /* no transfers - nothing to do ! */
1052 /* align data properly */
1053 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1055 /* store offset temporarily */
1056 parm.size[1] = parm.size[0];
1059 * The number of DMA tags required depends on
1060 * the number of endpoints. The current estimate
1061 * for maximum number of DMA tags per endpoint
1064 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1067 * DMA tags for QH, TD, Data and more.
1069 parm.dma_tag_max += 8;
1071 parm.dma_tag_p += parm.dma_tag_max;
1073 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1076 /* align data properly */
1077 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1079 /* store offset temporarily */
1080 parm.size[3] = parm.size[0];
1082 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1085 /* align data properly */
1086 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1088 /* store offset temporarily */
1089 parm.size[4] = parm.size[0];
1091 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1094 /* store end offset temporarily */
1095 parm.size[5] = parm.size[0];
1097 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1100 /* store end offset temporarily */
1102 parm.size[2] = parm.size[0];
1104 /* align data properly */
1105 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1107 parm.size[6] = parm.size[0];
1109 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1112 /* align data properly */
1113 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1115 /* allocate zeroed memory */
1116 buf = kmalloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1119 parm.err = USB_ERR_NOMEM;
1120 DPRINTFN(0, "cannot allocate memory block for "
1121 "configuration (%d bytes)\n",
1125 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1126 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1127 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1128 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1129 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1134 if (info->setup_refcount == 0) {
1136 * "usbd_transfer_unsetup_sub" will unlock
1137 * the bus mutex before returning !
1139 USB_BUS_LOCK(info->bus);
1141 /* something went wrong */
1142 usbd_transfer_unsetup_sub(info, 0);
1146 usbd_transfer_unsetup(ppxfer, n_setup);
1151 /*------------------------------------------------------------------------*
1152 * usbd_transfer_unsetup_sub - factored out code
1153 *------------------------------------------------------------------------*/
1155 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1158 struct usb_page_cache *pc;
1161 USB_BUS_LOCK_ASSERT(info->bus);
1163 /* wait for any outstanding DMA operations */
1167 temp = usbd_get_dma_delay(info->udev);
1169 usb_pause_mtx(&info->bus->bus_lock,
1170 USB_MS_TO_TICKS(temp));
1174 /* make sure that our done messages are not queued anywhere */
1175 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1177 USB_BUS_UNLOCK(info->bus);
1180 /* free DMA'able memory, if any */
1181 pc = info->dma_page_cache_start;
1182 while (pc != info->dma_page_cache_end) {
1183 usb_pc_free_mem(pc);
1187 /* free DMA maps in all "xfer->frbuffers" */
1188 pc = info->xfer_page_cache_start;
1189 while (pc != info->xfer_page_cache_end) {
1190 usb_pc_dmamap_destroy(pc);
1194 /* free all DMA tags */
1195 usb_dma_tag_unsetup(&info->dma_parent_tag);
1198 cv_destroy(&info->cv_drain);
1201 * free the "memory_base" last, hence the "info" structure is
1202 * contained within the "memory_base"!
1204 kfree(info->memory_base, M_USB);
1207 /*------------------------------------------------------------------------*
1208 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1210 * NOTE: All USB transfers in progress will get called back passing
1211 * the error code "USB_ERR_CANCELLED" before this function
1213 *------------------------------------------------------------------------*/
1215 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1217 struct usb_xfer *xfer;
1218 struct usb_xfer_root *info;
1219 uint8_t needs_delay = 0;
1222 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1223 "usbd_transfer_unsetup can sleep!");
1227 xfer = pxfer[n_setup];
1234 USB_XFER_LOCK(xfer);
1235 USB_BUS_LOCK(info->bus);
1238 * HINT: when you start/stop a transfer, it might be a
1239 * good idea to directly use the "pxfer[]" structure:
1241 * usbd_transfer_start(sc->pxfer[0]);
1242 * usbd_transfer_stop(sc->pxfer[0]);
1244 * That way, if your code has many parts that will not
1245 * stop running under the same lock, in other words
1246 * "xfer_mtx", the usbd_transfer_start and
1247 * usbd_transfer_stop functions will simply return
1248 * when they detect a NULL pointer argument.
1250 * To avoid any races we clear the "pxfer[]" pointer
1251 * while holding the private mutex of the driver:
1253 pxfer[n_setup] = NULL;
1255 USB_BUS_UNLOCK(info->bus);
1256 USB_XFER_UNLOCK(xfer);
1258 usbd_transfer_drain(xfer);
1261 if (xfer->flags_int.bdma_enable)
1265 * NOTE: default endpoint does not have an
1266 * interface, even if endpoint->iface_index == 0
1268 USB_BUS_LOCK(info->bus);
1269 xfer->endpoint->refcount_alloc--;
1270 USB_BUS_UNLOCK(info->bus);
1272 usb_callout_drain(&xfer->timeout_handle);
1274 USB_BUS_LOCK(info->bus);
1277 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1278 "reference count\n"));
1281 info->setup_refcount--;
1283 if (info->setup_refcount == 0) {
1284 usbd_transfer_unsetup_sub(info,
1287 USB_BUS_UNLOCK(info->bus);
1292 /*------------------------------------------------------------------------*
1293 * usbd_control_transfer_init - factored out code
1295 * In USB Device Mode we have to wait for the SETUP packet which
1296 * containst the "struct usb_device_request" structure, before we can
1297 * transfer any data. In USB Host Mode we already have the SETUP
1298 * packet at the moment the USB transfer is started. This leads us to
1299 * having to setup the USB transfer at two different places in
1300 * time. This function just contains factored out control transfer
1301 * initialisation code, so that we don't duplicate the code.
1302 *------------------------------------------------------------------------*/
1304 usbd_control_transfer_init(struct usb_xfer *xfer)
1306 struct usb_device_request req;
1308 /* copy out the USB request header */
1310 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1312 /* setup remainder */
1314 xfer->flags_int.control_rem = UGETW(req.wLength);
1316 /* copy direction to endpoint variable */
1318 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1320 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1323 /*------------------------------------------------------------------------*
1324 * usbd_setup_ctrl_transfer
1326 * This function handles initialisation of control transfers. Control
1327 * transfers are special in that regard that they can both transmit
1333 *------------------------------------------------------------------------*/
1335 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1339 /* Check for control endpoint stall */
1340 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1341 /* the control transfer is no longer active */
1342 xfer->flags_int.control_stall = 1;
1343 xfer->flags_int.control_act = 0;
1345 /* don't stall control transfer by default */
1346 xfer->flags_int.control_stall = 0;
1349 /* Check for invalid number of frames */
1350 if (xfer->nframes > 2) {
1352 * If you need to split a control transfer, you
1353 * have to do one part at a time. Only with
1354 * non-control transfers you can do multiple
1357 DPRINTFN(0, "Too many frames: %u\n",
1358 (unsigned int)xfer->nframes);
1363 * Check if there is a control
1364 * transfer in progress:
1366 if (xfer->flags_int.control_act) {
1368 if (xfer->flags_int.control_hdr) {
1370 /* clear send header flag */
1372 xfer->flags_int.control_hdr = 0;
1374 /* setup control transfer */
1375 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1376 usbd_control_transfer_init(xfer);
1379 /* get data length */
1385 /* the size of the SETUP structure is hardcoded ! */
1387 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1388 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1389 xfer->frlengths[0], sizeof(struct
1390 usb_device_request));
1393 /* check USB mode */
1394 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1396 /* check number of frames */
1397 if (xfer->nframes != 1) {
1399 * We need to receive the setup
1400 * message first so that we know the
1403 DPRINTF("Misconfigured transfer\n");
1407 * Set a dummy "control_rem" value. This
1408 * variable will be overwritten later by a
1409 * call to "usbd_control_transfer_init()" !
1411 xfer->flags_int.control_rem = 0xFFFF;
1414 /* setup "endpoint" and "control_rem" */
1416 usbd_control_transfer_init(xfer);
1419 /* set transfer-header flag */
1421 xfer->flags_int.control_hdr = 1;
1423 /* get data length */
1425 len = (xfer->sumlen - sizeof(struct usb_device_request));
1428 /* check if there is a length mismatch */
1430 if (len > xfer->flags_int.control_rem) {
1431 DPRINTFN(0, "Length (%d) greater than "
1432 "remaining length (%d)\n", len,
1433 xfer->flags_int.control_rem);
1436 /* check if we are doing a short transfer */
1438 if (xfer->flags.force_short_xfer) {
1439 xfer->flags_int.control_rem = 0;
1441 if ((len != xfer->max_data_length) &&
1442 (len != xfer->flags_int.control_rem) &&
1443 (xfer->nframes != 1)) {
1444 DPRINTFN(0, "Short control transfer without "
1445 "force_short_xfer set\n");
1448 xfer->flags_int.control_rem -= len;
1451 /* the status part is executed when "control_act" is 0 */
1453 if ((xfer->flags_int.control_rem > 0) ||
1454 (xfer->flags.manual_status)) {
1455 /* don't execute the STATUS stage yet */
1456 xfer->flags_int.control_act = 1;
1459 if ((!xfer->flags_int.control_hdr) &&
1460 (xfer->nframes == 1)) {
1462 * This is not a valid operation!
1464 DPRINTFN(0, "Invalid parameter "
1469 /* time to execute the STATUS stage */
1470 xfer->flags_int.control_act = 0;
1472 return (0); /* success */
1475 return (1); /* failure */
1478 /*------------------------------------------------------------------------*
1479 * usbd_transfer_submit - start USB hardware for the given transfer
1481 * This function should only be called from the USB callback.
1482 *------------------------------------------------------------------------*/
1484 usbd_transfer_submit(struct usb_xfer *xfer)
1486 struct usb_xfer_root *info;
1487 struct usb_bus *bus;
1493 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1494 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1498 if (USB_DEBUG_VAR > 0) {
1501 usb_dump_endpoint(xfer->endpoint);
1503 USB_BUS_UNLOCK(bus);
1507 USB_XFER_LOCK_ASSERT(xfer);
1508 USB_BUS_LOCK_ASSERT_NOTOWNED(bus);
1510 /* Only open the USB transfer once! */
1511 if (!xfer->flags_int.open) {
1512 xfer->flags_int.open = 1;
1517 (xfer->endpoint->methods->open) (xfer);
1518 USB_BUS_UNLOCK(bus);
1520 /* set "transferring" flag */
1521 xfer->flags_int.transferring = 1;
1524 /* increment power reference */
1525 usbd_transfer_power_ref(xfer, 1);
1528 * Check if the transfer is waiting on a queue, most
1529 * frequently the "done_q":
1531 if (xfer->wait_queue) {
1533 usbd_transfer_dequeue(xfer);
1534 USB_BUS_UNLOCK(bus);
1536 /* clear "did_dma_delay" flag */
1537 xfer->flags_int.did_dma_delay = 0;
1539 /* clear "did_close" flag */
1540 xfer->flags_int.did_close = 0;
1543 /* clear "bdma_setup" flag */
1544 xfer->flags_int.bdma_setup = 0;
1546 /* by default we cannot cancel any USB transfer immediately */
1547 xfer->flags_int.can_cancel_immed = 0;
1549 /* clear lengths and frame counts by default */
1554 /* clear any previous errors */
1557 /* Check if the device is still alive */
1558 if (info->udev->state < USB_STATE_POWERED) {
1561 * Must return cancelled error code else
1562 * device drivers can hang.
1564 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1565 USB_BUS_UNLOCK(bus);
1570 if (xfer->nframes == 0) {
1571 if (xfer->flags.stall_pipe) {
1573 * Special case - want to stall without transferring
1576 DPRINTF("xfer=%p nframes=0: stall "
1577 "or clear stall!\n", xfer);
1579 xfer->flags_int.can_cancel_immed = 1;
1580 /* start the transfer */
1581 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1582 USB_BUS_UNLOCK(bus);
1586 usbd_transfer_done(xfer, USB_ERR_INVAL);
1587 USB_BUS_UNLOCK(bus);
1590 /* compute some variables */
1592 for (x = 0; x != xfer->nframes; x++) {
1593 /* make a copy of the frlenghts[] */
1594 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1595 /* compute total transfer length */
1596 xfer->sumlen += xfer->frlengths[x];
1597 if (xfer->sumlen < xfer->frlengths[x]) {
1598 /* length wrapped around */
1600 usbd_transfer_done(xfer, USB_ERR_INVAL);
1601 USB_BUS_UNLOCK(bus);
1606 /* clear some internal flags */
1608 xfer->flags_int.short_xfer_ok = 0;
1609 xfer->flags_int.short_frames_ok = 0;
1611 /* check if this is a control transfer */
1613 if (xfer->flags_int.control_xfr) {
1615 if (usbd_setup_ctrl_transfer(xfer)) {
1617 usbd_transfer_done(xfer, USB_ERR_STALLED);
1618 USB_BUS_UNLOCK(bus);
1623 * Setup filtered version of some transfer flags,
1624 * in case of data read direction
1626 if (USB_GET_DATA_ISREAD(xfer)) {
1628 if (xfer->flags.short_frames_ok) {
1629 xfer->flags_int.short_xfer_ok = 1;
1630 xfer->flags_int.short_frames_ok = 1;
1631 } else if (xfer->flags.short_xfer_ok) {
1632 xfer->flags_int.short_xfer_ok = 1;
1634 /* check for control transfer */
1635 if (xfer->flags_int.control_xfr) {
1637 * 1) Control transfers do not support
1638 * reception of multiple short USB
1639 * frames in host mode and device side
1640 * mode, with exception of:
1642 * 2) Due to sometimes buggy device
1643 * side firmware we need to do a
1644 * STATUS stage in case of short
1645 * control transfers in USB host mode.
1646 * The STATUS stage then becomes the
1647 * "alt_next" to the DATA stage.
1649 xfer->flags_int.short_frames_ok = 1;
1654 * Check if BUS-DMA support is enabled and try to load virtual
1655 * buffers into DMA, if any:
1658 if (xfer->flags_int.bdma_enable) {
1659 /* insert the USB transfer last in the BUS-DMA queue */
1660 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1665 * Enter the USB transfer into the Host Controller or
1666 * Device Controller schedule:
1668 usbd_pipe_enter(xfer);
1671 /*------------------------------------------------------------------------*
1672 * usbd_pipe_enter - factored out code
1673 *------------------------------------------------------------------------*/
1675 usbd_pipe_enter(struct usb_xfer *xfer)
1677 struct usb_endpoint *ep;
1679 USB_XFER_LOCK_ASSERT(xfer);
1681 USB_BUS_LOCK(xfer->xroot->bus);
1683 ep = xfer->endpoint;
1687 /* enter the transfer */
1688 (ep->methods->enter) (xfer);
1690 xfer->flags_int.can_cancel_immed = 1;
1692 /* check for transfer error */
1694 /* some error has happened */
1695 usbd_transfer_done(xfer, 0);
1696 USB_BUS_UNLOCK(xfer->xroot->bus);
1700 /* start the transfer */
1701 usb_command_wrapper(&ep->endpoint_q, xfer);
1702 USB_BUS_UNLOCK(xfer->xroot->bus);
1705 /*------------------------------------------------------------------------*
1706 * usbd_transfer_start - start an USB transfer
1708 * NOTE: Calling this function more than one time will only
1709 * result in a single transfer start, until the USB transfer
1711 *------------------------------------------------------------------------*/
1713 usbd_transfer_start(struct usb_xfer *xfer)
1716 /* transfer is gone */
1719 USB_XFER_LOCK_ASSERT(xfer);
1721 /* mark the USB transfer started */
1723 if (!xfer->flags_int.started) {
1724 /* lock the BUS lock to avoid races updating flags_int */
1725 USB_BUS_LOCK(xfer->xroot->bus);
1726 xfer->flags_int.started = 1;
1727 USB_BUS_UNLOCK(xfer->xroot->bus);
1729 /* check if the USB transfer callback is already transferring */
1731 if (xfer->flags_int.transferring) {
1734 USB_BUS_LOCK(xfer->xroot->bus);
1735 /* call the USB transfer callback */
1736 usbd_callback_ss_done_defer(xfer);
1737 USB_BUS_UNLOCK(xfer->xroot->bus);
1740 /*------------------------------------------------------------------------*
1741 * usbd_transfer_stop - stop an USB transfer
1743 * NOTE: Calling this function more than one time will only
1744 * result in a single transfer stop.
1745 * NOTE: When this function returns it is not safe to free nor
1746 * reuse any DMA buffers. See "usbd_transfer_drain()".
1747 *------------------------------------------------------------------------*/
1749 usbd_transfer_stop(struct usb_xfer *xfer)
1751 struct usb_endpoint *ep;
1754 /* transfer is gone */
1758 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1761 /* check if the USB transfer was ever opened */
1763 if (!xfer->flags_int.open) {
1764 if (xfer->flags_int.started) {
1765 /* nothing to do except clearing the "started" flag */
1766 /* lock the BUS lock to avoid races updating flags_int */
1767 USB_BUS_LOCK(xfer->xroot->bus);
1768 xfer->flags_int.started = 0;
1769 USB_BUS_UNLOCK(xfer->xroot->bus);
1773 /* try to stop the current USB transfer */
1775 USB_BUS_LOCK(xfer->xroot->bus);
1776 /* override any previous error */
1777 xfer->error = USB_ERR_CANCELLED;
1780 * Clear "open" and "started" when both private and USB lock
1781 * is locked so that we don't get a race updating "flags_int"
1783 xfer->flags_int.open = 0;
1784 xfer->flags_int.started = 0;
1787 * Check if we can cancel the USB transfer immediately.
1789 if (xfer->flags_int.transferring) {
1790 if (xfer->flags_int.can_cancel_immed &&
1791 (!xfer->flags_int.did_close)) {
1794 * The following will lead to an USB_ERR_CANCELLED
1795 * error code being passed to the USB callback.
1797 (xfer->endpoint->methods->close) (xfer);
1798 /* only close once */
1799 xfer->flags_int.did_close = 1;
1801 /* need to wait for the next done callback */
1806 /* close here and now */
1807 (xfer->endpoint->methods->close) (xfer);
1810 * Any additional DMA delay is done by
1811 * "usbd_transfer_unsetup()".
1815 * Special case. Check if we need to restart a blocked
1818 ep = xfer->endpoint;
1821 * If the current USB transfer is completing we need
1822 * to start the next one:
1824 if (ep->endpoint_q.curr == xfer) {
1825 usb_command_wrapper(&ep->endpoint_q, NULL);
1829 USB_BUS_UNLOCK(xfer->xroot->bus);
1832 /*------------------------------------------------------------------------*
1833 * usbd_transfer_pending
1835 * This function will check if an USB transfer is pending which is a
1836 * little bit complicated!
1839 * 1: Pending: The USB transfer will receive a callback in the future.
1840 *------------------------------------------------------------------------*/
1842 usbd_transfer_pending(struct usb_xfer *xfer)
1844 struct usb_xfer_root *info;
1845 struct usb_xfer_queue *pq;
1848 /* transfer is gone */
1852 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1855 if (xfer->flags_int.transferring) {
1859 USB_BUS_LOCK(xfer->xroot->bus);
1860 if (xfer->wait_queue) {
1861 /* we are waiting on a queue somewhere */
1862 USB_BUS_UNLOCK(xfer->xroot->bus);
1868 if (pq->curr == xfer) {
1869 /* we are currently scheduled for callback */
1870 USB_BUS_UNLOCK(xfer->xroot->bus);
1873 /* we are not pending */
1874 USB_BUS_UNLOCK(xfer->xroot->bus);
1878 /*------------------------------------------------------------------------*
1879 * usbd_transfer_drain
1881 * This function will stop the USB transfer and wait for any
1882 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1883 * are loaded into DMA can safely be freed or reused after that this
1884 * function has returned.
1885 *------------------------------------------------------------------------*/
1887 usbd_transfer_drain(struct usb_xfer *xfer)
1890 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1891 "usbd_transfer_drain can sleep!");
1895 /* transfer is gone */
1898 USB_XFER_LOCK_ASSERT_NOTOWNED(xfer);
1899 USB_XFER_LOCK(xfer);
1901 usbd_transfer_stop(xfer);
1903 while (usbd_transfer_pending(xfer) ||
1904 xfer->flags_int.doing_callback) {
1907 * It is allowed that the callback can drop its
1908 * transfer mutex. In that case checking only
1909 * "usbd_transfer_pending()" is not enough to tell if
1910 * the USB transfer is fully drained. We also need to
1911 * check the internal "doing_callback" flag.
1913 xfer->flags_int.draining = 1;
1916 * Wait until the current outstanding USB
1917 * transfer is complete !
1919 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_lock);
1921 USB_XFER_UNLOCK(xfer);
1924 struct usb_page_cache *
1925 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1927 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1929 return (&xfer->frbuffers[frindex]);
1932 /*------------------------------------------------------------------------*
1933 * usbd_xfer_get_fps_shift
1935 * The following function is only useful for isochronous transfers. It
1936 * returns how many times the frame execution rate has been shifted
1942 *------------------------------------------------------------------------*/
1944 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1946 return (xfer->fps_shift);
1950 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1952 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1954 return (xfer->frlengths[frindex]);
1957 /*------------------------------------------------------------------------*
1958 * usbd_xfer_set_frame_data
1960 * This function sets the pointer of the buffer that should
1961 * loaded directly into DMA for the given USB frame. Passing "ptr"
1962 * equal to NULL while the corresponding "frlength" is greater
1963 * than zero gives undefined results!
1964 *------------------------------------------------------------------------*/
1966 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1967 void *ptr, usb_frlength_t len)
1969 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1971 /* set virtual address to load and length */
1972 xfer->frbuffers[frindex].buffer = ptr;
1973 usbd_xfer_set_frame_len(xfer, frindex, len);
1977 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1978 void **ptr, int *len)
1980 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1983 *ptr = xfer->frbuffers[frindex].buffer;
1985 *len = xfer->frlengths[frindex];
1988 /*------------------------------------------------------------------------*
1989 * usbd_xfer_old_frame_length
1991 * This function returns the framelength of the given frame at the
1992 * time the transfer was submitted. This function can be used to
1993 * compute the starting data pointer of the next isochronous frame
1994 * when an isochronous transfer has completed.
1995 *------------------------------------------------------------------------*/
1997 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
1999 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2001 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2005 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2009 *actlen = xfer->actlen;
2011 *sumlen = xfer->sumlen;
2012 if (aframes != NULL)
2013 *aframes = xfer->aframes;
2014 if (nframes != NULL)
2015 *nframes = xfer->nframes;
2018 /*------------------------------------------------------------------------*
2019 * usbd_xfer_set_frame_offset
2021 * This function sets the frame data buffer offset relative to the beginning
2022 * of the USB DMA buffer allocated for this USB transfer.
2023 *------------------------------------------------------------------------*/
2025 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2026 usb_frcount_t frindex)
2028 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2029 "when the USB buffer is external\n"));
2030 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2032 /* set virtual address to load */
2033 xfer->frbuffers[frindex].buffer =
2034 USB_ADD_BYTES(xfer->local_buffer, offset);
2038 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2044 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2050 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2056 usbd_xfer_max_frames(struct usb_xfer *xfer)
2058 return (xfer->max_frame_count);
2062 usbd_xfer_max_len(struct usb_xfer *xfer)
2064 return (xfer->max_data_length);
2068 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2070 return (xfer->max_frame_size);
2074 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2077 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2079 xfer->frlengths[frindex] = len;
2082 /*------------------------------------------------------------------------*
2083 * usb_callback_proc - factored out code
2085 * This function performs USB callbacks.
2086 *------------------------------------------------------------------------*/
2088 usb_callback_proc(struct usb_proc_msg *_pm)
2090 struct usb_done_msg *pm = (void *)_pm;
2091 struct usb_xfer_root *info = pm->xroot;
2093 /* Change locking order */
2094 USB_BUS_UNLOCK(info->bus);
2097 * We exploit the fact that the mutex is the same for all
2098 * callbacks that will be called from this thread:
2100 lockmgr(info->xfer_lock, LK_EXCLUSIVE);
2101 USB_BUS_LOCK(info->bus);
2103 /* Continue where we lost track */
2104 usb_command_wrapper(&info->done_q,
2107 lockmgr(info->xfer_lock, LK_RELEASE);
2110 /*------------------------------------------------------------------------*
2111 * usbd_callback_ss_done_defer
2113 * This function will defer the start, stop and done callback to the
2115 *------------------------------------------------------------------------*/
2117 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2119 struct usb_xfer_root *info = xfer->xroot;
2120 struct usb_xfer_queue *pq = &info->done_q;
2122 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2124 if (pq->curr != xfer) {
2125 usbd_transfer_enqueue(pq, xfer);
2127 if (!pq->recurse_1) {
2130 * We have to postpone the callback due to the fact we
2131 * will have a Lock Order Reversal, LOR, if we try to
2134 if (usb_proc_msignal(info->done_p,
2135 &info->done_m[0], &info->done_m[1])) {
2139 /* clear second recurse flag */
2146 /*------------------------------------------------------------------------*
2147 * usbd_callback_wrapper
2149 * This is a wrapper for USB callbacks. This wrapper does some
2150 * auto-magic things like figuring out if we can call the callback
2151 * directly from the current context or if we need to wakeup the
2152 * interrupt process.
2153 *------------------------------------------------------------------------*/
2155 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2157 struct usb_xfer *xfer = pq->curr;
2158 struct usb_xfer_root *info = xfer->xroot;
2160 USB_BUS_LOCK_ASSERT(info->bus);
2161 if (!lockowned(info->xfer_lock)) {
2163 * Cases that end up here:
2165 * 5) HW interrupt done callback or other source.
2167 DPRINTFN(3, "case 5\n");
2170 * We have to postpone the callback due to the fact we
2171 * will have a Lock Order Reversal, LOR, if we try to
2174 if (usb_proc_msignal(info->done_p,
2175 &info->done_m[0], &info->done_m[1])) {
2181 * Cases that end up here:
2183 * 1) We are starting a transfer
2184 * 2) We are prematurely calling back a transfer
2185 * 3) We are stopping a transfer
2186 * 4) We are doing an ordinary callback
2188 DPRINTFN(3, "case 1-4\n");
2189 /* get next USB transfer in the queue */
2190 info->done_q.curr = NULL;
2192 /* set flag in case of drain */
2193 xfer->flags_int.doing_callback = 1;
2195 USB_BUS_UNLOCK(info->bus);
2196 USB_BUS_LOCK_ASSERT_NOTOWNED(info->bus);
2198 /* set correct USB state for callback */
2199 if (!xfer->flags_int.transferring) {
2200 xfer->usb_state = USB_ST_SETUP;
2201 if (!xfer->flags_int.started) {
2202 /* we got stopped before we even got started */
2203 USB_BUS_LOCK(info->bus);
2208 if (usbd_callback_wrapper_sub(xfer)) {
2209 /* the callback has been deferred */
2210 USB_BUS_LOCK(info->bus);
2214 /* decrement power reference */
2215 usbd_transfer_power_ref(xfer, -1);
2217 xfer->flags_int.transferring = 0;
2220 xfer->usb_state = USB_ST_ERROR;
2222 /* set transferred state */
2223 xfer->usb_state = USB_ST_TRANSFERRED;
2225 /* sync DMA memory, if any */
2226 if (xfer->flags_int.bdma_enable &&
2227 (!xfer->flags_int.bdma_no_post_sync)) {
2228 usb_bdma_post_sync(xfer);
2235 if (xfer->usb_state != USB_ST_SETUP)
2236 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2238 USB_XFER_LOCK_ASSERT(xfer);
2239 /* call processing routine */
2240 (xfer->callback) (xfer, xfer->error);
2242 /* pickup the USB mutex again */
2243 USB_BUS_LOCK(info->bus);
2246 * Check if we got started after that we got cancelled, but
2247 * before we managed to do the callback.
2249 if ((!xfer->flags_int.open) &&
2250 (xfer->flags_int.started) &&
2251 (xfer->usb_state == USB_ST_ERROR)) {
2252 /* clear flag in case of drain */
2253 xfer->flags_int.doing_callback = 0;
2254 /* try to loop, but not recursivly */
2255 usb_command_wrapper(&info->done_q, xfer);
2260 /* clear flag in case of drain */
2261 xfer->flags_int.doing_callback = 0;
2264 * Check if we are draining.
2266 if (xfer->flags_int.draining &&
2267 (!xfer->flags_int.transferring)) {
2268 /* "usbd_transfer_drain()" is waiting for end of transfer */
2269 xfer->flags_int.draining = 0;
2270 cv_broadcast(&info->cv_drain);
2273 /* do the next callback, if any */
2274 usb_command_wrapper(&info->done_q,
2278 /*------------------------------------------------------------------------*
2279 * usb_dma_delay_done_cb
2281 * This function is called when the DMA delay has been exectuded, and
2282 * will make sure that the callback is called to complete the USB
2283 * transfer. This code path is ususally only used when there is an USB
2284 * error like USB_ERR_CANCELLED.
2285 *------------------------------------------------------------------------*/
2287 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2289 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2291 DPRINTFN(3, "Completed %p\n", xfer);
2293 /* queue callback for execution, again */
2294 usbd_transfer_done(xfer, 0);
2297 /*------------------------------------------------------------------------*
2298 * usbd_transfer_dequeue
2300 * - This function is used to remove an USB transfer from a USB
2303 * - This function can be called multiple times in a row.
2304 *------------------------------------------------------------------------*/
2306 usbd_transfer_dequeue(struct usb_xfer *xfer)
2308 struct usb_xfer_queue *pq;
2310 pq = xfer->wait_queue;
2312 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2313 xfer->wait_queue = NULL;
2317 /*------------------------------------------------------------------------*
2318 * usbd_transfer_enqueue
2320 * - This function is used to insert an USB transfer into a USB *
2323 * - This function can be called multiple times in a row.
2324 *------------------------------------------------------------------------*/
2326 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2329 * Insert the USB transfer into the queue, if it is not
2330 * already on a USB transfer queue:
2332 if (xfer->wait_queue == NULL) {
2333 xfer->wait_queue = pq;
2334 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2338 /*------------------------------------------------------------------------*
2339 * usbd_transfer_done
2341 * - This function is used to remove an USB transfer from the busdma,
2342 * pipe or interrupt queue.
2344 * - This function is used to queue the USB transfer on the done
2347 * - This function is used to stop any USB transfer timeouts.
2348 *------------------------------------------------------------------------*/
2350 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2352 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2354 DPRINTF("err=%s\n", usbd_errstr(error));
2357 * If we are not transferring then just return.
2358 * This can happen during transfer cancel.
2360 if (!xfer->flags_int.transferring) {
2361 DPRINTF("not transferring\n");
2362 /* end of control transfer, if any */
2363 xfer->flags_int.control_act = 0;
2366 /* only set transfer error if not already set */
2368 xfer->error = error;
2370 /* stop any callouts */
2371 usb_callout_stop(&xfer->timeout_handle);
2374 * If we are waiting on a queue, just remove the USB transfer
2375 * from the queue, if any. We should have the required locks
2376 * locked to do the remove when this function is called.
2378 usbd_transfer_dequeue(xfer);
2381 if (lockowned(xfer->xroot->xfer_lock)) {
2382 struct usb_xfer_queue *pq;
2385 * If the private USB lock is not locked, then we assume
2386 * that the BUS-DMA load stage has been passed:
2388 pq = &xfer->xroot->dma_q;
2390 if (pq->curr == xfer) {
2391 /* start the next BUS-DMA load, if any */
2392 usb_command_wrapper(pq, NULL);
2396 /* keep some statistics */
2398 xfer->xroot->bus->stats_err.uds_requests
2399 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2401 xfer->xroot->bus->stats_ok.uds_requests
2402 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2405 /* call the USB transfer callback */
2406 usbd_callback_ss_done_defer(xfer);
2409 /*------------------------------------------------------------------------*
2410 * usbd_transfer_start_cb
2412 * This function is called to start the USB transfer when
2413 * "xfer->interval" is greater than zero, and and the endpoint type is
2415 *------------------------------------------------------------------------*/
2417 usbd_transfer_start_cb(void *arg)
2419 struct usb_xfer *xfer = arg;
2420 struct usb_endpoint *ep = xfer->endpoint;
2422 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2427 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2429 /* start USB transfer, if no error */
2430 if (xfer->error == 0)
2431 (ep->methods->start) (xfer);
2433 xfer->flags_int.can_cancel_immed = 1;
2435 /* check for error */
2437 /* some error has happened */
2438 usbd_transfer_done(xfer, 0);
2442 /*------------------------------------------------------------------------*
2443 * usbd_xfer_set_stall
2445 * This function is used to set the stall flag outside the
2446 * callback. This function is NULL safe.
2447 *------------------------------------------------------------------------*/
2449 usbd_xfer_set_stall(struct usb_xfer *xfer)
2455 USB_XFER_LOCK_ASSERT(xfer);
2457 /* avoid any races by locking the USB mutex */
2458 USB_BUS_LOCK(xfer->xroot->bus);
2459 xfer->flags.stall_pipe = 1;
2460 USB_BUS_UNLOCK(xfer->xroot->bus);
2464 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2466 return (xfer->endpoint->is_stalled);
2469 /*------------------------------------------------------------------------*
2470 * usbd_transfer_clear_stall
2472 * This function is used to clear the stall flag outside the
2473 * callback. This function is NULL safe.
2474 *------------------------------------------------------------------------*/
2476 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2482 USB_XFER_LOCK_ASSERT(xfer);
2484 /* avoid any races by locking the USB mutex */
2485 USB_BUS_LOCK(xfer->xroot->bus);
2487 xfer->flags.stall_pipe = 0;
2489 USB_BUS_UNLOCK(xfer->xroot->bus);
2492 /*------------------------------------------------------------------------*
2495 * This function is used to add an USB transfer to the pipe transfer list.
2496 *------------------------------------------------------------------------*/
2498 usbd_pipe_start(struct usb_xfer_queue *pq)
2500 struct usb_endpoint *ep;
2501 struct usb_xfer *xfer;
2505 ep = xfer->endpoint;
2507 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2510 * If the endpoint is already stalled we do nothing !
2512 if (ep->is_stalled) {
2516 * Check if we are supposed to stall the endpoint:
2518 if (xfer->flags.stall_pipe) {
2519 struct usb_device *udev;
2520 struct usb_xfer_root *info;
2522 /* clear stall command */
2523 xfer->flags.stall_pipe = 0;
2525 /* get pointer to USB device */
2530 * Only stall BULK and INTERRUPT endpoints.
2532 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2533 if ((type == UE_BULK) ||
2534 (type == UE_INTERRUPT)) {
2539 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2540 (udev->bus->methods->set_stall) (
2541 udev, NULL, ep, &did_stall);
2542 } else if (udev->ctrl_xfer[1]) {
2543 info = udev->ctrl_xfer[1]->xroot;
2545 &info->bus->non_giant_callback_proc,
2546 &udev->cs_msg[0], &udev->cs_msg[1]);
2548 /* should not happen */
2549 DPRINTFN(0, "No stall handler\n");
2552 * Check if we should stall. Some USB hardware
2553 * handles set- and clear-stall in hardware.
2557 * The transfer will be continued when
2558 * the clear-stall control endpoint
2559 * message is received.
2564 } else if (type == UE_ISOCHRONOUS) {
2567 * Make sure any FIFO overflow or other FIFO
2568 * error conditions go away by resetting the
2569 * endpoint FIFO through the clear stall
2572 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2573 (udev->bus->methods->clear_stall) (udev, ep);
2577 /* Set or clear stall complete - special case */
2578 if (xfer->nframes == 0) {
2579 /* we are complete */
2581 usbd_transfer_done(xfer, 0);
2587 * 1) Start the first transfer queued.
2589 * 2) Re-start the current USB transfer.
2592 * Check if there should be any
2593 * pre transfer start delay:
2595 if (xfer->interval > 0) {
2596 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2597 if ((type == UE_BULK) ||
2598 (type == UE_CONTROL)) {
2599 usbd_transfer_timeout_ms(xfer,
2600 &usbd_transfer_start_cb,
2608 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2610 /* start USB transfer, if no error */
2611 if (xfer->error == 0)
2612 (ep->methods->start) (xfer);
2614 xfer->flags_int.can_cancel_immed = 1;
2616 /* check for error */
2618 /* some error has happened */
2619 usbd_transfer_done(xfer, 0);
2623 /*------------------------------------------------------------------------*
2624 * usbd_transfer_timeout_ms
2626 * This function is used to setup a timeout on the given USB
2627 * transfer. If the timeout has been deferred the callback given by
2628 * "cb" will get called after "ms" milliseconds.
2629 *------------------------------------------------------------------------*/
2631 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2632 void (*cb) (void *arg), usb_timeout_t ms)
2634 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2637 usb_callout_reset(&xfer->timeout_handle,
2638 USB_MS_TO_TICKS(ms), cb, xfer);
2641 /*------------------------------------------------------------------------*
2642 * usbd_callback_wrapper_sub
2644 * - This function will update variables in an USB transfer after
2645 * that the USB transfer is complete.
2647 * - This function is used to start the next USB transfer on the
2648 * ep transfer queue, if any.
2650 * NOTE: In some special cases the USB transfer will not be removed from
2651 * the pipe queue, but remain first. To enforce USB transfer removal call
2652 * this function passing the error code "USB_ERR_CANCELLED".
2656 * Else: The callback has been deferred.
2657 *------------------------------------------------------------------------*/
2659 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2661 struct usb_endpoint *ep;
2662 struct usb_bus *bus;
2665 bus = xfer->xroot->bus;
2667 if ((!xfer->flags_int.open) &&
2668 (!xfer->flags_int.did_close)) {
2671 (xfer->endpoint->methods->close) (xfer);
2672 USB_BUS_UNLOCK(bus);
2673 /* only close once */
2674 xfer->flags_int.did_close = 1;
2675 return (1); /* wait for new callback */
2678 * If we have a non-hardware induced error we
2679 * need to do the DMA delay!
2681 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2682 (xfer->error == USB_ERR_CANCELLED ||
2683 xfer->error == USB_ERR_TIMEOUT ||
2684 bus->methods->start_dma_delay != NULL)) {
2688 /* only delay once */
2689 xfer->flags_int.did_dma_delay = 1;
2691 /* we can not cancel this delay */
2692 xfer->flags_int.can_cancel_immed = 0;
2694 temp = usbd_get_dma_delay(xfer->xroot->udev);
2696 DPRINTFN(3, "DMA delay, %u ms, "
2697 "on %p\n", temp, xfer);
2702 * Some hardware solutions have dedicated
2703 * events when it is safe to free DMA'ed
2704 * memory. For the other hardware platforms we
2705 * use a static delay.
2707 if (bus->methods->start_dma_delay != NULL) {
2708 (bus->methods->start_dma_delay) (xfer);
2710 usbd_transfer_timeout_ms(xfer,
2711 (void *)&usb_dma_delay_done_cb, temp);
2713 USB_BUS_UNLOCK(bus);
2714 return (1); /* wait for new callback */
2717 /* check actual number of frames */
2718 if (xfer->aframes > xfer->nframes) {
2719 if (xfer->error == 0) {
2720 panic("%s: actual number of frames, %d, is "
2721 "greater than initial number of frames, %d\n",
2722 __FUNCTION__, xfer->aframes, xfer->nframes);
2724 /* just set some valid value */
2725 xfer->aframes = xfer->nframes;
2728 /* compute actual length */
2731 for (x = 0; x != xfer->aframes; x++) {
2732 xfer->actlen += xfer->frlengths[x];
2736 * Frames that were not transferred get zero actual length in
2737 * case the USB device driver does not check the actual number
2738 * of frames transferred, "xfer->aframes":
2740 for (; x < xfer->nframes; x++) {
2741 usbd_xfer_set_frame_len(xfer, x, 0);
2744 /* check actual length */
2745 if (xfer->actlen > xfer->sumlen) {
2746 if (xfer->error == 0) {
2747 panic("%s: actual length, %d, is greater than "
2748 "initial length, %d\n",
2749 __FUNCTION__, xfer->actlen, xfer->sumlen);
2751 /* just set some valid value */
2752 xfer->actlen = xfer->sumlen;
2755 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2756 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2757 xfer->aframes, xfer->nframes);
2760 /* end of control transfer, if any */
2761 xfer->flags_int.control_act = 0;
2763 /* check if we should block the execution queue */
2764 if ((xfer->error != USB_ERR_CANCELLED) &&
2765 (xfer->flags.pipe_bof)) {
2766 DPRINTFN(2, "xfer=%p: Block On Failure "
2767 "on endpoint=%p\n", xfer, xfer->endpoint);
2771 /* check for short transfers */
2772 if (xfer->actlen < xfer->sumlen) {
2774 /* end of control transfer, if any */
2775 xfer->flags_int.control_act = 0;
2777 if (!xfer->flags_int.short_xfer_ok) {
2778 xfer->error = USB_ERR_SHORT_XFER;
2779 if (xfer->flags.pipe_bof) {
2780 DPRINTFN(2, "xfer=%p: Block On Failure on "
2781 "Short Transfer on endpoint %p.\n",
2782 xfer, xfer->endpoint);
2788 * Check if we are in the middle of a
2791 if (xfer->flags_int.control_act) {
2792 DPRINTFN(5, "xfer=%p: Control transfer "
2793 "active on endpoint=%p\n", xfer, xfer->endpoint);
2799 ep = xfer->endpoint;
2802 * If the current USB transfer is completing we need to start the
2806 if (ep->endpoint_q.curr == xfer) {
2807 usb_command_wrapper(&ep->endpoint_q, NULL);
2809 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2810 /* there is another USB transfer waiting */
2812 /* this is the last USB transfer */
2813 /* clear isochronous sync flag */
2814 xfer->endpoint->is_synced = 0;
2817 USB_BUS_UNLOCK(bus);
2822 /*------------------------------------------------------------------------*
2823 * usb_command_wrapper
2825 * This function is used to execute commands non-recursivly on an USB
2827 *------------------------------------------------------------------------*/
2829 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2833 * If the transfer is not already processing,
2836 if (pq->curr != xfer) {
2837 usbd_transfer_enqueue(pq, xfer);
2838 if (pq->curr != NULL) {
2839 /* something is already processing */
2840 DPRINTFN(6, "busy %p\n", pq->curr);
2845 /* Get next element in queue */
2849 if (!pq->recurse_1) {
2853 /* set both recurse flags */
2857 if (pq->curr == NULL) {
2858 xfer = TAILQ_FIRST(&pq->head);
2860 TAILQ_REMOVE(&pq->head, xfer,
2862 xfer->wait_queue = NULL;
2868 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2870 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2872 } while (!pq->recurse_2);
2874 /* clear first recurse flag */
2878 /* clear second recurse flag */
2883 /*------------------------------------------------------------------------*
2884 * usbd_ctrl_transfer_setup
2886 * This function is used to setup the default USB control endpoint
2888 *------------------------------------------------------------------------*/
2890 usbd_ctrl_transfer_setup(struct usb_device *udev)
2892 struct usb_xfer *xfer;
2894 uint8_t iface_index;
2896 /* check for root HUB */
2897 if (udev->parent_hub == NULL)
2901 xfer = udev->ctrl_xfer[0];
2903 USB_XFER_LOCK(xfer);
2905 ((xfer->address == udev->address) &&
2906 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2907 udev->ddesc.bMaxPacketSize));
2908 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2911 * NOTE: checking "xfer->address" and
2912 * starting the USB transfer must be
2915 usbd_transfer_start(xfer);
2918 USB_XFER_UNLOCK(xfer);
2925 * All parameters are exactly the same like before.
2931 * Update wMaxPacketSize for the default control endpoint:
2933 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2934 udev->ddesc.bMaxPacketSize;
2937 * Unsetup any existing USB transfer:
2939 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2942 * Reset clear stall error counter.
2944 udev->clear_stall_errors = 0;
2947 * Try to setup a new USB transfer for the
2948 * default control endpoint:
2951 if (usbd_transfer_setup(udev, &iface_index,
2952 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2953 &udev->device_lock)) {
2954 DPRINTFN(0, "could not setup default "
2961 /*------------------------------------------------------------------------*
2962 * usbd_clear_data_toggle - factored out code
2964 * NOTE: the intention of this function is not to reset the hardware
2966 *------------------------------------------------------------------------*/
2968 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2970 USB_BUS_LOCK_ASSERT(udev->bus);
2972 /* check that we have a valid case */
2973 if (udev->flags.usb_mode == USB_MODE_HOST &&
2974 udev->parent_hub != NULL &&
2975 udev->bus->methods->clear_stall != NULL &&
2976 ep->methods != NULL) {
2977 (udev->bus->methods->clear_stall) (udev, ep);
2981 /*------------------------------------------------------------------------*
2982 * usbd_clear_data_toggle - factored out code
2984 * NOTE: the intention of this function is not to reset the hardware
2985 * data toggle on the USB device side.
2986 *------------------------------------------------------------------------*/
2988 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2990 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2992 USB_BUS_LOCK(udev->bus);
2993 ep->toggle_next = 0;
2994 /* some hardware needs a callback to clear the data toggle */
2995 usbd_clear_stall_locked(udev, ep);
2996 USB_BUS_UNLOCK(udev->bus);
2999 /*------------------------------------------------------------------------*
3000 * usbd_clear_stall_callback - factored out clear stall callback
3003 * xfer1: Clear Stall Control Transfer
3004 * xfer2: Stalled USB Transfer
3006 * This function is NULL safe.
3012 * Clear stall config example:
3014 * static const struct usb_config my_clearstall = {
3015 * .type = UE_CONTROL,
3017 * .direction = UE_DIR_ANY,
3018 * .interval = 50, //50 milliseconds
3019 * .bufsize = sizeof(struct usb_device_request),
3020 * .timeout = 1000, //1.000 seconds
3021 * .callback = &my_clear_stall_callback, // **
3022 * .usb_mode = USB_MODE_HOST,
3025 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3026 * passing the correct parameters.
3027 *------------------------------------------------------------------------*/
3029 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3030 struct usb_xfer *xfer2)
3032 struct usb_device_request req;
3034 if (xfer2 == NULL) {
3035 /* looks like we are tearing down */
3036 DPRINTF("NULL input parameter\n");
3039 USB_XFER_LOCK_ASSERT(xfer1);
3040 USB_XFER_LOCK_ASSERT(xfer2);
3042 switch (USB_GET_STATE(xfer1)) {
3046 * pre-clear the data toggle to DATA0 ("umass.c" and
3047 * "ata-usb.c" depends on this)
3050 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3052 /* setup a clear-stall packet */
3054 req.bmRequestType = UT_WRITE_ENDPOINT;
3055 req.bRequest = UR_CLEAR_FEATURE;
3056 USETW(req.wValue, UF_ENDPOINT_HALT);
3057 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3059 USETW(req.wLength, 0);
3062 * "usbd_transfer_setup_sub()" will ensure that
3063 * we have sufficient room in the buffer for
3064 * the request structure!
3067 /* copy in the transfer */
3069 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3072 xfer1->frlengths[0] = sizeof(req);
3075 usbd_transfer_submit(xfer1);
3078 case USB_ST_TRANSFERRED:
3081 default: /* Error */
3082 if (xfer1->error == USB_ERR_CANCELLED) {
3087 return (1); /* Clear Stall Finished */
3090 /*------------------------------------------------------------------------*
3091 * usbd_transfer_poll
3093 * The following function gets called from the USB keyboard driver and
3094 * UMASS when the system has paniced.
3096 * NOTE: It is currently not possible to resume normal operation on
3097 * the USB controller which has been polled, due to clearing of the
3098 * "up_dsleep" and "up_msleep" flags.
3099 *------------------------------------------------------------------------*/
3101 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3103 struct usb_xfer *xfer;
3104 struct usb_xfer_root *xroot;
3105 struct usb_device *udev;
3106 struct usb_proc_msg *pm;
3111 for (n = 0; n != max; n++) {
3112 /* Extra checks to avoid panic */
3115 continue; /* no USB transfer */
3116 xroot = xfer->xroot;
3118 continue; /* no USB root */
3121 continue; /* no USB device */
3122 if (udev->bus == NULL)
3123 continue; /* no BUS structure */
3124 if (udev->bus->methods == NULL)
3125 continue; /* no BUS methods */
3126 if (udev->bus->methods->xfer_poll == NULL)
3127 continue; /* no poll method */
3129 /* make sure that the BUS mutex is not locked */
3131 while (lockowned(&xroot->udev->bus->bus_lock)) {
3132 lockmgr(&xroot->udev->bus->bus_lock, LK_RELEASE);
3136 /* make sure that the transfer mutex is not locked */
3138 while (lockowned(xroot->xfer_lock)) {
3139 lockmgr(xroot->xfer_lock, LK_RELEASE);
3143 /* Make sure cv_signal() and cv_broadcast() is not called */
3144 udev->bus->control_xfer_proc.up_msleep = 0;
3145 udev->bus->explore_proc.up_msleep = 0;
3146 udev->bus->giant_callback_proc.up_msleep = 0;
3147 udev->bus->non_giant_callback_proc.up_msleep = 0;
3149 /* poll USB hardware */
3150 (udev->bus->methods->xfer_poll) (udev->bus);
3152 USB_BUS_LOCK(xroot->bus);
3154 /* check for clear stall */
3155 if (udev->ctrl_xfer[1] != NULL) {
3157 /* poll clear stall start */
3158 pm = &udev->cs_msg[0].hdr;
3159 (pm->pm_callback) (pm);
3160 /* poll clear stall done thread */
3161 pm = &udev->ctrl_xfer[1]->
3162 xroot->done_m[0].hdr;
3163 (pm->pm_callback) (pm);
3166 /* poll done thread */
3167 pm = &xroot->done_m[0].hdr;
3168 (pm->pm_callback) (pm);
3170 USB_BUS_UNLOCK(xroot->bus);
3172 /* restore transfer mutex */
3174 lockmgr(xroot->xfer_lock, LK_EXCLUSIVE);
3176 /* restore BUS mutex */
3178 lockmgr(&xroot->udev->bus->bus_lock, LK_EXCLUSIVE);
3183 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3184 uint8_t type, enum usb_dev_speed speed)
3186 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3187 [USB_SPEED_LOW] = 8,
3188 [USB_SPEED_FULL] = 64,
3189 [USB_SPEED_HIGH] = 1024,
3190 [USB_SPEED_VARIABLE] = 1024,
3191 [USB_SPEED_SUPER] = 1024,
3194 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3195 [USB_SPEED_LOW] = 0, /* invalid */
3196 [USB_SPEED_FULL] = 1023,
3197 [USB_SPEED_HIGH] = 1024,
3198 [USB_SPEED_VARIABLE] = 3584,
3199 [USB_SPEED_SUPER] = 1024,
3202 static const uint16_t control_min[USB_SPEED_MAX] = {
3203 [USB_SPEED_LOW] = 8,
3204 [USB_SPEED_FULL] = 8,
3205 [USB_SPEED_HIGH] = 64,
3206 [USB_SPEED_VARIABLE] = 512,
3207 [USB_SPEED_SUPER] = 512,
3210 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3211 [USB_SPEED_LOW] = 8,
3212 [USB_SPEED_FULL] = 8,
3213 [USB_SPEED_HIGH] = 512,
3214 [USB_SPEED_VARIABLE] = 512,
3215 [USB_SPEED_SUPER] = 1024,
3220 memset(ptr, 0, sizeof(*ptr));
3224 ptr->range.max = intr_range_max[speed];
3226 case UE_ISOCHRONOUS:
3227 ptr->range.max = isoc_range_max[speed];
3230 if (type == UE_BULK)
3231 temp = bulk_min[speed];
3232 else /* UE_CONTROL */
3233 temp = control_min[speed];
3235 /* default is fixed */
3236 ptr->fixed[0] = temp;
3237 ptr->fixed[1] = temp;
3238 ptr->fixed[2] = temp;
3239 ptr->fixed[3] = temp;
3241 if (speed == USB_SPEED_FULL) {
3242 /* multiple sizes */
3247 if ((speed == USB_SPEED_VARIABLE) &&
3248 (type == UE_BULK)) {
3249 /* multiple sizes */
3250 ptr->fixed[2] = 1024;
3251 ptr->fixed[3] = 1536;
3258 usbd_xfer_softc(struct usb_xfer *xfer)
3260 return (xfer->priv_sc);
3264 usbd_xfer_get_priv(struct usb_xfer *xfer)
3266 return (xfer->priv_fifo);
3270 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3272 xfer->priv_fifo = ptr;
3276 usbd_xfer_state(struct usb_xfer *xfer)
3278 return (xfer->usb_state);
3282 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3285 case USB_FORCE_SHORT_XFER:
3286 xfer->flags.force_short_xfer = 1;
3288 case USB_SHORT_XFER_OK:
3289 xfer->flags.short_xfer_ok = 1;
3291 case USB_MULTI_SHORT_OK:
3292 xfer->flags.short_frames_ok = 1;
3294 case USB_MANUAL_STATUS:
3295 xfer->flags.manual_status = 1;
3301 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3304 case USB_FORCE_SHORT_XFER:
3305 xfer->flags.force_short_xfer = 0;
3307 case USB_SHORT_XFER_OK:
3308 xfer->flags.short_xfer_ok = 0;
3310 case USB_MULTI_SHORT_OK:
3311 xfer->flags.short_frames_ok = 0;
3313 case USB_MANUAL_STATUS:
3314 xfer->flags.manual_status = 0;
3320 * The following function returns in milliseconds when the isochronous
3321 * transfer was completed by the hardware. The returned value wraps
3322 * around 65536 milliseconds.
3325 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3327 return (xfer->isoc_time_complete);