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