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