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