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