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