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