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