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