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/linker_set.h>
36 #include <sys/module.h>
38 #include <sys/mutex.h>
39 #include <sys/condvar.h>
40 #include <sys/sysctl.h>
42 #include <sys/unistd.h>
43 #include <sys/callout.h>
44 #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>
64 struct usb_std_packet_size {
66 uint16_t min; /* inclusive */
67 uint16_t max; /* inclusive */
73 static usb_callback_t usb_request_callback;
75 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
77 /* This transfer is used for generic control endpoint transfers */
81 .endpoint = 0x00, /* Control endpoint */
82 .direction = UE_DIR_ANY,
83 .bufsize = USB_EP0_BUFSIZE, /* bytes */
84 .flags = {.proxy_buffer = 1,},
85 .callback = &usb_request_callback,
86 .usb_mode = USB_MODE_DUAL, /* both modes */
89 /* This transfer is used for generic clear stall only */
93 .endpoint = 0x00, /* Control pipe */
94 .direction = UE_DIR_ANY,
95 .bufsize = sizeof(struct usb_device_request),
96 .callback = &usb_do_clear_stall_callback,
97 .timeout = 1000, /* 1 second */
98 .interval = 50, /* 50ms */
99 .usb_mode = USB_MODE_HOST,
103 /* function prototypes */
105 static void usbd_update_max_frame_size(struct usb_xfer *);
106 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
107 static void usbd_control_transfer_init(struct usb_xfer *);
108 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
109 static void usb_callback_proc(struct usb_proc_msg *);
110 static void usbd_callback_ss_done_defer(struct usb_xfer *);
111 static void usbd_callback_wrapper(struct usb_xfer_queue *);
112 static void usb_dma_delay_done_cb(void *);
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 */
141 if (xfer->max_packet_count == 2) {
142 xfer->max_frame_size = 2 * xfer->max_packet_size;
143 } else if (xfer->max_packet_count == 3) {
144 xfer->max_frame_size = 3 * xfer->max_packet_size;
146 xfer->max_frame_size = xfer->max_packet_size;
150 /*------------------------------------------------------------------------*
153 * The following function is called when we need to
154 * synchronize with DMA hardware.
157 * 0: no DMA delay required
158 * Else: milliseconds of DMA delay
159 *------------------------------------------------------------------------*/
161 usbd_get_dma_delay(struct usb_bus *bus)
165 if (bus->methods->get_dma_delay) {
166 (bus->methods->get_dma_delay) (bus, &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 >= 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 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_descriptor *edesc;
320 struct usb_std_packet_size std_size;
321 usb_frcount_t n_frlengths;
322 usb_frcount_t n_frbuffers;
328 * Sanity check. The following parameters must be initialized before
329 * calling this function.
331 if ((parm->hc_max_packet_size == 0) ||
332 (parm->hc_max_packet_count == 0) ||
333 (parm->hc_max_frame_size == 0)) {
334 parm->err = USB_ERR_INVAL;
337 edesc = xfer->endpoint->edesc;
339 type = (edesc->bmAttributes & UE_XFERTYPE);
341 xfer->flags = setup->flags;
342 xfer->nframes = setup->frames;
343 xfer->timeout = setup->timeout;
344 xfer->callback = setup->callback;
345 xfer->interval = setup->interval;
346 xfer->endpointno = edesc->bEndpointAddress;
347 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
348 xfer->max_packet_count = 1;
349 /* make a shadow copy: */
350 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
352 parm->bufsize = setup->bufsize;
354 if (parm->speed == USB_SPEED_HIGH) {
355 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
356 xfer->max_packet_size &= 0x7FF;
358 /* range check "max_packet_count" */
360 if (xfer->max_packet_count > parm->hc_max_packet_count) {
361 xfer->max_packet_count = parm->hc_max_packet_count;
363 /* filter "wMaxPacketSize" according to HC capabilities */
365 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
366 (xfer->max_packet_size == 0)) {
367 xfer->max_packet_size = parm->hc_max_packet_size;
369 /* filter "wMaxPacketSize" according to standard sizes */
371 usbd_get_std_packet_size(&std_size, type, parm->speed);
373 if (std_size.range.min || std_size.range.max) {
375 if (xfer->max_packet_size < std_size.range.min) {
376 xfer->max_packet_size = std_size.range.min;
378 if (xfer->max_packet_size > std_size.range.max) {
379 xfer->max_packet_size = std_size.range.max;
383 if (xfer->max_packet_size >= std_size.fixed[3]) {
384 xfer->max_packet_size = std_size.fixed[3];
385 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
386 xfer->max_packet_size = std_size.fixed[2];
387 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
388 xfer->max_packet_size = std_size.fixed[1];
390 /* only one possibility left */
391 xfer->max_packet_size = std_size.fixed[0];
395 /* compute "max_frame_size" */
397 usbd_update_max_frame_size(xfer);
399 /* check interrupt interval and transfer pre-delay */
401 if (type == UE_ISOCHRONOUS) {
403 uint16_t frame_limit;
405 xfer->interval = 0; /* not used, must be zero */
406 xfer->flags_int.isochronous_xfr = 1; /* set flag */
408 if (xfer->timeout == 0) {
410 * set a default timeout in
411 * case something goes wrong!
413 xfer->timeout = 1000 / 4;
415 switch (parm->speed) {
418 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
422 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
423 xfer->fps_shift = edesc->bInterval;
424 if (xfer->fps_shift > 0)
426 if (xfer->fps_shift > 3)
431 if (xfer->nframes > frame_limit) {
433 * this is not going to work
436 parm->err = USB_ERR_INVAL;
439 if (xfer->nframes == 0) {
441 * this is not a valid value
443 parm->err = USB_ERR_ZERO_NFRAMES;
449 * if a value is specified use that else check the endpoint
452 if (xfer->interval == 0) {
454 if (type == UE_INTERRUPT) {
456 xfer->interval = edesc->bInterval;
458 switch (parm->speed) {
459 case USB_SPEED_SUPER:
460 case USB_SPEED_VARIABLE:
462 if (xfer->interval < 4)
464 else if (xfer->interval > 16)
465 xfer->interval = (1<<(16-4));
468 (1 << (xfer->interval-4));
477 if (xfer->interval == 0) {
479 * One millisecond is the smallest
480 * interval we support:
489 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
490 * to be equal to zero when setting up USB transfers, hence
491 * this leads to alot of extra code in the USB kernel.
494 if ((xfer->max_frame_size == 0) ||
495 (xfer->max_packet_size == 0)) {
499 if ((parm->bufsize <= MIN_PKT) &&
500 (type != UE_CONTROL) &&
504 xfer->max_packet_size = MIN_PKT;
505 xfer->max_packet_count = 1;
506 parm->bufsize = 0; /* automatic setup length */
507 usbd_update_max_frame_size(xfer);
510 parm->err = USB_ERR_ZERO_MAXP;
519 * check if we should setup a default
523 if (parm->bufsize == 0) {
525 parm->bufsize = xfer->max_frame_size;
527 if (type == UE_ISOCHRONOUS) {
528 parm->bufsize *= xfer->nframes;
532 * check if we are about to setup a proxy
536 if (xfer->flags.proxy_buffer) {
538 /* round bufsize up */
540 parm->bufsize += (xfer->max_frame_size - 1);
542 if (parm->bufsize < xfer->max_frame_size) {
543 /* length wrapped around */
544 parm->err = USB_ERR_INVAL;
547 /* subtract remainder */
549 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
551 /* add length of USB device request structure, if any */
553 if (type == UE_CONTROL) {
554 parm->bufsize += REQ_SIZE; /* SETUP message */
557 xfer->max_data_length = parm->bufsize;
559 /* Setup "n_frlengths" and "n_frbuffers" */
561 if (type == UE_ISOCHRONOUS) {
562 n_frlengths = xfer->nframes;
566 if (type == UE_CONTROL) {
567 xfer->flags_int.control_xfr = 1;
568 if (xfer->nframes == 0) {
569 if (parm->bufsize <= REQ_SIZE) {
571 * there will never be any data
580 if (xfer->nframes == 0) {
585 n_frlengths = xfer->nframes;
586 n_frbuffers = xfer->nframes;
590 * check if we have room for the
591 * USB device request structure:
594 if (type == UE_CONTROL) {
596 if (xfer->max_data_length < REQ_SIZE) {
597 /* length wrapped around or too small bufsize */
598 parm->err = USB_ERR_INVAL;
601 xfer->max_data_length -= REQ_SIZE;
603 /* setup "frlengths" */
604 xfer->frlengths = parm->xfer_length_ptr;
605 parm->xfer_length_ptr += n_frlengths;
607 /* setup "frbuffers" */
608 xfer->frbuffers = parm->xfer_page_cache_ptr;
609 parm->xfer_page_cache_ptr += n_frbuffers;
611 /* initialize max frame count */
612 xfer->max_frame_count = xfer->nframes;
615 * check if we need to setup
619 if (!xfer->flags.ext_buffer) {
622 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
627 USB_ADD_BYTES(parm->buf, parm->size[0]);
629 usbd_xfer_set_frame_offset(xfer, 0, 0);
631 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
632 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
635 parm->size[0] += parm->bufsize;
637 /* align data again */
638 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
641 * Compute maximum buffer size
644 if (parm->bufsize_max < parm->bufsize) {
645 parm->bufsize_max = parm->bufsize;
648 if (xfer->flags_int.bdma_enable) {
650 * Setup "dma_page_ptr".
652 * Proof for formula below:
654 * Assume there are three USB frames having length "a", "b" and
655 * "c". These USB frames will at maximum need "z"
656 * "usb_page" structures. "z" is given by:
658 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
659 * ((c / USB_PAGE_SIZE) + 2);
661 * Constraining "a", "b" and "c" like this:
663 * (a + b + c) <= parm->bufsize
667 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
669 * Here is the general formula:
671 xfer->dma_page_ptr = parm->dma_page_ptr;
672 parm->dma_page_ptr += (2 * n_frbuffers);
673 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
677 /* correct maximum data length */
678 xfer->max_data_length = 0;
680 /* subtract USB frame remainder from "hc_max_frame_size" */
682 xfer->max_hc_frame_size =
683 (parm->hc_max_frame_size -
684 (parm->hc_max_frame_size % xfer->max_frame_size));
686 if (xfer->max_hc_frame_size == 0) {
687 parm->err = USB_ERR_INVAL;
691 /* initialize frame buffers */
694 for (x = 0; x != n_frbuffers; x++) {
695 xfer->frbuffers[x].tag_parent =
696 &xfer->xroot->dma_parent_tag;
698 if (xfer->flags_int.bdma_enable &&
699 (parm->bufsize_max > 0)) {
701 if (usb_pc_dmamap_create(
703 parm->bufsize_max)) {
704 parm->err = USB_ERR_NOMEM;
714 * Set some dummy values so that we avoid division by zero:
716 xfer->max_hc_frame_size = 1;
717 xfer->max_frame_size = 1;
718 xfer->max_packet_size = 1;
719 xfer->max_data_length = 0;
721 xfer->max_frame_count = 0;
725 /*------------------------------------------------------------------------*
726 * usbd_transfer_setup - setup an array of USB transfers
728 * NOTE: You must always call "usbd_transfer_unsetup" after calling
729 * "usbd_transfer_setup" if success was returned.
731 * The idea is that the USB device driver should pre-allocate all its
732 * transfers by one call to this function.
737 *------------------------------------------------------------------------*/
739 usbd_transfer_setup(struct usb_device *udev,
740 const uint8_t *ifaces, struct usb_xfer **ppxfer,
741 const struct usb_config *setup_start, uint16_t n_setup,
742 void *priv_sc, struct mtx *xfer_mtx)
744 struct usb_xfer dummy;
745 struct usb_setup_params parm;
746 const struct usb_config *setup_end = setup_start + n_setup;
747 const struct usb_config *setup;
748 struct usb_endpoint *ep;
749 struct usb_xfer_root *info;
750 struct usb_xfer *xfer;
759 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
760 "usbd_transfer_setup can sleep!");
762 /* do some checking first */
765 DPRINTFN(6, "setup array has zero length!\n");
766 return (USB_ERR_INVAL);
769 DPRINTFN(6, "ifaces array is NULL!\n");
770 return (USB_ERR_INVAL);
772 if (xfer_mtx == NULL) {
773 DPRINTFN(6, "using global lock\n");
777 for (setup = setup_start, n = 0;
778 setup != setup_end; setup++, n++) {
779 if (setup->bufsize == (usb_frlength_t)-1) {
780 parm.err = USB_ERR_BAD_BUFSIZE;
781 DPRINTF("invalid bufsize\n");
783 if (setup->callback == NULL) {
784 parm.err = USB_ERR_NO_CALLBACK;
785 DPRINTF("no callback\n");
793 bzero(&parm, sizeof(parm));
796 parm.speed = usbd_get_speed(udev);
797 parm.hc_max_packet_count = 1;
799 if (parm.speed >= USB_SPEED_MAX) {
800 parm.err = USB_ERR_INVAL;
803 /* setup all transfers */
809 * Initialize the "usb_xfer_root" structure,
810 * which is common for all our USB transfers.
812 info = USB_ADD_BYTES(buf, 0);
814 info->memory_base = buf;
815 info->memory_size = parm.size[0];
818 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
819 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
821 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
822 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
824 cv_init(&info->cv_drain, "WDRAIN");
826 info->xfer_mtx = xfer_mtx;
828 usb_dma_tag_setup(&info->dma_parent_tag,
829 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
830 xfer_mtx, &usb_bdma_done_event, 32, parm.dma_tag_max);
833 info->bus = udev->bus;
836 TAILQ_INIT(&info->done_q.head);
837 info->done_q.command = &usbd_callback_wrapper;
839 TAILQ_INIT(&info->dma_q.head);
840 info->dma_q.command = &usb_bdma_work_loop;
842 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
843 info->done_m[0].xroot = info;
844 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
845 info->done_m[1].xroot = info;
848 * In device side mode control endpoint
849 * requests need to run from a separate
850 * context, else there is a chance of
853 if (setup_start == usb_control_ep_cfg)
855 &udev->bus->control_xfer_proc;
856 else if (xfer_mtx == &Giant)
858 &udev->bus->giant_callback_proc;
861 &udev->bus->non_giant_callback_proc;
867 parm.size[0] += sizeof(info[0]);
869 for (setup = setup_start, n = 0;
870 setup != setup_end; setup++, n++) {
872 /* skip USB transfers without callbacks: */
873 if (setup->callback == NULL) {
876 /* see if there is a matching endpoint */
877 ep = usbd_get_endpoint(udev,
878 ifaces[setup->if_index], setup);
880 if ((ep == NULL) || (ep->methods == NULL)) {
881 if (setup->flags.no_pipe_ok)
883 if ((setup->usb_mode != USB_MODE_DUAL) &&
884 (setup->usb_mode != udev->flags.usb_mode))
886 parm.err = USB_ERR_NO_PIPE;
890 /* align data properly */
891 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
893 /* store current setup pointer */
894 parm.curr_setup = setup;
898 * Common initialization of the
899 * "usb_xfer" structure.
901 xfer = USB_ADD_BYTES(buf, parm.size[0]);
902 xfer->address = udev->address;
903 xfer->priv_sc = priv_sc;
906 usb_callout_init_mtx(&xfer->timeout_handle,
907 &udev->bus->bus_mtx, 0);
910 * Setup a dummy xfer, hence we are
911 * writing to the "usb_xfer"
912 * structure pointed to by "xfer"
913 * before we have allocated any
917 bzero(&dummy, sizeof(dummy));
921 /* set transfer endpoint pointer */
924 parm.size[0] += sizeof(xfer[0]);
925 parm.methods = xfer->endpoint->methods;
926 parm.curr_xfer = xfer;
929 * Call the Host or Device controller transfer
932 (udev->bus->methods->xfer_setup) (&parm);
934 /* check for error */
940 * Increment the endpoint refcount. This
941 * basically prevents setting a new
942 * configuration and alternate setting
943 * when USB transfers are in use on
944 * the given interface. Search the USB
945 * code for "endpoint->refcount_alloc" if you
946 * want more information.
948 USB_BUS_LOCK(info->bus);
949 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
950 parm.err = USB_ERR_INVAL;
952 xfer->endpoint->refcount_alloc++;
954 if (xfer->endpoint->refcount_alloc == 0)
955 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
956 USB_BUS_UNLOCK(info->bus);
959 * Whenever we set ppxfer[] then we
960 * also need to increment the
963 info->setup_refcount++;
966 * Transfer is successfully setup and
972 /* check for error */
977 if (buf || parm.err) {
981 /* no transfers - nothing to do ! */
984 /* align data properly */
985 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
987 /* store offset temporarily */
988 parm.size[1] = parm.size[0];
991 * The number of DMA tags required depends on
992 * the number of endpoints. The current estimate
993 * for maximum number of DMA tags per endpoint
996 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
999 * DMA tags for QH, TD, Data and more.
1001 parm.dma_tag_max += 8;
1003 parm.dma_tag_p += parm.dma_tag_max;
1005 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1008 /* align data properly */
1009 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1011 /* store offset temporarily */
1012 parm.size[3] = parm.size[0];
1014 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1017 /* align data properly */
1018 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1020 /* store offset temporarily */
1021 parm.size[4] = parm.size[0];
1023 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1026 /* store end offset temporarily */
1027 parm.size[5] = parm.size[0];
1029 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1032 /* store end offset temporarily */
1034 parm.size[2] = parm.size[0];
1036 /* align data properly */
1037 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1039 parm.size[6] = parm.size[0];
1041 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1044 /* align data properly */
1045 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1047 /* allocate zeroed memory */
1048 buf = malloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1051 parm.err = USB_ERR_NOMEM;
1052 DPRINTFN(0, "cannot allocate memory block for "
1053 "configuration (%d bytes)\n",
1057 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1058 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1059 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1060 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1061 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1066 if (info->setup_refcount == 0) {
1068 * "usbd_transfer_unsetup_sub" will unlock
1069 * the bus mutex before returning !
1071 USB_BUS_LOCK(info->bus);
1073 /* something went wrong */
1074 usbd_transfer_unsetup_sub(info, 0);
1078 usbd_transfer_unsetup(ppxfer, n_setup);
1083 /*------------------------------------------------------------------------*
1084 * usbd_transfer_unsetup_sub - factored out code
1085 *------------------------------------------------------------------------*/
1087 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1089 struct usb_page_cache *pc;
1091 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1093 /* wait for any outstanding DMA operations */
1097 temp = usbd_get_dma_delay(info->bus);
1098 usb_pause_mtx(&info->bus->bus_mtx,
1099 USB_MS_TO_TICKS(temp));
1102 /* make sure that our done messages are not queued anywhere */
1103 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1105 USB_BUS_UNLOCK(info->bus);
1108 /* free DMA'able memory, if any */
1109 pc = info->dma_page_cache_start;
1110 while (pc != info->dma_page_cache_end) {
1111 usb_pc_free_mem(pc);
1115 /* free DMA maps in all "xfer->frbuffers" */
1116 pc = info->xfer_page_cache_start;
1117 while (pc != info->xfer_page_cache_end) {
1118 usb_pc_dmamap_destroy(pc);
1122 /* free all DMA tags */
1123 usb_dma_tag_unsetup(&info->dma_parent_tag);
1126 cv_destroy(&info->cv_drain);
1129 * free the "memory_base" last, hence the "info" structure is
1130 * contained within the "memory_base"!
1132 free(info->memory_base, M_USB);
1135 /*------------------------------------------------------------------------*
1136 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1138 * NOTE: All USB transfers in progress will get called back passing
1139 * the error code "USB_ERR_CANCELLED" before this function
1141 *------------------------------------------------------------------------*/
1143 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1145 struct usb_xfer *xfer;
1146 struct usb_xfer_root *info;
1147 uint8_t needs_delay = 0;
1149 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1150 "usbd_transfer_unsetup can sleep!");
1153 xfer = pxfer[n_setup];
1160 USB_XFER_LOCK(xfer);
1161 USB_BUS_LOCK(info->bus);
1164 * HINT: when you start/stop a transfer, it might be a
1165 * good idea to directly use the "pxfer[]" structure:
1167 * usbd_transfer_start(sc->pxfer[0]);
1168 * usbd_transfer_stop(sc->pxfer[0]);
1170 * That way, if your code has many parts that will not
1171 * stop running under the same lock, in other words
1172 * "xfer_mtx", the usbd_transfer_start and
1173 * usbd_transfer_stop functions will simply return
1174 * when they detect a NULL pointer argument.
1176 * To avoid any races we clear the "pxfer[]" pointer
1177 * while holding the private mutex of the driver:
1179 pxfer[n_setup] = NULL;
1181 USB_BUS_UNLOCK(info->bus);
1182 USB_XFER_UNLOCK(xfer);
1184 usbd_transfer_drain(xfer);
1187 if (xfer->flags_int.bdma_enable)
1191 * NOTE: default endpoint does not have an
1192 * interface, even if endpoint->iface_index == 0
1194 USB_BUS_LOCK(info->bus);
1195 xfer->endpoint->refcount_alloc--;
1196 USB_BUS_UNLOCK(info->bus);
1198 usb_callout_drain(&xfer->timeout_handle);
1200 USB_BUS_LOCK(info->bus);
1202 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1203 "reference count\n"));
1205 info->setup_refcount--;
1207 if (info->setup_refcount == 0) {
1208 usbd_transfer_unsetup_sub(info,
1211 USB_BUS_UNLOCK(info->bus);
1216 /*------------------------------------------------------------------------*
1217 * usbd_control_transfer_init - factored out code
1219 * In USB Device Mode we have to wait for the SETUP packet which
1220 * containst the "struct usb_device_request" structure, before we can
1221 * transfer any data. In USB Host Mode we already have the SETUP
1222 * packet at the moment the USB transfer is started. This leads us to
1223 * having to setup the USB transfer at two different places in
1224 * time. This function just contains factored out control transfer
1225 * initialisation code, so that we don't duplicate the code.
1226 *------------------------------------------------------------------------*/
1228 usbd_control_transfer_init(struct usb_xfer *xfer)
1230 struct usb_device_request req;
1232 /* copy out the USB request header */
1234 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1236 /* setup remainder */
1238 xfer->flags_int.control_rem = UGETW(req.wLength);
1240 /* copy direction to endpoint variable */
1242 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1244 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1247 /*------------------------------------------------------------------------*
1248 * usbd_setup_ctrl_transfer
1250 * This function handles initialisation of control transfers. Control
1251 * transfers are special in that regard that they can both transmit
1257 *------------------------------------------------------------------------*/
1259 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1263 /* Check for control endpoint stall */
1264 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1265 /* the control transfer is no longer active */
1266 xfer->flags_int.control_stall = 1;
1267 xfer->flags_int.control_act = 0;
1269 /* don't stall control transfer by default */
1270 xfer->flags_int.control_stall = 0;
1273 /* Check for invalid number of frames */
1274 if (xfer->nframes > 2) {
1276 * If you need to split a control transfer, you
1277 * have to do one part at a time. Only with
1278 * non-control transfers you can do multiple
1281 DPRINTFN(0, "Too many frames: %u\n",
1282 (unsigned int)xfer->nframes);
1287 * Check if there is a control
1288 * transfer in progress:
1290 if (xfer->flags_int.control_act) {
1292 if (xfer->flags_int.control_hdr) {
1294 /* clear send header flag */
1296 xfer->flags_int.control_hdr = 0;
1298 /* setup control transfer */
1299 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1300 usbd_control_transfer_init(xfer);
1303 /* get data length */
1309 /* the size of the SETUP structure is hardcoded ! */
1311 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1312 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1313 xfer->frlengths[0], sizeof(struct
1314 usb_device_request));
1317 /* check USB mode */
1318 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1320 /* check number of frames */
1321 if (xfer->nframes != 1) {
1323 * We need to receive the setup
1324 * message first so that we know the
1327 DPRINTF("Misconfigured transfer\n");
1331 * Set a dummy "control_rem" value. This
1332 * variable will be overwritten later by a
1333 * call to "usbd_control_transfer_init()" !
1335 xfer->flags_int.control_rem = 0xFFFF;
1338 /* setup "endpoint" and "control_rem" */
1340 usbd_control_transfer_init(xfer);
1343 /* set transfer-header flag */
1345 xfer->flags_int.control_hdr = 1;
1347 /* get data length */
1349 len = (xfer->sumlen - sizeof(struct usb_device_request));
1352 /* check if there is a length mismatch */
1354 if (len > xfer->flags_int.control_rem) {
1355 DPRINTFN(0, "Length (%d) greater than "
1356 "remaining length (%d)\n", len,
1357 xfer->flags_int.control_rem);
1360 /* check if we are doing a short transfer */
1362 if (xfer->flags.force_short_xfer) {
1363 xfer->flags_int.control_rem = 0;
1365 if ((len != xfer->max_data_length) &&
1366 (len != xfer->flags_int.control_rem) &&
1367 (xfer->nframes != 1)) {
1368 DPRINTFN(0, "Short control transfer without "
1369 "force_short_xfer set\n");
1372 xfer->flags_int.control_rem -= len;
1375 /* the status part is executed when "control_act" is 0 */
1377 if ((xfer->flags_int.control_rem > 0) ||
1378 (xfer->flags.manual_status)) {
1379 /* don't execute the STATUS stage yet */
1380 xfer->flags_int.control_act = 1;
1383 if ((!xfer->flags_int.control_hdr) &&
1384 (xfer->nframes == 1)) {
1386 * This is not a valid operation!
1388 DPRINTFN(0, "Invalid parameter "
1393 /* time to execute the STATUS stage */
1394 xfer->flags_int.control_act = 0;
1396 return (0); /* success */
1399 return (1); /* failure */
1402 /*------------------------------------------------------------------------*
1403 * usbd_transfer_submit - start USB hardware for the given transfer
1405 * This function should only be called from the USB callback.
1406 *------------------------------------------------------------------------*/
1408 usbd_transfer_submit(struct usb_xfer *xfer)
1410 struct usb_xfer_root *info;
1411 struct usb_bus *bus;
1417 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1418 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1422 if (USB_DEBUG_VAR > 0) {
1425 usb_dump_endpoint(xfer->endpoint);
1427 USB_BUS_UNLOCK(bus);
1431 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1432 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1434 /* Only open the USB transfer once! */
1435 if (!xfer->flags_int.open) {
1436 xfer->flags_int.open = 1;
1441 (xfer->endpoint->methods->open) (xfer);
1442 USB_BUS_UNLOCK(bus);
1444 /* set "transferring" flag */
1445 xfer->flags_int.transferring = 1;
1448 /* increment power reference */
1449 usbd_transfer_power_ref(xfer, 1);
1452 * Check if the transfer is waiting on a queue, most
1453 * frequently the "done_q":
1455 if (xfer->wait_queue) {
1457 usbd_transfer_dequeue(xfer);
1458 USB_BUS_UNLOCK(bus);
1460 /* clear "did_dma_delay" flag */
1461 xfer->flags_int.did_dma_delay = 0;
1463 /* clear "did_close" flag */
1464 xfer->flags_int.did_close = 0;
1467 /* clear "bdma_setup" flag */
1468 xfer->flags_int.bdma_setup = 0;
1470 /* by default we cannot cancel any USB transfer immediately */
1471 xfer->flags_int.can_cancel_immed = 0;
1473 /* clear lengths and frame counts by default */
1478 /* clear any previous errors */
1481 /* Check if the device is still alive */
1482 if (info->udev->state < USB_STATE_POWERED) {
1485 * Must return cancelled error code else
1486 * device drivers can hang.
1488 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1489 USB_BUS_UNLOCK(bus);
1494 if (xfer->nframes == 0) {
1495 if (xfer->flags.stall_pipe) {
1497 * Special case - want to stall without transferring
1500 DPRINTF("xfer=%p nframes=0: stall "
1501 "or clear stall!\n", xfer);
1503 xfer->flags_int.can_cancel_immed = 1;
1504 /* start the transfer */
1505 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1506 USB_BUS_UNLOCK(bus);
1510 usbd_transfer_done(xfer, USB_ERR_INVAL);
1511 USB_BUS_UNLOCK(bus);
1514 /* compute total transfer length */
1516 for (x = 0; x != xfer->nframes; x++) {
1517 xfer->sumlen += xfer->frlengths[x];
1518 if (xfer->sumlen < xfer->frlengths[x]) {
1519 /* length wrapped around */
1521 usbd_transfer_done(xfer, USB_ERR_INVAL);
1522 USB_BUS_UNLOCK(bus);
1527 /* clear some internal flags */
1529 xfer->flags_int.short_xfer_ok = 0;
1530 xfer->flags_int.short_frames_ok = 0;
1532 /* check if this is a control transfer */
1534 if (xfer->flags_int.control_xfr) {
1536 if (usbd_setup_ctrl_transfer(xfer)) {
1538 usbd_transfer_done(xfer, USB_ERR_STALLED);
1539 USB_BUS_UNLOCK(bus);
1544 * Setup filtered version of some transfer flags,
1545 * in case of data read direction
1547 if (USB_GET_DATA_ISREAD(xfer)) {
1549 if (xfer->flags.short_frames_ok) {
1550 xfer->flags_int.short_xfer_ok = 1;
1551 xfer->flags_int.short_frames_ok = 1;
1552 } else if (xfer->flags.short_xfer_ok) {
1553 xfer->flags_int.short_xfer_ok = 1;
1555 /* check for control transfer */
1556 if (xfer->flags_int.control_xfr) {
1558 * 1) Control transfers do not support
1559 * reception of multiple short USB
1560 * frames in host mode and device side
1561 * mode, with exception of:
1563 * 2) Due to sometimes buggy device
1564 * side firmware we need to do a
1565 * STATUS stage in case of short
1566 * control transfers in USB host mode.
1567 * The STATUS stage then becomes the
1568 * "alt_next" to the DATA stage.
1570 xfer->flags_int.short_frames_ok = 1;
1575 * Check if BUS-DMA support is enabled and try to load virtual
1576 * buffers into DMA, if any:
1579 if (xfer->flags_int.bdma_enable) {
1580 /* insert the USB transfer last in the BUS-DMA queue */
1581 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1586 * Enter the USB transfer into the Host Controller or
1587 * Device Controller schedule:
1589 usbd_pipe_enter(xfer);
1592 /*------------------------------------------------------------------------*
1593 * usbd_pipe_enter - factored out code
1594 *------------------------------------------------------------------------*/
1596 usbd_pipe_enter(struct usb_xfer *xfer)
1598 struct usb_endpoint *ep;
1600 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1602 USB_BUS_LOCK(xfer->xroot->bus);
1604 ep = xfer->endpoint;
1608 /* enter the transfer */
1609 (ep->methods->enter) (xfer);
1611 xfer->flags_int.can_cancel_immed = 1;
1613 /* check for transfer error */
1615 /* some error has happened */
1616 usbd_transfer_done(xfer, 0);
1617 USB_BUS_UNLOCK(xfer->xroot->bus);
1621 /* start the transfer */
1622 usb_command_wrapper(&ep->endpoint_q, xfer);
1623 USB_BUS_UNLOCK(xfer->xroot->bus);
1626 /*------------------------------------------------------------------------*
1627 * usbd_transfer_start - start an USB transfer
1629 * NOTE: Calling this function more than one time will only
1630 * result in a single transfer start, until the USB transfer
1632 *------------------------------------------------------------------------*/
1634 usbd_transfer_start(struct usb_xfer *xfer)
1637 /* transfer is gone */
1640 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1642 /* mark the USB transfer started */
1644 if (!xfer->flags_int.started) {
1645 /* lock the BUS lock to avoid races updating flags_int */
1646 USB_BUS_LOCK(xfer->xroot->bus);
1647 xfer->flags_int.started = 1;
1648 USB_BUS_UNLOCK(xfer->xroot->bus);
1650 /* check if the USB transfer callback is already transferring */
1652 if (xfer->flags_int.transferring) {
1655 USB_BUS_LOCK(xfer->xroot->bus);
1656 /* call the USB transfer callback */
1657 usbd_callback_ss_done_defer(xfer);
1658 USB_BUS_UNLOCK(xfer->xroot->bus);
1661 /*------------------------------------------------------------------------*
1662 * usbd_transfer_stop - stop an USB transfer
1664 * NOTE: Calling this function more than one time will only
1665 * result in a single transfer stop.
1666 * NOTE: When this function returns it is not safe to free nor
1667 * reuse any DMA buffers. See "usbd_transfer_drain()".
1668 *------------------------------------------------------------------------*/
1670 usbd_transfer_stop(struct usb_xfer *xfer)
1672 struct usb_endpoint *ep;
1675 /* transfer is gone */
1678 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1680 /* check if the USB transfer was ever opened */
1682 if (!xfer->flags_int.open) {
1683 if (xfer->flags_int.started) {
1684 /* nothing to do except clearing the "started" flag */
1685 /* lock the BUS lock to avoid races updating flags_int */
1686 USB_BUS_LOCK(xfer->xroot->bus);
1687 xfer->flags_int.started = 0;
1688 USB_BUS_UNLOCK(xfer->xroot->bus);
1692 /* try to stop the current USB transfer */
1694 USB_BUS_LOCK(xfer->xroot->bus);
1695 /* override any previous error */
1696 xfer->error = USB_ERR_CANCELLED;
1699 * Clear "open" and "started" when both private and USB lock
1700 * is locked so that we don't get a race updating "flags_int"
1702 xfer->flags_int.open = 0;
1703 xfer->flags_int.started = 0;
1706 * Check if we can cancel the USB transfer immediately.
1708 if (xfer->flags_int.transferring) {
1709 if (xfer->flags_int.can_cancel_immed &&
1710 (!xfer->flags_int.did_close)) {
1713 * The following will lead to an USB_ERR_CANCELLED
1714 * error code being passed to the USB callback.
1716 (xfer->endpoint->methods->close) (xfer);
1717 /* only close once */
1718 xfer->flags_int.did_close = 1;
1720 /* need to wait for the next done callback */
1725 /* close here and now */
1726 (xfer->endpoint->methods->close) (xfer);
1729 * Any additional DMA delay is done by
1730 * "usbd_transfer_unsetup()".
1734 * Special case. Check if we need to restart a blocked
1737 ep = xfer->endpoint;
1740 * If the current USB transfer is completing we need
1741 * to start the next one:
1743 if (ep->endpoint_q.curr == xfer) {
1744 usb_command_wrapper(&ep->endpoint_q, NULL);
1748 USB_BUS_UNLOCK(xfer->xroot->bus);
1751 /*------------------------------------------------------------------------*
1752 * usbd_transfer_pending
1754 * This function will check if an USB transfer is pending which is a
1755 * little bit complicated!
1758 * 1: Pending: The USB transfer will receive a callback in the future.
1759 *------------------------------------------------------------------------*/
1761 usbd_transfer_pending(struct usb_xfer *xfer)
1763 struct usb_xfer_root *info;
1764 struct usb_xfer_queue *pq;
1767 /* transfer is gone */
1770 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1772 if (xfer->flags_int.transferring) {
1776 USB_BUS_LOCK(xfer->xroot->bus);
1777 if (xfer->wait_queue) {
1778 /* we are waiting on a queue somewhere */
1779 USB_BUS_UNLOCK(xfer->xroot->bus);
1785 if (pq->curr == xfer) {
1786 /* we are currently scheduled for callback */
1787 USB_BUS_UNLOCK(xfer->xroot->bus);
1790 /* we are not pending */
1791 USB_BUS_UNLOCK(xfer->xroot->bus);
1795 /*------------------------------------------------------------------------*
1796 * usbd_transfer_drain
1798 * This function will stop the USB transfer and wait for any
1799 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1800 * are loaded into DMA can safely be freed or reused after that this
1801 * function has returned.
1802 *------------------------------------------------------------------------*/
1804 usbd_transfer_drain(struct usb_xfer *xfer)
1806 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1807 "usbd_transfer_drain can sleep!");
1810 /* transfer is gone */
1813 if (xfer->xroot->xfer_mtx != &Giant) {
1814 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1816 USB_XFER_LOCK(xfer);
1818 usbd_transfer_stop(xfer);
1820 while (usbd_transfer_pending(xfer) ||
1821 xfer->flags_int.doing_callback) {
1824 * It is allowed that the callback can drop its
1825 * transfer mutex. In that case checking only
1826 * "usbd_transfer_pending()" is not enough to tell if
1827 * the USB transfer is fully drained. We also need to
1828 * check the internal "doing_callback" flag.
1830 xfer->flags_int.draining = 1;
1833 * Wait until the current outstanding USB
1834 * transfer is complete !
1836 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1838 USB_XFER_UNLOCK(xfer);
1841 struct usb_page_cache *
1842 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1844 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1846 return (&xfer->frbuffers[frindex]);
1849 /*------------------------------------------------------------------------*
1850 * usbd_xfer_get_fps_shift
1852 * The following function is only useful for isochronous transfers. It
1853 * returns how many times the frame execution rate has been shifted
1859 *------------------------------------------------------------------------*/
1861 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1863 return (xfer->fps_shift);
1867 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1869 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1871 return (xfer->frlengths[frindex]);
1874 /*------------------------------------------------------------------------*
1875 * usbd_xfer_set_frame_data
1877 * This function sets the pointer of the buffer that should
1878 * loaded directly into DMA for the given USB frame. Passing "ptr"
1879 * equal to NULL while the corresponding "frlength" is greater
1880 * than zero gives undefined results!
1881 *------------------------------------------------------------------------*/
1883 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1884 void *ptr, usb_frlength_t len)
1886 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1888 /* set virtual address to load and length */
1889 xfer->frbuffers[frindex].buffer = ptr;
1890 usbd_xfer_set_frame_len(xfer, frindex, len);
1894 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1895 void **ptr, int *len)
1897 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1900 *ptr = xfer->frbuffers[frindex].buffer;
1902 *len = xfer->frlengths[frindex];
1906 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
1910 *actlen = xfer->actlen;
1912 *sumlen = xfer->sumlen;
1913 if (aframes != NULL)
1914 *aframes = xfer->aframes;
1915 if (nframes != NULL)
1916 *nframes = xfer->nframes;
1919 /*------------------------------------------------------------------------*
1920 * usbd_xfer_set_frame_offset
1922 * This function sets the frame data buffer offset relative to the beginning
1923 * of the USB DMA buffer allocated for this USB transfer.
1924 *------------------------------------------------------------------------*/
1926 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
1927 usb_frcount_t frindex)
1929 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
1930 "when the USB buffer is external\n"));
1931 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1933 /* set virtual address to load */
1934 xfer->frbuffers[frindex].buffer =
1935 USB_ADD_BYTES(xfer->local_buffer, offset);
1939 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
1945 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
1951 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
1957 usbd_xfer_max_frames(struct usb_xfer *xfer)
1959 return (xfer->max_frame_count);
1963 usbd_xfer_max_len(struct usb_xfer *xfer)
1965 return (xfer->max_data_length);
1969 usbd_xfer_max_framelen(struct usb_xfer *xfer)
1971 return (xfer->max_frame_size);
1975 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
1978 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1980 xfer->frlengths[frindex] = len;
1983 /*------------------------------------------------------------------------*
1984 * usb_callback_proc - factored out code
1986 * This function performs USB callbacks.
1987 *------------------------------------------------------------------------*/
1989 usb_callback_proc(struct usb_proc_msg *_pm)
1991 struct usb_done_msg *pm = (void *)_pm;
1992 struct usb_xfer_root *info = pm->xroot;
1994 /* Change locking order */
1995 USB_BUS_UNLOCK(info->bus);
1998 * We exploit the fact that the mutex is the same for all
1999 * callbacks that will be called from this thread:
2001 mtx_lock(info->xfer_mtx);
2002 USB_BUS_LOCK(info->bus);
2004 /* Continue where we lost track */
2005 usb_command_wrapper(&info->done_q,
2008 mtx_unlock(info->xfer_mtx);
2011 /*------------------------------------------------------------------------*
2012 * usbd_callback_ss_done_defer
2014 * This function will defer the start, stop and done callback to the
2016 *------------------------------------------------------------------------*/
2018 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2020 struct usb_xfer_root *info = xfer->xroot;
2021 struct usb_xfer_queue *pq = &info->done_q;
2023 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2025 if (pq->curr != xfer) {
2026 usbd_transfer_enqueue(pq, xfer);
2028 if (!pq->recurse_1) {
2031 * We have to postpone the callback due to the fact we
2032 * will have a Lock Order Reversal, LOR, if we try to
2035 if (usb_proc_msignal(info->done_p,
2036 &info->done_m[0], &info->done_m[1])) {
2040 /* clear second recurse flag */
2047 /*------------------------------------------------------------------------*
2048 * usbd_callback_wrapper
2050 * This is a wrapper for USB callbacks. This wrapper does some
2051 * auto-magic things like figuring out if we can call the callback
2052 * directly from the current context or if we need to wakeup the
2053 * interrupt process.
2054 *------------------------------------------------------------------------*/
2056 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2058 struct usb_xfer *xfer = pq->curr;
2059 struct usb_xfer_root *info = xfer->xroot;
2061 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2062 if (!mtx_owned(info->xfer_mtx)) {
2064 * Cases that end up here:
2066 * 5) HW interrupt done callback or other source.
2068 DPRINTFN(3, "case 5\n");
2071 * We have to postpone the callback due to the fact we
2072 * will have a Lock Order Reversal, LOR, if we try to
2075 if (usb_proc_msignal(info->done_p,
2076 &info->done_m[0], &info->done_m[1])) {
2082 * Cases that end up here:
2084 * 1) We are starting a transfer
2085 * 2) We are prematurely calling back a transfer
2086 * 3) We are stopping a transfer
2087 * 4) We are doing an ordinary callback
2089 DPRINTFN(3, "case 1-4\n");
2090 /* get next USB transfer in the queue */
2091 info->done_q.curr = NULL;
2093 /* set flag in case of drain */
2094 xfer->flags_int.doing_callback = 1;
2096 USB_BUS_UNLOCK(info->bus);
2097 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2099 /* set correct USB state for callback */
2100 if (!xfer->flags_int.transferring) {
2101 xfer->usb_state = USB_ST_SETUP;
2102 if (!xfer->flags_int.started) {
2103 /* we got stopped before we even got started */
2104 USB_BUS_LOCK(info->bus);
2109 if (usbd_callback_wrapper_sub(xfer)) {
2110 /* the callback has been deferred */
2111 USB_BUS_LOCK(info->bus);
2115 /* decrement power reference */
2116 usbd_transfer_power_ref(xfer, -1);
2118 xfer->flags_int.transferring = 0;
2121 xfer->usb_state = USB_ST_ERROR;
2123 /* set transferred state */
2124 xfer->usb_state = USB_ST_TRANSFERRED;
2126 /* sync DMA memory, if any */
2127 if (xfer->flags_int.bdma_enable &&
2128 (!xfer->flags_int.bdma_no_post_sync)) {
2129 usb_bdma_post_sync(xfer);
2135 /* call processing routine */
2136 (xfer->callback) (xfer, xfer->error);
2138 /* pickup the USB mutex again */
2139 USB_BUS_LOCK(info->bus);
2142 * Check if we got started after that we got cancelled, but
2143 * before we managed to do the callback.
2145 if ((!xfer->flags_int.open) &&
2146 (xfer->flags_int.started) &&
2147 (xfer->usb_state == USB_ST_ERROR)) {
2148 /* clear flag in case of drain */
2149 xfer->flags_int.doing_callback = 0;
2150 /* try to loop, but not recursivly */
2151 usb_command_wrapper(&info->done_q, xfer);
2156 /* clear flag in case of drain */
2157 xfer->flags_int.doing_callback = 0;
2160 * Check if we are draining.
2162 if (xfer->flags_int.draining &&
2163 (!xfer->flags_int.transferring)) {
2164 /* "usbd_transfer_drain()" is waiting for end of transfer */
2165 xfer->flags_int.draining = 0;
2166 cv_broadcast(&info->cv_drain);
2169 /* do the next callback, if any */
2170 usb_command_wrapper(&info->done_q,
2174 /*------------------------------------------------------------------------*
2175 * usb_dma_delay_done_cb
2177 * This function is called when the DMA delay has been exectuded, and
2178 * will make sure that the callback is called to complete the USB
2179 * transfer. This code path is ususally only used when there is an USB
2180 * error like USB_ERR_CANCELLED.
2181 *------------------------------------------------------------------------*/
2183 usb_dma_delay_done_cb(void *arg)
2185 struct usb_xfer *xfer = arg;
2187 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2189 DPRINTFN(3, "Completed %p\n", xfer);
2191 /* queue callback for execution, again */
2192 usbd_transfer_done(xfer, 0);
2195 /*------------------------------------------------------------------------*
2196 * usbd_transfer_dequeue
2198 * - This function is used to remove an USB transfer from a USB
2201 * - This function can be called multiple times in a row.
2202 *------------------------------------------------------------------------*/
2204 usbd_transfer_dequeue(struct usb_xfer *xfer)
2206 struct usb_xfer_queue *pq;
2208 pq = xfer->wait_queue;
2210 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2211 xfer->wait_queue = NULL;
2215 /*------------------------------------------------------------------------*
2216 * usbd_transfer_enqueue
2218 * - This function is used to insert an USB transfer into a USB *
2221 * - This function can be called multiple times in a row.
2222 *------------------------------------------------------------------------*/
2224 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2227 * Insert the USB transfer into the queue, if it is not
2228 * already on a USB transfer queue:
2230 if (xfer->wait_queue == NULL) {
2231 xfer->wait_queue = pq;
2232 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2236 /*------------------------------------------------------------------------*
2237 * usbd_transfer_done
2239 * - This function is used to remove an USB transfer from the busdma,
2240 * pipe or interrupt queue.
2242 * - This function is used to queue the USB transfer on the done
2245 * - This function is used to stop any USB transfer timeouts.
2246 *------------------------------------------------------------------------*/
2248 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2250 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2252 DPRINTF("err=%s\n", usbd_errstr(error));
2255 * If we are not transferring then just return.
2256 * This can happen during transfer cancel.
2258 if (!xfer->flags_int.transferring) {
2259 DPRINTF("not transferring\n");
2260 /* end of control transfer, if any */
2261 xfer->flags_int.control_act = 0;
2264 /* only set transfer error if not already set */
2266 xfer->error = error;
2268 /* stop any callouts */
2269 usb_callout_stop(&xfer->timeout_handle);
2272 * If we are waiting on a queue, just remove the USB transfer
2273 * from the queue, if any. We should have the required locks
2274 * locked to do the remove when this function is called.
2276 usbd_transfer_dequeue(xfer);
2279 if (mtx_owned(xfer->xroot->xfer_mtx)) {
2280 struct usb_xfer_queue *pq;
2283 * If the private USB lock is not locked, then we assume
2284 * that the BUS-DMA load stage has been passed:
2286 pq = &xfer->xroot->dma_q;
2288 if (pq->curr == xfer) {
2289 /* start the next BUS-DMA load, if any */
2290 usb_command_wrapper(pq, NULL);
2294 /* keep some statistics */
2296 xfer->xroot->bus->stats_err.uds_requests
2297 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2299 xfer->xroot->bus->stats_ok.uds_requests
2300 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2303 /* call the USB transfer callback */
2304 usbd_callback_ss_done_defer(xfer);
2307 /*------------------------------------------------------------------------*
2308 * usbd_transfer_start_cb
2310 * This function is called to start the USB transfer when
2311 * "xfer->interval" is greater than zero, and and the endpoint type is
2313 *------------------------------------------------------------------------*/
2315 usbd_transfer_start_cb(void *arg)
2317 struct usb_xfer *xfer = arg;
2318 struct usb_endpoint *ep = xfer->endpoint;
2320 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2324 /* start the transfer */
2325 (ep->methods->start) (xfer);
2327 xfer->flags_int.can_cancel_immed = 1;
2329 /* check for error */
2331 /* some error has happened */
2332 usbd_transfer_done(xfer, 0);
2336 /*------------------------------------------------------------------------*
2337 * usbd_xfer_set_stall
2339 * This function is used to set the stall flag outside the
2340 * callback. This function is NULL safe.
2341 *------------------------------------------------------------------------*/
2343 usbd_xfer_set_stall(struct usb_xfer *xfer)
2349 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2351 /* avoid any races by locking the USB mutex */
2352 USB_BUS_LOCK(xfer->xroot->bus);
2353 xfer->flags.stall_pipe = 1;
2354 USB_BUS_UNLOCK(xfer->xroot->bus);
2358 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2360 return (xfer->endpoint->is_stalled);
2363 /*------------------------------------------------------------------------*
2364 * usbd_transfer_clear_stall
2366 * This function is used to clear the stall flag outside the
2367 * callback. This function is NULL safe.
2368 *------------------------------------------------------------------------*/
2370 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2376 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2378 /* avoid any races by locking the USB mutex */
2379 USB_BUS_LOCK(xfer->xroot->bus);
2381 xfer->flags.stall_pipe = 0;
2383 USB_BUS_UNLOCK(xfer->xroot->bus);
2386 /*------------------------------------------------------------------------*
2389 * This function is used to add an USB transfer to the pipe transfer list.
2390 *------------------------------------------------------------------------*/
2392 usbd_pipe_start(struct usb_xfer_queue *pq)
2394 struct usb_endpoint *ep;
2395 struct usb_xfer *xfer;
2399 ep = xfer->endpoint;
2401 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2404 * If the endpoint is already stalled we do nothing !
2406 if (ep->is_stalled) {
2410 * Check if we are supposed to stall the endpoint:
2412 if (xfer->flags.stall_pipe) {
2413 struct usb_device *udev;
2414 struct usb_xfer_root *info;
2416 /* clear stall command */
2417 xfer->flags.stall_pipe = 0;
2419 /* get pointer to USB device */
2424 * Only stall BULK and INTERRUPT endpoints.
2426 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2427 if ((type == UE_BULK) ||
2428 (type == UE_INTERRUPT)) {
2433 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2434 (udev->bus->methods->set_stall) (
2435 udev, NULL, ep, &did_stall);
2436 } else if (udev->ctrl_xfer[1]) {
2437 info = udev->ctrl_xfer[1]->xroot;
2439 &info->bus->non_giant_callback_proc,
2440 &udev->cs_msg[0], &udev->cs_msg[1]);
2442 /* should not happen */
2443 DPRINTFN(0, "No stall handler\n");
2446 * Check if we should stall. Some USB hardware
2447 * handles set- and clear-stall in hardware.
2451 * The transfer will be continued when
2452 * the clear-stall control endpoint
2453 * message is received.
2458 } else if (type == UE_ISOCHRONOUS) {
2461 * Make sure any FIFO overflow or other FIFO
2462 * error conditions go away by resetting the
2463 * endpoint FIFO through the clear stall
2466 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2467 (udev->bus->methods->clear_stall) (udev, ep);
2471 /* Set or clear stall complete - special case */
2472 if (xfer->nframes == 0) {
2473 /* we are complete */
2475 usbd_transfer_done(xfer, 0);
2481 * 1) Start the first transfer queued.
2483 * 2) Re-start the current USB transfer.
2486 * Check if there should be any
2487 * pre transfer start delay:
2489 if (xfer->interval > 0) {
2490 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2491 if ((type == UE_BULK) ||
2492 (type == UE_CONTROL)) {
2493 usbd_transfer_timeout_ms(xfer,
2494 &usbd_transfer_start_cb,
2501 /* start USB transfer */
2502 (ep->methods->start) (xfer);
2504 xfer->flags_int.can_cancel_immed = 1;
2506 /* check for error */
2508 /* some error has happened */
2509 usbd_transfer_done(xfer, 0);
2513 /*------------------------------------------------------------------------*
2514 * usbd_transfer_timeout_ms
2516 * This function is used to setup a timeout on the given USB
2517 * transfer. If the timeout has been deferred the callback given by
2518 * "cb" will get called after "ms" milliseconds.
2519 *------------------------------------------------------------------------*/
2521 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2522 void (*cb) (void *arg), usb_timeout_t ms)
2524 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2527 usb_callout_reset(&xfer->timeout_handle,
2528 USB_MS_TO_TICKS(ms), cb, xfer);
2531 /*------------------------------------------------------------------------*
2532 * usbd_callback_wrapper_sub
2534 * - This function will update variables in an USB transfer after
2535 * that the USB transfer is complete.
2537 * - This function is used to start the next USB transfer on the
2538 * ep transfer queue, if any.
2540 * NOTE: In some special cases the USB transfer will not be removed from
2541 * the pipe queue, but remain first. To enforce USB transfer removal call
2542 * this function passing the error code "USB_ERR_CANCELLED".
2546 * Else: The callback has been deferred.
2547 *------------------------------------------------------------------------*/
2549 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2551 struct usb_endpoint *ep;
2554 if ((!xfer->flags_int.open) &&
2555 (!xfer->flags_int.did_close)) {
2557 USB_BUS_LOCK(xfer->xroot->bus);
2558 (xfer->endpoint->methods->close) (xfer);
2559 USB_BUS_UNLOCK(xfer->xroot->bus);
2560 /* only close once */
2561 xfer->flags_int.did_close = 1;
2562 return (1); /* wait for new callback */
2565 * If we have a non-hardware induced error we
2566 * need to do the DMA delay!
2568 if (((xfer->error == USB_ERR_CANCELLED) ||
2569 (xfer->error == USB_ERR_TIMEOUT)) &&
2570 (!xfer->flags_int.did_dma_delay)) {
2574 /* only delay once */
2575 xfer->flags_int.did_dma_delay = 1;
2577 /* we can not cancel this delay */
2578 xfer->flags_int.can_cancel_immed = 0;
2580 temp = usbd_get_dma_delay(xfer->xroot->bus);
2582 DPRINTFN(3, "DMA delay, %u ms, "
2583 "on %p\n", temp, xfer);
2586 USB_BUS_LOCK(xfer->xroot->bus);
2587 usbd_transfer_timeout_ms(xfer,
2588 &usb_dma_delay_done_cb, temp);
2589 USB_BUS_UNLOCK(xfer->xroot->bus);
2590 return (1); /* wait for new callback */
2593 /* check actual number of frames */
2594 if (xfer->aframes > xfer->nframes) {
2595 if (xfer->error == 0) {
2596 panic("%s: actual number of frames, %d, is "
2597 "greater than initial number of frames, %d\n",
2598 __FUNCTION__, xfer->aframes, xfer->nframes);
2600 /* just set some valid value */
2601 xfer->aframes = xfer->nframes;
2604 /* compute actual length */
2607 for (x = 0; x != xfer->aframes; x++) {
2608 xfer->actlen += xfer->frlengths[x];
2612 * Frames that were not transferred get zero actual length in
2613 * case the USB device driver does not check the actual number
2614 * of frames transferred, "xfer->aframes":
2616 for (; x < xfer->nframes; x++) {
2617 usbd_xfer_set_frame_len(xfer, x, 0);
2620 /* check actual length */
2621 if (xfer->actlen > xfer->sumlen) {
2622 if (xfer->error == 0) {
2623 panic("%s: actual length, %d, is greater than "
2624 "initial length, %d\n",
2625 __FUNCTION__, xfer->actlen, xfer->sumlen);
2627 /* just set some valid value */
2628 xfer->actlen = xfer->sumlen;
2631 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2632 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2633 xfer->aframes, xfer->nframes);
2636 /* end of control transfer, if any */
2637 xfer->flags_int.control_act = 0;
2639 /* check if we should block the execution queue */
2640 if ((xfer->error != USB_ERR_CANCELLED) &&
2641 (xfer->flags.pipe_bof)) {
2642 DPRINTFN(2, "xfer=%p: Block On Failure "
2643 "on endpoint=%p\n", xfer, xfer->endpoint);
2647 /* check for short transfers */
2648 if (xfer->actlen < xfer->sumlen) {
2650 /* end of control transfer, if any */
2651 xfer->flags_int.control_act = 0;
2653 if (!xfer->flags_int.short_xfer_ok) {
2654 xfer->error = USB_ERR_SHORT_XFER;
2655 if (xfer->flags.pipe_bof) {
2656 DPRINTFN(2, "xfer=%p: Block On Failure on "
2657 "Short Transfer on endpoint %p.\n",
2658 xfer, xfer->endpoint);
2664 * Check if we are in the middle of a
2667 if (xfer->flags_int.control_act) {
2668 DPRINTFN(5, "xfer=%p: Control transfer "
2669 "active on endpoint=%p\n", xfer, xfer->endpoint);
2675 ep = xfer->endpoint;
2678 * If the current USB transfer is completing we need to start the
2681 USB_BUS_LOCK(xfer->xroot->bus);
2682 if (ep->endpoint_q.curr == xfer) {
2683 usb_command_wrapper(&ep->endpoint_q, NULL);
2685 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2686 /* there is another USB transfer waiting */
2688 /* this is the last USB transfer */
2689 /* clear isochronous sync flag */
2690 xfer->endpoint->is_synced = 0;
2693 USB_BUS_UNLOCK(xfer->xroot->bus);
2698 /*------------------------------------------------------------------------*
2699 * usb_command_wrapper
2701 * This function is used to execute commands non-recursivly on an USB
2703 *------------------------------------------------------------------------*/
2705 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2709 * If the transfer is not already processing,
2712 if (pq->curr != xfer) {
2713 usbd_transfer_enqueue(pq, xfer);
2714 if (pq->curr != NULL) {
2715 /* something is already processing */
2716 DPRINTFN(6, "busy %p\n", pq->curr);
2721 /* Get next element in queue */
2725 if (!pq->recurse_1) {
2729 /* set both recurse flags */
2733 if (pq->curr == NULL) {
2734 xfer = TAILQ_FIRST(&pq->head);
2736 TAILQ_REMOVE(&pq->head, xfer,
2738 xfer->wait_queue = NULL;
2744 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2746 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2748 } while (!pq->recurse_2);
2750 /* clear first recurse flag */
2754 /* clear second recurse flag */
2759 /*------------------------------------------------------------------------*
2760 * usbd_ctrl_transfer_setup
2762 * This function is used to setup the default USB control endpoint
2764 *------------------------------------------------------------------------*/
2766 usbd_ctrl_transfer_setup(struct usb_device *udev)
2768 struct usb_xfer *xfer;
2770 uint8_t iface_index;
2772 /* check for root HUB */
2773 if (udev->parent_hub == NULL)
2777 xfer = udev->ctrl_xfer[0];
2779 USB_XFER_LOCK(xfer);
2781 ((xfer->address == udev->address) &&
2782 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2783 udev->ddesc.bMaxPacketSize));
2784 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2787 * NOTE: checking "xfer->address" and
2788 * starting the USB transfer must be
2791 usbd_transfer_start(xfer);
2794 USB_XFER_UNLOCK(xfer);
2801 * All parameters are exactly the same like before.
2807 * Update wMaxPacketSize for the default control endpoint:
2809 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2810 udev->ddesc.bMaxPacketSize;
2813 * Unsetup any existing USB transfer:
2815 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2818 * Try to setup a new USB transfer for the
2819 * default control endpoint:
2822 if (usbd_transfer_setup(udev, &iface_index,
2823 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2824 &udev->device_mtx)) {
2825 DPRINTFN(0, "could not setup default "
2832 /*------------------------------------------------------------------------*
2833 * usbd_clear_data_toggle - factored out code
2835 * NOTE: the intention of this function is not to reset the hardware
2837 *------------------------------------------------------------------------*/
2839 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2841 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2843 USB_BUS_LOCK(udev->bus);
2844 ep->toggle_next = 0;
2845 USB_BUS_UNLOCK(udev->bus);
2848 /*------------------------------------------------------------------------*
2849 * usbd_clear_stall_callback - factored out clear stall callback
2852 * xfer1: Clear Stall Control Transfer
2853 * xfer2: Stalled USB Transfer
2855 * This function is NULL safe.
2861 * Clear stall config example:
2863 * static const struct usb_config my_clearstall = {
2864 * .type = UE_CONTROL,
2866 * .direction = UE_DIR_ANY,
2867 * .interval = 50, //50 milliseconds
2868 * .bufsize = sizeof(struct usb_device_request),
2869 * .timeout = 1000, //1.000 seconds
2870 * .callback = &my_clear_stall_callback, // **
2871 * .usb_mode = USB_MODE_HOST,
2874 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
2875 * passing the correct parameters.
2876 *------------------------------------------------------------------------*/
2878 usbd_clear_stall_callback(struct usb_xfer *xfer1,
2879 struct usb_xfer *xfer2)
2881 struct usb_device_request req;
2883 if (xfer2 == NULL) {
2884 /* looks like we are tearing down */
2885 DPRINTF("NULL input parameter\n");
2888 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
2889 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
2891 switch (USB_GET_STATE(xfer1)) {
2895 * pre-clear the data toggle to DATA0 ("umass.c" and
2896 * "ata-usb.c" depends on this)
2899 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
2901 /* setup a clear-stall packet */
2903 req.bmRequestType = UT_WRITE_ENDPOINT;
2904 req.bRequest = UR_CLEAR_FEATURE;
2905 USETW(req.wValue, UF_ENDPOINT_HALT);
2906 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
2908 USETW(req.wLength, 0);
2911 * "usbd_transfer_setup_sub()" will ensure that
2912 * we have sufficient room in the buffer for
2913 * the request structure!
2916 /* copy in the transfer */
2918 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
2921 xfer1->frlengths[0] = sizeof(req);
2924 usbd_transfer_submit(xfer1);
2927 case USB_ST_TRANSFERRED:
2930 default: /* Error */
2931 if (xfer1->error == USB_ERR_CANCELLED) {
2936 return (1); /* Clear Stall Finished */
2939 /*------------------------------------------------------------------------*
2940 * usbd_transfer_poll
2942 * The following function gets called from the USB keyboard driver and
2943 * UMASS when the system has paniced.
2945 * NOTE: It is currently not possible to resume normal operation on
2946 * the USB controller which has been polled, due to clearing of the
2947 * "up_dsleep" and "up_msleep" flags.
2948 *------------------------------------------------------------------------*/
2950 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
2952 struct usb_xfer *xfer;
2953 struct usb_xfer_root *xroot;
2954 struct usb_device *udev;
2955 struct usb_proc_msg *pm;
2960 for (n = 0; n != max; n++) {
2961 /* Extra checks to avoid panic */
2964 continue; /* no USB transfer */
2965 xroot = xfer->xroot;
2967 continue; /* no USB root */
2970 continue; /* no USB device */
2971 if (udev->bus == NULL)
2972 continue; /* no BUS structure */
2973 if (udev->bus->methods == NULL)
2974 continue; /* no BUS methods */
2975 if (udev->bus->methods->xfer_poll == NULL)
2976 continue; /* no poll method */
2978 /* make sure that the BUS mutex is not locked */
2980 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
2981 mtx_unlock(&xroot->udev->bus->bus_mtx);
2985 /* make sure that the transfer mutex is not locked */
2987 while (mtx_owned(xroot->xfer_mtx)) {
2988 mtx_unlock(xroot->xfer_mtx);
2992 /* Make sure cv_signal() and cv_broadcast() is not called */
2993 udev->bus->control_xfer_proc.up_msleep = 0;
2994 udev->bus->explore_proc.up_msleep = 0;
2995 udev->bus->giant_callback_proc.up_msleep = 0;
2996 udev->bus->non_giant_callback_proc.up_msleep = 0;
2998 /* poll USB hardware */
2999 (udev->bus->methods->xfer_poll) (udev->bus);
3001 USB_BUS_LOCK(xroot->bus);
3003 /* check for clear stall */
3004 if (udev->ctrl_xfer[1] != NULL) {
3006 /* poll clear stall start */
3007 pm = &udev->cs_msg[0].hdr;
3008 (pm->pm_callback) (pm);
3009 /* poll clear stall done thread */
3010 pm = &udev->ctrl_xfer[1]->
3011 xroot->done_m[0].hdr;
3012 (pm->pm_callback) (pm);
3015 /* poll done thread */
3016 pm = &xroot->done_m[0].hdr;
3017 (pm->pm_callback) (pm);
3019 USB_BUS_UNLOCK(xroot->bus);
3021 /* restore transfer mutex */
3023 mtx_lock(xroot->xfer_mtx);
3025 /* restore BUS mutex */
3027 mtx_lock(&xroot->udev->bus->bus_mtx);
3032 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3033 uint8_t type, enum usb_dev_speed speed)
3035 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3036 [USB_SPEED_LOW] = 8,
3037 [USB_SPEED_FULL] = 64,
3038 [USB_SPEED_HIGH] = 1024,
3039 [USB_SPEED_VARIABLE] = 1024,
3040 [USB_SPEED_SUPER] = 1024,
3043 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3044 [USB_SPEED_LOW] = 0, /* invalid */
3045 [USB_SPEED_FULL] = 1023,
3046 [USB_SPEED_HIGH] = 1024,
3047 [USB_SPEED_VARIABLE] = 3584,
3048 [USB_SPEED_SUPER] = 1024,
3051 static const uint16_t control_min[USB_SPEED_MAX] = {
3052 [USB_SPEED_LOW] = 8,
3053 [USB_SPEED_FULL] = 8,
3054 [USB_SPEED_HIGH] = 64,
3055 [USB_SPEED_VARIABLE] = 512,
3056 [USB_SPEED_SUPER] = 512,
3059 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3060 [USB_SPEED_LOW] = 0, /* not supported */
3061 [USB_SPEED_FULL] = 8,
3062 [USB_SPEED_HIGH] = 512,
3063 [USB_SPEED_VARIABLE] = 512,
3064 [USB_SPEED_SUPER] = 1024,
3069 memset(ptr, 0, sizeof(*ptr));
3073 ptr->range.max = intr_range_max[speed];
3075 case UE_ISOCHRONOUS:
3076 ptr->range.max = isoc_range_max[speed];
3079 if (type == UE_BULK)
3080 temp = bulk_min[speed];
3081 else /* UE_CONTROL */
3082 temp = control_min[speed];
3084 /* default is fixed */
3085 ptr->fixed[0] = temp;
3086 ptr->fixed[1] = temp;
3087 ptr->fixed[2] = temp;
3088 ptr->fixed[3] = temp;
3090 if (speed == USB_SPEED_FULL) {
3091 /* multiple sizes */
3096 if ((speed == USB_SPEED_VARIABLE) &&
3097 (type == UE_BULK)) {
3098 /* multiple sizes */
3099 ptr->fixed[2] = 1024;
3100 ptr->fixed[3] = 1536;
3107 usbd_xfer_softc(struct usb_xfer *xfer)
3109 return (xfer->priv_sc);
3113 usbd_xfer_get_priv(struct usb_xfer *xfer)
3115 return (xfer->priv_fifo);
3119 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3121 xfer->priv_fifo = ptr;
3125 usbd_xfer_state(struct usb_xfer *xfer)
3127 return (xfer->usb_state);
3131 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3134 case USB_FORCE_SHORT_XFER:
3135 xfer->flags.force_short_xfer = 1;
3137 case USB_SHORT_XFER_OK:
3138 xfer->flags.short_xfer_ok = 1;
3140 case USB_MULTI_SHORT_OK:
3141 xfer->flags.short_frames_ok = 1;
3143 case USB_MANUAL_STATUS:
3144 xfer->flags.manual_status = 1;
3150 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3153 case USB_FORCE_SHORT_XFER:
3154 xfer->flags.force_short_xfer = 0;
3156 case USB_SHORT_XFER_OK:
3157 xfer->flags.short_xfer_ok = 0;
3159 case USB_MULTI_SHORT_OK:
3160 xfer->flags.short_frames_ok = 0;
3162 case USB_MANUAL_STATUS:
3163 xfer->flags.manual_status = 0;
3169 * The following function returns in milliseconds when the isochronous
3170 * transfer was completed by the hardware. The returned value wraps
3171 * around 65536 milliseconds.
3174 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3176 return (xfer->isoc_time_complete);