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 usbd_transfer_start_cb(void *);
113 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
114 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
115 uint8_t type, enum usb_dev_speed speed);
117 /*------------------------------------------------------------------------*
118 * usb_request_callback
119 *------------------------------------------------------------------------*/
121 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
123 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
124 usb_handle_request_callback(xfer, error);
126 usbd_do_request_callback(xfer, error);
129 /*------------------------------------------------------------------------*
130 * usbd_update_max_frame_size
132 * This function updates the maximum frame size, hence high speed USB
133 * can transfer multiple consecutive packets.
134 *------------------------------------------------------------------------*/
136 usbd_update_max_frame_size(struct usb_xfer *xfer)
138 /* compute maximum frame size */
139 /* this computation should not overflow 16-bit */
140 /* max = 15 * 1024 */
142 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
145 /*------------------------------------------------------------------------*
148 * The following function is called when we need to
149 * synchronize with DMA hardware.
152 * 0: no DMA delay required
153 * Else: milliseconds of DMA delay
154 *------------------------------------------------------------------------*/
156 usbd_get_dma_delay(struct usb_device *udev)
158 struct usb_bus_methods *mtod;
161 mtod = udev->bus->methods;
164 if (mtod->get_dma_delay) {
165 (mtod->get_dma_delay) (udev, &temp);
167 * Round up and convert to milliseconds. Note that we use
168 * 1024 milliseconds per second. to save a division.
176 /*------------------------------------------------------------------------*
177 * usbd_transfer_setup_sub_malloc
179 * This function will allocate one or more DMA'able memory chunks
180 * according to "size", "align" and "count" arguments. "ppc" is
181 * pointed to a linear array of USB page caches afterwards.
186 *------------------------------------------------------------------------*/
189 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
190 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
193 struct usb_page_cache *pc;
203 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
205 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
208 return (0); /* nothing to allocate */
211 * Make sure that the size is aligned properly.
213 size = -((-size) & (-align));
216 * Try multi-allocation chunks to reduce the number of DMA
217 * allocations, hence DMA allocations are slow.
219 if (size >= PAGE_SIZE) {
223 /* compute number of objects per page */
224 n_obj = (PAGE_SIZE / size);
226 * Compute number of DMA chunks, rounded up
229 n_dma_pc = ((count + n_obj - 1) / n_obj);
232 if (parm->buf == NULL) {
234 parm->dma_page_ptr += n_dma_pc;
235 parm->dma_page_cache_ptr += n_dma_pc;
236 parm->dma_page_ptr += count;
237 parm->xfer_page_cache_ptr += count;
240 for (x = 0; x != n_dma_pc; x++) {
241 /* need to initialize the page cache */
242 parm->dma_page_cache_ptr[x].tag_parent =
243 &parm->curr_xfer->xroot->dma_parent_tag;
245 for (x = 0; x != count; x++) {
246 /* need to initialize the page cache */
247 parm->xfer_page_cache_ptr[x].tag_parent =
248 &parm->curr_xfer->xroot->dma_parent_tag;
252 *ppc = parm->xfer_page_cache_ptr;
254 r = count; /* set remainder count */
255 z = n_obj * size; /* set allocation size */
256 pc = parm->xfer_page_cache_ptr;
257 pg = parm->dma_page_ptr;
259 for (x = 0; x != n_dma_pc; x++) {
262 /* compute last remainder */
266 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
268 return (1); /* failure */
270 /* Set beginning of current buffer */
271 buf = parm->dma_page_cache_ptr->buffer;
272 /* Make room for one DMA page cache and one page */
273 parm->dma_page_cache_ptr++;
276 for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
278 /* Load sub-chunk into DMA */
279 if (usb_pc_dmamap_create(pc, size)) {
280 return (1); /* failure */
282 pc->buffer = USB_ADD_BYTES(buf, y * size);
285 mtx_lock(pc->tag_parent->mtx);
286 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
287 mtx_unlock(pc->tag_parent->mtx);
288 return (1); /* failure */
290 mtx_unlock(pc->tag_parent->mtx);
294 parm->xfer_page_cache_ptr = pc;
295 parm->dma_page_ptr = pg;
300 /*------------------------------------------------------------------------*
301 * usbd_transfer_setup_sub - transfer setup subroutine
303 * This function must be called from the "xfer_setup" callback of the
304 * USB Host or Device controller driver when setting up an USB
305 * transfer. This function will setup correct packet sizes, buffer
306 * sizes, flags and more, that are stored in the "usb_xfer"
308 *------------------------------------------------------------------------*/
310 usbd_transfer_setup_sub(struct usb_setup_params *parm)
316 struct usb_xfer *xfer = parm->curr_xfer;
317 const struct usb_config *setup = parm->curr_setup;
318 struct usb_endpoint_ss_comp_descriptor *ecomp;
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;
338 ecomp = xfer->endpoint->ecomp;
340 type = (edesc->bmAttributes & UE_XFERTYPE);
342 xfer->flags = setup->flags;
343 xfer->nframes = setup->frames;
344 xfer->timeout = setup->timeout;
345 xfer->callback = setup->callback;
346 xfer->interval = setup->interval;
347 xfer->endpointno = edesc->bEndpointAddress;
348 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
349 xfer->max_packet_count = 1;
350 /* make a shadow copy: */
351 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
353 parm->bufsize = setup->bufsize;
355 switch (parm->speed) {
360 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
362 /* check for invalid max packet count */
363 if (xfer->max_packet_count > 3)
364 xfer->max_packet_count = 3;
369 xfer->max_packet_size &= 0x7FF;
371 case USB_SPEED_SUPER:
372 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
375 xfer->max_packet_count += ecomp->bMaxBurst;
377 if ((xfer->max_packet_count == 0) ||
378 (xfer->max_packet_count > 16))
379 xfer->max_packet_count = 16;
383 xfer->max_packet_count = 1;
389 mult = (ecomp->bmAttributes & 3) + 1;
393 xfer->max_packet_count *= mult;
399 xfer->max_packet_size &= 0x7FF;
404 /* range check "max_packet_count" */
406 if (xfer->max_packet_count > parm->hc_max_packet_count) {
407 xfer->max_packet_count = parm->hc_max_packet_count;
409 /* filter "wMaxPacketSize" according to HC capabilities */
411 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
412 (xfer->max_packet_size == 0)) {
413 xfer->max_packet_size = parm->hc_max_packet_size;
415 /* filter "wMaxPacketSize" according to standard sizes */
417 usbd_get_std_packet_size(&std_size, type, parm->speed);
419 if (std_size.range.min || std_size.range.max) {
421 if (xfer->max_packet_size < std_size.range.min) {
422 xfer->max_packet_size = std_size.range.min;
424 if (xfer->max_packet_size > std_size.range.max) {
425 xfer->max_packet_size = std_size.range.max;
429 if (xfer->max_packet_size >= std_size.fixed[3]) {
430 xfer->max_packet_size = std_size.fixed[3];
431 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
432 xfer->max_packet_size = std_size.fixed[2];
433 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
434 xfer->max_packet_size = std_size.fixed[1];
436 /* only one possibility left */
437 xfer->max_packet_size = std_size.fixed[0];
441 /* compute "max_frame_size" */
443 usbd_update_max_frame_size(xfer);
445 /* check interrupt interval and transfer pre-delay */
447 if (type == UE_ISOCHRONOUS) {
449 uint16_t frame_limit;
451 xfer->interval = 0; /* not used, must be zero */
452 xfer->flags_int.isochronous_xfr = 1; /* set flag */
454 if (xfer->timeout == 0) {
456 * set a default timeout in
457 * case something goes wrong!
459 xfer->timeout = 1000 / 4;
461 switch (parm->speed) {
464 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
468 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
469 xfer->fps_shift = edesc->bInterval;
470 if (xfer->fps_shift > 0)
472 if (xfer->fps_shift > 3)
477 if (xfer->nframes > frame_limit) {
479 * this is not going to work
482 parm->err = USB_ERR_INVAL;
485 if (xfer->nframes == 0) {
487 * this is not a valid value
489 parm->err = USB_ERR_ZERO_NFRAMES;
495 * If a value is specified use that else check the
496 * endpoint descriptor!
498 if (type == UE_INTERRUPT) {
502 if (xfer->interval == 0) {
504 xfer->interval = edesc->bInterval;
506 switch (parm->speed) {
512 if (xfer->interval < 4)
514 else if (xfer->interval > 16)
515 xfer->interval = (1 << (16 - 4));
518 (1 << (xfer->interval - 4));
523 if (xfer->interval == 0) {
525 * One millisecond is the smallest
526 * interval we support:
534 while ((temp != 0) && (temp < xfer->interval)) {
539 switch (parm->speed) {
544 xfer->fps_shift += 3;
551 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
552 * to be equal to zero when setting up USB transfers, hence
553 * this leads to alot of extra code in the USB kernel.
556 if ((xfer->max_frame_size == 0) ||
557 (xfer->max_packet_size == 0)) {
561 if ((parm->bufsize <= MIN_PKT) &&
562 (type != UE_CONTROL) &&
566 xfer->max_packet_size = MIN_PKT;
567 xfer->max_packet_count = 1;
568 parm->bufsize = 0; /* automatic setup length */
569 usbd_update_max_frame_size(xfer);
572 parm->err = USB_ERR_ZERO_MAXP;
581 * check if we should setup a default
585 if (parm->bufsize == 0) {
587 parm->bufsize = xfer->max_frame_size;
589 if (type == UE_ISOCHRONOUS) {
590 parm->bufsize *= xfer->nframes;
594 * check if we are about to setup a proxy
598 if (xfer->flags.proxy_buffer) {
600 /* round bufsize up */
602 parm->bufsize += (xfer->max_frame_size - 1);
604 if (parm->bufsize < xfer->max_frame_size) {
605 /* length wrapped around */
606 parm->err = USB_ERR_INVAL;
609 /* subtract remainder */
611 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
613 /* add length of USB device request structure, if any */
615 if (type == UE_CONTROL) {
616 parm->bufsize += REQ_SIZE; /* SETUP message */
619 xfer->max_data_length = parm->bufsize;
621 /* Setup "n_frlengths" and "n_frbuffers" */
623 if (type == UE_ISOCHRONOUS) {
624 n_frlengths = xfer->nframes;
628 if (type == UE_CONTROL) {
629 xfer->flags_int.control_xfr = 1;
630 if (xfer->nframes == 0) {
631 if (parm->bufsize <= REQ_SIZE) {
633 * there will never be any data
642 if (xfer->nframes == 0) {
647 n_frlengths = xfer->nframes;
648 n_frbuffers = xfer->nframes;
652 * check if we have room for the
653 * USB device request structure:
656 if (type == UE_CONTROL) {
658 if (xfer->max_data_length < REQ_SIZE) {
659 /* length wrapped around or too small bufsize */
660 parm->err = USB_ERR_INVAL;
663 xfer->max_data_length -= REQ_SIZE;
665 /* setup "frlengths" */
666 xfer->frlengths = parm->xfer_length_ptr;
667 parm->xfer_length_ptr += n_frlengths;
669 /* setup "frbuffers" */
670 xfer->frbuffers = parm->xfer_page_cache_ptr;
671 parm->xfer_page_cache_ptr += n_frbuffers;
673 /* initialize max frame count */
674 xfer->max_frame_count = xfer->nframes;
677 * check if we need to setup
681 if (!xfer->flags.ext_buffer) {
684 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
689 USB_ADD_BYTES(parm->buf, parm->size[0]);
691 usbd_xfer_set_frame_offset(xfer, 0, 0);
693 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
694 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
697 parm->size[0] += parm->bufsize;
699 /* align data again */
700 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
703 * Compute maximum buffer size
706 if (parm->bufsize_max < parm->bufsize) {
707 parm->bufsize_max = parm->bufsize;
710 if (xfer->flags_int.bdma_enable) {
712 * Setup "dma_page_ptr".
714 * Proof for formula below:
716 * Assume there are three USB frames having length "a", "b" and
717 * "c". These USB frames will at maximum need "z"
718 * "usb_page" structures. "z" is given by:
720 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
721 * ((c / USB_PAGE_SIZE) + 2);
723 * Constraining "a", "b" and "c" like this:
725 * (a + b + c) <= parm->bufsize
729 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
731 * Here is the general formula:
733 xfer->dma_page_ptr = parm->dma_page_ptr;
734 parm->dma_page_ptr += (2 * n_frbuffers);
735 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
739 /* correct maximum data length */
740 xfer->max_data_length = 0;
742 /* subtract USB frame remainder from "hc_max_frame_size" */
744 xfer->max_hc_frame_size =
745 (parm->hc_max_frame_size -
746 (parm->hc_max_frame_size % xfer->max_frame_size));
748 if (xfer->max_hc_frame_size == 0) {
749 parm->err = USB_ERR_INVAL;
753 /* initialize frame buffers */
756 for (x = 0; x != n_frbuffers; x++) {
757 xfer->frbuffers[x].tag_parent =
758 &xfer->xroot->dma_parent_tag;
760 if (xfer->flags_int.bdma_enable &&
761 (parm->bufsize_max > 0)) {
763 if (usb_pc_dmamap_create(
765 parm->bufsize_max)) {
766 parm->err = USB_ERR_NOMEM;
776 * Set some dummy values so that we avoid division by zero:
778 xfer->max_hc_frame_size = 1;
779 xfer->max_frame_size = 1;
780 xfer->max_packet_size = 1;
781 xfer->max_data_length = 0;
783 xfer->max_frame_count = 0;
787 /*------------------------------------------------------------------------*
788 * usbd_transfer_setup - setup an array of USB transfers
790 * NOTE: You must always call "usbd_transfer_unsetup" after calling
791 * "usbd_transfer_setup" if success was returned.
793 * The idea is that the USB device driver should pre-allocate all its
794 * transfers by one call to this function.
799 *------------------------------------------------------------------------*/
801 usbd_transfer_setup(struct usb_device *udev,
802 const uint8_t *ifaces, struct usb_xfer **ppxfer,
803 const struct usb_config *setup_start, uint16_t n_setup,
804 void *priv_sc, struct mtx *xfer_mtx)
806 struct usb_xfer dummy;
807 struct usb_setup_params parm;
808 const struct usb_config *setup_end = setup_start + n_setup;
809 const struct usb_config *setup;
810 struct usb_endpoint *ep;
811 struct usb_xfer_root *info;
812 struct usb_xfer *xfer;
821 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
822 "usbd_transfer_setup can sleep!");
824 /* do some checking first */
827 DPRINTFN(6, "setup array has zero length!\n");
828 return (USB_ERR_INVAL);
831 DPRINTFN(6, "ifaces array is NULL!\n");
832 return (USB_ERR_INVAL);
834 if (xfer_mtx == NULL) {
835 DPRINTFN(6, "using global lock\n");
839 for (setup = setup_start, n = 0;
840 setup != setup_end; setup++, n++) {
841 if (setup->bufsize == (usb_frlength_t)-1) {
842 parm.err = USB_ERR_BAD_BUFSIZE;
843 DPRINTF("invalid bufsize\n");
845 if (setup->callback == NULL) {
846 parm.err = USB_ERR_NO_CALLBACK;
847 DPRINTF("no callback\n");
855 bzero(&parm, sizeof(parm));
858 parm.speed = usbd_get_speed(udev);
859 parm.hc_max_packet_count = 1;
861 if (parm.speed >= USB_SPEED_MAX) {
862 parm.err = USB_ERR_INVAL;
865 /* setup all transfers */
871 * Initialize the "usb_xfer_root" structure,
872 * which is common for all our USB transfers.
874 info = USB_ADD_BYTES(buf, 0);
876 info->memory_base = buf;
877 info->memory_size = parm.size[0];
880 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
881 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
883 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
884 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
886 cv_init(&info->cv_drain, "WDRAIN");
888 info->xfer_mtx = xfer_mtx;
890 usb_dma_tag_setup(&info->dma_parent_tag,
891 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
892 xfer_mtx, &usb_bdma_done_event, 32, parm.dma_tag_max);
895 info->bus = udev->bus;
898 TAILQ_INIT(&info->done_q.head);
899 info->done_q.command = &usbd_callback_wrapper;
901 TAILQ_INIT(&info->dma_q.head);
902 info->dma_q.command = &usb_bdma_work_loop;
904 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
905 info->done_m[0].xroot = info;
906 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
907 info->done_m[1].xroot = info;
910 * In device side mode control endpoint
911 * requests need to run from a separate
912 * context, else there is a chance of
915 if (setup_start == usb_control_ep_cfg)
917 &udev->bus->control_xfer_proc;
918 else if (xfer_mtx == &Giant)
920 &udev->bus->giant_callback_proc;
923 &udev->bus->non_giant_callback_proc;
929 parm.size[0] += sizeof(info[0]);
931 for (setup = setup_start, n = 0;
932 setup != setup_end; setup++, n++) {
934 /* skip USB transfers without callbacks: */
935 if (setup->callback == NULL) {
938 /* see if there is a matching endpoint */
939 ep = usbd_get_endpoint(udev,
940 ifaces[setup->if_index], setup);
942 if ((ep == NULL) || (ep->methods == NULL)) {
943 if (setup->flags.no_pipe_ok)
945 if ((setup->usb_mode != USB_MODE_DUAL) &&
946 (setup->usb_mode != udev->flags.usb_mode))
948 parm.err = USB_ERR_NO_PIPE;
952 /* align data properly */
953 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
955 /* store current setup pointer */
956 parm.curr_setup = setup;
960 * Common initialization of the
961 * "usb_xfer" structure.
963 xfer = USB_ADD_BYTES(buf, parm.size[0]);
964 xfer->address = udev->address;
965 xfer->priv_sc = priv_sc;
968 usb_callout_init_mtx(&xfer->timeout_handle,
969 &udev->bus->bus_mtx, 0);
972 * Setup a dummy xfer, hence we are
973 * writing to the "usb_xfer"
974 * structure pointed to by "xfer"
975 * before we have allocated any
979 bzero(&dummy, sizeof(dummy));
983 /* set transfer endpoint pointer */
986 parm.size[0] += sizeof(xfer[0]);
987 parm.methods = xfer->endpoint->methods;
988 parm.curr_xfer = xfer;
991 * Call the Host or Device controller transfer
994 (udev->bus->methods->xfer_setup) (&parm);
996 /* check for error */
1002 * Increment the endpoint refcount. This
1003 * basically prevents setting a new
1004 * configuration and alternate setting
1005 * when USB transfers are in use on
1006 * the given interface. Search the USB
1007 * code for "endpoint->refcount_alloc" if you
1008 * want more information.
1010 USB_BUS_LOCK(info->bus);
1011 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1012 parm.err = USB_ERR_INVAL;
1014 xfer->endpoint->refcount_alloc++;
1016 if (xfer->endpoint->refcount_alloc == 0)
1017 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1018 USB_BUS_UNLOCK(info->bus);
1021 * Whenever we set ppxfer[] then we
1022 * also need to increment the
1025 info->setup_refcount++;
1028 * Transfer is successfully setup and
1034 /* check for error */
1039 if (buf || parm.err) {
1042 if (refcount == 0) {
1043 /* no transfers - nothing to do ! */
1046 /* align data properly */
1047 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1049 /* store offset temporarily */
1050 parm.size[1] = parm.size[0];
1053 * The number of DMA tags required depends on
1054 * the number of endpoints. The current estimate
1055 * for maximum number of DMA tags per endpoint
1058 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1061 * DMA tags for QH, TD, Data and more.
1063 parm.dma_tag_max += 8;
1065 parm.dma_tag_p += parm.dma_tag_max;
1067 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1070 /* align data properly */
1071 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1073 /* store offset temporarily */
1074 parm.size[3] = parm.size[0];
1076 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1079 /* align data properly */
1080 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1082 /* store offset temporarily */
1083 parm.size[4] = parm.size[0];
1085 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1088 /* store end offset temporarily */
1089 parm.size[5] = parm.size[0];
1091 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1094 /* store end offset temporarily */
1096 parm.size[2] = parm.size[0];
1098 /* align data properly */
1099 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1101 parm.size[6] = parm.size[0];
1103 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1106 /* align data properly */
1107 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1109 /* allocate zeroed memory */
1110 buf = malloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1113 parm.err = USB_ERR_NOMEM;
1114 DPRINTFN(0, "cannot allocate memory block for "
1115 "configuration (%d bytes)\n",
1119 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1120 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1121 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1122 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1123 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1128 if (info->setup_refcount == 0) {
1130 * "usbd_transfer_unsetup_sub" will unlock
1131 * the bus mutex before returning !
1133 USB_BUS_LOCK(info->bus);
1135 /* something went wrong */
1136 usbd_transfer_unsetup_sub(info, 0);
1140 usbd_transfer_unsetup(ppxfer, n_setup);
1145 /*------------------------------------------------------------------------*
1146 * usbd_transfer_unsetup_sub - factored out code
1147 *------------------------------------------------------------------------*/
1149 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1151 struct usb_page_cache *pc;
1153 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1155 /* wait for any outstanding DMA operations */
1159 temp = usbd_get_dma_delay(info->udev);
1161 usb_pause_mtx(&info->bus->bus_mtx,
1162 USB_MS_TO_TICKS(temp));
1166 /* make sure that our done messages are not queued anywhere */
1167 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1169 USB_BUS_UNLOCK(info->bus);
1172 /* free DMA'able memory, if any */
1173 pc = info->dma_page_cache_start;
1174 while (pc != info->dma_page_cache_end) {
1175 usb_pc_free_mem(pc);
1179 /* free DMA maps in all "xfer->frbuffers" */
1180 pc = info->xfer_page_cache_start;
1181 while (pc != info->xfer_page_cache_end) {
1182 usb_pc_dmamap_destroy(pc);
1186 /* free all DMA tags */
1187 usb_dma_tag_unsetup(&info->dma_parent_tag);
1190 cv_destroy(&info->cv_drain);
1193 * free the "memory_base" last, hence the "info" structure is
1194 * contained within the "memory_base"!
1196 free(info->memory_base, M_USB);
1199 /*------------------------------------------------------------------------*
1200 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1202 * NOTE: All USB transfers in progress will get called back passing
1203 * the error code "USB_ERR_CANCELLED" before this function
1205 *------------------------------------------------------------------------*/
1207 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1209 struct usb_xfer *xfer;
1210 struct usb_xfer_root *info;
1211 uint8_t needs_delay = 0;
1213 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1214 "usbd_transfer_unsetup can sleep!");
1217 xfer = pxfer[n_setup];
1224 USB_XFER_LOCK(xfer);
1225 USB_BUS_LOCK(info->bus);
1228 * HINT: when you start/stop a transfer, it might be a
1229 * good idea to directly use the "pxfer[]" structure:
1231 * usbd_transfer_start(sc->pxfer[0]);
1232 * usbd_transfer_stop(sc->pxfer[0]);
1234 * That way, if your code has many parts that will not
1235 * stop running under the same lock, in other words
1236 * "xfer_mtx", the usbd_transfer_start and
1237 * usbd_transfer_stop functions will simply return
1238 * when they detect a NULL pointer argument.
1240 * To avoid any races we clear the "pxfer[]" pointer
1241 * while holding the private mutex of the driver:
1243 pxfer[n_setup] = NULL;
1245 USB_BUS_UNLOCK(info->bus);
1246 USB_XFER_UNLOCK(xfer);
1248 usbd_transfer_drain(xfer);
1251 if (xfer->flags_int.bdma_enable)
1255 * NOTE: default endpoint does not have an
1256 * interface, even if endpoint->iface_index == 0
1258 USB_BUS_LOCK(info->bus);
1259 xfer->endpoint->refcount_alloc--;
1260 USB_BUS_UNLOCK(info->bus);
1262 usb_callout_drain(&xfer->timeout_handle);
1264 USB_BUS_LOCK(info->bus);
1266 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1267 "reference count\n"));
1269 info->setup_refcount--;
1271 if (info->setup_refcount == 0) {
1272 usbd_transfer_unsetup_sub(info,
1275 USB_BUS_UNLOCK(info->bus);
1280 /*------------------------------------------------------------------------*
1281 * usbd_control_transfer_init - factored out code
1283 * In USB Device Mode we have to wait for the SETUP packet which
1284 * containst the "struct usb_device_request" structure, before we can
1285 * transfer any data. In USB Host Mode we already have the SETUP
1286 * packet at the moment the USB transfer is started. This leads us to
1287 * having to setup the USB transfer at two different places in
1288 * time. This function just contains factored out control transfer
1289 * initialisation code, so that we don't duplicate the code.
1290 *------------------------------------------------------------------------*/
1292 usbd_control_transfer_init(struct usb_xfer *xfer)
1294 struct usb_device_request req;
1296 /* copy out the USB request header */
1298 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1300 /* setup remainder */
1302 xfer->flags_int.control_rem = UGETW(req.wLength);
1304 /* copy direction to endpoint variable */
1306 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1308 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1311 /*------------------------------------------------------------------------*
1312 * usbd_setup_ctrl_transfer
1314 * This function handles initialisation of control transfers. Control
1315 * transfers are special in that regard that they can both transmit
1321 *------------------------------------------------------------------------*/
1323 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1327 /* Check for control endpoint stall */
1328 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1329 /* the control transfer is no longer active */
1330 xfer->flags_int.control_stall = 1;
1331 xfer->flags_int.control_act = 0;
1333 /* don't stall control transfer by default */
1334 xfer->flags_int.control_stall = 0;
1337 /* Check for invalid number of frames */
1338 if (xfer->nframes > 2) {
1340 * If you need to split a control transfer, you
1341 * have to do one part at a time. Only with
1342 * non-control transfers you can do multiple
1345 DPRINTFN(0, "Too many frames: %u\n",
1346 (unsigned int)xfer->nframes);
1351 * Check if there is a control
1352 * transfer in progress:
1354 if (xfer->flags_int.control_act) {
1356 if (xfer->flags_int.control_hdr) {
1358 /* clear send header flag */
1360 xfer->flags_int.control_hdr = 0;
1362 /* setup control transfer */
1363 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1364 usbd_control_transfer_init(xfer);
1367 /* get data length */
1373 /* the size of the SETUP structure is hardcoded ! */
1375 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1376 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1377 xfer->frlengths[0], sizeof(struct
1378 usb_device_request));
1381 /* check USB mode */
1382 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1384 /* check number of frames */
1385 if (xfer->nframes != 1) {
1387 * We need to receive the setup
1388 * message first so that we know the
1391 DPRINTF("Misconfigured transfer\n");
1395 * Set a dummy "control_rem" value. This
1396 * variable will be overwritten later by a
1397 * call to "usbd_control_transfer_init()" !
1399 xfer->flags_int.control_rem = 0xFFFF;
1402 /* setup "endpoint" and "control_rem" */
1404 usbd_control_transfer_init(xfer);
1407 /* set transfer-header flag */
1409 xfer->flags_int.control_hdr = 1;
1411 /* get data length */
1413 len = (xfer->sumlen - sizeof(struct usb_device_request));
1416 /* check if there is a length mismatch */
1418 if (len > xfer->flags_int.control_rem) {
1419 DPRINTFN(0, "Length (%d) greater than "
1420 "remaining length (%d)\n", len,
1421 xfer->flags_int.control_rem);
1424 /* check if we are doing a short transfer */
1426 if (xfer->flags.force_short_xfer) {
1427 xfer->flags_int.control_rem = 0;
1429 if ((len != xfer->max_data_length) &&
1430 (len != xfer->flags_int.control_rem) &&
1431 (xfer->nframes != 1)) {
1432 DPRINTFN(0, "Short control transfer without "
1433 "force_short_xfer set\n");
1436 xfer->flags_int.control_rem -= len;
1439 /* the status part is executed when "control_act" is 0 */
1441 if ((xfer->flags_int.control_rem > 0) ||
1442 (xfer->flags.manual_status)) {
1443 /* don't execute the STATUS stage yet */
1444 xfer->flags_int.control_act = 1;
1447 if ((!xfer->flags_int.control_hdr) &&
1448 (xfer->nframes == 1)) {
1450 * This is not a valid operation!
1452 DPRINTFN(0, "Invalid parameter "
1457 /* time to execute the STATUS stage */
1458 xfer->flags_int.control_act = 0;
1460 return (0); /* success */
1463 return (1); /* failure */
1466 /*------------------------------------------------------------------------*
1467 * usbd_transfer_submit - start USB hardware for the given transfer
1469 * This function should only be called from the USB callback.
1470 *------------------------------------------------------------------------*/
1472 usbd_transfer_submit(struct usb_xfer *xfer)
1474 struct usb_xfer_root *info;
1475 struct usb_bus *bus;
1481 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1482 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1486 if (USB_DEBUG_VAR > 0) {
1489 usb_dump_endpoint(xfer->endpoint);
1491 USB_BUS_UNLOCK(bus);
1495 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1496 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1498 /* Only open the USB transfer once! */
1499 if (!xfer->flags_int.open) {
1500 xfer->flags_int.open = 1;
1505 (xfer->endpoint->methods->open) (xfer);
1506 USB_BUS_UNLOCK(bus);
1508 /* set "transferring" flag */
1509 xfer->flags_int.transferring = 1;
1512 /* increment power reference */
1513 usbd_transfer_power_ref(xfer, 1);
1516 * Check if the transfer is waiting on a queue, most
1517 * frequently the "done_q":
1519 if (xfer->wait_queue) {
1521 usbd_transfer_dequeue(xfer);
1522 USB_BUS_UNLOCK(bus);
1524 /* clear "did_dma_delay" flag */
1525 xfer->flags_int.did_dma_delay = 0;
1527 /* clear "did_close" flag */
1528 xfer->flags_int.did_close = 0;
1531 /* clear "bdma_setup" flag */
1532 xfer->flags_int.bdma_setup = 0;
1534 /* by default we cannot cancel any USB transfer immediately */
1535 xfer->flags_int.can_cancel_immed = 0;
1537 /* clear lengths and frame counts by default */
1542 /* clear any previous errors */
1545 /* Check if the device is still alive */
1546 if (info->udev->state < USB_STATE_POWERED) {
1549 * Must return cancelled error code else
1550 * device drivers can hang.
1552 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1553 USB_BUS_UNLOCK(bus);
1558 if (xfer->nframes == 0) {
1559 if (xfer->flags.stall_pipe) {
1561 * Special case - want to stall without transferring
1564 DPRINTF("xfer=%p nframes=0: stall "
1565 "or clear stall!\n", xfer);
1567 xfer->flags_int.can_cancel_immed = 1;
1568 /* start the transfer */
1569 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1570 USB_BUS_UNLOCK(bus);
1574 usbd_transfer_done(xfer, USB_ERR_INVAL);
1575 USB_BUS_UNLOCK(bus);
1578 /* compute total transfer length */
1580 for (x = 0; x != xfer->nframes; x++) {
1581 xfer->sumlen += xfer->frlengths[x];
1582 if (xfer->sumlen < xfer->frlengths[x]) {
1583 /* length wrapped around */
1585 usbd_transfer_done(xfer, USB_ERR_INVAL);
1586 USB_BUS_UNLOCK(bus);
1591 /* clear some internal flags */
1593 xfer->flags_int.short_xfer_ok = 0;
1594 xfer->flags_int.short_frames_ok = 0;
1596 /* check if this is a control transfer */
1598 if (xfer->flags_int.control_xfr) {
1600 if (usbd_setup_ctrl_transfer(xfer)) {
1602 usbd_transfer_done(xfer, USB_ERR_STALLED);
1603 USB_BUS_UNLOCK(bus);
1608 * Setup filtered version of some transfer flags,
1609 * in case of data read direction
1611 if (USB_GET_DATA_ISREAD(xfer)) {
1613 if (xfer->flags.short_frames_ok) {
1614 xfer->flags_int.short_xfer_ok = 1;
1615 xfer->flags_int.short_frames_ok = 1;
1616 } else if (xfer->flags.short_xfer_ok) {
1617 xfer->flags_int.short_xfer_ok = 1;
1619 /* check for control transfer */
1620 if (xfer->flags_int.control_xfr) {
1622 * 1) Control transfers do not support
1623 * reception of multiple short USB
1624 * frames in host mode and device side
1625 * mode, with exception of:
1627 * 2) Due to sometimes buggy device
1628 * side firmware we need to do a
1629 * STATUS stage in case of short
1630 * control transfers in USB host mode.
1631 * The STATUS stage then becomes the
1632 * "alt_next" to the DATA stage.
1634 xfer->flags_int.short_frames_ok = 1;
1639 * Check if BUS-DMA support is enabled and try to load virtual
1640 * buffers into DMA, if any:
1643 if (xfer->flags_int.bdma_enable) {
1644 /* insert the USB transfer last in the BUS-DMA queue */
1645 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1650 * Enter the USB transfer into the Host Controller or
1651 * Device Controller schedule:
1653 usbd_pipe_enter(xfer);
1656 /*------------------------------------------------------------------------*
1657 * usbd_pipe_enter - factored out code
1658 *------------------------------------------------------------------------*/
1660 usbd_pipe_enter(struct usb_xfer *xfer)
1662 struct usb_endpoint *ep;
1664 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1666 USB_BUS_LOCK(xfer->xroot->bus);
1668 ep = xfer->endpoint;
1672 /* enter the transfer */
1673 (ep->methods->enter) (xfer);
1675 xfer->flags_int.can_cancel_immed = 1;
1677 /* check for transfer error */
1679 /* some error has happened */
1680 usbd_transfer_done(xfer, 0);
1681 USB_BUS_UNLOCK(xfer->xroot->bus);
1685 /* start the transfer */
1686 usb_command_wrapper(&ep->endpoint_q, xfer);
1687 USB_BUS_UNLOCK(xfer->xroot->bus);
1690 /*------------------------------------------------------------------------*
1691 * usbd_transfer_start - start an USB transfer
1693 * NOTE: Calling this function more than one time will only
1694 * result in a single transfer start, until the USB transfer
1696 *------------------------------------------------------------------------*/
1698 usbd_transfer_start(struct usb_xfer *xfer)
1701 /* transfer is gone */
1704 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1706 /* mark the USB transfer started */
1708 if (!xfer->flags_int.started) {
1709 /* lock the BUS lock to avoid races updating flags_int */
1710 USB_BUS_LOCK(xfer->xroot->bus);
1711 xfer->flags_int.started = 1;
1712 USB_BUS_UNLOCK(xfer->xroot->bus);
1714 /* check if the USB transfer callback is already transferring */
1716 if (xfer->flags_int.transferring) {
1719 USB_BUS_LOCK(xfer->xroot->bus);
1720 /* call the USB transfer callback */
1721 usbd_callback_ss_done_defer(xfer);
1722 USB_BUS_UNLOCK(xfer->xroot->bus);
1725 /*------------------------------------------------------------------------*
1726 * usbd_transfer_stop - stop an USB transfer
1728 * NOTE: Calling this function more than one time will only
1729 * result in a single transfer stop.
1730 * NOTE: When this function returns it is not safe to free nor
1731 * reuse any DMA buffers. See "usbd_transfer_drain()".
1732 *------------------------------------------------------------------------*/
1734 usbd_transfer_stop(struct usb_xfer *xfer)
1736 struct usb_endpoint *ep;
1739 /* transfer is gone */
1742 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1744 /* check if the USB transfer was ever opened */
1746 if (!xfer->flags_int.open) {
1747 if (xfer->flags_int.started) {
1748 /* nothing to do except clearing the "started" flag */
1749 /* lock the BUS lock to avoid races updating flags_int */
1750 USB_BUS_LOCK(xfer->xroot->bus);
1751 xfer->flags_int.started = 0;
1752 USB_BUS_UNLOCK(xfer->xroot->bus);
1756 /* try to stop the current USB transfer */
1758 USB_BUS_LOCK(xfer->xroot->bus);
1759 /* override any previous error */
1760 xfer->error = USB_ERR_CANCELLED;
1763 * Clear "open" and "started" when both private and USB lock
1764 * is locked so that we don't get a race updating "flags_int"
1766 xfer->flags_int.open = 0;
1767 xfer->flags_int.started = 0;
1770 * Check if we can cancel the USB transfer immediately.
1772 if (xfer->flags_int.transferring) {
1773 if (xfer->flags_int.can_cancel_immed &&
1774 (!xfer->flags_int.did_close)) {
1777 * The following will lead to an USB_ERR_CANCELLED
1778 * error code being passed to the USB callback.
1780 (xfer->endpoint->methods->close) (xfer);
1781 /* only close once */
1782 xfer->flags_int.did_close = 1;
1784 /* need to wait for the next done callback */
1789 /* close here and now */
1790 (xfer->endpoint->methods->close) (xfer);
1793 * Any additional DMA delay is done by
1794 * "usbd_transfer_unsetup()".
1798 * Special case. Check if we need to restart a blocked
1801 ep = xfer->endpoint;
1804 * If the current USB transfer is completing we need
1805 * to start the next one:
1807 if (ep->endpoint_q.curr == xfer) {
1808 usb_command_wrapper(&ep->endpoint_q, NULL);
1812 USB_BUS_UNLOCK(xfer->xroot->bus);
1815 /*------------------------------------------------------------------------*
1816 * usbd_transfer_pending
1818 * This function will check if an USB transfer is pending which is a
1819 * little bit complicated!
1822 * 1: Pending: The USB transfer will receive a callback in the future.
1823 *------------------------------------------------------------------------*/
1825 usbd_transfer_pending(struct usb_xfer *xfer)
1827 struct usb_xfer_root *info;
1828 struct usb_xfer_queue *pq;
1831 /* transfer is gone */
1834 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1836 if (xfer->flags_int.transferring) {
1840 USB_BUS_LOCK(xfer->xroot->bus);
1841 if (xfer->wait_queue) {
1842 /* we are waiting on a queue somewhere */
1843 USB_BUS_UNLOCK(xfer->xroot->bus);
1849 if (pq->curr == xfer) {
1850 /* we are currently scheduled for callback */
1851 USB_BUS_UNLOCK(xfer->xroot->bus);
1854 /* we are not pending */
1855 USB_BUS_UNLOCK(xfer->xroot->bus);
1859 /*------------------------------------------------------------------------*
1860 * usbd_transfer_drain
1862 * This function will stop the USB transfer and wait for any
1863 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1864 * are loaded into DMA can safely be freed or reused after that this
1865 * function has returned.
1866 *------------------------------------------------------------------------*/
1868 usbd_transfer_drain(struct usb_xfer *xfer)
1870 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1871 "usbd_transfer_drain can sleep!");
1874 /* transfer is gone */
1877 if (xfer->xroot->xfer_mtx != &Giant) {
1878 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1880 USB_XFER_LOCK(xfer);
1882 usbd_transfer_stop(xfer);
1884 while (usbd_transfer_pending(xfer) ||
1885 xfer->flags_int.doing_callback) {
1888 * It is allowed that the callback can drop its
1889 * transfer mutex. In that case checking only
1890 * "usbd_transfer_pending()" is not enough to tell if
1891 * the USB transfer is fully drained. We also need to
1892 * check the internal "doing_callback" flag.
1894 xfer->flags_int.draining = 1;
1897 * Wait until the current outstanding USB
1898 * transfer is complete !
1900 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1902 USB_XFER_UNLOCK(xfer);
1905 struct usb_page_cache *
1906 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1908 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1910 return (&xfer->frbuffers[frindex]);
1913 /*------------------------------------------------------------------------*
1914 * usbd_xfer_get_fps_shift
1916 * The following function is only useful for isochronous transfers. It
1917 * returns how many times the frame execution rate has been shifted
1923 *------------------------------------------------------------------------*/
1925 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1927 return (xfer->fps_shift);
1931 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1933 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1935 return (xfer->frlengths[frindex]);
1938 /*------------------------------------------------------------------------*
1939 * usbd_xfer_set_frame_data
1941 * This function sets the pointer of the buffer that should
1942 * loaded directly into DMA for the given USB frame. Passing "ptr"
1943 * equal to NULL while the corresponding "frlength" is greater
1944 * than zero gives undefined results!
1945 *------------------------------------------------------------------------*/
1947 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1948 void *ptr, usb_frlength_t len)
1950 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1952 /* set virtual address to load and length */
1953 xfer->frbuffers[frindex].buffer = ptr;
1954 usbd_xfer_set_frame_len(xfer, frindex, len);
1958 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1959 void **ptr, int *len)
1961 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1964 *ptr = xfer->frbuffers[frindex].buffer;
1966 *len = xfer->frlengths[frindex];
1970 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
1974 *actlen = xfer->actlen;
1976 *sumlen = xfer->sumlen;
1977 if (aframes != NULL)
1978 *aframes = xfer->aframes;
1979 if (nframes != NULL)
1980 *nframes = xfer->nframes;
1983 /*------------------------------------------------------------------------*
1984 * usbd_xfer_set_frame_offset
1986 * This function sets the frame data buffer offset relative to the beginning
1987 * of the USB DMA buffer allocated for this USB transfer.
1988 *------------------------------------------------------------------------*/
1990 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
1991 usb_frcount_t frindex)
1993 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
1994 "when the USB buffer is external\n"));
1995 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1997 /* set virtual address to load */
1998 xfer->frbuffers[frindex].buffer =
1999 USB_ADD_BYTES(xfer->local_buffer, offset);
2003 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2009 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2015 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2021 usbd_xfer_max_frames(struct usb_xfer *xfer)
2023 return (xfer->max_frame_count);
2027 usbd_xfer_max_len(struct usb_xfer *xfer)
2029 return (xfer->max_data_length);
2033 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2035 return (xfer->max_frame_size);
2039 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2042 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2044 xfer->frlengths[frindex] = len;
2047 /*------------------------------------------------------------------------*
2048 * usb_callback_proc - factored out code
2050 * This function performs USB callbacks.
2051 *------------------------------------------------------------------------*/
2053 usb_callback_proc(struct usb_proc_msg *_pm)
2055 struct usb_done_msg *pm = (void *)_pm;
2056 struct usb_xfer_root *info = pm->xroot;
2058 /* Change locking order */
2059 USB_BUS_UNLOCK(info->bus);
2062 * We exploit the fact that the mutex is the same for all
2063 * callbacks that will be called from this thread:
2065 mtx_lock(info->xfer_mtx);
2066 USB_BUS_LOCK(info->bus);
2068 /* Continue where we lost track */
2069 usb_command_wrapper(&info->done_q,
2072 mtx_unlock(info->xfer_mtx);
2075 /*------------------------------------------------------------------------*
2076 * usbd_callback_ss_done_defer
2078 * This function will defer the start, stop and done callback to the
2080 *------------------------------------------------------------------------*/
2082 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2084 struct usb_xfer_root *info = xfer->xroot;
2085 struct usb_xfer_queue *pq = &info->done_q;
2087 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2089 if (pq->curr != xfer) {
2090 usbd_transfer_enqueue(pq, xfer);
2092 if (!pq->recurse_1) {
2095 * We have to postpone the callback due to the fact we
2096 * will have a Lock Order Reversal, LOR, if we try to
2099 if (usb_proc_msignal(info->done_p,
2100 &info->done_m[0], &info->done_m[1])) {
2104 /* clear second recurse flag */
2111 /*------------------------------------------------------------------------*
2112 * usbd_callback_wrapper
2114 * This is a wrapper for USB callbacks. This wrapper does some
2115 * auto-magic things like figuring out if we can call the callback
2116 * directly from the current context or if we need to wakeup the
2117 * interrupt process.
2118 *------------------------------------------------------------------------*/
2120 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2122 struct usb_xfer *xfer = pq->curr;
2123 struct usb_xfer_root *info = xfer->xroot;
2125 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2126 if (!mtx_owned(info->xfer_mtx)) {
2128 * Cases that end up here:
2130 * 5) HW interrupt done callback or other source.
2132 DPRINTFN(3, "case 5\n");
2135 * We have to postpone the callback due to the fact we
2136 * will have a Lock Order Reversal, LOR, if we try to
2139 if (usb_proc_msignal(info->done_p,
2140 &info->done_m[0], &info->done_m[1])) {
2146 * Cases that end up here:
2148 * 1) We are starting a transfer
2149 * 2) We are prematurely calling back a transfer
2150 * 3) We are stopping a transfer
2151 * 4) We are doing an ordinary callback
2153 DPRINTFN(3, "case 1-4\n");
2154 /* get next USB transfer in the queue */
2155 info->done_q.curr = NULL;
2157 /* set flag in case of drain */
2158 xfer->flags_int.doing_callback = 1;
2160 USB_BUS_UNLOCK(info->bus);
2161 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2163 /* set correct USB state for callback */
2164 if (!xfer->flags_int.transferring) {
2165 xfer->usb_state = USB_ST_SETUP;
2166 if (!xfer->flags_int.started) {
2167 /* we got stopped before we even got started */
2168 USB_BUS_LOCK(info->bus);
2173 if (usbd_callback_wrapper_sub(xfer)) {
2174 /* the callback has been deferred */
2175 USB_BUS_LOCK(info->bus);
2179 /* decrement power reference */
2180 usbd_transfer_power_ref(xfer, -1);
2182 xfer->flags_int.transferring = 0;
2185 xfer->usb_state = USB_ST_ERROR;
2187 /* set transferred state */
2188 xfer->usb_state = USB_ST_TRANSFERRED;
2190 /* sync DMA memory, if any */
2191 if (xfer->flags_int.bdma_enable &&
2192 (!xfer->flags_int.bdma_no_post_sync)) {
2193 usb_bdma_post_sync(xfer);
2199 /* call processing routine */
2200 (xfer->callback) (xfer, xfer->error);
2202 /* pickup the USB mutex again */
2203 USB_BUS_LOCK(info->bus);
2206 * Check if we got started after that we got cancelled, but
2207 * before we managed to do the callback.
2209 if ((!xfer->flags_int.open) &&
2210 (xfer->flags_int.started) &&
2211 (xfer->usb_state == USB_ST_ERROR)) {
2212 /* clear flag in case of drain */
2213 xfer->flags_int.doing_callback = 0;
2214 /* try to loop, but not recursivly */
2215 usb_command_wrapper(&info->done_q, xfer);
2220 /* clear flag in case of drain */
2221 xfer->flags_int.doing_callback = 0;
2224 * Check if we are draining.
2226 if (xfer->flags_int.draining &&
2227 (!xfer->flags_int.transferring)) {
2228 /* "usbd_transfer_drain()" is waiting for end of transfer */
2229 xfer->flags_int.draining = 0;
2230 cv_broadcast(&info->cv_drain);
2233 /* do the next callback, if any */
2234 usb_command_wrapper(&info->done_q,
2238 /*------------------------------------------------------------------------*
2239 * usb_dma_delay_done_cb
2241 * This function is called when the DMA delay has been exectuded, and
2242 * will make sure that the callback is called to complete the USB
2243 * transfer. This code path is ususally only used when there is an USB
2244 * error like USB_ERR_CANCELLED.
2245 *------------------------------------------------------------------------*/
2247 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2249 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2251 DPRINTFN(3, "Completed %p\n", xfer);
2253 /* queue callback for execution, again */
2254 usbd_transfer_done(xfer, 0);
2257 /*------------------------------------------------------------------------*
2258 * usbd_transfer_dequeue
2260 * - This function is used to remove an USB transfer from a USB
2263 * - This function can be called multiple times in a row.
2264 *------------------------------------------------------------------------*/
2266 usbd_transfer_dequeue(struct usb_xfer *xfer)
2268 struct usb_xfer_queue *pq;
2270 pq = xfer->wait_queue;
2272 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2273 xfer->wait_queue = NULL;
2277 /*------------------------------------------------------------------------*
2278 * usbd_transfer_enqueue
2280 * - This function is used to insert an USB transfer into a USB *
2283 * - This function can be called multiple times in a row.
2284 *------------------------------------------------------------------------*/
2286 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2289 * Insert the USB transfer into the queue, if it is not
2290 * already on a USB transfer queue:
2292 if (xfer->wait_queue == NULL) {
2293 xfer->wait_queue = pq;
2294 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2298 /*------------------------------------------------------------------------*
2299 * usbd_transfer_done
2301 * - This function is used to remove an USB transfer from the busdma,
2302 * pipe or interrupt queue.
2304 * - This function is used to queue the USB transfer on the done
2307 * - This function is used to stop any USB transfer timeouts.
2308 *------------------------------------------------------------------------*/
2310 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2312 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2314 DPRINTF("err=%s\n", usbd_errstr(error));
2317 * If we are not transferring then just return.
2318 * This can happen during transfer cancel.
2320 if (!xfer->flags_int.transferring) {
2321 DPRINTF("not transferring\n");
2322 /* end of control transfer, if any */
2323 xfer->flags_int.control_act = 0;
2326 /* only set transfer error if not already set */
2328 xfer->error = error;
2330 /* stop any callouts */
2331 usb_callout_stop(&xfer->timeout_handle);
2334 * If we are waiting on a queue, just remove the USB transfer
2335 * from the queue, if any. We should have the required locks
2336 * locked to do the remove when this function is called.
2338 usbd_transfer_dequeue(xfer);
2341 if (mtx_owned(xfer->xroot->xfer_mtx)) {
2342 struct usb_xfer_queue *pq;
2345 * If the private USB lock is not locked, then we assume
2346 * that the BUS-DMA load stage has been passed:
2348 pq = &xfer->xroot->dma_q;
2350 if (pq->curr == xfer) {
2351 /* start the next BUS-DMA load, if any */
2352 usb_command_wrapper(pq, NULL);
2356 /* keep some statistics */
2358 xfer->xroot->bus->stats_err.uds_requests
2359 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2361 xfer->xroot->bus->stats_ok.uds_requests
2362 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2365 /* call the USB transfer callback */
2366 usbd_callback_ss_done_defer(xfer);
2369 /*------------------------------------------------------------------------*
2370 * usbd_transfer_start_cb
2372 * This function is called to start the USB transfer when
2373 * "xfer->interval" is greater than zero, and and the endpoint type is
2375 *------------------------------------------------------------------------*/
2377 usbd_transfer_start_cb(void *arg)
2379 struct usb_xfer *xfer = arg;
2380 struct usb_endpoint *ep = xfer->endpoint;
2382 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2386 /* start the transfer */
2387 (ep->methods->start) (xfer);
2389 xfer->flags_int.can_cancel_immed = 1;
2391 /* check for error */
2393 /* some error has happened */
2394 usbd_transfer_done(xfer, 0);
2398 /*------------------------------------------------------------------------*
2399 * usbd_xfer_set_stall
2401 * This function is used to set the stall flag outside the
2402 * callback. This function is NULL safe.
2403 *------------------------------------------------------------------------*/
2405 usbd_xfer_set_stall(struct usb_xfer *xfer)
2411 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2413 /* avoid any races by locking the USB mutex */
2414 USB_BUS_LOCK(xfer->xroot->bus);
2415 xfer->flags.stall_pipe = 1;
2416 USB_BUS_UNLOCK(xfer->xroot->bus);
2420 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2422 return (xfer->endpoint->is_stalled);
2425 /*------------------------------------------------------------------------*
2426 * usbd_transfer_clear_stall
2428 * This function is used to clear the stall flag outside the
2429 * callback. This function is NULL safe.
2430 *------------------------------------------------------------------------*/
2432 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2438 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2440 /* avoid any races by locking the USB mutex */
2441 USB_BUS_LOCK(xfer->xroot->bus);
2443 xfer->flags.stall_pipe = 0;
2445 USB_BUS_UNLOCK(xfer->xroot->bus);
2448 /*------------------------------------------------------------------------*
2451 * This function is used to add an USB transfer to the pipe transfer list.
2452 *------------------------------------------------------------------------*/
2454 usbd_pipe_start(struct usb_xfer_queue *pq)
2456 struct usb_endpoint *ep;
2457 struct usb_xfer *xfer;
2461 ep = xfer->endpoint;
2463 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2466 * If the endpoint is already stalled we do nothing !
2468 if (ep->is_stalled) {
2472 * Check if we are supposed to stall the endpoint:
2474 if (xfer->flags.stall_pipe) {
2475 struct usb_device *udev;
2476 struct usb_xfer_root *info;
2478 /* clear stall command */
2479 xfer->flags.stall_pipe = 0;
2481 /* get pointer to USB device */
2486 * Only stall BULK and INTERRUPT endpoints.
2488 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2489 if ((type == UE_BULK) ||
2490 (type == UE_INTERRUPT)) {
2495 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2496 (udev->bus->methods->set_stall) (
2497 udev, NULL, ep, &did_stall);
2498 } else if (udev->ctrl_xfer[1]) {
2499 info = udev->ctrl_xfer[1]->xroot;
2501 &info->bus->non_giant_callback_proc,
2502 &udev->cs_msg[0], &udev->cs_msg[1]);
2504 /* should not happen */
2505 DPRINTFN(0, "No stall handler\n");
2508 * Check if we should stall. Some USB hardware
2509 * handles set- and clear-stall in hardware.
2513 * The transfer will be continued when
2514 * the clear-stall control endpoint
2515 * message is received.
2520 } else if (type == UE_ISOCHRONOUS) {
2523 * Make sure any FIFO overflow or other FIFO
2524 * error conditions go away by resetting the
2525 * endpoint FIFO through the clear stall
2528 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2529 (udev->bus->methods->clear_stall) (udev, ep);
2533 /* Set or clear stall complete - special case */
2534 if (xfer->nframes == 0) {
2535 /* we are complete */
2537 usbd_transfer_done(xfer, 0);
2543 * 1) Start the first transfer queued.
2545 * 2) Re-start the current USB transfer.
2548 * Check if there should be any
2549 * pre transfer start delay:
2551 if (xfer->interval > 0) {
2552 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2553 if ((type == UE_BULK) ||
2554 (type == UE_CONTROL)) {
2555 usbd_transfer_timeout_ms(xfer,
2556 &usbd_transfer_start_cb,
2563 /* start USB transfer */
2564 (ep->methods->start) (xfer);
2566 xfer->flags_int.can_cancel_immed = 1;
2568 /* check for error */
2570 /* some error has happened */
2571 usbd_transfer_done(xfer, 0);
2575 /*------------------------------------------------------------------------*
2576 * usbd_transfer_timeout_ms
2578 * This function is used to setup a timeout on the given USB
2579 * transfer. If the timeout has been deferred the callback given by
2580 * "cb" will get called after "ms" milliseconds.
2581 *------------------------------------------------------------------------*/
2583 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2584 void (*cb) (void *arg), usb_timeout_t ms)
2586 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2589 usb_callout_reset(&xfer->timeout_handle,
2590 USB_MS_TO_TICKS(ms), cb, xfer);
2593 /*------------------------------------------------------------------------*
2594 * usbd_callback_wrapper_sub
2596 * - This function will update variables in an USB transfer after
2597 * that the USB transfer is complete.
2599 * - This function is used to start the next USB transfer on the
2600 * ep transfer queue, if any.
2602 * NOTE: In some special cases the USB transfer will not be removed from
2603 * the pipe queue, but remain first. To enforce USB transfer removal call
2604 * this function passing the error code "USB_ERR_CANCELLED".
2608 * Else: The callback has been deferred.
2609 *------------------------------------------------------------------------*/
2611 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2613 struct usb_endpoint *ep;
2614 struct usb_bus *bus;
2617 bus = xfer->xroot->bus;
2619 if ((!xfer->flags_int.open) &&
2620 (!xfer->flags_int.did_close)) {
2623 (xfer->endpoint->methods->close) (xfer);
2624 USB_BUS_UNLOCK(bus);
2625 /* only close once */
2626 xfer->flags_int.did_close = 1;
2627 return (1); /* wait for new callback */
2630 * If we have a non-hardware induced error we
2631 * need to do the DMA delay!
2633 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2634 (xfer->error == USB_ERR_CANCELLED ||
2635 xfer->error == USB_ERR_TIMEOUT ||
2636 bus->methods->start_dma_delay != NULL)) {
2640 /* only delay once */
2641 xfer->flags_int.did_dma_delay = 1;
2643 /* we can not cancel this delay */
2644 xfer->flags_int.can_cancel_immed = 0;
2646 temp = usbd_get_dma_delay(xfer->xroot->udev);
2648 DPRINTFN(3, "DMA delay, %u ms, "
2649 "on %p\n", temp, xfer);
2654 * Some hardware solutions have dedicated
2655 * events when it is safe to free DMA'ed
2656 * memory. For the other hardware platforms we
2657 * use a static delay.
2659 if (bus->methods->start_dma_delay != NULL) {
2660 (bus->methods->start_dma_delay) (xfer);
2662 usbd_transfer_timeout_ms(xfer,
2663 (void *)&usb_dma_delay_done_cb, temp);
2665 USB_BUS_UNLOCK(bus);
2666 return (1); /* wait for new callback */
2669 /* check actual number of frames */
2670 if (xfer->aframes > xfer->nframes) {
2671 if (xfer->error == 0) {
2672 panic("%s: actual number of frames, %d, is "
2673 "greater than initial number of frames, %d\n",
2674 __FUNCTION__, xfer->aframes, xfer->nframes);
2676 /* just set some valid value */
2677 xfer->aframes = xfer->nframes;
2680 /* compute actual length */
2683 for (x = 0; x != xfer->aframes; x++) {
2684 xfer->actlen += xfer->frlengths[x];
2688 * Frames that were not transferred get zero actual length in
2689 * case the USB device driver does not check the actual number
2690 * of frames transferred, "xfer->aframes":
2692 for (; x < xfer->nframes; x++) {
2693 usbd_xfer_set_frame_len(xfer, x, 0);
2696 /* check actual length */
2697 if (xfer->actlen > xfer->sumlen) {
2698 if (xfer->error == 0) {
2699 panic("%s: actual length, %d, is greater than "
2700 "initial length, %d\n",
2701 __FUNCTION__, xfer->actlen, xfer->sumlen);
2703 /* just set some valid value */
2704 xfer->actlen = xfer->sumlen;
2707 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2708 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2709 xfer->aframes, xfer->nframes);
2712 /* end of control transfer, if any */
2713 xfer->flags_int.control_act = 0;
2715 /* check if we should block the execution queue */
2716 if ((xfer->error != USB_ERR_CANCELLED) &&
2717 (xfer->flags.pipe_bof)) {
2718 DPRINTFN(2, "xfer=%p: Block On Failure "
2719 "on endpoint=%p\n", xfer, xfer->endpoint);
2723 /* check for short transfers */
2724 if (xfer->actlen < xfer->sumlen) {
2726 /* end of control transfer, if any */
2727 xfer->flags_int.control_act = 0;
2729 if (!xfer->flags_int.short_xfer_ok) {
2730 xfer->error = USB_ERR_SHORT_XFER;
2731 if (xfer->flags.pipe_bof) {
2732 DPRINTFN(2, "xfer=%p: Block On Failure on "
2733 "Short Transfer on endpoint %p.\n",
2734 xfer, xfer->endpoint);
2740 * Check if we are in the middle of a
2743 if (xfer->flags_int.control_act) {
2744 DPRINTFN(5, "xfer=%p: Control transfer "
2745 "active on endpoint=%p\n", xfer, xfer->endpoint);
2751 ep = xfer->endpoint;
2754 * If the current USB transfer is completing we need to start the
2758 if (ep->endpoint_q.curr == xfer) {
2759 usb_command_wrapper(&ep->endpoint_q, NULL);
2761 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2762 /* there is another USB transfer waiting */
2764 /* this is the last USB transfer */
2765 /* clear isochronous sync flag */
2766 xfer->endpoint->is_synced = 0;
2769 USB_BUS_UNLOCK(bus);
2774 /*------------------------------------------------------------------------*
2775 * usb_command_wrapper
2777 * This function is used to execute commands non-recursivly on an USB
2779 *------------------------------------------------------------------------*/
2781 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2785 * If the transfer is not already processing,
2788 if (pq->curr != xfer) {
2789 usbd_transfer_enqueue(pq, xfer);
2790 if (pq->curr != NULL) {
2791 /* something is already processing */
2792 DPRINTFN(6, "busy %p\n", pq->curr);
2797 /* Get next element in queue */
2801 if (!pq->recurse_1) {
2805 /* set both recurse flags */
2809 if (pq->curr == NULL) {
2810 xfer = TAILQ_FIRST(&pq->head);
2812 TAILQ_REMOVE(&pq->head, xfer,
2814 xfer->wait_queue = NULL;
2820 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2822 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2824 } while (!pq->recurse_2);
2826 /* clear first recurse flag */
2830 /* clear second recurse flag */
2835 /*------------------------------------------------------------------------*
2836 * usbd_ctrl_transfer_setup
2838 * This function is used to setup the default USB control endpoint
2840 *------------------------------------------------------------------------*/
2842 usbd_ctrl_transfer_setup(struct usb_device *udev)
2844 struct usb_xfer *xfer;
2846 uint8_t iface_index;
2848 /* check for root HUB */
2849 if (udev->parent_hub == NULL)
2853 xfer = udev->ctrl_xfer[0];
2855 USB_XFER_LOCK(xfer);
2857 ((xfer->address == udev->address) &&
2858 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2859 udev->ddesc.bMaxPacketSize));
2860 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2863 * NOTE: checking "xfer->address" and
2864 * starting the USB transfer must be
2867 usbd_transfer_start(xfer);
2870 USB_XFER_UNLOCK(xfer);
2877 * All parameters are exactly the same like before.
2883 * Update wMaxPacketSize for the default control endpoint:
2885 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2886 udev->ddesc.bMaxPacketSize;
2889 * Unsetup any existing USB transfer:
2891 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2894 * Try to setup a new USB transfer for the
2895 * default control endpoint:
2898 if (usbd_transfer_setup(udev, &iface_index,
2899 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2900 &udev->device_mtx)) {
2901 DPRINTFN(0, "could not setup default "
2908 /*------------------------------------------------------------------------*
2909 * usbd_clear_data_toggle - factored out code
2911 * NOTE: the intention of this function is not to reset the hardware
2913 *------------------------------------------------------------------------*/
2915 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2917 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
2919 /* check that we have a valid case */
2920 if (udev->flags.usb_mode == USB_MODE_HOST &&
2921 udev->parent_hub != NULL &&
2922 udev->bus->methods->clear_stall != NULL &&
2923 ep->methods != NULL) {
2924 (udev->bus->methods->clear_stall) (udev, ep);
2928 /*------------------------------------------------------------------------*
2929 * usbd_clear_data_toggle - factored out code
2931 * NOTE: the intention of this function is not to reset the hardware
2932 * data toggle on the USB device side.
2933 *------------------------------------------------------------------------*/
2935 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2937 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2939 USB_BUS_LOCK(udev->bus);
2940 ep->toggle_next = 0;
2941 /* some hardware needs a callback to clear the data toggle */
2942 usbd_clear_stall_locked(udev, ep);
2943 USB_BUS_UNLOCK(udev->bus);
2946 /*------------------------------------------------------------------------*
2947 * usbd_clear_stall_callback - factored out clear stall callback
2950 * xfer1: Clear Stall Control Transfer
2951 * xfer2: Stalled USB Transfer
2953 * This function is NULL safe.
2959 * Clear stall config example:
2961 * static const struct usb_config my_clearstall = {
2962 * .type = UE_CONTROL,
2964 * .direction = UE_DIR_ANY,
2965 * .interval = 50, //50 milliseconds
2966 * .bufsize = sizeof(struct usb_device_request),
2967 * .timeout = 1000, //1.000 seconds
2968 * .callback = &my_clear_stall_callback, // **
2969 * .usb_mode = USB_MODE_HOST,
2972 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
2973 * passing the correct parameters.
2974 *------------------------------------------------------------------------*/
2976 usbd_clear_stall_callback(struct usb_xfer *xfer1,
2977 struct usb_xfer *xfer2)
2979 struct usb_device_request req;
2981 if (xfer2 == NULL) {
2982 /* looks like we are tearing down */
2983 DPRINTF("NULL input parameter\n");
2986 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
2987 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
2989 switch (USB_GET_STATE(xfer1)) {
2993 * pre-clear the data toggle to DATA0 ("umass.c" and
2994 * "ata-usb.c" depends on this)
2997 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
2999 /* setup a clear-stall packet */
3001 req.bmRequestType = UT_WRITE_ENDPOINT;
3002 req.bRequest = UR_CLEAR_FEATURE;
3003 USETW(req.wValue, UF_ENDPOINT_HALT);
3004 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3006 USETW(req.wLength, 0);
3009 * "usbd_transfer_setup_sub()" will ensure that
3010 * we have sufficient room in the buffer for
3011 * the request structure!
3014 /* copy in the transfer */
3016 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3019 xfer1->frlengths[0] = sizeof(req);
3022 usbd_transfer_submit(xfer1);
3025 case USB_ST_TRANSFERRED:
3028 default: /* Error */
3029 if (xfer1->error == USB_ERR_CANCELLED) {
3034 return (1); /* Clear Stall Finished */
3037 /*------------------------------------------------------------------------*
3038 * usbd_transfer_poll
3040 * The following function gets called from the USB keyboard driver and
3041 * UMASS when the system has paniced.
3043 * NOTE: It is currently not possible to resume normal operation on
3044 * the USB controller which has been polled, due to clearing of the
3045 * "up_dsleep" and "up_msleep" flags.
3046 *------------------------------------------------------------------------*/
3048 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3050 struct usb_xfer *xfer;
3051 struct usb_xfer_root *xroot;
3052 struct usb_device *udev;
3053 struct usb_proc_msg *pm;
3058 for (n = 0; n != max; n++) {
3059 /* Extra checks to avoid panic */
3062 continue; /* no USB transfer */
3063 xroot = xfer->xroot;
3065 continue; /* no USB root */
3068 continue; /* no USB device */
3069 if (udev->bus == NULL)
3070 continue; /* no BUS structure */
3071 if (udev->bus->methods == NULL)
3072 continue; /* no BUS methods */
3073 if (udev->bus->methods->xfer_poll == NULL)
3074 continue; /* no poll method */
3076 /* make sure that the BUS mutex is not locked */
3078 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3079 mtx_unlock(&xroot->udev->bus->bus_mtx);
3083 /* make sure that the transfer mutex is not locked */
3085 while (mtx_owned(xroot->xfer_mtx)) {
3086 mtx_unlock(xroot->xfer_mtx);
3090 /* Make sure cv_signal() and cv_broadcast() is not called */
3091 udev->bus->control_xfer_proc.up_msleep = 0;
3092 udev->bus->explore_proc.up_msleep = 0;
3093 udev->bus->giant_callback_proc.up_msleep = 0;
3094 udev->bus->non_giant_callback_proc.up_msleep = 0;
3096 /* poll USB hardware */
3097 (udev->bus->methods->xfer_poll) (udev->bus);
3099 USB_BUS_LOCK(xroot->bus);
3101 /* check for clear stall */
3102 if (udev->ctrl_xfer[1] != NULL) {
3104 /* poll clear stall start */
3105 pm = &udev->cs_msg[0].hdr;
3106 (pm->pm_callback) (pm);
3107 /* poll clear stall done thread */
3108 pm = &udev->ctrl_xfer[1]->
3109 xroot->done_m[0].hdr;
3110 (pm->pm_callback) (pm);
3113 /* poll done thread */
3114 pm = &xroot->done_m[0].hdr;
3115 (pm->pm_callback) (pm);
3117 USB_BUS_UNLOCK(xroot->bus);
3119 /* restore transfer mutex */
3121 mtx_lock(xroot->xfer_mtx);
3123 /* restore BUS mutex */
3125 mtx_lock(&xroot->udev->bus->bus_mtx);
3130 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3131 uint8_t type, enum usb_dev_speed speed)
3133 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3134 [USB_SPEED_LOW] = 8,
3135 [USB_SPEED_FULL] = 64,
3136 [USB_SPEED_HIGH] = 1024,
3137 [USB_SPEED_VARIABLE] = 1024,
3138 [USB_SPEED_SUPER] = 1024,
3141 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3142 [USB_SPEED_LOW] = 0, /* invalid */
3143 [USB_SPEED_FULL] = 1023,
3144 [USB_SPEED_HIGH] = 1024,
3145 [USB_SPEED_VARIABLE] = 3584,
3146 [USB_SPEED_SUPER] = 1024,
3149 static const uint16_t control_min[USB_SPEED_MAX] = {
3150 [USB_SPEED_LOW] = 8,
3151 [USB_SPEED_FULL] = 8,
3152 [USB_SPEED_HIGH] = 64,
3153 [USB_SPEED_VARIABLE] = 512,
3154 [USB_SPEED_SUPER] = 512,
3157 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3158 [USB_SPEED_LOW] = 8,
3159 [USB_SPEED_FULL] = 8,
3160 [USB_SPEED_HIGH] = 512,
3161 [USB_SPEED_VARIABLE] = 512,
3162 [USB_SPEED_SUPER] = 1024,
3167 memset(ptr, 0, sizeof(*ptr));
3171 ptr->range.max = intr_range_max[speed];
3173 case UE_ISOCHRONOUS:
3174 ptr->range.max = isoc_range_max[speed];
3177 if (type == UE_BULK)
3178 temp = bulk_min[speed];
3179 else /* UE_CONTROL */
3180 temp = control_min[speed];
3182 /* default is fixed */
3183 ptr->fixed[0] = temp;
3184 ptr->fixed[1] = temp;
3185 ptr->fixed[2] = temp;
3186 ptr->fixed[3] = temp;
3188 if (speed == USB_SPEED_FULL) {
3189 /* multiple sizes */
3194 if ((speed == USB_SPEED_VARIABLE) &&
3195 (type == UE_BULK)) {
3196 /* multiple sizes */
3197 ptr->fixed[2] = 1024;
3198 ptr->fixed[3] = 1536;
3205 usbd_xfer_softc(struct usb_xfer *xfer)
3207 return (xfer->priv_sc);
3211 usbd_xfer_get_priv(struct usb_xfer *xfer)
3213 return (xfer->priv_fifo);
3217 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3219 xfer->priv_fifo = ptr;
3223 usbd_xfer_state(struct usb_xfer *xfer)
3225 return (xfer->usb_state);
3229 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3232 case USB_FORCE_SHORT_XFER:
3233 xfer->flags.force_short_xfer = 1;
3235 case USB_SHORT_XFER_OK:
3236 xfer->flags.short_xfer_ok = 1;
3238 case USB_MULTI_SHORT_OK:
3239 xfer->flags.short_frames_ok = 1;
3241 case USB_MANUAL_STATUS:
3242 xfer->flags.manual_status = 1;
3248 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3251 case USB_FORCE_SHORT_XFER:
3252 xfer->flags.force_short_xfer = 0;
3254 case USB_SHORT_XFER_OK:
3255 xfer->flags.short_xfer_ok = 0;
3257 case USB_MULTI_SHORT_OK:
3258 xfer->flags.short_frames_ok = 0;
3260 case USB_MANUAL_STATUS:
3261 xfer->flags.manual_status = 0;
3267 * The following function returns in milliseconds when the isochronous
3268 * transfer was completed by the hardware. The returned value wraps
3269 * around 65536 milliseconds.
3272 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3274 return (xfer->isoc_time_complete);