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, 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_enum_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_setup_ctrl_transfer
1350 * This function handles initialisation of control transfers. Control
1351 * transfers are special in that regard that they can both transmit
1357 *------------------------------------------------------------------------*/
1359 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1363 /* Check for control endpoint stall */
1364 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1365 /* the control transfer is no longer active */
1366 xfer->flags_int.control_stall = 1;
1367 xfer->flags_int.control_act = 0;
1369 /* don't stall control transfer by default */
1370 xfer->flags_int.control_stall = 0;
1373 /* Check for invalid number of frames */
1374 if (xfer->nframes > 2) {
1376 * If you need to split a control transfer, you
1377 * have to do one part at a time. Only with
1378 * non-control transfers you can do multiple
1381 DPRINTFN(0, "Too many frames: %u\n",
1382 (unsigned int)xfer->nframes);
1387 * Check if there is a control
1388 * transfer in progress:
1390 if (xfer->flags_int.control_act) {
1392 if (xfer->flags_int.control_hdr) {
1394 /* clear send header flag */
1396 xfer->flags_int.control_hdr = 0;
1398 /* setup control transfer */
1399 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1400 usbd_control_transfer_init(xfer);
1403 /* get data length */
1409 /* the size of the SETUP structure is hardcoded ! */
1411 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1412 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1413 xfer->frlengths[0], sizeof(struct
1414 usb_device_request));
1417 /* check USB mode */
1418 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1420 /* check number of frames */
1421 if (xfer->nframes != 1) {
1423 * We need to receive the setup
1424 * message first so that we know the
1427 DPRINTF("Misconfigured transfer\n");
1431 * Set a dummy "control_rem" value. This
1432 * variable will be overwritten later by a
1433 * call to "usbd_control_transfer_init()" !
1435 xfer->flags_int.control_rem = 0xFFFF;
1438 /* setup "endpoint" and "control_rem" */
1440 usbd_control_transfer_init(xfer);
1443 /* set transfer-header flag */
1445 xfer->flags_int.control_hdr = 1;
1447 /* get data length */
1449 len = (xfer->sumlen - sizeof(struct usb_device_request));
1452 /* check if there is a length mismatch */
1454 if (len > xfer->flags_int.control_rem) {
1455 DPRINTFN(0, "Length (%d) greater than "
1456 "remaining length (%d)\n", len,
1457 xfer->flags_int.control_rem);
1460 /* check if we are doing a short transfer */
1462 if (xfer->flags.force_short_xfer) {
1463 xfer->flags_int.control_rem = 0;
1465 if ((len != xfer->max_data_length) &&
1466 (len != xfer->flags_int.control_rem) &&
1467 (xfer->nframes != 1)) {
1468 DPRINTFN(0, "Short control transfer without "
1469 "force_short_xfer set\n");
1472 xfer->flags_int.control_rem -= len;
1475 /* the status part is executed when "control_act" is 0 */
1477 if ((xfer->flags_int.control_rem > 0) ||
1478 (xfer->flags.manual_status)) {
1479 /* don't execute the STATUS stage yet */
1480 xfer->flags_int.control_act = 1;
1483 if ((!xfer->flags_int.control_hdr) &&
1484 (xfer->nframes == 1)) {
1486 * This is not a valid operation!
1488 DPRINTFN(0, "Invalid parameter "
1493 /* time to execute the STATUS stage */
1494 xfer->flags_int.control_act = 0;
1496 return (0); /* success */
1499 return (1); /* failure */
1502 /*------------------------------------------------------------------------*
1503 * usbd_transfer_submit - start USB hardware for the given transfer
1505 * This function should only be called from the USB callback.
1506 *------------------------------------------------------------------------*/
1508 usbd_transfer_submit(struct usb_xfer *xfer)
1510 struct usb_xfer_root *info;
1511 struct usb_bus *bus;
1517 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1518 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1522 if (USB_DEBUG_VAR > 0) {
1525 usb_dump_endpoint(xfer->endpoint);
1527 USB_BUS_UNLOCK(bus);
1531 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1532 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1534 /* Only open the USB transfer once! */
1535 if (!xfer->flags_int.open) {
1536 xfer->flags_int.open = 1;
1541 (xfer->endpoint->methods->open) (xfer);
1542 USB_BUS_UNLOCK(bus);
1544 /* set "transferring" flag */
1545 xfer->flags_int.transferring = 1;
1548 /* increment power reference */
1549 usbd_transfer_power_ref(xfer, 1);
1552 * Check if the transfer is waiting on a queue, most
1553 * frequently the "done_q":
1555 if (xfer->wait_queue) {
1557 usbd_transfer_dequeue(xfer);
1558 USB_BUS_UNLOCK(bus);
1560 /* clear "did_dma_delay" flag */
1561 xfer->flags_int.did_dma_delay = 0;
1563 /* clear "did_close" flag */
1564 xfer->flags_int.did_close = 0;
1567 /* clear "bdma_setup" flag */
1568 xfer->flags_int.bdma_setup = 0;
1570 /* by default we cannot cancel any USB transfer immediately */
1571 xfer->flags_int.can_cancel_immed = 0;
1573 /* clear lengths and frame counts by default */
1578 /* clear any previous errors */
1581 /* Check if the device is still alive */
1582 if (info->udev->state < USB_STATE_POWERED) {
1585 * Must return cancelled error code else
1586 * device drivers can hang.
1588 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1589 USB_BUS_UNLOCK(bus);
1594 if (xfer->nframes == 0) {
1595 if (xfer->flags.stall_pipe) {
1597 * Special case - want to stall without transferring
1600 DPRINTF("xfer=%p nframes=0: stall "
1601 "or clear stall!\n", xfer);
1603 xfer->flags_int.can_cancel_immed = 1;
1604 /* start the transfer */
1605 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1606 USB_BUS_UNLOCK(bus);
1610 usbd_transfer_done(xfer, USB_ERR_INVAL);
1611 USB_BUS_UNLOCK(bus);
1614 /* compute some variables */
1616 for (x = 0; x != xfer->nframes; x++) {
1617 /* make a copy of the frlenghts[] */
1618 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1619 /* compute total transfer length */
1620 xfer->sumlen += xfer->frlengths[x];
1621 if (xfer->sumlen < xfer->frlengths[x]) {
1622 /* length wrapped around */
1624 usbd_transfer_done(xfer, USB_ERR_INVAL);
1625 USB_BUS_UNLOCK(bus);
1630 /* clear some internal flags */
1632 xfer->flags_int.short_xfer_ok = 0;
1633 xfer->flags_int.short_frames_ok = 0;
1635 /* check if this is a control transfer */
1637 if (xfer->flags_int.control_xfr) {
1639 if (usbd_setup_ctrl_transfer(xfer)) {
1641 usbd_transfer_done(xfer, USB_ERR_STALLED);
1642 USB_BUS_UNLOCK(bus);
1647 * Setup filtered version of some transfer flags,
1648 * in case of data read direction
1650 if (USB_GET_DATA_ISREAD(xfer)) {
1652 if (xfer->flags.short_frames_ok) {
1653 xfer->flags_int.short_xfer_ok = 1;
1654 xfer->flags_int.short_frames_ok = 1;
1655 } else if (xfer->flags.short_xfer_ok) {
1656 xfer->flags_int.short_xfer_ok = 1;
1658 /* check for control transfer */
1659 if (xfer->flags_int.control_xfr) {
1661 * 1) Control transfers do not support
1662 * reception of multiple short USB
1663 * frames in host mode and device side
1664 * mode, with exception of:
1666 * 2) Due to sometimes buggy device
1667 * side firmware we need to do a
1668 * STATUS stage in case of short
1669 * control transfers in USB host mode.
1670 * The STATUS stage then becomes the
1671 * "alt_next" to the DATA stage.
1673 xfer->flags_int.short_frames_ok = 1;
1678 * Check if BUS-DMA support is enabled and try to load virtual
1679 * buffers into DMA, if any:
1682 if (xfer->flags_int.bdma_enable) {
1683 /* insert the USB transfer last in the BUS-DMA queue */
1684 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1689 * Enter the USB transfer into the Host Controller or
1690 * Device Controller schedule:
1692 usbd_pipe_enter(xfer);
1695 /*------------------------------------------------------------------------*
1696 * usbd_pipe_enter - factored out code
1697 *------------------------------------------------------------------------*/
1699 usbd_pipe_enter(struct usb_xfer *xfer)
1701 struct usb_endpoint *ep;
1703 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1705 USB_BUS_LOCK(xfer->xroot->bus);
1707 ep = xfer->endpoint;
1711 /* the transfer can now be cancelled */
1712 xfer->flags_int.can_cancel_immed = 1;
1714 /* enter the transfer */
1715 (ep->methods->enter) (xfer);
1717 /* check for transfer error */
1719 /* some error has happened */
1720 usbd_transfer_done(xfer, 0);
1721 USB_BUS_UNLOCK(xfer->xroot->bus);
1725 /* start the transfer */
1726 usb_command_wrapper(&ep->endpoint_q, xfer);
1727 USB_BUS_UNLOCK(xfer->xroot->bus);
1730 /*------------------------------------------------------------------------*
1731 * usbd_transfer_start - start an USB transfer
1733 * NOTE: Calling this function more than one time will only
1734 * result in a single transfer start, until the USB transfer
1736 *------------------------------------------------------------------------*/
1738 usbd_transfer_start(struct usb_xfer *xfer)
1741 /* transfer is gone */
1744 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1746 /* mark the USB transfer started */
1748 if (!xfer->flags_int.started) {
1749 /* lock the BUS lock to avoid races updating flags_int */
1750 USB_BUS_LOCK(xfer->xroot->bus);
1751 xfer->flags_int.started = 1;
1752 USB_BUS_UNLOCK(xfer->xroot->bus);
1754 /* check if the USB transfer callback is already transferring */
1756 if (xfer->flags_int.transferring) {
1759 USB_BUS_LOCK(xfer->xroot->bus);
1760 /* call the USB transfer callback */
1761 usbd_callback_ss_done_defer(xfer);
1762 USB_BUS_UNLOCK(xfer->xroot->bus);
1765 /*------------------------------------------------------------------------*
1766 * usbd_transfer_stop - stop an USB transfer
1768 * NOTE: Calling this function more than one time will only
1769 * result in a single transfer stop.
1770 * NOTE: When this function returns it is not safe to free nor
1771 * reuse any DMA buffers. See "usbd_transfer_drain()".
1772 *------------------------------------------------------------------------*/
1774 usbd_transfer_stop(struct usb_xfer *xfer)
1776 struct usb_endpoint *ep;
1779 /* transfer is gone */
1782 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1784 /* check if the USB transfer was ever opened */
1786 if (!xfer->flags_int.open) {
1787 if (xfer->flags_int.started) {
1788 /* nothing to do except clearing the "started" flag */
1789 /* lock the BUS lock to avoid races updating flags_int */
1790 USB_BUS_LOCK(xfer->xroot->bus);
1791 xfer->flags_int.started = 0;
1792 USB_BUS_UNLOCK(xfer->xroot->bus);
1796 /* try to stop the current USB transfer */
1798 USB_BUS_LOCK(xfer->xroot->bus);
1799 /* override any previous error */
1800 xfer->error = USB_ERR_CANCELLED;
1803 * Clear "open" and "started" when both private and USB lock
1804 * is locked so that we don't get a race updating "flags_int"
1806 xfer->flags_int.open = 0;
1807 xfer->flags_int.started = 0;
1810 * Check if we can cancel the USB transfer immediately.
1812 if (xfer->flags_int.transferring) {
1813 if (xfer->flags_int.can_cancel_immed &&
1814 (!xfer->flags_int.did_close)) {
1817 * The following will lead to an USB_ERR_CANCELLED
1818 * error code being passed to the USB callback.
1820 (xfer->endpoint->methods->close) (xfer);
1821 /* only close once */
1822 xfer->flags_int.did_close = 1;
1824 /* need to wait for the next done callback */
1829 /* close here and now */
1830 (xfer->endpoint->methods->close) (xfer);
1833 * Any additional DMA delay is done by
1834 * "usbd_transfer_unsetup()".
1838 * Special case. Check if we need to restart a blocked
1841 ep = xfer->endpoint;
1844 * If the current USB transfer is completing we need
1845 * to start the next one:
1847 if (ep->endpoint_q.curr == xfer) {
1848 usb_command_wrapper(&ep->endpoint_q, NULL);
1852 USB_BUS_UNLOCK(xfer->xroot->bus);
1855 /*------------------------------------------------------------------------*
1856 * usbd_transfer_pending
1858 * This function will check if an USB transfer is pending which is a
1859 * little bit complicated!
1862 * 1: Pending: The USB transfer will receive a callback in the future.
1863 *------------------------------------------------------------------------*/
1865 usbd_transfer_pending(struct usb_xfer *xfer)
1867 struct usb_xfer_root *info;
1868 struct usb_xfer_queue *pq;
1871 /* transfer is gone */
1874 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1876 if (xfer->flags_int.transferring) {
1880 USB_BUS_LOCK(xfer->xroot->bus);
1881 if (xfer->wait_queue) {
1882 /* we are waiting on a queue somewhere */
1883 USB_BUS_UNLOCK(xfer->xroot->bus);
1889 if (pq->curr == xfer) {
1890 /* we are currently scheduled for callback */
1891 USB_BUS_UNLOCK(xfer->xroot->bus);
1894 /* we are not pending */
1895 USB_BUS_UNLOCK(xfer->xroot->bus);
1899 /*------------------------------------------------------------------------*
1900 * usbd_transfer_drain
1902 * This function will stop the USB transfer and wait for any
1903 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1904 * are loaded into DMA can safely be freed or reused after that this
1905 * function has returned.
1906 *------------------------------------------------------------------------*/
1908 usbd_transfer_drain(struct usb_xfer *xfer)
1910 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1911 "usbd_transfer_drain can sleep!");
1914 /* transfer is gone */
1917 if (xfer->xroot->xfer_mtx != &Giant) {
1918 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1920 USB_XFER_LOCK(xfer);
1922 usbd_transfer_stop(xfer);
1924 while (usbd_transfer_pending(xfer) ||
1925 xfer->flags_int.doing_callback) {
1928 * It is allowed that the callback can drop its
1929 * transfer mutex. In that case checking only
1930 * "usbd_transfer_pending()" is not enough to tell if
1931 * the USB transfer is fully drained. We also need to
1932 * check the internal "doing_callback" flag.
1934 xfer->flags_int.draining = 1;
1937 * Wait until the current outstanding USB
1938 * transfer is complete !
1940 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1942 USB_XFER_UNLOCK(xfer);
1945 struct usb_page_cache *
1946 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1948 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1950 return (&xfer->frbuffers[frindex]);
1954 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
1956 struct usb_page_search page_info;
1958 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1960 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
1961 return (page_info.buffer);
1964 /*------------------------------------------------------------------------*
1965 * usbd_xfer_get_fps_shift
1967 * The following function is only useful for isochronous transfers. It
1968 * returns how many times the frame execution rate has been shifted
1974 *------------------------------------------------------------------------*/
1976 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1978 return (xfer->fps_shift);
1982 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1984 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1986 return (xfer->frlengths[frindex]);
1989 /*------------------------------------------------------------------------*
1990 * usbd_xfer_set_frame_data
1992 * This function sets the pointer of the buffer that should
1993 * loaded directly into DMA for the given USB frame. Passing "ptr"
1994 * equal to NULL while the corresponding "frlength" is greater
1995 * than zero gives undefined results!
1996 *------------------------------------------------------------------------*/
1998 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1999 void *ptr, usb_frlength_t len)
2001 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2003 /* set virtual address to load and length */
2004 xfer->frbuffers[frindex].buffer = ptr;
2005 usbd_xfer_set_frame_len(xfer, frindex, len);
2009 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2010 void **ptr, int *len)
2012 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2015 *ptr = xfer->frbuffers[frindex].buffer;
2017 *len = xfer->frlengths[frindex];
2020 /*------------------------------------------------------------------------*
2021 * usbd_xfer_old_frame_length
2023 * This function returns the framelength of the given frame at the
2024 * time the transfer was submitted. This function can be used to
2025 * compute the starting data pointer of the next isochronous frame
2026 * when an isochronous transfer has completed.
2027 *------------------------------------------------------------------------*/
2029 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2031 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2033 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2037 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2041 *actlen = xfer->actlen;
2043 *sumlen = xfer->sumlen;
2044 if (aframes != NULL)
2045 *aframes = xfer->aframes;
2046 if (nframes != NULL)
2047 *nframes = xfer->nframes;
2050 /*------------------------------------------------------------------------*
2051 * usbd_xfer_set_frame_offset
2053 * This function sets the frame data buffer offset relative to the beginning
2054 * of the USB DMA buffer allocated for this USB transfer.
2055 *------------------------------------------------------------------------*/
2057 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2058 usb_frcount_t frindex)
2060 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2061 "when the USB buffer is external\n"));
2062 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2064 /* set virtual address to load */
2065 xfer->frbuffers[frindex].buffer =
2066 USB_ADD_BYTES(xfer->local_buffer, offset);
2070 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2076 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2082 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2088 usbd_xfer_max_frames(struct usb_xfer *xfer)
2090 return (xfer->max_frame_count);
2094 usbd_xfer_max_len(struct usb_xfer *xfer)
2096 return (xfer->max_data_length);
2100 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2102 return (xfer->max_frame_size);
2106 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2109 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2111 xfer->frlengths[frindex] = len;
2114 /*------------------------------------------------------------------------*
2115 * usb_callback_proc - factored out code
2117 * This function performs USB callbacks.
2118 *------------------------------------------------------------------------*/
2120 usb_callback_proc(struct usb_proc_msg *_pm)
2122 struct usb_done_msg *pm = (void *)_pm;
2123 struct usb_xfer_root *info = pm->xroot;
2125 /* Change locking order */
2126 USB_BUS_UNLOCK(info->bus);
2129 * We exploit the fact that the mutex is the same for all
2130 * callbacks that will be called from this thread:
2132 mtx_lock(info->xfer_mtx);
2133 USB_BUS_LOCK(info->bus);
2135 /* Continue where we lost track */
2136 usb_command_wrapper(&info->done_q,
2139 mtx_unlock(info->xfer_mtx);
2142 /*------------------------------------------------------------------------*
2143 * usbd_callback_ss_done_defer
2145 * This function will defer the start, stop and done callback to the
2147 *------------------------------------------------------------------------*/
2149 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2151 struct usb_xfer_root *info = xfer->xroot;
2152 struct usb_xfer_queue *pq = &info->done_q;
2154 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2156 if (pq->curr != xfer) {
2157 usbd_transfer_enqueue(pq, xfer);
2159 if (!pq->recurse_1) {
2162 * We have to postpone the callback due to the fact we
2163 * will have a Lock Order Reversal, LOR, if we try to
2166 if (usb_proc_msignal(info->done_p,
2167 &info->done_m[0], &info->done_m[1])) {
2171 /* clear second recurse flag */
2178 /*------------------------------------------------------------------------*
2179 * usbd_callback_wrapper
2181 * This is a wrapper for USB callbacks. This wrapper does some
2182 * auto-magic things like figuring out if we can call the callback
2183 * directly from the current context or if we need to wakeup the
2184 * interrupt process.
2185 *------------------------------------------------------------------------*/
2187 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2189 struct usb_xfer *xfer = pq->curr;
2190 struct usb_xfer_root *info = xfer->xroot;
2192 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2193 if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2195 * Cases that end up here:
2197 * 5) HW interrupt done callback or other source.
2199 DPRINTFN(3, "case 5\n");
2202 * We have to postpone the callback due to the fact we
2203 * will have a Lock Order Reversal, LOR, if we try to
2206 if (usb_proc_msignal(info->done_p,
2207 &info->done_m[0], &info->done_m[1])) {
2213 * Cases that end up here:
2215 * 1) We are starting a transfer
2216 * 2) We are prematurely calling back a transfer
2217 * 3) We are stopping a transfer
2218 * 4) We are doing an ordinary callback
2220 DPRINTFN(3, "case 1-4\n");
2221 /* get next USB transfer in the queue */
2222 info->done_q.curr = NULL;
2224 /* set flag in case of drain */
2225 xfer->flags_int.doing_callback = 1;
2227 USB_BUS_UNLOCK(info->bus);
2228 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2230 /* set correct USB state for callback */
2231 if (!xfer->flags_int.transferring) {
2232 xfer->usb_state = USB_ST_SETUP;
2233 if (!xfer->flags_int.started) {
2234 /* we got stopped before we even got started */
2235 USB_BUS_LOCK(info->bus);
2240 if (usbd_callback_wrapper_sub(xfer)) {
2241 /* the callback has been deferred */
2242 USB_BUS_LOCK(info->bus);
2246 /* decrement power reference */
2247 usbd_transfer_power_ref(xfer, -1);
2249 xfer->flags_int.transferring = 0;
2252 xfer->usb_state = USB_ST_ERROR;
2254 /* set transferred state */
2255 xfer->usb_state = USB_ST_TRANSFERRED;
2257 /* sync DMA memory, if any */
2258 if (xfer->flags_int.bdma_enable &&
2259 (!xfer->flags_int.bdma_no_post_sync)) {
2260 usb_bdma_post_sync(xfer);
2267 if (xfer->usb_state != USB_ST_SETUP)
2268 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2270 /* call processing routine */
2271 (xfer->callback) (xfer, xfer->error);
2273 /* pickup the USB mutex again */
2274 USB_BUS_LOCK(info->bus);
2277 * Check if we got started after that we got cancelled, but
2278 * before we managed to do the callback.
2280 if ((!xfer->flags_int.open) &&
2281 (xfer->flags_int.started) &&
2282 (xfer->usb_state == USB_ST_ERROR)) {
2283 /* clear flag in case of drain */
2284 xfer->flags_int.doing_callback = 0;
2285 /* try to loop, but not recursivly */
2286 usb_command_wrapper(&info->done_q, xfer);
2291 /* clear flag in case of drain */
2292 xfer->flags_int.doing_callback = 0;
2295 * Check if we are draining.
2297 if (xfer->flags_int.draining &&
2298 (!xfer->flags_int.transferring)) {
2299 /* "usbd_transfer_drain()" is waiting for end of transfer */
2300 xfer->flags_int.draining = 0;
2301 cv_broadcast(&info->cv_drain);
2304 /* do the next callback, if any */
2305 usb_command_wrapper(&info->done_q,
2309 /*------------------------------------------------------------------------*
2310 * usb_dma_delay_done_cb
2312 * This function is called when the DMA delay has been exectuded, and
2313 * will make sure that the callback is called to complete the USB
2314 * transfer. This code path is ususally only used when there is an USB
2315 * error like USB_ERR_CANCELLED.
2316 *------------------------------------------------------------------------*/
2318 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2320 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2322 DPRINTFN(3, "Completed %p\n", xfer);
2324 /* queue callback for execution, again */
2325 usbd_transfer_done(xfer, 0);
2328 /*------------------------------------------------------------------------*
2329 * usbd_transfer_dequeue
2331 * - This function is used to remove an USB transfer from a USB
2334 * - This function can be called multiple times in a row.
2335 *------------------------------------------------------------------------*/
2337 usbd_transfer_dequeue(struct usb_xfer *xfer)
2339 struct usb_xfer_queue *pq;
2341 pq = xfer->wait_queue;
2343 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2344 xfer->wait_queue = NULL;
2348 /*------------------------------------------------------------------------*
2349 * usbd_transfer_enqueue
2351 * - This function is used to insert an USB transfer into a USB *
2354 * - This function can be called multiple times in a row.
2355 *------------------------------------------------------------------------*/
2357 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2360 * Insert the USB transfer into the queue, if it is not
2361 * already on a USB transfer queue:
2363 if (xfer->wait_queue == NULL) {
2364 xfer->wait_queue = pq;
2365 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2369 /*------------------------------------------------------------------------*
2370 * usbd_transfer_done
2372 * - This function is used to remove an USB transfer from the busdma,
2373 * pipe or interrupt queue.
2375 * - This function is used to queue the USB transfer on the done
2378 * - This function is used to stop any USB transfer timeouts.
2379 *------------------------------------------------------------------------*/
2381 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2383 struct usb_xfer_root *info = xfer->xroot;
2385 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2387 DPRINTF("err=%s\n", usbd_errstr(error));
2390 * If we are not transferring then just return.
2391 * This can happen during transfer cancel.
2393 if (!xfer->flags_int.transferring) {
2394 DPRINTF("not transferring\n");
2395 /* end of control transfer, if any */
2396 xfer->flags_int.control_act = 0;
2399 /* only set transfer error, if not already set */
2400 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2401 xfer->error = error;
2403 /* stop any callouts */
2404 usb_callout_stop(&xfer->timeout_handle);
2407 * If we are waiting on a queue, just remove the USB transfer
2408 * from the queue, if any. We should have the required locks
2409 * locked to do the remove when this function is called.
2411 usbd_transfer_dequeue(xfer);
2414 if (mtx_owned(info->xfer_mtx)) {
2415 struct usb_xfer_queue *pq;
2418 * If the private USB lock is not locked, then we assume
2419 * that the BUS-DMA load stage has been passed:
2423 if (pq->curr == xfer) {
2424 /* start the next BUS-DMA load, if any */
2425 usb_command_wrapper(pq, NULL);
2429 /* keep some statistics */
2431 info->bus->stats_err.uds_requests
2432 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2434 info->bus->stats_ok.uds_requests
2435 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2438 /* call the USB transfer callback */
2439 usbd_callback_ss_done_defer(xfer);
2442 /*------------------------------------------------------------------------*
2443 * usbd_transfer_start_cb
2445 * This function is called to start the USB transfer when
2446 * "xfer->interval" is greater than zero, and and the endpoint type is
2448 *------------------------------------------------------------------------*/
2450 usbd_transfer_start_cb(void *arg)
2452 struct usb_xfer *xfer = arg;
2453 struct usb_endpoint *ep = xfer->endpoint;
2455 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2460 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2463 /* the transfer can now be cancelled */
2464 xfer->flags_int.can_cancel_immed = 1;
2466 /* start USB transfer, if no error */
2467 if (xfer->error == 0)
2468 (ep->methods->start) (xfer);
2470 /* check for transfer error */
2472 /* some error has happened */
2473 usbd_transfer_done(xfer, 0);
2477 /*------------------------------------------------------------------------*
2478 * usbd_xfer_set_stall
2480 * This function is used to set the stall flag outside the
2481 * callback. This function is NULL safe.
2482 *------------------------------------------------------------------------*/
2484 usbd_xfer_set_stall(struct usb_xfer *xfer)
2490 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2492 /* avoid any races by locking the USB mutex */
2493 USB_BUS_LOCK(xfer->xroot->bus);
2494 xfer->flags.stall_pipe = 1;
2495 USB_BUS_UNLOCK(xfer->xroot->bus);
2499 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2501 return (xfer->endpoint->is_stalled);
2504 /*------------------------------------------------------------------------*
2505 * usbd_transfer_clear_stall
2507 * This function is used to clear the stall flag outside the
2508 * callback. This function is NULL safe.
2509 *------------------------------------------------------------------------*/
2511 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2517 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2519 /* avoid any races by locking the USB mutex */
2520 USB_BUS_LOCK(xfer->xroot->bus);
2522 xfer->flags.stall_pipe = 0;
2524 USB_BUS_UNLOCK(xfer->xroot->bus);
2527 /*------------------------------------------------------------------------*
2530 * This function is used to add an USB transfer to the pipe transfer list.
2531 *------------------------------------------------------------------------*/
2533 usbd_pipe_start(struct usb_xfer_queue *pq)
2535 struct usb_endpoint *ep;
2536 struct usb_xfer *xfer;
2540 ep = xfer->endpoint;
2542 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2545 * If the endpoint is already stalled we do nothing !
2547 if (ep->is_stalled) {
2551 * Check if we are supposed to stall the endpoint:
2553 if (xfer->flags.stall_pipe) {
2554 struct usb_device *udev;
2555 struct usb_xfer_root *info;
2557 /* clear stall command */
2558 xfer->flags.stall_pipe = 0;
2560 /* get pointer to USB device */
2565 * Only stall BULK and INTERRUPT endpoints.
2567 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2568 if ((type == UE_BULK) ||
2569 (type == UE_INTERRUPT)) {
2574 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2575 (udev->bus->methods->set_stall) (
2576 udev, NULL, ep, &did_stall);
2577 } else if (udev->ctrl_xfer[1]) {
2578 info = udev->ctrl_xfer[1]->xroot;
2580 &info->bus->non_giant_callback_proc,
2581 &udev->cs_msg[0], &udev->cs_msg[1]);
2583 /* should not happen */
2584 DPRINTFN(0, "No stall handler\n");
2587 * Check if we should stall. Some USB hardware
2588 * handles set- and clear-stall in hardware.
2592 * The transfer will be continued when
2593 * the clear-stall control endpoint
2594 * message is received.
2599 } else if (type == UE_ISOCHRONOUS) {
2602 * Make sure any FIFO overflow or other FIFO
2603 * error conditions go away by resetting the
2604 * endpoint FIFO through the clear stall
2607 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2608 (udev->bus->methods->clear_stall) (udev, ep);
2612 /* Set or clear stall complete - special case */
2613 if (xfer->nframes == 0) {
2614 /* we are complete */
2616 usbd_transfer_done(xfer, 0);
2622 * 1) Start the first transfer queued.
2624 * 2) Re-start the current USB transfer.
2627 * Check if there should be any
2628 * pre transfer start delay:
2630 if (xfer->interval > 0) {
2631 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2632 if ((type == UE_BULK) ||
2633 (type == UE_CONTROL)) {
2634 usbd_transfer_timeout_ms(xfer,
2635 &usbd_transfer_start_cb,
2643 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2645 /* the transfer can now be cancelled */
2646 xfer->flags_int.can_cancel_immed = 1;
2648 /* start USB transfer, if no error */
2649 if (xfer->error == 0)
2650 (ep->methods->start) (xfer);
2652 /* check for transfer error */
2654 /* some error has happened */
2655 usbd_transfer_done(xfer, 0);
2659 /*------------------------------------------------------------------------*
2660 * usbd_transfer_timeout_ms
2662 * This function is used to setup a timeout on the given USB
2663 * transfer. If the timeout has been deferred the callback given by
2664 * "cb" will get called after "ms" milliseconds.
2665 *------------------------------------------------------------------------*/
2667 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2668 void (*cb) (void *arg), usb_timeout_t ms)
2670 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2673 usb_callout_reset(&xfer->timeout_handle,
2674 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2677 /*------------------------------------------------------------------------*
2678 * usbd_callback_wrapper_sub
2680 * - This function will update variables in an USB transfer after
2681 * that the USB transfer is complete.
2683 * - This function is used to start the next USB transfer on the
2684 * ep transfer queue, if any.
2686 * NOTE: In some special cases the USB transfer will not be removed from
2687 * the pipe queue, but remain first. To enforce USB transfer removal call
2688 * this function passing the error code "USB_ERR_CANCELLED".
2692 * Else: The callback has been deferred.
2693 *------------------------------------------------------------------------*/
2695 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2697 struct usb_endpoint *ep;
2698 struct usb_bus *bus;
2701 bus = xfer->xroot->bus;
2703 if ((!xfer->flags_int.open) &&
2704 (!xfer->flags_int.did_close)) {
2707 (xfer->endpoint->methods->close) (xfer);
2708 USB_BUS_UNLOCK(bus);
2709 /* only close once */
2710 xfer->flags_int.did_close = 1;
2711 return (1); /* wait for new callback */
2714 * If we have a non-hardware induced error we
2715 * need to do the DMA delay!
2717 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2718 (xfer->error == USB_ERR_CANCELLED ||
2719 xfer->error == USB_ERR_TIMEOUT ||
2720 bus->methods->start_dma_delay != NULL)) {
2724 /* only delay once */
2725 xfer->flags_int.did_dma_delay = 1;
2727 /* we can not cancel this delay */
2728 xfer->flags_int.can_cancel_immed = 0;
2730 temp = usbd_get_dma_delay(xfer->xroot->udev);
2732 DPRINTFN(3, "DMA delay, %u ms, "
2733 "on %p\n", temp, xfer);
2738 * Some hardware solutions have dedicated
2739 * events when it is safe to free DMA'ed
2740 * memory. For the other hardware platforms we
2741 * use a static delay.
2743 if (bus->methods->start_dma_delay != NULL) {
2744 (bus->methods->start_dma_delay) (xfer);
2746 usbd_transfer_timeout_ms(xfer,
2747 (void (*)(void *))&usb_dma_delay_done_cb,
2750 USB_BUS_UNLOCK(bus);
2751 return (1); /* wait for new callback */
2754 /* check actual number of frames */
2755 if (xfer->aframes > xfer->nframes) {
2756 if (xfer->error == 0) {
2757 panic("%s: actual number of frames, %d, is "
2758 "greater than initial number of frames, %d\n",
2759 __FUNCTION__, xfer->aframes, xfer->nframes);
2761 /* just set some valid value */
2762 xfer->aframes = xfer->nframes;
2765 /* compute actual length */
2768 for (x = 0; x != xfer->aframes; x++) {
2769 xfer->actlen += xfer->frlengths[x];
2773 * Frames that were not transferred get zero actual length in
2774 * case the USB device driver does not check the actual number
2775 * of frames transferred, "xfer->aframes":
2777 for (; x < xfer->nframes; x++) {
2778 usbd_xfer_set_frame_len(xfer, x, 0);
2781 /* check actual length */
2782 if (xfer->actlen > xfer->sumlen) {
2783 if (xfer->error == 0) {
2784 panic("%s: actual length, %d, is greater than "
2785 "initial length, %d\n",
2786 __FUNCTION__, xfer->actlen, xfer->sumlen);
2788 /* just set some valid value */
2789 xfer->actlen = xfer->sumlen;
2792 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2793 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2794 xfer->aframes, xfer->nframes);
2797 /* end of control transfer, if any */
2798 xfer->flags_int.control_act = 0;
2800 #if USB_HAVE_TT_SUPPORT
2801 switch (xfer->error) {
2802 case USB_ERR_NORMAL_COMPLETION:
2803 case USB_ERR_SHORT_XFER:
2804 case USB_ERR_STALLED:
2805 case USB_ERR_CANCELLED:
2809 /* try to reset the TT, if any */
2811 uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2812 USB_BUS_UNLOCK(bus);
2816 /* check if we should block the execution queue */
2817 if ((xfer->error != USB_ERR_CANCELLED) &&
2818 (xfer->flags.pipe_bof)) {
2819 DPRINTFN(2, "xfer=%p: Block On Failure "
2820 "on endpoint=%p\n", xfer, xfer->endpoint);
2824 /* check for short transfers */
2825 if (xfer->actlen < xfer->sumlen) {
2827 /* end of control transfer, if any */
2828 xfer->flags_int.control_act = 0;
2830 if (!xfer->flags_int.short_xfer_ok) {
2831 xfer->error = USB_ERR_SHORT_XFER;
2832 if (xfer->flags.pipe_bof) {
2833 DPRINTFN(2, "xfer=%p: Block On Failure on "
2834 "Short Transfer on endpoint %p.\n",
2835 xfer, xfer->endpoint);
2841 * Check if we are in the middle of a
2844 if (xfer->flags_int.control_act) {
2845 DPRINTFN(5, "xfer=%p: Control transfer "
2846 "active on endpoint=%p\n", xfer, xfer->endpoint);
2852 ep = xfer->endpoint;
2855 * If the current USB transfer is completing we need to start the
2859 if (ep->endpoint_q.curr == xfer) {
2860 usb_command_wrapper(&ep->endpoint_q, NULL);
2862 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2863 /* there is another USB transfer waiting */
2865 /* this is the last USB transfer */
2866 /* clear isochronous sync flag */
2867 xfer->endpoint->is_synced = 0;
2870 USB_BUS_UNLOCK(bus);
2875 /*------------------------------------------------------------------------*
2876 * usb_command_wrapper
2878 * This function is used to execute commands non-recursivly on an USB
2880 *------------------------------------------------------------------------*/
2882 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2886 * If the transfer is not already processing,
2889 if (pq->curr != xfer) {
2890 usbd_transfer_enqueue(pq, xfer);
2891 if (pq->curr != NULL) {
2892 /* something is already processing */
2893 DPRINTFN(6, "busy %p\n", pq->curr);
2898 /* Get next element in queue */
2902 if (!pq->recurse_1) {
2906 /* set both recurse flags */
2910 if (pq->curr == NULL) {
2911 xfer = TAILQ_FIRST(&pq->head);
2913 TAILQ_REMOVE(&pq->head, xfer,
2915 xfer->wait_queue = NULL;
2921 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2923 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2925 } while (!pq->recurse_2);
2927 /* clear first recurse flag */
2931 /* clear second recurse flag */
2936 /*------------------------------------------------------------------------*
2937 * usbd_ctrl_transfer_setup
2939 * This function is used to setup the default USB control endpoint
2941 *------------------------------------------------------------------------*/
2943 usbd_ctrl_transfer_setup(struct usb_device *udev)
2945 struct usb_xfer *xfer;
2947 uint8_t iface_index;
2949 /* check for root HUB */
2950 if (udev->parent_hub == NULL)
2954 xfer = udev->ctrl_xfer[0];
2956 USB_XFER_LOCK(xfer);
2958 ((xfer->address == udev->address) &&
2959 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2960 udev->ddesc.bMaxPacketSize));
2961 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2964 * NOTE: checking "xfer->address" and
2965 * starting the USB transfer must be
2968 usbd_transfer_start(xfer);
2971 USB_XFER_UNLOCK(xfer);
2978 * All parameters are exactly the same like before.
2984 * Update wMaxPacketSize for the default control endpoint:
2986 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2987 udev->ddesc.bMaxPacketSize;
2990 * Unsetup any existing USB transfer:
2992 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2995 * Reset clear stall error counter.
2997 udev->clear_stall_errors = 0;
3000 * Try to setup a new USB transfer for the
3001 * default control endpoint:
3004 if (usbd_transfer_setup(udev, &iface_index,
3005 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3006 &udev->device_mtx)) {
3007 DPRINTFN(0, "could not setup default "
3014 /*------------------------------------------------------------------------*
3015 * usbd_clear_data_toggle - factored out code
3017 * NOTE: the intention of this function is not to reset the hardware
3019 *------------------------------------------------------------------------*/
3021 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3023 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3025 /* check that we have a valid case */
3026 if (udev->flags.usb_mode == USB_MODE_HOST &&
3027 udev->parent_hub != NULL &&
3028 udev->bus->methods->clear_stall != NULL &&
3029 ep->methods != NULL) {
3030 (udev->bus->methods->clear_stall) (udev, ep);
3034 /*------------------------------------------------------------------------*
3035 * usbd_clear_data_toggle - factored out code
3037 * NOTE: the intention of this function is not to reset the hardware
3038 * data toggle on the USB device side.
3039 *------------------------------------------------------------------------*/
3041 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3043 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3045 USB_BUS_LOCK(udev->bus);
3046 ep->toggle_next = 0;
3047 /* some hardware needs a callback to clear the data toggle */
3048 usbd_clear_stall_locked(udev, ep);
3049 USB_BUS_UNLOCK(udev->bus);
3052 /*------------------------------------------------------------------------*
3053 * usbd_clear_stall_callback - factored out clear stall callback
3056 * xfer1: Clear Stall Control Transfer
3057 * xfer2: Stalled USB Transfer
3059 * This function is NULL safe.
3065 * Clear stall config example:
3067 * static const struct usb_config my_clearstall = {
3068 * .type = UE_CONTROL,
3070 * .direction = UE_DIR_ANY,
3071 * .interval = 50, //50 milliseconds
3072 * .bufsize = sizeof(struct usb_device_request),
3073 * .timeout = 1000, //1.000 seconds
3074 * .callback = &my_clear_stall_callback, // **
3075 * .usb_mode = USB_MODE_HOST,
3078 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3079 * passing the correct parameters.
3080 *------------------------------------------------------------------------*/
3082 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3083 struct usb_xfer *xfer2)
3085 struct usb_device_request req;
3087 if (xfer2 == NULL) {
3088 /* looks like we are tearing down */
3089 DPRINTF("NULL input parameter\n");
3092 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3093 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3095 switch (USB_GET_STATE(xfer1)) {
3099 * pre-clear the data toggle to DATA0 ("umass.c" and
3100 * "ata-usb.c" depends on this)
3103 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3105 /* setup a clear-stall packet */
3107 req.bmRequestType = UT_WRITE_ENDPOINT;
3108 req.bRequest = UR_CLEAR_FEATURE;
3109 USETW(req.wValue, UF_ENDPOINT_HALT);
3110 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3112 USETW(req.wLength, 0);
3115 * "usbd_transfer_setup_sub()" will ensure that
3116 * we have sufficient room in the buffer for
3117 * the request structure!
3120 /* copy in the transfer */
3122 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3125 xfer1->frlengths[0] = sizeof(req);
3128 usbd_transfer_submit(xfer1);
3131 case USB_ST_TRANSFERRED:
3134 default: /* Error */
3135 if (xfer1->error == USB_ERR_CANCELLED) {
3140 return (1); /* Clear Stall Finished */
3143 /*------------------------------------------------------------------------*
3144 * usbd_transfer_poll
3146 * The following function gets called from the USB keyboard driver and
3147 * UMASS when the system has paniced.
3149 * NOTE: It is currently not possible to resume normal operation on
3150 * the USB controller which has been polled, due to clearing of the
3151 * "up_dsleep" and "up_msleep" flags.
3152 *------------------------------------------------------------------------*/
3154 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3156 struct usb_xfer *xfer;
3157 struct usb_xfer_root *xroot;
3158 struct usb_device *udev;
3159 struct usb_proc_msg *pm;
3164 for (n = 0; n != max; n++) {
3165 /* Extra checks to avoid panic */
3168 continue; /* no USB transfer */
3169 xroot = xfer->xroot;
3171 continue; /* no USB root */
3174 continue; /* no USB device */
3175 if (udev->bus == NULL)
3176 continue; /* no BUS structure */
3177 if (udev->bus->methods == NULL)
3178 continue; /* no BUS methods */
3179 if (udev->bus->methods->xfer_poll == NULL)
3180 continue; /* no poll method */
3182 /* make sure that the BUS mutex is not locked */
3184 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3185 mtx_unlock(&xroot->udev->bus->bus_mtx);
3189 /* make sure that the transfer mutex is not locked */
3191 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3192 mtx_unlock(xroot->xfer_mtx);
3196 /* Make sure cv_signal() and cv_broadcast() is not called */
3197 udev->bus->control_xfer_proc.up_msleep = 0;
3198 udev->bus->explore_proc.up_msleep = 0;
3199 udev->bus->giant_callback_proc.up_msleep = 0;
3200 udev->bus->non_giant_callback_proc.up_msleep = 0;
3202 /* poll USB hardware */
3203 (udev->bus->methods->xfer_poll) (udev->bus);
3205 USB_BUS_LOCK(xroot->bus);
3207 /* check for clear stall */
3208 if (udev->ctrl_xfer[1] != NULL) {
3210 /* poll clear stall start */
3211 pm = &udev->cs_msg[0].hdr;
3212 (pm->pm_callback) (pm);
3213 /* poll clear stall done thread */
3214 pm = &udev->ctrl_xfer[1]->
3215 xroot->done_m[0].hdr;
3216 (pm->pm_callback) (pm);
3219 /* poll done thread */
3220 pm = &xroot->done_m[0].hdr;
3221 (pm->pm_callback) (pm);
3223 USB_BUS_UNLOCK(xroot->bus);
3225 /* restore transfer mutex */
3227 mtx_lock(xroot->xfer_mtx);
3229 /* restore BUS mutex */
3231 mtx_lock(&xroot->udev->bus->bus_mtx);
3236 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3237 uint8_t type, enum usb_dev_speed speed)
3239 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3240 [USB_SPEED_LOW] = 8,
3241 [USB_SPEED_FULL] = 64,
3242 [USB_SPEED_HIGH] = 1024,
3243 [USB_SPEED_VARIABLE] = 1024,
3244 [USB_SPEED_SUPER] = 1024,
3247 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3248 [USB_SPEED_LOW] = 0, /* invalid */
3249 [USB_SPEED_FULL] = 1023,
3250 [USB_SPEED_HIGH] = 1024,
3251 [USB_SPEED_VARIABLE] = 3584,
3252 [USB_SPEED_SUPER] = 1024,
3255 static const uint16_t control_min[USB_SPEED_MAX] = {
3256 [USB_SPEED_LOW] = 8,
3257 [USB_SPEED_FULL] = 8,
3258 [USB_SPEED_HIGH] = 64,
3259 [USB_SPEED_VARIABLE] = 512,
3260 [USB_SPEED_SUPER] = 512,
3263 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3264 [USB_SPEED_LOW] = 8,
3265 [USB_SPEED_FULL] = 8,
3266 [USB_SPEED_HIGH] = 512,
3267 [USB_SPEED_VARIABLE] = 512,
3268 [USB_SPEED_SUPER] = 1024,
3273 memset(ptr, 0, sizeof(*ptr));
3277 ptr->range.max = intr_range_max[speed];
3279 case UE_ISOCHRONOUS:
3280 ptr->range.max = isoc_range_max[speed];
3283 if (type == UE_BULK)
3284 temp = bulk_min[speed];
3285 else /* UE_CONTROL */
3286 temp = control_min[speed];
3288 /* default is fixed */
3289 ptr->fixed[0] = temp;
3290 ptr->fixed[1] = temp;
3291 ptr->fixed[2] = temp;
3292 ptr->fixed[3] = temp;
3294 if (speed == USB_SPEED_FULL) {
3295 /* multiple sizes */
3300 if ((speed == USB_SPEED_VARIABLE) &&
3301 (type == UE_BULK)) {
3302 /* multiple sizes */
3303 ptr->fixed[2] = 1024;
3304 ptr->fixed[3] = 1536;
3311 usbd_xfer_softc(struct usb_xfer *xfer)
3313 return (xfer->priv_sc);
3317 usbd_xfer_get_priv(struct usb_xfer *xfer)
3319 return (xfer->priv_fifo);
3323 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3325 xfer->priv_fifo = ptr;
3329 usbd_xfer_state(struct usb_xfer *xfer)
3331 return (xfer->usb_state);
3335 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3338 case USB_FORCE_SHORT_XFER:
3339 xfer->flags.force_short_xfer = 1;
3341 case USB_SHORT_XFER_OK:
3342 xfer->flags.short_xfer_ok = 1;
3344 case USB_MULTI_SHORT_OK:
3345 xfer->flags.short_frames_ok = 1;
3347 case USB_MANUAL_STATUS:
3348 xfer->flags.manual_status = 1;
3354 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3357 case USB_FORCE_SHORT_XFER:
3358 xfer->flags.force_short_xfer = 0;
3360 case USB_SHORT_XFER_OK:
3361 xfer->flags.short_xfer_ok = 0;
3363 case USB_MULTI_SHORT_OK:
3364 xfer->flags.short_frames_ok = 0;
3366 case USB_MANUAL_STATUS:
3367 xfer->flags.manual_status = 0;
3373 * The following function returns in milliseconds when the isochronous
3374 * transfer was completed by the hardware. The returned value wraps
3375 * around 65536 milliseconds.
3378 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3380 return (xfer->isoc_time_complete);
3384 * The following function returns non-zero if the max packet size
3385 * field was clamped to a valid value. Else it returns zero.
3388 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3390 return (xfer->flags_int.maxp_was_clamped);