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