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 static const struct usb_config usb_control_ep_quirk_cfg[USB_CTRL_XFER_MAX] = {
111 /* This transfer is used for generic control endpoint transfers */
115 .endpoint = 0x00, /* Control endpoint */
116 .direction = UE_DIR_ANY,
117 .bufsize = 65535, /* bytes */
118 .callback = &usb_request_callback,
119 .usb_mode = USB_MODE_DUAL, /* both modes */
122 /* This transfer is used for generic clear stall only */
126 .endpoint = 0x00, /* Control pipe */
127 .direction = UE_DIR_ANY,
128 .bufsize = sizeof(struct usb_device_request),
129 .callback = &usb_do_clear_stall_callback,
130 .timeout = 1000, /* 1 second */
131 .interval = 50, /* 50ms */
132 .usb_mode = USB_MODE_HOST,
136 /* function prototypes */
138 static void usbd_update_max_frame_size(struct usb_xfer *);
139 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
140 static void usbd_control_transfer_init(struct usb_xfer *);
141 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
142 static void usb_callback_proc(struct usb_proc_msg *);
143 static void usbd_callback_ss_done_defer(struct usb_xfer *);
144 static void usbd_callback_wrapper(struct usb_xfer_queue *);
145 static void usbd_transfer_start_cb(void *);
146 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
147 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
148 uint8_t type, enum usb_dev_speed speed);
150 /*------------------------------------------------------------------------*
151 * usb_request_callback
152 *------------------------------------------------------------------------*/
154 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
156 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
157 usb_handle_request_callback(xfer, error);
159 usbd_do_request_callback(xfer, error);
162 /*------------------------------------------------------------------------*
163 * usbd_update_max_frame_size
165 * This function updates the maximum frame size, hence high speed USB
166 * can transfer multiple consecutive packets.
167 *------------------------------------------------------------------------*/
169 usbd_update_max_frame_size(struct usb_xfer *xfer)
171 /* compute maximum frame size */
172 /* this computation should not overflow 16-bit */
173 /* max = 15 * 1024 */
175 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
178 /*------------------------------------------------------------------------*
181 * The following function is called when we need to
182 * synchronize with DMA hardware.
185 * 0: no DMA delay required
186 * Else: milliseconds of DMA delay
187 *------------------------------------------------------------------------*/
189 usbd_get_dma_delay(struct usb_device *udev)
191 const struct usb_bus_methods *mtod;
194 mtod = udev->bus->methods;
197 if (mtod->get_dma_delay) {
198 (mtod->get_dma_delay) (udev, &temp);
200 * Round up and convert to milliseconds. Note that we use
201 * 1024 milliseconds per second. to save a division.
209 /*------------------------------------------------------------------------*
210 * usbd_transfer_setup_sub_malloc
212 * This function will allocate one or more DMA'able memory chunks
213 * according to "size", "align" and "count" arguments. "ppc" is
214 * pointed to a linear array of USB page caches afterwards.
216 * If the "align" argument is equal to "1" a non-contiguous allocation
217 * can happen. Else if the "align" argument is greater than "1", the
218 * allocation will always be contiguous in memory.
223 *------------------------------------------------------------------------*/
226 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
227 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
230 struct usb_page_cache *pc;
241 USB_ASSERT(align > 0, ("Invalid alignment, 0x%08x\n",
243 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
246 return (0); /* nothing to allocate */
249 * Make sure that the size is aligned properly.
251 size = -((-size) & (-align));
254 * Try multi-allocation chunks to reduce the number of DMA
255 * allocations, hence DMA allocations are slow.
258 /* special case - non-cached multi page DMA memory */
260 n_dma_pg = (2 + (size / USB_PAGE_SIZE));
262 } else if (size >= USB_PAGE_SIZE) {
267 /* compute number of objects per page */
268 #ifdef USB_DMA_SINGLE_ALLOC
271 n_obj = (USB_PAGE_SIZE / size);
274 * Compute number of DMA chunks, rounded up
277 n_dma_pc = howmany(count, n_obj);
282 * DMA memory is allocated once, but mapped twice. That's why
283 * there is one list for auto-free and another list for
284 * non-auto-free which only holds the mapping and not the
287 if (parm->buf == NULL) {
288 /* reserve memory (auto-free) */
289 parm->dma_page_ptr += n_dma_pc * n_dma_pg;
290 parm->dma_page_cache_ptr += n_dma_pc;
292 /* reserve memory (no-auto-free) */
293 parm->dma_page_ptr += count * n_dma_pg;
294 parm->xfer_page_cache_ptr += count;
297 for (x = 0; x != n_dma_pc; x++) {
298 /* need to initialize the page cache */
299 parm->dma_page_cache_ptr[x].tag_parent =
300 &parm->curr_xfer->xroot->dma_parent_tag;
302 for (x = 0; x != count; x++) {
303 /* need to initialize the page cache */
304 parm->xfer_page_cache_ptr[x].tag_parent =
305 &parm->curr_xfer->xroot->dma_parent_tag;
310 *ppc = parm->xfer_page_cache_ptr;
312 *ppc = parm->dma_page_cache_ptr;
314 r = count; /* set remainder count */
315 z = n_obj * size; /* set allocation size */
316 pc = parm->xfer_page_cache_ptr;
317 pg = parm->dma_page_ptr;
321 * Avoid mapping memory twice if only a single object
322 * should be allocated per page cache:
324 for (x = 0; x != n_dma_pc; x++) {
325 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
327 return (1); /* failure */
329 /* Make room for one DMA page cache and "n_dma_pg" pages */
330 parm->dma_page_cache_ptr++;
334 for (x = 0; x != n_dma_pc; x++) {
337 /* compute last remainder */
341 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
343 return (1); /* failure */
345 /* Set beginning of current buffer */
346 buf = parm->dma_page_cache_ptr->buffer;
347 /* Make room for one DMA page cache and "n_dma_pg" pages */
348 parm->dma_page_cache_ptr++;
351 for (y = 0; (y != n_obj); y++, r--, pc++, pg += n_dma_pg) {
353 /* Load sub-chunk into DMA */
354 if (usb_pc_dmamap_create(pc, size)) {
355 return (1); /* failure */
357 pc->buffer = USB_ADD_BYTES(buf, y * size);
360 USB_MTX_LOCK(pc->tag_parent->mtx);
361 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
362 USB_MTX_UNLOCK(pc->tag_parent->mtx);
363 return (1); /* failure */
365 USB_MTX_UNLOCK(pc->tag_parent->mtx);
370 parm->xfer_page_cache_ptr = pc;
371 parm->dma_page_ptr = pg;
376 /*------------------------------------------------------------------------*
377 * usbd_transfer_setup_sub - transfer setup subroutine
379 * This function must be called from the "xfer_setup" callback of the
380 * USB Host or Device controller driver when setting up an USB
381 * transfer. This function will setup correct packet sizes, buffer
382 * sizes, flags and more, that are stored in the "usb_xfer"
384 *------------------------------------------------------------------------*/
386 usbd_transfer_setup_sub(struct usb_setup_params *parm)
392 struct usb_xfer *xfer = parm->curr_xfer;
393 const struct usb_config *setup = parm->curr_setup;
394 struct usb_endpoint_ss_comp_descriptor *ecomp;
395 struct usb_endpoint_descriptor *edesc;
396 struct usb_std_packet_size std_size;
397 usb_frcount_t n_frlengths;
398 usb_frcount_t n_frbuffers;
405 * Sanity check. The following parameters must be initialized before
406 * calling this function.
408 if ((parm->hc_max_packet_size == 0) ||
409 (parm->hc_max_packet_count == 0) ||
410 (parm->hc_max_frame_size == 0)) {
411 parm->err = USB_ERR_INVAL;
414 edesc = xfer->endpoint->edesc;
415 ecomp = xfer->endpoint->ecomp;
417 type = (edesc->bmAttributes & UE_XFERTYPE);
419 xfer->flags = setup->flags;
420 xfer->nframes = setup->frames;
421 xfer->timeout = setup->timeout;
422 xfer->callback = setup->callback;
423 xfer->interval = setup->interval;
424 xfer->endpointno = edesc->bEndpointAddress;
425 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
426 xfer->max_packet_count = 1;
427 /* make a shadow copy: */
428 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
430 parm->bufsize = setup->bufsize;
432 switch (parm->speed) {
437 xfer->max_packet_count +=
438 (xfer->max_packet_size >> 11) & 3;
440 /* check for invalid max packet count */
441 if (xfer->max_packet_count > 3)
442 xfer->max_packet_count = 3;
447 xfer->max_packet_size &= 0x7FF;
449 case USB_SPEED_SUPER:
450 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
453 xfer->max_packet_count += ecomp->bMaxBurst;
455 if ((xfer->max_packet_count == 0) ||
456 (xfer->max_packet_count > 16))
457 xfer->max_packet_count = 16;
461 xfer->max_packet_count = 1;
467 mult = UE_GET_SS_ISO_MULT(
468 ecomp->bmAttributes) + 1;
472 xfer->max_packet_count *= mult;
478 xfer->max_packet_size &= 0x7FF;
483 /* range check "max_packet_count" */
485 if (xfer->max_packet_count > parm->hc_max_packet_count) {
486 xfer->max_packet_count = parm->hc_max_packet_count;
489 /* store max packet size value before filtering */
491 maxp_old = xfer->max_packet_size;
493 /* filter "wMaxPacketSize" according to HC capabilities */
495 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
496 (xfer->max_packet_size == 0)) {
497 xfer->max_packet_size = parm->hc_max_packet_size;
499 /* filter "wMaxPacketSize" according to standard sizes */
501 usbd_get_std_packet_size(&std_size, type, parm->speed);
503 if (std_size.range.min || std_size.range.max) {
505 if (xfer->max_packet_size < std_size.range.min) {
506 xfer->max_packet_size = std_size.range.min;
508 if (xfer->max_packet_size > std_size.range.max) {
509 xfer->max_packet_size = std_size.range.max;
513 if (xfer->max_packet_size >= std_size.fixed[3]) {
514 xfer->max_packet_size = std_size.fixed[3];
515 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
516 xfer->max_packet_size = std_size.fixed[2];
517 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
518 xfer->max_packet_size = std_size.fixed[1];
520 /* only one possibility left */
521 xfer->max_packet_size = std_size.fixed[0];
526 * Check if the max packet size was outside its allowed range
527 * and clamped to a valid value:
529 if (maxp_old != xfer->max_packet_size)
530 xfer->flags_int.maxp_was_clamped = 1;
532 /* compute "max_frame_size" */
534 usbd_update_max_frame_size(xfer);
536 /* check interrupt interval and transfer pre-delay */
538 if (type == UE_ISOCHRONOUS) {
540 uint16_t frame_limit;
542 xfer->interval = 0; /* not used, must be zero */
543 xfer->flags_int.isochronous_xfr = 1; /* set flag */
545 if (xfer->timeout == 0) {
547 * set a default timeout in
548 * case something goes wrong!
550 xfer->timeout = 1000 / 4;
552 switch (parm->speed) {
555 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
559 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
560 xfer->fps_shift = edesc->bInterval;
561 if (xfer->fps_shift > 0)
563 if (xfer->fps_shift > 3)
565 if (xfer->flags.pre_scale_frames != 0)
566 xfer->nframes <<= (3 - xfer->fps_shift);
570 if (xfer->nframes > frame_limit) {
572 * this is not going to work
575 parm->err = USB_ERR_INVAL;
578 if (xfer->nframes == 0) {
580 * this is not a valid value
582 parm->err = USB_ERR_ZERO_NFRAMES;
588 * If a value is specified use that else check the
589 * endpoint descriptor!
591 if (type == UE_INTERRUPT) {
595 if (xfer->interval == 0) {
597 xfer->interval = edesc->bInterval;
599 switch (parm->speed) {
605 if (xfer->interval < 4)
607 else if (xfer->interval > 16)
608 xfer->interval = (1 << (16 - 4));
611 (1 << (xfer->interval - 4));
616 if (xfer->interval == 0) {
618 * One millisecond is the smallest
619 * interval we support:
627 while ((temp != 0) && (temp < xfer->interval)) {
632 switch (parm->speed) {
637 xfer->fps_shift += 3;
644 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
645 * to be equal to zero when setting up USB transfers, hence
646 * this leads to a lot of extra code in the USB kernel.
649 if ((xfer->max_frame_size == 0) ||
650 (xfer->max_packet_size == 0)) {
654 if ((parm->bufsize <= MIN_PKT) &&
655 (type != UE_CONTROL) &&
659 xfer->max_packet_size = MIN_PKT;
660 xfer->max_packet_count = 1;
661 parm->bufsize = 0; /* automatic setup length */
662 usbd_update_max_frame_size(xfer);
665 parm->err = USB_ERR_ZERO_MAXP;
674 * check if we should setup a default
678 if (parm->bufsize == 0) {
680 parm->bufsize = xfer->max_frame_size;
682 if (type == UE_ISOCHRONOUS) {
683 parm->bufsize *= xfer->nframes;
687 * check if we are about to setup a proxy
691 if (xfer->flags.proxy_buffer) {
693 /* round bufsize up */
695 parm->bufsize += (xfer->max_frame_size - 1);
697 if (parm->bufsize < xfer->max_frame_size) {
698 /* length wrapped around */
699 parm->err = USB_ERR_INVAL;
702 /* subtract remainder */
704 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
706 /* add length of USB device request structure, if any */
708 if (type == UE_CONTROL) {
709 parm->bufsize += REQ_SIZE; /* SETUP message */
712 xfer->max_data_length = parm->bufsize;
714 /* Setup "n_frlengths" and "n_frbuffers" */
716 if (type == UE_ISOCHRONOUS) {
717 n_frlengths = xfer->nframes;
721 if (type == UE_CONTROL) {
722 xfer->flags_int.control_xfr = 1;
723 if (xfer->nframes == 0) {
724 if (parm->bufsize <= REQ_SIZE) {
726 * there will never be any data
735 if (xfer->nframes == 0) {
740 n_frlengths = xfer->nframes;
741 n_frbuffers = xfer->nframes;
745 * check if we have room for the
746 * USB device request structure:
749 if (type == UE_CONTROL) {
751 if (xfer->max_data_length < REQ_SIZE) {
752 /* length wrapped around or too small bufsize */
753 parm->err = USB_ERR_INVAL;
756 xfer->max_data_length -= REQ_SIZE;
759 * Setup "frlengths" and shadow "frlengths" for keeping the
760 * initial frame lengths when a USB transfer is complete. This
761 * information is useful when computing isochronous offsets.
763 xfer->frlengths = parm->xfer_length_ptr;
764 parm->xfer_length_ptr += 2 * n_frlengths;
766 /* setup "frbuffers" */
767 xfer->frbuffers = parm->xfer_page_cache_ptr;
768 parm->xfer_page_cache_ptr += n_frbuffers;
770 /* initialize max frame count */
771 xfer->max_frame_count = xfer->nframes;
774 * check if we need to setup
778 if (!xfer->flags.ext_buffer) {
780 struct usb_page_search page_info;
781 struct usb_page_cache *pc;
783 if (usbd_transfer_setup_sub_malloc(parm,
784 &pc, parm->bufsize, 1, 1)) {
785 parm->err = USB_ERR_NOMEM;
786 } else if (parm->buf != NULL) {
788 usbd_get_page(pc, 0, &page_info);
790 xfer->local_buffer = page_info.buffer;
792 usbd_xfer_set_frame_offset(xfer, 0, 0);
794 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
795 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
800 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
802 if (parm->buf != NULL) {
804 USB_ADD_BYTES(parm->buf, parm->size[0]);
806 usbd_xfer_set_frame_offset(xfer, 0, 0);
808 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
809 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
812 parm->size[0] += parm->bufsize;
814 /* align data again */
815 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
819 * Compute maximum buffer size
822 if (parm->bufsize_max < parm->bufsize) {
823 parm->bufsize_max = parm->bufsize;
826 if (xfer->flags_int.bdma_enable) {
828 * Setup "dma_page_ptr".
830 * Proof for formula below:
832 * Assume there are three USB frames having length "a", "b" and
833 * "c". These USB frames will at maximum need "z"
834 * "usb_page" structures. "z" is given by:
836 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
837 * ((c / USB_PAGE_SIZE) + 2);
839 * Constraining "a", "b" and "c" like this:
841 * (a + b + c) <= parm->bufsize
845 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
847 * Here is the general formula:
849 xfer->dma_page_ptr = parm->dma_page_ptr;
850 parm->dma_page_ptr += (2 * n_frbuffers);
851 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
855 /* correct maximum data length */
856 xfer->max_data_length = 0;
858 /* subtract USB frame remainder from "hc_max_frame_size" */
860 xfer->max_hc_frame_size =
861 (parm->hc_max_frame_size -
862 (parm->hc_max_frame_size % xfer->max_frame_size));
864 if (xfer->max_hc_frame_size == 0) {
865 parm->err = USB_ERR_INVAL;
869 /* initialize frame buffers */
872 for (x = 0; x != n_frbuffers; x++) {
873 xfer->frbuffers[x].tag_parent =
874 &xfer->xroot->dma_parent_tag;
876 if (xfer->flags_int.bdma_enable &&
877 (parm->bufsize_max > 0)) {
879 if (usb_pc_dmamap_create(
881 parm->bufsize_max)) {
882 parm->err = USB_ERR_NOMEM;
892 * Set some dummy values so that we avoid division by zero:
894 xfer->max_hc_frame_size = 1;
895 xfer->max_frame_size = 1;
896 xfer->max_packet_size = 1;
897 xfer->max_data_length = 0;
899 xfer->max_frame_count = 0;
904 usbd_transfer_setup_has_bulk(const struct usb_config *setup_start,
908 uint8_t type = setup_start[n_setup].type;
909 if (type == UE_BULK || type == UE_BULK_INTR ||
916 /*------------------------------------------------------------------------*
917 * usbd_transfer_setup - setup an array of USB transfers
919 * NOTE: You must always call "usbd_transfer_unsetup" after calling
920 * "usbd_transfer_setup" if success was returned.
922 * The idea is that the USB device driver should pre-allocate all its
923 * transfers by one call to this function.
928 *------------------------------------------------------------------------*/
930 usbd_transfer_setup(struct usb_device *udev,
931 const uint8_t *ifaces, struct usb_xfer **ppxfer,
932 const struct usb_config *setup_start, uint16_t n_setup,
933 void *priv_sc, struct mtx *xfer_mtx)
935 const struct usb_config *setup_end = setup_start + n_setup;
936 const struct usb_config *setup;
937 struct usb_setup_params *parm;
938 struct usb_endpoint *ep;
939 struct usb_xfer_root *info;
940 struct usb_xfer *xfer;
942 usb_error_t error = 0;
947 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
948 "usbd_transfer_setup can sleep!");
950 /* do some checking first */
953 DPRINTFN(6, "setup array has zero length!\n");
954 return (USB_ERR_INVAL);
956 if (ifaces == NULL) {
957 DPRINTFN(6, "ifaces array is NULL!\n");
958 return (USB_ERR_INVAL);
960 if (xfer_mtx == NULL) {
961 DPRINTFN(6, "using global lock\n");
965 /* more sanity checks */
967 for (setup = setup_start, n = 0;
968 setup != setup_end; setup++, n++) {
969 if (setup->bufsize == (usb_frlength_t)-1) {
970 error = USB_ERR_BAD_BUFSIZE;
971 DPRINTF("invalid bufsize\n");
973 if (setup->callback == NULL) {
974 error = USB_ERR_NO_CALLBACK;
975 DPRINTF("no callback\n");
983 /* Protect scratch area */
984 do_unlock = usbd_ctrl_lock(udev);
989 parm = &udev->scratch.xfer_setup[0].parm;
990 memset(parm, 0, sizeof(*parm));
993 parm->speed = usbd_get_speed(udev);
994 parm->hc_max_packet_count = 1;
996 if (parm->speed >= USB_SPEED_MAX) {
997 parm->err = USB_ERR_INVAL;
1000 /* setup all transfers */
1006 * Initialize the "usb_xfer_root" structure,
1007 * which is common for all our USB transfers.
1009 info = USB_ADD_BYTES(buf, 0);
1011 info->memory_base = buf;
1012 info->memory_size = parm->size[0];
1015 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
1016 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
1018 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
1019 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
1021 cv_init(&info->cv_drain, "WDRAIN");
1023 info->xfer_mtx = xfer_mtx;
1025 usb_dma_tag_setup(&info->dma_parent_tag,
1026 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
1027 xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
1031 info->bus = udev->bus;
1034 TAILQ_INIT(&info->done_q.head);
1035 info->done_q.command = &usbd_callback_wrapper;
1037 TAILQ_INIT(&info->dma_q.head);
1038 info->dma_q.command = &usb_bdma_work_loop;
1040 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
1041 info->done_m[0].xroot = info;
1042 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
1043 info->done_m[1].xroot = info;
1046 * In device side mode control endpoint
1047 * requests need to run from a separate
1048 * context, else there is a chance of
1051 if (setup_start == usb_control_ep_cfg ||
1052 setup_start == usb_control_ep_quirk_cfg)
1054 USB_BUS_CONTROL_XFER_PROC(udev->bus);
1055 else if (xfer_mtx == &Giant)
1057 USB_BUS_GIANT_PROC(udev->bus);
1058 else if (usbd_transfer_setup_has_bulk(setup_start, n_setup))
1060 USB_BUS_NON_GIANT_BULK_PROC(udev->bus);
1063 USB_BUS_NON_GIANT_ISOC_PROC(udev->bus);
1069 parm->size[0] += sizeof(info[0]);
1071 for (setup = setup_start, n = 0;
1072 setup != setup_end; setup++, n++) {
1074 /* skip USB transfers without callbacks: */
1075 if (setup->callback == NULL) {
1078 /* see if there is a matching endpoint */
1079 ep = usbd_get_endpoint(udev,
1080 ifaces[setup->if_index], setup);
1083 * Check that the USB PIPE is valid and that
1084 * the endpoint mode is proper.
1086 * Make sure we don't allocate a streams
1087 * transfer when such a combination is not
1090 if ((ep == NULL) || (ep->methods == NULL) ||
1091 ((ep->ep_mode != USB_EP_MODE_STREAMS) &&
1092 (ep->ep_mode != USB_EP_MODE_DEFAULT)) ||
1093 (setup->stream_id != 0 &&
1094 (setup->stream_id >= USB_MAX_EP_STREAMS ||
1095 (ep->ep_mode != USB_EP_MODE_STREAMS)))) {
1096 if (setup->flags.no_pipe_ok)
1098 if ((setup->usb_mode != USB_MODE_DUAL) &&
1099 (setup->usb_mode != udev->flags.usb_mode))
1101 parm->err = USB_ERR_NO_PIPE;
1105 /* align data properly */
1106 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1108 /* store current setup pointer */
1109 parm->curr_setup = setup;
1113 * Common initialization of the
1114 * "usb_xfer" structure.
1116 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1117 xfer->address = udev->address;
1118 xfer->priv_sc = priv_sc;
1121 usb_callout_init_mtx(&xfer->timeout_handle,
1122 &udev->bus->bus_mtx, 0);
1125 * Setup a dummy xfer, hence we are
1126 * writing to the "usb_xfer"
1127 * structure pointed to by "xfer"
1128 * before we have allocated any
1131 xfer = &udev->scratch.xfer_setup[0].dummy;
1132 memset(xfer, 0, sizeof(*xfer));
1136 /* set transfer endpoint pointer */
1137 xfer->endpoint = ep;
1139 /* set transfer stream ID */
1140 xfer->stream_id = setup->stream_id;
1142 parm->size[0] += sizeof(xfer[0]);
1143 parm->methods = xfer->endpoint->methods;
1144 parm->curr_xfer = xfer;
1147 * Call the Host or Device controller transfer
1150 (udev->bus->methods->xfer_setup) (parm);
1152 /* check for error */
1158 * Increment the endpoint refcount. This
1159 * basically prevents setting a new
1160 * configuration and alternate setting
1161 * when USB transfers are in use on
1162 * the given interface. Search the USB
1163 * code for "endpoint->refcount_alloc" if you
1164 * want more information.
1166 USB_BUS_LOCK(info->bus);
1167 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1168 parm->err = USB_ERR_INVAL;
1170 xfer->endpoint->refcount_alloc++;
1172 if (xfer->endpoint->refcount_alloc == 0)
1173 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1174 USB_BUS_UNLOCK(info->bus);
1177 * Whenever we set ppxfer[] then we
1178 * also need to increment the
1181 info->setup_refcount++;
1184 * Transfer is successfully setup and
1190 /* check for error */
1195 if (buf != NULL || parm->err != 0)
1198 /* if no transfers, nothing to do */
1202 /* align data properly */
1203 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1205 /* store offset temporarily */
1206 parm->size[1] = parm->size[0];
1209 * The number of DMA tags required depends on
1210 * the number of endpoints. The current estimate
1211 * for maximum number of DMA tags per endpoint
1213 * 1) for loading memory
1214 * 2) for allocating memory
1215 * 3) for fixing memory [UHCI]
1217 parm->dma_tag_max += 3 * MIN(n_setup, USB_EP_MAX);
1220 * DMA tags for QH, TD, Data and more.
1222 parm->dma_tag_max += 8;
1224 parm->dma_tag_p += parm->dma_tag_max;
1226 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1229 /* align data properly */
1230 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1232 /* store offset temporarily */
1233 parm->size[3] = parm->size[0];
1235 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1238 /* align data properly */
1239 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1241 /* store offset temporarily */
1242 parm->size[4] = parm->size[0];
1244 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1247 /* store end offset temporarily */
1248 parm->size[5] = parm->size[0];
1250 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1253 /* store end offset temporarily */
1255 parm->size[2] = parm->size[0];
1257 /* align data properly */
1258 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1260 parm->size[6] = parm->size[0];
1262 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1265 /* align data properly */
1266 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1268 /* allocate zeroed memory */
1269 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1272 parm->err = USB_ERR_NOMEM;
1273 DPRINTFN(0, "cannot allocate memory block for "
1274 "configuration (%d bytes)\n",
1278 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1279 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1280 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1281 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1282 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1287 if (info->setup_refcount == 0) {
1289 * "usbd_transfer_unsetup_sub" will unlock
1290 * the bus mutex before returning !
1292 USB_BUS_LOCK(info->bus);
1294 /* something went wrong */
1295 usbd_transfer_unsetup_sub(info, 0);
1299 /* check if any errors happened */
1301 usbd_transfer_unsetup(ppxfer, n_setup);
1306 usbd_ctrl_unlock(udev);
1311 /*------------------------------------------------------------------------*
1312 * usbd_transfer_unsetup_sub - factored out code
1313 *------------------------------------------------------------------------*/
1315 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1318 struct usb_page_cache *pc;
1321 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1323 /* wait for any outstanding DMA operations */
1327 temp = usbd_get_dma_delay(info->udev);
1329 usb_pause_mtx(&info->bus->bus_mtx,
1330 USB_MS_TO_TICKS(temp));
1334 /* make sure that our done messages are not queued anywhere */
1335 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1337 USB_BUS_UNLOCK(info->bus);
1340 /* free DMA'able memory, if any */
1341 pc = info->dma_page_cache_start;
1342 while (pc != info->dma_page_cache_end) {
1343 usb_pc_free_mem(pc);
1347 /* free DMA maps in all "xfer->frbuffers" */
1348 pc = info->xfer_page_cache_start;
1349 while (pc != info->xfer_page_cache_end) {
1350 usb_pc_dmamap_destroy(pc);
1354 /* free all DMA tags */
1355 usb_dma_tag_unsetup(&info->dma_parent_tag);
1358 cv_destroy(&info->cv_drain);
1361 * free the "memory_base" last, hence the "info" structure is
1362 * contained within the "memory_base"!
1364 free(info->memory_base, M_USB);
1367 /*------------------------------------------------------------------------*
1368 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1370 * NOTE: All USB transfers in progress will get called back passing
1371 * the error code "USB_ERR_CANCELLED" before this function
1373 *------------------------------------------------------------------------*/
1375 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1377 struct usb_xfer *xfer;
1378 struct usb_xfer_root *info;
1379 uint8_t needs_delay = 0;
1381 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1382 "usbd_transfer_unsetup can sleep!");
1385 xfer = pxfer[n_setup];
1392 USB_XFER_LOCK(xfer);
1393 USB_BUS_LOCK(info->bus);
1396 * HINT: when you start/stop a transfer, it might be a
1397 * good idea to directly use the "pxfer[]" structure:
1399 * usbd_transfer_start(sc->pxfer[0]);
1400 * usbd_transfer_stop(sc->pxfer[0]);
1402 * That way, if your code has many parts that will not
1403 * stop running under the same lock, in other words
1404 * "xfer_mtx", the usbd_transfer_start and
1405 * usbd_transfer_stop functions will simply return
1406 * when they detect a NULL pointer argument.
1408 * To avoid any races we clear the "pxfer[]" pointer
1409 * while holding the private mutex of the driver:
1411 pxfer[n_setup] = NULL;
1413 USB_BUS_UNLOCK(info->bus);
1414 USB_XFER_UNLOCK(xfer);
1416 usbd_transfer_drain(xfer);
1419 if (xfer->flags_int.bdma_enable)
1423 * NOTE: default endpoint does not have an
1424 * interface, even if endpoint->iface_index == 0
1426 USB_BUS_LOCK(info->bus);
1427 xfer->endpoint->refcount_alloc--;
1428 USB_BUS_UNLOCK(info->bus);
1430 usb_callout_drain(&xfer->timeout_handle);
1432 USB_BUS_LOCK(info->bus);
1434 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1435 "reference count\n"));
1437 info->setup_refcount--;
1439 if (info->setup_refcount == 0) {
1440 usbd_transfer_unsetup_sub(info,
1443 USB_BUS_UNLOCK(info->bus);
1448 /*------------------------------------------------------------------------*
1449 * usbd_control_transfer_init - factored out code
1451 * In USB Device Mode we have to wait for the SETUP packet which
1452 * containst the "struct usb_device_request" structure, before we can
1453 * transfer any data. In USB Host Mode we already have the SETUP
1454 * packet at the moment the USB transfer is started. This leads us to
1455 * having to setup the USB transfer at two different places in
1456 * time. This function just contains factored out control transfer
1457 * initialisation code, so that we don't duplicate the code.
1458 *------------------------------------------------------------------------*/
1460 usbd_control_transfer_init(struct usb_xfer *xfer)
1462 struct usb_device_request req;
1464 /* copy out the USB request header */
1466 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1468 /* setup remainder */
1470 xfer->flags_int.control_rem = UGETW(req.wLength);
1472 /* copy direction to endpoint variable */
1474 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1476 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1479 /*------------------------------------------------------------------------*
1480 * usbd_control_transfer_did_data
1482 * This function returns non-zero if a control endpoint has
1483 * transferred the first DATA packet after the SETUP packet.
1484 * Else it returns zero.
1485 *------------------------------------------------------------------------*/
1487 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1489 struct usb_device_request req;
1491 /* SETUP packet is not yet sent */
1492 if (xfer->flags_int.control_hdr != 0)
1495 /* copy out the USB request header */
1496 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1498 /* compare remainder to the initial value */
1499 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1502 /*------------------------------------------------------------------------*
1503 * usbd_setup_ctrl_transfer
1505 * This function handles initialisation of control transfers. Control
1506 * transfers are special in that regard that they can both transmit
1512 *------------------------------------------------------------------------*/
1514 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1518 /* Check for control endpoint stall */
1519 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1520 /* the control transfer is no longer active */
1521 xfer->flags_int.control_stall = 1;
1522 xfer->flags_int.control_act = 0;
1524 /* don't stall control transfer by default */
1525 xfer->flags_int.control_stall = 0;
1528 /* Check for invalid number of frames */
1529 if (xfer->nframes > 2) {
1531 * If you need to split a control transfer, you
1532 * have to do one part at a time. Only with
1533 * non-control transfers you can do multiple
1536 DPRINTFN(0, "Too many frames: %u\n",
1537 (unsigned int)xfer->nframes);
1542 * Check if there is a control
1543 * transfer in progress:
1545 if (xfer->flags_int.control_act) {
1547 if (xfer->flags_int.control_hdr) {
1549 /* clear send header flag */
1551 xfer->flags_int.control_hdr = 0;
1553 /* setup control transfer */
1554 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1555 usbd_control_transfer_init(xfer);
1558 /* get data length */
1564 /* the size of the SETUP structure is hardcoded ! */
1566 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1567 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1568 xfer->frlengths[0], sizeof(struct
1569 usb_device_request));
1572 /* check USB mode */
1573 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1575 /* check number of frames */
1576 if (xfer->nframes != 1) {
1578 * We need to receive the setup
1579 * message first so that we know the
1582 DPRINTF("Misconfigured transfer\n");
1586 * Set a dummy "control_rem" value. This
1587 * variable will be overwritten later by a
1588 * call to "usbd_control_transfer_init()" !
1590 xfer->flags_int.control_rem = 0xFFFF;
1593 /* setup "endpoint" and "control_rem" */
1595 usbd_control_transfer_init(xfer);
1598 /* set transfer-header flag */
1600 xfer->flags_int.control_hdr = 1;
1602 /* get data length */
1604 len = (xfer->sumlen - sizeof(struct usb_device_request));
1607 /* update did data flag */
1609 xfer->flags_int.control_did_data =
1610 usbd_control_transfer_did_data(xfer);
1612 /* check if there is a length mismatch */
1614 if (len > xfer->flags_int.control_rem) {
1615 DPRINTFN(0, "Length (%d) greater than "
1616 "remaining length (%d)\n", len,
1617 xfer->flags_int.control_rem);
1620 /* check if we are doing a short transfer */
1622 if (xfer->flags.force_short_xfer) {
1623 xfer->flags_int.control_rem = 0;
1625 if ((len != xfer->max_data_length) &&
1626 (len != xfer->flags_int.control_rem) &&
1627 (xfer->nframes != 1)) {
1628 DPRINTFN(0, "Short control transfer without "
1629 "force_short_xfer set\n");
1632 xfer->flags_int.control_rem -= len;
1635 /* the status part is executed when "control_act" is 0 */
1637 if ((xfer->flags_int.control_rem > 0) ||
1638 (xfer->flags.manual_status)) {
1639 /* don't execute the STATUS stage yet */
1640 xfer->flags_int.control_act = 1;
1643 if ((!xfer->flags_int.control_hdr) &&
1644 (xfer->nframes == 1)) {
1646 * This is not a valid operation!
1648 DPRINTFN(0, "Invalid parameter "
1653 /* time to execute the STATUS stage */
1654 xfer->flags_int.control_act = 0;
1656 return (0); /* success */
1659 return (1); /* failure */
1662 /*------------------------------------------------------------------------*
1663 * usbd_transfer_submit - start USB hardware for the given transfer
1665 * This function should only be called from the USB callback.
1666 *------------------------------------------------------------------------*/
1668 usbd_transfer_submit(struct usb_xfer *xfer)
1670 struct usb_xfer_root *info;
1671 struct usb_bus *bus;
1677 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1678 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1682 if (USB_DEBUG_VAR > 0) {
1685 usb_dump_endpoint(xfer->endpoint);
1687 USB_BUS_UNLOCK(bus);
1691 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1692 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1694 /* Only open the USB transfer once! */
1695 if (!xfer->flags_int.open) {
1696 xfer->flags_int.open = 1;
1701 (xfer->endpoint->methods->open) (xfer);
1702 USB_BUS_UNLOCK(bus);
1704 /* set "transferring" flag */
1705 xfer->flags_int.transferring = 1;
1708 /* increment power reference */
1709 usbd_transfer_power_ref(xfer, 1);
1712 * Check if the transfer is waiting on a queue, most
1713 * frequently the "done_q":
1715 if (xfer->wait_queue) {
1717 usbd_transfer_dequeue(xfer);
1718 USB_BUS_UNLOCK(bus);
1720 /* clear "did_dma_delay" flag */
1721 xfer->flags_int.did_dma_delay = 0;
1723 /* clear "did_close" flag */
1724 xfer->flags_int.did_close = 0;
1727 /* clear "bdma_setup" flag */
1728 xfer->flags_int.bdma_setup = 0;
1730 /* by default we cannot cancel any USB transfer immediately */
1731 xfer->flags_int.can_cancel_immed = 0;
1733 /* clear lengths and frame counts by default */
1738 /* clear any previous errors */
1741 /* Check if the device is still alive */
1742 if (info->udev->state < USB_STATE_POWERED) {
1745 * Must return cancelled error code else
1746 * device drivers can hang.
1748 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1749 USB_BUS_UNLOCK(bus);
1754 if (xfer->nframes == 0) {
1755 if (xfer->flags.stall_pipe) {
1757 * Special case - want to stall without transferring
1760 DPRINTF("xfer=%p nframes=0: stall "
1761 "or clear stall!\n", xfer);
1763 xfer->flags_int.can_cancel_immed = 1;
1764 /* start the transfer */
1765 usb_command_wrapper(&xfer->endpoint->
1766 endpoint_q[xfer->stream_id], xfer);
1767 USB_BUS_UNLOCK(bus);
1771 usbd_transfer_done(xfer, USB_ERR_INVAL);
1772 USB_BUS_UNLOCK(bus);
1775 /* compute some variables */
1777 for (x = 0; x != xfer->nframes; x++) {
1778 /* make a copy of the frlenghts[] */
1779 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1780 /* compute total transfer length */
1781 xfer->sumlen += xfer->frlengths[x];
1782 if (xfer->sumlen < xfer->frlengths[x]) {
1783 /* length wrapped around */
1785 usbd_transfer_done(xfer, USB_ERR_INVAL);
1786 USB_BUS_UNLOCK(bus);
1791 /* clear some internal flags */
1793 xfer->flags_int.short_xfer_ok = 0;
1794 xfer->flags_int.short_frames_ok = 0;
1796 /* check if this is a control transfer */
1798 if (xfer->flags_int.control_xfr) {
1800 if (usbd_setup_ctrl_transfer(xfer)) {
1802 usbd_transfer_done(xfer, USB_ERR_STALLED);
1803 USB_BUS_UNLOCK(bus);
1808 * Setup filtered version of some transfer flags,
1809 * in case of data read direction
1811 if (USB_GET_DATA_ISREAD(xfer)) {
1813 if (xfer->flags.short_frames_ok) {
1814 xfer->flags_int.short_xfer_ok = 1;
1815 xfer->flags_int.short_frames_ok = 1;
1816 } else if (xfer->flags.short_xfer_ok) {
1817 xfer->flags_int.short_xfer_ok = 1;
1819 /* check for control transfer */
1820 if (xfer->flags_int.control_xfr) {
1822 * 1) Control transfers do not support
1823 * reception of multiple short USB
1824 * frames in host mode and device side
1825 * mode, with exception of:
1827 * 2) Due to sometimes buggy device
1828 * side firmware we need to do a
1829 * STATUS stage in case of short
1830 * control transfers in USB host mode.
1831 * The STATUS stage then becomes the
1832 * "alt_next" to the DATA stage.
1834 xfer->flags_int.short_frames_ok = 1;
1839 * Check if BUS-DMA support is enabled and try to load virtual
1840 * buffers into DMA, if any:
1843 if (xfer->flags_int.bdma_enable) {
1844 /* insert the USB transfer last in the BUS-DMA queue */
1845 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1850 * Enter the USB transfer into the Host Controller or
1851 * Device Controller schedule:
1853 usbd_pipe_enter(xfer);
1856 /*------------------------------------------------------------------------*
1857 * usbd_pipe_enter - factored out code
1858 *------------------------------------------------------------------------*/
1860 usbd_pipe_enter(struct usb_xfer *xfer)
1862 struct usb_endpoint *ep;
1864 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1866 USB_BUS_LOCK(xfer->xroot->bus);
1868 ep = xfer->endpoint;
1872 /* the transfer can now be cancelled */
1873 xfer->flags_int.can_cancel_immed = 1;
1875 /* enter the transfer */
1876 (ep->methods->enter) (xfer);
1878 /* check for transfer error */
1880 /* some error has happened */
1881 usbd_transfer_done(xfer, 0);
1882 USB_BUS_UNLOCK(xfer->xroot->bus);
1886 /* start the transfer */
1887 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1888 USB_BUS_UNLOCK(xfer->xroot->bus);
1891 /*------------------------------------------------------------------------*
1892 * usbd_transfer_start - start an USB transfer
1894 * NOTE: Calling this function more than one time will only
1895 * result in a single transfer start, until the USB transfer
1897 *------------------------------------------------------------------------*/
1899 usbd_transfer_start(struct usb_xfer *xfer)
1902 /* transfer is gone */
1905 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1907 /* mark the USB transfer started */
1909 if (!xfer->flags_int.started) {
1910 /* lock the BUS lock to avoid races updating flags_int */
1911 USB_BUS_LOCK(xfer->xroot->bus);
1912 xfer->flags_int.started = 1;
1913 USB_BUS_UNLOCK(xfer->xroot->bus);
1915 /* check if the USB transfer callback is already transferring */
1917 if (xfer->flags_int.transferring) {
1920 USB_BUS_LOCK(xfer->xroot->bus);
1921 /* call the USB transfer callback */
1922 usbd_callback_ss_done_defer(xfer);
1923 USB_BUS_UNLOCK(xfer->xroot->bus);
1926 /*------------------------------------------------------------------------*
1927 * usbd_transfer_stop - stop an USB transfer
1929 * NOTE: Calling this function more than one time will only
1930 * result in a single transfer stop.
1931 * NOTE: When this function returns it is not safe to free nor
1932 * reuse any DMA buffers. See "usbd_transfer_drain()".
1933 *------------------------------------------------------------------------*/
1935 usbd_transfer_stop(struct usb_xfer *xfer)
1937 struct usb_endpoint *ep;
1940 /* transfer is gone */
1943 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1945 /* check if the USB transfer was ever opened */
1947 if (!xfer->flags_int.open) {
1948 if (xfer->flags_int.started) {
1949 /* nothing to do except clearing the "started" flag */
1950 /* lock the BUS lock to avoid races updating flags_int */
1951 USB_BUS_LOCK(xfer->xroot->bus);
1952 xfer->flags_int.started = 0;
1953 USB_BUS_UNLOCK(xfer->xroot->bus);
1957 /* try to stop the current USB transfer */
1959 USB_BUS_LOCK(xfer->xroot->bus);
1960 /* override any previous error */
1961 xfer->error = USB_ERR_CANCELLED;
1964 * Clear "open" and "started" when both private and USB lock
1965 * is locked so that we don't get a race updating "flags_int"
1967 xfer->flags_int.open = 0;
1968 xfer->flags_int.started = 0;
1971 * Check if we can cancel the USB transfer immediately.
1973 if (xfer->flags_int.transferring) {
1974 if (xfer->flags_int.can_cancel_immed &&
1975 (!xfer->flags_int.did_close)) {
1978 * The following will lead to an USB_ERR_CANCELLED
1979 * error code being passed to the USB callback.
1981 (xfer->endpoint->methods->close) (xfer);
1982 /* only close once */
1983 xfer->flags_int.did_close = 1;
1985 /* need to wait for the next done callback */
1990 /* close here and now */
1991 (xfer->endpoint->methods->close) (xfer);
1994 * Any additional DMA delay is done by
1995 * "usbd_transfer_unsetup()".
1999 * Special case. Check if we need to restart a blocked
2002 ep = xfer->endpoint;
2005 * If the current USB transfer is completing we need
2006 * to start the next one:
2008 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2009 usb_command_wrapper(
2010 &ep->endpoint_q[xfer->stream_id], NULL);
2014 USB_BUS_UNLOCK(xfer->xroot->bus);
2017 /*------------------------------------------------------------------------*
2018 * usbd_transfer_pending
2020 * This function will check if an USB transfer is pending which is a
2021 * little bit complicated!
2024 * 1: Pending: The USB transfer will receive a callback in the future.
2025 *------------------------------------------------------------------------*/
2027 usbd_transfer_pending(struct usb_xfer *xfer)
2029 struct usb_xfer_root *info;
2030 struct usb_xfer_queue *pq;
2033 /* transfer is gone */
2036 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2038 if (xfer->flags_int.transferring) {
2042 USB_BUS_LOCK(xfer->xroot->bus);
2043 if (xfer->wait_queue) {
2044 /* we are waiting on a queue somewhere */
2045 USB_BUS_UNLOCK(xfer->xroot->bus);
2051 if (pq->curr == xfer) {
2052 /* we are currently scheduled for callback */
2053 USB_BUS_UNLOCK(xfer->xroot->bus);
2056 /* we are not pending */
2057 USB_BUS_UNLOCK(xfer->xroot->bus);
2061 /*------------------------------------------------------------------------*
2062 * usbd_transfer_drain
2064 * This function will stop the USB transfer and wait for any
2065 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2066 * are loaded into DMA can safely be freed or reused after that this
2067 * function has returned.
2068 *------------------------------------------------------------------------*/
2070 usbd_transfer_drain(struct usb_xfer *xfer)
2072 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2073 "usbd_transfer_drain can sleep!");
2076 /* transfer is gone */
2079 if (xfer->xroot->xfer_mtx != &Giant) {
2080 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2082 USB_XFER_LOCK(xfer);
2084 usbd_transfer_stop(xfer);
2086 while (usbd_transfer_pending(xfer) ||
2087 xfer->flags_int.doing_callback) {
2090 * It is allowed that the callback can drop its
2091 * transfer mutex. In that case checking only
2092 * "usbd_transfer_pending()" is not enough to tell if
2093 * the USB transfer is fully drained. We also need to
2094 * check the internal "doing_callback" flag.
2096 xfer->flags_int.draining = 1;
2099 * Wait until the current outstanding USB
2100 * transfer is complete !
2102 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2104 USB_XFER_UNLOCK(xfer);
2107 struct usb_page_cache *
2108 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2110 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2112 return (&xfer->frbuffers[frindex]);
2116 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2118 struct usb_page_search page_info;
2120 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2122 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2123 return (page_info.buffer);
2126 /*------------------------------------------------------------------------*
2127 * usbd_xfer_get_fps_shift
2129 * The following function is only useful for isochronous transfers. It
2130 * returns how many times the frame execution rate has been shifted
2136 *------------------------------------------------------------------------*/
2138 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2140 return (xfer->fps_shift);
2144 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2146 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2148 return (xfer->frlengths[frindex]);
2151 /*------------------------------------------------------------------------*
2152 * usbd_xfer_set_frame_data
2154 * This function sets the pointer of the buffer that should
2155 * loaded directly into DMA for the given USB frame. Passing "ptr"
2156 * equal to NULL while the corresponding "frlength" is greater
2157 * than zero gives undefined results!
2158 *------------------------------------------------------------------------*/
2160 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2161 void *ptr, usb_frlength_t len)
2163 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2165 /* set virtual address to load and length */
2166 xfer->frbuffers[frindex].buffer = ptr;
2167 usbd_xfer_set_frame_len(xfer, frindex, len);
2171 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2172 void **ptr, int *len)
2174 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2177 *ptr = xfer->frbuffers[frindex].buffer;
2179 *len = xfer->frlengths[frindex];
2182 /*------------------------------------------------------------------------*
2183 * usbd_xfer_old_frame_length
2185 * This function returns the framelength of the given frame at the
2186 * time the transfer was submitted. This function can be used to
2187 * compute the starting data pointer of the next isochronous frame
2188 * when an isochronous transfer has completed.
2189 *------------------------------------------------------------------------*/
2191 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2193 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2195 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2199 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2203 *actlen = xfer->actlen;
2205 *sumlen = xfer->sumlen;
2206 if (aframes != NULL)
2207 *aframes = xfer->aframes;
2208 if (nframes != NULL)
2209 *nframes = xfer->nframes;
2212 /*------------------------------------------------------------------------*
2213 * usbd_xfer_set_frame_offset
2215 * This function sets the frame data buffer offset relative to the beginning
2216 * of the USB DMA buffer allocated for this USB transfer.
2217 *------------------------------------------------------------------------*/
2219 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2220 usb_frcount_t frindex)
2222 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2223 "when the USB buffer is external\n"));
2224 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2226 /* set virtual address to load */
2227 xfer->frbuffers[frindex].buffer =
2228 USB_ADD_BYTES(xfer->local_buffer, offset);
2232 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2238 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2244 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2250 usbd_xfer_max_frames(struct usb_xfer *xfer)
2252 return (xfer->max_frame_count);
2256 usbd_xfer_max_len(struct usb_xfer *xfer)
2258 return (xfer->max_data_length);
2262 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2264 return (xfer->max_frame_size);
2268 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2271 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2273 xfer->frlengths[frindex] = len;
2276 /*------------------------------------------------------------------------*
2277 * usb_callback_proc - factored out code
2279 * This function performs USB callbacks.
2280 *------------------------------------------------------------------------*/
2282 usb_callback_proc(struct usb_proc_msg *_pm)
2284 struct usb_done_msg *pm = (void *)_pm;
2285 struct usb_xfer_root *info = pm->xroot;
2287 /* Change locking order */
2288 USB_BUS_UNLOCK(info->bus);
2291 * We exploit the fact that the mutex is the same for all
2292 * callbacks that will be called from this thread:
2294 USB_MTX_LOCK(info->xfer_mtx);
2295 USB_BUS_LOCK(info->bus);
2297 /* Continue where we lost track */
2298 usb_command_wrapper(&info->done_q,
2301 USB_MTX_UNLOCK(info->xfer_mtx);
2304 /*------------------------------------------------------------------------*
2305 * usbd_callback_ss_done_defer
2307 * This function will defer the start, stop and done callback to the
2309 *------------------------------------------------------------------------*/
2311 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2313 struct usb_xfer_root *info = xfer->xroot;
2314 struct usb_xfer_queue *pq = &info->done_q;
2316 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2318 if (pq->curr != xfer) {
2319 usbd_transfer_enqueue(pq, xfer);
2321 if (!pq->recurse_1) {
2324 * We have to postpone the callback due to the fact we
2325 * will have a Lock Order Reversal, LOR, if we try to
2328 (void) usb_proc_msignal(info->done_p,
2329 &info->done_m[0], &info->done_m[1]);
2331 /* clear second recurse flag */
2338 /*------------------------------------------------------------------------*
2339 * usbd_callback_wrapper
2341 * This is a wrapper for USB callbacks. This wrapper does some
2342 * auto-magic things like figuring out if we can call the callback
2343 * directly from the current context or if we need to wakeup the
2344 * interrupt process.
2345 *------------------------------------------------------------------------*/
2347 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2349 struct usb_xfer *xfer = pq->curr;
2350 struct usb_xfer_root *info = xfer->xroot;
2352 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2353 if ((pq->recurse_3 != 0 || mtx_owned(info->xfer_mtx) == 0) &&
2354 USB_IN_POLLING_MODE_FUNC() == 0) {
2356 * Cases that end up here:
2358 * 5) HW interrupt done callback or other source.
2359 * 6) HW completed transfer during callback
2361 DPRINTFN(3, "case 5 and 6\n");
2364 * We have to postpone the callback due to the fact we
2365 * will have a Lock Order Reversal, LOR, if we try to
2368 * Postponing the callback also ensures that other USB
2369 * transfer queues get a chance.
2371 (void) usb_proc_msignal(info->done_p,
2372 &info->done_m[0], &info->done_m[1]);
2376 * Cases that end up here:
2378 * 1) We are starting a transfer
2379 * 2) We are prematurely calling back a transfer
2380 * 3) We are stopping a transfer
2381 * 4) We are doing an ordinary callback
2383 DPRINTFN(3, "case 1-4\n");
2384 /* get next USB transfer in the queue */
2385 info->done_q.curr = NULL;
2387 /* set flag in case of drain */
2388 xfer->flags_int.doing_callback = 1;
2390 USB_BUS_UNLOCK(info->bus);
2391 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2393 /* set correct USB state for callback */
2394 if (!xfer->flags_int.transferring) {
2395 xfer->usb_state = USB_ST_SETUP;
2396 if (!xfer->flags_int.started) {
2397 /* we got stopped before we even got started */
2398 USB_BUS_LOCK(info->bus);
2403 if (usbd_callback_wrapper_sub(xfer)) {
2404 /* the callback has been deferred */
2405 USB_BUS_LOCK(info->bus);
2409 /* decrement power reference */
2410 usbd_transfer_power_ref(xfer, -1);
2412 xfer->flags_int.transferring = 0;
2415 xfer->usb_state = USB_ST_ERROR;
2417 /* set transferred state */
2418 xfer->usb_state = USB_ST_TRANSFERRED;
2420 /* sync DMA memory, if any */
2421 if (xfer->flags_int.bdma_enable &&
2422 (!xfer->flags_int.bdma_no_post_sync)) {
2423 usb_bdma_post_sync(xfer);
2430 if (xfer->usb_state != USB_ST_SETUP) {
2431 USB_BUS_LOCK(info->bus);
2432 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2433 USB_BUS_UNLOCK(info->bus);
2436 /* call processing routine */
2437 (xfer->callback) (xfer, xfer->error);
2439 /* pickup the USB mutex again */
2440 USB_BUS_LOCK(info->bus);
2443 * Check if we got started after that we got cancelled, but
2444 * before we managed to do the callback.
2446 if ((!xfer->flags_int.open) &&
2447 (xfer->flags_int.started) &&
2448 (xfer->usb_state == USB_ST_ERROR)) {
2449 /* clear flag in case of drain */
2450 xfer->flags_int.doing_callback = 0;
2451 /* try to loop, but not recursivly */
2452 usb_command_wrapper(&info->done_q, xfer);
2457 /* clear flag in case of drain */
2458 xfer->flags_int.doing_callback = 0;
2461 * Check if we are draining.
2463 if (xfer->flags_int.draining &&
2464 (!xfer->flags_int.transferring)) {
2465 /* "usbd_transfer_drain()" is waiting for end of transfer */
2466 xfer->flags_int.draining = 0;
2467 cv_broadcast(&info->cv_drain);
2470 /* do the next callback, if any */
2471 usb_command_wrapper(&info->done_q,
2475 /*------------------------------------------------------------------------*
2476 * usb_dma_delay_done_cb
2478 * This function is called when the DMA delay has been exectuded, and
2479 * will make sure that the callback is called to complete the USB
2480 * transfer. This code path is usually only used when there is an USB
2481 * error like USB_ERR_CANCELLED.
2482 *------------------------------------------------------------------------*/
2484 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2486 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2488 DPRINTFN(3, "Completed %p\n", xfer);
2490 /* queue callback for execution, again */
2491 usbd_transfer_done(xfer, 0);
2494 /*------------------------------------------------------------------------*
2495 * usbd_transfer_dequeue
2497 * - This function is used to remove an USB transfer from a USB
2500 * - This function can be called multiple times in a row.
2501 *------------------------------------------------------------------------*/
2503 usbd_transfer_dequeue(struct usb_xfer *xfer)
2505 struct usb_xfer_queue *pq;
2507 pq = xfer->wait_queue;
2509 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2510 xfer->wait_queue = NULL;
2514 /*------------------------------------------------------------------------*
2515 * usbd_transfer_enqueue
2517 * - This function is used to insert an USB transfer into a USB *
2520 * - This function can be called multiple times in a row.
2521 *------------------------------------------------------------------------*/
2523 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2526 * Insert the USB transfer into the queue, if it is not
2527 * already on a USB transfer queue:
2529 if (xfer->wait_queue == NULL) {
2530 xfer->wait_queue = pq;
2531 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2535 /*------------------------------------------------------------------------*
2536 * usbd_transfer_done
2538 * - This function is used to remove an USB transfer from the busdma,
2539 * pipe or interrupt queue.
2541 * - This function is used to queue the USB transfer on the done
2544 * - This function is used to stop any USB transfer timeouts.
2545 *------------------------------------------------------------------------*/
2547 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2549 struct usb_xfer_root *info = xfer->xroot;
2551 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2553 DPRINTF("err=%s\n", usbd_errstr(error));
2556 * If we are not transferring then just return.
2557 * This can happen during transfer cancel.
2559 if (!xfer->flags_int.transferring) {
2560 DPRINTF("not transferring\n");
2561 /* end of control transfer, if any */
2562 xfer->flags_int.control_act = 0;
2565 /* only set transfer error, if not already set */
2566 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2567 xfer->error = error;
2569 /* stop any callouts */
2570 usb_callout_stop(&xfer->timeout_handle);
2573 * If we are waiting on a queue, just remove the USB transfer
2574 * from the queue, if any. We should have the required locks
2575 * locked to do the remove when this function is called.
2577 usbd_transfer_dequeue(xfer);
2580 if (mtx_owned(info->xfer_mtx)) {
2581 struct usb_xfer_queue *pq;
2584 * If the private USB lock is not locked, then we assume
2585 * that the BUS-DMA load stage has been passed:
2589 if (pq->curr == xfer) {
2590 /* start the next BUS-DMA load, if any */
2591 usb_command_wrapper(pq, NULL);
2595 /* keep some statistics */
2597 info->bus->stats_err.uds_requests
2598 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2600 info->bus->stats_ok.uds_requests
2601 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2604 /* call the USB transfer callback */
2605 usbd_callback_ss_done_defer(xfer);
2608 /*------------------------------------------------------------------------*
2609 * usbd_transfer_start_cb
2611 * This function is called to start the USB transfer when
2612 * "xfer->interval" is greater than zero, and and the endpoint type is
2614 *------------------------------------------------------------------------*/
2616 usbd_transfer_start_cb(void *arg)
2618 struct usb_xfer *xfer = arg;
2619 struct usb_endpoint *ep = xfer->endpoint;
2621 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2626 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2629 /* the transfer can now be cancelled */
2630 xfer->flags_int.can_cancel_immed = 1;
2632 /* start USB transfer, if no error */
2633 if (xfer->error == 0)
2634 (ep->methods->start) (xfer);
2636 /* check for transfer error */
2638 /* some error has happened */
2639 usbd_transfer_done(xfer, 0);
2643 /*------------------------------------------------------------------------*
2644 * usbd_xfer_set_stall
2646 * This function is used to set the stall flag outside the
2647 * callback. This function is NULL safe.
2648 *------------------------------------------------------------------------*/
2650 usbd_xfer_set_stall(struct usb_xfer *xfer)
2656 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2658 /* avoid any races by locking the USB mutex */
2659 USB_BUS_LOCK(xfer->xroot->bus);
2660 xfer->flags.stall_pipe = 1;
2661 USB_BUS_UNLOCK(xfer->xroot->bus);
2665 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2667 return (xfer->endpoint->is_stalled);
2670 /*------------------------------------------------------------------------*
2671 * usbd_transfer_clear_stall
2673 * This function is used to clear the stall flag outside the
2674 * callback. This function is NULL safe.
2675 *------------------------------------------------------------------------*/
2677 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2683 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2685 /* avoid any races by locking the USB mutex */
2686 USB_BUS_LOCK(xfer->xroot->bus);
2688 xfer->flags.stall_pipe = 0;
2690 USB_BUS_UNLOCK(xfer->xroot->bus);
2693 /*------------------------------------------------------------------------*
2696 * This function is used to add an USB transfer to the pipe transfer list.
2697 *------------------------------------------------------------------------*/
2699 usbd_pipe_start(struct usb_xfer_queue *pq)
2701 struct usb_endpoint *ep;
2702 struct usb_xfer *xfer;
2706 ep = xfer->endpoint;
2708 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2711 * If the endpoint is already stalled we do nothing !
2713 if (ep->is_stalled) {
2717 * Check if we are supposed to stall the endpoint:
2719 if (xfer->flags.stall_pipe) {
2720 struct usb_device *udev;
2721 struct usb_xfer_root *info;
2723 /* clear stall command */
2724 xfer->flags.stall_pipe = 0;
2726 /* get pointer to USB device */
2731 * Only stall BULK and INTERRUPT endpoints.
2733 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2734 if ((type == UE_BULK) ||
2735 (type == UE_INTERRUPT)) {
2740 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2741 (udev->bus->methods->set_stall) (
2742 udev, ep, &did_stall);
2743 } else if (udev->ctrl_xfer[1]) {
2744 info = udev->ctrl_xfer[1]->xroot;
2746 USB_BUS_CS_PROC(info->bus),
2747 &udev->cs_msg[0], &udev->cs_msg[1]);
2749 /* should not happen */
2750 DPRINTFN(0, "No stall handler\n");
2753 * Check if we should stall. Some USB hardware
2754 * handles set- and clear-stall in hardware.
2758 * The transfer will be continued when
2759 * the clear-stall control endpoint
2760 * message is received.
2765 } else if (type == UE_ISOCHRONOUS) {
2768 * Make sure any FIFO overflow or other FIFO
2769 * error conditions go away by resetting the
2770 * endpoint FIFO through the clear stall
2773 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2774 (udev->bus->methods->clear_stall) (udev, ep);
2778 /* Set or clear stall complete - special case */
2779 if (xfer->nframes == 0) {
2780 /* we are complete */
2782 usbd_transfer_done(xfer, 0);
2788 * 1) Start the first transfer queued.
2790 * 2) Re-start the current USB transfer.
2793 * Check if there should be any
2794 * pre transfer start delay:
2796 if (xfer->interval > 0) {
2797 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2798 if ((type == UE_BULK) ||
2799 (type == UE_CONTROL)) {
2800 usbd_transfer_timeout_ms(xfer,
2801 &usbd_transfer_start_cb,
2809 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2811 /* the transfer can now be cancelled */
2812 xfer->flags_int.can_cancel_immed = 1;
2814 /* start USB transfer, if no error */
2815 if (xfer->error == 0)
2816 (ep->methods->start) (xfer);
2818 /* check for transfer error */
2820 /* some error has happened */
2821 usbd_transfer_done(xfer, 0);
2825 /*------------------------------------------------------------------------*
2826 * usbd_transfer_timeout_ms
2828 * This function is used to setup a timeout on the given USB
2829 * transfer. If the timeout has been deferred the callback given by
2830 * "cb" will get called after "ms" milliseconds.
2831 *------------------------------------------------------------------------*/
2833 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2834 void (*cb) (void *arg), usb_timeout_t ms)
2836 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2839 usb_callout_reset(&xfer->timeout_handle,
2840 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2843 /*------------------------------------------------------------------------*
2844 * usbd_callback_wrapper_sub
2846 * - This function will update variables in an USB transfer after
2847 * that the USB transfer is complete.
2849 * - This function is used to start the next USB transfer on the
2850 * ep transfer queue, if any.
2852 * NOTE: In some special cases the USB transfer will not be removed from
2853 * the pipe queue, but remain first. To enforce USB transfer removal call
2854 * this function passing the error code "USB_ERR_CANCELLED".
2858 * Else: The callback has been deferred.
2859 *------------------------------------------------------------------------*/
2861 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2863 struct usb_endpoint *ep;
2864 struct usb_bus *bus;
2867 bus = xfer->xroot->bus;
2869 if ((!xfer->flags_int.open) &&
2870 (!xfer->flags_int.did_close)) {
2873 (xfer->endpoint->methods->close) (xfer);
2874 USB_BUS_UNLOCK(bus);
2875 /* only close once */
2876 xfer->flags_int.did_close = 1;
2877 return (1); /* wait for new callback */
2880 * If we have a non-hardware induced error we
2881 * need to do the DMA delay!
2883 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2884 (xfer->error == USB_ERR_CANCELLED ||
2885 xfer->error == USB_ERR_TIMEOUT ||
2886 bus->methods->start_dma_delay != NULL)) {
2890 /* only delay once */
2891 xfer->flags_int.did_dma_delay = 1;
2893 /* we can not cancel this delay */
2894 xfer->flags_int.can_cancel_immed = 0;
2896 temp = usbd_get_dma_delay(xfer->xroot->udev);
2898 DPRINTFN(3, "DMA delay, %u ms, "
2899 "on %p\n", temp, xfer);
2904 * Some hardware solutions have dedicated
2905 * events when it is safe to free DMA'ed
2906 * memory. For the other hardware platforms we
2907 * use a static delay.
2909 if (bus->methods->start_dma_delay != NULL) {
2910 (bus->methods->start_dma_delay) (xfer);
2912 usbd_transfer_timeout_ms(xfer,
2913 (void (*)(void *))&usb_dma_delay_done_cb,
2916 USB_BUS_UNLOCK(bus);
2917 return (1); /* wait for new callback */
2920 /* check actual number of frames */
2921 if (xfer->aframes > xfer->nframes) {
2922 if (xfer->error == 0) {
2923 panic("%s: actual number of frames, %d, is "
2924 "greater than initial number of frames, %d\n",
2925 __FUNCTION__, xfer->aframes, xfer->nframes);
2927 /* just set some valid value */
2928 xfer->aframes = xfer->nframes;
2931 /* compute actual length */
2934 for (x = 0; x != xfer->aframes; x++) {
2935 xfer->actlen += xfer->frlengths[x];
2939 * Frames that were not transferred get zero actual length in
2940 * case the USB device driver does not check the actual number
2941 * of frames transferred, "xfer->aframes":
2943 for (; x < xfer->nframes; x++) {
2944 usbd_xfer_set_frame_len(xfer, x, 0);
2947 /* check actual length */
2948 if (xfer->actlen > xfer->sumlen) {
2949 if (xfer->error == 0) {
2950 panic("%s: actual length, %d, is greater than "
2951 "initial length, %d\n",
2952 __FUNCTION__, xfer->actlen, xfer->sumlen);
2954 /* just set some valid value */
2955 xfer->actlen = xfer->sumlen;
2958 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2959 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2960 xfer->aframes, xfer->nframes);
2963 /* end of control transfer, if any */
2964 xfer->flags_int.control_act = 0;
2966 #if USB_HAVE_TT_SUPPORT
2967 switch (xfer->error) {
2968 case USB_ERR_NORMAL_COMPLETION:
2969 case USB_ERR_SHORT_XFER:
2970 case USB_ERR_STALLED:
2971 case USB_ERR_CANCELLED:
2975 /* try to reset the TT, if any */
2977 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2978 USB_BUS_UNLOCK(bus);
2982 /* check if we should block the execution queue */
2983 if ((xfer->error != USB_ERR_CANCELLED) &&
2984 (xfer->flags.pipe_bof)) {
2985 DPRINTFN(2, "xfer=%p: Block On Failure "
2986 "on endpoint=%p\n", xfer, xfer->endpoint);
2990 /* check for short transfers */
2991 if (xfer->actlen < xfer->sumlen) {
2993 /* end of control transfer, if any */
2994 xfer->flags_int.control_act = 0;
2996 if (!xfer->flags_int.short_xfer_ok) {
2997 xfer->error = USB_ERR_SHORT_XFER;
2998 if (xfer->flags.pipe_bof) {
2999 DPRINTFN(2, "xfer=%p: Block On Failure on "
3000 "Short Transfer on endpoint %p.\n",
3001 xfer, xfer->endpoint);
3007 * Check if we are in the middle of a
3010 if (xfer->flags_int.control_act) {
3011 DPRINTFN(5, "xfer=%p: Control transfer "
3012 "active on endpoint=%p\n", xfer, xfer->endpoint);
3018 ep = xfer->endpoint;
3021 * If the current USB transfer is completing we need to start the
3025 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
3026 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
3028 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
3029 TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
3030 /* there is another USB transfer waiting */
3032 /* this is the last USB transfer */
3033 /* clear isochronous sync flag */
3034 xfer->endpoint->is_synced = 0;
3037 USB_BUS_UNLOCK(bus);
3042 /*------------------------------------------------------------------------*
3043 * usb_command_wrapper
3045 * This function is used to execute commands non-recursivly on an USB
3047 *------------------------------------------------------------------------*/
3049 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
3053 * If the transfer is not already processing,
3056 if (pq->curr != xfer) {
3057 usbd_transfer_enqueue(pq, xfer);
3058 if (pq->curr != NULL) {
3059 /* something is already processing */
3060 DPRINTFN(6, "busy %p\n", pq->curr);
3065 /* Get next element in queue */
3069 if (!pq->recurse_1) {
3071 /* clear third recurse flag */
3075 /* set two first recurse flags */
3079 if (pq->curr == NULL) {
3080 xfer = TAILQ_FIRST(&pq->head);
3082 TAILQ_REMOVE(&pq->head, xfer,
3084 xfer->wait_queue = NULL;
3090 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3092 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3095 * Set third recurse flag to indicate
3096 * recursion happened:
3100 } while (!pq->recurse_2);
3102 /* clear first recurse flag */
3106 /* clear second recurse flag */
3111 /*------------------------------------------------------------------------*
3112 * usbd_ctrl_transfer_setup
3114 * This function is used to setup the default USB control endpoint
3116 *------------------------------------------------------------------------*/
3118 usbd_ctrl_transfer_setup(struct usb_device *udev)
3120 struct usb_xfer *xfer;
3122 uint8_t iface_index;
3124 /* check for root HUB */
3125 if (udev->parent_hub == NULL)
3129 xfer = udev->ctrl_xfer[0];
3131 USB_XFER_LOCK(xfer);
3133 ((xfer->address == udev->address) &&
3134 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3135 udev->ddesc.bMaxPacketSize));
3136 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3139 * NOTE: checking "xfer->address" and
3140 * starting the USB transfer must be
3143 usbd_transfer_start(xfer);
3146 USB_XFER_UNLOCK(xfer);
3153 * All parameters are exactly the same like before.
3159 * Update wMaxPacketSize for the default control endpoint:
3161 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3162 udev->ddesc.bMaxPacketSize;
3165 * Unsetup any existing USB transfer:
3167 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3170 * Reset clear stall error counter.
3172 udev->clear_stall_errors = 0;
3175 * Try to setup a new USB transfer for the
3176 * default control endpoint:
3179 if (usbd_transfer_setup(udev, &iface_index,
3180 udev->ctrl_xfer, udev->bus->control_ep_quirk ?
3181 usb_control_ep_quirk_cfg : usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3182 &udev->device_mtx)) {
3183 DPRINTFN(0, "could not setup default "
3190 /*------------------------------------------------------------------------*
3191 * usbd_clear_data_toggle - factored out code
3193 * NOTE: the intention of this function is not to reset the hardware
3195 *------------------------------------------------------------------------*/
3197 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3199 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3201 /* check that we have a valid case */
3202 if (udev->flags.usb_mode == USB_MODE_HOST &&
3203 udev->parent_hub != NULL &&
3204 udev->bus->methods->clear_stall != NULL &&
3205 ep->methods != NULL) {
3206 (udev->bus->methods->clear_stall) (udev, ep);
3210 /*------------------------------------------------------------------------*
3211 * usbd_clear_data_toggle - factored out code
3213 * NOTE: the intention of this function is not to reset the hardware
3214 * data toggle on the USB device side.
3215 *------------------------------------------------------------------------*/
3217 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3219 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3221 USB_BUS_LOCK(udev->bus);
3222 ep->toggle_next = 0;
3223 /* some hardware needs a callback to clear the data toggle */
3224 usbd_clear_stall_locked(udev, ep);
3225 USB_BUS_UNLOCK(udev->bus);
3228 /*------------------------------------------------------------------------*
3229 * usbd_clear_stall_callback - factored out clear stall callback
3232 * xfer1: Clear Stall Control Transfer
3233 * xfer2: Stalled USB Transfer
3235 * This function is NULL safe.
3241 * Clear stall config example:
3243 * static const struct usb_config my_clearstall = {
3244 * .type = UE_CONTROL,
3246 * .direction = UE_DIR_ANY,
3247 * .interval = 50, //50 milliseconds
3248 * .bufsize = sizeof(struct usb_device_request),
3249 * .timeout = 1000, //1.000 seconds
3250 * .callback = &my_clear_stall_callback, // **
3251 * .usb_mode = USB_MODE_HOST,
3254 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3255 * passing the correct parameters.
3256 *------------------------------------------------------------------------*/
3258 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3259 struct usb_xfer *xfer2)
3261 struct usb_device_request req;
3263 if (xfer2 == NULL) {
3264 /* looks like we are tearing down */
3265 DPRINTF("NULL input parameter\n");
3268 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3269 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3271 switch (USB_GET_STATE(xfer1)) {
3275 * pre-clear the data toggle to DATA0 ("umass.c" and
3276 * "ata-usb.c" depends on this)
3279 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3281 /* setup a clear-stall packet */
3283 req.bmRequestType = UT_WRITE_ENDPOINT;
3284 req.bRequest = UR_CLEAR_FEATURE;
3285 USETW(req.wValue, UF_ENDPOINT_HALT);
3286 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3288 USETW(req.wLength, 0);
3291 * "usbd_transfer_setup_sub()" will ensure that
3292 * we have sufficient room in the buffer for
3293 * the request structure!
3296 /* copy in the transfer */
3298 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3301 xfer1->frlengths[0] = sizeof(req);
3304 usbd_transfer_submit(xfer1);
3307 case USB_ST_TRANSFERRED:
3310 default: /* Error */
3311 if (xfer1->error == USB_ERR_CANCELLED) {
3316 return (1); /* Clear Stall Finished */
3319 /*------------------------------------------------------------------------*
3320 * usbd_transfer_poll
3322 * The following function gets called from the USB keyboard driver and
3323 * UMASS when the system has paniced.
3325 * NOTE: It is currently not possible to resume normal operation on
3326 * the USB controller which has been polled, due to clearing of the
3327 * "up_dsleep" and "up_msleep" flags.
3328 *------------------------------------------------------------------------*/
3330 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3332 struct usb_xfer *xfer;
3333 struct usb_xfer_root *xroot;
3334 struct usb_device *udev;
3335 struct usb_proc_msg *pm;
3336 struct usb_bus *bus;
3338 uint16_t drop_bus_spin;
3342 for (n = 0; n != max; n++) {
3343 /* Extra checks to avoid panic */
3346 continue; /* no USB transfer */
3347 xroot = xfer->xroot;
3349 continue; /* no USB root */
3352 continue; /* no USB device */
3355 continue; /* no BUS structure */
3356 if (bus->methods == NULL)
3357 continue; /* no BUS methods */
3358 if (bus->methods->xfer_poll == NULL)
3359 continue; /* no poll method */
3365 if (USB_IN_POLLING_MODE_FUNC() == 0) {
3366 /* make sure that the BUS spin mutex is not locked */
3367 while (mtx_owned(&bus->bus_spin_lock)) {
3368 mtx_unlock_spin(&bus->bus_spin_lock);
3372 /* make sure that the BUS mutex is not locked */
3373 while (mtx_owned(&bus->bus_mtx)) {
3374 mtx_unlock(&bus->bus_mtx);
3378 /* make sure that the transfer mutex is not locked */
3379 while (mtx_owned(xroot->xfer_mtx)) {
3380 mtx_unlock(xroot->xfer_mtx);
3385 /* Make sure cv_signal() and cv_broadcast() is not called */
3386 USB_BUS_CONTROL_XFER_PROC(bus)->up_msleep = 0;
3387 USB_BUS_EXPLORE_PROC(bus)->up_msleep = 0;
3388 USB_BUS_GIANT_PROC(bus)->up_msleep = 0;
3389 USB_BUS_NON_GIANT_ISOC_PROC(bus)->up_msleep = 0;
3390 USB_BUS_NON_GIANT_BULK_PROC(bus)->up_msleep = 0;
3392 /* poll USB hardware */
3393 (bus->methods->xfer_poll) (bus);
3395 USB_BUS_LOCK(xroot->bus);
3397 /* check for clear stall */
3398 if (udev->ctrl_xfer[1] != NULL) {
3400 /* poll clear stall start */
3401 pm = &udev->cs_msg[0].hdr;
3402 (pm->pm_callback) (pm);
3403 /* poll clear stall done thread */
3404 pm = &udev->ctrl_xfer[1]->
3405 xroot->done_m[0].hdr;
3406 (pm->pm_callback) (pm);
3409 /* poll done thread */
3410 pm = &xroot->done_m[0].hdr;
3411 (pm->pm_callback) (pm);
3413 USB_BUS_UNLOCK(xroot->bus);
3415 /* restore transfer mutex */
3417 mtx_lock(xroot->xfer_mtx);
3419 /* restore BUS mutex */
3421 mtx_lock(&bus->bus_mtx);
3423 /* restore BUS spin mutex */
3424 while (drop_bus_spin--)
3425 mtx_lock_spin(&bus->bus_spin_lock);
3430 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3431 uint8_t type, enum usb_dev_speed speed)
3433 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3434 [USB_SPEED_LOW] = 8,
3435 [USB_SPEED_FULL] = 64,
3436 [USB_SPEED_HIGH] = 1024,
3437 [USB_SPEED_VARIABLE] = 1024,
3438 [USB_SPEED_SUPER] = 1024,
3441 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3442 [USB_SPEED_LOW] = 0, /* invalid */
3443 [USB_SPEED_FULL] = 1023,
3444 [USB_SPEED_HIGH] = 1024,
3445 [USB_SPEED_VARIABLE] = 3584,
3446 [USB_SPEED_SUPER] = 1024,
3449 static const uint16_t control_min[USB_SPEED_MAX] = {
3450 [USB_SPEED_LOW] = 8,
3451 [USB_SPEED_FULL] = 8,
3452 [USB_SPEED_HIGH] = 64,
3453 [USB_SPEED_VARIABLE] = 512,
3454 [USB_SPEED_SUPER] = 512,
3457 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3458 [USB_SPEED_LOW] = 8,
3459 [USB_SPEED_FULL] = 8,
3460 [USB_SPEED_HIGH] = 512,
3461 [USB_SPEED_VARIABLE] = 512,
3462 [USB_SPEED_SUPER] = 1024,
3467 memset(ptr, 0, sizeof(*ptr));
3471 ptr->range.max = intr_range_max[speed];
3473 case UE_ISOCHRONOUS:
3474 ptr->range.max = isoc_range_max[speed];
3477 if (type == UE_BULK)
3478 temp = bulk_min[speed];
3479 else /* UE_CONTROL */
3480 temp = control_min[speed];
3482 /* default is fixed */
3483 ptr->fixed[0] = temp;
3484 ptr->fixed[1] = temp;
3485 ptr->fixed[2] = temp;
3486 ptr->fixed[3] = temp;
3488 if (speed == USB_SPEED_FULL) {
3489 /* multiple sizes */
3494 if ((speed == USB_SPEED_VARIABLE) &&
3495 (type == UE_BULK)) {
3496 /* multiple sizes */
3497 ptr->fixed[2] = 1024;
3498 ptr->fixed[3] = 1536;
3505 usbd_xfer_softc(struct usb_xfer *xfer)
3507 return (xfer->priv_sc);
3511 usbd_xfer_get_priv(struct usb_xfer *xfer)
3513 return (xfer->priv_fifo);
3517 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3519 xfer->priv_fifo = ptr;
3523 usbd_xfer_state(struct usb_xfer *xfer)
3525 return (xfer->usb_state);
3529 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3532 case USB_FORCE_SHORT_XFER:
3533 xfer->flags.force_short_xfer = 1;
3535 case USB_SHORT_XFER_OK:
3536 xfer->flags.short_xfer_ok = 1;
3538 case USB_MULTI_SHORT_OK:
3539 xfer->flags.short_frames_ok = 1;
3541 case USB_MANUAL_STATUS:
3542 xfer->flags.manual_status = 1;
3548 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3551 case USB_FORCE_SHORT_XFER:
3552 xfer->flags.force_short_xfer = 0;
3554 case USB_SHORT_XFER_OK:
3555 xfer->flags.short_xfer_ok = 0;
3557 case USB_MULTI_SHORT_OK:
3558 xfer->flags.short_frames_ok = 0;
3560 case USB_MANUAL_STATUS:
3561 xfer->flags.manual_status = 0;
3567 * The following function returns in milliseconds when the isochronous
3568 * transfer was completed by the hardware. The returned value wraps
3569 * around 65536 milliseconds.
3572 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3574 return (xfer->isoc_time_complete);
3578 * The following function returns non-zero if the max packet size
3579 * field was clamped to a valid value. Else it returns zero.
3582 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3584 return (xfer->flags_int.maxp_was_clamped);