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