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