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