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