3 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
5 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #ifdef USB_GLOBAL_INCLUDE_FILE
30 #include USB_GLOBAL_INCLUDE_FILE
32 #include <sys/stdint.h>
33 #include <sys/stddef.h>
34 #include <sys/param.h>
35 #include <sys/queue.h>
36 #include <sys/types.h>
37 #include <sys/systm.h>
38 #include <sys/kernel.h>
40 #include <sys/module.h>
42 #include <sys/mutex.h>
43 #include <sys/condvar.h>
44 #include <sys/sysctl.h>
46 #include <sys/unistd.h>
47 #include <sys/callout.h>
48 #include <sys/malloc.h>
51 #include <dev/usb/usb.h>
52 #include <dev/usb/usbdi.h>
53 #include <dev/usb/usbdi_util.h>
55 #define USB_DEBUG_VAR usb_debug
57 #include <dev/usb/usb_core.h>
58 #include <dev/usb/usb_busdma.h>
59 #include <dev/usb/usb_process.h>
60 #include <dev/usb/usb_transfer.h>
61 #include <dev/usb/usb_device.h>
62 #include <dev/usb/usb_debug.h>
63 #include <dev/usb/usb_util.h>
65 #include <dev/usb/usb_controller.h>
66 #include <dev/usb/usb_bus.h>
67 #include <dev/usb/usb_pf.h>
68 #endif /* USB_GLOBAL_INCLUDE_FILE */
70 struct usb_std_packet_size {
72 uint16_t min; /* inclusive */
73 uint16_t max; /* inclusive */
79 static usb_callback_t usb_request_callback;
81 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
83 /* This transfer is used for generic control endpoint transfers */
87 .endpoint = 0x00, /* Control endpoint */
88 .direction = UE_DIR_ANY,
89 .bufsize = USB_EP0_BUFSIZE, /* bytes */
90 .flags = {.proxy_buffer = 1,},
91 .callback = &usb_request_callback,
92 .usb_mode = USB_MODE_DUAL, /* both modes */
95 /* This transfer is used for generic clear stall only */
99 .endpoint = 0x00, /* Control pipe */
100 .direction = UE_DIR_ANY,
101 .bufsize = sizeof(struct usb_device_request),
102 .callback = &usb_do_clear_stall_callback,
103 .timeout = 1000, /* 1 second */
104 .interval = 50, /* 50ms */
105 .usb_mode = USB_MODE_HOST,
109 /* function prototypes */
111 static void usbd_update_max_frame_size(struct usb_xfer *);
112 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
113 static void usbd_control_transfer_init(struct usb_xfer *);
114 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
115 static void usb_callback_proc(struct usb_proc_msg *);
116 static void usbd_callback_ss_done_defer(struct usb_xfer *);
117 static void usbd_callback_wrapper(struct usb_xfer_queue *);
118 static void usbd_transfer_start_cb(void *);
119 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
120 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
121 uint8_t type, enum usb_dev_speed speed);
123 /*------------------------------------------------------------------------*
124 * usb_request_callback
125 *------------------------------------------------------------------------*/
127 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
129 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
130 usb_handle_request_callback(xfer, error);
132 usbd_do_request_callback(xfer, error);
135 /*------------------------------------------------------------------------*
136 * usbd_update_max_frame_size
138 * This function updates the maximum frame size, hence high speed USB
139 * can transfer multiple consecutive packets.
140 *------------------------------------------------------------------------*/
142 usbd_update_max_frame_size(struct usb_xfer *xfer)
144 /* compute maximum frame size */
145 /* this computation should not overflow 16-bit */
146 /* max = 15 * 1024 */
148 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
151 /*------------------------------------------------------------------------*
154 * The following function is called when we need to
155 * synchronize with DMA hardware.
158 * 0: no DMA delay required
159 * Else: milliseconds of DMA delay
160 *------------------------------------------------------------------------*/
162 usbd_get_dma_delay(struct usb_device *udev)
164 const struct usb_bus_methods *mtod;
167 mtod = udev->bus->methods;
170 if (mtod->get_dma_delay) {
171 (mtod->get_dma_delay) (udev, &temp);
173 * Round up and convert to milliseconds. Note that we use
174 * 1024 milliseconds per second. to save a division.
182 /*------------------------------------------------------------------------*
183 * usbd_transfer_setup_sub_malloc
185 * This function will allocate one or more DMA'able memory chunks
186 * according to "size", "align" and "count" arguments. "ppc" is
187 * pointed to a linear array of USB page caches afterwards.
189 * If the "align" argument is equal to "1" a non-contiguous allocation
190 * can happen. Else if the "align" argument is greater than "1", the
191 * allocation will always be contiguous in memory.
196 *------------------------------------------------------------------------*/
199 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
200 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
203 struct usb_page_cache *pc;
214 USB_ASSERT(align > 0, ("Invalid alignment, 0x%08x\n",
216 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
219 return (0); /* nothing to allocate */
222 * Make sure that the size is aligned properly.
224 size = -((-size) & (-align));
227 * Try multi-allocation chunks to reduce the number of DMA
228 * allocations, hence DMA allocations are slow.
231 /* special case - non-cached multi page DMA memory */
233 n_dma_pg = (2 + (size / USB_PAGE_SIZE));
235 } else if (size >= USB_PAGE_SIZE) {
240 /* compute number of objects per page */
241 #ifdef USB_DMA_SINGLE_ALLOC
244 n_obj = (USB_PAGE_SIZE / size);
247 * Compute number of DMA chunks, rounded up
250 n_dma_pc = howmany(count, n_obj);
255 * DMA memory is allocated once, but mapped twice. That's why
256 * there is one list for auto-free and another list for
257 * non-auto-free which only holds the mapping and not the
260 if (parm->buf == NULL) {
261 /* reserve memory (auto-free) */
262 parm->dma_page_ptr += n_dma_pc * n_dma_pg;
263 parm->dma_page_cache_ptr += n_dma_pc;
265 /* reserve memory (no-auto-free) */
266 parm->dma_page_ptr += count * n_dma_pg;
267 parm->xfer_page_cache_ptr += count;
270 for (x = 0; x != n_dma_pc; x++) {
271 /* need to initialize the page cache */
272 parm->dma_page_cache_ptr[x].tag_parent =
273 &parm->curr_xfer->xroot->dma_parent_tag;
275 for (x = 0; x != count; x++) {
276 /* need to initialize the page cache */
277 parm->xfer_page_cache_ptr[x].tag_parent =
278 &parm->curr_xfer->xroot->dma_parent_tag;
283 *ppc = parm->xfer_page_cache_ptr;
285 *ppc = parm->dma_page_cache_ptr;
287 r = count; /* set remainder count */
288 z = n_obj * size; /* set allocation size */
289 pc = parm->xfer_page_cache_ptr;
290 pg = parm->dma_page_ptr;
294 * Avoid mapping memory twice if only a single object
295 * should be allocated per page cache:
297 for (x = 0; x != n_dma_pc; x++) {
298 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
300 return (1); /* failure */
302 /* Make room for one DMA page cache and "n_dma_pg" pages */
303 parm->dma_page_cache_ptr++;
307 for (x = 0; x != n_dma_pc; x++) {
310 /* compute last remainder */
314 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
316 return (1); /* failure */
318 /* Set beginning of current buffer */
319 buf = parm->dma_page_cache_ptr->buffer;
320 /* Make room for one DMA page cache and "n_dma_pg" pages */
321 parm->dma_page_cache_ptr++;
324 for (y = 0; (y != n_obj); y++, r--, pc++, pg += n_dma_pg) {
326 /* Load sub-chunk into DMA */
327 if (usb_pc_dmamap_create(pc, size)) {
328 return (1); /* failure */
330 pc->buffer = USB_ADD_BYTES(buf, y * size);
333 USB_MTX_LOCK(pc->tag_parent->mtx);
334 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
335 USB_MTX_UNLOCK(pc->tag_parent->mtx);
336 return (1); /* failure */
338 USB_MTX_UNLOCK(pc->tag_parent->mtx);
343 parm->xfer_page_cache_ptr = pc;
344 parm->dma_page_ptr = pg;
349 /*------------------------------------------------------------------------*
350 * usbd_transfer_setup_sub - transfer setup subroutine
352 * This function must be called from the "xfer_setup" callback of the
353 * USB Host or Device controller driver when setting up an USB
354 * transfer. This function will setup correct packet sizes, buffer
355 * sizes, flags and more, that are stored in the "usb_xfer"
357 *------------------------------------------------------------------------*/
359 usbd_transfer_setup_sub(struct usb_setup_params *parm)
365 struct usb_xfer *xfer = parm->curr_xfer;
366 const struct usb_config *setup = parm->curr_setup;
367 struct usb_endpoint_ss_comp_descriptor *ecomp;
368 struct usb_endpoint_descriptor *edesc;
369 struct usb_std_packet_size std_size;
370 usb_frcount_t n_frlengths;
371 usb_frcount_t n_frbuffers;
378 * Sanity check. The following parameters must be initialized before
379 * calling this function.
381 if ((parm->hc_max_packet_size == 0) ||
382 (parm->hc_max_packet_count == 0) ||
383 (parm->hc_max_frame_size == 0)) {
384 parm->err = USB_ERR_INVAL;
387 edesc = xfer->endpoint->edesc;
388 ecomp = xfer->endpoint->ecomp;
390 type = (edesc->bmAttributes & UE_XFERTYPE);
392 xfer->flags = setup->flags;
393 xfer->nframes = setup->frames;
394 xfer->timeout = setup->timeout;
395 xfer->callback = setup->callback;
396 xfer->interval = setup->interval;
397 xfer->endpointno = edesc->bEndpointAddress;
398 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
399 xfer->max_packet_count = 1;
400 /* make a shadow copy: */
401 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
403 parm->bufsize = setup->bufsize;
405 switch (parm->speed) {
410 xfer->max_packet_count +=
411 (xfer->max_packet_size >> 11) & 3;
413 /* check for invalid max packet count */
414 if (xfer->max_packet_count > 3)
415 xfer->max_packet_count = 3;
420 xfer->max_packet_size &= 0x7FF;
422 case USB_SPEED_SUPER:
423 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
426 xfer->max_packet_count += ecomp->bMaxBurst;
428 if ((xfer->max_packet_count == 0) ||
429 (xfer->max_packet_count > 16))
430 xfer->max_packet_count = 16;
434 xfer->max_packet_count = 1;
440 mult = UE_GET_SS_ISO_MULT(
441 ecomp->bmAttributes) + 1;
445 xfer->max_packet_count *= mult;
451 xfer->max_packet_size &= 0x7FF;
456 /* range check "max_packet_count" */
458 if (xfer->max_packet_count > parm->hc_max_packet_count) {
459 xfer->max_packet_count = parm->hc_max_packet_count;
462 /* store max packet size value before filtering */
464 maxp_old = xfer->max_packet_size;
466 /* filter "wMaxPacketSize" according to HC capabilities */
468 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
469 (xfer->max_packet_size == 0)) {
470 xfer->max_packet_size = parm->hc_max_packet_size;
472 /* filter "wMaxPacketSize" according to standard sizes */
474 usbd_get_std_packet_size(&std_size, type, parm->speed);
476 if (std_size.range.min || std_size.range.max) {
478 if (xfer->max_packet_size < std_size.range.min) {
479 xfer->max_packet_size = std_size.range.min;
481 if (xfer->max_packet_size > std_size.range.max) {
482 xfer->max_packet_size = std_size.range.max;
486 if (xfer->max_packet_size >= std_size.fixed[3]) {
487 xfer->max_packet_size = std_size.fixed[3];
488 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
489 xfer->max_packet_size = std_size.fixed[2];
490 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
491 xfer->max_packet_size = std_size.fixed[1];
493 /* only one possibility left */
494 xfer->max_packet_size = std_size.fixed[0];
499 * Check if the max packet size was outside its allowed range
500 * and clamped to a valid value:
502 if (maxp_old != xfer->max_packet_size)
503 xfer->flags_int.maxp_was_clamped = 1;
505 /* compute "max_frame_size" */
507 usbd_update_max_frame_size(xfer);
509 /* check interrupt interval and transfer pre-delay */
511 if (type == UE_ISOCHRONOUS) {
513 uint16_t frame_limit;
515 xfer->interval = 0; /* not used, must be zero */
516 xfer->flags_int.isochronous_xfr = 1; /* set flag */
518 if (xfer->timeout == 0) {
520 * set a default timeout in
521 * case something goes wrong!
523 xfer->timeout = 1000 / 4;
525 switch (parm->speed) {
528 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
532 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
533 xfer->fps_shift = edesc->bInterval;
534 if (xfer->fps_shift > 0)
536 if (xfer->fps_shift > 3)
538 if (xfer->flags.pre_scale_frames != 0)
539 xfer->nframes <<= (3 - xfer->fps_shift);
543 if (xfer->nframes > frame_limit) {
545 * this is not going to work
548 parm->err = USB_ERR_INVAL;
551 if (xfer->nframes == 0) {
553 * this is not a valid value
555 parm->err = USB_ERR_ZERO_NFRAMES;
561 * If a value is specified use that else check the
562 * endpoint descriptor!
564 if (type == UE_INTERRUPT) {
568 if (xfer->interval == 0) {
570 xfer->interval = edesc->bInterval;
572 switch (parm->speed) {
578 if (xfer->interval < 4)
580 else if (xfer->interval > 16)
581 xfer->interval = (1 << (16 - 4));
584 (1 << (xfer->interval - 4));
589 if (xfer->interval == 0) {
591 * One millisecond is the smallest
592 * interval we support:
600 while ((temp != 0) && (temp < xfer->interval)) {
605 switch (parm->speed) {
610 xfer->fps_shift += 3;
617 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
618 * to be equal to zero when setting up USB transfers, hence
619 * this leads to a lot of extra code in the USB kernel.
622 if ((xfer->max_frame_size == 0) ||
623 (xfer->max_packet_size == 0)) {
627 if ((parm->bufsize <= MIN_PKT) &&
628 (type != UE_CONTROL) &&
632 xfer->max_packet_size = MIN_PKT;
633 xfer->max_packet_count = 1;
634 parm->bufsize = 0; /* automatic setup length */
635 usbd_update_max_frame_size(xfer);
638 parm->err = USB_ERR_ZERO_MAXP;
647 * check if we should setup a default
651 if (parm->bufsize == 0) {
653 parm->bufsize = xfer->max_frame_size;
655 if (type == UE_ISOCHRONOUS) {
656 parm->bufsize *= xfer->nframes;
660 * check if we are about to setup a proxy
664 if (xfer->flags.proxy_buffer) {
666 /* round bufsize up */
668 parm->bufsize += (xfer->max_frame_size - 1);
670 if (parm->bufsize < xfer->max_frame_size) {
671 /* length wrapped around */
672 parm->err = USB_ERR_INVAL;
675 /* subtract remainder */
677 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
679 /* add length of USB device request structure, if any */
681 if (type == UE_CONTROL) {
682 parm->bufsize += REQ_SIZE; /* SETUP message */
685 xfer->max_data_length = parm->bufsize;
687 /* Setup "n_frlengths" and "n_frbuffers" */
689 if (type == UE_ISOCHRONOUS) {
690 n_frlengths = xfer->nframes;
694 if (type == UE_CONTROL) {
695 xfer->flags_int.control_xfr = 1;
696 if (xfer->nframes == 0) {
697 if (parm->bufsize <= REQ_SIZE) {
699 * there will never be any data
708 if (xfer->nframes == 0) {
713 n_frlengths = xfer->nframes;
714 n_frbuffers = xfer->nframes;
718 * check if we have room for the
719 * USB device request structure:
722 if (type == UE_CONTROL) {
724 if (xfer->max_data_length < REQ_SIZE) {
725 /* length wrapped around or too small bufsize */
726 parm->err = USB_ERR_INVAL;
729 xfer->max_data_length -= REQ_SIZE;
732 * Setup "frlengths" and shadow "frlengths" for keeping the
733 * initial frame lengths when a USB transfer is complete. This
734 * information is useful when computing isochronous offsets.
736 xfer->frlengths = parm->xfer_length_ptr;
737 parm->xfer_length_ptr += 2 * n_frlengths;
739 /* setup "frbuffers" */
740 xfer->frbuffers = parm->xfer_page_cache_ptr;
741 parm->xfer_page_cache_ptr += n_frbuffers;
743 /* initialize max frame count */
744 xfer->max_frame_count = xfer->nframes;
747 * check if we need to setup
751 if (!xfer->flags.ext_buffer) {
753 struct usb_page_search page_info;
754 struct usb_page_cache *pc;
756 if (usbd_transfer_setup_sub_malloc(parm,
757 &pc, parm->bufsize, 1, 1)) {
758 parm->err = USB_ERR_NOMEM;
759 } else if (parm->buf != NULL) {
761 usbd_get_page(pc, 0, &page_info);
763 xfer->local_buffer = page_info.buffer;
765 usbd_xfer_set_frame_offset(xfer, 0, 0);
767 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
768 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
773 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
775 if (parm->buf != NULL) {
777 USB_ADD_BYTES(parm->buf, parm->size[0]);
779 usbd_xfer_set_frame_offset(xfer, 0, 0);
781 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
782 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
785 parm->size[0] += parm->bufsize;
787 /* align data again */
788 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
792 * Compute maximum buffer size
795 if (parm->bufsize_max < parm->bufsize) {
796 parm->bufsize_max = parm->bufsize;
799 if (xfer->flags_int.bdma_enable) {
801 * Setup "dma_page_ptr".
803 * Proof for formula below:
805 * Assume there are three USB frames having length "a", "b" and
806 * "c". These USB frames will at maximum need "z"
807 * "usb_page" structures. "z" is given by:
809 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
810 * ((c / USB_PAGE_SIZE) + 2);
812 * Constraining "a", "b" and "c" like this:
814 * (a + b + c) <= parm->bufsize
818 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
820 * Here is the general formula:
822 xfer->dma_page_ptr = parm->dma_page_ptr;
823 parm->dma_page_ptr += (2 * n_frbuffers);
824 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
828 /* correct maximum data length */
829 xfer->max_data_length = 0;
831 /* subtract USB frame remainder from "hc_max_frame_size" */
833 xfer->max_hc_frame_size =
834 (parm->hc_max_frame_size -
835 (parm->hc_max_frame_size % xfer->max_frame_size));
837 if (xfer->max_hc_frame_size == 0) {
838 parm->err = USB_ERR_INVAL;
842 /* initialize frame buffers */
845 for (x = 0; x != n_frbuffers; x++) {
846 xfer->frbuffers[x].tag_parent =
847 &xfer->xroot->dma_parent_tag;
849 if (xfer->flags_int.bdma_enable &&
850 (parm->bufsize_max > 0)) {
852 if (usb_pc_dmamap_create(
854 parm->bufsize_max)) {
855 parm->err = USB_ERR_NOMEM;
865 * Set some dummy values so that we avoid division by zero:
867 xfer->max_hc_frame_size = 1;
868 xfer->max_frame_size = 1;
869 xfer->max_packet_size = 1;
870 xfer->max_data_length = 0;
872 xfer->max_frame_count = 0;
877 usbd_transfer_setup_has_bulk(const struct usb_config *setup_start,
881 uint8_t type = setup_start[n_setup].type;
882 if (type == UE_BULK || type == UE_BULK_INTR ||
889 /*------------------------------------------------------------------------*
890 * usbd_transfer_setup - setup an array of USB transfers
892 * NOTE: You must always call "usbd_transfer_unsetup" after calling
893 * "usbd_transfer_setup" if success was returned.
895 * The idea is that the USB device driver should pre-allocate all its
896 * transfers by one call to this function.
901 *------------------------------------------------------------------------*/
903 usbd_transfer_setup(struct usb_device *udev,
904 const uint8_t *ifaces, struct usb_xfer **ppxfer,
905 const struct usb_config *setup_start, uint16_t n_setup,
906 void *priv_sc, struct mtx *xfer_mtx)
908 const struct usb_config *setup_end = setup_start + n_setup;
909 const struct usb_config *setup;
910 struct usb_setup_params *parm;
911 struct usb_endpoint *ep;
912 struct usb_xfer_root *info;
913 struct usb_xfer *xfer;
915 usb_error_t error = 0;
920 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
921 "usbd_transfer_setup can sleep!");
923 /* do some checking first */
926 DPRINTFN(6, "setup array has zero length!\n");
927 return (USB_ERR_INVAL);
929 if (ifaces == NULL) {
930 DPRINTFN(6, "ifaces array is NULL!\n");
931 return (USB_ERR_INVAL);
933 if (xfer_mtx == NULL) {
934 DPRINTFN(6, "using global lock\n");
938 /* more sanity checks */
940 for (setup = setup_start, n = 0;
941 setup != setup_end; setup++, n++) {
942 if (setup->bufsize == (usb_frlength_t)-1) {
943 error = USB_ERR_BAD_BUFSIZE;
944 DPRINTF("invalid bufsize\n");
946 if (setup->callback == NULL) {
947 error = USB_ERR_NO_CALLBACK;
948 DPRINTF("no callback\n");
956 /* Protect scratch area */
957 do_unlock = usbd_ctrl_lock(udev);
962 parm = &udev->scratch.xfer_setup[0].parm;
963 memset(parm, 0, sizeof(*parm));
966 parm->speed = usbd_get_speed(udev);
967 parm->hc_max_packet_count = 1;
969 if (parm->speed >= USB_SPEED_MAX) {
970 parm->err = USB_ERR_INVAL;
973 /* setup all transfers */
979 * Initialize the "usb_xfer_root" structure,
980 * which is common for all our USB transfers.
982 info = USB_ADD_BYTES(buf, 0);
984 info->memory_base = buf;
985 info->memory_size = parm->size[0];
988 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
989 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
991 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
992 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
994 cv_init(&info->cv_drain, "WDRAIN");
996 info->xfer_mtx = xfer_mtx;
998 usb_dma_tag_setup(&info->dma_parent_tag,
999 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
1000 xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
1004 info->bus = udev->bus;
1007 TAILQ_INIT(&info->done_q.head);
1008 info->done_q.command = &usbd_callback_wrapper;
1010 TAILQ_INIT(&info->dma_q.head);
1011 info->dma_q.command = &usb_bdma_work_loop;
1013 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
1014 info->done_m[0].xroot = info;
1015 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
1016 info->done_m[1].xroot = info;
1019 * In device side mode control endpoint
1020 * requests need to run from a separate
1021 * context, else there is a chance of
1024 if (setup_start == usb_control_ep_cfg)
1026 USB_BUS_CONTROL_XFER_PROC(udev->bus);
1027 else if (xfer_mtx == &Giant)
1029 USB_BUS_GIANT_PROC(udev->bus);
1030 else if (usbd_transfer_setup_has_bulk(setup_start, n_setup))
1032 USB_BUS_NON_GIANT_BULK_PROC(udev->bus);
1035 USB_BUS_NON_GIANT_ISOC_PROC(udev->bus);
1041 parm->size[0] += sizeof(info[0]);
1043 for (setup = setup_start, n = 0;
1044 setup != setup_end; setup++, n++) {
1046 /* skip USB transfers without callbacks: */
1047 if (setup->callback == NULL) {
1050 /* see if there is a matching endpoint */
1051 ep = usbd_get_endpoint(udev,
1052 ifaces[setup->if_index], setup);
1055 * Check that the USB PIPE is valid and that
1056 * the endpoint mode is proper.
1058 * Make sure we don't allocate a streams
1059 * transfer when such a combination is not
1062 if ((ep == NULL) || (ep->methods == NULL) ||
1063 ((ep->ep_mode != USB_EP_MODE_STREAMS) &&
1064 (ep->ep_mode != USB_EP_MODE_DEFAULT)) ||
1065 (setup->stream_id != 0 &&
1066 (setup->stream_id >= USB_MAX_EP_STREAMS ||
1067 (ep->ep_mode != USB_EP_MODE_STREAMS)))) {
1068 if (setup->flags.no_pipe_ok)
1070 if ((setup->usb_mode != USB_MODE_DUAL) &&
1071 (setup->usb_mode != udev->flags.usb_mode))
1073 parm->err = USB_ERR_NO_PIPE;
1077 /* align data properly */
1078 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1080 /* store current setup pointer */
1081 parm->curr_setup = setup;
1085 * Common initialization of the
1086 * "usb_xfer" structure.
1088 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1089 xfer->address = udev->address;
1090 xfer->priv_sc = priv_sc;
1093 usb_callout_init_mtx(&xfer->timeout_handle,
1094 &udev->bus->bus_mtx, 0);
1097 * Setup a dummy xfer, hence we are
1098 * writing to the "usb_xfer"
1099 * structure pointed to by "xfer"
1100 * before we have allocated any
1103 xfer = &udev->scratch.xfer_setup[0].dummy;
1104 memset(xfer, 0, sizeof(*xfer));
1108 /* set transfer endpoint pointer */
1109 xfer->endpoint = ep;
1111 /* set transfer stream ID */
1112 xfer->stream_id = setup->stream_id;
1114 parm->size[0] += sizeof(xfer[0]);
1115 parm->methods = xfer->endpoint->methods;
1116 parm->curr_xfer = xfer;
1119 * Call the Host or Device controller transfer
1122 (udev->bus->methods->xfer_setup) (parm);
1124 /* check for error */
1130 * Increment the endpoint refcount. This
1131 * basically prevents setting a new
1132 * configuration and alternate setting
1133 * when USB transfers are in use on
1134 * the given interface. Search the USB
1135 * code for "endpoint->refcount_alloc" if you
1136 * want more information.
1138 USB_BUS_LOCK(info->bus);
1139 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1140 parm->err = USB_ERR_INVAL;
1142 xfer->endpoint->refcount_alloc++;
1144 if (xfer->endpoint->refcount_alloc == 0)
1145 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1146 USB_BUS_UNLOCK(info->bus);
1149 * Whenever we set ppxfer[] then we
1150 * also need to increment the
1153 info->setup_refcount++;
1156 * Transfer is successfully setup and
1162 /* check for error */
1167 if (buf != NULL || parm->err != 0)
1170 /* if no transfers, nothing to do */
1174 /* align data properly */
1175 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1177 /* store offset temporarily */
1178 parm->size[1] = parm->size[0];
1181 * The number of DMA tags required depends on
1182 * the number of endpoints. The current estimate
1183 * for maximum number of DMA tags per endpoint
1185 * 1) for loading memory
1186 * 2) for allocating memory
1187 * 3) for fixing memory [UHCI]
1189 parm->dma_tag_max += 3 * MIN(n_setup, USB_EP_MAX);
1192 * DMA tags for QH, TD, Data and more.
1194 parm->dma_tag_max += 8;
1196 parm->dma_tag_p += parm->dma_tag_max;
1198 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1201 /* align data properly */
1202 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1204 /* store offset temporarily */
1205 parm->size[3] = parm->size[0];
1207 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1210 /* align data properly */
1211 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1213 /* store offset temporarily */
1214 parm->size[4] = parm->size[0];
1216 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1219 /* store end offset temporarily */
1220 parm->size[5] = parm->size[0];
1222 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1225 /* store end offset temporarily */
1227 parm->size[2] = parm->size[0];
1229 /* align data properly */
1230 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1232 parm->size[6] = parm->size[0];
1234 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1237 /* align data properly */
1238 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1240 /* allocate zeroed memory */
1241 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1244 parm->err = USB_ERR_NOMEM;
1245 DPRINTFN(0, "cannot allocate memory block for "
1246 "configuration (%d bytes)\n",
1250 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1251 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1252 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1253 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1254 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1259 if (info->setup_refcount == 0) {
1261 * "usbd_transfer_unsetup_sub" will unlock
1262 * the bus mutex before returning !
1264 USB_BUS_LOCK(info->bus);
1266 /* something went wrong */
1267 usbd_transfer_unsetup_sub(info, 0);
1271 /* check if any errors happened */
1273 usbd_transfer_unsetup(ppxfer, n_setup);
1278 usbd_ctrl_unlock(udev);
1283 /*------------------------------------------------------------------------*
1284 * usbd_transfer_unsetup_sub - factored out code
1285 *------------------------------------------------------------------------*/
1287 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1290 struct usb_page_cache *pc;
1293 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1295 /* wait for any outstanding DMA operations */
1299 temp = usbd_get_dma_delay(info->udev);
1301 usb_pause_mtx(&info->bus->bus_mtx,
1302 USB_MS_TO_TICKS(temp));
1306 /* make sure that our done messages are not queued anywhere */
1307 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1309 USB_BUS_UNLOCK(info->bus);
1312 /* free DMA'able memory, if any */
1313 pc = info->dma_page_cache_start;
1314 while (pc != info->dma_page_cache_end) {
1315 usb_pc_free_mem(pc);
1319 /* free DMA maps in all "xfer->frbuffers" */
1320 pc = info->xfer_page_cache_start;
1321 while (pc != info->xfer_page_cache_end) {
1322 usb_pc_dmamap_destroy(pc);
1326 /* free all DMA tags */
1327 usb_dma_tag_unsetup(&info->dma_parent_tag);
1330 cv_destroy(&info->cv_drain);
1333 * free the "memory_base" last, hence the "info" structure is
1334 * contained within the "memory_base"!
1336 free(info->memory_base, M_USB);
1339 /*------------------------------------------------------------------------*
1340 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1342 * NOTE: All USB transfers in progress will get called back passing
1343 * the error code "USB_ERR_CANCELLED" before this function
1345 *------------------------------------------------------------------------*/
1347 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1349 struct usb_xfer *xfer;
1350 struct usb_xfer_root *info;
1351 uint8_t needs_delay = 0;
1353 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1354 "usbd_transfer_unsetup can sleep!");
1357 xfer = pxfer[n_setup];
1364 USB_XFER_LOCK(xfer);
1365 USB_BUS_LOCK(info->bus);
1368 * HINT: when you start/stop a transfer, it might be a
1369 * good idea to directly use the "pxfer[]" structure:
1371 * usbd_transfer_start(sc->pxfer[0]);
1372 * usbd_transfer_stop(sc->pxfer[0]);
1374 * That way, if your code has many parts that will not
1375 * stop running under the same lock, in other words
1376 * "xfer_mtx", the usbd_transfer_start and
1377 * usbd_transfer_stop functions will simply return
1378 * when they detect a NULL pointer argument.
1380 * To avoid any races we clear the "pxfer[]" pointer
1381 * while holding the private mutex of the driver:
1383 pxfer[n_setup] = NULL;
1385 USB_BUS_UNLOCK(info->bus);
1386 USB_XFER_UNLOCK(xfer);
1388 usbd_transfer_drain(xfer);
1391 if (xfer->flags_int.bdma_enable)
1395 * NOTE: default endpoint does not have an
1396 * interface, even if endpoint->iface_index == 0
1398 USB_BUS_LOCK(info->bus);
1399 xfer->endpoint->refcount_alloc--;
1400 USB_BUS_UNLOCK(info->bus);
1402 usb_callout_drain(&xfer->timeout_handle);
1404 USB_BUS_LOCK(info->bus);
1406 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1407 "reference count\n"));
1409 info->setup_refcount--;
1411 if (info->setup_refcount == 0) {
1412 usbd_transfer_unsetup_sub(info,
1415 USB_BUS_UNLOCK(info->bus);
1420 /*------------------------------------------------------------------------*
1421 * usbd_control_transfer_init - factored out code
1423 * In USB Device Mode we have to wait for the SETUP packet which
1424 * containst the "struct usb_device_request" structure, before we can
1425 * transfer any data. In USB Host Mode we already have the SETUP
1426 * packet at the moment the USB transfer is started. This leads us to
1427 * having to setup the USB transfer at two different places in
1428 * time. This function just contains factored out control transfer
1429 * initialisation code, so that we don't duplicate the code.
1430 *------------------------------------------------------------------------*/
1432 usbd_control_transfer_init(struct usb_xfer *xfer)
1434 struct usb_device_request req;
1436 /* copy out the USB request header */
1438 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1440 /* setup remainder */
1442 xfer->flags_int.control_rem = UGETW(req.wLength);
1444 /* copy direction to endpoint variable */
1446 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1448 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1451 /*------------------------------------------------------------------------*
1452 * usbd_control_transfer_did_data
1454 * This function returns non-zero if a control endpoint has
1455 * transferred the first DATA packet after the SETUP packet.
1456 * Else it returns zero.
1457 *------------------------------------------------------------------------*/
1459 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1461 struct usb_device_request req;
1463 /* SETUP packet is not yet sent */
1464 if (xfer->flags_int.control_hdr != 0)
1467 /* copy out the USB request header */
1468 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1470 /* compare remainder to the initial value */
1471 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1474 /*------------------------------------------------------------------------*
1475 * usbd_setup_ctrl_transfer
1477 * This function handles initialisation of control transfers. Control
1478 * transfers are special in that regard that they can both transmit
1484 *------------------------------------------------------------------------*/
1486 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1490 /* Check for control endpoint stall */
1491 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1492 /* the control transfer is no longer active */
1493 xfer->flags_int.control_stall = 1;
1494 xfer->flags_int.control_act = 0;
1496 /* don't stall control transfer by default */
1497 xfer->flags_int.control_stall = 0;
1500 /* Check for invalid number of frames */
1501 if (xfer->nframes > 2) {
1503 * If you need to split a control transfer, you
1504 * have to do one part at a time. Only with
1505 * non-control transfers you can do multiple
1508 DPRINTFN(0, "Too many frames: %u\n",
1509 (unsigned int)xfer->nframes);
1514 * Check if there is a control
1515 * transfer in progress:
1517 if (xfer->flags_int.control_act) {
1519 if (xfer->flags_int.control_hdr) {
1521 /* clear send header flag */
1523 xfer->flags_int.control_hdr = 0;
1525 /* setup control transfer */
1526 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1527 usbd_control_transfer_init(xfer);
1530 /* get data length */
1536 /* the size of the SETUP structure is hardcoded ! */
1538 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1539 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1540 xfer->frlengths[0], sizeof(struct
1541 usb_device_request));
1544 /* check USB mode */
1545 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1547 /* check number of frames */
1548 if (xfer->nframes != 1) {
1550 * We need to receive the setup
1551 * message first so that we know the
1554 DPRINTF("Misconfigured transfer\n");
1558 * Set a dummy "control_rem" value. This
1559 * variable will be overwritten later by a
1560 * call to "usbd_control_transfer_init()" !
1562 xfer->flags_int.control_rem = 0xFFFF;
1565 /* setup "endpoint" and "control_rem" */
1567 usbd_control_transfer_init(xfer);
1570 /* set transfer-header flag */
1572 xfer->flags_int.control_hdr = 1;
1574 /* get data length */
1576 len = (xfer->sumlen - sizeof(struct usb_device_request));
1579 /* update did data flag */
1581 xfer->flags_int.control_did_data =
1582 usbd_control_transfer_did_data(xfer);
1584 /* check if there is a length mismatch */
1586 if (len > xfer->flags_int.control_rem) {
1587 DPRINTFN(0, "Length (%d) greater than "
1588 "remaining length (%d)\n", len,
1589 xfer->flags_int.control_rem);
1592 /* check if we are doing a short transfer */
1594 if (xfer->flags.force_short_xfer) {
1595 xfer->flags_int.control_rem = 0;
1597 if ((len != xfer->max_data_length) &&
1598 (len != xfer->flags_int.control_rem) &&
1599 (xfer->nframes != 1)) {
1600 DPRINTFN(0, "Short control transfer without "
1601 "force_short_xfer set\n");
1604 xfer->flags_int.control_rem -= len;
1607 /* the status part is executed when "control_act" is 0 */
1609 if ((xfer->flags_int.control_rem > 0) ||
1610 (xfer->flags.manual_status)) {
1611 /* don't execute the STATUS stage yet */
1612 xfer->flags_int.control_act = 1;
1615 if ((!xfer->flags_int.control_hdr) &&
1616 (xfer->nframes == 1)) {
1618 * This is not a valid operation!
1620 DPRINTFN(0, "Invalid parameter "
1625 /* time to execute the STATUS stage */
1626 xfer->flags_int.control_act = 0;
1628 return (0); /* success */
1631 return (1); /* failure */
1634 /*------------------------------------------------------------------------*
1635 * usbd_transfer_submit - start USB hardware for the given transfer
1637 * This function should only be called from the USB callback.
1638 *------------------------------------------------------------------------*/
1640 usbd_transfer_submit(struct usb_xfer *xfer)
1642 struct usb_xfer_root *info;
1643 struct usb_bus *bus;
1649 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1650 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1654 if (USB_DEBUG_VAR > 0) {
1657 usb_dump_endpoint(xfer->endpoint);
1659 USB_BUS_UNLOCK(bus);
1663 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1664 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1666 /* Only open the USB transfer once! */
1667 if (!xfer->flags_int.open) {
1668 xfer->flags_int.open = 1;
1673 (xfer->endpoint->methods->open) (xfer);
1674 USB_BUS_UNLOCK(bus);
1676 /* set "transferring" flag */
1677 xfer->flags_int.transferring = 1;
1680 /* increment power reference */
1681 usbd_transfer_power_ref(xfer, 1);
1684 * Check if the transfer is waiting on a queue, most
1685 * frequently the "done_q":
1687 if (xfer->wait_queue) {
1689 usbd_transfer_dequeue(xfer);
1690 USB_BUS_UNLOCK(bus);
1692 /* clear "did_dma_delay" flag */
1693 xfer->flags_int.did_dma_delay = 0;
1695 /* clear "did_close" flag */
1696 xfer->flags_int.did_close = 0;
1699 /* clear "bdma_setup" flag */
1700 xfer->flags_int.bdma_setup = 0;
1702 /* by default we cannot cancel any USB transfer immediately */
1703 xfer->flags_int.can_cancel_immed = 0;
1705 /* clear lengths and frame counts by default */
1710 /* clear any previous errors */
1713 /* Check if the device is still alive */
1714 if (info->udev->state < USB_STATE_POWERED) {
1717 * Must return cancelled error code else
1718 * device drivers can hang.
1720 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1721 USB_BUS_UNLOCK(bus);
1726 if (xfer->nframes == 0) {
1727 if (xfer->flags.stall_pipe) {
1729 * Special case - want to stall without transferring
1732 DPRINTF("xfer=%p nframes=0: stall "
1733 "or clear stall!\n", xfer);
1735 xfer->flags_int.can_cancel_immed = 1;
1736 /* start the transfer */
1737 usb_command_wrapper(&xfer->endpoint->
1738 endpoint_q[xfer->stream_id], xfer);
1739 USB_BUS_UNLOCK(bus);
1743 usbd_transfer_done(xfer, USB_ERR_INVAL);
1744 USB_BUS_UNLOCK(bus);
1747 /* compute some variables */
1749 for (x = 0; x != xfer->nframes; x++) {
1750 /* make a copy of the frlenghts[] */
1751 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1752 /* compute total transfer length */
1753 xfer->sumlen += xfer->frlengths[x];
1754 if (xfer->sumlen < xfer->frlengths[x]) {
1755 /* length wrapped around */
1757 usbd_transfer_done(xfer, USB_ERR_INVAL);
1758 USB_BUS_UNLOCK(bus);
1763 /* clear some internal flags */
1765 xfer->flags_int.short_xfer_ok = 0;
1766 xfer->flags_int.short_frames_ok = 0;
1768 /* check if this is a control transfer */
1770 if (xfer->flags_int.control_xfr) {
1772 if (usbd_setup_ctrl_transfer(xfer)) {
1774 usbd_transfer_done(xfer, USB_ERR_STALLED);
1775 USB_BUS_UNLOCK(bus);
1780 * Setup filtered version of some transfer flags,
1781 * in case of data read direction
1783 if (USB_GET_DATA_ISREAD(xfer)) {
1785 if (xfer->flags.short_frames_ok) {
1786 xfer->flags_int.short_xfer_ok = 1;
1787 xfer->flags_int.short_frames_ok = 1;
1788 } else if (xfer->flags.short_xfer_ok) {
1789 xfer->flags_int.short_xfer_ok = 1;
1791 /* check for control transfer */
1792 if (xfer->flags_int.control_xfr) {
1794 * 1) Control transfers do not support
1795 * reception of multiple short USB
1796 * frames in host mode and device side
1797 * mode, with exception of:
1799 * 2) Due to sometimes buggy device
1800 * side firmware we need to do a
1801 * STATUS stage in case of short
1802 * control transfers in USB host mode.
1803 * The STATUS stage then becomes the
1804 * "alt_next" to the DATA stage.
1806 xfer->flags_int.short_frames_ok = 1;
1811 * Check if BUS-DMA support is enabled and try to load virtual
1812 * buffers into DMA, if any:
1815 if (xfer->flags_int.bdma_enable) {
1816 /* insert the USB transfer last in the BUS-DMA queue */
1817 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1822 * Enter the USB transfer into the Host Controller or
1823 * Device Controller schedule:
1825 usbd_pipe_enter(xfer);
1828 /*------------------------------------------------------------------------*
1829 * usbd_pipe_enter - factored out code
1830 *------------------------------------------------------------------------*/
1832 usbd_pipe_enter(struct usb_xfer *xfer)
1834 struct usb_endpoint *ep;
1836 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1838 USB_BUS_LOCK(xfer->xroot->bus);
1840 ep = xfer->endpoint;
1844 /* the transfer can now be cancelled */
1845 xfer->flags_int.can_cancel_immed = 1;
1847 /* enter the transfer */
1848 (ep->methods->enter) (xfer);
1850 /* check for transfer error */
1852 /* some error has happened */
1853 usbd_transfer_done(xfer, 0);
1854 USB_BUS_UNLOCK(xfer->xroot->bus);
1858 /* start the transfer */
1859 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1860 USB_BUS_UNLOCK(xfer->xroot->bus);
1863 /*------------------------------------------------------------------------*
1864 * usbd_transfer_start - start an USB transfer
1866 * NOTE: Calling this function more than one time will only
1867 * result in a single transfer start, until the USB transfer
1869 *------------------------------------------------------------------------*/
1871 usbd_transfer_start(struct usb_xfer *xfer)
1874 /* transfer is gone */
1877 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1879 /* mark the USB transfer started */
1881 if (!xfer->flags_int.started) {
1882 /* lock the BUS lock to avoid races updating flags_int */
1883 USB_BUS_LOCK(xfer->xroot->bus);
1884 xfer->flags_int.started = 1;
1885 USB_BUS_UNLOCK(xfer->xroot->bus);
1887 /* check if the USB transfer callback is already transferring */
1889 if (xfer->flags_int.transferring) {
1892 USB_BUS_LOCK(xfer->xroot->bus);
1893 /* call the USB transfer callback */
1894 usbd_callback_ss_done_defer(xfer);
1895 USB_BUS_UNLOCK(xfer->xroot->bus);
1898 /*------------------------------------------------------------------------*
1899 * usbd_transfer_stop - stop an USB transfer
1901 * NOTE: Calling this function more than one time will only
1902 * result in a single transfer stop.
1903 * NOTE: When this function returns it is not safe to free nor
1904 * reuse any DMA buffers. See "usbd_transfer_drain()".
1905 *------------------------------------------------------------------------*/
1907 usbd_transfer_stop(struct usb_xfer *xfer)
1909 struct usb_endpoint *ep;
1912 /* transfer is gone */
1915 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1917 /* check if the USB transfer was ever opened */
1919 if (!xfer->flags_int.open) {
1920 if (xfer->flags_int.started) {
1921 /* nothing to do except clearing the "started" flag */
1922 /* lock the BUS lock to avoid races updating flags_int */
1923 USB_BUS_LOCK(xfer->xroot->bus);
1924 xfer->flags_int.started = 0;
1925 USB_BUS_UNLOCK(xfer->xroot->bus);
1929 /* try to stop the current USB transfer */
1931 USB_BUS_LOCK(xfer->xroot->bus);
1932 /* override any previous error */
1933 xfer->error = USB_ERR_CANCELLED;
1936 * Clear "open" and "started" when both private and USB lock
1937 * is locked so that we don't get a race updating "flags_int"
1939 xfer->flags_int.open = 0;
1940 xfer->flags_int.started = 0;
1943 * Check if we can cancel the USB transfer immediately.
1945 if (xfer->flags_int.transferring) {
1946 if (xfer->flags_int.can_cancel_immed &&
1947 (!xfer->flags_int.did_close)) {
1950 * The following will lead to an USB_ERR_CANCELLED
1951 * error code being passed to the USB callback.
1953 (xfer->endpoint->methods->close) (xfer);
1954 /* only close once */
1955 xfer->flags_int.did_close = 1;
1957 /* need to wait for the next done callback */
1962 /* close here and now */
1963 (xfer->endpoint->methods->close) (xfer);
1966 * Any additional DMA delay is done by
1967 * "usbd_transfer_unsetup()".
1971 * Special case. Check if we need to restart a blocked
1974 ep = xfer->endpoint;
1977 * If the current USB transfer is completing we need
1978 * to start the next one:
1980 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
1981 usb_command_wrapper(
1982 &ep->endpoint_q[xfer->stream_id], NULL);
1986 USB_BUS_UNLOCK(xfer->xroot->bus);
1989 /*------------------------------------------------------------------------*
1990 * usbd_transfer_pending
1992 * This function will check if an USB transfer is pending which is a
1993 * little bit complicated!
1996 * 1: Pending: The USB transfer will receive a callback in the future.
1997 *------------------------------------------------------------------------*/
1999 usbd_transfer_pending(struct usb_xfer *xfer)
2001 struct usb_xfer_root *info;
2002 struct usb_xfer_queue *pq;
2005 /* transfer is gone */
2008 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2010 if (xfer->flags_int.transferring) {
2014 USB_BUS_LOCK(xfer->xroot->bus);
2015 if (xfer->wait_queue) {
2016 /* we are waiting on a queue somewhere */
2017 USB_BUS_UNLOCK(xfer->xroot->bus);
2023 if (pq->curr == xfer) {
2024 /* we are currently scheduled for callback */
2025 USB_BUS_UNLOCK(xfer->xroot->bus);
2028 /* we are not pending */
2029 USB_BUS_UNLOCK(xfer->xroot->bus);
2033 /*------------------------------------------------------------------------*
2034 * usbd_transfer_drain
2036 * This function will stop the USB transfer and wait for any
2037 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2038 * are loaded into DMA can safely be freed or reused after that this
2039 * function has returned.
2040 *------------------------------------------------------------------------*/
2042 usbd_transfer_drain(struct usb_xfer *xfer)
2044 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2045 "usbd_transfer_drain can sleep!");
2048 /* transfer is gone */
2051 if (xfer->xroot->xfer_mtx != &Giant) {
2052 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2054 USB_XFER_LOCK(xfer);
2056 usbd_transfer_stop(xfer);
2058 while (usbd_transfer_pending(xfer) ||
2059 xfer->flags_int.doing_callback) {
2062 * It is allowed that the callback can drop its
2063 * transfer mutex. In that case checking only
2064 * "usbd_transfer_pending()" is not enough to tell if
2065 * the USB transfer is fully drained. We also need to
2066 * check the internal "doing_callback" flag.
2068 xfer->flags_int.draining = 1;
2071 * Wait until the current outstanding USB
2072 * transfer is complete !
2074 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2076 USB_XFER_UNLOCK(xfer);
2079 struct usb_page_cache *
2080 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2082 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2084 return (&xfer->frbuffers[frindex]);
2088 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2090 struct usb_page_search page_info;
2092 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2094 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2095 return (page_info.buffer);
2098 /*------------------------------------------------------------------------*
2099 * usbd_xfer_get_fps_shift
2101 * The following function is only useful for isochronous transfers. It
2102 * returns how many times the frame execution rate has been shifted
2108 *------------------------------------------------------------------------*/
2110 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2112 return (xfer->fps_shift);
2116 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2118 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2120 return (xfer->frlengths[frindex]);
2123 /*------------------------------------------------------------------------*
2124 * usbd_xfer_set_frame_data
2126 * This function sets the pointer of the buffer that should
2127 * loaded directly into DMA for the given USB frame. Passing "ptr"
2128 * equal to NULL while the corresponding "frlength" is greater
2129 * than zero gives undefined results!
2130 *------------------------------------------------------------------------*/
2132 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2133 void *ptr, usb_frlength_t len)
2135 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2137 /* set virtual address to load and length */
2138 xfer->frbuffers[frindex].buffer = ptr;
2139 usbd_xfer_set_frame_len(xfer, frindex, len);
2143 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2144 void **ptr, int *len)
2146 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2149 *ptr = xfer->frbuffers[frindex].buffer;
2151 *len = xfer->frlengths[frindex];
2154 /*------------------------------------------------------------------------*
2155 * usbd_xfer_old_frame_length
2157 * This function returns the framelength of the given frame at the
2158 * time the transfer was submitted. This function can be used to
2159 * compute the starting data pointer of the next isochronous frame
2160 * when an isochronous transfer has completed.
2161 *------------------------------------------------------------------------*/
2163 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2165 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2167 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2171 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2175 *actlen = xfer->actlen;
2177 *sumlen = xfer->sumlen;
2178 if (aframes != NULL)
2179 *aframes = xfer->aframes;
2180 if (nframes != NULL)
2181 *nframes = xfer->nframes;
2184 /*------------------------------------------------------------------------*
2185 * usbd_xfer_set_frame_offset
2187 * This function sets the frame data buffer offset relative to the beginning
2188 * of the USB DMA buffer allocated for this USB transfer.
2189 *------------------------------------------------------------------------*/
2191 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2192 usb_frcount_t frindex)
2194 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2195 "when the USB buffer is external\n"));
2196 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2198 /* set virtual address to load */
2199 xfer->frbuffers[frindex].buffer =
2200 USB_ADD_BYTES(xfer->local_buffer, offset);
2204 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2210 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2216 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2222 usbd_xfer_max_frames(struct usb_xfer *xfer)
2224 return (xfer->max_frame_count);
2228 usbd_xfer_max_len(struct usb_xfer *xfer)
2230 return (xfer->max_data_length);
2234 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2236 return (xfer->max_frame_size);
2240 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2243 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2245 xfer->frlengths[frindex] = len;
2248 /*------------------------------------------------------------------------*
2249 * usb_callback_proc - factored out code
2251 * This function performs USB callbacks.
2252 *------------------------------------------------------------------------*/
2254 usb_callback_proc(struct usb_proc_msg *_pm)
2256 struct usb_done_msg *pm = (void *)_pm;
2257 struct usb_xfer_root *info = pm->xroot;
2259 /* Change locking order */
2260 USB_BUS_UNLOCK(info->bus);
2263 * We exploit the fact that the mutex is the same for all
2264 * callbacks that will be called from this thread:
2266 USB_MTX_LOCK(info->xfer_mtx);
2267 USB_BUS_LOCK(info->bus);
2269 /* Continue where we lost track */
2270 usb_command_wrapper(&info->done_q,
2273 USB_MTX_UNLOCK(info->xfer_mtx);
2276 /*------------------------------------------------------------------------*
2277 * usbd_callback_ss_done_defer
2279 * This function will defer the start, stop and done callback to the
2281 *------------------------------------------------------------------------*/
2283 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2285 struct usb_xfer_root *info = xfer->xroot;
2286 struct usb_xfer_queue *pq = &info->done_q;
2288 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2290 if (pq->curr != xfer) {
2291 usbd_transfer_enqueue(pq, xfer);
2293 if (!pq->recurse_1) {
2296 * We have to postpone the callback due to the fact we
2297 * will have a Lock Order Reversal, LOR, if we try to
2300 (void) usb_proc_msignal(info->done_p,
2301 &info->done_m[0], &info->done_m[1]);
2303 /* clear second recurse flag */
2310 /*------------------------------------------------------------------------*
2311 * usbd_callback_wrapper
2313 * This is a wrapper for USB callbacks. This wrapper does some
2314 * auto-magic things like figuring out if we can call the callback
2315 * directly from the current context or if we need to wakeup the
2316 * interrupt process.
2317 *------------------------------------------------------------------------*/
2319 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2321 struct usb_xfer *xfer = pq->curr;
2322 struct usb_xfer_root *info = xfer->xroot;
2324 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2325 if ((pq->recurse_3 != 0 || mtx_owned(info->xfer_mtx) == 0) &&
2326 USB_IN_POLLING_MODE_FUNC() == 0) {
2328 * Cases that end up here:
2330 * 5) HW interrupt done callback or other source.
2331 * 6) HW completed transfer during callback
2333 DPRINTFN(3, "case 5 and 6\n");
2336 * We have to postpone the callback due to the fact we
2337 * will have a Lock Order Reversal, LOR, if we try to
2340 * Postponing the callback also ensures that other USB
2341 * transfer queues get a chance.
2343 (void) usb_proc_msignal(info->done_p,
2344 &info->done_m[0], &info->done_m[1]);
2348 * Cases that end up here:
2350 * 1) We are starting a transfer
2351 * 2) We are prematurely calling back a transfer
2352 * 3) We are stopping a transfer
2353 * 4) We are doing an ordinary callback
2355 DPRINTFN(3, "case 1-4\n");
2356 /* get next USB transfer in the queue */
2357 info->done_q.curr = NULL;
2359 /* set flag in case of drain */
2360 xfer->flags_int.doing_callback = 1;
2362 USB_BUS_UNLOCK(info->bus);
2363 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2365 /* set correct USB state for callback */
2366 if (!xfer->flags_int.transferring) {
2367 xfer->usb_state = USB_ST_SETUP;
2368 if (!xfer->flags_int.started) {
2369 /* we got stopped before we even got started */
2370 USB_BUS_LOCK(info->bus);
2375 if (usbd_callback_wrapper_sub(xfer)) {
2376 /* the callback has been deferred */
2377 USB_BUS_LOCK(info->bus);
2381 /* decrement power reference */
2382 usbd_transfer_power_ref(xfer, -1);
2384 xfer->flags_int.transferring = 0;
2387 xfer->usb_state = USB_ST_ERROR;
2389 /* set transferred state */
2390 xfer->usb_state = USB_ST_TRANSFERRED;
2392 /* sync DMA memory, if any */
2393 if (xfer->flags_int.bdma_enable &&
2394 (!xfer->flags_int.bdma_no_post_sync)) {
2395 usb_bdma_post_sync(xfer);
2402 if (xfer->usb_state != USB_ST_SETUP) {
2403 USB_BUS_LOCK(info->bus);
2404 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2405 USB_BUS_UNLOCK(info->bus);
2408 /* call processing routine */
2409 (xfer->callback) (xfer, xfer->error);
2411 /* pickup the USB mutex again */
2412 USB_BUS_LOCK(info->bus);
2415 * Check if we got started after that we got cancelled, but
2416 * before we managed to do the callback.
2418 if ((!xfer->flags_int.open) &&
2419 (xfer->flags_int.started) &&
2420 (xfer->usb_state == USB_ST_ERROR)) {
2421 /* clear flag in case of drain */
2422 xfer->flags_int.doing_callback = 0;
2423 /* try to loop, but not recursivly */
2424 usb_command_wrapper(&info->done_q, xfer);
2429 /* clear flag in case of drain */
2430 xfer->flags_int.doing_callback = 0;
2433 * Check if we are draining.
2435 if (xfer->flags_int.draining &&
2436 (!xfer->flags_int.transferring)) {
2437 /* "usbd_transfer_drain()" is waiting for end of transfer */
2438 xfer->flags_int.draining = 0;
2439 cv_broadcast(&info->cv_drain);
2442 /* do the next callback, if any */
2443 usb_command_wrapper(&info->done_q,
2447 /*------------------------------------------------------------------------*
2448 * usb_dma_delay_done_cb
2450 * This function is called when the DMA delay has been exectuded, and
2451 * will make sure that the callback is called to complete the USB
2452 * transfer. This code path is usually only used when there is an USB
2453 * error like USB_ERR_CANCELLED.
2454 *------------------------------------------------------------------------*/
2456 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2458 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2460 DPRINTFN(3, "Completed %p\n", xfer);
2462 /* queue callback for execution, again */
2463 usbd_transfer_done(xfer, 0);
2466 /*------------------------------------------------------------------------*
2467 * usbd_transfer_dequeue
2469 * - This function is used to remove an USB transfer from a USB
2472 * - This function can be called multiple times in a row.
2473 *------------------------------------------------------------------------*/
2475 usbd_transfer_dequeue(struct usb_xfer *xfer)
2477 struct usb_xfer_queue *pq;
2479 pq = xfer->wait_queue;
2481 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2482 xfer->wait_queue = NULL;
2486 /*------------------------------------------------------------------------*
2487 * usbd_transfer_enqueue
2489 * - This function is used to insert an USB transfer into a USB *
2492 * - This function can be called multiple times in a row.
2493 *------------------------------------------------------------------------*/
2495 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2498 * Insert the USB transfer into the queue, if it is not
2499 * already on a USB transfer queue:
2501 if (xfer->wait_queue == NULL) {
2502 xfer->wait_queue = pq;
2503 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2507 /*------------------------------------------------------------------------*
2508 * usbd_transfer_done
2510 * - This function is used to remove an USB transfer from the busdma,
2511 * pipe or interrupt queue.
2513 * - This function is used to queue the USB transfer on the done
2516 * - This function is used to stop any USB transfer timeouts.
2517 *------------------------------------------------------------------------*/
2519 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2521 struct usb_xfer_root *info = xfer->xroot;
2523 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2525 DPRINTF("err=%s\n", usbd_errstr(error));
2528 * If we are not transferring then just return.
2529 * This can happen during transfer cancel.
2531 if (!xfer->flags_int.transferring) {
2532 DPRINTF("not transferring\n");
2533 /* end of control transfer, if any */
2534 xfer->flags_int.control_act = 0;
2537 /* only set transfer error, if not already set */
2538 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2539 xfer->error = error;
2541 /* stop any callouts */
2542 usb_callout_stop(&xfer->timeout_handle);
2545 * If we are waiting on a queue, just remove the USB transfer
2546 * from the queue, if any. We should have the required locks
2547 * locked to do the remove when this function is called.
2549 usbd_transfer_dequeue(xfer);
2552 if (mtx_owned(info->xfer_mtx)) {
2553 struct usb_xfer_queue *pq;
2556 * If the private USB lock is not locked, then we assume
2557 * that the BUS-DMA load stage has been passed:
2561 if (pq->curr == xfer) {
2562 /* start the next BUS-DMA load, if any */
2563 usb_command_wrapper(pq, NULL);
2567 /* keep some statistics */
2569 info->bus->stats_err.uds_requests
2570 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2572 info->bus->stats_ok.uds_requests
2573 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2576 /* call the USB transfer callback */
2577 usbd_callback_ss_done_defer(xfer);
2580 /*------------------------------------------------------------------------*
2581 * usbd_transfer_start_cb
2583 * This function is called to start the USB transfer when
2584 * "xfer->interval" is greater than zero, and and the endpoint type is
2586 *------------------------------------------------------------------------*/
2588 usbd_transfer_start_cb(void *arg)
2590 struct usb_xfer *xfer = arg;
2591 struct usb_endpoint *ep = xfer->endpoint;
2593 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2598 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2601 /* the transfer can now be cancelled */
2602 xfer->flags_int.can_cancel_immed = 1;
2604 /* start USB transfer, if no error */
2605 if (xfer->error == 0)
2606 (ep->methods->start) (xfer);
2608 /* check for transfer error */
2610 /* some error has happened */
2611 usbd_transfer_done(xfer, 0);
2615 /*------------------------------------------------------------------------*
2616 * usbd_xfer_set_stall
2618 * This function is used to set the stall flag outside the
2619 * callback. This function is NULL safe.
2620 *------------------------------------------------------------------------*/
2622 usbd_xfer_set_stall(struct usb_xfer *xfer)
2628 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2630 /* avoid any races by locking the USB mutex */
2631 USB_BUS_LOCK(xfer->xroot->bus);
2632 xfer->flags.stall_pipe = 1;
2633 USB_BUS_UNLOCK(xfer->xroot->bus);
2637 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2639 return (xfer->endpoint->is_stalled);
2642 /*------------------------------------------------------------------------*
2643 * usbd_transfer_clear_stall
2645 * This function is used to clear the stall flag outside the
2646 * callback. This function is NULL safe.
2647 *------------------------------------------------------------------------*/
2649 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2655 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2657 /* avoid any races by locking the USB mutex */
2658 USB_BUS_LOCK(xfer->xroot->bus);
2660 xfer->flags.stall_pipe = 0;
2662 USB_BUS_UNLOCK(xfer->xroot->bus);
2665 /*------------------------------------------------------------------------*
2668 * This function is used to add an USB transfer to the pipe transfer list.
2669 *------------------------------------------------------------------------*/
2671 usbd_pipe_start(struct usb_xfer_queue *pq)
2673 struct usb_endpoint *ep;
2674 struct usb_xfer *xfer;
2678 ep = xfer->endpoint;
2680 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2683 * If the endpoint is already stalled we do nothing !
2685 if (ep->is_stalled) {
2689 * Check if we are supposed to stall the endpoint:
2691 if (xfer->flags.stall_pipe) {
2692 struct usb_device *udev;
2693 struct usb_xfer_root *info;
2695 /* clear stall command */
2696 xfer->flags.stall_pipe = 0;
2698 /* get pointer to USB device */
2703 * Only stall BULK and INTERRUPT endpoints.
2705 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2706 if ((type == UE_BULK) ||
2707 (type == UE_INTERRUPT)) {
2712 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2713 (udev->bus->methods->set_stall) (
2714 udev, ep, &did_stall);
2715 } else if (udev->ctrl_xfer[1]) {
2716 info = udev->ctrl_xfer[1]->xroot;
2718 USB_BUS_CS_PROC(info->bus),
2719 &udev->cs_msg[0], &udev->cs_msg[1]);
2721 /* should not happen */
2722 DPRINTFN(0, "No stall handler\n");
2725 * Check if we should stall. Some USB hardware
2726 * handles set- and clear-stall in hardware.
2730 * The transfer will be continued when
2731 * the clear-stall control endpoint
2732 * message is received.
2737 } else if (type == UE_ISOCHRONOUS) {
2740 * Make sure any FIFO overflow or other FIFO
2741 * error conditions go away by resetting the
2742 * endpoint FIFO through the clear stall
2745 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2746 (udev->bus->methods->clear_stall) (udev, ep);
2750 /* Set or clear stall complete - special case */
2751 if (xfer->nframes == 0) {
2752 /* we are complete */
2754 usbd_transfer_done(xfer, 0);
2760 * 1) Start the first transfer queued.
2762 * 2) Re-start the current USB transfer.
2765 * Check if there should be any
2766 * pre transfer start delay:
2768 if (xfer->interval > 0) {
2769 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2770 if ((type == UE_BULK) ||
2771 (type == UE_CONTROL)) {
2772 usbd_transfer_timeout_ms(xfer,
2773 &usbd_transfer_start_cb,
2781 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2783 /* the transfer can now be cancelled */
2784 xfer->flags_int.can_cancel_immed = 1;
2786 /* start USB transfer, if no error */
2787 if (xfer->error == 0)
2788 (ep->methods->start) (xfer);
2790 /* check for transfer error */
2792 /* some error has happened */
2793 usbd_transfer_done(xfer, 0);
2797 /*------------------------------------------------------------------------*
2798 * usbd_transfer_timeout_ms
2800 * This function is used to setup a timeout on the given USB
2801 * transfer. If the timeout has been deferred the callback given by
2802 * "cb" will get called after "ms" milliseconds.
2803 *------------------------------------------------------------------------*/
2805 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2806 void (*cb) (void *arg), usb_timeout_t ms)
2808 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2811 usb_callout_reset(&xfer->timeout_handle,
2812 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2815 /*------------------------------------------------------------------------*
2816 * usbd_callback_wrapper_sub
2818 * - This function will update variables in an USB transfer after
2819 * that the USB transfer is complete.
2821 * - This function is used to start the next USB transfer on the
2822 * ep transfer queue, if any.
2824 * NOTE: In some special cases the USB transfer will not be removed from
2825 * the pipe queue, but remain first. To enforce USB transfer removal call
2826 * this function passing the error code "USB_ERR_CANCELLED".
2830 * Else: The callback has been deferred.
2831 *------------------------------------------------------------------------*/
2833 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2835 struct usb_endpoint *ep;
2836 struct usb_bus *bus;
2839 bus = xfer->xroot->bus;
2841 if ((!xfer->flags_int.open) &&
2842 (!xfer->flags_int.did_close)) {
2845 (xfer->endpoint->methods->close) (xfer);
2846 USB_BUS_UNLOCK(bus);
2847 /* only close once */
2848 xfer->flags_int.did_close = 1;
2849 return (1); /* wait for new callback */
2852 * If we have a non-hardware induced error we
2853 * need to do the DMA delay!
2855 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2856 (xfer->error == USB_ERR_CANCELLED ||
2857 xfer->error == USB_ERR_TIMEOUT ||
2858 bus->methods->start_dma_delay != NULL)) {
2862 /* only delay once */
2863 xfer->flags_int.did_dma_delay = 1;
2865 /* we can not cancel this delay */
2866 xfer->flags_int.can_cancel_immed = 0;
2868 temp = usbd_get_dma_delay(xfer->xroot->udev);
2870 DPRINTFN(3, "DMA delay, %u ms, "
2871 "on %p\n", temp, xfer);
2876 * Some hardware solutions have dedicated
2877 * events when it is safe to free DMA'ed
2878 * memory. For the other hardware platforms we
2879 * use a static delay.
2881 if (bus->methods->start_dma_delay != NULL) {
2882 (bus->methods->start_dma_delay) (xfer);
2884 usbd_transfer_timeout_ms(xfer,
2885 (void (*)(void *))&usb_dma_delay_done_cb,
2888 USB_BUS_UNLOCK(bus);
2889 return (1); /* wait for new callback */
2892 /* check actual number of frames */
2893 if (xfer->aframes > xfer->nframes) {
2894 if (xfer->error == 0) {
2895 panic("%s: actual number of frames, %d, is "
2896 "greater than initial number of frames, %d\n",
2897 __FUNCTION__, xfer->aframes, xfer->nframes);
2899 /* just set some valid value */
2900 xfer->aframes = xfer->nframes;
2903 /* compute actual length */
2906 for (x = 0; x != xfer->aframes; x++) {
2907 xfer->actlen += xfer->frlengths[x];
2911 * Frames that were not transferred get zero actual length in
2912 * case the USB device driver does not check the actual number
2913 * of frames transferred, "xfer->aframes":
2915 for (; x < xfer->nframes; x++) {
2916 usbd_xfer_set_frame_len(xfer, x, 0);
2919 /* check actual length */
2920 if (xfer->actlen > xfer->sumlen) {
2921 if (xfer->error == 0) {
2922 panic("%s: actual length, %d, is greater than "
2923 "initial length, %d\n",
2924 __FUNCTION__, xfer->actlen, xfer->sumlen);
2926 /* just set some valid value */
2927 xfer->actlen = xfer->sumlen;
2930 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2931 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2932 xfer->aframes, xfer->nframes);
2935 /* end of control transfer, if any */
2936 xfer->flags_int.control_act = 0;
2938 #if USB_HAVE_TT_SUPPORT
2939 switch (xfer->error) {
2940 case USB_ERR_NORMAL_COMPLETION:
2941 case USB_ERR_SHORT_XFER:
2942 case USB_ERR_STALLED:
2943 case USB_ERR_CANCELLED:
2947 /* try to reset the TT, if any */
2949 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2950 USB_BUS_UNLOCK(bus);
2954 /* check if we should block the execution queue */
2955 if ((xfer->error != USB_ERR_CANCELLED) &&
2956 (xfer->flags.pipe_bof)) {
2957 DPRINTFN(2, "xfer=%p: Block On Failure "
2958 "on endpoint=%p\n", xfer, xfer->endpoint);
2962 /* check for short transfers */
2963 if (xfer->actlen < xfer->sumlen) {
2965 /* end of control transfer, if any */
2966 xfer->flags_int.control_act = 0;
2968 if (!xfer->flags_int.short_xfer_ok) {
2969 xfer->error = USB_ERR_SHORT_XFER;
2970 if (xfer->flags.pipe_bof) {
2971 DPRINTFN(2, "xfer=%p: Block On Failure on "
2972 "Short Transfer on endpoint %p.\n",
2973 xfer, xfer->endpoint);
2979 * Check if we are in the middle of a
2982 if (xfer->flags_int.control_act) {
2983 DPRINTFN(5, "xfer=%p: Control transfer "
2984 "active on endpoint=%p\n", xfer, xfer->endpoint);
2990 ep = xfer->endpoint;
2993 * If the current USB transfer is completing we need to start the
2997 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2998 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
3000 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
3001 TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
3002 /* there is another USB transfer waiting */
3004 /* this is the last USB transfer */
3005 /* clear isochronous sync flag */
3006 xfer->endpoint->is_synced = 0;
3009 USB_BUS_UNLOCK(bus);
3014 /*------------------------------------------------------------------------*
3015 * usb_command_wrapper
3017 * This function is used to execute commands non-recursivly on an USB
3019 *------------------------------------------------------------------------*/
3021 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
3025 * If the transfer is not already processing,
3028 if (pq->curr != xfer) {
3029 usbd_transfer_enqueue(pq, xfer);
3030 if (pq->curr != NULL) {
3031 /* something is already processing */
3032 DPRINTFN(6, "busy %p\n", pq->curr);
3037 /* Get next element in queue */
3041 if (!pq->recurse_1) {
3043 /* clear third recurse flag */
3047 /* set two first recurse flags */
3051 if (pq->curr == NULL) {
3052 xfer = TAILQ_FIRST(&pq->head);
3054 TAILQ_REMOVE(&pq->head, xfer,
3056 xfer->wait_queue = NULL;
3062 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3064 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3067 * Set third recurse flag to indicate
3068 * recursion happened:
3072 } while (!pq->recurse_2);
3074 /* clear first recurse flag */
3078 /* clear second recurse flag */
3083 /*------------------------------------------------------------------------*
3084 * usbd_ctrl_transfer_setup
3086 * This function is used to setup the default USB control endpoint
3088 *------------------------------------------------------------------------*/
3090 usbd_ctrl_transfer_setup(struct usb_device *udev)
3092 struct usb_xfer *xfer;
3094 uint8_t iface_index;
3096 /* check for root HUB */
3097 if (udev->parent_hub == NULL)
3101 xfer = udev->ctrl_xfer[0];
3103 USB_XFER_LOCK(xfer);
3105 ((xfer->address == udev->address) &&
3106 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3107 udev->ddesc.bMaxPacketSize));
3108 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3111 * NOTE: checking "xfer->address" and
3112 * starting the USB transfer must be
3115 usbd_transfer_start(xfer);
3118 USB_XFER_UNLOCK(xfer);
3125 * All parameters are exactly the same like before.
3131 * Update wMaxPacketSize for the default control endpoint:
3133 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3134 udev->ddesc.bMaxPacketSize;
3137 * Unsetup any existing USB transfer:
3139 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3142 * Reset clear stall error counter.
3144 udev->clear_stall_errors = 0;
3147 * Try to setup a new USB transfer for the
3148 * default control endpoint:
3151 if (usbd_transfer_setup(udev, &iface_index,
3152 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3153 &udev->device_mtx)) {
3154 DPRINTFN(0, "could not setup default "
3161 /*------------------------------------------------------------------------*
3162 * usbd_clear_data_toggle - factored out code
3164 * NOTE: the intention of this function is not to reset the hardware
3166 *------------------------------------------------------------------------*/
3168 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3170 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3172 /* check that we have a valid case */
3173 if (udev->flags.usb_mode == USB_MODE_HOST &&
3174 udev->parent_hub != NULL &&
3175 udev->bus->methods->clear_stall != NULL &&
3176 ep->methods != NULL) {
3177 (udev->bus->methods->clear_stall) (udev, ep);
3181 /*------------------------------------------------------------------------*
3182 * usbd_clear_data_toggle - factored out code
3184 * NOTE: the intention of this function is not to reset the hardware
3185 * data toggle on the USB device side.
3186 *------------------------------------------------------------------------*/
3188 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3190 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3192 USB_BUS_LOCK(udev->bus);
3193 ep->toggle_next = 0;
3194 /* some hardware needs a callback to clear the data toggle */
3195 usbd_clear_stall_locked(udev, ep);
3196 USB_BUS_UNLOCK(udev->bus);
3199 /*------------------------------------------------------------------------*
3200 * usbd_clear_stall_callback - factored out clear stall callback
3203 * xfer1: Clear Stall Control Transfer
3204 * xfer2: Stalled USB Transfer
3206 * This function is NULL safe.
3212 * Clear stall config example:
3214 * static const struct usb_config my_clearstall = {
3215 * .type = UE_CONTROL,
3217 * .direction = UE_DIR_ANY,
3218 * .interval = 50, //50 milliseconds
3219 * .bufsize = sizeof(struct usb_device_request),
3220 * .timeout = 1000, //1.000 seconds
3221 * .callback = &my_clear_stall_callback, // **
3222 * .usb_mode = USB_MODE_HOST,
3225 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3226 * passing the correct parameters.
3227 *------------------------------------------------------------------------*/
3229 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3230 struct usb_xfer *xfer2)
3232 struct usb_device_request req;
3234 if (xfer2 == NULL) {
3235 /* looks like we are tearing down */
3236 DPRINTF("NULL input parameter\n");
3239 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3240 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3242 switch (USB_GET_STATE(xfer1)) {
3246 * pre-clear the data toggle to DATA0 ("umass.c" and
3247 * "ata-usb.c" depends on this)
3250 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3252 /* setup a clear-stall packet */
3254 req.bmRequestType = UT_WRITE_ENDPOINT;
3255 req.bRequest = UR_CLEAR_FEATURE;
3256 USETW(req.wValue, UF_ENDPOINT_HALT);
3257 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3259 USETW(req.wLength, 0);
3262 * "usbd_transfer_setup_sub()" will ensure that
3263 * we have sufficient room in the buffer for
3264 * the request structure!
3267 /* copy in the transfer */
3269 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3272 xfer1->frlengths[0] = sizeof(req);
3275 usbd_transfer_submit(xfer1);
3278 case USB_ST_TRANSFERRED:
3281 default: /* Error */
3282 if (xfer1->error == USB_ERR_CANCELLED) {
3287 return (1); /* Clear Stall Finished */
3290 /*------------------------------------------------------------------------*
3291 * usbd_transfer_poll
3293 * The following function gets called from the USB keyboard driver and
3294 * UMASS when the system has paniced.
3296 * NOTE: It is currently not possible to resume normal operation on
3297 * the USB controller which has been polled, due to clearing of the
3298 * "up_dsleep" and "up_msleep" flags.
3299 *------------------------------------------------------------------------*/
3301 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3303 struct usb_xfer *xfer;
3304 struct usb_xfer_root *xroot;
3305 struct usb_device *udev;
3306 struct usb_proc_msg *pm;
3307 struct usb_bus *bus;
3309 uint16_t drop_bus_spin;
3313 for (n = 0; n != max; n++) {
3314 /* Extra checks to avoid panic */
3317 continue; /* no USB transfer */
3318 xroot = xfer->xroot;
3320 continue; /* no USB root */
3323 continue; /* no USB device */
3326 continue; /* no BUS structure */
3327 if (bus->methods == NULL)
3328 continue; /* no BUS methods */
3329 if (bus->methods->xfer_poll == NULL)
3330 continue; /* no poll method */
3336 if (USB_IN_POLLING_MODE_FUNC() == 0) {
3337 /* make sure that the BUS spin mutex is not locked */
3338 while (mtx_owned(&bus->bus_spin_lock)) {
3339 mtx_unlock_spin(&bus->bus_spin_lock);
3343 /* make sure that the BUS mutex is not locked */
3344 while (mtx_owned(&bus->bus_mtx)) {
3345 mtx_unlock(&bus->bus_mtx);
3349 /* make sure that the transfer mutex is not locked */
3350 while (mtx_owned(xroot->xfer_mtx)) {
3351 mtx_unlock(xroot->xfer_mtx);
3356 /* Make sure cv_signal() and cv_broadcast() is not called */
3357 USB_BUS_CONTROL_XFER_PROC(bus)->up_msleep = 0;
3358 USB_BUS_EXPLORE_PROC(bus)->up_msleep = 0;
3359 USB_BUS_GIANT_PROC(bus)->up_msleep = 0;
3360 USB_BUS_NON_GIANT_ISOC_PROC(bus)->up_msleep = 0;
3361 USB_BUS_NON_GIANT_BULK_PROC(bus)->up_msleep = 0;
3363 /* poll USB hardware */
3364 (bus->methods->xfer_poll) (bus);
3366 USB_BUS_LOCK(xroot->bus);
3368 /* check for clear stall */
3369 if (udev->ctrl_xfer[1] != NULL) {
3371 /* poll clear stall start */
3372 pm = &udev->cs_msg[0].hdr;
3373 (pm->pm_callback) (pm);
3374 /* poll clear stall done thread */
3375 pm = &udev->ctrl_xfer[1]->
3376 xroot->done_m[0].hdr;
3377 (pm->pm_callback) (pm);
3380 /* poll done thread */
3381 pm = &xroot->done_m[0].hdr;
3382 (pm->pm_callback) (pm);
3384 USB_BUS_UNLOCK(xroot->bus);
3386 /* restore transfer mutex */
3388 mtx_lock(xroot->xfer_mtx);
3390 /* restore BUS mutex */
3392 mtx_lock(&bus->bus_mtx);
3394 /* restore BUS spin mutex */
3395 while (drop_bus_spin--)
3396 mtx_lock_spin(&bus->bus_spin_lock);
3401 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3402 uint8_t type, enum usb_dev_speed speed)
3404 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3405 [USB_SPEED_LOW] = 8,
3406 [USB_SPEED_FULL] = 64,
3407 [USB_SPEED_HIGH] = 1024,
3408 [USB_SPEED_VARIABLE] = 1024,
3409 [USB_SPEED_SUPER] = 1024,
3412 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3413 [USB_SPEED_LOW] = 0, /* invalid */
3414 [USB_SPEED_FULL] = 1023,
3415 [USB_SPEED_HIGH] = 1024,
3416 [USB_SPEED_VARIABLE] = 3584,
3417 [USB_SPEED_SUPER] = 1024,
3420 static const uint16_t control_min[USB_SPEED_MAX] = {
3421 [USB_SPEED_LOW] = 8,
3422 [USB_SPEED_FULL] = 8,
3423 [USB_SPEED_HIGH] = 64,
3424 [USB_SPEED_VARIABLE] = 512,
3425 [USB_SPEED_SUPER] = 512,
3428 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3429 [USB_SPEED_LOW] = 8,
3430 [USB_SPEED_FULL] = 8,
3431 [USB_SPEED_HIGH] = 512,
3432 [USB_SPEED_VARIABLE] = 512,
3433 [USB_SPEED_SUPER] = 1024,
3438 memset(ptr, 0, sizeof(*ptr));
3442 ptr->range.max = intr_range_max[speed];
3444 case UE_ISOCHRONOUS:
3445 ptr->range.max = isoc_range_max[speed];
3448 if (type == UE_BULK)
3449 temp = bulk_min[speed];
3450 else /* UE_CONTROL */
3451 temp = control_min[speed];
3453 /* default is fixed */
3454 ptr->fixed[0] = temp;
3455 ptr->fixed[1] = temp;
3456 ptr->fixed[2] = temp;
3457 ptr->fixed[3] = temp;
3459 if (speed == USB_SPEED_FULL) {
3460 /* multiple sizes */
3465 if ((speed == USB_SPEED_VARIABLE) &&
3466 (type == UE_BULK)) {
3467 /* multiple sizes */
3468 ptr->fixed[2] = 1024;
3469 ptr->fixed[3] = 1536;
3476 usbd_xfer_softc(struct usb_xfer *xfer)
3478 return (xfer->priv_sc);
3482 usbd_xfer_get_priv(struct usb_xfer *xfer)
3484 return (xfer->priv_fifo);
3488 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3490 xfer->priv_fifo = ptr;
3494 usbd_xfer_state(struct usb_xfer *xfer)
3496 return (xfer->usb_state);
3500 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3503 case USB_FORCE_SHORT_XFER:
3504 xfer->flags.force_short_xfer = 1;
3506 case USB_SHORT_XFER_OK:
3507 xfer->flags.short_xfer_ok = 1;
3509 case USB_MULTI_SHORT_OK:
3510 xfer->flags.short_frames_ok = 1;
3512 case USB_MANUAL_STATUS:
3513 xfer->flags.manual_status = 1;
3519 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3522 case USB_FORCE_SHORT_XFER:
3523 xfer->flags.force_short_xfer = 0;
3525 case USB_SHORT_XFER_OK:
3526 xfer->flags.short_xfer_ok = 0;
3528 case USB_MULTI_SHORT_OK:
3529 xfer->flags.short_frames_ok = 0;
3531 case USB_MANUAL_STATUS:
3532 xfer->flags.manual_status = 0;
3538 * The following function returns in milliseconds when the isochronous
3539 * transfer was completed by the hardware. The returned value wraps
3540 * around 65536 milliseconds.
3543 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3545 return (xfer->isoc_time_complete);
3549 * The following function returns non-zero if the max packet size
3550 * field was clamped to a valid value. Else it returns zero.
3553 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3555 return (xfer->flags_int.maxp_was_clamped);