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_ctrl_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, udev->bus->dma_bits,
922 info->bus = udev->bus;
925 TAILQ_INIT(&info->done_q.head);
926 info->done_q.command = &usbd_callback_wrapper;
928 TAILQ_INIT(&info->dma_q.head);
929 info->dma_q.command = &usb_bdma_work_loop;
931 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
932 info->done_m[0].xroot = info;
933 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
934 info->done_m[1].xroot = info;
937 * In device side mode control endpoint
938 * requests need to run from a separate
939 * context, else there is a chance of
942 if (setup_start == usb_control_ep_cfg)
944 &udev->bus->control_xfer_proc;
945 else if (xfer_mtx == &Giant)
947 &udev->bus->giant_callback_proc;
950 &udev->bus->non_giant_callback_proc;
956 parm->size[0] += sizeof(info[0]);
958 for (setup = setup_start, n = 0;
959 setup != setup_end; setup++, n++) {
961 /* skip USB transfers without callbacks: */
962 if (setup->callback == NULL) {
965 /* see if there is a matching endpoint */
966 ep = usbd_get_endpoint(udev,
967 ifaces[setup->if_index], setup);
969 if ((ep == NULL) || (ep->methods == NULL)) {
970 if (setup->flags.no_pipe_ok)
972 if ((setup->usb_mode != USB_MODE_DUAL) &&
973 (setup->usb_mode != udev->flags.usb_mode))
975 parm->err = USB_ERR_NO_PIPE;
979 /* align data properly */
980 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
982 /* store current setup pointer */
983 parm->curr_setup = setup;
987 * Common initialization of the
988 * "usb_xfer" structure.
990 xfer = USB_ADD_BYTES(buf, parm->size[0]);
991 xfer->address = udev->address;
992 xfer->priv_sc = priv_sc;
995 usb_callout_init_mtx(&xfer->timeout_handle,
996 &udev->bus->bus_mtx, 0);
999 * Setup a dummy xfer, hence we are
1000 * writing to the "usb_xfer"
1001 * structure pointed to by "xfer"
1002 * before we have allocated any
1005 xfer = &udev->scratch.xfer_setup[0].dummy;
1006 memset(xfer, 0, sizeof(*xfer));
1010 /* set transfer endpoint pointer */
1011 xfer->endpoint = ep;
1013 parm->size[0] += sizeof(xfer[0]);
1014 parm->methods = xfer->endpoint->methods;
1015 parm->curr_xfer = xfer;
1018 * Call the Host or Device controller transfer
1021 (udev->bus->methods->xfer_setup) (parm);
1023 /* check for error */
1029 * Increment the endpoint refcount. This
1030 * basically prevents setting a new
1031 * configuration and alternate setting
1032 * when USB transfers are in use on
1033 * the given interface. Search the USB
1034 * code for "endpoint->refcount_alloc" if you
1035 * want more information.
1037 USB_BUS_LOCK(info->bus);
1038 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1039 parm->err = USB_ERR_INVAL;
1041 xfer->endpoint->refcount_alloc++;
1043 if (xfer->endpoint->refcount_alloc == 0)
1044 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1045 USB_BUS_UNLOCK(info->bus);
1048 * Whenever we set ppxfer[] then we
1049 * also need to increment the
1052 info->setup_refcount++;
1055 * Transfer is successfully setup and
1061 /* check for error */
1066 if (buf != NULL || parm->err != 0)
1069 /* if no transfers, nothing to do */
1073 /* align data properly */
1074 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1076 /* store offset temporarily */
1077 parm->size[1] = parm->size[0];
1080 * The number of DMA tags required depends on
1081 * the number of endpoints. The current estimate
1082 * for maximum number of DMA tags per endpoint
1085 parm->dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1088 * DMA tags for QH, TD, Data and more.
1090 parm->dma_tag_max += 8;
1092 parm->dma_tag_p += parm->dma_tag_max;
1094 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1097 /* align data properly */
1098 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1100 /* store offset temporarily */
1101 parm->size[3] = parm->size[0];
1103 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1106 /* align data properly */
1107 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1109 /* store offset temporarily */
1110 parm->size[4] = parm->size[0];
1112 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1115 /* store end offset temporarily */
1116 parm->size[5] = parm->size[0];
1118 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1121 /* store end offset temporarily */
1123 parm->size[2] = parm->size[0];
1125 /* align data properly */
1126 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1128 parm->size[6] = parm->size[0];
1130 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1133 /* align data properly */
1134 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1136 /* allocate zeroed memory */
1137 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1140 parm->err = USB_ERR_NOMEM;
1141 DPRINTFN(0, "cannot allocate memory block for "
1142 "configuration (%d bytes)\n",
1146 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1147 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1148 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1149 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1150 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1155 if (info->setup_refcount == 0) {
1157 * "usbd_transfer_unsetup_sub" will unlock
1158 * the bus mutex before returning !
1160 USB_BUS_LOCK(info->bus);
1162 /* something went wrong */
1163 usbd_transfer_unsetup_sub(info, 0);
1167 /* check if any errors happened */
1169 usbd_transfer_unsetup(ppxfer, n_setup);
1174 usbd_ctrl_unlock(udev);
1179 /*------------------------------------------------------------------------*
1180 * usbd_transfer_unsetup_sub - factored out code
1181 *------------------------------------------------------------------------*/
1183 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1186 struct usb_page_cache *pc;
1189 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1191 /* wait for any outstanding DMA operations */
1195 temp = usbd_get_dma_delay(info->udev);
1197 usb_pause_mtx(&info->bus->bus_mtx,
1198 USB_MS_TO_TICKS(temp));
1202 /* make sure that our done messages are not queued anywhere */
1203 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1205 USB_BUS_UNLOCK(info->bus);
1208 /* free DMA'able memory, if any */
1209 pc = info->dma_page_cache_start;
1210 while (pc != info->dma_page_cache_end) {
1211 usb_pc_free_mem(pc);
1215 /* free DMA maps in all "xfer->frbuffers" */
1216 pc = info->xfer_page_cache_start;
1217 while (pc != info->xfer_page_cache_end) {
1218 usb_pc_dmamap_destroy(pc);
1222 /* free all DMA tags */
1223 usb_dma_tag_unsetup(&info->dma_parent_tag);
1226 cv_destroy(&info->cv_drain);
1229 * free the "memory_base" last, hence the "info" structure is
1230 * contained within the "memory_base"!
1232 free(info->memory_base, M_USB);
1235 /*------------------------------------------------------------------------*
1236 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1238 * NOTE: All USB transfers in progress will get called back passing
1239 * the error code "USB_ERR_CANCELLED" before this function
1241 *------------------------------------------------------------------------*/
1243 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1245 struct usb_xfer *xfer;
1246 struct usb_xfer_root *info;
1247 uint8_t needs_delay = 0;
1249 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1250 "usbd_transfer_unsetup can sleep!");
1253 xfer = pxfer[n_setup];
1260 USB_XFER_LOCK(xfer);
1261 USB_BUS_LOCK(info->bus);
1264 * HINT: when you start/stop a transfer, it might be a
1265 * good idea to directly use the "pxfer[]" structure:
1267 * usbd_transfer_start(sc->pxfer[0]);
1268 * usbd_transfer_stop(sc->pxfer[0]);
1270 * That way, if your code has many parts that will not
1271 * stop running under the same lock, in other words
1272 * "xfer_mtx", the usbd_transfer_start and
1273 * usbd_transfer_stop functions will simply return
1274 * when they detect a NULL pointer argument.
1276 * To avoid any races we clear the "pxfer[]" pointer
1277 * while holding the private mutex of the driver:
1279 pxfer[n_setup] = NULL;
1281 USB_BUS_UNLOCK(info->bus);
1282 USB_XFER_UNLOCK(xfer);
1284 usbd_transfer_drain(xfer);
1287 if (xfer->flags_int.bdma_enable)
1291 * NOTE: default endpoint does not have an
1292 * interface, even if endpoint->iface_index == 0
1294 USB_BUS_LOCK(info->bus);
1295 xfer->endpoint->refcount_alloc--;
1296 USB_BUS_UNLOCK(info->bus);
1298 usb_callout_drain(&xfer->timeout_handle);
1300 USB_BUS_LOCK(info->bus);
1302 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1303 "reference count\n"));
1305 info->setup_refcount--;
1307 if (info->setup_refcount == 0) {
1308 usbd_transfer_unsetup_sub(info,
1311 USB_BUS_UNLOCK(info->bus);
1316 /*------------------------------------------------------------------------*
1317 * usbd_control_transfer_init - factored out code
1319 * In USB Device Mode we have to wait for the SETUP packet which
1320 * containst the "struct usb_device_request" structure, before we can
1321 * transfer any data. In USB Host Mode we already have the SETUP
1322 * packet at the moment the USB transfer is started. This leads us to
1323 * having to setup the USB transfer at two different places in
1324 * time. This function just contains factored out control transfer
1325 * initialisation code, so that we don't duplicate the code.
1326 *------------------------------------------------------------------------*/
1328 usbd_control_transfer_init(struct usb_xfer *xfer)
1330 struct usb_device_request req;
1332 /* copy out the USB request header */
1334 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1336 /* setup remainder */
1338 xfer->flags_int.control_rem = UGETW(req.wLength);
1340 /* copy direction to endpoint variable */
1342 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1344 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1347 /*------------------------------------------------------------------------*
1348 * usbd_control_transfer_did_data
1350 * This function returns non-zero if a control endpoint has
1351 * transferred the first DATA packet after the SETUP packet.
1352 * Else it returns zero.
1353 *------------------------------------------------------------------------*/
1355 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1357 struct usb_device_request req;
1359 /* SETUP packet is not yet sent */
1360 if (xfer->flags_int.control_hdr != 0)
1363 /* copy out the USB request header */
1364 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1366 /* compare remainder to the initial value */
1367 return (xfer->flags_int.control_rem != UGETW(req.wLength));
1370 /*------------------------------------------------------------------------*
1371 * usbd_setup_ctrl_transfer
1373 * This function handles initialisation of control transfers. Control
1374 * transfers are special in that regard that they can both transmit
1380 *------------------------------------------------------------------------*/
1382 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1386 /* Check for control endpoint stall */
1387 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1388 /* the control transfer is no longer active */
1389 xfer->flags_int.control_stall = 1;
1390 xfer->flags_int.control_act = 0;
1392 /* don't stall control transfer by default */
1393 xfer->flags_int.control_stall = 0;
1396 /* Check for invalid number of frames */
1397 if (xfer->nframes > 2) {
1399 * If you need to split a control transfer, you
1400 * have to do one part at a time. Only with
1401 * non-control transfers you can do multiple
1404 DPRINTFN(0, "Too many frames: %u\n",
1405 (unsigned int)xfer->nframes);
1410 * Check if there is a control
1411 * transfer in progress:
1413 if (xfer->flags_int.control_act) {
1415 if (xfer->flags_int.control_hdr) {
1417 /* clear send header flag */
1419 xfer->flags_int.control_hdr = 0;
1421 /* setup control transfer */
1422 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1423 usbd_control_transfer_init(xfer);
1426 /* get data length */
1432 /* the size of the SETUP structure is hardcoded ! */
1434 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1435 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1436 xfer->frlengths[0], sizeof(struct
1437 usb_device_request));
1440 /* check USB mode */
1441 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1443 /* check number of frames */
1444 if (xfer->nframes != 1) {
1446 * We need to receive the setup
1447 * message first so that we know the
1450 DPRINTF("Misconfigured transfer\n");
1454 * Set a dummy "control_rem" value. This
1455 * variable will be overwritten later by a
1456 * call to "usbd_control_transfer_init()" !
1458 xfer->flags_int.control_rem = 0xFFFF;
1461 /* setup "endpoint" and "control_rem" */
1463 usbd_control_transfer_init(xfer);
1466 /* set transfer-header flag */
1468 xfer->flags_int.control_hdr = 1;
1470 /* get data length */
1472 len = (xfer->sumlen - sizeof(struct usb_device_request));
1475 /* update did data flag */
1477 xfer->flags_int.control_did_data =
1478 usbd_control_transfer_did_data(xfer);
1480 /* check if there is a length mismatch */
1482 if (len > xfer->flags_int.control_rem) {
1483 DPRINTFN(0, "Length (%d) greater than "
1484 "remaining length (%d)\n", len,
1485 xfer->flags_int.control_rem);
1488 /* check if we are doing a short transfer */
1490 if (xfer->flags.force_short_xfer) {
1491 xfer->flags_int.control_rem = 0;
1493 if ((len != xfer->max_data_length) &&
1494 (len != xfer->flags_int.control_rem) &&
1495 (xfer->nframes != 1)) {
1496 DPRINTFN(0, "Short control transfer without "
1497 "force_short_xfer set\n");
1500 xfer->flags_int.control_rem -= len;
1503 /* the status part is executed when "control_act" is 0 */
1505 if ((xfer->flags_int.control_rem > 0) ||
1506 (xfer->flags.manual_status)) {
1507 /* don't execute the STATUS stage yet */
1508 xfer->flags_int.control_act = 1;
1511 if ((!xfer->flags_int.control_hdr) &&
1512 (xfer->nframes == 1)) {
1514 * This is not a valid operation!
1516 DPRINTFN(0, "Invalid parameter "
1521 /* time to execute the STATUS stage */
1522 xfer->flags_int.control_act = 0;
1524 return (0); /* success */
1527 return (1); /* failure */
1530 /*------------------------------------------------------------------------*
1531 * usbd_transfer_submit - start USB hardware for the given transfer
1533 * This function should only be called from the USB callback.
1534 *------------------------------------------------------------------------*/
1536 usbd_transfer_submit(struct usb_xfer *xfer)
1538 struct usb_xfer_root *info;
1539 struct usb_bus *bus;
1545 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1546 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1550 if (USB_DEBUG_VAR > 0) {
1553 usb_dump_endpoint(xfer->endpoint);
1555 USB_BUS_UNLOCK(bus);
1559 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1560 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1562 /* Only open the USB transfer once! */
1563 if (!xfer->flags_int.open) {
1564 xfer->flags_int.open = 1;
1569 (xfer->endpoint->methods->open) (xfer);
1570 USB_BUS_UNLOCK(bus);
1572 /* set "transferring" flag */
1573 xfer->flags_int.transferring = 1;
1576 /* increment power reference */
1577 usbd_transfer_power_ref(xfer, 1);
1580 * Check if the transfer is waiting on a queue, most
1581 * frequently the "done_q":
1583 if (xfer->wait_queue) {
1585 usbd_transfer_dequeue(xfer);
1586 USB_BUS_UNLOCK(bus);
1588 /* clear "did_dma_delay" flag */
1589 xfer->flags_int.did_dma_delay = 0;
1591 /* clear "did_close" flag */
1592 xfer->flags_int.did_close = 0;
1595 /* clear "bdma_setup" flag */
1596 xfer->flags_int.bdma_setup = 0;
1598 /* by default we cannot cancel any USB transfer immediately */
1599 xfer->flags_int.can_cancel_immed = 0;
1601 /* clear lengths and frame counts by default */
1606 /* clear any previous errors */
1609 /* Check if the device is still alive */
1610 if (info->udev->state < USB_STATE_POWERED) {
1613 * Must return cancelled error code else
1614 * device drivers can hang.
1616 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1617 USB_BUS_UNLOCK(bus);
1622 if (xfer->nframes == 0) {
1623 if (xfer->flags.stall_pipe) {
1625 * Special case - want to stall without transferring
1628 DPRINTF("xfer=%p nframes=0: stall "
1629 "or clear stall!\n", xfer);
1631 xfer->flags_int.can_cancel_immed = 1;
1632 /* start the transfer */
1633 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1634 USB_BUS_UNLOCK(bus);
1638 usbd_transfer_done(xfer, USB_ERR_INVAL);
1639 USB_BUS_UNLOCK(bus);
1642 /* compute some variables */
1644 for (x = 0; x != xfer->nframes; x++) {
1645 /* make a copy of the frlenghts[] */
1646 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1647 /* compute total transfer length */
1648 xfer->sumlen += xfer->frlengths[x];
1649 if (xfer->sumlen < xfer->frlengths[x]) {
1650 /* length wrapped around */
1652 usbd_transfer_done(xfer, USB_ERR_INVAL);
1653 USB_BUS_UNLOCK(bus);
1658 /* clear some internal flags */
1660 xfer->flags_int.short_xfer_ok = 0;
1661 xfer->flags_int.short_frames_ok = 0;
1663 /* check if this is a control transfer */
1665 if (xfer->flags_int.control_xfr) {
1667 if (usbd_setup_ctrl_transfer(xfer)) {
1669 usbd_transfer_done(xfer, USB_ERR_STALLED);
1670 USB_BUS_UNLOCK(bus);
1675 * Setup filtered version of some transfer flags,
1676 * in case of data read direction
1678 if (USB_GET_DATA_ISREAD(xfer)) {
1680 if (xfer->flags.short_frames_ok) {
1681 xfer->flags_int.short_xfer_ok = 1;
1682 xfer->flags_int.short_frames_ok = 1;
1683 } else if (xfer->flags.short_xfer_ok) {
1684 xfer->flags_int.short_xfer_ok = 1;
1686 /* check for control transfer */
1687 if (xfer->flags_int.control_xfr) {
1689 * 1) Control transfers do not support
1690 * reception of multiple short USB
1691 * frames in host mode and device side
1692 * mode, with exception of:
1694 * 2) Due to sometimes buggy device
1695 * side firmware we need to do a
1696 * STATUS stage in case of short
1697 * control transfers in USB host mode.
1698 * The STATUS stage then becomes the
1699 * "alt_next" to the DATA stage.
1701 xfer->flags_int.short_frames_ok = 1;
1706 * Check if BUS-DMA support is enabled and try to load virtual
1707 * buffers into DMA, if any:
1710 if (xfer->flags_int.bdma_enable) {
1711 /* insert the USB transfer last in the BUS-DMA queue */
1712 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1717 * Enter the USB transfer into the Host Controller or
1718 * Device Controller schedule:
1720 usbd_pipe_enter(xfer);
1723 /*------------------------------------------------------------------------*
1724 * usbd_pipe_enter - factored out code
1725 *------------------------------------------------------------------------*/
1727 usbd_pipe_enter(struct usb_xfer *xfer)
1729 struct usb_endpoint *ep;
1731 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1733 USB_BUS_LOCK(xfer->xroot->bus);
1735 ep = xfer->endpoint;
1739 /* the transfer can now be cancelled */
1740 xfer->flags_int.can_cancel_immed = 1;
1742 /* enter the transfer */
1743 (ep->methods->enter) (xfer);
1745 /* check for transfer error */
1747 /* some error has happened */
1748 usbd_transfer_done(xfer, 0);
1749 USB_BUS_UNLOCK(xfer->xroot->bus);
1753 /* start the transfer */
1754 usb_command_wrapper(&ep->endpoint_q, xfer);
1755 USB_BUS_UNLOCK(xfer->xroot->bus);
1758 /*------------------------------------------------------------------------*
1759 * usbd_transfer_start - start an USB transfer
1761 * NOTE: Calling this function more than one time will only
1762 * result in a single transfer start, until the USB transfer
1764 *------------------------------------------------------------------------*/
1766 usbd_transfer_start(struct usb_xfer *xfer)
1769 /* transfer is gone */
1772 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1774 /* mark the USB transfer started */
1776 if (!xfer->flags_int.started) {
1777 /* lock the BUS lock to avoid races updating flags_int */
1778 USB_BUS_LOCK(xfer->xroot->bus);
1779 xfer->flags_int.started = 1;
1780 USB_BUS_UNLOCK(xfer->xroot->bus);
1782 /* check if the USB transfer callback is already transferring */
1784 if (xfer->flags_int.transferring) {
1787 USB_BUS_LOCK(xfer->xroot->bus);
1788 /* call the USB transfer callback */
1789 usbd_callback_ss_done_defer(xfer);
1790 USB_BUS_UNLOCK(xfer->xroot->bus);
1793 /*------------------------------------------------------------------------*
1794 * usbd_transfer_stop - stop an USB transfer
1796 * NOTE: Calling this function more than one time will only
1797 * result in a single transfer stop.
1798 * NOTE: When this function returns it is not safe to free nor
1799 * reuse any DMA buffers. See "usbd_transfer_drain()".
1800 *------------------------------------------------------------------------*/
1802 usbd_transfer_stop(struct usb_xfer *xfer)
1804 struct usb_endpoint *ep;
1807 /* transfer is gone */
1810 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1812 /* check if the USB transfer was ever opened */
1814 if (!xfer->flags_int.open) {
1815 if (xfer->flags_int.started) {
1816 /* nothing to do except clearing the "started" flag */
1817 /* lock the BUS lock to avoid races updating flags_int */
1818 USB_BUS_LOCK(xfer->xroot->bus);
1819 xfer->flags_int.started = 0;
1820 USB_BUS_UNLOCK(xfer->xroot->bus);
1824 /* try to stop the current USB transfer */
1826 USB_BUS_LOCK(xfer->xroot->bus);
1827 /* override any previous error */
1828 xfer->error = USB_ERR_CANCELLED;
1831 * Clear "open" and "started" when both private and USB lock
1832 * is locked so that we don't get a race updating "flags_int"
1834 xfer->flags_int.open = 0;
1835 xfer->flags_int.started = 0;
1838 * Check if we can cancel the USB transfer immediately.
1840 if (xfer->flags_int.transferring) {
1841 if (xfer->flags_int.can_cancel_immed &&
1842 (!xfer->flags_int.did_close)) {
1845 * The following will lead to an USB_ERR_CANCELLED
1846 * error code being passed to the USB callback.
1848 (xfer->endpoint->methods->close) (xfer);
1849 /* only close once */
1850 xfer->flags_int.did_close = 1;
1852 /* need to wait for the next done callback */
1857 /* close here and now */
1858 (xfer->endpoint->methods->close) (xfer);
1861 * Any additional DMA delay is done by
1862 * "usbd_transfer_unsetup()".
1866 * Special case. Check if we need to restart a blocked
1869 ep = xfer->endpoint;
1872 * If the current USB transfer is completing we need
1873 * to start the next one:
1875 if (ep->endpoint_q.curr == xfer) {
1876 usb_command_wrapper(&ep->endpoint_q, NULL);
1880 USB_BUS_UNLOCK(xfer->xroot->bus);
1883 /*------------------------------------------------------------------------*
1884 * usbd_transfer_pending
1886 * This function will check if an USB transfer is pending which is a
1887 * little bit complicated!
1890 * 1: Pending: The USB transfer will receive a callback in the future.
1891 *------------------------------------------------------------------------*/
1893 usbd_transfer_pending(struct usb_xfer *xfer)
1895 struct usb_xfer_root *info;
1896 struct usb_xfer_queue *pq;
1899 /* transfer is gone */
1902 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1904 if (xfer->flags_int.transferring) {
1908 USB_BUS_LOCK(xfer->xroot->bus);
1909 if (xfer->wait_queue) {
1910 /* we are waiting on a queue somewhere */
1911 USB_BUS_UNLOCK(xfer->xroot->bus);
1917 if (pq->curr == xfer) {
1918 /* we are currently scheduled for callback */
1919 USB_BUS_UNLOCK(xfer->xroot->bus);
1922 /* we are not pending */
1923 USB_BUS_UNLOCK(xfer->xroot->bus);
1927 /*------------------------------------------------------------------------*
1928 * usbd_transfer_drain
1930 * This function will stop the USB transfer and wait for any
1931 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1932 * are loaded into DMA can safely be freed or reused after that this
1933 * function has returned.
1934 *------------------------------------------------------------------------*/
1936 usbd_transfer_drain(struct usb_xfer *xfer)
1938 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1939 "usbd_transfer_drain can sleep!");
1942 /* transfer is gone */
1945 if (xfer->xroot->xfer_mtx != &Giant) {
1946 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1948 USB_XFER_LOCK(xfer);
1950 usbd_transfer_stop(xfer);
1952 while (usbd_transfer_pending(xfer) ||
1953 xfer->flags_int.doing_callback) {
1956 * It is allowed that the callback can drop its
1957 * transfer mutex. In that case checking only
1958 * "usbd_transfer_pending()" is not enough to tell if
1959 * the USB transfer is fully drained. We also need to
1960 * check the internal "doing_callback" flag.
1962 xfer->flags_int.draining = 1;
1965 * Wait until the current outstanding USB
1966 * transfer is complete !
1968 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1970 USB_XFER_UNLOCK(xfer);
1973 struct usb_page_cache *
1974 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1976 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1978 return (&xfer->frbuffers[frindex]);
1982 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
1984 struct usb_page_search page_info;
1986 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1988 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
1989 return (page_info.buffer);
1992 /*------------------------------------------------------------------------*
1993 * usbd_xfer_get_fps_shift
1995 * The following function is only useful for isochronous transfers. It
1996 * returns how many times the frame execution rate has been shifted
2002 *------------------------------------------------------------------------*/
2004 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2006 return (xfer->fps_shift);
2010 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2012 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2014 return (xfer->frlengths[frindex]);
2017 /*------------------------------------------------------------------------*
2018 * usbd_xfer_set_frame_data
2020 * This function sets the pointer of the buffer that should
2021 * loaded directly into DMA for the given USB frame. Passing "ptr"
2022 * equal to NULL while the corresponding "frlength" is greater
2023 * than zero gives undefined results!
2024 *------------------------------------------------------------------------*/
2026 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2027 void *ptr, usb_frlength_t len)
2029 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2031 /* set virtual address to load and length */
2032 xfer->frbuffers[frindex].buffer = ptr;
2033 usbd_xfer_set_frame_len(xfer, frindex, len);
2037 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2038 void **ptr, int *len)
2040 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2043 *ptr = xfer->frbuffers[frindex].buffer;
2045 *len = xfer->frlengths[frindex];
2048 /*------------------------------------------------------------------------*
2049 * usbd_xfer_old_frame_length
2051 * This function returns the framelength of the given frame at the
2052 * time the transfer was submitted. This function can be used to
2053 * compute the starting data pointer of the next isochronous frame
2054 * when an isochronous transfer has completed.
2055 *------------------------------------------------------------------------*/
2057 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2059 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2061 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2065 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2069 *actlen = xfer->actlen;
2071 *sumlen = xfer->sumlen;
2072 if (aframes != NULL)
2073 *aframes = xfer->aframes;
2074 if (nframes != NULL)
2075 *nframes = xfer->nframes;
2078 /*------------------------------------------------------------------------*
2079 * usbd_xfer_set_frame_offset
2081 * This function sets the frame data buffer offset relative to the beginning
2082 * of the USB DMA buffer allocated for this USB transfer.
2083 *------------------------------------------------------------------------*/
2085 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2086 usb_frcount_t frindex)
2088 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2089 "when the USB buffer is external\n"));
2090 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2092 /* set virtual address to load */
2093 xfer->frbuffers[frindex].buffer =
2094 USB_ADD_BYTES(xfer->local_buffer, offset);
2098 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2104 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2110 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2116 usbd_xfer_max_frames(struct usb_xfer *xfer)
2118 return (xfer->max_frame_count);
2122 usbd_xfer_max_len(struct usb_xfer *xfer)
2124 return (xfer->max_data_length);
2128 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2130 return (xfer->max_frame_size);
2134 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2137 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2139 xfer->frlengths[frindex] = len;
2142 /*------------------------------------------------------------------------*
2143 * usb_callback_proc - factored out code
2145 * This function performs USB callbacks.
2146 *------------------------------------------------------------------------*/
2148 usb_callback_proc(struct usb_proc_msg *_pm)
2150 struct usb_done_msg *pm = (void *)_pm;
2151 struct usb_xfer_root *info = pm->xroot;
2153 /* Change locking order */
2154 USB_BUS_UNLOCK(info->bus);
2157 * We exploit the fact that the mutex is the same for all
2158 * callbacks that will be called from this thread:
2160 mtx_lock(info->xfer_mtx);
2161 USB_BUS_LOCK(info->bus);
2163 /* Continue where we lost track */
2164 usb_command_wrapper(&info->done_q,
2167 mtx_unlock(info->xfer_mtx);
2170 /*------------------------------------------------------------------------*
2171 * usbd_callback_ss_done_defer
2173 * This function will defer the start, stop and done callback to the
2175 *------------------------------------------------------------------------*/
2177 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2179 struct usb_xfer_root *info = xfer->xroot;
2180 struct usb_xfer_queue *pq = &info->done_q;
2182 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2184 if (pq->curr != xfer) {
2185 usbd_transfer_enqueue(pq, xfer);
2187 if (!pq->recurse_1) {
2190 * We have to postpone the callback due to the fact we
2191 * will have a Lock Order Reversal, LOR, if we try to
2194 if (usb_proc_msignal(info->done_p,
2195 &info->done_m[0], &info->done_m[1])) {
2199 /* clear second recurse flag */
2206 /*------------------------------------------------------------------------*
2207 * usbd_callback_wrapper
2209 * This is a wrapper for USB callbacks. This wrapper does some
2210 * auto-magic things like figuring out if we can call the callback
2211 * directly from the current context or if we need to wakeup the
2212 * interrupt process.
2213 *------------------------------------------------------------------------*/
2215 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2217 struct usb_xfer *xfer = pq->curr;
2218 struct usb_xfer_root *info = xfer->xroot;
2220 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2221 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2223 * Cases that end up here:
2225 * 5) HW interrupt done callback or other source.
2227 DPRINTFN(3, "case 5\n");
2230 * We have to postpone the callback due to the fact we
2231 * will have a Lock Order Reversal, LOR, if we try to
2234 if (usb_proc_msignal(info->done_p,
2235 &info->done_m[0], &info->done_m[1])) {
2241 * Cases that end up here:
2243 * 1) We are starting a transfer
2244 * 2) We are prematurely calling back a transfer
2245 * 3) We are stopping a transfer
2246 * 4) We are doing an ordinary callback
2248 DPRINTFN(3, "case 1-4\n");
2249 /* get next USB transfer in the queue */
2250 info->done_q.curr = NULL;
2252 /* set flag in case of drain */
2253 xfer->flags_int.doing_callback = 1;
2255 USB_BUS_UNLOCK(info->bus);
2256 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2258 /* set correct USB state for callback */
2259 if (!xfer->flags_int.transferring) {
2260 xfer->usb_state = USB_ST_SETUP;
2261 if (!xfer->flags_int.started) {
2262 /* we got stopped before we even got started */
2263 USB_BUS_LOCK(info->bus);
2268 if (usbd_callback_wrapper_sub(xfer)) {
2269 /* the callback has been deferred */
2270 USB_BUS_LOCK(info->bus);
2274 /* decrement power reference */
2275 usbd_transfer_power_ref(xfer, -1);
2277 xfer->flags_int.transferring = 0;
2280 xfer->usb_state = USB_ST_ERROR;
2282 /* set transferred state */
2283 xfer->usb_state = USB_ST_TRANSFERRED;
2285 /* sync DMA memory, if any */
2286 if (xfer->flags_int.bdma_enable &&
2287 (!xfer->flags_int.bdma_no_post_sync)) {
2288 usb_bdma_post_sync(xfer);
2295 if (xfer->usb_state != USB_ST_SETUP) {
2296 USB_BUS_LOCK(info->bus);
2297 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2298 USB_BUS_UNLOCK(info->bus);
2301 /* call processing routine */
2302 (xfer->callback) (xfer, xfer->error);
2304 /* pickup the USB mutex again */
2305 USB_BUS_LOCK(info->bus);
2308 * Check if we got started after that we got cancelled, but
2309 * before we managed to do the callback.
2311 if ((!xfer->flags_int.open) &&
2312 (xfer->flags_int.started) &&
2313 (xfer->usb_state == USB_ST_ERROR)) {
2314 /* clear flag in case of drain */
2315 xfer->flags_int.doing_callback = 0;
2316 /* try to loop, but not recursivly */
2317 usb_command_wrapper(&info->done_q, xfer);
2322 /* clear flag in case of drain */
2323 xfer->flags_int.doing_callback = 0;
2326 * Check if we are draining.
2328 if (xfer->flags_int.draining &&
2329 (!xfer->flags_int.transferring)) {
2330 /* "usbd_transfer_drain()" is waiting for end of transfer */
2331 xfer->flags_int.draining = 0;
2332 cv_broadcast(&info->cv_drain);
2335 /* do the next callback, if any */
2336 usb_command_wrapper(&info->done_q,
2340 /*------------------------------------------------------------------------*
2341 * usb_dma_delay_done_cb
2343 * This function is called when the DMA delay has been exectuded, and
2344 * will make sure that the callback is called to complete the USB
2345 * transfer. This code path is ususally only used when there is an USB
2346 * error like USB_ERR_CANCELLED.
2347 *------------------------------------------------------------------------*/
2349 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2351 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2353 DPRINTFN(3, "Completed %p\n", xfer);
2355 /* queue callback for execution, again */
2356 usbd_transfer_done(xfer, 0);
2359 /*------------------------------------------------------------------------*
2360 * usbd_transfer_dequeue
2362 * - This function is used to remove an USB transfer from a USB
2365 * - This function can be called multiple times in a row.
2366 *------------------------------------------------------------------------*/
2368 usbd_transfer_dequeue(struct usb_xfer *xfer)
2370 struct usb_xfer_queue *pq;
2372 pq = xfer->wait_queue;
2374 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2375 xfer->wait_queue = NULL;
2379 /*------------------------------------------------------------------------*
2380 * usbd_transfer_enqueue
2382 * - This function is used to insert an USB transfer into a USB *
2385 * - This function can be called multiple times in a row.
2386 *------------------------------------------------------------------------*/
2388 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2391 * Insert the USB transfer into the queue, if it is not
2392 * already on a USB transfer queue:
2394 if (xfer->wait_queue == NULL) {
2395 xfer->wait_queue = pq;
2396 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2400 /*------------------------------------------------------------------------*
2401 * usbd_transfer_done
2403 * - This function is used to remove an USB transfer from the busdma,
2404 * pipe or interrupt queue.
2406 * - This function is used to queue the USB transfer on the done
2409 * - This function is used to stop any USB transfer timeouts.
2410 *------------------------------------------------------------------------*/
2412 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2414 struct usb_xfer_root *info = xfer->xroot;
2416 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2418 DPRINTF("err=%s\n", usbd_errstr(error));
2421 * If we are not transferring then just return.
2422 * This can happen during transfer cancel.
2424 if (!xfer->flags_int.transferring) {
2425 DPRINTF("not transferring\n");
2426 /* end of control transfer, if any */
2427 xfer->flags_int.control_act = 0;
2430 /* only set transfer error, if not already set */
2431 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2432 xfer->error = error;
2434 /* stop any callouts */
2435 usb_callout_stop(&xfer->timeout_handle);
2438 * If we are waiting on a queue, just remove the USB transfer
2439 * from the queue, if any. We should have the required locks
2440 * locked to do the remove when this function is called.
2442 usbd_transfer_dequeue(xfer);
2445 if (mtx_owned(info->xfer_mtx)) {
2446 struct usb_xfer_queue *pq;
2449 * If the private USB lock is not locked, then we assume
2450 * that the BUS-DMA load stage has been passed:
2454 if (pq->curr == xfer) {
2455 /* start the next BUS-DMA load, if any */
2456 usb_command_wrapper(pq, NULL);
2460 /* keep some statistics */
2462 info->bus->stats_err.uds_requests
2463 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2465 info->bus->stats_ok.uds_requests
2466 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2469 /* call the USB transfer callback */
2470 usbd_callback_ss_done_defer(xfer);
2473 /*------------------------------------------------------------------------*
2474 * usbd_transfer_start_cb
2476 * This function is called to start the USB transfer when
2477 * "xfer->interval" is greater than zero, and and the endpoint type is
2479 *------------------------------------------------------------------------*/
2481 usbd_transfer_start_cb(void *arg)
2483 struct usb_xfer *xfer = arg;
2484 struct usb_endpoint *ep = xfer->endpoint;
2486 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2491 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2494 /* the transfer can now be cancelled */
2495 xfer->flags_int.can_cancel_immed = 1;
2497 /* start USB transfer, if no error */
2498 if (xfer->error == 0)
2499 (ep->methods->start) (xfer);
2501 /* check for transfer error */
2503 /* some error has happened */
2504 usbd_transfer_done(xfer, 0);
2508 /*------------------------------------------------------------------------*
2509 * usbd_xfer_set_stall
2511 * This function is used to set the stall flag outside the
2512 * callback. This function is NULL safe.
2513 *------------------------------------------------------------------------*/
2515 usbd_xfer_set_stall(struct usb_xfer *xfer)
2521 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2523 /* avoid any races by locking the USB mutex */
2524 USB_BUS_LOCK(xfer->xroot->bus);
2525 xfer->flags.stall_pipe = 1;
2526 USB_BUS_UNLOCK(xfer->xroot->bus);
2530 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2532 return (xfer->endpoint->is_stalled);
2535 /*------------------------------------------------------------------------*
2536 * usbd_transfer_clear_stall
2538 * This function is used to clear the stall flag outside the
2539 * callback. This function is NULL safe.
2540 *------------------------------------------------------------------------*/
2542 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2548 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2550 /* avoid any races by locking the USB mutex */
2551 USB_BUS_LOCK(xfer->xroot->bus);
2553 xfer->flags.stall_pipe = 0;
2555 USB_BUS_UNLOCK(xfer->xroot->bus);
2558 /*------------------------------------------------------------------------*
2561 * This function is used to add an USB transfer to the pipe transfer list.
2562 *------------------------------------------------------------------------*/
2564 usbd_pipe_start(struct usb_xfer_queue *pq)
2566 struct usb_endpoint *ep;
2567 struct usb_xfer *xfer;
2571 ep = xfer->endpoint;
2573 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2576 * If the endpoint is already stalled we do nothing !
2578 if (ep->is_stalled) {
2582 * Check if we are supposed to stall the endpoint:
2584 if (xfer->flags.stall_pipe) {
2585 struct usb_device *udev;
2586 struct usb_xfer_root *info;
2588 /* clear stall command */
2589 xfer->flags.stall_pipe = 0;
2591 /* get pointer to USB device */
2596 * Only stall BULK and INTERRUPT endpoints.
2598 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2599 if ((type == UE_BULK) ||
2600 (type == UE_INTERRUPT)) {
2605 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2606 (udev->bus->methods->set_stall) (
2607 udev, NULL, ep, &did_stall);
2608 } else if (udev->ctrl_xfer[1]) {
2609 info = udev->ctrl_xfer[1]->xroot;
2611 &info->bus->non_giant_callback_proc,
2612 &udev->cs_msg[0], &udev->cs_msg[1]);
2614 /* should not happen */
2615 DPRINTFN(0, "No stall handler\n");
2618 * Check if we should stall. Some USB hardware
2619 * handles set- and clear-stall in hardware.
2623 * The transfer will be continued when
2624 * the clear-stall control endpoint
2625 * message is received.
2630 } else if (type == UE_ISOCHRONOUS) {
2633 * Make sure any FIFO overflow or other FIFO
2634 * error conditions go away by resetting the
2635 * endpoint FIFO through the clear stall
2638 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2639 (udev->bus->methods->clear_stall) (udev, ep);
2643 /* Set or clear stall complete - special case */
2644 if (xfer->nframes == 0) {
2645 /* we are complete */
2647 usbd_transfer_done(xfer, 0);
2653 * 1) Start the first transfer queued.
2655 * 2) Re-start the current USB transfer.
2658 * Check if there should be any
2659 * pre transfer start delay:
2661 if (xfer->interval > 0) {
2662 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2663 if ((type == UE_BULK) ||
2664 (type == UE_CONTROL)) {
2665 usbd_transfer_timeout_ms(xfer,
2666 &usbd_transfer_start_cb,
2674 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2676 /* the transfer can now be cancelled */
2677 xfer->flags_int.can_cancel_immed = 1;
2679 /* start USB transfer, if no error */
2680 if (xfer->error == 0)
2681 (ep->methods->start) (xfer);
2683 /* check for transfer error */
2685 /* some error has happened */
2686 usbd_transfer_done(xfer, 0);
2690 /*------------------------------------------------------------------------*
2691 * usbd_transfer_timeout_ms
2693 * This function is used to setup a timeout on the given USB
2694 * transfer. If the timeout has been deferred the callback given by
2695 * "cb" will get called after "ms" milliseconds.
2696 *------------------------------------------------------------------------*/
2698 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2699 void (*cb) (void *arg), usb_timeout_t ms)
2701 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2704 usb_callout_reset(&xfer->timeout_handle,
2705 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2708 /*------------------------------------------------------------------------*
2709 * usbd_callback_wrapper_sub
2711 * - This function will update variables in an USB transfer after
2712 * that the USB transfer is complete.
2714 * - This function is used to start the next USB transfer on the
2715 * ep transfer queue, if any.
2717 * NOTE: In some special cases the USB transfer will not be removed from
2718 * the pipe queue, but remain first. To enforce USB transfer removal call
2719 * this function passing the error code "USB_ERR_CANCELLED".
2723 * Else: The callback has been deferred.
2724 *------------------------------------------------------------------------*/
2726 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2728 struct usb_endpoint *ep;
2729 struct usb_bus *bus;
2732 bus = xfer->xroot->bus;
2734 if ((!xfer->flags_int.open) &&
2735 (!xfer->flags_int.did_close)) {
2738 (xfer->endpoint->methods->close) (xfer);
2739 USB_BUS_UNLOCK(bus);
2740 /* only close once */
2741 xfer->flags_int.did_close = 1;
2742 return (1); /* wait for new callback */
2745 * If we have a non-hardware induced error we
2746 * need to do the DMA delay!
2748 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2749 (xfer->error == USB_ERR_CANCELLED ||
2750 xfer->error == USB_ERR_TIMEOUT ||
2751 bus->methods->start_dma_delay != NULL)) {
2755 /* only delay once */
2756 xfer->flags_int.did_dma_delay = 1;
2758 /* we can not cancel this delay */
2759 xfer->flags_int.can_cancel_immed = 0;
2761 temp = usbd_get_dma_delay(xfer->xroot->udev);
2763 DPRINTFN(3, "DMA delay, %u ms, "
2764 "on %p\n", temp, xfer);
2769 * Some hardware solutions have dedicated
2770 * events when it is safe to free DMA'ed
2771 * memory. For the other hardware platforms we
2772 * use a static delay.
2774 if (bus->methods->start_dma_delay != NULL) {
2775 (bus->methods->start_dma_delay) (xfer);
2777 usbd_transfer_timeout_ms(xfer,
2778 (void (*)(void *))&usb_dma_delay_done_cb,
2781 USB_BUS_UNLOCK(bus);
2782 return (1); /* wait for new callback */
2785 /* check actual number of frames */
2786 if (xfer->aframes > xfer->nframes) {
2787 if (xfer->error == 0) {
2788 panic("%s: actual number of frames, %d, is "
2789 "greater than initial number of frames, %d\n",
2790 __FUNCTION__, xfer->aframes, xfer->nframes);
2792 /* just set some valid value */
2793 xfer->aframes = xfer->nframes;
2796 /* compute actual length */
2799 for (x = 0; x != xfer->aframes; x++) {
2800 xfer->actlen += xfer->frlengths[x];
2804 * Frames that were not transferred get zero actual length in
2805 * case the USB device driver does not check the actual number
2806 * of frames transferred, "xfer->aframes":
2808 for (; x < xfer->nframes; x++) {
2809 usbd_xfer_set_frame_len(xfer, x, 0);
2812 /* check actual length */
2813 if (xfer->actlen > xfer->sumlen) {
2814 if (xfer->error == 0) {
2815 panic("%s: actual length, %d, is greater than "
2816 "initial length, %d\n",
2817 __FUNCTION__, xfer->actlen, xfer->sumlen);
2819 /* just set some valid value */
2820 xfer->actlen = xfer->sumlen;
2823 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2824 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2825 xfer->aframes, xfer->nframes);
2828 /* end of control transfer, if any */
2829 xfer->flags_int.control_act = 0;
2831 #if USB_HAVE_TT_SUPPORT
2832 switch (xfer->error) {
2833 case USB_ERR_NORMAL_COMPLETION:
2834 case USB_ERR_SHORT_XFER:
2835 case USB_ERR_STALLED:
2836 case USB_ERR_CANCELLED:
2840 /* try to reset the TT, if any */
2842 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2843 USB_BUS_UNLOCK(bus);
2847 /* check if we should block the execution queue */
2848 if ((xfer->error != USB_ERR_CANCELLED) &&
2849 (xfer->flags.pipe_bof)) {
2850 DPRINTFN(2, "xfer=%p: Block On Failure "
2851 "on endpoint=%p\n", xfer, xfer->endpoint);
2855 /* check for short transfers */
2856 if (xfer->actlen < xfer->sumlen) {
2858 /* end of control transfer, if any */
2859 xfer->flags_int.control_act = 0;
2861 if (!xfer->flags_int.short_xfer_ok) {
2862 xfer->error = USB_ERR_SHORT_XFER;
2863 if (xfer->flags.pipe_bof) {
2864 DPRINTFN(2, "xfer=%p: Block On Failure on "
2865 "Short Transfer on endpoint %p.\n",
2866 xfer, xfer->endpoint);
2872 * Check if we are in the middle of a
2875 if (xfer->flags_int.control_act) {
2876 DPRINTFN(5, "xfer=%p: Control transfer "
2877 "active on endpoint=%p\n", xfer, xfer->endpoint);
2883 ep = xfer->endpoint;
2886 * If the current USB transfer is completing we need to start the
2890 if (ep->endpoint_q.curr == xfer) {
2891 usb_command_wrapper(&ep->endpoint_q, NULL);
2893 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2894 /* there is another USB transfer waiting */
2896 /* this is the last USB transfer */
2897 /* clear isochronous sync flag */
2898 xfer->endpoint->is_synced = 0;
2901 USB_BUS_UNLOCK(bus);
2906 /*------------------------------------------------------------------------*
2907 * usb_command_wrapper
2909 * This function is used to execute commands non-recursivly on an USB
2911 *------------------------------------------------------------------------*/
2913 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2917 * If the transfer is not already processing,
2920 if (pq->curr != xfer) {
2921 usbd_transfer_enqueue(pq, xfer);
2922 if (pq->curr != NULL) {
2923 /* something is already processing */
2924 DPRINTFN(6, "busy %p\n", pq->curr);
2929 /* Get next element in queue */
2933 if (!pq->recurse_1) {
2937 /* set both recurse flags */
2941 if (pq->curr == NULL) {
2942 xfer = TAILQ_FIRST(&pq->head);
2944 TAILQ_REMOVE(&pq->head, xfer,
2946 xfer->wait_queue = NULL;
2952 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2954 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2956 } while (!pq->recurse_2);
2958 /* clear first recurse flag */
2962 /* clear second recurse flag */
2967 /*------------------------------------------------------------------------*
2968 * usbd_ctrl_transfer_setup
2970 * This function is used to setup the default USB control endpoint
2972 *------------------------------------------------------------------------*/
2974 usbd_ctrl_transfer_setup(struct usb_device *udev)
2976 struct usb_xfer *xfer;
2978 uint8_t iface_index;
2980 /* check for root HUB */
2981 if (udev->parent_hub == NULL)
2985 xfer = udev->ctrl_xfer[0];
2987 USB_XFER_LOCK(xfer);
2989 ((xfer->address == udev->address) &&
2990 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2991 udev->ddesc.bMaxPacketSize));
2992 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2995 * NOTE: checking "xfer->address" and
2996 * starting the USB transfer must be
2999 usbd_transfer_start(xfer);
3002 USB_XFER_UNLOCK(xfer);
3009 * All parameters are exactly the same like before.
3015 * Update wMaxPacketSize for the default control endpoint:
3017 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3018 udev->ddesc.bMaxPacketSize;
3021 * Unsetup any existing USB transfer:
3023 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3026 * Reset clear stall error counter.
3028 udev->clear_stall_errors = 0;
3031 * Try to setup a new USB transfer for the
3032 * default control endpoint:
3035 if (usbd_transfer_setup(udev, &iface_index,
3036 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3037 &udev->device_mtx)) {
3038 DPRINTFN(0, "could not setup default "
3045 /*------------------------------------------------------------------------*
3046 * usbd_clear_data_toggle - factored out code
3048 * NOTE: the intention of this function is not to reset the hardware
3050 *------------------------------------------------------------------------*/
3052 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3054 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3056 /* check that we have a valid case */
3057 if (udev->flags.usb_mode == USB_MODE_HOST &&
3058 udev->parent_hub != NULL &&
3059 udev->bus->methods->clear_stall != NULL &&
3060 ep->methods != NULL) {
3061 (udev->bus->methods->clear_stall) (udev, ep);
3065 /*------------------------------------------------------------------------*
3066 * usbd_clear_data_toggle - factored out code
3068 * NOTE: the intention of this function is not to reset the hardware
3069 * data toggle on the USB device side.
3070 *------------------------------------------------------------------------*/
3072 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3074 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3076 USB_BUS_LOCK(udev->bus);
3077 ep->toggle_next = 0;
3078 /* some hardware needs a callback to clear the data toggle */
3079 usbd_clear_stall_locked(udev, ep);
3080 USB_BUS_UNLOCK(udev->bus);
3083 /*------------------------------------------------------------------------*
3084 * usbd_clear_stall_callback - factored out clear stall callback
3087 * xfer1: Clear Stall Control Transfer
3088 * xfer2: Stalled USB Transfer
3090 * This function is NULL safe.
3096 * Clear stall config example:
3098 * static const struct usb_config my_clearstall = {
3099 * .type = UE_CONTROL,
3101 * .direction = UE_DIR_ANY,
3102 * .interval = 50, //50 milliseconds
3103 * .bufsize = sizeof(struct usb_device_request),
3104 * .timeout = 1000, //1.000 seconds
3105 * .callback = &my_clear_stall_callback, // **
3106 * .usb_mode = USB_MODE_HOST,
3109 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3110 * passing the correct parameters.
3111 *------------------------------------------------------------------------*/
3113 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3114 struct usb_xfer *xfer2)
3116 struct usb_device_request req;
3118 if (xfer2 == NULL) {
3119 /* looks like we are tearing down */
3120 DPRINTF("NULL input parameter\n");
3123 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3124 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3126 switch (USB_GET_STATE(xfer1)) {
3130 * pre-clear the data toggle to DATA0 ("umass.c" and
3131 * "ata-usb.c" depends on this)
3134 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3136 /* setup a clear-stall packet */
3138 req.bmRequestType = UT_WRITE_ENDPOINT;
3139 req.bRequest = UR_CLEAR_FEATURE;
3140 USETW(req.wValue, UF_ENDPOINT_HALT);
3141 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3143 USETW(req.wLength, 0);
3146 * "usbd_transfer_setup_sub()" will ensure that
3147 * we have sufficient room in the buffer for
3148 * the request structure!
3151 /* copy in the transfer */
3153 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3156 xfer1->frlengths[0] = sizeof(req);
3159 usbd_transfer_submit(xfer1);
3162 case USB_ST_TRANSFERRED:
3165 default: /* Error */
3166 if (xfer1->error == USB_ERR_CANCELLED) {
3171 return (1); /* Clear Stall Finished */
3174 /*------------------------------------------------------------------------*
3175 * usbd_transfer_poll
3177 * The following function gets called from the USB keyboard driver and
3178 * UMASS when the system has paniced.
3180 * NOTE: It is currently not possible to resume normal operation on
3181 * the USB controller which has been polled, due to clearing of the
3182 * "up_dsleep" and "up_msleep" flags.
3183 *------------------------------------------------------------------------*/
3185 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3187 struct usb_xfer *xfer;
3188 struct usb_xfer_root *xroot;
3189 struct usb_device *udev;
3190 struct usb_proc_msg *pm;
3195 for (n = 0; n != max; n++) {
3196 /* Extra checks to avoid panic */
3199 continue; /* no USB transfer */
3200 xroot = xfer->xroot;
3202 continue; /* no USB root */
3205 continue; /* no USB device */
3206 if (udev->bus == NULL)
3207 continue; /* no BUS structure */
3208 if (udev->bus->methods == NULL)
3209 continue; /* no BUS methods */
3210 if (udev->bus->methods->xfer_poll == NULL)
3211 continue; /* no poll method */
3213 /* make sure that the BUS mutex is not locked */
3215 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3216 mtx_unlock(&xroot->udev->bus->bus_mtx);
3220 /* make sure that the transfer mutex is not locked */
3222 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3223 mtx_unlock(xroot->xfer_mtx);
3227 /* Make sure cv_signal() and cv_broadcast() is not called */
3228 udev->bus->control_xfer_proc.up_msleep = 0;
3229 udev->bus->explore_proc.up_msleep = 0;
3230 udev->bus->giant_callback_proc.up_msleep = 0;
3231 udev->bus->non_giant_callback_proc.up_msleep = 0;
3233 /* poll USB hardware */
3234 (udev->bus->methods->xfer_poll) (udev->bus);
3236 USB_BUS_LOCK(xroot->bus);
3238 /* check for clear stall */
3239 if (udev->ctrl_xfer[1] != NULL) {
3241 /* poll clear stall start */
3242 pm = &udev->cs_msg[0].hdr;
3243 (pm->pm_callback) (pm);
3244 /* poll clear stall done thread */
3245 pm = &udev->ctrl_xfer[1]->
3246 xroot->done_m[0].hdr;
3247 (pm->pm_callback) (pm);
3250 /* poll done thread */
3251 pm = &xroot->done_m[0].hdr;
3252 (pm->pm_callback) (pm);
3254 USB_BUS_UNLOCK(xroot->bus);
3256 /* restore transfer mutex */
3258 mtx_lock(xroot->xfer_mtx);
3260 /* restore BUS mutex */
3262 mtx_lock(&xroot->udev->bus->bus_mtx);
3267 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3268 uint8_t type, enum usb_dev_speed speed)
3270 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3271 [USB_SPEED_LOW] = 8,
3272 [USB_SPEED_FULL] = 64,
3273 [USB_SPEED_HIGH] = 1024,
3274 [USB_SPEED_VARIABLE] = 1024,
3275 [USB_SPEED_SUPER] = 1024,
3278 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3279 [USB_SPEED_LOW] = 0, /* invalid */
3280 [USB_SPEED_FULL] = 1023,
3281 [USB_SPEED_HIGH] = 1024,
3282 [USB_SPEED_VARIABLE] = 3584,
3283 [USB_SPEED_SUPER] = 1024,
3286 static const uint16_t control_min[USB_SPEED_MAX] = {
3287 [USB_SPEED_LOW] = 8,
3288 [USB_SPEED_FULL] = 8,
3289 [USB_SPEED_HIGH] = 64,
3290 [USB_SPEED_VARIABLE] = 512,
3291 [USB_SPEED_SUPER] = 512,
3294 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3295 [USB_SPEED_LOW] = 8,
3296 [USB_SPEED_FULL] = 8,
3297 [USB_SPEED_HIGH] = 512,
3298 [USB_SPEED_VARIABLE] = 512,
3299 [USB_SPEED_SUPER] = 1024,
3304 memset(ptr, 0, sizeof(*ptr));
3308 ptr->range.max = intr_range_max[speed];
3310 case UE_ISOCHRONOUS:
3311 ptr->range.max = isoc_range_max[speed];
3314 if (type == UE_BULK)
3315 temp = bulk_min[speed];
3316 else /* UE_CONTROL */
3317 temp = control_min[speed];
3319 /* default is fixed */
3320 ptr->fixed[0] = temp;
3321 ptr->fixed[1] = temp;
3322 ptr->fixed[2] = temp;
3323 ptr->fixed[3] = temp;
3325 if (speed == USB_SPEED_FULL) {
3326 /* multiple sizes */
3331 if ((speed == USB_SPEED_VARIABLE) &&
3332 (type == UE_BULK)) {
3333 /* multiple sizes */
3334 ptr->fixed[2] = 1024;
3335 ptr->fixed[3] = 1536;
3342 usbd_xfer_softc(struct usb_xfer *xfer)
3344 return (xfer->priv_sc);
3348 usbd_xfer_get_priv(struct usb_xfer *xfer)
3350 return (xfer->priv_fifo);
3354 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3356 xfer->priv_fifo = ptr;
3360 usbd_xfer_state(struct usb_xfer *xfer)
3362 return (xfer->usb_state);
3366 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3369 case USB_FORCE_SHORT_XFER:
3370 xfer->flags.force_short_xfer = 1;
3372 case USB_SHORT_XFER_OK:
3373 xfer->flags.short_xfer_ok = 1;
3375 case USB_MULTI_SHORT_OK:
3376 xfer->flags.short_frames_ok = 1;
3378 case USB_MANUAL_STATUS:
3379 xfer->flags.manual_status = 1;
3385 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3388 case USB_FORCE_SHORT_XFER:
3389 xfer->flags.force_short_xfer = 0;
3391 case USB_SHORT_XFER_OK:
3392 xfer->flags.short_xfer_ok = 0;
3394 case USB_MULTI_SHORT_OK:
3395 xfer->flags.short_frames_ok = 0;
3397 case USB_MANUAL_STATUS:
3398 xfer->flags.manual_status = 0;
3404 * The following function returns in milliseconds when the isochronous
3405 * transfer was completed by the hardware. The returned value wraps
3406 * around 65536 milliseconds.
3409 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3411 return (xfer->isoc_time_complete);
3415 * The following function returns non-zero if the max packet size
3416 * field was clamped to a valid value. Else it returns zero.
3419 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3421 return (xfer->flags_int.maxp_was_clamped);