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