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