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_setup_ctrl_transfer
1349 * This function handles initialisation of control transfers. Control
1350 * transfers are special in that regard that they can both transmit
1356 *------------------------------------------------------------------------*/
1358 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1362 /* Check for control endpoint stall */
1363 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1364 /* the control transfer is no longer active */
1365 xfer->flags_int.control_stall = 1;
1366 xfer->flags_int.control_act = 0;
1368 /* don't stall control transfer by default */
1369 xfer->flags_int.control_stall = 0;
1372 /* Check for invalid number of frames */
1373 if (xfer->nframes > 2) {
1375 * If you need to split a control transfer, you
1376 * have to do one part at a time. Only with
1377 * non-control transfers you can do multiple
1380 DPRINTFN(0, "Too many frames: %u\n",
1381 (unsigned int)xfer->nframes);
1386 * Check if there is a control
1387 * transfer in progress:
1389 if (xfer->flags_int.control_act) {
1391 if (xfer->flags_int.control_hdr) {
1393 /* clear send header flag */
1395 xfer->flags_int.control_hdr = 0;
1397 /* setup control transfer */
1398 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1399 usbd_control_transfer_init(xfer);
1402 /* get data length */
1408 /* the size of the SETUP structure is hardcoded ! */
1410 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1411 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1412 xfer->frlengths[0], sizeof(struct
1413 usb_device_request));
1416 /* check USB mode */
1417 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1419 /* check number of frames */
1420 if (xfer->nframes != 1) {
1422 * We need to receive the setup
1423 * message first so that we know the
1426 DPRINTF("Misconfigured transfer\n");
1430 * Set a dummy "control_rem" value. This
1431 * variable will be overwritten later by a
1432 * call to "usbd_control_transfer_init()" !
1434 xfer->flags_int.control_rem = 0xFFFF;
1437 /* setup "endpoint" and "control_rem" */
1439 usbd_control_transfer_init(xfer);
1442 /* set transfer-header flag */
1444 xfer->flags_int.control_hdr = 1;
1446 /* get data length */
1448 len = (xfer->sumlen - sizeof(struct usb_device_request));
1451 /* check if there is a length mismatch */
1453 if (len > xfer->flags_int.control_rem) {
1454 DPRINTFN(0, "Length (%d) greater than "
1455 "remaining length (%d)\n", len,
1456 xfer->flags_int.control_rem);
1459 /* check if we are doing a short transfer */
1461 if (xfer->flags.force_short_xfer) {
1462 xfer->flags_int.control_rem = 0;
1464 if ((len != xfer->max_data_length) &&
1465 (len != xfer->flags_int.control_rem) &&
1466 (xfer->nframes != 1)) {
1467 DPRINTFN(0, "Short control transfer without "
1468 "force_short_xfer set\n");
1471 xfer->flags_int.control_rem -= len;
1474 /* the status part is executed when "control_act" is 0 */
1476 if ((xfer->flags_int.control_rem > 0) ||
1477 (xfer->flags.manual_status)) {
1478 /* don't execute the STATUS stage yet */
1479 xfer->flags_int.control_act = 1;
1482 if ((!xfer->flags_int.control_hdr) &&
1483 (xfer->nframes == 1)) {
1485 * This is not a valid operation!
1487 DPRINTFN(0, "Invalid parameter "
1492 /* time to execute the STATUS stage */
1493 xfer->flags_int.control_act = 0;
1495 return (0); /* success */
1498 return (1); /* failure */
1501 /*------------------------------------------------------------------------*
1502 * usbd_transfer_submit - start USB hardware for the given transfer
1504 * This function should only be called from the USB callback.
1505 *------------------------------------------------------------------------*/
1507 usbd_transfer_submit(struct usb_xfer *xfer)
1509 struct usb_xfer_root *info;
1510 struct usb_bus *bus;
1516 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1517 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1521 if (USB_DEBUG_VAR > 0) {
1524 usb_dump_endpoint(xfer->endpoint);
1526 USB_BUS_UNLOCK(bus);
1530 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1531 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1533 /* Only open the USB transfer once! */
1534 if (!xfer->flags_int.open) {
1535 xfer->flags_int.open = 1;
1540 (xfer->endpoint->methods->open) (xfer);
1541 USB_BUS_UNLOCK(bus);
1543 /* set "transferring" flag */
1544 xfer->flags_int.transferring = 1;
1547 /* increment power reference */
1548 usbd_transfer_power_ref(xfer, 1);
1551 * Check if the transfer is waiting on a queue, most
1552 * frequently the "done_q":
1554 if (xfer->wait_queue) {
1556 usbd_transfer_dequeue(xfer);
1557 USB_BUS_UNLOCK(bus);
1559 /* clear "did_dma_delay" flag */
1560 xfer->flags_int.did_dma_delay = 0;
1562 /* clear "did_close" flag */
1563 xfer->flags_int.did_close = 0;
1566 /* clear "bdma_setup" flag */
1567 xfer->flags_int.bdma_setup = 0;
1569 /* by default we cannot cancel any USB transfer immediately */
1570 xfer->flags_int.can_cancel_immed = 0;
1572 /* clear lengths and frame counts by default */
1577 /* clear any previous errors */
1580 /* Check if the device is still alive */
1581 if (info->udev->state < USB_STATE_POWERED) {
1584 * Must return cancelled error code else
1585 * device drivers can hang.
1587 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1588 USB_BUS_UNLOCK(bus);
1593 if (xfer->nframes == 0) {
1594 if (xfer->flags.stall_pipe) {
1596 * Special case - want to stall without transferring
1599 DPRINTF("xfer=%p nframes=0: stall "
1600 "or clear stall!\n", xfer);
1602 xfer->flags_int.can_cancel_immed = 1;
1603 /* start the transfer */
1604 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1605 USB_BUS_UNLOCK(bus);
1609 usbd_transfer_done(xfer, USB_ERR_INVAL);
1610 USB_BUS_UNLOCK(bus);
1613 /* compute some variables */
1615 for (x = 0; x != xfer->nframes; x++) {
1616 /* make a copy of the frlenghts[] */
1617 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1618 /* compute total transfer length */
1619 xfer->sumlen += xfer->frlengths[x];
1620 if (xfer->sumlen < xfer->frlengths[x]) {
1621 /* length wrapped around */
1623 usbd_transfer_done(xfer, USB_ERR_INVAL);
1624 USB_BUS_UNLOCK(bus);
1629 /* clear some internal flags */
1631 xfer->flags_int.short_xfer_ok = 0;
1632 xfer->flags_int.short_frames_ok = 0;
1634 /* check if this is a control transfer */
1636 if (xfer->flags_int.control_xfr) {
1638 if (usbd_setup_ctrl_transfer(xfer)) {
1640 usbd_transfer_done(xfer, USB_ERR_STALLED);
1641 USB_BUS_UNLOCK(bus);
1646 * Setup filtered version of some transfer flags,
1647 * in case of data read direction
1649 if (USB_GET_DATA_ISREAD(xfer)) {
1651 if (xfer->flags.short_frames_ok) {
1652 xfer->flags_int.short_xfer_ok = 1;
1653 xfer->flags_int.short_frames_ok = 1;
1654 } else if (xfer->flags.short_xfer_ok) {
1655 xfer->flags_int.short_xfer_ok = 1;
1657 /* check for control transfer */
1658 if (xfer->flags_int.control_xfr) {
1660 * 1) Control transfers do not support
1661 * reception of multiple short USB
1662 * frames in host mode and device side
1663 * mode, with exception of:
1665 * 2) Due to sometimes buggy device
1666 * side firmware we need to do a
1667 * STATUS stage in case of short
1668 * control transfers in USB host mode.
1669 * The STATUS stage then becomes the
1670 * "alt_next" to the DATA stage.
1672 xfer->flags_int.short_frames_ok = 1;
1677 * Check if BUS-DMA support is enabled and try to load virtual
1678 * buffers into DMA, if any:
1681 if (xfer->flags_int.bdma_enable) {
1682 /* insert the USB transfer last in the BUS-DMA queue */
1683 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1688 * Enter the USB transfer into the Host Controller or
1689 * Device Controller schedule:
1691 usbd_pipe_enter(xfer);
1694 /*------------------------------------------------------------------------*
1695 * usbd_pipe_enter - factored out code
1696 *------------------------------------------------------------------------*/
1698 usbd_pipe_enter(struct usb_xfer *xfer)
1700 struct usb_endpoint *ep;
1702 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1704 USB_BUS_LOCK(xfer->xroot->bus);
1706 ep = xfer->endpoint;
1710 /* the transfer can now be cancelled */
1711 xfer->flags_int.can_cancel_immed = 1;
1713 /* enter the transfer */
1714 (ep->methods->enter) (xfer);
1716 /* check for transfer error */
1718 /* some error has happened */
1719 usbd_transfer_done(xfer, 0);
1720 USB_BUS_UNLOCK(xfer->xroot->bus);
1724 /* start the transfer */
1725 usb_command_wrapper(&ep->endpoint_q, xfer);
1726 USB_BUS_UNLOCK(xfer->xroot->bus);
1729 /*------------------------------------------------------------------------*
1730 * usbd_transfer_start - start an USB transfer
1732 * NOTE: Calling this function more than one time will only
1733 * result in a single transfer start, until the USB transfer
1735 *------------------------------------------------------------------------*/
1737 usbd_transfer_start(struct usb_xfer *xfer)
1740 /* transfer is gone */
1743 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1745 /* mark the USB transfer started */
1747 if (!xfer->flags_int.started) {
1748 /* lock the BUS lock to avoid races updating flags_int */
1749 USB_BUS_LOCK(xfer->xroot->bus);
1750 xfer->flags_int.started = 1;
1751 USB_BUS_UNLOCK(xfer->xroot->bus);
1753 /* check if the USB transfer callback is already transferring */
1755 if (xfer->flags_int.transferring) {
1758 USB_BUS_LOCK(xfer->xroot->bus);
1759 /* call the USB transfer callback */
1760 usbd_callback_ss_done_defer(xfer);
1761 USB_BUS_UNLOCK(xfer->xroot->bus);
1764 /*------------------------------------------------------------------------*
1765 * usbd_transfer_stop - stop an USB transfer
1767 * NOTE: Calling this function more than one time will only
1768 * result in a single transfer stop.
1769 * NOTE: When this function returns it is not safe to free nor
1770 * reuse any DMA buffers. See "usbd_transfer_drain()".
1771 *------------------------------------------------------------------------*/
1773 usbd_transfer_stop(struct usb_xfer *xfer)
1775 struct usb_endpoint *ep;
1778 /* transfer is gone */
1781 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1783 /* check if the USB transfer was ever opened */
1785 if (!xfer->flags_int.open) {
1786 if (xfer->flags_int.started) {
1787 /* nothing to do except clearing the "started" flag */
1788 /* lock the BUS lock to avoid races updating flags_int */
1789 USB_BUS_LOCK(xfer->xroot->bus);
1790 xfer->flags_int.started = 0;
1791 USB_BUS_UNLOCK(xfer->xroot->bus);
1795 /* try to stop the current USB transfer */
1797 USB_BUS_LOCK(xfer->xroot->bus);
1798 /* override any previous error */
1799 xfer->error = USB_ERR_CANCELLED;
1802 * Clear "open" and "started" when both private and USB lock
1803 * is locked so that we don't get a race updating "flags_int"
1805 xfer->flags_int.open = 0;
1806 xfer->flags_int.started = 0;
1809 * Check if we can cancel the USB transfer immediately.
1811 if (xfer->flags_int.transferring) {
1812 if (xfer->flags_int.can_cancel_immed &&
1813 (!xfer->flags_int.did_close)) {
1816 * The following will lead to an USB_ERR_CANCELLED
1817 * error code being passed to the USB callback.
1819 (xfer->endpoint->methods->close) (xfer);
1820 /* only close once */
1821 xfer->flags_int.did_close = 1;
1823 /* need to wait for the next done callback */
1828 /* close here and now */
1829 (xfer->endpoint->methods->close) (xfer);
1832 * Any additional DMA delay is done by
1833 * "usbd_transfer_unsetup()".
1837 * Special case. Check if we need to restart a blocked
1840 ep = xfer->endpoint;
1843 * If the current USB transfer is completing we need
1844 * to start the next one:
1846 if (ep->endpoint_q.curr == xfer) {
1847 usb_command_wrapper(&ep->endpoint_q, NULL);
1851 USB_BUS_UNLOCK(xfer->xroot->bus);
1854 /*------------------------------------------------------------------------*
1855 * usbd_transfer_pending
1857 * This function will check if an USB transfer is pending which is a
1858 * little bit complicated!
1861 * 1: Pending: The USB transfer will receive a callback in the future.
1862 *------------------------------------------------------------------------*/
1864 usbd_transfer_pending(struct usb_xfer *xfer)
1866 struct usb_xfer_root *info;
1867 struct usb_xfer_queue *pq;
1870 /* transfer is gone */
1873 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1875 if (xfer->flags_int.transferring) {
1879 USB_BUS_LOCK(xfer->xroot->bus);
1880 if (xfer->wait_queue) {
1881 /* we are waiting on a queue somewhere */
1882 USB_BUS_UNLOCK(xfer->xroot->bus);
1888 if (pq->curr == xfer) {
1889 /* we are currently scheduled for callback */
1890 USB_BUS_UNLOCK(xfer->xroot->bus);
1893 /* we are not pending */
1894 USB_BUS_UNLOCK(xfer->xroot->bus);
1898 /*------------------------------------------------------------------------*
1899 * usbd_transfer_drain
1901 * This function will stop the USB transfer and wait for any
1902 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1903 * are loaded into DMA can safely be freed or reused after that this
1904 * function has returned.
1905 *------------------------------------------------------------------------*/
1907 usbd_transfer_drain(struct usb_xfer *xfer)
1909 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1910 "usbd_transfer_drain can sleep!");
1913 /* transfer is gone */
1916 if (xfer->xroot->xfer_mtx != &Giant) {
1917 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1919 USB_XFER_LOCK(xfer);
1921 usbd_transfer_stop(xfer);
1923 while (usbd_transfer_pending(xfer) ||
1924 xfer->flags_int.doing_callback) {
1927 * It is allowed that the callback can drop its
1928 * transfer mutex. In that case checking only
1929 * "usbd_transfer_pending()" is not enough to tell if
1930 * the USB transfer is fully drained. We also need to
1931 * check the internal "doing_callback" flag.
1933 xfer->flags_int.draining = 1;
1936 * Wait until the current outstanding USB
1937 * transfer is complete !
1939 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1941 USB_XFER_UNLOCK(xfer);
1944 struct usb_page_cache *
1945 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1947 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1949 return (&xfer->frbuffers[frindex]);
1953 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
1955 struct usb_page_search page_info;
1957 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1959 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
1960 return (page_info.buffer);
1963 /*------------------------------------------------------------------------*
1964 * usbd_xfer_get_fps_shift
1966 * The following function is only useful for isochronous transfers. It
1967 * returns how many times the frame execution rate has been shifted
1973 *------------------------------------------------------------------------*/
1975 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1977 return (xfer->fps_shift);
1981 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1983 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1985 return (xfer->frlengths[frindex]);
1988 /*------------------------------------------------------------------------*
1989 * usbd_xfer_set_frame_data
1991 * This function sets the pointer of the buffer that should
1992 * loaded directly into DMA for the given USB frame. Passing "ptr"
1993 * equal to NULL while the corresponding "frlength" is greater
1994 * than zero gives undefined results!
1995 *------------------------------------------------------------------------*/
1997 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1998 void *ptr, usb_frlength_t len)
2000 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2002 /* set virtual address to load and length */
2003 xfer->frbuffers[frindex].buffer = ptr;
2004 usbd_xfer_set_frame_len(xfer, frindex, len);
2008 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2009 void **ptr, int *len)
2011 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2014 *ptr = xfer->frbuffers[frindex].buffer;
2016 *len = xfer->frlengths[frindex];
2019 /*------------------------------------------------------------------------*
2020 * usbd_xfer_old_frame_length
2022 * This function returns the framelength of the given frame at the
2023 * time the transfer was submitted. This function can be used to
2024 * compute the starting data pointer of the next isochronous frame
2025 * when an isochronous transfer has completed.
2026 *------------------------------------------------------------------------*/
2028 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2030 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2032 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2036 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2040 *actlen = xfer->actlen;
2042 *sumlen = xfer->sumlen;
2043 if (aframes != NULL)
2044 *aframes = xfer->aframes;
2045 if (nframes != NULL)
2046 *nframes = xfer->nframes;
2049 /*------------------------------------------------------------------------*
2050 * usbd_xfer_set_frame_offset
2052 * This function sets the frame data buffer offset relative to the beginning
2053 * of the USB DMA buffer allocated for this USB transfer.
2054 *------------------------------------------------------------------------*/
2056 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2057 usb_frcount_t frindex)
2059 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2060 "when the USB buffer is external\n"));
2061 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2063 /* set virtual address to load */
2064 xfer->frbuffers[frindex].buffer =
2065 USB_ADD_BYTES(xfer->local_buffer, offset);
2069 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2075 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2081 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2087 usbd_xfer_max_frames(struct usb_xfer *xfer)
2089 return (xfer->max_frame_count);
2093 usbd_xfer_max_len(struct usb_xfer *xfer)
2095 return (xfer->max_data_length);
2099 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2101 return (xfer->max_frame_size);
2105 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2108 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2110 xfer->frlengths[frindex] = len;
2113 /*------------------------------------------------------------------------*
2114 * usb_callback_proc - factored out code
2116 * This function performs USB callbacks.
2117 *------------------------------------------------------------------------*/
2119 usb_callback_proc(struct usb_proc_msg *_pm)
2121 struct usb_done_msg *pm = (void *)_pm;
2122 struct usb_xfer_root *info = pm->xroot;
2124 /* Change locking order */
2125 USB_BUS_UNLOCK(info->bus);
2128 * We exploit the fact that the mutex is the same for all
2129 * callbacks that will be called from this thread:
2131 mtx_lock(info->xfer_mtx);
2132 USB_BUS_LOCK(info->bus);
2134 /* Continue where we lost track */
2135 usb_command_wrapper(&info->done_q,
2138 mtx_unlock(info->xfer_mtx);
2141 /*------------------------------------------------------------------------*
2142 * usbd_callback_ss_done_defer
2144 * This function will defer the start, stop and done callback to the
2146 *------------------------------------------------------------------------*/
2148 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2150 struct usb_xfer_root *info = xfer->xroot;
2151 struct usb_xfer_queue *pq = &info->done_q;
2153 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2155 if (pq->curr != xfer) {
2156 usbd_transfer_enqueue(pq, xfer);
2158 if (!pq->recurse_1) {
2161 * We have to postpone the callback due to the fact we
2162 * will have a Lock Order Reversal, LOR, if we try to
2165 if (usb_proc_msignal(info->done_p,
2166 &info->done_m[0], &info->done_m[1])) {
2170 /* clear second recurse flag */
2177 /*------------------------------------------------------------------------*
2178 * usbd_callback_wrapper
2180 * This is a wrapper for USB callbacks. This wrapper does some
2181 * auto-magic things like figuring out if we can call the callback
2182 * directly from the current context or if we need to wakeup the
2183 * interrupt process.
2184 *------------------------------------------------------------------------*/
2186 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2188 struct usb_xfer *xfer = pq->curr;
2189 struct usb_xfer_root *info = xfer->xroot;
2191 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2192 if (!mtx_owned(info->xfer_mtx)) {
2194 * Cases that end up here:
2196 * 5) HW interrupt done callback or other source.
2198 DPRINTFN(3, "case 5\n");
2201 * We have to postpone the callback due to the fact we
2202 * will have a Lock Order Reversal, LOR, if we try to
2205 if (usb_proc_msignal(info->done_p,
2206 &info->done_m[0], &info->done_m[1])) {
2212 * Cases that end up here:
2214 * 1) We are starting a transfer
2215 * 2) We are prematurely calling back a transfer
2216 * 3) We are stopping a transfer
2217 * 4) We are doing an ordinary callback
2219 DPRINTFN(3, "case 1-4\n");
2220 /* get next USB transfer in the queue */
2221 info->done_q.curr = NULL;
2223 /* set flag in case of drain */
2224 xfer->flags_int.doing_callback = 1;
2226 USB_BUS_UNLOCK(info->bus);
2227 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2229 /* set correct USB state for callback */
2230 if (!xfer->flags_int.transferring) {
2231 xfer->usb_state = USB_ST_SETUP;
2232 if (!xfer->flags_int.started) {
2233 /* we got stopped before we even got started */
2234 USB_BUS_LOCK(info->bus);
2239 if (usbd_callback_wrapper_sub(xfer)) {
2240 /* the callback has been deferred */
2241 USB_BUS_LOCK(info->bus);
2245 /* decrement power reference */
2246 usbd_transfer_power_ref(xfer, -1);
2248 xfer->flags_int.transferring = 0;
2251 xfer->usb_state = USB_ST_ERROR;
2253 /* set transferred state */
2254 xfer->usb_state = USB_ST_TRANSFERRED;
2256 /* sync DMA memory, if any */
2257 if (xfer->flags_int.bdma_enable &&
2258 (!xfer->flags_int.bdma_no_post_sync)) {
2259 usb_bdma_post_sync(xfer);
2266 if (xfer->usb_state != USB_ST_SETUP)
2267 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2269 /* call processing routine */
2270 (xfer->callback) (xfer, xfer->error);
2272 /* pickup the USB mutex again */
2273 USB_BUS_LOCK(info->bus);
2276 * Check if we got started after that we got cancelled, but
2277 * before we managed to do the callback.
2279 if ((!xfer->flags_int.open) &&
2280 (xfer->flags_int.started) &&
2281 (xfer->usb_state == USB_ST_ERROR)) {
2282 /* clear flag in case of drain */
2283 xfer->flags_int.doing_callback = 0;
2284 /* try to loop, but not recursivly */
2285 usb_command_wrapper(&info->done_q, xfer);
2290 /* clear flag in case of drain */
2291 xfer->flags_int.doing_callback = 0;
2294 * Check if we are draining.
2296 if (xfer->flags_int.draining &&
2297 (!xfer->flags_int.transferring)) {
2298 /* "usbd_transfer_drain()" is waiting for end of transfer */
2299 xfer->flags_int.draining = 0;
2300 cv_broadcast(&info->cv_drain);
2303 /* do the next callback, if any */
2304 usb_command_wrapper(&info->done_q,
2308 /*------------------------------------------------------------------------*
2309 * usb_dma_delay_done_cb
2311 * This function is called when the DMA delay has been exectuded, and
2312 * will make sure that the callback is called to complete the USB
2313 * transfer. This code path is ususally only used when there is an USB
2314 * error like USB_ERR_CANCELLED.
2315 *------------------------------------------------------------------------*/
2317 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2319 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2321 DPRINTFN(3, "Completed %p\n", xfer);
2323 /* queue callback for execution, again */
2324 usbd_transfer_done(xfer, 0);
2327 /*------------------------------------------------------------------------*
2328 * usbd_transfer_dequeue
2330 * - This function is used to remove an USB transfer from a USB
2333 * - This function can be called multiple times in a row.
2334 *------------------------------------------------------------------------*/
2336 usbd_transfer_dequeue(struct usb_xfer *xfer)
2338 struct usb_xfer_queue *pq;
2340 pq = xfer->wait_queue;
2342 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2343 xfer->wait_queue = NULL;
2347 /*------------------------------------------------------------------------*
2348 * usbd_transfer_enqueue
2350 * - This function is used to insert an USB transfer into a USB *
2353 * - This function can be called multiple times in a row.
2354 *------------------------------------------------------------------------*/
2356 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2359 * Insert the USB transfer into the queue, if it is not
2360 * already on a USB transfer queue:
2362 if (xfer->wait_queue == NULL) {
2363 xfer->wait_queue = pq;
2364 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2368 /*------------------------------------------------------------------------*
2369 * usbd_transfer_done
2371 * - This function is used to remove an USB transfer from the busdma,
2372 * pipe or interrupt queue.
2374 * - This function is used to queue the USB transfer on the done
2377 * - This function is used to stop any USB transfer timeouts.
2378 *------------------------------------------------------------------------*/
2380 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2382 struct usb_xfer_root *info = xfer->xroot;
2384 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2386 DPRINTF("err=%s\n", usbd_errstr(error));
2389 * If we are not transferring then just return.
2390 * This can happen during transfer cancel.
2392 if (!xfer->flags_int.transferring) {
2393 DPRINTF("not transferring\n");
2394 /* end of control transfer, if any */
2395 xfer->flags_int.control_act = 0;
2398 /* only set transfer error, if not already set */
2399 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2400 xfer->error = error;
2402 /* stop any callouts */
2403 usb_callout_stop(&xfer->timeout_handle);
2406 * If we are waiting on a queue, just remove the USB transfer
2407 * from the queue, if any. We should have the required locks
2408 * locked to do the remove when this function is called.
2410 usbd_transfer_dequeue(xfer);
2413 if (mtx_owned(info->xfer_mtx)) {
2414 struct usb_xfer_queue *pq;
2417 * If the private USB lock is not locked, then we assume
2418 * that the BUS-DMA load stage has been passed:
2422 if (pq->curr == xfer) {
2423 /* start the next BUS-DMA load, if any */
2424 usb_command_wrapper(pq, NULL);
2428 /* keep some statistics */
2430 info->bus->stats_err.uds_requests
2431 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2433 info->bus->stats_ok.uds_requests
2434 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2437 /* call the USB transfer callback */
2438 usbd_callback_ss_done_defer(xfer);
2441 /*------------------------------------------------------------------------*
2442 * usbd_transfer_start_cb
2444 * This function is called to start the USB transfer when
2445 * "xfer->interval" is greater than zero, and and the endpoint type is
2447 *------------------------------------------------------------------------*/
2449 usbd_transfer_start_cb(void *arg)
2451 struct usb_xfer *xfer = arg;
2452 struct usb_endpoint *ep = xfer->endpoint;
2454 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2459 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2462 /* the transfer can now be cancelled */
2463 xfer->flags_int.can_cancel_immed = 1;
2465 /* start USB transfer, if no error */
2466 if (xfer->error == 0)
2467 (ep->methods->start) (xfer);
2469 /* check for transfer error */
2471 /* some error has happened */
2472 usbd_transfer_done(xfer, 0);
2476 /*------------------------------------------------------------------------*
2477 * usbd_xfer_set_stall
2479 * This function is used to set the stall flag outside the
2480 * callback. This function is NULL safe.
2481 *------------------------------------------------------------------------*/
2483 usbd_xfer_set_stall(struct usb_xfer *xfer)
2489 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2491 /* avoid any races by locking the USB mutex */
2492 USB_BUS_LOCK(xfer->xroot->bus);
2493 xfer->flags.stall_pipe = 1;
2494 USB_BUS_UNLOCK(xfer->xroot->bus);
2498 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2500 return (xfer->endpoint->is_stalled);
2503 /*------------------------------------------------------------------------*
2504 * usbd_transfer_clear_stall
2506 * This function is used to clear the stall flag outside the
2507 * callback. This function is NULL safe.
2508 *------------------------------------------------------------------------*/
2510 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2516 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2518 /* avoid any races by locking the USB mutex */
2519 USB_BUS_LOCK(xfer->xroot->bus);
2521 xfer->flags.stall_pipe = 0;
2523 USB_BUS_UNLOCK(xfer->xroot->bus);
2526 /*------------------------------------------------------------------------*
2529 * This function is used to add an USB transfer to the pipe transfer list.
2530 *------------------------------------------------------------------------*/
2532 usbd_pipe_start(struct usb_xfer_queue *pq)
2534 struct usb_endpoint *ep;
2535 struct usb_xfer *xfer;
2539 ep = xfer->endpoint;
2541 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2544 * If the endpoint is already stalled we do nothing !
2546 if (ep->is_stalled) {
2550 * Check if we are supposed to stall the endpoint:
2552 if (xfer->flags.stall_pipe) {
2553 struct usb_device *udev;
2554 struct usb_xfer_root *info;
2556 /* clear stall command */
2557 xfer->flags.stall_pipe = 0;
2559 /* get pointer to USB device */
2564 * Only stall BULK and INTERRUPT endpoints.
2566 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2567 if ((type == UE_BULK) ||
2568 (type == UE_INTERRUPT)) {
2573 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2574 (udev->bus->methods->set_stall) (
2575 udev, NULL, ep, &did_stall);
2576 } else if (udev->ctrl_xfer[1]) {
2577 info = udev->ctrl_xfer[1]->xroot;
2579 &info->bus->non_giant_callback_proc,
2580 &udev->cs_msg[0], &udev->cs_msg[1]);
2582 /* should not happen */
2583 DPRINTFN(0, "No stall handler\n");
2586 * Check if we should stall. Some USB hardware
2587 * handles set- and clear-stall in hardware.
2591 * The transfer will be continued when
2592 * the clear-stall control endpoint
2593 * message is received.
2598 } else if (type == UE_ISOCHRONOUS) {
2601 * Make sure any FIFO overflow or other FIFO
2602 * error conditions go away by resetting the
2603 * endpoint FIFO through the clear stall
2606 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2607 (udev->bus->methods->clear_stall) (udev, ep);
2611 /* Set or clear stall complete - special case */
2612 if (xfer->nframes == 0) {
2613 /* we are complete */
2615 usbd_transfer_done(xfer, 0);
2621 * 1) Start the first transfer queued.
2623 * 2) Re-start the current USB transfer.
2626 * Check if there should be any
2627 * pre transfer start delay:
2629 if (xfer->interval > 0) {
2630 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2631 if ((type == UE_BULK) ||
2632 (type == UE_CONTROL)) {
2633 usbd_transfer_timeout_ms(xfer,
2634 &usbd_transfer_start_cb,
2642 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2644 /* the transfer can now be cancelled */
2645 xfer->flags_int.can_cancel_immed = 1;
2647 /* start USB transfer, if no error */
2648 if (xfer->error == 0)
2649 (ep->methods->start) (xfer);
2651 /* check for transfer error */
2653 /* some error has happened */
2654 usbd_transfer_done(xfer, 0);
2658 /*------------------------------------------------------------------------*
2659 * usbd_transfer_timeout_ms
2661 * This function is used to setup a timeout on the given USB
2662 * transfer. If the timeout has been deferred the callback given by
2663 * "cb" will get called after "ms" milliseconds.
2664 *------------------------------------------------------------------------*/
2666 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2667 void (*cb) (void *arg), usb_timeout_t ms)
2669 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2672 usb_callout_reset(&xfer->timeout_handle,
2673 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2676 /*------------------------------------------------------------------------*
2677 * usbd_callback_wrapper_sub
2679 * - This function will update variables in an USB transfer after
2680 * that the USB transfer is complete.
2682 * - This function is used to start the next USB transfer on the
2683 * ep transfer queue, if any.
2685 * NOTE: In some special cases the USB transfer will not be removed from
2686 * the pipe queue, but remain first. To enforce USB transfer removal call
2687 * this function passing the error code "USB_ERR_CANCELLED".
2691 * Else: The callback has been deferred.
2692 *------------------------------------------------------------------------*/
2694 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2696 struct usb_endpoint *ep;
2697 struct usb_bus *bus;
2700 bus = xfer->xroot->bus;
2702 if ((!xfer->flags_int.open) &&
2703 (!xfer->flags_int.did_close)) {
2706 (xfer->endpoint->methods->close) (xfer);
2707 USB_BUS_UNLOCK(bus);
2708 /* only close once */
2709 xfer->flags_int.did_close = 1;
2710 return (1); /* wait for new callback */
2713 * If we have a non-hardware induced error we
2714 * need to do the DMA delay!
2716 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2717 (xfer->error == USB_ERR_CANCELLED ||
2718 xfer->error == USB_ERR_TIMEOUT ||
2719 bus->methods->start_dma_delay != NULL)) {
2723 /* only delay once */
2724 xfer->flags_int.did_dma_delay = 1;
2726 /* we can not cancel this delay */
2727 xfer->flags_int.can_cancel_immed = 0;
2729 temp = usbd_get_dma_delay(xfer->xroot->udev);
2731 DPRINTFN(3, "DMA delay, %u ms, "
2732 "on %p\n", temp, xfer);
2737 * Some hardware solutions have dedicated
2738 * events when it is safe to free DMA'ed
2739 * memory. For the other hardware platforms we
2740 * use a static delay.
2742 if (bus->methods->start_dma_delay != NULL) {
2743 (bus->methods->start_dma_delay) (xfer);
2745 usbd_transfer_timeout_ms(xfer,
2746 (void (*)(void *))&usb_dma_delay_done_cb,
2749 USB_BUS_UNLOCK(bus);
2750 return (1); /* wait for new callback */
2753 /* check actual number of frames */
2754 if (xfer->aframes > xfer->nframes) {
2755 if (xfer->error == 0) {
2756 panic("%s: actual number of frames, %d, is "
2757 "greater than initial number of frames, %d\n",
2758 __FUNCTION__, xfer->aframes, xfer->nframes);
2760 /* just set some valid value */
2761 xfer->aframes = xfer->nframes;
2764 /* compute actual length */
2767 for (x = 0; x != xfer->aframes; x++) {
2768 xfer->actlen += xfer->frlengths[x];
2772 * Frames that were not transferred get zero actual length in
2773 * case the USB device driver does not check the actual number
2774 * of frames transferred, "xfer->aframes":
2776 for (; x < xfer->nframes; x++) {
2777 usbd_xfer_set_frame_len(xfer, x, 0);
2780 /* check actual length */
2781 if (xfer->actlen > xfer->sumlen) {
2782 if (xfer->error == 0) {
2783 panic("%s: actual length, %d, is greater than "
2784 "initial length, %d\n",
2785 __FUNCTION__, xfer->actlen, xfer->sumlen);
2787 /* just set some valid value */
2788 xfer->actlen = xfer->sumlen;
2791 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2792 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2793 xfer->aframes, xfer->nframes);
2796 /* end of control transfer, if any */
2797 xfer->flags_int.control_act = 0;
2799 #if USB_HAVE_TT_SUPPORT
2800 switch (xfer->error) {
2801 case USB_ERR_NORMAL_COMPLETION:
2802 case USB_ERR_SHORT_XFER:
2803 case USB_ERR_STALLED:
2804 case USB_ERR_CANCELLED:
2808 /* try to reset the TT, if any */
2810 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2811 USB_BUS_UNLOCK(bus);
2815 /* check if we should block the execution queue */
2816 if ((xfer->error != USB_ERR_CANCELLED) &&
2817 (xfer->flags.pipe_bof)) {
2818 DPRINTFN(2, "xfer=%p: Block On Failure "
2819 "on endpoint=%p\n", xfer, xfer->endpoint);
2823 /* check for short transfers */
2824 if (xfer->actlen < xfer->sumlen) {
2826 /* end of control transfer, if any */
2827 xfer->flags_int.control_act = 0;
2829 if (!xfer->flags_int.short_xfer_ok) {
2830 xfer->error = USB_ERR_SHORT_XFER;
2831 if (xfer->flags.pipe_bof) {
2832 DPRINTFN(2, "xfer=%p: Block On Failure on "
2833 "Short Transfer on endpoint %p.\n",
2834 xfer, xfer->endpoint);
2840 * Check if we are in the middle of a
2843 if (xfer->flags_int.control_act) {
2844 DPRINTFN(5, "xfer=%p: Control transfer "
2845 "active on endpoint=%p\n", xfer, xfer->endpoint);
2851 ep = xfer->endpoint;
2854 * If the current USB transfer is completing we need to start the
2858 if (ep->endpoint_q.curr == xfer) {
2859 usb_command_wrapper(&ep->endpoint_q, NULL);
2861 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2862 /* there is another USB transfer waiting */
2864 /* this is the last USB transfer */
2865 /* clear isochronous sync flag */
2866 xfer->endpoint->is_synced = 0;
2869 USB_BUS_UNLOCK(bus);
2874 /*------------------------------------------------------------------------*
2875 * usb_command_wrapper
2877 * This function is used to execute commands non-recursivly on an USB
2879 *------------------------------------------------------------------------*/
2881 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2885 * If the transfer is not already processing,
2888 if (pq->curr != xfer) {
2889 usbd_transfer_enqueue(pq, xfer);
2890 if (pq->curr != NULL) {
2891 /* something is already processing */
2892 DPRINTFN(6, "busy %p\n", pq->curr);
2897 /* Get next element in queue */
2901 if (!pq->recurse_1) {
2905 /* set both recurse flags */
2909 if (pq->curr == NULL) {
2910 xfer = TAILQ_FIRST(&pq->head);
2912 TAILQ_REMOVE(&pq->head, xfer,
2914 xfer->wait_queue = NULL;
2920 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2922 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2924 } while (!pq->recurse_2);
2926 /* clear first recurse flag */
2930 /* clear second recurse flag */
2935 /*------------------------------------------------------------------------*
2936 * usbd_ctrl_transfer_setup
2938 * This function is used to setup the default USB control endpoint
2940 *------------------------------------------------------------------------*/
2942 usbd_ctrl_transfer_setup(struct usb_device *udev)
2944 struct usb_xfer *xfer;
2946 uint8_t iface_index;
2948 /* check for root HUB */
2949 if (udev->parent_hub == NULL)
2953 xfer = udev->ctrl_xfer[0];
2955 USB_XFER_LOCK(xfer);
2957 ((xfer->address == udev->address) &&
2958 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2959 udev->ddesc.bMaxPacketSize));
2960 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2963 * NOTE: checking "xfer->address" and
2964 * starting the USB transfer must be
2967 usbd_transfer_start(xfer);
2970 USB_XFER_UNLOCK(xfer);
2977 * All parameters are exactly the same like before.
2983 * Update wMaxPacketSize for the default control endpoint:
2985 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2986 udev->ddesc.bMaxPacketSize;
2989 * Unsetup any existing USB transfer:
2991 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2994 * Reset clear stall error counter.
2996 udev->clear_stall_errors = 0;
2999 * Try to setup a new USB transfer for the
3000 * default control endpoint:
3003 if (usbd_transfer_setup(udev, &iface_index,
3004 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3005 &udev->device_mtx)) {
3006 DPRINTFN(0, "could not setup default "
3013 /*------------------------------------------------------------------------*
3014 * usbd_clear_data_toggle - factored out code
3016 * NOTE: the intention of this function is not to reset the hardware
3018 *------------------------------------------------------------------------*/
3020 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3022 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3024 /* check that we have a valid case */
3025 if (udev->flags.usb_mode == USB_MODE_HOST &&
3026 udev->parent_hub != NULL &&
3027 udev->bus->methods->clear_stall != NULL &&
3028 ep->methods != NULL) {
3029 (udev->bus->methods->clear_stall) (udev, ep);
3033 /*------------------------------------------------------------------------*
3034 * usbd_clear_data_toggle - factored out code
3036 * NOTE: the intention of this function is not to reset the hardware
3037 * data toggle on the USB device side.
3038 *------------------------------------------------------------------------*/
3040 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3042 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3044 USB_BUS_LOCK(udev->bus);
3045 ep->toggle_next = 0;
3046 /* some hardware needs a callback to clear the data toggle */
3047 usbd_clear_stall_locked(udev, ep);
3048 USB_BUS_UNLOCK(udev->bus);
3051 /*------------------------------------------------------------------------*
3052 * usbd_clear_stall_callback - factored out clear stall callback
3055 * xfer1: Clear Stall Control Transfer
3056 * xfer2: Stalled USB Transfer
3058 * This function is NULL safe.
3064 * Clear stall config example:
3066 * static const struct usb_config my_clearstall = {
3067 * .type = UE_CONTROL,
3069 * .direction = UE_DIR_ANY,
3070 * .interval = 50, //50 milliseconds
3071 * .bufsize = sizeof(struct usb_device_request),
3072 * .timeout = 1000, //1.000 seconds
3073 * .callback = &my_clear_stall_callback, // **
3074 * .usb_mode = USB_MODE_HOST,
3077 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3078 * passing the correct parameters.
3079 *------------------------------------------------------------------------*/
3081 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3082 struct usb_xfer *xfer2)
3084 struct usb_device_request req;
3086 if (xfer2 == NULL) {
3087 /* looks like we are tearing down */
3088 DPRINTF("NULL input parameter\n");
3091 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3092 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3094 switch (USB_GET_STATE(xfer1)) {
3098 * pre-clear the data toggle to DATA0 ("umass.c" and
3099 * "ata-usb.c" depends on this)
3102 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3104 /* setup a clear-stall packet */
3106 req.bmRequestType = UT_WRITE_ENDPOINT;
3107 req.bRequest = UR_CLEAR_FEATURE;
3108 USETW(req.wValue, UF_ENDPOINT_HALT);
3109 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3111 USETW(req.wLength, 0);
3114 * "usbd_transfer_setup_sub()" will ensure that
3115 * we have sufficient room in the buffer for
3116 * the request structure!
3119 /* copy in the transfer */
3121 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3124 xfer1->frlengths[0] = sizeof(req);
3127 usbd_transfer_submit(xfer1);
3130 case USB_ST_TRANSFERRED:
3133 default: /* Error */
3134 if (xfer1->error == USB_ERR_CANCELLED) {
3139 return (1); /* Clear Stall Finished */
3142 /*------------------------------------------------------------------------*
3143 * usbd_transfer_poll
3145 * The following function gets called from the USB keyboard driver and
3146 * UMASS when the system has paniced.
3148 * NOTE: It is currently not possible to resume normal operation on
3149 * the USB controller which has been polled, due to clearing of the
3150 * "up_dsleep" and "up_msleep" flags.
3151 *------------------------------------------------------------------------*/
3153 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3155 struct usb_xfer *xfer;
3156 struct usb_xfer_root *xroot;
3157 struct usb_device *udev;
3158 struct usb_proc_msg *pm;
3163 for (n = 0; n != max; n++) {
3164 /* Extra checks to avoid panic */
3167 continue; /* no USB transfer */
3168 xroot = xfer->xroot;
3170 continue; /* no USB root */
3173 continue; /* no USB device */
3174 if (udev->bus == NULL)
3175 continue; /* no BUS structure */
3176 if (udev->bus->methods == NULL)
3177 continue; /* no BUS methods */
3178 if (udev->bus->methods->xfer_poll == NULL)
3179 continue; /* no poll method */
3181 /* make sure that the BUS mutex is not locked */
3183 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3184 mtx_unlock(&xroot->udev->bus->bus_mtx);
3188 /* make sure that the transfer mutex is not locked */
3190 while (mtx_owned(xroot->xfer_mtx)) {
3191 mtx_unlock(xroot->xfer_mtx);
3195 /* Make sure cv_signal() and cv_broadcast() is not called */
3196 udev->bus->control_xfer_proc.up_msleep = 0;
3197 udev->bus->explore_proc.up_msleep = 0;
3198 udev->bus->giant_callback_proc.up_msleep = 0;
3199 udev->bus->non_giant_callback_proc.up_msleep = 0;
3201 /* poll USB hardware */
3202 (udev->bus->methods->xfer_poll) (udev->bus);
3204 USB_BUS_LOCK(xroot->bus);
3206 /* check for clear stall */
3207 if (udev->ctrl_xfer[1] != NULL) {
3209 /* poll clear stall start */
3210 pm = &udev->cs_msg[0].hdr;
3211 (pm->pm_callback) (pm);
3212 /* poll clear stall done thread */
3213 pm = &udev->ctrl_xfer[1]->
3214 xroot->done_m[0].hdr;
3215 (pm->pm_callback) (pm);
3218 /* poll done thread */
3219 pm = &xroot->done_m[0].hdr;
3220 (pm->pm_callback) (pm);
3222 USB_BUS_UNLOCK(xroot->bus);
3224 /* restore transfer mutex */
3226 mtx_lock(xroot->xfer_mtx);
3228 /* restore BUS mutex */
3230 mtx_lock(&xroot->udev->bus->bus_mtx);
3235 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3236 uint8_t type, enum usb_dev_speed speed)
3238 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3239 [USB_SPEED_LOW] = 8,
3240 [USB_SPEED_FULL] = 64,
3241 [USB_SPEED_HIGH] = 1024,
3242 [USB_SPEED_VARIABLE] = 1024,
3243 [USB_SPEED_SUPER] = 1024,
3246 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3247 [USB_SPEED_LOW] = 0, /* invalid */
3248 [USB_SPEED_FULL] = 1023,
3249 [USB_SPEED_HIGH] = 1024,
3250 [USB_SPEED_VARIABLE] = 3584,
3251 [USB_SPEED_SUPER] = 1024,
3254 static const uint16_t control_min[USB_SPEED_MAX] = {
3255 [USB_SPEED_LOW] = 8,
3256 [USB_SPEED_FULL] = 8,
3257 [USB_SPEED_HIGH] = 64,
3258 [USB_SPEED_VARIABLE] = 512,
3259 [USB_SPEED_SUPER] = 512,
3262 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3263 [USB_SPEED_LOW] = 8,
3264 [USB_SPEED_FULL] = 8,
3265 [USB_SPEED_HIGH] = 512,
3266 [USB_SPEED_VARIABLE] = 512,
3267 [USB_SPEED_SUPER] = 1024,
3272 memset(ptr, 0, sizeof(*ptr));
3276 ptr->range.max = intr_range_max[speed];
3278 case UE_ISOCHRONOUS:
3279 ptr->range.max = isoc_range_max[speed];
3282 if (type == UE_BULK)
3283 temp = bulk_min[speed];
3284 else /* UE_CONTROL */
3285 temp = control_min[speed];
3287 /* default is fixed */
3288 ptr->fixed[0] = temp;
3289 ptr->fixed[1] = temp;
3290 ptr->fixed[2] = temp;
3291 ptr->fixed[3] = temp;
3293 if (speed == USB_SPEED_FULL) {
3294 /* multiple sizes */
3299 if ((speed == USB_SPEED_VARIABLE) &&
3300 (type == UE_BULK)) {
3301 /* multiple sizes */
3302 ptr->fixed[2] = 1024;
3303 ptr->fixed[3] = 1536;
3310 usbd_xfer_softc(struct usb_xfer *xfer)
3312 return (xfer->priv_sc);
3316 usbd_xfer_get_priv(struct usb_xfer *xfer)
3318 return (xfer->priv_fifo);
3322 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3324 xfer->priv_fifo = ptr;
3328 usbd_xfer_state(struct usb_xfer *xfer)
3330 return (xfer->usb_state);
3334 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3337 case USB_FORCE_SHORT_XFER:
3338 xfer->flags.force_short_xfer = 1;
3340 case USB_SHORT_XFER_OK:
3341 xfer->flags.short_xfer_ok = 1;
3343 case USB_MULTI_SHORT_OK:
3344 xfer->flags.short_frames_ok = 1;
3346 case USB_MANUAL_STATUS:
3347 xfer->flags.manual_status = 1;
3353 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3356 case USB_FORCE_SHORT_XFER:
3357 xfer->flags.force_short_xfer = 0;
3359 case USB_SHORT_XFER_OK:
3360 xfer->flags.short_xfer_ok = 0;
3362 case USB_MULTI_SHORT_OK:
3363 xfer->flags.short_frames_ok = 0;
3365 case USB_MANUAL_STATUS:
3366 xfer->flags.manual_status = 0;
3372 * The following function returns in milliseconds when the isochronous
3373 * transfer was completed by the hardware. The returned value wraps
3374 * around 65536 milliseconds.
3377 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3379 return (xfer->isoc_time_complete);
3383 * The following function returns non-zero if the max packet size
3384 * field was clamped to a valid value. Else it returns zero.
3387 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3389 return (xfer->flags_int.maxp_was_clamped);