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 = (ecomp->bmAttributes & 3) + 1;
361 max_packet_count *= mult;
367 max_packet_size &= 0x7FF;
372 return (max_packet_size * max_packet_count);
375 /*------------------------------------------------------------------------*
376 * usbd_transfer_setup_sub - transfer setup subroutine
378 * This function must be called from the "xfer_setup" callback of the
379 * USB Host or Device controller driver when setting up an USB
380 * transfer. This function will setup correct packet sizes, buffer
381 * sizes, flags and more, that are stored in the "usb_xfer"
383 *------------------------------------------------------------------------*/
385 usbd_transfer_setup_sub(struct usb_setup_params *parm)
391 struct usb_xfer *xfer = parm->curr_xfer;
392 const struct usb_config *setup = parm->curr_setup;
393 struct usb_endpoint_ss_comp_descriptor *ecomp;
394 struct usb_endpoint_descriptor *edesc;
395 struct usb_std_packet_size std_size;
396 usb_frcount_t n_frlengths;
397 usb_frcount_t n_frbuffers;
404 * Sanity check. The following parameters must be initialized before
405 * calling this function.
407 if ((parm->hc_max_packet_size == 0) ||
408 (parm->hc_max_packet_count == 0) ||
409 (parm->hc_max_frame_size == 0)) {
410 parm->err = USB_ERR_INVAL;
413 edesc = xfer->endpoint->edesc;
414 ecomp = xfer->endpoint->ecomp;
416 type = (edesc->bmAttributes & UE_XFERTYPE);
418 xfer->flags = setup->flags;
419 xfer->nframes = setup->frames;
420 xfer->timeout = setup->timeout;
421 xfer->callback = setup->callback;
422 xfer->interval = setup->interval;
423 xfer->endpointno = edesc->bEndpointAddress;
424 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
425 xfer->max_packet_count = 1;
426 /* make a shadow copy: */
427 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
429 parm->bufsize = setup->bufsize;
431 switch (parm->speed) {
436 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
438 /* check for invalid max packet count */
439 if (xfer->max_packet_count > 3)
440 xfer->max_packet_count = 3;
445 xfer->max_packet_size &= 0x7FF;
447 case USB_SPEED_SUPER:
448 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
451 xfer->max_packet_count += ecomp->bMaxBurst;
453 if ((xfer->max_packet_count == 0) ||
454 (xfer->max_packet_count > 16))
455 xfer->max_packet_count = 16;
459 xfer->max_packet_count = 1;
465 mult = (ecomp->bmAttributes & 3) + 1;
469 xfer->max_packet_count *= mult;
475 xfer->max_packet_size &= 0x7FF;
480 /* range check "max_packet_count" */
482 if (xfer->max_packet_count > parm->hc_max_packet_count) {
483 xfer->max_packet_count = parm->hc_max_packet_count;
486 /* store max packet size value before filtering */
488 maxp_old = xfer->max_packet_size;
490 /* filter "wMaxPacketSize" according to HC capabilities */
492 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
493 (xfer->max_packet_size == 0)) {
494 xfer->max_packet_size = parm->hc_max_packet_size;
496 /* filter "wMaxPacketSize" according to standard sizes */
498 usbd_get_std_packet_size(&std_size, type, parm->speed);
500 if (std_size.range.min || std_size.range.max) {
502 if (xfer->max_packet_size < std_size.range.min) {
503 xfer->max_packet_size = std_size.range.min;
505 if (xfer->max_packet_size > std_size.range.max) {
506 xfer->max_packet_size = std_size.range.max;
510 if (xfer->max_packet_size >= std_size.fixed[3]) {
511 xfer->max_packet_size = std_size.fixed[3];
512 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
513 xfer->max_packet_size = std_size.fixed[2];
514 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
515 xfer->max_packet_size = std_size.fixed[1];
517 /* only one possibility left */
518 xfer->max_packet_size = std_size.fixed[0];
523 * Check if the max packet size was outside its allowed range
524 * and clamped to a valid value:
526 if (maxp_old != xfer->max_packet_size)
527 xfer->flags_int.maxp_was_clamped = 1;
529 /* compute "max_frame_size" */
531 usbd_update_max_frame_size(xfer);
533 /* check interrupt interval and transfer pre-delay */
535 if (type == UE_ISOCHRONOUS) {
537 uint16_t frame_limit;
539 xfer->interval = 0; /* not used, must be zero */
540 xfer->flags_int.isochronous_xfr = 1; /* set flag */
542 if (xfer->timeout == 0) {
544 * set a default timeout in
545 * case something goes wrong!
547 xfer->timeout = 1000 / 4;
549 switch (parm->speed) {
552 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
556 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
557 xfer->fps_shift = edesc->bInterval;
558 if (xfer->fps_shift > 0)
560 if (xfer->fps_shift > 3)
562 if (xfer->flags.pre_scale_frames != 0)
563 xfer->nframes <<= (3 - xfer->fps_shift);
567 if (xfer->nframes > frame_limit) {
569 * this is not going to work
572 parm->err = USB_ERR_INVAL;
575 if (xfer->nframes == 0) {
577 * this is not a valid value
579 parm->err = USB_ERR_ZERO_NFRAMES;
585 * If a value is specified use that else check the
586 * endpoint descriptor!
588 if (type == UE_INTERRUPT) {
592 if (xfer->interval == 0) {
594 xfer->interval = edesc->bInterval;
596 switch (parm->speed) {
602 if (xfer->interval < 4)
604 else if (xfer->interval > 16)
605 xfer->interval = (1 << (16 - 4));
608 (1 << (xfer->interval - 4));
613 if (xfer->interval == 0) {
615 * One millisecond is the smallest
616 * interval we support:
624 while ((temp != 0) && (temp < xfer->interval)) {
629 switch (parm->speed) {
634 xfer->fps_shift += 3;
641 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
642 * to be equal to zero when setting up USB transfers, hence
643 * this leads to alot of extra code in the USB kernel.
646 if ((xfer->max_frame_size == 0) ||
647 (xfer->max_packet_size == 0)) {
651 if ((parm->bufsize <= MIN_PKT) &&
652 (type != UE_CONTROL) &&
656 xfer->max_packet_size = MIN_PKT;
657 xfer->max_packet_count = 1;
658 parm->bufsize = 0; /* automatic setup length */
659 usbd_update_max_frame_size(xfer);
662 parm->err = USB_ERR_ZERO_MAXP;
671 * check if we should setup a default
675 if (parm->bufsize == 0) {
677 parm->bufsize = xfer->max_frame_size;
679 if (type == UE_ISOCHRONOUS) {
680 parm->bufsize *= xfer->nframes;
684 * check if we are about to setup a proxy
688 if (xfer->flags.proxy_buffer) {
690 /* round bufsize up */
692 parm->bufsize += (xfer->max_frame_size - 1);
694 if (parm->bufsize < xfer->max_frame_size) {
695 /* length wrapped around */
696 parm->err = USB_ERR_INVAL;
699 /* subtract remainder */
701 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
703 /* add length of USB device request structure, if any */
705 if (type == UE_CONTROL) {
706 parm->bufsize += REQ_SIZE; /* SETUP message */
709 xfer->max_data_length = parm->bufsize;
711 /* Setup "n_frlengths" and "n_frbuffers" */
713 if (type == UE_ISOCHRONOUS) {
714 n_frlengths = xfer->nframes;
718 if (type == UE_CONTROL) {
719 xfer->flags_int.control_xfr = 1;
720 if (xfer->nframes == 0) {
721 if (parm->bufsize <= REQ_SIZE) {
723 * there will never be any data
732 if (xfer->nframes == 0) {
737 n_frlengths = xfer->nframes;
738 n_frbuffers = xfer->nframes;
742 * check if we have room for the
743 * USB device request structure:
746 if (type == UE_CONTROL) {
748 if (xfer->max_data_length < REQ_SIZE) {
749 /* length wrapped around or too small bufsize */
750 parm->err = USB_ERR_INVAL;
753 xfer->max_data_length -= REQ_SIZE;
756 * Setup "frlengths" and shadow "frlengths" for keeping the
757 * initial frame lengths when a USB transfer is complete. This
758 * information is useful when computing isochronous offsets.
760 xfer->frlengths = parm->xfer_length_ptr;
761 parm->xfer_length_ptr += 2 * n_frlengths;
763 /* setup "frbuffers" */
764 xfer->frbuffers = parm->xfer_page_cache_ptr;
765 parm->xfer_page_cache_ptr += n_frbuffers;
767 /* initialize max frame count */
768 xfer->max_frame_count = xfer->nframes;
771 * check if we need to setup
775 if (!xfer->flags.ext_buffer) {
778 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
783 USB_ADD_BYTES(parm->buf, parm->size[0]);
785 usbd_xfer_set_frame_offset(xfer, 0, 0);
787 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
788 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
791 parm->size[0] += parm->bufsize;
793 /* align data again */
794 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
797 * Compute maximum buffer size
800 if (parm->bufsize_max < parm->bufsize) {
801 parm->bufsize_max = parm->bufsize;
804 if (xfer->flags_int.bdma_enable) {
806 * Setup "dma_page_ptr".
808 * Proof for formula below:
810 * Assume there are three USB frames having length "a", "b" and
811 * "c". These USB frames will at maximum need "z"
812 * "usb_page" structures. "z" is given by:
814 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
815 * ((c / USB_PAGE_SIZE) + 2);
817 * Constraining "a", "b" and "c" like this:
819 * (a + b + c) <= parm->bufsize
823 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
825 * Here is the general formula:
827 xfer->dma_page_ptr = parm->dma_page_ptr;
828 parm->dma_page_ptr += (2 * n_frbuffers);
829 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
833 /* correct maximum data length */
834 xfer->max_data_length = 0;
836 /* subtract USB frame remainder from "hc_max_frame_size" */
838 xfer->max_hc_frame_size =
839 (parm->hc_max_frame_size -
840 (parm->hc_max_frame_size % xfer->max_frame_size));
842 if (xfer->max_hc_frame_size == 0) {
843 parm->err = USB_ERR_INVAL;
847 /* initialize frame buffers */
850 for (x = 0; x != n_frbuffers; x++) {
851 xfer->frbuffers[x].tag_parent =
852 &xfer->xroot->dma_parent_tag;
854 if (xfer->flags_int.bdma_enable &&
855 (parm->bufsize_max > 0)) {
857 if (usb_pc_dmamap_create(
859 parm->bufsize_max)) {
860 parm->err = USB_ERR_NOMEM;
870 * Set some dummy values so that we avoid division by zero:
872 xfer->max_hc_frame_size = 1;
873 xfer->max_frame_size = 1;
874 xfer->max_packet_size = 1;
875 xfer->max_data_length = 0;
877 xfer->max_frame_count = 0;
881 /*------------------------------------------------------------------------*
882 * usbd_transfer_setup - setup an array of USB transfers
884 * NOTE: You must always call "usbd_transfer_unsetup" after calling
885 * "usbd_transfer_setup" if success was returned.
887 * The idea is that the USB device driver should pre-allocate all its
888 * transfers by one call to this function.
893 *------------------------------------------------------------------------*/
895 usbd_transfer_setup(struct usb_device *udev,
896 const uint8_t *ifaces, struct usb_xfer **ppxfer,
897 const struct usb_config *setup_start, uint16_t n_setup,
898 void *priv_sc, struct mtx *xfer_mtx)
900 const struct usb_config *setup_end = setup_start + n_setup;
901 const struct usb_config *setup;
902 struct usb_setup_params *parm;
903 struct usb_endpoint *ep;
904 struct usb_xfer_root *info;
905 struct usb_xfer *xfer;
907 usb_error_t error = 0;
912 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
913 "usbd_transfer_setup can sleep!");
915 /* do some checking first */
918 DPRINTFN(6, "setup array has zero length!\n");
919 return (USB_ERR_INVAL);
922 DPRINTFN(6, "ifaces array is NULL!\n");
923 return (USB_ERR_INVAL);
925 if (xfer_mtx == NULL) {
926 DPRINTFN(6, "using global lock\n");
930 /* more sanity checks */
932 for (setup = setup_start, n = 0;
933 setup != setup_end; setup++, n++) {
934 if (setup->bufsize == (usb_frlength_t)-1) {
935 error = USB_ERR_BAD_BUFSIZE;
936 DPRINTF("invalid bufsize\n");
938 if (setup->callback == NULL) {
939 error = USB_ERR_NO_CALLBACK;
940 DPRINTF("no callback\n");
948 /* Protect scratch area */
949 do_unlock = usbd_ctrl_lock(udev);
954 parm = &udev->scratch.xfer_setup[0].parm;
955 memset(parm, 0, sizeof(*parm));
958 parm->speed = usbd_get_speed(udev);
959 parm->hc_max_packet_count = 1;
961 if (parm->speed >= USB_SPEED_MAX) {
962 parm->err = USB_ERR_INVAL;
965 /* setup all transfers */
971 * Initialize the "usb_xfer_root" structure,
972 * which is common for all our USB transfers.
974 info = USB_ADD_BYTES(buf, 0);
976 info->memory_base = buf;
977 info->memory_size = parm->size[0];
980 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
981 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
983 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
984 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
986 cv_init(&info->cv_drain, "WDRAIN");
988 info->xfer_mtx = xfer_mtx;
990 usb_dma_tag_setup(&info->dma_parent_tag,
991 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
992 xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
996 info->bus = udev->bus;
999 TAILQ_INIT(&info->done_q.head);
1000 info->done_q.command = &usbd_callback_wrapper;
1002 TAILQ_INIT(&info->dma_q.head);
1003 info->dma_q.command = &usb_bdma_work_loop;
1005 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
1006 info->done_m[0].xroot = info;
1007 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
1008 info->done_m[1].xroot = info;
1011 * In device side mode control endpoint
1012 * requests need to run from a separate
1013 * context, else there is a chance of
1016 if (setup_start == usb_control_ep_cfg)
1018 &udev->bus->control_xfer_proc;
1019 else if (xfer_mtx == &Giant)
1021 &udev->bus->giant_callback_proc;
1024 &udev->bus->non_giant_callback_proc;
1030 parm->size[0] += sizeof(info[0]);
1032 for (setup = setup_start, n = 0;
1033 setup != setup_end; setup++, n++) {
1035 /* skip USB transfers without callbacks: */
1036 if (setup->callback == NULL) {
1039 /* see if there is a matching endpoint */
1040 ep = usbd_get_endpoint(udev,
1041 ifaces[setup->if_index], setup);
1043 if ((ep == NULL) || (ep->methods == NULL)) {
1044 if (setup->flags.no_pipe_ok)
1046 if ((setup->usb_mode != USB_MODE_DUAL) &&
1047 (setup->usb_mode != udev->flags.usb_mode))
1049 parm->err = USB_ERR_NO_PIPE;
1053 /* align data properly */
1054 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1056 /* store current setup pointer */
1057 parm->curr_setup = setup;
1061 * Common initialization of the
1062 * "usb_xfer" structure.
1064 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1065 xfer->address = udev->address;
1066 xfer->priv_sc = priv_sc;
1069 usb_callout_init_mtx(&xfer->timeout_handle,
1070 &udev->bus->bus_mtx, 0);
1073 * Setup a dummy xfer, hence we are
1074 * writing to the "usb_xfer"
1075 * structure pointed to by "xfer"
1076 * before we have allocated any
1079 xfer = &udev->scratch.xfer_setup[0].dummy;
1080 memset(xfer, 0, sizeof(*xfer));
1084 /* set transfer endpoint pointer */
1085 xfer->endpoint = ep;
1087 parm->size[0] += sizeof(xfer[0]);
1088 parm->methods = xfer->endpoint->methods;
1089 parm->curr_xfer = xfer;
1092 * Call the Host or Device controller transfer
1095 (udev->bus->methods->xfer_setup) (parm);
1097 /* check for error */
1103 * Increment the endpoint refcount. This
1104 * basically prevents setting a new
1105 * configuration and alternate setting
1106 * when USB transfers are in use on
1107 * the given interface. Search the USB
1108 * code for "endpoint->refcount_alloc" if you
1109 * want more information.
1111 USB_BUS_LOCK(info->bus);
1112 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1113 parm->err = USB_ERR_INVAL;
1115 xfer->endpoint->refcount_alloc++;
1117 if (xfer->endpoint->refcount_alloc == 0)
1118 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1119 USB_BUS_UNLOCK(info->bus);
1122 * Whenever we set ppxfer[] then we
1123 * also need to increment the
1126 info->setup_refcount++;
1129 * Transfer is successfully setup and
1135 /* check for error */
1140 if (buf != NULL || parm->err != 0)
1143 /* if no transfers, nothing to do */
1147 /* align data properly */
1148 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1150 /* store offset temporarily */
1151 parm->size[1] = parm->size[0];
1154 * The number of DMA tags required depends on
1155 * the number of endpoints. The current estimate
1156 * for maximum number of DMA tags per endpoint
1159 parm->dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1162 * DMA tags for QH, TD, Data and more.
1164 parm->dma_tag_max += 8;
1166 parm->dma_tag_p += parm->dma_tag_max;
1168 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1171 /* align data properly */
1172 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1174 /* store offset temporarily */
1175 parm->size[3] = parm->size[0];
1177 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1180 /* align data properly */
1181 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1183 /* store offset temporarily */
1184 parm->size[4] = parm->size[0];
1186 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1189 /* store end offset temporarily */
1190 parm->size[5] = parm->size[0];
1192 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1195 /* store end offset temporarily */
1197 parm->size[2] = parm->size[0];
1199 /* align data properly */
1200 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1202 parm->size[6] = parm->size[0];
1204 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1207 /* align data properly */
1208 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1210 /* allocate zeroed memory */
1211 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1214 parm->err = USB_ERR_NOMEM;
1215 DPRINTFN(0, "cannot allocate memory block for "
1216 "configuration (%d bytes)\n",
1220 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1221 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1222 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1223 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1224 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1229 if (info->setup_refcount == 0) {
1231 * "usbd_transfer_unsetup_sub" will unlock
1232 * the bus mutex before returning !
1234 USB_BUS_LOCK(info->bus);
1236 /* something went wrong */
1237 usbd_transfer_unsetup_sub(info, 0);
1241 /* check if any errors happened */
1243 usbd_transfer_unsetup(ppxfer, n_setup);
1248 usbd_ctrl_unlock(udev);
1253 /*------------------------------------------------------------------------*
1254 * usbd_transfer_unsetup_sub - factored out code
1255 *------------------------------------------------------------------------*/
1257 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1260 struct usb_page_cache *pc;
1263 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1265 /* wait for any outstanding DMA operations */
1269 temp = usbd_get_dma_delay(info->udev);
1271 usb_pause_mtx(&info->bus->bus_mtx,
1272 USB_MS_TO_TICKS(temp));
1276 /* make sure that our done messages are not queued anywhere */
1277 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1279 USB_BUS_UNLOCK(info->bus);
1282 /* free DMA'able memory, if any */
1283 pc = info->dma_page_cache_start;
1284 while (pc != info->dma_page_cache_end) {
1285 usb_pc_free_mem(pc);
1289 /* free DMA maps in all "xfer->frbuffers" */
1290 pc = info->xfer_page_cache_start;
1291 while (pc != info->xfer_page_cache_end) {
1292 usb_pc_dmamap_destroy(pc);
1296 /* free all DMA tags */
1297 usb_dma_tag_unsetup(&info->dma_parent_tag);
1300 cv_destroy(&info->cv_drain);
1303 * free the "memory_base" last, hence the "info" structure is
1304 * contained within the "memory_base"!
1306 free(info->memory_base, M_USB);
1309 /*------------------------------------------------------------------------*
1310 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1312 * NOTE: All USB transfers in progress will get called back passing
1313 * the error code "USB_ERR_CANCELLED" before this function
1315 *------------------------------------------------------------------------*/
1317 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1319 struct usb_xfer *xfer;
1320 struct usb_xfer_root *info;
1321 uint8_t needs_delay = 0;
1323 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1324 "usbd_transfer_unsetup can sleep!");
1327 xfer = pxfer[n_setup];
1334 USB_XFER_LOCK(xfer);
1335 USB_BUS_LOCK(info->bus);
1338 * HINT: when you start/stop a transfer, it might be a
1339 * good idea to directly use the "pxfer[]" structure:
1341 * usbd_transfer_start(sc->pxfer[0]);
1342 * usbd_transfer_stop(sc->pxfer[0]);
1344 * That way, if your code has many parts that will not
1345 * stop running under the same lock, in other words
1346 * "xfer_mtx", the usbd_transfer_start and
1347 * usbd_transfer_stop functions will simply return
1348 * when they detect a NULL pointer argument.
1350 * To avoid any races we clear the "pxfer[]" pointer
1351 * while holding the private mutex of the driver:
1353 pxfer[n_setup] = NULL;
1355 USB_BUS_UNLOCK(info->bus);
1356 USB_XFER_UNLOCK(xfer);
1358 usbd_transfer_drain(xfer);
1361 if (xfer->flags_int.bdma_enable)
1365 * NOTE: default endpoint does not have an
1366 * interface, even if endpoint->iface_index == 0
1368 USB_BUS_LOCK(info->bus);
1369 xfer->endpoint->refcount_alloc--;
1370 USB_BUS_UNLOCK(info->bus);
1372 usb_callout_drain(&xfer->timeout_handle);
1374 USB_BUS_LOCK(info->bus);
1376 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1377 "reference count\n"));
1379 info->setup_refcount--;
1381 if (info->setup_refcount == 0) {
1382 usbd_transfer_unsetup_sub(info,
1385 USB_BUS_UNLOCK(info->bus);
1390 /*------------------------------------------------------------------------*
1391 * usbd_control_transfer_init - factored out code
1393 * In USB Device Mode we have to wait for the SETUP packet which
1394 * containst the "struct usb_device_request" structure, before we can
1395 * transfer any data. In USB Host Mode we already have the SETUP
1396 * packet at the moment the USB transfer is started. This leads us to
1397 * having to setup the USB transfer at two different places in
1398 * time. This function just contains factored out control transfer
1399 * initialisation code, so that we don't duplicate the code.
1400 *------------------------------------------------------------------------*/
1402 usbd_control_transfer_init(struct usb_xfer *xfer)
1404 struct usb_device_request req;
1406 /* copy out the USB request header */
1408 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1410 /* setup remainder */
1412 xfer->flags_int.control_rem = UGETW(req.wLength);
1414 /* copy direction to endpoint variable */
1416 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1418 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1421 /*------------------------------------------------------------------------*
1422 * usbd_control_transfer_did_data
1424 * This function returns non-zero if a control endpoint has
1425 * transferred the first DATA packet after the SETUP packet.
1426 * Else it returns zero.
1427 *------------------------------------------------------------------------*/
1429 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1431 struct usb_device_request req;
1433 /* SETUP packet is not yet sent */
1434 if (xfer->flags_int.control_hdr != 0)
1437 /* copy out the USB request header */
1438 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1440 /* compare remainder to the initial value */
1441 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1444 /*------------------------------------------------------------------------*
1445 * usbd_setup_ctrl_transfer
1447 * This function handles initialisation of control transfers. Control
1448 * transfers are special in that regard that they can both transmit
1454 *------------------------------------------------------------------------*/
1456 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1460 /* Check for control endpoint stall */
1461 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1462 /* the control transfer is no longer active */
1463 xfer->flags_int.control_stall = 1;
1464 xfer->flags_int.control_act = 0;
1466 /* don't stall control transfer by default */
1467 xfer->flags_int.control_stall = 0;
1470 /* Check for invalid number of frames */
1471 if (xfer->nframes > 2) {
1473 * If you need to split a control transfer, you
1474 * have to do one part at a time. Only with
1475 * non-control transfers you can do multiple
1478 DPRINTFN(0, "Too many frames: %u\n",
1479 (unsigned int)xfer->nframes);
1484 * Check if there is a control
1485 * transfer in progress:
1487 if (xfer->flags_int.control_act) {
1489 if (xfer->flags_int.control_hdr) {
1491 /* clear send header flag */
1493 xfer->flags_int.control_hdr = 0;
1495 /* setup control transfer */
1496 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1497 usbd_control_transfer_init(xfer);
1500 /* get data length */
1506 /* the size of the SETUP structure is hardcoded ! */
1508 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1509 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1510 xfer->frlengths[0], sizeof(struct
1511 usb_device_request));
1514 /* check USB mode */
1515 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1517 /* check number of frames */
1518 if (xfer->nframes != 1) {
1520 * We need to receive the setup
1521 * message first so that we know the
1524 DPRINTF("Misconfigured transfer\n");
1528 * Set a dummy "control_rem" value. This
1529 * variable will be overwritten later by a
1530 * call to "usbd_control_transfer_init()" !
1532 xfer->flags_int.control_rem = 0xFFFF;
1535 /* setup "endpoint" and "control_rem" */
1537 usbd_control_transfer_init(xfer);
1540 /* set transfer-header flag */
1542 xfer->flags_int.control_hdr = 1;
1544 /* get data length */
1546 len = (xfer->sumlen - sizeof(struct usb_device_request));
1549 /* update did data flag */
1551 xfer->flags_int.control_did_data =
1552 usbd_control_transfer_did_data(xfer);
1554 /* check if there is a length mismatch */
1556 if (len > xfer->flags_int.control_rem) {
1557 DPRINTFN(0, "Length (%d) greater than "
1558 "remaining length (%d)\n", len,
1559 xfer->flags_int.control_rem);
1562 /* check if we are doing a short transfer */
1564 if (xfer->flags.force_short_xfer) {
1565 xfer->flags_int.control_rem = 0;
1567 if ((len != xfer->max_data_length) &&
1568 (len != xfer->flags_int.control_rem) &&
1569 (xfer->nframes != 1)) {
1570 DPRINTFN(0, "Short control transfer without "
1571 "force_short_xfer set\n");
1574 xfer->flags_int.control_rem -= len;
1577 /* the status part is executed when "control_act" is 0 */
1579 if ((xfer->flags_int.control_rem > 0) ||
1580 (xfer->flags.manual_status)) {
1581 /* don't execute the STATUS stage yet */
1582 xfer->flags_int.control_act = 1;
1585 if ((!xfer->flags_int.control_hdr) &&
1586 (xfer->nframes == 1)) {
1588 * This is not a valid operation!
1590 DPRINTFN(0, "Invalid parameter "
1595 /* time to execute the STATUS stage */
1596 xfer->flags_int.control_act = 0;
1598 return (0); /* success */
1601 return (1); /* failure */
1604 /*------------------------------------------------------------------------*
1605 * usbd_transfer_submit - start USB hardware for the given transfer
1607 * This function should only be called from the USB callback.
1608 *------------------------------------------------------------------------*/
1610 usbd_transfer_submit(struct usb_xfer *xfer)
1612 struct usb_xfer_root *info;
1613 struct usb_bus *bus;
1619 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1620 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1624 if (USB_DEBUG_VAR > 0) {
1627 usb_dump_endpoint(xfer->endpoint);
1629 USB_BUS_UNLOCK(bus);
1633 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1634 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1636 /* Only open the USB transfer once! */
1637 if (!xfer->flags_int.open) {
1638 xfer->flags_int.open = 1;
1643 (xfer->endpoint->methods->open) (xfer);
1644 USB_BUS_UNLOCK(bus);
1646 /* set "transferring" flag */
1647 xfer->flags_int.transferring = 1;
1650 /* increment power reference */
1651 usbd_transfer_power_ref(xfer, 1);
1654 * Check if the transfer is waiting on a queue, most
1655 * frequently the "done_q":
1657 if (xfer->wait_queue) {
1659 usbd_transfer_dequeue(xfer);
1660 USB_BUS_UNLOCK(bus);
1662 /* clear "did_dma_delay" flag */
1663 xfer->flags_int.did_dma_delay = 0;
1665 /* clear "did_close" flag */
1666 xfer->flags_int.did_close = 0;
1669 /* clear "bdma_setup" flag */
1670 xfer->flags_int.bdma_setup = 0;
1672 /* by default we cannot cancel any USB transfer immediately */
1673 xfer->flags_int.can_cancel_immed = 0;
1675 /* clear lengths and frame counts by default */
1680 /* clear any previous errors */
1683 /* Check if the device is still alive */
1684 if (info->udev->state < USB_STATE_POWERED) {
1687 * Must return cancelled error code else
1688 * device drivers can hang.
1690 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1691 USB_BUS_UNLOCK(bus);
1696 if (xfer->nframes == 0) {
1697 if (xfer->flags.stall_pipe) {
1699 * Special case - want to stall without transferring
1702 DPRINTF("xfer=%p nframes=0: stall "
1703 "or clear stall!\n", xfer);
1705 xfer->flags_int.can_cancel_immed = 1;
1706 /* start the transfer */
1707 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1708 USB_BUS_UNLOCK(bus);
1712 usbd_transfer_done(xfer, USB_ERR_INVAL);
1713 USB_BUS_UNLOCK(bus);
1716 /* compute some variables */
1718 for (x = 0; x != xfer->nframes; x++) {
1719 /* make a copy of the frlenghts[] */
1720 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1721 /* compute total transfer length */
1722 xfer->sumlen += xfer->frlengths[x];
1723 if (xfer->sumlen < xfer->frlengths[x]) {
1724 /* length wrapped around */
1726 usbd_transfer_done(xfer, USB_ERR_INVAL);
1727 USB_BUS_UNLOCK(bus);
1732 /* clear some internal flags */
1734 xfer->flags_int.short_xfer_ok = 0;
1735 xfer->flags_int.short_frames_ok = 0;
1737 /* check if this is a control transfer */
1739 if (xfer->flags_int.control_xfr) {
1741 if (usbd_setup_ctrl_transfer(xfer)) {
1743 usbd_transfer_done(xfer, USB_ERR_STALLED);
1744 USB_BUS_UNLOCK(bus);
1749 * Setup filtered version of some transfer flags,
1750 * in case of data read direction
1752 if (USB_GET_DATA_ISREAD(xfer)) {
1754 if (xfer->flags.short_frames_ok) {
1755 xfer->flags_int.short_xfer_ok = 1;
1756 xfer->flags_int.short_frames_ok = 1;
1757 } else if (xfer->flags.short_xfer_ok) {
1758 xfer->flags_int.short_xfer_ok = 1;
1760 /* check for control transfer */
1761 if (xfer->flags_int.control_xfr) {
1763 * 1) Control transfers do not support
1764 * reception of multiple short USB
1765 * frames in host mode and device side
1766 * mode, with exception of:
1768 * 2) Due to sometimes buggy device
1769 * side firmware we need to do a
1770 * STATUS stage in case of short
1771 * control transfers in USB host mode.
1772 * The STATUS stage then becomes the
1773 * "alt_next" to the DATA stage.
1775 xfer->flags_int.short_frames_ok = 1;
1780 * Check if BUS-DMA support is enabled and try to load virtual
1781 * buffers into DMA, if any:
1784 if (xfer->flags_int.bdma_enable) {
1785 /* insert the USB transfer last in the BUS-DMA queue */
1786 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1791 * Enter the USB transfer into the Host Controller or
1792 * Device Controller schedule:
1794 usbd_pipe_enter(xfer);
1797 /*------------------------------------------------------------------------*
1798 * usbd_pipe_enter - factored out code
1799 *------------------------------------------------------------------------*/
1801 usbd_pipe_enter(struct usb_xfer *xfer)
1803 struct usb_endpoint *ep;
1805 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1807 USB_BUS_LOCK(xfer->xroot->bus);
1809 ep = xfer->endpoint;
1813 /* the transfer can now be cancelled */
1814 xfer->flags_int.can_cancel_immed = 1;
1816 /* enter the transfer */
1817 (ep->methods->enter) (xfer);
1819 /* check for transfer error */
1821 /* some error has happened */
1822 usbd_transfer_done(xfer, 0);
1823 USB_BUS_UNLOCK(xfer->xroot->bus);
1827 /* start the transfer */
1828 usb_command_wrapper(&ep->endpoint_q, xfer);
1829 USB_BUS_UNLOCK(xfer->xroot->bus);
1832 /*------------------------------------------------------------------------*
1833 * usbd_transfer_start - start an USB transfer
1835 * NOTE: Calling this function more than one time will only
1836 * result in a single transfer start, until the USB transfer
1838 *------------------------------------------------------------------------*/
1840 usbd_transfer_start(struct usb_xfer *xfer)
1843 /* transfer is gone */
1846 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1848 /* mark the USB transfer started */
1850 if (!xfer->flags_int.started) {
1851 /* lock the BUS lock to avoid races updating flags_int */
1852 USB_BUS_LOCK(xfer->xroot->bus);
1853 xfer->flags_int.started = 1;
1854 USB_BUS_UNLOCK(xfer->xroot->bus);
1856 /* check if the USB transfer callback is already transferring */
1858 if (xfer->flags_int.transferring) {
1861 USB_BUS_LOCK(xfer->xroot->bus);
1862 /* call the USB transfer callback */
1863 usbd_callback_ss_done_defer(xfer);
1864 USB_BUS_UNLOCK(xfer->xroot->bus);
1867 /*------------------------------------------------------------------------*
1868 * usbd_transfer_stop - stop an USB transfer
1870 * NOTE: Calling this function more than one time will only
1871 * result in a single transfer stop.
1872 * NOTE: When this function returns it is not safe to free nor
1873 * reuse any DMA buffers. See "usbd_transfer_drain()".
1874 *------------------------------------------------------------------------*/
1876 usbd_transfer_stop(struct usb_xfer *xfer)
1878 struct usb_endpoint *ep;
1881 /* transfer is gone */
1884 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1886 /* check if the USB transfer was ever opened */
1888 if (!xfer->flags_int.open) {
1889 if (xfer->flags_int.started) {
1890 /* nothing to do except clearing the "started" flag */
1891 /* lock the BUS lock to avoid races updating flags_int */
1892 USB_BUS_LOCK(xfer->xroot->bus);
1893 xfer->flags_int.started = 0;
1894 USB_BUS_UNLOCK(xfer->xroot->bus);
1898 /* try to stop the current USB transfer */
1900 USB_BUS_LOCK(xfer->xroot->bus);
1901 /* override any previous error */
1902 xfer->error = USB_ERR_CANCELLED;
1905 * Clear "open" and "started" when both private and USB lock
1906 * is locked so that we don't get a race updating "flags_int"
1908 xfer->flags_int.open = 0;
1909 xfer->flags_int.started = 0;
1912 * Check if we can cancel the USB transfer immediately.
1914 if (xfer->flags_int.transferring) {
1915 if (xfer->flags_int.can_cancel_immed &&
1916 (!xfer->flags_int.did_close)) {
1919 * The following will lead to an USB_ERR_CANCELLED
1920 * error code being passed to the USB callback.
1922 (xfer->endpoint->methods->close) (xfer);
1923 /* only close once */
1924 xfer->flags_int.did_close = 1;
1926 /* need to wait for the next done callback */
1931 /* close here and now */
1932 (xfer->endpoint->methods->close) (xfer);
1935 * Any additional DMA delay is done by
1936 * "usbd_transfer_unsetup()".
1940 * Special case. Check if we need to restart a blocked
1943 ep = xfer->endpoint;
1946 * If the current USB transfer is completing we need
1947 * to start the next one:
1949 if (ep->endpoint_q.curr == xfer) {
1950 usb_command_wrapper(&ep->endpoint_q, NULL);
1954 USB_BUS_UNLOCK(xfer->xroot->bus);
1957 /*------------------------------------------------------------------------*
1958 * usbd_transfer_pending
1960 * This function will check if an USB transfer is pending which is a
1961 * little bit complicated!
1964 * 1: Pending: The USB transfer will receive a callback in the future.
1965 *------------------------------------------------------------------------*/
1967 usbd_transfer_pending(struct usb_xfer *xfer)
1969 struct usb_xfer_root *info;
1970 struct usb_xfer_queue *pq;
1973 /* transfer is gone */
1976 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1978 if (xfer->flags_int.transferring) {
1982 USB_BUS_LOCK(xfer->xroot->bus);
1983 if (xfer->wait_queue) {
1984 /* we are waiting on a queue somewhere */
1985 USB_BUS_UNLOCK(xfer->xroot->bus);
1991 if (pq->curr == xfer) {
1992 /* we are currently scheduled for callback */
1993 USB_BUS_UNLOCK(xfer->xroot->bus);
1996 /* we are not pending */
1997 USB_BUS_UNLOCK(xfer->xroot->bus);
2001 /*------------------------------------------------------------------------*
2002 * usbd_transfer_drain
2004 * This function will stop the USB transfer and wait for any
2005 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2006 * are loaded into DMA can safely be freed or reused after that this
2007 * function has returned.
2008 *------------------------------------------------------------------------*/
2010 usbd_transfer_drain(struct usb_xfer *xfer)
2012 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2013 "usbd_transfer_drain can sleep!");
2016 /* transfer is gone */
2019 if (xfer->xroot->xfer_mtx != &Giant) {
2020 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2022 USB_XFER_LOCK(xfer);
2024 usbd_transfer_stop(xfer);
2026 while (usbd_transfer_pending(xfer) ||
2027 xfer->flags_int.doing_callback) {
2030 * It is allowed that the callback can drop its
2031 * transfer mutex. In that case checking only
2032 * "usbd_transfer_pending()" is not enough to tell if
2033 * the USB transfer is fully drained. We also need to
2034 * check the internal "doing_callback" flag.
2036 xfer->flags_int.draining = 1;
2039 * Wait until the current outstanding USB
2040 * transfer is complete !
2042 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2044 USB_XFER_UNLOCK(xfer);
2047 struct usb_page_cache *
2048 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2050 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2052 return (&xfer->frbuffers[frindex]);
2056 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2058 struct usb_page_search page_info;
2060 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2062 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2063 return (page_info.buffer);
2066 /*------------------------------------------------------------------------*
2067 * usbd_xfer_get_fps_shift
2069 * The following function is only useful for isochronous transfers. It
2070 * returns how many times the frame execution rate has been shifted
2076 *------------------------------------------------------------------------*/
2078 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2080 return (xfer->fps_shift);
2084 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2086 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2088 return (xfer->frlengths[frindex]);
2091 /*------------------------------------------------------------------------*
2092 * usbd_xfer_set_frame_data
2094 * This function sets the pointer of the buffer that should
2095 * loaded directly into DMA for the given USB frame. Passing "ptr"
2096 * equal to NULL while the corresponding "frlength" is greater
2097 * than zero gives undefined results!
2098 *------------------------------------------------------------------------*/
2100 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2101 void *ptr, usb_frlength_t len)
2103 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2105 /* set virtual address to load and length */
2106 xfer->frbuffers[frindex].buffer = ptr;
2107 usbd_xfer_set_frame_len(xfer, frindex, len);
2111 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2112 void **ptr, int *len)
2114 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2117 *ptr = xfer->frbuffers[frindex].buffer;
2119 *len = xfer->frlengths[frindex];
2122 /*------------------------------------------------------------------------*
2123 * usbd_xfer_old_frame_length
2125 * This function returns the framelength of the given frame at the
2126 * time the transfer was submitted. This function can be used to
2127 * compute the starting data pointer of the next isochronous frame
2128 * when an isochronous transfer has completed.
2129 *------------------------------------------------------------------------*/
2131 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2133 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2135 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2139 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2143 *actlen = xfer->actlen;
2145 *sumlen = xfer->sumlen;
2146 if (aframes != NULL)
2147 *aframes = xfer->aframes;
2148 if (nframes != NULL)
2149 *nframes = xfer->nframes;
2152 /*------------------------------------------------------------------------*
2153 * usbd_xfer_set_frame_offset
2155 * This function sets the frame data buffer offset relative to the beginning
2156 * of the USB DMA buffer allocated for this USB transfer.
2157 *------------------------------------------------------------------------*/
2159 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2160 usb_frcount_t frindex)
2162 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2163 "when the USB buffer is external\n"));
2164 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2166 /* set virtual address to load */
2167 xfer->frbuffers[frindex].buffer =
2168 USB_ADD_BYTES(xfer->local_buffer, offset);
2172 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2178 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2184 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2190 usbd_xfer_max_frames(struct usb_xfer *xfer)
2192 return (xfer->max_frame_count);
2196 usbd_xfer_max_len(struct usb_xfer *xfer)
2198 return (xfer->max_data_length);
2202 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2204 return (xfer->max_frame_size);
2208 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2211 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2213 xfer->frlengths[frindex] = len;
2216 /*------------------------------------------------------------------------*
2217 * usb_callback_proc - factored out code
2219 * This function performs USB callbacks.
2220 *------------------------------------------------------------------------*/
2222 usb_callback_proc(struct usb_proc_msg *_pm)
2224 struct usb_done_msg *pm = (void *)_pm;
2225 struct usb_xfer_root *info = pm->xroot;
2227 /* Change locking order */
2228 USB_BUS_UNLOCK(info->bus);
2231 * We exploit the fact that the mutex is the same for all
2232 * callbacks that will be called from this thread:
2234 mtx_lock(info->xfer_mtx);
2235 USB_BUS_LOCK(info->bus);
2237 /* Continue where we lost track */
2238 usb_command_wrapper(&info->done_q,
2241 mtx_unlock(info->xfer_mtx);
2244 /*------------------------------------------------------------------------*
2245 * usbd_callback_ss_done_defer
2247 * This function will defer the start, stop and done callback to the
2249 *------------------------------------------------------------------------*/
2251 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2253 struct usb_xfer_root *info = xfer->xroot;
2254 struct usb_xfer_queue *pq = &info->done_q;
2256 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2258 if (pq->curr != xfer) {
2259 usbd_transfer_enqueue(pq, xfer);
2261 if (!pq->recurse_1) {
2264 * We have to postpone the callback due to the fact we
2265 * will have a Lock Order Reversal, LOR, if we try to
2268 if (usb_proc_msignal(info->done_p,
2269 &info->done_m[0], &info->done_m[1])) {
2273 /* clear second recurse flag */
2280 /*------------------------------------------------------------------------*
2281 * usbd_callback_wrapper
2283 * This is a wrapper for USB callbacks. This wrapper does some
2284 * auto-magic things like figuring out if we can call the callback
2285 * directly from the current context or if we need to wakeup the
2286 * interrupt process.
2287 *------------------------------------------------------------------------*/
2289 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2291 struct usb_xfer *xfer = pq->curr;
2292 struct usb_xfer_root *info = xfer->xroot;
2294 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2295 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2297 * Cases that end up here:
2299 * 5) HW interrupt done callback or other source.
2301 DPRINTFN(3, "case 5\n");
2304 * We have to postpone the callback due to the fact we
2305 * will have a Lock Order Reversal, LOR, if we try to
2308 if (usb_proc_msignal(info->done_p,
2309 &info->done_m[0], &info->done_m[1])) {
2315 * Cases that end up here:
2317 * 1) We are starting a transfer
2318 * 2) We are prematurely calling back a transfer
2319 * 3) We are stopping a transfer
2320 * 4) We are doing an ordinary callback
2322 DPRINTFN(3, "case 1-4\n");
2323 /* get next USB transfer in the queue */
2324 info->done_q.curr = NULL;
2326 /* set flag in case of drain */
2327 xfer->flags_int.doing_callback = 1;
2329 USB_BUS_UNLOCK(info->bus);
2330 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2332 /* set correct USB state for callback */
2333 if (!xfer->flags_int.transferring) {
2334 xfer->usb_state = USB_ST_SETUP;
2335 if (!xfer->flags_int.started) {
2336 /* we got stopped before we even got started */
2337 USB_BUS_LOCK(info->bus);
2342 if (usbd_callback_wrapper_sub(xfer)) {
2343 /* the callback has been deferred */
2344 USB_BUS_LOCK(info->bus);
2348 /* decrement power reference */
2349 usbd_transfer_power_ref(xfer, -1);
2351 xfer->flags_int.transferring = 0;
2354 xfer->usb_state = USB_ST_ERROR;
2356 /* set transferred state */
2357 xfer->usb_state = USB_ST_TRANSFERRED;
2359 /* sync DMA memory, if any */
2360 if (xfer->flags_int.bdma_enable &&
2361 (!xfer->flags_int.bdma_no_post_sync)) {
2362 usb_bdma_post_sync(xfer);
2369 if (xfer->usb_state != USB_ST_SETUP) {
2370 USB_BUS_LOCK(info->bus);
2371 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2372 USB_BUS_UNLOCK(info->bus);
2375 /* call processing routine */
2376 (xfer->callback) (xfer, xfer->error);
2378 /* pickup the USB mutex again */
2379 USB_BUS_LOCK(info->bus);
2382 * Check if we got started after that we got cancelled, but
2383 * before we managed to do the callback.
2385 if ((!xfer->flags_int.open) &&
2386 (xfer->flags_int.started) &&
2387 (xfer->usb_state == USB_ST_ERROR)) {
2388 /* clear flag in case of drain */
2389 xfer->flags_int.doing_callback = 0;
2390 /* try to loop, but not recursivly */
2391 usb_command_wrapper(&info->done_q, xfer);
2396 /* clear flag in case of drain */
2397 xfer->flags_int.doing_callback = 0;
2400 * Check if we are draining.
2402 if (xfer->flags_int.draining &&
2403 (!xfer->flags_int.transferring)) {
2404 /* "usbd_transfer_drain()" is waiting for end of transfer */
2405 xfer->flags_int.draining = 0;
2406 cv_broadcast(&info->cv_drain);
2409 /* do the next callback, if any */
2410 usb_command_wrapper(&info->done_q,
2414 /*------------------------------------------------------------------------*
2415 * usb_dma_delay_done_cb
2417 * This function is called when the DMA delay has been exectuded, and
2418 * will make sure that the callback is called to complete the USB
2419 * transfer. This code path is ususally only used when there is an USB
2420 * error like USB_ERR_CANCELLED.
2421 *------------------------------------------------------------------------*/
2423 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2425 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2427 DPRINTFN(3, "Completed %p\n", xfer);
2429 /* queue callback for execution, again */
2430 usbd_transfer_done(xfer, 0);
2433 /*------------------------------------------------------------------------*
2434 * usbd_transfer_dequeue
2436 * - This function is used to remove an USB transfer from a USB
2439 * - This function can be called multiple times in a row.
2440 *------------------------------------------------------------------------*/
2442 usbd_transfer_dequeue(struct usb_xfer *xfer)
2444 struct usb_xfer_queue *pq;
2446 pq = xfer->wait_queue;
2448 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2449 xfer->wait_queue = NULL;
2453 /*------------------------------------------------------------------------*
2454 * usbd_transfer_enqueue
2456 * - This function is used to insert an USB transfer into a USB *
2459 * - This function can be called multiple times in a row.
2460 *------------------------------------------------------------------------*/
2462 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2465 * Insert the USB transfer into the queue, if it is not
2466 * already on a USB transfer queue:
2468 if (xfer->wait_queue == NULL) {
2469 xfer->wait_queue = pq;
2470 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2474 /*------------------------------------------------------------------------*
2475 * usbd_transfer_done
2477 * - This function is used to remove an USB transfer from the busdma,
2478 * pipe or interrupt queue.
2480 * - This function is used to queue the USB transfer on the done
2483 * - This function is used to stop any USB transfer timeouts.
2484 *------------------------------------------------------------------------*/
2486 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2488 struct usb_xfer_root *info = xfer->xroot;
2490 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2492 DPRINTF("err=%s\n", usbd_errstr(error));
2495 * If we are not transferring then just return.
2496 * This can happen during transfer cancel.
2498 if (!xfer->flags_int.transferring) {
2499 DPRINTF("not transferring\n");
2500 /* end of control transfer, if any */
2501 xfer->flags_int.control_act = 0;
2504 /* only set transfer error, if not already set */
2505 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2506 xfer->error = error;
2508 /* stop any callouts */
2509 usb_callout_stop(&xfer->timeout_handle);
2512 * If we are waiting on a queue, just remove the USB transfer
2513 * from the queue, if any. We should have the required locks
2514 * locked to do the remove when this function is called.
2516 usbd_transfer_dequeue(xfer);
2519 if (mtx_owned(info->xfer_mtx)) {
2520 struct usb_xfer_queue *pq;
2523 * If the private USB lock is not locked, then we assume
2524 * that the BUS-DMA load stage has been passed:
2528 if (pq->curr == xfer) {
2529 /* start the next BUS-DMA load, if any */
2530 usb_command_wrapper(pq, NULL);
2534 /* keep some statistics */
2536 info->bus->stats_err.uds_requests
2537 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2539 info->bus->stats_ok.uds_requests
2540 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2543 /* call the USB transfer callback */
2544 usbd_callback_ss_done_defer(xfer);
2547 /*------------------------------------------------------------------------*
2548 * usbd_transfer_start_cb
2550 * This function is called to start the USB transfer when
2551 * "xfer->interval" is greater than zero, and and the endpoint type is
2553 *------------------------------------------------------------------------*/
2555 usbd_transfer_start_cb(void *arg)
2557 struct usb_xfer *xfer = arg;
2558 struct usb_endpoint *ep = xfer->endpoint;
2560 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2565 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2568 /* the transfer can now be cancelled */
2569 xfer->flags_int.can_cancel_immed = 1;
2571 /* start USB transfer, if no error */
2572 if (xfer->error == 0)
2573 (ep->methods->start) (xfer);
2575 /* check for transfer error */
2577 /* some error has happened */
2578 usbd_transfer_done(xfer, 0);
2582 /*------------------------------------------------------------------------*
2583 * usbd_xfer_set_stall
2585 * This function is used to set the stall flag outside the
2586 * callback. This function is NULL safe.
2587 *------------------------------------------------------------------------*/
2589 usbd_xfer_set_stall(struct usb_xfer *xfer)
2595 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2597 /* avoid any races by locking the USB mutex */
2598 USB_BUS_LOCK(xfer->xroot->bus);
2599 xfer->flags.stall_pipe = 1;
2600 USB_BUS_UNLOCK(xfer->xroot->bus);
2604 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2606 return (xfer->endpoint->is_stalled);
2609 /*------------------------------------------------------------------------*
2610 * usbd_transfer_clear_stall
2612 * This function is used to clear the stall flag outside the
2613 * callback. This function is NULL safe.
2614 *------------------------------------------------------------------------*/
2616 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2622 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2624 /* avoid any races by locking the USB mutex */
2625 USB_BUS_LOCK(xfer->xroot->bus);
2627 xfer->flags.stall_pipe = 0;
2629 USB_BUS_UNLOCK(xfer->xroot->bus);
2632 /*------------------------------------------------------------------------*
2635 * This function is used to add an USB transfer to the pipe transfer list.
2636 *------------------------------------------------------------------------*/
2638 usbd_pipe_start(struct usb_xfer_queue *pq)
2640 struct usb_endpoint *ep;
2641 struct usb_xfer *xfer;
2645 ep = xfer->endpoint;
2647 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2650 * If the endpoint is already stalled we do nothing !
2652 if (ep->is_stalled) {
2656 * Check if we are supposed to stall the endpoint:
2658 if (xfer->flags.stall_pipe) {
2659 struct usb_device *udev;
2660 struct usb_xfer_root *info;
2662 /* clear stall command */
2663 xfer->flags.stall_pipe = 0;
2665 /* get pointer to USB device */
2670 * Only stall BULK and INTERRUPT endpoints.
2672 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2673 if ((type == UE_BULK) ||
2674 (type == UE_INTERRUPT)) {
2679 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2680 (udev->bus->methods->set_stall) (
2681 udev, NULL, ep, &did_stall);
2682 } else if (udev->ctrl_xfer[1]) {
2683 info = udev->ctrl_xfer[1]->xroot;
2685 &info->bus->non_giant_callback_proc,
2686 &udev->cs_msg[0], &udev->cs_msg[1]);
2688 /* should not happen */
2689 DPRINTFN(0, "No stall handler\n");
2692 * Check if we should stall. Some USB hardware
2693 * handles set- and clear-stall in hardware.
2697 * The transfer will be continued when
2698 * the clear-stall control endpoint
2699 * message is received.
2704 } else if (type == UE_ISOCHRONOUS) {
2707 * Make sure any FIFO overflow or other FIFO
2708 * error conditions go away by resetting the
2709 * endpoint FIFO through the clear stall
2712 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2713 (udev->bus->methods->clear_stall) (udev, ep);
2717 /* Set or clear stall complete - special case */
2718 if (xfer->nframes == 0) {
2719 /* we are complete */
2721 usbd_transfer_done(xfer, 0);
2727 * 1) Start the first transfer queued.
2729 * 2) Re-start the current USB transfer.
2732 * Check if there should be any
2733 * pre transfer start delay:
2735 if (xfer->interval > 0) {
2736 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2737 if ((type == UE_BULK) ||
2738 (type == UE_CONTROL)) {
2739 usbd_transfer_timeout_ms(xfer,
2740 &usbd_transfer_start_cb,
2748 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2750 /* the transfer can now be cancelled */
2751 xfer->flags_int.can_cancel_immed = 1;
2753 /* start USB transfer, if no error */
2754 if (xfer->error == 0)
2755 (ep->methods->start) (xfer);
2757 /* check for transfer error */
2759 /* some error has happened */
2760 usbd_transfer_done(xfer, 0);
2764 /*------------------------------------------------------------------------*
2765 * usbd_transfer_timeout_ms
2767 * This function is used to setup a timeout on the given USB
2768 * transfer. If the timeout has been deferred the callback given by
2769 * "cb" will get called after "ms" milliseconds.
2770 *------------------------------------------------------------------------*/
2772 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2773 void (*cb) (void *arg), usb_timeout_t ms)
2775 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2778 usb_callout_reset(&xfer->timeout_handle,
2779 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2782 /*------------------------------------------------------------------------*
2783 * usbd_callback_wrapper_sub
2785 * - This function will update variables in an USB transfer after
2786 * that the USB transfer is complete.
2788 * - This function is used to start the next USB transfer on the
2789 * ep transfer queue, if any.
2791 * NOTE: In some special cases the USB transfer will not be removed from
2792 * the pipe queue, but remain first. To enforce USB transfer removal call
2793 * this function passing the error code "USB_ERR_CANCELLED".
2797 * Else: The callback has been deferred.
2798 *------------------------------------------------------------------------*/
2800 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2802 struct usb_endpoint *ep;
2803 struct usb_bus *bus;
2806 bus = xfer->xroot->bus;
2808 if ((!xfer->flags_int.open) &&
2809 (!xfer->flags_int.did_close)) {
2812 (xfer->endpoint->methods->close) (xfer);
2813 USB_BUS_UNLOCK(bus);
2814 /* only close once */
2815 xfer->flags_int.did_close = 1;
2816 return (1); /* wait for new callback */
2819 * If we have a non-hardware induced error we
2820 * need to do the DMA delay!
2822 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2823 (xfer->error == USB_ERR_CANCELLED ||
2824 xfer->error == USB_ERR_TIMEOUT ||
2825 bus->methods->start_dma_delay != NULL)) {
2829 /* only delay once */
2830 xfer->flags_int.did_dma_delay = 1;
2832 /* we can not cancel this delay */
2833 xfer->flags_int.can_cancel_immed = 0;
2835 temp = usbd_get_dma_delay(xfer->xroot->udev);
2837 DPRINTFN(3, "DMA delay, %u ms, "
2838 "on %p\n", temp, xfer);
2843 * Some hardware solutions have dedicated
2844 * events when it is safe to free DMA'ed
2845 * memory. For the other hardware platforms we
2846 * use a static delay.
2848 if (bus->methods->start_dma_delay != NULL) {
2849 (bus->methods->start_dma_delay) (xfer);
2851 usbd_transfer_timeout_ms(xfer,
2852 (void (*)(void *))&usb_dma_delay_done_cb,
2855 USB_BUS_UNLOCK(bus);
2856 return (1); /* wait for new callback */
2859 /* check actual number of frames */
2860 if (xfer->aframes > xfer->nframes) {
2861 if (xfer->error == 0) {
2862 panic("%s: actual number of frames, %d, is "
2863 "greater than initial number of frames, %d\n",
2864 __FUNCTION__, xfer->aframes, xfer->nframes);
2866 /* just set some valid value */
2867 xfer->aframes = xfer->nframes;
2870 /* compute actual length */
2873 for (x = 0; x != xfer->aframes; x++) {
2874 xfer->actlen += xfer->frlengths[x];
2878 * Frames that were not transferred get zero actual length in
2879 * case the USB device driver does not check the actual number
2880 * of frames transferred, "xfer->aframes":
2882 for (; x < xfer->nframes; x++) {
2883 usbd_xfer_set_frame_len(xfer, x, 0);
2886 /* check actual length */
2887 if (xfer->actlen > xfer->sumlen) {
2888 if (xfer->error == 0) {
2889 panic("%s: actual length, %d, is greater than "
2890 "initial length, %d\n",
2891 __FUNCTION__, xfer->actlen, xfer->sumlen);
2893 /* just set some valid value */
2894 xfer->actlen = xfer->sumlen;
2897 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2898 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2899 xfer->aframes, xfer->nframes);
2902 /* end of control transfer, if any */
2903 xfer->flags_int.control_act = 0;
2905 #if USB_HAVE_TT_SUPPORT
2906 switch (xfer->error) {
2907 case USB_ERR_NORMAL_COMPLETION:
2908 case USB_ERR_SHORT_XFER:
2909 case USB_ERR_STALLED:
2910 case USB_ERR_CANCELLED:
2914 /* try to reset the TT, if any */
2916 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2917 USB_BUS_UNLOCK(bus);
2921 /* check if we should block the execution queue */
2922 if ((xfer->error != USB_ERR_CANCELLED) &&
2923 (xfer->flags.pipe_bof)) {
2924 DPRINTFN(2, "xfer=%p: Block On Failure "
2925 "on endpoint=%p\n", xfer, xfer->endpoint);
2929 /* check for short transfers */
2930 if (xfer->actlen < xfer->sumlen) {
2932 /* end of control transfer, if any */
2933 xfer->flags_int.control_act = 0;
2935 if (!xfer->flags_int.short_xfer_ok) {
2936 xfer->error = USB_ERR_SHORT_XFER;
2937 if (xfer->flags.pipe_bof) {
2938 DPRINTFN(2, "xfer=%p: Block On Failure on "
2939 "Short Transfer on endpoint %p.\n",
2940 xfer, xfer->endpoint);
2946 * Check if we are in the middle of a
2949 if (xfer->flags_int.control_act) {
2950 DPRINTFN(5, "xfer=%p: Control transfer "
2951 "active on endpoint=%p\n", xfer, xfer->endpoint);
2957 ep = xfer->endpoint;
2960 * If the current USB transfer is completing we need to start the
2964 if (ep->endpoint_q.curr == xfer) {
2965 usb_command_wrapper(&ep->endpoint_q, NULL);
2967 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2968 /* there is another USB transfer waiting */
2970 /* this is the last USB transfer */
2971 /* clear isochronous sync flag */
2972 xfer->endpoint->is_synced = 0;
2975 USB_BUS_UNLOCK(bus);
2980 /*------------------------------------------------------------------------*
2981 * usb_command_wrapper
2983 * This function is used to execute commands non-recursivly on an USB
2985 *------------------------------------------------------------------------*/
2987 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2991 * If the transfer is not already processing,
2994 if (pq->curr != xfer) {
2995 usbd_transfer_enqueue(pq, xfer);
2996 if (pq->curr != NULL) {
2997 /* something is already processing */
2998 DPRINTFN(6, "busy %p\n", pq->curr);
3003 /* Get next element in queue */
3007 if (!pq->recurse_1) {
3011 /* set both recurse flags */
3015 if (pq->curr == NULL) {
3016 xfer = TAILQ_FIRST(&pq->head);
3018 TAILQ_REMOVE(&pq->head, xfer,
3020 xfer->wait_queue = NULL;
3026 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3028 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3030 } while (!pq->recurse_2);
3032 /* clear first recurse flag */
3036 /* clear second recurse flag */
3041 /*------------------------------------------------------------------------*
3042 * usbd_ctrl_transfer_setup
3044 * This function is used to setup the default USB control endpoint
3046 *------------------------------------------------------------------------*/
3048 usbd_ctrl_transfer_setup(struct usb_device *udev)
3050 struct usb_xfer *xfer;
3052 uint8_t iface_index;
3054 /* check for root HUB */
3055 if (udev->parent_hub == NULL)
3059 xfer = udev->ctrl_xfer[0];
3061 USB_XFER_LOCK(xfer);
3063 ((xfer->address == udev->address) &&
3064 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3065 udev->ddesc.bMaxPacketSize));
3066 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3069 * NOTE: checking "xfer->address" and
3070 * starting the USB transfer must be
3073 usbd_transfer_start(xfer);
3076 USB_XFER_UNLOCK(xfer);
3083 * All parameters are exactly the same like before.
3089 * Update wMaxPacketSize for the default control endpoint:
3091 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3092 udev->ddesc.bMaxPacketSize;
3095 * Unsetup any existing USB transfer:
3097 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3100 * Reset clear stall error counter.
3102 udev->clear_stall_errors = 0;
3105 * Try to setup a new USB transfer for the
3106 * default control endpoint:
3109 if (usbd_transfer_setup(udev, &iface_index,
3110 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3111 &udev->device_mtx)) {
3112 DPRINTFN(0, "could not setup default "
3119 /*------------------------------------------------------------------------*
3120 * usbd_clear_data_toggle - factored out code
3122 * NOTE: the intention of this function is not to reset the hardware
3124 *------------------------------------------------------------------------*/
3126 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3128 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3130 /* check that we have a valid case */
3131 if (udev->flags.usb_mode == USB_MODE_HOST &&
3132 udev->parent_hub != NULL &&
3133 udev->bus->methods->clear_stall != NULL &&
3134 ep->methods != NULL) {
3135 (udev->bus->methods->clear_stall) (udev, ep);
3139 /*------------------------------------------------------------------------*
3140 * usbd_clear_data_toggle - factored out code
3142 * NOTE: the intention of this function is not to reset the hardware
3143 * data toggle on the USB device side.
3144 *------------------------------------------------------------------------*/
3146 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3148 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3150 USB_BUS_LOCK(udev->bus);
3151 ep->toggle_next = 0;
3152 /* some hardware needs a callback to clear the data toggle */
3153 usbd_clear_stall_locked(udev, ep);
3154 USB_BUS_UNLOCK(udev->bus);
3157 /*------------------------------------------------------------------------*
3158 * usbd_clear_stall_callback - factored out clear stall callback
3161 * xfer1: Clear Stall Control Transfer
3162 * xfer2: Stalled USB Transfer
3164 * This function is NULL safe.
3170 * Clear stall config example:
3172 * static const struct usb_config my_clearstall = {
3173 * .type = UE_CONTROL,
3175 * .direction = UE_DIR_ANY,
3176 * .interval = 50, //50 milliseconds
3177 * .bufsize = sizeof(struct usb_device_request),
3178 * .timeout = 1000, //1.000 seconds
3179 * .callback = &my_clear_stall_callback, // **
3180 * .usb_mode = USB_MODE_HOST,
3183 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3184 * passing the correct parameters.
3185 *------------------------------------------------------------------------*/
3187 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3188 struct usb_xfer *xfer2)
3190 struct usb_device_request req;
3192 if (xfer2 == NULL) {
3193 /* looks like we are tearing down */
3194 DPRINTF("NULL input parameter\n");
3197 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3198 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3200 switch (USB_GET_STATE(xfer1)) {
3204 * pre-clear the data toggle to DATA0 ("umass.c" and
3205 * "ata-usb.c" depends on this)
3208 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3210 /* setup a clear-stall packet */
3212 req.bmRequestType = UT_WRITE_ENDPOINT;
3213 req.bRequest = UR_CLEAR_FEATURE;
3214 USETW(req.wValue, UF_ENDPOINT_HALT);
3215 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3217 USETW(req.wLength, 0);
3220 * "usbd_transfer_setup_sub()" will ensure that
3221 * we have sufficient room in the buffer for
3222 * the request structure!
3225 /* copy in the transfer */
3227 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3230 xfer1->frlengths[0] = sizeof(req);
3233 usbd_transfer_submit(xfer1);
3236 case USB_ST_TRANSFERRED:
3239 default: /* Error */
3240 if (xfer1->error == USB_ERR_CANCELLED) {
3245 return (1); /* Clear Stall Finished */
3248 /*------------------------------------------------------------------------*
3249 * usbd_transfer_poll
3251 * The following function gets called from the USB keyboard driver and
3252 * UMASS when the system has paniced.
3254 * NOTE: It is currently not possible to resume normal operation on
3255 * the USB controller which has been polled, due to clearing of the
3256 * "up_dsleep" and "up_msleep" flags.
3257 *------------------------------------------------------------------------*/
3259 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3261 struct usb_xfer *xfer;
3262 struct usb_xfer_root *xroot;
3263 struct usb_device *udev;
3264 struct usb_proc_msg *pm;
3269 for (n = 0; n != max; n++) {
3270 /* Extra checks to avoid panic */
3273 continue; /* no USB transfer */
3274 xroot = xfer->xroot;
3276 continue; /* no USB root */
3279 continue; /* no USB device */
3280 if (udev->bus == NULL)
3281 continue; /* no BUS structure */
3282 if (udev->bus->methods == NULL)
3283 continue; /* no BUS methods */
3284 if (udev->bus->methods->xfer_poll == NULL)
3285 continue; /* no poll method */
3287 /* make sure that the BUS mutex is not locked */
3289 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3290 mtx_unlock(&xroot->udev->bus->bus_mtx);
3294 /* make sure that the transfer mutex is not locked */
3296 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3297 mtx_unlock(xroot->xfer_mtx);
3301 /* Make sure cv_signal() and cv_broadcast() is not called */
3302 udev->bus->control_xfer_proc.up_msleep = 0;
3303 udev->bus->explore_proc.up_msleep = 0;
3304 udev->bus->giant_callback_proc.up_msleep = 0;
3305 udev->bus->non_giant_callback_proc.up_msleep = 0;
3307 /* poll USB hardware */
3308 (udev->bus->methods->xfer_poll) (udev->bus);
3310 USB_BUS_LOCK(xroot->bus);
3312 /* check for clear stall */
3313 if (udev->ctrl_xfer[1] != NULL) {
3315 /* poll clear stall start */
3316 pm = &udev->cs_msg[0].hdr;
3317 (pm->pm_callback) (pm);
3318 /* poll clear stall done thread */
3319 pm = &udev->ctrl_xfer[1]->
3320 xroot->done_m[0].hdr;
3321 (pm->pm_callback) (pm);
3324 /* poll done thread */
3325 pm = &xroot->done_m[0].hdr;
3326 (pm->pm_callback) (pm);
3328 USB_BUS_UNLOCK(xroot->bus);
3330 /* restore transfer mutex */
3332 mtx_lock(xroot->xfer_mtx);
3334 /* restore BUS mutex */
3336 mtx_lock(&xroot->udev->bus->bus_mtx);
3341 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3342 uint8_t type, enum usb_dev_speed speed)
3344 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3345 [USB_SPEED_LOW] = 8,
3346 [USB_SPEED_FULL] = 64,
3347 [USB_SPEED_HIGH] = 1024,
3348 [USB_SPEED_VARIABLE] = 1024,
3349 [USB_SPEED_SUPER] = 1024,
3352 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3353 [USB_SPEED_LOW] = 0, /* invalid */
3354 [USB_SPEED_FULL] = 1023,
3355 [USB_SPEED_HIGH] = 1024,
3356 [USB_SPEED_VARIABLE] = 3584,
3357 [USB_SPEED_SUPER] = 1024,
3360 static const uint16_t control_min[USB_SPEED_MAX] = {
3361 [USB_SPEED_LOW] = 8,
3362 [USB_SPEED_FULL] = 8,
3363 [USB_SPEED_HIGH] = 64,
3364 [USB_SPEED_VARIABLE] = 512,
3365 [USB_SPEED_SUPER] = 512,
3368 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3369 [USB_SPEED_LOW] = 8,
3370 [USB_SPEED_FULL] = 8,
3371 [USB_SPEED_HIGH] = 512,
3372 [USB_SPEED_VARIABLE] = 512,
3373 [USB_SPEED_SUPER] = 1024,
3378 memset(ptr, 0, sizeof(*ptr));
3382 ptr->range.max = intr_range_max[speed];
3384 case UE_ISOCHRONOUS:
3385 ptr->range.max = isoc_range_max[speed];
3388 if (type == UE_BULK)
3389 temp = bulk_min[speed];
3390 else /* UE_CONTROL */
3391 temp = control_min[speed];
3393 /* default is fixed */
3394 ptr->fixed[0] = temp;
3395 ptr->fixed[1] = temp;
3396 ptr->fixed[2] = temp;
3397 ptr->fixed[3] = temp;
3399 if (speed == USB_SPEED_FULL) {
3400 /* multiple sizes */
3405 if ((speed == USB_SPEED_VARIABLE) &&
3406 (type == UE_BULK)) {
3407 /* multiple sizes */
3408 ptr->fixed[2] = 1024;
3409 ptr->fixed[3] = 1536;
3416 usbd_xfer_softc(struct usb_xfer *xfer)
3418 return (xfer->priv_sc);
3422 usbd_xfer_get_priv(struct usb_xfer *xfer)
3424 return (xfer->priv_fifo);
3428 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3430 xfer->priv_fifo = ptr;
3434 usbd_xfer_state(struct usb_xfer *xfer)
3436 return (xfer->usb_state);
3440 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3443 case USB_FORCE_SHORT_XFER:
3444 xfer->flags.force_short_xfer = 1;
3446 case USB_SHORT_XFER_OK:
3447 xfer->flags.short_xfer_ok = 1;
3449 case USB_MULTI_SHORT_OK:
3450 xfer->flags.short_frames_ok = 1;
3452 case USB_MANUAL_STATUS:
3453 xfer->flags.manual_status = 1;
3459 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3462 case USB_FORCE_SHORT_XFER:
3463 xfer->flags.force_short_xfer = 0;
3465 case USB_SHORT_XFER_OK:
3466 xfer->flags.short_xfer_ok = 0;
3468 case USB_MULTI_SHORT_OK:
3469 xfer->flags.short_frames_ok = 0;
3471 case USB_MANUAL_STATUS:
3472 xfer->flags.manual_status = 0;
3478 * The following function returns in milliseconds when the isochronous
3479 * transfer was completed by the hardware. The returned value wraps
3480 * around 65536 milliseconds.
3483 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3485 return (xfer->isoc_time_complete);
3489 * The following function returns non-zero if the max packet size
3490 * field was clamped to a valid value. Else it returns zero.
3493 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3495 return (xfer->flags_int.maxp_was_clamped);