]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/usb/usb_transfer.c
MFC r286799:
[FreeBSD/stable/10.git] / sys / dev / usb / usb_transfer.c
1 /* $FreeBSD$ */
2 /*-
3  * Copyright (c) 2008 Hans Petter Selasky. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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
24  * SUCH DAMAGE.
25  */
26
27 #ifdef USB_GLOBAL_INCLUDE_FILE
28 #include USB_GLOBAL_INCLUDE_FILE
29 #else
30 #include <sys/stdint.h>
31 #include <sys/stddef.h>
32 #include <sys/param.h>
33 #include <sys/queue.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/bus.h>
38 #include <sys/module.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/condvar.h>
42 #include <sys/sysctl.h>
43 #include <sys/sx.h>
44 #include <sys/unistd.h>
45 #include <sys/callout.h>
46 #include <sys/malloc.h>
47 #include <sys/priv.h>
48 #include <sys/proc.h>
49
50 #include <dev/usb/usb.h>
51 #include <dev/usb/usbdi.h>
52 #include <dev/usb/usbdi_util.h>
53
54 #define USB_DEBUG_VAR usb_debug
55
56 #include <dev/usb/usb_core.h>
57 #include <dev/usb/usb_busdma.h>
58 #include <dev/usb/usb_process.h>
59 #include <dev/usb/usb_transfer.h>
60 #include <dev/usb/usb_device.h>
61 #include <dev/usb/usb_debug.h>
62 #include <dev/usb/usb_util.h>
63
64 #include <dev/usb/usb_controller.h>
65 #include <dev/usb/usb_bus.h>
66 #include <dev/usb/usb_pf.h>
67 #endif                  /* USB_GLOBAL_INCLUDE_FILE */
68
69 struct usb_std_packet_size {
70         struct {
71                 uint16_t min;           /* inclusive */
72                 uint16_t max;           /* inclusive */
73         }       range;
74
75         uint16_t fixed[4];
76 };
77
78 static usb_callback_t usb_request_callback;
79
80 static const struct usb_config usb_control_ep_cfg[USB_CTRL_XFER_MAX] = {
81
82         /* This transfer is used for generic control endpoint transfers */
83
84         [0] = {
85                 .type = UE_CONTROL,
86                 .endpoint = 0x00,       /* Control endpoint */
87                 .direction = UE_DIR_ANY,
88                 .bufsize = USB_EP0_BUFSIZE,     /* bytes */
89                 .flags = {.proxy_buffer = 1,},
90                 .callback = &usb_request_callback,
91                 .usb_mode = USB_MODE_DUAL,      /* both modes */
92         },
93
94         /* This transfer is used for generic clear stall only */
95
96         [1] = {
97                 .type = UE_CONTROL,
98                 .endpoint = 0x00,       /* Control pipe */
99                 .direction = UE_DIR_ANY,
100                 .bufsize = sizeof(struct usb_device_request),
101                 .callback = &usb_do_clear_stall_callback,
102                 .timeout = 1000,        /* 1 second */
103                 .interval = 50, /* 50ms */
104                 .usb_mode = USB_MODE_HOST,
105         },
106 };
107
108 /* function prototypes */
109
110 static void     usbd_update_max_frame_size(struct usb_xfer *);
111 static void     usbd_transfer_unsetup_sub(struct usb_xfer_root *, uint8_t);
112 static void     usbd_control_transfer_init(struct usb_xfer *);
113 static int      usbd_setup_ctrl_transfer(struct usb_xfer *);
114 static void     usb_callback_proc(struct usb_proc_msg *);
115 static void     usbd_callback_ss_done_defer(struct usb_xfer *);
116 static void     usbd_callback_wrapper(struct usb_xfer_queue *);
117 static void     usbd_transfer_start_cb(void *);
118 static uint8_t  usbd_callback_wrapper_sub(struct usb_xfer *);
119 static void     usbd_get_std_packet_size(struct usb_std_packet_size *ptr, 
120                     uint8_t type, enum usb_dev_speed speed);
121
122 /*------------------------------------------------------------------------*
123  *      usb_request_callback
124  *------------------------------------------------------------------------*/
125 static void
126 usb_request_callback(struct usb_xfer *xfer, usb_error_t error)
127 {
128         if (xfer->flags_int.usb_mode == USB_MODE_DEVICE)
129                 usb_handle_request_callback(xfer, error);
130         else
131                 usbd_do_request_callback(xfer, error);
132 }
133
134 /*------------------------------------------------------------------------*
135  *      usbd_update_max_frame_size
136  *
137  * This function updates the maximum frame size, hence high speed USB
138  * can transfer multiple consecutive packets.
139  *------------------------------------------------------------------------*/
140 static void
141 usbd_update_max_frame_size(struct usb_xfer *xfer)
142 {
143         /* compute maximum frame size */
144         /* this computation should not overflow 16-bit */
145         /* max = 15 * 1024 */
146
147         xfer->max_frame_size = xfer->max_packet_size * xfer->max_packet_count;
148 }
149
150 /*------------------------------------------------------------------------*
151  *      usbd_get_dma_delay
152  *
153  * The following function is called when we need to
154  * synchronize with DMA hardware.
155  *
156  * Returns:
157  *    0: no DMA delay required
158  * Else: milliseconds of DMA delay
159  *------------------------------------------------------------------------*/
160 usb_timeout_t
161 usbd_get_dma_delay(struct usb_device *udev)
162 {
163         struct usb_bus_methods *mtod;
164         uint32_t temp;
165
166         mtod = udev->bus->methods;
167         temp = 0;
168
169         if (mtod->get_dma_delay) {
170                 (mtod->get_dma_delay) (udev, &temp);
171                 /*
172                  * Round up and convert to milliseconds. Note that we use
173                  * 1024 milliseconds per second. to save a division.
174                  */
175                 temp += 0x3FF;
176                 temp /= 0x400;
177         }
178         return (temp);
179 }
180
181 /*------------------------------------------------------------------------*
182  *      usbd_transfer_setup_sub_malloc
183  *
184  * This function will allocate one or more DMA'able memory chunks
185  * according to "size", "align" and "count" arguments. "ppc" is
186  * pointed to a linear array of USB page caches afterwards.
187  *
188  * If the "align" argument is equal to "1" a non-contiguous allocation
189  * can happen. Else if the "align" argument is greater than "1", the
190  * allocation will always be contiguous in memory.
191  *
192  * Returns:
193  *    0: Success
194  * Else: Failure
195  *------------------------------------------------------------------------*/
196 #if USB_HAVE_BUSDMA
197 uint8_t
198 usbd_transfer_setup_sub_malloc(struct usb_setup_params *parm,
199     struct usb_page_cache **ppc, usb_size_t size, usb_size_t align,
200     usb_size_t count)
201 {
202         struct usb_page_cache *pc;
203         struct usb_page *pg;
204         void *buf;
205         usb_size_t n_dma_pc;
206         usb_size_t n_dma_pg;
207         usb_size_t n_obj;
208         usb_size_t x;
209         usb_size_t y;
210         usb_size_t r;
211         usb_size_t z;
212
213         USB_ASSERT(align > 0, ("Invalid alignment, 0x%08x\n",
214             align));
215         USB_ASSERT(size > 0, ("Invalid size = 0\n"));
216
217         if (count == 0) {
218                 return (0);             /* nothing to allocate */
219         }
220         /*
221          * Make sure that the size is aligned properly.
222          */
223         size = -((-size) & (-align));
224
225         /*
226          * Try multi-allocation chunks to reduce the number of DMA
227          * allocations, hence DMA allocations are slow.
228          */
229         if (align == 1) {
230                 /* special case - non-cached multi page DMA memory */
231                 n_dma_pc = count;
232                 n_dma_pg = (2 + (size / USB_PAGE_SIZE));
233                 n_obj = 1;
234         } else if (size >= USB_PAGE_SIZE) {
235                 n_dma_pc = count;
236                 n_dma_pg = 1;
237                 n_obj = 1;
238         } else {
239                 /* compute number of objects per page */
240 #ifdef USB_DMA_SINGLE_ALLOC
241                 n_obj = 1;
242 #else
243                 n_obj = (USB_PAGE_SIZE / size);
244 #endif
245                 /*
246                  * Compute number of DMA chunks, rounded up
247                  * to nearest one:
248                  */
249                 n_dma_pc = ((count + n_obj - 1) / n_obj);
250                 n_dma_pg = 1;
251         }
252
253         /*
254          * DMA memory is allocated once, but mapped twice. That's why
255          * there is one list for auto-free and another list for
256          * non-auto-free which only holds the mapping and not the
257          * allocation.
258          */
259         if (parm->buf == NULL) {
260                 /* reserve memory (auto-free) */
261                 parm->dma_page_ptr += n_dma_pc * n_dma_pg;
262                 parm->dma_page_cache_ptr += n_dma_pc;
263
264                 /* reserve memory (no-auto-free) */
265                 parm->dma_page_ptr += count * n_dma_pg;
266                 parm->xfer_page_cache_ptr += count;
267                 return (0);
268         }
269         for (x = 0; x != n_dma_pc; x++) {
270                 /* need to initialize the page cache */
271                 parm->dma_page_cache_ptr[x].tag_parent =
272                     &parm->curr_xfer->xroot->dma_parent_tag;
273         }
274         for (x = 0; x != count; x++) {
275                 /* need to initialize the page cache */
276                 parm->xfer_page_cache_ptr[x].tag_parent =
277                     &parm->curr_xfer->xroot->dma_parent_tag;
278         }
279
280         if (ppc != NULL) {
281                 if (n_obj != 1)
282                         *ppc = parm->xfer_page_cache_ptr;
283                 else
284                         *ppc = parm->dma_page_cache_ptr;
285         }
286         r = count;                      /* set remainder count */
287         z = n_obj * size;               /* set allocation size */
288         pc = parm->xfer_page_cache_ptr;
289         pg = parm->dma_page_ptr;
290
291         if (n_obj == 1) {
292             /*
293              * Avoid mapping memory twice if only a single object
294              * should be allocated per page cache:
295              */
296             for (x = 0; x != n_dma_pc; x++) {
297                 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
298                     pg, z, align)) {
299                         return (1);     /* failure */
300                 }
301                 /* Make room for one DMA page cache and "n_dma_pg" pages */
302                 parm->dma_page_cache_ptr++;
303                 pg += n_dma_pg;
304             }
305         } else {
306             for (x = 0; x != n_dma_pc; x++) {
307
308                 if (r < n_obj) {
309                         /* compute last remainder */
310                         z = r * size;
311                         n_obj = r;
312                 }
313                 if (usb_pc_alloc_mem(parm->dma_page_cache_ptr,
314                     pg, z, align)) {
315                         return (1);     /* failure */
316                 }
317                 /* Set beginning of current buffer */
318                 buf = parm->dma_page_cache_ptr->buffer;
319                 /* Make room for one DMA page cache and "n_dma_pg" pages */
320                 parm->dma_page_cache_ptr++;
321                 pg += n_dma_pg;
322
323                 for (y = 0; (y != n_obj); y++, r--, pc++, pg += n_dma_pg) {
324
325                         /* Load sub-chunk into DMA */
326                         if (usb_pc_dmamap_create(pc, size)) {
327                                 return (1);     /* failure */
328                         }
329                         pc->buffer = USB_ADD_BYTES(buf, y * size);
330                         pc->page_start = pg;
331
332                         mtx_lock(pc->tag_parent->mtx);
333                         if (usb_pc_load_mem(pc, size, 1 /* synchronous */ )) {
334                                 mtx_unlock(pc->tag_parent->mtx);
335                                 return (1);     /* failure */
336                         }
337                         mtx_unlock(pc->tag_parent->mtx);
338                 }
339             }
340         }
341
342         parm->xfer_page_cache_ptr = pc;
343         parm->dma_page_ptr = pg;
344         return (0);
345 }
346 #endif
347
348 /*------------------------------------------------------------------------*
349  *      usbd_transfer_setup_sub - transfer setup subroutine
350  *
351  * This function must be called from the "xfer_setup" callback of the
352  * USB Host or Device controller driver when setting up an USB
353  * transfer. This function will setup correct packet sizes, buffer
354  * sizes, flags and more, that are stored in the "usb_xfer"
355  * structure.
356  *------------------------------------------------------------------------*/
357 void
358 usbd_transfer_setup_sub(struct usb_setup_params *parm)
359 {
360         enum {
361                 REQ_SIZE = 8,
362                 MIN_PKT = 8,
363         };
364         struct usb_xfer *xfer = parm->curr_xfer;
365         const struct usb_config *setup = parm->curr_setup;
366         struct usb_endpoint_ss_comp_descriptor *ecomp;
367         struct usb_endpoint_descriptor *edesc;
368         struct usb_std_packet_size std_size;
369         usb_frcount_t n_frlengths;
370         usb_frcount_t n_frbuffers;
371         usb_frcount_t x;
372         uint16_t maxp_old;
373         uint8_t type;
374         uint8_t zmps;
375
376         /*
377          * Sanity check. The following parameters must be initialized before
378          * calling this function.
379          */
380         if ((parm->hc_max_packet_size == 0) ||
381             (parm->hc_max_packet_count == 0) ||
382             (parm->hc_max_frame_size == 0)) {
383                 parm->err = USB_ERR_INVAL;
384                 goto done;
385         }
386         edesc = xfer->endpoint->edesc;
387         ecomp = xfer->endpoint->ecomp;
388
389         type = (edesc->bmAttributes & UE_XFERTYPE);
390
391         xfer->flags = setup->flags;
392         xfer->nframes = setup->frames;
393         xfer->timeout = setup->timeout;
394         xfer->callback = setup->callback;
395         xfer->interval = setup->interval;
396         xfer->endpointno = edesc->bEndpointAddress;
397         xfer->max_packet_size = UGETW(edesc->wMaxPacketSize);
398         xfer->max_packet_count = 1;
399         /* make a shadow copy: */
400         xfer->flags_int.usb_mode = parm->udev->flags.usb_mode;
401
402         parm->bufsize = setup->bufsize;
403
404         switch (parm->speed) {
405         case USB_SPEED_HIGH:
406                 switch (type) {
407                 case UE_ISOCHRONOUS:
408                 case UE_INTERRUPT:
409                         xfer->max_packet_count +=
410                             (xfer->max_packet_size >> 11) & 3;
411
412                         /* check for invalid max packet count */
413                         if (xfer->max_packet_count > 3)
414                                 xfer->max_packet_count = 3;
415                         break;
416                 default:
417                         break;
418                 }
419                 xfer->max_packet_size &= 0x7FF;
420                 break;
421         case USB_SPEED_SUPER:
422                 xfer->max_packet_count += (xfer->max_packet_size >> 11) & 3;
423
424                 if (ecomp != NULL)
425                         xfer->max_packet_count += ecomp->bMaxBurst;
426
427                 if ((xfer->max_packet_count == 0) || 
428                     (xfer->max_packet_count > 16))
429                         xfer->max_packet_count = 16;
430
431                 switch (type) {
432                 case UE_CONTROL:
433                         xfer->max_packet_count = 1;
434                         break;
435                 case UE_ISOCHRONOUS:
436                         if (ecomp != NULL) {
437                                 uint8_t mult;
438
439                                 mult = UE_GET_SS_ISO_MULT(
440                                     ecomp->bmAttributes) + 1;
441                                 if (mult > 3)
442                                         mult = 3;
443
444                                 xfer->max_packet_count *= mult;
445                         }
446                         break;
447                 default:
448                         break;
449                 }
450                 xfer->max_packet_size &= 0x7FF;
451                 break;
452         default:
453                 break;
454         }
455         /* range check "max_packet_count" */
456
457         if (xfer->max_packet_count > parm->hc_max_packet_count) {
458                 xfer->max_packet_count = parm->hc_max_packet_count;
459         }
460
461         /* store max packet size value before filtering */
462
463         maxp_old = xfer->max_packet_size;
464
465         /* filter "wMaxPacketSize" according to HC capabilities */
466
467         if ((xfer->max_packet_size > parm->hc_max_packet_size) ||
468             (xfer->max_packet_size == 0)) {
469                 xfer->max_packet_size = parm->hc_max_packet_size;
470         }
471         /* filter "wMaxPacketSize" according to standard sizes */
472
473         usbd_get_std_packet_size(&std_size, type, parm->speed);
474
475         if (std_size.range.min || std_size.range.max) {
476
477                 if (xfer->max_packet_size < std_size.range.min) {
478                         xfer->max_packet_size = std_size.range.min;
479                 }
480                 if (xfer->max_packet_size > std_size.range.max) {
481                         xfer->max_packet_size = std_size.range.max;
482                 }
483         } else {
484
485                 if (xfer->max_packet_size >= std_size.fixed[3]) {
486                         xfer->max_packet_size = std_size.fixed[3];
487                 } else if (xfer->max_packet_size >= std_size.fixed[2]) {
488                         xfer->max_packet_size = std_size.fixed[2];
489                 } else if (xfer->max_packet_size >= std_size.fixed[1]) {
490                         xfer->max_packet_size = std_size.fixed[1];
491                 } else {
492                         /* only one possibility left */
493                         xfer->max_packet_size = std_size.fixed[0];
494                 }
495         }
496
497         /*
498          * Check if the max packet size was outside its allowed range
499          * and clamped to a valid value:
500          */
501         if (maxp_old != xfer->max_packet_size)
502                 xfer->flags_int.maxp_was_clamped = 1;
503         
504         /* compute "max_frame_size" */
505
506         usbd_update_max_frame_size(xfer);
507
508         /* check interrupt interval and transfer pre-delay */
509
510         if (type == UE_ISOCHRONOUS) {
511
512                 uint16_t frame_limit;
513
514                 xfer->interval = 0;     /* not used, must be zero */
515                 xfer->flags_int.isochronous_xfr = 1;    /* set flag */
516
517                 if (xfer->timeout == 0) {
518                         /*
519                          * set a default timeout in
520                          * case something goes wrong!
521                          */
522                         xfer->timeout = 1000 / 4;
523                 }
524                 switch (parm->speed) {
525                 case USB_SPEED_LOW:
526                 case USB_SPEED_FULL:
527                         frame_limit = USB_MAX_FS_ISOC_FRAMES_PER_XFER;
528                         xfer->fps_shift = 0;
529                         break;
530                 default:
531                         frame_limit = USB_MAX_HS_ISOC_FRAMES_PER_XFER;
532                         xfer->fps_shift = edesc->bInterval;
533                         if (xfer->fps_shift > 0)
534                                 xfer->fps_shift--;
535                         if (xfer->fps_shift > 3)
536                                 xfer->fps_shift = 3;
537                         if (xfer->flags.pre_scale_frames != 0)
538                                 xfer->nframes <<= (3 - xfer->fps_shift);
539                         break;
540                 }
541
542                 if (xfer->nframes > frame_limit) {
543                         /*
544                          * this is not going to work
545                          * cross hardware
546                          */
547                         parm->err = USB_ERR_INVAL;
548                         goto done;
549                 }
550                 if (xfer->nframes == 0) {
551                         /*
552                          * this is not a valid value
553                          */
554                         parm->err = USB_ERR_ZERO_NFRAMES;
555                         goto done;
556                 }
557         } else {
558
559                 /*
560                  * If a value is specified use that else check the
561                  * endpoint descriptor!
562                  */
563                 if (type == UE_INTERRUPT) {
564
565                         uint32_t temp;
566
567                         if (xfer->interval == 0) {
568
569                                 xfer->interval = edesc->bInterval;
570
571                                 switch (parm->speed) {
572                                 case USB_SPEED_LOW:
573                                 case USB_SPEED_FULL:
574                                         break;
575                                 default:
576                                         /* 125us -> 1ms */
577                                         if (xfer->interval < 4)
578                                                 xfer->interval = 1;
579                                         else if (xfer->interval > 16)
580                                                 xfer->interval = (1 << (16 - 4));
581                                         else
582                                                 xfer->interval = 
583                                                     (1 << (xfer->interval - 4));
584                                         break;
585                                 }
586                         }
587
588                         if (xfer->interval == 0) {
589                                 /*
590                                  * One millisecond is the smallest
591                                  * interval we support:
592                                  */
593                                 xfer->interval = 1;
594                         }
595
596                         xfer->fps_shift = 0;
597                         temp = 1;
598
599                         while ((temp != 0) && (temp < xfer->interval)) {
600                                 xfer->fps_shift++;
601                                 temp *= 2;
602                         }
603
604                         switch (parm->speed) {
605                         case USB_SPEED_LOW:
606                         case USB_SPEED_FULL:
607                                 break;
608                         default:
609                                 xfer->fps_shift += 3;
610                                 break;
611                         }
612                 }
613         }
614
615         /*
616          * NOTE: we do not allow "max_packet_size" or "max_frame_size"
617          * to be equal to zero when setting up USB transfers, hence
618          * this leads to alot of extra code in the USB kernel.
619          */
620
621         if ((xfer->max_frame_size == 0) ||
622             (xfer->max_packet_size == 0)) {
623
624                 zmps = 1;
625
626                 if ((parm->bufsize <= MIN_PKT) &&
627                     (type != UE_CONTROL) &&
628                     (type != UE_BULK)) {
629
630                         /* workaround */
631                         xfer->max_packet_size = MIN_PKT;
632                         xfer->max_packet_count = 1;
633                         parm->bufsize = 0;      /* automatic setup length */
634                         usbd_update_max_frame_size(xfer);
635
636                 } else {
637                         parm->err = USB_ERR_ZERO_MAXP;
638                         goto done;
639                 }
640
641         } else {
642                 zmps = 0;
643         }
644
645         /*
646          * check if we should setup a default
647          * length:
648          */
649
650         if (parm->bufsize == 0) {
651
652                 parm->bufsize = xfer->max_frame_size;
653
654                 if (type == UE_ISOCHRONOUS) {
655                         parm->bufsize *= xfer->nframes;
656                 }
657         }
658         /*
659          * check if we are about to setup a proxy
660          * type of buffer:
661          */
662
663         if (xfer->flags.proxy_buffer) {
664
665                 /* round bufsize up */
666
667                 parm->bufsize += (xfer->max_frame_size - 1);
668
669                 if (parm->bufsize < xfer->max_frame_size) {
670                         /* length wrapped around */
671                         parm->err = USB_ERR_INVAL;
672                         goto done;
673                 }
674                 /* subtract remainder */
675
676                 parm->bufsize -= (parm->bufsize % xfer->max_frame_size);
677
678                 /* add length of USB device request structure, if any */
679
680                 if (type == UE_CONTROL) {
681                         parm->bufsize += REQ_SIZE;      /* SETUP message */
682                 }
683         }
684         xfer->max_data_length = parm->bufsize;
685
686         /* Setup "n_frlengths" and "n_frbuffers" */
687
688         if (type == UE_ISOCHRONOUS) {
689                 n_frlengths = xfer->nframes;
690                 n_frbuffers = 1;
691         } else {
692
693                 if (type == UE_CONTROL) {
694                         xfer->flags_int.control_xfr = 1;
695                         if (xfer->nframes == 0) {
696                                 if (parm->bufsize <= REQ_SIZE) {
697                                         /*
698                                          * there will never be any data
699                                          * stage
700                                          */
701                                         xfer->nframes = 1;
702                                 } else {
703                                         xfer->nframes = 2;
704                                 }
705                         }
706                 } else {
707                         if (xfer->nframes == 0) {
708                                 xfer->nframes = 1;
709                         }
710                 }
711
712                 n_frlengths = xfer->nframes;
713                 n_frbuffers = xfer->nframes;
714         }
715
716         /*
717          * check if we have room for the
718          * USB device request structure:
719          */
720
721         if (type == UE_CONTROL) {
722
723                 if (xfer->max_data_length < REQ_SIZE) {
724                         /* length wrapped around or too small bufsize */
725                         parm->err = USB_ERR_INVAL;
726                         goto done;
727                 }
728                 xfer->max_data_length -= REQ_SIZE;
729         }
730         /*
731          * Setup "frlengths" and shadow "frlengths" for keeping the
732          * initial frame lengths when a USB transfer is complete. This
733          * information is useful when computing isochronous offsets.
734          */
735         xfer->frlengths = parm->xfer_length_ptr;
736         parm->xfer_length_ptr += 2 * n_frlengths;
737
738         /* setup "frbuffers" */
739         xfer->frbuffers = parm->xfer_page_cache_ptr;
740         parm->xfer_page_cache_ptr += n_frbuffers;
741
742         /* initialize max frame count */
743         xfer->max_frame_count = xfer->nframes;
744
745         /*
746          * check if we need to setup
747          * a local buffer:
748          */
749
750         if (!xfer->flags.ext_buffer) {
751 #if USB_HAVE_BUSDMA
752                 struct usb_page_search page_info;
753                 struct usb_page_cache *pc;
754
755                 if (usbd_transfer_setup_sub_malloc(parm,
756                     &pc, parm->bufsize, 1, 1)) {
757                         parm->err = USB_ERR_NOMEM;
758                 } else if (parm->buf != NULL) {
759
760                         usbd_get_page(pc, 0, &page_info);
761
762                         xfer->local_buffer = page_info.buffer;
763
764                         usbd_xfer_set_frame_offset(xfer, 0, 0);
765
766                         if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
767                                 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
768                         }
769                 }
770 #else
771                 /* align data */
772                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
773
774                 if (parm->buf != NULL) {
775                         xfer->local_buffer =
776                             USB_ADD_BYTES(parm->buf, parm->size[0]);
777
778                         usbd_xfer_set_frame_offset(xfer, 0, 0);
779
780                         if ((type == UE_CONTROL) && (n_frbuffers > 1)) {
781                                 usbd_xfer_set_frame_offset(xfer, REQ_SIZE, 1);
782                         }
783                 }
784                 parm->size[0] += parm->bufsize;
785
786                 /* align data again */
787                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
788 #endif
789         }
790         /*
791          * Compute maximum buffer size
792          */
793
794         if (parm->bufsize_max < parm->bufsize) {
795                 parm->bufsize_max = parm->bufsize;
796         }
797 #if USB_HAVE_BUSDMA
798         if (xfer->flags_int.bdma_enable) {
799                 /*
800                  * Setup "dma_page_ptr".
801                  *
802                  * Proof for formula below:
803                  *
804                  * Assume there are three USB frames having length "a", "b" and
805                  * "c". These USB frames will at maximum need "z"
806                  * "usb_page" structures. "z" is given by:
807                  *
808                  * z = ((a / USB_PAGE_SIZE) + 2) + ((b / USB_PAGE_SIZE) + 2) +
809                  * ((c / USB_PAGE_SIZE) + 2);
810                  *
811                  * Constraining "a", "b" and "c" like this:
812                  *
813                  * (a + b + c) <= parm->bufsize
814                  *
815                  * We know that:
816                  *
817                  * z <= ((parm->bufsize / USB_PAGE_SIZE) + (3*2));
818                  *
819                  * Here is the general formula:
820                  */
821                 xfer->dma_page_ptr = parm->dma_page_ptr;
822                 parm->dma_page_ptr += (2 * n_frbuffers);
823                 parm->dma_page_ptr += (parm->bufsize / USB_PAGE_SIZE);
824         }
825 #endif
826         if (zmps) {
827                 /* correct maximum data length */
828                 xfer->max_data_length = 0;
829         }
830         /* subtract USB frame remainder from "hc_max_frame_size" */
831
832         xfer->max_hc_frame_size =
833             (parm->hc_max_frame_size -
834             (parm->hc_max_frame_size % xfer->max_frame_size));
835
836         if (xfer->max_hc_frame_size == 0) {
837                 parm->err = USB_ERR_INVAL;
838                 goto done;
839         }
840
841         /* initialize frame buffers */
842
843         if (parm->buf) {
844                 for (x = 0; x != n_frbuffers; x++) {
845                         xfer->frbuffers[x].tag_parent =
846                             &xfer->xroot->dma_parent_tag;
847 #if USB_HAVE_BUSDMA
848                         if (xfer->flags_int.bdma_enable &&
849                             (parm->bufsize_max > 0)) {
850
851                                 if (usb_pc_dmamap_create(
852                                     xfer->frbuffers + x,
853                                     parm->bufsize_max)) {
854                                         parm->err = USB_ERR_NOMEM;
855                                         goto done;
856                                 }
857                         }
858 #endif
859                 }
860         }
861 done:
862         if (parm->err) {
863                 /*
864                  * Set some dummy values so that we avoid division by zero:
865                  */
866                 xfer->max_hc_frame_size = 1;
867                 xfer->max_frame_size = 1;
868                 xfer->max_packet_size = 1;
869                 xfer->max_data_length = 0;
870                 xfer->nframes = 0;
871                 xfer->max_frame_count = 0;
872         }
873 }
874
875 /*------------------------------------------------------------------------*
876  *      usbd_transfer_setup - setup an array of USB transfers
877  *
878  * NOTE: You must always call "usbd_transfer_unsetup" after calling
879  * "usbd_transfer_setup" if success was returned.
880  *
881  * The idea is that the USB device driver should pre-allocate all its
882  * transfers by one call to this function.
883  *
884  * Return values:
885  *    0: Success
886  * Else: Failure
887  *------------------------------------------------------------------------*/
888 usb_error_t
889 usbd_transfer_setup(struct usb_device *udev,
890     const uint8_t *ifaces, struct usb_xfer **ppxfer,
891     const struct usb_config *setup_start, uint16_t n_setup,
892     void *priv_sc, struct mtx *xfer_mtx)
893 {
894         const struct usb_config *setup_end = setup_start + n_setup;
895         const struct usb_config *setup;
896         struct usb_setup_params *parm;
897         struct usb_endpoint *ep;
898         struct usb_xfer_root *info;
899         struct usb_xfer *xfer;
900         void *buf = NULL;
901         usb_error_t error = 0;
902         uint16_t n;
903         uint16_t refcount;
904         uint8_t do_unlock;
905
906         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
907             "usbd_transfer_setup can sleep!");
908
909         /* do some checking first */
910
911         if (n_setup == 0) {
912                 DPRINTFN(6, "setup array has zero length!\n");
913                 return (USB_ERR_INVAL);
914         }
915         if (ifaces == 0) {
916                 DPRINTFN(6, "ifaces array is NULL!\n");
917                 return (USB_ERR_INVAL);
918         }
919         if (xfer_mtx == NULL) {
920                 DPRINTFN(6, "using global lock\n");
921                 xfer_mtx = &Giant;
922         }
923
924         /* more sanity checks */
925
926         for (setup = setup_start, n = 0;
927             setup != setup_end; setup++, n++) {
928                 if (setup->bufsize == (usb_frlength_t)-1) {
929                         error = USB_ERR_BAD_BUFSIZE;
930                         DPRINTF("invalid bufsize\n");
931                 }
932                 if (setup->callback == NULL) {
933                         error = USB_ERR_NO_CALLBACK;
934                         DPRINTF("no callback\n");
935                 }
936                 ppxfer[n] = NULL;
937         }
938
939         if (error)
940                 return (error);
941
942         /* Protect scratch area */
943         do_unlock = usbd_enum_lock(udev);
944
945         refcount = 0;
946         info = NULL;
947
948         parm = &udev->scratch.xfer_setup[0].parm;
949         memset(parm, 0, sizeof(*parm));
950
951         parm->udev = udev;
952         parm->speed = usbd_get_speed(udev);
953         parm->hc_max_packet_count = 1;
954
955         if (parm->speed >= USB_SPEED_MAX) {
956                 parm->err = USB_ERR_INVAL;
957                 goto done;
958         }
959         /* setup all transfers */
960
961         while (1) {
962
963                 if (buf) {
964                         /*
965                          * Initialize the "usb_xfer_root" structure,
966                          * which is common for all our USB transfers.
967                          */
968                         info = USB_ADD_BYTES(buf, 0);
969
970                         info->memory_base = buf;
971                         info->memory_size = parm->size[0];
972
973 #if USB_HAVE_BUSDMA
974                         info->dma_page_cache_start = USB_ADD_BYTES(buf, parm->size[4]);
975                         info->dma_page_cache_end = USB_ADD_BYTES(buf, parm->size[5]);
976 #endif
977                         info->xfer_page_cache_start = USB_ADD_BYTES(buf, parm->size[5]);
978                         info->xfer_page_cache_end = USB_ADD_BYTES(buf, parm->size[2]);
979
980                         cv_init(&info->cv_drain, "WDRAIN");
981
982                         info->xfer_mtx = xfer_mtx;
983 #if USB_HAVE_BUSDMA
984                         usb_dma_tag_setup(&info->dma_parent_tag,
985                             parm->dma_tag_p, udev->bus->dma_parent_tag[0].tag,
986                             xfer_mtx, &usb_bdma_done_event, udev->bus->dma_bits,
987                             parm->dma_tag_max);
988 #endif
989
990                         info->bus = udev->bus;
991                         info->udev = udev;
992
993                         TAILQ_INIT(&info->done_q.head);
994                         info->done_q.command = &usbd_callback_wrapper;
995 #if USB_HAVE_BUSDMA
996                         TAILQ_INIT(&info->dma_q.head);
997                         info->dma_q.command = &usb_bdma_work_loop;
998 #endif
999                         info->done_m[0].hdr.pm_callback = &usb_callback_proc;
1000                         info->done_m[0].xroot = info;
1001                         info->done_m[1].hdr.pm_callback = &usb_callback_proc;
1002                         info->done_m[1].xroot = info;
1003
1004                         /* 
1005                          * In device side mode control endpoint
1006                          * requests need to run from a separate
1007                          * context, else there is a chance of
1008                          * deadlock!
1009                          */
1010                         if (setup_start == usb_control_ep_cfg)
1011                                 info->done_p =
1012                                     USB_BUS_CONTROL_XFER_PROC(udev->bus);
1013                         else if (xfer_mtx == &Giant)
1014                                 info->done_p =
1015                                     USB_BUS_GIANT_PROC(udev->bus);
1016                         else
1017                                 info->done_p =
1018                                     USB_BUS_NON_GIANT_PROC(udev->bus);
1019                 }
1020                 /* reset sizes */
1021
1022                 parm->size[0] = 0;
1023                 parm->buf = buf;
1024                 parm->size[0] += sizeof(info[0]);
1025
1026                 for (setup = setup_start, n = 0;
1027                     setup != setup_end; setup++, n++) {
1028
1029                         /* skip USB transfers without callbacks: */
1030                         if (setup->callback == NULL) {
1031                                 continue;
1032                         }
1033                         /* see if there is a matching endpoint */
1034                         ep = usbd_get_endpoint(udev,
1035                             ifaces[setup->if_index], setup);
1036
1037                         /*
1038                          * Check that the USB PIPE is valid and that
1039                          * the endpoint mode is proper.
1040                          *
1041                          * Make sure we don't allocate a streams
1042                          * transfer when such a combination is not
1043                          * valid.
1044                          */
1045                         if ((ep == NULL) || (ep->methods == NULL) ||
1046                             ((ep->ep_mode != USB_EP_MODE_STREAMS) &&
1047                             (ep->ep_mode != USB_EP_MODE_DEFAULT)) ||
1048                             (setup->stream_id != 0 &&
1049                             (setup->stream_id >= USB_MAX_EP_STREAMS ||
1050                             (ep->ep_mode != USB_EP_MODE_STREAMS)))) {
1051                                 if (setup->flags.no_pipe_ok)
1052                                         continue;
1053                                 if ((setup->usb_mode != USB_MODE_DUAL) &&
1054                                     (setup->usb_mode != udev->flags.usb_mode))
1055                                         continue;
1056                                 parm->err = USB_ERR_NO_PIPE;
1057                                 goto done;
1058                         }
1059
1060                         /* align data properly */
1061                         parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1062
1063                         /* store current setup pointer */
1064                         parm->curr_setup = setup;
1065
1066                         if (buf) {
1067                                 /*
1068                                  * Common initialization of the
1069                                  * "usb_xfer" structure.
1070                                  */
1071                                 xfer = USB_ADD_BYTES(buf, parm->size[0]);
1072                                 xfer->address = udev->address;
1073                                 xfer->priv_sc = priv_sc;
1074                                 xfer->xroot = info;
1075
1076                                 usb_callout_init_mtx(&xfer->timeout_handle,
1077                                     &udev->bus->bus_mtx, 0);
1078                         } else {
1079                                 /*
1080                                  * Setup a dummy xfer, hence we are
1081                                  * writing to the "usb_xfer"
1082                                  * structure pointed to by "xfer"
1083                                  * before we have allocated any
1084                                  * memory:
1085                                  */
1086                                 xfer = &udev->scratch.xfer_setup[0].dummy;
1087                                 memset(xfer, 0, sizeof(*xfer));
1088                                 refcount++;
1089                         }
1090
1091                         /* set transfer endpoint pointer */
1092                         xfer->endpoint = ep;
1093
1094                         /* set transfer stream ID */
1095                         xfer->stream_id = setup->stream_id;
1096
1097                         parm->size[0] += sizeof(xfer[0]);
1098                         parm->methods = xfer->endpoint->methods;
1099                         parm->curr_xfer = xfer;
1100
1101                         /*
1102                          * Call the Host or Device controller transfer
1103                          * setup routine:
1104                          */
1105                         (udev->bus->methods->xfer_setup) (parm);
1106
1107                         /* check for error */
1108                         if (parm->err)
1109                                 goto done;
1110
1111                         if (buf) {
1112                                 /*
1113                                  * Increment the endpoint refcount. This
1114                                  * basically prevents setting a new
1115                                  * configuration and alternate setting
1116                                  * when USB transfers are in use on
1117                                  * the given interface. Search the USB
1118                                  * code for "endpoint->refcount_alloc" if you
1119                                  * want more information.
1120                                  */
1121                                 USB_BUS_LOCK(info->bus);
1122                                 if (xfer->endpoint->refcount_alloc >= USB_EP_REF_MAX)
1123                                         parm->err = USB_ERR_INVAL;
1124
1125                                 xfer->endpoint->refcount_alloc++;
1126
1127                                 if (xfer->endpoint->refcount_alloc == 0)
1128                                         panic("usbd_transfer_setup(): Refcount wrapped to zero\n");
1129                                 USB_BUS_UNLOCK(info->bus);
1130
1131                                 /*
1132                                  * Whenever we set ppxfer[] then we
1133                                  * also need to increment the
1134                                  * "setup_refcount":
1135                                  */
1136                                 info->setup_refcount++;
1137
1138                                 /*
1139                                  * Transfer is successfully setup and
1140                                  * can be used:
1141                                  */
1142                                 ppxfer[n] = xfer;
1143                         }
1144
1145                         /* check for error */
1146                         if (parm->err)
1147                                 goto done;
1148                 }
1149
1150                 if (buf != NULL || parm->err != 0)
1151                         goto done;
1152
1153                 /* if no transfers, nothing to do */
1154                 if (refcount == 0)
1155                         goto done;
1156
1157                 /* align data properly */
1158                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1159
1160                 /* store offset temporarily */
1161                 parm->size[1] = parm->size[0];
1162
1163                 /*
1164                  * The number of DMA tags required depends on
1165                  * the number of endpoints. The current estimate
1166                  * for maximum number of DMA tags per endpoint
1167                  * is three:
1168                  * 1) for loading memory
1169                  * 2) for allocating memory
1170                  * 3) for fixing memory [UHCI]
1171                  */
1172                 parm->dma_tag_max += 3 * MIN(n_setup, USB_EP_MAX);
1173
1174                 /*
1175                  * DMA tags for QH, TD, Data and more.
1176                  */
1177                 parm->dma_tag_max += 8;
1178
1179                 parm->dma_tag_p += parm->dma_tag_max;
1180
1181                 parm->size[0] += ((uint8_t *)parm->dma_tag_p) -
1182                     ((uint8_t *)0);
1183
1184                 /* align data properly */
1185                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1186
1187                 /* store offset temporarily */
1188                 parm->size[3] = parm->size[0];
1189
1190                 parm->size[0] += ((uint8_t *)parm->dma_page_ptr) -
1191                     ((uint8_t *)0);
1192
1193                 /* align data properly */
1194                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1195
1196                 /* store offset temporarily */
1197                 parm->size[4] = parm->size[0];
1198
1199                 parm->size[0] += ((uint8_t *)parm->dma_page_cache_ptr) -
1200                     ((uint8_t *)0);
1201
1202                 /* store end offset temporarily */
1203                 parm->size[5] = parm->size[0];
1204
1205                 parm->size[0] += ((uint8_t *)parm->xfer_page_cache_ptr) -
1206                     ((uint8_t *)0);
1207
1208                 /* store end offset temporarily */
1209
1210                 parm->size[2] = parm->size[0];
1211
1212                 /* align data properly */
1213                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1214
1215                 parm->size[6] = parm->size[0];
1216
1217                 parm->size[0] += ((uint8_t *)parm->xfer_length_ptr) -
1218                     ((uint8_t *)0);
1219
1220                 /* align data properly */
1221                 parm->size[0] += ((-parm->size[0]) & (USB_HOST_ALIGN - 1));
1222
1223                 /* allocate zeroed memory */
1224                 buf = malloc(parm->size[0], M_USB, M_WAITOK | M_ZERO);
1225
1226                 if (buf == NULL) {
1227                         parm->err = USB_ERR_NOMEM;
1228                         DPRINTFN(0, "cannot allocate memory block for "
1229                             "configuration (%d bytes)\n",
1230                             parm->size[0]);
1231                         goto done;
1232                 }
1233                 parm->dma_tag_p = USB_ADD_BYTES(buf, parm->size[1]);
1234                 parm->dma_page_ptr = USB_ADD_BYTES(buf, parm->size[3]);
1235                 parm->dma_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[4]);
1236                 parm->xfer_page_cache_ptr = USB_ADD_BYTES(buf, parm->size[5]);
1237                 parm->xfer_length_ptr = USB_ADD_BYTES(buf, parm->size[6]);
1238         }
1239
1240 done:
1241         if (buf) {
1242                 if (info->setup_refcount == 0) {
1243                         /*
1244                          * "usbd_transfer_unsetup_sub" will unlock
1245                          * the bus mutex before returning !
1246                          */
1247                         USB_BUS_LOCK(info->bus);
1248
1249                         /* something went wrong */
1250                         usbd_transfer_unsetup_sub(info, 0);
1251                 }
1252         }
1253
1254         /* check if any errors happened */
1255         if (parm->err)
1256                 usbd_transfer_unsetup(ppxfer, n_setup);
1257
1258         error = parm->err;
1259
1260         if (do_unlock)
1261                 usbd_enum_unlock(udev);
1262
1263         return (error);
1264 }
1265
1266 /*------------------------------------------------------------------------*
1267  *      usbd_transfer_unsetup_sub - factored out code
1268  *------------------------------------------------------------------------*/
1269 static void
1270 usbd_transfer_unsetup_sub(struct usb_xfer_root *info, uint8_t needs_delay)
1271 {
1272 #if USB_HAVE_BUSDMA
1273         struct usb_page_cache *pc;
1274 #endif
1275
1276         USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
1277
1278         /* wait for any outstanding DMA operations */
1279
1280         if (needs_delay) {
1281                 usb_timeout_t temp;
1282                 temp = usbd_get_dma_delay(info->udev);
1283                 if (temp != 0) {
1284                         usb_pause_mtx(&info->bus->bus_mtx,
1285                             USB_MS_TO_TICKS(temp));
1286                 }
1287         }
1288
1289         /* make sure that our done messages are not queued anywhere */
1290         usb_proc_mwait(info->done_p, &info->done_m[0], &info->done_m[1]);
1291
1292         USB_BUS_UNLOCK(info->bus);
1293
1294 #if USB_HAVE_BUSDMA
1295         /* free DMA'able memory, if any */
1296         pc = info->dma_page_cache_start;
1297         while (pc != info->dma_page_cache_end) {
1298                 usb_pc_free_mem(pc);
1299                 pc++;
1300         }
1301
1302         /* free DMA maps in all "xfer->frbuffers" */
1303         pc = info->xfer_page_cache_start;
1304         while (pc != info->xfer_page_cache_end) {
1305                 usb_pc_dmamap_destroy(pc);
1306                 pc++;
1307         }
1308
1309         /* free all DMA tags */
1310         usb_dma_tag_unsetup(&info->dma_parent_tag);
1311 #endif
1312
1313         cv_destroy(&info->cv_drain);
1314
1315         /*
1316          * free the "memory_base" last, hence the "info" structure is
1317          * contained within the "memory_base"!
1318          */
1319         free(info->memory_base, M_USB);
1320 }
1321
1322 /*------------------------------------------------------------------------*
1323  *      usbd_transfer_unsetup - unsetup/free an array of USB transfers
1324  *
1325  * NOTE: All USB transfers in progress will get called back passing
1326  * the error code "USB_ERR_CANCELLED" before this function
1327  * returns.
1328  *------------------------------------------------------------------------*/
1329 void
1330 usbd_transfer_unsetup(struct usb_xfer **pxfer, uint16_t n_setup)
1331 {
1332         struct usb_xfer *xfer;
1333         struct usb_xfer_root *info;
1334         uint8_t needs_delay = 0;
1335
1336         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1337             "usbd_transfer_unsetup can sleep!");
1338
1339         while (n_setup--) {
1340                 xfer = pxfer[n_setup];
1341
1342                 if (xfer == NULL)
1343                         continue;
1344
1345                 info = xfer->xroot;
1346
1347                 USB_XFER_LOCK(xfer);
1348                 USB_BUS_LOCK(info->bus);
1349
1350                 /*
1351                  * HINT: when you start/stop a transfer, it might be a
1352                  * good idea to directly use the "pxfer[]" structure:
1353                  *
1354                  * usbd_transfer_start(sc->pxfer[0]);
1355                  * usbd_transfer_stop(sc->pxfer[0]);
1356                  *
1357                  * That way, if your code has many parts that will not
1358                  * stop running under the same lock, in other words
1359                  * "xfer_mtx", the usbd_transfer_start and
1360                  * usbd_transfer_stop functions will simply return
1361                  * when they detect a NULL pointer argument.
1362                  *
1363                  * To avoid any races we clear the "pxfer[]" pointer
1364                  * while holding the private mutex of the driver:
1365                  */
1366                 pxfer[n_setup] = NULL;
1367
1368                 USB_BUS_UNLOCK(info->bus);
1369                 USB_XFER_UNLOCK(xfer);
1370
1371                 usbd_transfer_drain(xfer);
1372
1373 #if USB_HAVE_BUSDMA
1374                 if (xfer->flags_int.bdma_enable)
1375                         needs_delay = 1;
1376 #endif
1377                 /*
1378                  * NOTE: default endpoint does not have an
1379                  * interface, even if endpoint->iface_index == 0
1380                  */
1381                 USB_BUS_LOCK(info->bus);
1382                 xfer->endpoint->refcount_alloc--;
1383                 USB_BUS_UNLOCK(info->bus);
1384
1385                 usb_callout_drain(&xfer->timeout_handle);
1386
1387                 USB_BUS_LOCK(info->bus);
1388
1389                 USB_ASSERT(info->setup_refcount != 0, ("Invalid setup "
1390                     "reference count\n"));
1391
1392                 info->setup_refcount--;
1393
1394                 if (info->setup_refcount == 0) {
1395                         usbd_transfer_unsetup_sub(info,
1396                             needs_delay);
1397                 } else {
1398                         USB_BUS_UNLOCK(info->bus);
1399                 }
1400         }
1401 }
1402
1403 /*------------------------------------------------------------------------*
1404  *      usbd_control_transfer_init - factored out code
1405  *
1406  * In USB Device Mode we have to wait for the SETUP packet which
1407  * containst the "struct usb_device_request" structure, before we can
1408  * transfer any data. In USB Host Mode we already have the SETUP
1409  * packet at the moment the USB transfer is started. This leads us to
1410  * having to setup the USB transfer at two different places in
1411  * time. This function just contains factored out control transfer
1412  * initialisation code, so that we don't duplicate the code.
1413  *------------------------------------------------------------------------*/
1414 static void
1415 usbd_control_transfer_init(struct usb_xfer *xfer)
1416 {
1417         struct usb_device_request req;
1418
1419         /* copy out the USB request header */
1420
1421         usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1422
1423         /* setup remainder */
1424
1425         xfer->flags_int.control_rem = UGETW(req.wLength);
1426
1427         /* copy direction to endpoint variable */
1428
1429         xfer->endpointno &= ~(UE_DIR_IN | UE_DIR_OUT);
1430         xfer->endpointno |=
1431             (req.bmRequestType & UT_READ) ? UE_DIR_IN : UE_DIR_OUT;
1432 }
1433
1434 /*------------------------------------------------------------------------*
1435  *      usbd_control_transfer_did_data
1436  *
1437  * This function returns non-zero if a control endpoint has
1438  * transferred the first DATA packet after the SETUP packet.
1439  * Else it returns zero.
1440  *------------------------------------------------------------------------*/
1441 static uint8_t
1442 usbd_control_transfer_did_data(struct usb_xfer *xfer)
1443 {
1444         struct usb_device_request req;
1445
1446         /* SETUP packet is not yet sent */
1447         if (xfer->flags_int.control_hdr != 0)
1448                 return (0);
1449
1450         /* copy out the USB request header */
1451         usbd_copy_out(xfer->frbuffers, 0, &req, sizeof(req));
1452
1453         /* compare remainder to the initial value */
1454         return (xfer->flags_int.control_rem != UGETW(req.wLength));
1455 }
1456
1457 /*------------------------------------------------------------------------*
1458  *      usbd_setup_ctrl_transfer
1459  *
1460  * This function handles initialisation of control transfers. Control
1461  * transfers are special in that regard that they can both transmit
1462  * and receive data.
1463  *
1464  * Return values:
1465  *    0: Success
1466  * Else: Failure
1467  *------------------------------------------------------------------------*/
1468 static int
1469 usbd_setup_ctrl_transfer(struct usb_xfer *xfer)
1470 {
1471         usb_frlength_t len;
1472
1473         /* Check for control endpoint stall */
1474         if (xfer->flags.stall_pipe && xfer->flags_int.control_act) {
1475                 /* the control transfer is no longer active */
1476                 xfer->flags_int.control_stall = 1;
1477                 xfer->flags_int.control_act = 0;
1478         } else {
1479                 /* don't stall control transfer by default */
1480                 xfer->flags_int.control_stall = 0;
1481         }
1482
1483         /* Check for invalid number of frames */
1484         if (xfer->nframes > 2) {
1485                 /*
1486                  * If you need to split a control transfer, you
1487                  * have to do one part at a time. Only with
1488                  * non-control transfers you can do multiple
1489                  * parts a time.
1490                  */
1491                 DPRINTFN(0, "Too many frames: %u\n",
1492                     (unsigned int)xfer->nframes);
1493                 goto error;
1494         }
1495
1496         /*
1497          * Check if there is a control
1498          * transfer in progress:
1499          */
1500         if (xfer->flags_int.control_act) {
1501
1502                 if (xfer->flags_int.control_hdr) {
1503
1504                         /* clear send header flag */
1505
1506                         xfer->flags_int.control_hdr = 0;
1507
1508                         /* setup control transfer */
1509                         if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1510                                 usbd_control_transfer_init(xfer);
1511                         }
1512                 }
1513                 /* get data length */
1514
1515                 len = xfer->sumlen;
1516
1517         } else {
1518
1519                 /* the size of the SETUP structure is hardcoded ! */
1520
1521                 if (xfer->frlengths[0] != sizeof(struct usb_device_request)) {
1522                         DPRINTFN(0, "Wrong framelength %u != %zu\n",
1523                             xfer->frlengths[0], sizeof(struct
1524                             usb_device_request));
1525                         goto error;
1526                 }
1527                 /* check USB mode */
1528                 if (xfer->flags_int.usb_mode == USB_MODE_DEVICE) {
1529
1530                         /* check number of frames */
1531                         if (xfer->nframes != 1) {
1532                                 /*
1533                                  * We need to receive the setup
1534                                  * message first so that we know the
1535                                  * data direction!
1536                                  */
1537                                 DPRINTF("Misconfigured transfer\n");
1538                                 goto error;
1539                         }
1540                         /*
1541                          * Set a dummy "control_rem" value.  This
1542                          * variable will be overwritten later by a
1543                          * call to "usbd_control_transfer_init()" !
1544                          */
1545                         xfer->flags_int.control_rem = 0xFFFF;
1546                 } else {
1547
1548                         /* setup "endpoint" and "control_rem" */
1549
1550                         usbd_control_transfer_init(xfer);
1551                 }
1552
1553                 /* set transfer-header flag */
1554
1555                 xfer->flags_int.control_hdr = 1;
1556
1557                 /* get data length */
1558
1559                 len = (xfer->sumlen - sizeof(struct usb_device_request));
1560         }
1561
1562         /* update did data flag */
1563
1564         xfer->flags_int.control_did_data =
1565             usbd_control_transfer_did_data(xfer);
1566
1567         /* check if there is a length mismatch */
1568
1569         if (len > xfer->flags_int.control_rem) {
1570                 DPRINTFN(0, "Length (%d) greater than "
1571                     "remaining length (%d)\n", len,
1572                     xfer->flags_int.control_rem);
1573                 goto error;
1574         }
1575         /* check if we are doing a short transfer */
1576
1577         if (xfer->flags.force_short_xfer) {
1578                 xfer->flags_int.control_rem = 0;
1579         } else {
1580                 if ((len != xfer->max_data_length) &&
1581                     (len != xfer->flags_int.control_rem) &&
1582                     (xfer->nframes != 1)) {
1583                         DPRINTFN(0, "Short control transfer without "
1584                             "force_short_xfer set\n");
1585                         goto error;
1586                 }
1587                 xfer->flags_int.control_rem -= len;
1588         }
1589
1590         /* the status part is executed when "control_act" is 0 */
1591
1592         if ((xfer->flags_int.control_rem > 0) ||
1593             (xfer->flags.manual_status)) {
1594                 /* don't execute the STATUS stage yet */
1595                 xfer->flags_int.control_act = 1;
1596
1597                 /* sanity check */
1598                 if ((!xfer->flags_int.control_hdr) &&
1599                     (xfer->nframes == 1)) {
1600                         /*
1601                          * This is not a valid operation!
1602                          */
1603                         DPRINTFN(0, "Invalid parameter "
1604                             "combination\n");
1605                         goto error;
1606                 }
1607         } else {
1608                 /* time to execute the STATUS stage */
1609                 xfer->flags_int.control_act = 0;
1610         }
1611         return (0);                     /* success */
1612
1613 error:
1614         return (1);                     /* failure */
1615 }
1616
1617 /*------------------------------------------------------------------------*
1618  *      usbd_transfer_submit - start USB hardware for the given transfer
1619  *
1620  * This function should only be called from the USB callback.
1621  *------------------------------------------------------------------------*/
1622 void
1623 usbd_transfer_submit(struct usb_xfer *xfer)
1624 {
1625         struct usb_xfer_root *info;
1626         struct usb_bus *bus;
1627         usb_frcount_t x;
1628
1629         info = xfer->xroot;
1630         bus = info->bus;
1631
1632         DPRINTF("xfer=%p, endpoint=%p, nframes=%d, dir=%s\n",
1633             xfer, xfer->endpoint, xfer->nframes, USB_GET_DATA_ISREAD(xfer) ?
1634             "read" : "write");
1635
1636 #ifdef USB_DEBUG
1637         if (USB_DEBUG_VAR > 0) {
1638                 USB_BUS_LOCK(bus);
1639
1640                 usb_dump_endpoint(xfer->endpoint);
1641
1642                 USB_BUS_UNLOCK(bus);
1643         }
1644 #endif
1645
1646         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1647         USB_BUS_LOCK_ASSERT(bus, MA_NOTOWNED);
1648
1649         /* Only open the USB transfer once! */
1650         if (!xfer->flags_int.open) {
1651                 xfer->flags_int.open = 1;
1652
1653                 DPRINTF("open\n");
1654
1655                 USB_BUS_LOCK(bus);
1656                 (xfer->endpoint->methods->open) (xfer);
1657                 USB_BUS_UNLOCK(bus);
1658         }
1659         /* set "transferring" flag */
1660         xfer->flags_int.transferring = 1;
1661
1662 #if USB_HAVE_POWERD
1663         /* increment power reference */
1664         usbd_transfer_power_ref(xfer, 1);
1665 #endif
1666         /*
1667          * Check if the transfer is waiting on a queue, most
1668          * frequently the "done_q":
1669          */
1670         if (xfer->wait_queue) {
1671                 USB_BUS_LOCK(bus);
1672                 usbd_transfer_dequeue(xfer);
1673                 USB_BUS_UNLOCK(bus);
1674         }
1675         /* clear "did_dma_delay" flag */
1676         xfer->flags_int.did_dma_delay = 0;
1677
1678         /* clear "did_close" flag */
1679         xfer->flags_int.did_close = 0;
1680
1681 #if USB_HAVE_BUSDMA
1682         /* clear "bdma_setup" flag */
1683         xfer->flags_int.bdma_setup = 0;
1684 #endif
1685         /* by default we cannot cancel any USB transfer immediately */
1686         xfer->flags_int.can_cancel_immed = 0;
1687
1688         /* clear lengths and frame counts by default */
1689         xfer->sumlen = 0;
1690         xfer->actlen = 0;
1691         xfer->aframes = 0;
1692
1693         /* clear any previous errors */
1694         xfer->error = 0;
1695
1696         /* Check if the device is still alive */
1697         if (info->udev->state < USB_STATE_POWERED) {
1698                 USB_BUS_LOCK(bus);
1699                 /*
1700                  * Must return cancelled error code else
1701                  * device drivers can hang.
1702                  */
1703                 usbd_transfer_done(xfer, USB_ERR_CANCELLED);
1704                 USB_BUS_UNLOCK(bus);
1705                 return;
1706         }
1707
1708         /* sanity check */
1709         if (xfer->nframes == 0) {
1710                 if (xfer->flags.stall_pipe) {
1711                         /*
1712                          * Special case - want to stall without transferring
1713                          * any data:
1714                          */
1715                         DPRINTF("xfer=%p nframes=0: stall "
1716                             "or clear stall!\n", xfer);
1717                         USB_BUS_LOCK(bus);
1718                         xfer->flags_int.can_cancel_immed = 1;
1719                         /* start the transfer */
1720                         usb_command_wrapper(&xfer->endpoint->
1721                             endpoint_q[xfer->stream_id], xfer);
1722                         USB_BUS_UNLOCK(bus);
1723                         return;
1724                 }
1725                 USB_BUS_LOCK(bus);
1726                 usbd_transfer_done(xfer, USB_ERR_INVAL);
1727                 USB_BUS_UNLOCK(bus);
1728                 return;
1729         }
1730         /* compute some variables */
1731
1732         for (x = 0; x != xfer->nframes; x++) {
1733                 /* make a copy of the frlenghts[] */
1734                 xfer->frlengths[x + xfer->max_frame_count] = xfer->frlengths[x];
1735                 /* compute total transfer length */
1736                 xfer->sumlen += xfer->frlengths[x];
1737                 if (xfer->sumlen < xfer->frlengths[x]) {
1738                         /* length wrapped around */
1739                         USB_BUS_LOCK(bus);
1740                         usbd_transfer_done(xfer, USB_ERR_INVAL);
1741                         USB_BUS_UNLOCK(bus);
1742                         return;
1743                 }
1744         }
1745
1746         /* clear some internal flags */
1747
1748         xfer->flags_int.short_xfer_ok = 0;
1749         xfer->flags_int.short_frames_ok = 0;
1750
1751         /* check if this is a control transfer */
1752
1753         if (xfer->flags_int.control_xfr) {
1754
1755                 if (usbd_setup_ctrl_transfer(xfer)) {
1756                         USB_BUS_LOCK(bus);
1757                         usbd_transfer_done(xfer, USB_ERR_STALLED);
1758                         USB_BUS_UNLOCK(bus);
1759                         return;
1760                 }
1761         }
1762         /*
1763          * Setup filtered version of some transfer flags,
1764          * in case of data read direction
1765          */
1766         if (USB_GET_DATA_ISREAD(xfer)) {
1767
1768                 if (xfer->flags.short_frames_ok) {
1769                         xfer->flags_int.short_xfer_ok = 1;
1770                         xfer->flags_int.short_frames_ok = 1;
1771                 } else if (xfer->flags.short_xfer_ok) {
1772                         xfer->flags_int.short_xfer_ok = 1;
1773
1774                         /* check for control transfer */
1775                         if (xfer->flags_int.control_xfr) {
1776                                 /*
1777                                  * 1) Control transfers do not support
1778                                  * reception of multiple short USB
1779                                  * frames in host mode and device side
1780                                  * mode, with exception of:
1781                                  *
1782                                  * 2) Due to sometimes buggy device
1783                                  * side firmware we need to do a
1784                                  * STATUS stage in case of short
1785                                  * control transfers in USB host mode.
1786                                  * The STATUS stage then becomes the
1787                                  * "alt_next" to the DATA stage.
1788                                  */
1789                                 xfer->flags_int.short_frames_ok = 1;
1790                         }
1791                 }
1792         }
1793         /*
1794          * Check if BUS-DMA support is enabled and try to load virtual
1795          * buffers into DMA, if any:
1796          */
1797 #if USB_HAVE_BUSDMA
1798         if (xfer->flags_int.bdma_enable) {
1799                 /* insert the USB transfer last in the BUS-DMA queue */
1800                 usb_command_wrapper(&xfer->xroot->dma_q, xfer);
1801                 return;
1802         }
1803 #endif
1804         /*
1805          * Enter the USB transfer into the Host Controller or
1806          * Device Controller schedule:
1807          */
1808         usbd_pipe_enter(xfer);
1809 }
1810
1811 /*------------------------------------------------------------------------*
1812  *      usbd_pipe_enter - factored out code
1813  *------------------------------------------------------------------------*/
1814 void
1815 usbd_pipe_enter(struct usb_xfer *xfer)
1816 {
1817         struct usb_endpoint *ep;
1818
1819         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1820
1821         USB_BUS_LOCK(xfer->xroot->bus);
1822
1823         ep = xfer->endpoint;
1824
1825         DPRINTF("enter\n");
1826
1827         /* the transfer can now be cancelled */
1828         xfer->flags_int.can_cancel_immed = 1;
1829
1830         /* enter the transfer */
1831         (ep->methods->enter) (xfer);
1832
1833         /* check for transfer error */
1834         if (xfer->error) {
1835                 /* some error has happened */
1836                 usbd_transfer_done(xfer, 0);
1837                 USB_BUS_UNLOCK(xfer->xroot->bus);
1838                 return;
1839         }
1840
1841         /* start the transfer */
1842         usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], xfer);
1843         USB_BUS_UNLOCK(xfer->xroot->bus);
1844 }
1845
1846 /*------------------------------------------------------------------------*
1847  *      usbd_transfer_start - start an USB transfer
1848  *
1849  * NOTE: Calling this function more than one time will only
1850  *       result in a single transfer start, until the USB transfer
1851  *       completes.
1852  *------------------------------------------------------------------------*/
1853 void
1854 usbd_transfer_start(struct usb_xfer *xfer)
1855 {
1856         if (xfer == NULL) {
1857                 /* transfer is gone */
1858                 return;
1859         }
1860         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1861
1862         /* mark the USB transfer started */
1863
1864         if (!xfer->flags_int.started) {
1865                 /* lock the BUS lock to avoid races updating flags_int */
1866                 USB_BUS_LOCK(xfer->xroot->bus);
1867                 xfer->flags_int.started = 1;
1868                 USB_BUS_UNLOCK(xfer->xroot->bus);
1869         }
1870         /* check if the USB transfer callback is already transferring */
1871
1872         if (xfer->flags_int.transferring) {
1873                 return;
1874         }
1875         USB_BUS_LOCK(xfer->xroot->bus);
1876         /* call the USB transfer callback */
1877         usbd_callback_ss_done_defer(xfer);
1878         USB_BUS_UNLOCK(xfer->xroot->bus);
1879 }
1880
1881 /*------------------------------------------------------------------------*
1882  *      usbd_transfer_stop - stop an USB transfer
1883  *
1884  * NOTE: Calling this function more than one time will only
1885  *       result in a single transfer stop.
1886  * NOTE: When this function returns it is not safe to free nor
1887  *       reuse any DMA buffers. See "usbd_transfer_drain()".
1888  *------------------------------------------------------------------------*/
1889 void
1890 usbd_transfer_stop(struct usb_xfer *xfer)
1891 {
1892         struct usb_endpoint *ep;
1893
1894         if (xfer == NULL) {
1895                 /* transfer is gone */
1896                 return;
1897         }
1898         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1899
1900         /* check if the USB transfer was ever opened */
1901
1902         if (!xfer->flags_int.open) {
1903                 if (xfer->flags_int.started) {
1904                         /* nothing to do except clearing the "started" flag */
1905                         /* lock the BUS lock to avoid races updating flags_int */
1906                         USB_BUS_LOCK(xfer->xroot->bus);
1907                         xfer->flags_int.started = 0;
1908                         USB_BUS_UNLOCK(xfer->xroot->bus);
1909                 }
1910                 return;
1911         }
1912         /* try to stop the current USB transfer */
1913
1914         USB_BUS_LOCK(xfer->xroot->bus);
1915         /* override any previous error */
1916         xfer->error = USB_ERR_CANCELLED;
1917
1918         /*
1919          * Clear "open" and "started" when both private and USB lock
1920          * is locked so that we don't get a race updating "flags_int"
1921          */
1922         xfer->flags_int.open = 0;
1923         xfer->flags_int.started = 0;
1924
1925         /*
1926          * Check if we can cancel the USB transfer immediately.
1927          */
1928         if (xfer->flags_int.transferring) {
1929                 if (xfer->flags_int.can_cancel_immed &&
1930                     (!xfer->flags_int.did_close)) {
1931                         DPRINTF("close\n");
1932                         /*
1933                          * The following will lead to an USB_ERR_CANCELLED
1934                          * error code being passed to the USB callback.
1935                          */
1936                         (xfer->endpoint->methods->close) (xfer);
1937                         /* only close once */
1938                         xfer->flags_int.did_close = 1;
1939                 } else {
1940                         /* need to wait for the next done callback */
1941                 }
1942         } else {
1943                 DPRINTF("close\n");
1944
1945                 /* close here and now */
1946                 (xfer->endpoint->methods->close) (xfer);
1947
1948                 /*
1949                  * Any additional DMA delay is done by
1950                  * "usbd_transfer_unsetup()".
1951                  */
1952
1953                 /*
1954                  * Special case. Check if we need to restart a blocked
1955                  * endpoint.
1956                  */
1957                 ep = xfer->endpoint;
1958
1959                 /*
1960                  * If the current USB transfer is completing we need
1961                  * to start the next one:
1962                  */
1963                 if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
1964                         usb_command_wrapper(
1965                             &ep->endpoint_q[xfer->stream_id], NULL);
1966                 }
1967         }
1968
1969         USB_BUS_UNLOCK(xfer->xroot->bus);
1970 }
1971
1972 /*------------------------------------------------------------------------*
1973  *      usbd_transfer_pending
1974  *
1975  * This function will check if an USB transfer is pending which is a
1976  * little bit complicated!
1977  * Return values:
1978  * 0: Not pending
1979  * 1: Pending: The USB transfer will receive a callback in the future.
1980  *------------------------------------------------------------------------*/
1981 uint8_t
1982 usbd_transfer_pending(struct usb_xfer *xfer)
1983 {
1984         struct usb_xfer_root *info;
1985         struct usb_xfer_queue *pq;
1986
1987         if (xfer == NULL) {
1988                 /* transfer is gone */
1989                 return (0);
1990         }
1991         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1992
1993         if (xfer->flags_int.transferring) {
1994                 /* trivial case */
1995                 return (1);
1996         }
1997         USB_BUS_LOCK(xfer->xroot->bus);
1998         if (xfer->wait_queue) {
1999                 /* we are waiting on a queue somewhere */
2000                 USB_BUS_UNLOCK(xfer->xroot->bus);
2001                 return (1);
2002         }
2003         info = xfer->xroot;
2004         pq = &info->done_q;
2005
2006         if (pq->curr == xfer) {
2007                 /* we are currently scheduled for callback */
2008                 USB_BUS_UNLOCK(xfer->xroot->bus);
2009                 return (1);
2010         }
2011         /* we are not pending */
2012         USB_BUS_UNLOCK(xfer->xroot->bus);
2013         return (0);
2014 }
2015
2016 /*------------------------------------------------------------------------*
2017  *      usbd_transfer_drain
2018  *
2019  * This function will stop the USB transfer and wait for any
2020  * additional BUS-DMA and HW-DMA operations to complete. Buffers that
2021  * are loaded into DMA can safely be freed or reused after that this
2022  * function has returned.
2023  *------------------------------------------------------------------------*/
2024 void
2025 usbd_transfer_drain(struct usb_xfer *xfer)
2026 {
2027         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2028             "usbd_transfer_drain can sleep!");
2029
2030         if (xfer == NULL) {
2031                 /* transfer is gone */
2032                 return;
2033         }
2034         if (xfer->xroot->xfer_mtx != &Giant) {
2035                 USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
2036         }
2037         USB_XFER_LOCK(xfer);
2038
2039         usbd_transfer_stop(xfer);
2040
2041         while (usbd_transfer_pending(xfer) || 
2042             xfer->flags_int.doing_callback) {
2043
2044                 /* 
2045                  * It is allowed that the callback can drop its
2046                  * transfer mutex. In that case checking only
2047                  * "usbd_transfer_pending()" is not enough to tell if
2048                  * the USB transfer is fully drained. We also need to
2049                  * check the internal "doing_callback" flag.
2050                  */
2051                 xfer->flags_int.draining = 1;
2052
2053                 /*
2054                  * Wait until the current outstanding USB
2055                  * transfer is complete !
2056                  */
2057                 cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
2058         }
2059         USB_XFER_UNLOCK(xfer);
2060 }
2061
2062 struct usb_page_cache *
2063 usbd_xfer_get_frame(struct usb_xfer *xfer, usb_frcount_t frindex)
2064 {
2065         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2066
2067         return (&xfer->frbuffers[frindex]);
2068 }
2069
2070 void *
2071 usbd_xfer_get_frame_buffer(struct usb_xfer *xfer, usb_frcount_t frindex)
2072 {
2073         struct usb_page_search page_info;
2074
2075         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2076
2077         usbd_get_page(&xfer->frbuffers[frindex], 0, &page_info);
2078         return (page_info.buffer);
2079 }
2080
2081 /*------------------------------------------------------------------------*
2082  *      usbd_xfer_get_fps_shift
2083  *
2084  * The following function is only useful for isochronous transfers. It
2085  * returns how many times the frame execution rate has been shifted
2086  * down.
2087  *
2088  * Return value:
2089  * Success: 0..3
2090  * Failure: 0
2091  *------------------------------------------------------------------------*/
2092 uint8_t
2093 usbd_xfer_get_fps_shift(struct usb_xfer *xfer)
2094 {
2095         return (xfer->fps_shift);
2096 }
2097
2098 usb_frlength_t
2099 usbd_xfer_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex)
2100 {
2101         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2102
2103         return (xfer->frlengths[frindex]);
2104 }
2105
2106 /*------------------------------------------------------------------------*
2107  *      usbd_xfer_set_frame_data
2108  *
2109  * This function sets the pointer of the buffer that should
2110  * loaded directly into DMA for the given USB frame. Passing "ptr"
2111  * equal to NULL while the corresponding "frlength" is greater
2112  * than zero gives undefined results!
2113  *------------------------------------------------------------------------*/
2114 void
2115 usbd_xfer_set_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2116     void *ptr, usb_frlength_t len)
2117 {
2118         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2119
2120         /* set virtual address to load and length */
2121         xfer->frbuffers[frindex].buffer = ptr;
2122         usbd_xfer_set_frame_len(xfer, frindex, len);
2123 }
2124
2125 void
2126 usbd_xfer_frame_data(struct usb_xfer *xfer, usb_frcount_t frindex,
2127     void **ptr, int *len)
2128 {
2129         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2130
2131         if (ptr != NULL)
2132                 *ptr = xfer->frbuffers[frindex].buffer;
2133         if (len != NULL)
2134                 *len = xfer->frlengths[frindex];
2135 }
2136
2137 /*------------------------------------------------------------------------*
2138  *      usbd_xfer_old_frame_length
2139  *
2140  * This function returns the framelength of the given frame at the
2141  * time the transfer was submitted. This function can be used to
2142  * compute the starting data pointer of the next isochronous frame
2143  * when an isochronous transfer has completed.
2144  *------------------------------------------------------------------------*/
2145 usb_frlength_t
2146 usbd_xfer_old_frame_length(struct usb_xfer *xfer, usb_frcount_t frindex)
2147 {
2148         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2149
2150         return (xfer->frlengths[frindex + xfer->max_frame_count]);
2151 }
2152
2153 void
2154 usbd_xfer_status(struct usb_xfer *xfer, int *actlen, int *sumlen, int *aframes,
2155     int *nframes)
2156 {
2157         if (actlen != NULL)
2158                 *actlen = xfer->actlen;
2159         if (sumlen != NULL)
2160                 *sumlen = xfer->sumlen;
2161         if (aframes != NULL)
2162                 *aframes = xfer->aframes;
2163         if (nframes != NULL)
2164                 *nframes = xfer->nframes;
2165 }
2166
2167 /*------------------------------------------------------------------------*
2168  *      usbd_xfer_set_frame_offset
2169  *
2170  * This function sets the frame data buffer offset relative to the beginning
2171  * of the USB DMA buffer allocated for this USB transfer.
2172  *------------------------------------------------------------------------*/
2173 void
2174 usbd_xfer_set_frame_offset(struct usb_xfer *xfer, usb_frlength_t offset,
2175     usb_frcount_t frindex)
2176 {
2177         KASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
2178             "when the USB buffer is external\n"));
2179         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2180
2181         /* set virtual address to load */
2182         xfer->frbuffers[frindex].buffer =
2183             USB_ADD_BYTES(xfer->local_buffer, offset);
2184 }
2185
2186 void
2187 usbd_xfer_set_interval(struct usb_xfer *xfer, int i)
2188 {
2189         xfer->interval = i;
2190 }
2191
2192 void
2193 usbd_xfer_set_timeout(struct usb_xfer *xfer, int t)
2194 {
2195         xfer->timeout = t;
2196 }
2197
2198 void
2199 usbd_xfer_set_frames(struct usb_xfer *xfer, usb_frcount_t n)
2200 {
2201         xfer->nframes = n;
2202 }
2203
2204 usb_frcount_t
2205 usbd_xfer_max_frames(struct usb_xfer *xfer)
2206 {
2207         return (xfer->max_frame_count);
2208 }
2209
2210 usb_frlength_t
2211 usbd_xfer_max_len(struct usb_xfer *xfer)
2212 {
2213         return (xfer->max_data_length);
2214 }
2215
2216 usb_frlength_t
2217 usbd_xfer_max_framelen(struct usb_xfer *xfer)
2218 {
2219         return (xfer->max_frame_size);
2220 }
2221
2222 void
2223 usbd_xfer_set_frame_len(struct usb_xfer *xfer, usb_frcount_t frindex,
2224     usb_frlength_t len)
2225 {
2226         KASSERT(frindex < xfer->max_frame_count, ("frame index overflow"));
2227
2228         xfer->frlengths[frindex] = len;
2229 }
2230
2231 /*------------------------------------------------------------------------*
2232  *      usb_callback_proc - factored out code
2233  *
2234  * This function performs USB callbacks.
2235  *------------------------------------------------------------------------*/
2236 static void
2237 usb_callback_proc(struct usb_proc_msg *_pm)
2238 {
2239         struct usb_done_msg *pm = (void *)_pm;
2240         struct usb_xfer_root *info = pm->xroot;
2241
2242         /* Change locking order */
2243         USB_BUS_UNLOCK(info->bus);
2244
2245         /*
2246          * We exploit the fact that the mutex is the same for all
2247          * callbacks that will be called from this thread:
2248          */
2249         mtx_lock(info->xfer_mtx);
2250         USB_BUS_LOCK(info->bus);
2251
2252         /* Continue where we lost track */
2253         usb_command_wrapper(&info->done_q,
2254             info->done_q.curr);
2255
2256         mtx_unlock(info->xfer_mtx);
2257 }
2258
2259 /*------------------------------------------------------------------------*
2260  *      usbd_callback_ss_done_defer
2261  *
2262  * This function will defer the start, stop and done callback to the
2263  * correct thread.
2264  *------------------------------------------------------------------------*/
2265 static void
2266 usbd_callback_ss_done_defer(struct usb_xfer *xfer)
2267 {
2268         struct usb_xfer_root *info = xfer->xroot;
2269         struct usb_xfer_queue *pq = &info->done_q;
2270
2271         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2272
2273         if (pq->curr != xfer) {
2274                 usbd_transfer_enqueue(pq, xfer);
2275         }
2276         if (!pq->recurse_1) {
2277
2278                 /*
2279                  * We have to postpone the callback due to the fact we
2280                  * will have a Lock Order Reversal, LOR, if we try to
2281                  * proceed !
2282                  */
2283                 if (usb_proc_msignal(info->done_p,
2284                     &info->done_m[0], &info->done_m[1])) {
2285                         /* ignore */
2286                 }
2287         } else {
2288                 /* clear second recurse flag */
2289                 pq->recurse_2 = 0;
2290         }
2291         return;
2292
2293 }
2294
2295 /*------------------------------------------------------------------------*
2296  *      usbd_callback_wrapper
2297  *
2298  * This is a wrapper for USB callbacks. This wrapper does some
2299  * auto-magic things like figuring out if we can call the callback
2300  * directly from the current context or if we need to wakeup the
2301  * interrupt process.
2302  *------------------------------------------------------------------------*/
2303 static void
2304 usbd_callback_wrapper(struct usb_xfer_queue *pq)
2305 {
2306         struct usb_xfer *xfer = pq->curr;
2307         struct usb_xfer_root *info = xfer->xroot;
2308
2309         USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2310         if (!mtx_owned(info->xfer_mtx) && !SCHEDULER_STOPPED()) {
2311                 /*
2312                  * Cases that end up here:
2313                  *
2314                  * 5) HW interrupt done callback or other source.
2315                  */
2316                 DPRINTFN(3, "case 5\n");
2317
2318                 /*
2319                  * We have to postpone the callback due to the fact we
2320                  * will have a Lock Order Reversal, LOR, if we try to
2321                  * proceed !
2322                  */
2323                 if (usb_proc_msignal(info->done_p,
2324                     &info->done_m[0], &info->done_m[1])) {
2325                         /* ignore */
2326                 }
2327                 return;
2328         }
2329         /*
2330          * Cases that end up here:
2331          *
2332          * 1) We are starting a transfer
2333          * 2) We are prematurely calling back a transfer
2334          * 3) We are stopping a transfer
2335          * 4) We are doing an ordinary callback
2336          */
2337         DPRINTFN(3, "case 1-4\n");
2338         /* get next USB transfer in the queue */
2339         info->done_q.curr = NULL;
2340
2341         /* set flag in case of drain */
2342         xfer->flags_int.doing_callback = 1;
2343
2344         USB_BUS_UNLOCK(info->bus);
2345         USB_BUS_LOCK_ASSERT(info->bus, MA_NOTOWNED);
2346
2347         /* set correct USB state for callback */
2348         if (!xfer->flags_int.transferring) {
2349                 xfer->usb_state = USB_ST_SETUP;
2350                 if (!xfer->flags_int.started) {
2351                         /* we got stopped before we even got started */
2352                         USB_BUS_LOCK(info->bus);
2353                         goto done;
2354                 }
2355         } else {
2356
2357                 if (usbd_callback_wrapper_sub(xfer)) {
2358                         /* the callback has been deferred */
2359                         USB_BUS_LOCK(info->bus);
2360                         goto done;
2361                 }
2362 #if USB_HAVE_POWERD
2363                 /* decrement power reference */
2364                 usbd_transfer_power_ref(xfer, -1);
2365 #endif
2366                 xfer->flags_int.transferring = 0;
2367
2368                 if (xfer->error) {
2369                         xfer->usb_state = USB_ST_ERROR;
2370                 } else {
2371                         /* set transferred state */
2372                         xfer->usb_state = USB_ST_TRANSFERRED;
2373 #if USB_HAVE_BUSDMA
2374                         /* sync DMA memory, if any */
2375                         if (xfer->flags_int.bdma_enable &&
2376                             (!xfer->flags_int.bdma_no_post_sync)) {
2377                                 usb_bdma_post_sync(xfer);
2378                         }
2379 #endif
2380                 }
2381         }
2382
2383 #if USB_HAVE_PF
2384         if (xfer->usb_state != USB_ST_SETUP) {
2385                 USB_BUS_LOCK(info->bus);
2386                 usbpf_xfertap(xfer, USBPF_XFERTAP_DONE);
2387                 USB_BUS_UNLOCK(info->bus);
2388         }
2389 #endif
2390         /* call processing routine */
2391         (xfer->callback) (xfer, xfer->error);
2392
2393         /* pickup the USB mutex again */
2394         USB_BUS_LOCK(info->bus);
2395
2396         /*
2397          * Check if we got started after that we got cancelled, but
2398          * before we managed to do the callback.
2399          */
2400         if ((!xfer->flags_int.open) &&
2401             (xfer->flags_int.started) &&
2402             (xfer->usb_state == USB_ST_ERROR)) {
2403                 /* clear flag in case of drain */
2404                 xfer->flags_int.doing_callback = 0;
2405                 /* try to loop, but not recursivly */
2406                 usb_command_wrapper(&info->done_q, xfer);
2407                 return;
2408         }
2409
2410 done:
2411         /* clear flag in case of drain */
2412         xfer->flags_int.doing_callback = 0;
2413
2414         /*
2415          * Check if we are draining.
2416          */
2417         if (xfer->flags_int.draining &&
2418             (!xfer->flags_int.transferring)) {
2419                 /* "usbd_transfer_drain()" is waiting for end of transfer */
2420                 xfer->flags_int.draining = 0;
2421                 cv_broadcast(&info->cv_drain);
2422         }
2423
2424         /* do the next callback, if any */
2425         usb_command_wrapper(&info->done_q,
2426             info->done_q.curr);
2427 }
2428
2429 /*------------------------------------------------------------------------*
2430  *      usb_dma_delay_done_cb
2431  *
2432  * This function is called when the DMA delay has been exectuded, and
2433  * will make sure that the callback is called to complete the USB
2434  * transfer. This code path is ususally only used when there is an USB
2435  * error like USB_ERR_CANCELLED.
2436  *------------------------------------------------------------------------*/
2437 void
2438 usb_dma_delay_done_cb(struct usb_xfer *xfer)
2439 {
2440         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2441
2442         DPRINTFN(3, "Completed %p\n", xfer);
2443
2444         /* queue callback for execution, again */
2445         usbd_transfer_done(xfer, 0);
2446 }
2447
2448 /*------------------------------------------------------------------------*
2449  *      usbd_transfer_dequeue
2450  *
2451  *  - This function is used to remove an USB transfer from a USB
2452  *  transfer queue.
2453  *
2454  *  - This function can be called multiple times in a row.
2455  *------------------------------------------------------------------------*/
2456 void
2457 usbd_transfer_dequeue(struct usb_xfer *xfer)
2458 {
2459         struct usb_xfer_queue *pq;
2460
2461         pq = xfer->wait_queue;
2462         if (pq) {
2463                 TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2464                 xfer->wait_queue = NULL;
2465         }
2466 }
2467
2468 /*------------------------------------------------------------------------*
2469  *      usbd_transfer_enqueue
2470  *
2471  *  - This function is used to insert an USB transfer into a USB *
2472  *  transfer queue.
2473  *
2474  *  - This function can be called multiple times in a row.
2475  *------------------------------------------------------------------------*/
2476 void
2477 usbd_transfer_enqueue(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
2478 {
2479         /*
2480          * Insert the USB transfer into the queue, if it is not
2481          * already on a USB transfer queue:
2482          */
2483         if (xfer->wait_queue == NULL) {
2484                 xfer->wait_queue = pq;
2485                 TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2486         }
2487 }
2488
2489 /*------------------------------------------------------------------------*
2490  *      usbd_transfer_done
2491  *
2492  *  - This function is used to remove an USB transfer from the busdma,
2493  *  pipe or interrupt queue.
2494  *
2495  *  - This function is used to queue the USB transfer on the done
2496  *  queue.
2497  *
2498  *  - This function is used to stop any USB transfer timeouts.
2499  *------------------------------------------------------------------------*/
2500 void
2501 usbd_transfer_done(struct usb_xfer *xfer, usb_error_t error)
2502 {
2503         struct usb_xfer_root *info = xfer->xroot;
2504
2505         USB_BUS_LOCK_ASSERT(info->bus, MA_OWNED);
2506
2507         DPRINTF("err=%s\n", usbd_errstr(error));
2508
2509         /*
2510          * If we are not transferring then just return.
2511          * This can happen during transfer cancel.
2512          */
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;
2517                 return;
2518         }
2519         /* only set transfer error, if not already set */
2520         if (xfer->error == USB_ERR_NORMAL_COMPLETION)
2521                 xfer->error = error;
2522
2523         /* stop any callouts */
2524         usb_callout_stop(&xfer->timeout_handle);
2525
2526         /*
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.
2530          */
2531         usbd_transfer_dequeue(xfer);
2532
2533 #if USB_HAVE_BUSDMA
2534         if (mtx_owned(info->xfer_mtx)) {
2535                 struct usb_xfer_queue *pq;
2536
2537                 /*
2538                  * If the private USB lock is not locked, then we assume
2539                  * that the BUS-DMA load stage has been passed:
2540                  */
2541                 pq = &info->dma_q;
2542
2543                 if (pq->curr == xfer) {
2544                         /* start the next BUS-DMA load, if any */
2545                         usb_command_wrapper(pq, NULL);
2546                 }
2547         }
2548 #endif
2549         /* keep some statistics */
2550         if (xfer->error) {
2551                 info->bus->stats_err.uds_requests
2552                     [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2553         } else {
2554                 info->bus->stats_ok.uds_requests
2555                     [xfer->endpoint->edesc->bmAttributes & UE_XFERTYPE]++;
2556         }
2557
2558         /* call the USB transfer callback */
2559         usbd_callback_ss_done_defer(xfer);
2560 }
2561
2562 /*------------------------------------------------------------------------*
2563  *      usbd_transfer_start_cb
2564  *
2565  * This function is called to start the USB transfer when
2566  * "xfer->interval" is greater than zero, and and the endpoint type is
2567  * BULK or CONTROL.
2568  *------------------------------------------------------------------------*/
2569 static void
2570 usbd_transfer_start_cb(void *arg)
2571 {
2572         struct usb_xfer *xfer = arg;
2573         struct usb_endpoint *ep = xfer->endpoint;
2574
2575         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2576
2577         DPRINTF("start\n");
2578
2579 #if USB_HAVE_PF
2580         usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2581 #endif
2582
2583         /* the transfer can now be cancelled */
2584         xfer->flags_int.can_cancel_immed = 1;
2585
2586         /* start USB transfer, if no error */
2587         if (xfer->error == 0)
2588                 (ep->methods->start) (xfer);
2589
2590         /* check for transfer error */
2591         if (xfer->error) {
2592                 /* some error has happened */
2593                 usbd_transfer_done(xfer, 0);
2594         }
2595 }
2596
2597 /*------------------------------------------------------------------------*
2598  *      usbd_xfer_set_stall
2599  *
2600  * This function is used to set the stall flag outside the
2601  * callback. This function is NULL safe.
2602  *------------------------------------------------------------------------*/
2603 void
2604 usbd_xfer_set_stall(struct usb_xfer *xfer)
2605 {
2606         if (xfer == NULL) {
2607                 /* tearing down */
2608                 return;
2609         }
2610         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2611
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);
2616 }
2617
2618 int
2619 usbd_xfer_is_stalled(struct usb_xfer *xfer)
2620 {
2621         return (xfer->endpoint->is_stalled);
2622 }
2623
2624 /*------------------------------------------------------------------------*
2625  *      usbd_transfer_clear_stall
2626  *
2627  * This function is used to clear the stall flag outside the
2628  * callback. This function is NULL safe.
2629  *------------------------------------------------------------------------*/
2630 void
2631 usbd_transfer_clear_stall(struct usb_xfer *xfer)
2632 {
2633         if (xfer == NULL) {
2634                 /* tearing down */
2635                 return;
2636         }
2637         USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2638
2639         /* avoid any races by locking the USB mutex */
2640         USB_BUS_LOCK(xfer->xroot->bus);
2641
2642         xfer->flags.stall_pipe = 0;
2643
2644         USB_BUS_UNLOCK(xfer->xroot->bus);
2645 }
2646
2647 /*------------------------------------------------------------------------*
2648  *      usbd_pipe_start
2649  *
2650  * This function is used to add an USB transfer to the pipe transfer list.
2651  *------------------------------------------------------------------------*/
2652 void
2653 usbd_pipe_start(struct usb_xfer_queue *pq)
2654 {
2655         struct usb_endpoint *ep;
2656         struct usb_xfer *xfer;
2657         uint8_t type;
2658
2659         xfer = pq->curr;
2660         ep = xfer->endpoint;
2661
2662         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2663
2664         /*
2665          * If the endpoint is already stalled we do nothing !
2666          */
2667         if (ep->is_stalled) {
2668                 return;
2669         }
2670         /*
2671          * Check if we are supposed to stall the endpoint:
2672          */
2673         if (xfer->flags.stall_pipe) {
2674                 struct usb_device *udev;
2675                 struct usb_xfer_root *info;
2676
2677                 /* clear stall command */
2678                 xfer->flags.stall_pipe = 0;
2679
2680                 /* get pointer to USB device */
2681                 info = xfer->xroot;
2682                 udev = info->udev;
2683
2684                 /*
2685                  * Only stall BULK and INTERRUPT endpoints.
2686                  */
2687                 type = (ep->edesc->bmAttributes & UE_XFERTYPE);
2688                 if ((type == UE_BULK) ||
2689                     (type == UE_INTERRUPT)) {
2690                         uint8_t did_stall;
2691
2692                         did_stall = 1;
2693
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;
2699                                 usb_proc_msignal(
2700                                     USB_BUS_NON_GIANT_PROC(info->bus),
2701                                     &udev->cs_msg[0], &udev->cs_msg[1]);
2702                         } else {
2703                                 /* should not happen */
2704                                 DPRINTFN(0, "No stall handler\n");
2705                         }
2706                         /*
2707                          * Check if we should stall. Some USB hardware
2708                          * handles set- and clear-stall in hardware.
2709                          */
2710                         if (did_stall) {
2711                                 /*
2712                                  * The transfer will be continued when
2713                                  * the clear-stall control endpoint
2714                                  * message is received.
2715                                  */
2716                                 ep->is_stalled = 1;
2717                                 return;
2718                         }
2719                 } else if (type == UE_ISOCHRONOUS) {
2720
2721                         /* 
2722                          * Make sure any FIFO overflow or other FIFO
2723                          * error conditions go away by resetting the
2724                          * endpoint FIFO through the clear stall
2725                          * method.
2726                          */
2727                         if (udev->flags.usb_mode == USB_MODE_DEVICE) {
2728                                 (udev->bus->methods->clear_stall) (udev, ep);
2729                         }
2730                 }
2731         }
2732         /* Set or clear stall complete - special case */
2733         if (xfer->nframes == 0) {
2734                 /* we are complete */
2735                 xfer->aframes = 0;
2736                 usbd_transfer_done(xfer, 0);
2737                 return;
2738         }
2739         /*
2740          * Handled cases:
2741          *
2742          * 1) Start the first transfer queued.
2743          *
2744          * 2) Re-start the current USB transfer.
2745          */
2746         /*
2747          * Check if there should be any
2748          * pre transfer start delay:
2749          */
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,
2756                             xfer->interval);
2757                         return;
2758                 }
2759         }
2760         DPRINTF("start\n");
2761
2762 #if USB_HAVE_PF
2763         usbpf_xfertap(xfer, USBPF_XFERTAP_SUBMIT);
2764 #endif
2765         /* the transfer can now be cancelled */
2766         xfer->flags_int.can_cancel_immed = 1;
2767
2768         /* start USB transfer, if no error */
2769         if (xfer->error == 0)
2770                 (ep->methods->start) (xfer);
2771
2772         /* check for transfer error */
2773         if (xfer->error) {
2774                 /* some error has happened */
2775                 usbd_transfer_done(xfer, 0);
2776         }
2777 }
2778
2779 /*------------------------------------------------------------------------*
2780  *      usbd_transfer_timeout_ms
2781  *
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  *------------------------------------------------------------------------*/
2786 void
2787 usbd_transfer_timeout_ms(struct usb_xfer *xfer,
2788     void (*cb) (void *arg), usb_timeout_t ms)
2789 {
2790         USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2791
2792         /* defer delay */
2793         usb_callout_reset(&xfer->timeout_handle,
2794             USB_MS_TO_TICKS(ms) + USB_CALLOUT_ZERO_TICKS, cb, xfer);
2795 }
2796
2797 /*------------------------------------------------------------------------*
2798  *      usbd_callback_wrapper_sub
2799  *
2800  *  - This function will update variables in an USB transfer after
2801  *  that the USB transfer is complete.
2802  *
2803  *  - This function is used to start the next USB transfer on the
2804  *  ep transfer queue, if any.
2805  *
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".
2809  *
2810  * Return values:
2811  * 0: Success.
2812  * Else: The callback has been deferred.
2813  *------------------------------------------------------------------------*/
2814 static uint8_t
2815 usbd_callback_wrapper_sub(struct usb_xfer *xfer)
2816 {
2817         struct usb_endpoint *ep;
2818         struct usb_bus *bus;
2819         usb_frcount_t x;
2820
2821         bus = xfer->xroot->bus;
2822
2823         if ((!xfer->flags_int.open) &&
2824             (!xfer->flags_int.did_close)) {
2825                 DPRINTF("close\n");
2826                 USB_BUS_LOCK(bus);
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 */
2832         }
2833         /*
2834          * If we have a non-hardware induced error we
2835          * need to do the DMA delay!
2836          */
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)) {
2841
2842                 usb_timeout_t temp;
2843
2844                 /* only delay once */
2845                 xfer->flags_int.did_dma_delay = 1;
2846
2847                 /* we can not cancel this delay */
2848                 xfer->flags_int.can_cancel_immed = 0;
2849
2850                 temp = usbd_get_dma_delay(xfer->xroot->udev);
2851
2852                 DPRINTFN(3, "DMA delay, %u ms, "
2853                     "on %p\n", temp, xfer);
2854
2855                 if (temp != 0) {
2856                         USB_BUS_LOCK(bus);
2857                         /*
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.
2862                          */
2863                         if (bus->methods->start_dma_delay != NULL) {
2864                                 (bus->methods->start_dma_delay) (xfer);
2865                         } else {
2866                                 usbd_transfer_timeout_ms(xfer,
2867                                     (void (*)(void *))&usb_dma_delay_done_cb,
2868                                     temp);
2869                         }
2870                         USB_BUS_UNLOCK(bus);
2871                         return (1);     /* wait for new callback */
2872                 }
2873         }
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                             __FUNCTION__, xfer->aframes, xfer->nframes);
2880                 } else {
2881                         /* just set some valid value */
2882                         xfer->aframes = xfer->nframes;
2883                 }
2884         }
2885         /* compute actual length */
2886         xfer->actlen = 0;
2887
2888         for (x = 0; x != xfer->aframes; x++) {
2889                 xfer->actlen += xfer->frlengths[x];
2890         }
2891
2892         /*
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":
2896          */
2897         for (; x < xfer->nframes; x++) {
2898                 usbd_xfer_set_frame_len(xfer, x, 0);
2899         }
2900
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                             __FUNCTION__, xfer->actlen, xfer->sumlen);
2907                 } else {
2908                         /* just set some valid value */
2909                         xfer->actlen = xfer->sumlen;
2910                 }
2911         }
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);
2915
2916         if (xfer->error) {
2917                 /* end of control transfer, if any */
2918                 xfer->flags_int.control_act = 0;
2919
2920 #if USB_HAVE_TT_SUPPORT
2921                 switch (xfer->error) {
2922                 case USB_ERR_NORMAL_COMPLETION:
2923                 case USB_ERR_SHORT_XFER:
2924                 case USB_ERR_STALLED:
2925                 case USB_ERR_CANCELLED:
2926                         /* nothing to do */
2927                         break;
2928                 default:
2929                         /* try to reset the TT, if any */
2930                         USB_BUS_LOCK(bus);
2931                         uhub_tt_buffer_reset_async_locked(xfer->xroot->udev, xfer->endpoint);
2932                         USB_BUS_UNLOCK(bus);
2933                         break;
2934                 }
2935 #endif
2936                 /* check if we should block the execution queue */
2937                 if ((xfer->error != USB_ERR_CANCELLED) &&
2938                     (xfer->flags.pipe_bof)) {
2939                         DPRINTFN(2, "xfer=%p: Block On Failure "
2940                             "on endpoint=%p\n", xfer, xfer->endpoint);
2941                         goto done;
2942                 }
2943         } else {
2944                 /* check for short transfers */
2945                 if (xfer->actlen < xfer->sumlen) {
2946
2947                         /* end of control transfer, if any */
2948                         xfer->flags_int.control_act = 0;
2949
2950                         if (!xfer->flags_int.short_xfer_ok) {
2951                                 xfer->error = USB_ERR_SHORT_XFER;
2952                                 if (xfer->flags.pipe_bof) {
2953                                         DPRINTFN(2, "xfer=%p: Block On Failure on "
2954                                             "Short Transfer on endpoint %p.\n",
2955                                             xfer, xfer->endpoint);
2956                                         goto done;
2957                                 }
2958                         }
2959                 } else {
2960                         /*
2961                          * Check if we are in the middle of a
2962                          * control transfer:
2963                          */
2964                         if (xfer->flags_int.control_act) {
2965                                 DPRINTFN(5, "xfer=%p: Control transfer "
2966                                     "active on endpoint=%p\n", xfer, xfer->endpoint);
2967                                 goto done;
2968                         }
2969                 }
2970         }
2971
2972         ep = xfer->endpoint;
2973
2974         /*
2975          * If the current USB transfer is completing we need to start the
2976          * next one:
2977          */
2978         USB_BUS_LOCK(bus);
2979         if (ep->endpoint_q[xfer->stream_id].curr == xfer) {
2980                 usb_command_wrapper(&ep->endpoint_q[xfer->stream_id], NULL);
2981
2982                 if (ep->endpoint_q[xfer->stream_id].curr != NULL ||
2983                     TAILQ_FIRST(&ep->endpoint_q[xfer->stream_id].head) != NULL) {
2984                         /* there is another USB transfer waiting */
2985                 } else {
2986                         /* this is the last USB transfer */
2987                         /* clear isochronous sync flag */
2988                         xfer->endpoint->is_synced = 0;
2989                 }
2990         }
2991         USB_BUS_UNLOCK(bus);
2992 done:
2993         return (0);
2994 }
2995
2996 /*------------------------------------------------------------------------*
2997  *      usb_command_wrapper
2998  *
2999  * This function is used to execute commands non-recursivly on an USB
3000  * transfer.
3001  *------------------------------------------------------------------------*/
3002 void
3003 usb_command_wrapper(struct usb_xfer_queue *pq, struct usb_xfer *xfer)
3004 {
3005         if (xfer) {
3006                 /*
3007                  * If the transfer is not already processing,
3008                  * queue it!
3009                  */
3010                 if (pq->curr != xfer) {
3011                         usbd_transfer_enqueue(pq, xfer);
3012                         if (pq->curr != NULL) {
3013                                 /* something is already processing */
3014                                 DPRINTFN(6, "busy %p\n", pq->curr);
3015                                 return;
3016                         }
3017                 }
3018         } else {
3019                 /* Get next element in queue */
3020                 pq->curr = NULL;
3021         }
3022
3023         if (!pq->recurse_1) {
3024
3025                 do {
3026
3027                         /* set both recurse flags */
3028                         pq->recurse_1 = 1;
3029                         pq->recurse_2 = 1;
3030
3031                         if (pq->curr == NULL) {
3032                                 xfer = TAILQ_FIRST(&pq->head);
3033                                 if (xfer) {
3034                                         TAILQ_REMOVE(&pq->head, xfer,
3035                                             wait_entry);
3036                                         xfer->wait_queue = NULL;
3037                                         pq->curr = xfer;
3038                                 } else {
3039                                         break;
3040                                 }
3041                         }
3042                         DPRINTFN(6, "cb %p (enter)\n", pq->curr);
3043                         (pq->command) (pq);
3044                         DPRINTFN(6, "cb %p (leave)\n", pq->curr);
3045
3046                 } while (!pq->recurse_2);
3047
3048                 /* clear first recurse flag */
3049                 pq->recurse_1 = 0;
3050
3051         } else {
3052                 /* clear second recurse flag */
3053                 pq->recurse_2 = 0;
3054         }
3055 }
3056
3057 /*------------------------------------------------------------------------*
3058  *      usbd_ctrl_transfer_setup
3059  *
3060  * This function is used to setup the default USB control endpoint
3061  * transfer.
3062  *------------------------------------------------------------------------*/
3063 void
3064 usbd_ctrl_transfer_setup(struct usb_device *udev)
3065 {
3066         struct usb_xfer *xfer;
3067         uint8_t no_resetup;
3068         uint8_t iface_index;
3069
3070         /* check for root HUB */
3071         if (udev->parent_hub == NULL)
3072                 return;
3073 repeat:
3074
3075         xfer = udev->ctrl_xfer[0];
3076         if (xfer) {
3077                 USB_XFER_LOCK(xfer);
3078                 no_resetup =
3079                     ((xfer->address == udev->address) &&
3080                     (udev->ctrl_ep_desc.wMaxPacketSize[0] ==
3081                     udev->ddesc.bMaxPacketSize));
3082                 if (udev->flags.usb_mode == USB_MODE_DEVICE) {
3083                         if (no_resetup) {
3084                                 /*
3085                                  * NOTE: checking "xfer->address" and
3086                                  * starting the USB transfer must be
3087                                  * atomic!
3088                                  */
3089                                 usbd_transfer_start(xfer);
3090                         }
3091                 }
3092                 USB_XFER_UNLOCK(xfer);
3093         } else {
3094                 no_resetup = 0;
3095         }
3096
3097         if (no_resetup) {
3098                 /*
3099                  * All parameters are exactly the same like before.
3100                  * Just return.
3101                  */
3102                 return;
3103         }
3104         /*
3105          * Update wMaxPacketSize for the default control endpoint:
3106          */
3107         udev->ctrl_ep_desc.wMaxPacketSize[0] =
3108             udev->ddesc.bMaxPacketSize;
3109
3110         /*
3111          * Unsetup any existing USB transfer:
3112          */
3113         usbd_transfer_unsetup(udev->ctrl_xfer, USB_CTRL_XFER_MAX);
3114
3115         /*
3116          * Reset clear stall error counter.
3117          */
3118         udev->clear_stall_errors = 0;
3119
3120         /*
3121          * Try to setup a new USB transfer for the
3122          * default control endpoint:
3123          */
3124         iface_index = 0;
3125         if (usbd_transfer_setup(udev, &iface_index,
3126             udev->ctrl_xfer, usb_control_ep_cfg, USB_CTRL_XFER_MAX, NULL,
3127             &udev->device_mtx)) {
3128                 DPRINTFN(0, "could not setup default "
3129                     "USB transfer\n");
3130         } else {
3131                 goto repeat;
3132         }
3133 }
3134
3135 /*------------------------------------------------------------------------*
3136  *      usbd_clear_data_toggle - factored out code
3137  *
3138  * NOTE: the intention of this function is not to reset the hardware
3139  * data toggle.
3140  *------------------------------------------------------------------------*/
3141 void
3142 usbd_clear_stall_locked(struct usb_device *udev, struct usb_endpoint *ep)
3143 {
3144         USB_BUS_LOCK_ASSERT(udev->bus, MA_OWNED);
3145
3146         /* check that we have a valid case */
3147         if (udev->flags.usb_mode == USB_MODE_HOST &&
3148             udev->parent_hub != NULL &&
3149             udev->bus->methods->clear_stall != NULL &&
3150             ep->methods != NULL) {
3151                 (udev->bus->methods->clear_stall) (udev, ep);
3152         }
3153 }
3154
3155 /*------------------------------------------------------------------------*
3156  *      usbd_clear_data_toggle - factored out code
3157  *
3158  * NOTE: the intention of this function is not to reset the hardware
3159  * data toggle on the USB device side.
3160  *------------------------------------------------------------------------*/
3161 void
3162 usbd_clear_data_toggle(struct usb_device *udev, struct usb_endpoint *ep)
3163 {
3164         DPRINTFN(5, "udev=%p endpoint=%p\n", udev, ep);
3165
3166         USB_BUS_LOCK(udev->bus);
3167         ep->toggle_next = 0;
3168         /* some hardware needs a callback to clear the data toggle */
3169         usbd_clear_stall_locked(udev, ep);
3170         USB_BUS_UNLOCK(udev->bus);
3171 }
3172
3173 /*------------------------------------------------------------------------*
3174  *      usbd_clear_stall_callback - factored out clear stall callback
3175  *
3176  * Input parameters:
3177  *  xfer1: Clear Stall Control Transfer
3178  *  xfer2: Stalled USB Transfer
3179  *
3180  * This function is NULL safe.
3181  *
3182  * Return values:
3183  *   0: In progress
3184  *   Else: Finished
3185  *
3186  * Clear stall config example:
3187  *
3188  * static const struct usb_config my_clearstall =  {
3189  *      .type = UE_CONTROL,
3190  *      .endpoint = 0,
3191  *      .direction = UE_DIR_ANY,
3192  *      .interval = 50, //50 milliseconds
3193  *      .bufsize = sizeof(struct usb_device_request),
3194  *      .timeout = 1000, //1.000 seconds
3195  *      .callback = &my_clear_stall_callback, // **
3196  *      .usb_mode = USB_MODE_HOST,
3197  * };
3198  *
3199  * ** "my_clear_stall_callback" calls "usbd_clear_stall_callback"
3200  * passing the correct parameters.
3201  *------------------------------------------------------------------------*/
3202 uint8_t
3203 usbd_clear_stall_callback(struct usb_xfer *xfer1,
3204     struct usb_xfer *xfer2)
3205 {
3206         struct usb_device_request req;
3207
3208         if (xfer2 == NULL) {
3209                 /* looks like we are tearing down */
3210                 DPRINTF("NULL input parameter\n");
3211                 return (0);
3212         }
3213         USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
3214         USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
3215
3216         switch (USB_GET_STATE(xfer1)) {
3217         case USB_ST_SETUP:
3218
3219                 /*
3220                  * pre-clear the data toggle to DATA0 ("umass.c" and
3221                  * "ata-usb.c" depends on this)
3222                  */
3223
3224                 usbd_clear_data_toggle(xfer2->xroot->udev, xfer2->endpoint);
3225
3226                 /* setup a clear-stall packet */
3227
3228                 req.bmRequestType = UT_WRITE_ENDPOINT;
3229                 req.bRequest = UR_CLEAR_FEATURE;
3230                 USETW(req.wValue, UF_ENDPOINT_HALT);
3231                 req.wIndex[0] = xfer2->endpoint->edesc->bEndpointAddress;
3232                 req.wIndex[1] = 0;
3233                 USETW(req.wLength, 0);
3234
3235                 /*
3236                  * "usbd_transfer_setup_sub()" will ensure that
3237                  * we have sufficient room in the buffer for
3238                  * the request structure!
3239                  */
3240
3241                 /* copy in the transfer */
3242
3243                 usbd_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
3244
3245                 /* set length */
3246                 xfer1->frlengths[0] = sizeof(req);
3247                 xfer1->nframes = 1;
3248
3249                 usbd_transfer_submit(xfer1);
3250                 return (0);
3251
3252         case USB_ST_TRANSFERRED:
3253                 break;
3254
3255         default:                        /* Error */
3256                 if (xfer1->error == USB_ERR_CANCELLED) {
3257                         return (0);
3258                 }
3259                 break;
3260         }
3261         return (1);                     /* Clear Stall Finished */
3262 }
3263
3264 /*------------------------------------------------------------------------*
3265  *      usbd_transfer_poll
3266  *
3267  * The following function gets called from the USB keyboard driver and
3268  * UMASS when the system has paniced.
3269  *
3270  * NOTE: It is currently not possible to resume normal operation on
3271  * the USB controller which has been polled, due to clearing of the
3272  * "up_dsleep" and "up_msleep" flags.
3273  *------------------------------------------------------------------------*/
3274 void
3275 usbd_transfer_poll(struct usb_xfer **ppxfer, uint16_t max)
3276 {
3277         struct usb_xfer *xfer;
3278         struct usb_xfer_root *xroot;
3279         struct usb_device *udev;
3280         struct usb_proc_msg *pm;
3281         uint16_t n;
3282         uint16_t drop_bus;
3283         uint16_t drop_xfer;
3284
3285         for (n = 0; n != max; n++) {
3286                 /* Extra checks to avoid panic */
3287                 xfer = ppxfer[n];
3288                 if (xfer == NULL)
3289                         continue;       /* no USB transfer */
3290                 xroot = xfer->xroot;
3291                 if (xroot == NULL)
3292                         continue;       /* no USB root */
3293                 udev = xroot->udev;
3294                 if (udev == NULL)
3295                         continue;       /* no USB device */
3296                 if (udev->bus == NULL)
3297                         continue;       /* no BUS structure */
3298                 if (udev->bus->methods == NULL)
3299                         continue;       /* no BUS methods */
3300                 if (udev->bus->methods->xfer_poll == NULL)
3301                         continue;       /* no poll method */
3302
3303                 /* make sure that the BUS mutex is not locked */
3304                 drop_bus = 0;
3305                 while (mtx_owned(&xroot->udev->bus->bus_mtx) && !SCHEDULER_STOPPED()) {
3306                         mtx_unlock(&xroot->udev->bus->bus_mtx);
3307                         drop_bus++;
3308                 }
3309
3310                 /* make sure that the transfer mutex is not locked */
3311                 drop_xfer = 0;
3312                 while (mtx_owned(xroot->xfer_mtx) && !SCHEDULER_STOPPED()) {
3313                         mtx_unlock(xroot->xfer_mtx);
3314                         drop_xfer++;
3315                 }
3316
3317                 /* Make sure cv_signal() and cv_broadcast() is not called */
3318                 USB_BUS_CONTROL_XFER_PROC(udev->bus)->up_msleep = 0;
3319                 USB_BUS_EXPLORE_PROC(udev->bus)->up_msleep = 0;
3320                 USB_BUS_GIANT_PROC(udev->bus)->up_msleep = 0;
3321                 USB_BUS_NON_GIANT_PROC(udev->bus)->up_msleep = 0;
3322
3323                 /* poll USB hardware */
3324                 (udev->bus->methods->xfer_poll) (udev->bus);
3325
3326                 USB_BUS_LOCK(xroot->bus);
3327
3328                 /* check for clear stall */
3329                 if (udev->ctrl_xfer[1] != NULL) {
3330
3331                         /* poll clear stall start */
3332                         pm = &udev->cs_msg[0].hdr;
3333                         (pm->pm_callback) (pm);
3334                         /* poll clear stall done thread */
3335                         pm = &udev->ctrl_xfer[1]->
3336                             xroot->done_m[0].hdr;
3337                         (pm->pm_callback) (pm);
3338                 }
3339
3340                 /* poll done thread */
3341                 pm = &xroot->done_m[0].hdr;
3342                 (pm->pm_callback) (pm);
3343
3344                 USB_BUS_UNLOCK(xroot->bus);
3345
3346                 /* restore transfer mutex */
3347                 while (drop_xfer--)
3348                         mtx_lock(xroot->xfer_mtx);
3349
3350                 /* restore BUS mutex */
3351                 while (drop_bus--)
3352                         mtx_lock(&xroot->udev->bus->bus_mtx);
3353         }
3354 }
3355
3356 static void
3357 usbd_get_std_packet_size(struct usb_std_packet_size *ptr,
3358     uint8_t type, enum usb_dev_speed speed)
3359 {
3360         static const uint16_t intr_range_max[USB_SPEED_MAX] = {
3361                 [USB_SPEED_LOW] = 8,
3362                 [USB_SPEED_FULL] = 64,
3363                 [USB_SPEED_HIGH] = 1024,
3364                 [USB_SPEED_VARIABLE] = 1024,
3365                 [USB_SPEED_SUPER] = 1024,
3366         };
3367
3368         static const uint16_t isoc_range_max[USB_SPEED_MAX] = {
3369                 [USB_SPEED_LOW] = 0,    /* invalid */
3370                 [USB_SPEED_FULL] = 1023,
3371                 [USB_SPEED_HIGH] = 1024,
3372                 [USB_SPEED_VARIABLE] = 3584,
3373                 [USB_SPEED_SUPER] = 1024,
3374         };
3375
3376         static const uint16_t control_min[USB_SPEED_MAX] = {
3377                 [USB_SPEED_LOW] = 8,
3378                 [USB_SPEED_FULL] = 8,
3379                 [USB_SPEED_HIGH] = 64,
3380                 [USB_SPEED_VARIABLE] = 512,
3381                 [USB_SPEED_SUPER] = 512,
3382         };
3383
3384         static const uint16_t bulk_min[USB_SPEED_MAX] = {
3385                 [USB_SPEED_LOW] = 8,
3386                 [USB_SPEED_FULL] = 8,
3387                 [USB_SPEED_HIGH] = 512,
3388                 [USB_SPEED_VARIABLE] = 512,
3389                 [USB_SPEED_SUPER] = 1024,
3390         };
3391
3392         uint16_t temp;
3393
3394         memset(ptr, 0, sizeof(*ptr));
3395
3396         switch (type) {
3397         case UE_INTERRUPT:
3398                 ptr->range.max = intr_range_max[speed];
3399                 break;
3400         case UE_ISOCHRONOUS:
3401                 ptr->range.max = isoc_range_max[speed];
3402                 break;
3403         default:
3404                 if (type == UE_BULK)
3405                         temp = bulk_min[speed];
3406                 else /* UE_CONTROL */
3407                         temp = control_min[speed];
3408
3409                 /* default is fixed */
3410                 ptr->fixed[0] = temp;
3411                 ptr->fixed[1] = temp;
3412                 ptr->fixed[2] = temp;
3413                 ptr->fixed[3] = temp;
3414
3415                 if (speed == USB_SPEED_FULL) {
3416                         /* multiple sizes */
3417                         ptr->fixed[1] = 16;
3418                         ptr->fixed[2] = 32;
3419                         ptr->fixed[3] = 64;
3420                 }
3421                 if ((speed == USB_SPEED_VARIABLE) &&
3422                     (type == UE_BULK)) {
3423                         /* multiple sizes */
3424                         ptr->fixed[2] = 1024;
3425                         ptr->fixed[3] = 1536;
3426                 }
3427                 break;
3428         }
3429 }
3430
3431 void    *
3432 usbd_xfer_softc(struct usb_xfer *xfer)
3433 {
3434         return (xfer->priv_sc);
3435 }
3436
3437 void *
3438 usbd_xfer_get_priv(struct usb_xfer *xfer)
3439 {
3440         return (xfer->priv_fifo);
3441 }
3442
3443 void
3444 usbd_xfer_set_priv(struct usb_xfer *xfer, void *ptr)
3445 {
3446         xfer->priv_fifo = ptr;
3447 }
3448
3449 uint8_t
3450 usbd_xfer_state(struct usb_xfer *xfer)
3451 {
3452         return (xfer->usb_state);
3453 }
3454
3455 void
3456 usbd_xfer_set_flag(struct usb_xfer *xfer, int flag)
3457 {
3458         switch (flag) {
3459                 case USB_FORCE_SHORT_XFER:
3460                         xfer->flags.force_short_xfer = 1;
3461                         break;
3462                 case USB_SHORT_XFER_OK:
3463                         xfer->flags.short_xfer_ok = 1;
3464                         break;
3465                 case USB_MULTI_SHORT_OK:
3466                         xfer->flags.short_frames_ok = 1;
3467                         break;
3468                 case USB_MANUAL_STATUS:
3469                         xfer->flags.manual_status = 1;
3470                         break;
3471         }
3472 }
3473
3474 void
3475 usbd_xfer_clr_flag(struct usb_xfer *xfer, int flag)
3476 {
3477         switch (flag) {
3478                 case USB_FORCE_SHORT_XFER:
3479                         xfer->flags.force_short_xfer = 0;
3480                         break;
3481                 case USB_SHORT_XFER_OK:
3482                         xfer->flags.short_xfer_ok = 0;
3483                         break;
3484                 case USB_MULTI_SHORT_OK:
3485                         xfer->flags.short_frames_ok = 0;
3486                         break;
3487                 case USB_MANUAL_STATUS:
3488                         xfer->flags.manual_status = 0;
3489                         break;
3490         }
3491 }
3492
3493 /*
3494  * The following function returns in milliseconds when the isochronous
3495  * transfer was completed by the hardware. The returned value wraps
3496  * around 65536 milliseconds.
3497  */
3498 uint16_t
3499 usbd_xfer_get_timestamp(struct usb_xfer *xfer)
3500 {
3501         return (xfer->isoc_time_complete);
3502 }
3503
3504 /*
3505  * The following function returns non-zero if the max packet size
3506  * field was clamped to a valid value. Else it returns zero.
3507  */
3508 uint8_t
3509 usbd_xfer_maxp_was_clamped(struct usb_xfer *xfer)
3510 {
3511         return (xfer->flags_int.maxp_was_clamped);
3512 }