3 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 #include <sys/stdint.h>
28 #include <sys/stddef.h>
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/types.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
35 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/sysctl.h>
41 #include <sys/unistd.h>
42 #include <sys/callout.h>
43 #include <sys/malloc.h>
47 #include <dev/usb/usb.h>
48 #include <dev/usb/usbdi.h>
49 #include <dev/usb/usbdi_util.h>
51 #define USB_DEBUG_VAR usb_debug
53 #include <dev/usb/usb_core.h>
54 #include <dev/usb/usb_busdma.h>
55 #include <dev/usb/usb_process.h>
56 #include <dev/usb/usb_transfer.h>
57 #include <dev/usb/usb_device.h>
58 #include <dev/usb/usb_debug.h>
59 #include <dev/usb/usb_util.h>
61 #include <dev/usb/usb_controller.h>
62 #include <dev/usb/usb_bus.h>
63 #include <dev/usb/usb_pf.h>
65 struct usb_std_packet_size {
67 uint16_t min; /* inclusive */
68 uint16_t max; /* inclusive */
74 static usb_callback_t usb_request_callback;
76 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
78 /* This transfer is used for generic control endpoint transfers */
82 .endpoint = 0x00, /* Control endpoint */
83 .direction = UE_DIR_ANY,
84 .bufsize = USB_EP0_BUFSIZE, /* bytes */
85 .flags = {.proxy_buffer = 1,},
86 .callback = &usb_request_callback,
87 .usb_mode = USB_MODE_DUAL, /* both modes */
90 /* This transfer is used for generic clear stall only */
94 .endpoint = 0x00, /* Control pipe */
95 .direction = UE_DIR_ANY,
96 .bufsize = sizeof(struct usb_device_request),
97 .callback = &usb_do_clear_stall_callback,
98 .timeout = 1000, /* 1 second */
99 .interval = 50, /* 50ms */
100 .usb_mode = USB_MODE_HOST,
104 /* function prototypes */
106 static void usbd_update_max_frame_size(struct usb_xfer *);
107 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
108 static void usbd_control_transfer_init(struct usb_xfer *);
109 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
110 static void usb_callback_proc(struct usb_proc_msg *);
111 static void usbd_callback_ss_done_defer(struct usb_xfer *);
112 static void usbd_callback_wrapper(struct usb_xfer_queue *);
113 static void usbd_transfer_start_cb(void *);
114 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
115 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
116 uint8_t type, enum usb_dev_speed speed);
118 /*------------------------------------------------------------------------*
119 * usb_request_callback
120 *------------------------------------------------------------------------*/
122 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
124 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
125 usb_handle_request_callback(xfer, error);
127 usbd_do_request_callback(xfer, error);
130 /*------------------------------------------------------------------------*
131 * usbd_update_max_frame_size
133 * This function updates the maximum frame size, hence high speed USB
134 * can transfer multiple consecutive packets.
135 *------------------------------------------------------------------------*/
137 usbd_update_max_frame_size(struct usb_xfer *xfer)
139 /* compute maximum frame size */
140 /* this computation should not overflow 16-bit */
141 /* max = 15 * 1024 */
143 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
146 /*------------------------------------------------------------------------*
149 * The following function is called when we need to
150 * synchronize with DMA hardware.
153 * 0: no DMA delay required
154 * Else: milliseconds of DMA delay
155 *------------------------------------------------------------------------*/
157 usbd_get_dma_delay(struct usb_device *udev)
159 struct usb_bus_methods *mtod;
162 mtod = udev->bus->methods;
165 if (mtod->get_dma_delay) {
166 (mtod->get_dma_delay) (udev, &temp);
168 * Round up and convert to milliseconds. Note that we use
169 * 1024 milliseconds per second. to save a division.
177 /*------------------------------------------------------------------------*
178 * usbd_transfer_setup_sub_malloc
180 * This function will allocate one or more DMA'able memory chunks
181 * according to "size", "align" and "count" arguments. "ppc" is
182 * pointed to a linear array of USB page caches afterwards.
187 *------------------------------------------------------------------------*/
190 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
191 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
194 struct usb_page_cache *pc;
204 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
206 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
209 return (0); /* nothing to allocate */
212 * Make sure that the size is aligned properly.
214 size = -((-size) & (-align));
217 * Try multi-allocation chunks to reduce the number of DMA
218 * allocations, hence DMA allocations are slow.
220 if (size >= USB_PAGE_SIZE) {
224 /* compute number of objects per page */
225 n_obj = (USB_PAGE_SIZE / size);
227 * Compute number of DMA chunks, rounded up
230 n_dma_pc = ((count + n_obj - 1) / n_obj);
233 if (parm->buf == NULL) {
235 parm->dma_page_ptr += n_dma_pc;
236 parm->dma_page_cache_ptr += n_dma_pc;
237 parm->dma_page_ptr += count;
238 parm->xfer_page_cache_ptr += count;
241 for (x = 0; x != n_dma_pc; x++) {
242 /* need to initialize the page cache */
243 parm->dma_page_cache_ptr[x].tag_parent =
244 &parm->curr_xfer->xroot->dma_parent_tag;
246 for (x = 0; x != count; x++) {
247 /* need to initialize the page cache */
248 parm->xfer_page_cache_ptr[x].tag_parent =
249 &parm->curr_xfer->xroot->dma_parent_tag;
253 *ppc = parm->xfer_page_cache_ptr;
255 r = count; /* set remainder count */
256 z = n_obj * size; /* set allocation size */
257 pc = parm->xfer_page_cache_ptr;
258 pg = parm->dma_page_ptr;
260 for (x = 0; x != n_dma_pc; x++) {
263 /* compute last remainder */
267 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
269 return (1); /* failure */
271 /* Set beginning of current buffer */
272 buf = parm->dma_page_cache_ptr->buffer;
273 /* Make room for one DMA page cache and one page */
274 parm->dma_page_cache_ptr++;
277 for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
279 /* Load sub-chunk into DMA */
280 if (usb_pc_dmamap_create(pc, size)) {
281 return (1); /* failure */
283 pc->buffer = USB_ADD_BYTES(buf, y * size);
286 mtx_lock(pc->tag_parent->mtx);
287 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
288 mtx_unlock(pc->tag_parent->mtx);
289 return (1); /* failure */
291 mtx_unlock(pc->tag_parent->mtx);
295 parm->xfer_page_cache_ptr = pc;
296 parm->dma_page_ptr = pg;
301 /*------------------------------------------------------------------------*
302 * usbd_get_max_frame_length
304 * This function returns the maximum single frame length as computed by
305 * usbd_transfer_setup(). It is useful when computing buffer sizes for
306 * devices having multiple alternate settings. The SuperSpeed endpoint
307 * companion pointer is allowed to be NULL.
308 *------------------------------------------------------------------------*/
310 usbd_get_max_frame_length(const struct usb_endpoint_descriptor *edesc,
311 const struct usb_endpoint_ss_comp_descriptor *ecomp,
312 enum usb_dev_speed speed)
314 uint32_t max_packet_size;
315 uint32_t max_packet_count;
318 max_packet_size = UGETW(edesc->wMaxPacketSize);
319 max_packet_count = 1;
320 type = (edesc->bmAttributes & UE_XFERTYPE);
328 (max_packet_size >> 11) & 3;
330 /* check for invalid max packet count */
331 if (max_packet_count > 3)
332 max_packet_count = 3;
337 max_packet_size &= 0x7FF;
339 case USB_SPEED_SUPER:
340 max_packet_count += (max_packet_size >> 11) & 3;
343 max_packet_count += ecomp->bMaxBurst;
345 if ((max_packet_count == 0) ||
346 (max_packet_count > 16))
347 max_packet_count = 16;
351 max_packet_count = 1;
357 mult = UE_GET_SS_ISO_MULT(
358 ecomp->bmAttributes) + 1;
362 max_packet_count *= mult;
368 max_packet_size &= 0x7FF;
373 return (max_packet_size * max_packet_count);
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 += (xfer->max_packet_size >> 11) & 3;
439 /* check for invalid max packet count */
440 if (xfer->max_packet_count > 3)
441 xfer->max_packet_count = 3;
446 xfer->max_packet_size &= 0x7FF;
448 case USB_SPEED_SUPER:
449 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
452 xfer->max_packet_count += ecomp->bMaxBurst;
454 if ((xfer->max_packet_count == 0) ||
455 (xfer->max_packet_count > 16))
456 xfer->max_packet_count = 16;
460 xfer->max_packet_count = 1;
466 mult = (ecomp->bmAttributes & 3) + 1;
470 xfer->max_packet_count *= mult;
476 xfer->max_packet_size &= 0x7FF;
481 /* range check "max_packet_count" */
483 if (xfer->max_packet_count > parm->hc_max_packet_count) {
484 xfer->max_packet_count = parm->hc_max_packet_count;
487 /* store max packet size value before filtering */
489 maxp_old = xfer->max_packet_size;
491 /* filter "wMaxPacketSize" according to HC capabilities */
493 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
494 (xfer->max_packet_size == 0)) {
495 xfer->max_packet_size = parm->hc_max_packet_size;
497 /* filter "wMaxPacketSize" according to standard sizes */
499 usbd_get_std_packet_size(&std_size, type, parm->speed);
501 if (std_size.range.min || std_size.range.max) {
503 if (xfer->max_packet_size < std_size.range.min) {
504 xfer->max_packet_size = std_size.range.min;
506 if (xfer->max_packet_size > std_size.range.max) {
507 xfer->max_packet_size = std_size.range.max;
511 if (xfer->max_packet_size >= std_size.fixed[3]) {
512 xfer->max_packet_size = std_size.fixed[3];
513 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
514 xfer->max_packet_size = std_size.fixed[2];
515 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
516 xfer->max_packet_size = std_size.fixed[1];
518 /* only one possibility left */
519 xfer->max_packet_size = std_size.fixed[0];
524 * Check if the max packet size was outside its allowed range
525 * and clamped to a valid value:
527 if (maxp_old != xfer->max_packet_size)
528 xfer->flags_int.maxp_was_clamped = 1;
530 /* compute "max_frame_size" */
532 usbd_update_max_frame_size(xfer);
534 /* check interrupt interval and transfer pre-delay */
536 if (type == UE_ISOCHRONOUS) {
538 uint16_t frame_limit;
540 xfer->interval = 0; /* not used, must be zero */
541 xfer->flags_int.isochronous_xfr = 1; /* set flag */
543 if (xfer->timeout == 0) {
545 * set a default timeout in
546 * case something goes wrong!
548 xfer->timeout = 1000 / 4;
550 switch (parm->speed) {
553 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
557 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
558 xfer->fps_shift = edesc->bInterval;
559 if (xfer->fps_shift > 0)
561 if (xfer->fps_shift > 3)
563 if (xfer->flags.pre_scale_frames != 0)
564 xfer->nframes <<= (3 - xfer->fps_shift);
568 if (xfer->nframes > frame_limit) {
570 * this is not going to work
573 parm->err = USB_ERR_INVAL;
576 if (xfer->nframes == 0) {
578 * this is not a valid value
580 parm->err = USB_ERR_ZERO_NFRAMES;
586 * If a value is specified use that else check the
587 * endpoint descriptor!
589 if (type == UE_INTERRUPT) {
593 if (xfer->interval == 0) {
595 xfer->interval = edesc->bInterval;
597 switch (parm->speed) {
603 if (xfer->interval < 4)
605 else if (xfer->interval > 16)
606 xfer->interval = (1 << (16 - 4));
609 (1 << (xfer->interval - 4));
614 if (xfer->interval == 0) {
616 * One millisecond is the smallest
617 * interval we support:
625 while ((temp != 0) && (temp < xfer->interval)) {
630 switch (parm->speed) {
635 xfer->fps_shift += 3;
642 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
643 * to be equal to zero when setting up USB transfers, hence
644 * this leads to alot of extra code in the USB kernel.
647 if ((xfer->max_frame_size == 0) ||
648 (xfer->max_packet_size == 0)) {
652 if ((parm->bufsize <= MIN_PKT) &&
653 (type != UE_CONTROL) &&
657 xfer->max_packet_size = MIN_PKT;
658 xfer->max_packet_count = 1;
659 parm->bufsize = 0; /* automatic setup length */
660 usbd_update_max_frame_size(xfer);
663 parm->err = USB_ERR_ZERO_MAXP;
672 * check if we should setup a default
676 if (parm->bufsize == 0) {
678 parm->bufsize = xfer->max_frame_size;
680 if (type == UE_ISOCHRONOUS) {
681 parm->bufsize *= xfer->nframes;
685 * check if we are about to setup a proxy
689 if (xfer->flags.proxy_buffer) {
691 /* round bufsize up */
693 parm->bufsize += (xfer->max_frame_size - 1);
695 if (parm->bufsize < xfer->max_frame_size) {
696 /* length wrapped around */
697 parm->err = USB_ERR_INVAL;
700 /* subtract remainder */
702 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
704 /* add length of USB device request structure, if any */
706 if (type == UE_CONTROL) {
707 parm->bufsize += REQ_SIZE; /* SETUP message */
710 xfer->max_data_length = parm->bufsize;
712 /* Setup "n_frlengths" and "n_frbuffers" */
714 if (type == UE_ISOCHRONOUS) {
715 n_frlengths = xfer->nframes;
719 if (type == UE_CONTROL) {
720 xfer->flags_int.control_xfr = 1;
721 if (xfer->nframes == 0) {
722 if (parm->bufsize <= REQ_SIZE) {
724 * there will never be any data
733 if (xfer->nframes == 0) {
738 n_frlengths = xfer->nframes;
739 n_frbuffers = xfer->nframes;
743 * check if we have room for the
744 * USB device request structure:
747 if (type == UE_CONTROL) {
749 if (xfer->max_data_length < REQ_SIZE) {
750 /* length wrapped around or too small bufsize */
751 parm->err = USB_ERR_INVAL;
754 xfer->max_data_length -= REQ_SIZE;
757 * Setup "frlengths" and shadow "frlengths" for keeping the
758 * initial frame lengths when a USB transfer is complete. This
759 * information is useful when computing isochronous offsets.
761 xfer->frlengths = parm->xfer_length_ptr;
762 parm->xfer_length_ptr += 2 * n_frlengths;
764 /* setup "frbuffers" */
765 xfer->frbuffers = parm->xfer_page_cache_ptr;
766 parm->xfer_page_cache_ptr += n_frbuffers;
768 /* initialize max frame count */
769 xfer->max_frame_count = xfer->nframes;
772 * check if we need to setup
776 if (!xfer->flags.ext_buffer) {
779 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
784 USB_ADD_BYTES(parm->buf, parm->size[0]);
786 usbd_xfer_set_frame_offset(xfer, 0, 0);
788 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
789 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
792 parm->size[0] += parm->bufsize;
794 /* align data again */
795 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
798 * Compute maximum buffer size
801 if (parm->bufsize_max < parm->bufsize) {
802 parm->bufsize_max = parm->bufsize;
805 if (xfer->flags_int.bdma_enable) {
807 * Setup "dma_page_ptr".
809 * Proof for formula below:
811 * Assume there are three USB frames having length "a", "b" and
812 * "c". These USB frames will at maximum need "z"
813 * "usb_page" structures. "z" is given by:
815 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
816 * ((c / USB_PAGE_SIZE) + 2);
818 * Constraining "a", "b" and "c" like this:
820 * (a + b + c) <= parm->bufsize
824 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
826 * Here is the general formula:
828 xfer->dma_page_ptr = parm->dma_page_ptr;
829 parm->dma_page_ptr += (2 * n_frbuffers);
830 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
834 /* correct maximum data length */
835 xfer->max_data_length = 0;
837 /* subtract USB frame remainder from "hc_max_frame_size" */
839 xfer->max_hc_frame_size =
840 (parm->hc_max_frame_size -
841 (parm->hc_max_frame_size % xfer->max_frame_size));
843 if (xfer->max_hc_frame_size == 0) {
844 parm->err = USB_ERR_INVAL;
848 /* initialize frame buffers */
851 for (x = 0; x != n_frbuffers; x++) {
852 xfer->frbuffers[x].tag_parent =
853 &xfer->xroot->dma_parent_tag;
855 if (xfer->flags_int.bdma_enable &&
856 (parm->bufsize_max > 0)) {
858 if (usb_pc_dmamap_create(
860 parm->bufsize_max)) {
861 parm->err = USB_ERR_NOMEM;
871 * Set some dummy values so that we avoid division by zero:
873 xfer->max_hc_frame_size = 1;
874 xfer->max_frame_size = 1;
875 xfer->max_packet_size = 1;
876 xfer->max_data_length = 0;
878 xfer->max_frame_count = 0;
882 /*------------------------------------------------------------------------*
883 * usbd_transfer_setup - setup an array of USB transfers
885 * NOTE: You must always call "usbd_transfer_unsetup" after calling
886 * "usbd_transfer_setup" if success was returned.
888 * The idea is that the USB device driver should pre-allocate all its
889 * transfers by one call to this function.
894 *------------------------------------------------------------------------*/
896 usbd_transfer_setup(struct usb_device *udev,
897 const uint8_t *ifaces, struct usb_xfer **ppxfer,
898 const struct usb_config *setup_start, uint16_t n_setup,
899 void *priv_sc, struct mtx *xfer_mtx)
901 const struct usb_config *setup_end = setup_start + n_setup;
902 const struct usb_config *setup;
903 struct usb_setup_params *parm;
904 struct usb_endpoint *ep;
905 struct usb_xfer_root *info;
906 struct usb_xfer *xfer;
908 usb_error_t error = 0;
913 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
914 "usbd_transfer_setup can sleep!");
916 /* do some checking first */
919 DPRINTFN(6, "setup array has zero length!\n");
920 return (USB_ERR_INVAL);
923 DPRINTFN(6, "ifaces array is NULL!\n");
924 return (USB_ERR_INVAL);
926 if (xfer_mtx == NULL) {
927 DPRINTFN(6, "using global lock\n");
931 /* more sanity checks */
933 for (setup = setup_start, n = 0;
934 setup != setup_end; setup++, n++) {
935 if (setup->bufsize == (usb_frlength_t)-1) {
936 error = USB_ERR_BAD_BUFSIZE;
937 DPRINTF("invalid bufsize\n");
939 if (setup->callback == NULL) {
940 error = USB_ERR_NO_CALLBACK;
941 DPRINTF("no callback\n");
949 /* Protect scratch area */
950 do_unlock = usbd_ctrl_lock(udev);
955 parm = &udev->scratch.xfer_setup[0].parm;
956 memset(parm, 0, sizeof(*parm));
959 parm->speed = usbd_get_speed(udev);
960 parm->hc_max_packet_count = 1;
962 if (parm->speed >= USB_SPEED_MAX) {
963 parm->err = USB_ERR_INVAL;
966 /* setup all transfers */
972 * Initialize the "usb_xfer_root" structure,
973 * which is common for all our USB transfers.
975 info = USB_ADD_BYTES(buf, 0);
977 info->memory_base = buf;
978 info->memory_size = parm->size[0];
981 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
982 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
984 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
985 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
987 cv_init(&info->cv_drain, "WDRAIN");
989 info->xfer_mtx = xfer_mtx;
991 usb_dma_tag_setup(&info->dma_parent_tag,
992 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
993 xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
997 info->bus = udev->bus;
1000 TAILQ_INIT(&info->done_q.head);
1001 info->done_q.command = &usbd_callback_wrapper;
1003 TAILQ_INIT(&info->dma_q.head);
1004 info->dma_q.command = &usb_bdma_work_loop;
1006 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
1007 info->done_m[0].xroot = info;
1008 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
1009 info->done_m[1].xroot = info;
1012 * In device side mode control endpoint
1013 * requests need to run from a separate
1014 * context, else there is a chance of
1017 if (setup_start == usb_control_ep_cfg)
1019 &udev->bus->control_xfer_proc;
1020 else if (xfer_mtx == &Giant)
1022 &udev->bus->giant_callback_proc;
1025 &udev->bus->non_giant_callback_proc;
1031 parm->size[0] += sizeof(info[0]);
1033 for (setup = setup_start, n = 0;
1034 setup != setup_end; setup++, n++) {
1036 /* skip USB transfers without callbacks: */
1037 if (setup->callback == NULL) {
1040 /* see if there is a matching endpoint */
1041 ep = usbd_get_endpoint(udev,
1042 ifaces[setup->if_index], setup);
1044 if ((ep == NULL) || (ep->methods == NULL)) {
1045 if (setup->flags.no_pipe_ok)
1047 if ((setup->usb_mode != USB_MODE_DUAL) &&
1048 (setup->usb_mode != udev->flags.usb_mode))
1050 parm->err = USB_ERR_NO_PIPE;
1054 /* align data properly */
1055 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1057 /* store current setup pointer */
1058 parm->curr_setup = setup;
1062 * Common initialization of the
1063 * "usb_xfer" structure.
1065 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1066 xfer->address = udev->address;
1067 xfer->priv_sc = priv_sc;
1070 usb_callout_init_mtx(&xfer->timeout_handle,
1071 &udev->bus->bus_mtx, 0);
1074 * Setup a dummy xfer, hence we are
1075 * writing to the "usb_xfer"
1076 * structure pointed to by "xfer"
1077 * before we have allocated any
1080 xfer = &udev->scratch.xfer_setup[0].dummy;
1081 memset(xfer, 0, sizeof(*xfer));
1085 /* set transfer endpoint pointer */
1086 xfer->endpoint = ep;
1088 parm->size[0] += sizeof(xfer[0]);
1089 parm->methods = xfer->endpoint->methods;
1090 parm->curr_xfer = xfer;
1093 * Call the Host or Device controller transfer
1096 (udev->bus->methods->xfer_setup) (parm);
1098 /* check for error */
1104 * Increment the endpoint refcount. This
1105 * basically prevents setting a new
1106 * configuration and alternate setting
1107 * when USB transfers are in use on
1108 * the given interface. Search the USB
1109 * code for "endpoint->refcount_alloc" if you
1110 * want more information.
1112 USB_BUS_LOCK(info->bus);
1113 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1114 parm->err = USB_ERR_INVAL;
1116 xfer->endpoint->refcount_alloc++;
1118 if (xfer->endpoint->refcount_alloc == 0)
1119 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1120 USB_BUS_UNLOCK(info->bus);
1123 * Whenever we set ppxfer[] then we
1124 * also need to increment the
1127 info->setup_refcount++;
1130 * Transfer is successfully setup and
1136 /* check for error */
1141 if (buf != NULL || parm->err != 0)
1144 /* if no transfers, nothing to do */
1148 /* align data properly */
1149 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1151 /* store offset temporarily */
1152 parm->size[1] = parm->size[0];
1155 * The number of DMA tags required depends on
1156 * the number of endpoints. The current estimate
1157 * for maximum number of DMA tags per endpoint
1160 parm->dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1163 * DMA tags for QH, TD, Data and more.
1165 parm->dma_tag_max += 8;
1167 parm->dma_tag_p += parm->dma_tag_max;
1169 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1172 /* align data properly */
1173 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1175 /* store offset temporarily */
1176 parm->size[3] = parm->size[0];
1178 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1181 /* align data properly */
1182 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1184 /* store offset temporarily */
1185 parm->size[4] = parm->size[0];
1187 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1190 /* store end offset temporarily */
1191 parm->size[5] = parm->size[0];
1193 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1196 /* store end offset temporarily */
1198 parm->size[2] = parm->size[0];
1200 /* align data properly */
1201 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1203 parm->size[6] = parm->size[0];
1205 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1208 /* align data properly */
1209 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1211 /* allocate zeroed memory */
1212 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1215 parm->err = USB_ERR_NOMEM;
1216 DPRINTFN(0, "cannot allocate memory block for "
1217 "configuration (%d bytes)\n",
1221 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1222 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1223 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1224 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1225 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1230 if (info->setup_refcount == 0) {
1232 * "usbd_transfer_unsetup_sub" will unlock
1233 * the bus mutex before returning !
1235 USB_BUS_LOCK(info->bus);
1237 /* something went wrong */
1238 usbd_transfer_unsetup_sub(info, 0);
1242 /* check if any errors happened */
1244 usbd_transfer_unsetup(ppxfer, n_setup);
1249 usbd_ctrl_unlock(udev);
1254 /*------------------------------------------------------------------------*
1255 * usbd_transfer_unsetup_sub - factored out code
1256 *------------------------------------------------------------------------*/
1258 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1261 struct usb_page_cache *pc;
1264 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1266 /* wait for any outstanding DMA operations */
1270 temp = usbd_get_dma_delay(info->udev);
1272 usb_pause_mtx(&info->bus->bus_mtx,
1273 USB_MS_TO_TICKS(temp));
1277 /* make sure that our done messages are not queued anywhere */
1278 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1280 USB_BUS_UNLOCK(info->bus);
1283 /* free DMA'able memory, if any */
1284 pc = info->dma_page_cache_start;
1285 while (pc != info->dma_page_cache_end) {
1286 usb_pc_free_mem(pc);
1290 /* free DMA maps in all "xfer->frbuffers" */
1291 pc = info->xfer_page_cache_start;
1292 while (pc != info->xfer_page_cache_end) {
1293 usb_pc_dmamap_destroy(pc);
1297 /* free all DMA tags */
1298 usb_dma_tag_unsetup(&info->dma_parent_tag);
1301 cv_destroy(&info->cv_drain);
1304 * free the "memory_base" last, hence the "info" structure is
1305 * contained within the "memory_base"!
1307 free(info->memory_base, M_USB);
1310 /*------------------------------------------------------------------------*
1311 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1313 * NOTE: All USB transfers in progress will get called back passing
1314 * the error code "USB_ERR_CANCELLED" before this function
1316 *------------------------------------------------------------------------*/
1318 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1320 struct usb_xfer *xfer;
1321 struct usb_xfer_root *info;
1322 uint8_t needs_delay = 0;
1324 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1325 "usbd_transfer_unsetup can sleep!");
1328 xfer = pxfer[n_setup];
1335 USB_XFER_LOCK(xfer);
1336 USB_BUS_LOCK(info->bus);
1339 * HINT: when you start/stop a transfer, it might be a
1340 * good idea to directly use the "pxfer[]" structure:
1342 * usbd_transfer_start(sc->pxfer[0]);
1343 * usbd_transfer_stop(sc->pxfer[0]);
1345 * That way, if your code has many parts that will not
1346 * stop running under the same lock, in other words
1347 * "xfer_mtx", the usbd_transfer_start and
1348 * usbd_transfer_stop functions will simply return
1349 * when they detect a NULL pointer argument.
1351 * To avoid any races we clear the "pxfer[]" pointer
1352 * while holding the private mutex of the driver:
1354 pxfer[n_setup] = NULL;
1356 USB_BUS_UNLOCK(info->bus);
1357 USB_XFER_UNLOCK(xfer);
1359 usbd_transfer_drain(xfer);
1362 if (xfer->flags_int.bdma_enable)
1366 * NOTE: default endpoint does not have an
1367 * interface, even if endpoint->iface_index == 0
1369 USB_BUS_LOCK(info->bus);
1370 xfer->endpoint->refcount_alloc--;
1371 USB_BUS_UNLOCK(info->bus);
1373 usb_callout_drain(&xfer->timeout_handle);
1375 USB_BUS_LOCK(info->bus);
1377 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1378 "reference count\n"));
1380 info->setup_refcount--;
1382 if (info->setup_refcount == 0) {
1383 usbd_transfer_unsetup_sub(info,
1386 USB_BUS_UNLOCK(info->bus);
1391 /*------------------------------------------------------------------------*
1392 * usbd_control_transfer_init - factored out code
1394 * In USB Device Mode we have to wait for the SETUP packet which
1395 * containst the "struct usb_device_request" structure, before we can
1396 * transfer any data. In USB Host Mode we already have the SETUP
1397 * packet at the moment the USB transfer is started. This leads us to
1398 * having to setup the USB transfer at two different places in
1399 * time. This function just contains factored out control transfer
1400 * initialisation code, so that we don't duplicate the code.
1401 *------------------------------------------------------------------------*/
1403 usbd_control_transfer_init(struct usb_xfer *xfer)
1405 struct usb_device_request req;
1407 /* copy out the USB request header */
1409 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1411 /* setup remainder */
1413 xfer->flags_int.control_rem = UGETW(req.wLength);
1415 /* copy direction to endpoint variable */
1417 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1419 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1422 /*------------------------------------------------------------------------*
1423 * usbd_control_transfer_did_data
1425 * This function returns non-zero if a control endpoint has
1426 * transferred the first DATA packet after the SETUP packet.
1427 * Else it returns zero.
1428 *------------------------------------------------------------------------*/
1430 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1432 struct usb_device_request req;
1434 /* SETUP packet is not yet sent */
1435 if (xfer->flags_int.control_hdr != 0)
1438 /* copy out the USB request header */
1439 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1441 /* compare remainder to the initial value */
1442 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1445 /*------------------------------------------------------------------------*
1446 * usbd_setup_ctrl_transfer
1448 * This function handles initialisation of control transfers. Control
1449 * transfers are special in that regard that they can both transmit
1455 *------------------------------------------------------------------------*/
1457 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1461 /* Check for control endpoint stall */
1462 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1463 /* the control transfer is no longer active */
1464 xfer->flags_int.control_stall = 1;
1465 xfer->flags_int.control_act = 0;
1467 /* don't stall control transfer by default */
1468 xfer->flags_int.control_stall = 0;
1471 /* Check for invalid number of frames */
1472 if (xfer->nframes > 2) {
1474 * If you need to split a control transfer, you
1475 * have to do one part at a time. Only with
1476 * non-control transfers you can do multiple
1479 DPRINTFN(0, "Too many frames: %u\n",
1480 (unsigned int)xfer->nframes);
1485 * Check if there is a control
1486 * transfer in progress:
1488 if (xfer->flags_int.control_act) {
1490 if (xfer->flags_int.control_hdr) {
1492 /* clear send header flag */
1494 xfer->flags_int.control_hdr = 0;
1496 /* setup control transfer */
1497 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1498 usbd_control_transfer_init(xfer);
1501 /* get data length */
1507 /* the size of the SETUP structure is hardcoded ! */
1509 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1510 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1511 xfer->frlengths[0], sizeof(struct
1512 usb_device_request));
1515 /* check USB mode */
1516 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1518 /* check number of frames */
1519 if (xfer->nframes != 1) {
1521 * We need to receive the setup
1522 * message first so that we know the
1525 DPRINTF("Misconfigured transfer\n");
1529 * Set a dummy "control_rem" value. This
1530 * variable will be overwritten later by a
1531 * call to "usbd_control_transfer_init()" !
1533 xfer->flags_int.control_rem = 0xFFFF;
1536 /* setup "endpoint" and "control_rem" */
1538 usbd_control_transfer_init(xfer);
1541 /* set transfer-header flag */
1543 xfer->flags_int.control_hdr = 1;
1545 /* get data length */
1547 len = (xfer->sumlen - sizeof(struct usb_device_request));
1550 /* update did data flag */
1552 xfer->flags_int.control_did_data =
1553 usbd_control_transfer_did_data(xfer);
1555 /* check if there is a length mismatch */
1557 if (len > xfer->flags_int.control_rem) {
1558 DPRINTFN(0, "Length (%d) greater than "
1559 "remaining length (%d)\n", len,
1560 xfer->flags_int.control_rem);
1563 /* check if we are doing a short transfer */
1565 if (xfer->flags.force_short_xfer) {
1566 xfer->flags_int.control_rem = 0;
1568 if ((len != xfer->max_data_length) &&
1569 (len != xfer->flags_int.control_rem) &&
1570 (xfer->nframes != 1)) {
1571 DPRINTFN(0, "Short control transfer without "
1572 "force_short_xfer set\n");
1575 xfer->flags_int.control_rem -= len;
1578 /* the status part is executed when "control_act" is 0 */
1580 if ((xfer->flags_int.control_rem > 0) ||
1581 (xfer->flags.manual_status)) {
1582 /* don't execute the STATUS stage yet */
1583 xfer->flags_int.control_act = 1;
1586 if ((!xfer->flags_int.control_hdr) &&
1587 (xfer->nframes == 1)) {
1589 * This is not a valid operation!
1591 DPRINTFN(0, "Invalid parameter "
1596 /* time to execute the STATUS stage */
1597 xfer->flags_int.control_act = 0;
1599 return (0); /* success */
1602 return (1); /* failure */
1605 /*------------------------------------------------------------------------*
1606 * usbd_transfer_submit - start USB hardware for the given transfer
1608 * This function should only be called from the USB callback.
1609 *------------------------------------------------------------------------*/
1611 usbd_transfer_submit(struct usb_xfer *xfer)
1613 struct usb_xfer_root *info;
1614 struct usb_bus *bus;
1620 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1621 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1625 if (USB_DEBUG_VAR > 0) {
1628 usb_dump_endpoint(xfer->endpoint);
1630 USB_BUS_UNLOCK(bus);
1634 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1635 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1637 /* Only open the USB transfer once! */
1638 if (!xfer->flags_int.open) {
1639 xfer->flags_int.open = 1;
1644 (xfer->endpoint->methods->open) (xfer);
1645 USB_BUS_UNLOCK(bus);
1647 /* set "transferring" flag */
1648 xfer->flags_int.transferring = 1;
1651 /* increment power reference */
1652 usbd_transfer_power_ref(xfer, 1);
1655 * Check if the transfer is waiting on a queue, most
1656 * frequently the "done_q":
1658 if (xfer->wait_queue) {
1660 usbd_transfer_dequeue(xfer);
1661 USB_BUS_UNLOCK(bus);
1663 /* clear "did_dma_delay" flag */
1664 xfer->flags_int.did_dma_delay = 0;
1666 /* clear "did_close" flag */
1667 xfer->flags_int.did_close = 0;
1670 /* clear "bdma_setup" flag */
1671 xfer->flags_int.bdma_setup = 0;
1673 /* by default we cannot cancel any USB transfer immediately */
1674 xfer->flags_int.can_cancel_immed = 0;
1676 /* clear lengths and frame counts by default */
1681 /* clear any previous errors */
1684 /* Check if the device is still alive */
1685 if (info->udev->state < USB_STATE_POWERED) {
1688 * Must return cancelled error code else
1689 * device drivers can hang.
1691 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1692 USB_BUS_UNLOCK(bus);
1697 if (xfer->nframes == 0) {
1698 if (xfer->flags.stall_pipe) {
1700 * Special case - want to stall without transferring
1703 DPRINTF("xfer=%p nframes=0: stall "
1704 "or clear stall!\n", xfer);
1706 xfer->flags_int.can_cancel_immed = 1;
1707 /* start the transfer */
1708 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1709 USB_BUS_UNLOCK(bus);
1713 usbd_transfer_done(xfer, USB_ERR_INVAL);
1714 USB_BUS_UNLOCK(bus);
1717 /* compute some variables */
1719 for (x = 0; x != xfer->nframes; x++) {
1720 /* make a copy of the frlenghts[] */
1721 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1722 /* compute total transfer length */
1723 xfer->sumlen += xfer->frlengths[x];
1724 if (xfer->sumlen < xfer->frlengths[x]) {
1725 /* length wrapped around */
1727 usbd_transfer_done(xfer, USB_ERR_INVAL);
1728 USB_BUS_UNLOCK(bus);
1733 /* clear some internal flags */
1735 xfer->flags_int.short_xfer_ok = 0;
1736 xfer->flags_int.short_frames_ok = 0;
1738 /* check if this is a control transfer */
1740 if (xfer->flags_int.control_xfr) {
1742 if (usbd_setup_ctrl_transfer(xfer)) {
1744 usbd_transfer_done(xfer, USB_ERR_STALLED);
1745 USB_BUS_UNLOCK(bus);
1750 * Setup filtered version of some transfer flags,
1751 * in case of data read direction
1753 if (USB_GET_DATA_ISREAD(xfer)) {
1755 if (xfer->flags.short_frames_ok) {
1756 xfer->flags_int.short_xfer_ok = 1;
1757 xfer->flags_int.short_frames_ok = 1;
1758 } else if (xfer->flags.short_xfer_ok) {
1759 xfer->flags_int.short_xfer_ok = 1;
1761 /* check for control transfer */
1762 if (xfer->flags_int.control_xfr) {
1764 * 1) Control transfers do not support
1765 * reception of multiple short USB
1766 * frames in host mode and device side
1767 * mode, with exception of:
1769 * 2) Due to sometimes buggy device
1770 * side firmware we need to do a
1771 * STATUS stage in case of short
1772 * control transfers in USB host mode.
1773 * The STATUS stage then becomes the
1774 * "alt_next" to the DATA stage.
1776 xfer->flags_int.short_frames_ok = 1;
1781 * Check if BUS-DMA support is enabled and try to load virtual
1782 * buffers into DMA, if any:
1785 if (xfer->flags_int.bdma_enable) {
1786 /* insert the USB transfer last in the BUS-DMA queue */
1787 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1792 * Enter the USB transfer into the Host Controller or
1793 * Device Controller schedule:
1795 usbd_pipe_enter(xfer);
1798 /*------------------------------------------------------------------------*
1799 * usbd_pipe_enter - factored out code
1800 *------------------------------------------------------------------------*/
1802 usbd_pipe_enter(struct usb_xfer *xfer)
1804 struct usb_endpoint *ep;
1806 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1808 USB_BUS_LOCK(xfer->xroot->bus);
1810 ep = xfer->endpoint;
1814 /* the transfer can now be cancelled */
1815 xfer->flags_int.can_cancel_immed = 1;
1817 /* enter the transfer */
1818 (ep->methods->enter) (xfer);
1820 /* check for transfer error */
1822 /* some error has happened */
1823 usbd_transfer_done(xfer, 0);
1824 USB_BUS_UNLOCK(xfer->xroot->bus);
1828 /* start the transfer */
1829 usb_command_wrapper(&ep->endpoint_q, xfer);
1830 USB_BUS_UNLOCK(xfer->xroot->bus);
1833 /*------------------------------------------------------------------------*
1834 * usbd_transfer_start - start an USB transfer
1836 * NOTE: Calling this function more than one time will only
1837 * result in a single transfer start, until the USB transfer
1839 *------------------------------------------------------------------------*/
1841 usbd_transfer_start(struct usb_xfer *xfer)
1844 /* transfer is gone */
1847 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1849 /* mark the USB transfer started */
1851 if (!xfer->flags_int.started) {
1852 /* lock the BUS lock to avoid races updating flags_int */
1853 USB_BUS_LOCK(xfer->xroot->bus);
1854 xfer->flags_int.started = 1;
1855 USB_BUS_UNLOCK(xfer->xroot->bus);
1857 /* check if the USB transfer callback is already transferring */
1859 if (xfer->flags_int.transferring) {
1862 USB_BUS_LOCK(xfer->xroot->bus);
1863 /* call the USB transfer callback */
1864 usbd_callback_ss_done_defer(xfer);
1865 USB_BUS_UNLOCK(xfer->xroot->bus);
1868 /*------------------------------------------------------------------------*
1869 * usbd_transfer_stop - stop an USB transfer
1871 * NOTE: Calling this function more than one time will only
1872 * result in a single transfer stop.
1873 * NOTE: When this function returns it is not safe to free nor
1874 * reuse any DMA buffers. See "usbd_transfer_drain()".
1875 *------------------------------------------------------------------------*/
1877 usbd_transfer_stop(struct usb_xfer *xfer)
1879 struct usb_endpoint *ep;
1882 /* transfer is gone */
1885 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1887 /* check if the USB transfer was ever opened */
1889 if (!xfer->flags_int.open) {
1890 if (xfer->flags_int.started) {
1891 /* nothing to do except clearing the "started" flag */
1892 /* lock the BUS lock to avoid races updating flags_int */
1893 USB_BUS_LOCK(xfer->xroot->bus);
1894 xfer->flags_int.started = 0;
1895 USB_BUS_UNLOCK(xfer->xroot->bus);
1899 /* try to stop the current USB transfer */
1901 USB_BUS_LOCK(xfer->xroot->bus);
1902 /* override any previous error */
1903 xfer->error = USB_ERR_CANCELLED;
1906 * Clear "open" and "started" when both private and USB lock
1907 * is locked so that we don't get a race updating "flags_int"
1909 xfer->flags_int.open = 0;
1910 xfer->flags_int.started = 0;
1913 * Check if we can cancel the USB transfer immediately.
1915 if (xfer->flags_int.transferring) {
1916 if (xfer->flags_int.can_cancel_immed &&
1917 (!xfer->flags_int.did_close)) {
1920 * The following will lead to an USB_ERR_CANCELLED
1921 * error code being passed to the USB callback.
1923 (xfer->endpoint->methods->close) (xfer);
1924 /* only close once */
1925 xfer->flags_int.did_close = 1;
1927 /* need to wait for the next done callback */
1932 /* close here and now */
1933 (xfer->endpoint->methods->close) (xfer);
1936 * Any additional DMA delay is done by
1937 * "usbd_transfer_unsetup()".
1941 * Special case. Check if we need to restart a blocked
1944 ep = xfer->endpoint;
1947 * If the current USB transfer is completing we need
1948 * to start the next one:
1950 if (ep->endpoint_q.curr == xfer) {
1951 usb_command_wrapper(&ep->endpoint_q, NULL);
1955 USB_BUS_UNLOCK(xfer->xroot->bus);
1958 /*------------------------------------------------------------------------*
1959 * usbd_transfer_pending
1961 * This function will check if an USB transfer is pending which is a
1962 * little bit complicated!
1965 * 1: Pending: The USB transfer will receive a callback in the future.
1966 *------------------------------------------------------------------------*/
1968 usbd_transfer_pending(struct usb_xfer *xfer)
1970 struct usb_xfer_root *info;
1971 struct usb_xfer_queue *pq;
1974 /* transfer is gone */
1977 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1979 if (xfer->flags_int.transferring) {
1983 USB_BUS_LOCK(xfer->xroot->bus);
1984 if (xfer->wait_queue) {
1985 /* we are waiting on a queue somewhere */
1986 USB_BUS_UNLOCK(xfer->xroot->bus);
1992 if (pq->curr == xfer) {
1993 /* we are currently scheduled for callback */
1994 USB_BUS_UNLOCK(xfer->xroot->bus);
1997 /* we are not pending */
1998 USB_BUS_UNLOCK(xfer->xroot->bus);
2002 /*------------------------------------------------------------------------*
2003 * usbd_transfer_drain
2005 * This function will stop the USB transfer and wait for any
2006 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2007 * are loaded into DMA can safely be freed or reused after that this
2008 * function has returned.
2009 *------------------------------------------------------------------------*/
2011 usbd_transfer_drain(struct usb_xfer *xfer)
2013 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2014 "usbd_transfer_drain can sleep!");
2017 /* transfer is gone */
2020 if (xfer->xroot->xfer_mtx != &Giant) {
2021 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2023 USB_XFER_LOCK(xfer);
2025 usbd_transfer_stop(xfer);
2027 while (usbd_transfer_pending(xfer) ||
2028 xfer->flags_int.doing_callback) {
2031 * It is allowed that the callback can drop its
2032 * transfer mutex. In that case checking only
2033 * "usbd_transfer_pending()" is not enough to tell if
2034 * the USB transfer is fully drained. We also need to
2035 * check the internal "doing_callback" flag.
2037 xfer->flags_int.draining = 1;
2040 * Wait until the current outstanding USB
2041 * transfer is complete !
2043 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2045 USB_XFER_UNLOCK(xfer);
2048 struct usb_page_cache *
2049 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2051 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2053 return (&xfer->frbuffers[frindex]);
2057 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2059 struct usb_page_search page_info;
2061 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2063 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2064 return (page_info.buffer);
2067 /*------------------------------------------------------------------------*
2068 * usbd_xfer_get_fps_shift
2070 * The following function is only useful for isochronous transfers. It
2071 * returns how many times the frame execution rate has been shifted
2077 *------------------------------------------------------------------------*/
2079 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2081 return (xfer->fps_shift);
2085 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2087 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2089 return (xfer->frlengths[frindex]);
2092 /*------------------------------------------------------------------------*
2093 * usbd_xfer_set_frame_data
2095 * This function sets the pointer of the buffer that should
2096 * loaded directly into DMA for the given USB frame. Passing "ptr"
2097 * equal to NULL while the corresponding "frlength" is greater
2098 * than zero gives undefined results!
2099 *------------------------------------------------------------------------*/
2101 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2102 void *ptr, usb_frlength_t len)
2104 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2106 /* set virtual address to load and length */
2107 xfer->frbuffers[frindex].buffer = ptr;
2108 usbd_xfer_set_frame_len(xfer, frindex, len);
2112 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2113 void **ptr, int *len)
2115 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2118 *ptr = xfer->frbuffers[frindex].buffer;
2120 *len = xfer->frlengths[frindex];
2123 /*------------------------------------------------------------------------*
2124 * usbd_xfer_old_frame_length
2126 * This function returns the framelength of the given frame at the
2127 * time the transfer was submitted. This function can be used to
2128 * compute the starting data pointer of the next isochronous frame
2129 * when an isochronous transfer has completed.
2130 *------------------------------------------------------------------------*/
2132 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2134 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2136 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2140 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2144 *actlen = xfer->actlen;
2146 *sumlen = xfer->sumlen;
2147 if (aframes != NULL)
2148 *aframes = xfer->aframes;
2149 if (nframes != NULL)
2150 *nframes = xfer->nframes;
2153 /*------------------------------------------------------------------------*
2154 * usbd_xfer_set_frame_offset
2156 * This function sets the frame data buffer offset relative to the beginning
2157 * of the USB DMA buffer allocated for this USB transfer.
2158 *------------------------------------------------------------------------*/
2160 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2161 usb_frcount_t frindex)
2163 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2164 "when the USB buffer is external\n"));
2165 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2167 /* set virtual address to load */
2168 xfer->frbuffers[frindex].buffer =
2169 USB_ADD_BYTES(xfer->local_buffer, offset);
2173 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2179 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2185 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2191 usbd_xfer_max_frames(struct usb_xfer *xfer)
2193 return (xfer->max_frame_count);
2197 usbd_xfer_max_len(struct usb_xfer *xfer)
2199 return (xfer->max_data_length);
2203 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2205 return (xfer->max_frame_size);
2209 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2212 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2214 xfer->frlengths[frindex] = len;
2217 /*------------------------------------------------------------------------*
2218 * usb_callback_proc - factored out code
2220 * This function performs USB callbacks.
2221 *------------------------------------------------------------------------*/
2223 usb_callback_proc(struct usb_proc_msg *_pm)
2225 struct usb_done_msg *pm = (void *)_pm;
2226 struct usb_xfer_root *info = pm->xroot;
2228 /* Change locking order */
2229 USB_BUS_UNLOCK(info->bus);
2232 * We exploit the fact that the mutex is the same for all
2233 * callbacks that will be called from this thread:
2235 mtx_lock(info->xfer_mtx);
2236 USB_BUS_LOCK(info->bus);
2238 /* Continue where we lost track */
2239 usb_command_wrapper(&info->done_q,
2242 mtx_unlock(info->xfer_mtx);
2245 /*------------------------------------------------------------------------*
2246 * usbd_callback_ss_done_defer
2248 * This function will defer the start, stop and done callback to the
2250 *------------------------------------------------------------------------*/
2252 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2254 struct usb_xfer_root *info = xfer->xroot;
2255 struct usb_xfer_queue *pq = &info->done_q;
2257 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2259 if (pq->curr != xfer) {
2260 usbd_transfer_enqueue(pq, xfer);
2262 if (!pq->recurse_1) {
2265 * We have to postpone the callback due to the fact we
2266 * will have a Lock Order Reversal, LOR, if we try to
2269 if (usb_proc_msignal(info->done_p,
2270 &info->done_m[0], &info->done_m[1])) {
2274 /* clear second recurse flag */
2281 /*------------------------------------------------------------------------*
2282 * usbd_callback_wrapper
2284 * This is a wrapper for USB callbacks. This wrapper does some
2285 * auto-magic things like figuring out if we can call the callback
2286 * directly from the current context or if we need to wakeup the
2287 * interrupt process.
2288 *------------------------------------------------------------------------*/
2290 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2292 struct usb_xfer *xfer = pq->curr;
2293 struct usb_xfer_root *info = xfer->xroot;
2295 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2296 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2298 * Cases that end up here:
2300 * 5) HW interrupt done callback or other source.
2302 DPRINTFN(3, "case 5\n");
2305 * We have to postpone the callback due to the fact we
2306 * will have a Lock Order Reversal, LOR, if we try to
2309 if (usb_proc_msignal(info->done_p,
2310 &info->done_m[0], &info->done_m[1])) {
2316 * Cases that end up here:
2318 * 1) We are starting a transfer
2319 * 2) We are prematurely calling back a transfer
2320 * 3) We are stopping a transfer
2321 * 4) We are doing an ordinary callback
2323 DPRINTFN(3, "case 1-4\n");
2324 /* get next USB transfer in the queue */
2325 info->done_q.curr = NULL;
2327 /* set flag in case of drain */
2328 xfer->flags_int.doing_callback = 1;
2330 USB_BUS_UNLOCK(info->bus);
2331 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2333 /* set correct USB state for callback */
2334 if (!xfer->flags_int.transferring) {
2335 xfer->usb_state = USB_ST_SETUP;
2336 if (!xfer->flags_int.started) {
2337 /* we got stopped before we even got started */
2338 USB_BUS_LOCK(info->bus);
2343 if (usbd_callback_wrapper_sub(xfer)) {
2344 /* the callback has been deferred */
2345 USB_BUS_LOCK(info->bus);
2349 /* decrement power reference */
2350 usbd_transfer_power_ref(xfer, -1);
2352 xfer->flags_int.transferring = 0;
2355 xfer->usb_state = USB_ST_ERROR;
2357 /* set transferred state */
2358 xfer->usb_state = USB_ST_TRANSFERRED;
2360 /* sync DMA memory, if any */
2361 if (xfer->flags_int.bdma_enable &&
2362 (!xfer->flags_int.bdma_no_post_sync)) {
2363 usb_bdma_post_sync(xfer);
2370 if (xfer->usb_state != USB_ST_SETUP) {
2371 USB_BUS_LOCK(info->bus);
2372 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2373 USB_BUS_UNLOCK(info->bus);
2376 /* call processing routine */
2377 (xfer->callback) (xfer, xfer->error);
2379 /* pickup the USB mutex again */
2380 USB_BUS_LOCK(info->bus);
2383 * Check if we got started after that we got cancelled, but
2384 * before we managed to do the callback.
2386 if ((!xfer->flags_int.open) &&
2387 (xfer->flags_int.started) &&
2388 (xfer->usb_state == USB_ST_ERROR)) {
2389 /* clear flag in case of drain */
2390 xfer->flags_int.doing_callback = 0;
2391 /* try to loop, but not recursivly */
2392 usb_command_wrapper(&info->done_q, xfer);
2397 /* clear flag in case of drain */
2398 xfer->flags_int.doing_callback = 0;
2401 * Check if we are draining.
2403 if (xfer->flags_int.draining &&
2404 (!xfer->flags_int.transferring)) {
2405 /* "usbd_transfer_drain()" is waiting for end of transfer */
2406 xfer->flags_int.draining = 0;
2407 cv_broadcast(&info->cv_drain);
2410 /* do the next callback, if any */
2411 usb_command_wrapper(&info->done_q,
2415 /*------------------------------------------------------------------------*
2416 * usb_dma_delay_done_cb
2418 * This function is called when the DMA delay has been exectuded, and
2419 * will make sure that the callback is called to complete the USB
2420 * transfer. This code path is ususally only used when there is an USB
2421 * error like USB_ERR_CANCELLED.
2422 *------------------------------------------------------------------------*/
2424 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2426 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2428 DPRINTFN(3, "Completed %p\n", xfer);
2430 /* queue callback for execution, again */
2431 usbd_transfer_done(xfer, 0);
2434 /*------------------------------------------------------------------------*
2435 * usbd_transfer_dequeue
2437 * - This function is used to remove an USB transfer from a USB
2440 * - This function can be called multiple times in a row.
2441 *------------------------------------------------------------------------*/
2443 usbd_transfer_dequeue(struct usb_xfer *xfer)
2445 struct usb_xfer_queue *pq;
2447 pq = xfer->wait_queue;
2449 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2450 xfer->wait_queue = NULL;
2454 /*------------------------------------------------------------------------*
2455 * usbd_transfer_enqueue
2457 * - This function is used to insert an USB transfer into a USB *
2460 * - This function can be called multiple times in a row.
2461 *------------------------------------------------------------------------*/
2463 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2466 * Insert the USB transfer into the queue, if it is not
2467 * already on a USB transfer queue:
2469 if (xfer->wait_queue == NULL) {
2470 xfer->wait_queue = pq;
2471 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2475 /*------------------------------------------------------------------------*
2476 * usbd_transfer_done
2478 * - This function is used to remove an USB transfer from the busdma,
2479 * pipe or interrupt queue.
2481 * - This function is used to queue the USB transfer on the done
2484 * - This function is used to stop any USB transfer timeouts.
2485 *------------------------------------------------------------------------*/
2487 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2489 struct usb_xfer_root *info = xfer->xroot;
2491 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2493 DPRINTF("err=%s\n", usbd_errstr(error));
2496 * If we are not transferring then just return.
2497 * This can happen during transfer cancel.
2499 if (!xfer->flags_int.transferring) {
2500 DPRINTF("not transferring\n");
2501 /* end of control transfer, if any */
2502 xfer->flags_int.control_act = 0;
2505 /* only set transfer error, if not already set */
2506 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2507 xfer->error = error;
2509 /* stop any callouts */
2510 usb_callout_stop(&xfer->timeout_handle);
2513 * If we are waiting on a queue, just remove the USB transfer
2514 * from the queue, if any. We should have the required locks
2515 * locked to do the remove when this function is called.
2517 usbd_transfer_dequeue(xfer);
2520 if (mtx_owned(info->xfer_mtx)) {
2521 struct usb_xfer_queue *pq;
2524 * If the private USB lock is not locked, then we assume
2525 * that the BUS-DMA load stage has been passed:
2529 if (pq->curr == xfer) {
2530 /* start the next BUS-DMA load, if any */
2531 usb_command_wrapper(pq, NULL);
2535 /* keep some statistics */
2537 info->bus->stats_err.uds_requests
2538 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2540 info->bus->stats_ok.uds_requests
2541 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2544 /* call the USB transfer callback */
2545 usbd_callback_ss_done_defer(xfer);
2548 /*------------------------------------------------------------------------*
2549 * usbd_transfer_start_cb
2551 * This function is called to start the USB transfer when
2552 * "xfer->interval" is greater than zero, and and the endpoint type is
2554 *------------------------------------------------------------------------*/
2556 usbd_transfer_start_cb(void *arg)
2558 struct usb_xfer *xfer = arg;
2559 struct usb_endpoint *ep = xfer->endpoint;
2561 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2566 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2569 /* the transfer can now be cancelled */
2570 xfer->flags_int.can_cancel_immed = 1;
2572 /* start USB transfer, if no error */
2573 if (xfer->error == 0)
2574 (ep->methods->start) (xfer);
2576 /* check for transfer error */
2578 /* some error has happened */
2579 usbd_transfer_done(xfer, 0);
2583 /*------------------------------------------------------------------------*
2584 * usbd_xfer_set_stall
2586 * This function is used to set the stall flag outside the
2587 * callback. This function is NULL safe.
2588 *------------------------------------------------------------------------*/
2590 usbd_xfer_set_stall(struct usb_xfer *xfer)
2596 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2598 /* avoid any races by locking the USB mutex */
2599 USB_BUS_LOCK(xfer->xroot->bus);
2600 xfer->flags.stall_pipe = 1;
2601 USB_BUS_UNLOCK(xfer->xroot->bus);
2605 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2607 return (xfer->endpoint->is_stalled);
2610 /*------------------------------------------------------------------------*
2611 * usbd_transfer_clear_stall
2613 * This function is used to clear the stall flag outside the
2614 * callback. This function is NULL safe.
2615 *------------------------------------------------------------------------*/
2617 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2623 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2625 /* avoid any races by locking the USB mutex */
2626 USB_BUS_LOCK(xfer->xroot->bus);
2628 xfer->flags.stall_pipe = 0;
2630 USB_BUS_UNLOCK(xfer->xroot->bus);
2633 /*------------------------------------------------------------------------*
2636 * This function is used to add an USB transfer to the pipe transfer list.
2637 *------------------------------------------------------------------------*/
2639 usbd_pipe_start(struct usb_xfer_queue *pq)
2641 struct usb_endpoint *ep;
2642 struct usb_xfer *xfer;
2646 ep = xfer->endpoint;
2648 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2651 * If the endpoint is already stalled we do nothing !
2653 if (ep->is_stalled) {
2657 * Check if we are supposed to stall the endpoint:
2659 if (xfer->flags.stall_pipe) {
2660 struct usb_device *udev;
2661 struct usb_xfer_root *info;
2663 /* clear stall command */
2664 xfer->flags.stall_pipe = 0;
2666 /* get pointer to USB device */
2671 * Only stall BULK and INTERRUPT endpoints.
2673 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2674 if ((type == UE_BULK) ||
2675 (type == UE_INTERRUPT)) {
2680 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2681 (udev->bus->methods->set_stall) (
2682 udev, NULL, ep, &did_stall);
2683 } else if (udev->ctrl_xfer[1]) {
2684 info = udev->ctrl_xfer[1]->xroot;
2686 &info->bus->non_giant_callback_proc,
2687 &udev->cs_msg[0], &udev->cs_msg[1]);
2689 /* should not happen */
2690 DPRINTFN(0, "No stall handler\n");
2693 * Check if we should stall. Some USB hardware
2694 * handles set- and clear-stall in hardware.
2698 * The transfer will be continued when
2699 * the clear-stall control endpoint
2700 * message is received.
2705 } else if (type == UE_ISOCHRONOUS) {
2708 * Make sure any FIFO overflow or other FIFO
2709 * error conditions go away by resetting the
2710 * endpoint FIFO through the clear stall
2713 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2714 (udev->bus->methods->clear_stall) (udev, ep);
2718 /* Set or clear stall complete - special case */
2719 if (xfer->nframes == 0) {
2720 /* we are complete */
2722 usbd_transfer_done(xfer, 0);
2728 * 1) Start the first transfer queued.
2730 * 2) Re-start the current USB transfer.
2733 * Check if there should be any
2734 * pre transfer start delay:
2736 if (xfer->interval > 0) {
2737 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2738 if ((type == UE_BULK) ||
2739 (type == UE_CONTROL)) {
2740 usbd_transfer_timeout_ms(xfer,
2741 &usbd_transfer_start_cb,
2749 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2751 /* the transfer can now be cancelled */
2752 xfer->flags_int.can_cancel_immed = 1;
2754 /* start USB transfer, if no error */
2755 if (xfer->error == 0)
2756 (ep->methods->start) (xfer);
2758 /* check for transfer error */
2760 /* some error has happened */
2761 usbd_transfer_done(xfer, 0);
2765 /*------------------------------------------------------------------------*
2766 * usbd_transfer_timeout_ms
2768 * This function is used to setup a timeout on the given USB
2769 * transfer. If the timeout has been deferred the callback given by
2770 * "cb" will get called after "ms" milliseconds.
2771 *------------------------------------------------------------------------*/
2773 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2774 void (*cb) (void *arg), usb_timeout_t ms)
2776 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2779 usb_callout_reset(&xfer->timeout_handle,
2780 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2783 /*------------------------------------------------------------------------*
2784 * usbd_callback_wrapper_sub
2786 * - This function will update variables in an USB transfer after
2787 * that the USB transfer is complete.
2789 * - This function is used to start the next USB transfer on the
2790 * ep transfer queue, if any.
2792 * NOTE: In some special cases the USB transfer will not be removed from
2793 * the pipe queue, but remain first. To enforce USB transfer removal call
2794 * this function passing the error code "USB_ERR_CANCELLED".
2798 * Else: The callback has been deferred.
2799 *------------------------------------------------------------------------*/
2801 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2803 struct usb_endpoint *ep;
2804 struct usb_bus *bus;
2807 bus = xfer->xroot->bus;
2809 if ((!xfer->flags_int.open) &&
2810 (!xfer->flags_int.did_close)) {
2813 (xfer->endpoint->methods->close) (xfer);
2814 USB_BUS_UNLOCK(bus);
2815 /* only close once */
2816 xfer->flags_int.did_close = 1;
2817 return (1); /* wait for new callback */
2820 * If we have a non-hardware induced error we
2821 * need to do the DMA delay!
2823 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2824 (xfer->error == USB_ERR_CANCELLED ||
2825 xfer->error == USB_ERR_TIMEOUT ||
2826 bus->methods->start_dma_delay != NULL)) {
2830 /* only delay once */
2831 xfer->flags_int.did_dma_delay = 1;
2833 /* we can not cancel this delay */
2834 xfer->flags_int.can_cancel_immed = 0;
2836 temp = usbd_get_dma_delay(xfer->xroot->udev);
2838 DPRINTFN(3, "DMA delay, %u ms, "
2839 "on %p\n", temp, xfer);
2844 * Some hardware solutions have dedicated
2845 * events when it is safe to free DMA'ed
2846 * memory. For the other hardware platforms we
2847 * use a static delay.
2849 if (bus->methods->start_dma_delay != NULL) {
2850 (bus->methods->start_dma_delay) (xfer);
2852 usbd_transfer_timeout_ms(xfer,
2853 (void (*)(void *))&usb_dma_delay_done_cb,
2856 USB_BUS_UNLOCK(bus);
2857 return (1); /* wait for new callback */
2860 /* check actual number of frames */
2861 if (xfer->aframes > xfer->nframes) {
2862 if (xfer->error == 0) {
2863 panic("%s: actual number of frames, %d, is "
2864 "greater than initial number of frames, %d\n",
2865 __FUNCTION__, xfer->aframes, xfer->nframes);
2867 /* just set some valid value */
2868 xfer->aframes = xfer->nframes;
2871 /* compute actual length */
2874 for (x = 0; x != xfer->aframes; x++) {
2875 xfer->actlen += xfer->frlengths[x];
2879 * Frames that were not transferred get zero actual length in
2880 * case the USB device driver does not check the actual number
2881 * of frames transferred, "xfer->aframes":
2883 for (; x < xfer->nframes; x++) {
2884 usbd_xfer_set_frame_len(xfer, x, 0);
2887 /* check actual length */
2888 if (xfer->actlen > xfer->sumlen) {
2889 if (xfer->error == 0) {
2890 panic("%s: actual length, %d, is greater than "
2891 "initial length, %d\n",
2892 __FUNCTION__, xfer->actlen, xfer->sumlen);
2894 /* just set some valid value */
2895 xfer->actlen = xfer->sumlen;
2898 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2899 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2900 xfer->aframes, xfer->nframes);
2903 /* end of control transfer, if any */
2904 xfer->flags_int.control_act = 0;
2906 #if USB_HAVE_TT_SUPPORT
2907 switch (xfer->error) {
2908 case USB_ERR_NORMAL_COMPLETION:
2909 case USB_ERR_SHORT_XFER:
2910 case USB_ERR_STALLED:
2911 case USB_ERR_CANCELLED:
2915 /* try to reset the TT, if any */
2917 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2918 USB_BUS_UNLOCK(bus);
2922 /* check if we should block the execution queue */
2923 if ((xfer->error != USB_ERR_CANCELLED) &&
2924 (xfer->flags.pipe_bof)) {
2925 DPRINTFN(2, "xfer=%p: Block On Failure "
2926 "on endpoint=%p\n", xfer, xfer->endpoint);
2930 /* check for short transfers */
2931 if (xfer->actlen < xfer->sumlen) {
2933 /* end of control transfer, if any */
2934 xfer->flags_int.control_act = 0;
2936 if (!xfer->flags_int.short_xfer_ok) {
2937 xfer->error = USB_ERR_SHORT_XFER;
2938 if (xfer->flags.pipe_bof) {
2939 DPRINTFN(2, "xfer=%p: Block On Failure on "
2940 "Short Transfer on endpoint %p.\n",
2941 xfer, xfer->endpoint);
2947 * Check if we are in the middle of a
2950 if (xfer->flags_int.control_act) {
2951 DPRINTFN(5, "xfer=%p: Control transfer "
2952 "active on endpoint=%p\n", xfer, xfer->endpoint);
2958 ep = xfer->endpoint;
2961 * If the current USB transfer is completing we need to start the
2965 if (ep->endpoint_q.curr == xfer) {
2966 usb_command_wrapper(&ep->endpoint_q, NULL);
2968 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2969 /* there is another USB transfer waiting */
2971 /* this is the last USB transfer */
2972 /* clear isochronous sync flag */
2973 xfer->endpoint->is_synced = 0;
2976 USB_BUS_UNLOCK(bus);
2981 /*------------------------------------------------------------------------*
2982 * usb_command_wrapper
2984 * This function is used to execute commands non-recursivly on an USB
2986 *------------------------------------------------------------------------*/
2988 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2992 * If the transfer is not already processing,
2995 if (pq->curr != xfer) {
2996 usbd_transfer_enqueue(pq, xfer);
2997 if (pq->curr != NULL) {
2998 /* something is already processing */
2999 DPRINTFN(6, "busy %p\n", pq->curr);
3004 /* Get next element in queue */
3008 if (!pq->recurse_1) {
3012 /* set both recurse flags */
3016 if (pq->curr == NULL) {
3017 xfer = TAILQ_FIRST(&pq->head);
3019 TAILQ_REMOVE(&pq->head, xfer,
3021 xfer->wait_queue = NULL;
3027 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3029 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3031 } while (!pq->recurse_2);
3033 /* clear first recurse flag */
3037 /* clear second recurse flag */
3042 /*------------------------------------------------------------------------*
3043 * usbd_ctrl_transfer_setup
3045 * This function is used to setup the default USB control endpoint
3047 *------------------------------------------------------------------------*/
3049 usbd_ctrl_transfer_setup(struct usb_device *udev)
3051 struct usb_xfer *xfer;
3053 uint8_t iface_index;
3055 /* check for root HUB */
3056 if (udev->parent_hub == NULL)
3060 xfer = udev->ctrl_xfer[0];
3062 USB_XFER_LOCK(xfer);
3064 ((xfer->address == udev->address) &&
3065 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3066 udev->ddesc.bMaxPacketSize));
3067 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3070 * NOTE: checking "xfer->address" and
3071 * starting the USB transfer must be
3074 usbd_transfer_start(xfer);
3077 USB_XFER_UNLOCK(xfer);
3084 * All parameters are exactly the same like before.
3090 * Update wMaxPacketSize for the default control endpoint:
3092 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3093 udev->ddesc.bMaxPacketSize;
3096 * Unsetup any existing USB transfer:
3098 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3101 * Reset clear stall error counter.
3103 udev->clear_stall_errors = 0;
3106 * Try to setup a new USB transfer for the
3107 * default control endpoint:
3110 if (usbd_transfer_setup(udev, &iface_index,
3111 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3112 &udev->device_mtx)) {
3113 DPRINTFN(0, "could not setup default "
3120 /*------------------------------------------------------------------------*
3121 * usbd_clear_data_toggle - factored out code
3123 * NOTE: the intention of this function is not to reset the hardware
3125 *------------------------------------------------------------------------*/
3127 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3129 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3131 /* check that we have a valid case */
3132 if (udev->flags.usb_mode == USB_MODE_HOST &&
3133 udev->parent_hub != NULL &&
3134 udev->bus->methods->clear_stall != NULL &&
3135 ep->methods != NULL) {
3136 (udev->bus->methods->clear_stall) (udev, ep);
3140 /*------------------------------------------------------------------------*
3141 * usbd_clear_data_toggle - factored out code
3143 * NOTE: the intention of this function is not to reset the hardware
3144 * data toggle on the USB device side.
3145 *------------------------------------------------------------------------*/
3147 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3149 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3151 USB_BUS_LOCK(udev->bus);
3152 ep->toggle_next = 0;
3153 /* some hardware needs a callback to clear the data toggle */
3154 usbd_clear_stall_locked(udev, ep);
3155 USB_BUS_UNLOCK(udev->bus);
3158 /*------------------------------------------------------------------------*
3159 * usbd_clear_stall_callback - factored out clear stall callback
3162 * xfer1: Clear Stall Control Transfer
3163 * xfer2: Stalled USB Transfer
3165 * This function is NULL safe.
3171 * Clear stall config example:
3173 * static const struct usb_config my_clearstall = {
3174 * .type = UE_CONTROL,
3176 * .direction = UE_DIR_ANY,
3177 * .interval = 50, //50 milliseconds
3178 * .bufsize = sizeof(struct usb_device_request),
3179 * .timeout = 1000, //1.000 seconds
3180 * .callback = &my_clear_stall_callback, // **
3181 * .usb_mode = USB_MODE_HOST,
3184 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3185 * passing the correct parameters.
3186 *------------------------------------------------------------------------*/
3188 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3189 struct usb_xfer *xfer2)
3191 struct usb_device_request req;
3193 if (xfer2 == NULL) {
3194 /* looks like we are tearing down */
3195 DPRINTF("NULL input parameter\n");
3198 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3199 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3201 switch (USB_GET_STATE(xfer1)) {
3205 * pre-clear the data toggle to DATA0 ("umass.c" and
3206 * "ata-usb.c" depends on this)
3209 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3211 /* setup a clear-stall packet */
3213 req.bmRequestType = UT_WRITE_ENDPOINT;
3214 req.bRequest = UR_CLEAR_FEATURE;
3215 USETW(req.wValue, UF_ENDPOINT_HALT);
3216 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3218 USETW(req.wLength, 0);
3221 * "usbd_transfer_setup_sub()" will ensure that
3222 * we have sufficient room in the buffer for
3223 * the request structure!
3226 /* copy in the transfer */
3228 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3231 xfer1->frlengths[0] = sizeof(req);
3234 usbd_transfer_submit(xfer1);
3237 case USB_ST_TRANSFERRED:
3240 default: /* Error */
3241 if (xfer1->error == USB_ERR_CANCELLED) {
3246 return (1); /* Clear Stall Finished */
3249 /*------------------------------------------------------------------------*
3250 * usbd_transfer_poll
3252 * The following function gets called from the USB keyboard driver and
3253 * UMASS when the system has paniced.
3255 * NOTE: It is currently not possible to resume normal operation on
3256 * the USB controller which has been polled, due to clearing of the
3257 * "up_dsleep" and "up_msleep" flags.
3258 *------------------------------------------------------------------------*/
3260 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3262 struct usb_xfer *xfer;
3263 struct usb_xfer_root *xroot;
3264 struct usb_device *udev;
3265 struct usb_proc_msg *pm;
3270 for (n = 0; n != max; n++) {
3271 /* Extra checks to avoid panic */
3274 continue; /* no USB transfer */
3275 xroot = xfer->xroot;
3277 continue; /* no USB root */
3280 continue; /* no USB device */
3281 if (udev->bus == NULL)
3282 continue; /* no BUS structure */
3283 if (udev->bus->methods == NULL)
3284 continue; /* no BUS methods */
3285 if (udev->bus->methods->xfer_poll == NULL)
3286 continue; /* no poll method */
3288 /* make sure that the BUS mutex is not locked */
3290 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3291 mtx_unlock(&xroot->udev->bus->bus_mtx);
3295 /* make sure that the transfer mutex is not locked */
3297 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3298 mtx_unlock(xroot->xfer_mtx);
3302 /* Make sure cv_signal() and cv_broadcast() is not called */
3303 udev->bus->control_xfer_proc.up_msleep = 0;
3304 udev->bus->explore_proc.up_msleep = 0;
3305 udev->bus->giant_callback_proc.up_msleep = 0;
3306 udev->bus->non_giant_callback_proc.up_msleep = 0;
3308 /* poll USB hardware */
3309 (udev->bus->methods->xfer_poll) (udev->bus);
3311 USB_BUS_LOCK(xroot->bus);
3313 /* check for clear stall */
3314 if (udev->ctrl_xfer[1] != NULL) {
3316 /* poll clear stall start */
3317 pm = &udev->cs_msg[0].hdr;
3318 (pm->pm_callback) (pm);
3319 /* poll clear stall done thread */
3320 pm = &udev->ctrl_xfer[1]->
3321 xroot->done_m[0].hdr;
3322 (pm->pm_callback) (pm);
3325 /* poll done thread */
3326 pm = &xroot->done_m[0].hdr;
3327 (pm->pm_callback) (pm);
3329 USB_BUS_UNLOCK(xroot->bus);
3331 /* restore transfer mutex */
3333 mtx_lock(xroot->xfer_mtx);
3335 /* restore BUS mutex */
3337 mtx_lock(&xroot->udev->bus->bus_mtx);
3342 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3343 uint8_t type, enum usb_dev_speed speed)
3345 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3346 [USB_SPEED_LOW] = 8,
3347 [USB_SPEED_FULL] = 64,
3348 [USB_SPEED_HIGH] = 1024,
3349 [USB_SPEED_VARIABLE] = 1024,
3350 [USB_SPEED_SUPER] = 1024,
3353 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3354 [USB_SPEED_LOW] = 0, /* invalid */
3355 [USB_SPEED_FULL] = 1023,
3356 [USB_SPEED_HIGH] = 1024,
3357 [USB_SPEED_VARIABLE] = 3584,
3358 [USB_SPEED_SUPER] = 1024,
3361 static const uint16_t control_min[USB_SPEED_MAX] = {
3362 [USB_SPEED_LOW] = 8,
3363 [USB_SPEED_FULL] = 8,
3364 [USB_SPEED_HIGH] = 64,
3365 [USB_SPEED_VARIABLE] = 512,
3366 [USB_SPEED_SUPER] = 512,
3369 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3370 [USB_SPEED_LOW] = 8,
3371 [USB_SPEED_FULL] = 8,
3372 [USB_SPEED_HIGH] = 512,
3373 [USB_SPEED_VARIABLE] = 512,
3374 [USB_SPEED_SUPER] = 1024,
3379 memset(ptr, 0, sizeof(*ptr));
3383 ptr->range.max = intr_range_max[speed];
3385 case UE_ISOCHRONOUS:
3386 ptr->range.max = isoc_range_max[speed];
3389 if (type == UE_BULK)
3390 temp = bulk_min[speed];
3391 else /* UE_CONTROL */
3392 temp = control_min[speed];
3394 /* default is fixed */
3395 ptr->fixed[0] = temp;
3396 ptr->fixed[1] = temp;
3397 ptr->fixed[2] = temp;
3398 ptr->fixed[3] = temp;
3400 if (speed == USB_SPEED_FULL) {
3401 /* multiple sizes */
3406 if ((speed == USB_SPEED_VARIABLE) &&
3407 (type == UE_BULK)) {
3408 /* multiple sizes */
3409 ptr->fixed[2] = 1024;
3410 ptr->fixed[3] = 1536;
3417 usbd_xfer_softc(struct usb_xfer *xfer)
3419 return (xfer->priv_sc);
3423 usbd_xfer_get_priv(struct usb_xfer *xfer)
3425 return (xfer->priv_fifo);
3429 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3431 xfer->priv_fifo = ptr;
3435 usbd_xfer_state(struct usb_xfer *xfer)
3437 return (xfer->usb_state);
3441 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3444 case USB_FORCE_SHORT_XFER:
3445 xfer->flags.force_short_xfer = 1;
3447 case USB_SHORT_XFER_OK:
3448 xfer->flags.short_xfer_ok = 1;
3450 case USB_MULTI_SHORT_OK:
3451 xfer->flags.short_frames_ok = 1;
3453 case USB_MANUAL_STATUS:
3454 xfer->flags.manual_status = 1;
3460 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3463 case USB_FORCE_SHORT_XFER:
3464 xfer->flags.force_short_xfer = 0;
3466 case USB_SHORT_XFER_OK:
3467 xfer->flags.short_xfer_ok = 0;
3469 case USB_MULTI_SHORT_OK:
3470 xfer->flags.short_frames_ok = 0;
3472 case USB_MANUAL_STATUS:
3473 xfer->flags.manual_status = 0;
3479 * The following function returns in milliseconds when the isochronous
3480 * transfer was completed by the hardware. The returned value wraps
3481 * around 65536 milliseconds.
3484 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3486 return (xfer->isoc_time_complete);
3490 * The following function returns non-zero if the max packet size
3491 * field was clamped to a valid value. Else it returns zero.
3494 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3496 return (xfer->flags_int.maxp_was_clamped);