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