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