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/linker_set.h>
36 #include <sys/module.h>
38 #include <sys/mutex.h>
39 #include <sys/condvar.h>
40 #include <sys/sysctl.h>
42 #include <sys/unistd.h>
43 #include <sys/callout.h>
44 #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>
64 struct usb_std_packet_size {
66 uint16_t min; /* inclusive */
67 uint16_t max; /* inclusive */
73 static usb_callback_t usb_request_callback;
75 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
77 /* This transfer is used for generic control endpoint transfers */
81 .endpoint = 0x00, /* Control endpoint */
82 .direction = UE_DIR_ANY,
83 .bufsize = USB_EP0_BUFSIZE, /* bytes */
84 .flags = {.proxy_buffer = 1,},
85 .callback = &usb_request_callback,
86 .usb_mode = USB_MODE_DUAL, /* both modes */
89 /* This transfer is used for generic clear stall only */
93 .endpoint = 0x00, /* Control pipe */
94 .direction = UE_DIR_ANY,
95 .bufsize = sizeof(struct usb_device_request),
96 .callback = &usb_do_clear_stall_callback,
97 .timeout = 1000, /* 1 second */
98 .interval = 50, /* 50ms */
99 .usb_mode = USB_MODE_HOST,
103 /* function prototypes */
105 static void usbd_update_max_frame_size(struct usb_xfer *);
106 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
107 static void usbd_control_transfer_init(struct usb_xfer *);
108 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
109 static void usb_callback_proc(struct usb_proc_msg *);
110 static void usbd_callback_ss_done_defer(struct usb_xfer *);
111 static void usbd_callback_wrapper(struct usb_xfer_queue *);
112 static void usbd_transfer_start_cb(void *);
113 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
114 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
115 uint8_t type, enum usb_dev_speed speed);
117 /*------------------------------------------------------------------------*
118 * usb_request_callback
119 *------------------------------------------------------------------------*/
121 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
123 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
124 usb_handle_request_callback(xfer, error);
126 usbd_do_request_callback(xfer, error);
129 /*------------------------------------------------------------------------*
130 * usbd_update_max_frame_size
132 * This function updates the maximum frame size, hence high speed USB
133 * can transfer multiple consecutive packets.
134 *------------------------------------------------------------------------*/
136 usbd_update_max_frame_size(struct usb_xfer *xfer)
138 /* compute maximum frame size */
139 /* this computation should not overflow 16-bit */
140 /* max = 15 * 1024 */
142 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
145 /*------------------------------------------------------------------------*
148 * The following function is called when we need to
149 * synchronize with DMA hardware.
152 * 0: no DMA delay required
153 * Else: milliseconds of DMA delay
154 *------------------------------------------------------------------------*/
156 usbd_get_dma_delay(struct usb_device *udev)
158 struct usb_bus_methods *mtod;
161 mtod = udev->bus->methods;
164 if (mtod->get_dma_delay) {
165 (mtod->get_dma_delay) (udev, &temp);
167 * Round up and convert to milliseconds. Note that we use
168 * 1024 milliseconds per second. to save a division.
176 /*------------------------------------------------------------------------*
177 * usbd_transfer_setup_sub_malloc
179 * This function will allocate one or more DMA'able memory chunks
180 * according to "size", "align" and "count" arguments. "ppc" is
181 * pointed to a linear array of USB page caches afterwards.
186 *------------------------------------------------------------------------*/
189 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
190 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
193 struct usb_page_cache *pc;
203 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
205 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
208 return (0); /* nothing to allocate */
211 * Make sure that the size is aligned properly.
213 size = -((-size) & (-align));
216 * Try multi-allocation chunks to reduce the number of DMA
217 * allocations, hence DMA allocations are slow.
219 if (size >= PAGE_SIZE) {
223 /* compute number of objects per page */
224 n_obj = (PAGE_SIZE / size);
226 * Compute number of DMA chunks, rounded up
229 n_dma_pc = ((count + n_obj - 1) / n_obj);
232 if (parm->buf == NULL) {
234 parm->dma_page_ptr += n_dma_pc;
235 parm->dma_page_cache_ptr += n_dma_pc;
236 parm->dma_page_ptr += count;
237 parm->xfer_page_cache_ptr += count;
240 for (x = 0; x != n_dma_pc; x++) {
241 /* need to initialize the page cache */
242 parm->dma_page_cache_ptr[x].tag_parent =
243 &parm->curr_xfer->xroot->dma_parent_tag;
245 for (x = 0; x != count; x++) {
246 /* need to initialize the page cache */
247 parm->xfer_page_cache_ptr[x].tag_parent =
248 &parm->curr_xfer->xroot->dma_parent_tag;
252 *ppc = parm->xfer_page_cache_ptr;
254 r = count; /* set remainder count */
255 z = n_obj * size; /* set allocation size */
256 pc = parm->xfer_page_cache_ptr;
257 pg = parm->dma_page_ptr;
259 for (x = 0; x != n_dma_pc; x++) {
262 /* compute last remainder */
266 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
268 return (1); /* failure */
270 /* Set beginning of current buffer */
271 buf = parm->dma_page_cache_ptr->buffer;
272 /* Make room for one DMA page cache and one page */
273 parm->dma_page_cache_ptr++;
276 for (y = 0; (y != n_obj); y++, r--, pc++, pg++) {
278 /* Load sub-chunk into DMA */
279 if (usb_pc_dmamap_create(pc, size)) {
280 return (1); /* failure */
282 pc->buffer = USB_ADD_BYTES(buf, y * size);
285 mtx_lock(pc->tag_parent->mtx);
286 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
287 mtx_unlock(pc->tag_parent->mtx);
288 return (1); /* failure */
290 mtx_unlock(pc->tag_parent->mtx);
294 parm->xfer_page_cache_ptr = pc;
295 parm->dma_page_ptr = pg;
300 /*------------------------------------------------------------------------*
301 * usbd_transfer_setup_sub - transfer setup subroutine
303 * This function must be called from the "xfer_setup" callback of the
304 * USB Host or Device controller driver when setting up an USB
305 * transfer. This function will setup correct packet sizes, buffer
306 * sizes, flags and more, that are stored in the "usb_xfer"
308 *------------------------------------------------------------------------*/
310 usbd_transfer_setup_sub(struct usb_setup_params *parm)
316 struct usb_xfer *xfer = parm->curr_xfer;
317 const struct usb_config *setup = parm->curr_setup;
318 struct usb_endpoint_ss_comp_descriptor *ecomp;
319 struct usb_endpoint_descriptor *edesc;
320 struct usb_std_packet_size std_size;
321 usb_frcount_t n_frlengths;
322 usb_frcount_t n_frbuffers;
328 * Sanity check. The following parameters must be initialized before
329 * calling this function.
331 if ((parm->hc_max_packet_size == 0) ||
332 (parm->hc_max_packet_count == 0) ||
333 (parm->hc_max_frame_size == 0)) {
334 parm->err = USB_ERR_INVAL;
337 edesc = xfer->endpoint->edesc;
338 ecomp = xfer->endpoint->ecomp;
340 type = (edesc->bmAttributes & UE_XFERTYPE);
342 xfer->flags = setup->flags;
343 xfer->nframes = setup->frames;
344 xfer->timeout = setup->timeout;
345 xfer->callback = setup->callback;
346 xfer->interval = setup->interval;
347 xfer->endpointno = edesc->bEndpointAddress;
348 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
349 xfer->max_packet_count = 1;
350 /* make a shadow copy: */
351 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
353 parm->bufsize = setup->bufsize;
355 switch (parm->speed) {
360 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
362 /* check for invalid max packet count */
363 if (xfer->max_packet_count > 3)
364 xfer->max_packet_count = 3;
369 xfer->max_packet_size &= 0x7FF;
371 case USB_SPEED_SUPER:
372 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
375 xfer->max_packet_count += ecomp->bMaxBurst;
377 if ((xfer->max_packet_count == 0) ||
378 (xfer->max_packet_count > 16))
379 xfer->max_packet_count = 16;
383 xfer->max_packet_count = 1;
389 mult = (ecomp->bmAttributes & 3) + 1;
393 xfer->max_packet_count *= mult;
399 xfer->max_packet_size &= 0x7FF;
404 /* range check "max_packet_count" */
406 if (xfer->max_packet_count > parm->hc_max_packet_count) {
407 xfer->max_packet_count = parm->hc_max_packet_count;
409 /* filter "wMaxPacketSize" according to HC capabilities */
411 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
412 (xfer->max_packet_size == 0)) {
413 xfer->max_packet_size = parm->hc_max_packet_size;
415 /* filter "wMaxPacketSize" according to standard sizes */
417 usbd_get_std_packet_size(&std_size, type, parm->speed);
419 if (std_size.range.min || std_size.range.max) {
421 if (xfer->max_packet_size < std_size.range.min) {
422 xfer->max_packet_size = std_size.range.min;
424 if (xfer->max_packet_size > std_size.range.max) {
425 xfer->max_packet_size = std_size.range.max;
429 if (xfer->max_packet_size >= std_size.fixed[3]) {
430 xfer->max_packet_size = std_size.fixed[3];
431 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
432 xfer->max_packet_size = std_size.fixed[2];
433 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
434 xfer->max_packet_size = std_size.fixed[1];
436 /* only one possibility left */
437 xfer->max_packet_size = std_size.fixed[0];
441 /* compute "max_frame_size" */
443 usbd_update_max_frame_size(xfer);
445 /* check interrupt interval and transfer pre-delay */
447 if (type == UE_ISOCHRONOUS) {
449 uint16_t frame_limit;
451 xfer->interval = 0; /* not used, must be zero */
452 xfer->flags_int.isochronous_xfr = 1; /* set flag */
454 if (xfer->timeout == 0) {
456 * set a default timeout in
457 * case something goes wrong!
459 xfer->timeout = 1000 / 4;
461 switch (parm->speed) {
464 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
468 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
469 xfer->fps_shift = edesc->bInterval;
470 if (xfer->fps_shift > 0)
472 if (xfer->fps_shift > 3)
474 if (xfer->flags.pre_scale_frames != 0)
475 xfer->nframes <<= (3 - xfer->fps_shift);
479 if (xfer->nframes > frame_limit) {
481 * this is not going to work
484 parm->err = USB_ERR_INVAL;
487 if (xfer->nframes == 0) {
489 * this is not a valid value
491 parm->err = USB_ERR_ZERO_NFRAMES;
497 * If a value is specified use that else check the
498 * endpoint descriptor!
500 if (type == UE_INTERRUPT) {
504 if (xfer->interval == 0) {
506 xfer->interval = edesc->bInterval;
508 switch (parm->speed) {
514 if (xfer->interval < 4)
516 else if (xfer->interval > 16)
517 xfer->interval = (1 << (16 - 4));
520 (1 << (xfer->interval - 4));
525 if (xfer->interval == 0) {
527 * One millisecond is the smallest
528 * interval we support:
536 while ((temp != 0) && (temp < xfer->interval)) {
541 switch (parm->speed) {
546 xfer->fps_shift += 3;
553 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
554 * to be equal to zero when setting up USB transfers, hence
555 * this leads to alot of extra code in the USB kernel.
558 if ((xfer->max_frame_size == 0) ||
559 (xfer->max_packet_size == 0)) {
563 if ((parm->bufsize <= MIN_PKT) &&
564 (type != UE_CONTROL) &&
568 xfer->max_packet_size = MIN_PKT;
569 xfer->max_packet_count = 1;
570 parm->bufsize = 0; /* automatic setup length */
571 usbd_update_max_frame_size(xfer);
574 parm->err = USB_ERR_ZERO_MAXP;
583 * check if we should setup a default
587 if (parm->bufsize == 0) {
589 parm->bufsize = xfer->max_frame_size;
591 if (type == UE_ISOCHRONOUS) {
592 parm->bufsize *= xfer->nframes;
596 * check if we are about to setup a proxy
600 if (xfer->flags.proxy_buffer) {
602 /* round bufsize up */
604 parm->bufsize += (xfer->max_frame_size - 1);
606 if (parm->bufsize < xfer->max_frame_size) {
607 /* length wrapped around */
608 parm->err = USB_ERR_INVAL;
611 /* subtract remainder */
613 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
615 /* add length of USB device request structure, if any */
617 if (type == UE_CONTROL) {
618 parm->bufsize += REQ_SIZE; /* SETUP message */
621 xfer->max_data_length = parm->bufsize;
623 /* Setup "n_frlengths" and "n_frbuffers" */
625 if (type == UE_ISOCHRONOUS) {
626 n_frlengths = xfer->nframes;
630 if (type == UE_CONTROL) {
631 xfer->flags_int.control_xfr = 1;
632 if (xfer->nframes == 0) {
633 if (parm->bufsize <= REQ_SIZE) {
635 * there will never be any data
644 if (xfer->nframes == 0) {
649 n_frlengths = xfer->nframes;
650 n_frbuffers = xfer->nframes;
654 * check if we have room for the
655 * USB device request structure:
658 if (type == UE_CONTROL) {
660 if (xfer->max_data_length < REQ_SIZE) {
661 /* length wrapped around or too small bufsize */
662 parm->err = USB_ERR_INVAL;
665 xfer->max_data_length -= REQ_SIZE;
667 /* setup "frlengths" */
668 xfer->frlengths = parm->xfer_length_ptr;
669 parm->xfer_length_ptr += n_frlengths;
671 /* setup "frbuffers" */
672 xfer->frbuffers = parm->xfer_page_cache_ptr;
673 parm->xfer_page_cache_ptr += n_frbuffers;
675 /* initialize max frame count */
676 xfer->max_frame_count = xfer->nframes;
679 * check if we need to setup
683 if (!xfer->flags.ext_buffer) {
686 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
691 USB_ADD_BYTES(parm->buf, parm->size[0]);
693 usbd_xfer_set_frame_offset(xfer, 0, 0);
695 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
696 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
699 parm->size[0] += parm->bufsize;
701 /* align data again */
702 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
705 * Compute maximum buffer size
708 if (parm->bufsize_max < parm->bufsize) {
709 parm->bufsize_max = parm->bufsize;
712 if (xfer->flags_int.bdma_enable) {
714 * Setup "dma_page_ptr".
716 * Proof for formula below:
718 * Assume there are three USB frames having length "a", "b" and
719 * "c". These USB frames will at maximum need "z"
720 * "usb_page" structures. "z" is given by:
722 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
723 * ((c / USB_PAGE_SIZE) + 2);
725 * Constraining "a", "b" and "c" like this:
727 * (a + b + c) <= parm->bufsize
731 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
733 * Here is the general formula:
735 xfer->dma_page_ptr = parm->dma_page_ptr;
736 parm->dma_page_ptr += (2 * n_frbuffers);
737 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
741 /* correct maximum data length */
742 xfer->max_data_length = 0;
744 /* subtract USB frame remainder from "hc_max_frame_size" */
746 xfer->max_hc_frame_size =
747 (parm->hc_max_frame_size -
748 (parm->hc_max_frame_size % xfer->max_frame_size));
750 if (xfer->max_hc_frame_size == 0) {
751 parm->err = USB_ERR_INVAL;
755 /* initialize frame buffers */
758 for (x = 0; x != n_frbuffers; x++) {
759 xfer->frbuffers[x].tag_parent =
760 &xfer->xroot->dma_parent_tag;
762 if (xfer->flags_int.bdma_enable &&
763 (parm->bufsize_max > 0)) {
765 if (usb_pc_dmamap_create(
767 parm->bufsize_max)) {
768 parm->err = USB_ERR_NOMEM;
778 * Set some dummy values so that we avoid division by zero:
780 xfer->max_hc_frame_size = 1;
781 xfer->max_frame_size = 1;
782 xfer->max_packet_size = 1;
783 xfer->max_data_length = 0;
785 xfer->max_frame_count = 0;
789 /*------------------------------------------------------------------------*
790 * usbd_transfer_setup - setup an array of USB transfers
792 * NOTE: You must always call "usbd_transfer_unsetup" after calling
793 * "usbd_transfer_setup" if success was returned.
795 * The idea is that the USB device driver should pre-allocate all its
796 * transfers by one call to this function.
801 *------------------------------------------------------------------------*/
803 usbd_transfer_setup(struct usb_device *udev,
804 const uint8_t *ifaces, struct usb_xfer **ppxfer,
805 const struct usb_config *setup_start, uint16_t n_setup,
806 void *priv_sc, struct mtx *xfer_mtx)
808 struct usb_xfer dummy;
809 struct usb_setup_params parm;
810 const struct usb_config *setup_end = setup_start + n_setup;
811 const struct usb_config *setup;
812 struct usb_endpoint *ep;
813 struct usb_xfer_root *info;
814 struct usb_xfer *xfer;
823 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
824 "usbd_transfer_setup can sleep!");
826 /* do some checking first */
829 DPRINTFN(6, "setup array has zero length!\n");
830 return (USB_ERR_INVAL);
833 DPRINTFN(6, "ifaces array is NULL!\n");
834 return (USB_ERR_INVAL);
836 if (xfer_mtx == NULL) {
837 DPRINTFN(6, "using global lock\n");
841 for (setup = setup_start, n = 0;
842 setup != setup_end; setup++, n++) {
843 if (setup->bufsize == (usb_frlength_t)-1) {
844 parm.err = USB_ERR_BAD_BUFSIZE;
845 DPRINTF("invalid bufsize\n");
847 if (setup->callback == NULL) {
848 parm.err = USB_ERR_NO_CALLBACK;
849 DPRINTF("no callback\n");
857 bzero(&parm, sizeof(parm));
860 parm.speed = usbd_get_speed(udev);
861 parm.hc_max_packet_count = 1;
863 if (parm.speed >= USB_SPEED_MAX) {
864 parm.err = USB_ERR_INVAL;
867 /* setup all transfers */
873 * Initialize the "usb_xfer_root" structure,
874 * which is common for all our USB transfers.
876 info = USB_ADD_BYTES(buf, 0);
878 info->memory_base = buf;
879 info->memory_size = parm.size[0];
882 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
883 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
885 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
886 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
888 cv_init(&info->cv_drain, "WDRAIN");
890 info->xfer_mtx = xfer_mtx;
892 usb_dma_tag_setup(&info->dma_parent_tag,
893 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
894 xfer_mtx, &usb_bdma_done_event, 32, parm.dma_tag_max);
897 info->bus = udev->bus;
900 TAILQ_INIT(&info->done_q.head);
901 info->done_q.command = &usbd_callback_wrapper;
903 TAILQ_INIT(&info->dma_q.head);
904 info->dma_q.command = &usb_bdma_work_loop;
906 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
907 info->done_m[0].xroot = info;
908 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
909 info->done_m[1].xroot = info;
912 * In device side mode control endpoint
913 * requests need to run from a separate
914 * context, else there is a chance of
917 if (setup_start == usb_control_ep_cfg)
919 &udev->bus->control_xfer_proc;
920 else if (xfer_mtx == &Giant)
922 &udev->bus->giant_callback_proc;
925 &udev->bus->non_giant_callback_proc;
931 parm.size[0] += sizeof(info[0]);
933 for (setup = setup_start, n = 0;
934 setup != setup_end; setup++, n++) {
936 /* skip USB transfers without callbacks: */
937 if (setup->callback == NULL) {
940 /* see if there is a matching endpoint */
941 ep = usbd_get_endpoint(udev,
942 ifaces[setup->if_index], setup);
944 if ((ep == NULL) || (ep->methods == NULL)) {
945 if (setup->flags.no_pipe_ok)
947 if ((setup->usb_mode != USB_MODE_DUAL) &&
948 (setup->usb_mode != udev->flags.usb_mode))
950 parm.err = USB_ERR_NO_PIPE;
954 /* align data properly */
955 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
957 /* store current setup pointer */
958 parm.curr_setup = setup;
962 * Common initialization of the
963 * "usb_xfer" structure.
965 xfer = USB_ADD_BYTES(buf, parm.size[0]);
966 xfer->address = udev->address;
967 xfer->priv_sc = priv_sc;
970 usb_callout_init_mtx(&xfer->timeout_handle,
971 &udev->bus->bus_mtx, 0);
974 * Setup a dummy xfer, hence we are
975 * writing to the "usb_xfer"
976 * structure pointed to by "xfer"
977 * before we have allocated any
981 bzero(&dummy, sizeof(dummy));
985 /* set transfer endpoint pointer */
988 parm.size[0] += sizeof(xfer[0]);
989 parm.methods = xfer->endpoint->methods;
990 parm.curr_xfer = xfer;
993 * Call the Host or Device controller transfer
996 (udev->bus->methods->xfer_setup) (&parm);
998 /* check for error */
1004 * Increment the endpoint refcount. This
1005 * basically prevents setting a new
1006 * configuration and alternate setting
1007 * when USB transfers are in use on
1008 * the given interface. Search the USB
1009 * code for "endpoint->refcount_alloc" if you
1010 * want more information.
1012 USB_BUS_LOCK(info->bus);
1013 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1014 parm.err = USB_ERR_INVAL;
1016 xfer->endpoint->refcount_alloc++;
1018 if (xfer->endpoint->refcount_alloc == 0)
1019 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1020 USB_BUS_UNLOCK(info->bus);
1023 * Whenever we set ppxfer[] then we
1024 * also need to increment the
1027 info->setup_refcount++;
1030 * Transfer is successfully setup and
1036 /* check for error */
1041 if (buf || parm.err) {
1044 if (refcount == 0) {
1045 /* no transfers - nothing to do ! */
1048 /* align data properly */
1049 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1051 /* store offset temporarily */
1052 parm.size[1] = parm.size[0];
1055 * The number of DMA tags required depends on
1056 * the number of endpoints. The current estimate
1057 * for maximum number of DMA tags per endpoint
1060 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1063 * DMA tags for QH, TD, Data and more.
1065 parm.dma_tag_max += 8;
1067 parm.dma_tag_p += parm.dma_tag_max;
1069 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1072 /* align data properly */
1073 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1075 /* store offset temporarily */
1076 parm.size[3] = parm.size[0];
1078 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1081 /* align data properly */
1082 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1084 /* store offset temporarily */
1085 parm.size[4] = parm.size[0];
1087 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1090 /* store end offset temporarily */
1091 parm.size[5] = parm.size[0];
1093 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1096 /* store end offset temporarily */
1098 parm.size[2] = parm.size[0];
1100 /* align data properly */
1101 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1103 parm.size[6] = parm.size[0];
1105 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1108 /* align data properly */
1109 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1111 /* allocate zeroed memory */
1112 buf = malloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1115 parm.err = USB_ERR_NOMEM;
1116 DPRINTFN(0, "cannot allocate memory block for "
1117 "configuration (%d bytes)\n",
1121 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1122 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1123 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1124 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1125 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1130 if (info->setup_refcount == 0) {
1132 * "usbd_transfer_unsetup_sub" will unlock
1133 * the bus mutex before returning !
1135 USB_BUS_LOCK(info->bus);
1137 /* something went wrong */
1138 usbd_transfer_unsetup_sub(info, 0);
1142 usbd_transfer_unsetup(ppxfer, n_setup);
1147 /*------------------------------------------------------------------------*
1148 * usbd_transfer_unsetup_sub - factored out code
1149 *------------------------------------------------------------------------*/
1151 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1154 struct usb_page_cache *pc;
1157 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1159 /* wait for any outstanding DMA operations */
1163 temp = usbd_get_dma_delay(info->udev);
1165 usb_pause_mtx(&info->bus->bus_mtx,
1166 USB_MS_TO_TICKS(temp));
1170 /* make sure that our done messages are not queued anywhere */
1171 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1173 USB_BUS_UNLOCK(info->bus);
1176 /* free DMA'able memory, if any */
1177 pc = info->dma_page_cache_start;
1178 while (pc != info->dma_page_cache_end) {
1179 usb_pc_free_mem(pc);
1183 /* free DMA maps in all "xfer->frbuffers" */
1184 pc = info->xfer_page_cache_start;
1185 while (pc != info->xfer_page_cache_end) {
1186 usb_pc_dmamap_destroy(pc);
1190 /* free all DMA tags */
1191 usb_dma_tag_unsetup(&info->dma_parent_tag);
1194 cv_destroy(&info->cv_drain);
1197 * free the "memory_base" last, hence the "info" structure is
1198 * contained within the "memory_base"!
1200 free(info->memory_base, M_USB);
1203 /*------------------------------------------------------------------------*
1204 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1206 * NOTE: All USB transfers in progress will get called back passing
1207 * the error code "USB_ERR_CANCELLED" before this function
1209 *------------------------------------------------------------------------*/
1211 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1213 struct usb_xfer *xfer;
1214 struct usb_xfer_root *info;
1215 uint8_t needs_delay = 0;
1217 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1218 "usbd_transfer_unsetup can sleep!");
1221 xfer = pxfer[n_setup];
1228 USB_XFER_LOCK(xfer);
1229 USB_BUS_LOCK(info->bus);
1232 * HINT: when you start/stop a transfer, it might be a
1233 * good idea to directly use the "pxfer[]" structure:
1235 * usbd_transfer_start(sc->pxfer[0]);
1236 * usbd_transfer_stop(sc->pxfer[0]);
1238 * That way, if your code has many parts that will not
1239 * stop running under the same lock, in other words
1240 * "xfer_mtx", the usbd_transfer_start and
1241 * usbd_transfer_stop functions will simply return
1242 * when they detect a NULL pointer argument.
1244 * To avoid any races we clear the "pxfer[]" pointer
1245 * while holding the private mutex of the driver:
1247 pxfer[n_setup] = NULL;
1249 USB_BUS_UNLOCK(info->bus);
1250 USB_XFER_UNLOCK(xfer);
1252 usbd_transfer_drain(xfer);
1255 if (xfer->flags_int.bdma_enable)
1259 * NOTE: default endpoint does not have an
1260 * interface, even if endpoint->iface_index == 0
1262 USB_BUS_LOCK(info->bus);
1263 xfer->endpoint->refcount_alloc--;
1264 USB_BUS_UNLOCK(info->bus);
1266 usb_callout_drain(&xfer->timeout_handle);
1268 USB_BUS_LOCK(info->bus);
1270 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1271 "reference count\n"));
1273 info->setup_refcount--;
1275 if (info->setup_refcount == 0) {
1276 usbd_transfer_unsetup_sub(info,
1279 USB_BUS_UNLOCK(info->bus);
1284 /*------------------------------------------------------------------------*
1285 * usbd_control_transfer_init - factored out code
1287 * In USB Device Mode we have to wait for the SETUP packet which
1288 * containst the "struct usb_device_request" structure, before we can
1289 * transfer any data. In USB Host Mode we already have the SETUP
1290 * packet at the moment the USB transfer is started. This leads us to
1291 * having to setup the USB transfer at two different places in
1292 * time. This function just contains factored out control transfer
1293 * initialisation code, so that we don't duplicate the code.
1294 *------------------------------------------------------------------------*/
1296 usbd_control_transfer_init(struct usb_xfer *xfer)
1298 struct usb_device_request req;
1300 /* copy out the USB request header */
1302 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1304 /* setup remainder */
1306 xfer->flags_int.control_rem = UGETW(req.wLength);
1308 /* copy direction to endpoint variable */
1310 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1312 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1315 /*------------------------------------------------------------------------*
1316 * usbd_setup_ctrl_transfer
1318 * This function handles initialisation of control transfers. Control
1319 * transfers are special in that regard that they can both transmit
1325 *------------------------------------------------------------------------*/
1327 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1331 /* Check for control endpoint stall */
1332 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1333 /* the control transfer is no longer active */
1334 xfer->flags_int.control_stall = 1;
1335 xfer->flags_int.control_act = 0;
1337 /* don't stall control transfer by default */
1338 xfer->flags_int.control_stall = 0;
1341 /* Check for invalid number of frames */
1342 if (xfer->nframes > 2) {
1344 * If you need to split a control transfer, you
1345 * have to do one part at a time. Only with
1346 * non-control transfers you can do multiple
1349 DPRINTFN(0, "Too many frames: %u\n",
1350 (unsigned int)xfer->nframes);
1355 * Check if there is a control
1356 * transfer in progress:
1358 if (xfer->flags_int.control_act) {
1360 if (xfer->flags_int.control_hdr) {
1362 /* clear send header flag */
1364 xfer->flags_int.control_hdr = 0;
1366 /* setup control transfer */
1367 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1368 usbd_control_transfer_init(xfer);
1371 /* get data length */
1377 /* the size of the SETUP structure is hardcoded ! */
1379 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1380 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1381 xfer->frlengths[0], sizeof(struct
1382 usb_device_request));
1385 /* check USB mode */
1386 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1388 /* check number of frames */
1389 if (xfer->nframes != 1) {
1391 * We need to receive the setup
1392 * message first so that we know the
1395 DPRINTF("Misconfigured transfer\n");
1399 * Set a dummy "control_rem" value. This
1400 * variable will be overwritten later by a
1401 * call to "usbd_control_transfer_init()" !
1403 xfer->flags_int.control_rem = 0xFFFF;
1406 /* setup "endpoint" and "control_rem" */
1408 usbd_control_transfer_init(xfer);
1411 /* set transfer-header flag */
1413 xfer->flags_int.control_hdr = 1;
1415 /* get data length */
1417 len = (xfer->sumlen - sizeof(struct usb_device_request));
1420 /* check if there is a length mismatch */
1422 if (len > xfer->flags_int.control_rem) {
1423 DPRINTFN(0, "Length (%d) greater than "
1424 "remaining length (%d)\n", len,
1425 xfer->flags_int.control_rem);
1428 /* check if we are doing a short transfer */
1430 if (xfer->flags.force_short_xfer) {
1431 xfer->flags_int.control_rem = 0;
1433 if ((len != xfer->max_data_length) &&
1434 (len != xfer->flags_int.control_rem) &&
1435 (xfer->nframes != 1)) {
1436 DPRINTFN(0, "Short control transfer without "
1437 "force_short_xfer set\n");
1440 xfer->flags_int.control_rem -= len;
1443 /* the status part is executed when "control_act" is 0 */
1445 if ((xfer->flags_int.control_rem > 0) ||
1446 (xfer->flags.manual_status)) {
1447 /* don't execute the STATUS stage yet */
1448 xfer->flags_int.control_act = 1;
1451 if ((!xfer->flags_int.control_hdr) &&
1452 (xfer->nframes == 1)) {
1454 * This is not a valid operation!
1456 DPRINTFN(0, "Invalid parameter "
1461 /* time to execute the STATUS stage */
1462 xfer->flags_int.control_act = 0;
1464 return (0); /* success */
1467 return (1); /* failure */
1470 /*------------------------------------------------------------------------*
1471 * usbd_transfer_submit - start USB hardware for the given transfer
1473 * This function should only be called from the USB callback.
1474 *------------------------------------------------------------------------*/
1476 usbd_transfer_submit(struct usb_xfer *xfer)
1478 struct usb_xfer_root *info;
1479 struct usb_bus *bus;
1485 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1486 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1490 if (USB_DEBUG_VAR > 0) {
1493 usb_dump_endpoint(xfer->endpoint);
1495 USB_BUS_UNLOCK(bus);
1499 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1500 USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1502 /* Only open the USB transfer once! */
1503 if (!xfer->flags_int.open) {
1504 xfer->flags_int.open = 1;
1509 (xfer->endpoint->methods->open) (xfer);
1510 USB_BUS_UNLOCK(bus);
1512 /* set "transferring" flag */
1513 xfer->flags_int.transferring = 1;
1516 /* increment power reference */
1517 usbd_transfer_power_ref(xfer, 1);
1520 * Check if the transfer is waiting on a queue, most
1521 * frequently the "done_q":
1523 if (xfer->wait_queue) {
1525 usbd_transfer_dequeue(xfer);
1526 USB_BUS_UNLOCK(bus);
1528 /* clear "did_dma_delay" flag */
1529 xfer->flags_int.did_dma_delay = 0;
1531 /* clear "did_close" flag */
1532 xfer->flags_int.did_close = 0;
1535 /* clear "bdma_setup" flag */
1536 xfer->flags_int.bdma_setup = 0;
1538 /* by default we cannot cancel any USB transfer immediately */
1539 xfer->flags_int.can_cancel_immed = 0;
1541 /* clear lengths and frame counts by default */
1546 /* clear any previous errors */
1549 /* Check if the device is still alive */
1550 if (info->udev->state < USB_STATE_POWERED) {
1553 * Must return cancelled error code else
1554 * device drivers can hang.
1556 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1557 USB_BUS_UNLOCK(bus);
1562 if (xfer->nframes == 0) {
1563 if (xfer->flags.stall_pipe) {
1565 * Special case - want to stall without transferring
1568 DPRINTF("xfer=%p nframes=0: stall "
1569 "or clear stall!\n", xfer);
1571 xfer->flags_int.can_cancel_immed = 1;
1572 /* start the transfer */
1573 usb_command_wrapper(&xfer->endpoint->endpoint_q, xfer);
1574 USB_BUS_UNLOCK(bus);
1578 usbd_transfer_done(xfer, USB_ERR_INVAL);
1579 USB_BUS_UNLOCK(bus);
1582 /* compute total transfer length */
1584 for (x = 0; x != xfer->nframes; x++) {
1585 xfer->sumlen += xfer->frlengths[x];
1586 if (xfer->sumlen < xfer->frlengths[x]) {
1587 /* length wrapped around */
1589 usbd_transfer_done(xfer, USB_ERR_INVAL);
1590 USB_BUS_UNLOCK(bus);
1595 /* clear some internal flags */
1597 xfer->flags_int.short_xfer_ok = 0;
1598 xfer->flags_int.short_frames_ok = 0;
1600 /* check if this is a control transfer */
1602 if (xfer->flags_int.control_xfr) {
1604 if (usbd_setup_ctrl_transfer(xfer)) {
1606 usbd_transfer_done(xfer, USB_ERR_STALLED);
1607 USB_BUS_UNLOCK(bus);
1612 * Setup filtered version of some transfer flags,
1613 * in case of data read direction
1615 if (USB_GET_DATA_ISREAD(xfer)) {
1617 if (xfer->flags.short_frames_ok) {
1618 xfer->flags_int.short_xfer_ok = 1;
1619 xfer->flags_int.short_frames_ok = 1;
1620 } else if (xfer->flags.short_xfer_ok) {
1621 xfer->flags_int.short_xfer_ok = 1;
1623 /* check for control transfer */
1624 if (xfer->flags_int.control_xfr) {
1626 * 1) Control transfers do not support
1627 * reception of multiple short USB
1628 * frames in host mode and device side
1629 * mode, with exception of:
1631 * 2) Due to sometimes buggy device
1632 * side firmware we need to do a
1633 * STATUS stage in case of short
1634 * control transfers in USB host mode.
1635 * The STATUS stage then becomes the
1636 * "alt_next" to the DATA stage.
1638 xfer->flags_int.short_frames_ok = 1;
1643 * Check if BUS-DMA support is enabled and try to load virtual
1644 * buffers into DMA, if any:
1647 if (xfer->flags_int.bdma_enable) {
1648 /* insert the USB transfer last in the BUS-DMA queue */
1649 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1654 * Enter the USB transfer into the Host Controller or
1655 * Device Controller schedule:
1657 usbd_pipe_enter(xfer);
1660 /*------------------------------------------------------------------------*
1661 * usbd_pipe_enter - factored out code
1662 *------------------------------------------------------------------------*/
1664 usbd_pipe_enter(struct usb_xfer *xfer)
1666 struct usb_endpoint *ep;
1668 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1670 USB_BUS_LOCK(xfer->xroot->bus);
1672 ep = xfer->endpoint;
1676 /* enter the transfer */
1677 (ep->methods->enter) (xfer);
1679 xfer->flags_int.can_cancel_immed = 1;
1681 /* check for transfer error */
1683 /* some error has happened */
1684 usbd_transfer_done(xfer, 0);
1685 USB_BUS_UNLOCK(xfer->xroot->bus);
1689 /* start the transfer */
1690 usb_command_wrapper(&ep->endpoint_q, xfer);
1691 USB_BUS_UNLOCK(xfer->xroot->bus);
1694 /*------------------------------------------------------------------------*
1695 * usbd_transfer_start - start an USB transfer
1697 * NOTE: Calling this function more than one time will only
1698 * result in a single transfer start, until the USB transfer
1700 *------------------------------------------------------------------------*/
1702 usbd_transfer_start(struct usb_xfer *xfer)
1705 /* transfer is gone */
1708 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1710 /* mark the USB transfer started */
1712 if (!xfer->flags_int.started) {
1713 /* lock the BUS lock to avoid races updating flags_int */
1714 USB_BUS_LOCK(xfer->xroot->bus);
1715 xfer->flags_int.started = 1;
1716 USB_BUS_UNLOCK(xfer->xroot->bus);
1718 /* check if the USB transfer callback is already transferring */
1720 if (xfer->flags_int.transferring) {
1723 USB_BUS_LOCK(xfer->xroot->bus);
1724 /* call the USB transfer callback */
1725 usbd_callback_ss_done_defer(xfer);
1726 USB_BUS_UNLOCK(xfer->xroot->bus);
1729 /*------------------------------------------------------------------------*
1730 * usbd_transfer_stop - stop an USB transfer
1732 * NOTE: Calling this function more than one time will only
1733 * result in a single transfer stop.
1734 * NOTE: When this function returns it is not safe to free nor
1735 * reuse any DMA buffers. See "usbd_transfer_drain()".
1736 *------------------------------------------------------------------------*/
1738 usbd_transfer_stop(struct usb_xfer *xfer)
1740 struct usb_endpoint *ep;
1743 /* transfer is gone */
1746 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1748 /* check if the USB transfer was ever opened */
1750 if (!xfer->flags_int.open) {
1751 if (xfer->flags_int.started) {
1752 /* nothing to do except clearing the "started" flag */
1753 /* lock the BUS lock to avoid races updating flags_int */
1754 USB_BUS_LOCK(xfer->xroot->bus);
1755 xfer->flags_int.started = 0;
1756 USB_BUS_UNLOCK(xfer->xroot->bus);
1760 /* try to stop the current USB transfer */
1762 USB_BUS_LOCK(xfer->xroot->bus);
1763 /* override any previous error */
1764 xfer->error = USB_ERR_CANCELLED;
1767 * Clear "open" and "started" when both private and USB lock
1768 * is locked so that we don't get a race updating "flags_int"
1770 xfer->flags_int.open = 0;
1771 xfer->flags_int.started = 0;
1774 * Check if we can cancel the USB transfer immediately.
1776 if (xfer->flags_int.transferring) {
1777 if (xfer->flags_int.can_cancel_immed &&
1778 (!xfer->flags_int.did_close)) {
1781 * The following will lead to an USB_ERR_CANCELLED
1782 * error code being passed to the USB callback.
1784 (xfer->endpoint->methods->close) (xfer);
1785 /* only close once */
1786 xfer->flags_int.did_close = 1;
1788 /* need to wait for the next done callback */
1793 /* close here and now */
1794 (xfer->endpoint->methods->close) (xfer);
1797 * Any additional DMA delay is done by
1798 * "usbd_transfer_unsetup()".
1802 * Special case. Check if we need to restart a blocked
1805 ep = xfer->endpoint;
1808 * If the current USB transfer is completing we need
1809 * to start the next one:
1811 if (ep->endpoint_q.curr == xfer) {
1812 usb_command_wrapper(&ep->endpoint_q, NULL);
1816 USB_BUS_UNLOCK(xfer->xroot->bus);
1819 /*------------------------------------------------------------------------*
1820 * usbd_transfer_pending
1822 * This function will check if an USB transfer is pending which is a
1823 * little bit complicated!
1826 * 1: Pending: The USB transfer will receive a callback in the future.
1827 *------------------------------------------------------------------------*/
1829 usbd_transfer_pending(struct usb_xfer *xfer)
1831 struct usb_xfer_root *info;
1832 struct usb_xfer_queue *pq;
1835 /* transfer is gone */
1838 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1840 if (xfer->flags_int.transferring) {
1844 USB_BUS_LOCK(xfer->xroot->bus);
1845 if (xfer->wait_queue) {
1846 /* we are waiting on a queue somewhere */
1847 USB_BUS_UNLOCK(xfer->xroot->bus);
1853 if (pq->curr == xfer) {
1854 /* we are currently scheduled for callback */
1855 USB_BUS_UNLOCK(xfer->xroot->bus);
1858 /* we are not pending */
1859 USB_BUS_UNLOCK(xfer->xroot->bus);
1863 /*------------------------------------------------------------------------*
1864 * usbd_transfer_drain
1866 * This function will stop the USB transfer and wait for any
1867 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1868 * are loaded into DMA can safely be freed or reused after that this
1869 * function has returned.
1870 *------------------------------------------------------------------------*/
1872 usbd_transfer_drain(struct usb_xfer *xfer)
1874 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1875 "usbd_transfer_drain can sleep!");
1878 /* transfer is gone */
1881 if (xfer->xroot->xfer_mtx != &Giant) {
1882 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1884 USB_XFER_LOCK(xfer);
1886 usbd_transfer_stop(xfer);
1888 while (usbd_transfer_pending(xfer) ||
1889 xfer->flags_int.doing_callback) {
1892 * It is allowed that the callback can drop its
1893 * transfer mutex. In that case checking only
1894 * "usbd_transfer_pending()" is not enough to tell if
1895 * the USB transfer is fully drained. We also need to
1896 * check the internal "doing_callback" flag.
1898 xfer->flags_int.draining = 1;
1901 * Wait until the current outstanding USB
1902 * transfer is complete !
1904 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1906 USB_XFER_UNLOCK(xfer);
1909 struct usb_page_cache *
1910 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1912 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1914 return (&xfer->frbuffers[frindex]);
1917 /*------------------------------------------------------------------------*
1918 * usbd_xfer_get_fps_shift
1920 * The following function is only useful for isochronous transfers. It
1921 * returns how many times the frame execution rate has been shifted
1927 *------------------------------------------------------------------------*/
1929 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1931 return (xfer->fps_shift);
1935 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1937 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1939 return (xfer->frlengths[frindex]);
1942 /*------------------------------------------------------------------------*
1943 * usbd_xfer_set_frame_data
1945 * This function sets the pointer of the buffer that should
1946 * loaded directly into DMA for the given USB frame. Passing "ptr"
1947 * equal to NULL while the corresponding "frlength" is greater
1948 * than zero gives undefined results!
1949 *------------------------------------------------------------------------*/
1951 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1952 void *ptr, usb_frlength_t len)
1954 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1956 /* set virtual address to load and length */
1957 xfer->frbuffers[frindex].buffer = ptr;
1958 usbd_xfer_set_frame_len(xfer, frindex, len);
1962 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1963 void **ptr, int *len)
1965 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1968 *ptr = xfer->frbuffers[frindex].buffer;
1970 *len = xfer->frlengths[frindex];
1974 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
1978 *actlen = xfer->actlen;
1980 *sumlen = xfer->sumlen;
1981 if (aframes != NULL)
1982 *aframes = xfer->aframes;
1983 if (nframes != NULL)
1984 *nframes = xfer->nframes;
1987 /*------------------------------------------------------------------------*
1988 * usbd_xfer_set_frame_offset
1990 * This function sets the frame data buffer offset relative to the beginning
1991 * of the USB DMA buffer allocated for this USB transfer.
1992 *------------------------------------------------------------------------*/
1994 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
1995 usb_frcount_t frindex)
1997 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
1998 "when the USB buffer is external\n"));
1999 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2001 /* set virtual address to load */
2002 xfer->frbuffers[frindex].buffer =
2003 USB_ADD_BYTES(xfer->local_buffer, offset);
2007 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2013 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2019 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2025 usbd_xfer_max_frames(struct usb_xfer *xfer)
2027 return (xfer->max_frame_count);
2031 usbd_xfer_max_len(struct usb_xfer *xfer)
2033 return (xfer->max_data_length);
2037 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2039 return (xfer->max_frame_size);
2043 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2046 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2048 xfer->frlengths[frindex] = len;
2051 /*------------------------------------------------------------------------*
2052 * usb_callback_proc - factored out code
2054 * This function performs USB callbacks.
2055 *------------------------------------------------------------------------*/
2057 usb_callback_proc(struct usb_proc_msg *_pm)
2059 struct usb_done_msg *pm = (void *)_pm;
2060 struct usb_xfer_root *info = pm->xroot;
2062 /* Change locking order */
2063 USB_BUS_UNLOCK(info->bus);
2066 * We exploit the fact that the mutex is the same for all
2067 * callbacks that will be called from this thread:
2069 mtx_lock(info->xfer_mtx);
2070 USB_BUS_LOCK(info->bus);
2072 /* Continue where we lost track */
2073 usb_command_wrapper(&info->done_q,
2076 mtx_unlock(info->xfer_mtx);
2079 /*------------------------------------------------------------------------*
2080 * usbd_callback_ss_done_defer
2082 * This function will defer the start, stop and done callback to the
2084 *------------------------------------------------------------------------*/
2086 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2088 struct usb_xfer_root *info = xfer->xroot;
2089 struct usb_xfer_queue *pq = &info->done_q;
2091 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2093 if (pq->curr != xfer) {
2094 usbd_transfer_enqueue(pq, xfer);
2096 if (!pq->recurse_1) {
2099 * We have to postpone the callback due to the fact we
2100 * will have a Lock Order Reversal, LOR, if we try to
2103 if (usb_proc_msignal(info->done_p,
2104 &info->done_m[0], &info->done_m[1])) {
2108 /* clear second recurse flag */
2115 /*------------------------------------------------------------------------*
2116 * usbd_callback_wrapper
2118 * This is a wrapper for USB callbacks. This wrapper does some
2119 * auto-magic things like figuring out if we can call the callback
2120 * directly from the current context or if we need to wakeup the
2121 * interrupt process.
2122 *------------------------------------------------------------------------*/
2124 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2126 struct usb_xfer *xfer = pq->curr;
2127 struct usb_xfer_root *info = xfer->xroot;
2129 USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2130 if (!mtx_owned(info->xfer_mtx)) {
2132 * Cases that end up here:
2134 * 5) HW interrupt done callback or other source.
2136 DPRINTFN(3, "case 5\n");
2139 * We have to postpone the callback due to the fact we
2140 * will have a Lock Order Reversal, LOR, if we try to
2143 if (usb_proc_msignal(info->done_p,
2144 &info->done_m[0], &info->done_m[1])) {
2150 * Cases that end up here:
2152 * 1) We are starting a transfer
2153 * 2) We are prematurely calling back a transfer
2154 * 3) We are stopping a transfer
2155 * 4) We are doing an ordinary callback
2157 DPRINTFN(3, "case 1-4\n");
2158 /* get next USB transfer in the queue */
2159 info->done_q.curr = NULL;
2161 /* set flag in case of drain */
2162 xfer->flags_int.doing_callback = 1;
2164 USB_BUS_UNLOCK(info->bus);
2165 USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2167 /* set correct USB state for callback */
2168 if (!xfer->flags_int.transferring) {
2169 xfer->usb_state = USB_ST_SETUP;
2170 if (!xfer->flags_int.started) {
2171 /* we got stopped before we even got started */
2172 USB_BUS_LOCK(info->bus);
2177 if (usbd_callback_wrapper_sub(xfer)) {
2178 /* the callback has been deferred */
2179 USB_BUS_LOCK(info->bus);
2183 /* decrement power reference */
2184 usbd_transfer_power_ref(xfer, -1);
2186 xfer->flags_int.transferring = 0;
2189 xfer->usb_state = USB_ST_ERROR;
2191 /* set transferred state */
2192 xfer->usb_state = USB_ST_TRANSFERRED;
2194 /* sync DMA memory, if any */
2195 if (xfer->flags_int.bdma_enable &&
2196 (!xfer->flags_int.bdma_no_post_sync)) {
2197 usb_bdma_post_sync(xfer);
2203 /* call processing routine */
2204 (xfer->callback) (xfer, xfer->error);
2206 /* pickup the USB mutex again */
2207 USB_BUS_LOCK(info->bus);
2210 * Check if we got started after that we got cancelled, but
2211 * before we managed to do the callback.
2213 if ((!xfer->flags_int.open) &&
2214 (xfer->flags_int.started) &&
2215 (xfer->usb_state == USB_ST_ERROR)) {
2216 /* clear flag in case of drain */
2217 xfer->flags_int.doing_callback = 0;
2218 /* try to loop, but not recursivly */
2219 usb_command_wrapper(&info->done_q, xfer);
2224 /* clear flag in case of drain */
2225 xfer->flags_int.doing_callback = 0;
2228 * Check if we are draining.
2230 if (xfer->flags_int.draining &&
2231 (!xfer->flags_int.transferring)) {
2232 /* "usbd_transfer_drain()" is waiting for end of transfer */
2233 xfer->flags_int.draining = 0;
2234 cv_broadcast(&info->cv_drain);
2237 /* do the next callback, if any */
2238 usb_command_wrapper(&info->done_q,
2242 /*------------------------------------------------------------------------*
2243 * usb_dma_delay_done_cb
2245 * This function is called when the DMA delay has been exectuded, and
2246 * will make sure that the callback is called to complete the USB
2247 * transfer. This code path is ususally only used when there is an USB
2248 * error like USB_ERR_CANCELLED.
2249 *------------------------------------------------------------------------*/
2251 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2253 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2255 DPRINTFN(3, "Completed %p\n", xfer);
2257 /* queue callback for execution, again */
2258 usbd_transfer_done(xfer, 0);
2261 /*------------------------------------------------------------------------*
2262 * usbd_transfer_dequeue
2264 * - This function is used to remove an USB transfer from a USB
2267 * - This function can be called multiple times in a row.
2268 *------------------------------------------------------------------------*/
2270 usbd_transfer_dequeue(struct usb_xfer *xfer)
2272 struct usb_xfer_queue *pq;
2274 pq = xfer->wait_queue;
2276 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2277 xfer->wait_queue = NULL;
2281 /*------------------------------------------------------------------------*
2282 * usbd_transfer_enqueue
2284 * - This function is used to insert an USB transfer into a USB *
2287 * - This function can be called multiple times in a row.
2288 *------------------------------------------------------------------------*/
2290 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2293 * Insert the USB transfer into the queue, if it is not
2294 * already on a USB transfer queue:
2296 if (xfer->wait_queue == NULL) {
2297 xfer->wait_queue = pq;
2298 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2302 /*------------------------------------------------------------------------*
2303 * usbd_transfer_done
2305 * - This function is used to remove an USB transfer from the busdma,
2306 * pipe or interrupt queue.
2308 * - This function is used to queue the USB transfer on the done
2311 * - This function is used to stop any USB transfer timeouts.
2312 *------------------------------------------------------------------------*/
2314 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2316 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2318 DPRINTF("err=%s\n", usbd_errstr(error));
2321 * If we are not transferring then just return.
2322 * This can happen during transfer cancel.
2324 if (!xfer->flags_int.transferring) {
2325 DPRINTF("not transferring\n");
2326 /* end of control transfer, if any */
2327 xfer->flags_int.control_act = 0;
2330 /* only set transfer error if not already set */
2332 xfer->error = error;
2334 /* stop any callouts */
2335 usb_callout_stop(&xfer->timeout_handle);
2338 * If we are waiting on a queue, just remove the USB transfer
2339 * from the queue, if any. We should have the required locks
2340 * locked to do the remove when this function is called.
2342 usbd_transfer_dequeue(xfer);
2345 if (mtx_owned(xfer->xroot->xfer_mtx)) {
2346 struct usb_xfer_queue *pq;
2349 * If the private USB lock is not locked, then we assume
2350 * that the BUS-DMA load stage has been passed:
2352 pq = &xfer->xroot->dma_q;
2354 if (pq->curr == xfer) {
2355 /* start the next BUS-DMA load, if any */
2356 usb_command_wrapper(pq, NULL);
2360 /* keep some statistics */
2362 xfer->xroot->bus->stats_err.uds_requests
2363 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2365 xfer->xroot->bus->stats_ok.uds_requests
2366 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2369 /* call the USB transfer callback */
2370 usbd_callback_ss_done_defer(xfer);
2373 /*------------------------------------------------------------------------*
2374 * usbd_transfer_start_cb
2376 * This function is called to start the USB transfer when
2377 * "xfer->interval" is greater than zero, and and the endpoint type is
2379 *------------------------------------------------------------------------*/
2381 usbd_transfer_start_cb(void *arg)
2383 struct usb_xfer *xfer = arg;
2384 struct usb_endpoint *ep = xfer->endpoint;
2386 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2390 /* start the transfer */
2391 (ep->methods->start) (xfer);
2393 xfer->flags_int.can_cancel_immed = 1;
2395 /* check for error */
2397 /* some error has happened */
2398 usbd_transfer_done(xfer, 0);
2402 /*------------------------------------------------------------------------*
2403 * usbd_xfer_set_stall
2405 * This function is used to set the stall flag outside the
2406 * callback. This function is NULL safe.
2407 *------------------------------------------------------------------------*/
2409 usbd_xfer_set_stall(struct usb_xfer *xfer)
2415 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2417 /* avoid any races by locking the USB mutex */
2418 USB_BUS_LOCK(xfer->xroot->bus);
2419 xfer->flags.stall_pipe = 1;
2420 USB_BUS_UNLOCK(xfer->xroot->bus);
2424 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2426 return (xfer->endpoint->is_stalled);
2429 /*------------------------------------------------------------------------*
2430 * usbd_transfer_clear_stall
2432 * This function is used to clear the stall flag outside the
2433 * callback. This function is NULL safe.
2434 *------------------------------------------------------------------------*/
2436 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2442 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2444 /* avoid any races by locking the USB mutex */
2445 USB_BUS_LOCK(xfer->xroot->bus);
2447 xfer->flags.stall_pipe = 0;
2449 USB_BUS_UNLOCK(xfer->xroot->bus);
2452 /*------------------------------------------------------------------------*
2455 * This function is used to add an USB transfer to the pipe transfer list.
2456 *------------------------------------------------------------------------*/
2458 usbd_pipe_start(struct usb_xfer_queue *pq)
2460 struct usb_endpoint *ep;
2461 struct usb_xfer *xfer;
2465 ep = xfer->endpoint;
2467 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2470 * If the endpoint is already stalled we do nothing !
2472 if (ep->is_stalled) {
2476 * Check if we are supposed to stall the endpoint:
2478 if (xfer->flags.stall_pipe) {
2479 struct usb_device *udev;
2480 struct usb_xfer_root *info;
2482 /* clear stall command */
2483 xfer->flags.stall_pipe = 0;
2485 /* get pointer to USB device */
2490 * Only stall BULK and INTERRUPT endpoints.
2492 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2493 if ((type == UE_BULK) ||
2494 (type == UE_INTERRUPT)) {
2499 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2500 (udev->bus->methods->set_stall) (
2501 udev, NULL, ep, &did_stall);
2502 } else if (udev->ctrl_xfer[1]) {
2503 info = udev->ctrl_xfer[1]->xroot;
2505 &info->bus->non_giant_callback_proc,
2506 &udev->cs_msg[0], &udev->cs_msg[1]);
2508 /* should not happen */
2509 DPRINTFN(0, "No stall handler\n");
2512 * Check if we should stall. Some USB hardware
2513 * handles set- and clear-stall in hardware.
2517 * The transfer will be continued when
2518 * the clear-stall control endpoint
2519 * message is received.
2524 } else if (type == UE_ISOCHRONOUS) {
2527 * Make sure any FIFO overflow or other FIFO
2528 * error conditions go away by resetting the
2529 * endpoint FIFO through the clear stall
2532 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2533 (udev->bus->methods->clear_stall) (udev, ep);
2537 /* Set or clear stall complete - special case */
2538 if (xfer->nframes == 0) {
2539 /* we are complete */
2541 usbd_transfer_done(xfer, 0);
2547 * 1) Start the first transfer queued.
2549 * 2) Re-start the current USB transfer.
2552 * Check if there should be any
2553 * pre transfer start delay:
2555 if (xfer->interval > 0) {
2556 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2557 if ((type == UE_BULK) ||
2558 (type == UE_CONTROL)) {
2559 usbd_transfer_timeout_ms(xfer,
2560 &usbd_transfer_start_cb,
2567 /* start USB transfer */
2568 (ep->methods->start) (xfer);
2570 xfer->flags_int.can_cancel_immed = 1;
2572 /* check for error */
2574 /* some error has happened */
2575 usbd_transfer_done(xfer, 0);
2579 /*------------------------------------------------------------------------*
2580 * usbd_transfer_timeout_ms
2582 * This function is used to setup a timeout on the given USB
2583 * transfer. If the timeout has been deferred the callback given by
2584 * "cb" will get called after "ms" milliseconds.
2585 *------------------------------------------------------------------------*/
2587 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2588 void (*cb) (void *arg), usb_timeout_t ms)
2590 USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2593 usb_callout_reset(&xfer->timeout_handle,
2594 USB_MS_TO_TICKS(ms), cb, xfer);
2597 /*------------------------------------------------------------------------*
2598 * usbd_callback_wrapper_sub
2600 * - This function will update variables in an USB transfer after
2601 * that the USB transfer is complete.
2603 * - This function is used to start the next USB transfer on the
2604 * ep transfer queue, if any.
2606 * NOTE: In some special cases the USB transfer will not be removed from
2607 * the pipe queue, but remain first. To enforce USB transfer removal call
2608 * this function passing the error code "USB_ERR_CANCELLED".
2612 * Else: The callback has been deferred.
2613 *------------------------------------------------------------------------*/
2615 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2617 struct usb_endpoint *ep;
2618 struct usb_bus *bus;
2621 bus = xfer->xroot->bus;
2623 if ((!xfer->flags_int.open) &&
2624 (!xfer->flags_int.did_close)) {
2627 (xfer->endpoint->methods->close) (xfer);
2628 USB_BUS_UNLOCK(bus);
2629 /* only close once */
2630 xfer->flags_int.did_close = 1;
2631 return (1); /* wait for new callback */
2634 * If we have a non-hardware induced error we
2635 * need to do the DMA delay!
2637 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2638 (xfer->error == USB_ERR_CANCELLED ||
2639 xfer->error == USB_ERR_TIMEOUT ||
2640 bus->methods->start_dma_delay != NULL)) {
2644 /* only delay once */
2645 xfer->flags_int.did_dma_delay = 1;
2647 /* we can not cancel this delay */
2648 xfer->flags_int.can_cancel_immed = 0;
2650 temp = usbd_get_dma_delay(xfer->xroot->udev);
2652 DPRINTFN(3, "DMA delay, %u ms, "
2653 "on %p\n", temp, xfer);
2658 * Some hardware solutions have dedicated
2659 * events when it is safe to free DMA'ed
2660 * memory. For the other hardware platforms we
2661 * use a static delay.
2663 if (bus->methods->start_dma_delay != NULL) {
2664 (bus->methods->start_dma_delay) (xfer);
2666 usbd_transfer_timeout_ms(xfer,
2667 (void *)&usb_dma_delay_done_cb, temp);
2669 USB_BUS_UNLOCK(bus);
2670 return (1); /* wait for new callback */
2673 /* check actual number of frames */
2674 if (xfer->aframes > xfer->nframes) {
2675 if (xfer->error == 0) {
2676 panic("%s: actual number of frames, %d, is "
2677 "greater than initial number of frames, %d\n",
2678 __FUNCTION__, xfer->aframes, xfer->nframes);
2680 /* just set some valid value */
2681 xfer->aframes = xfer->nframes;
2684 /* compute actual length */
2687 for (x = 0; x != xfer->aframes; x++) {
2688 xfer->actlen += xfer->frlengths[x];
2692 * Frames that were not transferred get zero actual length in
2693 * case the USB device driver does not check the actual number
2694 * of frames transferred, "xfer->aframes":
2696 for (; x < xfer->nframes; x++) {
2697 usbd_xfer_set_frame_len(xfer, x, 0);
2700 /* check actual length */
2701 if (xfer->actlen > xfer->sumlen) {
2702 if (xfer->error == 0) {
2703 panic("%s: actual length, %d, is greater than "
2704 "initial length, %d\n",
2705 __FUNCTION__, xfer->actlen, xfer->sumlen);
2707 /* just set some valid value */
2708 xfer->actlen = xfer->sumlen;
2711 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2712 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2713 xfer->aframes, xfer->nframes);
2716 /* end of control transfer, if any */
2717 xfer->flags_int.control_act = 0;
2719 /* check if we should block the execution queue */
2720 if ((xfer->error != USB_ERR_CANCELLED) &&
2721 (xfer->flags.pipe_bof)) {
2722 DPRINTFN(2, "xfer=%p: Block On Failure "
2723 "on endpoint=%p\n", xfer, xfer->endpoint);
2727 /* check for short transfers */
2728 if (xfer->actlen < xfer->sumlen) {
2730 /* end of control transfer, if any */
2731 xfer->flags_int.control_act = 0;
2733 if (!xfer->flags_int.short_xfer_ok) {
2734 xfer->error = USB_ERR_SHORT_XFER;
2735 if (xfer->flags.pipe_bof) {
2736 DPRINTFN(2, "xfer=%p: Block On Failure on "
2737 "Short Transfer on endpoint %p.\n",
2738 xfer, xfer->endpoint);
2744 * Check if we are in the middle of a
2747 if (xfer->flags_int.control_act) {
2748 DPRINTFN(5, "xfer=%p: Control transfer "
2749 "active on endpoint=%p\n", xfer, xfer->endpoint);
2755 ep = xfer->endpoint;
2758 * If the current USB transfer is completing we need to start the
2762 if (ep->endpoint_q.curr == xfer) {
2763 usb_command_wrapper(&ep->endpoint_q, NULL);
2765 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2766 /* there is another USB transfer waiting */
2768 /* this is the last USB transfer */
2769 /* clear isochronous sync flag */
2770 xfer->endpoint->is_synced = 0;
2773 USB_BUS_UNLOCK(bus);
2778 /*------------------------------------------------------------------------*
2779 * usb_command_wrapper
2781 * This function is used to execute commands non-recursivly on an USB
2783 *------------------------------------------------------------------------*/
2785 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2789 * If the transfer is not already processing,
2792 if (pq->curr != xfer) {
2793 usbd_transfer_enqueue(pq, xfer);
2794 if (pq->curr != NULL) {
2795 /* something is already processing */
2796 DPRINTFN(6, "busy %p\n", pq->curr);
2801 /* Get next element in queue */
2805 if (!pq->recurse_1) {
2809 /* set both recurse flags */
2813 if (pq->curr == NULL) {
2814 xfer = TAILQ_FIRST(&pq->head);
2816 TAILQ_REMOVE(&pq->head, xfer,
2818 xfer->wait_queue = NULL;
2824 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2826 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2828 } while (!pq->recurse_2);
2830 /* clear first recurse flag */
2834 /* clear second recurse flag */
2839 /*------------------------------------------------------------------------*
2840 * usbd_ctrl_transfer_setup
2842 * This function is used to setup the default USB control endpoint
2844 *------------------------------------------------------------------------*/
2846 usbd_ctrl_transfer_setup(struct usb_device *udev)
2848 struct usb_xfer *xfer;
2850 uint8_t iface_index;
2852 /* check for root HUB */
2853 if (udev->parent_hub == NULL)
2857 xfer = udev->ctrl_xfer[0];
2859 USB_XFER_LOCK(xfer);
2861 ((xfer->address == udev->address) &&
2862 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2863 udev->ddesc.bMaxPacketSize));
2864 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2867 * NOTE: checking "xfer->address" and
2868 * starting the USB transfer must be
2871 usbd_transfer_start(xfer);
2874 USB_XFER_UNLOCK(xfer);
2881 * All parameters are exactly the same like before.
2887 * Update wMaxPacketSize for the default control endpoint:
2889 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2890 udev->ddesc.bMaxPacketSize;
2893 * Unsetup any existing USB transfer:
2895 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2898 * Try to setup a new USB transfer for the
2899 * default control endpoint:
2902 if (usbd_transfer_setup(udev, &iface_index,
2903 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2904 &udev->device_mtx)) {
2905 DPRINTFN(0, "could not setup default "
2912 /*------------------------------------------------------------------------*
2913 * usbd_clear_data_toggle - factored out code
2915 * NOTE: the intention of this function is not to reset the hardware
2917 *------------------------------------------------------------------------*/
2919 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2921 USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
2923 /* check that we have a valid case */
2924 if (udev->flags.usb_mode == USB_MODE_HOST &&
2925 udev->parent_hub != NULL &&
2926 udev->bus->methods->clear_stall != NULL &&
2927 ep->methods != NULL) {
2928 (udev->bus->methods->clear_stall) (udev, ep);
2932 /*------------------------------------------------------------------------*
2933 * usbd_clear_data_toggle - factored out code
2935 * NOTE: the intention of this function is not to reset the hardware
2936 * data toggle on the USB device side.
2937 *------------------------------------------------------------------------*/
2939 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2941 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2943 USB_BUS_LOCK(udev->bus);
2944 ep->toggle_next = 0;
2945 /* some hardware needs a callback to clear the data toggle */
2946 usbd_clear_stall_locked(udev, ep);
2947 USB_BUS_UNLOCK(udev->bus);
2950 /*------------------------------------------------------------------------*
2951 * usbd_clear_stall_callback - factored out clear stall callback
2954 * xfer1: Clear Stall Control Transfer
2955 * xfer2: Stalled USB Transfer
2957 * This function is NULL safe.
2963 * Clear stall config example:
2965 * static const struct usb_config my_clearstall = {
2966 * .type = UE_CONTROL,
2968 * .direction = UE_DIR_ANY,
2969 * .interval = 50, //50 milliseconds
2970 * .bufsize = sizeof(struct usb_device_request),
2971 * .timeout = 1000, //1.000 seconds
2972 * .callback = &my_clear_stall_callback, // **
2973 * .usb_mode = USB_MODE_HOST,
2976 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
2977 * passing the correct parameters.
2978 *------------------------------------------------------------------------*/
2980 usbd_clear_stall_callback(struct usb_xfer *xfer1,
2981 struct usb_xfer *xfer2)
2983 struct usb_device_request req;
2985 if (xfer2 == NULL) {
2986 /* looks like we are tearing down */
2987 DPRINTF("NULL input parameter\n");
2990 USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
2991 USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
2993 switch (USB_GET_STATE(xfer1)) {
2997 * pre-clear the data toggle to DATA0 ("umass.c" and
2998 * "ata-usb.c" depends on this)
3001 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3003 /* setup a clear-stall packet */
3005 req.bmRequestType = UT_WRITE_ENDPOINT;
3006 req.bRequest = UR_CLEAR_FEATURE;
3007 USETW(req.wValue, UF_ENDPOINT_HALT);
3008 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3010 USETW(req.wLength, 0);
3013 * "usbd_transfer_setup_sub()" will ensure that
3014 * we have sufficient room in the buffer for
3015 * the request structure!
3018 /* copy in the transfer */
3020 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3023 xfer1->frlengths[0] = sizeof(req);
3026 usbd_transfer_submit(xfer1);
3029 case USB_ST_TRANSFERRED:
3032 default: /* Error */
3033 if (xfer1->error == USB_ERR_CANCELLED) {
3038 return (1); /* Clear Stall Finished */
3041 /*------------------------------------------------------------------------*
3042 * usbd_transfer_poll
3044 * The following function gets called from the USB keyboard driver and
3045 * UMASS when the system has paniced.
3047 * NOTE: It is currently not possible to resume normal operation on
3048 * the USB controller which has been polled, due to clearing of the
3049 * "up_dsleep" and "up_msleep" flags.
3050 *------------------------------------------------------------------------*/
3052 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3054 struct usb_xfer *xfer;
3055 struct usb_xfer_root *xroot;
3056 struct usb_device *udev;
3057 struct usb_proc_msg *pm;
3062 for (n = 0; n != max; n++) {
3063 /* Extra checks to avoid panic */
3066 continue; /* no USB transfer */
3067 xroot = xfer->xroot;
3069 continue; /* no USB root */
3072 continue; /* no USB device */
3073 if (udev->bus == NULL)
3074 continue; /* no BUS structure */
3075 if (udev->bus->methods == NULL)
3076 continue; /* no BUS methods */
3077 if (udev->bus->methods->xfer_poll == NULL)
3078 continue; /* no poll method */
3080 /* make sure that the BUS mutex is not locked */
3082 while (mtx_owned(&xroot->udev->bus->bus_mtx)) {
3083 mtx_unlock(&xroot->udev->bus->bus_mtx);
3087 /* make sure that the transfer mutex is not locked */
3089 while (mtx_owned(xroot->xfer_mtx)) {
3090 mtx_unlock(xroot->xfer_mtx);
3094 /* Make sure cv_signal() and cv_broadcast() is not called */
3095 udev->bus->control_xfer_proc.up_msleep = 0;
3096 udev->bus->explore_proc.up_msleep = 0;
3097 udev->bus->giant_callback_proc.up_msleep = 0;
3098 udev->bus->non_giant_callback_proc.up_msleep = 0;
3100 /* poll USB hardware */
3101 (udev->bus->methods->xfer_poll) (udev->bus);
3103 USB_BUS_LOCK(xroot->bus);
3105 /* check for clear stall */
3106 if (udev->ctrl_xfer[1] != NULL) {
3108 /* poll clear stall start */
3109 pm = &udev->cs_msg[0].hdr;
3110 (pm->pm_callback) (pm);
3111 /* poll clear stall done thread */
3112 pm = &udev->ctrl_xfer[1]->
3113 xroot->done_m[0].hdr;
3114 (pm->pm_callback) (pm);
3117 /* poll done thread */
3118 pm = &xroot->done_m[0].hdr;
3119 (pm->pm_callback) (pm);
3121 USB_BUS_UNLOCK(xroot->bus);
3123 /* restore transfer mutex */
3125 mtx_lock(xroot->xfer_mtx);
3127 /* restore BUS mutex */
3129 mtx_lock(&xroot->udev->bus->bus_mtx);
3134 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3135 uint8_t type, enum usb_dev_speed speed)
3137 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3138 [USB_SPEED_LOW] = 8,
3139 [USB_SPEED_FULL] = 64,
3140 [USB_SPEED_HIGH] = 1024,
3141 [USB_SPEED_VARIABLE] = 1024,
3142 [USB_SPEED_SUPER] = 1024,
3145 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3146 [USB_SPEED_LOW] = 0, /* invalid */
3147 [USB_SPEED_FULL] = 1023,
3148 [USB_SPEED_HIGH] = 1024,
3149 [USB_SPEED_VARIABLE] = 3584,
3150 [USB_SPEED_SUPER] = 1024,
3153 static const uint16_t control_min[USB_SPEED_MAX] = {
3154 [USB_SPEED_LOW] = 8,
3155 [USB_SPEED_FULL] = 8,
3156 [USB_SPEED_HIGH] = 64,
3157 [USB_SPEED_VARIABLE] = 512,
3158 [USB_SPEED_SUPER] = 512,
3161 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3162 [USB_SPEED_LOW] = 8,
3163 [USB_SPEED_FULL] = 8,
3164 [USB_SPEED_HIGH] = 512,
3165 [USB_SPEED_VARIABLE] = 512,
3166 [USB_SPEED_SUPER] = 1024,
3171 memset(ptr, 0, sizeof(*ptr));
3175 ptr->range.max = intr_range_max[speed];
3177 case UE_ISOCHRONOUS:
3178 ptr->range.max = isoc_range_max[speed];
3181 if (type == UE_BULK)
3182 temp = bulk_min[speed];
3183 else /* UE_CONTROL */
3184 temp = control_min[speed];
3186 /* default is fixed */
3187 ptr->fixed[0] = temp;
3188 ptr->fixed[1] = temp;
3189 ptr->fixed[2] = temp;
3190 ptr->fixed[3] = temp;
3192 if (speed == USB_SPEED_FULL) {
3193 /* multiple sizes */
3198 if ((speed == USB_SPEED_VARIABLE) &&
3199 (type == UE_BULK)) {
3200 /* multiple sizes */
3201 ptr->fixed[2] = 1024;
3202 ptr->fixed[3] = 1536;
3209 usbd_xfer_softc(struct usb_xfer *xfer)
3211 return (xfer->priv_sc);
3215 usbd_xfer_get_priv(struct usb_xfer *xfer)
3217 return (xfer->priv_fifo);
3221 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3223 xfer->priv_fifo = ptr;
3227 usbd_xfer_state(struct usb_xfer *xfer)
3229 return (xfer->usb_state);
3233 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3236 case USB_FORCE_SHORT_XFER:
3237 xfer->flags.force_short_xfer = 1;
3239 case USB_SHORT_XFER_OK:
3240 xfer->flags.short_xfer_ok = 1;
3242 case USB_MULTI_SHORT_OK:
3243 xfer->flags.short_frames_ok = 1;
3245 case USB_MANUAL_STATUS:
3246 xfer->flags.manual_status = 1;
3252 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3255 case USB_FORCE_SHORT_XFER:
3256 xfer->flags.force_short_xfer = 0;
3258 case USB_SHORT_XFER_OK:
3259 xfer->flags.short_xfer_ok = 0;
3261 case USB_MULTI_SHORT_OK:
3262 xfer->flags.short_frames_ok = 0;
3264 case USB_MANUAL_STATUS:
3265 xfer->flags.manual_status = 0;
3271 * The following function returns in milliseconds when the isochronous
3272 * transfer was completed by the hardware. The returned value wraps
3273 * around 65536 milliseconds.
3276 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3278 return (xfer->isoc_time_complete);