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