2 * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/stdint.h>
27 #include <sys/param.h>
28 #include <sys/queue.h>
29 #include <sys/types.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
33 #include <sys/module.h>
35 #include <sys/mutex.h>
36 #include <sys/condvar.h>
37 #include <sys/sysctl.h>
38 #include <sys/unistd.h>
39 #include <sys/callout.h>
40 #include <sys/malloc.h>
44 #include <bus/u4b/usb.h>
45 #include <bus/u4b/usbdi.h>
46 #include <bus/u4b/usbdi_util.h>
48 #define USB_DEBUG_VAR usb_debug
50 #include <bus/u4b/usb_core.h>
51 #include <bus/u4b/usb_busdma.h>
52 #include <bus/u4b/usb_process.h>
53 #include <bus/u4b/usb_transfer.h>
54 #include <bus/u4b/usb_device.h>
55 #include <bus/u4b/usb_debug.h>
56 #include <bus/u4b/usb_util.h>
58 #include <bus/u4b/usb_controller.h>
59 #include <bus/u4b/usb_bus.h>
60 #include <bus/u4b/usb_pf.h>
62 struct usb_std_packet_size {
64 uint16_t min; /* inclusive */
65 uint16_t max; /* inclusive */
71 static usb_callback_t usb_request_callback;
73 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
75 /* This transfer is used for generic control endpoint transfers */
79 .endpoint = 0x00, /* Control endpoint */
80 .direction = UE_DIR_ANY,
81 .bufsize = USB_EP0_BUFSIZE, /* bytes */
82 .flags = {.proxy_buffer = 1,},
83 .callback = &usb_request_callback,
84 .usb_mode = USB_MODE_DUAL, /* both modes */
87 /* This transfer is used for generic clear stall only */
91 .endpoint = 0x00, /* Control pipe */
92 .direction = UE_DIR_ANY,
93 .bufsize = sizeof(struct usb_device_request),
94 .callback = &usb_do_clear_stall_callback,
95 .timeout = 1000, /* 1 second */
96 .interval = 50, /* 50ms */
97 .usb_mode = USB_MODE_HOST,
101 /* function prototypes */
103 static void usbd_update_max_frame_size(struct usb_xfer *);
104 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
105 static void usbd_control_transfer_init(struct usb_xfer *);
106 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
107 static void usb_callback_proc(struct usb_proc_msg *);
108 static void usbd_callback_ss_done_defer(struct usb_xfer *);
109 static void usbd_callback_wrapper(struct usb_xfer_queue *);
110 static void usbd_transfer_start_cb(void *);
111 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
112 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
113 uint8_t type, enum usb_dev_speed speed);
115 /*------------------------------------------------------------------------*
116 * usb_request_callback
117 *------------------------------------------------------------------------*/
119 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
121 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
122 usb_handle_request_callback(xfer, error);
124 usbd_do_request_callback(xfer, error);
127 /*------------------------------------------------------------------------*
128 * usbd_update_max_frame_size
130 * This function updates the maximum frame size, hence high speed USB
131 * can transfer multiple consecutive packets.
132 *------------------------------------------------------------------------*/
134 usbd_update_max_frame_size(struct usb_xfer *xfer)
136 /* compute maximum frame size */
137 /* this computation should not overflow 16-bit */
138 /* max = 15 * 1024 */
140 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
143 /*------------------------------------------------------------------------*
146 * The following function is called when we need to
147 * synchronize with DMA hardware.
150 * 0: no DMA delay required
151 * Else: milliseconds of DMA delay
152 *------------------------------------------------------------------------*/
154 usbd_get_dma_delay(struct usb_device *udev)
156 struct usb_bus_methods *mtod;
159 mtod = udev->bus->methods;
162 if (mtod->get_dma_delay) {
163 (mtod->get_dma_delay) (udev, &temp);
165 * Round up and convert to milliseconds. Note that we use
166 * 1024 milliseconds per second. to save a division.
174 /*------------------------------------------------------------------------*
175 * usbd_transfer_setup_sub_malloc
177 * This function will allocate one or more DMA'able memory chunks
178 * according to "size", "align" and "count" arguments. "ppc" is
179 * pointed to a linear array of USB page caches afterwards.
184 *------------------------------------------------------------------------*/
187 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
188 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
191 struct usb_page_cache *pc;
202 USB_ASSERT(align > 1, ("Invalid alignment, 0x%08x\n",
204 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 lockmgr(pc->tag_parent->lock, LK_EXCLUSIVE);
286 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
287 lockmgr(pc->tag_parent->lock, LK_RELEASE);
288 return (1); /* failure */
290 lockmgr(pc->tag_parent->lock, LK_RELEASE);
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;
668 * Setup "frlengths" and shadow "frlengths" for keeping the
669 * initial frame lengths when a USB transfer is complete. This
670 * information is useful when computing isochronous offsets.
672 xfer->frlengths = parm->xfer_length_ptr;
673 parm->xfer_length_ptr += 2 * n_frlengths;
675 /* setup "frbuffers" */
676 xfer->frbuffers = parm->xfer_page_cache_ptr;
677 parm->xfer_page_cache_ptr += n_frbuffers;
679 /* initialize max frame count */
680 xfer->max_frame_count = xfer->nframes;
683 * check if we need to setup
687 if (!xfer->flags.ext_buffer) {
690 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
695 USB_ADD_BYTES(parm->buf, parm->size[0]);
697 usbd_xfer_set_frame_offset(xfer, 0, 0);
699 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
700 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
703 parm->size[0] += parm->bufsize;
705 /* align data again */
706 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
709 * Compute maximum buffer size
712 if (parm->bufsize_max < parm->bufsize) {
713 parm->bufsize_max = parm->bufsize;
716 if (xfer->flags_int.bdma_enable) {
718 * Setup "dma_page_ptr".
720 * Proof for formula below:
722 * Assume there are three USB frames having length "a", "b" and
723 * "c". These USB frames will at maximum need "z"
724 * "usb_page" structures. "z" is given by:
726 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
727 * ((c / USB_PAGE_SIZE) + 2);
729 * Constraining "a", "b" and "c" like this:
731 * (a + b + c) <= parm->bufsize
735 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
737 * Here is the general formula:
739 xfer->dma_page_ptr = parm->dma_page_ptr;
740 parm->dma_page_ptr += (2 * n_frbuffers);
741 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
745 /* correct maximum data length */
746 xfer->max_data_length = 0;
748 /* subtract USB frame remainder from "hc_max_frame_size" */
750 xfer->max_hc_frame_size =
751 (parm->hc_max_frame_size -
752 (parm->hc_max_frame_size % xfer->max_frame_size));
754 if (xfer->max_hc_frame_size == 0) {
755 parm->err = USB_ERR_INVAL;
759 /* initialize frame buffers */
762 for (x = 0; x != n_frbuffers; x++) {
763 xfer->frbuffers[x].tag_parent =
764 &xfer->xroot->dma_parent_tag;
766 if (xfer->flags_int.bdma_enable &&
767 (parm->bufsize_max > 0)) {
769 if (usb_pc_dmamap_create(
771 parm->bufsize_max)) {
772 parm->err = USB_ERR_NOMEM;
782 * Set some dummy values so that we avoid division by zero:
784 xfer->max_hc_frame_size = 1;
785 xfer->max_frame_size = 1;
786 xfer->max_packet_size = 1;
787 xfer->max_data_length = 0;
789 xfer->max_frame_count = 0;
793 /*------------------------------------------------------------------------*
794 * usbd_transfer_setup - setup an array of USB transfers
796 * NOTE: You must always call "usbd_transfer_unsetup" after calling
797 * "usbd_transfer_setup" if success was returned.
799 * The idea is that the USB device driver should pre-allocate all its
800 * transfers by one call to this function.
805 *------------------------------------------------------------------------*/
807 usbd_transfer_setup(struct usb_device *udev,
808 const uint8_t *ifaces, struct usb_xfer **ppxfer,
809 const struct usb_config *setup_start, uint16_t n_setup,
810 void *priv_sc, struct lock *xfer_lock)
812 struct usb_xfer dummy;
813 struct usb_setup_params parm;
814 const struct usb_config *setup_end = setup_start + n_setup;
815 const struct usb_config *setup;
816 struct usb_endpoint *ep;
817 struct usb_xfer_root *info;
818 struct usb_xfer *xfer;
828 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
829 "usbd_transfer_setup can sleep!");
832 /* do some checking first */
835 DPRINTFN(6, "setup array has zero length!\n");
836 return (USB_ERR_INVAL);
838 if (ifaces == NULL) {
839 DPRINTFN(6, "ifaces array is NULL!\n");
840 return (USB_ERR_INVAL);
842 if (xfer_lock == NULL) {
843 panic("xfer without lock!\n");
844 DPRINTFN(6, "using global lock\n");
847 for (setup = setup_start, n = 0;
848 setup != setup_end; setup++, n++) {
849 if (setup->bufsize == (usb_frlength_t)-1) {
850 parm.err = USB_ERR_BAD_BUFSIZE;
851 DPRINTF("invalid bufsize\n");
853 if (setup->callback == NULL) {
854 parm.err = USB_ERR_NO_CALLBACK;
855 DPRINTF("no callback\n");
863 memset(&parm, 0, sizeof(parm));
866 parm.speed = usbd_get_speed(udev);
867 parm.hc_max_packet_count = 1;
869 if (parm.speed >= USB_SPEED_MAX) {
870 parm.err = USB_ERR_INVAL;
873 /* setup all transfers */
879 * Initialize the "usb_xfer_root" structure,
880 * which is common for all our USB transfers.
882 info = USB_ADD_BYTES(buf, 0);
884 info->memory_base = buf;
885 info->memory_size = parm.size[0];
888 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm.size[4]);
889 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm.size[5]);
891 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm.size[5]);
892 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm.size[2]);
894 cv_init(&info->cv_drain, "WDRAIN");
896 info->xfer_lock = xfer_lock;
898 usb_dma_tag_setup(&info->dma_parent_tag,
899 parm.dma_tag_p, udev->bus->dma_parent_tag[0].tag,
900 xfer_lock, &usb_bdma_done_event, 32, parm.dma_tag_max);
903 info->bus = udev->bus;
906 TAILQ_INIT(&info->done_q.head);
907 info->done_q.command = &usbd_callback_wrapper;
909 TAILQ_INIT(&info->dma_q.head);
910 info->dma_q.command = &usb_bdma_work_loop;
912 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
913 info->done_m[0].xroot = info;
914 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
915 info->done_m[1].xroot = info;
918 * In device side mode control endpoint
919 * requests need to run from a separate
920 * context, else there is a chance of
923 if (setup_start == usb_control_ep_cfg)
925 &udev->bus->control_xfer_proc;
928 &udev->bus->non_giant_callback_proc;
934 parm.size[0] += sizeof(info[0]);
936 for (setup = setup_start, n = 0;
937 setup != setup_end; setup++, n++) {
939 /* skip USB transfers without callbacks: */
940 if (setup->callback == NULL) {
943 /* see if there is a matching endpoint */
944 ep = usbd_get_endpoint(udev,
945 ifaces[setup->if_index], setup);
947 if ((ep == NULL) || (ep->methods == NULL)) {
948 if (setup->flags.no_pipe_ok)
950 if ((setup->usb_mode != USB_MODE_DUAL) &&
951 (setup->usb_mode != udev->flags.usb_mode))
953 parm.err = USB_ERR_NO_PIPE;
957 /* align data properly */
958 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
960 /* store current setup pointer */
961 parm.curr_setup = setup;
965 * Common initialization of the
966 * "usb_xfer" structure.
968 xfer = USB_ADD_BYTES(buf, parm.size[0]);
969 xfer->address = udev->address;
970 xfer->priv_sc = priv_sc;
973 usb_callout_init_mtx(&xfer->timeout_handle,
974 &udev->bus->bus_lock, 0);
977 * Setup a dummy xfer, hence we are
978 * writing to the "usb_xfer"
979 * structure pointed to by "xfer"
980 * before we have allocated any
984 memset(&dummy, 0, sizeof(dummy));
988 /* set transfer endpoint pointer */
991 parm.size[0] += sizeof(xfer[0]);
992 parm.methods = xfer->endpoint->methods;
993 parm.curr_xfer = xfer;
996 * Call the Host or Device controller transfer
999 (udev->bus->methods->xfer_setup) (&parm);
1001 /* check for error */
1007 * Increment the endpoint refcount. This
1008 * basically prevents setting a new
1009 * configuration and alternate setting
1010 * when USB transfers are in use on
1011 * the given interface. Search the USB
1012 * code for "endpoint->refcount_alloc" if you
1013 * want more information.
1015 USB_BUS_LOCK(info->bus);
1016 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1017 parm.err = USB_ERR_INVAL;
1019 xfer->endpoint->refcount_alloc++;
1021 if (xfer->endpoint->refcount_alloc == 0)
1022 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1023 USB_BUS_UNLOCK(info->bus);
1026 * Whenever we set ppxfer[] then we
1027 * also need to increment the
1030 info->setup_refcount++;
1033 * Transfer is successfully setup and
1039 /* check for error */
1044 if (buf || parm.err) {
1047 if (refcount == 0) {
1048 /* no transfers - nothing to do ! */
1051 /* align data properly */
1052 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1054 /* store offset temporarily */
1055 parm.size[1] = parm.size[0];
1058 * The number of DMA tags required depends on
1059 * the number of endpoints. The current estimate
1060 * for maximum number of DMA tags per endpoint
1063 parm.dma_tag_max += 2 * MIN(n_setup, USB_EP_MAX);
1066 * DMA tags for QH, TD, Data and more.
1068 parm.dma_tag_max += 8;
1070 parm.dma_tag_p += parm.dma_tag_max;
1072 parm.size[0] += ((uint8_t *)parm.dma_tag_p) -
1075 /* align data properly */
1076 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1078 /* store offset temporarily */
1079 parm.size[3] = parm.size[0];
1081 parm.size[0] += ((uint8_t *)parm.dma_page_ptr) -
1084 /* align data properly */
1085 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1087 /* store offset temporarily */
1088 parm.size[4] = parm.size[0];
1090 parm.size[0] += ((uint8_t *)parm.dma_page_cache_ptr) -
1093 /* store end offset temporarily */
1094 parm.size[5] = parm.size[0];
1096 parm.size[0] += ((uint8_t *)parm.xfer_page_cache_ptr) -
1099 /* store end offset temporarily */
1101 parm.size[2] = parm.size[0];
1103 /* align data properly */
1104 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1106 parm.size[6] = parm.size[0];
1108 parm.size[0] += ((uint8_t *)parm.xfer_length_ptr) -
1111 /* align data properly */
1112 parm.size[0] += ((-parm.size[0]) & (USB_HOST_ALIGN - 1));
1114 /* allocate zeroed memory */
1115 buf = kmalloc(parm.size[0], M_USB, M_WAITOK | M_ZERO);
1117 parm.dma_tag_p = USB_ADD_BYTES(buf, parm.size[1]);
1118 parm.dma_page_ptr = USB_ADD_BYTES(buf, parm.size[3]);
1119 parm.dma_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[4]);
1120 parm.xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm.size[5]);
1121 parm.xfer_length_ptr = USB_ADD_BYTES(buf, parm.size[6]);
1126 if (info->setup_refcount == 0) {
1128 * "usbd_transfer_unsetup_sub" will unlock
1129 * the bus mutex before returning !
1131 USB_BUS_LOCK(info->bus);
1133 /* something went wrong */
1134 usbd_transfer_unsetup_sub(info, 0);
1138 usbd_transfer_unsetup(ppxfer, n_setup);
1143 /*------------------------------------------------------------------------*
1144 * usbd_transfer_unsetup_sub - factored out code
1145 *------------------------------------------------------------------------*/
1147 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1150 struct usb_page_cache *pc;
1153 USB_BUS_LOCK_ASSERT(info->bus);
1155 /* wait for any outstanding DMA operations */
1159 temp = usbd_get_dma_delay(info->udev);
1161 usb_pause_mtx(&info->bus->bus_lock,
1162 USB_MS_TO_TICKS(temp));
1166 /* make sure that our done messages are not queued anywhere */
1167 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1169 USB_BUS_UNLOCK(info->bus);
1172 /* free DMA'able memory, if any */
1173 pc = info->dma_page_cache_start;
1174 while (pc != info->dma_page_cache_end) {
1175 usb_pc_free_mem(pc);
1179 /* free DMA maps in all "xfer->frbuffers" */
1180 pc = info->xfer_page_cache_start;
1181 while (pc != info->xfer_page_cache_end) {
1182 usb_pc_dmamap_destroy(pc);
1186 /* free all DMA tags */
1187 usb_dma_tag_unsetup(&info->dma_parent_tag);
1190 cv_destroy(&info->cv_drain);
1193 * free the "memory_base" last, hence the "info" structure is
1194 * contained within the "memory_base"!
1196 kfree(info->memory_base, M_USB);
1199 /*------------------------------------------------------------------------*
1200 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1202 * NOTE: All USB transfers in progress will get called back passing
1203 * the error code "USB_ERR_CANCELLED" before this function
1205 *------------------------------------------------------------------------*/
1207 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1209 struct usb_xfer *xfer;
1210 struct usb_xfer_root *info;
1211 uint8_t needs_delay = 0;
1214 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1215 "usbd_transfer_unsetup can sleep!");
1219 xfer = pxfer[n_setup];
1226 USB_XFER_LOCK(xfer);
1227 USB_BUS_LOCK(info->bus);
1230 * HINT: when you start/stop a transfer, it might be a
1231 * good idea to directly use the "pxfer[]" structure:
1233 * usbd_transfer_start(sc->pxfer[0]);
1234 * usbd_transfer_stop(sc->pxfer[0]);
1236 * That way, if your code has many parts that will not
1237 * stop running under the same lock, in other words
1238 * "xfer_mtx", the usbd_transfer_start and
1239 * usbd_transfer_stop functions will simply return
1240 * when they detect a NULL pointer argument.
1242 * To avoid any races we clear the "pxfer[]" pointer
1243 * while holding the private mutex of the driver:
1245 pxfer[n_setup] = NULL;
1247 USB_BUS_UNLOCK(info->bus);
1248 USB_XFER_UNLOCK(xfer);
1250 usbd_transfer_drain(xfer);
1253 if (xfer->flags_int.bdma_enable)
1257 * NOTE: default endpoint does not have an
1258 * interface, even if endpoint->iface_index == 0
1260 USB_BUS_LOCK(info->bus);
1261 xfer->endpoint->refcount_alloc--;
1262 USB_BUS_UNLOCK(info->bus);
1264 usb_callout_drain(&xfer->timeout_handle);
1266 USB_BUS_LOCK(info->bus);
1269 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1270 "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);
1500 USB_BUS_LOCK_ASSERT_NOTOWNED(bus);
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 some variables */
1584 for (x = 0; x != xfer->nframes; x++) {
1585 /* make a copy of the frlenghts[] */
1586 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1587 /* compute total transfer length */
1588 xfer->sumlen += xfer->frlengths[x];
1589 if (xfer->sumlen < xfer->frlengths[x]) {
1590 /* length wrapped around */
1592 usbd_transfer_done(xfer, USB_ERR_INVAL);
1593 USB_BUS_UNLOCK(bus);
1598 /* clear some internal flags */
1600 xfer->flags_int.short_xfer_ok = 0;
1601 xfer->flags_int.short_frames_ok = 0;
1603 /* check if this is a control transfer */
1605 if (xfer->flags_int.control_xfr) {
1607 if (usbd_setup_ctrl_transfer(xfer)) {
1609 usbd_transfer_done(xfer, USB_ERR_STALLED);
1610 USB_BUS_UNLOCK(bus);
1615 * Setup filtered version of some transfer flags,
1616 * in case of data read direction
1618 if (USB_GET_DATA_ISREAD(xfer)) {
1620 if (xfer->flags.short_frames_ok) {
1621 xfer->flags_int.short_xfer_ok = 1;
1622 xfer->flags_int.short_frames_ok = 1;
1623 } else if (xfer->flags.short_xfer_ok) {
1624 xfer->flags_int.short_xfer_ok = 1;
1626 /* check for control transfer */
1627 if (xfer->flags_int.control_xfr) {
1629 * 1) Control transfers do not support
1630 * reception of multiple short USB
1631 * frames in host mode and device side
1632 * mode, with exception of:
1634 * 2) Due to sometimes buggy device
1635 * side firmware we need to do a
1636 * STATUS stage in case of short
1637 * control transfers in USB host mode.
1638 * The STATUS stage then becomes the
1639 * "alt_next" to the DATA stage.
1641 xfer->flags_int.short_frames_ok = 1;
1646 * Check if BUS-DMA support is enabled and try to load virtual
1647 * buffers into DMA, if any:
1650 if (xfer->flags_int.bdma_enable) {
1651 /* insert the USB transfer last in the BUS-DMA queue */
1652 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1657 * Enter the USB transfer into the Host Controller or
1658 * Device Controller schedule:
1660 usbd_pipe_enter(xfer);
1663 /*------------------------------------------------------------------------*
1664 * usbd_pipe_enter - factored out code
1665 *------------------------------------------------------------------------*/
1667 usbd_pipe_enter(struct usb_xfer *xfer)
1669 struct usb_endpoint *ep;
1671 USB_XFER_LOCK_ASSERT(xfer);
1673 USB_BUS_LOCK(xfer->xroot->bus);
1675 ep = xfer->endpoint;
1679 /* enter the transfer */
1680 (ep->methods->enter) (xfer);
1682 xfer->flags_int.can_cancel_immed = 1;
1684 /* check for transfer error */
1686 /* some error has happened */
1687 usbd_transfer_done(xfer, 0);
1688 USB_BUS_UNLOCK(xfer->xroot->bus);
1692 /* start the transfer */
1693 usb_command_wrapper(&ep->endpoint_q, xfer);
1694 USB_BUS_UNLOCK(xfer->xroot->bus);
1697 /*------------------------------------------------------------------------*
1698 * usbd_transfer_start - start an USB transfer
1700 * NOTE: Calling this function more than one time will only
1701 * result in a single transfer start, until the USB transfer
1703 *------------------------------------------------------------------------*/
1705 usbd_transfer_start(struct usb_xfer *xfer)
1708 /* transfer is gone */
1711 USB_XFER_LOCK_ASSERT(xfer);
1713 /* mark the USB transfer started */
1715 if (!xfer->flags_int.started) {
1716 /* lock the BUS lock to avoid races updating flags_int */
1717 USB_BUS_LOCK(xfer->xroot->bus);
1718 xfer->flags_int.started = 1;
1719 USB_BUS_UNLOCK(xfer->xroot->bus);
1721 /* check if the USB transfer callback is already transferring */
1723 if (xfer->flags_int.transferring) {
1726 USB_BUS_LOCK(xfer->xroot->bus);
1727 /* call the USB transfer callback */
1728 usbd_callback_ss_done_defer(xfer);
1729 USB_BUS_UNLOCK(xfer->xroot->bus);
1732 /*------------------------------------------------------------------------*
1733 * usbd_transfer_stop - stop an USB transfer
1735 * NOTE: Calling this function more than one time will only
1736 * result in a single transfer stop.
1737 * NOTE: When this function returns it is not safe to free nor
1738 * reuse any DMA buffers. See "usbd_transfer_drain()".
1739 *------------------------------------------------------------------------*/
1741 usbd_transfer_stop(struct usb_xfer *xfer)
1743 struct usb_endpoint *ep;
1746 /* transfer is gone */
1750 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1753 /* check if the USB transfer was ever opened */
1755 if (!xfer->flags_int.open) {
1756 if (xfer->flags_int.started) {
1757 /* nothing to do except clearing the "started" flag */
1758 /* lock the BUS lock to avoid races updating flags_int */
1759 USB_BUS_LOCK(xfer->xroot->bus);
1760 xfer->flags_int.started = 0;
1761 USB_BUS_UNLOCK(xfer->xroot->bus);
1765 /* try to stop the current USB transfer */
1767 USB_BUS_LOCK(xfer->xroot->bus);
1768 /* override any previous error */
1769 xfer->error = USB_ERR_CANCELLED;
1772 * Clear "open" and "started" when both private and USB lock
1773 * is locked so that we don't get a race updating "flags_int"
1775 xfer->flags_int.open = 0;
1776 xfer->flags_int.started = 0;
1779 * Check if we can cancel the USB transfer immediately.
1781 if (xfer->flags_int.transferring) {
1782 if (xfer->flags_int.can_cancel_immed &&
1783 (!xfer->flags_int.did_close)) {
1786 * The following will lead to an USB_ERR_CANCELLED
1787 * error code being passed to the USB callback.
1789 (xfer->endpoint->methods->close) (xfer);
1790 /* only close once */
1791 xfer->flags_int.did_close = 1;
1793 /* need to wait for the next done callback */
1798 /* close here and now */
1799 (xfer->endpoint->methods->close) (xfer);
1802 * Any additional DMA delay is done by
1803 * "usbd_transfer_unsetup()".
1807 * Special case. Check if we need to restart a blocked
1810 ep = xfer->endpoint;
1813 * If the current USB transfer is completing we need
1814 * to start the next one:
1816 if (ep->endpoint_q.curr == xfer) {
1817 usb_command_wrapper(&ep->endpoint_q, NULL);
1821 USB_BUS_UNLOCK(xfer->xroot->bus);
1824 /*------------------------------------------------------------------------*
1825 * usbd_transfer_pending
1827 * This function will check if an USB transfer is pending which is a
1828 * little bit complicated!
1831 * 1: Pending: The USB transfer will receive a callback in the future.
1832 *------------------------------------------------------------------------*/
1834 usbd_transfer_pending(struct usb_xfer *xfer)
1836 struct usb_xfer_root *info;
1837 struct usb_xfer_queue *pq;
1840 /* transfer is gone */
1844 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1847 if (xfer->flags_int.transferring) {
1851 USB_BUS_LOCK(xfer->xroot->bus);
1852 if (xfer->wait_queue) {
1853 /* we are waiting on a queue somewhere */
1854 USB_BUS_UNLOCK(xfer->xroot->bus);
1860 if (pq->curr == xfer) {
1861 /* we are currently scheduled for callback */
1862 USB_BUS_UNLOCK(xfer->xroot->bus);
1865 /* we are not pending */
1866 USB_BUS_UNLOCK(xfer->xroot->bus);
1870 /*------------------------------------------------------------------------*
1871 * usbd_transfer_drain
1873 * This function will stop the USB transfer and wait for any
1874 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1875 * are loaded into DMA can safely be freed or reused after that this
1876 * function has returned.
1877 *------------------------------------------------------------------------*/
1879 usbd_transfer_drain(struct usb_xfer *xfer)
1882 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1883 "usbd_transfer_drain can sleep!");
1887 /* transfer is gone */
1890 USB_XFER_LOCK_ASSERT_NOTOWNED(xfer);
1891 USB_XFER_LOCK(xfer);
1893 usbd_transfer_stop(xfer);
1895 while (usbd_transfer_pending(xfer) ||
1896 xfer->flags_int.doing_callback) {
1899 * It is allowed that the callback can drop its
1900 * transfer mutex. In that case checking only
1901 * "usbd_transfer_pending()" is not enough to tell if
1902 * the USB transfer is fully drained. We also need to
1903 * check the internal "doing_callback" flag.
1905 xfer->flags_int.draining = 1;
1908 * Wait until the current outstanding USB
1909 * transfer is complete !
1911 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_lock);
1913 USB_XFER_UNLOCK(xfer);
1916 struct usb_page_cache *
1917 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
1919 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1921 return (&xfer->frbuffers[frindex]);
1924 /*------------------------------------------------------------------------*
1925 * usbd_xfer_get_fps_shift
1927 * The following function is only useful for isochronous transfers. It
1928 * returns how many times the frame execution rate has been shifted
1934 *------------------------------------------------------------------------*/
1936 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
1938 return (xfer->fps_shift);
1942 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
1944 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1946 return (xfer->frlengths[frindex]);
1949 /*------------------------------------------------------------------------*
1950 * usbd_xfer_set_frame_data
1952 * This function sets the pointer of the buffer that should
1953 * loaded directly into DMA for the given USB frame. Passing "ptr"
1954 * equal to NULL while the corresponding "frlength" is greater
1955 * than zero gives undefined results!
1956 *------------------------------------------------------------------------*/
1958 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1959 void *ptr, usb_frlength_t len)
1961 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1963 /* set virtual address to load and length */
1964 xfer->frbuffers[frindex].buffer = ptr;
1965 usbd_xfer_set_frame_len(xfer, frindex, len);
1969 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
1970 void **ptr, int *len)
1972 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1975 *ptr = xfer->frbuffers[frindex].buffer;
1977 *len = xfer->frlengths[frindex];
1980 /*------------------------------------------------------------------------*
1981 * usbd_xfer_old_frame_length
1983 * This function returns the framelength of the given frame at the
1984 * time the transfer was submitted. This function can be used to
1985 * compute the starting data pointer of the next isochronous frame
1986 * when an isochronous transfer has completed.
1987 *------------------------------------------------------------------------*/
1989 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
1991 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
1993 return (xfer->frlengths[frindex + xfer->max_frame_count]);
1997 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2001 *actlen = xfer->actlen;
2003 *sumlen = xfer->sumlen;
2004 if (aframes != NULL)
2005 *aframes = xfer->aframes;
2006 if (nframes != NULL)
2007 *nframes = xfer->nframes;
2010 /*------------------------------------------------------------------------*
2011 * usbd_xfer_set_frame_offset
2013 * This function sets the frame data buffer offset relative to the beginning
2014 * of the USB DMA buffer allocated for this USB transfer.
2015 *------------------------------------------------------------------------*/
2017 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2018 usb_frcount_t frindex)
2020 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2021 "when the USB buffer is external\n"));
2022 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2024 /* set virtual address to load */
2025 xfer->frbuffers[frindex].buffer =
2026 USB_ADD_BYTES(xfer->local_buffer, offset);
2030 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2036 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2042 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2048 usbd_xfer_max_frames(struct usb_xfer *xfer)
2050 return (xfer->max_frame_count);
2054 usbd_xfer_max_len(struct usb_xfer *xfer)
2056 return (xfer->max_data_length);
2060 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2062 return (xfer->max_frame_size);
2066 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2069 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2071 xfer->frlengths[frindex] = len;
2074 /*------------------------------------------------------------------------*
2075 * usb_callback_proc - factored out code
2077 * This function performs USB callbacks.
2078 *------------------------------------------------------------------------*/
2080 usb_callback_proc(struct usb_proc_msg *_pm)
2082 struct usb_done_msg *pm = (void *)_pm;
2083 struct usb_xfer_root *info = pm->xroot;
2085 /* Change locking order */
2086 USB_BUS_UNLOCK(info->bus);
2089 * We exploit the fact that the mutex is the same for all
2090 * callbacks that will be called from this thread:
2092 lockmgr(info->xfer_lock, LK_EXCLUSIVE);
2093 USB_BUS_LOCK(info->bus);
2095 /* Continue where we lost track */
2096 usb_command_wrapper(&info->done_q,
2099 lockmgr(info->xfer_lock, LK_RELEASE);
2102 /*------------------------------------------------------------------------*
2103 * usbd_callback_ss_done_defer
2105 * This function will defer the start, stop and done callback to the
2107 *------------------------------------------------------------------------*/
2109 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2111 struct usb_xfer_root *info = xfer->xroot;
2112 struct usb_xfer_queue *pq = &info->done_q;
2114 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2116 if (pq->curr != xfer) {
2117 usbd_transfer_enqueue(pq, xfer);
2119 if (!pq->recurse_1) {
2122 * We have to postpone the callback due to the fact we
2123 * will have a Lock Order Reversal, LOR, if we try to
2126 if (usb_proc_msignal(info->done_p,
2127 &info->done_m[0], &info->done_m[1])) {
2131 /* clear second recurse flag */
2138 /*------------------------------------------------------------------------*
2139 * usbd_callback_wrapper
2141 * This is a wrapper for USB callbacks. This wrapper does some
2142 * auto-magic things like figuring out if we can call the callback
2143 * directly from the current context or if we need to wakeup the
2144 * interrupt process.
2145 *------------------------------------------------------------------------*/
2147 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2149 struct usb_xfer *xfer = pq->curr;
2150 struct usb_xfer_root *info = xfer->xroot;
2152 USB_BUS_LOCK_ASSERT(info->bus);
2153 if (!lockowned(info->xfer_lock)) {
2155 * Cases that end up here:
2157 * 5) HW interrupt done callback or other source.
2159 DPRINTFN(3, "case 5\n");
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])) {
2173 * Cases that end up here:
2175 * 1) We are starting a transfer
2176 * 2) We are prematurely calling back a transfer
2177 * 3) We are stopping a transfer
2178 * 4) We are doing an ordinary callback
2180 DPRINTFN(3, "case 1-4\n");
2181 /* get next USB transfer in the queue */
2182 info->done_q.curr = NULL;
2184 /* set flag in case of drain */
2185 xfer->flags_int.doing_callback = 1;
2187 USB_BUS_UNLOCK(info->bus);
2188 USB_BUS_LOCK_ASSERT_NOTOWNED(info->bus);
2190 /* set correct USB state for callback */
2191 if (!xfer->flags_int.transferring) {
2192 xfer->usb_state = USB_ST_SETUP;
2193 if (!xfer->flags_int.started) {
2194 /* we got stopped before we even got started */
2195 USB_BUS_LOCK(info->bus);
2200 if (usbd_callback_wrapper_sub(xfer)) {
2201 /* the callback has been deferred */
2202 USB_BUS_LOCK(info->bus);
2206 /* decrement power reference */
2207 usbd_transfer_power_ref(xfer, -1);
2209 xfer->flags_int.transferring = 0;
2212 xfer->usb_state = USB_ST_ERROR;
2214 /* set transferred state */
2215 xfer->usb_state = USB_ST_TRANSFERRED;
2217 /* sync DMA memory, if any */
2218 if (xfer->flags_int.bdma_enable &&
2219 (!xfer->flags_int.bdma_no_post_sync)) {
2220 usb_bdma_post_sync(xfer);
2227 if (xfer->usb_state != USB_ST_SETUP)
2228 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2230 USB_XFER_LOCK_ASSERT(xfer);
2231 /* call processing routine */
2232 (xfer->callback) (xfer, xfer->error);
2234 /* pickup the USB mutex again */
2235 USB_BUS_LOCK(info->bus);
2238 * Check if we got started after that we got cancelled, but
2239 * before we managed to do the callback.
2241 if ((!xfer->flags_int.open) &&
2242 (xfer->flags_int.started) &&
2243 (xfer->usb_state == USB_ST_ERROR)) {
2244 /* clear flag in case of drain */
2245 xfer->flags_int.doing_callback = 0;
2246 /* try to loop, but not recursivly */
2247 usb_command_wrapper(&info->done_q, xfer);
2252 /* clear flag in case of drain */
2253 xfer->flags_int.doing_callback = 0;
2256 * Check if we are draining.
2258 if (xfer->flags_int.draining &&
2259 (!xfer->flags_int.transferring)) {
2260 /* "usbd_transfer_drain()" is waiting for end of transfer */
2261 xfer->flags_int.draining = 0;
2262 cv_broadcast(&info->cv_drain);
2265 /* do the next callback, if any */
2266 usb_command_wrapper(&info->done_q,
2270 /*------------------------------------------------------------------------*
2271 * usb_dma_delay_done_cb
2273 * This function is called when the DMA delay has been exectuded, and
2274 * will make sure that the callback is called to complete the USB
2275 * transfer. This code path is ususally only used when there is an USB
2276 * error like USB_ERR_CANCELLED.
2277 *------------------------------------------------------------------------*/
2279 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2281 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2283 DPRINTFN(3, "Completed %p\n", xfer);
2285 /* queue callback for execution, again */
2286 usbd_transfer_done(xfer, 0);
2289 /*------------------------------------------------------------------------*
2290 * usbd_transfer_dequeue
2292 * - This function is used to remove an USB transfer from a USB
2295 * - This function can be called multiple times in a row.
2296 *------------------------------------------------------------------------*/
2298 usbd_transfer_dequeue(struct usb_xfer *xfer)
2300 struct usb_xfer_queue *pq;
2302 pq = xfer->wait_queue;
2304 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2305 xfer->wait_queue = NULL;
2309 /*------------------------------------------------------------------------*
2310 * usbd_transfer_enqueue
2312 * - This function is used to insert an USB transfer into a USB *
2315 * - This function can be called multiple times in a row.
2316 *------------------------------------------------------------------------*/
2318 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2321 * Insert the USB transfer into the queue, if it is not
2322 * already on a USB transfer queue:
2324 if (xfer->wait_queue == NULL) {
2325 xfer->wait_queue = pq;
2326 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2330 /*------------------------------------------------------------------------*
2331 * usbd_transfer_done
2333 * - This function is used to remove an USB transfer from the busdma,
2334 * pipe or interrupt queue.
2336 * - This function is used to queue the USB transfer on the done
2339 * - This function is used to stop any USB transfer timeouts.
2340 *------------------------------------------------------------------------*/
2342 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2344 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2346 DPRINTF("err=%s\n", usbd_errstr(error));
2349 * If we are not transferring then just return.
2350 * This can happen during transfer cancel.
2352 if (!xfer->flags_int.transferring) {
2353 DPRINTF("not transferring\n");
2354 /* end of control transfer, if any */
2355 xfer->flags_int.control_act = 0;
2358 /* only set transfer error if not already set */
2360 xfer->error = error;
2362 /* stop any callouts */
2363 usb_callout_stop(&xfer->timeout_handle);
2366 * If we are waiting on a queue, just remove the USB transfer
2367 * from the queue, if any. We should have the required locks
2368 * locked to do the remove when this function is called.
2370 usbd_transfer_dequeue(xfer);
2373 if (lockowned(xfer->xroot->xfer_lock)) {
2374 struct usb_xfer_queue *pq;
2377 * If the private USB lock is not locked, then we assume
2378 * that the BUS-DMA load stage has been passed:
2380 pq = &xfer->xroot->dma_q;
2382 if (pq->curr == xfer) {
2383 /* start the next BUS-DMA load, if any */
2384 usb_command_wrapper(pq, NULL);
2388 /* keep some statistics */
2390 xfer->xroot->bus->stats_err.uds_requests
2391 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2393 xfer->xroot->bus->stats_ok.uds_requests
2394 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2397 /* call the USB transfer callback */
2398 usbd_callback_ss_done_defer(xfer);
2401 /*------------------------------------------------------------------------*
2402 * usbd_transfer_start_cb
2404 * This function is called to start the USB transfer when
2405 * "xfer->interval" is greater than zero, and and the endpoint type is
2407 *------------------------------------------------------------------------*/
2409 usbd_transfer_start_cb(void *arg)
2411 struct usb_xfer *xfer = arg;
2412 struct usb_endpoint *ep = xfer->endpoint;
2414 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2419 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2421 /* start USB transfer, if no error */
2422 if (xfer->error == 0)
2423 (ep->methods->start) (xfer);
2425 xfer->flags_int.can_cancel_immed = 1;
2427 /* check for error */
2429 /* some error has happened */
2430 usbd_transfer_done(xfer, 0);
2434 /*------------------------------------------------------------------------*
2435 * usbd_xfer_set_stall
2437 * This function is used to set the stall flag outside the
2438 * callback. This function is NULL safe.
2439 *------------------------------------------------------------------------*/
2441 usbd_xfer_set_stall(struct usb_xfer *xfer)
2447 USB_XFER_LOCK_ASSERT(xfer);
2449 /* avoid any races by locking the USB mutex */
2450 USB_BUS_LOCK(xfer->xroot->bus);
2451 xfer->flags.stall_pipe = 1;
2452 USB_BUS_UNLOCK(xfer->xroot->bus);
2456 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2458 return (xfer->endpoint->is_stalled);
2461 /*------------------------------------------------------------------------*
2462 * usbd_transfer_clear_stall
2464 * This function is used to clear the stall flag outside the
2465 * callback. This function is NULL safe.
2466 *------------------------------------------------------------------------*/
2468 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2474 USB_XFER_LOCK_ASSERT(xfer);
2476 /* avoid any races by locking the USB mutex */
2477 USB_BUS_LOCK(xfer->xroot->bus);
2479 xfer->flags.stall_pipe = 0;
2481 USB_BUS_UNLOCK(xfer->xroot->bus);
2484 /*------------------------------------------------------------------------*
2487 * This function is used to add an USB transfer to the pipe transfer list.
2488 *------------------------------------------------------------------------*/
2490 usbd_pipe_start(struct usb_xfer_queue *pq)
2492 struct usb_endpoint *ep;
2493 struct usb_xfer *xfer;
2497 ep = xfer->endpoint;
2499 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2502 * If the endpoint is already stalled we do nothing !
2504 if (ep->is_stalled) {
2508 * Check if we are supposed to stall the endpoint:
2510 if (xfer->flags.stall_pipe) {
2511 struct usb_device *udev;
2512 struct usb_xfer_root *info;
2514 /* clear stall command */
2515 xfer->flags.stall_pipe = 0;
2517 /* get pointer to USB device */
2522 * Only stall BULK and INTERRUPT endpoints.
2524 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2525 if ((type == UE_BULK) ||
2526 (type == UE_INTERRUPT)) {
2531 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2532 (udev->bus->methods->set_stall) (
2533 udev, NULL, ep, &did_stall);
2534 } else if (udev->ctrl_xfer[1]) {
2535 info = udev->ctrl_xfer[1]->xroot;
2537 &info->bus->non_giant_callback_proc,
2538 &udev->cs_msg[0], &udev->cs_msg[1]);
2540 /* should not happen */
2541 DPRINTFN(0, "No stall handler\n");
2544 * Check if we should stall. Some USB hardware
2545 * handles set- and clear-stall in hardware.
2549 * The transfer will be continued when
2550 * the clear-stall control endpoint
2551 * message is received.
2556 } else if (type == UE_ISOCHRONOUS) {
2559 * Make sure any FIFO overflow or other FIFO
2560 * error conditions go away by resetting the
2561 * endpoint FIFO through the clear stall
2564 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2565 (udev->bus->methods->clear_stall) (udev, ep);
2569 /* Set or clear stall complete - special case */
2570 if (xfer->nframes == 0) {
2571 /* we are complete */
2573 usbd_transfer_done(xfer, 0);
2579 * 1) Start the first transfer queued.
2581 * 2) Re-start the current USB transfer.
2584 * Check if there should be any
2585 * pre transfer start delay:
2587 if (xfer->interval > 0) {
2588 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2589 if ((type == UE_BULK) ||
2590 (type == UE_CONTROL)) {
2591 usbd_transfer_timeout_ms(xfer,
2592 &usbd_transfer_start_cb,
2600 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2602 /* start USB transfer, if no error */
2603 if (xfer->error == 0)
2604 (ep->methods->start) (xfer);
2606 xfer->flags_int.can_cancel_immed = 1;
2608 /* check for error */
2610 /* some error has happened */
2611 usbd_transfer_done(xfer, 0);
2615 /*------------------------------------------------------------------------*
2616 * usbd_transfer_timeout_ms
2618 * This function is used to setup a timeout on the given USB
2619 * transfer. If the timeout has been deferred the callback given by
2620 * "cb" will get called after "ms" milliseconds.
2621 *------------------------------------------------------------------------*/
2623 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2624 void (*cb) (void *arg), usb_timeout_t ms)
2626 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2629 usb_callout_reset(&xfer->timeout_handle,
2630 USB_MS_TO_TICKS(ms), cb, xfer);
2633 /*------------------------------------------------------------------------*
2634 * usbd_callback_wrapper_sub
2636 * - This function will update variables in an USB transfer after
2637 * that the USB transfer is complete.
2639 * - This function is used to start the next USB transfer on the
2640 * ep transfer queue, if any.
2642 * NOTE: In some special cases the USB transfer will not be removed from
2643 * the pipe queue, but remain first. To enforce USB transfer removal call
2644 * this function passing the error code "USB_ERR_CANCELLED".
2648 * Else: The callback has been deferred.
2649 *------------------------------------------------------------------------*/
2651 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2653 struct usb_endpoint *ep;
2654 struct usb_bus *bus;
2657 bus = xfer->xroot->bus;
2659 if ((!xfer->flags_int.open) &&
2660 (!xfer->flags_int.did_close)) {
2663 (xfer->endpoint->methods->close) (xfer);
2664 USB_BUS_UNLOCK(bus);
2665 /* only close once */
2666 xfer->flags_int.did_close = 1;
2667 return (1); /* wait for new callback */
2670 * If we have a non-hardware induced error we
2671 * need to do the DMA delay!
2673 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2674 (xfer->error == USB_ERR_CANCELLED ||
2675 xfer->error == USB_ERR_TIMEOUT ||
2676 bus->methods->start_dma_delay != NULL)) {
2680 /* only delay once */
2681 xfer->flags_int.did_dma_delay = 1;
2683 /* we can not cancel this delay */
2684 xfer->flags_int.can_cancel_immed = 0;
2686 temp = usbd_get_dma_delay(xfer->xroot->udev);
2688 DPRINTFN(3, "DMA delay, %u ms, "
2689 "on %p\n", temp, xfer);
2694 * Some hardware solutions have dedicated
2695 * events when it is safe to free DMA'ed
2696 * memory. For the other hardware platforms we
2697 * use a static delay.
2699 if (bus->methods->start_dma_delay != NULL) {
2700 (bus->methods->start_dma_delay) (xfer);
2702 usbd_transfer_timeout_ms(xfer,
2703 (void *)&usb_dma_delay_done_cb, temp);
2705 USB_BUS_UNLOCK(bus);
2706 return (1); /* wait for new callback */
2709 /* check actual number of frames */
2710 if (xfer->aframes > xfer->nframes) {
2711 if (xfer->error == 0) {
2712 panic("%s: actual number of frames, %d, is "
2713 "greater than initial number of frames, %d\n",
2714 __FUNCTION__, xfer->aframes, xfer->nframes);
2716 /* just set some valid value */
2717 xfer->aframes = xfer->nframes;
2720 /* compute actual length */
2723 for (x = 0; x != xfer->aframes; x++) {
2724 xfer->actlen += xfer->frlengths[x];
2728 * Frames that were not transferred get zero actual length in
2729 * case the USB device driver does not check the actual number
2730 * of frames transferred, "xfer->aframes":
2732 for (; x < xfer->nframes; x++) {
2733 usbd_xfer_set_frame_len(xfer, x, 0);
2736 /* check actual length */
2737 if (xfer->actlen > xfer->sumlen) {
2738 if (xfer->error == 0) {
2739 panic("%s: actual length, %d, is greater than "
2740 "initial length, %d\n",
2741 __FUNCTION__, xfer->actlen, xfer->sumlen);
2743 /* just set some valid value */
2744 xfer->actlen = xfer->sumlen;
2747 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2748 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2749 xfer->aframes, xfer->nframes);
2752 /* end of control transfer, if any */
2753 xfer->flags_int.control_act = 0;
2755 /* check if we should block the execution queue */
2756 if ((xfer->error != USB_ERR_CANCELLED) &&
2757 (xfer->flags.pipe_bof)) {
2758 DPRINTFN(2, "xfer=%p: Block On Failure "
2759 "on endpoint=%p\n", xfer, xfer->endpoint);
2763 /* check for short transfers */
2764 if (xfer->actlen < xfer->sumlen) {
2766 /* end of control transfer, if any */
2767 xfer->flags_int.control_act = 0;
2769 if (!xfer->flags_int.short_xfer_ok) {
2770 xfer->error = USB_ERR_SHORT_XFER;
2771 if (xfer->flags.pipe_bof) {
2772 DPRINTFN(2, "xfer=%p: Block On Failure on "
2773 "Short Transfer on endpoint %p.\n",
2774 xfer, xfer->endpoint);
2780 * Check if we are in the middle of a
2783 if (xfer->flags_int.control_act) {
2784 DPRINTFN(5, "xfer=%p: Control transfer "
2785 "active on endpoint=%p\n", xfer, xfer->endpoint);
2791 ep = xfer->endpoint;
2794 * If the current USB transfer is completing we need to start the
2798 if (ep->endpoint_q.curr == xfer) {
2799 usb_command_wrapper(&ep->endpoint_q, NULL);
2801 if (ep->endpoint_q.curr || TAILQ_FIRST(&ep->endpoint_q.head)) {
2802 /* there is another USB transfer waiting */
2804 /* this is the last USB transfer */
2805 /* clear isochronous sync flag */
2806 xfer->endpoint->is_synced = 0;
2809 USB_BUS_UNLOCK(bus);
2814 /*------------------------------------------------------------------------*
2815 * usb_command_wrapper
2817 * This function is used to execute commands non-recursivly on an USB
2819 *------------------------------------------------------------------------*/
2821 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2825 * If the transfer is not already processing,
2828 if (pq->curr != xfer) {
2829 usbd_transfer_enqueue(pq, xfer);
2830 if (pq->curr != NULL) {
2831 /* something is already processing */
2832 DPRINTFN(6, "busy %p\n", pq->curr);
2837 /* Get next element in queue */
2841 if (!pq->recurse_1) {
2845 /* set both recurse flags */
2849 if (pq->curr == NULL) {
2850 xfer = TAILQ_FIRST(&pq->head);
2852 TAILQ_REMOVE(&pq->head, xfer,
2854 xfer->wait_queue = NULL;
2860 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2862 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2864 } while (!pq->recurse_2);
2866 /* clear first recurse flag */
2870 /* clear second recurse flag */
2875 /*------------------------------------------------------------------------*
2876 * usbd_ctrl_transfer_setup
2878 * This function is used to setup the default USB control endpoint
2880 *------------------------------------------------------------------------*/
2882 usbd_ctrl_transfer_setup(struct usb_device *udev)
2884 struct usb_xfer *xfer;
2886 uint8_t iface_index;
2888 /* check for root HUB */
2889 if (udev->parent_hub == NULL)
2893 xfer = udev->ctrl_xfer[0];
2895 USB_XFER_LOCK(xfer);
2897 ((xfer->address == udev->address) &&
2898 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
2899 udev->ddesc.bMaxPacketSize));
2900 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2903 * NOTE: checking "xfer->address" and
2904 * starting the USB transfer must be
2907 usbd_transfer_start(xfer);
2910 USB_XFER_UNLOCK(xfer);
2917 * All parameters are exactly the same like before.
2923 * Update wMaxPacketSize for the default control endpoint:
2925 udev->ctrl_ep_desc.wMaxPacketSize[0] =
2926 udev->ddesc.bMaxPacketSize;
2929 * Unsetup any existing USB transfer:
2931 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
2934 * Reset clear stall error counter.
2936 udev->clear_stall_errors = 0;
2939 * Try to setup a new USB transfer for the
2940 * default control endpoint:
2943 if (usbd_transfer_setup(udev, &iface_index,
2944 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
2945 &udev->device_lock)) {
2946 DPRINTFN(0, "could not setup default "
2953 /*------------------------------------------------------------------------*
2954 * usbd_clear_data_toggle - factored out code
2956 * NOTE: the intention of this function is not to reset the hardware
2958 *------------------------------------------------------------------------*/
2960 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
2962 USB_BUS_LOCK_ASSERT(udev->bus);
2964 /* check that we have a valid case */
2965 if (udev->flags.usb_mode == USB_MODE_HOST &&
2966 udev->parent_hub != NULL &&
2967 udev->bus->methods->clear_stall != NULL &&
2968 ep->methods != NULL) {
2969 (udev->bus->methods->clear_stall) (udev, ep);
2973 /*------------------------------------------------------------------------*
2974 * usbd_clear_data_toggle - factored out code
2976 * NOTE: the intention of this function is not to reset the hardware
2977 * data toggle on the USB device side.
2978 *------------------------------------------------------------------------*/
2980 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
2982 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
2984 USB_BUS_LOCK(udev->bus);
2985 ep->toggle_next = 0;
2986 /* some hardware needs a callback to clear the data toggle */
2987 usbd_clear_stall_locked(udev, ep);
2988 USB_BUS_UNLOCK(udev->bus);
2991 /*------------------------------------------------------------------------*
2992 * usbd_clear_stall_callback - factored out clear stall callback
2995 * xfer1: Clear Stall Control Transfer
2996 * xfer2: Stalled USB Transfer
2998 * This function is NULL safe.
3004 * Clear stall config example:
3006 * static const struct usb_config my_clearstall = {
3007 * .type = UE_CONTROL,
3009 * .direction = UE_DIR_ANY,
3010 * .interval = 50, //50 milliseconds
3011 * .bufsize = sizeof(struct usb_device_request),
3012 * .timeout = 1000, //1.000 seconds
3013 * .callback = &my_clear_stall_callback, // **
3014 * .usb_mode = USB_MODE_HOST,
3017 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3018 * passing the correct parameters.
3019 *------------------------------------------------------------------------*/
3021 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3022 struct usb_xfer *xfer2)
3024 struct usb_device_request req;
3026 if (xfer2 == NULL) {
3027 /* looks like we are tearing down */
3028 DPRINTF("NULL input parameter\n");
3031 USB_XFER_LOCK_ASSERT(xfer1);
3032 USB_XFER_LOCK_ASSERT(xfer2);
3034 switch (USB_GET_STATE(xfer1)) {
3038 * pre-clear the data toggle to DATA0 ("umass.c" and
3039 * "ata-usb.c" depends on this)
3042 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3044 /* setup a clear-stall packet */
3046 req.bmRequestType = UT_WRITE_ENDPOINT;
3047 req.bRequest = UR_CLEAR_FEATURE;
3048 USETW(req.wValue, UF_ENDPOINT_HALT);
3049 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3051 USETW(req.wLength, 0);
3054 * "usbd_transfer_setup_sub()" will ensure that
3055 * we have sufficient room in the buffer for
3056 * the request structure!
3059 /* copy in the transfer */
3061 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3064 xfer1->frlengths[0] = sizeof(req);
3067 usbd_transfer_submit(xfer1);
3070 case USB_ST_TRANSFERRED:
3073 default: /* Error */
3074 if (xfer1->error == USB_ERR_CANCELLED) {
3079 return (1); /* Clear Stall Finished */
3082 /*------------------------------------------------------------------------*
3083 * usbd_transfer_poll
3085 * The following function gets called from the USB keyboard driver and
3086 * UMASS when the system has paniced.
3088 * NOTE: It is currently not possible to resume normal operation on
3089 * the USB controller which has been polled, due to clearing of the
3090 * "up_dsleep" and "up_msleep" flags.
3091 *------------------------------------------------------------------------*/
3093 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3095 struct usb_xfer *xfer;
3096 struct usb_xfer_root *xroot;
3097 struct usb_device *udev;
3098 struct usb_proc_msg *pm;
3103 for (n = 0; n != max; n++) {
3104 /* Extra checks to avoid panic */
3107 continue; /* no USB transfer */
3108 xroot = xfer->xroot;
3110 continue; /* no USB root */
3113 continue; /* no USB device */
3114 if (udev->bus == NULL)
3115 continue; /* no BUS structure */
3116 if (udev->bus->methods == NULL)
3117 continue; /* no BUS methods */
3118 if (udev->bus->methods->xfer_poll == NULL)
3119 continue; /* no poll method */
3121 /* make sure that the BUS mutex is not locked */
3123 while (lockowned(&xroot->udev->bus->bus_lock)) {
3124 lockmgr(&xroot->udev->bus->bus_lock, LK_RELEASE);
3128 /* make sure that the transfer mutex is not locked */
3130 while (lockowned(xroot->xfer_lock)) {
3131 lockmgr(xroot->xfer_lock, LK_RELEASE);
3135 /* Make sure cv_signal() and cv_broadcast() is not called */
3136 udev->bus->control_xfer_proc.up_msleep = 0;
3137 udev->bus->explore_proc.up_msleep = 0;
3138 udev->bus->giant_callback_proc.up_msleep = 0;
3139 udev->bus->non_giant_callback_proc.up_msleep = 0;
3141 /* poll USB hardware */
3142 (udev->bus->methods->xfer_poll) (udev->bus);
3144 USB_BUS_LOCK(xroot->bus);
3146 /* check for clear stall */
3147 if (udev->ctrl_xfer[1] != NULL) {
3149 /* poll clear stall start */
3150 pm = &udev->cs_msg[0].hdr;
3151 (pm->pm_callback) (pm);
3152 /* poll clear stall done thread */
3153 pm = &udev->ctrl_xfer[1]->
3154 xroot->done_m[0].hdr;
3155 (pm->pm_callback) (pm);
3158 /* poll done thread */
3159 pm = &xroot->done_m[0].hdr;
3160 (pm->pm_callback) (pm);
3162 USB_BUS_UNLOCK(xroot->bus);
3164 /* restore transfer mutex */
3166 lockmgr(xroot->xfer_lock, LK_EXCLUSIVE);
3168 /* restore BUS mutex */
3170 lockmgr(&xroot->udev->bus->bus_lock, LK_EXCLUSIVE);
3175 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3176 uint8_t type, enum usb_dev_speed speed)
3178 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3179 [USB_SPEED_LOW] = 8,
3180 [USB_SPEED_FULL] = 64,
3181 [USB_SPEED_HIGH] = 1024,
3182 [USB_SPEED_VARIABLE] = 1024,
3183 [USB_SPEED_SUPER] = 1024,
3186 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3187 [USB_SPEED_LOW] = 0, /* invalid */
3188 [USB_SPEED_FULL] = 1023,
3189 [USB_SPEED_HIGH] = 1024,
3190 [USB_SPEED_VARIABLE] = 3584,
3191 [USB_SPEED_SUPER] = 1024,
3194 static const uint16_t control_min[USB_SPEED_MAX] = {
3195 [USB_SPEED_LOW] = 8,
3196 [USB_SPEED_FULL] = 8,
3197 [USB_SPEED_HIGH] = 64,
3198 [USB_SPEED_VARIABLE] = 512,
3199 [USB_SPEED_SUPER] = 512,
3202 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3203 [USB_SPEED_LOW] = 8,
3204 [USB_SPEED_FULL] = 8,
3205 [USB_SPEED_HIGH] = 512,
3206 [USB_SPEED_VARIABLE] = 512,
3207 [USB_SPEED_SUPER] = 1024,
3212 memset(ptr, 0, sizeof(*ptr));
3216 ptr->range.max = intr_range_max[speed];
3218 case UE_ISOCHRONOUS:
3219 ptr->range.max = isoc_range_max[speed];
3222 if (type == UE_BULK)
3223 temp = bulk_min[speed];
3224 else /* UE_CONTROL */
3225 temp = control_min[speed];
3227 /* default is fixed */
3228 ptr->fixed[0] = temp;
3229 ptr->fixed[1] = temp;
3230 ptr->fixed[2] = temp;
3231 ptr->fixed[3] = temp;
3233 if (speed == USB_SPEED_FULL) {
3234 /* multiple sizes */
3239 if ((speed == USB_SPEED_VARIABLE) &&
3240 (type == UE_BULK)) {
3241 /* multiple sizes */
3242 ptr->fixed[2] = 1024;
3243 ptr->fixed[3] = 1536;
3250 usbd_xfer_softc(struct usb_xfer *xfer)
3252 return (xfer->priv_sc);
3256 usbd_xfer_get_priv(struct usb_xfer *xfer)
3258 return (xfer->priv_fifo);
3262 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3264 xfer->priv_fifo = ptr;
3268 usbd_xfer_state(struct usb_xfer *xfer)
3270 return (xfer->usb_state);
3274 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3277 case USB_FORCE_SHORT_XFER:
3278 xfer->flags.force_short_xfer = 1;
3280 case USB_SHORT_XFER_OK:
3281 xfer->flags.short_xfer_ok = 1;
3283 case USB_MULTI_SHORT_OK:
3284 xfer->flags.short_frames_ok = 1;
3286 case USB_MANUAL_STATUS:
3287 xfer->flags.manual_status = 1;
3293 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3296 case USB_FORCE_SHORT_XFER:
3297 xfer->flags.force_short_xfer = 0;
3299 case USB_SHORT_XFER_OK:
3300 xfer->flags.short_xfer_ok = 0;
3302 case USB_MULTI_SHORT_OK:
3303 xfer->flags.short_frames_ok = 0;
3305 case USB_MANUAL_STATUS:
3306 xfer->flags.manual_status = 0;
3312 * The following function returns in milliseconds when the isochronous
3313 * transfer was completed by the hardware. The returned value wraps
3314 * around 65536 milliseconds.
3317 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3319 return (xfer->isoc_time_complete);