usb_transfer.c revision 188411
1/* $FreeBSD: head/sys/dev/usb2/core/usb2_transfer.c 188411 2009-02-09 21:56:33Z 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	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
1694
1695	if (xfer->flags_int.transferring) {
1696		/* trivial case */
1697		return (1);
1698	}
1699	USB_BUS_LOCK(xfer->xroot->bus);
1700	if (xfer->wait_queue) {
1701		/* we are waiting on a queue somewhere */
1702		USB_BUS_UNLOCK(xfer->xroot->bus);
1703		return (1);
1704	}
1705	info = xfer->xroot;
1706	pq = &info->done_q;
1707
1708	if (pq->curr == xfer) {
1709		/* we are currently scheduled for callback */
1710		USB_BUS_UNLOCK(xfer->xroot->bus);
1711		return (1);
1712	}
1713	/* we are not pending */
1714	USB_BUS_UNLOCK(xfer->xroot->bus);
1715	return (0);
1716}
1717
1718/*------------------------------------------------------------------------*
1719 *	usb2_transfer_drain
1720 *
1721 * This function will stop the USB transfer and wait for any
1722 * additional BUS-DMA and HW-DMA operations to complete. Buffers that
1723 * are loaded into DMA can safely be freed or reused after that this
1724 * function has returned.
1725 *------------------------------------------------------------------------*/
1726void
1727usb2_transfer_drain(struct usb2_xfer *xfer)
1728{
1729	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1730	    "usb2_transfer_drain can sleep!");
1731
1732	if (xfer == NULL) {
1733		/* transfer is gone */
1734		return;
1735	}
1736	if (xfer->xroot->xfer_mtx != &Giant) {
1737		USB_XFER_LOCK_ASSERT(xfer, MA_NOTOWNED);
1738	}
1739	USB_XFER_LOCK(xfer);
1740
1741	usb2_transfer_stop(xfer);
1742
1743	while (usb2_transfer_pending(xfer)) {
1744		xfer->flags_int.draining = 1;
1745		/*
1746		 * Wait until the current outstanding USB
1747		 * transfer is complete !
1748		 */
1749		usb2_cv_wait(&xfer->xroot->cv_drain, xfer->xroot->xfer_mtx);
1750	}
1751	USB_XFER_UNLOCK(xfer);
1752}
1753
1754/*------------------------------------------------------------------------*
1755 *	usb2_set_frame_data
1756 *
1757 * This function sets the pointer of the buffer that should
1758 * loaded directly into DMA for the given USB frame. Passing "ptr"
1759 * equal to NULL while the corresponding "frlength" is greater
1760 * than zero gives undefined results!
1761 *------------------------------------------------------------------------*/
1762void
1763usb2_set_frame_data(struct usb2_xfer *xfer, void *ptr, uint32_t frindex)
1764{
1765	/* set virtual address to load and length */
1766	xfer->frbuffers[frindex].buffer = ptr;
1767}
1768
1769/*------------------------------------------------------------------------*
1770 *	usb2_set_frame_offset
1771 *
1772 * This function sets the frame data buffer offset relative to the beginning
1773 * of the USB DMA buffer allocated for this USB transfer.
1774 *------------------------------------------------------------------------*/
1775void
1776usb2_set_frame_offset(struct usb2_xfer *xfer, uint32_t offset,
1777    uint32_t frindex)
1778{
1779	USB_ASSERT(!xfer->flags.ext_buffer, ("Cannot offset data frame "
1780	    "when the USB buffer is external!\n"));
1781
1782	/* set virtual address to load */
1783	xfer->frbuffers[frindex].buffer =
1784	    USB_ADD_BYTES(xfer->local_buffer, offset);
1785}
1786
1787/*------------------------------------------------------------------------*
1788 *	usb2_callback_proc - factored out code
1789 *
1790 * This function performs USB callbacks.
1791 *------------------------------------------------------------------------*/
1792static void
1793usb2_callback_proc(struct usb2_proc_msg *_pm)
1794{
1795	struct usb2_done_msg *pm = (void *)_pm;
1796	struct usb2_xfer_root *info = pm->xroot;
1797
1798	/* Change locking order */
1799	USB_BUS_UNLOCK(info->bus);
1800
1801	/*
1802	 * We exploit the fact that the mutex is the same for all
1803	 * callbacks that will be called from this thread:
1804	 */
1805	mtx_lock(info->xfer_mtx);
1806	USB_BUS_LOCK(info->bus);
1807
1808	/* Continue where we lost track */
1809	usb2_command_wrapper(&info->done_q,
1810	    info->done_q.curr);
1811
1812	mtx_unlock(info->xfer_mtx);
1813}
1814
1815/*------------------------------------------------------------------------*
1816 *	usb2_callback_ss_done_defer
1817 *
1818 * This function will defer the start, stop and done callback to the
1819 * correct thread.
1820 *------------------------------------------------------------------------*/
1821static void
1822usb2_callback_ss_done_defer(struct usb2_xfer *xfer)
1823{
1824	struct usb2_xfer_root *info = xfer->xroot;
1825	struct usb2_xfer_queue *pq = &info->done_q;
1826
1827	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1828
1829	if (pq->curr != xfer) {
1830		usb2_transfer_enqueue(pq, xfer);
1831	}
1832	if (!pq->recurse_1) {
1833
1834		/*
1835	         * We have to postpone the callback due to the fact we
1836	         * will have a Lock Order Reversal, LOR, if we try to
1837	         * proceed !
1838	         */
1839		if (usb2_proc_msignal(info->done_p,
1840		    &info->done_m[0], &info->done_m[1])) {
1841			/* ignore */
1842		}
1843	} else {
1844		/* clear second recurse flag */
1845		pq->recurse_2 = 0;
1846	}
1847	return;
1848
1849}
1850
1851/*------------------------------------------------------------------------*
1852 *	usb2_callback_wrapper
1853 *
1854 * This is a wrapper for USB callbacks. This wrapper does some
1855 * auto-magic things like figuring out if we can call the callback
1856 * directly from the current context or if we need to wakeup the
1857 * interrupt process.
1858 *------------------------------------------------------------------------*/
1859static void
1860usb2_callback_wrapper(struct usb2_xfer_queue *pq)
1861{
1862	struct usb2_xfer *xfer = pq->curr;
1863	struct usb2_xfer_root *info = xfer->xroot;
1864
1865	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1866	if (!mtx_owned(xfer->xroot->xfer_mtx)) {
1867		/*
1868	       	 * Cases that end up here:
1869		 *
1870		 * 5) HW interrupt done callback or other source.
1871		 */
1872		DPRINTFN(3, "case 5\n");
1873
1874		/*
1875	         * We have to postpone the callback due to the fact we
1876	         * will have a Lock Order Reversal, LOR, if we try to
1877	         * proceed !
1878	         */
1879		if (usb2_proc_msignal(info->done_p,
1880		    &info->done_m[0], &info->done_m[1])) {
1881			/* ignore */
1882		}
1883		return;
1884	}
1885	/*
1886	 * Cases that end up here:
1887	 *
1888	 * 1) We are starting a transfer
1889	 * 2) We are prematurely calling back a transfer
1890	 * 3) We are stopping a transfer
1891	 * 4) We are doing an ordinary callback
1892	 */
1893	DPRINTFN(3, "case 1-4\n");
1894	/* get next USB transfer in the queue */
1895	info->done_q.curr = NULL;
1896
1897	USB_BUS_UNLOCK(xfer->xroot->bus);
1898	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_NOTOWNED);
1899
1900	/* set correct USB state for callback */
1901	if (!xfer->flags_int.transferring) {
1902		xfer->usb2_state = USB_ST_SETUP;
1903		if (!xfer->flags_int.started) {
1904			/* we got stopped before we even got started */
1905			USB_BUS_LOCK(xfer->xroot->bus);
1906			goto done;
1907		}
1908	} else {
1909
1910		if (usb2_callback_wrapper_sub(xfer)) {
1911			/* the callback has been deferred */
1912			USB_BUS_LOCK(xfer->xroot->bus);
1913			goto done;
1914		}
1915		/* decrement power reference */
1916		usb2_transfer_power_ref(xfer, -1);
1917
1918		xfer->flags_int.transferring = 0;
1919
1920		if (xfer->error) {
1921			xfer->usb2_state = USB_ST_ERROR;
1922		} else {
1923			/* set transferred state */
1924			xfer->usb2_state = USB_ST_TRANSFERRED;
1925
1926			/* sync DMA memory, if any */
1927			if (xfer->flags_int.bdma_enable &&
1928			    (!xfer->flags_int.bdma_no_post_sync)) {
1929				usb2_bdma_post_sync(xfer);
1930			}
1931		}
1932	}
1933
1934	/* call processing routine */
1935	(xfer->callback) (xfer);
1936
1937	/* pickup the USB mutex again */
1938	USB_BUS_LOCK(xfer->xroot->bus);
1939
1940	/*
1941	 * Check if we got started after that we got cancelled, but
1942	 * before we managed to do the callback.
1943	 */
1944	if ((!xfer->flags_int.open) &&
1945	    (xfer->flags_int.started) &&
1946	    (xfer->usb2_state == USB_ST_ERROR)) {
1947		/* try to loop, but not recursivly */
1948		usb2_command_wrapper(&info->done_q, xfer);
1949		return;
1950	}
1951
1952done:
1953	/*
1954	 * Check if we are draining.
1955	 */
1956	if (xfer->flags_int.draining &&
1957	    (!xfer->flags_int.transferring)) {
1958		/* "usb2_transfer_drain()" is waiting for end of transfer */
1959		xfer->flags_int.draining = 0;
1960		usb2_cv_broadcast(&xfer->xroot->cv_drain);
1961	}
1962
1963	/* do the next callback, if any */
1964	usb2_command_wrapper(&info->done_q,
1965	    info->done_q.curr);
1966}
1967
1968/*------------------------------------------------------------------------*
1969 *	usb2_dma_delay_done_cb
1970 *
1971 * This function is called when the DMA delay has been exectuded, and
1972 * will make sure that the callback is called to complete the USB
1973 * transfer. This code path is ususally only used when there is an USB
1974 * error like USB_ERR_CANCELLED.
1975 *------------------------------------------------------------------------*/
1976static void
1977usb2_dma_delay_done_cb(void *arg)
1978{
1979	struct usb2_xfer *xfer = arg;
1980
1981	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
1982
1983	DPRINTFN(3, "Completed %p\n", xfer);
1984
1985	/* queue callback for execution, again */
1986	usb2_transfer_done(xfer, 0);
1987}
1988
1989/*------------------------------------------------------------------------*
1990 *	usb2_transfer_dequeue
1991 *
1992 *  - This function is used to remove an USB transfer from a USB
1993 *  transfer queue.
1994 *
1995 *  - This function can be called multiple times in a row.
1996 *------------------------------------------------------------------------*/
1997void
1998usb2_transfer_dequeue(struct usb2_xfer *xfer)
1999{
2000	struct usb2_xfer_queue *pq;
2001
2002	pq = xfer->wait_queue;
2003	if (pq) {
2004		TAILQ_REMOVE(&pq->head, xfer, wait_entry);
2005		xfer->wait_queue = NULL;
2006	}
2007}
2008
2009/*------------------------------------------------------------------------*
2010 *	usb2_transfer_enqueue
2011 *
2012 *  - This function is used to insert an USB transfer into a USB *
2013 *  transfer queue.
2014 *
2015 *  - This function can be called multiple times in a row.
2016 *------------------------------------------------------------------------*/
2017void
2018usb2_transfer_enqueue(struct usb2_xfer_queue *pq, struct usb2_xfer *xfer)
2019{
2020	/*
2021	 * Insert the USB transfer into the queue, if it is not
2022	 * already on a USB transfer queue:
2023	 */
2024	if (xfer->wait_queue == NULL) {
2025		xfer->wait_queue = pq;
2026		TAILQ_INSERT_TAIL(&pq->head, xfer, wait_entry);
2027	}
2028}
2029
2030/*------------------------------------------------------------------------*
2031 *	usb2_transfer_done
2032 *
2033 *  - This function is used to remove an USB transfer from the busdma,
2034 *  pipe or interrupt queue.
2035 *
2036 *  - This function is used to queue the USB transfer on the done
2037 *  queue.
2038 *
2039 *  - This function is used to stop any USB transfer timeouts.
2040 *------------------------------------------------------------------------*/
2041void
2042usb2_transfer_done(struct usb2_xfer *xfer, usb2_error_t error)
2043{
2044	struct usb2_xfer_queue *pq;
2045
2046	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2047
2048	DPRINTF("err=%s\n", usb2_errstr(error));
2049
2050	/*
2051	 * If we are not transferring then just return.
2052	 * This can happen during transfer cancel.
2053	 */
2054	if (!xfer->flags_int.transferring) {
2055		DPRINTF("not transferring\n");
2056		return;
2057	}
2058	/* only set transfer error if not already set */
2059	if (!xfer->error) {
2060		xfer->error = error;
2061	}
2062	/* stop any callouts */
2063	usb2_callout_stop(&xfer->timeout_handle);
2064
2065	/*
2066	 * If we are waiting on a queue, just remove the USB transfer
2067	 * from the queue, if any. We should have the required locks
2068	 * locked to do the remove when this function is called.
2069	 */
2070	usb2_transfer_dequeue(xfer);
2071
2072	if (mtx_owned(xfer->xroot->xfer_mtx)) {
2073		/*
2074		 * If the private USB lock is not locked, then we assume
2075		 * that the BUS-DMA load stage has been passed:
2076		 */
2077		pq = &xfer->xroot->dma_q;
2078
2079		if (pq->curr == xfer) {
2080			/* start the next BUS-DMA load, if any */
2081			usb2_command_wrapper(pq, NULL);
2082		}
2083	}
2084	/* keep some statistics */
2085	if (xfer->error) {
2086		xfer->xroot->bus->stats_err.uds_requests
2087		    [xfer->pipe->edesc->bmAttributes & UE_XFERTYPE]++;
2088	} else {
2089		xfer->xroot->bus->stats_ok.uds_requests
2090		    [xfer->pipe->edesc->bmAttributes & UE_XFERTYPE]++;
2091	}
2092
2093	/* call the USB transfer callback */
2094	usb2_callback_ss_done_defer(xfer);
2095}
2096
2097/*------------------------------------------------------------------------*
2098 *	usb2_transfer_start_cb
2099 *
2100 * This function is called to start the USB transfer when
2101 * "xfer->interval" is greater than zero, and and the endpoint type is
2102 * BULK or CONTROL.
2103 *------------------------------------------------------------------------*/
2104static void
2105usb2_transfer_start_cb(void *arg)
2106{
2107	struct usb2_xfer *xfer = arg;
2108	struct usb2_pipe *pipe = xfer->pipe;
2109
2110	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2111
2112	DPRINTF("start\n");
2113
2114	/* start the transfer */
2115	(pipe->methods->start) (xfer);
2116
2117	/* check cancelability */
2118	if (pipe->methods->start_is_cancelable) {
2119		xfer->flags_int.can_cancel_immed = 1;
2120		if (xfer->error) {
2121			/* some error has happened */
2122			usb2_transfer_done(xfer, 0);
2123		}
2124	} else {
2125		xfer->flags_int.can_cancel_immed = 0;
2126	}
2127}
2128
2129/*------------------------------------------------------------------------*
2130 *	usb2_transfer_set_stall
2131 *
2132 * This function is used to set the stall flag outside the
2133 * callback. This function is NULL safe.
2134 *------------------------------------------------------------------------*/
2135void
2136usb2_transfer_set_stall(struct usb2_xfer *xfer)
2137{
2138	if (xfer == NULL) {
2139		/* tearing down */
2140		return;
2141	}
2142	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2143
2144	/* avoid any races by locking the USB mutex */
2145	USB_BUS_LOCK(xfer->xroot->bus);
2146
2147	xfer->flags.stall_pipe = 1;
2148
2149	USB_BUS_UNLOCK(xfer->xroot->bus);
2150}
2151
2152/*------------------------------------------------------------------------*
2153 *	usb2_transfer_clear_stall
2154 *
2155 * This function is used to clear the stall flag outside the
2156 * callback. This function is NULL safe.
2157 *------------------------------------------------------------------------*/
2158void
2159usb2_transfer_clear_stall(struct usb2_xfer *xfer)
2160{
2161	if (xfer == NULL) {
2162		/* tearing down */
2163		return;
2164	}
2165	USB_XFER_LOCK_ASSERT(xfer, MA_OWNED);
2166
2167	/* avoid any races by locking the USB mutex */
2168	USB_BUS_LOCK(xfer->xroot->bus);
2169
2170	xfer->flags.stall_pipe = 0;
2171
2172	USB_BUS_UNLOCK(xfer->xroot->bus);
2173}
2174
2175/*------------------------------------------------------------------------*
2176 *	usb2_pipe_start
2177 *
2178 * This function is used to add an USB transfer to the pipe transfer list.
2179 *------------------------------------------------------------------------*/
2180void
2181usb2_pipe_start(struct usb2_xfer_queue *pq)
2182{
2183	struct usb2_pipe *pipe;
2184	struct usb2_xfer *xfer;
2185	uint8_t type;
2186
2187	xfer = pq->curr;
2188	pipe = xfer->pipe;
2189
2190	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2191
2192	/*
2193	 * If the pipe is already stalled we do nothing !
2194	 */
2195	if (pipe->is_stalled) {
2196		return;
2197	}
2198	/*
2199	 * Check if we are supposed to stall the pipe:
2200	 */
2201	if (xfer->flags.stall_pipe) {
2202		/* clear stall command */
2203		xfer->flags.stall_pipe = 0;
2204
2205		/*
2206		 * Only stall BULK and INTERRUPT endpoints.
2207		 */
2208		type = (pipe->edesc->bmAttributes & UE_XFERTYPE);
2209		if ((type == UE_BULK) ||
2210		    (type == UE_INTERRUPT)) {
2211			struct usb2_device *udev;
2212			struct usb2_xfer_root *info;
2213
2214			info = xfer->xroot;
2215			udev = info->udev;
2216			pipe->is_stalled = 1;
2217
2218			if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
2219				(udev->bus->methods->set_stall) (
2220				    udev, NULL, pipe);
2221			} else if (udev->default_xfer[1]) {
2222				info = udev->default_xfer[1]->xroot;
2223				if (usb2_proc_msignal(
2224				    &info->bus->non_giant_callback_proc,
2225				    &udev->cs_msg[0], &udev->cs_msg[1])) {
2226					/* ignore */
2227				}
2228			} else {
2229				/* should not happen */
2230				DPRINTFN(0, "No stall handler!\n");
2231			}
2232			/*
2233			 * We get started again when the stall is cleared!
2234			 */
2235			return;
2236		}
2237	}
2238	/* Set or clear stall complete - special case */
2239	if (xfer->nframes == 0) {
2240		/* we are complete */
2241		xfer->aframes = 0;
2242		usb2_transfer_done(xfer, 0);
2243		return;
2244	}
2245	/*
2246	 * Handled cases:
2247	 *
2248	 * 1) Start the first transfer queued.
2249	 *
2250	 * 2) Re-start the current USB transfer.
2251	 */
2252	/*
2253	 * Check if there should be any
2254	 * pre transfer start delay:
2255	 */
2256	if (xfer->interval > 0) {
2257		type = (pipe->edesc->bmAttributes & UE_XFERTYPE);
2258		if ((type == UE_BULK) ||
2259		    (type == UE_CONTROL)) {
2260			usb2_transfer_timeout_ms(xfer,
2261			    &usb2_transfer_start_cb,
2262			    xfer->interval);
2263			return;
2264		}
2265	}
2266	DPRINTF("start\n");
2267
2268	/* start USB transfer */
2269	(pipe->methods->start) (xfer);
2270
2271	/* check cancelability */
2272	if (pipe->methods->start_is_cancelable) {
2273		xfer->flags_int.can_cancel_immed = 1;
2274		if (xfer->error) {
2275			/* some error has happened */
2276			usb2_transfer_done(xfer, 0);
2277		}
2278	} else {
2279		xfer->flags_int.can_cancel_immed = 0;
2280	}
2281}
2282
2283/*------------------------------------------------------------------------*
2284 *	usb2_transfer_timeout_ms
2285 *
2286 * This function is used to setup a timeout on the given USB
2287 * transfer. If the timeout has been deferred the callback given by
2288 * "cb" will get called after "ms" milliseconds.
2289 *------------------------------------------------------------------------*/
2290void
2291usb2_transfer_timeout_ms(struct usb2_xfer *xfer,
2292    void (*cb) (void *arg), uint32_t ms)
2293{
2294	USB_BUS_LOCK_ASSERT(xfer->xroot->bus, MA_OWNED);
2295
2296	/* defer delay */
2297	usb2_callout_reset(&xfer->timeout_handle,
2298	    USB_MS_TO_TICKS(ms), cb, xfer);
2299}
2300
2301/*------------------------------------------------------------------------*
2302 *	usb2_callback_wrapper_sub
2303 *
2304 *  - This function will update variables in an USB transfer after
2305 *  that the USB transfer is complete.
2306 *
2307 *  - This function is used to start the next USB transfer on the
2308 *  pipe transfer queue, if any.
2309 *
2310 * NOTE: In some special cases the USB transfer will not be removed from
2311 * the pipe queue, but remain first. To enforce USB transfer removal call
2312 * this function passing the error code "USB_ERR_CANCELLED".
2313 *
2314 * Return values:
2315 * 0: Success.
2316 * Else: The callback has been deferred.
2317 *------------------------------------------------------------------------*/
2318static uint8_t
2319usb2_callback_wrapper_sub(struct usb2_xfer *xfer)
2320{
2321	struct usb2_pipe *pipe;
2322	uint32_t x;
2323
2324	if ((!xfer->flags_int.open) &&
2325	    (!xfer->flags_int.did_close)) {
2326		DPRINTF("close\n");
2327		USB_BUS_LOCK(xfer->xroot->bus);
2328		(xfer->pipe->methods->close) (xfer);
2329		USB_BUS_UNLOCK(xfer->xroot->bus);
2330		/* only close once */
2331		xfer->flags_int.did_close = 1;
2332		return (1);		/* wait for new callback */
2333	}
2334	/*
2335	 * If we have a non-hardware induced error we
2336	 * need to do the DMA delay!
2337	 */
2338	if (((xfer->error == USB_ERR_CANCELLED) ||
2339	    (xfer->error == USB_ERR_TIMEOUT)) &&
2340	    (!xfer->flags_int.did_dma_delay)) {
2341
2342		uint32_t temp;
2343
2344		/* only delay once */
2345		xfer->flags_int.did_dma_delay = 1;
2346
2347		/* we can not cancel this delay */
2348		xfer->flags_int.can_cancel_immed = 0;
2349
2350		temp = usb2_get_dma_delay(xfer->xroot->bus);
2351
2352		DPRINTFN(3, "DMA delay, %u ms, "
2353		    "on %p\n", temp, xfer);
2354
2355		if (temp != 0) {
2356			USB_BUS_LOCK(xfer->xroot->bus);
2357			usb2_transfer_timeout_ms(xfer,
2358			    &usb2_dma_delay_done_cb, temp);
2359			USB_BUS_UNLOCK(xfer->xroot->bus);
2360			return (1);	/* wait for new callback */
2361		}
2362	}
2363	/* check actual number of frames */
2364	if (xfer->aframes > xfer->nframes) {
2365		if (xfer->error == 0) {
2366			panic("%s: actual number of frames, %d, is "
2367			    "greater than initial number of frames, %d!\n",
2368			    __FUNCTION__, xfer->aframes, xfer->nframes);
2369		} else {
2370			/* just set some valid value */
2371			xfer->aframes = xfer->nframes;
2372		}
2373	}
2374	/* compute actual length */
2375	xfer->actlen = 0;
2376
2377	for (x = 0; x != xfer->aframes; x++) {
2378		xfer->actlen += xfer->frlengths[x];
2379	}
2380
2381	/*
2382	 * Frames that were not transferred get zero actual length in
2383	 * case the USB device driver does not check the actual number
2384	 * of frames transferred, "xfer->aframes":
2385	 */
2386	for (; x < xfer->nframes; x++) {
2387		xfer->frlengths[x] = 0;
2388	}
2389
2390	/* check actual length */
2391	if (xfer->actlen > xfer->sumlen) {
2392		if (xfer->error == 0) {
2393			panic("%s: actual length, %d, is greater than "
2394			    "initial length, %d!\n",
2395			    __FUNCTION__, xfer->actlen, xfer->sumlen);
2396		} else {
2397			/* just set some valid value */
2398			xfer->actlen = xfer->sumlen;
2399		}
2400	}
2401	DPRINTFN(6, "xfer=%p pipe=%p sts=%d alen=%d, slen=%d, afrm=%d, nfrm=%d\n",
2402	    xfer, xfer->pipe, xfer->error, xfer->actlen, xfer->sumlen,
2403	    xfer->aframes, xfer->nframes);
2404
2405	if (xfer->error) {
2406		/* end of control transfer, if any */
2407		xfer->flags_int.control_act = 0;
2408
2409		/* check if we should block the execution queue */
2410		if ((xfer->error != USB_ERR_CANCELLED) &&
2411		    (xfer->flags.pipe_bof)) {
2412			DPRINTFN(2, "xfer=%p: Block On Failure "
2413			    "on pipe=%p\n", xfer, xfer->pipe);
2414			goto done;
2415		}
2416	} else {
2417		/* check for short transfers */
2418		if (xfer->actlen < xfer->sumlen) {
2419
2420			/* end of control transfer, if any */
2421			xfer->flags_int.control_act = 0;
2422
2423			if (!xfer->flags_int.short_xfer_ok) {
2424				xfer->error = USB_ERR_SHORT_XFER;
2425				if (xfer->flags.pipe_bof) {
2426					DPRINTFN(2, "xfer=%p: Block On Failure on "
2427					    "Short Transfer on pipe %p.\n",
2428					    xfer, xfer->pipe);
2429					goto done;
2430				}
2431			}
2432		} else {
2433			/*
2434			 * Check if we are in the middle of a
2435			 * control transfer:
2436			 */
2437			if (xfer->flags_int.control_act) {
2438				DPRINTFN(5, "xfer=%p: Control transfer "
2439				    "active on pipe=%p\n", xfer, xfer->pipe);
2440				goto done;
2441			}
2442		}
2443	}
2444
2445	pipe = xfer->pipe;
2446
2447	/*
2448	 * If the current USB transfer is completing we need to start the
2449	 * next one:
2450	 */
2451	USB_BUS_LOCK(xfer->xroot->bus);
2452	if (pipe->pipe_q.curr == xfer) {
2453		usb2_command_wrapper(&pipe->pipe_q, NULL);
2454
2455		if (pipe->pipe_q.curr || TAILQ_FIRST(&pipe->pipe_q.head)) {
2456			/* there is another USB transfer waiting */
2457		} else {
2458			/* this is the last USB transfer */
2459			/* clear isochronous sync flag */
2460			xfer->pipe->is_synced = 0;
2461		}
2462	}
2463	USB_BUS_UNLOCK(xfer->xroot->bus);
2464done:
2465	return (0);
2466}
2467
2468/*------------------------------------------------------------------------*
2469 *	usb2_command_wrapper
2470 *
2471 * This function is used to execute commands non-recursivly on an USB
2472 * transfer.
2473 *------------------------------------------------------------------------*/
2474void
2475usb2_command_wrapper(struct usb2_xfer_queue *pq, struct usb2_xfer *xfer)
2476{
2477	if (xfer) {
2478		/*
2479		 * If the transfer is not already processing,
2480		 * queue it!
2481		 */
2482		if (pq->curr != xfer) {
2483			usb2_transfer_enqueue(pq, xfer);
2484			if (pq->curr != NULL) {
2485				/* something is already processing */
2486				DPRINTFN(6, "busy %p\n", pq->curr);
2487				return;
2488			}
2489		}
2490	} else {
2491		/* Get next element in queue */
2492		pq->curr = NULL;
2493	}
2494
2495	if (!pq->recurse_1) {
2496
2497		do {
2498
2499			/* set both recurse flags */
2500			pq->recurse_1 = 1;
2501			pq->recurse_2 = 1;
2502
2503			if (pq->curr == NULL) {
2504				xfer = TAILQ_FIRST(&pq->head);
2505				if (xfer) {
2506					TAILQ_REMOVE(&pq->head, xfer,
2507					    wait_entry);
2508					xfer->wait_queue = NULL;
2509					pq->curr = xfer;
2510				} else {
2511					break;
2512				}
2513			}
2514			DPRINTFN(6, "cb %p (enter)\n", pq->curr);
2515			(pq->command) (pq);
2516			DPRINTFN(6, "cb %p (leave)\n", pq->curr);
2517
2518		} while (!pq->recurse_2);
2519
2520		/* clear first recurse flag */
2521		pq->recurse_1 = 0;
2522
2523	} else {
2524		/* clear second recurse flag */
2525		pq->recurse_2 = 0;
2526	}
2527}
2528
2529/*------------------------------------------------------------------------*
2530 *	usb2_default_transfer_setup
2531 *
2532 * This function is used to setup the default USB control endpoint
2533 * transfer.
2534 *------------------------------------------------------------------------*/
2535void
2536usb2_default_transfer_setup(struct usb2_device *udev)
2537{
2538	struct usb2_xfer *xfer;
2539	uint8_t no_resetup;
2540	uint8_t iface_index;
2541
2542repeat:
2543
2544	xfer = udev->default_xfer[0];
2545	if (xfer) {
2546		USB_XFER_LOCK(xfer);
2547		no_resetup =
2548		    ((xfer->address == udev->address) &&
2549		    (udev->default_ep_desc.wMaxPacketSize[0] ==
2550		    udev->ddesc.bMaxPacketSize));
2551		if (udev->flags.usb2_mode == USB_MODE_DEVICE) {
2552			if (no_resetup) {
2553				/*
2554				 * NOTE: checking "xfer->address" and
2555				 * starting the USB transfer must be
2556				 * atomic!
2557				 */
2558				usb2_transfer_start(xfer);
2559			}
2560		}
2561		USB_XFER_UNLOCK(xfer);
2562	} else {
2563		no_resetup = 0;
2564	}
2565
2566	if (no_resetup) {
2567		/*
2568	         * All parameters are exactly the same like before.
2569	         * Just return.
2570	         */
2571		return;
2572	}
2573	/*
2574	 * Update wMaxPacketSize for the default control endpoint:
2575	 */
2576	udev->default_ep_desc.wMaxPacketSize[0] =
2577	    udev->ddesc.bMaxPacketSize;
2578
2579	/*
2580	 * Unsetup any existing USB transfer:
2581	 */
2582	usb2_transfer_unsetup(udev->default_xfer, USB_DEFAULT_XFER_MAX);
2583
2584	/*
2585	 * Try to setup a new USB transfer for the
2586	 * default control endpoint:
2587	 */
2588	iface_index = 0;
2589	if (usb2_transfer_setup(udev, &iface_index,
2590	    udev->default_xfer, usb2_control_ep_cfg, USB_DEFAULT_XFER_MAX, NULL,
2591	    udev->default_mtx)) {
2592		DPRINTFN(0, "could not setup default "
2593		    "USB transfer!\n");
2594	} else {
2595		goto repeat;
2596	}
2597}
2598
2599/*------------------------------------------------------------------------*
2600 *	usb2_clear_data_toggle - factored out code
2601 *
2602 * NOTE: the intention of this function is not to reset the hardware
2603 * data toggle.
2604 *------------------------------------------------------------------------*/
2605void
2606usb2_clear_data_toggle(struct usb2_device *udev, struct usb2_pipe *pipe)
2607{
2608	DPRINTFN(5, "udev=%p pipe=%p\n", udev, pipe);
2609
2610	USB_BUS_LOCK(udev->bus);
2611	pipe->toggle_next = 0;
2612	USB_BUS_UNLOCK(udev->bus);
2613}
2614
2615/*------------------------------------------------------------------------*
2616 *	usb2_clear_stall_callback - factored out clear stall callback
2617 *
2618 * Input parameters:
2619 *  xfer1: Clear Stall Control Transfer
2620 *  xfer2: Stalled USB Transfer
2621 *
2622 * This function is NULL safe.
2623 *
2624 * Return values:
2625 *   0: In progress
2626 *   Else: Finished
2627 *
2628 * Clear stall config example:
2629 *
2630 * static const struct usb2_config my_clearstall =  {
2631 *	.type = UE_CONTROL,
2632 *	.endpoint = 0,
2633 *	.direction = UE_DIR_ANY,
2634 *	.interval = 50, //50 milliseconds
2635 *	.bufsize = sizeof(struct usb2_device_request),
2636 *	.mh.timeout = 1000, //1.000 seconds
2637 *	.mh.flags = { },
2638 *	.mh.callback = &my_clear_stall_callback, // **
2639 * };
2640 *
2641 * ** "my_clear_stall_callback" calls "usb2_clear_stall_callback"
2642 * passing the correct parameters.
2643 *------------------------------------------------------------------------*/
2644uint8_t
2645usb2_clear_stall_callback(struct usb2_xfer *xfer1,
2646    struct usb2_xfer *xfer2)
2647{
2648	struct usb2_device_request req;
2649
2650	if (xfer2 == NULL) {
2651		/* looks like we are tearing down */
2652		DPRINTF("NULL input parameter\n");
2653		return (0);
2654	}
2655	USB_XFER_LOCK_ASSERT(xfer1, MA_OWNED);
2656	USB_XFER_LOCK_ASSERT(xfer2, MA_OWNED);
2657
2658	switch (USB_GET_STATE(xfer1)) {
2659	case USB_ST_SETUP:
2660
2661		/*
2662		 * pre-clear the data toggle to DATA0 ("umass.c" and
2663		 * "ata-usb.c" depends on this)
2664		 */
2665
2666		usb2_clear_data_toggle(xfer2->xroot->udev, xfer2->pipe);
2667
2668		/* setup a clear-stall packet */
2669
2670		req.bmRequestType = UT_WRITE_ENDPOINT;
2671		req.bRequest = UR_CLEAR_FEATURE;
2672		USETW(req.wValue, UF_ENDPOINT_HALT);
2673		req.wIndex[0] = xfer2->pipe->edesc->bEndpointAddress;
2674		req.wIndex[1] = 0;
2675		USETW(req.wLength, 0);
2676
2677		/*
2678		 * "usb2_transfer_setup_sub()" will ensure that
2679		 * we have sufficient room in the buffer for
2680		 * the request structure!
2681		 */
2682
2683		/* copy in the transfer */
2684
2685		usb2_copy_in(xfer1->frbuffers, 0, &req, sizeof(req));
2686
2687		/* set length */
2688		xfer1->frlengths[0] = sizeof(req);
2689		xfer1->nframes = 1;
2690
2691		usb2_start_hardware(xfer1);
2692		return (0);
2693
2694	case USB_ST_TRANSFERRED:
2695		break;
2696
2697	default:			/* Error */
2698		if (xfer1->error == USB_ERR_CANCELLED) {
2699			return (0);
2700		}
2701		break;
2702	}
2703	return (1);			/* Clear Stall Finished */
2704}
2705
2706#if (USB_NO_POLL == 0)
2707
2708/*------------------------------------------------------------------------*
2709 *	usb2_callout_poll
2710 *------------------------------------------------------------------------*/
2711static void
2712usb2_callout_poll(struct usb2_xfer *xfer)
2713{
2714	struct usb2_callout *co;
2715	void (*cb) (void *);
2716	void *arg;
2717	struct mtx *mtx;
2718	uint32_t delta;
2719
2720	if (xfer == NULL) {
2721		return;
2722	}
2723	co = &xfer->timeout_handle;
2724
2725#if __FreeBSD_version >= 800000
2726	mtx = (void *)(co->co.c_lock);
2727#else
2728	mtx = co->co.c_mtx;
2729#endif
2730	mtx_lock(mtx);
2731
2732	if (usb2_callout_pending(co)) {
2733		delta = ticks - co->co.c_time;
2734		if (!(delta & 0x80000000)) {
2735
2736			cb = co->co.c_func;
2737			arg = co->co.c_arg;
2738
2739			/* timed out */
2740			usb2_callout_stop(co);
2741
2742			(cb) (arg);
2743		}
2744	}
2745	mtx_unlock(mtx);
2746}
2747
2748
2749/*------------------------------------------------------------------------*
2750 *	usb2_do_poll
2751 *
2752 * This function is called from keyboard driver when in polling
2753 * mode.
2754 *------------------------------------------------------------------------*/
2755void
2756usb2_do_poll(struct usb2_xfer **ppxfer, uint16_t max)
2757{
2758	struct usb2_xfer *xfer;
2759	struct usb2_xfer_root *xroot;
2760	struct usb2_device *udev;
2761	struct usb2_proc_msg *pm;
2762	uint32_t to;
2763	uint16_t n;
2764
2765	/* compute system tick delay */
2766	to = ((uint32_t)(1000000)) / ((uint32_t)(hz));
2767	DELAY(to);
2768	atomic_add_int((volatile int *)&ticks, 1);
2769
2770	for (n = 0; n != max; n++) {
2771		xfer = ppxfer[n];
2772		if (xfer) {
2773			xroot = xfer->xroot;
2774			udev = xroot->udev;
2775
2776			/*
2777			 * Poll hardware - signal that we are polling by
2778			 * locking the private mutex:
2779			 */
2780			USB_XFER_LOCK(xfer);
2781			(udev->bus->methods->do_poll) (udev->bus);
2782			USB_XFER_UNLOCK(xfer);
2783
2784			/* poll clear stall start */
2785			USB_BUS_LOCK(xfer->xroot->bus);
2786			pm = &udev->cs_msg[0].hdr;
2787			(pm->pm_callback) (pm);
2788			USB_BUS_UNLOCK(xfer->xroot->bus);
2789
2790			if (udev->default_xfer[1]) {
2791
2792				/* poll timeout */
2793				usb2_callout_poll(udev->default_xfer[1]);
2794
2795				/* poll clear stall done thread */
2796				USB_BUS_LOCK(xfer->xroot->bus);
2797				pm = &udev->default_xfer[1]->
2798				    xroot->done_m[0].hdr;
2799				(pm->pm_callback) (pm);
2800				USB_BUS_UNLOCK(xfer->xroot->bus);
2801			}
2802			/* poll timeout */
2803			usb2_callout_poll(xfer);
2804
2805			/* poll done thread */
2806			USB_BUS_LOCK(xfer->xroot->bus);
2807			pm = &xroot->done_m[0].hdr;
2808			(pm->pm_callback) (pm);
2809			USB_BUS_UNLOCK(xfer->xroot->bus);
2810		}
2811	}
2812}
2813
2814#else
2815
2816void
2817usb2_do_poll(struct usb2_xfer **ppxfer, uint16_t max)
2818{
2819	/* polling not supported */
2820}
2821
2822#endif
2823