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