1 /* $FreeBSD: head/sys/dev/usb/usb_transfer.c 276717 2015-01-05 20:22:18Z hselasky $ */
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/param.h>
29 #include <sys/queue.h>
30 #include <sys/types.h>
31 #include <sys/systm.h>
32 #include <sys/kernel.h>
34 #include <sys/thread.h>
35 #include <sys/module.h>
37 #include <sys/mutex.h>
38 #include <sys/condvar.h>
39 #include <sys/sysctl.h>
40 #include <sys/unistd.h>
41 #include <sys/callout.h>
42 #include <sys/malloc.h>
46 #include <sys/thread2.h>
48 #include <bus/u4b/usb.h>
49 #include <bus/u4b/usbdi.h>
50 #include <bus/u4b/usbdi_util.h>
52 #define USB_DEBUG_VAR usb_debug
54 #include <bus/u4b/usb_core.h>
55 #include <bus/u4b/usb_busdma.h>
56 #include <bus/u4b/usb_process.h>
57 #include <bus/u4b/usb_transfer.h>
58 #include <bus/u4b/usb_device.h>
59 #include <bus/u4b/usb_debug.h>
60 #include <bus/u4b/usb_util.h>
62 #include <bus/u4b/usb_controller.h>
63 #include <bus/u4b/usb_bus.h>
64 #include <bus/u4b/usb_pf.h>
66 struct usb_std_packet_size {
68 uint16_t min; /* inclusive */
69 uint16_t max; /* inclusive */
75 static usb_callback_t usb_request_callback;
77 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
79 /* This transfer is used for generic control endpoint transfers */
83 .endpoint = 0x00, /* Control endpoint */
84 .direction = UE_DIR_ANY,
85 .bufsize = USB_EP0_BUFSIZE, /* bytes */
86 .flags = {.proxy_buffer = 1,},
87 .callback = &usb_request_callback,
88 .usb_mode = USB_MODE_DUAL, /* both modes */
91 /* This transfer is used for generic clear stall only */
95 .endpoint = 0x00, /* Control pipe */
96 .direction = UE_DIR_ANY,
97 .bufsize = sizeof(struct usb_device_request),
98 .callback = &usb_do_clear_stall_callback,
99 .timeout = 1000, /* 1 second */
100 .interval = 50, /* 50ms */
101 .usb_mode = USB_MODE_HOST,
105 /* function prototypes */
107 static void usbd_update_max_frame_size(struct usb_xfer *);
108 static void usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
109 static void usbd_delayed_free(void *data, struct malloc_type *mtype);
110 static void usbd_control_transfer_init(struct usb_xfer *);
111 static int usbd_setup_ctrl_transfer(struct usb_xfer *);
112 static void usb_callback_proc(struct usb_proc_msg *);
113 static void usbd_callback_ss_done_defer(struct usb_xfer *);
114 static void usbd_callback_wrapper(struct usb_xfer_queue *);
115 static void usbd_transfer_start_cb(void *);
116 static uint8_t usbd_callback_wrapper_sub(struct usb_xfer *);
117 static void usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
118 uint8_t type, enum usb_dev_speed speed);
120 /*------------------------------------------------------------------------*
121 * usb_request_callback
122 *------------------------------------------------------------------------*/
124 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
126 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
127 usb_handle_request_callback(xfer, error);
129 usbd_do_request_callback(xfer, error);
132 /*------------------------------------------------------------------------*
133 * usbd_update_max_frame_size
135 * This function updates the maximum frame size, hence high speed USB
136 * can transfer multiple consecutive packets.
137 *------------------------------------------------------------------------*/
139 usbd_update_max_frame_size(struct usb_xfer *xfer)
141 /* compute maximum frame size */
142 /* this computation should not overflow 16-bit */
143 /* max = 15 * 1024 */
145 xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
148 /*------------------------------------------------------------------------*
151 * The following function is called when we need to
152 * synchronize with DMA hardware.
155 * 0: no DMA delay required
156 * Else: milliseconds of DMA delay
157 *------------------------------------------------------------------------*/
159 usbd_get_dma_delay(struct usb_device *udev)
161 const struct usb_bus_methods *mtod;
164 mtod = udev->bus->methods;
167 if (mtod->get_dma_delay) {
168 (mtod->get_dma_delay) (udev, &temp);
170 * Round up and convert to milliseconds. Note that we use
171 * 1024 milliseconds per second. to save a division.
179 /*------------------------------------------------------------------------*
180 * usbd_transfer_setup_sub_malloc
182 * This function will allocate one or more DMA'able memory chunks
183 * according to "size", "align" and "count" arguments. "ppc" is
184 * pointed to a linear array of USB page caches afterwards.
186 * If the "align" argument is equal to "1" a non-contiguous allocation
187 * can happen. Else if the "align" argument is greater than "1", the
188 * allocation will always be contiguous in memory.
193 *------------------------------------------------------------------------*/
196 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
197 struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
200 struct usb_page_cache *pc;
211 USB_ASSERT(align > 0, ("Invalid alignment, 0x%08x\n",
213 USB_ASSERT(size > 0, ("Invalid size = 0\n"));
216 return (0); /* nothing to allocate */
219 * Make sure that the size is aligned properly.
221 size = -((-size) & (-align));
224 * Try multi-allocation chunks to reduce the number of DMA
225 * allocations, hence DMA allocations are slow.
228 /* special case - non-cached multi page DMA memory */
230 n_dma_pg = (2 + (size / USB_PAGE_SIZE));
232 } else if (size >= USB_PAGE_SIZE) {
237 /* compute number of objects per page */
238 n_obj = (USB_PAGE_SIZE / size);
240 * Compute number of DMA chunks, rounded up
243 n_dma_pc = ((count + n_obj - 1) / n_obj);
248 * DMA memory is allocated once, but mapped twice. That's why
249 * there is one list for auto-free and another list for
250 * non-auto-free which only holds the mapping and not the
253 if (parm->buf == NULL) {
254 /* reserve memory (auto-free) */
255 parm->dma_page_ptr += n_dma_pc * n_dma_pg;
256 parm->dma_page_cache_ptr += n_dma_pc;
258 /* reserve memory (no-auto-free) */
259 parm->dma_page_ptr += count * n_dma_pg;
260 parm->xfer_page_cache_ptr += count;
263 for (x = 0; x != n_dma_pc; x++) {
264 /* need to initialize the page cache */
265 parm->dma_page_cache_ptr[x].tag_parent =
266 &parm->curr_xfer->xroot->dma_parent_tag;
268 for (x = 0; x != count; x++) {
269 /* need to initialize the page cache */
270 parm->xfer_page_cache_ptr[x].tag_parent =
271 &parm->curr_xfer->xroot->dma_parent_tag;
275 *ppc = parm->xfer_page_cache_ptr;
277 r = count; /* set remainder count */
278 z = n_obj * size; /* set allocation size */
279 pc = parm->xfer_page_cache_ptr;
280 pg = parm->dma_page_ptr;
282 for (x = 0; x != n_dma_pc; x++) {
285 /* compute last remainder */
289 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
291 return (1); /* failure */
293 /* Set beginning of current buffer */
294 buf = parm->dma_page_cache_ptr->buffer;
295 /* Make room for one DMA page cache and one page */
296 parm->dma_page_cache_ptr++;
299 for (y = 0; (y != n_obj); y++, r--, pc++, pg += n_dma_pg) {
301 /* Load sub-chunk into DMA */
302 if (usb_pc_dmamap_create(pc, size)) {
303 return (1); /* failure */
305 pc->buffer = USB_ADD_BYTES(buf, y * size);
308 lockmgr(pc->tag_parent->lock, LK_EXCLUSIVE);
309 if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
310 lockmgr(pc->tag_parent->lock, LK_RELEASE);
311 return (1); /* failure */
313 lockmgr(pc->tag_parent->lock, LK_RELEASE);
317 parm->xfer_page_cache_ptr = pc;
318 parm->dma_page_ptr = pg;
323 /*------------------------------------------------------------------------*
324 * usbd_transfer_setup_sub - transfer setup subroutine
326 * This function must be called from the "xfer_setup" callback of the
327 * USB Host or Device controller driver when setting up an USB
328 * transfer. This function will setup correct packet sizes, buffer
329 * sizes, flags and more, that are stored in the "usb_xfer"
331 *------------------------------------------------------------------------*/
333 usbd_transfer_setup_sub(struct usb_setup_params *parm)
339 struct usb_xfer *xfer = parm->curr_xfer;
340 const struct usb_config *setup = parm->curr_setup;
341 struct usb_endpoint_ss_comp_descriptor *ecomp;
342 struct usb_endpoint_descriptor *edesc;
343 struct usb_std_packet_size std_size;
344 usb_frcount_t n_frlengths;
345 usb_frcount_t n_frbuffers;
352 * Sanity check. The following parameters must be initialized before
353 * calling this function.
355 if ((parm->hc_max_packet_size == 0) ||
356 (parm->hc_max_packet_count == 0) ||
357 (parm->hc_max_frame_size == 0)) {
358 parm->err = USB_ERR_INVAL;
361 edesc = xfer->endpoint->edesc;
362 ecomp = xfer->endpoint->ecomp;
364 type = (edesc->bmAttributes & UE_XFERTYPE);
366 xfer->flags = setup->flags;
367 xfer->nframes = setup->frames;
368 xfer->timeout = setup->timeout;
369 xfer->callback = setup->callback;
370 xfer->interval = setup->interval;
371 xfer->endpointno = edesc->bEndpointAddress;
372 xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
373 xfer->max_packet_count = 1;
374 /* make a shadow copy: */
375 xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
377 parm->bufsize = setup->bufsize;
379 switch (parm->speed) {
384 xfer->max_packet_count +=
385 (xfer->max_packet_size >> 11) & 3;
387 /* check for invalid max packet count */
388 if (xfer->max_packet_count > 3)
389 xfer->max_packet_count = 3;
394 xfer->max_packet_size &= 0x7FF;
396 case USB_SPEED_SUPER:
397 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
400 xfer->max_packet_count += ecomp->bMaxBurst;
402 if ((xfer->max_packet_count == 0) ||
403 (xfer->max_packet_count > 16))
404 xfer->max_packet_count = 16;
408 xfer->max_packet_count = 1;
414 mult = UE_GET_SS_ISO_MULT(
415 ecomp->bmAttributes) + 1;
419 xfer->max_packet_count *= mult;
425 xfer->max_packet_size &= 0x7FF;
430 /* range check "max_packet_count" */
432 if (xfer->max_packet_count > parm->hc_max_packet_count) {
433 xfer->max_packet_count = parm->hc_max_packet_count;
436 /* store max packet size value before filtering */
438 maxp_old = xfer->max_packet_size;
440 /* filter "wMaxPacketSize" according to HC capabilities */
442 if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
443 (xfer->max_packet_size == 0)) {
444 xfer->max_packet_size = parm->hc_max_packet_size;
446 /* filter "wMaxPacketSize" according to standard sizes */
448 usbd_get_std_packet_size(&std_size, type, parm->speed);
450 if (std_size.range.min || std_size.range.max) {
452 if (xfer->max_packet_size < std_size.range.min) {
453 xfer->max_packet_size = std_size.range.min;
455 if (xfer->max_packet_size > std_size.range.max) {
456 xfer->max_packet_size = std_size.range.max;
460 if (xfer->max_packet_size >= std_size.fixed[3]) {
461 xfer->max_packet_size = std_size.fixed[3];
462 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
463 xfer->max_packet_size = std_size.fixed[2];
464 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
465 xfer->max_packet_size = std_size.fixed[1];
467 /* only one possibility left */
468 xfer->max_packet_size = std_size.fixed[0];
473 * Check if the max packet size was outside its allowed range
474 * and clamped to a valid value:
476 if (maxp_old != xfer->max_packet_size)
477 xfer->flags_int.maxp_was_clamped = 1;
479 /* compute "max_frame_size" */
481 usbd_update_max_frame_size(xfer);
483 /* check interrupt interval and transfer pre-delay */
485 if (type == UE_ISOCHRONOUS) {
487 uint16_t frame_limit;
489 xfer->interval = 0; /* not used, must be zero */
490 xfer->flags_int.isochronous_xfr = 1; /* set flag */
492 if (xfer->timeout == 0) {
494 * set a default timeout in
495 * case something goes wrong!
497 xfer->timeout = 1000 / 4;
499 switch (parm->speed) {
502 frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
506 frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
507 xfer->fps_shift = edesc->bInterval;
508 if (xfer->fps_shift > 0)
510 if (xfer->fps_shift > 3)
512 if (xfer->flags.pre_scale_frames != 0)
513 xfer->nframes <<= (3 - xfer->fps_shift);
517 if (xfer->nframes > frame_limit) {
519 * this is not going to work
522 parm->err = USB_ERR_INVAL;
525 if (xfer->nframes == 0) {
527 * this is not a valid value
529 parm->err = USB_ERR_ZERO_NFRAMES;
535 * If a value is specified use that else check the
536 * endpoint descriptor!
538 if (type == UE_INTERRUPT) {
542 if (xfer->interval == 0) {
544 xfer->interval = edesc->bInterval;
546 switch (parm->speed) {
552 if (xfer->interval < 4)
554 else if (xfer->interval > 16)
555 xfer->interval = (1 << (16 - 4));
558 (1 << (xfer->interval - 4));
563 if (xfer->interval == 0) {
565 * One millisecond is the smallest
566 * interval we support:
574 while ((temp != 0) && (temp < xfer->interval)) {
579 switch (parm->speed) {
584 xfer->fps_shift += 3;
591 * NOTE: we do not allow "max_packet_size" or "max_frame_size"
592 * to be equal to zero when setting up USB transfers, hence
593 * this leads to alot of extra code in the USB kernel.
596 if ((xfer->max_frame_size == 0) ||
597 (xfer->max_packet_size == 0)) {
601 if ((parm->bufsize <= MIN_PKT) &&
602 (type != UE_CONTROL) &&
606 xfer->max_packet_size = MIN_PKT;
607 xfer->max_packet_count = 1;
608 parm->bufsize = 0; /* automatic setup length */
609 usbd_update_max_frame_size(xfer);
612 parm->err = USB_ERR_ZERO_MAXP;
621 * check if we should setup a default
625 if (parm->bufsize == 0) {
627 parm->bufsize = xfer->max_frame_size;
629 if (type == UE_ISOCHRONOUS) {
630 parm->bufsize *= xfer->nframes;
634 * check if we are about to setup a proxy
638 if (xfer->flags.proxy_buffer) {
640 /* round bufsize up */
642 parm->bufsize += (xfer->max_frame_size - 1);
644 if (parm->bufsize < xfer->max_frame_size) {
645 /* length wrapped around */
646 parm->err = USB_ERR_INVAL;
649 /* subtract remainder */
651 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
653 /* add length of USB device request structure, if any */
655 if (type == UE_CONTROL) {
656 parm->bufsize += REQ_SIZE; /* SETUP message */
659 xfer->max_data_length = parm->bufsize;
661 /* Setup "n_frlengths" and "n_frbuffers" */
663 if (type == UE_ISOCHRONOUS) {
664 n_frlengths = xfer->nframes;
668 if (type == UE_CONTROL) {
669 xfer->flags_int.control_xfr = 1;
670 if (xfer->nframes == 0) {
671 if (parm->bufsize <= REQ_SIZE) {
673 * there will never be any data
682 if (xfer->nframes == 0) {
687 n_frlengths = xfer->nframes;
688 n_frbuffers = xfer->nframes;
692 * check if we have room for the
693 * USB device request structure:
696 if (type == UE_CONTROL) {
698 if (xfer->max_data_length < REQ_SIZE) {
699 /* length wrapped around or too small bufsize */
700 parm->err = USB_ERR_INVAL;
703 xfer->max_data_length -= REQ_SIZE;
706 * Setup "frlengths" and shadow "frlengths" for keeping the
707 * initial frame lengths when a USB transfer is complete. This
708 * information is useful when computing isochronous offsets.
710 xfer->frlengths = parm->xfer_length_ptr;
711 parm->xfer_length_ptr += 2 * n_frlengths;
713 /* setup "frbuffers" */
714 xfer->frbuffers = parm->xfer_page_cache_ptr;
715 parm->xfer_page_cache_ptr += n_frbuffers;
717 /* initialize max frame count */
718 xfer->max_frame_count = xfer->nframes;
721 * check if we need to setup
725 if (!xfer->flags.ext_buffer) {
727 struct usb_page_search page_info;
728 struct usb_page_cache *pc;
730 if (usbd_transfer_setup_sub_malloc(parm,
731 &pc, parm->bufsize, 1, 1)) {
732 parm->err = USB_ERR_NOMEM;
733 } else if (parm->buf != NULL) {
735 usbd_get_page(pc, 0, &page_info);
737 xfer->local_buffer = page_info.buffer;
739 usbd_xfer_set_frame_offset(xfer, 0, 0);
741 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
742 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
747 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
749 if (parm->buf != NULL) {
751 USB_ADD_BYTES(parm->buf, parm->size[0]);
753 usbd_xfer_set_frame_offset(xfer, 0, 0);
755 if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
756 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
759 parm->size[0] += parm->bufsize;
761 /* align data again */
762 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
766 * Compute maximum buffer size
769 if (parm->bufsize_max < parm->bufsize) {
770 parm->bufsize_max = parm->bufsize;
773 if (xfer->flags_int.bdma_enable) {
775 * Setup "dma_page_ptr".
777 * Proof for formula below:
779 * Assume there are three USB frames having length "a", "b" and
780 * "c". These USB frames will at maximum need "z"
781 * "usb_page" structures. "z" is given by:
783 * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
784 * ((c / USB_PAGE_SIZE) + 2);
786 * Constraining "a", "b" and "c" like this:
788 * (a + b + c) <= parm->bufsize
792 * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
794 * Here is the general formula:
796 xfer->dma_page_ptr = parm->dma_page_ptr;
797 parm->dma_page_ptr += (2 * n_frbuffers);
798 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
802 /* correct maximum data length */
803 xfer->max_data_length = 0;
805 /* subtract USB frame remainder from "hc_max_frame_size" */
807 xfer->max_hc_frame_size =
808 (parm->hc_max_frame_size -
809 (parm->hc_max_frame_size % xfer->max_frame_size));
811 if (xfer->max_hc_frame_size == 0) {
812 parm->err = USB_ERR_INVAL;
816 /* initialize frame buffers */
819 for (x = 0; x != n_frbuffers; x++) {
820 xfer->frbuffers[x].tag_parent =
821 &xfer->xroot->dma_parent_tag;
823 if (xfer->flags_int.bdma_enable &&
824 (parm->bufsize_max > 0)) {
826 if (usb_pc_dmamap_create(
828 parm->bufsize_max)) {
829 parm->err = USB_ERR_NOMEM;
839 * Set some dummy values so that we avoid division by zero:
841 xfer->max_hc_frame_size = 1;
842 xfer->max_frame_size = 1;
843 xfer->max_packet_size = 1;
844 xfer->max_data_length = 0;
846 xfer->max_frame_count = 0;
850 /*------------------------------------------------------------------------*
851 * usbd_transfer_setup - setup an array of USB transfers
853 * NOTE: You must always call "usbd_transfer_unsetup" after calling
854 * "usbd_transfer_setup" if success was returned.
856 * The idea is that the USB device driver should pre-allocate all its
857 * transfers by one call to this function.
862 *------------------------------------------------------------------------*/
864 usbd_transfer_setup(struct usb_device *udev,
865 const uint8_t *ifaces, struct usb_xfer **ppxfer,
866 const struct usb_config *setup_start, uint16_t n_setup,
867 void *priv_sc, struct lock *xfer_lock)
869 const struct usb_config *setup_end = setup_start + n_setup;
870 const struct usb_config *setup;
871 struct usb_setup_params *parm;
872 struct usb_endpoint *ep;
873 struct usb_xfer_root *info;
874 struct usb_xfer *xfer;
876 usb_error_t error = 0;
882 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
883 "usbd_transfer_setup can sleep!");
886 /* do some checking first */
889 DPRINTFN(6, "setup array has zero length!\n");
890 return (USB_ERR_INVAL);
892 if (ifaces == NULL) {
893 DPRINTFN(6, "ifaces array is NULL!\n");
894 return (USB_ERR_INVAL);
896 if (xfer_lock == NULL) {
897 panic("xfer without lock!\n");
898 DPRINTFN(6, "using global lock\n");
901 /* more sanity checks */
903 for (setup = setup_start, n = 0;
904 setup != setup_end; setup++, n++) {
905 if (setup->bufsize == (usb_frlength_t)-1) {
906 error = USB_ERR_BAD_BUFSIZE;
907 DPRINTF("invalid bufsize\n");
909 if (setup->callback == NULL) {
910 error = USB_ERR_NO_CALLBACK;
911 DPRINTF("no callback\n");
919 /* Protect scratch area */
920 do_unlock = usbd_enum_lock(udev);
925 parm = &udev->scratch.xfer_setup[0].parm;
926 memset(parm, 0, sizeof(*parm));
929 parm->speed = usbd_get_speed(udev);
930 parm->hc_max_packet_count = 1;
932 if (parm->speed >= USB_SPEED_MAX) {
933 parm->err = USB_ERR_INVAL;
936 /* setup all transfers */
942 * Initialize the "usb_xfer_root" structure,
943 * which is common for all our USB transfers.
945 info = USB_ADD_BYTES(buf, 0);
947 info->memory_base = buf;
948 info->memory_size = parm->size[0];
951 info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
952 info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
954 info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
955 info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
957 cv_init(&info->cv_drain, "WDRAIN");
959 info->xfer_lock = xfer_lock;
961 usb_dma_tag_setup(&info->dma_parent_tag,
962 parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
963 xfer_lock, &usb_bdma_done_event, 32,
967 info->bus = udev->bus;
970 TAILQ_INIT(&info->done_q.head);
971 info->done_q.command = &usbd_callback_wrapper;
973 TAILQ_INIT(&info->dma_q.head);
974 info->dma_q.command = &usb_bdma_work_loop;
976 info->done_m[0].hdr.pm_callback = &usb_callback_proc;
977 info->done_m[0].xroot = info;
978 info->done_m[1].hdr.pm_callback = &usb_callback_proc;
979 info->done_m[1].xroot = info;
982 * In device side mode control endpoint
983 * requests need to run from a separate
984 * context, else there is a chance of
987 if (setup_start == usb_control_ep_cfg)
989 USB_BUS_CONTROL_XFER_PROC(udev->bus);
992 USB_BUS_NON_GIANT_PROC(udev->bus);
998 parm->size[0] += sizeof(info[0]);
1000 for (setup = setup_start, n = 0;
1001 setup != setup_end; setup++, n++) {
1003 /* skip USB transfers without callbacks: */
1004 if (setup->callback == NULL) {
1007 /* see if there is a matching endpoint */
1008 ep = usbd_get_endpoint(udev,
1009 ifaces[setup->if_index], setup);
1012 * Check that the USB PIPE is valid and that
1013 * the endpoint mode is proper.
1015 * Make sure we don't allocate a streams
1016 * transfer when such a combination is not
1019 if ((ep == NULL) || (ep->methods == NULL) ||
1020 ((ep->ep_mode != USB_EP_MODE_STREAMS) &&
1021 (ep->ep_mode != USB_EP_MODE_DEFAULT)) ||
1022 (setup->stream_id != 0 &&
1023 (setup->stream_id >= USB_MAX_EP_STREAMS ||
1024 (ep->ep_mode != USB_EP_MODE_STREAMS)))) {
1025 if (setup->flags.no_pipe_ok)
1027 if ((setup->usb_mode != USB_MODE_DUAL) &&
1028 (setup->usb_mode != udev->flags.usb_mode))
1030 parm->err = USB_ERR_NO_PIPE;
1034 /* align data properly */
1035 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1037 /* store current setup pointer */
1038 parm->curr_setup = setup;
1042 * Common initialization of the
1043 * "usb_xfer" structure.
1045 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1046 xfer->address = udev->address;
1047 xfer->priv_sc = priv_sc;
1050 usb_callout_init_mtx(&xfer->timeout_handle,
1051 &udev->bus->bus_lock, 0);
1054 * Setup a dummy xfer, hence we are
1055 * writing to the "usb_xfer"
1056 * structure pointed to by "xfer"
1057 * before we have allocated any
1060 xfer = &udev->scratch.xfer_setup[0].dummy;
1061 memset(xfer, 0, sizeof(*xfer));
1065 /* set transfer endpoint pointer */
1066 xfer->endpoint = ep;
1068 /* set transfer stream ID */
1069 xfer->stream_id = setup->stream_id;
1071 parm->size[0] += sizeof(xfer[0]);
1072 parm->methods = xfer->endpoint->methods;
1073 parm->curr_xfer = xfer;
1076 * Call the Host or Device controller transfer
1079 (udev->bus->methods->xfer_setup) (parm);
1081 /* check for error */
1087 * Increment the endpoint refcount. This
1088 * basically prevents setting a new
1089 * configuration and alternate setting
1090 * when USB transfers are in use on
1091 * the given interface. Search the USB
1092 * code for "endpoint->refcount_alloc" if you
1093 * want more information.
1095 USB_BUS_LOCK(info->bus);
1096 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1097 parm->err = USB_ERR_INVAL;
1099 xfer->endpoint->refcount_alloc++;
1101 if (xfer->endpoint->refcount_alloc == 0)
1102 panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1103 USB_BUS_UNLOCK(info->bus);
1106 * Whenever we set ppxfer[] then we
1107 * also need to increment the
1110 info->setup_refcount++;
1113 * Transfer is successfully setup and
1119 /* check for error */
1124 if (buf != NULL || parm->err != 0)
1127 /* if no transfers, nothing to do */
1131 /* align data properly */
1132 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1134 /* store offset temporarily */
1135 parm->size[1] = parm->size[0];
1138 * The number of DMA tags required depends on
1139 * the number of endpoints. The current estimate
1140 * for maximum number of DMA tags per endpoint
1142 * 1) for loading memory
1143 * 2) for allocating memory
1144 * 3) for fixing memory [UHCI]
1146 parm->dma_tag_max += 3 * MIN(n_setup, USB_EP_MAX);
1149 * DMA tags for QH, TD, Data and more.
1151 parm->dma_tag_max += 8;
1153 parm->dma_tag_p += parm->dma_tag_max;
1155 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1158 /* align data properly */
1159 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1161 /* store offset temporarily */
1162 parm->size[3] = parm->size[0];
1164 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1167 /* align data properly */
1168 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1170 /* store offset temporarily */
1171 parm->size[4] = parm->size[0];
1173 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1176 /* store end offset temporarily */
1177 parm->size[5] = parm->size[0];
1179 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1182 /* store end offset temporarily */
1184 parm->size[2] = parm->size[0];
1186 /* align data properly */
1187 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1189 parm->size[6] = parm->size[0];
1191 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1194 /* align data properly */
1195 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1197 /* allocate zeroed memory */
1198 buf = kmalloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1201 parm->err = USB_ERR_NOMEM;
1202 DPRINTFN(0, "cannot allocate memory block for "
1203 "configuration (%d bytes)\n",
1207 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1208 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1209 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1210 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1211 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1216 if (info->setup_refcount == 0) {
1218 * "usbd_transfer_unsetup_sub" will unlock
1219 * the bus mutex before returning !
1221 USB_BUS_LOCK(info->bus);
1223 /* something went wrong */
1224 usbd_transfer_unsetup_sub(info, 0);
1228 /* check if any errors happened */
1230 usbd_transfer_unsetup(ppxfer, n_setup);
1235 usbd_enum_unlock(udev);
1240 /*------------------------------------------------------------------------*
1241 * usbd_transfer_unsetup_sub - factored out code
1242 *------------------------------------------------------------------------*/
1244 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1247 struct usb_page_cache *pc;
1250 USB_BUS_LOCK_ASSERT(info->bus);
1252 /* wait for any outstanding DMA operations */
1253 /* This is insane */
1256 temp = usbd_get_dma_delay(info->udev);
1258 usb_pause_mtx(&info->bus->bus_lock,
1259 USB_MS_TO_TICKS(temp));
1263 /* make sure that our done messages are not queued anywhere */
1264 usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1266 USB_BUS_UNLOCK(info->bus);
1269 /* free DMA'able memory, if any */
1270 pc = info->dma_page_cache_start;
1271 while (pc != info->dma_page_cache_end) {
1272 usb_pc_free_mem(pc);
1276 /* free DMA maps in all "xfer->frbuffers" */
1277 pc = info->xfer_page_cache_start;
1278 while (pc != info->xfer_page_cache_end) {
1279 usb_pc_dmamap_destroy(pc);
1283 /* free all DMA tags */
1284 usb_dma_tag_unsetup(&info->dma_parent_tag);
1287 cv_destroy(&info->cv_drain);
1290 * free the "memory_base" last, hence the "info" structure is
1291 * contained within the "memory_base"!
1293 usbd_delayed_free(info->memory_base, M_USB);
1297 * This is a horrible hack and workaround to a very bad decision by
1298 * the original U4B coder to integrate the QH/TD structures into the
1299 * xfer and then free the whole mess all at once.
1301 * The problem is that the controller may still be accessing the QHs,
1302 * because it might have gotten side-tracked onto the removed QHs
1303 * chain link. They have to remain intact long enough for the
1304 * controller to get out.
1306 * This horrible hack basically just delays freeing by 256 slots.
1307 * It's not even time-based or door-bell based (which is the way
1308 * the linux driver does it)... but to fix it properly requires rewriting
1309 * too much of this driver.
1311 #define DFREE_SLOTS 256
1312 #define DFREE_MASK (DFREE_SLOTS - 1)
1314 static struct dfree_slot {
1316 struct malloc_type *mtype;
1317 } dfree_slots[DFREE_SLOTS];
1318 static int dfree_index;
1321 usbd_delayed_free(void *data, struct malloc_type *mtype)
1323 struct dfree_slot slot;
1327 index = atomic_fetchadd_int(&dfree_index, 1);
1328 index &= DFREE_MASK;
1329 slot = dfree_slots[index];
1330 dfree_slots[index].data = data;
1331 dfree_slots[index].mtype = mtype;
1334 kfree(slot.data, slot.mtype);
1337 /*------------------------------------------------------------------------*
1338 * usbd_transfer_unsetup - unsetup/free an array of USB transfers
1340 * NOTE: All USB transfers in progress will get called back passing
1341 * the error code "USB_ERR_CANCELLED" before this function
1343 *------------------------------------------------------------------------*/
1345 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1347 struct usb_xfer *xfer;
1348 struct usb_xfer_root *info;
1349 uint8_t needs_delay = 0;
1352 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1353 "usbd_transfer_unsetup can sleep!");
1357 xfer = pxfer[n_setup];
1364 USB_XFER_LOCK(xfer);
1365 USB_BUS_LOCK(info->bus);
1368 * HINT: when you start/stop a transfer, it might be a
1369 * good idea to directly use the "pxfer[]" structure:
1371 * usbd_transfer_start(sc->pxfer[0]);
1372 * usbd_transfer_stop(sc->pxfer[0]);
1374 * That way, if your code has many parts that will not
1375 * stop running under the same lock, in other words
1376 * "xfer_mtx", the usbd_transfer_start and
1377 * usbd_transfer_stop functions will simply return
1378 * when they detect a NULL pointer argument.
1380 * To avoid any races we clear the "pxfer[]" pointer
1381 * while holding the private mutex of the driver:
1383 pxfer[n_setup] = NULL;
1385 USB_BUS_UNLOCK(info->bus);
1386 USB_XFER_UNLOCK(xfer);
1388 usbd_transfer_drain(xfer);
1391 if (xfer->flags_int.bdma_enable)
1395 * NOTE: default endpoint does not have an
1396 * interface, even if endpoint->iface_index == 0
1398 USB_BUS_LOCK(info->bus);
1399 xfer->endpoint->refcount_alloc--;
1400 USB_BUS_UNLOCK(info->bus);
1402 usb_callout_drain(&xfer->timeout_handle);
1404 USB_BUS_LOCK(info->bus);
1406 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1407 "reference count\n"));
1409 info->setup_refcount--;
1411 if (info->setup_refcount == 0) {
1412 usbd_transfer_unsetup_sub(info,
1415 USB_BUS_UNLOCK(info->bus);
1420 /*------------------------------------------------------------------------*
1421 * usbd_control_transfer_init - factored out code
1423 * In USB Device Mode we have to wait for the SETUP packet which
1424 * containst the "struct usb_device_request" structure, before we can
1425 * transfer any data. In USB Host Mode we already have the SETUP
1426 * packet at the moment the USB transfer is started. This leads us to
1427 * having to setup the USB transfer at two different places in
1428 * time. This function just contains factored out control transfer
1429 * initialisation code, so that we don't duplicate the code.
1430 *------------------------------------------------------------------------*/
1432 usbd_control_transfer_init(struct usb_xfer *xfer)
1434 struct usb_device_request req;
1436 /* copy out the USB request header */
1438 usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1440 /* setup remainder */
1442 xfer->flags_int.control_rem = UGETW(req.wLength);
1444 /* copy direction to endpoint variable */
1446 xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1448 (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1451 /*------------------------------------------------------------------------*
1452 * usbd_setup_ctrl_transfer
1454 * This function handles initialisation of control transfers. Control
1455 * transfers are special in that regard that they can both transmit
1461 *------------------------------------------------------------------------*/
1463 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1467 /* Check for control endpoint stall */
1468 if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1469 /* the control transfer is no longer active */
1470 xfer->flags_int.control_stall = 1;
1471 xfer->flags_int.control_act = 0;
1473 /* don't stall control transfer by default */
1474 xfer->flags_int.control_stall = 0;
1477 /* Check for invalid number of frames */
1478 if (xfer->nframes > 2) {
1480 * If you need to split a control transfer, you
1481 * have to do one part at a time. Only with
1482 * non-control transfers you can do multiple
1485 DPRINTFN(0, "Too many frames: %u\n",
1486 (unsigned int)xfer->nframes);
1491 * Check if there is a control
1492 * transfer in progress:
1494 if (xfer->flags_int.control_act) {
1496 if (xfer->flags_int.control_hdr) {
1498 /* clear send header flag */
1500 xfer->flags_int.control_hdr = 0;
1502 /* setup control transfer */
1503 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1504 usbd_control_transfer_init(xfer);
1507 /* get data length */
1513 /* the size of the SETUP structure is hardcoded ! */
1515 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1516 DPRINTFN(0, "Wrong framelength %u != %zu\n",
1517 xfer->frlengths[0], sizeof(struct
1518 usb_device_request));
1521 /* check USB mode */
1522 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1524 /* check number of frames */
1525 if (xfer->nframes != 1) {
1527 * We need to receive the setup
1528 * message first so that we know the
1531 DPRINTF("Misconfigured transfer\n");
1535 * Set a dummy "control_rem" value. This
1536 * variable will be overwritten later by a
1537 * call to "usbd_control_transfer_init()" !
1539 xfer->flags_int.control_rem = 0xFFFF;
1542 /* setup "endpoint" and "control_rem" */
1544 usbd_control_transfer_init(xfer);
1547 /* set transfer-header flag */
1549 xfer->flags_int.control_hdr = 1;
1551 /* get data length */
1553 len = (xfer->sumlen - sizeof(struct usb_device_request));
1556 /* check if there is a length mismatch */
1558 if (len > xfer->flags_int.control_rem) {
1559 DPRINTFN(0, "Length (%d) greater than "
1560 "remaining length (%d)\n", len,
1561 xfer->flags_int.control_rem);
1564 /* check if we are doing a short transfer */
1566 if (xfer->flags.force_short_xfer) {
1567 xfer->flags_int.control_rem = 0;
1569 if ((len != xfer->max_data_length) &&
1570 (len != xfer->flags_int.control_rem) &&
1571 (xfer->nframes != 1)) {
1572 DPRINTFN(0, "Short control transfer without "
1573 "force_short_xfer set\n");
1576 xfer->flags_int.control_rem -= len;
1579 /* the status part is executed when "control_act" is 0 */
1581 if ((xfer->flags_int.control_rem > 0) ||
1582 (xfer->flags.manual_status)) {
1583 /* don't execute the STATUS stage yet */
1584 xfer->flags_int.control_act = 1;
1587 if ((!xfer->flags_int.control_hdr) &&
1588 (xfer->nframes == 1)) {
1590 * This is not a valid operation!
1592 DPRINTFN(0, "Invalid parameter "
1597 /* time to execute the STATUS stage */
1598 xfer->flags_int.control_act = 0;
1600 return (0); /* success */
1603 return (1); /* failure */
1606 /*------------------------------------------------------------------------*
1607 * usbd_transfer_submit - start USB hardware for the given transfer
1609 * This function should only be called from the USB callback.
1610 *------------------------------------------------------------------------*/
1612 usbd_transfer_submit(struct usb_xfer *xfer)
1614 struct usb_xfer_root *info;
1615 struct usb_bus *bus;
1621 DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1622 xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1626 if (USB_DEBUG_VAR > 0) {
1629 usb_dump_endpoint(xfer->endpoint);
1631 USB_BUS_UNLOCK(bus);
1635 USB_XFER_LOCK_ASSERT(xfer);
1636 USB_BUS_LOCK_ASSERT_NOTOWNED(bus);
1638 /* Only open the USB transfer once! */
1639 if (!xfer->flags_int.open) {
1640 xfer->flags_int.open = 1;
1645 (xfer->endpoint->methods->open) (xfer);
1646 USB_BUS_UNLOCK(bus);
1648 /* set "transferring" flag */
1649 xfer->flags_int.transferring = 1;
1652 /* increment power reference */
1653 usbd_transfer_power_ref(xfer, 1);
1656 * Check if the transfer is waiting on a queue, most
1657 * frequently the "done_q":
1659 if (xfer->wait_queue) {
1661 usbd_transfer_dequeue(xfer);
1662 USB_BUS_UNLOCK(bus);
1664 /* clear "did_dma_delay" flag */
1665 xfer->flags_int.did_dma_delay = 0;
1667 /* clear "did_close" flag */
1668 xfer->flags_int.did_close = 0;
1671 /* clear "bdma_setup" flag */
1672 xfer->flags_int.bdma_setup = 0;
1674 /* by default we cannot cancel any USB transfer immediately */
1675 xfer->flags_int.can_cancel_immed = 0;
1677 /* clear lengths and frame counts by default */
1682 /* clear any previous errors */
1685 /* Check if the device is still alive */
1686 if (info->udev->state < USB_STATE_POWERED) {
1689 * Must return cancelled error code else
1690 * device drivers can hang.
1692 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1693 USB_BUS_UNLOCK(bus);
1698 if (xfer->nframes == 0) {
1699 if (xfer->flags.stall_pipe) {
1701 * Special case - want to stall without transferring
1704 DPRINTF("xfer=%p nframes=0: stall "
1705 "or clear stall!\n", xfer);
1707 xfer->flags_int.can_cancel_immed = 1;
1708 /* start the transfer */
1709 usb_command_wrapper(&xfer->endpoint->
1710 endpoint_q[xfer->stream_id], xfer);
1711 USB_BUS_UNLOCK(bus);
1715 usbd_transfer_done(xfer, USB_ERR_INVAL);
1716 USB_BUS_UNLOCK(bus);
1719 /* compute some variables */
1721 for (x = 0; x != xfer->nframes; x++) {
1722 /* make a copy of the frlenghts[] */
1723 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1724 /* compute total transfer length */
1725 xfer->sumlen += xfer->frlengths[x];
1726 if (xfer->sumlen < xfer->frlengths[x]) {
1727 /* length wrapped around */
1729 usbd_transfer_done(xfer, USB_ERR_INVAL);
1730 USB_BUS_UNLOCK(bus);
1735 /* clear some internal flags */
1737 xfer->flags_int.short_xfer_ok = 0;
1738 xfer->flags_int.short_frames_ok = 0;
1740 /* check if this is a control transfer */
1742 if (xfer->flags_int.control_xfr) {
1744 if (usbd_setup_ctrl_transfer(xfer)) {
1746 usbd_transfer_done(xfer, USB_ERR_STALLED);
1747 USB_BUS_UNLOCK(bus);
1752 * Setup filtered version of some transfer flags,
1753 * in case of data read direction
1755 if (USB_GET_DATA_ISREAD(xfer)) {
1757 if (xfer->flags.short_frames_ok) {
1758 xfer->flags_int.short_xfer_ok = 1;
1759 xfer->flags_int.short_frames_ok = 1;
1760 } else if (xfer->flags.short_xfer_ok) {
1761 xfer->flags_int.short_xfer_ok = 1;
1763 /* check for control transfer */
1764 if (xfer->flags_int.control_xfr) {
1766 * 1) Control transfers do not support
1767 * reception of multiple short USB
1768 * frames in host mode and device side
1769 * mode, with exception of:
1771 * 2) Due to sometimes buggy device
1772 * side firmware we need to do a
1773 * STATUS stage in case of short
1774 * control transfers in USB host mode.
1775 * The STATUS stage then becomes the
1776 * "alt_next" to the DATA stage.
1778 xfer->flags_int.short_frames_ok = 1;
1783 * Check if BUS-DMA support is enabled and try to load virtual
1784 * buffers into DMA, if any:
1787 if (xfer->flags_int.bdma_enable) {
1788 /* insert the USB transfer last in the BUS-DMA queue */
1789 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1794 * Enter the USB transfer into the Host Controller or
1795 * Device Controller schedule:
1797 usbd_pipe_enter(xfer);
1800 /*------------------------------------------------------------------------*
1801 * usbd_pipe_enter - factored out code
1802 *------------------------------------------------------------------------*/
1804 usbd_pipe_enter(struct usb_xfer *xfer)
1806 struct usb_endpoint *ep;
1808 USB_XFER_LOCK_ASSERT(xfer);
1810 USB_BUS_LOCK(xfer->xroot->bus);
1812 ep = xfer->endpoint;
1816 /* the transfer can now be cancelled */
1817 xfer->flags_int.can_cancel_immed = 1;
1819 /* enter the transfer */
1820 (ep->methods->enter) (xfer);
1822 /* check for transfer error */
1824 /* some error has happened */
1825 usbd_transfer_done(xfer, 0);
1826 USB_BUS_UNLOCK(xfer->xroot->bus);
1830 /* start the transfer */
1831 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1832 USB_BUS_UNLOCK(xfer->xroot->bus);
1835 /*------------------------------------------------------------------------*
1836 * usbd_transfer_start - start an USB transfer
1838 * NOTE: Calling this function more than one time will only
1839 * result in a single transfer start, until the USB transfer
1841 *------------------------------------------------------------------------*/
1843 usbd_transfer_start(struct usb_xfer *xfer)
1846 /* transfer is gone */
1849 USB_XFER_LOCK_ASSERT(xfer);
1851 /* mark the USB transfer started */
1853 if (!xfer->flags_int.started) {
1854 /* lock the BUS lock to avoid races updating flags_int */
1855 USB_BUS_LOCK(xfer->xroot->bus);
1856 xfer->flags_int.started = 1;
1857 USB_BUS_UNLOCK(xfer->xroot->bus);
1859 /* check if the USB transfer callback is already transferring */
1861 if (xfer->flags_int.transferring) {
1864 USB_BUS_LOCK(xfer->xroot->bus);
1865 /* call the USB transfer callback */
1866 usbd_callback_ss_done_defer(xfer);
1867 USB_BUS_UNLOCK(xfer->xroot->bus);
1870 /*------------------------------------------------------------------------*
1871 * usbd_transfer_stop - stop an USB transfer
1873 * NOTE: Calling this function more than one time will only
1874 * result in a single transfer stop.
1875 * NOTE: When this function returns it is not safe to free nor
1876 * reuse any DMA buffers. See "usbd_transfer_drain()".
1877 *------------------------------------------------------------------------*/
1879 usbd_transfer_stop(struct usb_xfer *xfer)
1881 struct usb_endpoint *ep;
1884 /* transfer is gone */
1888 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1891 /* check if the USB transfer was ever opened */
1893 if (!xfer->flags_int.open) {
1894 if (xfer->flags_int.started) {
1895 /* nothing to do except clearing the "started" flag */
1896 /* lock the BUS lock to avoid races updating flags_int */
1897 USB_BUS_LOCK(xfer->xroot->bus);
1898 xfer->flags_int.started = 0;
1899 USB_BUS_UNLOCK(xfer->xroot->bus);
1903 /* try to stop the current USB transfer */
1905 USB_BUS_LOCK(xfer->xroot->bus);
1906 /* override any previous error */
1907 xfer->error = USB_ERR_CANCELLED;
1910 * Clear "open" and "started" when both private and USB lock
1911 * is locked so that we don't get a race updating "flags_int"
1913 xfer->flags_int.open = 0;
1914 xfer->flags_int.started = 0;
1917 * Check if we can cancel the USB transfer immediately.
1919 if (xfer->flags_int.transferring) {
1920 if (xfer->flags_int.can_cancel_immed &&
1921 (!xfer->flags_int.did_close)) {
1924 * The following will lead to an USB_ERR_CANCELLED
1925 * error code being passed to the USB callback.
1927 (xfer->endpoint->methods->close) (xfer);
1928 /* only close once */
1929 xfer->flags_int.did_close = 1;
1931 /* need to wait for the next done callback */
1936 /* close here and now */
1937 (xfer->endpoint->methods->close) (xfer);
1940 * Any additional DMA delay is done by
1941 * "usbd_transfer_unsetup()".
1945 * Special case. Check if we need to restart a blocked
1948 ep = xfer->endpoint;
1951 * If the current USB transfer is completing we need
1952 * to start the next one:
1954 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
1955 usb_command_wrapper(
1956 &ep->endpoint_q[xfer->stream_id], NULL);
1960 USB_BUS_UNLOCK(xfer->xroot->bus);
1963 /*------------------------------------------------------------------------*
1964 * usbd_transfer_pending
1966 * This function will check if an USB transfer is pending which is a
1967 * little bit complicated!
1970 * 1: Pending: The USB transfer will receive a callback in the future.
1971 *------------------------------------------------------------------------*/
1973 usbd_transfer_pending(struct usb_xfer *xfer)
1975 struct usb_xfer_root *info;
1976 struct usb_xfer_queue *pq;
1979 /* transfer is gone */
1983 USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1986 if (xfer->flags_int.transferring) {
1990 USB_BUS_LOCK(xfer->xroot->bus);
1991 if (xfer->wait_queue) {
1992 /* we are waiting on a queue somewhere */
1993 USB_BUS_UNLOCK(xfer->xroot->bus);
1999 if (pq->curr == xfer) {
2000 /* we are currently scheduled for callback */
2001 USB_BUS_UNLOCK(xfer->xroot->bus);
2004 /* we are not pending */
2005 USB_BUS_UNLOCK(xfer->xroot->bus);
2009 /*------------------------------------------------------------------------*
2010 * usbd_transfer_drain
2012 * This function will stop the USB transfer and wait for any
2013 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2014 * are loaded into DMA can safely be freed or reused after that this
2015 * function has returned.
2016 *------------------------------------------------------------------------*/
2018 usbd_transfer_drain(struct usb_xfer *xfer)
2021 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2022 "usbd_transfer_drain can sleep!");
2026 /* transfer is gone */
2029 USB_XFER_LOCK_ASSERT_NOTOWNED(xfer);
2030 USB_XFER_LOCK(xfer);
2032 usbd_transfer_stop(xfer);
2035 * It is allowed that the callback can drop its
2036 * transfer mutex. In that case checking only
2037 * "usbd_transfer_pending()" is not enough to tell if
2038 * the USB transfer is fully drained. We also need to
2039 * check the internal "doing_callback" flag.
2041 xfer->flags_int.draining = 1;
2044 * XXX hack, the wakeup of xfer can race conditions which
2045 * clear the pending status of the xfer.
2047 while (usbd_transfer_pending(xfer) ||
2048 xfer->flags_int.doing_callback) {
2051 * Wait until the current outstanding USB
2052 * transfer is complete !
2054 /* cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_lock); */
2055 lksleep(xfer, xfer->xroot->xfer_lock, 0, "DRAIN", hz);
2057 xfer->flags_int.draining = 0;
2058 USB_XFER_UNLOCK(xfer);
2061 struct usb_page_cache *
2062 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2064 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2066 return (&xfer->frbuffers[frindex]);
2070 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2072 struct usb_page_search page_info;
2074 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2076 usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2077 return (page_info.buffer);
2080 /*------------------------------------------------------------------------*
2081 * usbd_xfer_get_fps_shift
2083 * The following function is only useful for isochronous transfers. It
2084 * returns how many times the frame execution rate has been shifted
2090 *------------------------------------------------------------------------*/
2092 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2094 return (xfer->fps_shift);
2098 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2100 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2102 return (xfer->frlengths[frindex]);
2105 /*------------------------------------------------------------------------*
2106 * usbd_xfer_set_frame_data
2108 * This function sets the pointer of the buffer that should
2109 * loaded directly into DMA for the given USB frame. Passing "ptr"
2110 * equal to NULL while the corresponding "frlength" is greater
2111 * than zero gives undefined results!
2112 *------------------------------------------------------------------------*/
2114 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2115 void *ptr, usb_frlength_t len)
2117 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2119 /* set virtual address to load and length */
2120 xfer->frbuffers[frindex].buffer = ptr;
2121 usbd_xfer_set_frame_len(xfer, frindex, len);
2125 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2126 void **ptr, int *len)
2128 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2131 *ptr = xfer->frbuffers[frindex].buffer;
2133 *len = xfer->frlengths[frindex];
2136 /*------------------------------------------------------------------------*
2137 * usbd_xfer_old_frame_length
2139 * This function returns the framelength of the given frame at the
2140 * time the transfer was submitted. This function can be used to
2141 * compute the starting data pointer of the next isochronous frame
2142 * when an isochronous transfer has completed.
2143 *------------------------------------------------------------------------*/
2145 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2147 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2149 return (xfer->frlengths[frindex + xfer->max_frame_count]);
2153 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2157 *actlen = xfer->actlen;
2159 *sumlen = xfer->sumlen;
2160 if (aframes != NULL)
2161 *aframes = xfer->aframes;
2162 if (nframes != NULL)
2163 *nframes = xfer->nframes;
2166 /*------------------------------------------------------------------------*
2167 * usbd_xfer_set_frame_offset
2169 * This function sets the frame data buffer offset relative to the beginning
2170 * of the USB DMA buffer allocated for this USB transfer.
2171 *------------------------------------------------------------------------*/
2173 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2174 usb_frcount_t frindex)
2176 KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2177 "when the USB buffer is external\n"));
2178 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2180 /* set virtual address to load */
2181 xfer->frbuffers[frindex].buffer =
2182 USB_ADD_BYTES(xfer->local_buffer, offset);
2186 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2192 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2198 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2204 usbd_xfer_max_frames(struct usb_xfer *xfer)
2206 return (xfer->max_frame_count);
2210 usbd_xfer_max_len(struct usb_xfer *xfer)
2212 return (xfer->max_data_length);
2216 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2218 return (xfer->max_frame_size);
2222 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2225 KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2227 xfer->frlengths[frindex] = len;
2230 /*------------------------------------------------------------------------*
2231 * usb_callback_proc - factored out code
2233 * This function performs USB callbacks.
2234 *------------------------------------------------------------------------*/
2236 usb_callback_proc(struct usb_proc_msg *_pm)
2238 struct usb_done_msg *pm = (void *)_pm;
2239 struct usb_xfer_root *info = pm->xroot;
2241 /* Change locking order */
2242 USB_BUS_UNLOCK(info->bus);
2245 * We exploit the fact that the mutex is the same for all
2246 * callbacks that will be called from this thread:
2248 lockmgr(info->xfer_lock, LK_EXCLUSIVE);
2249 USB_BUS_LOCK(info->bus);
2251 /* Continue where we lost track */
2252 usb_command_wrapper(&info->done_q,
2255 lockmgr(info->xfer_lock, LK_RELEASE);
2258 /*------------------------------------------------------------------------*
2259 * usbd_callback_ss_done_defer
2261 * This function will defer the start, stop and done callback to the
2263 *------------------------------------------------------------------------*/
2265 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2267 struct usb_xfer_root *info = xfer->xroot;
2268 struct usb_xfer_queue *pq = &info->done_q;
2270 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2272 if (pq->curr != xfer) {
2273 usbd_transfer_enqueue(pq, xfer);
2275 if (!pq->recurse_1) {
2278 * We have to postpone the callback due to the fact we
2279 * will have a Lock Order Reversal, LOR, if we try to
2282 if (usb_proc_msignal(info->done_p,
2283 &info->done_m[0], &info->done_m[1])) {
2287 /* clear second recurse flag */
2294 /*------------------------------------------------------------------------*
2295 * usbd_callback_wrapper
2297 * This is a wrapper for USB callbacks. This wrapper does some
2298 * auto-magic things like figuring out if we can call the callback
2299 * directly from the current context or if we need to wakeup the
2300 * interrupt process.
2301 *------------------------------------------------------------------------*/
2303 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2305 struct usb_xfer *xfer = pq->curr;
2306 struct usb_xfer_root *info = xfer->xroot;
2308 USB_BUS_LOCK_ASSERT(info->bus);
2309 if (!lockowned(info->xfer_lock)) {
2311 * Cases that end up here:
2313 * 5) HW interrupt done callback or other source.
2315 DPRINTFN(3, "case 5\n");
2318 * We have to postpone the callback due to the fact we
2319 * will have a Lock Order Reversal, LOR, if we try to
2322 if (usb_proc_msignal(info->done_p,
2323 &info->done_m[0], &info->done_m[1])) {
2329 * Cases that end up here:
2331 * 1) We are starting a transfer
2332 * 2) We are prematurely calling back a transfer
2333 * 3) We are stopping a transfer
2334 * 4) We are doing an ordinary callback
2336 DPRINTFN(3, "case 1-4\n");
2337 /* get next USB transfer in the queue */
2338 info->done_q.curr = NULL;
2340 /* set flag in case of drain */
2341 xfer->flags_int.doing_callback = 1;
2343 USB_BUS_UNLOCK(info->bus);
2344 USB_BUS_LOCK_ASSERT_NOTOWNED(info->bus);
2346 /* set correct USB state for callback */
2347 if (!xfer->flags_int.transferring) {
2348 xfer->usb_state = USB_ST_SETUP;
2349 if (!xfer->flags_int.started) {
2350 /* we got stopped before we even got started */
2351 USB_BUS_LOCK(info->bus);
2356 if (usbd_callback_wrapper_sub(xfer)) {
2357 /* the callback has been deferred */
2358 USB_BUS_LOCK(info->bus);
2362 /* decrement power reference */
2363 usbd_transfer_power_ref(xfer, -1);
2365 xfer->flags_int.transferring = 0;
2368 xfer->usb_state = USB_ST_ERROR;
2370 /* set transferred state */
2371 xfer->usb_state = USB_ST_TRANSFERRED;
2373 /* sync DMA memory, if any */
2374 if (xfer->flags_int.bdma_enable &&
2375 (!xfer->flags_int.bdma_no_post_sync)) {
2376 usb_bdma_post_sync(xfer);
2383 if (xfer->usb_state != USB_ST_SETUP)
2384 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2386 /* call processing routine */
2387 (xfer->callback) (xfer, xfer->error);
2389 /* pickup the USB mutex again */
2390 USB_BUS_LOCK(info->bus);
2393 * Check if we got started after that we got cancelled, but
2394 * before we managed to do the callback.
2396 if ((!xfer->flags_int.open) &&
2397 (xfer->flags_int.started) &&
2398 (xfer->usb_state == USB_ST_ERROR)) {
2399 /* clear flag in case of drain */
2400 xfer->flags_int.doing_callback = 0;
2401 /* try to loop, but not recursivly */
2402 usb_command_wrapper(&info->done_q, xfer);
2407 /* clear flag in case of drain */
2408 xfer->flags_int.doing_callback = 0;
2411 * Check if we are draining.
2413 if (xfer->flags_int.draining &&
2414 (!xfer->flags_int.transferring)) {
2415 /* "usbd_transfer_drain()" is waiting for end of transfer */
2416 xfer->flags_int.draining = 0;
2417 /* cv_broadcast(&info->cv_drain); */
2421 /* do the next callback, if any */
2422 usb_command_wrapper(&info->done_q,
2426 /*------------------------------------------------------------------------*
2427 * usb_dma_delay_done_cb
2429 * This function is called when the DMA delay has been exectuded, and
2430 * will make sure that the callback is called to complete the USB
2431 * transfer. This code path is ususally only used when there is an USB
2432 * error like USB_ERR_CANCELLED.
2433 *------------------------------------------------------------------------*/
2435 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2437 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2439 DPRINTFN(3, "Completed %p\n", xfer);
2441 /* queue callback for execution, again */
2442 usbd_transfer_done(xfer, 0);
2445 /*------------------------------------------------------------------------*
2446 * usbd_transfer_dequeue
2448 * - This function is used to remove an USB transfer from a USB
2451 * - This function can be called multiple times in a row.
2452 *------------------------------------------------------------------------*/
2454 usbd_transfer_dequeue(struct usb_xfer *xfer)
2456 struct usb_xfer_queue *pq;
2458 pq = xfer->wait_queue;
2460 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2461 xfer->wait_queue = NULL;
2465 /*------------------------------------------------------------------------*
2466 * usbd_transfer_enqueue
2468 * - This function is used to insert an USB transfer into a USB *
2471 * - This function can be called multiple times in a row.
2472 *------------------------------------------------------------------------*/
2474 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2477 * Insert the USB transfer into the queue, if it is not
2478 * already on a USB transfer queue:
2481 KKASSERT(xfer->wait_queue == NULL);
2483 if (xfer->wait_queue == NULL) {
2484 xfer->wait_queue = pq;
2485 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2489 /*------------------------------------------------------------------------*
2490 * usbd_transfer_done
2492 * - This function is used to remove an USB transfer from the busdma,
2493 * pipe or interrupt queue.
2495 * - This function is used to queue the USB transfer on the done
2498 * - This function is used to stop any USB transfer timeouts.
2499 *------------------------------------------------------------------------*/
2501 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2503 struct usb_xfer_root *info = xfer->xroot;
2505 USB_BUS_LOCK_ASSERT(info->bus);
2507 DPRINTF("err=%s\n", usbd_errstr(error));
2510 * If we are not transferring then just return.
2511 * This can happen during transfer cancel.
2513 if (!xfer->flags_int.transferring) {
2514 DPRINTF("not transferring\n");
2515 /* end of control transfer, if any */
2516 xfer->flags_int.control_act = 0;
2519 /* only set transfer error, if not already set */
2520 if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2521 xfer->error = error;
2523 /* stop any callouts */
2524 usb_callout_stop(&xfer->timeout_handle);
2527 * If we are waiting on a queue, just remove the USB transfer
2528 * from the queue, if any. We should have the required locks
2529 * locked to do the remove when this function is called.
2531 usbd_transfer_dequeue(xfer);
2534 if (lockowned(xfer->xroot->xfer_lock)) {
2535 struct usb_xfer_queue *pq;
2538 * If the private USB lock is not locked, then we assume
2539 * that the BUS-DMA load stage has been passed:
2543 if (pq->curr == xfer) {
2544 /* start the next BUS-DMA load, if any */
2545 usb_command_wrapper(pq, NULL);
2549 /* keep some statistics */
2551 info->bus->stats_err.uds_requests
2552 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2554 info->bus->stats_ok.uds_requests
2555 [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2558 /* call the USB transfer callback */
2559 usbd_callback_ss_done_defer(xfer);
2562 /*------------------------------------------------------------------------*
2563 * usbd_transfer_start_cb
2565 * This function is called to start the USB transfer when
2566 * "xfer->interval" is greater than zero, and and the endpoint type is
2568 *------------------------------------------------------------------------*/
2570 usbd_transfer_start_cb(void *arg)
2572 struct usb_xfer *xfer = arg;
2573 struct usb_endpoint *ep = xfer->endpoint;
2575 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2580 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2583 /* the transfer can now be cancelled */
2584 xfer->flags_int.can_cancel_immed = 1;
2586 /* start USB transfer, if no error */
2587 if (xfer->error == 0)
2588 (ep->methods->start) (xfer);
2590 /* check for transfer error */
2592 /* some error has happened */
2593 usbd_transfer_done(xfer, 0);
2597 /*------------------------------------------------------------------------*
2598 * usbd_xfer_set_stall
2600 * This function is used to set the stall flag outside the
2601 * callback. This function is NULL safe.
2602 *------------------------------------------------------------------------*/
2604 usbd_xfer_set_stall(struct usb_xfer *xfer)
2610 USB_XFER_LOCK_ASSERT(xfer);
2612 /* avoid any races by locking the USB mutex */
2613 USB_BUS_LOCK(xfer->xroot->bus);
2614 xfer->flags.stall_pipe = 1;
2615 USB_BUS_UNLOCK(xfer->xroot->bus);
2619 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2621 return (xfer->endpoint->is_stalled);
2624 /*------------------------------------------------------------------------*
2625 * usbd_transfer_clear_stall
2627 * This function is used to clear the stall flag outside the
2628 * callback. This function is NULL safe.
2629 *------------------------------------------------------------------------*/
2631 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2637 USB_XFER_LOCK_ASSERT(xfer);
2639 /* avoid any races by locking the USB mutex */
2640 USB_BUS_LOCK(xfer->xroot->bus);
2642 xfer->flags.stall_pipe = 0;
2644 USB_BUS_UNLOCK(xfer->xroot->bus);
2647 /*------------------------------------------------------------------------*
2650 * This function is used to add an USB transfer to the pipe transfer list.
2651 *------------------------------------------------------------------------*/
2653 usbd_pipe_start(struct usb_xfer_queue *pq)
2655 struct usb_endpoint *ep;
2656 struct usb_xfer *xfer;
2660 ep = xfer->endpoint;
2662 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2665 * If the endpoint is already stalled we do nothing !
2667 if (ep->is_stalled) {
2671 * Check if we are supposed to stall the endpoint:
2673 if (xfer->flags.stall_pipe) {
2674 struct usb_device *udev;
2675 struct usb_xfer_root *info;
2677 /* clear stall command */
2678 xfer->flags.stall_pipe = 0;
2680 /* get pointer to USB device */
2685 * Only stall BULK and INTERRUPT endpoints.
2687 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2688 if ((type == UE_BULK) ||
2689 (type == UE_INTERRUPT)) {
2694 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2695 (udev->bus->methods->set_stall) (
2696 udev, ep, &did_stall);
2697 } else if (udev->ctrl_xfer[1]) {
2698 info = udev->ctrl_xfer[1]->xroot;
2700 USB_BUS_NON_GIANT_PROC(info->bus),
2701 &udev->cs_msg[0], &udev->cs_msg[1]);
2703 /* should not happen */
2704 DPRINTFN(0, "No stall handler\n");
2707 * Check if we should stall. Some USB hardware
2708 * handles set- and clear-stall in hardware.
2712 * The transfer will be continued when
2713 * the clear-stall control endpoint
2714 * message is received.
2719 } else if (type == UE_ISOCHRONOUS) {
2722 * Make sure any FIFO overflow or other FIFO
2723 * error conditions go away by resetting the
2724 * endpoint FIFO through the clear stall
2727 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2728 (udev->bus->methods->clear_stall) (udev, ep);
2732 /* Set or clear stall complete - special case */
2733 if (xfer->nframes == 0) {
2734 /* we are complete */
2736 usbd_transfer_done(xfer, 0);
2742 * 1) Start the first transfer queued.
2744 * 2) Re-start the current USB transfer.
2747 * Check if there should be any
2748 * pre transfer start delay:
2750 if (xfer->interval > 0) {
2751 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2752 if ((type == UE_BULK) ||
2753 (type == UE_CONTROL)) {
2754 usbd_transfer_timeout_ms(xfer,
2755 &usbd_transfer_start_cb,
2763 usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2765 /* the transfer can now be cancelled */
2766 xfer->flags_int.can_cancel_immed = 1;
2768 /* start USB transfer, if no error */
2769 if (xfer->error == 0)
2770 (ep->methods->start) (xfer);
2772 /* check for transfer error */
2774 /* some error has happened */
2775 usbd_transfer_done(xfer, 0);
2779 /*------------------------------------------------------------------------*
2780 * usbd_transfer_timeout_ms
2782 * This function is used to setup a timeout on the given USB
2783 * transfer. If the timeout has been deferred the callback given by
2784 * "cb" will get called after "ms" milliseconds.
2785 *------------------------------------------------------------------------*/
2787 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2788 void (*cb) (void *arg), usb_timeout_t ms)
2790 USB_BUS_LOCK_ASSERT(xfer->xroot->bus);
2793 usb_callout_reset(&xfer->timeout_handle,
2794 USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2797 /*------------------------------------------------------------------------*
2798 * usbd_callback_wrapper_sub
2800 * - This function will update variables in an USB transfer after
2801 * that the USB transfer is complete.
2803 * - This function is used to start the next USB transfer on the
2804 * ep transfer queue, if any.
2806 * NOTE: In some special cases the USB transfer will not be removed from
2807 * the pipe queue, but remain first. To enforce USB transfer removal call
2808 * this function passing the error code "USB_ERR_CANCELLED".
2812 * Else: The callback has been deferred.
2813 *------------------------------------------------------------------------*/
2815 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2817 struct usb_endpoint *ep;
2818 struct usb_bus *bus;
2821 bus = xfer->xroot->bus;
2823 if ((!xfer->flags_int.open) &&
2824 (!xfer->flags_int.did_close)) {
2827 (xfer->endpoint->methods->close) (xfer);
2828 USB_BUS_UNLOCK(bus);
2829 /* only close once */
2830 xfer->flags_int.did_close = 1;
2831 return (1); /* wait for new callback */
2834 * If we have a non-hardware induced error we
2835 * need to do the DMA delay!
2837 if (xfer->error != 0 && !xfer->flags_int.did_dma_delay &&
2838 (xfer->error == USB_ERR_CANCELLED ||
2839 xfer->error == USB_ERR_TIMEOUT ||
2840 bus->methods->start_dma_delay != NULL)) {
2844 /* only delay once */
2845 xfer->flags_int.did_dma_delay = 1;
2847 /* we can not cancel this delay */
2848 xfer->flags_int.can_cancel_immed = 0;
2850 temp = usbd_get_dma_delay(xfer->xroot->udev);
2852 DPRINTFN(3, "DMA delay, %u ms, "
2853 "on %p\n", temp, xfer);
2858 * Some hardware solutions have dedicated
2859 * events when it is safe to free DMA'ed
2860 * memory. For the other hardware platforms we
2861 * use a static delay.
2863 if (bus->methods->start_dma_delay != NULL) {
2864 (bus->methods->start_dma_delay) (xfer);
2866 usbd_transfer_timeout_ms(xfer,
2867 (void (*)(void *))&usb_dma_delay_done_cb,
2870 USB_BUS_UNLOCK(bus);
2871 return (1); /* wait for new callback */
2874 /* check actual number of frames */
2875 if (xfer->aframes > xfer->nframes) {
2876 if (xfer->error == 0) {
2877 panic("%s: actual number of frames, %d, is "
2878 "greater than initial number of frames, %d\n",
2879 __func__, xfer->aframes, xfer->nframes);
2881 /* just set some valid value */
2882 xfer->aframes = xfer->nframes;
2885 /* compute actual length */
2888 for (x = 0; x != xfer->aframes; x++) {
2889 xfer->actlen += xfer->frlengths[x];
2893 * Frames that were not transferred get zero actual length in
2894 * case the USB device driver does not check the actual number
2895 * of frames transferred, "xfer->aframes":
2897 for (; x < xfer->nframes; x++) {
2898 usbd_xfer_set_frame_len(xfer, x, 0);
2901 /* check actual length */
2902 if (xfer->actlen > xfer->sumlen) {
2903 if (xfer->error == 0) {
2904 panic("%s: actual length, %d, is greater than "
2905 "initial length, %d\n",
2906 __func__, xfer->actlen, xfer->sumlen);
2908 /* just set some valid value */
2909 xfer->actlen = xfer->sumlen;
2912 DPRINTFN(1, "xfer=%p endpoint=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2913 xfer, xfer->endpoint, xfer->error, xfer->actlen, xfer->sumlen,
2914 xfer->aframes, xfer->nframes);
2917 /* end of control transfer, if any */
2918 xfer->flags_int.control_act = 0;
2920 /* check if we should block the execution queue */
2921 if ((xfer->error != USB_ERR_CANCELLED) &&
2922 (xfer->flags.pipe_bof)) {
2923 DPRINTFN(2, "xfer=%p: Block On Failure "
2924 "on endpoint=%p\n", xfer, xfer->endpoint);
2928 /* check for short transfers */
2929 if (xfer->actlen < xfer->sumlen) {
2931 /* end of control transfer, if any */
2932 xfer->flags_int.control_act = 0;
2934 if (!xfer->flags_int.short_xfer_ok) {
2935 xfer->error = USB_ERR_SHORT_XFER;
2936 if (xfer->flags.pipe_bof) {
2937 DPRINTFN(2, "xfer=%p: Block On Failure on "
2938 "Short Transfer on endpoint %p.\n",
2939 xfer, xfer->endpoint);
2945 * Check if we are in the middle of a
2948 if (xfer->flags_int.control_act) {
2949 DPRINTFN(5, "xfer=%p: Control transfer "
2950 "active on endpoint=%p\n", xfer, xfer->endpoint);
2956 ep = xfer->endpoint;
2959 * If the current USB transfer is completing we need to start the
2963 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2964 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
2966 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
2967 TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
2968 /* there is another USB transfer waiting */
2970 /* this is the last USB transfer */
2971 /* clear isochronous sync flag */
2972 xfer->endpoint->is_synced = 0;
2975 USB_BUS_UNLOCK(bus);
2980 /*------------------------------------------------------------------------*
2981 * usb_command_wrapper
2983 * This function is used to execute commands non-recursivly on an USB
2985 *------------------------------------------------------------------------*/
2987 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2991 * If the transfer is not already processing,
2994 if (pq->curr != xfer) {
2995 usbd_transfer_enqueue(pq, xfer);
2996 if (pq->curr != NULL) {
2997 /* something is already processing */
2998 DPRINTFN(6, "busy %p\n", pq->curr);
3003 /* Get next element in queue */
3007 if (!pq->recurse_1) {
3011 /* set both recurse flags */
3015 if (pq->curr == NULL) {
3016 xfer = TAILQ_FIRST(&pq->head);
3018 TAILQ_REMOVE(&pq->head, xfer,
3020 xfer->wait_queue = NULL;
3026 DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3028 DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3030 } while (!pq->recurse_2);
3032 /* clear first recurse flag */
3036 /* clear second recurse flag */
3041 /*------------------------------------------------------------------------*
3042 * usbd_ctrl_transfer_setup
3044 * This function is used to setup the default USB control endpoint
3046 *------------------------------------------------------------------------*/
3048 usbd_ctrl_transfer_setup(struct usb_device *udev)
3050 struct usb_xfer *xfer;
3052 uint8_t iface_index;
3054 /* check for root HUB */
3055 if (udev->parent_hub == NULL)
3059 xfer = udev->ctrl_xfer[0];
3061 USB_XFER_LOCK(xfer);
3063 ((xfer->address == udev->address) &&
3064 (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3065 udev->ddesc.bMaxPacketSize));
3066 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3069 * NOTE: checking "xfer->address" and
3070 * starting the USB transfer must be
3073 usbd_transfer_start(xfer);
3076 USB_XFER_UNLOCK(xfer);
3083 * All parameters are exactly the same like before.
3089 * Update wMaxPacketSize for the default control endpoint:
3091 udev->ctrl_ep_desc.wMaxPacketSize[0] =
3092 udev->ddesc.bMaxPacketSize;
3095 * Unsetup any existing USB transfer:
3097 usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3100 * Reset clear stall error counter.
3102 udev->clear_stall_errors = 0;
3105 * Try to setup a new USB transfer for the
3106 * default control endpoint:
3109 if (usbd_transfer_setup(udev, &iface_index,
3110 udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3111 &udev->device_lock)) {
3112 DPRINTFN(0, "could not setup default "
3119 /*------------------------------------------------------------------------*
3120 * usbd_clear_data_toggle - factored out code
3122 * NOTE: the intention of this function is not to reset the hardware
3124 *------------------------------------------------------------------------*/
3126 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3128 USB_BUS_LOCK_ASSERT(udev->bus);
3130 /* check that we have a valid case */
3131 if (udev->flags.usb_mode == USB_MODE_HOST &&
3132 udev->parent_hub != NULL &&
3133 udev->bus->methods->clear_stall != NULL &&
3134 ep->methods != NULL) {
3135 (udev->bus->methods->clear_stall) (udev, ep);
3139 /*------------------------------------------------------------------------*
3140 * usbd_clear_data_toggle - factored out code
3142 * NOTE: the intention of this function is not to reset the hardware
3143 * data toggle on the USB device side.
3144 *------------------------------------------------------------------------*/
3146 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3148 DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3150 USB_BUS_LOCK(udev->bus);
3151 ep->toggle_next = 0;
3152 /* some hardware needs a callback to clear the data toggle */
3153 usbd_clear_stall_locked(udev, ep);
3154 USB_BUS_UNLOCK(udev->bus);
3157 /*------------------------------------------------------------------------*
3158 * usbd_clear_stall_callback - factored out clear stall callback
3161 * xfer1: Clear Stall Control Transfer
3162 * xfer2: Stalled USB Transfer
3164 * This function is NULL safe.
3170 * Clear stall config example:
3172 * static const struct usb_config my_clearstall = {
3173 * .type = UE_CONTROL,
3175 * .direction = UE_DIR_ANY,
3176 * .interval = 50, //50 milliseconds
3177 * .bufsize = sizeof(struct usb_device_request),
3178 * .timeout = 1000, //1.000 seconds
3179 * .callback = &my_clear_stall_callback, // **
3180 * .usb_mode = USB_MODE_HOST,
3183 * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3184 * passing the correct parameters.
3185 *------------------------------------------------------------------------*/
3187 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3188 struct usb_xfer *xfer2)
3190 struct usb_device_request req;
3192 if (xfer2 == NULL) {
3193 /* looks like we are tearing down */
3194 DPRINTF("NULL input parameter\n");
3197 USB_XFER_LOCK_ASSERT(xfer1);
3198 USB_XFER_LOCK_ASSERT(xfer2);
3200 switch (USB_GET_STATE(xfer1)) {
3204 * pre-clear the data toggle to DATA0 ("umass.c" and
3205 * "ata-usb.c" depends on this)
3208 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3210 /* setup a clear-stall packet */
3212 req.bmRequestType = UT_WRITE_ENDPOINT;
3213 req.bRequest = UR_CLEAR_FEATURE;
3214 USETW(req.wValue, UF_ENDPOINT_HALT);
3215 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3217 USETW(req.wLength, 0);
3220 * "usbd_transfer_setup_sub()" will ensure that
3221 * we have sufficient room in the buffer for
3222 * the request structure!
3225 /* copy in the transfer */
3227 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3230 xfer1->frlengths[0] = sizeof(req);
3233 usbd_transfer_submit(xfer1);
3236 case USB_ST_TRANSFERRED:
3239 default: /* Error */
3240 if (xfer1->error == USB_ERR_CANCELLED) {
3245 return (1); /* Clear Stall Finished */
3248 /*------------------------------------------------------------------------*
3249 * usbd_transfer_poll
3251 * The following function gets called from the USB keyboard driver and
3252 * UMASS when the system has paniced.
3254 * NOTE: It is currently not possible to resume normal operation on
3255 * the USB controller which has been polled, due to clearing of the
3256 * "up_dsleep" and "up_msleep" flags.
3257 *------------------------------------------------------------------------*/
3259 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3261 struct usb_xfer *xfer;
3262 struct usb_xfer_root *xroot;
3263 struct usb_device *udev;
3264 struct usb_proc_msg *pm;
3269 for (n = 0; n != max; n++) {
3270 /* Extra checks to avoid panic */
3273 continue; /* no USB transfer */
3274 xroot = xfer->xroot;
3276 continue; /* no USB root */
3279 continue; /* no USB device */
3280 if (udev->bus == NULL)
3281 continue; /* no BUS structure */
3282 if (udev->bus->methods == NULL)
3283 continue; /* no BUS methods */
3284 if (udev->bus->methods->xfer_poll == NULL)
3285 continue; /* no poll method */
3287 /* make sure that the BUS mutex is not locked */
3289 while (lockowned(&xroot->udev->bus->bus_lock)) {
3290 lockmgr(&xroot->udev->bus->bus_lock, LK_RELEASE);
3294 /* make sure that the transfer mutex is not locked */
3296 while (lockowned(xroot->xfer_lock)) {
3297 lockmgr(xroot->xfer_lock, LK_RELEASE);
3301 /* Make sure cv_signal() and cv_broadcast() is not called */
3302 USB_BUS_CONTROL_XFER_PROC(udev->bus)->up_msleep = 0;
3303 USB_BUS_EXPLORE_PROC(udev->bus)->up_msleep = 0;
3304 USB_BUS_GIANT_PROC(udev->bus)->up_msleep = 0;
3305 USB_BUS_NON_GIANT_PROC(udev->bus)->up_msleep = 0;
3307 /* poll USB hardware */
3308 (udev->bus->methods->xfer_poll) (udev->bus);
3310 USB_BUS_LOCK(xroot->bus);
3312 /* check for clear stall */
3313 if (udev->ctrl_xfer[1] != NULL) {
3315 /* poll clear stall start */
3316 pm = &udev->cs_msg[0].hdr;
3317 (pm->pm_callback) (pm);
3318 /* poll clear stall done thread */
3319 pm = &udev->ctrl_xfer[1]->
3320 xroot->done_m[0].hdr;
3321 (pm->pm_callback) (pm);
3324 /* poll done thread */
3325 pm = &xroot->done_m[0].hdr;
3326 (pm->pm_callback) (pm);
3328 USB_BUS_UNLOCK(xroot->bus);
3330 /* restore transfer mutex */
3332 lockmgr(xroot->xfer_lock, LK_EXCLUSIVE);
3334 /* restore BUS mutex */
3336 lockmgr(&xroot->udev->bus->bus_lock, LK_EXCLUSIVE);
3341 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3342 uint8_t type, enum usb_dev_speed speed)
3344 static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3345 [USB_SPEED_LOW] = 8,
3346 [USB_SPEED_FULL] = 64,
3347 [USB_SPEED_HIGH] = 1024,
3348 [USB_SPEED_VARIABLE] = 1024,
3349 [USB_SPEED_SUPER] = 1024,
3352 static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3353 [USB_SPEED_LOW] = 0, /* invalid */
3354 [USB_SPEED_FULL] = 1023,
3355 [USB_SPEED_HIGH] = 1024,
3356 [USB_SPEED_VARIABLE] = 3584,
3357 [USB_SPEED_SUPER] = 1024,
3360 static const uint16_t control_min[USB_SPEED_MAX] = {
3361 [USB_SPEED_LOW] = 8,
3362 [USB_SPEED_FULL] = 8,
3363 [USB_SPEED_HIGH] = 64,
3364 [USB_SPEED_VARIABLE] = 512,
3365 [USB_SPEED_SUPER] = 512,
3368 static const uint16_t bulk_min[USB_SPEED_MAX] = {
3369 [USB_SPEED_LOW] = 8,
3370 [USB_SPEED_FULL] = 8,
3371 [USB_SPEED_HIGH] = 512,
3372 [USB_SPEED_VARIABLE] = 512,
3373 [USB_SPEED_SUPER] = 1024,
3378 memset(ptr, 0, sizeof(*ptr));
3382 ptr->range.max = intr_range_max[speed];
3384 case UE_ISOCHRONOUS:
3385 ptr->range.max = isoc_range_max[speed];
3388 if (type == UE_BULK)
3389 temp = bulk_min[speed];
3390 else /* UE_CONTROL */
3391 temp = control_min[speed];
3393 /* default is fixed */
3394 ptr->fixed[0] = temp;
3395 ptr->fixed[1] = temp;
3396 ptr->fixed[2] = temp;
3397 ptr->fixed[3] = temp;
3399 if (speed == USB_SPEED_FULL) {
3400 /* multiple sizes */
3405 if ((speed == USB_SPEED_VARIABLE) &&
3406 (type == UE_BULK)) {
3407 /* multiple sizes */
3408 ptr->fixed[2] = 1024;
3409 ptr->fixed[3] = 1536;
3416 usbd_xfer_softc(struct usb_xfer *xfer)
3418 return (xfer->priv_sc);
3422 usbd_xfer_get_priv(struct usb_xfer *xfer)
3424 return (xfer->priv_fifo);
3428 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3430 xfer->priv_fifo = ptr;
3434 usbd_xfer_state(struct usb_xfer *xfer)
3436 return (xfer->usb_state);
3440 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3443 case USB_FORCE_SHORT_XFER:
3444 xfer->flags.force_short_xfer = 1;
3446 case USB_SHORT_XFER_OK:
3447 xfer->flags.short_xfer_ok = 1;
3449 case USB_MULTI_SHORT_OK:
3450 xfer->flags.short_frames_ok = 1;
3452 case USB_MANUAL_STATUS:
3453 xfer->flags.manual_status = 1;
3459 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3462 case USB_FORCE_SHORT_XFER:
3463 xfer->flags.force_short_xfer = 0;
3465 case USB_SHORT_XFER_OK:
3466 xfer->flags.short_xfer_ok = 0;
3468 case USB_MULTI_SHORT_OK:
3469 xfer->flags.short_frames_ok = 0;
3471 case USB_MANUAL_STATUS:
3472 xfer->flags.manual_status = 0;
3478 * The following function returns in milliseconds when the isochronous
3479 * transfer was completed by the hardware. The returned value wraps
3480 * around 65536 milliseconds.
3483 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3485 return (xfer->isoc_time_complete);
3489 * The following function returns non-zero if the max packet size
3490 * field was clamped to a valid value. Else it returns zero.
3493 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3495 return (xfer->flags_int.maxp_was_clamped);