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_transfer_setup_sub - transfer setup subroutine
304 * This function must be called from the "xfer_setup" callback of the
305 * USB Host or Device controller driver when setting up an USB
306 * transfer. This function will setup correct packet sizes, buffer
307 * sizes, flags and more, that are stored in the "usb_xfer"
309 *------------------------------------------------------------------------*/
311 usbd_transfer_setup_sub(struct usb_setup_params *parm)
317 struct usb_xfer *xfer = parm->curr_xfer;
318 const struct usb_config *setup = parm->curr_setup;
319 struct usb_endpoint_ss_comp_descriptor *ecomp;
320 struct usb_endpoint_descriptor *edesc;
321 struct usb_std_packet_size std_size;
322 usb_frcount_t n_frlengths;
323 usb_frcount_t n_frbuffers;
330 * Sanity check. The following parameters must be initialized before
331 * calling this function.
333 if ((parm->hc_max_packet_size == 0) ||
334 (parm->hc_max_packet_count == 0) ||
335 (parm->hc_max_frame_size == 0)) {
336 parm->err = USB_ERR_INVAL;
339 edesc = xfer->endpoint->edesc;
340 ecomp = xfer->endpoint->ecomp;
342 type = (edesc->bmAttributes & UE_XFERTYPE);
344 xfer->flags = setup->flags;
345 xfer->nframes = setup->frames;
346 xfer->timeout = setup->timeout;
347 xfer->callback = setup->callback;
348 xfer->interval = setup->interval;
349 xfer->endpointno = edesc->bEndpointAddress;
350 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
351 xfer->max_packet_count = 1;
352 /* make a shadow copy: */
353 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
355 parm->bufsize = setup->bufsize;
357 switch (parm->speed) {
362 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
364 /* check for invalid max packet count */
365 if (xfer->max_packet_count > 3)
366 xfer->max_packet_count = 3;
371 xfer->max_packet_size &= 0x7FF;
373 case USB_SPEED_SUPER:
374 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
377 xfer->max_packet_count += ecomp->bMaxBurst;
379 if ((xfer->max_packet_count == 0) ||
380 (xfer->max_packet_count > 16))
381 xfer->max_packet_count = 16;
385 xfer->max_packet_count = 1;
391 mult = (ecomp->bmAttributes & 3) + 1;
395 xfer->max_packet_count *= mult;
401 xfer->max_packet_size &= 0x7FF;
406 /* range check "max_packet_count" */
408 if (xfer->max_packet_count > parm->hc_max_packet_count) {
409 xfer->max_packet_count = parm->hc_max_packet_count;
412 /* store max packet size value before filtering */
414 maxp_old = xfer->max_packet_size;
416 /* filter "wMaxPacketSize" according to HC capabilities */
418 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
419 (xfer->max_packet_size == 0)) {
420 xfer->max_packet_size = parm->hc_max_packet_size;
422 /* filter "wMaxPacketSize" according to standard sizes */
424 usbd_get_std_packet_size(&std_size, type, parm->speed);
426 if (std_size.range.min || std_size.range.max) {
428 if (xfer->max_packet_size < std_size.range.min) {
429 xfer->max_packet_size = std_size.range.min;
431 if (xfer->max_packet_size > std_size.range.max) {
432 xfer->max_packet_size = std_size.range.max;
436 if (xfer->max_packet_size >= std_size.fixed[3]) {
437 xfer->max_packet_size = std_size.fixed[3];
438 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
439 xfer->max_packet_size = std_size.fixed[2];
440 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
441 xfer->max_packet_size = std_size.fixed[1];
443 /* only one possibility left */
444 xfer->max_packet_size = std_size.fixed[0];
449 * Check if the max packet size was outside its allowed range
450 * and clamped to a valid value:
452 if (maxp_old != xfer->max_packet_size)
453 xfer->flags_int.maxp_was_clamped = 1;
455 /* compute "max_frame_size" */
457 usbd_update_max_frame_size(xfer);
459 /* check interrupt interval and transfer pre-delay */
461 if (type == UE_ISOCHRONOUS) {
463 uint16_t frame_limit;
465 xfer->interval = 0; /* not used, must be zero */
466 xfer->flags_int.isochronous_xfr = 1; /* set flag */
468 if (xfer->timeout == 0) {
470 * set a default timeout in
471 * case something goes wrong!
473 xfer->timeout = 1000 / 4;
475 switch (parm->speed) {
478 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
482 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
483 xfer->fps_shift = edesc->bInterval;
484 if (xfer->fps_shift > 0)
486 if (xfer->fps_shift > 3)
488 if (xfer->flags.pre_scale_frames != 0)
489 xfer->nframes <<= (3 - xfer->fps_shift);
493 if (xfer->nframes > frame_limit) {
495 * this is not going to work
498 parm->err = USB_ERR_INVAL;
501 if (xfer->nframes == 0) {
503 * this is not a valid value
505 parm->err = USB_ERR_ZERO_NFRAMES;
511 * If a value is specified use that else check the
512 * endpoint descriptor!
514 if (type == UE_INTERRUPT) {
518 if (xfer->interval == 0) {
520 xfer->interval = edesc->bInterval;
522 switch (parm->speed) {
528 if (xfer->interval < 4)
530 else if (xfer->interval > 16)
531 xfer->interval = (1 << (16 - 4));
534 (1 << (xfer->interval - 4));
539 if (xfer->interval == 0) {
541 * One millisecond is the smallest
542 * interval we support:
550 while ((temp != 0) && (temp < xfer->interval)) {
555 switch (parm->speed) {
560 xfer->fps_shift += 3;
567 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
568 * to be equal to zero when setting up USB transfers, hence
569 * this leads to alot of extra code in the USB kernel.
572 if ((xfer->max_frame_size == 0) ||
573 (xfer->max_packet_size == 0)) {
577 if ((parm->bufsize <= MIN_PKT) &&
578 (type != UE_CONTROL) &&
582 xfer->max_packet_size = MIN_PKT;
583 xfer->max_packet_count = 1;
584 parm->bufsize = 0; /* automatic setup length */
585 usbd_update_max_frame_size(xfer);
588 parm->err = USB_ERR_ZERO_MAXP;
597 * check if we should setup a default
601 if (parm->bufsize == 0) {
603 parm->bufsize = xfer->max_frame_size;
605 if (type == UE_ISOCHRONOUS) {
606 parm->bufsize *= xfer->nframes;
610 * check if we are about to setup a proxy
614 if (xfer->flags.proxy_buffer) {
616 /* round bufsize up */
618 parm->bufsize += (xfer->max_frame_size - 1);
620 if (parm->bufsize < xfer->max_frame_size) {
621 /* length wrapped around */
622 parm->err = USB_ERR_INVAL;
625 /* subtract remainder */
627 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
629 /* add length of USB device request structure, if any */
631 if (type == UE_CONTROL) {
632 parm->bufsize += REQ_SIZE; /* SETUP message */
635 xfer->max_data_length = parm->bufsize;
637 /* Setup "n_frlengths" and "n_frbuffers" */
639 if (type == UE_ISOCHRONOUS) {
640 n_frlengths = xfer->nframes;
644 if (type == UE_CONTROL) {
645 xfer->flags_int.control_xfr = 1;
646 if (xfer->nframes == 0) {
647 if (parm->bufsize <= REQ_SIZE) {
649 * there will never be any data
658 if (xfer->nframes == 0) {
663 n_frlengths = xfer->nframes;
664 n_frbuffers = xfer->nframes;
668 * check if we have room for the
669 * USB device request structure:
672 if (type == UE_CONTROL) {
674 if (xfer->max_data_length < REQ_SIZE) {
675 /* length wrapped around or too small bufsize */
676 parm->err = USB_ERR_INVAL;
679 xfer->max_data_length -= REQ_SIZE;
682 * Setup "frlengths" and shadow "frlengths" for keeping the
683 * initial frame lengths when a USB transfer is complete. This
684 * information is useful when computing isochronous offsets.
686 xfer->frlengths = parm->xfer_length_ptr;
687 parm->xfer_length_ptr += 2 * n_frlengths;
689 /* setup "frbuffers" */
690 xfer->frbuffers = parm->xfer_page_cache_ptr;
691 parm->xfer_page_cache_ptr += n_frbuffers;
693 /* initialize max frame count */
694 xfer->max_frame_count = xfer->nframes;
697 * check if we need to setup
701 if (!xfer->flags.ext_buffer) {
704 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
709 USB_ADD_BYTES(parm->buf, parm->size[0]);
711 usbd_xfer_set_frame_offset(xfer, 0, 0);
713 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
714 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
717 parm->size[0] += parm->bufsize;
719 /* align data again */
720 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
723 * Compute maximum buffer size
726 if (parm->bufsize_max < parm->bufsize) {
727 parm->bufsize_max = parm->bufsize;
730 if (xfer->flags_int.bdma_enable) {
732 * Setup "dma_page_ptr".
734 * Proof for formula below:
736 * Assume there are three USB frames having length "a", "b" and
737 * "c". These USB frames will at maximum need "z"
738 * "usb_page" structures. "z" is given by:
740 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
741 * ((c / USB_PAGE_SIZE) + 2);
743 * Constraining "a", "b" and "c" like this:
745 * (a + b + c) <= parm->bufsize
749 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
751 * Here is the general formula:
753 xfer->dma_page_ptr = parm->dma_page_ptr;
754 parm->dma_page_ptr += (2 * n_frbuffers);
755 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
759 /* correct maximum data length */
760 xfer->max_data_length = 0;
762 /* subtract USB frame remainder from "hc_max_frame_size" */
764 xfer->max_hc_frame_size =
765 (parm->hc_max_frame_size -
766 (parm->hc_max_frame_size % xfer->max_frame_size));
768 if (xfer->max_hc_frame_size == 0) {
769 parm->err = USB_ERR_INVAL;
773 /* initialize frame buffers */
776 for (x = 0; x != n_frbuffers; x++) {
777 xfer->frbuffers[x].tag_parent =
778 &xfer->xroot->dma_parent_tag;
780 if (xfer->flags_int.bdma_enable &&
781 (parm->bufsize_max > 0)) {
783 if (usb_pc_dmamap_create(
785 parm->bufsize_max)) {
786 parm->err = USB_ERR_NOMEM;
796 * Set some dummy values so that we avoid division by zero:
798 xfer->max_hc_frame_size = 1;
799 xfer->max_frame_size = 1;
800 xfer->max_packet_size = 1;
801 xfer->max_data_length = 0;
803 xfer->max_frame_count = 0;
807 /*------------------------------------------------------------------------*
808 * usbd_transfer_setup - setup an array of USB transfers
810 * NOTE: You must always call "usbd_transfer_unsetup" after calling
811 * "usbd_transfer_setup" if success was returned.
813 * The idea is that the USB device driver should pre-allocate all its
814 * transfers by one call to this function.
819 *------------------------------------------------------------------------*/
821 usbd_transfer_setup(struct usb_device *udev,
822 const uint8_t *ifaces, struct usb_xfer **ppxfer,
823 const struct usb_config *setup_start, uint16_t n_setup,
824 void *priv_sc, struct mtx *xfer_mtx)
826 const struct usb_config *setup_end = setup_start + n_setup;
827 const struct usb_config *setup;
828 struct usb_setup_params *parm;
829 struct usb_endpoint *ep;
830 struct usb_xfer_root *info;
831 struct usb_xfer *xfer;
833 usb_error_t error = 0;
838 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
839 "usbd_transfer_setup can sleep!");
841 /* do some checking first */
844 DPRINTFN(6, "setup array has zero length!\n");
845 return (USB_ERR_INVAL);
848 DPRINTFN(6, "ifaces array is NULL!\n");
849 return (USB_ERR_INVAL);
851 if (xfer_mtx == NULL) {
852 DPRINTFN(6, "using global lock\n");
856 /* more sanity checks */
858 for (setup = setup_start, n = 0;
859 setup != setup_end; setup++, n++) {
860 if (setup->bufsize == (usb_frlength_t)-1) {
861 error = USB_ERR_BAD_BUFSIZE;
862 DPRINTF("invalid bufsize\n");
864 if (setup->callback == NULL) {
865 error = USB_ERR_NO_CALLBACK;
866 DPRINTF("no callback\n");
874 /* Protect scratch area */
875 do_unlock = usbd_enum_lock(udev);
880 parm = &udev->scratch.xfer_setup[0].parm;
881 memset(parm, 0, sizeof(*parm));
884 parm->speed = usbd_get_speed(udev);
885 parm->hc_max_packet_count = 1;
887 if (parm->speed >= USB_SPEED_MAX) {
888 parm->err = USB_ERR_INVAL;
891 /* setup all transfers */
897 * Initialize the "usb_xfer_root" structure,
898 * which is common for all our USB transfers.
900 info = USB_ADD_BYTES(buf, 0);
902 info->memory_base = buf;
903 info->memory_size = parm->size[0];
906 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
907 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
909 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
910 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
912 cv_init(&info->cv_drain, "WDRAIN");
914 info->xfer_mtx = xfer_mtx;
916 usb_dma_tag_setup(&info->dma_parent_tag,
917 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
918 xfer_mtx, &usb_bdma_done_event, 32, parm->dma_tag_max);
921 info->bus = udev->bus;
924 TAILQ_INIT(&info->done_q.head);
925 info->done_q.command = &usbd_callback_wrapper;
927 TAILQ_INIT(&info->dma_q.head);
928 info->dma_q.command = &usb_bdma_work_loop;
930 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
931 info->done_m[0].xroot = info;
932 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
933 info->done_m[1].xroot = info;
936 * In device side mode control endpoint
937 * requests need to run from a separate
938 * context, else there is a chance of
941 if (setup_start == usb_control_ep_cfg)
943 &udev->bus->control_xfer_proc;
944 else if (xfer_mtx == &Giant)
946 &udev->bus->giant_callback_proc;
949 &udev->bus->non_giant_callback_proc;
955 parm->size[0] += sizeof(info[0]);
957 for (setup = setup_start, n = 0;
958 setup != setup_end; setup++, n++) {
960 /* skip USB transfers without callbacks: */
961 if (setup->callback == NULL) {
964 /* see if there is a matching endpoint */
965 ep = usbd_get_endpoint(udev,
966 ifaces[setup->if_index], setup);
968 if ((ep == NULL) || (ep->methods == NULL)) {
969 if (setup->flags.no_pipe_ok)
971 if ((setup->usb_mode != USB_MODE_DUAL) &&
972 (setup->usb_mode != udev->flags.usb_mode))
974 parm->err = USB_ERR_NO_PIPE;
978 /* align data properly */
979 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
981 /* store current setup pointer */
982 parm->curr_setup = setup;
986 * Common initialization of the
987 * "usb_xfer" structure.
989 xfer = USB_ADD_BYTES(buf, parm->size[0]);
990 xfer->address = udev->address;
991 xfer->priv_sc = priv_sc;
994 usb_callout_init_mtx(&xfer->timeout_handle,
995 &udev->bus->bus_mtx, 0);
998 * Setup a dummy xfer, hence we are
999 * writing to the "usb_xfer"
1000 * structure pointed to by "xfer"
1001 * before we have allocated any
1004 xfer = &udev->scratch.xfer_setup[0].dummy;
1005 memset(xfer, 0, sizeof(*xfer));
1009 /* set transfer endpoint pointer */
1010 xfer->endpoint = ep;
1012 parm->size[0] += sizeof(xfer[0]);
1013 parm->methods = xfer->endpoint->methods;
1014 parm->curr_xfer = xfer;
1017 * Call the Host or Device controller transfer
1020 (udev->bus->methods->xfer_setup) (parm);
1022 /* check for error */
1028 * Increment the endpoint refcount. This
1029 * basically prevents setting a new
1030 * configuration and alternate setting
1031 * when USB transfers are in use on
1032 * the given interface. Search the USB
1033 * code for "endpoint->refcount_alloc" if you
1034 * want more information.
1036 USB_BUS_LOCK(info->bus);
1037 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1038 parm->err = USB_ERR_INVAL;
1040 xfer->endpoint->refcount_alloc++;
1042 if (xfer->endpoint->refcount_alloc == 0)
1043 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1044 USB_BUS_UNLOCK(info->bus);
1047 * Whenever we set ppxfer[] then we
1048 * also need to increment the
1051 info->setup_refcount++;
1054 * Transfer is successfully setup and
1060 /* check for error */
1065 if (buf != NULL || parm->err != 0)
1068 /* if no transfers, nothing to do */
1072 /* align data properly */
1073 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1075 /* store offset temporarily */
1076 parm->size[1] = parm->size[0];
1079 * The number of DMA tags required depends on
1080 * the number of endpoints. The current estimate
1081 * for maximum number of DMA tags per endpoint
1084 parm->dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1087 * DMA tags for QH, TD, Data and more.
1089 parm->dma_tag_max += 8;
1091 parm->dma_tag_p += parm->dma_tag_max;
1093 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1096 /* align data properly */
1097 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1099 /* store offset temporarily */
1100 parm->size[3] = parm->size[0];
1102 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1105 /* align data properly */
1106 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1108 /* store offset temporarily */
1109 parm->size[4] = parm->size[0];
1111 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1114 /* store end offset temporarily */
1115 parm->size[5] = parm->size[0];
1117 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1120 /* store end offset temporarily */
1122 parm->size[2] = parm->size[0];
1124 /* align data properly */
1125 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1127 parm->size[6] = parm->size[0];
1129 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1132 /* align data properly */
1133 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1135 /* allocate zeroed memory */
1136 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1139 parm->err = USB_ERR_NOMEM;
1140 DPRINTFN(0, "cannot allocate memory block for "
1141 "configuration (%d bytes)\n",
1145 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1146 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1147 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1148 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1149 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1154 if (info->setup_refcount == 0) {
1156 * "usbd_transfer_unsetup_sub" will unlock
1157 * the bus mutex before returning !
1159 USB_BUS_LOCK(info->bus);
1161 /* something went wrong */
1162 usbd_transfer_unsetup_sub(info, 0);
1166 /* check if any errors happened */
1168 usbd_transfer_unsetup(ppxfer, n_setup);
1173 usbd_enum_unlock(udev);
1178 /*------------------------------------------------------------------------*
1179 * usbd_transfer_unsetup_sub - factored out code
1180 *------------------------------------------------------------------------*/
1182 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1185 struct usb_page_cache *pc;
1188 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1190 /* wait for any outstanding DMA operations */
1194 temp = usbd_get_dma_delay(info->udev);
1196 usb_pause_mtx(&info->bus->bus_mtx,
1197 USB_MS_TO_TICKS(temp));
1201 /* make sure that our done messages are not queued anywhere */
1202 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1204 USB_BUS_UNLOCK(info->bus);
1207 /* free DMA'able memory, if any */
1208 pc = info->dma_page_cache_start;
1209 while (pc != info->dma_page_cache_end) {
1210 usb_pc_free_mem(pc);
1214 /* free DMA maps in all "xfer->frbuffers" */
1215 pc = info->xfer_page_cache_start;
1216 while (pc != info->xfer_page_cache_end) {
1217 usb_pc_dmamap_destroy(pc);
1221 /* free all DMA tags */
1222 usb_dma_tag_unsetup(&info->dma_parent_tag);
1225 cv_destroy(&info->cv_drain);
1228 * free the "memory_base" last, hence the "info" structure is
1229 * contained within the "memory_base"!
1231 free(info->memory_base, M_USB);
1234 /*------------------------------------------------------------------------*
1235 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1237 * NOTE: All USB transfers in progress will get called back passing
1238 * the error code "USB_ERR_CANCELLED" before this function
1240 *------------------------------------------------------------------------*/
1242 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1244 struct usb_xfer *xfer;
1245 struct usb_xfer_root *info;
1246 uint8_t needs_delay = 0;
1248 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1249 "usbd_transfer_unsetup can sleep!");
1252 xfer = pxfer[n_setup];
1259 USB_XFER_LOCK(xfer);
1260 USB_BUS_LOCK(info->bus);
1263 * HINT: when you start/stop a transfer, it might be a
1264 * good idea to directly use the "pxfer[]" structure:
1266 * usbd_transfer_start(sc->pxfer[0]);
1267 * usbd_transfer_stop(sc->pxfer[0]);
1269 * That way, if your code has many parts that will not
1270 * stop running under the same lock, in other words
1271 * "xfer_mtx", the usbd_transfer_start and
1272 * usbd_transfer_stop functions will simply return
1273 * when they detect a NULL pointer argument.
1275 * To avoid any races we clear the "pxfer[]" pointer
1276 * while holding the private mutex of the driver:
1278 pxfer[n_setup] = NULL;
1280 USB_BUS_UNLOCK(info->bus);
1281 USB_XFER_UNLOCK(xfer);
1283 usbd_transfer_drain(xfer);
1286 if (xfer->flags_int.bdma_enable)
1290 * NOTE: default endpoint does not have an
1291 * interface, even if endpoint->iface_index == 0
1293 USB_BUS_LOCK(info->bus);
1294 xfer->endpoint->refcount_alloc--;
1295 USB_BUS_UNLOCK(info->bus);
1297 usb_callout_drain(&xfer->timeout_handle);
1299 USB_BUS_LOCK(info->bus);
1301 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1302 "reference count\n"));
1304 info->setup_refcount--;
1306 if (info->setup_refcount == 0) {
1307 usbd_transfer_unsetup_sub(info,
1310 USB_BUS_UNLOCK(info->bus);
1315 /*------------------------------------------------------------------------*
1316 * usbd_control_transfer_init - factored out code
1318 * In USB Device Mode we have to wait for the SETUP packet which
1319 * containst the "struct usb_device_request" structure, before we can
1320 * transfer any data. In USB Host Mode we already have the SETUP
1321 * packet at the moment the USB transfer is started. This leads us to
1322 * having to setup the USB transfer at two different places in
1323 * time. This function just contains factored out control transfer
1324 * initialisation code, so that we don't duplicate the code.
1325 *------------------------------------------------------------------------*/
1327 usbd_control_transfer_init(struct usb_xfer *xfer)
1329 struct usb_device_request req;
1331 /* copy out the USB request header */
1333 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1335 /* setup remainder */
1337 xfer->flags_int.control_rem = UGETW(req.wLength);
1339 /* copy direction to endpoint variable */
1341 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1343 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1346 /*------------------------------------------------------------------------*
1347 * usbd_control_transfer_did_data
1349 * This function returns non-zero if a control endpoint has
1350 * transferred the first DATA packet after the SETUP packet.
1351 * Else it returns zero.
1352 *------------------------------------------------------------------------*/
1354 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1356 struct usb_device_request req;
1358 /* SETUP packet is not yet sent */
1359 if (xfer->flags_int.control_hdr != 0)
1362 /* copy out the USB request header */
1363 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1365 /* compare remainder to the initial value */
1366 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1369 /*------------------------------------------------------------------------*
1370 * usbd_setup_ctrl_transfer
1372 * This function handles initialisation of control transfers. Control
1373 * transfers are special in that regard that they can both transmit
1379 *------------------------------------------------------------------------*/
1381 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1385 /* Check for control endpoint stall */
1386 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1387 /* the control transfer is no longer active */
1388 xfer->flags_int.control_stall = 1;
1389 xfer->flags_int.control_act = 0;
1391 /* don't stall control transfer by default */
1392 xfer->flags_int.control_stall = 0;
1395 /* Check for invalid number of frames */
1396 if (xfer->nframes > 2) {
1398 * If you need to split a control transfer, you
1399 * have to do one part at a time. Only with
1400 * non-control transfers you can do multiple
1403 DPRINTFN(0, "Too many frames: %u\n",
1404 (unsigned int)xfer->nframes);
1409 * Check if there is a control
1410 * transfer in progress:
1412 if (xfer->flags_int.control_act) {
1414 if (xfer->flags_int.control_hdr) {
1416 /* clear send header flag */
1418 xfer->flags_int.control_hdr = 0;
1420 /* setup control transfer */
1421 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1422 usbd_control_transfer_init(xfer);
1425 /* get data length */
1431 /* the size of the SETUP structure is hardcoded ! */
1433 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1434 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1435 xfer->frlengths[0], sizeof(struct
1436 usb_device_request));
1439 /* check USB mode */
1440 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1442 /* check number of frames */
1443 if (xfer->nframes != 1) {
1445 * We need to receive the setup
1446 * message first so that we know the
1449 DPRINTF("Misconfigured transfer\n");
1453 * Set a dummy "control_rem" value. This
1454 * variable will be overwritten later by a
1455 * call to "usbd_control_transfer_init()" !
1457 xfer->flags_int.control_rem = 0xFFFF;
1460 /* setup "endpoint" and "control_rem" */
1462 usbd_control_transfer_init(xfer);
1465 /* set transfer-header flag */
1467 xfer->flags_int.control_hdr = 1;
1469 /* get data length */
1471 len = (xfer->sumlen - sizeof(struct usb_device_request));
1474 /* update did data flag */
1476 xfer->flags_int.control_did_data =
1477 usbd_control_transfer_did_data(xfer);
1479 /* check if there is a length mismatch */
1481 if (len > xfer->flags_int.control_rem) {
1482 DPRINTFN(0, "Length (%d) greater than "
1483 "remaining length (%d)\n", len,
1484 xfer->flags_int.control_rem);
1487 /* check if we are doing a short transfer */
1489 if (xfer->flags.force_short_xfer) {
1490 xfer->flags_int.control_rem = 0;
1492 if ((len != xfer->max_data_length) &&
1493 (len != xfer->flags_int.control_rem) &&
1494 (xfer->nframes != 1)) {
1495 DPRINTFN(0, "Short control transfer without "
1496 "force_short_xfer set\n");
1499 xfer->flags_int.control_rem -= len;
1502 /* the status part is executed when "control_act" is 0 */
1504 if ((xfer->flags_int.control_rem > 0) ||
1505 (xfer->flags.manual_status)) {
1506 /* don't execute the STATUS stage yet */
1507 xfer->flags_int.control_act = 1;
1510 if ((!xfer->flags_int.control_hdr) &&
1511 (xfer->nframes == 1)) {
1513 * This is not a valid operation!
1515 DPRINTFN(0, "Invalid parameter "
1520 /* time to execute the STATUS stage */
1521 xfer->flags_int.control_act = 0;
1523 return (0); /* success */
1526 return (1); /* failure */
1529 /*------------------------------------------------------------------------*
1530 * usbd_transfer_submit - start USB hardware for the given transfer
1532 * This function should only be called from the USB callback.
1533 *------------------------------------------------------------------------*/
1535 usbd_transfer_submit(struct usb_xfer *xfer)
1537 struct usb_xfer_root *info;
1538 struct usb_bus *bus;
1544 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1545 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1549 if (USB_DEBUG_VAR > 0) {
1552 usb_dump_endpoint(xfer->endpoint);
1554 USB_BUS_UNLOCK(bus);
1558 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1559 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1561 /* Only open the USB transfer once! */
1562 if (!xfer->flags_int.open) {
1563 xfer->flags_int.open = 1;
1568 (xfer->endpoint->methods->open) (xfer);
1569 USB_BUS_UNLOCK(bus);
1571 /* set "transferring" flag */
1572 xfer->flags_int.transferring = 1;
1575 /* increment power reference */
1576 usbd_transfer_power_ref(xfer, 1);
1579 * Check if the transfer is waiting on a queue, most
1580 * frequently the "done_q":
1582 if (xfer->wait_queue) {
1584 usbd_transfer_dequeue(xfer);
1585 USB_BUS_UNLOCK(bus);
1587 /* clear "did_dma_delay" flag */
1588 xfer->flags_int.did_dma_delay = 0;
1590 /* clear "did_close" flag */
1591 xfer->flags_int.did_close = 0;
1594 /* clear "bdma_setup" flag */
1595 xfer->flags_int.bdma_setup = 0;
1597 /* by default we cannot cancel any USB transfer immediately */
1598 xfer->flags_int.can_cancel_immed = 0;
1600 /* clear lengths and frame counts by default */
1605 /* clear any previous errors */
1608 /* Check if the device is still alive */
1609 if (info->udev->state < USB_STATE_POWERED) {
1612 * Must return cancelled error code else
1613 * device drivers can hang.
1615 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1616 USB_BUS_UNLOCK(bus);
1621 if (xfer->nframes == 0) {
1622 if (xfer->flags.stall_pipe) {
1624 * Special case - want to stall without transferring
1627 DPRINTF("xfer=%p nframes=0: stall "
1628 "or clear stall!\n", xfer);
1630 xfer->flags_int.can_cancel_immed = 1;
1631 /* start the transfer */
1632 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1633 USB_BUS_UNLOCK(bus);
1637 usbd_transfer_done(xfer, USB_ERR_INVAL);
1638 USB_BUS_UNLOCK(bus);
1641 /* compute some variables */
1643 for (x = 0; x != xfer->nframes; x++) {
1644 /* make a copy of the frlenghts[] */
1645 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1646 /* compute total transfer length */
1647 xfer->sumlen += xfer->frlengths[x];
1648 if (xfer->sumlen < xfer->frlengths[x]) {
1649 /* length wrapped around */
1651 usbd_transfer_done(xfer, USB_ERR_INVAL);
1652 USB_BUS_UNLOCK(bus);
1657 /* clear some internal flags */
1659 xfer->flags_int.short_xfer_ok = 0;
1660 xfer->flags_int.short_frames_ok = 0;
1662 /* check if this is a control transfer */
1664 if (xfer->flags_int.control_xfr) {
1666 if (usbd_setup_ctrl_transfer(xfer)) {
1668 usbd_transfer_done(xfer, USB_ERR_STALLED);
1669 USB_BUS_UNLOCK(bus);
1674 * Setup filtered version of some transfer flags,
1675 * in case of data read direction
1677 if (USB_GET_DATA_ISREAD(xfer)) {
1679 if (xfer->flags.short_frames_ok) {
1680 xfer->flags_int.short_xfer_ok = 1;
1681 xfer->flags_int.short_frames_ok = 1;
1682 } else if (xfer->flags.short_xfer_ok) {
1683 xfer->flags_int.short_xfer_ok = 1;
1685 /* check for control transfer */
1686 if (xfer->flags_int.control_xfr) {
1688 * 1) Control transfers do not support
1689 * reception of multiple short USB
1690 * frames in host mode and device side
1691 * mode, with exception of:
1693 * 2) Due to sometimes buggy device
1694 * side firmware we need to do a
1695 * STATUS stage in case of short
1696 * control transfers in USB host mode.
1697 * The STATUS stage then becomes the
1698 * "alt_next" to the DATA stage.
1700 xfer->flags_int.short_frames_ok = 1;
1705 * Check if BUS-DMA support is enabled and try to load virtual
1706 * buffers into DMA, if any:
1709 if (xfer->flags_int.bdma_enable) {
1710 /* insert the USB transfer last in the BUS-DMA queue */
1711 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1716 * Enter the USB transfer into the Host Controller or
1717 * Device Controller schedule:
1719 usbd_pipe_enter(xfer);
1722 /*------------------------------------------------------------------------*
1723 * usbd_pipe_enter - factored out code
1724 *------------------------------------------------------------------------*/
1726 usbd_pipe_enter(struct usb_xfer *xfer)
1728 struct usb_endpoint *ep;
1730 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1732 USB_BUS_LOCK(xfer->xroot->bus);
1734 ep = xfer->endpoint;
1738 /* the transfer can now be cancelled */
1739 xfer->flags_int.can_cancel_immed = 1;
1741 /* enter the transfer */
1742 (ep->methods->enter) (xfer);
1744 /* check for transfer error */
1746 /* some error has happened */
1747 usbd_transfer_done(xfer, 0);
1748 USB_BUS_UNLOCK(xfer->xroot->bus);
1752 /* start the transfer */
1753 usb_command_wrapper(&ep->endpoint_q, xfer);
1754 USB_BUS_UNLOCK(xfer->xroot->bus);
1757 /*------------------------------------------------------------------------*
1758 * usbd_transfer_start - start an USB transfer
1760 * NOTE: Calling this function more than one time will only
1761 * result in a single transfer start, until the USB transfer
1763 *------------------------------------------------------------------------*/
1765 usbd_transfer_start(struct usb_xfer *xfer)
1768 /* transfer is gone */
1771 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1773 /* mark the USB transfer started */
1775 if (!xfer->flags_int.started) {
1776 /* lock the BUS lock to avoid races updating flags_int */
1777 USB_BUS_LOCK(xfer->xroot->bus);
1778 xfer->flags_int.started = 1;
1779 USB_BUS_UNLOCK(xfer->xroot->bus);
1781 /* check if the USB transfer callback is already transferring */
1783 if (xfer->flags_int.transferring) {
1786 USB_BUS_LOCK(xfer->xroot->bus);
1787 /* call the USB transfer callback */
1788 usbd_callback_ss_done_defer(xfer);
1789 USB_BUS_UNLOCK(xfer->xroot->bus);
1792 /*------------------------------------------------------------------------*
1793 * usbd_transfer_stop - stop an USB transfer
1795 * NOTE: Calling this function more than one time will only
1796 * result in a single transfer stop.
1797 * NOTE: When this function returns it is not safe to free nor
1798 * reuse any DMA buffers. See "usbd_transfer_drain()".
1799 *------------------------------------------------------------------------*/
1801 usbd_transfer_stop(struct usb_xfer *xfer)
1803 struct usb_endpoint *ep;
1806 /* transfer is gone */
1809 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1811 /* check if the USB transfer was ever opened */
1813 if (!xfer->flags_int.open) {
1814 if (xfer->flags_int.started) {
1815 /* nothing to do except clearing the "started" flag */
1816 /* lock the BUS lock to avoid races updating flags_int */
1817 USB_BUS_LOCK(xfer->xroot->bus);
1818 xfer->flags_int.started = 0;
1819 USB_BUS_UNLOCK(xfer->xroot->bus);
1823 /* try to stop the current USB transfer */
1825 USB_BUS_LOCK(xfer->xroot->bus);
1826 /* override any previous error */
1827 xfer->error = USB_ERR_CANCELLED;
1830 * Clear "open" and "started" when both private and USB lock
1831 * is locked so that we don't get a race updating "flags_int"
1833 xfer->flags_int.open = 0;
1834 xfer->flags_int.started = 0;
1837 * Check if we can cancel the USB transfer immediately.
1839 if (xfer->flags_int.transferring) {
1840 if (xfer->flags_int.can_cancel_immed &&
1841 (!xfer->flags_int.did_close)) {
1844 * The following will lead to an USB_ERR_CANCELLED
1845 * error code being passed to the USB callback.
1847 (xfer->endpoint->methods->close) (xfer);
1848 /* only close once */
1849 xfer->flags_int.did_close = 1;
1851 /* need to wait for the next done callback */
1856 /* close here and now */
1857 (xfer->endpoint->methods->close) (xfer);
1860 * Any additional DMA delay is done by
1861 * "usbd_transfer_unsetup()".
1865 * Special case. Check if we need to restart a blocked
1868 ep = xfer->endpoint;
1871 * If the current USB transfer is completing we need
1872 * to start the next one:
1874 if (ep->endpoint_q.curr == xfer) {
1875 usb_command_wrapper(&ep->endpoint_q, NULL);
1879 USB_BUS_UNLOCK(xfer->xroot->bus);
1882 /*------------------------------------------------------------------------*
1883 * usbd_transfer_pending
1885 * This function will check if an USB transfer is pending which is a
1886 * little bit complicated!
1889 * 1: Pending: The USB transfer will receive a callback in the future.
1890 *------------------------------------------------------------------------*/
1892 usbd_transfer_pending(struct usb_xfer *xfer)
1894 struct usb_xfer_root *info;
1895 struct usb_xfer_queue *pq;
1898 /* transfer is gone */
1901 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1903 if (xfer->flags_int.transferring) {
1907 USB_BUS_LOCK(xfer->xroot->bus);
1908 if (xfer->wait_queue) {
1909 /* we are waiting on a queue somewhere */
1910 USB_BUS_UNLOCK(xfer->xroot->bus);
1916 if (pq->curr == xfer) {
1917 /* we are currently scheduled for callback */
1918 USB_BUS_UNLOCK(xfer->xroot->bus);
1921 /* we are not pending */
1922 USB_BUS_UNLOCK(xfer->xroot->bus);
1926 /*------------------------------------------------------------------------*
1927 * usbd_transfer_drain
1929 * This function will stop the USB transfer and wait for any
1930 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1931 * are loaded into DMA can safely be freed or reused after that this
1932 * function has returned.
1933 *------------------------------------------------------------------------*/
1935 usbd_transfer_drain(struct usb_xfer *xfer)
1937 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1938 "usbd_transfer_drain can sleep!");
1941 /* transfer is gone */
1944 if (xfer->xroot->xfer_mtx != &Giant) {
1945 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1947 USB_XFER_LOCK(xfer);
1949 usbd_transfer_stop(xfer);
1951 while (usbd_transfer_pending(xfer) ||
1952 xfer->flags_int.doing_callback) {
1955 * It is allowed that the callback can drop its
1956 * transfer mutex. In that case checking only
1957 * "usbd_transfer_pending()" is not enough to tell if
1958 * the USB transfer is fully drained. We also need to
1959 * check the internal "doing_callback" flag.
1961 xfer->flags_int.draining = 1;
1964 * Wait until the current outstanding USB
1965 * transfer is complete !
1967 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1969 USB_XFER_UNLOCK(xfer);
1972 struct usb_page_cache *
1973 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1975 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1977 return (&xfer->frbuffers[frindex]);
1981 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
1983 struct usb_page_search page_info;
1985 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1987 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
1988 return (page_info.buffer);
1991 /*------------------------------------------------------------------------*
1992 * usbd_xfer_get_fps_shift
1994 * The following function is only useful for isochronous transfers. It
1995 * returns how many times the frame execution rate has been shifted
2001 *------------------------------------------------------------------------*/
2003 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2005 return (xfer->fps_shift);
2009 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2011 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2013 return (xfer->frlengths[frindex]);
2016 /*------------------------------------------------------------------------*
2017 * usbd_xfer_set_frame_data
2019 * This function sets the pointer of the buffer that should
2020 * loaded directly into DMA for the given USB frame. Passing "ptr"
2021 * equal to NULL while the corresponding "frlength" is greater
2022 * than zero gives undefined results!
2023 *------------------------------------------------------------------------*/
2025 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2026 void *ptr, usb_frlength_t len)
2028 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2030 /* set virtual address to load and length */
2031 xfer->frbuffers[frindex].buffer = ptr;
2032 usbd_xfer_set_frame_len(xfer, frindex, len);
2036 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2037 void **ptr, int *len)
2039 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2042 *ptr = xfer->frbuffers[frindex].buffer;
2044 *len = xfer->frlengths[frindex];
2047 /*------------------------------------------------------------------------*
2048 * usbd_xfer_old_frame_length
2050 * This function returns the framelength of the given frame at the
2051 * time the transfer was submitted. This function can be used to
2052 * compute the starting data pointer of the next isochronous frame
2053 * when an isochronous transfer has completed.
2054 *------------------------------------------------------------------------*/
2056 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2058 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2060 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2064 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2068 *actlen = xfer->actlen;
2070 *sumlen = xfer->sumlen;
2071 if (aframes != NULL)
2072 *aframes = xfer->aframes;
2073 if (nframes != NULL)
2074 *nframes = xfer->nframes;
2077 /*------------------------------------------------------------------------*
2078 * usbd_xfer_set_frame_offset
2080 * This function sets the frame data buffer offset relative to the beginning
2081 * of the USB DMA buffer allocated for this USB transfer.
2082 *------------------------------------------------------------------------*/
2084 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2085 usb_frcount_t frindex)
2087 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2088 "when the USB buffer is external\n"));
2089 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2091 /* set virtual address to load */
2092 xfer->frbuffers[frindex].buffer =
2093 USB_ADD_BYTES(xfer->local_buffer, offset);
2097 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2103 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2109 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2115 usbd_xfer_max_frames(struct usb_xfer *xfer)
2117 return (xfer->max_frame_count);
2121 usbd_xfer_max_len(struct usb_xfer *xfer)
2123 return (xfer->max_data_length);
2127 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2129 return (xfer->max_frame_size);
2133 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2136 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2138 xfer->frlengths[frindex] = len;
2141 /*------------------------------------------------------------------------*
2142 * usb_callback_proc - factored out code
2144 * This function performs USB callbacks.
2145 *------------------------------------------------------------------------*/
2147 usb_callback_proc(struct usb_proc_msg *_pm)
2149 struct usb_done_msg *pm = (void *)_pm;
2150 struct usb_xfer_root *info = pm->xroot;
2152 /* Change locking order */
2153 USB_BUS_UNLOCK(info->bus);
2156 * We exploit the fact that the mutex is the same for all
2157 * callbacks that will be called from this thread:
2159 mtx_lock(info->xfer_mtx);
2160 USB_BUS_LOCK(info->bus);
2162 /* Continue where we lost track */
2163 usb_command_wrapper(&info->done_q,
2166 mtx_unlock(info->xfer_mtx);
2169 /*------------------------------------------------------------------------*
2170 * usbd_callback_ss_done_defer
2172 * This function will defer the start, stop and done callback to the
2174 *------------------------------------------------------------------------*/
2176 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2178 struct usb_xfer_root *info = xfer->xroot;
2179 struct usb_xfer_queue *pq = &info->done_q;
2181 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2183 if (pq->curr != xfer) {
2184 usbd_transfer_enqueue(pq, xfer);
2186 if (!pq->recurse_1) {
2189 * We have to postpone the callback due to the fact we
2190 * will have a Lock Order Reversal, LOR, if we try to
2193 if (usb_proc_msignal(info->done_p,
2194 &info->done_m[0], &info->done_m[1])) {
2198 /* clear second recurse flag */
2205 /*------------------------------------------------------------------------*
2206 * usbd_callback_wrapper
2208 * This is a wrapper for USB callbacks. This wrapper does some
2209 * auto-magic things like figuring out if we can call the callback
2210 * directly from the current context or if we need to wakeup the
2211 * interrupt process.
2212 *------------------------------------------------------------------------*/
2214 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2216 struct usb_xfer *xfer = pq->curr;
2217 struct usb_xfer_root *info = xfer->xroot;
2219 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2220 if (!mtx_owned(info->xfer_mtx)) {
2222 * Cases that end up here:
2224 * 5) HW interrupt done callback or other source.
2226 DPRINTFN(3, "case 5\n");
2229 * We have to postpone the callback due to the fact we
2230 * will have a Lock Order Reversal, LOR, if we try to
2233 if (usb_proc_msignal(info->done_p,
2234 &info->done_m[0], &info->done_m[1])) {
2240 * Cases that end up here:
2242 * 1) We are starting a transfer
2243 * 2) We are prematurely calling back a transfer
2244 * 3) We are stopping a transfer
2245 * 4) We are doing an ordinary callback
2247 DPRINTFN(3, "case 1-4\n");
2248 /* get next USB transfer in the queue */
2249 info->done_q.curr = NULL;
2251 /* set flag in case of drain */
2252 xfer->flags_int.doing_callback = 1;
2254 USB_BUS_UNLOCK(info->bus);
2255 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2257 /* set correct USB state for callback */
2258 if (!xfer->flags_int.transferring) {
2259 xfer->usb_state = USB_ST_SETUP;
2260 if (!xfer->flags_int.started) {
2261 /* we got stopped before we even got started */
2262 USB_BUS_LOCK(info->bus);
2267 if (usbd_callback_wrapper_sub(xfer)) {
2268 /* the callback has been deferred */
2269 USB_BUS_LOCK(info->bus);
2273 /* decrement power reference */
2274 usbd_transfer_power_ref(xfer, -1);
2276 xfer->flags_int.transferring = 0;
2279 xfer->usb_state = USB_ST_ERROR;
2281 /* set transferred state */
2282 xfer->usb_state = USB_ST_TRANSFERRED;
2284 /* sync DMA memory, if any */
2285 if (xfer->flags_int.bdma_enable &&
2286 (!xfer->flags_int.bdma_no_post_sync)) {
2287 usb_bdma_post_sync(xfer);
2294 if (xfer->usb_state != USB_ST_SETUP) {
2295 USB_BUS_LOCK(info->bus);
2296 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2297 USB_BUS_UNLOCK(info->bus);
2300 /* call processing routine */
2301 (xfer->callback) (xfer, xfer->error);
2303 /* pickup the USB mutex again */
2304 USB_BUS_LOCK(info->bus);
2307 * Check if we got started after that we got cancelled, but
2308 * before we managed to do the callback.
2310 if ((!xfer->flags_int.open) &&
2311 (xfer->flags_int.started) &&
2312 (xfer->usb_state == USB_ST_ERROR)) {
2313 /* clear flag in case of drain */
2314 xfer->flags_int.doing_callback = 0;
2315 /* try to loop, but not recursivly */
2316 usb_command_wrapper(&info->done_q, xfer);
2321 /* clear flag in case of drain */
2322 xfer->flags_int.doing_callback = 0;
2325 * Check if we are draining.
2327 if (xfer->flags_int.draining &&
2328 (!xfer->flags_int.transferring)) {
2329 /* "usbd_transfer_drain()" is waiting for end of transfer */
2330 xfer->flags_int.draining = 0;
2331 cv_broadcast(&info->cv_drain);
2334 /* do the next callback, if any */
2335 usb_command_wrapper(&info->done_q,
2339 /*------------------------------------------------------------------------*
2340 * usb_dma_delay_done_cb
2342 * This function is called when the DMA delay has been exectuded, and
2343 * will make sure that the callback is called to complete the USB
2344 * transfer. This code path is ususally only used when there is an USB
2345 * error like USB_ERR_CANCELLED.
2346 *------------------------------------------------------------------------*/
2348 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2350 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2352 DPRINTFN(3, "Completed %p\n", xfer);
2354 /* queue callback for execution, again */
2355 usbd_transfer_done(xfer, 0);
2358 /*------------------------------------------------------------------------*
2359 * usbd_transfer_dequeue
2361 * - This function is used to remove an USB transfer from a USB
2364 * - This function can be called multiple times in a row.
2365 *------------------------------------------------------------------------*/
2367 usbd_transfer_dequeue(struct usb_xfer *xfer)
2369 struct usb_xfer_queue *pq;
2371 pq = xfer->wait_queue;
2373 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2374 xfer->wait_queue = NULL;
2378 /*------------------------------------------------------------------------*
2379 * usbd_transfer_enqueue
2381 * - This function is used to insert an USB transfer into a USB *
2384 * - This function can be called multiple times in a row.
2385 *------------------------------------------------------------------------*/
2387 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2390 * Insert the USB transfer into the queue, if it is not
2391 * already on a USB transfer queue:
2393 if (xfer->wait_queue == NULL) {
2394 xfer->wait_queue = pq;
2395 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2399 /*------------------------------------------------------------------------*
2400 * usbd_transfer_done
2402 * - This function is used to remove an USB transfer from the busdma,
2403 * pipe or interrupt queue.
2405 * - This function is used to queue the USB transfer on the done
2408 * - This function is used to stop any USB transfer timeouts.
2409 *------------------------------------------------------------------------*/
2411 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2413 struct usb_xfer_root *info = xfer->xroot;
2415 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2417 DPRINTF("err=%s\n", usbd_errstr(error));
2420 * If we are not transferring then just return.
2421 * This can happen during transfer cancel.
2423 if (!xfer->flags_int.transferring) {
2424 DPRINTF("not transferring\n");
2425 /* end of control transfer, if any */
2426 xfer->flags_int.control_act = 0;
2429 /* only set transfer error, if not already set */
2430 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2431 xfer->error = error;
2433 /* stop any callouts */
2434 usb_callout_stop(&xfer->timeout_handle);
2437 * If we are waiting on a queue, just remove the USB transfer
2438 * from the queue, if any. We should have the required locks
2439 * locked to do the remove when this function is called.
2441 usbd_transfer_dequeue(xfer);
2444 if (mtx_owned(info->xfer_mtx)) {
2445 struct usb_xfer_queue *pq;
2448 * If the private USB lock is not locked, then we assume
2449 * that the BUS-DMA load stage has been passed:
2453 if (pq->curr == xfer) {
2454 /* start the next BUS-DMA load, if any */
2455 usb_command_wrapper(pq, NULL);
2459 /* keep some statistics */
2461 info->bus->stats_err.uds_requests
2462 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2464 info->bus->stats_ok.uds_requests
2465 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2468 /* call the USB transfer callback */
2469 usbd_callback_ss_done_defer(xfer);
2472 /*------------------------------------------------------------------------*
2473 * usbd_transfer_start_cb
2475 * This function is called to start the USB transfer when
2476 * "xfer->interval" is greater than zero, and and the endpoint type is
2478 *------------------------------------------------------------------------*/
2480 usbd_transfer_start_cb(void *arg)
2482 struct usb_xfer *xfer = arg;
2483 struct usb_endpoint *ep = xfer->endpoint;
2485 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2490 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2493 /* the transfer can now be cancelled */
2494 xfer->flags_int.can_cancel_immed = 1;
2496 /* start USB transfer, if no error */
2497 if (xfer->error == 0)
2498 (ep->methods->start) (xfer);
2500 /* check for transfer error */
2502 /* some error has happened */
2503 usbd_transfer_done(xfer, 0);
2507 /*------------------------------------------------------------------------*
2508 * usbd_xfer_set_stall
2510 * This function is used to set the stall flag outside the
2511 * callback. This function is NULL safe.
2512 *------------------------------------------------------------------------*/
2514 usbd_xfer_set_stall(struct usb_xfer *xfer)
2520 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2522 /* avoid any races by locking the USB mutex */
2523 USB_BUS_LOCK(xfer->xroot->bus);
2524 xfer->flags.stall_pipe = 1;
2525 USB_BUS_UNLOCK(xfer->xroot->bus);
2529 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2531 return (xfer->endpoint->is_stalled);
2534 /*------------------------------------------------------------------------*
2535 * usbd_transfer_clear_stall
2537 * This function is used to clear the stall flag outside the
2538 * callback. This function is NULL safe.
2539 *------------------------------------------------------------------------*/
2541 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2547 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2549 /* avoid any races by locking the USB mutex */
2550 USB_BUS_LOCK(xfer->xroot->bus);
2552 xfer->flags.stall_pipe = 0;
2554 USB_BUS_UNLOCK(xfer->xroot->bus);
2557 /*------------------------------------------------------------------------*
2560 * This function is used to add an USB transfer to the pipe transfer list.
2561 *------------------------------------------------------------------------*/
2563 usbd_pipe_start(struct usb_xfer_queue *pq)
2565 struct usb_endpoint *ep;
2566 struct usb_xfer *xfer;
2570 ep = xfer->endpoint;
2572 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2575 * If the endpoint is already stalled we do nothing !
2577 if (ep->is_stalled) {
2581 * Check if we are supposed to stall the endpoint:
2583 if (xfer->flags.stall_pipe) {
2584 struct usb_device *udev;
2585 struct usb_xfer_root *info;
2587 /* clear stall command */
2588 xfer->flags.stall_pipe = 0;
2590 /* get pointer to USB device */
2595 * Only stall BULK and INTERRUPT endpoints.
2597 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2598 if ((type == UE_BULK) ||
2599 (type == UE_INTERRUPT)) {
2604 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2605 (udev->bus->methods->set_stall) (
2606 udev, NULL, ep, &did_stall);
2607 } else if (udev->ctrl_xfer[1]) {
2608 info = udev->ctrl_xfer[1]->xroot;
2610 &info->bus->non_giant_callback_proc,
2611 &udev->cs_msg[0], &udev->cs_msg[1]);
2613 /* should not happen */
2614 DPRINTFN(0, "No stall handler\n");
2617 * Check if we should stall. Some USB hardware
2618 * handles set- and clear-stall in hardware.
2622 * The transfer will be continued when
2623 * the clear-stall control endpoint
2624 * message is received.
2629 } else if (type == UE_ISOCHRONOUS) {
2632 * Make sure any FIFO overflow or other FIFO
2633 * error conditions go away by resetting the
2634 * endpoint FIFO through the clear stall
2637 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2638 (udev->bus->methods->clear_stall) (udev, ep);
2642 /* Set or clear stall complete - special case */
2643 if (xfer->nframes == 0) {
2644 /* we are complete */
2646 usbd_transfer_done(xfer, 0);
2652 * 1) Start the first transfer queued.
2654 * 2) Re-start the current USB transfer.
2657 * Check if there should be any
2658 * pre transfer start delay:
2660 if (xfer->interval > 0) {
2661 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2662 if ((type == UE_BULK) ||
2663 (type == UE_CONTROL)) {
2664 usbd_transfer_timeout_ms(xfer,
2665 &usbd_transfer_start_cb,
2673 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2675 /* the transfer can now be cancelled */
2676 xfer->flags_int.can_cancel_immed = 1;
2678 /* start USB transfer, if no error */
2679 if (xfer->error == 0)
2680 (ep->methods->start) (xfer);
2682 /* check for transfer error */
2684 /* some error has happened */
2685 usbd_transfer_done(xfer, 0);
2689 /*------------------------------------------------------------------------*
2690 * usbd_transfer_timeout_ms
2692 * This function is used to setup a timeout on the given USB
2693 * transfer. If the timeout has been deferred the callback given by
2694 * "cb" will get called after "ms" milliseconds.
2695 *------------------------------------------------------------------------*/
2697 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2698 void (*cb) (void *arg), usb_timeout_t ms)
2700 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2703 usb_callout_reset(&xfer->timeout_handle,
2704 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2707 /*------------------------------------------------------------------------*
2708 * usbd_callback_wrapper_sub
2710 * - This function will update variables in an USB transfer after
2711 * that the USB transfer is complete.
2713 * - This function is used to start the next USB transfer on the
2714 * ep transfer queue, if any.
2716 * NOTE: In some special cases the USB transfer will not be removed from
2717 * the pipe queue, but remain first. To enforce USB transfer removal call
2718 * this function passing the error code "USB_ERR_CANCELLED".
2722 * Else: The callback has been deferred.
2723 *------------------------------------------------------------------------*/
2725 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2727 struct usb_endpoint *ep;
2728 struct usb_bus *bus;
2731 bus = xfer->xroot->bus;
2733 if ((!xfer->flags_int.open) &&
2734 (!xfer->flags_int.did_close)) {
2737 (xfer->endpoint->methods->close) (xfer);
2738 USB_BUS_UNLOCK(bus);
2739 /* only close once */
2740 xfer->flags_int.did_close = 1;
2741 return (1); /* wait for new callback */
2744 * If we have a non-hardware induced error we
2745 * need to do the DMA delay!
2747 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2748 (xfer->error == USB_ERR_CANCELLED ||
2749 xfer->error == USB_ERR_TIMEOUT ||
2750 bus->methods->start_dma_delay != NULL)) {
2754 /* only delay once */
2755 xfer->flags_int.did_dma_delay = 1;
2757 /* we can not cancel this delay */
2758 xfer->flags_int.can_cancel_immed = 0;
2760 temp = usbd_get_dma_delay(xfer->xroot->udev);
2762 DPRINTFN(3, "DMA delay, %u ms, "
2763 "on %p\n", temp, xfer);
2768 * Some hardware solutions have dedicated
2769 * events when it is safe to free DMA'ed
2770 * memory. For the other hardware platforms we
2771 * use a static delay.
2773 if (bus->methods->start_dma_delay != NULL) {
2774 (bus->methods->start_dma_delay) (xfer);
2776 usbd_transfer_timeout_ms(xfer,
2777 (void (*)(void *))&usb_dma_delay_done_cb,
2780 USB_BUS_UNLOCK(bus);
2781 return (1); /* wait for new callback */
2784 /* check actual number of frames */
2785 if (xfer->aframes > xfer->nframes) {
2786 if (xfer->error == 0) {
2787 panic("%s: actual number of frames, %d, is "
2788 "greater than initial number of frames, %d\n",
2789 __FUNCTION__, xfer->aframes, xfer->nframes);
2791 /* just set some valid value */
2792 xfer->aframes = xfer->nframes;
2795 /* compute actual length */
2798 for (x = 0; x != xfer->aframes; x++) {
2799 xfer->actlen += xfer->frlengths[x];
2803 * Frames that were not transferred get zero actual length in
2804 * case the USB device driver does not check the actual number
2805 * of frames transferred, "xfer->aframes":
2807 for (; x < xfer->nframes; x++) {
2808 usbd_xfer_set_frame_len(xfer, x, 0);
2811 /* check actual length */
2812 if (xfer->actlen > xfer->sumlen) {
2813 if (xfer->error == 0) {
2814 panic("%s: actual length, %d, is greater than "
2815 "initial length, %d\n",
2816 __FUNCTION__, xfer->actlen, xfer->sumlen);
2818 /* just set some valid value */
2819 xfer->actlen = xfer->sumlen;
2822 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2823 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2824 xfer->aframes, xfer->nframes);
2827 /* end of control transfer, if any */
2828 xfer->flags_int.control_act = 0;
2830 #if USB_HAVE_TT_SUPPORT
2831 switch (xfer->error) {
2832 case USB_ERR_NORMAL_COMPLETION:
2833 case USB_ERR_SHORT_XFER:
2834 case USB_ERR_STALLED:
2835 case USB_ERR_CANCELLED:
2839 /* try to reset the TT, if any */
2841 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2842 USB_BUS_UNLOCK(bus);
2846 /* check if we should block the execution queue */
2847 if ((xfer->error != USB_ERR_CANCELLED) &&
2848 (xfer->flags.pipe_bof)) {
2849 DPRINTFN(2, "xfer=%p: Block On Failure "
2850 "on endpoint=%p\n", xfer, xfer->endpoint);
2854 /* check for short transfers */
2855 if (xfer->actlen < xfer->sumlen) {
2857 /* end of control transfer, if any */
2858 xfer->flags_int.control_act = 0;
2860 if (!xfer->flags_int.short_xfer_ok) {
2861 xfer->error = USB_ERR_SHORT_XFER;
2862 if (xfer->flags.pipe_bof) {
2863 DPRINTFN(2, "xfer=%p: Block On Failure on "
2864 "Short Transfer on endpoint %p.\n",
2865 xfer, xfer->endpoint);
2871 * Check if we are in the middle of a
2874 if (xfer->flags_int.control_act) {
2875 DPRINTFN(5, "xfer=%p: Control transfer "
2876 "active on endpoint=%p\n", xfer, xfer->endpoint);
2882 ep = xfer->endpoint;
2885 * If the current USB transfer is completing we need to start the
2889 if (ep->endpoint_q.curr == xfer) {
2890 usb_command_wrapper(&ep->endpoint_q, NULL);
2892 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2893 /* there is another USB transfer waiting */
2895 /* this is the last USB transfer */
2896 /* clear isochronous sync flag */
2897 xfer->endpoint->is_synced = 0;
2900 USB_BUS_UNLOCK(bus);
2905 /*------------------------------------------------------------------------*
2906 * usb_command_wrapper
2908 * This function is used to execute commands non-recursivly on an USB
2910 *------------------------------------------------------------------------*/
2912 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2916 * If the transfer is not already processing,
2919 if (pq->curr != xfer) {
2920 usbd_transfer_enqueue(pq, xfer);
2921 if (pq->curr != NULL) {
2922 /* something is already processing */
2923 DPRINTFN(6, "busy %p\n", pq->curr);
2928 /* Get next element in queue */
2932 if (!pq->recurse_1) {
2936 /* set both recurse flags */
2940 if (pq->curr == NULL) {
2941 xfer = TAILQ_FIRST(&pq->head);
2943 TAILQ_REMOVE(&pq->head, xfer,
2945 xfer->wait_queue = NULL;
2951 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2953 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2955 } while (!pq->recurse_2);
2957 /* clear first recurse flag */
2961 /* clear second recurse flag */
2966 /*------------------------------------------------------------------------*
2967 * usbd_ctrl_transfer_setup
2969 * This function is used to setup the default USB control endpoint
2971 *------------------------------------------------------------------------*/
2973 usbd_ctrl_transfer_setup(struct usb_device *udev)
2975 struct usb_xfer *xfer;
2977 uint8_t iface_index;
2979 /* check for root HUB */
2980 if (udev->parent_hub == NULL)
2984 xfer = udev->ctrl_xfer[0];
2986 USB_XFER_LOCK(xfer);
2988 ((xfer->address == udev->address) &&
2989 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2990 udev->ddesc.bMaxPacketSize));
2991 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2994 * NOTE: checking "xfer->address" and
2995 * starting the USB transfer must be
2998 usbd_transfer_start(xfer);
3001 USB_XFER_UNLOCK(xfer);
3008 * All parameters are exactly the same like before.
3014 * Update wMaxPacketSize for the default control endpoint:
3016 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3017 udev->ddesc.bMaxPacketSize;
3020 * Unsetup any existing USB transfer:
3022 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3025 * Reset clear stall error counter.
3027 udev->clear_stall_errors = 0;
3030 * Try to setup a new USB transfer for the
3031 * default control endpoint:
3034 if (usbd_transfer_setup(udev, &iface_index,
3035 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3036 &udev->device_mtx)) {
3037 DPRINTFN(0, "could not setup default "
3044 /*------------------------------------------------------------------------*
3045 * usbd_clear_data_toggle - factored out code
3047 * NOTE: the intention of this function is not to reset the hardware
3049 *------------------------------------------------------------------------*/
3051 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3053 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3055 /* check that we have a valid case */
3056 if (udev->flags.usb_mode == USB_MODE_HOST &&
3057 udev->parent_hub != NULL &&
3058 udev->bus->methods->clear_stall != NULL &&
3059 ep->methods != NULL) {
3060 (udev->bus->methods->clear_stall) (udev, ep);
3064 /*------------------------------------------------------------------------*
3065 * usbd_clear_data_toggle - factored out code
3067 * NOTE: the intention of this function is not to reset the hardware
3068 * data toggle on the USB device side.
3069 *------------------------------------------------------------------------*/
3071 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3073 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3075 USB_BUS_LOCK(udev->bus);
3076 ep->toggle_next = 0;
3077 /* some hardware needs a callback to clear the data toggle */
3078 usbd_clear_stall_locked(udev, ep);
3079 USB_BUS_UNLOCK(udev->bus);
3082 /*------------------------------------------------------------------------*
3083 * usbd_clear_stall_callback - factored out clear stall callback
3086 * xfer1: Clear Stall Control Transfer
3087 * xfer2: Stalled USB Transfer
3089 * This function is NULL safe.
3095 * Clear stall config example:
3097 * static const struct usb_config my_clearstall = {
3098 * .type = UE_CONTROL,
3100 * .direction = UE_DIR_ANY,
3101 * .interval = 50, //50 milliseconds
3102 * .bufsize = sizeof(struct usb_device_request),
3103 * .timeout = 1000, //1.000 seconds
3104 * .callback = &my_clear_stall_callback, // **
3105 * .usb_mode = USB_MODE_HOST,
3108 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3109 * passing the correct parameters.
3110 *------------------------------------------------------------------------*/
3112 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3113 struct usb_xfer *xfer2)
3115 struct usb_device_request req;
3117 if (xfer2 == NULL) {
3118 /* looks like we are tearing down */
3119 DPRINTF("NULL input parameter\n");
3122 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3123 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3125 switch (USB_GET_STATE(xfer1)) {
3129 * pre-clear the data toggle to DATA0 ("umass.c" and
3130 * "ata-usb.c" depends on this)
3133 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3135 /* setup a clear-stall packet */
3137 req.bmRequestType = UT_WRITE_ENDPOINT;
3138 req.bRequest = UR_CLEAR_FEATURE;
3139 USETW(req.wValue, UF_ENDPOINT_HALT);
3140 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3142 USETW(req.wLength, 0);
3145 * "usbd_transfer_setup_sub()" will ensure that
3146 * we have sufficient room in the buffer for
3147 * the request structure!
3150 /* copy in the transfer */
3152 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3155 xfer1->frlengths[0] = sizeof(req);
3158 usbd_transfer_submit(xfer1);
3161 case USB_ST_TRANSFERRED:
3164 default: /* Error */
3165 if (xfer1->error == USB_ERR_CANCELLED) {
3170 return (1); /* Clear Stall Finished */
3173 /*------------------------------------------------------------------------*
3174 * usbd_transfer_poll
3176 * The following function gets called from the USB keyboard driver and
3177 * UMASS when the system has paniced.
3179 * NOTE: It is currently not possible to resume normal operation on
3180 * the USB controller which has been polled, due to clearing of the
3181 * "up_dsleep" and "up_msleep" flags.
3182 *------------------------------------------------------------------------*/
3184 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3186 struct usb_xfer *xfer;
3187 struct usb_xfer_root *xroot;
3188 struct usb_device *udev;
3189 struct usb_proc_msg *pm;
3194 for (n = 0; n != max; n++) {
3195 /* Extra checks to avoid panic */
3198 continue; /* no USB transfer */
3199 xroot = xfer->xroot;
3201 continue; /* no USB root */
3204 continue; /* no USB device */
3205 if (udev->bus == NULL)
3206 continue; /* no BUS structure */
3207 if (udev->bus->methods == NULL)
3208 continue; /* no BUS methods */
3209 if (udev->bus->methods->xfer_poll == NULL)
3210 continue; /* no poll method */
3212 /* make sure that the BUS mutex is not locked */
3214 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3215 mtx_unlock(&xroot->udev->bus->bus_mtx);
3219 /* make sure that the transfer mutex is not locked */
3221 while (mtx_owned(xroot->xfer_mtx)) {
3222 mtx_unlock(xroot->xfer_mtx);
3226 /* Make sure cv_signal() and cv_broadcast() is not called */
3227 udev->bus->control_xfer_proc.up_msleep = 0;
3228 udev->bus->explore_proc.up_msleep = 0;
3229 udev->bus->giant_callback_proc.up_msleep = 0;
3230 udev->bus->non_giant_callback_proc.up_msleep = 0;
3232 /* poll USB hardware */
3233 (udev->bus->methods->xfer_poll) (udev->bus);
3235 USB_BUS_LOCK(xroot->bus);
3237 /* check for clear stall */
3238 if (udev->ctrl_xfer[1] != NULL) {
3240 /* poll clear stall start */
3241 pm = &udev->cs_msg[0].hdr;
3242 (pm->pm_callback) (pm);
3243 /* poll clear stall done thread */
3244 pm = &udev->ctrl_xfer[1]->
3245 xroot->done_m[0].hdr;
3246 (pm->pm_callback) (pm);
3249 /* poll done thread */
3250 pm = &xroot->done_m[0].hdr;
3251 (pm->pm_callback) (pm);
3253 USB_BUS_UNLOCK(xroot->bus);
3255 /* restore transfer mutex */
3257 mtx_lock(xroot->xfer_mtx);
3259 /* restore BUS mutex */
3261 mtx_lock(&xroot->udev->bus->bus_mtx);
3266 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3267 uint8_t type, enum usb_dev_speed speed)
3269 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3270 [USB_SPEED_LOW] = 8,
3271 [USB_SPEED_FULL] = 64,
3272 [USB_SPEED_HIGH] = 1024,
3273 [USB_SPEED_VARIABLE] = 1024,
3274 [USB_SPEED_SUPER] = 1024,
3277 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3278 [USB_SPEED_LOW] = 0, /* invalid */
3279 [USB_SPEED_FULL] = 1023,
3280 [USB_SPEED_HIGH] = 1024,
3281 [USB_SPEED_VARIABLE] = 3584,
3282 [USB_SPEED_SUPER] = 1024,
3285 static const uint16_t control_min[USB_SPEED_MAX] = {
3286 [USB_SPEED_LOW] = 8,
3287 [USB_SPEED_FULL] = 8,
3288 [USB_SPEED_HIGH] = 64,
3289 [USB_SPEED_VARIABLE] = 512,
3290 [USB_SPEED_SUPER] = 512,
3293 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3294 [USB_SPEED_LOW] = 8,
3295 [USB_SPEED_FULL] = 8,
3296 [USB_SPEED_HIGH] = 512,
3297 [USB_SPEED_VARIABLE] = 512,
3298 [USB_SPEED_SUPER] = 1024,
3303 memset(ptr, 0, sizeof(*ptr));
3307 ptr->range.max = intr_range_max[speed];
3309 case UE_ISOCHRONOUS:
3310 ptr->range.max = isoc_range_max[speed];
3313 if (type == UE_BULK)
3314 temp = bulk_min[speed];
3315 else /* UE_CONTROL */
3316 temp = control_min[speed];
3318 /* default is fixed */
3319 ptr->fixed[0] = temp;
3320 ptr->fixed[1] = temp;
3321 ptr->fixed[2] = temp;
3322 ptr->fixed[3] = temp;
3324 if (speed == USB_SPEED_FULL) {
3325 /* multiple sizes */
3330 if ((speed == USB_SPEED_VARIABLE) &&
3331 (type == UE_BULK)) {
3332 /* multiple sizes */
3333 ptr->fixed[2] = 1024;
3334 ptr->fixed[3] = 1536;
3341 usbd_xfer_softc(struct usb_xfer *xfer)
3343 return (xfer->priv_sc);
3347 usbd_xfer_get_priv(struct usb_xfer *xfer)
3349 return (xfer->priv_fifo);
3353 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3355 xfer->priv_fifo = ptr;
3359 usbd_xfer_state(struct usb_xfer *xfer)
3361 return (xfer->usb_state);
3365 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3368 case USB_FORCE_SHORT_XFER:
3369 xfer->flags.force_short_xfer = 1;
3371 case USB_SHORT_XFER_OK:
3372 xfer->flags.short_xfer_ok = 1;
3374 case USB_MULTI_SHORT_OK:
3375 xfer->flags.short_frames_ok = 1;
3377 case USB_MANUAL_STATUS:
3378 xfer->flags.manual_status = 1;
3384 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3387 case USB_FORCE_SHORT_XFER:
3388 xfer->flags.force_short_xfer = 0;
3390 case USB_SHORT_XFER_OK:
3391 xfer->flags.short_xfer_ok = 0;
3393 case USB_MULTI_SHORT_OK:
3394 xfer->flags.short_frames_ok = 0;
3396 case USB_MANUAL_STATUS:
3397 xfer->flags.manual_status = 0;
3403 * The following function returns in milliseconds when the isochronous
3404 * transfer was completed by the hardware. The returned value wraps
3405 * around 65536 milliseconds.
3408 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3410 return (xfer->isoc_time_complete);
3414 * The following function returns non-zero if the max packet size
3415 * field was clamped to a valid value. Else it returns zero.
3418 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3420 return (xfer->flags_int.maxp_was_clamped);